[
  {
    "path": ".eslintrc.json",
    "content": "{\n\t\"env\": {\n\t\t\"browser\": true,\n\t\t\"es2021\": true\n\t},\n\t\"extends\": [\n\t\t\"eslint:recommended\",\n\t\t\"plugin:@typescript-eslint/recommended\",\n\t\t\"plugin:sonarjs/recommended\"\n\t],\n\t\"parser\": \"@typescript-eslint/parser\",\n\t\"parserOptions\": {\n\t\t\"ecmaVersion\": \"latest\",\n\t\t\"sourceType\": \"module\"\n\t},\n\t\"plugins\": [\"@typescript-eslint\", \"sonarjs\"],\n\t\"rules\": {\n\t\t\"@typescript-eslint/ban-types\": \"off\",\n\t\t\"@typescript-eslint/no-explicit-any\": \"off\",\n\t\t\"no-mixed-spaces-and-tabs\": \"off\",\n\t\t\"@typescript-eslint/no-non-null-assertion\": \"off\",\n\t\t\"@typescript-eslint/no-extra-semi\": \"off\",\n\t\t\"@typescript-eslint/ban-ts-comment\": \"off\",\n\t\t\"@typescript-eslint/no-namespace\": \"off\",\n\t\t\"no-case-declarations\": \"off\",\n\t\t\"no-extra-semi\": \"off\",\n\t\t\"sonarjs/cognitive-complexity\": \"off\",\n\t\t\"sonarjs/no-all-duplicated-branches\": \"off\"\n\t},\n\t\"ignorePatterns\": [\"example/*\", \"test/**/*\"]\n}\n"
  },
  {
    "path": ".github/FUNDING.yaml",
    "content": "github: SaltyAom"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/2-bug-report.yml",
    "content": "name: 🐛 Bug Report\ndescription: Report an issue that should be fixed\nlabels: [bug]\nbody:\n    - type: markdown\n      attributes:\n          value: |\n              Thank you for submitting a bug report. It helps make Elysia.JS better.\n\n              If you need help or support using Elysia.JS, and are not reporting a bug, please\n              head over to Q&A discussions [Discussions](https://github.com/elysiajs/elysia/discussions/categories/q-a), where you can ask questions in the Q&A forum.\n\n              Make sure you are running the version of Elysia.JS and Bun.Sh\n              The bug you are experiencing may already have been fixed.\n\n              Please try to include as much information as possible.\n\n    - type: input\n      attributes:\n          label: What version of Elysia is running?\n          description: Copy the row with `elysia` dependency from output `bun pm ls` command\n    - type: input\n      attributes:\n          label: What platform is your computer?\n          description: |\n              For MacOS and Linux: copy the output of `uname -mprs`\n              For Windows: copy the output of `\"$([Environment]::OSVersion | ForEach-Object VersionString) $(if ([Environment]::Is64BitOperatingSystem) { \"x64\" } else { \"x86\" })\"` in the PowerShell console\n    - type: input\n      attributes:\n        label: What environment are you using\n        description: |\n              Answer with runtime and version you are using.\n              - Bun version: `bun --version`\n              - Node version: `node --version`\n              - Deno version: `deno --version`\n              - Cloudflare Workers (compatability date if applicable)\n    - type: input\n      attributes:\n        label: Are you using dynamic mode?\n        description: Is your code using `new Elysia({ aot:false })`\n    - type: textarea\n      attributes:\n          label: What steps can reproduce the bug?\n          description: Explain the bug and provide a code snippet that can reproduce it.\n      validations:\n          required: true\n    - type: textarea\n      attributes:\n          label: What is the expected behavior?\n          description: If possible, please provide text instead of a screenshot.\n    - type: textarea\n      attributes:\n          label: What do you see instead?\n          description: If possible, please provide text instead of a screenshot.\n    - type: textarea\n      attributes:\n          label: Additional information\n          description: Is there anything else you think we should know?\n    - type: input\n      attributes:\n        label: Have you try removing the `node_modules` and `bun.lockb` and try again yet?\n        description: rm -rf node_modules && bun.lockb\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/3-feature-request.yml",
    "content": "name: 🚀 Feature Request\ndescription: Suggest an idea, feature, or enhancement\nlabels: [enhancement]\nbody:\n    - type: markdown\n      attributes:\n          value: |\n              Thank you for submitting an idea. It helps make Elysia.JS better.\n\n              If you want to discuss Elysia.JS, or learn how others are using Elysia.JS, please\n              head to our [Discord](https://discord.com/invite/y7kH46ZE) server, where you can chat among the community.\n    - type: textarea\n      attributes:\n          label: What is the problem this feature would solve?\n      validations:\n          required: true\n    - type: textarea\n      attributes:\n          label: What is the feature you are proposing to solve the problem?\n      validations:\n          required: true\n    - type: textarea\n      attributes:\n          label: What alternatives have you considered?\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: true\ncontact_links:\n    - name: 📗 Documentation Issue\n      url: https://github.com/elysiajs/documentation/issues/new/choose\n      about: Head over to our Documentation repository!\n    - name: 💬 Ask a Question\n      url: https://discord.gg/eaFJ2KDJck\n      about: Head over to our Discord!\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  - package-ecosystem: 'npm'\n    directory: './'\n    schedule:\n      interval: 'daily'\n\n  - package-ecosystem: 'github-actions'\n    directory: './'\n    schedule:\n      interval: 'daily'\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: Build and Test\n\non:\n    push:\n    pull_request:\n\njobs:\n    build:\n        name: Build and test code\n        runs-on: ubuntu-latest\n\n        steps:\n            - name: Checkout\n              uses: actions/checkout@v4\n\n            - name: Setup bun\n              uses: oven-sh/setup-bun@v1\n              with:\n                  bun-version: latest\n\n            - name: Install packages\n              run: bun install\n\n            - name: Build code\n              run: bun run build\n\n            - name: Test\n              run: bun run test\n\n            - name: Test\n              run: bun run test:cf\n\n            - name: Publish Preview\n              if: github.event_name == 'pull_request'\n              run: bunx pkg-pr-new publish\n"
  },
  {
    "path": ".github/workflows/publish.yml",
    "content": "name: Publish\n\non:\n  release:\n    types: [published]\n\ndefaults:\n  run:\n    shell: bash\n\npermissions:\n  id-token: write\n\nenv:\n  # Enable debug logging for actions\n  ACTIONS_RUNNER_DEBUG: true\n\njobs:\n  publish-npm:\n    name: 'Publish: npm Registry'\n    runs-on: ubuntu-latest\n    steps:\n      - name: 'Checkout'\n        uses: actions/checkout@v4\n\n      - name: 'Setup Bun'\n        uses: oven-sh/setup-bun@v1\n        with:\n          bun-version: latest\n          registry-url: \"https://registry.npmjs.org\"\n\n      - uses: actions/setup-node@v5\n        with:\n          node-version: '24.x'\n          registry-url: 'https://registry.npmjs.org'\n\n      - name: Install packages\n        run: bun install\n\n      - name: Build code\n        run: bun run build\n\n      - name: Test\n        run: bun run test\n\n      - name: Test\n        run: bun run test:cf\n\n      - name: 'Publish'\n        run: |\n          NODE_AUTH_TOKEN=\"\" npm publish --provenance --access=public\n"
  },
  {
    "path": ".gitignore",
    "content": ".DS_Store\n\nnode_modules\nbuild\ndump.rdb\ndist\ntrace\n.scannerwork\n*.tsbuildinfo\n.wrangler\n.elysia\nheap.json\nserver\n"
  },
  {
    "path": ".npmignore",
    "content": ".git\n.gitignore\n.github\n.prettierrc\n.eslintrc.js\n.eslint.json\n.swc.cjs.swcrc\n.swc.esm.swcrc\n.swcrc\n.husky\n.eslintrc.json\n\nbun.lock\nbun.lockb\nnode_modules\ntsconfig.json\nCHANGELOG.md\nheap.json\n\nexample\ntests\ntest\ndocs\nsrc\n.DS_Store\ntest\ntsconfig.cjs.json\ntsconfig.dts.json\ntsconfig.esm.json\ntsconfig.test.json\ntsconfig.test.tsbuildinfo\n\nCONTRIBUTING.md\nCODE_OF_CONDUCT.md\ntrace\n\nbuild.ts\n.scannerwork\nsrc\nserver\n"
  },
  {
    "path": ".npmrc",
    "content": "enable-pre-post-scripts=true\nregistry=https://registry.npmjs.org\nalways-auth=true\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n\t\"useTabs\": true,\n\t\"tabWidth\": 4,\n\t\"semi\": false,\n\t\"singleQuote\": true,\n\t\"trailingComma\": \"none\"\n}\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# 1.4.28 - 17 Mar 2025\nFeature:\n- [#1803](https://github.com/elysiajs/elysia/pull/1803) stream response with pull based backpressure\n- [#1802](https://github.com/elysiajs/elysia/pull/1802) handle range header for file/blob response\n- [#1722](https://github.com/elysiajs/elysia/pull/1772), [#1741](https://github.com/elysiajs/elysia/issues/1741) direct ReadableStream perf blow-up\n\nBug fix:\n- [#1805](https://github.com/elysiajs/elysia/pull/1805) dynamic imports inside .guard not registering routes\n- [#1771](https://github.com/elysiajs/elysia/issues/1771) breaks Bun HTML imports\n- [#1797](https://github.com/elysiajs/elysia/pull/1797) await mapped error response promise\n- [#1794](https://github.com/elysiajs/elysia/pull/1794) merge app cookie config into route cookie validator config\n- [#1796](https://github.com/elysiajs/elysia/pull/1796) check custom parser by full name\n- [#1795](https://github.com/elysiajs/elysia/pull/1795)  write transformed cookie value to cookie entry directly\n- [#1793](https://github.com/elysiajs/elysia/pull/1793) use cookie schema for cookie noValidate check\n- [#1792](https://github.com/elysiajs/elysia/pull/1792) throw ValidationError instead of boolean in response encode path\n- detect HTML bundle when inline response is Promise\n\nChange:\n- [#1613](https://github.com/elysiajs/elysia/pull/1613) export `ElysiaTypeCustomErrors`\n- remove Bun specific built\n- export `AnySchema`, `UnwrapSchema`, `ModelsToTypes` from root\n- conditional set headers of String and Object when no set.headers is set\n\n# 1.4.27 - 1 Mar 2026\nBug fix:\n- getSchemaValidator: handle TypeBox as sub type\n- handle cookie prototype pollution when parsing cookie\n\nImprovement:\n- conditional async on getSchemaValidator when schema is Standard Schema\n- use Response.json on Bun\n\n# 1.4.26 - 25 Feb 2026\nBug fix:\n- [#1755](https://github.com/elysiajs/elysia/issues/1755) deduplicate local handler from global event\n- [#1752](https://github.com/elysiajs/elysia/issues/1752) system router with trailing path doesn't match with non-trailing\n- url format redos\n- [#1747](https://github.com/elysiajs/elysia/issues/1747) parsing request from mount hang\n\n# 1.4.25 - 12 Feb 2026\nFeature:\n- export ElysiaStatus\n\nBug fix:\n- macro with conflict literal value per status\n- recursive macro with conflict value per status\n\n# 1.4.24 - 11 Feb 2026\nFeature:\n- graceful unsigned cookie transition\n\nBug fix:\n- [#1733](https://github.com/elysiajs/elysia/pull/1733) preserve multiple set-cookie headers in mounted handlers \n- object cookie with secret doesn't deserialized after parsed\n\n# 1.4.23 - 9 Feb 2026\nFeature:\n- [#1719](https://github.com/elysiajs/elysia/pull/1719) add t.Union/t.Intersection handling in property enumerations/checks\n- [#1697](https://github.com/elysiajs/elysia/pull/1697) extend complex formdata support to StandardSchema\n- [#1656](https://github.com/elysiajs/elysia/pull/1675) serialize custom array-like custom class with array sub class\n\nBug fix:\n- [#1721](https://github.com/elysiajs/elysia/issues/1721) Promise<Response> with response schema\n- [#1700](https://github.com/elysiajs/elysia/issues/1700) distinct union object\n- [#1683](https://github.com/elysiajs/elysia/pull/1683) response validation returns 500 instead of 422 for nested schemas in dynamic mode\n- [#1679](https://github.com/elysiajs/elysia/pull/1679) preserve headers when throwing from AsyncGenerator\n- [#1595](https://github.com/elysiajs/elysia/pull/1595) stream reference should point to teed value\n- fix can't modify immutable headers error\n\nChange:\n- update exact-mirror to 0.2.7\n\n# 1.4.22 - 14 Jan 2026\nImprovement:\n- use imperative check for `replaceURLPath` instead of allocating `new URL`\n- reduce ts-ignore/ts-expect-error on promise map handler\n- [#1655](https://github.com/elysiajs/elysia/pull/1655) decode single values in ArrayQuery\n\nBug fix:\n- [#1671](https://github.com/elysiajs/elysia/issues/1671) mount produces incorrect URL path when Elysia instance has prefix option\n- [https://github.com/elysiajs/elysia/issues/1617](https://github.com/elysiajs/elysia/issues/1617), [#1623](https://github.com/elysiajs/elysia/pull/1623) AOT compilation removes beforeHandle when using arrow function expression\n- [#1667](https://github.com/elysiajs/elysia/issues/1667) skip body parsing on mount with dynamic mode\n- [#1662](https://github.com/elysiajs/elysia/pull/1662) custom thenable fallback in `mapCompactResponse` causing runtime crash with undefined variable\n- [#1661](https://github.com/elysiajs/elysia/pull/1661), [#1663](https://github.com/elysiajs/elysia/pull/1663) fix SSE double-wrapping bug when returning pre-formatted Response\n- ValueError with summary missing types\n- Elysia not using Bun.routes by default\n\n# 1.4.21 - 4 Jan 2026\nImprovement:\n- [#1654](https://github.com/elysiajs/elysia/pull/1654) encode t.Date() to iso string\n- [#1624](https://github.com/elysiajs/elysia/pull/1624) apply macros before merging hooks in group method\n\nBug fix:\n- call Sucrose GC unref when possible (browser fallback)\n- add allowUnsafeValidationDetails to Standard Validator\n\n# 1.4.20 - 3 Jan 2026\nImprovement:\n- add `ModelValidator.schema` for accessing raw schema\n- [#1636](https://github.com/elysiajs/elysia/issues/1636) add `subscriptions` to `Elysia.ws` context\n- [#1638](https://github.com/elysiajs/elysia/pull/1638) unref Sucrose gc\n\nBug fix:\n- [#1649](https://github.com/elysiajs/elysia/pull/1649) add null check for object properties (t.Record)\n- [#1646](https://github.com/elysiajs/elysia/pull/1646) use constant-time comparison for signed cookie verification\n- [#1639](https://github.com/elysiajs/elysia/issues/1639) compose: ReferenceError: \"_r_r is not defined\" when onError returns plain object & mapResponse exists\n- [#1631](https://github.com/elysiajs/elysia/issues/1631) update Exact Mirror to 0.2.6\n- [#1630](https://github.com/elysiajs/elysia/issues/1630) enforce fetch to return MaybePromise<Response>\n\nBug fix:\n- `Elysia.models` broke when referencing non typebox model\n\n# 1.4.19 - 13 Dec 2025\nSecurity:\n- reject invalid cookie signature when using cookie rotation\n\nImprovement\n- [#1609](https://github.com/elysiajs/elysia/issues/1609) calling afterResponse with aot: false\n- [#1607](https://github.com/elysiajs/elysia/issues/1607), [#1606](https://github.com/elysiajs/elysia/issues/1606), [#1139](https://github.com/elysiajs/elysia/issues/1138) data coercion on nested form data\n- [#1604](https://github.com/elysiajs/elysia/issues/1604) save lazy compilation of `Elysia.fetch` for up to 45x performance improvement\n- [#1588](https://github.com/elysiajs/elysia/pull/1588), [#1587](https://github.com/elysiajs/elysia/pull/1587) add seen weakset during mergeDeep\n\nBug fix:\n- [#1614](https://github.com/elysiajs/elysia/issues/1614) Cloudflare Worker with dynamic path\n- add set immediate fallback\n- [#1597](https://github.com/elysiajs/elysia/issues/1597) safeParse, parse to static type\n- [#1596](https://github.com/elysiajs/elysia/issues/1596) handle context pass to function with sub context\n- [#1591](https://github.com/elysiajs/elysia/pull/1591), [#1590](https://github.com/elysiajs/elysia/pull/1591) merge set.headers without duplicating Response\n- [#1546](https://github.com/elysiajs/elysia/issues/1546) override group prefix type\n- [#1526](https://github.com/elysiajs/elysia/issues/1526) default error handler doesn't work in Cloudflare Workers\n- handle group with empty prefix in type-level\n\n# 1.4.18 - 4 Dec 2025\nSecurity:\n- use `JSON.stringify` over custom escape implementation\n\n# 1.4.17 - 2 Dec 2025\nImprovement:\n- [#1573](https://github.com/elysiajs/elysia/pull/1573) `Server` is always resolved to `any` when `@types/bun` is missing\n- [#1568](https://github.com/elysiajs/elysia/pull/1568) optimize cookie value comparison using FNV-1a hash\n- [#1549](https://github.com/elysiajs/elysia/pull/1549) Set-Cookie headers not sent when errors are thrown\n- [#1579](https://github.com/elysiajs/elysia/pull/1579) HEAD to handle Promise value\n\nSecurity:\n- cookie injection, prototype pollution, and RCE\n\nBug fix:\n- [#1550](https://github.com/elysiajs/elysia/pull/1550) excess property checking\n- allow cookie.sign to be string\n\nChange:\n- [#1584](https://github.com/elysiajs/elysia/pull/1584) change customError property to unknown\n- [#1556](https://github.com/elysiajs/elysia/issues/1556) prevent sending set-cookie header when cookie value is not modified\n- [#1563](https://github.com/elysiajs/elysia/issues/1563) standard schema on websocket\n- conditional parseQuery parameter\n- conditional pass `c.request` to handler for streaming response\n- fix missing `contentType` type on `parser`\n\n# 1.4.16 - 13 Nov 2025\nImprovement:\n- ValidationError: add `messageValue` as an alias of `errorValue`\n- ValidationError.detail now accept optional 2nd parameter `allowUnsafeValidatorDetails`\n- macro: add `introspect`\n- prevent redundant route compilation\n- merge multiple macro resolve response\n\nBug fix:\n- [#1543](https://github.com/elysiajs/elysia/pull/1524) respect toResponse() method on Error classes\n- [#1537](https://github.com/elysiajs/elysia/issues/1537) websocket: ping/pong not being called\n- [#1536](https://github.com/elysiajs/elysia/pull/1536) export ExtractErrorFromHandle\n- [#1535](https://github.com/elysiajs/elysia/pull/1535) skip response validation for generators and streams\n- [#1531](https://github.com/elysiajs/elysia/pull/1531) typo in ElysiaTypeCustomErrorCallback: valdation to validation\n- [#1528](https://github.com/elysiajs/elysia/issues/1528) error in parsing request body validation errors with Zod\n- [#1527](https://github.com/elysiajs/elysia/issues/1527) bracket handling in exact mirror\n- [#1524](https://github.com/elysiajs/elysia/pull/1524) head request handler not working\n\n# 1.4.15 - 3 Nov 2025\nBug fix:\n- 1.4.14 regression with Eden Treaty, and OpenAPI type gen\n\n# 1.4.14 - 3 Nov 2025\nFeature:\n- [#1520](https://github.com/elysiajs/elysia/issues/1520), [#1522](https://github.com/elysiajs/elysia/issues/1522) async handlers crash on HEAD request\n- [#1510](https://github.com/elysiajs/elysia/issues/1510) strict status response\n- [#1503](https://github.com/elysiajs/elysia/pull/1503) add t.NumericEnum() for numeric enum query handling\n- [#1450](https://github.com/elysiajs/elysia/pull/1450) call onAfterResponse when onError returns a value\n- remove redundant `Prettify`\n- prettify response for OpenAPI type gen\n- conditional apply macro context in type level\n- improve type performance in general\n\nChange:\n- remove `Prettify2`, `Partial2`\n\n# 1.4.13 - 23 Oct 2025\nFeature:\n- [#1453](https://github.com/elysiajs/elysia/issues/1453) add `allowUnsafeValidationDetails` for disabling unsafe validation details in production mode\n- allow rapid stream in non browser mode or `ELYSIA_RAPID_STREAM` is set\n- `afterResponse` now wait for generator stream to finish\n- trace of `handle`, and `afterResponse` now wait for generator stream to finish\n\nBug fix:\n- [#1502](https://github.com/elysiajs/elysia/issues/1502), [#1501](https://github.com/elysiajs/elysia/issues/1501) afterHandle doesn't update status\n- [#1500](https://github.com/elysiajs/elysia/issues/1500) export `InvalidFileType` from root\n- [#1495](https://github.com/elysiajs/elysia/pull/1495) request server hook parameters are typed as any (Bun 1.3.0)\n- [#1483](https://github.com/elysiajs/elysia/pull/1483) handle standard schema validators in ValidationError.all\n- [#1459](https://github.com/elysiajs/elysia/pull/1459) fix strictPath behavior when aot: false is set\n- [#1455](https://github.com/elysiajs/elysia/pull/1455) graceful shutdown not awaiting server.stop\n- [#1499](https://github.com/elysiajs/elysia/pull/1449) fails when merging with t.Optional schema\n- remove encoding chunk from native static response in Bun adapter\n\nChange:\n- make `@types/bun` an optional dependency\n\n# 1.4.12 - 14 Oct 2025\nImprovement:\n- named macro function callback\n- adjust build script\n\n# 1.4.11 - 12 Oct 2025\nBug fix:\n- [#1469](https://github.com/elysiajs/elysia/issues/1469) incorrect ping, pong type signature\n- [#1467](https://github.com/elysiajs/elysia/issues/1467) better error union handling in `onError`\n- [#1463](https://github.com/elysiajs/elysia/issues/1463) responseValue is undefined in afterHandle when beforeHandle returns status\n- [#1460](https://github.com/elysiajs/elysia/issues/1460) compressed response in mapResponse is corrupted if status !== 200\n- [#1456](https://github.com/elysiajs/elysia/issues/1456) add response type check for stream\n- [#1451](https://github.com/elysiajs/elysia/issues/1451) cookie validation is not running when there's no body schema\n- make `file-type` non optional dependency to fix default build problem\n\n# 1.4.10 - 9 Oct 2025\nBug fix:\n- [#1406](https://github.com/elysiajs/elysia/issues/1406) enforce return type in OptionalHandler\n- static handlers in Bun 1.3\n- conditional use `crypto` randomUUID if not available (eg. iOS Safari)\n\nChange:\n- `Elysia.file` readstream value is now IIFE to re-read\n\n# 1.4.9 - 29 Sep 2025\nImprovement:\n- add Cloudflare Worker test\n- add `Sucrose.Settings`\n- [#1443](https://github.com/elysiajs/elysia/pull/1443) add knip for detecting deadcode\n\n# 1.4.8 - 27 Sep 2025\nImprovement:\n- automatically clear up sucrose cache when not used\n- remove `Bun.hash` from checksum calculation\n\nChange:\n- make `file-type` optional to reduce bundle size\n- [#1432](https://github.com/elysiajs/elysia/pull/1432) missing context (set) in mapResponse for ElysiaFile\n- [#1435](https://github.com/elysiajs/elysia/pull/1435) missing cookies in SSE\n\n# 1.4.7 - 22 Sep 2025\nFeature:\n- experimental `adapter/cloudflare-worker`\n- add `ElysiaAdapter.beforeCompile`\n\nChange:\n- do not prettify routes when using `guard`, `group`\n- use `process.getBuiltinModule` instead of dynamic import for file\n- `Elysia.file.value` on Web Standard Adapter now is not a promise\n\n# 1.4.6 - 18 Sep 2025\nImprovement:\n- [#1406](https://github.com/elysiajs/elysia/issues/1406) strictly check for 200 inline status code\n- coerce union status value and return type\n- add `BunHTMLBundleLike` to Elysia inline handler\n- [#1405](https://github.com/elysiajs/elysia/issues/1405) prevent Elysia from being a dependency of itself\n- [#1416](https://github.com/elysiajs/elysia/issues/1416) check if object is frozen before merging, add try-catch to prevent crash\n- [#1419](https://github.com/elysiajs/elysia/issues/1419) guard doesn't apply scoped/global schema to object macro\n- [#1425](https://github.com/elysiajs/elysia/issues/1425) DELETE doesn't inherit derive/resolve type\n\nChange:\n- [#1409](https://github.com/elysiajs/elysia/issues/1409) onTransform now doesn't include type as it isn't validated yet, creating confusion\n\nBug fix:\n- [#1410](https://github.com/elysiajs/elysia/issues/1410) handle union derive/resolve property\n- probably fix mergeDeep attempted to assign to readonly property\n- derive/resolve inherit type in inline handler\n\n# 1.4.5 - 15 Sep 2025\nImprovement:\n- soundness for guard, group\n- overwrite primitive value if collide (intersectIfObject)\n\nBug fix:\n- standard schema incorrectly validate cookie and coercion\n- merge nested guard, group standalone schema properly\n\nBreaking Change:\n- no longer coerce type for .model with `t.Ref` by default\n\n# 1.4.4 - 13 Sep 2025\nBug fix:\n- merge schema in GET method\n- remove accidental console.log\n\n# 1.4.3 - 13 Sep 2025\nBug fix:\n- `mapValueError` should return all possible value both in dev environment and production environment\n- inline lifecycle get method doesn't inherit Singleton\n\n# 1.4.2 - 13 Sep 2025\nBug fix:\n- remove debug `q` from inline handler\n\n# 1.4.1 - 13 Sep 2025\nBug fix:\n- type error for inline Elysia.file\n\n# 1.4.0 - 13 Sep 2025\nFeature:\n- standard validator\n- macro schema, macro extension, macro detail\n- lifecycle type soundness\n- type inference reduced by ~11%\n- [#861](https://github.com/elysiajs/elysia/issues/861) missing HEAD method when register route with GET\n\nImprovement\n- [#861](https://github.com/elysiajs/elysia/issues/861) automatically add HEAD method when defining GET route\n\nChange\n- ObjectString/ArrayString no longer produce default value by default due to security reasons\n- Cookie now dynamically parse when format is likely JSON\n- export `fileType` for external file type validation for accurate response\n\nBreaking Change\n- remove macro v1 due to non type soundness\n- remove `error` function, use `status` instead\n- deprecation notice for `response` in `mapResponse`, `afterResponse`, use `responseValue` instead\n- remove reference array model by string eg. `user[]`, use `t.Array(t.Ref('user'))` instead\n\n# 1.3.22 - 6 Sep 2025\nBug fix:\n- safely unwrap t.Record\n\n# 1.3.21 - 31 Aug 2025\nBug fix:\n- [#1356](https://github.com/elysiajs/elysia/pull/1356) webSocket validation error handling in BunAdapter\n- [#1358](https://github.com/elysiajs/elysia/pull/1358) allow overriding websocket handler with listen options\n- [#1365](https://github.com/elysiajs/elysia/pull/1365) check if the plugin.constructor (fix import module in Bun 1.2.21)\n- [#1367](https://github.com/elysiajs/elysia/pull/1367) .trace hooks (onAfterResponse, etc...) not being called\n- [#1369](https://github.com/elysiajs/elysia/issues/1369) don't block microtask queue in SSE\n\n# 1.3.20 - 24 Aug 2025\nChange:\n- mime is undefined when using `Elysia.file` in Web Standard Adapter\n\n# 1.3.19 - 24 Aug 2025\nChange:\n- [#1357](https://github.com/elysiajs/elysia/issues/1357) return `Response` proxy as-is\n\nBug fix:\n- [elysiajs/node#45](https://github.com/elysiajs/node/issues/45) detect Response polyfill on Node\n\n# 1.3.18 - 23 Aug 2025\nBug fix:\n- `ReadableStream` is not pass to `handleStream` in `mapCompactResponse`, and `mapEarlyResponse`\n\n# 1.3.17 - 23 Aug 2025\nBug fix:\n- [#1353](https://github.com/elysiajs/elysia/issues/1353) normalize encodeSchema with Transform\n\n# 1.3.16 - 23 Aug 2025\nImprovement:\n- `sse` now infer type\n- `sse` now accepts `ReadableStream` to return stream as `text/event-stream`\n- refactor SSE handler\n- support returning `ReadableStream` from generator or async generator\n\nChange:\n- sse no longer include generated id by default\n\nBug fix:\n- static response now use callback clone instead of bind\n\n# 1.3.15 - 21 Aug 2025\nBug fix:\n- ValidationError.detail only handle custom error\n\n# 1.3.14 - 21 Aug 2025\nImprovement:\n- custom error on production mode\n- add `ValidationError.withDetail`\n- add `withDetail` for additional error information\n\n# 1.3.13 - 18 Aug 2025\nBug fix:\n- important performance degration, exact mirror normalize doesn't apply correctly\n- normalize optional property with special character\n\nChange:\n- update `exact-mirror` to `0.1.6`\n\n# 1.3.12 - 19 Aug 2025\nBug fix:\n- [#1348](https://github.com/elysiajs/elysia/issues/1348) onAfterResponse runs twice if NotFoundError thrown and onError provided\n\n# 1.3.11 - 18 Aug 2025\nBug fix:\n- [#1346](https://github.com/elysiajs/elysia/issues/1346) cannot declare 'mep' twice\n\n# 1.3.10 - 18 Aug 2025\nBug fix:\n- [#1028](https://github.com/elysiajs/elysia/issues/1028) query array nuqs format in dynamic mode\n- unwrap t.Import in dynamic mode\n\n# 1.3.9 - 18 Aug 2025\nFeature:\n- [#932](https://github.com/elysiajs/elysia/issues/932) add `t.ArrayBuffer`, `t.Uint8Array`\n\nBug fix:\n- [#459](https://github.com/elysiajs/elysia/issues/459) route prefix should give type error when prefix is not start with '/'\n- [#669](https://github.com/elysiajs/elysia/issues/669) add nullable field to t.Nullable for OpenAPI 3.0 spec\n- [#711](https://github.com/elysiajs/elysia/issues/711) set default headers for non-aot\n- [#713](https://github.com/elysiajs/elysia/issues/713) NotFoundError doesn't call onAfterResponse hook\n- [#771](https://github.com/elysiajs/elysia/issues/771) skip body parsing if Content-Type is present but body is not\n- [#747](https://github.com/elysiajs/elysia/issues/747) mapResponse inside mapError override error value\n- [#812](https://github.com/elysiajs/elysia/issues/812) check for minItems length before array validation\n- [#833](https://github.com/elysiajs/elysia/issues/833) cookie signing doesn't work in dynamic mode\n- [#859](https://github.com/elysiajs/elysia/issues/859) clean non-root additionalProperties\n- [#924](https://github.com/elysiajs/elysia/issues/924) decode path param\n- [#985](https://github.com/elysiajs/elysia/issues/924) Nullable accept options\n- [#1028](https://github.com/elysiajs/elysia/issues/1028) string | string[] query parameter, reference array\n- [#1120](https://github.com/elysiajs/elysia/issues/1120) cannot set multiple cookies when response is a file\n- [#1124](https://github.com/elysiajs/elysia/issues/1124) validate url encoded query\n- [#1158](https://github.com/elysiajs/elysia/issues/1158) prevent side-effect from guard merge\n- [#1162](https://github.com/elysiajs/elysia/issues/1162) handle encoded space in array query string\n- [#1267](https://github.com/elysiajs/elysia/issues/1267) parse without contentType headers throw Bad Request\n- [#1274](https://github.com/elysiajs/elysia/issues/1274) support .use(undefined | false) for conditional plugin\n- [#1276](https://github.com/elysiajs/elysia/issues/1276) mapResponse with set inference produce invalid instruction\n- [#1268](https://github.com/elysiajs/elysia/issues/1268) using number instead of stringifed value for reporting validation error\n- [#1288](https://github.com/elysiajs/elysia/issues/1288) handle array query string in dynamic mode\n- [#1294](https://github.com/elysiajs/elysia/issues/1294) return status from `derive` and `resolve` shouldn't call `onError`\n- [#1297](https://github.com/elysiajs/elysia/issues/1297), [#1325](https://github.com/elysiajs/elysia/pull/1325) fix HTML imported pages in compiled apps\n- [#1319](https://github.com/elysiajs/elysia/pull/1319) fix array of plugin usage causes incorrect path aggregation\n- [#1323](https://github.com/elysiajs/elysia/issues/1323) don't duplicate error from plugin\n- [#1327](https://github.com/elysiajs/elysia/pull/1327) ensure that t.Date value is Date in Encode\n- dynamic handle should handle named parser\n- instanceof ElysiaCustomStatusResponse should return true when import from root Elysia module\n\nImprovement:\n- remove `finally` from compose\n- `NotFoundError` should parse query if inferred\n- [#853](https://github.com/elysiajs/elysia/issues/853) Bun Static response now handle pre-compute `onRequest`, and `onError`\n- prettify ElysiaWS type\n- export `ElysiaCustomStatusResponse`\n- handle type-level status check in after response\n\nChange:\n- status no longer make value as readonly\n- afterResponse now call after response by scheduling setImmediate\n- update memoirist to 0.4.0\n- update exact-mirror to 0.1.5\n\n# 1.3.8 - 31 Jul 2025\nImprovement:\n- ElysiaFile doesn't inherits `set.headers` eg. cors\n- [Web Standard] automatically set `Content-Type`, `Content-Range` of ElysiaFile\n\nBug fix:\n- [#1316](https://github.com/elysiajs/elysia/pull/1316) fix context type when multiple macros are selected\n- [#1306](https://github.com/elysiajs/elysia/pull/1306) preserve type narrowing in getSchemaValidator\n- add `set` to `handleFile` when file is `ElysiaFile`\n- [Web Standard] inherit set.status for `ElysiaFile`\n- make `ElysiaAdapter.stop` optional\n\n# 1.3.7 - 31 Jul 2025\nBug fix:\n- [#1314](https://github.com/elysiajs/elysia/issues/1314) coerce TransformDecodeError to ValidationError\n- [#1313](https://github.com/elysiajs/elysia/pull/1313) onRequest not firing\n- [#1311](https://github.com/elysiajs/elysia/issues/1311) [Exact Mirror] handle property starts with a number\n- [#1310](https://github.com/elysiajs/elysia/issues/1310) webSocket fails to connect when inside group and guard\n- [#1309](https://github.com/elysiajs/elysia/issues/1309) encode is not called when using dynamic handler\n- [#1304](https://github.com/elysiajs/elysia/issues/1304) remove response body from HTTP 101, 204, 205, 304, 307, 308\n\nChange:\n- update exact mirror to 0.1.3\n- warn when stop is called instead of throwing an error\n\n# 1.3.6 - 24 Jul 2025\nImprovement:\n- [#1263](https://github.com/elysiajs/elysia/pull/1263) bun adapter add qi to routes that need query from guard\n- [#1270](https://github.com/elysiajs/elysia/pull/1270) add Symbol.dispose\n- [#1089](https://github.com/elysiajs/elysia/pull/1089) add stop function to ElysiaAdapter type\n\nBug fix:\n- [#1126](https://github.com/elysiajs/elysia/pull/1126) websocket errors not catching\n- [#1281](https://github.com/elysiajs/elysia/issues/1281) automatically enforce additional properties in nested schema (eg. array)\n- Dynamic handle decode signed cookie secret instead of accidental hardcoded value\n\n# 1.3.5 - 16 Jun 2025\nBug fix:\n- [#1255](https://github.com/elysiajs/elysia/issues/1255) regression in serving an imported HTML file\n- [#1251](https://github.com/elysiajs/elysia/issues/1251) property 'status' does not exist onError function\n- [#1247](https://github.com/elysiajs/elysia/pull/1247) ensure WebSockets get routed properly without AoT compilation\n- [#1246](https://github.com/elysiajs/elysia/issues/1246) property 'timeout' does not exist on type 'Server'\n- [#1245](https://github.com/elysiajs/elysia/issues/1245) error on onAfterHandle (no property 'response')\n- [#1239](https://github.com/elysiajs/elysia/issues/1239) t.Files validator breaks for response schema\n- [#1187](https://github.com/elysiajs/elysia/pull/1187), [#1169](https://github.com/elysiajs/elysia/issues/1169) websocket beforeLoad not being executed\n\n# 1.3.4 - 3 Jun 2025\nFeature:\n- sse helper\n\nBug fix:\n- [#1237](https://github.com/elysiajs/elysia/issues/1237) ws in a group merge error\n- [#1235](https://github.com/elysiajs/elysia/issues/1235) errors not handled correctly in resolve hook on dynamic mode\n- [#1234](https://github.com/elysiajs/elysia/issues/1234) optional path parameters can't follow required ones\n- [#1232](https://github.com/elysiajs/elysia/issues/1232) t.Files fails with array of files\n\nChange:\n- When yield is not sse, content-type is set to either `text/plain` or `application/json` based on the response type\n\n# 1.3.3 - 27 May 2025\nBug fix:\n- mapResponseContext is not passed to compose\n- await `ElysiaFile` when not using Bun\n- export `adapter/utils`\n\n# 1.3.2 - 27 May 2025\nFeature:\n- Support Bun native static response per method for Bun >= 1.2.14\n- [#1213](https://github.com/elysiajs/elysia/issues/1213) trace.time is undefined in .trace() callback\n\nImprovement:\n- implement all universal type\n- offload `AsyncGenerator`, `ReplaceFile` from Eden Treaty to `CreateEden`\n- [#1223](https://github.com/elysiajs/elysia/issues/1223) infer `status(200)` response from handler if not specified\n- [#1185](https://github.com/elysiajs/elysia/issues/1185) use non-greedy match for `isContextPassToFunction` to prevent false positive\n\n# 1.3.1 - 8 May 2025\nBug fix:\n- [#1200](https://github.com/elysiajs/elysia/issues/1200) limited Bun Router to supported method\n- [#1199](https://github.com/elysiajs/elysia/issues/1199) object are not normalized when t.Transform is provided\n- [#1198](https://github.com/elysiajs/elysia/issues/1198), [#1188](https://github.com/elysiajs/elysia/issues/1188), [#1186](https://github.com/elysiajs/elysia/issues/1186) exclude wildcard route from Bun router\n- [#1197](https://github.com/elysiajs/elysia/issues/1197) leave incorrect union field as-is\n- [#1195](https://github.com/elysiajs/elysia/issues/1195) invalid onAfterHandle typing\n- [#1194](https://github.com/elysiajs/elysia/issues/1194) normalize array response\n- [#1193](https://github.com/elysiajs/elysia/issues/1193) undefine value.schema.noValidate\n- [#1192](https://github.com/elysiajs/elysia/issues/1192) using a macro inside a group does not call the handler when using the `precompile` option\n- [#1190](https://github.com/elysiajs/elysia/issues/1190) derive and resolve handlers not being executed on WS context\n- [#1189](https://github.com/elysiajs/elysia/issues/1189) Type Inference Issue with Eden Treaty Group Endpoints\n- [#1185](https://github.com/elysiajs/elysia/issues/1185) path is missing from Context when Bun System Router is used\n- [#1184](https://github.com/elysiajs/elysia/issues/1184) Missing `mapEarlyResponse` on Bun System Router\n\nChange:\n- update `exact-mirror` to `0.1.2`\n\n# 1.3.0 - 5 May 2025\nFeature:\n- add `exactMirror`\n- add `systemRouter` config\n- `standalone Validator`\n- add `Elysia.Ref` for referencing schema with autocompletion instead of `t.Ref`\n- support Ref inside inline schema\n- add sucrose cache\n- new validation `t.Form`, `t.NoValidate`\n- use `file-type` to check file type\n- add `INVALID_FILE_TYPE` error\n- add `sanitize` options\n\nImprovement:\n- `encodeSchema` now stable and enabled by default\n- optimize types\n- reduce redundant type check when using Encode\n- optimize isAsync\n- unwrap Definition['typebox'] by default to prevent unnecessary UnwrapTypeModule call\n- Elysia.form can now be type check\n- refactor type-system\n- refactor `_types` into `~Types`\n- using aot compilation to check for custom Elysia type, eg. Numeric\n- refactor `app.router.static`, and move static router code generation to compile phase\n- optimize memory usage on `add`, `_use`, and some utility functions\n- improve start up time on multiple route\n- dynamically create cookie validator as needed in compilation process\n- reduce object cloning\n- optimize start index for finding delimiter of a content type header\n- Promise can now be a static response\n- `ParseError` now keeps stack trace\n- refactor `parseQuery` and `parseQueryFromURL`\n- add `config` options to `mount`\n- recompile automatically after async modules is mounted\n- support macro on when hook has function\n- support resolve macro on ws\n- [#1146](https://github.com/elysiajs/elysia/pull/1146) add support to return web API's File from handler\n- [#1165](https://github.com/elysiajs/elysia/pull/1165) skip non-numeric status codes in response schema validation\n- [#1177](https://github.com/elysiajs/elysia/issues/1177) cookie does not sign when an error is thrown\n\nBug fix:\n- `Response` returned from `onError` is using octet stream\n- unintentional memory allocation when using `mergeObjectArray`\n- handle empty space on Date query\n\nChange:\n- only provide `c.request` to mapResponse when `maybeStream` is true\n- use plain object for `routeTree` instead of `Map`\n- remove `compressHistoryHook` and `decompressHistoryHook`\n- webstandard handler now return `text/plain` if not on Bun\n- use non const value for `decorate` unless explicitly specified\n- `Elysia.mount` now set `detail.hide = true` by default\n\nBreaking Change:\n- remove `as('plugin')` in favor of `as('scoped')`\n- remove root `index` for Eden Treaty\n- remove `websocket` from `ElysiaAdapter`\n- remove `inference.request`\n\n# 1.2.25 - 6 Mar 2025\nBug fix:\n- [#1108](https://github.com/elysiajs/elysia/issues/1108) use validation response instead of return type when schema is provided\n- [#1105](https://github.com/elysiajs/elysia/pull/1105), [#1003](https://github.com/elysiajs/elysia/issues/1003) invalid parsing body with missed fields if used object model\n\n# 1.2.24 - 2 Mar 2025\nBug fix:\n- 200 object response is not inferring type in type-level\n- [#1091](https://github.com/elysiajs/elysia/issues/1091) route is not defined when using trace\n\n# 1.2.23 - 25 Feb 2025\nBug fix:\n- [#1087](https://github.com/elysiajs/elysia/pull/1087) websocket to parse string array\n- [#1088](https://github.com/elysiajs/elysia/pull/1088) infinite loop when inference body is empty\n\n# 1.2.22 - 24 Feb 2025\nBug fix:\n- [#1074](https://github.com/elysiajs/elysia/pull/1074) hasTransform doesn't detect Transform on root\n- [#873](https://github.com/elysiajs/elysia/issues/873#issuecomment-2676628776) encode before type check\n\n# 1.2.21 - 22 Feb 2025\nBug fix:\n- [#671](https://github.com/elysiajs/elysia/issues/671#issuecomment-2676263442) Transform inside t.Intersect isn't detected\n\n# 1.2.20 - 22 Feb 2025\nBug fix:\n- [#671](https://github.com/elysiajs/elysia/issues/671#issuecomment-2675777040) Transform query schema check fails\n- model type\n\n# 1.2.19 - 22 Feb 2025\nBug fix:\n- [#1078](https://github.com/elysiajs/elysia/issues/1078) array string default to '[]' instead of undefined\n\n# 1.2.18 - 22 Feb 2025\nBug fix:\n- duplicated static route may cause index conflict resulting in incorrect route\n\n# 1.2.17 - 21 Feb 2025\nBug fix:\n- `.mount` doesn't return pass entire request\n\n# 1.2.16 - 21 Feb 2025\nImprovement:\n- `AfterHandler` infer response type\n\nChange:\n- [#1068](https://github.com/elysiajs/elysia/issues/1068) update `@sinclair/typebox` to `0.34.27`\n\nBug fix:\n- [#1075](https://github.com/elysiajs/elysia/issues/1075) nested async plugins mismatch routes to handlers\n- [#1073](https://github.com/elysiajs/elysia/issues/1073) file type validation not working\n- [#1070](https://github.com/elysiajs/elysia/issues/1070) .mount is mutating the incoming request method\n- mount path is incorrect when using prefix with trailing `*`\n- [#873](https://github.com/elysiajs/elysia/issues/873) add `experimental.encodeSchema` for custom `Transform` Encode type\n\n# 1.2.15 - 19 Feb 2025\nBug fix:\n- [#1067](https://github.com/elysiajs/elysia/issues/1067) recompile async plugin once registered\n- [#1052](https://github.com/elysiajs/elysia/issues/1052) webSocket errors not getting catched by error handler\n- [#1038](https://github.com/elysiajs/elysia/issues/1038) incorrect type inference with deferred modules leads to TypeErrors in runtime\n- [#1015](https://github.com/elysiajs/elysia/issues/1015) using a model by name in route query leads to type mispatch, yet validation succeeds if doesn't use Ref\n- [#1047](https://github.com/elysiajs/elysia/issues/1047) ampersand in URL search params is discarded\n- detect `Transform` inside `t.Array` in `hasTransform`\n\nImprovement:\n- add test cases for `hasTransform`\n- `hasTransform` now supports Union, Intersect\n- remove redundant `decodeURIComponent` in nested query\n\n# 1.2.14 - 17 Feb 2025\nFeature:\n- parse nuqs string array format if query is specified as `t.Array(t.String())`\n\nImprovement:\n- handle recursive nested async plugin\n- Response now handle proxy streaming\n- [#971](https://github.com/elysiajs/elysia/issues/971) wrap import(\"fs/promises\") AND wrap import(\"fs\") in try-catch to avoid error (silly me, tee-hee~)\n- handle nested array property swap for `replaceSchemaType`\n\nBreaking Change:\n- [Internal] `Elysia.modules` now return void\n\n# 1.2.13 - 16 Feb 2025\nImprovement:\n- [#977](https://github.com/elysiajs/elysia/pull/977) use Registry instead of TypeSystem\n- remove redundant switch-case for path mapping when strictPath is disabled and path is overlapped\n- remove redundant allocation for nativeStaticHanlder when strictPath path is overlapped\n\nBug fix:\n- [#1062](https://github.com/elysiajs/elysia/pull/1062) correctly set t.Date() defaults\n- [#1050](https://github.com/elysiajs/elysia/issues/1050) app.onRequest(ctx => {ctx.server}): Can't find variable: getServer\n- [#1040](https://github.com/elysiajs/elysia/pull/1040) undefined route context on aot=false\n- [#1017](https://github.com/elysiajs/elysia/pull/1017) replace t.Number() for Type.Integer()\n- [#976](https://github.com/elysiajs/elysia/pull/976) error responses with aot: false\n- [#975](https://github.com/elysiajs/elysia/pull/975) await nested async plugins\n- [#971](https://github.com/elysiajs/elysia/issues/971) wrap import(\"fs/promises\") in try-catch to avoid error\n- [discord](https://discord.com/channels/1044804142461362206/1289400305506844672/1289400305506844672) file format doesn't check for '*' format\n\n# 1.2.12 - 4 Feb 2025\nBug fix:\n- warn when non-existing macro is used\n- parser doesn't generate optimize instruction\n\n# 1.2.11 - 1 Feb 2025\nFeature:\n- Reduce memory usage:\n\t- Compressed lifecycle event\n\t- Avoid unnecessary declaration in compose.ts\n\t- Lazily build radix tree for dynamic router\n\nChange:\n- Update TypeBox to 0.34.15\n\nBug fix:\n- [#1039](vhttps://github.com/elysiajs/elysia/issues/1039) Elysia fails to start with an error inside its own code when using decorate twice with Object.create(null)\n- [#1005](https://github.com/elysiajs/elysia/issues/1005) Parsing malformed body with NODE_ENV 'production' results in UNKNOWN error\n- [#1037](https://github.com/elysiajs/elysia/issues/1037) Validation errors in production throw undefined is not an object (evaluating 'error2.schema')\n- [#1036](https://github.com/elysiajs/elysia/issues/1036) Support Bun HTML import\n\n# 1.2.10 - 5 Jan 2025\nFeature:\n- add shorthand property for macro function\n\nImprovement:\n- use `deuri` instead of `fast-decode-uri-component`\n- [#985](https://github.com/elysiajs/elysia/issues/985) MaybeEmpty and Nullable should have options args\n\nBug fix:\n- Macro function doesn't inherits local/scoped derive and resolve in type-level\n\n# 1.2.9 - 28 Dec 2024\nBug fix:\n- Resolve macro unintentionally return instead of assign new context\n\n# 1.2.8 - 27 Dec 2024\nBug fix:\n- [#966](https://github.com/elysiajs/elysia/issues/966) generic error somehow return 200\n\n# 1.2.7 - 27 Dec 2024\nBug fix:\n- macro doesn't work with guard\n- [#981](https://github.com/elysiajs/elysia/issues/981) unable to deference schema, create default, and coerce value\n- [#966](https://github.com/elysiajs/elysia/issues/966) `error`'s value return as-if when thrown\n- [#964](https://github.com/elysiajs/elysia/issues/964) InvalidCookieSignature errors are not caught by onError\n- [#952](https://github.com/elysiajs/elysia/issues/952) onAfterResponse does not provide mapped response value unless aot is disabled\n- `mapResponse.response` is `{}` if no response schema is provided\n- Response doesn't reconcile when handler return `Response` is used with `mapResponse`\n- `onError` now accepts `error` as `number` when `Elysia.error` is thrown (but not returned)\n\n# 1.2.6 - 25 Dec 2024\nBug fix:\n- mapResponse with onError caused compilation error\n\n# 1.2.5 - 25 Dec 2024\nBug fix:\n- define universal/file in package export\n\n# 1.2.4 - 25 Dec 2024\nBug fix:\n- performance regression from eager access abortSignal\n\n# 1.2.3 - 25 Dec 2024\nBug fix:\n- [#973](https://github.com/elysiajs/elysia/issues/973) Parsing malformed body results in `UNKNOWN`-Error instead of `ParseError`\n- [#971](https://github.com/elysiajs/elysia/issues/971) remove top level import, use dynamic import instead\n- [#969](https://github.com/elysiajs/elysia/issues/969) Invalid context on `.onStart`, `.onStop`\n- [#965](https://github.com/elysiajs/elysia/issues/965) [Composer] failed to generate optimized handler. Unexpected identifier 'mapCompactResponse'\n- [#962](https://github.com/elysiajs/elysia/pull/962) fix schema default value when AOT is of\n- decorator name with space is not working\n\n# 1.2.2 - 24 Dec 2024\nBug fix:\n- conditional import and require\n\n# 1.2.1 - 23 Dec 2024\nBug fix:\n- conditional import for fs\n- object macro parameter maybe array\n- optional return for macro\n\n# 1.2.0 - 23 Dec 2024\nFeature:\n- Commitment to Universal Runtime Support\n    - Node Adapter\n    - Web Standard Adapter\n    - Bun Adapter\n    - Universal Utilities\n- Name parser\n- Add resolve support to Macro\n- Improve WebSocket\n    - Support ping, pong and latest Bun feature\n    - Match type declaration with Bun\n    - Support for return, yield\n    - Match Context type\n    - Performance Improvement\n        - Entire rewrite\n        - bind over getter return\n- Infer 422 validation\n- Compilation minification\n- Validation Stuff\n    - t.MaybeArray\n- Typebox Module & Nested model\n    - Inline module\n\nImprovement:\n- Memory Usage\n    - [Internal] Register loosePath in compilation process to reduce memory usage and reduce registration time from O(2n) to O(n)\n- Try to accept and coerce different version of Elysia plugin\n- Event Listener now infers path parameter automatically based on scope\n- Add ‘scoped’ to bulk `as` for casting type to ‘scoped’ similar to ‘plugin’\n\nChange:\n- Update `cookie` to 1.0.1\n- Update TypeBox to 0.33\n- `content-length` now accept number\n\nBreaking Change:\n- [Internal] Remove router internal property static.http.staticHandlers\n- [Internal] Router history compile now link with history composed\n\n# 1.1.27 - 23 Dec 2024\nBug fix:\n- [#963](https://github.com/elysiajs/elysia/pull/963) array parser on query string when AOT is off\n- [#961](https://github.com/elysiajs/elysia/pull/961) literal handler when AOT is off\n\n# 1.1.26 - 4 Dev 2024\nBug fix:\n- [#907](https://github.com/elysiajs/elysia/issues/907), [#872](https://github.com/elysiajs/elysia/issues/872), [#926](https://github.com/elysiajs/elysia/issues/926) BooleanString is not behave correctly if property is not provided\n- [#929](https://github.com/elysiajs/elysia/issues/929) Non-ASCII characters cause querystring index to be incorrectly slice\n- [#912](https://github.com/elysiajs/elysia/issues/912) handle JavaScript date numeric offset\n\n# 1.1.25 - 14 Nov 2024\nBug fix:\n- [#908](https://github.com/elysiajs/elysia/pull/908) boolean-string converted to string\n- [#905](https://github.com/elysiajs/elysia/pull/905) avoid response normailization side effects\n\nChange:\n- don't minify identifiers in bun bundle\n\n# 1.1.24 - 31 Oct 2024\nSecurity:\n- [#891](https://github.com/elysiajs/elysia/pull/891) Upgrade Cookie to 0.7.x to fix CVE-2024-47764\n\nBug fix:\n- [#885](https://github.com/elysiajs/elysia/pull/885) unwrap transform errors\n- [#903](https://github.com/elysiajs/elysia/pull/903) typebox object schemas without properties key\n\n# 1.1.23 - 22 Oct 2024\nBug fix:\n- Handle object with `.then` even if it's not promise (looking at you, Drizzle)\n\n# 1.1.22 - 13 Oct 2024\nBug fix:\n- Fix `set-cookie` to resent if value is accessed even without set\n\n# 1.1.21 - 13 Oct 2024\nImprovement:\n- infer 200 response from handle if not specified\n\n# 1.1.20 - 10 Oct 2024\nBug fix:\n- merge guard and not specified hook responses status\n\n# 1.1.19 - 7 Oct 2024\nBug fix:\n- unable to return `error` from derive/resolve\n\n# 1.1.18 - 4 Oct 2024\nBreaking change:\n- remove automatic conversion of 1-level deep object with file field to formdata\n\t- migration: wrap a response with `formdata`\n- (internal): remove `ELYSIA_RESPONSE` symbol\n- (internal) `error` now use `class ElysiaCustomStatusResponse` instead of plain object\n\nImprovement:\n- Optimize `object type` response mapping performance\n\n# 1.1.17 - 29 Sep 2024\nChange:\n- Coerce number to numeric on body root automatically\n- Coerce boolean to booleanString on body root automatically\n\nBug fix:\n- [#838](https://github.com/elysiajs/elysia/issues/838) invalid `onAfterResponse` typing\n- [#855](https://github.com/elysiajs/elysia/issues/855) Validation with Numeric & Number options doesn't work\n- [#843](https://github.com/elysiajs/elysia/issues/843) Resolve does not work with aot: false\n\n# 1.1.16 - 23 Sep 2024\nBug fix:\n- separate between `createStaticHandler` and `createNativeStaticHandler` for maintainability\n- performance degradation using inline fetch on text static response and file\n\n# 1.1.15 - 23 Sep 2024\nBug fix:\n- `createStaticResponse` unintentionally mutate `set.headers`\n\n# 1.1.14 - 23 Sep 2024\nFeature:\n- add auto-completion to `Content-Type` headers\n\nBug fix:\n- exclude file from Bun native static response until Bun support\n- set 'text/plain' for string if no content-type is set for native static response\n\n# 1.1.13 - 18 Sep 2024\nFeature:\n- [#813](https://github.com/elysiajs/elysia/pull/813) allow UnionEnum to get readonly array by @BleedingDev\n\nBug fix:\n- [#830](https://github.com/elysiajs/elysia/issues/830) Incorrect type for ws.publish\n- [#827](https://github.com/elysiajs/elysia/issues/827) returning a response is forcing application/json content-type\n- [#821](https://github.com/elysiajs/elysia/issues/821) handle \"+\" in query with validation\n- [#820](https://github.com/elysiajs/elysia/issues/820) params in hooks inside prefixed groups are incorrectly typed never\n- [#819](https://github.com/elysiajs/elysia/issues/819) setting cookie attribute before value cause cookie attribute to not be set\n- [#810](https://github.com/elysiajs/elysia/issues/810) wrong inference of response in afterResponse, includes status code\n\n# 1.1.12 - 4 Sep 2024\nFeature:\n- setup provenance publish\n- [#808](https://github.com/elysiajs/elysia/pull/808) add UnionEnum type with JSON schema enum usage\n- [#807](https://github.com/elysiajs/elysia/pull/807) add closeActiveConnections to Elysia.stop()\n\nBug fix:\n- [#808](https://github.com/elysiajs/elysia/pull/808) ArrayString type cast as Object instead of Array\n- config.nativeStaticResponse is not defined\n\n# 1.1.11 - 1 Sep 2024\nFeature:\n- native Bun static response\n\t- can be disabled by setting `app.config.nativeStaticResponse = false`\n- [#93](https://github.com/elysiajs/elysia/issues/93) export TypeSystemPolicy\n- [#752](https://github.com/elysiajs/elysia/issues/752) tye coercion on dynamic mode\n\nBug fix:\n- [#332](https://github.com/elysiajs/elysia/issues/332) mount() does not preserve body when fetching through http server\n- Using as('plugin') cast cause derive key to be unknown\n\n# 1.1.10 30 Aug 2024\nBug fix:\n- incorrect named export 'fasti-querystring' to 'fast-querystring'\n\n# 1.1.9 - 28 Aug 2024\nChange:\n- getter fields no longer stringified to JSON by default on returning response\n\nBug fix:\n- [#796](https://github.com/elysiajs/elysia/issues/796) ValueClone: Unable to clone value after 1.1.8 update\n- [#795](https://github.com/elysiajs/elysia/issues/795) Broken Dates after 1.1.8 update\n- [#793](https://github.com/elysiajs/elysia/issues/793) Unable to delete property. t.File()\n\n# 1.1.8 - 27 Aug 2024\nFeature:\n- [#748](https://github.com/elysiajs/elysia/issues/748) add standardHostname config\n\nBug fix:\n- [#787](https://github.com/elysiajs/elysia/issues/787) [#789](https://github.com/elysiajs/elysia/issues/789) [#737](https://github.com/elysiajs/elysia/issues/737) Unexpected TypeError on NODE_ENV=production in mapValueError\n- [#793](https://github.com/elysiajs/elysia/issues/793) unable to delete property t.File()\n- [#780](https://github.com/elysiajs/elysia/issues/780) error from sending empty body multipart/form-data\n- [#779](https://github.com/elysiajs/elysia/issues/779) custom errors thrown in onRequest are not usable when caught in onError\n- [#771](https://github.com/elysiajs/elysia/issues/771) error from body-parser when sent Content-Type header without body\n- [#679](https://github.com/elysiajs/elysia/issues/679) plugin registered by async inline function don't work\n- [#670](https://github.com/elysiajs/elysia/issues/670) support for classes and getter fields\n\n# 1.1.7 - 19 Aug 2024\nBug fix:\n- `parseQuery` is not parsing array on body\n\nChange:\n- rename `parseQuery` to `parseQueryFromURL`\n- export fast-querystring.js path\n\n# 1.1.6 - 12 Aug 2024\nFeature:\n- [#763](https://github.com/elysiajs/elysia/pull/763) add hide in detail to hide route from OpenAPI/swagger\n- add streaming support for fetch proxy\n\nBug fix:\n- [#776](https://github.com/elysiajs/elysia/issues/776) custom errors throw in onRequest do not get proper code set in onError\n\n# 1.1.5 - 2 Aug 2024\nFeature:\n- refactor fastQuerystring using switch and bitwise flag\n\nBug fix:\n- sucrose: invalid separateFunction on minified async function\n- [#758](https://github.com/elysiajs/elysia/issues/758) guard doesn't apply cookie schema\n\n# 1.1.4 - 23 Jul 2024\nFeature:\n- [#718](https://github.com/elysiajs/elysia/pull/718) implement normalization support for class instances with getter functions\n\nBug fix:\n- removeColonAlias accidentally slice -2 end index for last parameter\n- [#726](https://github.com/elysiajs/elysia/pull/726) lazy instantiation of `stringToStructureCoercions`\n- [#750](https://github.com/elysiajs/elysia/issues/750) Cookie: Right side of assignment cannot be destructured\n- [#749](https://github.com/elysiajs/elysia/issues/749) Query params following an array query are parsed as array items\n- [#751](https://github.com/elysiajs/elysia/issues/751) Dynamic mode response failed if null or undefined value is returned\n- [#741](https://github.com/elysiajs/elysia/issues/741) stream stringify object\n\n# 1.1.3 - 17 Jul 2024\nChange:\n- sucrose: exact inference name\n- use `mapResponse` instead of `mapCompactResponse` for stream\n\t- [#727](https://github.com/elysiajs/elysia/issues/727)\n- defers first stream execution before returning response\n\t- [#729](https://github.com/elysiajs/elysia/issues/729)\n- [#722](https://github.com/elysiajs/elysia/issues/722) derive context is not passed to onError\n\nBug fix:\n- `onError` with scope not being able to infer context type\n\n# 1.1.2 - 16 Jul 2024\nBug fix:\n- [#724](https://github.com/elysiajs/elysia/issues/724), [bun#12594](https://github.com/oven-sh/bun/issues/12594) sucrose: possibly fix `bun build --compile` not being able to infer first, and last context parameter\n- derive is being override by resolve in certain function\n\t- [#722](https://github.com/elysiajs/elysia/issues/722) Type error with global `app.derive` followed by onError\n- params on `onError` is now `{ [key in string]: string }` instead of `never`\n- [#721](https://github.com/elysiajs/elysia/issues/721) unexpected isContextPassToFunction: minified whitespace of arrow function causing inaccurate separateFunction\n\n# 1.1.1 - 16 Jul 2024\nBreaking Change:\n- parse query as `string` instead of `string | string[]` unless specified\n\n# 1.1.0 - 16 Jul 2024\nFeature:\n- Trace v2\n- Normalization is on by default\n- Data type coercion\n- Guard as, bulk as cast\n- Response status coercion\n- Optional path parameter\n- Generator response stream\n\nBreaking Change:\n- Parse value as string for all validators unless explicitly specified.\n    - See [50a5d92](https://github.com/elysiajs/elysia/commit/50a5d92ea3212c5f95f94552e4cb7d31b2c253ad), [44bf279](https://github.com/elysiajs/elysia/commit/44bf279c3752c6909533d19c83b24413d19d27fa).\n    - Remove objects auto-parsing in query unless explicitly specified via query\n   \t- Except query string as defined in RFC 3986, TLDR; query string could be either string or array of string.\n- Rename `onResponse` to `onAfterResponse`\n- [Internal] Remove $passthrough in favor of toResponse\n- [Internal] UnwrapRoute type now always resolve with status code\n\nImprovement:\n- Add auto-complete for `set.headers`\n- Add `server` property\n- `onError` supports array function\n- Parse query object with and without schema\n- Sucrose: improve isContextPassToFunction, and extractMainParameter stability\n- Add `replaceSchemaType`\n- Add `route` to `context`\n- Optimize recursive MacroToProperty type\n- Parse query array and object\n- Optimize code path for `composeGeneralHandler`\n- Add debug report on compiler panic\n- Reduce memory usage of route registration ~36% on large codebase\n    - Reduce compilation code path\n    - Remove trace inference\n    - Reduce router compilation code path\n    - removing route handler compilation cache (st${index}, stc${index})\n- Add undefined union to cookie in case if cookie is not present\n- Optimize response status resolve type inference\n\nChange:\n- Deprecated `ObjectString` for parsing array\n- Using `Cookie<unknown>` instead of `Cookie<any>` if schema is not defined\n- Remove prototype poluation from hook\n- remove static analysis for query name\n- remove query replace '+' in favor removing static query analysis\n- mapResponse is now called in error event\n- reconcilation decorator in type level\n\nBug fix:\n- Normalize headers accidentally use query validator check instead\n- `onError` missing trace symbol\n- Headers validator compilation is not cached\n- Deduplicate macro propagation\n- Websocket in nested group now work\n- Error response is not check unless successful status code is provided\n\n# 1.0.27 - 2 Jul 2024\nBug fix:\n- [#640](https://github.com/elysiajs/elysia/issues/640) Unable to access root level macros in plugins\n- [#606](https://github.com/elysiajs/elysia/issues/606) Object encoding in query parameters\n\n# 1.0.26 - 30 Jun 2024\nBug fix:\n- mapResponse is not called on beforeHandle, and afterHandle\n\n# 1.0.25 - 21 Jun 2024\nBug fix:\n- type is resolved as `File` if `@types/bun` is not installed when using with Eden Treaty\n\n# 1.0.24 - 18 Jun 2024\nBug fix:\n- `derive`, `resolve` support void return\n- [#677](https://github.com/elysiajs/elysia/issues/677) Query params validation for array of string fail\n\n# 1.0.23 - 9 Jun 2024\nFeature:\n- add `toResponse` for mapping custom response\n- [#606](https://github.com/elysiajs/elysia/issues/606) Object encoding in query parameters\n\nBug fix:\n- [#654](https://github.com/elysiajs/elysia/pull/654) set correct normalization behavior for addtional properties\n- [#649](https://github.com/elysiajs/elysia/pull/649) cookie decode value might be null\n- [#664](https://github.com/elysiajs/elysia/issues/664) \"default\" option is not being applied on validation\n- [#656](https://github.com/elysiajs/elysia/issues/656) ctx.query doesn't work in some case\n    - set forceDynamicQuery to true by default\n- [#658](https://github.com/elysiajs/elysia/issues/658) aot does not recognize the use of ctx.body within a try catch\n- [#630](https://github.com/elysiajs/elysia/issues/630) accessing ctx.query directly breaks the object\n\n# 1.0.22 - 23 May 2024\nBreaking Change:\n- set default cookie path to `/`\n\nFeature:\n- add `form` utility for returning explicit formdata\n- add object with image to return as `formdata`\n\nBug fix:\n- return `Bun.file` by specifying `t.File()` and `t.Object({ any: t.File() })` as a response\n\n# 1.0.21 - 21 May 2024\nBreaking Change:\n- `t.type({ error })` now accepts `(error: ({ type, validator, value, errors }) => unknown)` instead of `(error: (type, validator, value) => unknown)`\n\nImprovement:\n- `t.type({ error })` accepts `string | number | boolean | Object` instead of `string`\n- `t.type({ error })` return `string | number | boolean | Object | void` instead of `string`\n- add `errors: ValueError[]` to `t.type({ error({ errors }) {} })`\n\nBug fix:\n- [#644](https://github.com/elysiajs/elysia/issues/644) redirect doesn't work with `aot: false`\n- [#641](https://github.com/elysiajs/elysia/issues/641) cookie schema validation doesn't work with `aot: true`\n- [#615](https://github.com/elysiajs/elysia/issues/615) highlight derive and resolve when using `onError`\n\n# 1.0.20 - 13 May 2024\nBug fix:\n- macro is not inherits inside group\n\n# 1.0.19 - 13 May 2024\nBug fix:\n- remove set.clone spread operator for mapping Response\n\n# 1.0.18 - 11 May 2024\nFeature:\n- add support for partitioned cookie\n\nBug fix:\n- recursive MacroToProperty type on unknown macro\n\n# 1.0.17 - 9 May 2024\nImprovement:\n- add context.url to get full URL string (including query)\n- reduce query parsing instruction\n\n# 1.0.16 - 2 May 2024\nBug fix:\n- [ratelimit#28](https://github.com/rayriffy/elysia-rate-limit/issues/28) trace hang when using server-timing with rate-limit plugin\n\n# 1.0.15 - 27 Apr 2024\nFeature:\n- add `redirect` function to `Context`\n\nImprovement:\n- sucrose: remove unreachable query bracket check, reduce bracket instruction\n- sucrose: query accessor keyword check at initialization instead of in loop\n- sucrose: remove accessor check\n- sucrose: skip query check for immediate return\n\nChange:\n- sucrose: add `isArrowReturn` to `separateFunction`\n- sucrose: skip inference queries check if `query` is not found\n\nChange:\n- allow custom parser when `type` is specified\n- add `contentType` to context\n- soft deprecate `contentType` as 2nd `parse` parameter\n\nBug fix:\n- [#622](https://github.com/elysiajs/elysia/issues/622) sucrose: mistake cookie for query\n- duplicate format found\n- using `parse`, `type`, `body` generate invalid syntax\n\n# 1.0.14 - 22 Apr 2024\nImprovement:\n- [#596](https://github.com/elysiajs/elysia/pull/596) account for 20x response status schemas for type safety\n\nBug fix:\n- [#615](https://github.com/elysiajs/elysia/issues/615)\n- [588](https://github.com/elysiajs/elysia/issues/588) separate async derive/resolve function doesn't get await\n- primitive thrown result in invalid type\n\n# 1.0.12 - 5 Apr 2024\nImprovement:\n- export `InferContext` and `InferHandler`\n\nBug fix:\n- remove accidental `console.log` in `compile`\n\n# 1.0.12 - 5 Apr 2024\nFeature:\n- add `InferContext`\n\nBug fix:\n- returning null with response validation cause error\n\n# 1.0.11 - 2 Apr 2024\nBug fix:\n- possibly fix for \"Duplicate type kind 'Files' detected\"\n- add ajv-formats\n- [#562](https://github.com/elysiajs/elysia/pull/575) %26 (&) to be interpreted as & (query separator)\n\n# 1.0.10 - 30 Mar 2024\nBug fix:\n- [ServerTiming#1](https://github.com/elysiajs/elysia-server-timing/issues/1) late beforeHandle on set trace inference doesn't produce exit instruction\n\n# 1.0.9 - 25 Mar 2024\nFeature:\n- `Elysia.config.detail` constructor\n- shorthand `Elysia.tags` to constructor, `LocalHook`\n- guard inherits detail\n\nBug fix:\n- inference link on `precompile: false` creating unnecessary instruction\n\n# 1.0.8 - 25 Mar 2024\nFeature:\n- [#562](https://github.com/elysiajs/elysia/pull/562) add `normalize` config\n\nImprovement:\n- Scope cookie instruction to route level instead of global config\n- [#557](https://github.com/elysiajs/elysia/pull/557) cache tsc buildinfo for running faster\n- [#551](https://github.com/elysiajs/elysia/pull/551) use AnyElysia instead of inline Elysia<any>\n\nBug fix:\n- [#564](https://github.com/elysiajs/elysia/pull/564) Fixing \"ReadableStream is locked\"\n- [#552](https://github.com/elysiajs/elysia/pull/552) fix: shift promise in PromiseGroup even when rejected\n\n# 1.0.7 - 20 Mar 2024\nFeature:\n- add Elysia.propagate to propagate hook type from 'local' to 'scoped'\n\nImprovement:\n- remove function.$elysia\n- remove function extension\n\nBug fix:\n- duplicate macro call\n- [#548](https://github.com/elysiajs/elysia/issues/548) additional case for \"accessing all query params using property name (ctx.query) doesn't work anymore\"\n- [#599](https://github.com/elysiajs/elysia/issues/559) plugin with scoped settings not functioning correctly\n\n# 1.0.6 - 20 Mar 2024\nBug fix:\n- inline function doesn't propagate correctly on type level\n\n# 1.0.5 - 19 Mar 2024\nImprovement:\n- using regex for date pattern matching before using new Date validation\n- using tsc to emit declaration file instead of tsup\n- add `mapResponse` to MacroManager\n\nBug fix:\n- Ephemeral and Volatile type isn't recognize by MacroManager\n- inline guard cookie doesn't apply to local instance\n\n# 1.0.4 - 18 Mar 2024\nImprovement:\n- resolve, derive soundness\n\n# 1.0.3 - 18 Mar 2024\nImprovement:\n- Reduce instruction for static resource\n\nBug fix:\n- Fix returning mulitple status code using `error` doesn't accept the response\n\n# 1.0.2 - 18 Mar 2024\nFeature:\n- add `scoped` support for `derive` and `resolve`\n\nImprovement:\n- Type soundness\n- type inference performance improvement\n\n# 1.0.1 - 18 Mar 2024\nImprovement:\n- `mapHandler` now check passthrough once instead of twice\n- exclude return type of`ELYSIA_RESPONSE` type from `derive` and `resolve`\n- throw error if `error` is return in `derive` and `resolve`\n- handle `return error` on `transform`\n- [#502](https://github.com/elysiajs/elysia/pull/502) merge response schema from parent scope\n\nBug fix:\n- explicit `type: 'json'` with body schema throw unexpected `body.Check` is not a function\n- [#549](https://github.com/elysiajs/elysia/pull/549) await the .modules of nested Elysia instances\n- [#548](https://github.com/elysiajs/elysia/issues/548) Accessing all query params using property name (ctx.query) doesn't work anymore\n\n# 1.0.0 - 16 Mar 2024\nImprovement:\n- fine-grained reactive cookie\n- using single source of truth for cookie\n- macro support for websocket\n- add `mapResolve`\n- add `{ as: 'global' | 'scoped' | 'local' }` to lifecycle event\n- add ephemeral type\n- inline `error` to handler\n- inline `error` has auto-completion and type checking based on status code\n- handler now check return type of `error` based on status code\n- utility `Elysia._types` for types inference\n- [#495](https://github.com/elysiajs/elysia/issues/495) Provide user friendly error for failed parse\n- handler now infers return type for error status for Treaty\n- `t.Date` now allow stringified date\n- improves type test case\n- add test case for all life-cycle\n- resolve, mapResolve, derive, mapDerive use ephemeral type to scope down accurately\n- inference query dynamic variable\n\nBreaking Change:\n- [#513](https://github.com/elysiajs/elysia/issues/513) lifecycle is now local first\n\nChange:\n- group private API property\n- move `Elysia.routes` to `Elysia.router.history`\n- detect possible json before return\n- unknown response now return as-is instead of JSON.stringify()\n- change Elysia validation error to JSON instead of string\n- static content evalute hook JIT instead of AOT\n\nBug fix:\n- [#466](https://github.com/elysiajs/elysia/issues/466) Async Derive leaks request context to other requests if `aot: true`\n- [#505](https://github.com/elysiajs/elysia/issues/505) Empty ObjectString missing validation inside query schema\n- [#503](https://github.com/elysiajs/elysia/issues/503) Beta: undefined class when using decorate and derive\n- onStop callback called twice when calling .stop\n- mapDerive now resolve to `Singleton['derive']` instead of `Singleton['store']`\n- `ValidationError` doesn't return `content-type` as `application/json`\n- validate `error(status, value)` validate per status\n- derive/resolve always scoped to Global\n- duplicated onError call if not handled\n- [#516](https://github.com/elysiajs/elysia/issues/516) server timing breaks beforeHandle guards\n- cookie.remove() doesn't set correct cookie path\n\n# 0.8.17 - 12 Feb 2024\nFeature:\n- [#474](https://github.com/elysiajs/elysia/pull/474) Numeric Cookie with length >= 16 cant be parsed to number\n- [#476](https://github.com/elysiajs/elysia/pull/476) Using a query key that contains a hyphen or a dot raises a SyntaxError\n- [#460](https://github.com/elysiajs/elysia/pull/460)\n    - [#458](https://github.com/elysiajs/elysia/pull/458) Multiple scoped plugins do not register routes\n    - [#457](https://github.com/elysiajs/elysia/pull/457) Elysia arguments scoped and prefix do not work at the same time\n\nChange:\n- [#472](https://github.com/elysiajs/elysia/pull/472) Move documentation issue template to documentation repository\n\n# 0.8.16 - 6 Feb 2024\nFeature:\n- [#448](https://github.com/elysiajs/elysia/pull/448) BooleanString - @bogeychan\n\nBug fix:\n- [#451](https://github.com/elysiajs/elysia/pull/464) handle spread operator use on possible null or undefined\n- [#460](https://github.com/elysiajs/elysia/pull/460)\n    - [#457](https://github.com/elysiajs/elysia/pull/457) scoped plugin instances now respect the prefix property\n    - [#458](https://github.com/elysiajs/elysia/pull/458) adding a second scoped plugin does not unmount the route handler of a previously added scoped instance anymore.\n\n# 0.8.15 - 30 Jan 2024\nBug fix:\n- [#451](https://github.com/elysiajs/elysia/issues/451) macro does not run when it should (macro deduplication)\n- [#450](https://github.com/elysiajs/elysia/issues/450) Local hook parse doesn't get executed with `aot: false`\n\n# 0.8.14 - 26 Jan 2024\nBug fix:\n- types are missing in `exports.*`\n- [#441](https://github.com/elysiajs/elysia/issues/441) Vite doesn't get bundle without main\n\n# 0.8.13 - 26 Jan 2024\nBug fix:\n- types is not import\n- bun build regression on export * from '@sinclair/typebox/system'\n- update memoirist to use mjs\n\n# 0.8.12 - 26 Jan 2024\nChange:\n- using .mjs for es module\n\n# 0.8.11 - 26 Jan 2024\nChange:\n- using tsup instead of swc\n- [#441](https://github.com/elysiajs/elysia/issues/441) remove nanoid, using web crypto randomInt instead\n\nBug fix:\n- [#446](https://github.com/elysiajs/elysia/pull/446) numeric string check to use Number instead of parseInt\n- [#445](https://github.com/elysiajs/elysia/pull/445) empty body custom response when set.headers is empty\n\n# 0.8.10 - 24 Jan 2024\nBug fix:\n- [#440](https://github.com/elysiajs/elysia/pull/440) query params with + sign did not get converted\n- [#433](https://github.com/elysiajs/elysia/pull/433) remove crypto, unblock vite bundling, cloudflare worker support\n- [#422](https://github.com/elysiajs/elysia/pull/422) add check for instanceof if constructor.name doesn't match\n\n# 0.8.9 - 11 Jan 2024\nBug fix:\n- macro panic\n\n# 0.8.8. - 2 Jan 2024\nBug fix:\n- Add TypeBox back to Bun bundle\n\n# 0.8.7 - 1 Jan 2024\nImprovement:\n- [#385](https://github.com/elysiajs/elysia/issues/385) If error is instanceof Response, respond with it\n\nBug fix:\n- onRequest doesn't early return\n- handle thrown error function\n- [#373](https://github.com/elysiajs/elysia/issues/373) cookie is not set when File is return\n- [#379](https://github.com/elysiajs/elysia/issues/379) WebSocket: Sending a space character ' ' receives 0\n- [#317](https://github.com/elysiajs/elysia/issues/317) Exclude TypeBox from bundling\n\n# 0.8.6. - 29 Dec 2023\nBug fix:\n- body without default value thrown Object.assign error\n\n# 0.8.5. - 27 Dec 2023\nBug fix:\n- Bun entry point\n\n# 0.8.4. - 27 Dec 2023\nBug fix:\n- macro caused an Object.entries cannot be undefined\n- `mapResponse` and `afterHandle` missing decorators\n\n# 0.8.3. - 23 Dec 2023\nBug fix:\n- add early return on `isContextPassToFunction` for static content to prevent invalid regex\n\n# 0.8.2 - 23 Dec 2023\nBug fix:\n- `ctx.path` and `ctx.qi` is missing when using `onRequest`\n\n# 0.8.1 - 23 Dec 2023\nBug fix:\n- `be` is undefined when using `afterResponse` with `mapResponse`\n\n# 0.8.0 - 23 Dec 2023\nFeature:\n- `headers` initialization function\n- macro\n- static content\n- default property\n- error function\n- add stack trace to plugin checksum configurable by `config.analytic` (default to false)\n- new life-cycle\n    - `resolve`: derive after validation\n    - `mapResponse`: custom response mapping\n\nImprovement:\n- lazy query reference\n- add content-range header to `File` and `Blob` by default if etag is not used\n- update TypeBox to 0.32\n- override lifecycle response of `be` and `af`\n\nBreaking Change:\n- `afterHandle` no longer early return\n\nChange:\n- change validation response to JSON\n- differentiate derive from `decorator['request']` as `decorator['derive']`\n- `derive` now don't show infer type in onRequest\n\nBug fix:\n- remove `headers`, `path` from `PreContext`\n- remove `derive` from `PreContext`\n- Elysia type doesn't output custom `error`\n- `onStart` doesn't reflect server\n\n# 0.7.31 - 9 Dec 2023\nImprovement:\n- [#345](https://github.com/elysiajs/elysia/pull/345) add font to `SchemaOptions`\n- Update `@types/cookie` to `^0.6.0`\n\nBug fix:\n- [#338](https://github.com/elysiajs/elysia/pull/338) guard sandbox did not inherit global config.\n- [#330](https://github.com/elysiajs/elysia/pull/330) preserve query params for mounted handler\n- [#332](https://github.com/elysiajs/elysia/pull/332) reexport TSchema from typebox\n- [#319](https://github.com/elysiajs/elysia/pull/319) TypeBox Ref error when using Elysia.group()\n\n# 0.7.30 - 5 Dec 2023\nBug fix:\n- Emergency release override latest beta\n\n# 0.7.29 - 19 Nov 2023\nBug fix:\n- WebSocket params conflict with defined type\n- Inherits status code on custom error\n\n# 0.7.28 - 16 Nov 2023\nChore:\n- Update `cookie` to `0.6.0`\n\nBug fix:\n- [#314](https://github.com/elysiajs/elysia/pull/314) Unable to dereference schema with 'undefined' when using t.Ref\n\n# 0.7.27 - 16 Nov 2023\nBug fix:\n- [#312](https://github.com/elysiajs/elysia/issues/312) default params type suggestion for WebSocket\n- [#310](https://github.com/elysiajs/elysia/issues/310) Preserve original hostname when using `.mount()`\n- [#309](https://github.com/elysiajs/elysia/issues/309) t.RegExp doesn't work due to requiring default value\n- [#308](https://github.com/elysiajs/elysia/issues/308) t.Numeric should not convert empty string to 0\n- [#305](https://github.com/elysiajs/elysia/issues/305) Elysia({ scoped: true }) should still expose defined routes on type level\n- [#304](https://github.com/elysiajs/elysia/issues/304) Using a hook/guard/schema with a handler function and request without body results in a \"Unexpected end of JSON input\"-error\n- [#299](https://github.com/elysiajs/elysia/issues/299) Missing request.path parameter in .onRequest\n- [#289](https://github.com/elysiajs/elysia/issues/289) Ability to localize TypeBox errors\n- [#272](https://github.com/elysiajs/elysia/issues/272) onError handler has error property as undefined on Cloudflare Workers\n- [#210](https://github.com/elysiajs/elysia/issues/210) t.Numeric not validating properly\n- [#188](https://github.com/elysiajs/elysia/issues/188) Status codes of the error classes don't match the response through onError\n- [#140](https://github.com/elysiajs/elysia/issues/140) plugin hierarchy messes up derive function in child plugin\n- [#27](https://github.com/elysiajs/elysia/issues/27) Websocket definition in groups\n\n# 0.7.26 - 15 Nov 2023\nBug fix:\n- duplicated lifecycle event if using function plugin async\n\n# 0.7.25 - 14 Nov 2023\nBug fix:\n- Leaked type from `guard` callback and `group guard`\n\n# 0.7.24 - 8 Nov 2023\nBug fix:\n- add `ReadableStream` to response mapping to `mapResponse`\n\n# 0.7.23 - 8 Nov 2023\nBug fix:\n- Send `exit` status on early return with trace set\n\n# 0.7.22 - 8 Nov 2023\nChange:\n- Rewrite `trace`\n\nBug fix:\n- trace not awaiting multiple trace process\n- trace hang on early `beforeHandle` return\n- `afterHandle` with `trace.afterHandle` AoT cause duplicate value header\n\n# 0.7.21 - 27 Oct 2023\nBug fix:\n- [#281](https://github.com/elysiajs/elysia/pull/281) add cookie.remove options\n- add `await traceDone` to early return\n\n# 0.7.20 - 26 Oct 2023\nBug fix:\n- `trace` is stuck when inherits to plugin\n\nImprovement:\n- add unit test for `mapCompactResponse`, `Passthrough`\n\n# 0.7.19 - 25 Oct 2023\nBug fix:\n- add `$passthrough` for `mapCompactResponse`\n\n# 0.7.18 - 24 Oct 2023\nFeature:\n- add map handler for `ReadableStream`\n- add `$passthrough` for custom property for response mapping\n\nBug fix:\n- `.route` accept `string[]` instead of `string`\n\nChange:\n- remove `ElyEden`\n\n# 0.7.17 - 15 Oct 2023\nFeature:\n- add `ElyEden`\n- re-add `id` to websocket\n\nBug fix:\n- [#255](https://github.com/elysiajs/elysia/issues/255) removeCookie sends HTTP-Header that is ignored by the Browser\n- [#263](https://github.com/elysiajs/elysia/issues/263) http and websocket on same route\n- [#269](https://github.com/elysiajs/elysia/pull/269) Correct handling of Buffer object\n\n# 0.7.16 - 10 Oct 2023\nImprovement:\n- `t.Cookie` cookie option type\n- [#253](https://github.com/elysiajs/elysia/pull/253) platform agnostic cookie\n- Decorator like `state`, `decorate` and `derive`, doesn't apply to WebSocket `data`\n- re-export `Static` from\n\n# 0.7.15 - 26 Sep 2023\nChange:\n- Update TypeBox to 0.31.17\n- [#218](https://github.com/elysiajs/elysia/pull/218) Fix [#213](https://github.com/elysiajs/elysia/pull/213) prepend async redefined routes (partial fix)\n- Using set `onRequest` doesn't set headers and status on empty error handler\n\n# 0.7.14 - 26 Sep 2023\nBug fix:\n- Make `t.Files` parameter optional\n- model remap now using `TSchema` instead of literal type for creating type abstraction\n\n# 0.7.13 - 25 Sep 2023\nImprovement:\n- Using listener instead of microtick to handle `trace.set`\n- Set default cookie path to '/'\n\nBug fix:\n- Duplicate group path when hook is provided\n\n# 0.7.12 - 23 Sep 2023\nBug fix:\n- Handle cookie expire time\n- Set default value of config.cookie.path to '/'\n\n# 0.7.11 - 23 Sep 2023\nImprovement:\n- Skip cookie validation if schema is empty object\n\nBug fix:\n- Accept cookie property from constructor when schema is not defined\n\n# 0.7.10 - 23 Sep 2023\nBug fix:\n- handle FFI object in deepMerge, fix Prisma\n\n# 0.7.9 - 23 Sep 2023\nBug fix:\n- async instance cause config to be undefined\n\n# 0.7.8 - 23 Sep 2023\nBug fix:\n- async instance cause type conflict\n\n# 0.7.7 - 22 Sep 2023\nBug fix:\n- [#210](https://github.com/elysiajs/elysia/issues/210) `t.Numeric` allowing plain `String`\n- `t.ObjectString` allowing plain `String`\n- [#209](https://github.com/elysiajs/elysia/issues/209) `t.MaybeEmpty` tolerate `null` and `undefined`\n- [#205](https://github.com/elysiajs/elysia/issues/205) WebSocket routes not working in plugins\n- [#195](https://github.com/elysiajs/elysia/pull/195), [#201](https://github.com/elysiajs/elysia/pull/201) allow WebSocket destructuring\n\n# 0.7.6 - 21 Sep 2023\nBug fix:\n- Separate return type by status\n\n# 0.7.5 - 21 Sep 2023\nBug fix:\n- inject derive to `GraceHandler`\n\n# 0.7.4 - 21 Sep 2023\nBug fix:\n- check for class-like object\n- add `GraceHandler` to access both `app` and `context`\n\n# 0.7.3 - 21 Sep 2023\nBug fix:\n- resolve 200 by default when type is not provided\n\n# 0.7.2 - 20 Sep 2023\nBug fix:\n- decorator and store is resolved as `undefined` in `onError` hook\n- deepMerge with Module object\n- Retain comment in `.d.ts`\n\n# 0.7.1 - 20 Sep 2023\nBug Fix:\n- Class property is removed when calling deepMerge\n\n# 0.7.0 - 20 Sep 2023\nFeature:\n- rewrite type\n- rewrite Web Socket\n- add mapper method\n- add affix, prefix, suffix\n- trace\n- typeBox.Transfom\n- rewrite Type.ElysiaMeta to use TypeBox.Transform\n- new type:\n    - t.Cookie\n    - t.ObjectString\n    - t.MaybeEmpty\n    - t.Nullable\n- add `Context` to `onError`\n- lifecycle hook now accept array function\n- true encapsulation scope\n\nImprovement:\n- static Code Analysis now support rest parameter\n- breakdown dynamic router into single pipeline instead of inlining to static router to reduce memory usage\n- set `t.File` and `t.Files` to `File` instead of `Blob`\n- skip class instance merging\n- handle `UnknownContextPassToFunction`\n- [#157](https://github.com/elysiajs/elysia/pull/179) WebSocket - added unit tests and fixed example & api by @bogeychan\n- [#179](https://github.com/elysiajs/elysia/pull/179) add github action to run bun test by @arthurfiorette\n\nBreaking Change:\n- remove `ws` plugin, migrate to core\n- rename `addError` to `error`\n\nChange:\n- using single findDynamicRoute instead of inlining to static map\n- remove `mergician`\n- remove array routes due to problem with TypeScript\n\nBug fix:\n- strictly validate response by default\n- `t.Numeric` not working on headers / query / params\n- `t.Optional(t.Object({ [name]: t.Numeric }))` causing error\n- add null check before converting `Numeric`\n- inherits store to instance plugin\n- handle class overlapping\n- [#187](https://github.com/elysiajs/elysia/pull/187) InternalServerError message fixed to \"INTERNAL_SERVER_ERROR\" instead of \"NOT_FOUND\" by @bogeychan\n- [#167](https://github.com/elysiajs/elysia/pull/167) mapEarlyResponse with aot on after handle\n\n# 0.6.24 - 18 Sep 2023\nFeature:\n- [#149](https://github.com/elysiajs/elysia/pulls/149) support additional status codes in redirects\n\nImprovement:\n- [#157](https://github.com/elysiajs/elysia/pulls/157) added unit tests and fixed example & api\n\nBug fix:\n- [#167](https://github.com/elysiajs/elysia/pulls/167) mapEarlyResponse with aot on after handle\n- [#160](https://github.com/elysiajs/elysia/pulls/160) typo in test suite name\n- [#152](https://github.com/elysiajs/elysia/pulls/152) bad code in Internal server error class\n\n# 0.6.23 - 12 Sep 2023\nBug fix:\n- Maximum callstack for duplicated deep class / object\n- [#121](https://github.com/elysiajs/elysia/issues/121) Cannot use PrismaClient in .decorate or .state\n\n# 0.6.22 - 11 Sep 2023\nBug fix:\n- Remove `const` and `RemoveDeepWritable` from decorate to allow function call\n\n# 0.6.21 - 10 Sep 2023\nFeature:\n- [#112](https://github.com/elysiajs/elysia/issues/112) Route arrays\n\n# 0.6.20 - 9 Sep 2023\nBug fix:\n- [#107](https://github.com/elysiajs/elysia/issues/107) Elysia handler local hooks not recognizing registered errors on app instance\n\n# 0.6.19 - 7 Sep 2023\nBug fix:\n- Inherits state and error from plugin instance\n\n# 0.6.18 - 5 Sep 2023\nImprovement:\n- Automatically parse File to `Files` if set\n\n# 0.6.17 - 4 Sep 2023\nBug fix:\n- [#98](https://github.com/elysiajs/elysia/issues/98) Add context.set.cookie to accept array of string\n- [#92](https://github.com/elysiajs/elysia/pull/92) WebSocket beforeHandle unable to access plugins / state / derive's\n\n# 0.6.16 - 1 Sep 2023\nBug fix:\n- inherits `onError` lifecycle from plugin instance\n\n# 0.6.15 - 31 Aug 2023\nBug fix:\n- inherits `set` if `Response` is returned\n\n# 0.6.14 - 28 Aug 2023\nBug fix:\n- deduplicate plugin via global model\n- duplicated life-cycle\n- top-down plugin deduplication\n- plugin life-cycle leak on new model\n- add `Elysia.scope` to contain lifecycle, store, and decorators\n\n# 0.6.13 - 28 Aug 2023\nBug fix:\n- make this.server.reload optional to make Node compatability work\n- duplicate path name when using prefix config with group\n- don't filter local event inside new plugin model group\n- Remove post.handler in return\n\n# 0.6.12 - 26 Aug 2023\nBug fix:\n- Make this.server.reload optional to make Node compatability work\n\n# 0.6.11 - 16 Aug 2023\nBug fix:\n- [#86](https://github.com/elysiajs/elysia/issues/86) Group prefix repeating on inline function callback\n- [#88](https://github.com/elysiajs/elysia/issues/88), onResponse hooks validation return non 400\n\n# 0.6.10 - 13 Aug 2023\nBug fix:\n- Query is set to pathname when ? not presented in dynamic mode\n\n# 0.6.9 - 11 Aug 2023\nBug fix:\n- Derive not working on dynamic mode\n\n# 0.6.8 - 11 Aug 2023\nBug fix:\n- append routes on dynamic mode\n\n# 0.6.7 - 11 Aug 2023\nBug fix:\n- use: Plugin type inference\n\n# 0.6.6 - 11 Aug 2023\nBug fix:\n- Collide Elysia.prefix on other methods\n\n# 0.6.5 - 11 Aug 2023\nBug fix:\n- Collide Elysia.prefix type\n\n# 0.6.4 - 11 Aug 2023\nBug fix:\n- Collide Elysia.prefix type\n- Add skip group with prefix instance see [#85](https://github.com/elysiajs/elysia/pull/85)\n\n# 0.6.3 - 8 Aug 2023\nBug fix:\n- resolve .code and [ERROR_CODE]\n\n# 0.6.2 - 8 Aug 2023\nChange:\n- Add **ErrorCode** symbol\n\nBug fix:\n- Inline guard hook\n- Error code not handled\n- Set default query to {} when presented\n\n# 0.6.1 - 6 Aug 2023\nImprovement:\n- Drop usage of `node:process` to support Cloudflare Worker\n\n# 0.6.0 - 6 Aug 2023\nFeature:\n- Introducing Dynamic Mode (aot: false)\n- Introducing `.mount`\n- Introducing `.error` for handling Strict Error Type\n- Plugin checksum for plugin deduplication\n- Add `.onResponse`\n\nImprovement:\n- TypeBox 0.30\n- AfterHandle now automatically maps the value\n- Using Bun Build for targeting Bun\n- Support Cloudflare worker with Dynamic Mode (and ENV)\n\nChange:\n- Moved registerSchemaPath to @elysiajs/swagger\n\n# 0.6.0-alpha.4\nFeature:\n- Add `addError` to declaratively add Error to scope\n- Add `afterHandle` now can return a literal value instead of limited to only `Response`\n\n# 0.6.0-alpha.3 - 29 Jul 2023\nFeature:\n- Introduce `.mount`\n- Add dynamic mode for TypeBox\n- Add $elysiaChecksum to deduplicate lifecycle event\n- Add $elysiaHookType to differentiate between global and local hook in `use`\n\nFix:\n- Deduplication of plugin's lifecycle (see $elysiaHookType)\n\nChange:\n- Using Bun Build for target Bun\n\nBreaking Change:\n- [Internal] refactored `getSchemaValidator`, `getResponseSchemaValidator` to named parameters\n- [Internal] moved `registerSchemaPath` to `@elysiajs/swagger`\n\n# 0.6.0-alpha.2\nFeature:\n- [Internal] Add qi (queryIndex) to context\n- Add `error` field to Elysia type system for adding custom error message\n\n# 0.6.0-alpha.1\nFeature:\n- [Internal] Add support for accessing composedHandler via routes\n\n# 0.6.0-alpha.0\nFeature:\n- Dynamic mode for Cloudflare Worker\n- Support for registering custom error code\n- Using `loosePath` (by default), and add `config.strictPath\n- Support for setting basePath\n- Recursive path typing\n\nImprovement:\n- Slighty improve type checking speed\n\nBug Fix:\n- recursive schema collision causing infinite type\n\nBreaking Change:\n- Remove Elysia Symbol (Internal)\n\n# 0.5.25 - 25 Jul 2023\nBug fix:\n- ws resolve type to undefined instead of unknown cause unexpected type mismatched when not provided\n\n# 0.5.24 - 22 Jul 2023\nBug fix:\n- [#68](https://github.com/elysiajs/elysia/issues/68) invalid path params when using numeric\n\n# 0.5.23 - 20 Jul 2023\nBug fix:\n- [#68](https://github.com/elysiajs/elysia/issues/68) invalid optional query params when using numeric\n\n# 0.5.22 - 9 Jul 2023\nBug fix:\n- update onAfterHandle to be Response only\n\n# 0.5.20 - 23 Jun 2023\nBug fix:\n- async fn on Static Code Analysis\n\n# 0.5.19 - 19 Jun 2023\nBug fix:\n- optimize `ws` plugin type\n\n# 0.5.18 - 11 Jun 2023\nBug fix:\n- `mapEarlyResponse` is missing on request\n\n# 0.5.17 - 7 Jun 2023\nImprovement:\n- Respect explicit body type first\n- `mapCompactResponse` on `null` or `undefined` type\n\nBug fix:\n- Mapped unioned type on Static Code Analysis\n- `form` is `undefined` when using parsing `formData`\n\n# 0.5.16 - 5 Jun 2023\nImprovement:\n- Respect inner scope of lifecycle first\n- Add type support for local `afterHandle`\n\nBug fix:\n- `onAfterHandler` cause response to mutate on void\n\n# 0.5.15 - 4 Jun 2023\nImprovement:\n- Map CommonJS module in package.json\n\n# 0.5.14 - 4 June 2023\nImprovement:\n- Using tsc to compile CommonJS instead of SWC to support `module.exports` syntax\n\n# 0.5.13 - 4 June 2023\nBug fix:\n- Add loosen type for onError's code for defying custom error status\n\n# 0.5.12 - 3 June 2023\nBug fix:\n- Multiple onRequest cause error\n\n# 0.5.11 - 31 May 2023\nImprovement:\n- Experimental basic support for Static Code Analysis in Nodejs\n\n# 0.5.10 - 31 May 2023\nBug fix:\n- h is undefined when using headers in Node environment\n- Update Memoirist to 0.1.4 to support full CommonJS\n\n# 0.5.9 - 30 May 2023\nImprovement:\n- Add content-type support for 'none', 'arrayBuffer' / 'application/octet-stream'\n- Add type support type registration of wildcard params\n- Add support for 'config.basePath'\n\n# 0.5.8 - 27 May 2023\nImprovement:\n- Add support for returning a class instance\n\n# 0.5.7 - 25 May 2023\nBug fix:\n- Bun is undefined on other runtime\n\n# 0.5.6 - 25 May 2023\nImprovement:\n- Using `new Response` instead of factory `Response.json`\n\n# 0.5.5 - 25 May 2023\nImprovement:\n- Using request.json() to handle application/json body instead of JSON.parse(await c.text())\n\n# 0.5.4 - 25 May 2023\nImprovement:\n- Add Static Code Analysis for conditional try-catch\n- Reduce usage of method to accessor\n\n# 0.5.3 - 22 May 2023\nImprovement:\n- Add `mapCompactResponse` for static code analysis\n- Using `constructor.name` to inline object mapping\n- Using single assignment for URL destructuring\n- Using default map for dynamic route to remove static map label and break\n\nBug fix:\n- Web Socket context.headers is empty [Elysia#46](https://github.com/elysiajs/elysia/issues/46)\n\n# 0.5.2 - 16 May 2023\nImprovement:\n- Static Code Analysis for fallback route\n\nBug fix:\n- Remove constant generic from `state` to be mutable\n\n# 0.5.1 - 16 May 2023\nBug fix:\n- Syntax error if multiple numeric type is set\n- Prevent fallthrough behavior of switch map\n\n# 0.5.0 - 15 May 2023\nImprovement:\n- Add CommonJS support for running Elysia with Node adapter\n- Remove manual fragment mapping to speed up path extraction\n- Inline validator in `composeHandler` to improve performance\n- Use one time context assignment\n- Add support for lazy context injection via Static Code Analysis\n- Ensure response non nullability\n- Add unioned body validator check\n- Set default object handler to inherits\n- Using `constructor.name` mapping instead of `instanceof` to improve speed\n- Add dedicated error constructor to improve performance\n- Conditional literal fn for checking onRequest iteration\n- improve WebSocket type\n\nBug fix:\n- Possible\n\nBreaking Change:\n- Rename `innerHandle` to `fetch`\n    - to migrate: rename `.innerHandle` to `fetch`\n- Rename `.setModel` to `.model`\n    - to migrate: rename `setModel` to `model`\n- Remove `hook.schema` to `hook`\n    - to migrate: remove schema and curly brace `schema.type`:\n    ```ts\n    // from\n    app.post('/', ({ body }) => body, {\n        schema: {\n            body: t.Object({\n                username: t.String()\n            })\n        }\n    })\n\n    // to\n    app.post('/', ({ body }) => body, {\n        body: t.Object({\n            username: t.String()\n        })\n    })\n    ```\n- remove `mapPathnameRegex` (internal)\n\n# 0.5.0-beta.8 - 15 May 2023\nBug fix:\n- it recompile on async\n\n# 0.5.0-beta.7 15 May 2023\nBug fix:\n- detect promise on parse\n- using swc to compile to commonjs\n\n# 0.5.0-beta.6 - 15 May 2023\nImprovement:\n- Improve merge schema type\n\n# 0.5.0-beta.5 - 15 May 2023\nBug fix:\n- Add support for ALL method for dynamic path\n- Add support for parser in pre-compiled body\n\n# 0.5.0-beta.4 - 15 May 2023\nBug fix:\n- Use Memoirist instead of Raikiri in ws\n\n# 0.5.0-beta.3 - 15 May 2023\nImprovement:\n- Static Code Analysis on derive\n\n# 0.5.0-beta.2 - 14 May 2023\nImprovement:\n- Re-compile on lazy modules\n\n# 0.5.0-beta.1 - 14 May 2023\nImprovement:\n- Merge nested schema type\n\n# 0.4.14 - 2 May 2023\nFix:\n- set default object handler to inherits\n\n# 0.4.13 - 28 Apr 2023\nFix:\n- emergency override experimental version\n\n# 0.4.12 - 26 Apr 2023\nFix:\n- CatchResponse to return 200 status code by default when using Eden Treaty\n\n# 0.4.11 - 26 Apr 2023\nFix:\n- response schema doesn't unwrap response type\n\n# 0.4.10 - 25 Apr 2023\nFix:\n- Update Raikiri stability\n\n# 0.4.9 - 21 Apr 2023\nImprovement:\n- Add support for `parse` in websocket [#33](https://github.com/elysiajs/elysia/pull/33)\n\nFix:\n- Inherits out-of-order `onError` life cycle in nested group\n- Update Raikiri to 0.1.2 to handle mangled part\n\n# 0.4.8 - 18 Apr 2023\nFix:\n- Fix LocalHandler doesn't check single type response\n\n# 0.4.7 - 18 Apr 2023\nImprovement:\n- Update Raikiri to ^1.1.0\n\n# 0.4.6 - 10 Apr 2023\nImprovement:\n- perf: add static route main class\n- perf: reduce `ComposedHandler` to function instead of nested object\n\nFix:\n- `group` and `guard` shouldn't decorate a request on type-level (acceptable on run-time level for shared memory)\n\n# 0.4.5 - 6 Apr 2023\nFix:\n- Using default value check for `set.status` instead truthy value\n\n# 0.4.4 - 6 Apr 2023\nImprovement:\n- using `isNotEmpty` for `mapResponse`\n- pre check if `set.headers['Set-Cookie']` is array before converting to headers\n- using `mapPathnameAndQueryRegEx.exec(request.url)` instead of `request.url.match(mapPathnameAndQueryRegEx)`\n\n# 0.4.3 - 31 Mar 2023\nFix:\n- Scoped decorators\n\n# 0.4.2 - 31 Mar 2023\nImprovement:\n- Use constructor name for faster handler matching\n- Map Promise\n\n# 0.4.1 - 31 Mar 2023\nFix:\n- remove type module from package.json\n\n# 0.4.0 - 30 Mar 2023\nFeature:\n- Ahead of Time compilation\n- TypeBox 0.26\n- Validate response per status instead of union\n- Add `if` for conditional route\n- Custom Validation Error\n\nImprovement:\n- Update TypeBox to 0.26.8\n- Inline a declaration for response type\n- Refactor some type for faster response\n- Use Typebox `Error().First()` instead of iteration\n- Add `innerHandle` for returning an actual response (for benchmark)\n\nBreaking Change:\n- Separate `.fn` to `@elysiajs/fn`\n\n# 0.3.2 - 26 Mar 2023\nFix:\n- child to inhertis WebSocket plugin (https://github.com/elysiajs/elysia/issues/27)\n- multiple status response does not work with the group (https://github.com/elysiajs/elysia/issues/28)\n\n# 0.3.1 - 17 Mar 2023\nFix:\n- Wildcard fallback of Raikiri\n\n# 0.3.0 - 17 Mar 2023\nFeature:\n- Elysia Fn\n- Suport `multipart/form-data`\n- `t.File` and `t.Files` for file validation\n- `schema.content` for specifying content type\n\nImprovement:\n- Add string format: 'email', 'uuid', 'date', 'date-time'\n- Update @sinclair/typebox to 0.25.24\n- Update Raikiri to 0.2.0-beta.0 (ei)\n- Add file upload test thanks to #21 (@amirrezamahyari)\n- Pre compile lowercase method for Eden\n- Reduce complex instruction for most Elysia types\n- Change store type to `unknown`\n- Compile `ElysiaRoute` type to literal\n- Optimize type compliation, type inference and auto-completion\n- Improve type compilation speed\n- Improve TypeScript inference between plugin registration\n- Optimize TypeScript inference size\n- Context creation optimization\n- Use Raikiri router by default\n- Remove unused function\n- Refactor `registerSchemaPath` to support OpenAPI 3.0.3\n- Add `error` inference for Eden\n- Mark `@sinclair/typebox` as optional `peerDenpendencies`\n\nFix:\n- Raikiri 0.2 thrown error on not found\n- Union response with `t.File` is not working\n- Definitions isn't defined on Swagger\n- details are missing on group plugin\n- group plugin, isn't unable to compile schema\n- group is not exportable because EXPOSED is a private property\n- Multiple cookies doesn't set `content-type` to `application/json`\n- `EXPOSED` is not export when using `fn.permission`\n- Missing merged return type for `.ws`\n- Missing nanoid\n- context side-effects\n- `t.Files` in swagger is referring to single file\n- Eden response type is unknown\n- Unable to type `setModel` inference definition via Eden\n- Handle error thrown in non permission function\n- Exported variable has or is using name 'SCHEMA' from external module\n- Exported variable has or is using name 'DEFS' from external module\n- Possible errors for building Elysia app with `declaration: true` in `tsconfig.json`\n\nBreaking Change:\n- Rename `inject` to `derive`\n- Depreacate `ElysiaRoute`, changed to inline\n- Remove `derive`\n- Update from OpenAPI 2.x to OpenAPI 3.0.3\n- Move context.store[SYMBOL] to meta[SYMBOL]\n\n# 0.3.0-rc.9 - 16 Mar 2023\nImprovement:\n- Add string format: 'email', 'uuid', 'date', 'date-time'\n\n# 0.3.0-rc.8 - 16 Mar 2023\nFix:\n- Raikiri 0.2 thrown error on not found\n\n# 0.3.0-rc.7 - 16 Mar 2023\nImprovement:\n- Update @sinclair/typebox to 0.25.24\n- Update Raikiri to 0.2.0-beta.0 (ei)\n- Add file upload test thanks to #21 (@amirrezamahyari)\n\n# 0.3.0-rc.6 - 10 Mar 2023\nFix:\n- Union response with `t.File` is not working\n\n# 0.3.0-rc.5 - 10 Mar 2023\nFix:\n- Definitions isn't defined on Swagger\n- details are missing on group plugin\n- group plugin, isn't unable to compile schema\n- group is not exportable because EXPOSED is a private property\n\n# 0.3.0-rc.4 - 9 Mar 2023\nFix:\n- console.log while using cookie\n\n# 0.3.0-rc.3 - 9 Mar 2023\nBreaking Change:\n- Rename `inject` to `derive`\n\nFix:\n- Multiple cookies doesn't set `content-type` to `application/json`\n- `EXPOSED` is not export when using `fn.permission`\n\n# 0.3.0-rc.2 - 7 Mar 2023\nFix:\n- Missing merged return type for `.ws`\n\n# 0.3.0-rc.1 - 7 Mar 2023\nFix:\n- Missing nanoid\n\n# 0.3.0-beta.6 - 4 Mar 2023\nFix:\n- context side-effects\n\n# 0.3.0-beta.5 - 1 Mar 2023\nImprovement:\n- Pre compile lowercase method for Eden\n\n# 0.3.0-beta.3 - 27 Feb 2023\nImprovement:\n- ~33% faster for compiling type inference\n- Reduce complex instruction for most Elysia types\n- Change store type to `unknown`\n\nFix:\n- `t.Files` in swagger is referring to single file\n- Eden response type is unknown\n\n# 0.3.0-beta.2 - 27 Feb 2023\nImprovement:\n- Compile `ElysiaRoute` type to literal\n- Optimize type compliation, type inference and auto-completion\n- Improve type compilation speed by ~3x\n\nFix:\n- Unable to type `setModel` inference definition via Eden\n\nBreaking Change:\n- Depreacate `ElysiaRoute`, changed to inline\n\n# 0.3.0-beta.1 - 25 Feb 2023\nFix:\n- Handle error thrown in non permission function\n\n# 0.3.0-beta.0 - 25 Feb 2023\nFeature:\n- Elysia Fn\n- Suport `multipart/form-data`\n- `t.File` and `t.Files` for file validation\n- `schema.content` for specifying content type\n\nImprovement:\n- Improve TypeScript inference between plugin registration\n- Optimize TypeScript inference size\n- Context creation optimization\n- Use Raikiri router by default\n- Remove unused function\n- Refactor `registerSchemaPath` to support OpenAPI 3.0.3\n- Add `error` inference for Eden\n- Mark `@sinclair/typebox` as optional `peerDenpendencies`\n\nFix:\n- Exported variable has or is using name 'SCHEMA' from external module\n- Exported variable has or is using name 'DEFS' from external module\n- Possible errors for building Elysia app with `declaration: true` in `tsconfig.json`\n\nBreaking Change:\n- Remove `derive`\n- Update from OpenAPI 2.x to OpenAPI 3.0.3\n- Move context.store[SYMBOL] to meta[SYMBOL]\n\n# 0.2.9 - 20 Feb 2023\nBug fix:\n- `group` doesn't inherits `onError`\n\n# 0.2.8 - 20 Feb 2023\nBug fix:\n- `group` doesn't inherits `onError`\n\n# 0.2.7 - 15 Feb 2023\nImprovement:\n- Remove `bind(this)`\n\n# 0.2.6 - 10 Feb 2023\nFeature:\n- Add supports for multiple cookie\n\n# 0.2.5 - 1 Feb 2023\nImprovement:\n- Minor optimization\n\n# 0.2.4 - 1 Feb 2023\nImprovement:\n- Using SWC to bundle and minification\n- Minor optimization\n\n# 0.2.3 - 30 Jan 2023\nImprovement:\n- Update Raikiri to 0.0.0-beta.4\n\nChange:\n- Remove strictPath option and enabled by default\n\n# 0.2.2 - 30 Jan 2023\nImprovement:\n- Migrate from @medley/router to Raikiri\n- Minor optimization\n\n# 0.2.0-rc.1 - 24 Jan 2023\nImprovement:\n- Map OpenAPI's schema detail on response\n- Fix Type instantiation is excessively deep and possibly infinite\n- Improve TypeScript inference time by removing recursive type in generic\n- Inferred body is never instead of unknown\n\n# 0.2.0-rc.0 - 23 Jan 2023\nFeature:\n- Add support for reference model via `.model`\n- Add support for OpenAPI's `definitions` field\n\n# 0.2.0-beta.2 - 22 Jan 2023\nFeature:\n- Add support for custom openapi field using `schema.detail`\n- Add support for custom code for `response`\n\nImprovement:\n- Unioned status type for response\n- Optimize TypeScript inference performance\n\n# 0.2.0-beta.1 - 22 Jan 2023\nBreaking Change:\n- `onParse` now accepts `(context: PreContext, contentType: string)` instead of `(request: Request, contentType: string)`\n    - To migrate, add `.request` to context to access `Request`\n\nFeature:\n- `onRequest` and `onParse` now can access `PreContext`\n- Support `application/x-www-form-urlencoded` by default\n\nImprovement:\n- body parser now parse `content-type` with extra attribute eg. `application/json;charset=utf-8`\n\n# 0.2.0-beta.0 - 17 Jan 2023\nFeature:\n- Support for Async / lazy-load plugin\n\nImprovement:\n- Decode URI parameter path parameter\n- Handle union type correctly\n\n# 0.1.3 - 12 Jan 2023\nImprovement:\n- Validate `Response` object\n- Union type inference on response\n\n# 0.1.2 - 31 Dec 2022\nBug fix:\n- onRequest doesn't run in `group` and `guard`\n\n# 0.1.1 - 28 Dec 2022\nImprovement:\n- Parse encoded URI on querystring\n- Exclude URI fragment from querystring\n- Blasphemy hack for updating Elysia server using `--hot`\n- Exclude fragment on `getPath`\n\n# 0.1.0 - 24 Dec 2022\n[[Reburn](https://youtu.be/xVPDszGmTgg?t=1139)] is the first *stable* beta release for Elysia.\n\nHappy Christmas, wishing you happy tonight as we release the first stable release of Elysia.\n\nWith this API is now stabilized, and Elysia will focus on growing its ecosystem and plugins for common patterns.\n\n## Eden\nIntroducing [Eden](https://elysiajs.com/plugins/eden.html), a fully type-safe client for Elysia server like tRPC.\n\nA 600 bytes client for Elysia server, no code generation need, creating a fully type-safe, and auto-complete for both client and server.\n\nSee Eden in action [on Twitter](https://twitter.com/saltyAom/status/1602362204799438848?s=20&t=yqyxaNx_W0MNK9u3wnaK3g)\n\n## The fastest\nWith a lot effort put into micro-optimization and re-architecture, Elysia is the fastest Bun web framework benchmarked on 24 December 2022, outperformed 2/3 category put into test.\n\nSee benchmark results at [Bun http benchmark](https://github.com/SaltyAom/bun-http-framework-benchmark)\n\n## Improved Documentation\nElysia now have an improved documentation at [elysiajs.com](https://elysiajs.com).\n\nNow with a proper landing page, searchable content, and revised content put into.\n\n## Afterward\nMerry Christmas, and happy new year.\n\nAs 0.1 released, we recommended to give Elysia a try and build stuff with it.\n\nWith the wonderful tools, we are happy to looking forward to see what wonderful software will you build.\n\n---\n\n> Fly away, let me fly away\n> Never hide in dark\n> Head on, start a riot\n> Fly away, defying fate in my way\n> Crush it\n> Make it!\n> Feel\n> My\n> Heart!\n\n# 0.1.0.rc.10 - 21 Dec 2022\nChange:\n- Remove cjs format as Bun can import ESM from CJS\n- Remove comment on build file, rely on .t.ds instead\n\n# 0.1.0.rc.9 - 19 Dec 2022\nChange:\n- Support plugins which use `getPath`, and `mapQuery` on 0.1.0-rc.6\n\n# 0.1.0.rc.8 - 16 Dec 2022\nImprovement:\n- Infers type from `group`, and `guard`\n\nChange:\n- `Elysia.handle` now only accept valid `URL`\n\n# 0.1.0.rc.7 - 15 Dec 2022\nImprovement:\n- Minor optimization\n- `Router.register` now returns type\n- Inline default bodyParser\n\n# 0.1.0.rc.6 - 13 Dec 2022\nFix:\n- `.listen` object is now optional\n\n# 0.1.0.rc.5 - 13 Dec 2022\nBreaking Change:\n- `onError` change its type:\n```typescript\n// Previously\nonError: (error: Error, code: ErrorCode)\n\n// Now\nonError: (params: {\n    error: Error\n    code: ErrorCode\n    set: Context['set']\n}) => any\n```\n\nTo migrate, add curly brace to `onError` parameters.\n\n- `onRequest` change its type:\n```typescript\n// Previously\nonRequest: (request: Request, store: Instance['Store']) => any\n\n// Now\nonRequest: (params: {\n    request: Request,\n    store: Instance['store']\n    set: Context['set']\n})\n```\nTo migrate, add curly brace to `onRequest` parameters.\n\nFeature:\n- Manual patch for [bun#1435](https://github.com/oven-sh/bun/issues/1435), and unblock test suite for error handler.\n\n# 0.1.0.rc.4 - 12 Dec 2022\nFix:\n- Remove `console.log` for '*'\n\n# 0.1.0.rc.3 - 12 Dec 2022\nFeature:\n- Strict type for `SCHEMA`\n- Infered type parameters for `SCHEMA`\n\nFix:\n- Auto prefix path with `/` for non\n- Fallback catch all route for registered parameter\n\n# 0.1.0.rc.2 - 8 Dec 2022\nFix:\n- skip body parsing for 'HEAD'\n- missing response status on some error\n- compatability for cjs\n- add main fields for Bundlephobia supports\n- add declaration file for both esm and cjs\n- ship `src` for TypeScript support with `declare global`\n\n# 0.1.0.rc.1 - 6 Dec 2022\nStabilized API\n\nFeature:\n- add header access to context via `context.header`\n\nBreaking Change:\n- rename `schema.header` to `schema.headers`\n\n# 0.0.0-experimental.55 - 1 Dec 2022\nBug fix:\n- `inject` now accept `Context`\n\n# 0.0.0-experimental.54 - 1 Dec 2022\nFeature:\n- `derive` to creating derive state\n- `inject` to decorate method based on context\n\n# 0.0.0-experimental.53 - 24 Nov 2022\nFeature:\n- `.all` for registering path with any method\n\nImprovement:\n- `getSchemaValidator` now infer output type to be reusable with `@kingworldjs/trpc`\n\nBug fix:\n- `handler.hooks` is undefined on 404\n\n# 0.0.0-experimental.52 - 23 Nov 2022\nImprovement:\n- Decorators is now lazily allocate\n- `.serve` now accept numberic string as port for convenient with `process.env`\n\n# 0.0.0-experimental.51 - 22 Nov 2022\n[[Just Right Slow]](https://youtu.be/z7nN7ryqU28) introduce breaking major changes of KingWorld, specific on a plugin system.\n\nPreviously, we define plugin by accepting 2 parameters, `KingWorld` and `Config` like this:\n```typescript\nconst plugin = (app: KingWorld, config) => app\n\nnew KingWorld().use(plugin, {\n    // Provide some config here\n})\n```\n\nHowever, this has flaw by the design because:\n- No support for async plugin\n- No generic for type inference\n- Not possible to accept 3...n parameters (if need)\n- Hard/heavy work to get type inference\n\nTo fix all of the problem above, KingWorld now accept only one parameter.\n\nA callback which return KingWorld Instance, but accept anything before that.\n```typescript\nconst plugin = (config) => (app: KingWorld) => app\n\nnew KingWorld().use(plugin({\n    // provide some config here\n}))\n```\n\nThis is a workaround just like the way to register async plugin before exp.51, we accept any parameters in a function which return callback of a KingWorld instance.\n\nThis open a new possibility, plugin can now be async, generic type is now possible.\n\nMore over that, decorate can now accept any parameters as it doesn't really affect any performance or any real restriction.\n\nWhich means that something like this is now possible.\n```typescript\nconst a = <Name extends string = string>(name: Name) => (app: KingWorld) => app.decorate(name, {\n    hi: () => 'hi'\n})\n\nnew KingWorld()\n    .use(a('customName'))\n    // Retrieve generic from plugin, not possible before exp.51\n    .get({ customName } => customName.hi())\n```\n\nThis lead to even more safe with type safety, as you can now use any generic as you would like.\n\nThe first plugin to leverage this feature is [jwt](https://github.com/saltyaom/kingworld-jwt) which can introduce jwt function with custom namespace which is type safe.\n\nChange:\n- new `decorators` property for assigning fast `Context`\n\n# 0.0.0-experimental.50 - 21 Nov 2022\nImprovement:\n- Faster router.find performance\n- Faster query map performance\n- Early return on not found\n- Better type for `router`\n\nChange:\n- Remove `storeFactory` from router\n\n# 0.0.0-experimental.49 - 19 Nov 2022\nBug fix:\n- Conditionally return header in response\n\n# 0.0.0-experimental.48 - 18 Nov 2022\nBug fix:\n- Import Context as non-default\n- TypeScript's type not infering Context\n\n# 0.0.0-experimental.47 - 18 Nov 2022\nBug fix:\n- Remove `export default Context` as it's a type\n- Import Context as non-default\n\n# 0.0.0-experimental.46 - 18 Nov 2022\nBug fix:\n- Add custom response to `Blob`\n\n# 0.0.0-experimental.45 - 18 Nov 2022\nBug fix:\n- Set default HTTP status to 200 (https://github.com/oven-sh/bun/issues/1523)\n\n# 0.0.0-experimental.44 - 18 Nov 2022\nImprovement:\n- Faster object iteration for setting headers\n- `KingWorld` config now accept `Serve` including `SSL`\n\nChange:\n- Use direct comparison for falsey value\n\n# 0.0.0-experimental.42 - 13 Nov 2022\nBug fix:\n- Router doesn't handle part which start with the same letter\n\n# 0.0.0-experimental.41 - 9 Nov 2022\nChange:\n- Internal schema now use correct OpenAPI type (KingWorld need CORRECTION 💢💢)\n\n# 0.0.0-experimental.40 - 9 Nov 2022\nBreaking Change:\n- `Context` is now `interface` (non-constructable)\n- `responseHeaders`, `status`, `redirect` is now replaced with `set`\n    - To migrate:\n    ```typescript\n    // From\n    app.get('/', ({ responseHeaders, status, redirect }) => {\n        responseHeaders['server'] = 'KingWorld'\n        status(401)\n        redirect('/')\n    })\n\n    // To\n    app.get('/', ({ set }) => {\n        set.headers['server'] = 'KingWorld'\n        set.status = 401\n        set.redirect = '/'\n    })\n    ```\n\nImprovement:\n- Global `.schema` now infer type for handler\n- Add JSDocs for main method with example\n- `.listen` now accept `Bun.Server` as a callback function\n- Response support for `FileBlob`\n\n# 0.0.0-experimental.39 - 8 Nov 2022\nBreaking Change:\n- `method` is changed to `route`\n\nImprovement:\n- `LocalHook` now prefers the nearest type instead of the merge\n- Merge the nearest schema first\n- add `contentType` as a second parameter for `BodyParser`\n\nBug fix:\n- Correct type for `after handle`\n- Fix infinite cycling infer type for `Handler`\n\n# 0.0.0-experimental.38 - 7 Nov 2022\nBug fix:\n- Correct type for `afterHandle`\n\n# 0.0.0-experimental.37 - 6 Nov 2022\n[[Sage]](https://youtu.be/rgM5VGYToQQ) is one of the major experimental releases and breaking changes of KingWorld.\n\nThe major improvement of Sage is that it provides almost (if not) full support for TypeScript and type inference.\n\n## Type Inference\nKingWorld has a complex type of system. It's built with the DRY principle in mind, to reduce the developer's workload.\n\nThat's why KingWorld tries to type everything at its best, inferring type from your code into TypeScript's type.\n\nFor example, writing schema with nested `guard` is instructed with type and validation.\nThis ensures that your type will always be valid no matter what, and inferring type to your IDE automatically.\n![FgqOZUYVUAAVv6a](https://user-images.githubusercontent.com/35027979/200132497-63d68331-cf96-4e12-9f4d-b6a8d142eb69.jpg)\n\nYou can even type `response` to make your that you didn't leak any important data by forgetting to update the response when you're doing a migration.\n\n## Validator\nKingWorld's validator now replaced `zod`, and `ajv` with `@sinclair/typebox`.\n\nWith the new validator, validation is now faster than the previous version by 188x if you're using zod, and 4.1x if you're using ajv adapter.\n\nWith Edge Computing in mind, refactoring to new validate dropped the unused packages and reduced size by 181.2KB.\nTo give you an idea, KingWorld without a validator is around 10KB (non-gzipped).\n\nMemory usage is also reduced by almost half by changing the validator.\n###### According to M1 Max running `example/simple.ts`, running exp.36 uses 24MB of memory while exp.37 use 12MB of memory\n\nThis greatly improves the performance of KingWorld in a long run.\n\n## Changelog\nBreaking Change:\n- Replace `zod`, `zod-to-json-schema`, `ajv`, with `@sinclair/typebox`\n\nImprovement:\n- `use` now accept any non `KingWorld<{}, any>`\n- `use` now combine typed between current instance and plugin\n- `use` now auto infer type if function is inline\n- `LocalHook` can now infer `params` type from path string\n\nChange:\n- `TypedSchema` is now replaced with `Instance['schema']`\n\n# 0.0.0-experimental.36 - 4 Nov 2022\nBreaking Change:\n- `AfterRequestHandle` now accept (`Context`, `Response`) instead of `(Response, Context)`\n\nImprovement:\n- `.guard` now combine global and local recursively\n- `.use` now inherits schema\n\n# 0.0.0-experimental.35 - 3 Nov 2022\nBug fix:\n- Remove `console.log` on failed validation\n\n# 0.0.0-experimental.34 - 3 Nov 2022\nImprovement:\n- Add Ajv 8.11.0\n- Error log for validation is updated to `instancePath`\n\n# 0.0.0-experimental.33 - 3 Nov 2022\nFeature:\n- `.schema` for global schema validation\n- `.start`, `.stop` and accept `KingWorld<Instance>` as first parameter\n\nImprovement:\n- `.guard` now auto infer type from schema to `Handler`\n- scoped `.guard` now inherits hook\n- `NewInstance` now inherits `InheritSchema`\n\nBug fix:\n- Rename `afterHandle` to `onAfterHandle` to match naming convention\n- Make `afterHandle` in `RegisterHook` optional\n- Internal type conversion between `Hook`, `LocalHook`\n\n# 0.0.0-experimental.32 - 2 Nov 2022\nFeature:\n- add `afterHandle` hook\n\nImprovement:\n- Using `WithArray<T>` to reduce redundant type\n\nBug fix:\n- `beforeHandle` hook doesn't accept array\n\n# 0.0.0-experimental.31 - 2 Nov 2022\nBug fix:\n- Add `zod` by default\n\n# 0.0.0-experimental.30 - 2 Nov 2022\nBug fix:\n- Add `zod-to-json-schema` by default\n\n# 0.0.0-experimental.29 - 2 Nov 2022\n[Regulus]\n\nThis version introduces rework for internal architecture. Refine, and unify the structure of how KingWorld works internally.\n\nAlthough many refactoring might require, I can assure you that this is for the greater good, as the API refinement lay down a solid structure for the future of KingWorld.\n\nThanks to API refinement, this version also introduced a lot of new interesting features, and many APIs simplified.\n\nNotable improvements and new features:\n- Define Schema, auto-infer type, and validation\n- Simplifying Handler's generic\n- Unifying Life Cycle into one property\n- Custom Error handler, and body-parser\n- Before start/stop and clean up effect\n\n# 0.0.0-experimental.28 - 30 Oct 2022\nHappy halloween.\n\nThis version named [GHOST FOOD] is one of the big improvement for KingWorld, I have been working on lately.\nIt has a lot of feature change for better performance, and introduce lots of deprecation.\n\nBe sure to follow the migration section in `Breaking Change`.\n\nFeature:\n- Auto infer type from `plugin` after merging with `use`\n- `decorate` to extends `Context` method\n- add `addParser`, for custom handler for parsing body\n\nBreaking Change:\n- Moved `store` into `context.store`\n    - To migrate:\n    ```typescript\n    // From\n    app.get(({}, store) => store.a)\n\n    // To\n    app.get(({ store }) => store.a)\n    ```\n\n- `ref`, and `refFn` is now removed\n- Remove `Plugin` type, simplified Plugin type declaration\n    - To migrate:\n    ```typescript\n    // From\n    import type { Plugin } from 'kingworld'\n    const a: Plugin = (app) => app\n\n    // To\n    import type { KingWorld } from 'kingworld'\n    const a = (app: KingWorld) => app\n    ```\n\n- Migrate `Header` to `Record<string, unknown>`\n    - To migrate:\n    ```typescript\n    app.get(\"/\", ({ responseHeader }) => {\n        // From\n        responseHeader.append('X-Powered-By', 'KingWorld')\n\n        // To\n        responseHeader['X-Powered-By', 'KingWorld']\n\n        return \"KingWorld\"\n    })\n    ```\n\nChange:\n- Store is now globally mutable\n\nImprovement:\n- Faster header initialization\n- Faster hook initialization\n\n# 0.0.0-experimental.27 - 23 Sep 2022\nFeature:\n- Add `config.strictPath` for handling strict path\n\n# 0.0.0-experimental.26 - 10 Sep 2022\nImprovement:\n- Improve `clone` performance\n- Inline `ref` value\n- Using object to store internal route\n\nBug fix:\n- 404 on absolute path\n\n# 0.0.0-experimental.25 - 9 Sep 2022\nFeature:\n- Auto infer typed for `params`, `state`, `ref`\n- `onRequest` now accept async function\n- `refFn` syntax sugar for adding fn as reference instead of `() => () => value`\n\nImprovement:\n- Switch from `@saltyaom/trek-router` to `@medley/router`\n- Using `clone` instead of flatten object\n- Refactor path fn for inline cache\n- Refactor `Context` to class\n\nBug fix:\n- `.ref()` throw error when accept function\n\n# 0.0.0-experimental.24 - 21 Aug 2022\nChange:\n- optimized for `await`\n\n# 0.0.0-experimental.23 - 21 Aug 2022\nFeature:\n- Initialial config is now available, starting with `bodyLimit` config for limiting body size\n\nBreaking Change:\n- `ctx.body` is now a literal value instead of `Promise`\n    - To migrate, simply remove `await`\n\nChange:\n- `default` now accept `Handler` instead of `EmptyHandler`\n\nBug fix:\n- Default Error response now return `responseHeaders`\n- Possibly fixed parsing body error benchmark\n\n# 0.0.0-experimental.22 - 19 Aug 2022\nBreaking Change:\n- context.body is now deprecated, use request.text() or request.json() instead\n\nImprovement:\n- Using reference header to increase json response speed\n- Remove `body` getter, setter\n\nChange:\n- Using `instanceof` to early return `Response`\n\n# 0.0.0-experimental.21 - 14 Aug 2022\nBreaking Change:\n- `context.headers` now return `Header` instead of `Record<string, string>`\n\nFeature:\n- Add status function to `Context`\n- `handle` now accept `number | Serve`\n- Remove `querystring` to support native Cloudflare Worker\n- Using raw headers check to parse `body` type\n\n# 0.0.0-experimental.20 - 13 Aug 2022\nFeature:\n- Handle error as response\n\n# 0.0.0-experimental.19 - 13 Aug 2022\nChange:\n- Use Array Spread instead of concat as it's faster by 475%\n- Update to @saltyaom/trek-router 0.0.7 as it's faster by 10%\n- Use array.length instead of array[0] as it's faster by 4%\n\n# 0.0.0-experimental.18 - 8 Aug 2022\nChange:\n- With lazy initialization, KingWorld is faster by 15% (tested on 14' M1 Max)\n- Micro optimization\n- Remove `set` from headers\n\n# 0.0.0-experimental.17 - 15 Jul 2022\nChange:\n- Remove dependencies: `fluent-json-schema`, `fluent-schema-validator`\n- Update `@saltyaom/trek-router` to `0.0.2`\n\n# 0.0.0-experimental.16 - 15 Jul 2022\nBreaking Change:\n- Move `hook.schema` to separate plugin, [@kingworldjs/schema](https://github.com/saltyaom/kingworld-schema)\n    - To migrate, simply move all `hook.schema` to `preHandler` instead\n\nChange:\n- Rename type `ParsedRequest` to `Context`\n- Exposed `#addHandler` to `_addHandler`\n\n# 0.0.0-experimental.15 - 14 Jul 2022\nBreaking Change:\n- Rename `context.responseHeader` to `context.responseHeaders`\n- Change type of `responseHeaders` to `Header` instead of `Record<string, string>`\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our community include:\n\n* Demonstrating empathy and kindness toward other people\n* Being respectful of differing opinions, viewpoints, and experiences\n* Giving and gracefully accepting constructive feedback\n* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience\n* Focusing on what is best not just for us as individuals, but for the overall community\n\nExamples of unacceptable behavior include:\n\n* The use of sexualized language or imagery, and sexual attention or advances of any kind\n* Trolling, insulting or derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or email address, without their explicit permission\n* Contacting individual members, contributors, or leaders privately, outside designated community mechanisms, without their explicit permission\n* Other conduct which could reasonably be considered inappropriate in a professional setting\n\n## Enforcement Responsibilities\n\nMaintaners are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.\n\nMainteiners have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be reported to the maintainers. All complaints will be reviewed and investigated promptly and fairly.\n\nAll maintainers are obligated to respect the privacy and security of the reporter of any incident.\n\n## Enforcement Guidelines\n\nCommunity leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:\n\n### 1. Correction\n\n**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.\n\n**Consequence**: A private, written warning from maintainers, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.\n\n### 2. Warning\n\n**Community Impact**: A violation through a single incident or series of actions.\n\n**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.\n\n### 3. Temporary Ban\n\n**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.\n\n**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.\n\n### 4. Permanent Ban\n\n**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior,  harassment of an individual, or aggression toward or disparagement of classes of individuals.\n\n**Consequence**: A permanent ban from any sort of public interaction within the community.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at <https://www.contributor-covenant.org/version/2/0/code_of_conduct.html>.\n\nCommunity Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see the FAQ at <https://www.contributor-covenant.org/faq>. Translations are available at <https://www.contributor-covenant.org/translations>.\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Welcome to Elysia contributing guide\n\nThank you for investing your time in contributing to Elysia! Any contribution you make will be amazing :sparkles:.\n\nRead our [Code of Conduct](./CODE_OF_CONDUCT.md) to keep our community approachable and respectable.\n\nIn this guide you will get an overview of the contribution workflow from opening an issue, creating a PR, reviewing, and merging the PR.\n\n## Setup Local Development Environment\n\nElysia test cases are using [bun](https://bun.sh). Make sure you have the [latest version of bun](https://github.com/oven-sh/bun/releases) installed in your system.\n\nTo run Elysia locally:\n\n1. Clone this repository\n2. run `bun install` in project's root\n3. Run development with `bun run dev`\n\n### Unit Testing\n\nAll of the test files are located inside the [`test/`](test/) directory. Unit testing are powered by [bun's test](https://github.com/oven-sh/bun/tree/main/packages/bun-internal-test).\n\n- `bun test` to run all the test inside the [`test/`](test/) directory\n- `bun test test/<test-file>.ts` to run a specific test\n\n## Pull Request Guidelines\n\nRecommended to use `main` branch as a base to work on.\n\n#### General Recommendation\n- Please kindly verify that you have run test suite before request a review from maintainers with `bun run test`\n- We do not condone the usage of any form of plagiarism or copying code without proper attribution.\n- We do not tolerate disrespectful or inappropriate behavior within the community.\n- AI generated pull request without human interaction, review and supervision may result in close without further notice or ban from future contribution to Elysia.\n\n#### Adding New Features\n- Provide a reason why you would like to add this feature. Ideally before creating a PR, create a new issue with, explain the reason, tag as `feature request` and tag maintainer eg. \"saltyaom\"\n- It's recommended to add test cases to cover core feature of the feature you intent to add\n\n#### Fixing Bug\n- When opening an pull request fixing existing issue, please kindly include the issue link or id in the description\n- Provide a detailed description of the bug in the PR. Live demo preferred.\n- Add appropriate test coverage if applicable.\n- It's OK to have multiple small commits as you work on the PR. GitHub can automatically squash them before merging.\n\n## Thanks :purple_heart:\n\nThanks for all your contributions and efforts towards improving Elysia. We thank you for being part of our community :sparkles:!\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright 2022 saltyAom\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "<p align=center>\n <img src=https://github.com/user-attachments/assets/8168188b-ffaf-444f-8d09-c516ce140824 alt=\"Elysia Banner\" />\n</p>\n\n<h3 align=center>Elysia</h3>\n<p align=center>Ergonomic Framework for Humans</p>\n\n<p align=center>\n    <a href=https://elysiajs.com>Documentation</a> | <a href=https://discord.gg/eaFJ2KDJck>Discord</a> | <a href=https://github.com/sponsors/SaltyAom>Sponsors</a>\n</p>\n\n<br>\n\n<p align=center>TypeScript with End-to-End Type Safety, type integrity, and exceptional developer experience. Supercharged by Bun.</p>\n\n<br>\n\n![Elysia chan cover | bun creeate elysia app](https://github.com/user-attachments/assets/a649731a-8cba-4ca2-8424-6656cbf84956)\n\n<!---\n```bash\nbun create elysia app\n```\n\n![Elysia feature sheet including 18x faster than Express based on Techempower benchmark, Frontend RPC Connector, Advance TypeScript type, unified type single source of truth of type TypeScript runtime and documentation all at once, Made of Productivity focus on developer experience, powered by Bun, WinterCG Compliance, Fully type safe GraphQL (same author with GraphQL Mobius), documentation in one line, End-to-end type safety move fast and break nothing like tRPC, strong ecosystem most popular Bun native Web Framework](https://github.com/elysiajs/elysia/assets/35027979/d4b184ca-a622-434d-bb06-06c3110726af)\n\n## Documentation\nThe documentation is available on [elysiajs.com](https://elysiajs.com).\n\n## Contributing\nSee [Contributing Guide](CONTRIBUTING.md) and please follow our [Code of Conduct](CODE_OF_CONDUCT.md).\n\n## Discord\nCome join the [Discord community channel~](https://discord.gg/eaFJ2KDJck)\n\n--->\n"
  },
  {
    "path": "build.ts",
    "content": "import { $ } from 'bun'\nimport { build } from 'tsup'\nimport { fixImportsPlugin } from 'esbuild-fix-imports-plugin'\n\nimport pack from './package.json'\n\nif ('elysia' in pack.dependencies)\n\tthrow new Error(\"Error can't be a dependency of itself\")\n\nawait $`rm -rf dist`\n\nawait build({\n\tentry: ['src/**/*.ts'],\n\toutDir: 'dist',\n\tformat: ['esm', 'cjs'],\n\ttarget: 'node20',\n\tminifySyntax: true,\n\tminifyWhitespace: false,\n\tminifyIdentifiers: false,\n\tsplitting: false,\n\tsourcemap: false,\n\tcjsInterop: false,\n\tclean: true,\n\tbundle: false,\n\texternal: ['@sinclair/typebox', 'file-type'],\n\tesbuildPlugins: [fixImportsPlugin()]\n})\n\nawait $`tsc --project tsconfig.dts.json`\n\nprocess.exit()\n"
  },
  {
    "path": "example/a.ts",
    "content": "import { Elysia, t } from '../src'\nimport { req } from '../test/utils'\n\nconst app = new Elysia()\n\t.get('/', async () => {\n\t\tconst file = Bun.file('test/kyuukurarin.mp4')\n\n\t\t// Wrap the stream in another ReadableStream\n\t\t// perhaps we are concatenating streams or whatever\n\t\tconst body = new ReadableStream({\n\t\t\tasync start(controller) {\n\t\t\t\tconst reader = file.stream().getReader()\n\t\t\t\ttry {\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tconst { done, value } = await reader.read()\n\t\t\t\t\t\tif (done) break\n\t\t\t\t\t\tcontroller.enqueue(value)\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.close()\n\t\t\t\t} catch (err) {\n\t\t\t\t\tcontroller.error(err)\n\t\t\t\t} finally {\n\t\t\t\t\treader.releaseLock()\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\t// Returning the stream uses 100% for several minutes\n\t\treturn body\n\n\t\t// Returning the same stream wrapped in a Response servers the stream in a fraction of a second\n\t\t// return new Response(body);\n\t})\n\t.listen(3000)\n"
  },
  {
    "path": "example/async-recursive.ts",
    "content": "import { Elysia } from '../src'\nimport { req } from '../test/utils'\n\nconst delay = <T extends (...args: any) => any>(\n\tcallback: T,\n\tms = 617\n): Promise<ReturnType<T>> => Bun.sleep(ms).then(callback)\n\nconst yay = () => delay(() => new Elysia().use(import('./lazy')))\nconst yay2 = () => delay(() => new Elysia().use(yay), 5)\nconst yay3 = () => delay(() => new Elysia().use(yay2), 10)\nconst wrapper = new Elysia().use(async () => delay(() => yay3(), 6))\n\nconst app = new Elysia().use(wrapper)\n\nawait app.modules\n\n// should works\napp.handle(req('/lazy'))\n\t.then((x) => x.text())\n\t.then(console.log)\n"
  },
  {
    "path": "example/body.ts",
    "content": "import { Elysia, t } from '../src'\n\nconst app = new Elysia()\n\t// Add custom body parser\n\t.onParse(async ({ request, contentType }) => {\n\t\tswitch (contentType) {\n\t\t\tcase 'application/Elysia':\n\t\t\t\treturn request.text()\n\t\t}\n\t})\n\t.post('/', ({ body: { username } }) => `Hi ${username}`, {\n\t\tbody: t.Object({\n\t\t\tid: t.Number(),\n\t\t\tusername: t.String()\n\t\t})\n\t})\n\t// Increase id by 1 from body before main handler\n\t.post('/transform', ({ body }) => body, {\n\t\ttransform: ({ body }) => {\n\t\t\tbody.id = body.id + 1\n\t\t},\n\t\tbody: t.Object({\n\t\t\tid: t.Number(),\n\t\t\tusername: t.String()\n\t\t}),\n\t\tdetail: {\n\t\t\tsummary: 'A'\n\t\t}\n\t})\n\t.post('/mirror', ({ body }) => body)\n\t.listen(3000)\n\nconsole.log('🦊 Elysia is running at :8080')\n"
  },
  {
    "path": "example/cookie.ts",
    "content": "import { Elysia, t } from '../src'\n\nconst app = new Elysia({\n\tcookie: {\n\t\tsecrets: 'Fischl von Luftschloss Narfidort',\n\t\tsign: 'name'\n\t}\n})\n\t.get(\n\t\t'/council',\n\t\t({ cookie: { council } }) =>\n\t\t\t(council.value = [\n\t\t\t\t{\n\t\t\t\t\tname: 'Rin',\n\t\t\t\t\taffilation: 'Administration'\n\t\t\t\t}\n\t\t\t]),\n\t\t{\n\t\t\tcookie: t.Cookie({\n\t\t\t\tcouncil: t.Array(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tname: t.String(),\n\t\t\t\t\t\taffilation: t.String()\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t})\n\t\t}\n\t)\n\t.get('/create', ({ cookie: { name } }) => (name.value = 'Himari'))\n\t.get(\n\t\t'/update',\n\t\t({ cookie: { name } }) => {\n\t\t\tname.value = 'seminar: Rio'\n\t\t\tname.value = 'seminar: Himari'\n\t\t\tname.maxAge = 86400\n\n\t\t\treturn name.value\n\t\t},\n\t\t{\n\t\t\tcookie: t.Cookie({\n\t\t\t\tname: t.Optional(t.String())\n\t\t\t})\n\t\t}\n\t)\n\t.listen(3000)\n"
  },
  {
    "path": "example/counter.ts",
    "content": "import { Elysia } from '../src'\n\nnew Elysia()\n\t.state('counter', 0)\n\t.get('/', ({ store }) => store.counter++)\n\t.listen(3000)\n"
  },
  {
    "path": "example/custom-response.ts",
    "content": "import { Elysia } from '../src'\n\nconst prettyJson = new Elysia()\n\t.mapResponse(({ response }) => {\n\t\tif (response instanceof Object)\n\t\t\treturn new Response(JSON.stringify(response, null, 4))\n\t})\n\t.as('scoped')\n\nnew Elysia()\n\t.use(prettyJson)\n\t.get('/', () => ({\n\t\thello: 'world'\n\t}))\n\t.listen(3000)\n"
  },
  {
    "path": "example/derive.ts",
    "content": "import { Elysia } from '../src'\n\nnew Elysia()\n\t.state('counter', 0)\n\t.derive(({ store }) => ({\n\t\tincrease() {\n\t\t\tstore.counter++\n\t\t}\n\t}))\n\t.derive(({ store }) => ({\n\t\tstore: {\n\t\t\tdoubled: store.counter * 2,\n\t\t\ttripled: store.counter * 3\n\t\t}\n\t}))\n\t.get('/', ({ increase, store }) => {\n\t\tincrease()\n\t\tconst { counter, doubled, tripled } = store\n\n\t\treturn {\n\t\t\tcounter,\n\t\t\tdoubled,\n\t\t\ttripled\n\t\t}\n\t})\n\t.listen(3000, ({ hostname, port }) => {\n\t\tconsole.log(`🦊 running at http://${hostname}:${port}`)\n\t})\n"
  },
  {
    "path": "example/error.ts",
    "content": "import { Elysia, t } from '../src'\n\nnew Elysia()\n\t.post('/', ({ body }) => body, {\n\t\tbody: t.Object({\n\t\t\tusername: t.String(),\n\t\t\tpassword: t.String(),\n\t\t\tnested: t.Optional(\n\t\t\t\tt.Object({\n\t\t\t\t\thi: t.String()\n\t\t\t\t})\n\t\t\t)\n\t\t}),\n\t\terror({ error }) {\n\t\t\tconsole.log(error)\n\t\t}\n\t})\n\t.listen(3000)\n"
  },
  {
    "path": "example/extension.ts",
    "content": "import { Elysia, t } from '../src'\n\nconst a0 = new Elysia().get('/a0', () => 'a')\nconst a1 = new Elysia().get('/a1', () => 'a')\nconst a2 = new Elysia().get('/a2', () => 'a')\nconst a3 = new Elysia().get('/a3', () => 'a')\nconst a4 = new Elysia().get('/a4', () => 'a')\nconst a5 = new Elysia().get('/a5', () => 'a')\nconst a6 = new Elysia().get('/a6', () => 'a')\nconst a7 = new Elysia().get('/a7', () => 'a')\nconst a8 = new Elysia().get('/a8', () => 'a')\nconst a9 = new Elysia().get('/a9', () => 'a')\nconst a10 = new Elysia().get('/a10', () => 'a')\nconst a11 = new Elysia().get('/a11', () => 'a')\nconst a12 = new Elysia().get('/a12', () => 'a')\nconst a13 = new Elysia().get('/a13', () => 'a')\nconst a14 = new Elysia().get('/a14', () => 'a')\nconst a15 = new Elysia().get('/a15', () => 'a')\nconst a16 = new Elysia().get('/a16', () => 'a')\nconst a17 = new Elysia().get('/a17', () => 'a')\nconst a18 = new Elysia().get('/a18', () => 'a')\nconst a19 = new Elysia().get('/a19', () => 'a')\nconst a20 = new Elysia().get('/a20', () => 'a')\nconst a21 = new Elysia().get('/a21', () => 'a')\nconst a22 = new Elysia().get('/a22', () => 'a')\nconst a23 = new Elysia().get('/a23', () => 'a')\nconst a24 = new Elysia().get('/a24', () => 'a')\nconst a25 = new Elysia().get('/a25', () => 'a')\nconst a26 = new Elysia().get('/a26', () => 'a')\nconst a27 = new Elysia().get('/a27', () => 'a')\nconst a28 = new Elysia().get('/a28', () => 'a')\nconst a29 = new Elysia().get('/a29', () => 'a')\nconst a30 = new Elysia().get('/a30', () => 'a')\nconst a31 = new Elysia().get('/a31', () => 'a')\nconst a32 = new Elysia().get('/a32', () => 'a')\nconst a33 = new Elysia().get('/a33', () => 'a')\nconst a34 = new Elysia().get('/a34', () => 'a')\nconst a35 = new Elysia().get('/a35', () => 'a')\nconst a36 = new Elysia().get('/a36', () => 'a')\nconst a37 = new Elysia().get('/a37', () => 'a')\nconst a38 = new Elysia().get('/a38', () => 'a')\nconst a39 = new Elysia().get('/a39', () => 'a')\nconst a40 = new Elysia().get('/a40', () => 'a')\nconst a41 = new Elysia().get('/a41', () => 'a')\nconst a42 = new Elysia().get('/a42', () => 'a')\nconst a43 = new Elysia().get('/a43', () => 'a')\nconst a44 = new Elysia().get('/a44', () => 'a')\nconst a45 = new Elysia().get('/a45', () => 'a')\nconst a46 = new Elysia().get('/a46', () => 'a')\nconst a47 = new Elysia().get('/a47', () => 'a')\nconst a48 = new Elysia().get('/a48', () => 'a')\nconst a49 = new Elysia().get('/a49', () => 'a')\nconst a50 = new Elysia().get('/a50', () => 'a')\nconst a51 = new Elysia().get('/a51', () => 'a')\nconst a52 = new Elysia().get('/a52', () => 'a')\nconst a53 = new Elysia().get('/a53', () => 'a')\nconst a54 = new Elysia().get('/a54', () => 'a')\nconst a55 = new Elysia().get('/a55', () => 'a')\nconst a56 = new Elysia().get('/a56', () => 'a')\nconst a57 = new Elysia().get('/a57', () => 'a')\nconst a58 = new Elysia().get('/a58', () => 'a')\nconst a59 = new Elysia().get('/a59', () => 'a')\nconst a60 = new Elysia().get('/a60', () => 'a')\nconst a61 = new Elysia().get('/a61', () => 'a')\nconst a62 = new Elysia().get('/a62', () => 'a')\nconst a63 = new Elysia().get('/a63', () => 'a')\nconst a64 = new Elysia().get('/a64', () => 'a')\nconst a65 = new Elysia().get('/a65', () => 'a')\nconst a66 = new Elysia().get('/a66', () => 'a')\nconst a67 = new Elysia().get('/a67', () => 'a')\nconst a68 = new Elysia().get('/a68', () => 'a')\nconst a69 = new Elysia().get('/a69', () => 'a')\nconst a70 = new Elysia().get('/a70', () => 'a')\nconst a71 = new Elysia().get('/a71', () => 'a')\nconst a72 = new Elysia().get('/a72', () => 'a')\nconst a73 = new Elysia().get('/a73', () => 'a')\nconst a74 = new Elysia().get('/a74', () => 'a')\nconst a75 = new Elysia().get('/a75', () => 'a')\nconst a76 = new Elysia().get('/a76', () => 'a')\nconst a77 = new Elysia().get('/a77', () => 'a')\nconst a78 = new Elysia().get('/a78', () => 'a')\nconst a79 = new Elysia().get('/a79', () => 'a')\nconst a80 = new Elysia().get('/a80', () => 'a')\nconst a81 = new Elysia().get('/a81', () => 'a')\nconst a82 = new Elysia().get('/a82', () => 'a')\nconst a83 = new Elysia().get('/a83', () => 'a')\nconst a84 = new Elysia().get('/a84', () => 'a')\nconst a85 = new Elysia().get('/a85', () => 'a')\nconst a86 = new Elysia().get('/a86', () => 'a')\nconst a87 = new Elysia().get('/a87', () => 'a')\nconst a88 = new Elysia().get('/a88', () => 'a')\nconst a89 = new Elysia().get('/a89', () => 'a')\nconst a90 = new Elysia().get('/a90', () => 'a')\nconst a91 = new Elysia().get('/a91', () => 'a')\nconst a92 = new Elysia().get('/a92', () => 'a')\nconst a93 = new Elysia().get('/a93', () => 'a')\nconst a94 = new Elysia().get('/a94', () => 'a')\nconst a95 = new Elysia().get('/a95', () => 'a')\nconst a96 = new Elysia().get('/a96', () => 'a')\nconst a97 = new Elysia().get('/a97', () => 'a')\nconst a98 = new Elysia().get('/a98', () => 'a')\nconst a99 = new Elysia().get('/a99', () => 'a')\n\nconst app1 = new Elysia()\n\t.use(a0)\n\t.use(a1)\n\t.use(a2)\n\t.use(a3)\n\t.use(a4)\n\t.use(a5)\n\t.use(a6)\n\t.use(a7)\n\t.use(a8)\n\t.use(a9)\n\t.use(a10)\n\t.use(a11)\n\t.use(a12)\n\t.use(a13)\n\t.use(a14)\n\t.use(a15)\n\t.use(a16)\n\t.use(a17)\n\t.use(a18)\n\t.use(a19)\n\t.use(a20)\n\t.use(a21)\n\t.use(a22)\n\t.use(a23)\n\t.use(a24)\n\t.use(a25)\n\t.use(a26)\n\t.use(a27)\n\t.use(a28)\n\t.use(a29)\n\t.use(a30)\n\t.use(a31)\n\t.use(a32)\n\t.use(a33)\n\t.use(a34)\n\t.use(a35)\n\t.use(a36)\n\t.use(a37)\n\t.use(a38)\n\t.use(a39)\n\t.use(a40)\n\nconst app2 = new Elysia()\n\t.use(a41)\n\t.use(a42)\n\t.use(a43)\n\t.use(a44)\n\t.use(a45)\n\t.use(a46)\n\t.use(a47)\n\t.use(a48)\n\t.use(a49)\n\t.use(a50)\n\t.use(a51)\n\t.use(a52)\n\t.use(a53)\n\t.use(a54)\n\t.use(a55)\n\t.use(a56)\n\t.use(a57)\n\t.use(a58)\n\t.use(a59)\n\t.use(a60)\n\t.use(a61)\n\t.use(a62)\n\t.use(a63)\n\t.use(a64)\n\t.use(a65)\n\t.use(a66)\n\t.use(a67)\n\t.use(a68)\n\t.use(a69)\n\t.use(a70)\n\t.use(a71)\n\t.use(a72)\n\t.use(a73)\n\t.use(a74)\n\t.use(a75)\n\t.use(a76)\n\t.use(a77)\n\t.use(a78)\n\t.use(a79)\n\nconst app3 = new Elysia()\n\t.use(a80)\n\t.use(a81)\n\t.use(a82)\n\t.use(a83)\n\t.use(a84)\n\t.use(a85)\n\t.use(a86)\n\t.use(a87)\n\t.use(a88)\n\t.use(a89)\n\t.use(a90)\n\t.use(a91)\n\t.use(a92)\n\t.use(a93)\n\t.use(a94)\n\t.use(a95)\n\t.use(a96)\n\t.use(a97)\n\t.use(a98)\n\t.use(a99)\n\nconst main = new Elysia().use(app1).use(app2).use(app3)\n"
  },
  {
    "path": "example/file.ts",
    "content": "import { Elysia, file } from '../src'\nimport Page from './index.html'\n\n/**\n * Example of handle single static file\n *\n * @see https://github.com/elysiajs/elysia-static\n */\nnew Elysia()\n\t.headers({\n\t\tserver: 'Elysia'\n\t})\n\t.onRequest(({ request }) => {\n\t\tconsole.log(request.method, request.url)\n\t})\n\t.get('/', Page)\n\t.get('/tako', file('./example/takodachi.png'))\n\t.get('/mika.mp4', Bun.file('test/kyuukurarin.mp4'))\n\t.listen(3000)\n"
  },
  {
    "path": "example/guard.ts",
    "content": "import { Elysia, t } from '../src'\n\nnew Elysia()\n\t.state('name', 'salt')\n\t.get('/', ({ store: { name } }) => `Hi ${name}`, {\n\t\tquery: t.Object({\n\t\t\tname: t.String()\n\t\t})\n\t})\n\t// If query 'name' is not preset, skip the whole handler\n\t.guard(\n\t\t{\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t},\n\t\t(app) =>\n\t\t\tapp\n\t\t\t\t// Query type is inherited from guard\n\t\t\t\t.get('/profile', ({ query }) => `Hi`)\n\t\t\t\t// Store is inherited\n\t\t\t\t.post('/name', ({ store: { name }, body, query }) => name, {\n\t\t\t\t\tbody: t.Object({\n\t\t\t\t\t\tid: t.Number({\n\t\t\t\t\t\t\tminimum: 5\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tusername: t.String(),\n\t\t\t\t\t\tprofile: t.Object({\n\t\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\t)\n\t.listen(3000)\n"
  },
  {
    "path": "example/headers.ts",
    "content": "import { Elysia } from '../src'\n\nimport cookie from '../src/index'\n\nnew Elysia()\n\t.get('/', ({ set }) => {\n\t\tset.headers['x-powered-by'] = 'Elysia'\n\t\tset.status = 'Bad Request'\n\t})\n\t.listen(3000)\n"
  },
  {
    "path": "example/hook.ts",
    "content": "import { Elysia } from '../src'\n\nnew Elysia()\n\t// Create global mutable state\n\t.state('counter', 0)\n\t// Increase counter by 1 on every request on any handler\n\t.onTransform(({ store }) => {\n\t\tstore.counter++\n\t})\n\t.get('/', ({ store: { counter } }) => counter, {\n\t\t// Increase counter only when this handler is called\n\t\ttransform: [\n\t\t\t({ store }) => {\n\t\t\t\tstore.counter++\n\t\t\t},\n\t\t\t({ store }) => {\n\t\t\t\tstore.counter++\n\t\t\t}\n\t\t]\n\t})\n\t.listen(3000)\n"
  },
  {
    "path": "example/html-import.ts",
    "content": "import { Elysia, t } from '../src'\nimport Page from './index.html'\n\nnew Elysia()\n\t.get('/', Page)\n\t.get('/mika.mp4', Bun.file('test/kyuukurarin.mp4'))\n\t.listen(3000)\n"
  },
  {
    "path": "example/http.ts",
    "content": "import { Elysia, t } from '../src'\n\nconst t1 = performance.now()\n\nconst loggerPlugin = new Elysia()\n\t.get('/hi', () => 'Hi')\n\t.decorate('log', () => 'A')\n\t.decorate('date', () => new Date())\n\t.state('fromPlugin', 'From Logger')\n\t.use((app) => app.state('abc', 'abc'))\n\nconst app = new Elysia()\n\t.onRequest(({ set }) => {\n\t\tset.headers = {\n\t\t\t'Access-Control-Allow-Origin': '*'\n\t\t}\n\t})\n\t.use(loggerPlugin)\n\t.state('build', Date.now())\n\t.get('/', () => 'Elysia')\n\t.get('/tako', () => Bun.file('./example/takodachi.png'))\n\t.get('/json', () => ({\n\t\thi: 'world'\n\t}))\n\t.get('/root/plugin/log', ({ log, store: { build } }) => {\n\t\tlog()\n\n\t\treturn build\n\t})\n\t.get('/wildcard/*', () => 'Hi Wildcard')\n\t.get('/query', () => 'Elysia', {\n\t\tbeforeHandle: ({ query }) => {\n\t\t\tconsole.log('Name:', query?.name)\n\n\t\t\tif (query?.name === 'aom') return 'Hi saltyaom'\n\t\t},\n\t\tquery: t.Object({\n\t\t\tname: t.String()\n\t\t})\n\t})\n\t.post('/json', async ({ body }) => body, {\n\t\tbody: t.Object({\n\t\t\tname: t.String(),\n\t\t\tadditional: t.String()\n\t\t})\n\t})\n\t.post('/transform-body', async ({ body }) => body, {\n\t\tbeforeHandle: (ctx) => {\n\t\t\tctx.body = {\n\t\t\t\t...ctx.body,\n\t\t\t\tadditional: 'Elysia'\n\t\t\t}\n\t\t},\n\t\tbody: t.Object({\n\t\t\tname: t.String(),\n\t\t\tadditional: t.String()\n\t\t})\n\t})\n\t.get('/id/:id', ({ params: { id } }) => id, {\n\t\ttransform({ params }) {\n\t\t\tparams.id = +params.id\n\t\t},\n\t\tparams: t.Object({\n\t\t\tid: t.Number()\n\t\t})\n\t})\n\t.post('/new/:id', async ({ body, params }) => body, {\n\t\tparams: t.Object({\n\t\t\tid: t.Number()\n\t\t}),\n\t\tbody: t.Object({\n\t\t\tusername: t.String()\n\t\t})\n\t})\n\t.get('/trailing-slash', () => 'A')\n\t.group('/group', (app) =>\n\t\tapp\n\t\t\t.onBeforeHandle<{\n\t\t\t\tquery: {\n\t\t\t\t\tname: string\n\t\t\t\t}\n\t\t\t}>(({ query }) => {\n\t\t\t\tif (query?.name === 'aom') return 'Hi saltyaom'\n\t\t\t})\n\t\t\t.get('/', () => 'From Group')\n\t\t\t.get('/hi', () => 'HI GROUP')\n\t\t\t.get('/elysia', () => 'Welcome to Elysian Realm')\n\t\t\t.get('/fbk', () => 'FuBuKing')\n\t)\n\t.get('/response-header', ({ set }) => {\n\t\tset.status = 404\n\t\tset.headers['a'] = 'b'\n\n\t\treturn 'A'\n\t})\n\t.get('/this/is/my/deep/nested/root', () => 'Hi')\n\t.get('/build', ({ store: { build } }) => build)\n\t.get('/ref', ({ date }) => date())\n\t.get('/response', () => new Response('Hi'))\n\t.get('/error', () => new Error('Something went wrong'))\n\t.get('/401', ({ set }) => {\n\t\tset.status = 401\n\n\t\treturn 'Status should be 401'\n\t})\n\t.get('/timeout', async () => {\n\t\tawait new Promise((resolve) => setTimeout(resolve, 2000))\n\n\t\treturn 'A'\n\t})\n\t.all('/all', () => 'hi')\n\t.onError(({ code, error, set }) => {\n\t\tif (code === 'NOT_FOUND') {\n\t\t\tset.status = 404\n\n\t\t\treturn 'Not Found :('\n\t\t}\n\t})\n\nconst t2 = performance.now()\n\napp.listen(8080, ({ hostname, port }) => {\n\tconsole.log(`🦊 Elysia is running at http://${hostname}:${port}`)\n})\n\nconsole.log('took', t2 - t1, 'ms')\n"
  },
  {
    "path": "example/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>Bun HTML Import</title>\n\t</head>\n\t<body>\n\t\t<h1>Hi</h1>\n\t\t<video>\n\t\t\t<!-- <source src=\"/mika.mp4\" type=\"video/mp4\" /> -->\n\t\t</video>\n\t</body>\n</html>\n"
  },
  {
    "path": "example/lazy/index.ts",
    "content": "import Elysia from '../../src'\n\nexport const lazy = (app: Elysia) =>\n\tapp.state('a', 'b').get('/lazy', 'Hi from lazy loaded module')\n\nexport default lazy\n"
  },
  {
    "path": "example/lazy-module.ts",
    "content": "import { Elysia } from '../src'\n\nconst plugin = (app: Elysia) => app.get('/plugin', () => 'Plugin')\nconst asyncPlugin = async (app: Elysia) => app.get('/async', () => 'A')\n\nconst app = new Elysia()\n\t.decorate('a', () => 'hello')\n\t.use(plugin)\n\t.use(import('./lazy'))\n\t.use((app) => app.get('/inline', ({ store: { a } }) => 'inline'))\n\t.get('/', ({ a }) => a())\n\t.listen(3000)\n\nawait app.modules\n\nconsole.log(\n\t`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`\n)\n"
  },
  {
    "path": "example/native.ts",
    "content": "Bun.serve({\n\tport: 3000,\n\tfetch: (request) => {\n\t\tthrow new Error('A')\n\t},\n\terror(request) {\n\t\treturn new Response('error')\n\t}\n})\n"
  },
  {
    "path": "example/nested-multipart-files.ts",
    "content": "import { Elysia, t } from '../src'\n\n/**\n * Example: Nested File Uploads with Multipart Forms\n *\n * Elysia supports nested file uploads using dot notation in multipart forms.\n * This allows you to organize files and data in a nested structure while\n * still using standard multipart/form-data encoding.\n *\n * How it works:\n * 1. Client sends files with dot notation keys (e.g., \"user.avatar\")\n * 2. Elysia automatically reconstructs the nested object structure\n * 3. Your handler receives a properly nested object\n */\n\nconst app = new Elysia()\n\t// Basic nested file upload\n\t.post(\n\t\t'/user/profile',\n\t\t({ body }) => ({\n\t\t\tmessage: 'Profile created!',\n\t\t\tuser: {\n\t\t\t\tname: body.user.name,\n\t\t\t\tavatarSize: body.user.avatar.size\n\t\t\t}\n\t\t}),\n\t\t{\n\t\t\tbody: t.Object({\n\t\t\t\tuser: t.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tavatar: t.File()\n\t\t\t\t})\n\t\t\t})\n\t\t}\n\t)\n\n\t// Deeply nested files\n\t.post(\n\t\t'/user/portfolio',\n\t\t({ body }) => ({\n\t\t\tbio: body.user.profile.bio,\n\t\t\tphotoCount: body.user.profile.photos.length\n\t\t}),\n\t\t{\n\t\t\tbody: t.Object({\n\t\t\t\tuser: t.Object({\n\t\t\t\t\tprofile: t.Object({\n\t\t\t\t\t\tbio: t.String(),\n\t\t\t\t\t\tphotos: t.Files()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t}\n\t)\n\n\t// Mixed flat and nested fields\n\t.post(\n\t\t'/post',\n\t\t({ body }) => ({\n\t\t\ttitle: body.title,\n\t\t\tauthorName: body.author.name,\n\t\t\timageSize: body.author.avatar.size\n\t\t}),\n\t\t{\n\t\t\tbody: t.Object({\n\t\t\t\ttitle: t.String(),\n\t\t\t\tauthor: t.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tavatar: t.File()\n\t\t\t\t})\n\t\t\t})\n\t\t}\n\t)\n\t.listen(3000)\n\nconsole.log(`🦊 Server running at http://${app.server?.hostname}:${app.server?.port}`)\n\n/**\n * Client-side usage (with fetch):\n *\n * const formData = new FormData()\n * formData.append('user.name', 'John')\n * formData.append('user.avatar', fileBlob)\n *\n * await fetch('http://localhost:3000/user/profile', {\n *   method: 'POST',\n *   body: formData\n * })\n *\n *\n * Eden client usage (future):\n *\n * await client.user.profile.post({\n *   user: {\n *     name: 'John',\n *     avatar: fileBlob  // Eden will flatten this automatically\n *   }\n * })\n */\n"
  },
  {
    "path": "example/nested-schema.ts",
    "content": "import { Elysia, t } from '../src'\n\nnew Elysia()\n\t.guard(\n\t\t{\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t},\n\t\t(app) =>\n\t\t\tapp\n\t\t\t\t.get('/', ({ query }) => 'A', {\n\t\t\t\t\tbeforeHandle: ({ query }) => {},\n\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\ta: t.String()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t\t.guard(\n\t\t\t\t\t{\n\t\t\t\t\t\theaders: t.Object({\n\t\t\t\t\t\t\ta: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t},\n\t\t\t\t\t(app) =>\n\t\t\t\t\t\tapp.get('/a', () => 'A', {\n\t\t\t\t\t\t\tbeforeHandle: ({ query }) => {},\n\t\t\t\t\t\t\tbody: t.Object({\n\t\t\t\t\t\t\t\tusername: t.String()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t})\n\t\t\t\t)\n\t)\n\t.get('*', () => 'Star now work')\n\t.listen(3000)\n"
  },
  {
    "path": "example/newFile.ts",
    "content": ""
  },
  {
    "path": "example/openapi.ts",
    "content": "import { Elysia, t } from '../src'\nimport { openapi as OpenAPI } from '@elysiajs/openapi'\nimport { fromTypes } from '@elysiajs/openapi/gen'\n\nconst openapi = (a: any) =>\n\tnew Elysia().use((app) => {\n\t\tapp.use(\n\t\t\t// @ts-ignore\n\t\t\tOpenAPI(a)\n\t\t)\n\n\t\treturn app\n\t})\n\n// Elysia 1.4: lifecycle event type soundness\nexport const app = new Elysia()\n\t.use(\n\t\topenapi({\n\t\t\treferences: fromTypes('example/openapi.ts')\n\t\t})\n\t)\n\t.macro({\n\t\tauth: {\n\t\t\tresponse: {\n\t\t\t\t409: t.Literal('Conflict')\n\t\t\t},\n\t\t\tbeforeHandle({ status }) {\n\t\t\t\tif (Math.random() < 0.05) return status(410)\n\t\t\t},\n\t\t\tresolve: () => ({ a: 'a' })\n\t\t}\n\t})\n\t.onError(({ status }) => {\n\t\tif (Math.random() < 0.05) return status(400)\n\t})\n\t.resolve(({ status }) => {\n\t\tif (Math.random() < 0.05) return status(401)\n\t})\n\t.onBeforeHandle([\n\t\t({ status }) => {\n\t\t\tif (Math.random() < 0.05) return status(402)\n\t\t},\n\t\t({ status }) => {\n\t\t\tif (Math.random() < 0.05) return status(403)\n\t\t}\n\t])\n\t.guard({\n\t\tbeforeHandle: [\n\t\t\t({ status }) => {\n\t\t\t\tif (Math.random() < 0.05) return status(405)\n\t\t\t},\n\t\t\t({ status }) => {\n\t\t\t\tif (Math.random() < 0.05) return status(406)\n\t\t\t}\n\t\t],\n\t\tafterHandle({ status }) {\n\t\t\tif (Math.random() < 0.05) return status(407)\n\t\t},\n\t\terror({ status }) {\n\t\t\tif (Math.random() < 0.05) return status(408)\n\t\t}\n\t})\n\t.post(\n\t\t'/',\n\t\t({ status }) =>\n\t\t\tMath.random() < 0.05 ? status(409, 'Conflict') : 'Type Soundness',\n\t\t{\n\t\t\tauth: true,\n\t\t\tresponse: {\n\t\t\t\t411: t.Literal('Length Required')\n\t\t\t}\n\t\t}\n\t)\n\t.listen(3000)\n\n// app['~Routes']['post']['response']\n"
  },
  {
    "path": "example/params.ts",
    "content": "import { Elysia } from '../src'\n\nconst app = new Elysia()\n\t.get('/', () => 'Elysia')\n\t// Retrieve params, automatically typed\n\t.get('/id/:id', ({ params }) => params.id)\n\t.listen(3000)\n\nconsole.log('Listen')\n"
  },
  {
    "path": "example/proxy.ts",
    "content": "import { Elysia } from '../src'\n\nnew Elysia()\n\t.all('/*', ({ request, params, query }) =>\n\t\tfetch({\n\t\t\t...request,\n\t\t\turl: `https://macosplay.com/${params['*']}?${new URLSearchParams(query)}`\n\t\t})\n\t)\n\t.listen(3000)\n"
  },
  {
    "path": "example/redirect.ts",
    "content": "import { Elysia } from '../src'\n\nnew Elysia()\n\t.get('/', () => 'Hi')\n\t.get('/redirect', ({ redirect }) => redirect('/'))\n\t.listen(3000)\n"
  },
  {
    "path": "example/rename.ts",
    "content": "import { Elysia, t } from '../src'\n\n// ? Elysia#83 | Proposal: Standardized way of renaming third party plugin-scoped stuff\n// this would be a plugin provided by a third party\nconst myPlugin = new Elysia()\n\t.decorate('myProperty', 42)\n\t.model('salt', t.String())\n\nnew Elysia()\n\t.use(\n\t\tmyPlugin\n\t\t\t// map decorator, rename \"myProperty\" to \"renamedProperty\"\n\t\t\t.decorate(({ myProperty, ...decorators }) => ({\n\t\t\t\trenamedProperty: myProperty,\n\t\t\t\t...decorators\n\t\t\t}))\n\t\t\t// map model, rename \"salt\" to \"pepper\"\n\t\t\t.model(({ salt, ...models }) => ({\n\t\t\t\t...models,\n\t\t\t\tpepper: t.String()\n\t\t\t}))\n\t\t\t// Add prefix\n\t\t\t.prefix('decorator', 'unstable')\n\t)\n\t.get(\n\t\t'/mapped',\n\t\t({ unstableRenamedProperty }) => unstableRenamedProperty\n\t)\n\t.post('/pepper', ({ body }) => body, {\n\t\tbody: 'pepper',\n\t\t// response: t.String()\n\t})\n"
  },
  {
    "path": "example/response.ts",
    "content": "import { Elysia } from '../src'\n\nnew Elysia()\n\t.get('/', ({ set }) => {\n\t\tset.headers['X-POWERED-BY'] = 'Elysia'\n\n\t\t// Return custom response\n\t\treturn new Response('Shuba Shuba', {\n\t\t\theaders: {\n\t\t\t\tduck: 'shuba duck'\n\t\t\t},\n\t\t\tstatus: 418\n\t\t})\n\t})\n\t.listen(3000)\n"
  },
  {
    "path": "example/router.ts",
    "content": "import { Elysia } from '../src'\n\nconst prefix = <Prefix extends string = string>(prefix: Prefix) =>\n\tnew Elysia({ prefix })\n\t\t.state('b', 'b')\n\t\t.get('/2', () => 2)\n\t\t.guard({}, (app) => app.get('/do', () => 'something'))\n\t\t.group('/v2', (app) => app.guard({}, (app) => app.get('/ok', () => 1)))\n\nconst a = new Elysia()\n\t.get('/a', () => 'A')\n\t.guard({}, (app) => app.get('/guard', () => 'a'))\n\t.use(prefix('prefixed'))\n\t.listen(3000)\n"
  },
  {
    "path": "example/schema.ts",
    "content": "import { Elysia, t } from '../src'\n\nconst app = new Elysia()\n\t.model({\n\t\tname: t.Object({\n\t\t\tname: t.String()\n\t\t}),\n\t\tb: t.Object({\n\t\t\tresponse: t.Number()\n\t\t}),\n\t\tauthorization: t.Object({\n\t\t\tauthorization: t.String()\n\t\t})\n\t})\n\t// Strictly validate response\n\t.get('/', () => 'hi')\n\t// Strictly validate body and response\n\t.post('/', ({ body, query }) => body.id, {\n\t\tbody: t.Object({\n\t\t\tid: t.Number(),\n\t\t\tusername: t.String(),\n\t\t\tprofile: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\t})\n\t// Strictly validate query, params, and body\n\t.get('/query/:id', ({ query: { name }, params }) => name, {\n\t\tquery: t.Object({\n\t\t\tname: t.String()\n\t\t}),\n\t\tparams: t.Object({\n\t\t\tid: t.String()\n\t\t}),\n\t\tresponse: {\n\t\t\t200: t.String(),\n\t\t\t300: t.Object({\n\t\t\t\terror: t.String()\n\t\t\t})\n\t\t}\n\t})\n\t.guard(\n\t\t{\n\t\t\theaders: 'authorization'\n\t\t},\n\t\t(app) =>\n\t\t\tapp\n\t\t\t\t.derive(({ headers }) => ({\n\t\t\t\t\tuserId: headers.authorization\n\t\t\t\t}))\n\t\t\t\t.get('/', ({ userId }) => 'A')\n\t\t\t\t.post('/id/:id', ({ query, body, params, userId }) => body, {\n\t\t\t\t\tparams: t.Object({\n\t\t\t\t\t\tid: t.Number()\n\t\t\t\t\t}),\n\t\t\t\t\ttransform({ params }) {\n\t\t\t\t\t\tparams.id = +params.id\n\t\t\t\t\t}\n\t\t\t\t})\n\t)\n\t.listen(3000)\n"
  },
  {
    "path": "example/simple.ts",
    "content": "import { Elysia } from '../src'\n\n// Simple Hello World\nconst t1 = performance.now()\nnew Elysia()\n\t.get('/', () => 'Hi')\n\t.listen(3000)\n\nconsole.log(performance.now() - t1)\n\n// Bun.serve({\n// \tport: 8080,\n// \tfetch() {\n// \t\treturn new Response('Hi')\n// \t}\n// })\n\n"
  },
  {
    "path": "example/sleep.ts",
    "content": "const sleep = (time: number) => new Promise(resolve => setTimeout(resolve, time))\n\nBun.serve({\n\tport: 3000,\n\tfetch: async () => {\n\t\tawait sleep(1000)\n\n\t\treturn new Response('Hi')\n\t}\n})\n"
  },
  {
    "path": "example/spawn.ts",
    "content": "import { $ } from 'bun'\nimport { cpus } from 'os'\n\nconst total = cpus().length - 1\nconst ops = []\n\nfor (let i = 0; i < total; i++)\n\tops.push($`NODE_ENV=production bun example/a.ts`)\n\nawait Promise.all(ops)\n"
  },
  {
    "path": "example/store.ts",
    "content": "import { Elysia } from '../src'\n\nnew Elysia()\n\t// Create globally mutable store\n\t.state('name', 'Fubuki')\n\t.get('/id/:id', ({ params: { id }, store: { name } }) => `${id} ${name}`)\n"
  },
  {
    "path": "example/stress/a.ts",
    "content": "import { getHeapSpaceStatistics } from 'v8'\nimport { Elysia, t } from '../../src'\nimport { generateHeapSnapshot } from 'bun'\n\nconst memory = process.memoryUsage().heapTotal / 1024 / 1024\n\nconst total = 500\nconst sub = 1\n\nconst app = new Elysia()\nconst plugin = new Elysia()\n\nconst t1 = performance.now()\n\nfor (let i = 0; i < total * sub; i++)\n\tplugin.get(`/${i}`, () => 'hi', { response: t.String() })\n\napp.use(plugin)\n\nconst t2 = performance.now()\n\nBun.gc(true)\nconst memoryAfter = process.memoryUsage().heapTotal / 1024 / 1024\nconst totalRoutes = total * sub\nconst totalTime = t2 - t1\nconst avgTimePerRoute = totalTime / totalRoutes\n\nconsole.log(`${totalRoutes} routes took ${totalTime.toFixed(4)} ms`)\nconsole.log(`Average ${avgTimePerRoute.toFixed(4)} ms per route`)\nconsole.log(`${(memoryAfter - memory).toFixed(2)} MB memory used`)\n"
  },
  {
    "path": "example/stress/decorate.ts",
    "content": "import { Elysia, t } from '../../src'\n\nconst total = 1000\nconst sub = 50\n\nconst app = new Elysia()\n\nconst memory = process.memoryUsage().heapTotal / 1024 / 1024\nconsole.log(`${total} Elysia instances with ${sub} decorations each`)\n\nconst t1 = performance.now()\n\nfor (let i = 0; i < total; i++) {\n\tconst plugin = new Elysia()\n\n\tfor (let j = 0; j < sub; j++)\n\t\tplugin.decorate('a', {\n\t\t\t[`value-${i * sub + j}`]: 1\n\t\t})\n\n\tapp.use(plugin)\n}\n\nconst t2 = performance.now()\n\nBun.gc(true)\n\nconst memoryAfter = process.memoryUsage().heapTotal / 1024 / 1024\nconsole.log(+(memoryAfter - memory).toFixed(2), 'MB memory used')\nconsole.log('total', +(t2 - t1).toFixed(2), 'ms')\nconsole.log(+((t2 - t1) / (total * sub)).toFixed(6), 'decoration/ms')\n"
  },
  {
    "path": "example/stress/instance.ts",
    "content": "import { Elysia, t } from '../../src'\n\nconst total = 100\nconst sub = 5\n\nconst app = new Elysia({ precompile: true })\n\nconst memory = process.memoryUsage().heapTotal / 1024 / 1024\nconst t1 = performance.now()\n\nfor (let i = 0; i < total; i++) {\n\tconst plugin = new Elysia({\n\t\tcookie: {\n\t\t\tdomain: 'saltyaom.com',\n\t\t\tpriority: 'high',\n\t\t\tsecrets: 'a',\n\t\t\tsign: 'a'\n\t\t}\n\t})\n\n\tfor (let j = 0; j < sub; j++) plugin.get(`/${i * sub + j}`, () => 'hi')\n\n\tapp.use(plugin)\n}\n\nconst t2 = performance.now()\n\nBun.gc(true)\n\nconst memoryAfter = process.memoryUsage().heapTotal / 1024 / 1024\nconsole.log(+(memoryAfter - memory).toFixed(2), 'MB memory used')\nconsole.log(+(t2 - t1).toFixed(2), 'ms')\n"
  },
  {
    "path": "example/stress/memoir.ts",
    "content": "import { t } from '../../src'\nimport { Memoirist } from 'memoirist'\n\nconst total = 1000\nconst stack: Memoirist<any>[] = []\n\n{\n\tconst t1 = performance.now()\n\tconst memory = process.memoryUsage().heapTotal / 1024 / 1024\n\n\tfor (let i = 0; i < total; i++) {\n\t\tfor (let i = 0; i < 2; i++) {\n\t\t\tconst router = new Memoirist()\n\t\t\t// router.add('GET', '/a', () => 'Hello, World!')\n\t\t\t// router.add('GET', '/b', () => 'Hello, World!')\n\n\t\t\tstack.push(router)\n\t\t}\n\t}\n\n\tconst memoryAfter = process.memoryUsage().heapTotal / 1024 / 1024\n\tconst took = performance.now() - t1\n\n\tconsole.log(\n\t\tIntl.NumberFormat().format(total),\n\t\t'routes took',\n\t\t+took.toFixed(4),\n\t\t'ms'\n\t)\n\tconsole.log('Average', +(took / total).toFixed(4), 'ms / route')\n\n\tconsole.log(memoryAfter - memory, 'MB memory used')\n}\n"
  },
  {
    "path": "example/stress/multiple-routes.ts",
    "content": "import { Elysia, t } from '../../src'\nimport v8 from 'v8'\n\nconst total = 500\n\n{\n\tconst app = new Elysia({ precompile: true })\n\n\tconst t1 = performance.now()\n\tconst memory = process.memoryUsage().heapTotal / 1024 / 1024\n\n\tfor (let i = 0; i < total; i++)\n\t\tapp.get(`/id/${i}`, () => 'hello', {\n\t\t\tresponse: t.String()\n\t\t})\n\n\tconst memoryAfter = process.memoryUsage().heapTotal / 1024 / 1024\n\tconst took = performance.now() - t1\n\n\tconsole.log(\n\t\tIntl.NumberFormat().format(total),\n\t\t'routes took',\n\t\t+took.toFixed(4),\n\t\t'ms'\n\t)\n\tconsole.log('Average', +(took / total).toFixed(4), 'ms / route')\n\n\tconsole.log(memoryAfter - memory, 'MB memory used')\n\tconsole.log(((memoryAfter - memory) / total) * 1024, 'KB memory used')\n\n\t// v8.writeHeapSnapshot()\n}\n"
  },
  {
    "path": "example/stress/sucrose.ts",
    "content": "// @ts-nocheck\n\nimport { sucrose } from '../../src/sucrose'\n\nconst total = 100_000\nconst t = performance.now()\n\nfor (let i = 0; i < total; i++) {\n\tsucrose({\n\t\thandler: function ({ query }) {\n\t\t\tquery.a\n\t\t},\n\t\tafterHandle: [],\n\t\tbeforeHandle: [\n\t\t\tfunction a({ params: { a, c: d }, ...rest }) {\n\t\t\t\tquery.b\n\t\t\t},\n\t\t\t({ error }) => {}\n\t\t],\n\t\terror: [\n\t\t\tfunction a({ query, query: { a, c: d }, headers: { hello } }) {\n\t\t\t\tquery.b\n\t\t\t},\n\t\t\t({ query: { f } }) => {}\n\t\t],\n\t\tmapResponse: [],\n\t\tonResponse: [],\n\t\tparse: [],\n\t\trequest: [],\n\t\tstart: [],\n\t\tstop: [],\n\t\ttrace: [],\n\t\ttransform: []\n\t})\n}\n\nconst took = performance.now() - t\n\nconsole.log(\n\tIntl.NumberFormat().format(total),\n\t'check took',\n\t+took.toFixed(4),\n\t'ms'\n)\nconsole.log('Average', +(took / total).toFixed(4), 'ms / check')\n"
  },
  {
    "path": "example/type-inference.ts",
    "content": "import { Elysia } from '../src'\n\nconst counter = (app: Elysia) => app.state('counter', 0)\n\nnew Elysia()\n\t.use(counter)\n\t.guard({}, (app) => app.get('/id/:id', ({ store: { counter } }) => counter))\n\t.listen(3000)\n"
  },
  {
    "path": "example/uint8array.ts",
    "content": "import { Elysia, t } from '../src'\n\nnew Elysia()\n\t.post('/', ({ body }) => body, {\n\t\tbody: t.Uint8Array()\n\t})\n\t.listen(3000)\n\nconst response = await fetch('http://localhost:3000', {\n\tmethod: 'POST',\n\tbody: new Uint8Array([\n\t\t229, 143, 175, 230, 132, 155, 227, 129, 143, 227, 129, 166, 227, 129,\n\t\t148, 227, 130, 129, 227, 130, 147\n\t]),\n\theaders: { 'content-type': 'application/octet-stream' }\n})\n\nconsole.log(response.status)\nconsole.log(await response.text())\n"
  },
  {
    "path": "example/upload.ts",
    "content": "import { Elysia, t } from '../src'\nimport { upload } from '../test/utils'\n\nconst app = new Elysia()\n\t.post('/single', ({ body: { file } }) => file, {\n\t\tbody: t.Object({\n\t\t\tfile: t.File()\n\t\t})\n\t})\n\t.post(\n\t\t'/multiple',\n\t\t({ body: { files } }) => files.reduce((a, b) => a + b.size, 0),\n\t\t{\n\t\t\tbody: t.Object({\n\t\t\t\tfiles: t.Files()\n\t\t\t})\n\t\t}\n\t)\n\t.listen(3000)\n\nconst { request } = upload('/single', {\n\tfile: 'millenium.jpg'\n})\n\napp.handle(request)\n\t.then((r) => r.text())\n\t.then(console.log)\n"
  },
  {
    "path": "example/video.ts",
    "content": "import { Elysia } from 'elysia'\n\nnew Elysia()\n\t.get('/', Bun.file('test/kyuukurarin.mp4'))\n\t.listen(3000)\n"
  },
  {
    "path": "example/websocket.ts",
    "content": "import { Elysia } from '../src'\n\nconst app = new Elysia()\n\t.state('start', 'here')\n\t.ws('/ws', {\n\t\topen(ws) {\n\t\t\tws.subscribe('asdf')\n\t\t\tconsole.log('Open Connection:', ws.id)\n\t\t},\n\t\tclose(ws) {\n\t\t\tconsole.log('Closed Connection:', ws.id)\n\t\t},\n\t\tmessage(ws, message) {\n\t\t\tws.publish('asdf', message)\n\t\t\tws.send(message)\n\t\t}\n\t})\n\t.get('/publish/:publish', ({ params: { publish: text } }) => {\n\t\tapp.server!.publish('asdf', text)\n\n\t\treturn text\n\t})\n\t.listen(3000, (server) => {\n\t\tconsole.log(`http://${server.hostname}:${server.port}`)\n\t})\n"
  },
  {
    "path": "knip.json",
    "content": "{\n    \"entry\": [\n        \"src/index.ts\"\n    ],\n    \"project\": [\n        \"src/**/*.{js,ts}\"\n    ],\n    \"ignoreDependencies\": [\n        \"@types/cookie\",\n        \"arktype\",\n        \"@elysiajs/openapi\",\n        \"eslint-plugin-security\",\n        \"expect-type\",\n        \"prettier\",\n        \"valibot\",\n        \"zod\",\n        \"file-type\"\n    ],\n    \"ignoreBinaries\": [\n        \"dist/bun/index.js\"\n    ]\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n\t\"name\": \"elysia\",\n\t\"description\": \"Ergonomic Framework for Human\",\n\t\"version\": \"1.4.28\",\n\t\"author\": {\n\t\t\"name\": \"saltyAom\",\n\t\t\"url\": \"https://github.com/SaltyAom\",\n\t\t\"email\": \"saltyaom@gmail.com\"\n\t},\n\t\"main\": \"./dist/index.js\",\n\t\"module\": \"./dist/index.mjs\",\n\t\"types\": \"./dist/index.d.ts\",\n\t\"exports\": {\n\t\t\"./package.json\": \"./package.json\",\n\t\t\".\": {\n\t\t\t\"types\": \"./dist/index.d.ts\",\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"require\": \"./dist/index.js\"\n\t\t},\n\t\t\"./ws\": {\n\t\t\t\"types\": \"./dist/ws/index.d.ts\",\n\t\t\t\"import\": \"./dist/ws/index.mjs\",\n\t\t\t\"require\": \"./dist/ws/index.js\"\n\t\t},\n\t\t\"./ws/types\": {\n\t\t\t\"types\": \"./dist/ws/types.d.ts\",\n\t\t\t\"import\": \"./dist/ws/types.mjs\",\n\t\t\t\"require\": \"./dist/ws/types.js\"\n\t\t},\n\t\t\"./ws/bun\": {\n\t\t\t\"types\": \"./dist/ws/bun.d.ts\",\n\t\t\t\"import\": \"./dist/ws/bun.mjs\",\n\t\t\t\"require\": \"./dist/ws/bun.js\"\n\t\t},\n\t\t\"./compose\": {\n\t\t\t\"types\": \"./dist/compose.d.ts\",\n\t\t\t\"import\": \"./dist/compose.mjs\",\n\t\t\t\"require\": \"./dist/compose.js\"\n\t\t},\n\t\t\"./context\": {\n\t\t\t\"types\": \"./dist/context.d.ts\",\n\t\t\t\"import\": \"./dist/context.mjs\",\n\t\t\t\"require\": \"./dist/context.js\"\n\t\t},\n\t\t\"./cookies\": {\n\t\t\t\"types\": \"./dist/cookies.d.ts\",\n\t\t\t\"import\": \"./dist/cookies.mjs\",\n\t\t\t\"require\": \"./dist/cookies.js\"\n\t\t},\n\t\t\"./error\": {\n\t\t\t\"types\": \"./dist/error.d.ts\",\n\t\t\t\"import\": \"./dist/error.mjs\",\n\t\t\t\"require\": \"./dist/error.js\"\n\t\t},\n\t\t\"./schema\": {\n\t\t\t\"types\": \"./dist/schema.d.ts\",\n\t\t\t\"import\": \"./dist/schema.mjs\",\n\t\t\t\"require\": \"./dist/schema.js\"\n\t\t},\n\t\t\"./sucrose\": {\n\t\t\t\"types\": \"./dist/sucrose.d.ts\",\n\t\t\t\"import\": \"./dist/sucrose.mjs\",\n\t\t\t\"require\": \"./dist/sucrose.js\"\n\t\t},\n\t\t\"./trace\": {\n\t\t\t\"types\": \"./dist/trace.d.ts\",\n\t\t\t\"import\": \"./dist/trace.mjs\",\n\t\t\t\"require\": \"./dist/trace.js\"\n\t\t},\n\t\t\"./type-system\": {\n\t\t\t\"types\": \"./dist/type-system/index.d.ts\",\n\t\t\t\"import\": \"./dist/type-system/index.mjs\",\n\t\t\t\"require\": \"./dist/type-system/index.js\"\n\t\t},\n\t\t\"./type-system/format\": {\n\t\t\t\"types\": \"./dist/type-system/format.d.ts\",\n\t\t\t\"import\": \"./dist/type-system/format.mjs\",\n\t\t\t\"require\": \"./dist/type-system/format.js\"\n\t\t},\n\t\t\"./type-system/utils\": {\n\t\t\t\"types\": \"./dist/type-system/utils.d.ts\",\n\t\t\t\"import\": \"./dist/type-system/utils.mjs\",\n\t\t\t\"require\": \"./dist/type-system/utils.js\"\n\t\t},\n\t\t\"./type-system/types\": {\n\t\t\t\"types\": \"./dist/type-system/types.d.ts\",\n\t\t\t\"import\": \"./dist/type-system/types.mjs\",\n\t\t\t\"require\": \"./dist/type-system/types.js\"\n\t\t},\n\t\t\"./types\": {\n\t\t\t\"types\": \"./dist/types.d.ts\",\n\t\t\t\"import\": \"./dist/types.mjs\",\n\t\t\t\"require\": \"./dist/types.js\"\n\t\t},\n\t\t\"./utils\": {\n\t\t\t\"types\": \"./dist/utils.d.ts\",\n\t\t\t\"import\": \"./dist/utils.mjs\",\n\t\t\t\"require\": \"./dist/utils.js\"\n\t\t},\n\t\t\"./parse-query\": {\n\t\t\t\"types\": \"./dist/parse-query.d.ts\",\n\t\t\t\"import\": \"./dist/parse-query.mjs\",\n\t\t\t\"require\": \"./dist/parse-query.js\"\n\t\t},\n\t\t\"./adapter\": {\n\t\t\t\"types\": \"./dist/adapter/index.d.ts\",\n\t\t\t\"import\": \"./dist/adapter/index.mjs\",\n\t\t\t\"require\": \"./dist/adapter/index.js\"\n\t\t},\n\t\t\"./adapter/utils\": {\n\t\t\t\"types\": \"./dist/adapter/utils.d.ts\",\n\t\t\t\"import\": \"./dist/adapter/utils.mjs\",\n\t\t\t\"require\": \"./dist/adapter/utils.js\"\n\t\t},\n\t\t\"./adapter/bun\": {\n\t\t\t\"types\": \"./dist/adapter/bun/index.d.ts\",\n\t\t\t\"import\": \"./dist/adapter/bun/index.mjs\",\n\t\t\t\"require\": \"./dist/adapter/bun/index.js\"\n\t\t},\n\t\t\"./adapter/bun/handler\": {\n\t\t\t\"types\": \"./dist/adapter/bun/handler.d.ts\",\n\t\t\t\"import\": \"./dist/adapter/bun/handler.mjs\",\n\t\t\t\"require\": \"./dist/adapter/bun/handler.js\"\n\t\t},\n\t\t\"./adapter/bun/compose\": {\n\t\t\t\"types\": \"./dist/adapter/bun/compose.d.ts\",\n\t\t\t\"import\": \"./dist/adapter/bun/compose.mjs\",\n\t\t\t\"require\": \"./dist/adapter/bun/compose.js\"\n\t\t},\n\t\t\"./adapter/cloudflare-worker\": {\n\t\t\t\"types\": \"./dist/adapter/cloudflare-worker/index.d.ts\",\n\t\t\t\"import\": \"./dist/adapter/cloudflare-worker/index.mjs\",\n\t\t\t\"require\": \"./dist/adapter/cloudflare-worker/index.js\"\n\t\t},\n\t\t\"./adapter/web-standard\": {\n\t\t\t\"types\": \"./dist/adapter/web-standard/index.d.ts\",\n\t\t\t\"import\": \"./dist/adapter/web-standard/index.mjs\",\n\t\t\t\"require\": \"./dist/adapter/web-standard/index.js\"\n\t\t},\n\t\t\"./adapter/web-standard/handler\": {\n\t\t\t\"types\": \"./dist/adapter/web-standard/handler.d.ts\",\n\t\t\t\"import\": \"./dist/adapter/web-standard/handler.mjs\",\n\t\t\t\"require\": \"./dist/adapter/web-standard/handler.js\"\n\t\t},\n\t\t\"./universal\": {\n\t\t\t\"types\": \"./dist/universal/index.d.ts\",\n\t\t\t\"import\": \"./dist/universal/index.mjs\",\n\t\t\t\"require\": \"./dist/universal/index.js\"\n\t\t},\n\t\t\"./universal/server\": {\n\t\t\t\"types\": \"./dist/universal/server.d.ts\",\n\t\t\t\"import\": \"./dist/universal/server.mjs\",\n\t\t\t\"require\": \"./dist/universal/server.js\"\n\t\t},\n\t\t\"./universal/env\": {\n\t\t\t\"types\": \"./dist/universal/env.d.ts\",\n\t\t\t\"import\": \"./dist/universal/env.mjs\",\n\t\t\t\"require\": \"./dist/universal/env.js\"\n\t\t},\n\t\t\"./universal/file\": {\n\t\t\t\"types\": \"./dist/universal/file.d.ts\",\n\t\t\t\"import\": \"./dist/universal/file.mjs\",\n\t\t\t\"require\": \"./dist/universal/file.js\"\n\t\t}\n\t},\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"https://github.com/elysiajs/elysia\"\n\t},\n\t\"bugs\": \"https://github.com/elysiajs/elysia/issues\",\n\t\"homepage\": \"https://github.com/elysiajs/elysia\",\n\t\"keywords\": [\n\t\t\"bun\",\n\t\t\"http\",\n\t\t\"web\",\n\t\t\"server\"\n\t],\n\t\"license\": \"MIT\",\n\t\"scripts\": {\n\t\t\"test\": \"bun run test:functionality && bun run test:types && bun run test:node\",\n\t\t\"test:functionality\": \"bun test && bun run test:imports\",\n\t\t\"test:imports\": \"bun run test/type-system/import.ts\",\n\t\t\"test:types\": \"tsc --project tsconfig.test.json\",\n\t\t\"test:node\": \"npm install --prefix test/node/cjs && npm install --prefix test/node/esm/ && node test/node/cjs/index.js && node test/node/esm/index.js\",\n\t\t\"test:cf\": \"npm install --prefix test/cloudflare && cd test/cloudflare && bun run cf-typegen && bun run test\",\n\t\t\"dev\": \"bun run --watch example/a.ts\",\n\t\t\"build\": \"rm -rf dist && bun build.ts\",\n\t\t\"deadcode\": \"knip\",\n\t\t\"release\": \"bun run build && bun run test && bun publish\"\n\t},\n\t\"dependencies\": {\n\t\t\"cookie\": \"^1.1.1\",\n\t\t\"exact-mirror\": \"^0.2.7\",\n\t\t\"fast-decode-uri-component\": \"^1.0.1\",\n\t\t\"memoirist\": \"^0.4.0\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@elysiajs/openapi\": \"^1.4.1\",\n\t\t\"@types/bun\": \"^1.3.5\",\n\t\t\"@types/cookie\": \"1.0.0\",\n\t\t\"@types/fast-decode-uri-component\": \"^1.0.0\",\n\t\t\"@typescript-eslint/eslint-plugin\": \"^8.30.1\",\n\t\t\"@typescript-eslint/parser\": \"^8.30.1\",\n\t\t\"arktype\": \"^2.1.22\",\n\t\t\"esbuild-fix-imports-plugin\": \"^1.0.22\",\n\t\t\"eslint\": \"^9.24.0\",\n\t\t\"eslint-plugin-security\": \"^3.0.1\",\n\t\t\"eslint-plugin-sonarjs\": \"^3.0.2\",\n\t\t\"expect-type\": \"^1.2.1\",\n\t\t\"file-type\": \"^20.4.1\",\n\t\t\"knip\": \"^5.64.1\",\n\t\t\"prettier\": \"^3.5.3\",\n\t\t\"tsup\": \"^8.4.0\",\n\t\t\"typescript\": \"^5.8.3\",\n\t\t\"valibot\": \"^1.1.0\",\n\t\t\"zod\": \"^4.1.5\"\n\t},\n\t\"peerDependencies\": {\n\t\t\"@types/bun\": \">= 1.2.0\",\n\t\t\"@sinclair/typebox\": \">= 0.34.0 < 1\",\n\t\t\"exact-mirror\": \">= 0.0.9\",\n\t\t\"file-type\": \">= 20.0.0\",\n\t\t\"openapi-types\": \">= 12.0.0\",\n\t\t\"typescript\": \">= 5.0.0\"\n\t},\n\t\"overrides\": {\n\t\t\"esbuild\": \"0.25.4\"\n\t},\n\t\"peerDependenciesMeta\": {\n\t\t\"@types/bun\": {\n\t\t\t\"optional\": true\n\t\t},\n\t\t\"typescript\": {\n\t\t\t\"optional\": true\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/adapter/bun/compose.ts",
    "content": "import { mapEarlyResponse } from './handler'\nimport { sucrose, type Sucrose } from '../../sucrose'\nimport { createHoc, createOnRequestHandler, isAsync } from '../../compose'\n\nimport { randomId, ELYSIA_REQUEST_ID, redirect, isNotEmpty } from '../../utils'\nimport { status } from '../../error'\nimport { ELYSIA_TRACE } from '../../trace'\n\nimport type { AnyElysia } from '../..'\nimport type { InternalRoute, InputSchema } from '../../types'\n\nconst allocateIf = (value: string, condition: unknown) =>\n\tcondition ? value : ''\n\nconst createContext = (\n\tapp: AnyElysia,\n\troute: InternalRoute,\n\tinference: Sucrose.Inference,\n\tisInline = false\n) => {\n\tlet fnLiteral = ''\n\n\t// @ts-expect-error private\n\tconst defaultHeaders = app.setHeaders\n\n\tconst hasTrace = !!app.event.trace?.length\n\tif (hasTrace) fnLiteral += `const id=randomId()\\n`\n\n\tconst isDynamic = /[:*]/.test(route.path)\n\n\tconst standardHostname = app.config.handler?.standardHostname ?? true\n\n\tconst getQi =\n\t\t`const u=request.url,` +\n\t\t`s=u.indexOf('/',${standardHostname ? 11 : 7}),` +\n\t\t`qi=u.indexOf('?',s+1)\\n`\n\n\tconst needsQuery =\n\t\tinference.query ||\n\t\t!!route.hooks.query ||\n\t\t!!(route.hooks.standaloneValidator as InputSchema[])?.find(\n\t\t\t(x) => x.query\n\t\t) ||\n\t\tapp.event.request?.length\n\n\tif (needsQuery) fnLiteral += getQi\n\n\tconst getPath = !inference.path\n\t\t? ''\n\t\t: !isDynamic\n\t\t\t? `path:'${route.path}',`\n\t\t\t: `get path(){` +\n\t\t\t\t(needsQuery ? '' : getQi) +\n\t\t\t\t`if(qi===-1)return u.substring(s)\\n` +\n\t\t\t\t`return u.substring(s,qi)\\n` +\n\t\t\t\t`},`\n\n\tfnLiteral +=\n\t\tallocateIf(`const c=`, !isInline) +\n\t\t`{request,` +\n\t\t`store,` +\n\t\tallocateIf(`qi,`, needsQuery) +\n\t\tallocateIf(`params:request.params,`, isDynamic) +\n\t\tgetPath +\n\t\tallocateIf(\n\t\t\t`url:request.url,`,\n\t\t\thasTrace || inference.url || needsQuery\n\t\t) +\n\t\t`redirect,` +\n\t\t`status,` +\n\t\t`set:{headers:` +\n\t\t(isNotEmpty(defaultHeaders)\n\t\t\t? 'Object.assign({},app.setHeaders)'\n\t\t\t: 'Object.create(null)') +\n\t\t`,status:200}`\n\n\tif (inference.server) fnLiteral += `,get server(){return app.getServer()}`\n\n\tif (hasTrace) fnLiteral += ',[ELYSIA_REQUEST_ID]:id'\n\n\t{\n\t\tlet decoratorsLiteral = ''\n\t\t// @ts-expect-error private\n\t\tfor (const key of Object.keys(app.singleton.decorator))\n\t\t\tdecoratorsLiteral += `,'${key}':decorator['${key}']`\n\n\t\tfnLiteral += decoratorsLiteral\n\t}\n\n\tfnLiteral += `}\\n`\n\n\treturn fnLiteral\n}\n\nexport const createBunRouteHandler = (app: AnyElysia, route: InternalRoute) => {\n\tconst hasTrace = !!app.event.trace?.length\n\t// @ts-expect-error private property\n\tconst hasHoc = !!app.extender.higherOrderFunctions.length\n\n\tlet inference = sucrose(\n\t\troute.hooks,\n\t\t// @ts-expect-error\n\t\tapp.inference\n\t)\n\tinference = sucrose(\n\t\t{\n\t\t\thandler: route.handler\n\t\t},\n\t\tinference\n\t)\n\n\tlet fnLiteral =\n\t\t'const handler=data.handler,' +\n\t\t`app=data.app,` +\n\t\t'store=data.store,' +\n\t\t`decorator=data.decorator,` +\n\t\t'redirect=data.redirect,' +\n\t\t'route=data.route,' +\n\t\t'mapEarlyResponse=data.mapEarlyResponse,' +\n\t\tallocateIf('randomId=data.randomId,', hasTrace) +\n\t\tallocateIf(`ELYSIA_REQUEST_ID=data.ELYSIA_REQUEST_ID,`, hasTrace) +\n\t\tallocateIf(`ELYSIA_TRACE=data.ELYSIA_TRACE,`, hasTrace) +\n\t\tallocateIf(`trace=data.trace,`, hasTrace) +\n\t\tallocateIf(`hoc=data.hoc,`, hasHoc) +\n\t\t'status=data.status\\n'\n\n\tif (app.event.request?.length)\n\t\tfnLiteral += `const onRequest=app.event.request.map(x=>x.fn)\\n`\n\n\tfnLiteral += `${app.event.request?.find(isAsync) ? 'async' : ''} function map(request){`\n\n\tconst needsQuery =\n\t\tinference.query ||\n\t\t!!route.hooks.query ||\n\t\t!!(route.hooks.standaloneValidator as InputSchema[])?.find(\n\t\t\t(x) => x.query\n\t\t)\n\n\t// inference.query require declaring const 'qi'\n\tif (hasTrace || needsQuery || app.event.request?.length) {\n\t\tfnLiteral += createContext(app, route, inference)\n\t\tfnLiteral += createOnRequestHandler(app)\n\n\t\tfnLiteral += 'return handler(c)}'\n\t} else\n\t\tfnLiteral += `return handler(${createContext(app, route, inference, true)})}`\n\n\tfnLiteral += createHoc(app)\n\n\treturn Function(\n\t\t'data',\n\t\tfnLiteral\n\t)({\n\t\tapp,\n\t\thandler: route.compile?.() ?? route.composed,\n\t\tredirect,\n\t\tstatus,\n\t\t// @ts-expect-error private property\n\t\thoc: app.extender.higherOrderFunctions.map((x) => x.fn),\n\t\tstore: app.store,\n\t\tdecorator: app.decorator,\n\t\troute: route.path,\n\t\trandomId: hasTrace ? randomId : undefined,\n\t\tELYSIA_TRACE: hasTrace ? ELYSIA_TRACE : undefined,\n\t\tELYSIA_REQUEST_ID: hasTrace ? ELYSIA_REQUEST_ID : undefined,\n\t\ttrace: hasTrace ? app.event.trace?.map((x) => x?.fn ?? x) : undefined,\n\t\tmapEarlyResponse: mapEarlyResponse\n\t})\n}\n"
  },
  {
    "path": "src/adapter/bun/handler-native.ts",
    "content": "import { isHTMLBundle } from './index'\nimport type { Context } from '../../context'\nimport type { AnyLocalHook, MaybePromise } from '../../types'\n\nimport { mapResponse } from './handler'\n\nexport const createNativeStaticHandler = (\n\thandle: unknown,\n\thooks: AnyLocalHook,\n\tset?: Context['set']\n): (() => MaybePromise<Response>) | undefined => {\n\tif (typeof handle === 'function' || handle instanceof Blob) return\n\n\tif (isHTMLBundle(handle)) return () => handle as any\n\n\tconst response = mapResponse(\n\t\thandle instanceof Response\n\t\t\t? handle.clone()\n\t\t\t: handle instanceof Promise\n\t\t\t\t? handle.then((x) =>\n\t\t\t\t\t\tx instanceof Response\n\t\t\t\t\t\t\t? x.clone()\n\t\t\t\t\t\t\t: isHTMLBundle(x)\n\t\t\t\t\t\t\t\t? () => x\n\t\t\t\t\t\t\t\t: x\n\t\t\t\t\t)\n\t\t\t\t: handle,\n\t\tset ?? {\n\t\t\theaders: {}\n\t\t}\n\t)\n\n\tif (\n\t\t!hooks.parse?.length &&\n\t\t!hooks.transform?.length &&\n\t\t!hooks.beforeHandle?.length &&\n\t\t!hooks.afterHandle?.length\n\t) {\n\t\tif (response instanceof Promise)\n\t\t\treturn response.then((response) => {\n\t\t\t\tif (!response) return\n\n\t\t\t\treturn response.clone()\n\t\t\t}) as any as () => Promise<Response>\n\n\t\treturn () => response.clone() as Response\n\t}\n}\n"
  },
  {
    "path": "src/adapter/bun/handler.ts",
    "content": "// Similar to adapter/web-standard/handler but\n// string case is omitted header out\n// (this has a significant performance difference on Bun)\n\n/* eslint-disable sonarjs/no-nested-switch */\n/* eslint-disable sonarjs/no-duplicate-string */\nimport {\n\tcreateResponseHandler,\n\tcreateStreamHandler,\n\thandleFile,\n\thandleSet\n} from '../utils'\n\nimport { ElysiaFile } from '../../universal/file'\nimport { isNotEmpty } from '../../utils'\nimport { Cookie } from '../../cookies'\nimport { ElysiaCustomStatusResponse } from '../../error'\n\nimport type { Context } from '../../context'\nimport type { AnyLocalHook } from '../../types'\n\n// Response.json is faster than new Response(JSON.stringify()) in Bun\n// https://x.com/jarredsumner/status/2023328556210921948\nexport const mapResponse = (\n\tresponse: unknown,\n\tset: Context['set'],\n\trequest?: Request\n): Response => {\n\tif (isNotEmpty(set.headers) || set.status !== 200 || set.cookie) {\n\t\thandleSet(set)\n\n\t\tswitch (response?.constructor?.name) {\n\t\t\tcase 'String':\n\t\t\t\treturn new Response(response as string, set as any)\n\n\t\t\tcase 'Array':\n\t\t\tcase 'Object':\n\t\t\t\treturn Response.json(response, set as any)\n\n\t\t\tcase 'ElysiaFile':\n\t\t\t\treturn handleFile((response as ElysiaFile).value as File, set, request)\n\n\t\t\tcase 'File':\n\t\t\t\treturn handleFile(response as File, set, request)\n\n\t\t\tcase 'Blob':\n\t\t\t\treturn handleFile(response as Blob, set, request)\n\n\t\t\tcase 'ElysiaCustomStatusResponse':\n\t\t\t\tset.status = (response as ElysiaCustomStatusResponse<200>).code\n\n\t\t\t\treturn mapResponse(\n\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\tset,\n\t\t\t\t\trequest\n\t\t\t\t)\n\n\t\t\tcase undefined:\n\t\t\t\tif (!response) return new Response('', set as any)\n\n\t\t\t\treturn Response.json(response, set as any)\n\n\t\t\tcase 'Response':\n\t\t\t\treturn handleResponse(response as Response, set, request)\n\n\t\t\tcase 'Error':\n\t\t\t\treturn errorToResponse(response as Error, set)\n\n\t\t\tcase 'Promise':\n\t\t\t\treturn (response as Promise<any>).then((x) =>\n\t\t\t\t\tmapResponse(x, set, request)\n\t\t\t\t) as any\n\n\t\t\tcase 'Function':\n\t\t\t\treturn mapResponse((response as Function)(), set, request)\n\n\t\t\tcase 'Number':\n\t\t\tcase 'Boolean':\n\t\t\t\treturn new Response(\n\t\t\t\t\t(response as number | boolean).toString(),\n\t\t\t\t\tset as any\n\t\t\t\t)\n\n\t\t\tcase 'Cookie':\n\t\t\t\tif (response instanceof Cookie)\n\t\t\t\t\treturn new Response(response.value, set as any)\n\n\t\t\t\treturn new Response(response?.toString(), set as any)\n\n\t\t\tcase 'FormData':\n\t\t\t\treturn new Response(response as FormData, set as any)\n\n\t\t\tdefault:\n\t\t\t\t// recheck Response, Promise, Error because some library may extends Response\n\t\t\t\tif (response instanceof Response)\n\t\t\t\t\treturn handleResponse(response as Response, set, request)\n\n\t\t\t\tif (response instanceof Promise)\n\t\t\t\t\treturn response.then((x) => mapResponse(x, set)) as any\n\n\t\t\t\tif (response instanceof Error)\n\t\t\t\t\treturn errorToResponse(response as Error, set)\n\n\t\t\t\tif (response instanceof ElysiaCustomStatusResponse) {\n\t\t\t\t\tset.status = (\n\t\t\t\t\t\tresponse as ElysiaCustomStatusResponse<200>\n\t\t\t\t\t).code\n\n\t\t\t\t\treturn mapResponse(\n\t\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\t\tset,\n\t\t\t\t\t\trequest\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\ttypeof response?.next === 'function' ||\n\t\t\t\t\tresponse instanceof ReadableStream\n\t\t\t\t)\n\t\t\t\t\treturn handleStream(response as any, set, request) as any\n\n\t\t\t\tif (typeof (response as Promise<unknown>)?.then === 'function')\n\t\t\t\t\treturn (response as Promise<unknown>).then((x) =>\n\t\t\t\t\t\tmapResponse(x, set)\n\t\t\t\t\t) as any\n\n\t\t\t\t// custom class with an array-like value\n\t\t\t\t// eg. Bun.sql`` result\n\t\t\t\tif (Array.isArray(response))\n\t\t\t\t\treturn Response.json(response) as any\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\tif (typeof response?.toResponse === 'function')\n\t\t\t\t\treturn mapResponse((response as any).toResponse(), set)\n\n\t\t\t\tif ('charCodeAt' in (response as any)) {\n\t\t\t\t\tconst code = (response as any).charCodeAt(0)\n\n\t\t\t\t\tif (code === 123 || code === 91)\n\t\t\t\t\t\treturn Response.json(response, set as any) as any\n\t\t\t\t}\n\n\t\t\t\treturn new Response(response as any, set as any)\n\t\t}\n\t}\n\n\t// Stream response defers a 'set' API, assume that it may include 'set'\n\tif (\n\t\t// @ts-expect-error\n\t\ttypeof response?.next === 'function' ||\n\t\tresponse instanceof ReadableStream\n\t)\n\t\treturn handleStream(response as any, set, request) as any\n\n\treturn mapCompactResponse(response, request)\n}\n\nexport const mapEarlyResponse = (\n\tresponse: unknown,\n\tset: Context['set'],\n\trequest?: Request\n): Response | undefined => {\n\tif (response === undefined || response === null) return\n\n\tif (isNotEmpty(set.headers) || set.status !== 200 || set.cookie) {\n\t\thandleSet(set)\n\n\t\tswitch (response?.constructor?.name) {\n\t\t\tcase 'String':\n\t\t\t\treturn new Response(response as string, set as any)\n\n\t\t\tcase 'Array':\n\t\t\tcase 'Object':\n\t\t\t\treturn Response.json(response, set as any)\n\n\t\t\tcase 'ElysiaFile':\n\t\t\t\treturn handleFile((response as ElysiaFile).value as File, set, request)\n\n\t\t\tcase 'File':\n\t\t\t\treturn handleFile(response as File, set, request)\n\n\t\t\tcase 'Blob':\n\t\t\t\treturn handleFile(response as File | Blob, set, request)\n\n\t\t\tcase 'ElysiaCustomStatusResponse':\n\t\t\t\tset.status = (response as ElysiaCustomStatusResponse<200>).code\n\n\t\t\t\treturn mapEarlyResponse(\n\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\tset,\n\t\t\t\t\trequest\n\t\t\t\t)\n\n\t\t\tcase undefined:\n\t\t\t\tif (!response) return\n\n\t\t\t\treturn Response.json(response, set as any)\n\n\t\t\tcase 'Response':\n\t\t\t\treturn handleResponse(response as Response, set, request)\n\n\t\t\tcase 'Promise':\n\t\t\t\treturn (response as Promise<unknown>).then((x) =>\n\t\t\t\t\tmapEarlyResponse(x, set)\n\t\t\t\t) as any\n\n\t\t\tcase 'Error':\n\t\t\t\treturn errorToResponse(response as Error, set)\n\n\t\t\tcase 'Function':\n\t\t\t\treturn mapEarlyResponse((response as Function)(), set)\n\n\t\t\tcase 'Number':\n\t\t\tcase 'Boolean':\n\t\t\t\treturn new Response(\n\t\t\t\t\t(response as number | boolean).toString(),\n\t\t\t\t\tset as any\n\t\t\t\t)\n\n\t\t\tcase 'FormData':\n\t\t\t\treturn new Response(response as FormData)\n\n\t\t\tcase 'Cookie':\n\t\t\t\tif (response instanceof Cookie)\n\t\t\t\t\treturn new Response(response.value, set as any)\n\n\t\t\t\treturn new Response(response?.toString(), set as any)\n\n\t\t\tdefault:\n\t\t\t\tif (response instanceof Response)\n\t\t\t\t\treturn handleResponse(response, set, request)\n\n\t\t\t\tif (response instanceof Promise)\n\t\t\t\t\treturn response.then((x) => mapEarlyResponse(x, set)) as any\n\n\t\t\t\tif (response instanceof Error)\n\t\t\t\t\treturn errorToResponse(response as Error, set)\n\n\t\t\t\tif (response instanceof ElysiaCustomStatusResponse) {\n\t\t\t\t\tset.status = (\n\t\t\t\t\t\tresponse as ElysiaCustomStatusResponse<200>\n\t\t\t\t\t).code\n\n\t\t\t\t\treturn mapEarlyResponse(\n\t\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\t\tset,\n\t\t\t\t\t\trequest\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\ttypeof response?.next === 'function' ||\n\t\t\t\t\tresponse instanceof ReadableStream\n\t\t\t\t)\n\t\t\t\t\treturn handleStream(response as any, set, request) as any\n\n\t\t\t\tif (typeof (response as Promise<unknown>)?.then === 'function')\n\t\t\t\t\treturn (response as Promise<unknown>).then((x) =>\n\t\t\t\t\t\tmapEarlyResponse(x, set)\n\t\t\t\t\t) as any\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\tif (typeof response?.toResponse === 'function')\n\t\t\t\t\treturn mapEarlyResponse((response as any).toResponse(), set)\n\n\t\t\t\t// custom class with an array-like value\n\t\t\t\t// eg. Bun.sql`` result\n\t\t\t\tif (Array.isArray(response))\n\t\t\t\t\treturn Response.json(response) as any\n\n\t\t\t\tif ('charCodeAt' in (response as any)) {\n\t\t\t\t\tconst code = (response as any).charCodeAt(0)\n\n\t\t\t\t\tif (code === 123 || code === 91)\n\t\t\t\t\t\treturn Response.json(response, set as any) as any\n\t\t\t\t}\n\n\t\t\t\treturn new Response(response as any, set as any)\n\t\t}\n\t} else\n\t\tswitch (response?.constructor?.name) {\n\t\t\tcase 'String':\n\t\t\t\treturn new Response(response as string)\n\n\t\t\tcase 'Array':\n\t\t\tcase 'Object':\n\t\t\t\treturn Response.json(response, set as any)\n\n\t\t\tcase 'ElysiaFile':\n\t\t\t\treturn handleFile((response as ElysiaFile).value as File, set, request)\n\n\t\t\tcase 'File':\n\t\t\t\treturn handleFile(response as File, set, request)\n\n\t\t\tcase 'Blob':\n\t\t\t\treturn handleFile(response as File | Blob, set, request)\n\n\t\t\tcase 'ElysiaCustomStatusResponse':\n\t\t\t\tset.status = (response as ElysiaCustomStatusResponse<200>).code\n\n\t\t\t\treturn mapEarlyResponse(\n\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\tset,\n\t\t\t\t\trequest\n\t\t\t\t)\n\n\t\t\tcase undefined:\n\t\t\t\tif (!response) return new Response('')\n\n\t\t\t\treturn Response.json(response)\n\n\t\t\tcase 'Response':\n\t\t\t\treturn response as Response\n\n\t\t\tcase 'Promise':\n\t\t\t\treturn (response as Promise<unknown>).then((x) => {\n\t\t\t\t\tconst r = mapEarlyResponse(x, set)\n\t\t\t\t\tif (r !== undefined) return r\n\t\t\t\t}) as any\n\n\t\t\tcase 'Error':\n\t\t\t\treturn errorToResponse(response as Error, set)\n\n\t\t\tcase 'Function':\n\t\t\t\treturn mapCompactResponse((response as Function)(), request)\n\n\t\t\tcase 'Number':\n\t\t\tcase 'Boolean':\n\t\t\t\treturn new Response((response as number | boolean).toString())\n\n\t\t\tcase 'Cookie':\n\t\t\t\tif (response instanceof Cookie)\n\t\t\t\t\treturn new Response(response.value, set as any)\n\n\t\t\t\treturn new Response(response?.toString(), set as any)\n\n\t\t\tcase 'FormData':\n\t\t\t\treturn new Response(response as FormData)\n\n\t\t\tdefault:\n\t\t\t\tif (response instanceof Response) return response\n\n\t\t\t\tif (response instanceof Promise)\n\t\t\t\t\treturn response.then((x) => mapEarlyResponse(x, set)) as any\n\n\t\t\t\tif (response instanceof Error)\n\t\t\t\t\treturn errorToResponse(response as Error, set)\n\n\t\t\t\tif (response instanceof ElysiaCustomStatusResponse) {\n\t\t\t\t\tset.status = (\n\t\t\t\t\t\tresponse as ElysiaCustomStatusResponse<200>\n\t\t\t\t\t).code\n\n\t\t\t\t\treturn mapEarlyResponse(\n\t\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\t\tset,\n\t\t\t\t\t\trequest\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\ttypeof response?.next === 'function' ||\n\t\t\t\t\tresponse instanceof ReadableStream\n\t\t\t\t)\n\t\t\t\t\treturn handleStream(response as any, set, request) as any\n\n\t\t\t\tif (typeof (response as Promise<unknown>)?.then === 'function')\n\t\t\t\t\treturn (response as Promise<unknown>).then((x) =>\n\t\t\t\t\t\tmapEarlyResponse(x, set)\n\t\t\t\t\t) as any\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\tif (typeof response?.toResponse === 'function')\n\t\t\t\t\treturn mapEarlyResponse((response as any).toResponse(), set)\n\n\t\t\t\t// custom class with an array-like value\n\t\t\t\t// eg. Bun.sql`` result\n\t\t\t\tif (Array.isArray(response))\n\t\t\t\t\treturn Response.json(response) as any\n\n\t\t\t\tif ('charCodeAt' in (response as any)) {\n\t\t\t\t\tconst code = (response as any).charCodeAt(0)\n\n\t\t\t\t\tif (code === 123 || code === 91)\n\t\t\t\t\t\treturn Response.json(response, set as any) as any\n\t\t\t\t}\n\n\t\t\t\treturn new Response(response as any)\n\t\t}\n}\n\nexport const mapCompactResponse = (\n\tresponse: unknown,\n\trequest?: Request\n): Response => {\n\tswitch (response?.constructor?.name) {\n\t\tcase 'String':\n\t\t\treturn new Response(response as string)\n\n\t\tcase 'Object':\n\t\tcase 'Array':\n\t\t\treturn Response.json(response)\n\n\t\tcase 'ElysiaFile':\n\t\t\treturn handleFile((response as ElysiaFile).value as File, undefined, request)\n\n\t\tcase 'File':\n\t\t\treturn handleFile(response as File, undefined, request)\n\n\t\tcase 'Blob':\n\t\t\treturn handleFile(response as File | Blob, undefined, request)\n\n\t\tcase 'ElysiaCustomStatusResponse':\n\t\t\treturn mapResponse(\n\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t{\n\t\t\t\t\tstatus: (response as ElysiaCustomStatusResponse<200>).code,\n\t\t\t\t\theaders: {}\n\t\t\t\t}\n\t\t\t)\n\n\t\tcase undefined:\n\t\t\tif (!response) return new Response('')\n\n\t\t\treturn Response.json(response)\n\n\t\tcase 'Response':\n\t\t\treturn response as Response\n\n\t\tcase 'Error':\n\t\t\treturn errorToResponse(response as Error)\n\n\t\tcase 'Promise':\n\t\t\treturn (response as Promise<unknown>).then((x) =>\n\t\t\t\tmapCompactResponse(x, request)\n\t\t\t) as any\n\n\t\t// ? Maybe response or Blob\n\t\tcase 'Function':\n\t\t\treturn mapCompactResponse((response as Function)(), request)\n\n\t\tcase 'Number':\n\t\tcase 'Boolean':\n\t\t\treturn new Response((response as number | boolean).toString())\n\n\t\tcase 'FormData':\n\t\t\treturn new Response(response as FormData)\n\n\t\tdefault:\n\t\t\tif (response instanceof Response) return response\n\n\t\t\tif (response instanceof Promise)\n\t\t\t\treturn response.then((x) =>\n\t\t\t\t\tmapCompactResponse(x, request)\n\t\t\t\t) as any\n\n\t\t\tif (response instanceof Error)\n\t\t\t\treturn errorToResponse(response as Error)\n\n\t\t\tif (response instanceof ElysiaCustomStatusResponse)\n\t\t\t\treturn mapResponse(\n\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\t{\n\t\t\t\t\t\tstatus: (response as ElysiaCustomStatusResponse<200>)\n\t\t\t\t\t\t\t.code,\n\t\t\t\t\t\theaders: {}\n\t\t\t\t\t}\n\t\t\t\t)\n\n\t\t\tif (\n\t\t\t\t// @ts-expect-error\n\t\t\t\ttypeof response?.next === 'function' ||\n\t\t\t\tresponse instanceof ReadableStream\n\t\t\t)\n\t\t\t\treturn handleStream(response as any, undefined, request) as any\n\n\t\t\tif (typeof (response as Promise<unknown>)?.then === 'function')\n\t\t\t\treturn (response as Promise<unknown>).then((x) =>\n\t\t\t\t\tmapCompactResponse(x, request)\n\t\t\t\t) as any\n\n\t\t\t// @ts-expect-errors\n\t\t\tif (typeof response?.toResponse === 'function')\n\t\t\t\treturn mapCompactResponse((response as any).toResponse())\n\n\t\t\t// custom class with an array-like value\n\t\t\t// eg. Bun.sql`` result\n\t\t\tif (Array.isArray(response)) return Response.json(response) as any\n\n\t\t\tif ('charCodeAt' in (response as any)) {\n\t\t\t\tconst code = (response as any).charCodeAt(0)\n\n\t\t\t\tif (code === 123 || code === 91)\n\t\t\t\t\treturn Response.json(response) as any\n\t\t\t}\n\n\t\t\treturn new Response(response as any)\n\t}\n}\n\nexport const errorToResponse = (error: Error, set?: Context['set']) => {\n\t// @ts-expect-error\n\tif (typeof error?.toResponse === 'function') {\n\t\t// @ts-expect-error\n\t\tconst raw = error.toResponse()\n\t\tconst targetSet =\n\t\t\tset ??\n\t\t\t({ headers: {}, status: 200, redirect: '' } as Context['set'])\n\t\tconst apply = (resolved: unknown) => {\n\t\t\tif (resolved instanceof Response) targetSet.status = resolved.status\n\t\t\treturn mapResponse(resolved, targetSet)\n\t\t}\n\n\t\treturn typeof raw?.then === 'function' ? raw.then(apply) : apply(raw)\n\t}\n\n\treturn Response.json(\n\t\t{\n\t\t\tname: error?.name,\n\t\t\tmessage: error?.message,\n\t\t\tcause: error?.cause\n\t\t},\n\t\t{\n\t\t\tstatus:\n\t\t\t\tset?.status !== 200 ? ((set?.status as number) ?? 500) : 500,\n\t\t\theaders: set?.headers as any\n\t\t}\n\t)\n}\n\nexport const createStaticHandler = (\n\thandle: unknown,\n\thooks: Partial<AnyLocalHook>,\n\tsetHeaders: Context['set']['headers'] = {}\n): (() => Response) | undefined => {\n\tif (typeof handle === 'function') return\n\n\tconst response = mapResponse(handle, {\n\t\theaders: setHeaders\n\t})\n\n\tif (\n\t\t!hooks.parse?.length &&\n\t\t!hooks.transform?.length &&\n\t\t!hooks.beforeHandle?.length &&\n\t\t!hooks.afterHandle?.length\n\t)\n\t\treturn () => response.clone() as Response\n}\n\nconst handleResponse = createResponseHandler({\n\tmapResponse,\n\tmapCompactResponse\n})\n\nconst handleStream = createStreamHandler({\n\tmapResponse,\n\tmapCompactResponse\n})\n"
  },
  {
    "path": "src/adapter/bun/index.ts",
    "content": "/* eslint-disable sonarjs/no-duplicate-string */\nimport type { TSchema } from '@sinclair/typebox'\n\nimport { WebStandardAdapter } from '../web-standard/index'\nimport { parseSetCookies } from '../utils'\nimport type { ElysiaAdapter } from '../types'\nimport type { Serve } from '../../universal/server'\n\nimport { createBunRouteHandler } from './compose'\nimport { createNativeStaticHandler } from './handler-native'\n\nimport { serializeCookie } from '../../cookies'\nimport { isProduction, status, ValidationError } from '../../error'\nimport { getSchemaValidator } from '../../schema'\nimport {\n\thasHeaderShorthand,\n\tisNotEmpty,\n\tisNumericString,\n\trandomId,\n\tsupportPerMethodInlineHandler\n} from '../../utils'\n\nimport {\n\tmapResponse,\n\tmapEarlyResponse,\n\tmapCompactResponse,\n\tcreateStaticHandler\n} from './handler'\n\nimport {\n\tcreateHandleWSResponse,\n\tcreateWSMessageParser,\n\tElysiaWS,\n\twebsocket\n} from '../../ws/index'\nimport type { ServerWebSocket } from '../../ws/bun'\nimport type { AnyElysia } from '../..'\n\nconst optionalParam = /:.+?\\?(?=\\/|$)/\n\nconst getPossibleParams = (path: string) => {\n\tconst match = optionalParam.exec(path)\n\n\tif (!match) return [path]\n\n\tconst routes: string[] = []\n\n\tconst head = path.slice(0, match.index)\n\tconst param = match[0].slice(0, -1)\n\tconst tail = path.slice(match.index + match[0].length)\n\n\troutes.push(head.slice(0, -1))\n\troutes.push(head + param)\n\n\tfor (const fragment of getPossibleParams(tail)) {\n\t\tif (!fragment) continue\n\n\t\tif (!fragment.startsWith('/:'))\n\t\t\troutes.push(head.slice(0, -1) + fragment)\n\n\t\troutes.push(head + param + fragment)\n\t}\n\n\treturn routes\n}\n\nexport const isHTMLBundle = (handle: any) =>\n\ttypeof handle === 'object' &&\n\thandle !== null &&\n\t(handle.toString() === '[object HTMLBundle]' ||\n\t\ttypeof handle.index === 'string')\n\nconst supportedMethods = {\n\tGET: true,\n\tHEAD: true,\n\tOPTIONS: true,\n\tDELETE: true,\n\tPATCH: true,\n\tPOST: true,\n\tPUT: true\n} as const\n\nconst mapRoutes = (app: AnyElysia) => {\n\tif (!app.config.aot || app.config.systemRouter === false) return undefined\n\n\tconst routes = <Record<string, Function | Record<string, unknown>>>{}\n\n\tconst add = (\n\t\troute: {\n\t\t\tpath: string\n\t\t\tmethod: string\n\t\t},\n\t\thandler: Function\n\t) => {\n\t\tconst path = encodeURI(route.path)\n\n\t\tif (routes[path]) {\n\t\t\t// @ts-ignore\n\t\t\tif (!routes[path][route.method])\n\t\t\t\t// @ts-ignore\n\t\t\t\troutes[path][route.method] = handler\n\t\t} else\n\t\t\troutes[path] = {\n\t\t\t\t[route.method]: handler\n\t\t\t}\n\t}\n\n\t// @ts-expect-error\n\tconst tree = app.routeTree\n\n\tfor (const route of app.router.history) {\n\t\tif (typeof route.handler !== 'function') continue\n\n\t\tconst method = route.method\n\n\t\tif (\n\t\t\t(method === 'GET' && `WS_${route.path}` in tree) ||\n\t\t\tmethod === 'WS' ||\n\t\t\troute.path.charCodeAt(route.path.length - 1) === 42 ||\n\t\t\t!(method in supportedMethods)\n\t\t)\n\t\t\tcontinue\n\n\t\tif (method === 'ALL') {\n\t\t\tif (!(`WS_${route.path}` in tree))\n\t\t\t\troutes[route.path] = route.hooks?.config?.mount\n\t\t\t\t\t? route.hooks.trace ||\n\t\t\t\t\t\tapp.event.trace ||\n\t\t\t\t\t\t// @ts-expect-error private property\n\t\t\t\t\t\tapp.extender.higherOrderFunctions\n\t\t\t\t\t\t? createBunRouteHandler(app, route)\n\t\t\t\t\t\t: route.hooks.mount || route.handler\n\t\t\t\t\t: route.handler\n\n\t\t\tcontinue\n\t\t}\n\n\t\tlet compiled: Function\n\n\t\tconst handler = app.config.precompile\n\t\t\t? createBunRouteHandler(app, route)\n\t\t\t: (request: Request) => {\n\t\t\t\t\tif (compiled) return compiled(request)\n\n\t\t\t\t\treturn (compiled = createBunRouteHandler(app, route))(\n\t\t\t\t\t\trequest\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\tfor (const path of getPossibleParams(route.path))\n\t\t\tadd(\n\t\t\t\t{\n\t\t\t\t\tmethod,\n\t\t\t\t\tpath\n\t\t\t\t},\n\t\t\t\thandler\n\t\t\t)\n\t}\n\n\treturn routes\n}\n\ntype Routes = Record<string, Function | Response | Record<string, unknown>>\n\nconst mergeRoutes = (r1: Routes, r2?: Routes) => {\n\tif (!r2) return r1\n\n\tfor (const key of Object.keys(r2)) {\n\t\tif (r1[key] === r2[key]) continue\n\n\t\tif (!r1[key]) {\n\t\t\tr1[key] = r2[key]\n\t\t\tcontinue\n\t\t}\n\n\t\tif (r1[key] && r2[key]) {\n\t\t\tif (typeof r1[key] === 'function' || r1[key] instanceof Response) {\n\t\t\t\tr1[key] = r2[key]\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tr1[key] = {\n\t\t\t\t...r1[key],\n\t\t\t\t...r2[key]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn r1\n}\n\n// // https://github.com/elysiajs/elysia/issues/1752\n// inconsistent behavior between trailing slash and non-trailing slash\nexport const removeTrailingPath = (routes: Routes) => {\n\tfor (const key of Object.keys(routes))\n\t\tif (key.length > 1 && key.charCodeAt(key.length - 1) === 47) {\n\t\t\troutes[key.slice(0, -1)] = routes[key]\n\t\t\tdelete routes[key]\n\t\t}\n\n\treturn routes\n}\n\nexport const BunAdapter: ElysiaAdapter = {\n\t...WebStandardAdapter,\n\tname: 'bun',\n\thandler: {\n\t\tmapResponse,\n\t\tmapEarlyResponse,\n\t\tmapCompactResponse,\n\t\tcreateStaticHandler,\n\t\tcreateNativeStaticHandler\n\t},\n\tcomposeHandler: {\n\t\t...WebStandardAdapter.composeHandler,\n\t\theaders: hasHeaderShorthand\n\t\t\t? 'c.headers=c.request.headers.toJSON()\\n'\n\t\t\t: 'c.headers={}\\n' +\n\t\t\t\t'for(const [k,v] of c.request.headers.entries())' +\n\t\t\t\t'c.headers[k]=v\\n'\n\t},\n\tlisten(app) {\n\t\treturn (options, callback) => {\n\t\t\tif (typeof Bun === 'undefined')\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'.listen() is designed to run on Bun only. If you are running Elysia in other environment please use a dedicated plugin or export the handler via Elysia.fetch'\n\t\t\t\t)\n\n\t\t\tapp.compile()\n\n\t\t\tif (typeof options === 'string') {\n\t\t\t\tif (!isNumericString(options))\n\t\t\t\t\tthrow new Error('Port must be a numeric value')\n\n\t\t\t\toptions = parseInt(options)\n\t\t\t}\n\n\t\t\tconst createStaticRoute = <\n\t\t\t\tWithAsync extends boolean | undefined = false\n\t\t\t>(\n\t\t\t\titerator: AnyElysia['router']['response'],\n\t\t\t\t{ withAsync = false }: { withAsync?: WithAsync } = {}\n\t\t\t): true extends WithAsync\n\t\t\t\t? Promise<{\n\t\t\t\t\t\t[path: string]:\n\t\t\t\t\t\t\t| Response\n\t\t\t\t\t\t\t| { [method: string]: Response }\n\t\t\t\t\t}>\n\t\t\t\t: {\n\t\t\t\t\t\t[path: string]:\n\t\t\t\t\t\t\t| Response\n\t\t\t\t\t\t\t| { [method: string]: Response }\n\t\t\t\t\t} => {\n\t\t\t\tconst staticRoutes = <\n\t\t\t\t\t{\n\t\t\t\t\t\t[path: string]:\n\t\t\t\t\t\t\t| Response\n\t\t\t\t\t\t\t| { [method: string]: Response }\n\t\t\t\t\t}\n\t\t\t\t>{}\n\t\t\t\tconst ops = <Promise<any>[]>[]\n\n\t\t\t\tfor (let [path, route] of Object.entries(iterator)) {\n\t\t\t\t\tpath = encodeURI(path)\n\n\t\t\t\t\tif (supportPerMethodInlineHandler) {\n\t\t\t\t\t\tif (!route) continue\n\n\t\t\t\t\t\tfor (const [method, value] of Object.entries(route)) {\n\t\t\t\t\t\t\tif (!value || !(method in supportedMethods))\n\t\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t\t\tif (value instanceof Promise) {\n\t\t\t\t\t\t\t\tif (withAsync) {\n\t\t\t\t\t\t\t\t\tif (!staticRoutes[path])\n\t\t\t\t\t\t\t\t\t\tstaticRoutes[path] = {}\n\n\t\t\t\t\t\t\t\t\tops.push(\n\t\t\t\t\t\t\t\t\t\tvalue.then((awaited) => {\n\t\t\t\t\t\t\t\t\t\t\tif (awaited instanceof Response)\n\t\t\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\t\t\tstaticRoutes[path][method] =\n\t\t\t\t\t\t\t\t\t\t\t\t\tawaited\n\n\t\t\t\t\t\t\t\t\t\t\tif (isHTMLBundle(awaited))\n\t\t\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\t\t\tstaticRoutes[path][method] =\n\t\t\t\t\t\t\t\t\t\t\t\t\tawaited\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!(value instanceof Response) &&\n\t\t\t\t\t\t\t\t!isHTMLBundle(value)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t\t\tif (!staticRoutes[path]) staticRoutes[path] = {}\n\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\tstaticRoutes[path][method] = value\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (!route) continue\n\n\t\t\t\t\t\tif (route instanceof Promise) {\n\t\t\t\t\t\t\tif (withAsync) {\n\t\t\t\t\t\t\t\tif (!staticRoutes[path]) staticRoutes[path] = {}\n\n\t\t\t\t\t\t\t\tops.push(\n\t\t\t\t\t\t\t\t\troute.then((awaited) => {\n\t\t\t\t\t\t\t\t\t\tif (awaited instanceof Response)\n\t\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\t\tstaticRoutes[path] = awaited\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!(route instanceof Response)) continue\n\n\t\t\t\t\t\tstaticRoutes[path] = route\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (withAsync)\n\t\t\t\t\treturn Promise.all(ops).then(() => staticRoutes) as any\n\n\t\t\t\treturn staticRoutes as any\n\t\t\t}\n\n\t\t\tconst routes = removeTrailingPath(\n\t\t\t\tmergeRoutes(\n\t\t\t\t\tmergeRoutes(\n\t\t\t\t\t\tcreateStaticRoute(app.router.response),\n\t\t\t\t\t\tmapRoutes(app)\n\t\t\t\t\t),\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tapp.config.serve?.routes\n\t\t\t\t)\n\t\t\t)\n\n\t\t\tconst serve =\n\t\t\t\ttypeof options === 'object'\n\t\t\t\t\t? ({\n\t\t\t\t\t\t\tdevelopment: !isProduction,\n\t\t\t\t\t\t\treusePort: true,\n\t\t\t\t\t\t\tidleTimeout: 30,\n\t\t\t\t\t\t\t...(app.config.serve || {}),\n\t\t\t\t\t\t\t...(options || {}),\n\t\t\t\t\t\t\troutes,\n\t\t\t\t\t\t\twebsocket: {\n\t\t\t\t\t\t\t\t...(app.config.websocket || {}),\n\t\t\t\t\t\t\t\t...(websocket || {}),\n\t\t\t\t\t\t\t\t...(options.websocket || {})\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tfetch: app.fetch\n\t\t\t\t\t\t} as Serve)\n\t\t\t\t\t: ({\n\t\t\t\t\t\t\tdevelopment: !isProduction,\n\t\t\t\t\t\t\treusePort: true,\n\t\t\t\t\t\t\tidleTimeout: 30,\n\t\t\t\t\t\t\t...(app.config.serve || {}),\n\t\t\t\t\t\t\troutes,\n\t\t\t\t\t\t\twebsocket: {\n\t\t\t\t\t\t\t\t...(app.config.websocket || {}),\n\t\t\t\t\t\t\t\t...(websocket || {})\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tport: options,\n\t\t\t\t\t\t\tfetch: app.fetch\n\t\t\t\t\t\t} as Serve)\n\n\t\t\tapp.server = Bun.serve(serve as any) as any\n\n\t\t\tif (app.event.start)\n\t\t\t\tfor (let i = 0; i < app.event.start.length; i++)\n\t\t\t\t\tapp.event.start[i].fn(app)\n\n\t\t\tif (callback) callback(app.server!)\n\n\t\t\tprocess.on('beforeExit', async () => {\n\t\t\t\tif (app.server) {\n\t\t\t\t\tawait app.server.stop?.()\n\t\t\t\t\tapp.server = null\n\n\t\t\t\t\tif (app.event.stop)\n\t\t\t\t\t\tfor (let i = 0; i < app.event.stop.length; i++)\n\t\t\t\t\t\t\tapp.event.stop[i].fn(app)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\t// @ts-expect-error private\n\t\t\tapp.promisedModules.then(async () => {\n\t\t\t\tif (typeof app.config.aot) app.compile()\n\n\t\t\t\tconst routes = removeTrailingPath(\n\t\t\t\t\tmergeRoutes(\n\t\t\t\t\t\tmergeRoutes(\n\t\t\t\t\t\t\tawait createStaticRoute(app.router.response, {\n\t\t\t\t\t\t\t\twithAsync: true\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\tmapRoutes(app)\n\t\t\t\t\t\t),\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tapp.config.serve?.routes\n\t\t\t\t\t)\n\t\t\t\t)\n\n\t\t\t\tapp.server?.reload({\n\t\t\t\t\t...serve,\n\t\t\t\t\tfetch: app.fetch,\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\troutes\n\t\t\t\t})\n\n\t\t\t\tBun?.gc(false)\n\t\t\t})\n\t\t}\n\t},\n\tasync stop(app, closeActiveConnections) {\n\t\tif (app.server) {\n\t\t\tawait app.server.stop(closeActiveConnections)\n\t\t\tapp.server = null\n\n\t\t\tif (app.event.stop?.length)\n\t\t\t\tfor (let i = 0; i < app.event.stop.length; i++)\n\t\t\t\t\tapp.event.stop[i].fn(app)\n\t\t} else\n\t\t\tconsole.log(\n\t\t\t\t\"Elysia isn't running. Call `app.listen` to start the server.\",\n\t\t\t\tnew Error().stack\n\t\t\t)\n\t},\n\tws(app, path, options) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\tconst { parse, body, response, ...rest } = options\n\n\t\tconst messageValidator = getSchemaValidator(body, {\n\t\t\t// @ts-expect-error private property\n\t\t\tmodules: app.definitions.typebox,\n\t\t\t// @ts-expect-error private property\n\t\t\tmodels: app.definitions.type as Record<string, TSchema>,\n\t\t\tnormalize: app.config.normalize\n\t\t})\n\n\t\tconst validateMessage = messageValidator\n\t\t\t? messageValidator.provider === 'standard'\n\t\t\t\t? (data: unknown) =>\n\t\t\t\t\t\tmessageValidator.schema['~standard'].validate(data)\n\t\t\t\t\t\t\t.issues\n\t\t\t\t: (data: unknown) => messageValidator.Check(data) === false\n\t\t\t: undefined\n\n\t\tconst responseValidator = getSchemaValidator(response as any, {\n\t\t\t// @ts-expect-error private property\n\t\t\tmodules: app.definitions.typebox,\n\t\t\t// @ts-expect-error private property\n\t\t\tmodels: app.definitions.type as Record<string, TSchema>,\n\t\t\tnormalize: app.config.normalize\n\t\t})\n\n\t\tapp.route(\n\t\t\t'WS',\n\t\t\tpath as any,\n\t\t\tasync (context: any) => {\n\t\t\t\tconst server =\n\t\t\t\t\t(context.server as (typeof app)['server']) ?? app.server\n\n\t\t\t\t// ! Enable static code analysis just in case resolveUnknownFunction doesn't work, do not remove\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\t\t\tconst { set, path, qi, headers, query, params } = context\n\n\t\t\t\t// @ts-ignore\n\t\t\t\tcontext.validator = responseValidator\n\n\t\t\t\tif (options.upgrade) {\n\t\t\t\t\tif (typeof options.upgrade === 'function') {\n\t\t\t\t\t\tconst temp = options.upgrade(context as any)\n\t\t\t\t\t\tif (temp instanceof Promise) await temp\n\t\t\t\t\t} else if (options.upgrade)\n\t\t\t\t\t\tObject.assign(\n\t\t\t\t\t\t\tset.headers,\n\t\t\t\t\t\t\toptions.upgrade as Record<string, any>\n\t\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (set.cookie && isNotEmpty(set.cookie)) {\n\t\t\t\t\tconst cookie = serializeCookie(set.cookie)\n\n\t\t\t\t\tif (cookie) set.headers['set-cookie'] = cookie\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tset.headers['set-cookie'] &&\n\t\t\t\t\tArray.isArray(set.headers['set-cookie'])\n\t\t\t\t)\n\t\t\t\t\tset.headers = parseSetCookies(\n\t\t\t\t\t\tnew Headers(set.headers as any) as Headers,\n\t\t\t\t\t\tset.headers['set-cookie']\n\t\t\t\t\t) as any\n\n\t\t\t\tconst handleResponse = createHandleWSResponse(responseValidator)\n\t\t\t\tconst parseMessage = createWSMessageParser(parse as any)\n\n\t\t\t\tlet _id: string | undefined\n\n\t\t\t\tif (typeof options.beforeHandle === 'function') {\n\t\t\t\t\tconst result = options.beforeHandle(context)\n\t\t\t\t\tif (result instanceof Promise) await result\n\t\t\t\t}\n\n\t\t\t\tconst errorHandlers = [\n\t\t\t\t\t...(options.error\n\t\t\t\t\t\t? Array.isArray(options.error)\n\t\t\t\t\t\t\t? options.error\n\t\t\t\t\t\t\t: [options.error]\n\t\t\t\t\t\t: []),\n\t\t\t\t\t...(app.event.error ?? []).map((x) =>\n\t\t\t\t\t\ttypeof x === 'function' ? x : x.fn\n\t\t\t\t\t)\n\t\t\t\t].filter((x) => x)\n\n\t\t\t\tconst hasCustomErrorHandlers = errorHandlers.length > 0\n\n\t\t\t\tconst handleErrors = !hasCustomErrorHandlers\n\t\t\t\t\t? () => {}\n\t\t\t\t\t: async (ws: ServerWebSocket<any>, error: unknown) => {\n\t\t\t\t\t\t\tfor (const handleError of errorHandlers) {\n\t\t\t\t\t\t\t\tlet response = handleError(\n\t\t\t\t\t\t\t\t\tObject.assign(context, { error })\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tif (response instanceof Promise)\n\t\t\t\t\t\t\t\t\tresponse = await response\n\n\t\t\t\t\t\t\t\tawait handleResponse(ws, response)\n\n\t\t\t\t\t\t\t\tif (response) break\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tserver?.upgrade(context.request, {\n\t\t\t\t\t\theaders: isNotEmpty(set.headers)\n\t\t\t\t\t\t\t? (set.headers as Record<string, string>)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t...context,\n\t\t\t\t\t\t\tget id() {\n\t\t\t\t\t\t\t\tif (_id) return _id\n\n\t\t\t\t\t\t\t\treturn (_id = randomId())\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tvalidator: responseValidator,\n\t\t\t\t\t\t\tping(ws: ServerWebSocket<any>, data?: unknown) {\n\t\t\t\t\t\t\t\toptions.ping?.(ws as any, data)\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpong(ws: ServerWebSocket<any>, data?: unknown) {\n\t\t\t\t\t\t\t\toptions.pong?.(ws as any, data)\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\topen: async (ws: ServerWebSocket<any>) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait handleResponse(\n\t\t\t\t\t\t\t\t\t\tws,\n\t\t\t\t\t\t\t\t\t\toptions.open?.(\n\t\t\t\t\t\t\t\t\t\t\tnew ElysiaWS(ws, context as any)\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\thandleErrors(ws, error)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tmessage: async (\n\t\t\t\t\t\t\t\tws: ServerWebSocket<any>,\n\t\t\t\t\t\t\t\t_message: any\n\t\t\t\t\t\t\t) => {\n\t\t\t\t\t\t\t\tconst message = await parseMessage(ws, _message)\n\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\tvalidateMessage &&\n\t\t\t\t\t\t\t\t\tvalidateMessage(message)\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tconst validationError = new ValidationError(\n\t\t\t\t\t\t\t\t\t\t'message',\n\t\t\t\t\t\t\t\t\t\tmessageValidator!,\n\t\t\t\t\t\t\t\t\t\tmessage\n\t\t\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\tif (!hasCustomErrorHandlers)\n\t\t\t\t\t\t\t\t\t\treturn void ws.send(\n\t\t\t\t\t\t\t\t\t\t\tvalidationError.message as string\n\t\t\t\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\treturn handleErrors(ws, validationError)\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait handleResponse(\n\t\t\t\t\t\t\t\t\t\tws,\n\t\t\t\t\t\t\t\t\t\toptions.message?.(\n\t\t\t\t\t\t\t\t\t\t\tnew ElysiaWS(\n\t\t\t\t\t\t\t\t\t\t\t\tws,\n\t\t\t\t\t\t\t\t\t\t\t\tcontext as any,\n\t\t\t\t\t\t\t\t\t\t\t\tmessage\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\tmessage as any\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\thandleErrors(ws, error)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tdrain: async (ws: ServerWebSocket<any>) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait handleResponse(\n\t\t\t\t\t\t\t\t\t\tws,\n\t\t\t\t\t\t\t\t\t\toptions.drain?.(\n\t\t\t\t\t\t\t\t\t\t\tnew ElysiaWS(ws, context as any)\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\thandleErrors(ws, error)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tclose: async (\n\t\t\t\t\t\t\t\tws: ServerWebSocket<any>,\n\t\t\t\t\t\t\t\tcode: number,\n\t\t\t\t\t\t\t\treason: string\n\t\t\t\t\t\t\t) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait handleResponse(\n\t\t\t\t\t\t\t\t\t\tws,\n\t\t\t\t\t\t\t\t\t\toptions.close?.(\n\t\t\t\t\t\t\t\t\t\t\tnew ElysiaWS(ws, context as any),\n\t\t\t\t\t\t\t\t\t\t\tcode,\n\t\t\t\t\t\t\t\t\t\t\treason\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\thandleErrors(ws, error)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t\treturn\n\n\t\t\t\treturn status(400, 'Expected a websocket connection')\n\t\t\t},\n\t\t\t{\n\t\t\t\t...rest,\n\t\t\t\twebsocket: options\n\t\t\t} as any\n\t\t)\n\t}\n}\n"
  },
  {
    "path": "src/adapter/cloudflare-worker/index.ts",
    "content": "import { ElysiaAdapter } from '../..'\nimport { WebStandardAdapter } from '../web-standard/index'\nimport { composeErrorHandler } from '../../compose'\n\n/**\n * Cloudflare Adapter (Experimental)\n * @see https://elysiajs.com/integrations/cloudflare-worker\n *\n * @example\n * ```ts\n * import { Elysia } from 'elysia'\n * import { CloudflareAdapter } from 'elysia/adapter/cloudflare-worker'\n *\n * const app = new Elysia({\n * \t  adapter: CloudflareAdapter,\n * })\n * \t  .get('/', () => 'Hello Elysia')\n * \t  .compile()\n *\n * export default app\n * ```\n */\nexport const CloudflareAdapter: ElysiaAdapter = {\n\t...WebStandardAdapter,\n\tname: 'cloudflare-worker',\n\tcomposeGeneralHandler: {\n\t\t...WebStandardAdapter.composeGeneralHandler,\n\t\terror404(hasEventHook, hasErrorHook, afterHandle) {\n\t\t\tconst { code } = WebStandardAdapter.composeGeneralHandler.error404(\n\t\t\t\thasEventHook,\n\t\t\t\thasErrorHook,\n\t\t\t\tafterHandle\n\t\t\t)\n\n\t\t\treturn {\n\t\t\t\tcode,\n\t\t\t\tdeclare: hasErrorHook\n\t\t\t\t\t? ''\n\t\t\t\t\t: // This only work because Elysia only clone the Response via .clone()\n\t\t\t\t\t\t`const error404Message=notFound.message.toString()\\n` +\n\t\t\t\t\t\t`const error404={clone:()=>new Response(error404Message,{status:404})}\\n`\n\t\t\t}\n\t\t}\n\t},\n\tbeforeCompile(app) {\n\t\t// @ts-ignore\n\t\tapp.handleError = composeErrorHandler(app)\n\t\tfor (const route of app.routes) route.compile()\n\t},\n\tlisten() {\n\t\treturn () => {\n\t\t\tconsole.warn(\n\t\t\t\t'Cloudflare Worker does not support listen method. Please export default Elysia instance instead.'\n\t\t\t)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/adapter/index.ts",
    "content": "export type { ElysiaAdapter } from './types'\n"
  },
  {
    "path": "src/adapter/types.ts",
    "content": "import type { Serve, ListenCallback } from '../universal/server'\n\nimport type { AnyElysia } from '..'\nimport type { Context } from '../context'\nimport type { Sucrose } from '../sucrose'\n\nimport type { Prettify, AnyLocalHook, MaybePromise } from '../types'\nimport type { AnyWSLocalHook } from '../ws/types'\n\nexport interface ElysiaAdapter {\n\tname: string\n\tlisten(\n\t\tapp: AnyElysia\n\t): (\n\t\toptions: string | number | Partial<Serve>,\n\t\tcallback?: ListenCallback\n\t) => void\n\t/**\n\t * Stop server from serving\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * app.stop()\n\t * ```\n\t *\n\t * @example\n\t * ```typescript\n\t * app.stop(true) // Abruptly any requests inflight\n\t * ```\n\t */\n\tstop?(app: AnyElysia, closeActiveConnections?: boolean): Promise<void>\n\tisWebStandard?: boolean\n\thandler: {\n\t\t/**\n\t\t * Map return response on every case\n\t\t */\n\t\tmapResponse(\n\t\t\tresponse: unknown,\n\t\t\tset: Context['set'],\n\t\t\t...params: unknown[]\n\t\t): unknown\n\t\t/**\n\t\t * Map response on truthy value\n\t\t */\n\t\tmapEarlyResponse(\n\t\t\tresponse: unknown,\n\t\t\tset: Context['set'],\n\t\t\t...params: unknown[]\n\t\t): unknown\n\t\t/**\n\t\t * Map response without cookie, status or headers\n\t\t */\n\t\tmapCompactResponse(response: unknown, ...params: unknown[]): unknown\n\t\t/**\n\t\t * Compile inline to value\n\t\t *\n\t\t * @example\n\t\t * ```ts\n\t\t * Elysia().get('/', 'static')\n\t\t * ```\n\t\t */\n\t\tcreateStaticHandler?(\n\t\t\thandle: unknown,\n\t\t\thooks: AnyLocalHook,\n\t\t\tsetHeaders?: Context['set']['headers'],\n\t\t\t...params: unknown[]\n\t\t): (() => unknown) | undefined\n\t\t/**\n\t\t * If the runtime support cloning response\n\t\t *\n\t\t * eg. Bun.serve({ static })\n\t\t */\n\t\tcreateNativeStaticHandler?(\n\t\t\thandle: unknown,\n\t\t\thooks: AnyLocalHook,\n\t\t\tset?: Context['set']\n\t\t): (() => MaybePromise<Response>) | undefined\n\t}\n\tcomposeHandler: {\n\t\tmapResponseContext?: string\n\t\t/**\n\t\t * Declare any variable that will be used in the general handler\n\t\t */\n\t\tdeclare?(inference: Sucrose.Inference): string | undefined\n\t\t/**\n\t\t * Inject variable to the general handler\n\t\t */\n\t\tinject?: Record<string, unknown>\n\t\t/**\n\t\t * Whether retriving headers should be using webstandard headers\n\t\t *\n\t\t * @default false\n\t\t */\n\t\tpreferWebstandardHeaders?: boolean\n\t\t/**\n\t\t * fnLiteral for parsing request headers\n\t\t *\n\t\t * @declaration\n\t\t * c.headers: Context headers\n\t\t */\n\t\theaders: string\n\t\t/**\n\t\t * fnLiteral for parsing the request body\n\t\t *\n\t\t * @declaration\n\t\t * c.body: Context body\n\t\t */\n\t\tparser: Prettify<\n\t\t\tRecord<\n\t\t\t\t'json' | 'text' | 'urlencoded' | 'arrayBuffer' | 'formData',\n\t\t\t\t(isOptional: boolean) => string\n\t\t\t> & {\n\t\t\t\tdeclare?: string\n\t\t\t}\n\t\t>\n\t}\n\tcomposeGeneralHandler: {\n\t\tparameters?: string\n\t\terror404(\n\t\t\thasEventHook: boolean,\n\t\t\thasErrorHook: boolean,\n\t\t\tafterResponseHandler?: string\n\t\t): {\n\t\t\tdeclare: string\n\t\t\tcode: string\n\t\t}\n\t\t/**\n\t\t * fnLiteral of the general handler\n\t\t *\n\t\t * @declaration\n\t\t * c: Context\n\t\t * p: pathname\n\t\t */\n\t\tcreateContext(app: AnyElysia): string\n\t\t/**\n\t\t * Inject variable to the general handler\n\t\t */\n\t\tinject?: Record<string, unknown>\n\t}\n\tcomposeError: {\n\t\tdeclare?: string\n\t\tinject?: Record<string, unknown>\n\t\tmapResponseContext: string\n\t\tvalidationError: string\n\t\t/**\n\t\t * Handle thrown error which is instance of Error\n\t\t *\n\t\t * Despite its name of `unknownError`, it also handle named error like `NOT_FOUND`, `VALIDATION_ERROR`\n\t\t * It's named `unknownError` because it also catch unknown error\n\t\t */\n\t\tunknownError: string\n\t}\n\tws?(app: AnyElysia, path: string, handler: AnyWSLocalHook): unknown\n\t/**\n\t * Whether or not the runtime or framework the is built on top on has a router\n\t * eg. Bun.serve.routes, uWebSocket\n\t **/\n\tcreateSystemRouterHandler?(\n\t\tmethod: string,\n\t\tpath: string,\n\t\thook: AnyLocalHook,\n\t\tapp: AnyElysia\n\t): void\n\n\t/**\n\t * Call thing before compile\n\t */\n\tbeforeCompile?(app: AnyElysia): void\n}\n"
  },
  {
    "path": "src/adapter/utils.ts",
    "content": "import { serializeCookie } from '../cookies'\nimport { hasHeaderShorthand, isNotEmpty, StatusMap } from '../utils'\n\nimport type { Context } from '../context'\nimport { env } from '../universal'\nimport { isBun } from '../universal/utils'\nimport { MaybePromise } from '../types'\n\nexport const handleFile = (\n\tresponse: File | Blob,\n\tset?: Context['set'],\n\trequest?: Request\n): Response => {\n\tif (!isBun && response instanceof Promise)\n\t\treturn response.then((res) => handleFile(res, set, request)) as any\n\n\tconst size = response.size\n\n\tconst rangeHeader = request?.headers.get('range')\n\tif (rangeHeader) {\n\t\tconst match = /bytes=(\\d*)-(\\d*)/.exec(rangeHeader)\n\t\tif (match) {\n\t\t\tif (!match[1] && !match[2])\n\t\t\t\treturn new Response(null, {\n\t\t\t\t\tstatus: 416,\n\t\t\t\t\theaders: mergeHeaders(\n\t\t\t\t\t\tnew Headers({ 'content-range': `bytes */${size}` }),\n\t\t\t\t\t\tset?.headers ?? {}\n\t\t\t\t\t)\n\t\t\t\t})\n\n\t\t\tlet start: number\n\t\t\tlet end: number\n\n\t\t\tif (!match[1] && match[2]) {\n\t\t\t\tconst suffix = parseInt(match[2])\n\t\t\t\tstart = Math.max(0, size - suffix)\n\t\t\t\tend = size - 1\n\t\t\t} else {\n\t\t\t\tstart = match[1] ? parseInt(match[1]) : 0\n\t\t\t\tend = match[2]\n\t\t\t\t\t? Math.min(parseInt(match[2]), size - 1)\n\t\t\t\t\t: size - 1\n\t\t\t}\n\n\t\t\tif (start >= size || start > end) {\n\t\t\t\treturn new Response(null, {\n\t\t\t\t\tstatus: 416,\n\t\t\t\t\theaders: mergeHeaders(\n\t\t\t\t\t\tnew Headers({ 'content-range': `bytes */${size}` }),\n\t\t\t\t\t\tset?.headers ?? {}\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst contentLength = end - start + 1\n\t\t\tconst rangeHeaders = new Headers({\n\t\t\t\t'accept-ranges': 'bytes',\n\t\t\t\t'content-range': `bytes ${start}-${end}/${size}`,\n\t\t\t\t'content-length': String(contentLength)\n\t\t\t})\n\n\t\t\t// Blob.slice() exists at runtime but is absent from the ESNext lib typings\n\t\t\t// (no DOM lib). Cast through unknown to the minimal interface we need.\n\t\t\t// Pass response.type as third arg so the sliced blob preserves MIME type.\n\t\t\treturn new Response(\n\t\t\t\t(\n\t\t\t\t\tresponse as unknown as {\n\t\t\t\t\t\tslice(\n\t\t\t\t\t\t\tstart: number,\n\t\t\t\t\t\t\tend: number,\n\t\t\t\t\t\t\tcontentType?: string\n\t\t\t\t\t\t): Blob\n\t\t\t\t\t}\n\t\t\t\t).slice(start, end + 1, response.type),\n\t\t\t\t{\n\t\t\t\t\tstatus: 206,\n\t\t\t\t\theaders: mergeHeaders(rangeHeaders, set?.headers ?? {})\n\t\t\t\t}\n\t\t\t)\n\t\t}\n\t}\n\n\tconst immutable =\n\t\tset &&\n\t\t(set.status === 206 ||\n\t\t\tset.status === 304 ||\n\t\t\tset.status === 412 ||\n\t\t\tset.status === 416)\n\n\tconst defaultHeader = immutable\n\t\t? {}\n\t\t: ({\n\t\t\t\t'accept-ranges': 'bytes',\n\t\t\t\t'content-range': size\n\t\t\t\t\t? `bytes 0-${size - 1}/${size}`\n\t\t\t\t\t: undefined\n\t\t\t} as Record<string, string>)\n\n\tif (!set && !size) return new Response(response as Blob)\n\n\tif (!set)\n\t\treturn new Response(response as Blob, {\n\t\t\theaders: defaultHeader\n\t\t})\n\n\tif (set.headers instanceof Headers) {\n\t\tfor (const key of Object.keys(defaultHeader))\n\t\t\tif (key in set.headers) set.headers.append(key, defaultHeader[key])\n\n\t\tif (immutable) {\n\t\t\tset.headers.delete('content-length')\n\t\t\tset.headers.delete('accept-ranges')\n\t\t}\n\n\t\treturn new Response(response as Blob, set as any)\n\t}\n\n\tif (isNotEmpty(set.headers))\n\t\treturn new Response(response as Blob, {\n\t\t\tstatus: set.status as number,\n\t\t\theaders: Object.assign(defaultHeader, set.headers)\n\t\t})\n\n\treturn new Response(response as Blob, {\n\t\tstatus: set.status as number,\n\t\theaders: defaultHeader\n\t})\n}\n\nexport const parseSetCookies = (headers: Headers, setCookie: string[]) => {\n\tif (!headers) return headers\n\n\theaders.delete('set-cookie')\n\n\tfor (let i = 0; i < setCookie.length; i++) {\n\t\tconst index = setCookie[i].indexOf('=')\n\n\t\theaders.append(\n\t\t\t'set-cookie',\n\t\t\t`${setCookie[i].slice(0, index)}=${\n\t\t\t\tsetCookie[i].slice(index + 1) || ''\n\t\t\t}`\n\t\t)\n\t}\n\n\treturn headers\n}\n\nexport const responseToSetHeaders = (\n\tresponse: Response,\n\tset?: Context['set']\n) => {\n\tif (set?.headers) {\n\t\tif (response) {\n\t\t\tif (hasHeaderShorthand)\n\t\t\t\tObject.assign(set.headers, response.headers.toJSON())\n\t\t\telse\n\t\t\t\tfor (const [key, value] of response.headers.entries())\n\t\t\t\t\tif (key in set.headers) set.headers[key] = value\n\t\t}\n\n\t\tif (set.status === 200) set.status = response.status\n\n\t\t// ? `content-encoding` prevent response streaming\n\t\tif (set.headers['content-encoding'])\n\t\t\tdelete set.headers['content-encoding']\n\n\t\treturn set\n\t}\n\n\tif (!response)\n\t\treturn {\n\t\t\theaders: {},\n\t\t\tstatus: set?.status ?? 200\n\t\t}\n\n\tif (hasHeaderShorthand) {\n\t\tset = {\n\t\t\theaders: response.headers.toJSON(),\n\t\t\tstatus: set?.status ?? 200\n\t\t}\n\n\t\t// ? `content-encoding` prevent response streaming\n\t\tif (set.headers['content-encoding'])\n\t\t\tdelete set.headers['content-encoding']\n\n\t\treturn set\n\t}\n\n\tset = {\n\t\theaders: {},\n\t\tstatus: set?.status ?? 200\n\t}\n\n\tfor (const [key, value] of response.headers.entries()) {\n\t\t// ? `content-encoding` prevent response streaming\n\n\t\tif (key === 'content-encoding') continue\n\n\t\tif (key in set.headers) set.headers[key] = value\n\t}\n\n\treturn set\n}\n\ninterface CreateHandlerParameter {\n\tmapResponse(\n\t\tresponse: unknown,\n\t\tset: Context['set'],\n\t\trequest?: Request\n\t): Response\n\tmapCompactResponse(response: unknown, request?: Request): Response\n}\n\nconst enqueueBinaryChunk = (\n\tcontroller: ReadableStreamDefaultController,\n\tchunk: unknown\n): MaybePromise<boolean> => {\n\tif (chunk instanceof Blob)\n\t\treturn chunk.arrayBuffer().then((buffer) => {\n\t\t\tcontroller.enqueue(new Uint8Array(buffer))\n\t\t\treturn true as const\n\t\t})\n\n\tif (chunk instanceof Uint8Array) {\n\t\tcontroller.enqueue(chunk)\n\t\treturn true\n\t}\n\n\tif (chunk instanceof ArrayBuffer) {\n\t\tcontroller.enqueue(new Uint8Array(chunk))\n\t\treturn true\n\t}\n\n\tif (ArrayBuffer.isView(chunk)) {\n\t\tcontroller.enqueue(\n\t\t\tnew Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n\t\t)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nexport const createStreamHandler =\n\t({ mapResponse, mapCompactResponse }: CreateHandlerParameter) =>\n\tasync (\n\t\tgenerator: Generator | AsyncGenerator | ReadableStream,\n\t\tset?: Context['set'],\n\t\trequest?: Request,\n\t\tskipFormat?: boolean\n\t) => {\n\t\t// Since ReadableStream doesn't have next, init might be undefined\n\t\tlet init = (generator as Generator).next?.() as\n\t\t\t| IteratorResult<unknown>\n\t\t\t| undefined\n\n\t\tif (set) handleSet(set)\n\t\tif (init instanceof Promise) init = await init\n\n\t\t// Generator or ReadableStream is returned from a generator function\n\t\tif (init?.value instanceof ReadableStream) {\n\t\t\t// @ts-ignore\n\t\t\tgenerator = init.value\n\t\t} else if (init && (typeof init?.done === 'undefined' || init?.done)) {\n\t\t\tif (set) return mapResponse(init.value, set, request)\n\t\t\treturn mapCompactResponse(init.value, request)\n\t\t}\n\n\t\t// Check if stream is from a pre-formatted Response body\n\t\tconst isSSE =\n\t\t\t!skipFormat &&\n\t\t\t// @ts-ignore First SSE result is wrapped with sse()\n\t\t\t(init?.value?.sse ??\n\t\t\t\t// @ts-ignore ReadableStream is wrapped with sse()\n\t\t\t\tgenerator?.sse ??\n\t\t\t\t// User explicitly set content-type to SSE\n\t\t\t\tset?.headers['content-type']?.startsWith('text/event-stream'))\n\n\t\tconst format = isSSE\n\t\t\t? (data: string) => `data: ${data}\\n\\n`\n\t\t\t: (data: string) => data\n\n\t\tconst contentType = isSSE\n\t\t\t? 'text/event-stream'\n\t\t\t: init?.value && typeof init?.value === 'object'\n\t\t\t\t? 'application/json'\n\t\t\t\t: 'text/plain'\n\n\t\tif (set?.headers) {\n\t\t\tif (!set.headers['transfer-encoding'])\n\t\t\t\tset.headers['transfer-encoding'] = 'chunked'\n\t\t\tif (!set.headers['content-type'])\n\t\t\t\tset.headers['content-type'] = contentType\n\t\t\tif (!set.headers['cache-control'])\n\t\t\t\tset.headers['cache-control'] = 'no-cache'\n\t\t} else\n\t\t\tset = {\n\t\t\t\tstatus: 200,\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': contentType,\n\t\t\t\t\t'transfer-encoding': 'chunked',\n\t\t\t\t\t'cache-control': 'no-cache',\n\t\t\t\t\tconnection: 'keep-alive'\n\t\t\t\t}\n\t\t\t}\n\n\t\t// Get an explicit async iterator so pull() can advance one step at a time.\n\t\t// Generators already implement the iterator protocol directly (.next()),\n\t\t// while ReadableStream (which generator may be reassigned to above) needs\n\t\t// [Symbol.asyncIterator]() to produce one.\n\t\tconst iterator: AsyncIterator<unknown> =\n\t\t\ttypeof (generator as any).next === 'function'\n\t\t\t\t? (generator as AsyncIterator<unknown>)\n\t\t\t\t: (generator as any)[Symbol.asyncIterator]()\n\n\t\tlet end = false\n\n\t\treturn new Response(\n\t\t\tnew ReadableStream({\n\t\t\t\tstart(controller) {\n\t\t\t\t\t// Register abort handler once — terminates the iterator and\n\t\t\t\t\t// closes the stream so pull() won't be called again.\n\t\t\t\t\trequest?.signal?.addEventListener('abort', () => {\n\t\t\t\t\t\tend = true\n\t\t\t\t\t\titerator.return?.()\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcontroller.close()\n\t\t\t\t\t\t} catch {}\n\t\t\t\t\t})\n\n\t\t\t\t\t// Enqueue the already-extracted init value (first generator\n\t\t\t\t\t// result, used above for SSE detection). Subsequent values\n\t\t\t\t\t// are produced on-demand by pull().\n\t\t\t\t\tif (\n\t\t\t\t\t\t!init ||\n\t\t\t\t\t\tinit.value instanceof ReadableStream ||\n\t\t\t\t\t\tinit.value === undefined ||\n\t\t\t\t\t\tinit.value === null\n\t\t\t\t\t)\n\t\t\t\t\t\treturn\n\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tif (init.value.toSSE)\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tcontroller.enqueue(init.value.toSSE())\n\t\t\t\t\telse if (enqueueBinaryChunk(controller, init.value)) return\n\t\t\t\t\telse if (typeof init.value === 'object')\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\tformat(JSON.stringify(init.value))\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tcontroller.enqueue(format(init.value.toString()))\n\t\t\t\t\t\t}\n\t\t\t\t\telse controller.enqueue(format(init.value.toString()))\n\t\t\t\t},\n\n\t\t\t\tasync pull(controller) {\n\t\t\t\t\t// Respect abort/cancel that happened between pull() calls.\n\t\t\t\t\tif (end) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcontroller.close()\n\t\t\t\t\t\t} catch {}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst { value: chunk, done } = await iterator.next()\n\n\t\t\t\t\t\tif (done || end) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tcontroller.close()\n\t\t\t\t\t\t\t} catch {}\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// null/undefined chunks are skipped; the runtime will\n\t\t\t\t\t\t// call pull() again since nothing was enqueued.\n\t\t\t\t\t\tif (chunk === undefined || chunk === null) return\n\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tif (chunk.toSSE)\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\tcontroller.enqueue(chunk.toSSE())\n\t\t\t\t\t\telse if (enqueueBinaryChunk(controller, chunk)) return\n\t\t\t\t\t\telse if (typeof chunk === 'object')\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\t\tformat(JSON.stringify(chunk))\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tcontroller.enqueue(format(chunk.toString()))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\telse controller.enqueue(format(chunk.toString()))\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconsole.warn(error)\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcontroller.close()\n\t\t\t\t\t\t} catch {}\n\t\t\t\t\t}\n\t\t\t\t},\n\n\t\t\t\tcancel() {\n\t\t\t\t\tend = true\n\t\t\t\t\titerator.return?.()\n\t\t\t\t}\n\t\t\t}),\n\t\t\tset as any\n\t\t)\n\t}\n\nexport async function* streamResponse(response: Response) {\n\tconst body = response.body\n\n\tif (!body) return\n\n\tconst reader = body.getReader()\n\tconst decoder = new TextDecoder()\n\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read()\n\t\t\tif (done) break\n\n\t\t\tif (typeof value === 'string') yield value\n\t\t\telse yield decoder.decode(value)\n\t\t}\n\t} finally {\n\t\treader.releaseLock()\n\t}\n}\n\nexport const handleSet = (set: Context['set']) => {\n\tif (typeof set.status === 'string') set.status = StatusMap[set.status]\n\n\tif (set.cookie && isNotEmpty(set.cookie)) {\n\t\tconst cookie = serializeCookie(set.cookie)\n\n\t\tif (cookie) set.headers['set-cookie'] = cookie\n\t}\n\n\tif (set.headers['set-cookie'] && Array.isArray(set.headers['set-cookie'])) {\n\t\tset.headers = parseSetCookies(\n\t\t\tnew Headers(set.headers as any) as Headers,\n\t\t\tset.headers['set-cookie']\n\t\t) as any\n\t}\n}\n\n// Merge header by allocating a new one\n// In Bun, response.headers can be mutable\n// while in Node and Cloudflare Worker is not\n// default to creating a new one instead\nexport function mergeHeaders(\n\tresponseHeaders: Headers,\n\tsetHeaders: Context['set']['headers']\n) {\n\t// Direct clone preserves all headers including multiple set-cookie\n\tconst headers = new Headers(responseHeaders)\n\n\t// Merge headers: Response headers take precedence, set.headers fill in non-conflicting ones\n\tif (setHeaders instanceof Headers)\n\t\tfor (const key of setHeaders.keys()) {\n\t\t\tif (key === 'set-cookie') {\n\t\t\t\tif (headers.has('set-cookie')) continue\n\n\t\t\t\tfor (const cookie of setHeaders.getSetCookie())\n\t\t\t\t\theaders.append('set-cookie', cookie)\n\t\t\t} else if (!responseHeaders.has(key))\n\t\t\t\theaders.set(key, setHeaders?.get(key) ?? '')\n\t\t}\n\telse\n\t\tfor (const key in setHeaders)\n\t\t\tif (key === 'set-cookie')\n\t\t\t\theaders.append(key, setHeaders[key] as any)\n\t\t\telse if (!responseHeaders.has(key))\n\t\t\t\theaders.set(key, setHeaders[key] as any)\n\n\treturn headers\n}\n\nexport function mergeStatus(\n\tresponseStatus: number,\n\tsetStatus: Context['set']['status']\n) {\n\tif (typeof setStatus === 'string') setStatus = StatusMap[setStatus]\n\n\tif (responseStatus === 200) return setStatus\n\n\treturn responseStatus\n}\n\nexport const createResponseHandler = (handler: CreateHandlerParameter) => {\n\tconst handleStream = createStreamHandler(handler)\n\n\treturn (response: Response, set: Context['set'], request?: Request) => {\n\t\tconst newResponse = new Response(response.body, {\n\t\t\theaders: mergeHeaders(response.headers, set.headers),\n\t\t\tstatus: mergeStatus(response.status, set.status)\n\t\t})\n\n\t\tif (\n\t\t\t!(newResponse as Response).headers.has('content-length') &&\n\t\t\t(newResponse as Response).headers.get('transfer-encoding') ===\n\t\t\t\t'chunked'\n\t\t)\n\t\t\treturn handleStream(\n\t\t\t\tstreamResponse(newResponse as Response),\n\t\t\t\tresponseToSetHeaders(newResponse as Response, set),\n\t\t\t\trequest,\n\t\t\t\ttrue // don't auto-format SSE for pre-formatted Response\n\t\t\t) as any\n\n\t\treturn newResponse\n\t}\n}\n\nexport async function tee<T>(\n\tsource: AsyncIterable<T>,\n\tbranches = 2\n): Promise<AsyncIterableIterator<T>[]> {\n\tconst buffer: T[] = []\n\tlet done = false\n\tlet waiting: { resolve: () => void }[] = []\n\n\t;(async () => {\n\t\tfor await (const value of source) {\n\t\t\tbuffer.push(value)\n\t\t\twaiting.forEach((w) => w.resolve())\n\t\t\twaiting = []\n\t\t}\n\t\tdone = true\n\t\twaiting.forEach((w) => w.resolve())\n\t})()\n\n\tasync function* makeIterator(): AsyncIterableIterator<T> {\n\t\tlet i = 0\n\t\twhile (true) {\n\t\t\tif (i < buffer.length) {\n\t\t\t\tyield buffer[i++]\n\t\t\t} else if (done) {\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tawait new Promise<void>((resolve) => waiting.push({ resolve }))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn Array.from({ length: branches }, makeIterator)\n}\n"
  },
  {
    "path": "src/adapter/web-standard/handler.ts",
    "content": "/* eslint-disable sonarjs/no-nested-switch */\n/* eslint-disable sonarjs/no-duplicate-string */\nimport {\n\tcreateResponseHandler,\n\tcreateStreamHandler,\n\thandleFile,\n\thandleSet\n} from '../utils'\n\nimport { ElysiaFile, mime } from '../../universal/file'\nimport { isNotEmpty } from '../../utils'\nimport { Cookie } from '../../cookies'\nimport { ElysiaCustomStatusResponse } from '../../error'\n\nimport type { Context } from '../../context'\nimport type { AnyLocalHook, MaybePromise } from '../../types'\n\nconst handleElysiaFile = (\n\tfile: ElysiaFile,\n\tset: Context['set'] = {\n\t\theaders: {}\n\t},\n\trequest?: Request\n) => {\n\tconst path = file.path\n\tconst contentType =\n\t\tmime[path.slice(path.lastIndexOf('.') + 1) as any as keyof typeof mime]\n\n\tif (contentType) set.headers['content-type'] = contentType\n\n\tif (\n\t\tfile.stats &&\n\t\tset.status !== 206 &&\n\t\tset.status !== 304 &&\n\t\tset.status !== 412 &&\n\t\tset.status !== 416\n\t)\n\t\treturn file.stats!.then((stat) => {\n\t\t\tconst size = stat.size as number\n\n\t\t\tif (size !== undefined) {\n\t\t\t\tset.headers['content-range'] = `bytes 0-${size - 1}/${size}`\n\t\t\t\tset.headers['content-length'] = size\n\t\t\t}\n\n\t\t\treturn handleFile(file.value as any, set, request)\n\t\t}) as any\n\n\treturn handleFile(file.value as any, set, request)\n}\n\nexport const mapResponse = (\n\tresponse: unknown,\n\tset: Context['set'],\n\trequest?: Request\n): Response => {\n\tif (isNotEmpty(set.headers) || set.status !== 200 || set.cookie) {\n\t\thandleSet(set)\n\n\t\tswitch (response?.constructor?.name) {\n\t\t\tcase 'String':\n\t\t\t\tif (!set.headers['content-type'])\n\t\t\t\t\tset.headers['content-type'] = 'text/plain'\n\n\t\t\t\treturn new Response(response as string, set as any)\n\n\t\t\tcase 'Array':\n\t\t\tcase 'Object':\n\t\t\t\tif (!set.headers['content-type'])\n\t\t\t\t\tset.headers['content-type'] = 'application/json'\n\n\t\t\t\treturn new Response(JSON.stringify(response), set as any)\n\n\t\t\tcase 'ElysiaFile':\n\t\t\t\treturn handleElysiaFile(response as ElysiaFile, set, request)\n\n\t\t\tcase 'File':\n\t\t\t\treturn handleFile(response as File, set, request)\n\n\t\t\tcase 'Blob':\n\t\t\t\treturn handleFile(response as Blob, set, request)\n\n\t\t\tcase 'ElysiaCustomStatusResponse':\n\t\t\t\tset.status = (response as ElysiaCustomStatusResponse<200>).code\n\n\t\t\t\treturn mapResponse(\n\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\tset,\n\t\t\t\t\trequest\n\t\t\t\t)\n\n\t\t\tcase undefined:\n\t\t\t\tif (!response) return new Response('', set as any)\n\n\t\t\t\treturn new Response(JSON.stringify(response), set as any)\n\n\t\t\tcase 'Response':\n\t\t\t\treturn handleResponse(response as Response, set, request)\n\n\t\t\tcase 'Error':\n\t\t\t\treturn errorToResponse(response as Error, set)\n\n\t\t\tcase 'Promise':\n\t\t\t\treturn (response as Promise<any>).then((x) =>\n\t\t\t\t\tmapResponse(x, set, request)\n\t\t\t\t) as any\n\n\t\t\tcase 'Function':\n\t\t\t\treturn mapResponse((response as Function)(), set, request)\n\n\t\t\tcase 'Number':\n\t\t\tcase 'Boolean':\n\t\t\t\treturn new Response(\n\t\t\t\t\t(response as number | boolean).toString(),\n\t\t\t\t\tset as any\n\t\t\t\t)\n\n\t\t\tcase 'Cookie':\n\t\t\t\tif (response instanceof Cookie)\n\t\t\t\t\treturn new Response(response.value, set as any)\n\n\t\t\t\treturn new Response(response?.toString(), set as any)\n\n\t\t\tcase 'FormData':\n\t\t\t\treturn new Response(response as FormData, set as any)\n\n\t\t\tdefault:\n\t\t\t\t// recheck Response, Promise, Error because some library may extends Response\n\t\t\t\tif (response instanceof Response)\n\t\t\t\t\treturn handleResponse(response as Response, set, request)\n\n\t\t\t\tif (response instanceof Promise)\n\t\t\t\t\treturn response.then((x) => mapResponse(x, set)) as any\n\n\t\t\t\tif (response instanceof Error)\n\t\t\t\t\treturn errorToResponse(response as Error, set)\n\n\t\t\t\tif (response instanceof ElysiaCustomStatusResponse) {\n\t\t\t\t\tset.status = (\n\t\t\t\t\t\tresponse as ElysiaCustomStatusResponse<200>\n\t\t\t\t\t).code\n\n\t\t\t\t\treturn mapResponse(\n\t\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\t\tset,\n\t\t\t\t\t\trequest\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\ttypeof response?.next === 'function' ||\n\t\t\t\t\tresponse instanceof ReadableStream\n\t\t\t\t)\n\t\t\t\t\treturn handleStream(response as any, set, request) as any\n\n\t\t\t\tif (typeof (response as Promise<unknown>)?.then === 'function')\n\t\t\t\t\treturn (response as Promise<unknown>).then((x) =>\n\t\t\t\t\t\tmapResponse(x, set)\n\t\t\t\t\t) as any\n\n\t\t\t\t// custom class with an array-like value\n\t\t\t\t// eg. Bun.sql`` result\n\t\t\t\tif (Array.isArray(response))\n\t\t\t\t\treturn new Response(JSON.stringify(response), {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t\t\t}\n\t\t\t\t\t}) as any\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\tif (typeof response?.toResponse === 'function')\n\t\t\t\t\treturn mapResponse((response as any).toResponse(), set)\n\n\t\t\t\tif ('charCodeAt' in (response as any)) {\n\t\t\t\t\tconst code = (response as any).charCodeAt(0)\n\n\t\t\t\t\tif (code === 123 || code === 91) {\n\t\t\t\t\t\tif (!set.headers['Content-Type'])\n\t\t\t\t\t\t\tset.headers['Content-Type'] = 'application/json'\n\n\t\t\t\t\t\treturn new Response(\n\t\t\t\t\t\t\tJSON.stringify(response),\n\t\t\t\t\t\t\tset as any\n\t\t\t\t\t\t) as any\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn new Response(response as any, set as any)\n\t\t}\n\t}\n\n\t// Stream response defers a 'set' API, assume that it may include 'set'\n\tif (\n\t\t// @ts-expect-error\n\t\ttypeof response?.next === 'function' ||\n\t\tresponse instanceof ReadableStream\n\t)\n\t\treturn handleStream(response as any, set, request) as any\n\n\treturn mapCompactResponse(response, request)\n}\n\nexport const mapEarlyResponse = (\n\tresponse: unknown,\n\tset: Context['set'],\n\trequest?: Request\n): Response | undefined => {\n\tif (response === undefined || response === null) return\n\n\tif (isNotEmpty(set.headers) || set.status !== 200 || set.cookie) {\n\t\thandleSet(set)\n\n\t\tswitch (response?.constructor?.name) {\n\t\t\tcase 'String':\n\t\t\t\tif (!set.headers['content-type'])\n\t\t\t\t\tset.headers['content-type'] = 'text/plain'\n\n\t\t\t\treturn new Response(response as string, set as any)\n\n\t\t\tcase 'Array':\n\t\t\tcase 'Object':\n\t\t\t\tif (!set.headers['content-type'])\n\t\t\t\t\tset.headers['content-type'] = 'application/json'\n\n\t\t\t\treturn new Response(JSON.stringify(response), set as any)\n\n\t\t\tcase 'ElysiaFile':\n\t\t\t\treturn handleElysiaFile(response as ElysiaFile, set, request)\n\n\t\t\tcase 'File':\n\t\t\t\treturn handleFile(response as File, set, request)\n\n\t\t\tcase 'Blob':\n\t\t\t\treturn handleFile(response as File | Blob, set, request)\n\n\t\t\tcase 'ElysiaCustomStatusResponse':\n\t\t\t\tset.status = (response as ElysiaCustomStatusResponse<200>).code\n\n\t\t\t\treturn mapEarlyResponse(\n\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\tset,\n\t\t\t\t\trequest\n\t\t\t\t)\n\n\t\t\tcase undefined:\n\t\t\t\tif (!response) return\n\n\t\t\t\treturn new Response(JSON.stringify(response), set as any)\n\n\t\t\tcase 'Response':\n\t\t\t\treturn handleResponse(response as Response, set, request)\n\n\t\t\tcase 'Promise':\n\t\t\t\treturn (response as Promise<unknown>).then((x) =>\n\t\t\t\t\tmapEarlyResponse(x, set)\n\t\t\t\t) as any\n\n\t\t\tcase 'Error':\n\t\t\t\treturn errorToResponse(response as Error, set)\n\n\t\t\tcase 'Function':\n\t\t\t\treturn mapEarlyResponse((response as Function)(), set)\n\n\t\t\tcase 'Number':\n\t\t\tcase 'Boolean':\n\t\t\t\treturn new Response(\n\t\t\t\t\t(response as number | boolean).toString(),\n\t\t\t\t\tset as any\n\t\t\t\t)\n\n\t\t\tcase 'FormData':\n\t\t\t\treturn new Response(response as FormData)\n\n\t\t\tcase 'Cookie':\n\t\t\t\tif (response instanceof Cookie)\n\t\t\t\t\treturn new Response(response.value, set as any)\n\n\t\t\t\treturn new Response(response?.toString(), set as any)\n\n\t\t\tdefault:\n\t\t\t\tif (response instanceof Response)\n\t\t\t\t\treturn handleResponse(response, set, request)\n\n\t\t\t\tif (response instanceof Promise)\n\t\t\t\t\treturn response.then((x) => mapEarlyResponse(x, set)) as any\n\n\t\t\t\tif (response instanceof Error)\n\t\t\t\t\treturn errorToResponse(response as Error, set)\n\n\t\t\t\tif (response instanceof ElysiaCustomStatusResponse) {\n\t\t\t\t\tset.status = (\n\t\t\t\t\t\tresponse as ElysiaCustomStatusResponse<200>\n\t\t\t\t\t).code\n\n\t\t\t\t\treturn mapEarlyResponse(\n\t\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\t\tset,\n\t\t\t\t\t\trequest\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\ttypeof response?.next === 'function' ||\n\t\t\t\t\tresponse instanceof ReadableStream\n\t\t\t\t)\n\t\t\t\t\treturn handleStream(response as any, set, request) as any\n\n\t\t\t\tif (typeof (response as Promise<unknown>)?.then === 'function')\n\t\t\t\t\treturn (response as Promise<unknown>).then((x) =>\n\t\t\t\t\t\tmapEarlyResponse(x, set)\n\t\t\t\t\t) as any\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\tif (typeof response?.toResponse === 'function')\n\t\t\t\t\treturn mapEarlyResponse((response as any).toResponse(), set)\n\n\t\t\t\t// custom class with an array-like value\n\t\t\t\t// eg. Bun.sql`` result\n\t\t\t\tif (Array.isArray(response))\n\t\t\t\t\treturn new Response(JSON.stringify(response), {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t\t\t}\n\t\t\t\t\t}) as any\n\n\t\t\t\tif ('charCodeAt' in (response as any)) {\n\t\t\t\t\tconst code = (response as any).charCodeAt(0)\n\n\t\t\t\t\tif (code === 123 || code === 91) {\n\t\t\t\t\t\tif (!set.headers['Content-Type'])\n\t\t\t\t\t\t\tset.headers['Content-Type'] = 'application/json'\n\n\t\t\t\t\t\treturn new Response(\n\t\t\t\t\t\t\tJSON.stringify(response),\n\t\t\t\t\t\t\tset as any\n\t\t\t\t\t\t) as any\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn new Response(response as any, set as any)\n\t\t}\n\t} else\n\t\tswitch (response?.constructor?.name) {\n\t\t\tcase 'String':\n\t\t\t\tif (!set.headers['content-type'])\n\t\t\t\t\tset.headers['content-type'] = 'text/plain'\n\n\t\t\t\treturn new Response(response as string)\n\n\t\t\tcase 'Array':\n\t\t\tcase 'Object':\n\t\t\t\tif (!set.headers['content-type'])\n\t\t\t\t\tset.headers['content-type'] = 'application/json'\n\n\t\t\t\treturn new Response(JSON.stringify(response), set as any)\n\n\t\t\tcase 'ElysiaFile':\n\t\t\t\treturn handleElysiaFile(response as ElysiaFile, set, request)\n\n\t\t\tcase 'File':\n\t\t\t\treturn handleFile(response as File, set, request)\n\n\t\t\tcase 'Blob':\n\t\t\t\treturn handleFile(response as File | Blob, set, request)\n\n\t\t\tcase 'ElysiaCustomStatusResponse':\n\t\t\t\tset.status = (response as ElysiaCustomStatusResponse<200>).code\n\n\t\t\t\treturn mapEarlyResponse(\n\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\tset,\n\t\t\t\t\trequest\n\t\t\t\t)\n\n\t\t\tcase undefined:\n\t\t\t\tif (!response) return new Response('')\n\n\t\t\t\treturn new Response(JSON.stringify(response), {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\tcase 'Response':\n\t\t\t\treturn response as Response\n\n\t\t\tcase 'Promise':\n\t\t\t\treturn (response as Promise<unknown>).then((x) => {\n\t\t\t\t\tconst r = mapEarlyResponse(x, set)\n\t\t\t\t\tif (r !== undefined) return r\n\t\t\t\t}) as any\n\n\t\t\tcase 'Error':\n\t\t\t\treturn errorToResponse(response as Error, set)\n\n\t\t\tcase 'Function':\n\t\t\t\treturn mapCompactResponse((response as Function)(), request)\n\n\t\t\tcase 'Number':\n\t\t\tcase 'Boolean':\n\t\t\t\treturn new Response((response as number | boolean).toString())\n\n\t\t\tcase 'Cookie':\n\t\t\t\tif (response instanceof Cookie)\n\t\t\t\t\treturn new Response(response.value, set as any)\n\n\t\t\t\treturn new Response(response?.toString(), set as any)\n\n\t\t\tcase 'FormData':\n\t\t\t\treturn new Response(response as FormData)\n\n\t\t\tdefault:\n\t\t\t\tif (response instanceof Response) return response\n\n\t\t\t\tif (response instanceof Promise)\n\t\t\t\t\treturn response.then((x) => mapEarlyResponse(x, set)) as any\n\n\t\t\t\tif (response instanceof Error)\n\t\t\t\t\treturn errorToResponse(response as Error, set)\n\n\t\t\t\tif (response instanceof ElysiaCustomStatusResponse) {\n\t\t\t\t\tset.status = (\n\t\t\t\t\t\tresponse as ElysiaCustomStatusResponse<200>\n\t\t\t\t\t).code\n\n\t\t\t\t\treturn mapEarlyResponse(\n\t\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\t\tset,\n\t\t\t\t\t\trequest\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\ttypeof response?.next === 'function' ||\n\t\t\t\t\tresponse instanceof ReadableStream\n\t\t\t\t)\n\t\t\t\t\treturn handleStream(response as any, set, request) as any\n\n\t\t\t\tif (typeof (response as Promise<unknown>)?.then === 'function')\n\t\t\t\t\treturn (response as Promise<unknown>).then((x) =>\n\t\t\t\t\t\tmapEarlyResponse(x, set)\n\t\t\t\t\t) as any\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\tif (typeof response?.toResponse === 'function')\n\t\t\t\t\treturn mapEarlyResponse((response as any).toResponse(), set)\n\n\t\t\t\t// custom class with an array-like value\n\t\t\t\t// eg. Bun.sql`` result\n\t\t\t\tif (Array.isArray(response))\n\t\t\t\t\treturn new Response(JSON.stringify(response), {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t\t\t}\n\t\t\t\t\t}) as any\n\n\t\t\t\tif ('charCodeAt' in (response as any)) {\n\t\t\t\t\tconst code = (response as any).charCodeAt(0)\n\n\t\t\t\t\tif (code === 123 || code === 91) {\n\t\t\t\t\t\tif (!set.headers['Content-Type'])\n\t\t\t\t\t\t\tset.headers['Content-Type'] = 'application/json'\n\n\t\t\t\t\t\treturn new Response(\n\t\t\t\t\t\t\tJSON.stringify(response),\n\t\t\t\t\t\t\tset as any\n\t\t\t\t\t\t) as any\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn new Response(response as any)\n\t\t}\n}\n\nexport const mapCompactResponse = (\n\tresponse: unknown,\n\trequest?: Request\n): Response => {\n\tswitch (response?.constructor?.name) {\n\t\tcase 'String':\n\t\t\treturn new Response(response as string, {\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'text/plain'\n\t\t\t\t}\n\t\t\t})\n\n\t\tcase 'Object':\n\t\tcase 'Array':\n\t\t\treturn new Response(JSON.stringify(response), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t}\n\t\t\t})\n\n\t\tcase 'ElysiaFile':\n\t\t\treturn handleElysiaFile(response as ElysiaFile, undefined, request)\n\n\t\tcase 'File':\n\t\t\treturn handleFile(response as File, undefined, request)\n\n\t\tcase 'Blob':\n\t\t\treturn handleFile(response as File | Blob, undefined, request)\n\n\t\tcase 'ElysiaCustomStatusResponse':\n\t\t\treturn mapResponse(\n\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t{\n\t\t\t\t\tstatus: (response as ElysiaCustomStatusResponse<200>).code,\n\t\t\t\t\theaders: {}\n\t\t\t\t}\n\t\t\t)\n\n\t\tcase undefined:\n\t\t\tif (!response) return new Response('')\n\n\t\t\treturn new Response(JSON.stringify(response), {\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t}\n\t\t\t})\n\n\t\tcase 'Response':\n\t\t\treturn response as Response\n\n\t\tcase 'Error':\n\t\t\treturn errorToResponse(response as Error)\n\n\t\tcase 'Promise':\n\t\t\treturn (response as any as Promise<unknown>).then((x) =>\n\t\t\t\tmapCompactResponse(x, request)\n\t\t\t) as any\n\n\t\t// ? Maybe response or Blob\n\t\tcase 'Function':\n\t\t\treturn mapCompactResponse((response as Function)(), request)\n\n\t\tcase 'Number':\n\t\tcase 'Boolean':\n\t\t\treturn new Response((response as number | boolean).toString())\n\n\t\tcase 'FormData':\n\t\t\treturn new Response(response as FormData)\n\n\t\tdefault:\n\t\t\tif (response instanceof Response) return response\n\n\t\t\tif (response instanceof Promise)\n\t\t\t\treturn response.then((x) =>\n\t\t\t\t\tmapCompactResponse(x, request)\n\t\t\t\t) as any\n\n\t\t\tif (response instanceof Error)\n\t\t\t\treturn errorToResponse(response as Error)\n\n\t\t\tif (response instanceof ElysiaCustomStatusResponse)\n\t\t\t\treturn mapResponse(\n\t\t\t\t\t(response as ElysiaCustomStatusResponse<200>).response,\n\t\t\t\t\t{\n\t\t\t\t\t\tstatus: (response as ElysiaCustomStatusResponse<200>)\n\t\t\t\t\t\t\t.code,\n\t\t\t\t\t\theaders: {}\n\t\t\t\t\t}\n\t\t\t\t)\n\n\t\t\tif (\n\t\t\t\t// @ts-expect-error\n\t\t\t\ttypeof response?.next === 'function' ||\n\t\t\t\tresponse instanceof ReadableStream\n\t\t\t)\n\t\t\t\treturn handleStream(response as any, undefined, request) as any\n\n\t\t\tif (typeof (response as Promise<unknown>)?.then === 'function')\n\t\t\t\treturn (response as Promise<unknown>).then((x) =>\n\t\t\t\t\tmapCompactResponse(x, request)\n\t\t\t\t) as any\n\n\t\t\t// @ts-expect-error\n\t\t\tif (typeof response?.toResponse === 'function')\n\t\t\t\treturn mapCompactResponse((response as any).toResponse())\n\n\t\t\t// custom class with an array-like value\n\t\t\t// eg. Bun.sql`` result\n\t\t\tif (Array.isArray(response))\n\t\t\t\treturn new Response(JSON.stringify(response), {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t\t}\n\t\t\t\t}) as any\n\n\t\t\tif ('charCodeAt' in (response as any)) {\n\t\t\t\tconst code = (response as any).charCodeAt(0)\n\n\t\t\t\tif (code === 123 || code === 91) {\n\t\t\t\t\treturn new Response(JSON.stringify(response), {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t\t\t}\n\t\t\t\t\t}) as any\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn new Response(response as any)\n\t}\n}\n\nexport const errorToResponse = (\n\terror: Error & { toResponse?(): MaybePromise<Response> },\n\tset?: Context['set']\n) => {\n\tif (typeof error?.toResponse === 'function') {\n\t\tconst raw = error.toResponse()\n\t\tconst targetSet =\n\t\t\tset ??\n\t\t\t({ headers: {}, status: 200, redirect: '' } as Context['set'])\n\n\t\tconst apply = (resolved: unknown) => {\n\t\t\tif (resolved instanceof Response) targetSet.status = resolved.status\n\t\t\treturn mapResponse(resolved, targetSet)\n\t\t}\n\n\t\t// @ts-ignore\n\t\treturn typeof raw?.then === 'function' ? raw.then(apply) : apply(raw)\n\t}\n\n\treturn new Response(\n\t\tJSON.stringify({\n\t\t\tname: error?.name,\n\t\t\tmessage: error?.message,\n\t\t\tcause: error?.cause\n\t\t}),\n\t\t{\n\t\t\tstatus:\n\t\t\t\tset?.status !== 200 ? ((set?.status as number) ?? 500) : 500,\n\t\t\theaders: set?.headers as any\n\t\t}\n\t)\n}\n\nexport const createStaticHandler = (\n\thandle: unknown,\n\thooks: Partial<AnyLocalHook>,\n\tsetHeaders: Context['set']['headers'] = {}\n): (() => Response) | undefined => {\n\tif (typeof handle === 'function') return\n\n\tconst response = mapResponse(handle, {\n\t\theaders: setHeaders\n\t})\n\n\tif (\n\t\t!hooks.parse?.length &&\n\t\t!hooks.transform?.length &&\n\t\t!hooks.beforeHandle?.length &&\n\t\t!hooks.afterHandle?.length\n\t)\n\t\treturn () => response.clone() as Response\n}\n\nconst handleResponse = createResponseHandler({\n\tmapResponse,\n\tmapCompactResponse\n})\n\nconst handleStream = createStreamHandler({\n\tmapResponse,\n\tmapCompactResponse\n})\n"
  },
  {
    "path": "src/adapter/web-standard/index.ts",
    "content": "import {\n\tmapResponse,\n\tmapEarlyResponse,\n\tmapCompactResponse,\n\tcreateStaticHandler\n} from './handler'\n\nimport type { ElysiaAdapter } from '../types'\n\nexport const WebStandardAdapter: ElysiaAdapter = {\n\tname: 'web-standard',\n\tisWebStandard: true,\n\thandler: {\n\t\tmapResponse,\n\t\tmapEarlyResponse,\n\t\tmapCompactResponse,\n\t\tcreateStaticHandler\n\t},\n\tcomposeHandler: {\n\t\tmapResponseContext: 'c.request',\n\t\tpreferWebstandardHeaders: true,\n\t\t// @ts-ignore Bun specific\n\t\theaders:\n\t\t\t'c.headers={}\\n' +\n\t\t\t'for(const [k,v] of c.request.headers.entries())' +\n\t\t\t'c.headers[k]=v\\n',\n\t\tparser: {\n\t\t\tjson(isOptional) {\n\t\t\t\tif (isOptional)\n\t\t\t\t\treturn `try{c.body=await c.request.json()}catch{}\\n`\n\t\t\t\treturn `c.body=await c.request.json()\\n`\n\t\t\t},\n\t\t\ttext() {\n\t\t\t\treturn `c.body=await c.request.text()\\n`\n\t\t\t},\n\t\t\turlencoded() {\n\t\t\t\treturn `c.body=parseQuery(await c.request.text())\\n`\n\t\t\t},\n\t\t\tarrayBuffer() {\n\t\t\t\treturn `c.body=await c.request.arrayBuffer()\\n`\n\t\t\t},\n\t\t\tformData(isOptional) {\n\t\t\t\tlet fnLiteral = '\\nc.body={}\\n'\n\n\t\t\t\tif (isOptional)\n\t\t\t\t\tfnLiteral += `let form;try{form=await c.request.formData()}catch{}`\n\t\t\t\telse fnLiteral += `const form=await c.request.formData()\\n`\n\n\t\t\t\treturn (\n\t\t\t\t\tfnLiteral +\n\t\t\t\t\t`const dangerousKeys=new Set(['__proto__','constructor','prototype'])\\n` +\n\t\t\t\t\t`const isDangerousKey=(k)=>{` +\n\t\t\t\t\t`if(dangerousKeys.has(k))return true;` +\n\t\t\t\t\t`const m=k.match(/^(.+)\\\\[(\\\\d+)\\\\]$/);` +\n\t\t\t\t\t`return m?dangerousKeys.has(m[1]):false` +\n\t\t\t\t\t`}\\n` +\n\t\t\t\t\t`const parseArrayKey=(k)=>{` +\n\t\t\t\t\t`const m=k.match(/^(.+)\\\\[(\\\\d+)\\\\]$/);` +\n\t\t\t\t\t`return m?{name:m[1],index:parseInt(m[2],10)}:null` +\n\t\t\t\t\t`}\\n` +\n\t\t\t\t\t`for(const key of form.keys()){` +\n\t\t\t\t\t`if(c.body[key])continue\\n` +\n\t\t\t\t\t`const value=form.getAll(key)\\n` +\n\t\t\t\t\t`let finalValue\\n` +\n    \t\t\t\t`if(value.length===1){\\n` +\n    \t\t\t\t`const sv=value[0]\\n` +\n    \t\t\t\t`if(typeof sv==='string'&&(sv.charCodeAt(0)===123||sv.charCodeAt(0)===91)){\\n` +\n    \t\t\t\t`try{\\n` +\n    \t\t\t\t`const p=JSON.parse(sv)\\n` +\n    \t\t\t\t`if(p&&typeof p==='object')finalValue=p\\n` +\n    \t\t\t\t`}catch{}\\n` +\n    \t\t\t\t`}\\n` +\n    \t\t\t\t`if(finalValue===undefined)finalValue=sv\\n` +\n    \t\t\t\t`}else finalValue=value\\n` +\n\t\t\t\t\t`if(Array.isArray(finalValue)){\\n` +\n\t\t\t\t\t`const stringValue=finalValue.find((entry)=>typeof entry==='string')\\n` +\n\t\t\t\t\t`const files=typeof File==='undefined'?[]:finalValue.filter((entry)=>entry instanceof File)\\n` +\n\t\t\t\t\t`if(stringValue&&files.length&&stringValue.charCodeAt(0)===123){\\n` +\n\t\t\t\t\t`try{\\n` +\n\t\t\t\t\t`const parsed=JSON.parse(stringValue)\\n` +\n\t\t\t\t\t`if(parsed&&typeof parsed==='object'&&!Array.isArray(parsed)){\\n` +\n\t\t\t\t\t`if(!('file' in parsed)&&files.length===1)parsed.file=files[0]\\n` +\n\t\t\t\t\t`else if(!('files' in parsed)&&files.length>1)parsed.files=files\\n` +\n\t\t\t\t\t`finalValue=parsed\\n` +\n\t\t\t\t\t`}\\n` +\n\t\t\t\t\t`}catch{}\\n` +\n\t\t\t\t\t`}\\n` +\n\t\t\t\t\t`}\\n` +\n\t\t\t\t\t`if(key.includes('.')||key.includes('[')){` +\n\t\t\t\t\t`const keys=key.split('.')\\n` +\n\t\t\t\t\t`const lastKey=keys.pop()\\n` +\n\t\t\t\t\t`if(isDangerousKey(lastKey)||keys.some(isDangerousKey))continue\\n` +\n\t\t\t\t\t`let current=c.body\\n` +\n\t\t\t\t\t`for(const k of keys){` +\n\t\t\t\t\t`const arrayInfo=parseArrayKey(k)\\n` +\n\t\t\t\t\t`if(arrayInfo){` +\n\t\t\t\t\t`if(!Array.isArray(current[arrayInfo.name]))current[arrayInfo.name]=[]\\n` +\n\t\t\t\t\t`const existing=current[arrayInfo.name][arrayInfo.index]\\n` +\n\t\t\t\t\t`const isFile=typeof File!=='undefined'&&existing instanceof File\\n` +\n\t\t\t\t\t`if(!existing||typeof existing!=='object'||Array.isArray(existing)||isFile){\\n` +\n\t\t\t\t\t`let parsed\\n` +\n\t\t\t\t\t`if(typeof existing==='string'&&existing.charCodeAt(0)===123){\\n` +\n\t\t\t\t\t`try{` +\n\t\t\t\t\t`parsed=JSON.parse(existing)\\n` +\n\t\t\t\t\t`if(!parsed||typeof parsed!=='object'||Array.isArray(parsed))parsed=undefined` +\n\t\t\t\t\t`}catch{}\\n` +\n\t\t\t\t\t`}\\n` +\n\t\t\t\t\t`current[arrayInfo.name][arrayInfo.index]=parsed||{}\\n` +\n\t\t\t\t\t`}\\n` +\n\t\t\t\t\t`current=current[arrayInfo.name][arrayInfo.index]` +\n\t\t\t\t\t`}else{` +\n\t\t\t\t\t`if(!current[k]||typeof current[k]!=='object')current[k]={}\\n` +\n\t\t\t\t\t`current=current[k]` +\n\t\t\t\t\t`}` +\n\t\t\t\t\t`}\\n` +\n\t\t\t\t\t`const arrayInfo=parseArrayKey(lastKey)\\n` +\n\t\t\t\t\t`if(arrayInfo){` +\n\t\t\t\t\t`if(!Array.isArray(current[arrayInfo.name]))current[arrayInfo.name]=[]\\n` +\n\t\t\t\t\t`current[arrayInfo.name][arrayInfo.index]=finalValue` +\n\t\t\t\t\t`}else{` +\n\t\t\t\t\t`current[lastKey]=finalValue` +\n\t\t\t\t\t`}` +\n\t\t\t\t\t`}else c.body[key]=finalValue` +\n\t\t\t\t\t`}`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t},\n\tasync stop(app, closeActiveConnections) {\n\t\tif (!app.server)\n\t\t\tthrow new Error(\n\t\t\t\t\"Elysia isn't running. Call `app.listen` to start the server.\"\n\t\t\t)\n\n\t\tif (app.server) {\n\t\t\tawait app.server.stop(closeActiveConnections)\n\t\t\tapp.server = null\n\n\t\t\tif (app.event.stop?.length)\n\t\t\t\tfor (let i = 0; i < app.event.stop.length; i++)\n\t\t\t\t\tapp.event.stop[i].fn(app)\n\t\t}\n\t},\n\tcomposeGeneralHandler: {\n\t\tparameters: 'r',\n\t\tcreateContext(app) {\n\t\t\tlet decoratorsLiteral = ''\n\t\t\tlet fnLiteral = ''\n\n\t\t\t// @ts-expect-error private\n\t\t\tconst defaultHeaders = app.setHeaders\n\n\t\t\tfor (const key of Object.keys(app.decorator))\n\t\t\t\tdecoratorsLiteral += `,'${key}':decorator['${key}']`\n\n\t\t\tconst standardHostname =\n\t\t\t\tapp.config.handler?.standardHostname ?? true\n\t\t\tconst hasTrace = !!app.event.trace?.length\n\n\t\t\tfnLiteral +=\n\t\t\t\t`const u=r.url,` +\n\t\t\t\t`s=u.indexOf('/',${standardHostname ? 11 : 7}),` +\n\t\t\t\t`qi=u.indexOf('?',s+1),` +\n\t\t\t\t`p=u.substring(s,qi===-1?undefined:qi)\\n`\n\n\t\t\tif (hasTrace) fnLiteral += `const id=randomId()\\n`\n\n\t\t\tfnLiteral +=\n\t\t\t\t`const c={request:r,` +\n\t\t\t\t`store,` +\n\t\t\t\t`qi,` +\n\t\t\t\t`path:p,` +\n\t\t\t\t`url:u,` +\n\t\t\t\t`redirect,` +\n\t\t\t\t`status,` +\n\t\t\t\t`set:{headers:`\n\n\t\t\tfnLiteral += Object.keys(defaultHeaders ?? {}).length\n\t\t\t\t? 'Object.assign({},app.setHeaders)'\n\t\t\t\t: 'Object.create(null)'\n\n\t\t\tfnLiteral += `,status:200}`\n\n\t\t\t// @ts-expect-error private\n\t\t\tif (app.inference.server)\n\t\t\t\tfnLiteral += `,get server(){return app.getServer()}`\n\t\t\tif (hasTrace) fnLiteral += ',[ELYSIA_REQUEST_ID]:id'\n\t\t\tfnLiteral += decoratorsLiteral\n\t\t\tfnLiteral += `}\\n`\n\n\t\t\treturn fnLiteral\n\t\t},\n\t\terror404(hasEventHook, hasErrorHook, afterHandle = '') {\n\t\t\tlet findDynamicRoute =\n\t\t\t\t`if(route===null){` +\n\t\t\t\tafterHandle +\n\t\t\t\t(hasErrorHook ? '' : 'c.set.status=404') +\n\t\t\t\t'\\nreturn '\n\n\t\t\tif (hasErrorHook)\n\t\t\t\tfindDynamicRoute += `app.handleError(c,notFound,false,${this.parameters})`\n\t\t\telse\n\t\t\t\tfindDynamicRoute += hasEventHook\n\t\t\t\t\t? `c.response=c.responseValue=new Response(error404Message,{` +\n\t\t\t\t\t\t`status:c.set.status===200?404:c.set.status,` +\n\t\t\t\t\t\t`headers:c.set.headers` +\n\t\t\t\t\t\t`})`\n\t\t\t\t\t: `c.response=c.responseValue=error404.clone()`\n\n\t\t\tfindDynamicRoute += '}'\n\n\t\t\treturn {\n\t\t\t\tdeclare: hasErrorHook\n\t\t\t\t\t? ''\n\t\t\t\t\t: `const error404Message=notFound.message.toString()\\n` +\n\t\t\t\t\t\t`const error404=new Response(error404Message,{status:404})\\n`,\n\t\t\t\tcode: findDynamicRoute\n\t\t\t}\n\t\t}\n\t},\n\tcomposeError: {\n\t\tmapResponseContext: '',\n\t\tvalidationError:\n\t\t\t`set.headers['content-type']='application/json';` +\n\t\t\t`return mapResponse(error.message,set)`,\n\t\tunknownError:\n\t\t\t`set.status=error.status??set.status??500;` +\n\t\t\t`return mapResponse(error.message,set)`\n\t},\n\tlisten() {\n\t\treturn () => {\n\t\t\tthrow new Error(\n\t\t\t\t'WebStandard does not support listen, you might want to export default Elysia.fetch instead'\n\t\t\t)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/compose.ts",
    "content": "import { AnyElysia, Cookie } from './index'\n\nimport { Value, TransformDecodeError } from '@sinclair/typebox/value'\nimport {\n\tKind,\n\tTypeBoxError,\n\ttype TAnySchema,\n\ttype TSchema\n} from '@sinclair/typebox'\n\nimport decode from 'fast-decode-uri-component'\nimport {\n\tparseQuery,\n\tparseQueryFromURL,\n\tparseQueryStandardSchema\n} from './parse-query'\n\nimport {\n\tELYSIA_REQUEST_ID,\n\tgetLoosePath,\n\thasSetImmediate,\n\tlifeCycleToFn,\n\trandomId,\n\tredirect,\n\tsignCookie,\n\tisNotEmpty,\n\tencodePath,\n\tmergeCookie,\n\tgetResponseLength\n} from './utils'\nimport { isBun } from './universal/utils'\nimport { ParseError, status } from './error'\n\nimport {\n\tNotFoundError,\n\tValidationError,\n\tERROR_CODE,\n\tElysiaCustomStatusResponse\n} from './error'\nimport { ELYSIA_TRACE, type TraceHandler } from './trace'\n\nimport {\n\tElysiaTypeCheck,\n\tgetCookieValidator,\n\tgetSchemaProperties,\n\tgetSchemaValidator,\n\thasElysiaMeta,\n\thasType,\n\tisUnion,\n\tunwrapImportSchema\n} from './schema'\nimport { Sucrose, sucrose } from './sucrose'\nimport { parseCookie, type CookieOptions } from './cookies'\nimport { fileType } from './type-system/utils'\n\nimport type { TraceEvent } from './trace'\nimport type {\n\tComposedHandler,\n\tElysiaConfig,\n\tHandler,\n\tHookContainer,\n\tLifeCycleStore,\n\tMaybePromise,\n\tSchemaValidator\n} from './types'\nimport { tee } from './adapter/utils'\nimport { coercePrimitiveRoot } from './replace-schema'\n\nconst allocateIf = (value: string, condition: unknown) =>\n\tcondition ? value : ''\n\nconst defaultParsers = [\n\t'json',\n\t'text',\n\t'urlencoded',\n\t'arrayBuffer',\n\t'formdata',\n\t'application/json',\n\t// eslint-disable-next-line sonarjs/no-duplicate-string\n\t'text/plain',\n\t// eslint-disable-next-line sonarjs/no-duplicate-string\n\t'application/x-www-form-urlencoded',\n\t// eslint-disable-next-line sonarjs/no-duplicate-string\n\t'application/octet-stream',\n\t// eslint-disable-next-line sonarjs/no-duplicate-string\n\t'multipart/form-data'\n]\n\nconst createReport = ({\n\tcontext = 'c',\n\ttrace = [],\n\taddFn\n}: {\n\tcontext?: string\n\ttrace?: (TraceHandler | HookContainer<TraceHandler>)[]\n\taddFn(string: string): void\n}) => {\n\tif (!trace.length)\n\t\treturn () => {\n\t\t\treturn {\n\t\t\t\tresolveChild() {\n\t\t\t\t\treturn () => {}\n\t\t\t\t},\n\t\t\t\tresolve() {}\n\t\t\t}\n\t\t}\n\n\tfor (let i = 0; i < trace.length; i++)\n\t\taddFn(\n\t\t\t`let report${i},reportChild${i},reportErr${i},reportErrChild${i};` +\n\t\t\t\t`let trace${i}=${context}[ELYSIA_TRACE]?.[${i}]??trace[${i}](${context});\\n`\n\t\t)\n\n\t// const aliases: string[] = []\n\n\treturn (\n\t\tevent: TraceEvent,\n\t\t{\n\t\t\tname,\n\t\t\ttotal = 0,\n\t\t\talias\n\t\t}: {\n\t\t\tname?: string\n\t\t\tattribute?: string\n\t\t\ttotal?: number\n\t\t\talias?: string\n\t\t} = {}\n\t) => {\n\t\t// ? For debug specific event\n\t\t// if (event !== 'mapResponse')\n\t\t// \treturn {\n\t\t// \t\tresolveChild() {\n\t\t// \t\t\treturn () => {}\n\t\t// \t\t},\n\t\t// \t\tresolve() {}\n\t\t// \t}\n\n\t\tif (!name) name = 'anonymous'\n\n\t\tconst reporter = event === 'error' ? 'reportErr' : 'report'\n\n\t\tfor (let i = 0; i < trace.length; i++) {\n\t\t\taddFn(\n\t\t\t\t`${alias ? 'const ' : ''}${alias ?? reporter}${i}=trace${i}.${event}({` +\n\t\t\t\t\t`id,` +\n\t\t\t\t\t`event:'${event}',` +\n\t\t\t\t\t`name:'${name}',` +\n\t\t\t\t\t`begin:performance.now(),` +\n\t\t\t\t\t`total:${total}` +\n\t\t\t\t\t`})\\n`\n\t\t\t)\n\n\t\t\tif (alias) addFn(`${reporter}${i}=${alias}${i}\\n`)\n\t\t}\n\n\t\t// if (event === 'error')\n\t\t// \tfor (const alias of aliases)\n\t\t// \t\tfor (let i = 0; i < trace.length; i++)\n\t\t// \t\t\taddFn(\n\t\t// \t\t\t\t`const ${alias}Err${i}=trace${i}.${event}({` +\n\t\t// \t\t\t\t\t`id,` +\n\t\t// \t\t\t\t\t`event:'${event}',` +\n\t\t// \t\t\t\t\t`name:'${name}',` +\n\t\t// \t\t\t\t\t`begin:performance.now(),` +\n\t\t// \t\t\t\t\t`total:${total}` +\n\t\t// \t\t\t\t\t`})\\n`\n\t\t// \t\t\t)\n\n\t\treturn {\n\t\t\tresolve() {\n\t\t\t\tfor (let i = 0; i < trace.length; i++)\n\t\t\t\t\taddFn(`${alias ?? reporter}${i}.resolve()\\n`)\n\t\t\t},\n\t\t\tresolveChild(name: string) {\n\t\t\t\tfor (let i = 0; i < trace.length; i++) {\n\t\t\t\t\taddFn(\n\t\t\t\t\t\t`${reporter}Child${i}=${reporter}${i}.resolveChild?.shift()?.({` +\n\t\t\t\t\t\t\t`id,` +\n\t\t\t\t\t\t\t`event:'${event}',` +\n\t\t\t\t\t\t\t`name:'${name}',` +\n\t\t\t\t\t\t\t`begin:performance.now()` +\n\t\t\t\t\t\t\t`})\\n`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn (binding?: string) => {\n\t\t\t\t\tfor (let i = 0; i < trace.length; i++) {\n\t\t\t\t\t\tif (binding)\n\t\t\t\t\t\t\t// Don't report error because HTTP response is expected and not an actual error to look for\n\t\t\t\t\t\t\t// if (${binding} instanceof ElysiaCustomStatusResponse) {\n\t\t\t\t\t\t\t//     ${reporter}Child${i}?.(${binding}.error)\n\t\t\t\t\t\t\t//     ${reporter}Child${i}?.()\\n\n\t\t\t\t\t\t\t// } else\n\t\t\t\t\t\t\taddFn(\n\t\t\t\t\t\t\t\t`if(${binding} instanceof Error){` +\n\t\t\t\t\t\t\t\t\t`${reporter}Child${i}?.(${binding}) ` +\n\t\t\t\t\t\t\t\t\t`}else{` +\n\t\t\t\t\t\t\t\t\t`${reporter}Child${i}?.()` +\n\t\t\t\t\t\t\t\t\t'}'\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\telse addFn(`${reporter}Child${i}?.()\\n`)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nconst composeCleaner = ({\n\tschema,\n\tname,\n\ttype,\n\ttypeAlias = type,\n\tnormalize,\n\tignoreTryCatch = false\n}: {\n\tschema: ElysiaTypeCheck<any>\n\tname: string\n\ttype: keyof SchemaValidator\n\ttypeAlias?: string\n\tnormalize: ElysiaConfig<''>['normalize']\n\tignoreTryCatch?: boolean\n}) => {\n\tif (!normalize || !schema.Clean) return ''\n\n\tif (normalize === true || normalize === 'exactMirror') {\n\t\tif (ignoreTryCatch)\n\t\t\treturn `${name}=validator.${typeAlias}.Clean(${name})\\n`\n\n\t\treturn (\n\t\t\t`try{` +\n\t\t\t`${name}=validator.${typeAlias}.Clean(${name})\\n` +\n\t\t\t`}catch{}`\n\t\t)\n\t}\n\n\tif (normalize === 'typebox')\n\t\treturn `${name}=validator.${typeAlias}.Clean(${name})\\n`\n\n\treturn ''\n}\n\nconst composeValidationFactory = ({\n\tinjectResponse = '',\n\tnormalize = false,\n\tvalidator,\n\tencodeSchema = false,\n\tisStaticResponse = false,\n\thasSanitize = false,\n\tallowUnsafeValidationDetails = false\n}: {\n\tinjectResponse?: string\n\tnormalize?: ElysiaConfig<''>['normalize']\n\tvalidator: SchemaValidator\n\tencodeSchema?: boolean\n\tisStaticResponse?: boolean\n\thasSanitize?: boolean\n\tallowUnsafeValidationDetails?: boolean\n}) => ({\n\tvalidate: (type: string, value = `c.${type}`, error?: string) =>\n\t\t`c.set.status=422;throw new ValidationError('${type}',validator.${type},${value},${allowUnsafeValidationDetails}${error ? ',' + error : ''})`,\n\tresponse: (name = 'r') => {\n\t\tif (isStaticResponse || !validator.response) return ''\n\n\t\tlet code = injectResponse + '\\n'\n\n\t\tcode +=\n\t\t\t`if(${name} instanceof ElysiaCustomStatusResponse){` +\n\t\t\t`c.set.status=${name}.code\\n` +\n\t\t\t`${name}=${name}.response` +\n\t\t\t`}` +\n\t\t\t`if(${name} instanceof Response === false && typeof ${name}?.next !== 'function' && !(${name} instanceof ReadableStream))` +\n\t\t\t`switch(c.set.status){`\n\n\t\tfor (const [status, value] of Object.entries(validator.response!)) {\n\t\t\tcode += `\\ncase ${status}:\\n`\n\n\t\t\tif (value.provider === 'standard') {\n\t\t\t\tcode +=\n\t\t\t\t\t`let vare${status}=validator.response[${status}].Check(${name})\\n` +\n\t\t\t\t\t`if(vare${status} instanceof Promise)vare${status}=await vare${status}\\n` +\n\t\t\t\t\t`if(vare${status}.issues)` +\n\t\t\t\t\t`throw new ValidationError('response',validator.response[${status}],${name},${allowUnsafeValidationDetails},vare${status}.issues)\\n` +\n\t\t\t\t\t`${name}=vare${status}.value\\n` +\n\t\t\t\t\t`c.set.status=${status}\\n` +\n\t\t\t\t\t'break\\n'\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlet noValidate = value.schema?.noValidate === true\n\n\t\t\tif (!noValidate && value.schema?.$ref && value.schema?.$defs) {\n\t\t\t\tconst refKey = value.schema.$ref\n\t\t\t\tconst defKey =\n\t\t\t\t\ttypeof refKey === 'string' && refKey.includes('/')\n\t\t\t\t\t\t? refKey.split('/').pop()!\n\t\t\t\t\t\t: refKey\n\t\t\t\tconst referencedDef =\n\t\t\t\t\tvalue.schema.$defs[\n\t\t\t\t\t\tdefKey as keyof typeof value.schema.$defs\n\t\t\t\t\t]\n\n\t\t\t\tif (referencedDef?.noValidate === true) {\n\t\t\t\t\tnoValidate = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst appliedCleaner = noValidate || hasSanitize\n\n\t\t\tconst clean = ({ ignoreTryCatch = false } = {}) =>\n\t\t\t\tcomposeCleaner({\n\t\t\t\t\tname,\n\t\t\t\t\tschema: value,\n\t\t\t\t\ttype: 'response',\n\t\t\t\t\ttypeAlias: `response[${status}]`,\n\t\t\t\t\tnormalize,\n\t\t\t\t\tignoreTryCatch\n\t\t\t\t})\n\n\t\t\tif (appliedCleaner) code += clean()\n\n\t\t\tconst applyErrorCleaner =\n\t\t\t\t!appliedCleaner && normalize && !noValidate\n\n\t\t\t// Encode call TypeCheck.Check internally\n\t\t\tif (encodeSchema && value.hasTransform && !noValidate) {\n\t\t\t\tcode +=\n\t\t\t\t\t`try{` +\n\t\t\t\t\t`${name}=validator.response[${status}].Encode(${name})\\n`\n\n\t\t\t\tif (!appliedCleaner) code += clean({ ignoreTryCatch: true })\n\n\t\t\t\tcode +=\n\t\t\t\t\t`c.set.status=${status}` +\n\t\t\t\t\t`}catch{` +\n\t\t\t\t\t(applyErrorCleaner\n\t\t\t\t\t\t? `try{\\n` +\n\t\t\t\t\t\t\tclean({ ignoreTryCatch: true }) +\n\t\t\t\t\t\t\t`${name}=validator.response[${status}].Encode(${name})\\n` +\n\t\t\t\t\t\t\t`}catch{` +\n\t\t\t\t\t\t\t`throw new ValidationError('response',validator.response[${status}],${name},${allowUnsafeValidationDetails})` +\n\t\t\t\t\t\t\t`}`\n\t\t\t\t\t\t: `throw new ValidationError('response',validator.response[${status}],${name},${allowUnsafeValidationDetails})`) +\n\t\t\t\t\t`}`\n\t\t\t} else {\n\t\t\t\tif (!appliedCleaner) code += clean()\n\n\t\t\t\tif (!noValidate)\n\t\t\t\t\tcode +=\n\t\t\t\t\t\t`if(validator.response[${status}].Check(${name})===false)` +\n\t\t\t\t\t\t`throw new ValidationError('response',validator.response[${status}],${name},${allowUnsafeValidationDetails})\\n` +\n\t\t\t\t\t\t`c.set.status=${status}\\n`\n\t\t\t}\n\n\t\t\tcode += 'break\\n'\n\t\t}\n\n\t\treturn code + '}'\n\t}\n})\n\nconst isAsyncName = (v: Function | HookContainer) => {\n\t// @ts-ignore\n\tconst fn = v?.fn ?? v\n\n\treturn fn.constructor.name === 'AsyncFunction'\n}\n\nconst matchResponseClone = /=>\\s?response\\.clone\\(/\nconst matchFnReturn = /(?:return|=>)\\s?\\S+\\(|a(?:sync|wait)/\n\nexport const isAsync = (v: Function | HookContainer) => {\n\tconst isObject = typeof v === 'object'\n\tif (isObject && v.isAsync !== undefined) return v.isAsync\n\n\tconst fn = isObject ? v.fn : v\n\t// Check for both AsyncFunction and AsyncGeneratorFunction\n\t// AsyncGeneratorFunction needs to be treated as async because generator.next()\n\t// returns a Promise that may reject (e.g., when throwing from the generator)\n\tif (\n\t\tfn.constructor.name === 'AsyncFunction' ||\n\t\tfn.constructor.name === 'AsyncGeneratorFunction'\n\t)\n\t\treturn true\n\n\tconst literal: string = fn.toString()\n\n\tif (matchResponseClone.test(literal)) {\n\t\tif (isObject) v.isAsync = false\n\n\t\treturn false\n\t}\n\n\tconst result = matchFnReturn.test(literal)\n\tif (isObject) v.isAsync = result\n\n\treturn result\n}\n\nconst hasReturn = (v: string | HookContainer<any> | Function) => {\n\tconst isObject = typeof v === 'object'\n\n\tif (isObject && v.hasReturn !== undefined) return v.hasReturn\n\n\tconst fnLiteral = isObject\n\t\t? v.fn.toString()\n\t\t: typeof v === 'string'\n\t\t\t? v.toString()\n\t\t\t: v.toString()\n\n\tconst parenthesisEnd = fnLiteral.indexOf(')')\n\n\t// Check for arrow function expression (direct return without braces)\n\t// Handle both `) => x` and `)=>x` formats (with or without spaces)\n\tconst arrowIndex = fnLiteral.indexOf('=>', parenthesisEnd)\n\n\tif (arrowIndex !== -1) {\n\t\t// Skip any whitespace after `=>` (space, tab, newline, carriage return)\n\t\tlet afterArrow = arrowIndex + 2\n\t\tlet charCode: number\n\t\twhile (\n\t\t\tafterArrow < fnLiteral.length &&\n\t\t\t((charCode = fnLiteral.charCodeAt(afterArrow)) === 32 || // space\n\t\t\t\tcharCode === 9 || // tab\n\t\t\t\tcharCode === 10 || // newline\n\t\t\t\tcharCode === 13) // carriage return\n\t\t) {\n\t\t\tafterArrow++\n\t\t}\n\n\t\t// If the first non-whitespace char after `=>` is not `{`, it's a direct return\n\t\tif (\n\t\t\tafterArrow < fnLiteral.length &&\n\t\t\tfnLiteral.charCodeAt(afterArrow) !== 123\n\t\t) {\n\t\t\tif (isObject) v.hasReturn = true\n\n\t\t\treturn true\n\t\t}\n\t}\n\n\tconst result = fnLiteral.includes('return')\n\n\tif (isObject) v.hasReturn = result\n\n\treturn result\n}\n\nconst isGenerator = (v: Function | HookContainer) => {\n\t// @ts-ignore\n\tconst fn = v?.fn ?? v\n\n\treturn (\n\t\tfn.constructor.name === 'AsyncGeneratorFunction' ||\n\t\tfn.constructor.name === 'GeneratorFunction'\n\t)\n}\n\nconst coerceTransformDecodeError = (\n\tfnLiteral: string,\n\ttype: string,\n\tallowUnsafeValidationDetails = false,\n\tvalue = `c.${type}`\n) =>\n\t`try{${fnLiteral}}catch(error){` +\n\t`if(error.constructor.name === 'TransformDecodeError'){` +\n\t`c.set.status=422\\n` +\n\t`throw error.error ?? new ValidationError('${type}',validator.${type},${value},${allowUnsafeValidationDetails})}` +\n\t`}`\n\nconst setImmediateFn = hasSetImmediate\n\t? 'setImmediate'\n\t: 'Promise.resolve().then'\n\nexport const composeHandler = ({\n\tapp,\n\tpath,\n\tmethod,\n\thooks,\n\tvalidator,\n\thandler,\n\tallowMeta = false,\n\tinference\n}: {\n\tapp: AnyElysia\n\tpath: string\n\tmethod: string\n\thooks: Partial<LifeCycleStore>\n\tvalidator: SchemaValidator\n\thandler: unknown | Handler<any, any>\n\tallowMeta?: boolean\n\tinference: Sucrose.Inference\n}): ComposedHandler => {\n\tconst adapter = app['~adapter'].composeHandler\n\tconst adapterHandler = app['~adapter'].handler\n\tconst isHandleFn = typeof handler === 'function'\n\n\tif (!isHandleFn) {\n\t\thandler = adapterHandler.mapResponse(handler, {\n\t\t\t// @ts-expect-error private property\n\t\t\theaders: app.setHeaders ?? {}\n\t\t})\n\n\t\tconst isResponse =\n\t\t\thandler instanceof Response ||\n\t\t\t// @ts-ignore If it's not instanceof Response, it might be a polyfill (only on Node)\n\t\t\t(handler?.constructor?.name === 'Response' &&\n\t\t\t\ttypeof (handler as Response)?.clone === 'function')\n\n\t\tif (\n\t\t\thooks.parse?.length &&\n\t\t\thooks.transform?.length &&\n\t\t\thooks.beforeHandle?.length &&\n\t\t\thooks.afterHandle?.length\n\t\t) {\n\t\t\tif (isResponse)\n\t\t\t\treturn Function(\n\t\t\t\t\t'a',\n\t\t\t\t\t'\"use strict\";\\n' + `return function(){return a.clone()}`\n\t\t\t\t)(handler)\n\n\t\t\treturn Function(\n\t\t\t\t'a',\n\t\t\t\t'\"use strict\";\\n' + 'return function(){return a}'\n\t\t\t)(handler)\n\t\t}\n\n\t\tif (isResponse) {\n\t\t\tconst response = handler as Response\n\n\t\t\thandler = () => response.clone()\n\t\t}\n\t}\n\n\tconst handle = isHandleFn ? `handler(c)` : `handler`\n\n\tconst hasTrace = !!hooks.trace?.length\n\tlet fnLiteral = ''\n\n\tinference = sucrose(\n\t\tObject.assign({ handler: handler as any }, hooks),\n\t\tinference,\n\t\tapp.config.sucrose\n\t)\n\n\tif (adapter.declare) {\n\t\tconst literal = adapter.declare(inference)\n\n\t\tif (literal) fnLiteral += literal\n\t}\n\n\tif (inference.server)\n\t\tfnLiteral +=\n\t\t\t\"Object.defineProperty(c,'server',{\" +\n\t\t\t'get:function(){return getServer()}' +\n\t\t\t'})\\n'\n\n\tvalidator.createBody?.()\n\tvalidator.createQuery?.()\n\tvalidator.createHeaders?.()\n\tvalidator.createParams?.()\n\tvalidator.createCookie?.()\n\tvalidator.createResponse?.()\n\n\tconst hasValidation =\n\t\t!!validator.body ||\n\t\t!!validator.headers ||\n\t\t!!validator.params ||\n\t\t!!validator.query ||\n\t\t!!validator.cookie ||\n\t\t!!validator.response\n\n\tconst hasQuery = inference.query || !!validator.query\n\n\tconst requestNoBody =\n\t\thooks.parse?.length === 1 &&\n\t\t// @ts-expect-error\n\t\thooks.parse[0].fn === 'none'\n\n\tconst hasBody =\n\t\tmethod !== '' &&\n\t\tmethod !== 'GET' &&\n\t\tmethod !== 'HEAD' &&\n\t\t(inference.body || !!validator.body || !!hooks.parse?.length) &&\n\t\t!requestNoBody\n\n\t// @ts-expect-error private\n\tconst defaultHeaders = app.setHeaders\n\tconst hasDefaultHeaders =\n\t\tdefaultHeaders && !!Object.keys(defaultHeaders).length\n\n\t// ? defaultHeaders doesn't imply that user will use headers in handler\n\tconst hasHeaders =\n\t\tinference.headers ||\n\t\t!!validator.headers ||\n\t\t(adapter.preferWebstandardHeaders !== true && inference.body)\n\n\tconst hasCookie = inference.cookie || !!validator.cookie\n\n\tconst cookieMeta: {\n\t\tsecrets?: string | string[]\n\t\tsign: string[] | true\n\t\tproperties: { [x: string]: Object }\n\t} = validator.cookie?.config\n\t\t? mergeCookie(validator?.cookie?.config, app.config.cookie as any)\n\t\t: app.config.cookie\n\n\tlet _encodeCookie = ''\n\tconst encodeCookie = () => {\n\t\tif (_encodeCookie) return _encodeCookie\n\n\t\tif (cookieMeta?.sign) {\n\t\t\tif (cookieMeta.secrets === '')\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`cookie secret can't be an empty string at (${method}) ${path}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcause: `(${method}) ${path}`\n\t\t\t\t\t}\n\t\t\t\t)\n\n\t\t\tif (!cookieMeta.secrets)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`cookie secret must be defined (${method}) ${path}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcause: `(${method}) ${path}`\n\t\t\t\t\t}\n\t\t\t\t)\n\n\t\t\tconst secret = !cookieMeta.secrets\n\t\t\t\t? undefined\n\t\t\t\t: typeof cookieMeta.secrets === 'string'\n\t\t\t\t\t? cookieMeta.secrets\n\t\t\t\t\t: cookieMeta.secrets[0]\n\n\t\t\t_encodeCookie +=\n\t\t\t\t'const _setCookie = c.set.cookie\\n' + 'if(_setCookie){'\n\n\t\t\tif (cookieMeta.sign === true)\n\t\t\t\t_encodeCookie +=\n\t\t\t\t\t'for(const [key, cookie] of Object.entries(_setCookie)){' +\n\t\t\t\t\t`c.set.cookie[key].value=await signCookie(cookie.value,${!secret ? 'undefined' : JSON.stringify(secret)})` +\n\t\t\t\t\t'}'\n\t\t\telse {\n\t\t\t\tif (typeof cookieMeta.sign === 'string')\n\t\t\t\t\tcookieMeta.sign = [cookieMeta.sign]\n\n\t\t\t\tfor (const name of cookieMeta.sign)\n\t\t\t\t\t_encodeCookie +=\n\t\t\t\t\t\t`if(_setCookie[${JSON.stringify(name)}]?.value)` +\n\t\t\t\t\t\t`c.set.cookie[${JSON.stringify(name)}].value=await signCookie(_setCookie[${JSON.stringify(name)}].value,${!secret ? 'undefined' : JSON.stringify(secret)})\\n`\n\t\t\t}\n\n\t\t\t_encodeCookie += '}\\n'\n\t\t}\n\n\t\treturn _encodeCookie\n\t}\n\n\tconst normalize = app.config.normalize\n\tconst encodeSchema = app.config.encodeSchema\n\tconst allowUnsafeValidationDetails = app.config.allowUnsafeValidationDetails\n\n\tconst validation = composeValidationFactory({\n\t\tnormalize,\n\t\tvalidator,\n\t\tencodeSchema,\n\t\tisStaticResponse: handler instanceof Response,\n\t\thasSanitize: !!app.config.sanitize,\n\t\tallowUnsafeValidationDetails\n\t})\n\n\tif (hasHeaders) fnLiteral += adapter.headers\n\n\tif (hasTrace) fnLiteral += 'const id=c[ELYSIA_REQUEST_ID]\\n'\n\n\tconst report = createReport({\n\t\ttrace: hooks.trace,\n\t\taddFn: (word) => {\n\t\t\tfnLiteral += word\n\t\t}\n\t})\n\n\tfnLiteral += 'try{'\n\n\tif (hasCookie) {\n\t\tconst get = (name: keyof CookieOptions, defaultValue?: unknown) => {\n\t\t\t// @ts-ignore\n\t\t\tconst value = cookieMeta?.[name] ?? defaultValue\n\n\t\t\tif (value === undefined) return ''\n\n\t\t\tif (!value)\n\t\t\t\treturn typeof defaultValue === 'string'\n\t\t\t\t\t? `${name}:\"${defaultValue}\",`\n\t\t\t\t\t: `${name}:${defaultValue},`\n\n\t\t\tif (typeof value === 'string')\n\t\t\t\treturn `${name}:${JSON.stringify(value)},`\n\t\t\tif (value instanceof Date)\n\t\t\t\treturn `${name}: new Date(${value.getTime()}),`\n\n\t\t\treturn `${name}:${value},`\n\t\t}\n\n\t\tconst options = cookieMeta\n\t\t\t? `{secrets:${\n\t\t\t\t\tcookieMeta.secrets !== undefined && cookieMeta.secrets !== null\n\t\t\t\t\t\t? typeof cookieMeta.secrets === 'string'\n\t\t\t\t\t\t\t? JSON.stringify(cookieMeta.secrets)\n\t\t\t\t\t\t\t: '[' +\n\t\t\t\t\t\t\t\tcookieMeta.secrets\n\t\t\t\t\t\t\t\t\t.map((x) => JSON.stringify(x))\n\t\t\t\t\t\t\t\t\t.join(',') +\n\t\t\t\t\t\t\t\t']'\n\t\t\t\t\t\t: 'undefined'\n\t\t\t\t},` +\n\t\t\t\t`sign:${\n\t\t\t\t\tcookieMeta.sign === true\n\t\t\t\t\t\t? true\n\t\t\t\t\t\t: cookieMeta.sign !== undefined\n\t\t\t\t\t\t\t? typeof cookieMeta.sign === 'string'\n\t\t\t\t\t\t\t\t? JSON.stringify(cookieMeta.sign)\n\t\t\t\t\t\t\t\t: '[' +\n\t\t\t\t\t\t\t\t\tcookieMeta.sign\n\t\t\t\t\t\t\t\t\t\t.map((x) => JSON.stringify(x))\n\t\t\t\t\t\t\t\t\t\t.join(',') +\n\t\t\t\t\t\t\t\t\t']'\n\t\t\t\t\t\t\t: 'undefined'\n\t\t\t\t},` +\n\t\t\t\tget('domain') +\n\t\t\t\tget('expires') +\n\t\t\t\tget('httpOnly') +\n\t\t\t\tget('maxAge') +\n\t\t\t\tget('path', '/') +\n\t\t\t\tget('priority') +\n\t\t\t\tget('sameSite') +\n\t\t\t\tget('secure') +\n\t\t\t\t'}'\n\t\t\t: 'undefined'\n\n\t\tif (hasHeaders)\n\t\t\tfnLiteral += `\\nc.cookie=await parseCookie(c.set,c.headers.cookie,${options})\\n`\n\t\telse\n\t\t\tfnLiteral += `\\nc.cookie=await parseCookie(c.set,c.request.headers.get('cookie'),${options})\\n`\n\t}\n\n\tif (hasQuery) {\n\t\tlet arrayProperties: Record<string, true> = {}\n\t\tlet objectProperties: Record<string, true> = {}\n\t\tlet hasArrayProperty = false\n\t\tlet hasObjectProperty = false\n\n\t\tif (validator.query?.schema) {\n\t\t\tconst schema = unwrapImportSchema(validator.query?.schema)\n\t\t\tconst properties = getSchemaProperties(schema)\n\n\t\t\tif (properties) {\n\t\t\t\tfor (const [key, value] of Object.entries(properties)) {\n\t\t\t\t\tif (hasElysiaMeta('ArrayQuery', value as TSchema)) {\n\t\t\t\t\t\tarrayProperties[key] = true\n\t\t\t\t\t\thasArrayProperty = true\n\t\t\t\t\t}\n\n\t\t\t\t\tif (hasElysiaMeta('ObjectString', value as TSchema)) {\n\t\t\t\t\t\tobjectProperties[key] = true\n\t\t\t\t\t\thasObjectProperty = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfnLiteral +=\n\t\t\t'if(c.qi===-1){' +\n\t\t\t'c.query=Object.create(null)' +\n\t\t\t'}else{' +\n\t\t\t`c.query=parseQueryFromURL(c.url,c.qi+1${\n\t\t\t\t//\n\t\t\t\thasArrayProperty\n\t\t\t\t\t? ',' + JSON.stringify(arrayProperties)\n\t\t\t\t\t: hasObjectProperty\n\t\t\t\t\t\t? ',undefined'\n\t\t\t\t\t\t: ''\n\t\t\t}${\n\t\t\t\t//\n\t\t\t\thasObjectProperty ? ',' + JSON.stringify(objectProperties) : ''\n\t\t\t})` +\n\t\t\t'}'\n\t}\n\n\tconst isAsyncHandler = typeof handler === 'function' && isAsync(handler)\n\n\tconst saveResponse =\n\t\thasTrace || hooks.afterResponse?.length\n\t\t\t? 'c.response=c.responseValue= '\n\t\t\t: ''\n\n\tconst responseKeys = Object.keys(validator.response ?? {})\n\tconst hasMultipleResponses = responseKeys.length > 1\n\tconst hasSingle200 =\n\t\tresponseKeys.length === 0 ||\n\t\t(responseKeys.length === 1 && responseKeys[0] === '200')\n\n\tconst maybeAsync =\n\t\thasCookie ||\n\t\thasBody ||\n\t\tisAsyncHandler ||\n\t\t!!hooks.parse?.length ||\n\t\t!!hooks.afterHandle?.some(isAsync) ||\n\t\t!!hooks.beforeHandle?.some(isAsync) ||\n\t\t!!hooks.transform?.some(isAsync) ||\n\t\t!!hooks.mapResponse?.some(isAsync) ||\n\t\tvalidator.body?.provider === 'standard' ||\n\t\tvalidator.headers?.provider === 'standard' ||\n\t\tvalidator.query?.provider === 'standard' ||\n\t\tvalidator.params?.provider === 'standard' ||\n\t\tvalidator.cookie?.provider === 'standard' ||\n\t\tObject.values(validator.response ?? {}).find(\n\t\t\t(x) => x.provider === 'standard'\n\t\t)\n\n\tconst maybeStream =\n\t\t(typeof handler === 'function' ? isGenerator(handler as any) : false) ||\n\t\t!!hooks.beforeHandle?.some(isGenerator) ||\n\t\t!!hooks.afterHandle?.some(isGenerator) ||\n\t\t!!hooks.transform?.some(isGenerator)\n\n\tconst hasSet =\n\t\tinference.cookie ||\n\t\tinference.set ||\n\t\thasHeaders ||\n\t\thasTrace ||\n\t\thasMultipleResponses ||\n\t\t!hasSingle200 ||\n\t\t(isHandleFn && hasDefaultHeaders) ||\n\t\tmaybeStream\n\n\tlet _afterResponse: string | undefined\n\n\tconst afterResponse = (hasStream = true) => {\n\t\tif (_afterResponse !== undefined) return _afterResponse\n\n\t\tif (!hooks.afterResponse?.length && !hasTrace) return ''\n\n\t\tlet afterResponse = ''\n\n\t\tafterResponse +=\n\t\t\t`\\n${setImmediateFn}(async()=>{` +\n\t\t\t`if(c.responseValue){` +\n\t\t\t`if(c.responseValue instanceof ElysiaCustomStatusResponse) c.set.status=c.responseValue.code\\n` +\n\t\t\t(hasStream\n\t\t\t\t? `if(typeof afterHandlerStreamListener!=='undefined')for await(const v of afterHandlerStreamListener){}\\n`\n\t\t\t\t: '') +\n\t\t\t`}\\n`\n\n\t\tconst reporter = createReport({\n\t\t\ttrace: hooks.trace,\n\t\t\taddFn: (word) => {\n\t\t\t\tafterResponse += word\n\t\t\t}\n\t\t})('afterResponse', {\n\t\t\ttotal: hooks.afterResponse?.length\n\t\t})\n\n\t\tif (hooks.afterResponse?.length && hooks.afterResponse) {\n\t\t\tfor (let i = 0; i < hooks.afterResponse.length; i++) {\n\t\t\t\tconst endUnit = reporter.resolveChild(\n\t\t\t\t\thooks.afterResponse[i].fn.name\n\t\t\t\t)\n\t\t\t\tconst prefix = isAsync(hooks.afterResponse[i]) ? 'await ' : ''\n\t\t\t\tafterResponse += `\\n${prefix}e.afterResponse[${i}](c)\\n`\n\t\t\t\tendUnit()\n\t\t\t}\n\t\t}\n\n\t\treporter.resolve()\n\n\t\tafterResponse += '})\\n'\n\n\t\treturn (_afterResponse = afterResponse)\n\t}\n\n\tconst mapResponse = (r = 'r') => {\n\t\tconst after = afterResponse()\n\t\t// When maybeStream is true, mapResponse may return a Promise (from handleStream)\n\t\t// that can reject if the generator throws. We need to await it so the try-catch\n\t\t// can properly catch the rejection and route it to error handling.\n\t\t// Only add await if the function is async (maybeAsync), otherwise it would be a syntax error.\n\t\tconst awaitStream = maybeStream && maybeAsync ? 'await ' : ''\n\t\tconst response = `${awaitStream}${hasSet ? 'mapResponse' : 'mapCompactResponse'}(${saveResponse}${r}${hasSet ? ',c.set' : ''}${mapResponseContext})\\n`\n\n\t\tif (!after) return `return ${response}`\n\n\t\treturn `const _res=${response}` + after + `return _res`\n\t}\n\n\tconst mapResponseContext = adapter.mapResponseContext\n\t\t? `,${adapter.mapResponseContext}`\n\t\t: ''\n\n\tif (hasTrace || inference.route) fnLiteral += `c.route=\\`${path}\\`\\n`\n\tif (hasTrace || hooks.afterResponse?.length)\n\t\tfnLiteral += 'let afterHandlerStreamListener\\n'\n\n\tconst parseReporter = report('parse', {\n\t\ttotal: hooks.parse?.length\n\t})\n\n\tif (hasBody) {\n\t\tconst hasBodyInference =\n\t\t\t!!hooks.parse?.length || inference.body || validator.body\n\n\t\tif (adapter.parser.declare) fnLiteral += adapter.parser.declare\n\n\t\tfnLiteral += '\\ntry{'\n\n\t\tlet parser: string | undefined =\n\t\t\ttypeof hooks.parse === 'string'\n\t\t\t\t? hooks.parse\n\t\t\t\t: Array.isArray(hooks.parse) && hooks.parse.length === 1\n\t\t\t\t\t? typeof hooks.parse[0] === 'string'\n\t\t\t\t\t\t? hooks.parse[0]\n\t\t\t\t\t\t: typeof hooks.parse[0].fn === 'string'\n\t\t\t\t\t\t\t? hooks.parse[0].fn\n\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t: undefined\n\n\t\tif (!parser && validator.body && !hooks.parse?.length) {\n\t\t\tconst schema = validator.body.schema\n\t\t\tif (\n\t\t\t\tschema &&\n\t\t\t\tschema.anyOf &&\n\t\t\t\tschema[Kind] === 'Union' &&\n\t\t\t\tschema.anyOf?.length === 2 &&\n\t\t\t\tschema.anyOf?.find((x: TAnySchema) => x[Kind] === 'ElysiaForm')\n\t\t\t)\n\t\t\t\tparser = 'formdata'\n\t\t}\n\n\t\tif (parser && defaultParsers.includes(parser)) {\n\t\t\tconst reporter = report('parse', {\n\t\t\t\ttotal: hooks.parse?.length\n\t\t\t})\n\n\t\t\tconst isOptionalBody = !!validator.body?.isOptional\n\n\t\t\tswitch (parser) {\n\t\t\t\tcase 'json':\n\t\t\t\tcase 'application/json':\n\t\t\t\t\tfnLiteral += adapter.parser.json(isOptionalBody)\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'text':\n\t\t\t\tcase 'text/plain':\n\t\t\t\t\tfnLiteral += adapter.parser.text(isOptionalBody)\n\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'urlencoded':\n\t\t\t\tcase 'application/x-www-form-urlencoded':\n\t\t\t\t\tfnLiteral += adapter.parser.urlencoded(isOptionalBody)\n\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'arrayBuffer':\n\t\t\t\tcase 'application/octet-stream':\n\t\t\t\t\tfnLiteral += adapter.parser.arrayBuffer(isOptionalBody)\n\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'formdata':\n\t\t\t\tcase 'multipart/form-data':\n\t\t\t\t\tfnLiteral += adapter.parser.formData(isOptionalBody)\n\t\t\t\t\tbreak\n\n\t\t\t\tdefault:\n\t\t\t\t\tif (parser in app['~parser']) {\n\t\t\t\t\t\tfnLiteral += hasHeaders\n\t\t\t\t\t\t\t? `let contentType = c.headers['content-type']`\n\t\t\t\t\t\t\t: `let contentType = c.request.headers.get('content-type')`\n\n\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t`\\nif(contentType){` +\n\t\t\t\t\t\t\t`const index=contentType.indexOf(';')\\n` +\n\t\t\t\t\t\t\t`if(index!==-1)contentType=contentType.substring(0,index)}\\n` +\n\t\t\t\t\t\t\t`else{contentType=''}` +\n\t\t\t\t\t\t\t`c.contentType=contentType\\n` +\n\t\t\t\t\t\t\t`let result=parser['${parser}'](c, contentType)\\n` +\n\t\t\t\t\t\t\t`if(result instanceof Promise)result=await result\\n` +\n\t\t\t\t\t\t\t`if(result instanceof ElysiaCustomStatusResponse)throw result\\n` +\n\t\t\t\t\t\t\t`if(result!==undefined)c.body=result\\n` +\n\t\t\t\t\t\t\t'delete c.contentType\\n'\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treporter.resolve()\n\t\t} else if (hasBodyInference) {\n\t\t\tfnLiteral += '\\n'\n\n\t\t\tfnLiteral += 'let contentType\\n' + 'if(c.request.body)'\n\t\t\tfnLiteral += hasHeaders\n\t\t\t\t? `contentType=c.headers['content-type']\\n`\n\t\t\t\t: `contentType=c.request.headers.get('content-type')\\n`\n\n\t\t\tlet hasDefaultParser = false\n\t\t\tif (hooks.parse?.length)\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`if(contentType){\\n` +\n\t\t\t\t\t`const index=contentType.indexOf(';')\\n` +\n\t\t\t\t\t`\\nif(index!==-1)contentType=contentType.substring(0,index)` +\n\t\t\t\t\t`}else{contentType=''}` +\n\t\t\t\t\t`let used=false\\n` +\n\t\t\t\t\t`c.contentType=contentType\\n`\n\t\t\telse {\n\t\t\t\thasDefaultParser = true\n\t\t\t\tconst isOptionalBody = !!validator.body?.isOptional\n\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`if(contentType)` +\n\t\t\t\t\t`switch(contentType.charCodeAt(12)){` +\n\t\t\t\t\t`\\ncase 106:` +\n\t\t\t\t\tadapter.parser.json(isOptionalBody) +\n\t\t\t\t\t'break' +\n\t\t\t\t\t`\\n` +\n\t\t\t\t\t`case 120:` +\n\t\t\t\t\tadapter.parser.urlencoded(isOptionalBody) +\n\t\t\t\t\t`break` +\n\t\t\t\t\t`\\n` +\n\t\t\t\t\t`case 111:` +\n\t\t\t\t\tadapter.parser.arrayBuffer(isOptionalBody) +\n\t\t\t\t\t`break` +\n\t\t\t\t\t`\\n` +\n\t\t\t\t\t`case 114:` +\n\t\t\t\t\tadapter.parser.formData(isOptionalBody) +\n\t\t\t\t\t`break` +\n\t\t\t\t\t`\\n` +\n\t\t\t\t\t`default:` +\n\t\t\t\t\t`if(contentType.charCodeAt(0)===116){` +\n\t\t\t\t\tadapter.parser.text(isOptionalBody) +\n\t\t\t\t\t`}` +\n\t\t\t\t\t`break\\n` +\n\t\t\t\t\t`}`\n\t\t\t}\n\n\t\t\tconst reporter = report('parse', {\n\t\t\t\ttotal: hooks.parse?.length\n\t\t\t})\n\n\t\t\tif (hooks.parse)\n\t\t\t\tfor (let i = 0; i < hooks.parse.length; i++) {\n\t\t\t\t\tconst name = `bo${i}`\n\t\t\t\t\tif (i !== 0) fnLiteral += `\\nif(!used){`\n\n\t\t\t\t\tif (typeof hooks.parse[i].fn === 'string') {\n\t\t\t\t\t\tconst endUnit = reporter.resolveChild(\n\t\t\t\t\t\t\thooks.parse[i].fn as unknown as string\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\tconst isOptionalBody = !!validator.body?.isOptional\n\n\t\t\t\t\t\tswitch (hooks.parse[i].fn as unknown as string) {\n\t\t\t\t\t\t\tcase 'json':\n\t\t\t\t\t\t\tcase 'application/json':\n\t\t\t\t\t\t\t\thasDefaultParser = true\n\t\t\t\t\t\t\t\tfnLiteral += adapter.parser.json(isOptionalBody)\n\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\tcase 'text':\n\t\t\t\t\t\t\tcase 'text/plain':\n\t\t\t\t\t\t\t\thasDefaultParser = true\n\t\t\t\t\t\t\t\tfnLiteral += adapter.parser.text(isOptionalBody)\n\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\tcase 'urlencoded':\n\t\t\t\t\t\t\tcase 'application/x-www-form-urlencoded':\n\t\t\t\t\t\t\t\thasDefaultParser = true\n\t\t\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t\t\tadapter.parser.urlencoded(isOptionalBody)\n\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\tcase 'arrayBuffer':\n\t\t\t\t\t\t\tcase 'application/octet-stream':\n\t\t\t\t\t\t\t\thasDefaultParser = true\n\t\t\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t\t\tadapter.parser.arrayBuffer(isOptionalBody)\n\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\tcase 'formdata':\n\t\t\t\t\t\t\tcase 'multipart/form-data':\n\t\t\t\t\t\t\t\thasDefaultParser = true\n\t\t\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t\t\tadapter.parser.formData(isOptionalBody)\n\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t\t\t`let ${name}=parser['${hooks.parse[i].fn}'](c,contentType)\\n` +\n\t\t\t\t\t\t\t\t\t`if(${name} instanceof Promise)${name}=await ${name}\\n` +\n\t\t\t\t\t\t\t\t\t`if(${name}!==undefined){c.body=${name};used=true;}\\n`\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tendUnit()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst endUnit = reporter.resolveChild(\n\t\t\t\t\t\t\thooks.parse[i].fn.name\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t`let ${name}=e.parse[${i}]\\n` +\n\t\t\t\t\t\t\t`${name}=${name}(c,contentType)\\n` +\n\t\t\t\t\t\t\t`if(${name} instanceof Promise)${name}=await ${name}\\n` +\n\t\t\t\t\t\t\t`if(${name}!==undefined){c.body=${name};used=true}`\n\n\t\t\t\t\t\tendUnit()\n\t\t\t\t\t}\n\n\t\t\t\t\tif (i !== 0) fnLiteral += `}`\n\n\t\t\t\t\tif (hasDefaultParser) break\n\t\t\t\t}\n\n\t\t\treporter.resolve()\n\n\t\t\tif (!hasDefaultParser) {\n\t\t\t\tconst isOptionalBody = !!validator.body?.isOptional\n\n\t\t\t\tif (hooks.parse?.length) fnLiteral += `\\nif(!used){\\n`\n\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`switch(contentType){` +\n\t\t\t\t\t`case 'application/json':\\n` +\n\t\t\t\t\tadapter.parser.json(isOptionalBody) +\n\t\t\t\t\t`break\\n` +\n\t\t\t\t\t`case 'text/plain':` +\n\t\t\t\t\tadapter.parser.text(isOptionalBody) +\n\t\t\t\t\t`break` +\n\t\t\t\t\t'\\n' +\n\t\t\t\t\t`case 'application/x-www-form-urlencoded':` +\n\t\t\t\t\tadapter.parser.urlencoded(isOptionalBody) +\n\t\t\t\t\t`break` +\n\t\t\t\t\t'\\n' +\n\t\t\t\t\t`case 'application/octet-stream':` +\n\t\t\t\t\tadapter.parser.arrayBuffer(isOptionalBody) +\n\t\t\t\t\t`break` +\n\t\t\t\t\t'\\n' +\n\t\t\t\t\t`case 'multipart/form-data':` +\n\t\t\t\t\tadapter.parser.formData(isOptionalBody) +\n\t\t\t\t\t`break` +\n\t\t\t\t\t'\\n'\n\n\t\t\t\tfor (const key of Object.keys(app['~parser']))\n\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t`case '${key}':` +\n\t\t\t\t\t\t`let bo${key}=parser['${key}'](c,contentType)\\n` +\n\t\t\t\t\t\t`if(bo${key} instanceof Promise)bo${key}=await bo${key}\\n` +\n\t\t\t\t\t\t`if(bo${key} instanceof ElysiaCustomStatusResponse){` +\n\t\t\t\t\t\tmapResponse(`bo${key}`) +\n\t\t\t\t\t\t`}` +\n\t\t\t\t\t\t`if(bo${key}!==undefined)c.body=bo${key}\\n` +\n\t\t\t\t\t\t`break` +\n\t\t\t\t\t\t'\\n'\n\n\t\t\t\tif (hooks.parse?.length) fnLiteral += '}'\n\n\t\t\t\tfnLiteral += '}'\n\t\t\t}\n\n\t\t\tif (hooks.parse?.length) fnLiteral += '\\ndelete c.contentType'\n\t\t}\n\n\t\tfnLiteral += '}catch(error){throw new ParseError(error)}'\n\t}\n\n\tparseReporter.resolve()\n\n\tif (hooks?.transform || hasTrace) {\n\t\tconst reporter = report('transform', {\n\t\t\ttotal: hooks.transform?.length\n\t\t})\n\n\t\tif (hooks.transform?.length) {\n\t\t\tfnLiteral += 'let transformed\\n'\n\n\t\t\tfor (let i = 0; i < hooks.transform.length; i++) {\n\t\t\t\tconst transform = hooks.transform[i]\n\n\t\t\t\tconst endUnit = reporter.resolveChild(transform.fn.name)\n\n\t\t\t\tfnLiteral += isAsync(transform)\n\t\t\t\t\t? `transformed=await e.transform[${i}](c)\\n`\n\t\t\t\t\t: `transformed=e.transform[${i}](c)\\n`\n\n\t\t\t\tif (transform.subType === 'mapDerive')\n\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t`if(transformed instanceof ElysiaCustomStatusResponse){` +\n\t\t\t\t\t\tmapResponse('transformed') +\n\t\t\t\t\t\t`}else{` +\n\t\t\t\t\t\t`transformed.request=c.request\\n` +\n\t\t\t\t\t\t`transformed.store=c.store\\n` +\n\t\t\t\t\t\t`transformed.qi=c.qi\\n` +\n\t\t\t\t\t\t`transformed.path=c.path\\n` +\n\t\t\t\t\t\t`transformed.url=c.url\\n` +\n\t\t\t\t\t\t`transformed.redirect=c.redirect\\n` +\n\t\t\t\t\t\t`transformed.set=c.set\\n` +\n\t\t\t\t\t\t`transformed.error=c.error\\n` +\n\t\t\t\t\t\t`c=transformed` +\n\t\t\t\t\t\t'}'\n\t\t\t\telse\n\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t`if(transformed instanceof ElysiaCustomStatusResponse){` +\n\t\t\t\t\t\tmapResponse('transformed') +\n\t\t\t\t\t\t`}else Object.assign(c,transformed)\\n`\n\n\t\t\t\tendUnit()\n\t\t\t}\n\t\t}\n\n\t\treporter.resolve()\n\t}\n\n\tconst fileUnions = <ElysiaTypeCheck<any>[]>[]\n\n\tif (validator) {\n\t\tif (validator.headers) {\n\t\t\tif (validator.headers.hasDefault)\n\t\t\t\tfor (const [key, value] of Object.entries(\n\t\t\t\t\tValue.Default(\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tvalidator.headers.schema,\n\t\t\t\t\t\t{}\n\t\t\t\t\t) as Object\n\t\t\t\t)) {\n\t\t\t\t\tconst parsed =\n\t\t\t\t\t\ttypeof value === 'object'\n\t\t\t\t\t\t\t? JSON.stringify(value)\n\t\t\t\t\t\t\t: typeof value === 'string'\n\t\t\t\t\t\t\t\t? `'${value}'`\n\t\t\t\t\t\t\t\t: value\n\n\t\t\t\t\tif (parsed !== undefined)\n\t\t\t\t\t\tfnLiteral += `c.headers['${key}']??=${parsed}\\n`\n\t\t\t\t}\n\n\t\t\tfnLiteral += composeCleaner({\n\t\t\t\tname: 'c.headers',\n\t\t\t\tschema: validator.headers,\n\t\t\t\ttype: 'headers',\n\t\t\t\tnormalize\n\t\t\t})\n\n\t\t\tif (validator.headers.isOptional)\n\t\t\t\tfnLiteral += `if(isNotEmpty(c.headers)){`\n\n\t\t\tif (validator.headers?.provider === 'standard') {\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`let vah=validator.headers.Check(c.headers)\\n` +\n\t\t\t\t\t`if(vah instanceof Promise)vah=await vah\\n` +\n\t\t\t\t\t`if(vah.issues){` +\n\t\t\t\t\tvalidation.validate('headers', undefined, 'vah.issues') +\n\t\t\t\t\t'}else{c.headers=vah.value}\\n'\n\t\t\t} else if (validator.headers?.schema?.noValidate !== true)\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`if(validator.headers.Check(c.headers) === false){` +\n\t\t\t\t\tvalidation.validate('headers') +\n\t\t\t\t\t'}'\n\n\t\t\tif (validator.headers.hasTransform)\n\t\t\t\tfnLiteral += coerceTransformDecodeError(\n\t\t\t\t\t`c.headers=validator.headers.Decode(c.headers)\\n`,\n\t\t\t\t\t'headers',\n\t\t\t\t\tallowUnsafeValidationDetails\n\t\t\t\t)\n\n\t\t\tif (validator.headers.isOptional) fnLiteral += '}'\n\t\t}\n\n\t\tif (validator.params) {\n\t\t\tif (validator.params.hasDefault)\n\t\t\t\tfor (const [key, value] of Object.entries(\n\t\t\t\t\tValue.Default(\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tvalidator.params.schema,\n\t\t\t\t\t\t{}\n\t\t\t\t\t) as Object\n\t\t\t\t)) {\n\t\t\t\t\tconst parsed =\n\t\t\t\t\t\ttypeof value === 'object'\n\t\t\t\t\t\t\t? JSON.stringify(value)\n\t\t\t\t\t\t\t: typeof value === 'string'\n\t\t\t\t\t\t\t\t? `'${value}'`\n\t\t\t\t\t\t\t\t: value\n\n\t\t\t\t\tif (parsed !== undefined)\n\t\t\t\t\t\tfnLiteral += `c.params['${key}']??=${parsed}\\n`\n\t\t\t\t}\n\n\t\t\tif (validator.params.provider === 'standard') {\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`let vap=validator.params.Check(c.params)\\n` +\n\t\t\t\t\t`if(vap instanceof Promise)vap=await vap\\n` +\n\t\t\t\t\t`if(vap.issues){` +\n\t\t\t\t\tvalidation.validate('params', undefined, 'vap.issues') +\n\t\t\t\t\t'}else{c.params=vap.value}\\n'\n\t\t\t} else if (validator.params?.schema?.noValidate !== true)\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`if(validator.params.Check(c.params)===false){` +\n\t\t\t\t\tvalidation.validate('params') +\n\t\t\t\t\t'}'\n\n\t\t\tif (validator.params.hasTransform)\n\t\t\t\tfnLiteral += coerceTransformDecodeError(\n\t\t\t\t\t`c.params=validator.params.Decode(c.params)\\n`,\n\t\t\t\t\t'params',\n\t\t\t\t\tallowUnsafeValidationDetails\n\t\t\t\t)\n\t\t}\n\n\t\tif (validator.query) {\n\t\t\tif (Kind in validator.query?.schema && validator.query.hasDefault)\n\t\t\t\tfor (const [key, value] of Object.entries(\n\t\t\t\t\tValue.Default(\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tvalidator.query.schema,\n\t\t\t\t\t\t{}\n\t\t\t\t\t) as Object\n\t\t\t\t)) {\n\t\t\t\t\tconst parsed =\n\t\t\t\t\t\ttypeof value === 'object'\n\t\t\t\t\t\t\t? JSON.stringify(value)\n\t\t\t\t\t\t\t: typeof value === 'string'\n\t\t\t\t\t\t\t\t? `'${value}'`\n\t\t\t\t\t\t\t\t: value\n\n\t\t\t\t\tif (parsed !== undefined)\n\t\t\t\t\t\tfnLiteral += `if(c.query['${key}']===undefined)c.query['${key}']=${parsed}\\n`\n\t\t\t\t}\n\n\t\t\tfnLiteral += composeCleaner({\n\t\t\t\tname: 'c.query',\n\t\t\t\tschema: validator.query,\n\t\t\t\ttype: 'query',\n\t\t\t\tnormalize\n\t\t\t})\n\n\t\t\tif (validator.query.isOptional)\n\t\t\t\tfnLiteral += `if(isNotEmpty(c.query)){`\n\n\t\t\tif (validator.query.provider === 'standard') {\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`let vaq=validator.query.Check(c.query)\\n` +\n\t\t\t\t\t`if(vaq instanceof Promise)vaq=await vaq\\n` +\n\t\t\t\t\t`if(vaq.issues){` +\n\t\t\t\t\tvalidation.validate('query', undefined, 'vaq.issues') +\n\t\t\t\t\t'}else{c.query=vaq.value}\\n'\n\t\t\t} else if (validator.query?.schema?.noValidate !== true)\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`if(validator.query.Check(c.query)===false){` +\n\t\t\t\t\tvalidation.validate('query') +\n\t\t\t\t\t`}`\n\n\t\t\tif (validator.query.hasTransform) {\n\t\t\t\t// TypeBox Decode only work with single Decode at the time\n\t\t\t\t// If we have multiple Decode, it will handle only the first one\n\t\t\t\t// For query, we decode it twice to ensure that it works\n\t\t\t\tfnLiteral += coerceTransformDecodeError(\n\t\t\t\t\t`c.query=validator.query.Decode(c.query)\\n`,\n\t\t\t\t\t'query',\n\t\t\t\t\tallowUnsafeValidationDetails\n\t\t\t\t)\n\t\t\t\tfnLiteral += coerceTransformDecodeError(\n\t\t\t\t\t`c.query=validator.query.Decode(c.query)\\n`,\n\t\t\t\t\t'query',\n\t\t\t\t\tallowUnsafeValidationDetails\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (validator.query.isOptional) fnLiteral += `}`\n\t\t}\n\n\t\tif (hasBody && validator.body) {\n\t\t\tif (validator.body.hasTransform || validator.body.isOptional)\n\t\t\t\tfnLiteral += `const isNotEmptyObject=c.body&&(typeof c.body===\"object\"&&(isNotEmpty(c.body)||c.body instanceof ArrayBuffer))\\n`\n\n\t\t\tconst hasUnion = isUnion(validator.body.schema)\n\t\t\tlet hasNonUnionFileWithDefault = false\n\n\t\t\tif (validator.body.hasDefault) {\n\t\t\t\tlet value = Value.Default(\n\t\t\t\t\tvalidator.body.schema,\n\t\t\t\t\tvalidator.body.schema.type === 'object' ||\n\t\t\t\t\t\tunwrapImportSchema(validator.body.schema)[Kind] ===\n\t\t\t\t\t\t\t'Object'\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: undefined\n\t\t\t\t)\n\n\t\t\t\tconst schema = unwrapImportSchema(validator.body.schema)\n\n\t\t\t\tif (\n\t\t\t\t\t!hasUnion &&\n\t\t\t\t\tvalue &&\n\t\t\t\t\ttypeof value === 'object' &&\n\t\t\t\t\t(hasType('File', schema) || hasType('Files', schema))\n\t\t\t\t) {\n\t\t\t\t\thasNonUnionFileWithDefault = true\n\n\t\t\t\t\tfor (const [k, v] of Object.entries(value))\n\t\t\t\t\t\tif (v === 'File' || v === 'Files')\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\tdelete value[k]\n\n\t\t\t\t\tif (!isNotEmpty(value)) value = undefined\n\t\t\t\t}\n\n\t\t\t\tconst parsed =\n\t\t\t\t\ttypeof value === 'object'\n\t\t\t\t\t\t? JSON.stringify(value)\n\t\t\t\t\t\t: typeof value === 'string'\n\t\t\t\t\t\t\t? `'${value}'`\n\t\t\t\t\t\t\t: value\n\n\t\t\t\tif (value !== undefined && value !== null) {\n\t\t\t\t\tif (Array.isArray(value))\n\t\t\t\t\t\tfnLiteral += `if(!c.body)c.body=${parsed}\\n`\n\t\t\t\t\telse if (typeof value === 'object')\n\t\t\t\t\t\tfnLiteral += `c.body=Object.assign(${parsed},c.body)\\n`\n\t\t\t\t\telse fnLiteral += `c.body=${parsed}\\n`\n\t\t\t\t}\n\n\t\t\t\tfnLiteral += composeCleaner({\n\t\t\t\t\tname: 'c.body',\n\t\t\t\t\tschema: validator.body,\n\t\t\t\t\ttype: 'body',\n\t\t\t\t\tnormalize\n\t\t\t\t})\n\n\t\t\t\tif (validator.body.provider === 'standard') {\n\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t`let vab=validator.body.Check(c.body)\\n` +\n\t\t\t\t\t\t`if(vab instanceof Promise)vab=await vab\\n` +\n\t\t\t\t\t\t`if(vab.issues){` +\n\t\t\t\t\t\tvalidation.validate('body', undefined, 'vab.issues') +\n\t\t\t\t\t\t'}else{c.body=vab.value}\\n'\n\t\t\t\t} else if (validator.body?.schema?.noValidate !== true) {\n\t\t\t\t\tif (validator.body.isOptional)\n\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t`if(isNotEmptyObject&&validator.body.Check(c.body)===false){` +\n\t\t\t\t\t\t\tvalidation.validate('body') +\n\t\t\t\t\t\t\t'}'\n\t\t\t\t\telse\n\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t`if(validator.body.Check(c.body)===false){` +\n\t\t\t\t\t\t\tvalidation.validate('body') +\n\t\t\t\t\t\t\t`}`\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfnLiteral += composeCleaner({\n\t\t\t\t\tname: 'c.body',\n\t\t\t\t\tschema: validator.body,\n\t\t\t\t\ttype: 'body',\n\t\t\t\t\tnormalize\n\t\t\t\t})\n\n\t\t\t\tif (validator.body.provider === 'standard') {\n\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t`let vab=validator.body.Check(c.body)\\n` +\n\t\t\t\t\t\t`if(vab instanceof Promise)vab=await vab\\n` +\n\t\t\t\t\t\t`if(vab.issues){` +\n\t\t\t\t\t\tvalidation.validate('body', undefined, 'vab.issues') +\n\t\t\t\t\t\t'}else{c.body=vab.value}\\n'\n\t\t\t\t} else if (validator.body?.schema?.noValidate !== true) {\n\t\t\t\t\tif (validator.body.isOptional)\n\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t`if(isNotEmptyObject&&validator.body.Check(c.body)===false){` +\n\t\t\t\t\t\t\tvalidation.validate('body') +\n\t\t\t\t\t\t\t'}'\n\t\t\t\t\telse\n\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t`if(validator.body.Check(c.body)===false){` +\n\t\t\t\t\t\t\tvalidation.validate('body') +\n\t\t\t\t\t\t\t'}'\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (validator.body.hasTransform)\n\t\t\t\tfnLiteral += coerceTransformDecodeError(\n\t\t\t\t\t`if(isNotEmptyObject)c.body=validator.body.Decode(c.body)\\n`,\n\t\t\t\t\t'body',\n\t\t\t\t\tallowUnsafeValidationDetails\n\t\t\t\t)\n\n\t\t\tif (hasUnion && validator.body.schema.anyOf?.length) {\n\t\t\t\tconst iterator = Object.values(\n\t\t\t\t\tvalidator.body.schema.anyOf\n\t\t\t\t) as TAnySchema[]\n\n\t\t\t\tfor (let i = 0; i < iterator.length; i++) {\n\t\t\t\t\tconst type = iterator[i]\n\n\t\t\t\t\tif (hasType('File', type) || hasType('Files', type)) {\n\t\t\t\t\t\tconst candidate = getSchemaValidator(type, {\n\t\t\t\t\t\t\t// @ts-expect-error private property\n\t\t\t\t\t\t\tmodules: app.definitions.typebox,\n\t\t\t\t\t\t\tdynamic: !app.config.aot,\n\t\t\t\t\t\t\t// @ts-expect-error private property\n\t\t\t\t\t\t\tmodels: app.definitions.type,\n\t\t\t\t\t\t\tnormalize: app.config.normalize,\n\t\t\t\t\t\t\tadditionalCoerce: coercePrimitiveRoot(),\n\t\t\t\t\t\t\tsanitize: () => app.config.sanitize\n\t\t\t\t\t\t})\n\n\t\t\t\t\t\tif (candidate) {\n\t\t\t\t\t\t\tconst isFirst = fileUnions.length === 0\n\t\t\t\t\t\t\t// Handle case where schema is wrapped in a Union/Intersect (e.g., ObjectString coercion)\n\t\t\t\t\t\t\tconst properties =\n\t\t\t\t\t\t\t\tgetSchemaProperties(candidate.schema) ??\n\t\t\t\t\t\t\t\tgetSchemaProperties(type)\n\n\t\t\t\t\t\t\tif (!properties) continue\n\n\t\t\t\t\t\t\tconst iterator = Object.entries(properties) as [\n\t\t\t\t\t\t\t\tstring,\n\t\t\t\t\t\t\t\tTSchema\n\t\t\t\t\t\t\t][]\n\n\t\t\t\t\t\t\tlet validator = isFirst ? '\\n' : ' else '\n\t\t\t\t\t\t\tvalidator += `if(fileUnions[${fileUnions.length}].Check(c.body)){`\n\n\t\t\t\t\t\t\tlet validateFile = ''\n\t\t\t\t\t\t\tlet validatorLength = 0\n\t\t\t\t\t\t\tfor (let i = 0; i < iterator.length; i++) {\n\t\t\t\t\t\t\t\tconst [k, v] = iterator[i]\n\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t!v.extension ||\n\t\t\t\t\t\t\t\t\t(v[Kind] !== 'File' && v[Kind] !== 'Files')\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t\t\t\tif (validatorLength) validateFile += ','\n\t\t\t\t\t\t\t\tvalidateFile += `fileType(c.body.${k},${JSON.stringify(v.extension)},'body.${k}')`\n\n\t\t\t\t\t\t\t\tvalidatorLength++\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (validateFile) {\n\t\t\t\t\t\t\t\tif (validatorLength === 1)\n\t\t\t\t\t\t\t\t\tvalidator += `await ${validateFile}\\n`\n\t\t\t\t\t\t\t\telse if (validatorLength > 1)\n\t\t\t\t\t\t\t\t\tvalidator += `await Promise.all([${validateFile}])\\n`\n\n\t\t\t\t\t\t\t\tvalidator += '}'\n\n\t\t\t\t\t\t\t\tfnLiteral += validator\n\t\t\t\t\t\t\t\tfileUnions.push(candidate)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (\n\t\t\t\thasNonUnionFileWithDefault ||\n\t\t\t\t(!hasUnion &&\n\t\t\t\t\t(hasType(\n\t\t\t\t\t\t'File',\n\t\t\t\t\t\tunwrapImportSchema(validator.body.schema)\n\t\t\t\t\t) ||\n\t\t\t\t\t\thasType(\n\t\t\t\t\t\t\t'Files',\n\t\t\t\t\t\t\tunwrapImportSchema(validator.body.schema)\n\t\t\t\t\t\t)))\n\t\t\t) {\n\t\t\t\tlet validateFile = ''\n\n\t\t\t\tconst bodyProperties = getSchemaProperties(\n\t\t\t\t\tunwrapImportSchema(validator.body.schema)\n\t\t\t\t)\n\n\t\t\t\tlet i = 0\n\t\t\t\tif (bodyProperties) {\n\t\t\t\t\tfor (const [k, v] of Object.entries(bodyProperties) as [\n\t\t\t\t\t\tstring,\n\t\t\t\t\t\tTSchema\n\t\t\t\t\t][]) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!v.extension ||\n\t\t\t\t\t\t\t(v[Kind] !== 'File' && v[Kind] !== 'Files')\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t\tif (i) validateFile += ','\n\t\t\t\t\t\tvalidateFile += `fileType(c.body.${k},${JSON.stringify(v.extension)},'body.${k}')`\n\n\t\t\t\t\t\ti++\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (i) fnLiteral += '\\n'\n\n\t\t\t\tif (i === 1) fnLiteral += `await ${validateFile}\\n`\n\t\t\t\telse if (i > 1)\n\t\t\t\t\tfnLiteral += `await Promise.all([${validateFile}])\\n`\n\t\t\t}\n\t\t}\n\n\t\tif (validator.cookie) {\n\t\t\t// ! Get latest app.config.cookie\n\t\t\tvalidator.cookie.config = mergeCookie(\n\t\t\t\tvalidator.cookie.config,\n\t\t\t\tapp.config.cookie ?? {}\n\t\t\t)\n\n\t\t\tfnLiteral +=\n\t\t\t\t`let cookieValue={}\\n` +\n\t\t\t\t`for(const [key,value] of Object.entries(c.cookie))` +\n\t\t\t\t`cookieValue[key]=value.value\\n`\n\n\t\t\tif (validator.cookie.isOptional)\n\t\t\t\tfnLiteral += `if(isNotEmpty(c.cookie)){`\n\n\t\t\tif (validator.cookie.provider === 'standard') {\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`let vac=validator.cookie.Check(cookieValue)\\n` +\n\t\t\t\t\t`if(vac instanceof Promise)vac=await vac\\n` +\n\t\t\t\t\t`if(vac.issues){` +\n\t\t\t\t\tvalidation.validate('cookie', undefined, 'vac.issues') +\n\t\t\t\t\t'}else{cookieValue=vac.value}\\n'\n\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`for(const k of Object.keys(cookieValue))` +\n\t\t\t\t\t`c.cookie[k].value=cookieValue[k]\\n`\n\t\t\t} else if (validator.cookie?.schema?.noValidate !== true) {\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`if(validator.cookie.Check(cookieValue)===false){` +\n\t\t\t\t\tvalidation.validate('cookie', 'cookieValue') +\n\t\t\t\t\t'}'\n\n\t\t\t\tif (validator.cookie.hasTransform)\n\t\t\t\t\tfnLiteral += coerceTransformDecodeError(\n\t\t\t\t\t\t`for(const [key,value] of Object.entries(validator.cookie.Decode(cookieValue))){` +\n\t\t\t\t\t\t\t`c.cookie[key].value = value` +\n\t\t\t\t\t\t\t`}`,\n\t\t\t\t\t\t'cookie',\n\t\t\t\t\t\tallowUnsafeValidationDetails\n\t\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (validator.cookie.isOptional) fnLiteral += `}`\n\t\t}\n\t}\n\n\tif (hooks?.beforeHandle || hasTrace) {\n\t\tconst reporter = report('beforeHandle', {\n\t\t\ttotal: hooks.beforeHandle?.length\n\t\t})\n\n\t\tlet hasResolve = false\n\n\t\tif (hooks.beforeHandle?.length) {\n\t\t\tfor (let i = 0; i < hooks.beforeHandle.length; i++) {\n\t\t\t\tconst beforeHandle = hooks.beforeHandle[i]\n\n\t\t\t\tconst endUnit = reporter.resolveChild(beforeHandle.fn.name)\n\n\t\t\t\tconst returning = hasReturn(beforeHandle)\n\t\t\t\tconst isResolver =\n\t\t\t\t\tbeforeHandle.subType === 'resolve' ||\n\t\t\t\t\tbeforeHandle.subType === 'mapResolve'\n\n\t\t\t\tif (isResolver) {\n\t\t\t\t\tif (!hasResolve) {\n\t\t\t\t\t\thasResolve = true\n\t\t\t\t\t\tfnLiteral += '\\nlet resolved\\n'\n\t\t\t\t\t}\n\n\t\t\t\t\tfnLiteral += isAsync(beforeHandle)\n\t\t\t\t\t\t? `resolved=await e.beforeHandle[${i}](c);\\n`\n\t\t\t\t\t\t: `resolved=e.beforeHandle[${i}](c);\\n`\n\n\t\t\t\t\tif (beforeHandle.subType === 'mapResolve')\n\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t`if(resolved instanceof ElysiaCustomStatusResponse){` +\n\t\t\t\t\t\t\tmapResponse('resolved') +\n\t\t\t\t\t\t\t`}else{` +\n\t\t\t\t\t\t\t`resolved.request=c.request\\n` +\n\t\t\t\t\t\t\t`resolved.store=c.store\\n` +\n\t\t\t\t\t\t\t`resolved.qi=c.qi\\n` +\n\t\t\t\t\t\t\t`resolved.path=c.path\\n` +\n\t\t\t\t\t\t\t`resolved.url=c.url\\n` +\n\t\t\t\t\t\t\t`resolved.redirect=c.redirect\\n` +\n\t\t\t\t\t\t\t`resolved.set=c.set\\n` +\n\t\t\t\t\t\t\t`resolved.error=c.error\\n` +\n\t\t\t\t\t\t\t`c=resolved` +\n\t\t\t\t\t\t\t`}`\n\t\t\t\t\telse\n\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t`if(resolved instanceof ElysiaCustomStatusResponse){` +\n\t\t\t\t\t\t\tmapResponse('resolved') +\n\t\t\t\t\t\t\t`}` +\n\t\t\t\t\t\t\t`else Object.assign(c, resolved)\\n`\n\n\t\t\t\t\tendUnit()\n\t\t\t\t} else if (!returning) {\n\t\t\t\t\tfnLiteral += isAsync(beforeHandle)\n\t\t\t\t\t\t? `await e.beforeHandle[${i}](c)\\n`\n\t\t\t\t\t\t: `e.beforeHandle[${i}](c)\\n`\n\n\t\t\t\t\tendUnit()\n\t\t\t\t} else {\n\t\t\t\t\tfnLiteral += isAsync(beforeHandle)\n\t\t\t\t\t\t? `be=await e.beforeHandle[${i}](c)\\n`\n\t\t\t\t\t\t: `be=e.beforeHandle[${i}](c)\\n`\n\n\t\t\t\t\tendUnit('be')\n\n\t\t\t\t\tfnLiteral += `if(be!==undefined){`\n\t\t\t\t\treporter.resolve()\n\n\t\t\t\t\tif (hooks.afterHandle?.length || hasTrace) {\n\t\t\t\t\t\treport('handle', {\n\t\t\t\t\t\t\tname: isHandleFn\n\t\t\t\t\t\t\t\t? (handler as Function).name\n\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t\t}).resolve()\n\n\t\t\t\t\t\tconst reporter = report('afterHandle', {\n\t\t\t\t\t\t\ttotal: hooks.afterHandle?.length\n\t\t\t\t\t\t})\n\n\t\t\t\t\t\tif (hooks.afterHandle?.length) {\n\t\t\t\t\t\t\tfor (let i = 0; i < hooks.afterHandle.length; i++) {\n\t\t\t\t\t\t\t\tconst hook = hooks.afterHandle[i]\n\t\t\t\t\t\t\t\tconst returning = hasReturn(hook)\n\t\t\t\t\t\t\t\tconst endUnit = reporter.resolveChild(\n\t\t\t\t\t\t\t\t\thook.fn.name\n\t\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\tfnLiteral += `c.response=c.responseValue=be\\n`\n\n\t\t\t\t\t\t\t\tif (!returning) {\n\t\t\t\t\t\t\t\t\tfnLiteral += isAsync(hook.fn)\n\t\t\t\t\t\t\t\t\t\t? `await e.afterHandle[${i}](c, be)\\n`\n\t\t\t\t\t\t\t\t\t\t: `e.afterHandle[${i}](c, be)\\n`\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tfnLiteral += isAsync(hook.fn)\n\t\t\t\t\t\t\t\t\t\t? `af=await e.afterHandle[${i}](c)\\n`\n\t\t\t\t\t\t\t\t\t\t: `af=e.afterHandle[${i}](c)\\n`\n\n\t\t\t\t\t\t\t\t\tfnLiteral += `if(af!==undefined) c.response=c.responseValue=be=af\\n`\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tendUnit('af')\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treporter.resolve()\n\t\t\t\t\t}\n\n\t\t\t\t\tif (validator.response)\n\t\t\t\t\t\tfnLiteral += validation.response('be')\n\n\t\t\t\t\tconst mapResponseReporter = report('mapResponse', {\n\t\t\t\t\t\ttotal: hooks.mapResponse?.length\n\t\t\t\t\t})\n\n\t\t\t\t\tif (hooks.mapResponse?.length) {\n\t\t\t\t\t\tfnLiteral += `c.response=c.responseValue=be\\n`\n\n\t\t\t\t\t\tfor (let i = 0; i < hooks.mapResponse.length; i++) {\n\t\t\t\t\t\t\tconst mapResponse = hooks.mapResponse[i]\n\n\t\t\t\t\t\t\tconst endUnit = mapResponseReporter.resolveChild(\n\t\t\t\t\t\t\t\tmapResponse.fn.name\n\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t\t`if(mr===undefined){` +\n\t\t\t\t\t\t\t\t`mr=${isAsyncName(mapResponse) ? 'await ' : ''}e.mapResponse[${i}](c)\\n` +\n\t\t\t\t\t\t\t\t`if(mr!==undefined)be=c.response=c.responseValue=mr` +\n\t\t\t\t\t\t\t\t'}'\n\n\t\t\t\t\t\t\tendUnit()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tmapResponseReporter.resolve()\n\n\t\t\t\t\tfnLiteral += afterResponse()\n\n\t\t\t\t\tfnLiteral += encodeCookie()\n\t\t\t\t\tfnLiteral += `return mapEarlyResponse(${saveResponse}be,c.set${\n\t\t\t\t\t\tmapResponseContext\n\t\t\t\t\t})}\\n`\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treporter.resolve()\n\t}\n\n\tfunction reportHandler(name: string | undefined) {\n\t\tconst handleReporter = report('handle', {\n\t\t\tname,\n\t\t\talias: 'reportHandler'\n\t\t})\n\n\t\treturn () => {\n\t\t\tif (hasTrace) {\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`if(r&&(r[Symbol.iterator]||r[Symbol.asyncIterator])&&typeof r.next===\"function\"){` +\n\t\t\t\t\t(maybeAsync ? '' : `(async()=>{`) +\n\t\t\t\t\t`const stream=await tee(r,3)\\n` +\n\t\t\t\t\t`r=stream[0]\\n` +\n\t\t\t\t\t(hooks.afterHandle?.length\n\t\t\t\t\t\t? `c.response=c.responseValue=r\\n`\n\t\t\t\t\t\t: '') +\n\t\t\t\t\t`const listener=stream[1]\\n` +\n\t\t\t\t\t(hasTrace || hooks.afterResponse?.length\n\t\t\t\t\t\t? `afterHandlerStreamListener=stream[2]\\n`\n\t\t\t\t\t\t: '') +\n\t\t\t\t\t`${setImmediateFn}(async ()=>{` +\n\t\t\t\t\t`if(listener)for await(const v of listener){}\\n`\n\t\t\t\thandleReporter.resolve()\n\t\t\t\tfnLiteral += `})` + (maybeAsync ? '' : `})()`) + `}else{`\n\t\t\t\thandleReporter.resolve()\n\t\t\t\tfnLiteral += '}\\n'\n\t\t\t}\n\t\t}\n\t}\n\n\tif (hooks.afterHandle?.length || hasTrace) {\n\t\tconst resolveHandler = reportHandler(\n\t\t\tisHandleFn ? (handler as Function).name : undefined\n\t\t)\n\n\t\tif (hooks.afterHandle?.length)\n\t\t\tfnLiteral += isAsyncHandler\n\t\t\t\t? `let r=c.response=c.responseValue=await ${handle}\\n`\n\t\t\t\t: `let r=c.response=c.responseValue=${handle}\\n`\n\t\telse\n\t\t\tfnLiteral += isAsyncHandler\n\t\t\t\t? `let r=await ${handle}\\n`\n\t\t\t\t: `let r=${handle}\\n`\n\n\t\tresolveHandler()\n\n\t\tconst reporter = report('afterHandle', {\n\t\t\ttotal: hooks.afterHandle?.length\n\t\t})\n\n\t\tif (hooks.afterHandle?.length) {\n\t\t\tfor (let i = 0; i < hooks.afterHandle.length; i++) {\n\t\t\t\tconst hook = hooks.afterHandle[i]\n\t\t\t\tconst returning = hasReturn(hook)\n\t\t\t\tconst endUnit = reporter.resolveChild(hook.fn.name)\n\n\t\t\t\tif (!returning) {\n\t\t\t\t\tfnLiteral += isAsync(hook.fn)\n\t\t\t\t\t\t? `await e.afterHandle[${i}](c)\\n`\n\t\t\t\t\t\t: `e.afterHandle[${i}](c)\\n`\n\n\t\t\t\t\tendUnit()\n\t\t\t\t} else {\n\t\t\t\t\tfnLiteral += isAsync(hook.fn)\n\t\t\t\t\t\t? `af=await e.afterHandle[${i}](c)\\n`\n\t\t\t\t\t\t: `af=e.afterHandle[${i}](c)\\n`\n\n\t\t\t\t\tendUnit('af')\n\n\t\t\t\t\tif (validator.response) {\n\t\t\t\t\t\tfnLiteral += `if(af!==undefined){`\n\t\t\t\t\t\treporter.resolve()\n\n\t\t\t\t\t\tfnLiteral += validation.response('af')\n\n\t\t\t\t\t\tfnLiteral += `c.response=c.responseValue=af}`\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfnLiteral += `if(af!==undefined){`\n\t\t\t\t\t\treporter.resolve()\n\n\t\t\t\t\t\tfnLiteral += `c.response=c.responseValue=af}`\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treporter.resolve()\n\n\t\tif (hooks.afterHandle?.length) fnLiteral += `r=c.response\\n`\n\n\t\tif (validator.response) fnLiteral += validation.response()\n\n\t\tfnLiteral += encodeCookie()\n\n\t\tconst mapResponseReporter = report('mapResponse', {\n\t\t\ttotal: hooks.mapResponse?.length\n\t\t})\n\t\tif (hooks.mapResponse?.length) {\n\t\t\tfor (let i = 0; i < hooks.mapResponse.length; i++) {\n\t\t\t\tconst mapResponse = hooks.mapResponse[i]\n\n\t\t\t\tconst endUnit = mapResponseReporter.resolveChild(\n\t\t\t\t\tmapResponse.fn.name\n\t\t\t\t)\n\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`mr=${\n\t\t\t\t\t\tisAsyncName(mapResponse) ? 'await ' : ''\n\t\t\t\t\t}e.mapResponse[${i}](c)\\n` +\n\t\t\t\t\t`if(mr!==undefined)r=c.response=c.responseValue=mr\\n`\n\n\t\t\t\tendUnit()\n\t\t\t}\n\t\t}\n\t\tmapResponseReporter.resolve()\n\n\t\tfnLiteral += mapResponse()\n\t} else {\n\t\tconst resolveHandler = reportHandler(\n\t\t\tisHandleFn ? (handler as Function).name : undefined\n\t\t)\n\n\t\tif (validator.response || hooks.mapResponse?.length || hasTrace) {\n\t\t\tfnLiteral += isAsyncHandler\n\t\t\t\t? `let r=await ${handle}\\n`\n\t\t\t\t: `let r=${handle}\\n`\n\n\t\t\tresolveHandler()\n\n\t\t\tif (validator.response) fnLiteral += validation.response()\n\n\t\t\tconst mapResponseReporter = report('mapResponse', {\n\t\t\t\ttotal: hooks.mapResponse?.length\n\t\t\t})\n\n\t\t\tif (hooks.mapResponse?.length) {\n\t\t\t\tfnLiteral += '\\nc.response=c.responseValue=r\\n'\n\n\t\t\t\tfor (let i = 0; i < hooks.mapResponse.length; i++) {\n\t\t\t\t\tconst mapResponse = hooks.mapResponse[i]\n\n\t\t\t\t\tconst endUnit = mapResponseReporter.resolveChild(\n\t\t\t\t\t\tmapResponse.fn.name\n\t\t\t\t\t)\n\n\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t`\\nif(mr===undefined){` +\n\t\t\t\t\t\t`mr=${isAsyncName(mapResponse) ? 'await ' : ''}e.mapResponse[${i}](c)\\n` +\n\t\t\t\t\t\t`if(mr!==undefined)r=c.response=c.responseValue=mr` +\n\t\t\t\t\t\t`}\\n`\n\n\t\t\t\t\tendUnit()\n\t\t\t\t}\n\t\t\t}\n\t\t\tmapResponseReporter.resolve()\n\n\t\t\tfnLiteral += encodeCookie()\n\n\t\t\tif (handler instanceof Response) {\n\t\t\t\tfnLiteral += afterResponse()\n\n\t\t\t\tfnLiteral += inference.set\n\t\t\t\t\t? `if(` +\n\t\t\t\t\t\t`isNotEmpty(c.set.headers)||` +\n\t\t\t\t\t\t`c.set.status!==200||` +\n\t\t\t\t\t\t`c.set.redirect||` +\n\t\t\t\t\t\t`c.set.cookie)return mapResponse(${saveResponse}${handle}.clone(),c.set${\n\t\t\t\t\t\t\tmapResponseContext\n\t\t\t\t\t\t})\\n` +\n\t\t\t\t\t\t`else return ${handle}.clone()`\n\t\t\t\t\t: `return ${handle}.clone()`\n\n\t\t\t\tfnLiteral += '\\n'\n\t\t\t} else fnLiteral += mapResponse()\n\t\t} else if (hasCookie || hasTrace) {\n\t\t\tfnLiteral += isAsyncHandler\n\t\t\t\t? `let r=await ${handle}\\n`\n\t\t\t\t: `let r=${handle}\\n`\n\n\t\t\tresolveHandler()\n\n\t\t\tconst mapResponseReporter = report('mapResponse', {\n\t\t\t\ttotal: hooks.mapResponse?.length\n\t\t\t})\n\t\t\tif (hooks.mapResponse?.length) {\n\t\t\t\tfnLiteral += 'c.response=c.responseValue= r\\n'\n\n\t\t\t\tfor (let i = 0; i < hooks.mapResponse.length; i++) {\n\t\t\t\t\tconst mapResponse = hooks.mapResponse[i]\n\n\t\t\t\t\tconst endUnit = mapResponseReporter.resolveChild(\n\t\t\t\t\t\tmapResponse.fn.name\n\t\t\t\t\t)\n\n\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t`if(mr===undefined){` +\n\t\t\t\t\t\t`mr=${isAsyncName(mapResponse) ? 'await ' : ''}e.mapResponse[${i}](c)\\n` +\n\t\t\t\t\t\t`if(mr!==undefined)r=c.response=c.responseValue=mr` +\n\t\t\t\t\t\t`}`\n\n\t\t\t\t\tendUnit()\n\t\t\t\t}\n\t\t\t}\n\t\t\tmapResponseReporter.resolve()\n\n\t\t\tfnLiteral += encodeCookie() + mapResponse()\n\t\t} else {\n\t\t\tresolveHandler()\n\n\t\t\tconst handled = isAsyncHandler ? `await ${handle}` : handle\n\n\t\t\tif (handler instanceof Response) {\n\t\t\t\tfnLiteral += afterResponse()\n\n\t\t\t\tfnLiteral += inference.set\n\t\t\t\t\t? `if(isNotEmpty(c.set.headers)||` +\n\t\t\t\t\t\t`c.set.status!==200||` +\n\t\t\t\t\t\t`c.set.redirect||` +\n\t\t\t\t\t\t`c.set.cookie)` +\n\t\t\t\t\t\t`return mapResponse(${saveResponse}${handle}.clone(),c.set${\n\t\t\t\t\t\t\tmapResponseContext\n\t\t\t\t\t\t})\\n` +\n\t\t\t\t\t\t`else return ${handle}.clone()\\n`\n\t\t\t\t\t: `return ${handle}.clone()\\n`\n\t\t\t} else fnLiteral += mapResponse(handled)\n\t\t}\n\t}\n\n\tfnLiteral += `\\n}catch(error){`\n\n\tif (!maybeAsync && hooks.error?.length) fnLiteral += `return(async()=>{`\n\tfnLiteral +=\n\t\t`const set=c.set\\n` +\n\t\t`if(!set.status||set.status<300)set.status=error?.status||500\\n`\n\n\tif (hasCookie) fnLiteral += encodeCookie()\n\n\tif (hasTrace && hooks.trace)\n\t\tfor (let i = 0; i < hooks.trace.length; i++)\n\t\t\t// There's a case where the error is thrown before any trace is called\n\t\t\tfnLiteral += `report${i}?.resolve(error);reportChild${i}?.(error)\\n`\n\n\tconst errorReporter = report('error', {\n\t\ttotal: hooks.error?.length\n\t})\n\n\tif (hooks.error?.length) {\n\t\tfnLiteral += `c.error=error\\n`\n\n\t\tif (hasValidation)\n\t\t\tfnLiteral +=\n\t\t\t\t`if(error instanceof TypeBoxError){` +\n\t\t\t\t'c.code=\"VALIDATION\"\\n' +\n\t\t\t\t'c.set.status=422' +\n\t\t\t\t'}else{' +\n\t\t\t\t`c.code=error.code??error[ERROR_CODE]??\"UNKNOWN\"}`\n\t\telse fnLiteral += `c.code=error.code??error[ERROR_CODE]??\"UNKNOWN\"\\n`\n\n\t\tfnLiteral += `let er\\n`\n\t\t// Mapped error Response\n\t\tif (hooks.mapResponse?.length) fnLiteral += 'let mep\\n'\n\n\t\tfor (let i = 0; i < hooks.error.length; i++) {\n\t\t\tconst endUnit = errorReporter.resolveChild(hooks.error[i].fn.name)\n\n\t\t\tif (isAsync(hooks.error[i]))\n\t\t\t\tfnLiteral += `er=await e.error[${i}](c)\\n`\n\t\t\telse\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`er=e.error[${i}](c)\\n` +\n\t\t\t\t\t`if(er instanceof Promise)er=await er\\n`\n\n\t\t\tendUnit()\n\n\t\t\tif (hooks.mapResponse?.length) {\n\t\t\t\tconst mapResponseReporter = report('mapResponse', {\n\t\t\t\t\ttotal: hooks.mapResponse?.length\n\t\t\t\t})\n\n\t\t\t\tfor (let i = 0; i < hooks.mapResponse.length; i++) {\n\t\t\t\t\tconst mapResponse = hooks.mapResponse[i]\n\n\t\t\t\t\tconst endUnit = mapResponseReporter.resolveChild(\n\t\t\t\t\t\tmapResponse.fn.name\n\t\t\t\t\t)\n\n\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t`c.response=c.responseValue=er\\n` +\n\t\t\t\t\t\t`mep=e.mapResponse[${i}](c)\\n` +\n\t\t\t\t\t\t`if(mep instanceof Promise)mep=await mep\\n` +\n\t\t\t\t\t\t`if(mep!==undefined)er=mep\\n`\n\n\t\t\t\t\tendUnit()\n\t\t\t\t}\n\t\t\t\tmapResponseReporter.resolve()\n\t\t\t}\n\n\t\t\tfnLiteral += `er=mapEarlyResponse(er,set${mapResponseContext})\\n`\n\t\t\tfnLiteral += `if(er){`\n\n\t\t\tif (hasTrace && hooks.trace) {\n\t\t\t\tfor (let i = 0; i < hooks.trace.length; i++)\n\t\t\t\t\tfnLiteral += `report${i}.resolve()\\n`\n\n\t\t\t\terrorReporter.resolve()\n\t\t\t}\n\n\t\t\tfnLiteral += afterResponse(false)\n\t\t\tfnLiteral += `return er}`\n\t\t}\n\t}\n\n\terrorReporter.resolve()\n\n\tfnLiteral += `return handleError(c,error,true)`\n\tif (!maybeAsync && hooks.error?.length) fnLiteral += '})()'\n\tfnLiteral += '}'\n\n\tconst adapterVariables = adapter.inject\n\t\t? Object.keys(adapter.inject).join(',') + ','\n\t\t: ''\n\n\tlet init =\n\t\t`const {` +\n\t\t`handler,` +\n\t\t`handleError,` +\n\t\t`hooks:e, ` +\n\t\tallocateIf(`validator,`, hasValidation) +\n\t\t`mapResponse,` +\n\t\t`mapCompactResponse,` +\n\t\t`mapEarlyResponse,` +\n\t\t`isNotEmpty,` +\n\t\t`utils:{` +\n\t\tallocateIf(`parseQuery,`, hasBody) +\n\t\tallocateIf(`parseQueryFromURL,`, hasQuery) +\n\t\t`},` +\n\t\t`error:{` +\n\t\tallocateIf(`ValidationError,`, hasValidation) +\n\t\tallocateIf(`ParseError`, hasBody) +\n\t\t`},` +\n\t\t`fileType,` +\n\t\t`schema,` +\n\t\t`definitions,` +\n\t\t`tee,` +\n\t\t`ERROR_CODE,` +\n\t\tallocateIf(`parseCookie,`, hasCookie) +\n\t\tallocateIf(`signCookie,`, hasCookie) +\n\t\tallocateIf(`decodeURIComponent,`, hasQuery) +\n\t\t`ElysiaCustomStatusResponse,` +\n\t\tallocateIf(`ELYSIA_TRACE,`, hasTrace) +\n\t\tallocateIf(`ELYSIA_REQUEST_ID,`, hasTrace) +\n\t\tallocateIf('parser,', hooks.parse?.length) +\n\t\tallocateIf(`getServer,`, inference.server) +\n\t\tallocateIf(`fileUnions,`, fileUnions.length) +\n\t\tadapterVariables +\n\t\tallocateIf('TypeBoxError', hasValidation) +\n\t\t`}=hooks\\n` +\n\t\t`const trace=e.trace\\n` +\n\t\t`return ${maybeAsync ? 'async ' : ''}function handle(c){`\n\n\tif (hooks.beforeHandle?.length) init += 'let be\\n'\n\tif (hooks.afterHandle?.length) init += 'let af\\n'\n\tif (hooks.mapResponse?.length) init += 'let mr\\n'\n\tif (allowMeta) init += 'c.schema=schema\\nc.defs=definitions\\n'\n\n\tfnLiteral = init + fnLiteral + '}'\n\tinit = ''\n\n\ttry {\n\t\treturn Function(\n\t\t\t'hooks',\n\t\t\t'\"use strict\";\\n' + fnLiteral\n\t\t)({\n\t\t\thandler,\n\t\t\thooks: lifeCycleToFn(hooks),\n\t\t\tvalidator: hasValidation ? validator : undefined,\n\t\t\t// @ts-expect-error\n\t\t\thandleError: app.handleError,\n\t\t\tmapResponse: adapterHandler.mapResponse,\n\t\t\tmapCompactResponse: adapterHandler.mapCompactResponse,\n\t\t\tmapEarlyResponse: adapterHandler.mapEarlyResponse,\n\t\t\tisNotEmpty,\n\t\t\tutils: {\n\t\t\t\tparseQuery: hasBody ? parseQuery : undefined,\n\t\t\t\tparseQueryFromURL: hasQuery\n\t\t\t\t\t? validator.query?.provider === 'standard'\n\t\t\t\t\t\t? parseQueryStandardSchema\n\t\t\t\t\t\t: parseQueryFromURL\n\t\t\t\t\t: undefined\n\t\t\t},\n\t\t\terror: {\n\t\t\t\tValidationError: hasValidation ? ValidationError : undefined,\n\t\t\t\tParseError: hasBody ? ParseError : undefined\n\t\t\t},\n\t\t\tfileType,\n\t\t\tschema: app.router.history,\n\t\t\t// @ts-expect-error\n\t\t\tdefinitions: app.definitions.type,\n\t\t\ttee,\n\t\t\tERROR_CODE,\n\t\t\tparseCookie: hasCookie ? parseCookie : undefined,\n\t\t\tsignCookie: hasCookie ? signCookie : undefined,\n\t\t\tCookie: hasCookie ? Cookie : undefined,\n\t\t\tdecodeURIComponent: hasQuery ? decode : undefined,\n\t\t\tElysiaCustomStatusResponse,\n\t\t\tELYSIA_TRACE: hasTrace ? ELYSIA_TRACE : undefined,\n\t\t\tELYSIA_REQUEST_ID: hasTrace ? ELYSIA_REQUEST_ID : undefined,\n\t\t\t// @ts-expect-error private property\n\t\t\tgetServer: inference.server ? () => app.getServer() : undefined,\n\t\t\tfileUnions: fileUnions.length ? fileUnions : undefined,\n\t\t\tTypeBoxError: hasValidation ? TypeBoxError : undefined,\n\t\t\tparser: app['~parser'],\n\t\t\t...adapter.inject\n\t\t})\n\t} catch (error) {\n\t\tconst debugHooks = lifeCycleToFn(hooks)\n\n\t\tconsole.log('[Composer] failed to generate optimized handler')\n\t\tconsole.log('---')\n\t\tconsole.log({\n\t\t\thandler:\n\t\t\t\ttypeof handler === 'function' ? handler.toString() : handler,\n\t\t\tinstruction: fnLiteral,\n\t\t\thooks: {\n\t\t\t\t...debugHooks,\n\t\t\t\t// @ts-ignore\n\t\t\t\ttransform: debugHooks?.transform?.map?.((x) => x.toString()),\n\t\t\t\t// @ts-ignore\n\t\t\t\tresolve: debugHooks?.resolve?.map?.((x) => x.toString()),\n\t\t\t\t// @ts-ignore\n\t\t\t\tbeforeHandle: debugHooks?.beforeHandle?.map?.((x) =>\n\t\t\t\t\tx.toString()\n\t\t\t\t),\n\t\t\t\t// @ts-ignore\n\t\t\t\tafterHandle: debugHooks?.afterHandle?.map?.((x) =>\n\t\t\t\t\tx.toString()\n\t\t\t\t),\n\t\t\t\t// @ts-ignore\n\t\t\t\tmapResponse: debugHooks?.mapResponse?.map?.((x) =>\n\t\t\t\t\tx.toString()\n\t\t\t\t),\n\t\t\t\t// @ts-ignore\n\t\t\t\tparse: debugHooks?.parse?.map?.((x) => x.toString()),\n\t\t\t\t// @ts-ignore\n\t\t\t\terror: debugHooks?.error?.map?.((x) => x.toString()),\n\t\t\t\t// @ts-ignore\n\t\t\t\tafterResponse: debugHooks?.afterResponse?.map?.((x) =>\n\t\t\t\t\tx.toString()\n\t\t\t\t),\n\t\t\t\t// @ts-ignore\n\t\t\t\tstop: debugHooks?.stop?.map?.((x) => x.toString())\n\t\t\t},\n\t\t\tvalidator,\n\t\t\t// @ts-expect-error\n\t\t\tdefinitions: app.definitions.type,\n\t\t\terror\n\t\t})\n\t\tconsole.log('---')\n\n\t\tif (typeof process?.exit === 'function') process.exit(1)\n\t\treturn () => new Response('Internal Server Error', { status: 500 })\n\t}\n}\n\nexport interface ComposerGeneralHandlerOptions {\n\t/**\n\t * optimization for standard internet hostname\n\t * this will assume hostname is always use a standard internet hostname\n\t * assuming hostname is at minimum of 11 length of string (http://a.bc)\n\t *\n\t * setting this to true will skip the first 11 character of the hostname\n\t *\n\t * @default true\n\t */\n\tstandardHostname?: boolean\n}\n\nexport const createOnRequestHandler = (\n\tapp: AnyElysia,\n\taddFn?: (word: string) => void\n) => {\n\tlet fnLiteral = ''\n\n\tconst report = createReport({\n\t\ttrace: app.event.trace,\n\t\taddFn:\n\t\t\taddFn ??\n\t\t\t((word) => {\n\t\t\t\tfnLiteral += word\n\t\t\t})\n\t})\n\n\tconst reporter = report('request', {\n\t\ttotal: app.event.request?.length\n\t})\n\n\tif (app.event.request?.length) {\n\t\tfnLiteral += `try{`\n\n\t\tfor (let i = 0; i < app.event.request.length; i++) {\n\t\t\tconst hook = app.event.request[i]\n\t\t\tconst withReturn = hasReturn(hook)\n\t\t\tconst maybeAsync = isAsync(hook)\n\n\t\t\tconst endUnit = reporter.resolveChild(app.event.request[i].fn.name)\n\n\t\t\tif (withReturn) {\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`re=mapEarlyResponse(` +\n\t\t\t\t\t`${maybeAsync ? 'await ' : ''}onRequest[${i}](c),` +\n\t\t\t\t\t`c.set)\\n`\n\n\t\t\t\tendUnit('re')\n\t\t\t\tfnLiteral += `if(re!==undefined)return re\\n`\n\t\t\t} else {\n\t\t\t\tfnLiteral += `${maybeAsync ? 'await ' : ''}onRequest[${i}](c)\\n`\n\t\t\t\tendUnit()\n\t\t\t}\n\t\t}\n\n\t\tfnLiteral += `}catch(error){return app.handleError(c,error,false)}`\n\t}\n\n\treporter.resolve()\n\n\treturn fnLiteral\n}\n\nexport const createHoc = (app: AnyElysia, fnName = 'map') => {\n\t// @ts-expect-error private property\n\tconst hoc = app.extender.higherOrderFunctions\n\n\tif (!hoc.length) return 'return ' + fnName\n\n\tconst adapter = app['~adapter'].composeGeneralHandler\n\tlet handler = fnName\n\n\tfor (let i = 0; i < hoc.length; i++)\n\t\thandler = `hoc[${i}](${handler},${adapter.parameters})`\n\n\treturn `return function hocMap(${adapter.parameters}){return ${handler}(${adapter.parameters})}`\n}\n\nexport const composeGeneralHandler = (\n\tapp: AnyElysia\n): ((request: Request) => MaybePromise<Response>) => {\n\tconst adapter = app['~adapter'].composeGeneralHandler\n\tapp.router.http.build()\n\n\tconst isWebstandard = app['~adapter'].isWebStandard\n\tconst hasTrace = app.event.trace?.length\n\n\tlet fnLiteral = ''\n\n\tconst router = app.router\n\n\tlet findDynamicRoute = router.http.root.WS\n\t\t? `const route=router.find(r.method==='GET'&&r.headers.get('upgrade')==='websocket'?'WS':r.method,p)`\n\t\t: `const route=router.find(r.method,p)`\n\n\tfindDynamicRoute += router.http.root.ALL ? `??router.find('ALL',p)\\n` : '\\n'\n\n\tif (isWebstandard)\n\t\tfindDynamicRoute +=\n\t\t\t`if(r.method===\"HEAD\"){` +\n\t\t\t`const route=router.find(\"GET\",p);` +\n\t\t\t`if(route){` +\n\t\t\t`c.params=route.params;` +\n\t\t\t`const _res=route.store.handler?route.store.handler(c):route.store.compile()(c);` +\n\t\t\t`if(_res)` +\n\t\t\t`return Promise.resolve(_res).then((_res)=>{` +\n\t\t\t`if(!_res.headers)_res.headers=new Headers();` +\n\t\t\t`return getResponseLength(_res).then((length)=>{` +\n\t\t\t`_res.headers.set(\"content-length\", length);` +\n\t\t\t`return new Response(null,{status:_res.status,statusText:_res.statusText,headers:_res.headers});` +\n\t\t\t`})` +\n\t\t\t`});` +\n\t\t\t`}` +\n\t\t\t`}`\n\n\tlet afterResponse = `c.error=notFound\\n`\n\tif (app.event.afterResponse?.length && !app.event.error) {\n\t\tafterResponse = '\\nc.error=notFound\\n'\n\n\t\tconst prefix = app.event.afterResponse.some(isAsync) ? 'async' : ''\n\t\tafterResponse +=\n\t\t\t`\\n${setImmediateFn}(${prefix}()=>{` +\n\t\t\t`if(c.responseValue instanceof ElysiaCustomStatusResponse) c.set.status=c.responseValue.code\\n`\n\n\t\tfor (let i = 0; i < app.event.afterResponse.length; i++) {\n\t\t\tconst fn = app.event.afterResponse[i].fn\n\n\t\t\tafterResponse += `\\n${isAsyncName(fn) ? 'await ' : ''}afterResponse[${i}](c)\\n`\n\t\t}\n\n\t\tafterResponse += `})\\n`\n\t}\n\n\t// @ts-ignore\n\tif (app.inference.query)\n\t\tafterResponse +=\n\t\t\t'\\nif(c.qi===-1){' +\n\t\t\t'c.query={}' +\n\t\t\t'}else{' +\n\t\t\t'c.query=parseQueryFromURL(c.url,c.qi+1)' +\n\t\t\t'}'\n\n\tconst error404 = adapter.error404(\n\t\t!!app.event.request?.length,\n\t\t!!app.event.error?.length,\n\t\tafterResponse\n\t)\n\n\tfindDynamicRoute += error404.code\n\n\tfindDynamicRoute +=\n\t\t`\\nc.params=route.params\\n` +\n\t\t`if(route.store.handler)return route.store.handler(c)\\n` +\n\t\t`return route.store.compile()(c)\\n`\n\n\tlet switchMap = ''\n\tfor (const [path, methods] of Object.entries(router.static)) {\n\t\tswitchMap += `case'${path}':`\n\n\t\tif (app.config.strictPath !== true)\n\t\t\tswitchMap += `case'${getLoosePath(path)}':`\n\n\t\tconst encoded = encodePath(path)\n\t\tif (path !== encoded) switchMap += `case'${encoded}':`\n\n\t\tswitchMap += 'switch(r.method){'\n\n\t\tif ('GET' in methods || 'WS' in methods) {\n\t\t\tswitchMap += `case 'GET':`\n\n\t\t\tif ('WS' in methods) {\n\t\t\t\tswitchMap +=\n\t\t\t\t\t`if(r.headers.get('upgrade')==='websocket')` +\n\t\t\t\t\t`return ht[${methods.WS}].composed(c)\\n`\n\n\t\t\t\tif ('GET' in methods === false) {\n\t\t\t\t\tif ('ALL' in methods)\n\t\t\t\t\t\tswitchMap += `return ht[${methods.ALL}].composed(c)\\n`\n\t\t\t\t\telse switchMap += `break map\\n`\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ('GET' in methods)\n\t\t\t\tswitchMap += `return ht[${methods.GET}].composed(c)\\n`\n\t\t}\n\n\t\tif (\n\t\t\tisWebstandard &&\n\t\t\t('GET' in methods || 'ALL' in methods) &&\n\t\t\t'HEAD' in methods === false\n\t\t)\n\t\t\tswitchMap +=\n\t\t\t\t`case 'HEAD':` +\n\t\t\t\t`return Promise.resolve(ht[${methods.GET ?? methods.ALL}].composed(c)).then(_ht=>getResponseLength(_ht).then((length)=>{` +\n\t\t\t\t`_ht.headers.set('content-length', length)\\n` +\n\t\t\t\t`return new Response(null,{status:_ht.status,statusText:_ht.statusText,headers:_ht.headers})\\n` +\n\t\t\t\t`}))\\n`\n\n\t\tfor (const [method, index] of Object.entries(methods)) {\n\t\t\tif (method === 'ALL' || method === 'GET' || method === 'WS')\n\t\t\t\tcontinue\n\n\t\t\tswitchMap += `case '${method}':return ht[${index}].composed(c)\\n`\n\t\t}\n\n\t\tif ('ALL' in methods)\n\t\t\tswitchMap += `default:return ht[${methods.ALL}].composed(c)\\n`\n\t\telse switchMap += `default:break map\\n`\n\n\t\tswitchMap += '}'\n\t}\n\n\tconst maybeAsync = !!app.event.request?.some(isAsync)\n\n\tconst adapterVariables = adapter.inject\n\t\t? Object.keys(adapter.inject).join(',') + ','\n\t\t: ''\n\n\tfnLiteral +=\n\t\t`\\nconst {` +\n\t\t`app,` +\n\t\t`mapEarlyResponse,` +\n\t\t`NotFoundError,` +\n\t\t`randomId,` +\n\t\t`handleError,` +\n\t\t`status,` +\n\t\t`redirect,` +\n\t\t`getResponseLength,` +\n\t\t`ElysiaCustomStatusResponse,` +\n\t\t// @ts-ignore\n\t\tallocateIf(`parseQueryFromURL,`, app.inference.query) +\n\t\tallocateIf(`ELYSIA_TRACE,`, hasTrace) +\n\t\tallocateIf(`ELYSIA_REQUEST_ID,`, hasTrace) +\n\t\tadapterVariables +\n\t\t`}=data\\n` +\n\t\t`const store=app.singleton.store\\n` +\n\t\t`const decorator=app.singleton.decorator\\n` +\n\t\t`const staticRouter=app.router.static.http\\n` +\n\t\t`const ht=app.router.history\\n` +\n\t\t`const router=app.router.http\\n` +\n\t\t`const trace=app.event.trace?.map(x=>typeof x==='function'?x:x.fn)??[]\\n` +\n\t\t`const notFound=new NotFoundError()\\n` +\n\t\t`const hoc=app.extender.higherOrderFunctions.map(x=>x.fn)\\n`\n\n\tif (app.event.request?.length)\n\t\tfnLiteral += `const onRequest=app.event.request.map(x=>x.fn)\\n`\n\n\tif (app.event.afterResponse?.length)\n\t\tfnLiteral += `const afterResponse=app.event.afterResponse.map(x=>x.fn)\\n`\n\n\tfnLiteral += error404.declare\n\n\tif (app.event.trace?.length)\n\t\tfnLiteral +=\n\t\t\t`const ` +\n\t\t\tapp.event.trace\n\t\t\t\t.map((_, i) => `tr${i}=app.event.trace[${i}].fn`)\n\t\t\t\t.join(',') +\n\t\t\t'\\n'\n\n\tfnLiteral += `${maybeAsync ? 'async ' : ''}function map(${adapter.parameters}){`\n\n\tif (app.event.request?.length) fnLiteral += `let re\\n`\n\n\tfnLiteral += adapter.createContext(app)\n\n\tif (app.event.trace?.length)\n\t\tfnLiteral +=\n\t\t\t`c[ELYSIA_TRACE]=[` +\n\t\t\tapp.event.trace.map((_, i) => `tr${i}(c)`).join(',') +\n\t\t\t`]\\n`\n\n\tfnLiteral += createOnRequestHandler(app)\n\n\tif (switchMap) fnLiteral += `\\nmap: switch(p){\\n` + switchMap + `}`\n\n\tfnLiteral += findDynamicRoute + `}\\n` + createHoc(app)\n\n\tconst handleError = composeErrorHandler(app)\n\n\t// @ts-expect-error private property\n\tapp.handleError = handleError\n\n\tconst fn = Function(\n\t\t'data',\n\t\t'\"use strict\";\\n' + fnLiteral\n\t)({\n\t\tapp,\n\t\tmapEarlyResponse: app['~adapter']['handler'].mapEarlyResponse,\n\t\tNotFoundError,\n\t\trandomId,\n\t\thandleError,\n\t\tstatus,\n\t\tredirect,\n\t\tgetResponseLength,\n\t\tElysiaCustomStatusResponse,\n\t\t// @ts-ignore\n\t\tparseQueryFromURL: app.inference.query ? parseQueryFromURL : undefined,\n\t\tELYSIA_TRACE: hasTrace ? ELYSIA_TRACE : undefined,\n\t\tELYSIA_REQUEST_ID: hasTrace ? ELYSIA_REQUEST_ID : undefined,\n\t\t...adapter.inject\n\t})\n\n\tif (isBun) Bun.gc(false)\n\n\treturn fn\n}\n\nexport const composeErrorHandler = (app: AnyElysia) => {\n\tconst hooks = app.event\n\tlet fnLiteral = ''\n\n\tconst adapter = app['~adapter'].composeError\n\tconst adapterVariables = adapter.inject\n\t\t? Object.keys(adapter.inject).join(',') + ','\n\t\t: ''\n\n\tconst hasTrace = !!app.event.trace?.length\n\n\tfnLiteral +=\n\t\t`const {` +\n\t\t`mapResponse,` +\n\t\t`ERROR_CODE,` +\n\t\t`ElysiaCustomStatusResponse,` +\n\t\t`ValidationError,` +\n\t\t`TransformDecodeError,` +\n\t\tallocateIf(`onError,`, app.event.error) +\n\t\tallocateIf(`afterResponse,`, app.event.afterResponse) +\n\t\tallocateIf(`trace,`, app.event.trace) +\n\t\tallocateIf(`onMapResponse,`, app.event.mapResponse) +\n\t\tallocateIf(`ELYSIA_TRACE,`, hasTrace) +\n\t\tallocateIf(`ELYSIA_REQUEST_ID,`, hasTrace) +\n\t\tadapterVariables +\n\t\t`}=inject\\n`\n\n\t// Always make error handler async since toResponse() may return promises\n\tfnLiteral += `return async function(context,error,skipGlobal){`\n\n\tfnLiteral += ''\n\n\tif (hasTrace) fnLiteral += 'const id=context[ELYSIA_REQUEST_ID]\\n'\n\n\tconst report = createReport({\n\t\tcontext: 'context',\n\t\ttrace: hooks.trace,\n\t\taddFn: (word) => {\n\t\t\tfnLiteral += word\n\t\t}\n\t})\n\n\tconst afterResponse = () => {\n\t\tif (!hooks.afterResponse?.length && !hasTrace) return ''\n\n\t\tlet afterResponse = ''\n\t\tconst prefix = hooks.afterResponse?.some(isAsync) ? 'async' : ''\n\t\tafterResponse += `\\n${setImmediateFn}(${prefix}()=>{`\n\n\t\tconst reporter = createReport({\n\t\t\tcontext: 'context',\n\t\t\ttrace: hooks.trace,\n\t\t\taddFn: (word) => {\n\t\t\t\tafterResponse += word\n\t\t\t}\n\t\t})('afterResponse', {\n\t\t\ttotal: hooks.afterResponse?.length,\n\t\t\tname: 'context'\n\t\t})\n\n\t\tif (hooks.afterResponse?.length && hooks.afterResponse) {\n\t\t\tfor (let i = 0; i < hooks.afterResponse.length; i++) {\n\t\t\t\tconst fn = hooks.afterResponse[i].fn\n\t\t\t\tconst endUnit = reporter.resolveChild(fn.name)\n\n\t\t\t\tafterResponse += `\\n${isAsyncName(fn) ? 'await ' : ''}afterResponse[${i}](context)\\n`\n\n\t\t\t\tendUnit()\n\t\t\t}\n\t\t}\n\n\t\treporter.resolve()\n\n\t\tafterResponse += `})\\n`\n\n\t\treturn afterResponse\n\t}\n\n\tfnLiteral +=\n\t\t`const set=context.set\\n` +\n\t\t`let _r\\n` +\n\t\t`if(!context.code)context.code=error.code??error[ERROR_CODE]\\n` +\n\t\t`if(!(context.error instanceof Error))context.error=error\\n` +\n\t\t`if(error instanceof ElysiaCustomStatusResponse){` +\n\t\t`set.status=error.status=error.code\\n` +\n\t\t`error.message=error.response` +\n\t\t`}`\n\n\tif (adapter.declare) fnLiteral += adapter.declare\n\n\tconst saveResponse =\n\t\thasTrace || !!hooks.afterResponse?.length ? 'context.response = ' : ''\n\n\tfnLiteral +=\n\t\t`if(typeof error?.toResponse==='function'&&!(error instanceof ValidationError)&&!(error instanceof TransformDecodeError)){` +\n\t\t`try{` +\n\t\t`let raw=error.toResponse()\\n` +\n\t\t`if(typeof raw?.then==='function')raw=await raw\\n` +\n\t\t`if(raw instanceof Response)set.status=raw.status\\n` +\n\t\t`context.response=context.responseValue=raw\\n` +\n\t\t`}catch(toResponseError){\\n` +\n\t\t`}\\n` +\n\t\t`}\\n`\n\n\tif (app.event.error)\n\t\tfor (let i = 0; i < app.event.error.length; i++) {\n\t\t\tconst handler = app.event.error[i]\n\n\t\t\tconst response = `${\n\t\t\t\tisAsync(handler) ? 'await ' : ''\n\t\t\t}onError[${i}](context)\\n`\n\n\t\t\tfnLiteral += 'if(skipGlobal!==true&&!context.response){'\n\n\t\t\tif (hasReturn(handler)) {\n\t\t\t\tfnLiteral +=\n\t\t\t\t\t`_r=${response}\\nif(_r!==undefined){` +\n\t\t\t\t\t`if(_r instanceof Response){` +\n\t\t\t\t\tafterResponse() +\n\t\t\t\t\t`return mapResponse(_r,set${adapter.mapResponseContext})}` +\n\t\t\t\t\t`if(_r instanceof ElysiaCustomStatusResponse){` +\n\t\t\t\t\t`error.status=error.code\\n` +\n\t\t\t\t\t`error.message=error.response` +\n\t\t\t\t\t`}` +\n\t\t\t\t\t`if(set.status===200||!set.status)set.status=error.status\\n`\n\n\t\t\t\tconst mapResponseReporter = report('mapResponse', {\n\t\t\t\t\ttotal: hooks.mapResponse?.length,\n\t\t\t\t\tname: 'context'\n\t\t\t\t})\n\n\t\t\t\tif (hooks.mapResponse?.length) {\n\t\t\t\t\tfor (let i = 0; i < hooks.mapResponse.length; i++) {\n\t\t\t\t\t\tconst mapResponse = hooks.mapResponse[i]\n\n\t\t\t\t\t\tconst endUnit = mapResponseReporter.resolveChild(\n\t\t\t\t\t\t\tmapResponse.fn.name\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\tfnLiteral +=\n\t\t\t\t\t\t\t`context.response=context.responseValue=_r\\n` +\n\t\t\t\t\t\t\t`_r=${isAsyncName(mapResponse) ? 'await ' : ''}onMapResponse[${i}](context)\\n`\n\n\t\t\t\t\t\tendUnit()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmapResponseReporter.resolve()\n\n\t\t\t\tfnLiteral +=\n\t\t\t\t\tafterResponse() +\n\t\t\t\t\t`return mapResponse(${saveResponse}_r,set${adapter.mapResponseContext})}`\n\t\t\t} else fnLiteral += response\n\n\t\t\tfnLiteral += '}'\n\t\t}\n\n\tfnLiteral +=\n\t\t`if(error instanceof ValidationError||error instanceof TransformDecodeError){\\n` +\n\t\t`if(error.error)error=error.error\\n` +\n\t\t`set.status=error.status??422\\n` +\n\t\tafterResponse() +\n\t\tadapter.validationError +\n\t\t`\\n}\\n`\n\n\tfnLiteral +=\n\t\t`if(!context.response&&error instanceof Error){` +\n\t\tafterResponse() +\n\t\tadapter.unknownError +\n\t\t`\\n}`\n\n\tconst mapResponseReporter = report('mapResponse', {\n\t\ttotal: hooks.mapResponse?.length,\n\t\tname: 'context'\n\t})\n\n\tfnLiteral +=\n\t\t'\\nif(!context.response)context.response=context.responseValue=error.message??error\\n'\n\n\tif (hooks.mapResponse?.length) {\n\t\tfnLiteral += 'let mr\\n'\n\n\t\tfor (let i = 0; i < hooks.mapResponse.length; i++) {\n\t\t\tconst mapResponse = hooks.mapResponse[i]\n\n\t\t\tconst endUnit = mapResponseReporter.resolveChild(\n\t\t\t\tmapResponse.fn.name\n\t\t\t)\n\n\t\t\tfnLiteral +=\n\t\t\t\t`if(mr===undefined){` +\n\t\t\t\t`mr=${isAsyncName(mapResponse) ? 'await ' : ''}onMapResponse[${i}](context)\\n` +\n\t\t\t\t`if(mr!==undefined)error=context.response=context.responseValue=mr` +\n\t\t\t\t'}'\n\n\t\t\tendUnit()\n\t\t}\n\t}\n\n\tmapResponseReporter.resolve()\n\n\tfnLiteral +=\n\t\tafterResponse() +\n\t\t`\\nreturn mapResponse(${saveResponse}error,set${adapter.mapResponseContext})}`\n\n\tconst mapFn = (x: Function | HookContainer) =>\n\t\ttypeof x === 'function' ? x : x.fn\n\n\treturn Function(\n\t\t'inject',\n\t\t'\"use strict\";\\n' + fnLiteral\n\t)({\n\t\tmapResponse: app['~adapter'].handler.mapResponse,\n\t\tERROR_CODE,\n\t\tElysiaCustomStatusResponse,\n\t\tValidationError,\n\t\tTransformDecodeError,\n\t\tonError: app.event.error?.map(mapFn),\n\t\tafterResponse: app.event.afterResponse?.map(mapFn),\n\t\ttrace: app.event.trace?.map(mapFn),\n\t\tonMapResponse: app.event.mapResponse?.map(mapFn),\n\t\tELYSIA_TRACE: hasTrace ? ELYSIA_TRACE : undefined,\n\t\tELYSIA_REQUEST_ID: hasTrace ? ELYSIA_REQUEST_ID : undefined,\n\t\t...adapter.inject\n\t})\n}\n"
  },
  {
    "path": "src/context.ts",
    "content": "import type { Server } from './universal/server'\nimport type { Cookie, ElysiaCookie } from './cookies'\nimport type {\n\tStatusMap,\n\tInvertedStatusMap,\n\tredirect as Redirect\n} from './utils'\n\nimport { ElysiaCustomStatusResponse, status, type SelectiveStatus } from './error'\nimport type {\n\tRouteSchema,\n\tPrettify,\n\tResolvePath,\n\tSingletonBase,\n\tHTTPHeaders,\n\tInputSchema\n} from './types'\n\ntype InvertedStatusMapKey = keyof InvertedStatusMap\n\ntype CheckExcessProps<T, U> = 0 extends 1 & T\n\t? T // T is any\n\t: U extends U\n\t\t? Exclude<keyof T, keyof U> extends never\n\t\t\t? T\n\t\t\t: { [K in keyof U]: U[K] } & { [K in Exclude<keyof T, keyof U>]: never }\n\t\t: never\n\nexport type ErrorContext<\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tPath extends string | undefined = undefined\n> = Prettify<\n\t{\n\t\tbody: Route['body']\n\t\tquery: undefined extends Route['query']\n\t\t\t? Record<string, string | undefined>\n\t\t\t: Route['query']\n\t\tparams: undefined extends Route['params']\n\t\t\t? Path extends `${string}/${':' | '*'}${string}`\n\t\t\t\t? ResolvePath<Path>\n\t\t\t\t: { [key in string]: string }\n\t\t\t: Route['params']\n\t\theaders: undefined extends Route['headers']\n\t\t\t? Record<string, string | undefined>\n\t\t\t: Route['headers']\n\t\tcookie: undefined extends Route['cookie']\n\t\t\t? Record<string, Cookie<string | undefined>>\n\t\t\t: Record<string, Cookie<string | undefined>> & {\n\t\t\t\t\t[key in keyof Route['cookie']]-?: NonNullable<\n\t\t\t\t\t\tCookie<Route['cookie'][key]>\n\t\t\t\t\t>\n\t\t\t\t}\n\n\t\tserver: Server | null\n\t\tredirect: Redirect\n\n\t\tset: {\n\t\t\theaders: HTTPHeaders\n\t\t\tstatus?: number | keyof StatusMap\n\t\t\tredirect?: string\n\t\t\t/**\n\t\t\t * ! Internal Property\n\t\t\t *\n\t\t\t * Use `Context.cookie` instead\n\t\t\t */\n\t\t\tcookie?: Record<string, ElysiaCookie>\n\t\t}\n\n\t\tstatus: {} extends Route['response']\n\t\t\t? typeof status\n\t\t\t: <\n\t\t\t\t\tconst Code extends\n\t\t\t\t\t\t| keyof Route['response']\n\t\t\t\t\t\t| InvertedStatusMap[Extract<\n\t\t\t\t\t\t\t\tInvertedStatusMapKey,\n\t\t\t\t\t\t\t\tkeyof Route['response']\n\t\t\t\t\t\t  >],\n\t\t\t\t\tT extends Code extends keyof Route['response']\n\t\t\t\t\t\t? Route['response'][Code]\n\t\t\t\t\t\t: Code extends keyof StatusMap\n\t\t\t\t\t\t\t? // @ts-ignore StatusMap[Code] always valid because Code generic check\n\t\t\t\t\t\t\t\tRoute['response'][StatusMap[Code]]\n\t\t\t\t\t\t\t: never\n\t\t\t\t>(\n\t\t\t\t\tcode: Code,\n\t\t\t\t\tresponse: CheckExcessProps<\n\t\t\t\t\t\tT,\n\t\t\t\t\t\tCode extends keyof Route['response']\n\t\t\t\t\t\t\t? Route['response'][Code]\n\t\t\t\t\t\t\t: Code extends keyof StatusMap\n\t\t\t\t\t\t\t\t? // @ts-ignore StatusMap[Code] always valid because Code generic check\n\t\t\t\t\t\t\t\t\tRoute['response'][StatusMap[Code]]\n\t\t\t\t\t\t\t\t: never\n\t\t\t\t\t>\n\t\t\t\t) => ElysiaCustomStatusResponse<\n\t\t\t\t\t// @ts-ignore trust me bro\n\t\t\t\t\tCode,\n\t\t\t\t\tT\n\t\t\t\t>\n\n\t\t/**\n\t\t * Path extracted from incoming URL\n\t\t *\n\t\t * Represent a value extracted from URL\n\t\t *\n\t\t * @example '/id/9'\n\t\t */\n\t\tpath: string\n\t\t/**\n\t\t * Path as registered to router\n\t\t *\n\t\t * Represent a path registered to a router, not a URL\n\t\t *\n\t\t * @example '/id/:id'\n\t\t */\n\t\troute: string\n\t\trequest: Request\n\t\tstore: Singleton['store']\n\t} & Singleton['decorator'] &\n\t\tSingleton['derive'] &\n\t\tSingleton['resolve']\n>\n\ntype PrettifyIfObject<T> = T extends object ? Prettify<T> : T\n\nexport type Context<\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tPath extends string | undefined = undefined\n> = Prettify<\n\t{\n\t\tbody: PrettifyIfObject<Route['body'] & Singleton['resolve']['body']>\n\t\tquery: undefined extends Route['query']\n\t\t\t? {} extends NonNullable<Singleton['resolve']['query']>\n\t\t\t\t? Record<string, string>\n\t\t\t\t: Singleton['resolve']['query']\n\t\t\t: PrettifyIfObject<Route['query'] & Singleton['resolve']['query']>\n\t\tparams: undefined extends Route['params']\n\t\t\t? undefined extends Path\n\t\t\t\t? {} extends NonNullable<Singleton['resolve']['params']>\n\t\t\t\t\t? Record<string, string>\n\t\t\t\t\t: Singleton['resolve']['params']\n\t\t\t\t: Path extends `${string}/${':' | '*'}${string}`\n\t\t\t\t\t? ResolvePath<Path>\n\t\t\t\t\t: never\n\t\t\t: PrettifyIfObject<Route['params'] & Singleton['resolve']['params']>\n\t\theaders: undefined extends Route['headers']\n\t\t\t? {} extends NonNullable<Singleton['resolve']['headers']>\n\t\t\t\t? Record<string, string | undefined>\n\t\t\t\t: Singleton['resolve']['headers']\n\t\t\t: PrettifyIfObject<\n\t\t\t\t\tRoute['headers'] & Singleton['resolve']['headers']\n\t\t\t\t>\n\t\tcookie: undefined extends Route['cookie']\n\t\t\t? Record<string, Cookie<unknown>>\n\t\t\t: Record<string, Cookie<unknown>> &\n\t\t\t\t\tPrettify<\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t[key in keyof Route['cookie']]-?: Cookie<\n\t\t\t\t\t\t\t\tRoute['cookie'][key]\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t} & {\n\t\t\t\t\t\t\t[key in keyof Singleton['resolve']['cookie']]-?: Cookie<\n\t\t\t\t\t\t\t\tSingleton['resolve']['cookie'][key]\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t}\n\t\t\t\t\t>\n\n\t\tserver: Server | null\n\t\tredirect: Redirect\n\n\t\tset: {\n\t\t\theaders: HTTPHeaders\n\t\t\tstatus?: number | keyof StatusMap\n\t\t\t/**\n\t\t\t * @deprecated Use inline redirect instead\n\t\t\t *\n\t\t\t * @example Migration example\n\t\t\t * ```ts\n\t\t\t * new Elysia()\n\t\t\t *     .get(({ redirect }) => redirect('/'))\n\t\t\t * ```\n\t\t\t */\n\t\t\tredirect?: string\n\t\t\t/**\n\t\t\t * ! Internal Property\n\t\t\t *\n\t\t\t * Use `Context.cookie` instead\n\t\t\t */\n\t\t\tcookie?: Record<string, ElysiaCookie>\n\t\t}\n\n\t\t/**\n\t\t * Path extracted from incoming URL\n\t\t *\n\t\t * Represent a value extracted from URL\n\t\t *\n\t\t * @example '/id/9'\n\t\t */\n\t\tpath: string\n\t\t/**\n\t\t * Path as registered to router\n\t\t *\n\t\t * Represent a path registered to a router, not a URL\n\t\t *\n\t\t * @example '/id/:id'\n\t\t */\n\t\troute: string\n\t\trequest: Request\n\t\tstore: Singleton['store']\n\n\t\tstatus: {} extends Route['response']\n\t\t\t? typeof status\n\t\t\t: SelectiveStatus<Route['response']>\n\t} & Singleton['decorator'] &\n\t\tSingleton['derive'] &\n\t\tOmit<Singleton['resolve'], keyof InputSchema>\n>\n\n// Use to mimic request before mapping route\nexport type PreContext<\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t}\n> = Prettify<\n\t{\n\t\tstore: Singleton['store']\n\t\trequest: Request\n\n\t\tredirect: Redirect\n\t\tserver: Server | null\n\n\t\tset: {\n\t\t\theaders: HTTPHeaders\n\t\t\tstatus?: number\n\t\t\tredirect?: string\n\t\t}\n\n\t\tstatus: typeof status\n\t} & Singleton['decorator']\n>\n"
  },
  {
    "path": "src/cookies.ts",
    "content": "import { parse, serialize } from 'cookie'\n\nimport decode from 'fast-decode-uri-component'\n\nimport { isNotEmpty, unsignCookie } from './utils'\nimport { InvalidCookieSignature } from './error'\n\nimport type { Context } from './context'\nimport type { Prettify } from './types'\n\n// FNV-1a hash for fast string hashing\nconst hashString = (str: string): number => {\n\tconst FNV_OFFSET_BASIS = 2166136261\n\tconst FNV_PRIME = 16777619\n\n\tlet hash = FNV_OFFSET_BASIS\n\tconst len = str.length\n\n\tfor (let i = 0; i < len; i++) {\n\t\thash ^= str.charCodeAt(i)\n\t\thash = Math.imul(hash, FNV_PRIME)\n\t}\n\n\treturn hash >>> 0\n}\n\nexport interface CookieOptions {\n\t/**\n\t * Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.3|Domain Set-Cookie attribute}. By default, no\n\t * domain is set, and most clients will consider the cookie to apply to only\n\t * the current domain.\n\t */\n\tdomain?: string | undefined\n\n\t/**\n\t * Specifies the `Date` object to be the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.1|`Expires` `Set-Cookie` attribute}. By default,\n\t * no expiration is set, and most clients will consider this a \"non-persistent cookie\" and will delete\n\t * it on a condition like exiting a web browser application.\n\t *\n\t * *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}\n\t * states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is\n\t * possible not all clients by obey this, so if both are set, they should\n\t * point to the same date and time.\n\t */\n\texpires?: Date | undefined\n\t/**\n\t * Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.6|`HttpOnly` `Set-Cookie` attribute}.\n\t * When truthy, the `HttpOnly` attribute is set, otherwise it is not. By\n\t * default, the `HttpOnly` attribute is not set.\n\t *\n\t * *Note* be careful when setting this to true, as compliant clients will\n\t * not allow client-side JavaScript to see the cookie in `document.cookie`.\n\t */\n\thttpOnly?: boolean | undefined\n\t/**\n\t * Specifies the number (in seconds) to be the value for the `Max-Age`\n\t * `Set-Cookie` attribute. The given number will be converted to an integer\n\t * by rounding down. By default, no maximum age is set.\n\t *\n\t * *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}\n\t * states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is\n\t * possible not all clients by obey this, so if both are set, they should\n\t * point to the same date and time.\n\t */\n\tmaxAge?: number | undefined\n\t/**\n\t * Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.4|`Path` `Set-Cookie` attribute}.\n\t * By default, the path is considered the \"default path\".\n\t */\n\tpath?: string | undefined\n\t/**\n\t * Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1].\n\t *\n\t * - `'low'` will set the `Priority` attribute to `Low`.\n\t * - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set.\n\t * - `'high'` will set the `Priority` attribute to `High`.\n\t *\n\t * More information about the different priority levels can be found in\n\t * [the specification][rfc-west-cookie-priority-00-4.1].\n\t *\n\t * **note** This is an attribute that has not yet been fully standardized, and may change in the future.\n\t * This also means many clients may ignore this attribute until they understand it.\n\t */\n\tpriority?: 'low' | 'medium' | 'high' | undefined\n\t/**\n\t * Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](rfc-cutler-httpbis-partitioned-cookies)\n\t * attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the\n\t * `Partitioned` attribute is not set.\n\t *\n\t * **note** This is an attribute that has not yet been fully standardized, and may change in the future.\n\t * This also means many clients may ignore this attribute until they understand it.\n\t *\n\t * More information about can be found in [the proposal](https://github.com/privacycg/CHIPS)\n\t */\n\tpartitioned?: boolean | undefined\n\t/**\n\t * Specifies the boolean or string to be the value for the {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|`SameSite` `Set-Cookie` attribute}.\n\t *\n\t * - `true` will set the `SameSite` attribute to `Strict` for strict same\n\t * site enforcement.\n\t * - `false` will not set the `SameSite` attribute.\n\t * - `'lax'` will set the `SameSite` attribute to Lax for lax same site\n\t * enforcement.\n\t * - `'strict'` will set the `SameSite` attribute to Strict for strict same\n\t * site enforcement.\n\t *  - `'none'` will set the SameSite attribute to None for an explicit\n\t *  cross-site cookie.\n\t *\n\t * More information about the different enforcement levels can be found in {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|the specification}.\n\t *\n\t * *note* This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.\n\t */\n\tsameSite?: true | false | 'lax' | 'strict' | 'none' | undefined\n\t/**\n\t * Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.5|`Secure` `Set-Cookie` attribute}. When truthy, the\n\t * `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.\n\t *\n\t * *Note* be careful when setting this to `true`, as compliant clients will\n\t * not send the cookie back to the server in the future if the browser does\n\t * not have an HTTPS connection.\n\t */\n\tsecure?: boolean | undefined\n\n\t/**\n\t * Secret key for signing cookie\n\t *\n\t * If array is passed, will use Key Rotation.\n\t *\n\t * Key rotation is when an encryption key is retired\n\t * and replaced by generating a new cryptographic key.\n\t *\n\t * When null is provided in array,\n\t * Elysia will allow unsigned cookie for smooth\n\t * transition from unsign to sign\n\t */\n\tsecrets?: string | null | (string | null)[]\n}\n\nexport type ElysiaCookie = Prettify<\n\tCookieOptions & {\n\t\tvalue?: unknown\n\t}\n>\n\ntype Updater<T> = T | ((value: T) => T)\n\nexport class Cookie<T> implements ElysiaCookie {\n\tprivate valueHash?: number\n\n\tconstructor(\n\t\tprivate name: string,\n\t\tprivate jar: Record<string, ElysiaCookie>,\n\t\tprivate initial: Partial<ElysiaCookie> = Object.create(null)\n\t) {}\n\n\tget cookie() {\n\t\treturn this.jar[this.name] ?? this.initial\n\t}\n\n\tset cookie(jar: ElysiaCookie) {\n\t\tif (!(this.name in this.jar)) this.jar[this.name] = this.initial\n\n\t\tthis.jar[this.name] = jar\n\t\t// Invalidate hash cache when jar is modified directly\n\t\tthis.valueHash = undefined\n\t}\n\n\tprotected get setCookie() {\n\t\tif (!(this.name in this.jar)) this.jar[this.name] = this.initial\n\n\t\treturn this.jar[this.name]\n\t}\n\n\tprotected set setCookie(jar: ElysiaCookie) {\n\t\tthis.cookie = jar\n\t}\n\n\tget value(): T {\n\t\treturn this.cookie.value as T\n\t}\n\n\tset value(value: T) {\n\t\t// Check if value actually changed before creating entry in jar\n\t\tconst current = this.cookie.value\n\n\t\t// Simple equality check\n\t\tif (current === value) return\n\n\t\t// For objects, use hash-based comparison for performance\n\t\t// Note: Uses JSON.stringify for comparison, so key order matters\n\t\t// { a: 1, b: 2 } and { b: 2, a: 1 } are treated as different values\n\t\tif (\n\t\t\ttypeof current === 'object' &&\n\t\t\tcurrent !== null &&\n\t\t\ttypeof value === 'object' &&\n\t\t\tvalue !== null\n\t\t) {\n\t\t\ttry {\n\t\t\t\t// Cache stringified value to avoid duplicate stringify calls\n\t\t\t\tconst valueStr = JSON.stringify(value)\n\t\t\t\tconst newHash = hashString(valueStr)\n\n\t\t\t\t// If hash differs from cached hash, value definitely changed\n\t\t\t\tif (\n\t\t\t\t\tthis.valueHash !== undefined &&\n\t\t\t\t\tthis.valueHash !== newHash\n\t\t\t\t) {\n\t\t\t\t\tthis.valueHash = newHash\n\t\t\t\t}\n\t\t\t\t// First set (valueHash undefined) OR hashes match: do deep comparison\n\t\t\t\telse {\n\t\t\t\t\tif (JSON.stringify(current) === valueStr) {\n\t\t\t\t\t\tthis.valueHash = newHash\n\t\t\t\t\t\treturn // Values are identical, skip update\n\t\t\t\t\t}\n\t\t\t\t\tthis.valueHash = newHash\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t}\n\n\t\t// Only create entry in jar if value actually changed\n\t\tif (!(this.name in this.jar)) this.jar[this.name] = { ...this.initial }\n\t\tthis.jar[this.name].value = value\n\t}\n\n\tget expires() {\n\t\treturn this.cookie.expires\n\t}\n\n\tset expires(expires: Date | undefined) {\n\t\tthis.setCookie.expires = expires\n\t}\n\n\tget maxAge() {\n\t\treturn this.cookie.maxAge\n\t}\n\n\tset maxAge(maxAge: number | undefined) {\n\t\tthis.setCookie.maxAge = maxAge\n\t}\n\n\tget domain() {\n\t\treturn this.cookie.domain\n\t}\n\n\tset domain(domain: string | undefined) {\n\t\tthis.setCookie.domain = domain\n\t}\n\n\tget path() {\n\t\treturn this.cookie.path\n\t}\n\n\tset path(path: string | undefined) {\n\t\tthis.setCookie.path = path\n\t}\n\n\tget secure() {\n\t\treturn this.cookie.secure\n\t}\n\n\tset secure(secure: boolean | undefined) {\n\t\tthis.setCookie.secure = secure\n\t}\n\n\tget httpOnly() {\n\t\treturn this.cookie.httpOnly\n\t}\n\n\tset httpOnly(httpOnly: boolean | undefined) {\n\t\tthis.setCookie.httpOnly = httpOnly\n\t}\n\n\tget sameSite() {\n\t\treturn this.cookie.sameSite\n\t}\n\n\tset sameSite(\n\t\tsameSite: true | false | 'lax' | 'strict' | 'none' | undefined\n\t) {\n\t\tthis.setCookie.sameSite = sameSite\n\t}\n\n\tget priority() {\n\t\treturn this.cookie.priority\n\t}\n\n\tset priority(priority: 'low' | 'medium' | 'high' | undefined) {\n\t\tthis.setCookie.priority = priority\n\t}\n\n\tget partitioned() {\n\t\treturn this.cookie.partitioned\n\t}\n\n\tset partitioned(partitioned: boolean | undefined) {\n\t\tthis.setCookie.partitioned = partitioned\n\t}\n\n\tget secrets() {\n\t\treturn this.cookie.secrets\n\t}\n\n\tset secrets(secrets: ElysiaCookie['secrets']) {\n\t\tthis.setCookie.secrets = secrets\n\t}\n\n\tupdate(config: Updater<Partial<ElysiaCookie>>) {\n\t\tthis.setCookie = Object.assign(\n\t\t\tthis.cookie,\n\t\t\ttypeof config === 'function' ? config(this.cookie) : config\n\t\t)\n\n\t\treturn this\n\t}\n\n\tset(config: Updater<Partial<ElysiaCookie>>) {\n\t\tthis.setCookie = Object.assign(\n\t\t\t{\n\t\t\t\t...this.initial,\n\t\t\t\tvalue: this.value\n\t\t\t},\n\t\t\ttypeof config === 'function' ? config(this.cookie) : config\n\t\t)\n\n\t\treturn this\n\t}\n\n\tremove() {\n\t\tif (this.value === undefined) return\n\n\t\tthis.set({\n\t\t\texpires: new Date(0),\n\t\t\tmaxAge: 0,\n\t\t\tvalue: ''\n\t\t})\n\n\t\treturn this\n\t}\n\n\ttoString() {\n\t\treturn typeof this.value === 'object'\n\t\t\t? JSON.stringify(this.value)\n\t\t\t: (this.value?.toString() ?? '')\n\t}\n}\n\nexport const createCookieJar = (\n\tset: Context['set'],\n\tstore: Record<string, ElysiaCookie>,\n\tinitial?: Partial<ElysiaCookie>\n): Record<string, Cookie<unknown>> => {\n\tif (!set.cookie) set.cookie = Object.create(null)\n\n\treturn new Proxy(store, {\n\t\tget(_, key: string) {\n\t\t\tif (key in store)\n\t\t\t\treturn new Cookie(\n\t\t\t\t\tkey,\n\t\t\t\t\tset.cookie as Record<string, ElysiaCookie>,\n\t\t\t\t\tObject.assign({}, initial ?? {}, store[key])\n\t\t\t\t)\n\n\t\t\treturn new Cookie(\n\t\t\t\tkey,\n\t\t\t\tset.cookie as Record<string, ElysiaCookie>,\n\t\t\t\tObject.assign({}, initial)\n\t\t\t)\n\t\t}\n\t}) as Record<string, Cookie<unknown>>\n}\n\nexport const parseCookie = async (\n\tset: Context['set'],\n\tcookieString?: string | null,\n\t{\n\t\tsecrets,\n\t\tsign,\n\t\t...initial\n\t}: CookieOptions & {\n\t\tsign?: true | string | string[]\n\t} = Object.create(null)\n) => {\n\tif (!cookieString) return createCookieJar(set, Object.create(null), initial)\n\n\tconst isStringKey = typeof secrets === 'string'\n\tif (sign && sign !== true && !Array.isArray(sign)) sign = [sign]\n\n\tconst jar: Record<string, ElysiaCookie> = Object.create(null)\n\n\tconst cookies = parse(cookieString)\n\tfor (const [name, v] of Object.entries(cookies)) {\n\t\tif (\n\t\t\tv === undefined ||\n\t\t\tname === '__proto__' ||\n\t\t\tname === 'constructor' ||\n\t\t\tname === 'prototype'\n\t\t)\n\t\t\tcontinue\n\n\t\tlet value = decode(v)\n\n\t\tif (sign === true || sign?.includes(name)) {\n\t\t\tif (!secrets)\n\t\t\t\tthrow new Error('No secret is provided to cookie plugin')\n\n\t\t\tif (isStringKey) {\n\t\t\t\tif (typeof value !== 'string')\n\t\t\t\t\tthrow new InvalidCookieSignature(name)\n\n\t\t\t\tconst temp = await unsignCookie(value, secrets)\n\t\t\t\tif (temp === false) throw new InvalidCookieSignature(name)\n\n\t\t\t\tvalue = temp\n\t\t\t} else {\n\t\t\t\tlet decoded = false\n\t\t\t\tfor (let i = 0; i < secrets.length; i++) {\n\t\t\t\t\tif (typeof value !== 'string')\n\t\t\t\t\t\tthrow new InvalidCookieSignature(name)\n\n\t\t\t\t\tconst temp = await unsignCookie(value, secrets[i])\n\n\t\t\t\t\tif (temp !== false) {\n\t\t\t\t\t\tdecoded = true\n\t\t\t\t\t\tvalue = temp\n\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!decoded) throw new InvalidCookieSignature(name)\n\t\t\t}\n\t\t}\n\n\t\t// decode cookie after unsigned\n\t\tif (value) {\n\t\t\tconst starts = value.charCodeAt(0)\n\t\t\tconst ends = value.charCodeAt(value.length - 1)\n\n\t\t\tif (\n\t\t\t\t(starts === 123 && ends === 125) ||\n\t\t\t\t(starts === 91 && ends === 93)\n\t\t\t)\n\t\t\t\ttry {\n\t\t\t\t\tvalue = JSON.parse(value)\n\t\t\t\t} catch {}\n\t\t}\n\n\t\tjar[name] = Object.create(null)\n\t\tjar[name].value = value\n\t}\n\n\treturn createCookieJar(set, jar, initial)\n}\n\nexport const serializeCookie = (cookies: Context['set']['cookie']) => {\n\tif (!cookies || !isNotEmpty(cookies)) return undefined\n\n\tconst set: string[] = []\n\n\tfor (const [key, property] of Object.entries(cookies)) {\n\t\tif (!key || !property) continue\n\n\t\tconst value = property.value\n\t\tif (value === undefined || value === null) continue\n\n\t\tset.push(\n\t\t\tserialize(\n\t\t\t\tkey,\n\t\t\t\ttypeof value === 'object' ? JSON.stringify(value) : value + '',\n\t\t\t\tproperty\n\t\t\t)\n\t\t)\n\t}\n\n\tif (set.length === 0) return undefined\n\tif (set.length === 1) return set[0]\n\n\treturn set\n}\n"
  },
  {
    "path": "src/dynamic-handle.ts",
    "content": "import { TransformDecodeError } from '@sinclair/typebox/value'\nimport type { Context } from './context'\nimport { parseCookie } from './cookies'\nimport {\n\tElysiaCustomStatusResponse,\n\ttype ElysiaErrors,\n\tNotFoundError,\n\tstatus,\n\tValidationError\n} from './error'\nimport type { AnyElysia, CookieOptions } from './index'\nimport { parseQuery } from './parse-query'\nimport { getSchemaProperties, type ElysiaTypeCheck } from './schema'\nimport type { TypeCheck } from './type-system'\nimport type { Handler, LifeCycleStore, SchemaValidator } from './types'\nimport { hasSetImmediate, redirect, StatusMap, signCookie } from './utils'\n\n// JIT Handler\nexport type DynamicHandler = {\n\thandle: unknown | Handler<any, any>\n\tcontent?: string\n\thooks: Partial<LifeCycleStore>\n\tvalidator?: SchemaValidator\n\troute: string\n}\n\n/**\n * Matches array index notation in property paths\n * Examples:\n *   \"users[0]\"  → Group 1: \"users\", Group 2: \"0\"\n *   \"items[42]\" → Group 1: \"items\", Group 2: \"42\"\n *   \"a[123]\"    → Group 1: \"a\",     Group 2: \"123\"\n *\n * Does not match:\n *   \"users\"     → no brackets\n *   \"users[]\"   → no index\n *   \"users[ab]\" → non-numeric index\n */\nconst ARRAY_INDEX_REGEX = /^(.+)\\[(\\d+)\\]$/\nconst DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype'])\n\nconst isDangerousKey = (key: string): boolean => {\n\tif (DANGEROUS_KEYS.has(key)) return true\n\n\tconst match = key.match(ARRAY_INDEX_REGEX)\n\treturn match ? DANGEROUS_KEYS.has(match[1]) : false\n}\n\nconst parseArrayKey = (key: string) => {\n\tconst match = key.match(ARRAY_INDEX_REGEX)\n\tif (!match) return null\n\n\treturn {\n\t\tname: match[1],\n\t\tindex: parseInt(match[2], 10)\n\t}\n}\n\nconst parseObjectString = (entry: unknown) => {\n\tif (typeof entry !== 'string' || entry.charCodeAt(0) !== 123) return\n\n\ttry {\n\t\tconst parsed = JSON.parse(entry)\n\t\tif (parsed && typeof parsed === 'object' && !Array.isArray(parsed))\n\t\t\treturn parsed\n\t} catch {\n\t\treturn\n\t}\n}\n\nconst setNestedValue = (obj: Record<string, any>, path: string, value: any) => {\n\tconst keys = path.split('.')\n\tconst lastKey = keys.pop() as string\n\n\t// Validate all keys upfront\n\tif (isDangerousKey(lastKey) || keys.some(isDangerousKey)) return\n\n\tlet current = obj\n\n\t// Traverse intermediate keys\n\tfor (const key of keys) {\n\t\tconst arrayInfo = parseArrayKey(key)\n\n\t\tif (arrayInfo) {\n\t\t\t// Initialize array if needed\n\t\t\tif (!Array.isArray(current[arrayInfo.name]))\n\t\t\t\tcurrent[arrayInfo.name] = []\n\n\t\t\tconst existing = current[arrayInfo.name][arrayInfo.index]\n\t\t\tconst isFile =\n\t\t\t\ttypeof File !== 'undefined' && existing instanceof File\n\n\t\t\t// Initialize object at index if needed\n\t\t\tif (\n\t\t\t\t!existing ||\n\t\t\t\ttypeof existing !== 'object' ||\n\t\t\t\tArray.isArray(existing) ||\n\t\t\t\tisFile\n\t\t\t)\n\t\t\t\tcurrent[arrayInfo.name][arrayInfo.index] =\n\t\t\t\t\tparseObjectString(existing) ?? {}\n\n\t\t\tcurrent = current[arrayInfo.name][arrayInfo.index]\n\t\t} else {\n\t\t\t// Initialize object property if needed\n\t\t\tif (!current[key] || typeof current[key] !== 'object')\n\t\t\t\tcurrent[key] = {}\n\n\t\t\tcurrent = current[key]\n\t\t}\n\t}\n\n\t// Set final value\n\tconst arrayInfo = parseArrayKey(lastKey)\n\n\tif (arrayInfo) {\n\t\tif (!Array.isArray(current[arrayInfo.name]))\n\t\t\tcurrent[arrayInfo.name] = []\n\n\t\tcurrent[arrayInfo.name][arrayInfo.index] = value\n\t} else {\n\t\tcurrent[lastKey] = value\n\t}\n}\n\nconst normalizeFormValue = (value: unknown[]) => {\n    if (value.length === 1) {\n        const stringValue = value[0]\n        if (typeof stringValue === 'string') {\n            // Try to parse JSON objects (starting with '{') or arrays (starting with '[')\n            if (stringValue.charCodeAt(0) === 123 || stringValue.charCodeAt(0) === 91) {\n                try {\n                    const parsed = JSON.parse(stringValue)\n                    if (parsed && typeof parsed === 'object') {\n                        return parsed\n                    }\n                } catch {}\n            }\n        }\n        return value[0]\n    }\n\n\tconst stringValue = value.find(\n\t\t(entry): entry is string => typeof entry === 'string'\n\t)\n\tif (!stringValue) return value\n\n\tif (typeof File === 'undefined') return value\n\tconst files = value.filter((entry): entry is File => entry instanceof File)\n\tif (!files.length) return value\n\n\tif (stringValue.charCodeAt(0) !== 123) return value\n\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(stringValue)\n\t} catch {\n\t\treturn value\n\t}\n\n\tif (typeof parsed !== 'object' || parsed === null) return value\n\n\tif (!('file' in parsed) && files.length === 1)\n\t\t(parsed as Record<string, unknown>).file = files[0]\n\telse if (!('files' in parsed) && files.length > 1)\n\t\t(parsed as Record<string, unknown>).files = files\n\n\treturn parsed\n}\n\nconst injectDefaultValues = (\n\ttypeChecker: TypeCheck<any> | ElysiaTypeCheck<any>,\n\tobj: Record<string, any>\n) => {\n\t// @ts-expect-error private property\n\tlet schema = typeChecker.schema\n\tif (!schema) return\n\n\tif (schema.$defs?.[schema.$ref]) schema = schema.$defs[schema.$ref]\n\n\tconst properties = getSchemaProperties(schema)\n\tif (!properties) return\n\n\tfor (const [key, keySchema] of Object.entries(properties)) {\n\t\tobj[key] ??= keySchema.default\n\t}\n}\n\nexport const createDynamicHandler = (app: AnyElysia) => {\n\tconst { mapResponse, mapEarlyResponse } = app['~adapter'].handler\n\n\t// @ts-expect-error\n\tconst defaultHeader = app.setHeaders\n\n\treturn async (request: Request): Promise<Response> => {\n\t\tconst url = request.url,\n\t\t\ts = url.indexOf('/', 11),\n\t\t\tqi = url.indexOf('?', s + 1),\n\t\t\tpath = qi === -1 ? url.substring(s) : url.substring(s, qi)\n\n\t\tconst set: Context['set'] = {\n\t\t\tcookie: {},\n\t\t\tstatus: 200,\n\t\t\theaders: defaultHeader ? { ...defaultHeader } : {}\n\t\t}\n\n\t\tconst context = Object.assign(\n\t\t\t{},\n\t\t\t// @ts-expect-error\n\t\t\tapp.singleton.decorator,\n\t\t\t{\n\t\t\t\tset,\n\t\t\t\t// @ts-expect-error\n\t\t\t\tstore: app.singleton.store,\n\t\t\t\trequest,\n\t\t\t\tpath,\n\t\t\t\tqi,\n\t\t\t\terror: status,\n\t\t\t\tstatus,\n\t\t\t\tredirect\n\t\t\t}\n\t\t) as unknown as Context & {\n\t\t\tresponse: unknown\n\t\t}\n\n\t\tlet hooks: DynamicHandler['hooks']\n\n\t\ttry {\n\t\t\tif (app.event.request)\n\t\t\t\tfor (let i = 0; i < app.event.request.length; i++) {\n\t\t\t\t\tconst onRequest = app.event.request[i].fn\n\t\t\t\t\tlet response = onRequest(context as any)\n\t\t\t\t\tif (response instanceof Promise) response = await response\n\n\t\t\t\t\tresponse = mapEarlyResponse(response, set)\n\t\t\t\t\tif (response) return (context.response = response)\n\t\t\t\t}\n\n\t\t\tconst isWS =\n\t\t\t\trequest.method === 'GET' &&\n\t\t\t\trequest.headers.get('upgrade')?.toLowerCase() === 'websocket'\n\n\t\t\tconst methodKey = isWS ? 'WS' : request.method\n\n\t\t\tconst handler =\n\t\t\t\tapp.router.dynamic.find(request.method, path) ??\n\t\t\t\tapp.router.dynamic.find(methodKey, path) ??\n\t\t\t\tapp.router.dynamic.find('ALL', path)\n\n\t\t\tif (!handler) {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tcontext.query =\n\t\t\t\t\tqi === -1 ? {} : parseQuery(url.substring(qi + 1))\n\n\t\t\t\tthrow new NotFoundError()\n\t\t\t}\n\n\t\t\tconst { handle, validator, content, route } = handler.store\n\t\t\thooks = handler.store.hooks\n\n\t\t\t// @ts-ignore\n\t\t\tif (hooks.config?.mount)\n\t\t\t\t// @ts-ignore\n\t\t\t\treturn await hooks.config.mount(request)\n\n\t\t\tlet body: string | Record<string, any> | undefined\n\t\t\tif (request.method !== 'GET' && request.method !== 'HEAD') {\n\t\t\t\tif (content) {\n\t\t\t\t\tswitch (content) {\n\t\t\t\t\t\tcase 'application/json':\n\t\t\t\t\t\t\tbody = (await request.json()) as any\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\tcase 'text/plain':\n\t\t\t\t\t\t\tbody = await request.text()\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\tcase 'application/x-www-form-urlencoded':\n\t\t\t\t\t\t\tbody = parseQuery(await request.text())\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\tcase 'application/octet-stream':\n\t\t\t\t\t\t\tbody = await request.arrayBuffer()\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\tcase 'multipart/form-data': {\n\t\t\t\t\t\t\tbody = {}\n\n\t\t\t\t\t\t\tconst form = await request.formData()\n\t\t\t\t\t\t\tfor (const key of form.keys()) {\n\t\t\t\t\t\t\t\tif (body[key]) continue\n\n\t\t\t\t\t\t\t\tconst value = form.getAll(key)\n\t\t\t\t\t\t\t\tconst finalValue = normalizeFormValue(value)\n\n\t\t\t\t\t\t\t\tif (key.includes('.') || key.includes('['))\n\t\t\t\t\t\t\t\t\tsetNestedValue(body, key, finalValue)\n\t\t\t\t\t\t\t\telse body[key] = finalValue\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlet contentType\n\t\t\t\t\tif (request.body)\n\t\t\t\t\t\tcontentType = request.headers.get('content-type')\n\n\t\t\t\t\tif (contentType) {\n\t\t\t\t\t\tconst index = contentType.indexOf(';')\n\t\t\t\t\t\tif (index !== -1)\n\t\t\t\t\t\t\tcontentType = contentType.slice(0, index)\n\n\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\tcontext.contentType = contentType\n\n\t\t\t\t\t\tif (hooks.parse)\n\t\t\t\t\t\t\tfor (let i = 0; i < hooks.parse.length; i++) {\n\t\t\t\t\t\t\t\tconst hook = hooks.parse[i].fn\n\n\t\t\t\t\t\t\t\tif (typeof hook === 'string')\n\t\t\t\t\t\t\t\t\tswitch (hook) {\n\t\t\t\t\t\t\t\t\t\tcase 'json':\n\t\t\t\t\t\t\t\t\t\tcase 'application/json':\n\t\t\t\t\t\t\t\t\t\t\tbody = (await request.json()) as any\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\t\t\tcase 'text':\n\t\t\t\t\t\t\t\t\t\tcase 'text/plain':\n\t\t\t\t\t\t\t\t\t\t\tbody = await request.text()\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\t\t\tcase 'urlencoded':\n\t\t\t\t\t\t\t\t\t\tcase 'application/x-www-form-urlencoded':\n\t\t\t\t\t\t\t\t\t\t\tbody = parseQuery(\n\t\t\t\t\t\t\t\t\t\t\t\tawait request.text()\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\t\t\tcase 'arrayBuffer':\n\t\t\t\t\t\t\t\t\t\tcase 'application/octet-stream':\n\t\t\t\t\t\t\t\t\t\t\tbody = await request.arrayBuffer()\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\t\t\tcase 'formdata':\n\t\t\t\t\t\t\t\t\t\tcase 'multipart/form-data': {\n\t\t\t\t\t\t\t\t\t\t\tbody = {}\n\n\t\t\t\t\t\t\t\t\t\t\tconst form = await request.formData()\n\t\t\t\t\t\t\t\t\t\t\tfor (const key of form.keys()) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (body[key]) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\tconst value = form.getAll(key)\n\t\t\t\t\t\t\t\t\t\t\t\tconst finalValue = normalizeFormValue(value)\n\n\t\t\t\t\t\t\t\t\t\t\t\tif (key.includes('.') || key.includes('['))\n\t\t\t\t\t\t\t\t\t\t\t\t\tsetNestedValue(body, key, finalValue)\n\t\t\t\t\t\t\t\t\t\t\t\telse body[key] = finalValue\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tdefault: {\n\t\t\t\t\t\t\t\t\t\t\tconst parser = app['~parser'][hook]\n\t\t\t\t\t\t\t\t\t\t\tif (parser) {\n\t\t\t\t\t\t\t\t\t\t\t\tlet temp = parser(\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontext as any,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontentType\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\tif (temp instanceof Promise)\n\t\t\t\t\t\t\t\t\t\t\t\t\ttemp = await temp\n\n\t\t\t\t\t\t\t\t\t\t\t\tif (temp) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tbody = temp\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tlet temp = hook(context as any, contentType)\n\t\t\t\t\t\t\t\t\tif (temp instanceof Promise)\n\t\t\t\t\t\t\t\t\t\ttemp = await temp\n\n\t\t\t\t\t\t\t\t\tif (temp) {\n\t\t\t\t\t\t\t\t\t\tbody = temp\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\tdelete context.contentType\n\n\t\t\t\t\t\t// body might be empty string thus can't use !body\n\t\t\t\t\t\tif (body === undefined) {\n\t\t\t\t\t\t\tswitch (contentType) {\n\t\t\t\t\t\t\t\tcase 'application/json':\n\t\t\t\t\t\t\t\t\tbody = (await request.json()) as any\n\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\tcase 'text/plain':\n\t\t\t\t\t\t\t\t\tbody = await request.text()\n\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\tcase 'application/x-www-form-urlencoded':\n\t\t\t\t\t\t\t\t\tbody = parseQuery(await request.text())\n\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\tcase 'application/octet-stream':\n\t\t\t\t\t\t\t\t\tbody = await request.arrayBuffer()\n\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\tcase 'multipart/form-data': {\n\t\t\t\t\t\t\t\t\tbody = {}\n\n\t\t\t\t\t\t\t\t\tconst form = await request.formData()\n\t\t\t\t\t\t\t\t\tfor (const key of form.keys()) {\n\t\t\t\t\t\t\t\t\t\tif (body[key]) continue\n\n\t\t\t\t\t\t\t\t\t\tconst value = form.getAll(key)\n\t\t\t\t\t\t\t\t\t\tconst finalValue = normalizeFormValue(value)\n\n\t\t\t\t\t\t\t\t\t\tif (key.includes('.') || key.includes('['))\n\t\t\t\t\t\t\t\t\t\t\tsetNestedValue(body, key, finalValue)\n\t\t\t\t\t\t\t\t\t\telse body[key] = finalValue\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontext.route = route\n\t\t\tcontext.body = body\n\t\t\tcontext.params = handler?.params || undefined\n\n\t\t\t// @ts-expect-error\n\t\t\tcontext.query = qi === -1 ? {} : parseQuery(url.substring(qi + 1))\n\n\t\t\tcontext.headers = {}\n\t\t\tfor (const [key, value] of request.headers.entries())\n\t\t\t\tcontext.headers[key] = value\n\n\t\t\tconst cookieMeta = {\n\t\t\t\tdomain:\n\t\t\t\t\tapp.config.cookie?.domain ??\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tvalidator?.cookie?.config.domain,\n\t\t\t\texpires:\n\t\t\t\t\tapp.config.cookie?.expires ??\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tvalidator?.cookie?.config.expires,\n\t\t\t\thttpOnly:\n\t\t\t\t\tapp.config.cookie?.httpOnly ??\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tvalidator?.cookie?.config.httpOnly,\n\t\t\t\tmaxAge:\n\t\t\t\t\tapp.config.cookie?.maxAge ??\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tvalidator?.cookie?.config.maxAge,\n\t\t\t\t// @ts-expect-error\n\t\t\t\tpath: app.config.cookie?.path ?? validator?.cookie?.config.path,\n\t\t\t\tpriority:\n\t\t\t\t\tapp.config.cookie?.priority ??\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tvalidator?.cookie?.config.priority,\n\t\t\t\tpartitioned:\n\t\t\t\t\tapp.config.cookie?.partitioned ??\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tvalidator?.cookie?.config.partitioned,\n\t\t\t\tsameSite:\n\t\t\t\t\tapp.config.cookie?.sameSite ??\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tvalidator?.cookie?.config.sameSite,\n\t\t\t\tsecure:\n\t\t\t\t\tapp.config.cookie?.secure ??\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tvalidator?.cookie?.config.secure,\n\t\t\t\tsecrets:\n\t\t\t\t\tapp.config.cookie?.secrets ??\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tvalidator?.cookie?.config.secrets,\n\t\t\t\t// @ts-expect-error\n\t\t\t\tsign: app.config.cookie?.sign ?? validator?.cookie?.config.sign\n\t\t\t} as CookieOptions & {\n\t\t\t\tsign?: true | string | string[]\n\t\t\t}\n\n\t\t\tconst cookieHeaderValue = request.headers.get('cookie')\n\n\t\t\tcontext.cookie = (await parseCookie(\n\t\t\t\tcontext.set,\n\t\t\t\tcookieHeaderValue,\n\t\t\t\tcookieMeta\n\t\t\t)) as any\n\n\t\t\tconst headerValidator = validator?.createHeaders?.()\n\t\t\tif (headerValidator)\n\t\t\t\tinjectDefaultValues(headerValidator, context.headers)\n\n\t\t\tconst paramsValidator = validator?.createParams?.()\n\t\t\tif (paramsValidator)\n\t\t\t\tinjectDefaultValues(paramsValidator, context.params)\n\n\t\t\tconst queryValidator = validator?.createQuery?.()\n\t\t\tif (queryValidator)\n\t\t\t\tinjectDefaultValues(queryValidator, context.query)\n\n\t\t\tif (hooks.transform)\n\t\t\t\tfor (let i = 0; i < hooks.transform.length; i++) {\n\t\t\t\t\tconst hook = hooks.transform[i]\n\t\t\t\t\tlet response = hook.fn(context)\n\n\t\t\t\t\tif (response instanceof Promise) response = await response\n\n\t\t\t\t\t// @ts-expect-error just in case\n\t\t\t\t\tif (response instanceof ElysiaCustomStatusResponse) {\n\t\t\t\t\t\tconst result = mapEarlyResponse(response, context.set)\n\t\t\t\t\t\tif (result)\n\t\t\t\t\t\t\treturn (context.response = result) as Response\n\t\t\t\t\t}\n\n\t\t\t\t\tif (hook.subType === 'derive')\n\t\t\t\t\t\tObject.assign(context, response)\n\t\t\t\t}\n\n\t\t\tif (validator) {\n\t\t\t\tif (headerValidator) {\n\t\t\t\t\tconst _header = structuredClone(context.headers)\n\t\t\t\t\tfor (const [key, value] of request.headers)\n\t\t\t\t\t\t_header[key] = value\n\n\t\t\t\t\tif (validator.headers!.Check(_header) === false)\n\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t'header',\n\t\t\t\t\t\t\tvalidator.headers!,\n\t\t\t\t\t\t\t_header\n\t\t\t\t\t\t)\n\t\t\t\t} else if (validator.headers?.Decode)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tcontext.headers = validator.headers.Decode(context.headers)\n\n\t\t\t\tif (paramsValidator?.Check(context.params) === false) {\n\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t'params',\n\t\t\t\t\t\tvalidator.params!,\n\t\t\t\t\t\tcontext.params\n\t\t\t\t\t)\n\t\t\t\t} else if (validator.params?.Decode)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tcontext.params = validator.params.Decode(context.params)\n\n\t\t\t\tif (validator.query?.schema) {\n\t\t\t\t\tlet schema = validator.query.schema\n\t\t\t\t\tif (schema.$defs?.[schema.$ref])\n\t\t\t\t\t\tschema = schema.$defs[schema.$ref]\n\n\t\t\t\t\tconst properties = getSchemaProperties(schema)\n\n\t\t\t\t\tif (properties) {\n\t\t\t\t\t\tfor (const property of Object.keys(properties)) {\n\t\t\t\t\t\t\tconst value = properties[property]\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t(value.type === 'array' ||\n\t\t\t\t\t\t\t\t\tvalue.items?.type === 'string') &&\n\t\t\t\t\t\t\t\ttypeof context.query[property] === 'string' &&\n\t\t\t\t\t\t\t\tcontext.query[property]\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\t\tcontext.query[property] =\n\t\t\t\t\t\t\t\t\tcontext.query[property].split(',')\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (queryValidator?.Check(context.query) === false)\n\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t'query',\n\t\t\t\t\t\tvalidator.query!,\n\t\t\t\t\t\tcontext.query\n\t\t\t\t\t)\n\t\t\t\telse if (validator.query?.Decode)\n\t\t\t\t\tcontext.query = validator.query.Decode(context.query) as any\n\n\t\t\t\tif (validator.createCookie?.()) {\n\t\t\t\t\tlet cookieValue: Record<string, unknown> = {}\n\t\t\t\t\tfor (const [key, value] of Object.entries(context.cookie))\n\t\t\t\t\t\tcookieValue[key] = value.value\n\n\t\t\t\t\tif (validator.cookie!.Check(cookieValue) === false)\n\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t'cookie',\n\t\t\t\t\t\t\tvalidator.cookie!,\n\t\t\t\t\t\t\tcookieValue\n\t\t\t\t\t\t)\n\t\t\t\t\telse if (validator.cookie?.Decode)\n\t\t\t\t\t\tcookieValue = validator.cookie.Decode(\n\t\t\t\t\t\t\tcookieValue\n\t\t\t\t\t\t) as any\n\t\t\t\t}\n\n\t\t\t\tif (validator.createBody?.()?.Check(body) === false)\n\t\t\t\t\tthrow new ValidationError('body', validator.body!, body)\n\t\t\t\telse if (validator.body?.Decode) {\n\t\t\t\t\t\tlet decoded = validator.body.Decode(body) as any\n\t\t\t\t\t\tif (decoded instanceof Promise)\n\t\t\t\t\t\t\tdecoded = await decoded\n\n\t\t\t\t\t\t// Zod returns { value: ... } wrapper\n\t\t\t\t\t\tcontext.body = decoded?.value ?? decoded\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (hooks.beforeHandle)\n\t\t\t\tfor (let i = 0; i < hooks.beforeHandle.length; i++) {\n\t\t\t\t\tconst hook = hooks.beforeHandle[i]\n\t\t\t\t\tlet response = hook.fn(context)\n\t\t\t\t\tif (response instanceof Promise) response = await response\n\n\t\t\t\t\tif (response instanceof ElysiaCustomStatusResponse) {\n\t\t\t\t\t\tconst result = mapEarlyResponse(response, context.set)\n\t\t\t\t\t\tif (result)\n\t\t\t\t\t\t\treturn (context.response = result) as Response\n\t\t\t\t\t}\n\n\t\t\t\t\tif (hook.subType === 'resolve') {\n\t\t\t\t\t\tObject.assign(context, response)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\t// `false` is a falsey value, check for undefined instead\n\t\t\t\t\tif (response !== undefined) {\n\t\t\t\t\t\t;(\n\t\t\t\t\t\t\tcontext as Context & {\n\t\t\t\t\t\t\t\tresponse: unknown\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t).response = response\n\n\t\t\t\t\t\tif (hooks.afterHandle)\n\t\t\t\t\t\t\tfor (let i = 0; i < hooks.afterHandle.length; i++) {\n\t\t\t\t\t\t\t\tlet newResponse = hooks.afterHandle[i].fn(\n\t\t\t\t\t\t\t\t\tcontext as Context & {\n\t\t\t\t\t\t\t\t\t\tresponse: unknown\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tif (newResponse instanceof Promise)\n\t\t\t\t\t\t\t\t\tnewResponse = await newResponse\n\n\t\t\t\t\t\t\t\tif (newResponse) response = newResponse\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst result = mapEarlyResponse(response, context.set)\n\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\tif (result) return (context.response = result)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tlet response =\n\t\t\t\ttypeof handle === 'function' ? handle(context) : handle\n\t\t\tif (response instanceof Promise) response = await response\n\n\t\t\tif (!hooks.afterHandle?.length) {\n\t\t\t\tconst isCustomStatuResponse =\n\t\t\t\t\tresponse instanceof ElysiaCustomStatusResponse\n\n\t\t\t\tconst status = isCustomStatuResponse\n\t\t\t\t\t? response.code\n\t\t\t\t\t: set.status\n\t\t\t\t\t\t? typeof set.status === 'string'\n\t\t\t\t\t\t\t? StatusMap[set.status]\n\t\t\t\t\t\t\t: set.status\n\t\t\t\t\t\t: 200\n\n\t\t\t\tif (isCustomStatuResponse) {\n\t\t\t\t\tset.status = status\n\t\t\t\t\tresponse = response.response\n\t\t\t\t}\n\n\t\t\t\tconst responseValidator =\n\t\t\t\t\tvalidator?.createResponse?.()?.[status]\n\n\t\t\t\tif (responseValidator?.Check(response) === false) {\n\t\t\t\t\tif (responseValidator?.Clean) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst temp = responseValidator.Clean(response)\n\t\t\t\t\t\t\tif (responseValidator?.Check(temp) === false)\n\t\t\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t\t\t'response',\n\t\t\t\t\t\t\t\t\tresponseValidator,\n\t\t\t\t\t\t\t\t\tresponse\n\t\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\tresponse = temp\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (error instanceof ValidationError) throw error\n\n\t\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t\t'response',\n\t\t\t\t\t\t\t\tresponseValidator,\n\t\t\t\t\t\t\t\tresponse\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else\n\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t'response',\n\t\t\t\t\t\t\tresponseValidator,\n\t\t\t\t\t\t\tresponse\n\t\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (responseValidator?.Encode)\n\t\t\t\t\tresponse = responseValidator.Encode(response)\n\n\t\t\t\tif (responseValidator?.Clean)\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresponse = responseValidator.Clean(response)\n\t\t\t\t\t} catch {}\n\t\t\t} else {\n\t\t\t\t;(\n\t\t\t\t\tcontext as Context & {\n\t\t\t\t\t\tresponse: unknown\n\t\t\t\t\t}\n\t\t\t\t).response = response\n\n\t\t\t\tfor (let i = 0; i < hooks.afterHandle.length; i++) {\n\t\t\t\t\tlet response: unknown = hooks.afterHandle[i].fn(\n\t\t\t\t\t\tcontext as Context & {\n\t\t\t\t\t\t\tresponse: unknown\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t\tif (response instanceof Promise) response = await response\n\n\t\t\t\t\tconst isCustomStatuResponse =\n\t\t\t\t\t\tresponse instanceof ElysiaCustomStatusResponse\n\n\t\t\t\t\tconst status = isCustomStatuResponse\n\t\t\t\t\t\t? (response as ElysiaCustomStatusResponse<any>).code\n\t\t\t\t\t\t: set.status\n\t\t\t\t\t\t\t? typeof set.status === 'string'\n\t\t\t\t\t\t\t\t? StatusMap[set.status]\n\t\t\t\t\t\t\t\t: set.status\n\t\t\t\t\t\t\t: 200\n\n\t\t\t\t\tif (isCustomStatuResponse) {\n\t\t\t\t\t\tset.status = status\n\t\t\t\t\t\tresponse = (response as ElysiaCustomStatusResponse<any>)\n\t\t\t\t\t\t\t.response\n\t\t\t\t\t}\n\n\t\t\t\t\tconst responseValidator =\n\t\t\t\t\t\tvalidator?.createResponse?.()?.[status]\n\n\t\t\t\t\tif (responseValidator?.Check(response) === false) {\n\t\t\t\t\t\tif (responseValidator?.Clean) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst temp = responseValidator.Clean(response)\n\t\t\t\t\t\t\t\tif (responseValidator?.Check(temp) === false)\n\t\t\t\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t\t\t\t'response',\n\t\t\t\t\t\t\t\t\t\tresponseValidator,\n\t\t\t\t\t\t\t\t\t\tresponse\n\t\t\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\tresponse = temp\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tif (error instanceof ValidationError) throw error\n\n\t\t\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t\t\t'response',\n\t\t\t\t\t\t\t\t\tresponseValidator,\n\t\t\t\t\t\t\t\t\tresponse\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t\t'response',\n\t\t\t\t\t\t\t\tresponseValidator,\n\t\t\t\t\t\t\t\tresponse\n\t\t\t\t\t\t\t)\n\t\t\t\t\t}\n\n\t\t\t\t\tif (responseValidator?.Encode)\n\t\t\t\t\t\tcontext.response = response =\n\t\t\t\t\t\t\tresponseValidator.Encode(response)\n\n\t\t\t\t\tif (responseValidator?.Clean)\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcontext.response = response =\n\t\t\t\t\t\t\t\tresponseValidator.Clean(response)\n\t\t\t\t\t\t} catch {}\n\n\t\t\t\t\tconst result = mapEarlyResponse(response, context.set)\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tif (result !== undefined) return (context.response = result)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (context.set.cookie && cookieMeta?.sign) {\n\t\t\t\tconst secret = !cookieMeta.secrets\n\t\t\t\t\t? undefined\n\t\t\t\t\t: typeof cookieMeta.secrets === 'string'\n\t\t\t\t\t\t? cookieMeta.secrets\n\t\t\t\t\t\t: cookieMeta.secrets[0]\n\n\t\t\t\tif (cookieMeta.sign === true) {\n\t\t\t\t\tif (secret)\n\t\t\t\t\t\tfor (const [key, cookie] of Object.entries(\n\t\t\t\t\t\t\tcontext.set.cookie\n\t\t\t\t\t\t))\n\t\t\t\t\t\t\tcontext.set.cookie[key].value = await signCookie(\n\t\t\t\t\t\t\t\tcookie.value as any,\n\t\t\t\t\t\t\t\tsecret\n\t\t\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tconst properties = getSchemaProperties(validator?.cookie?.schema)\n\n\t\t\t\t\tif (secret)\n\t\t\t\t\t\tfor (const name of cookieMeta.sign) {\n\t\t\t\t\t\t\tif (!properties || !(name in properties)) continue\n\n\t\t\t\t\t\t\tif (context.set.cookie[name]?.value) {\n\t\t\t\t\t\t\t\tcontext.set.cookie[name].value =\n\t\t\t\t\t\t\t\t\tawait signCookie(\n\t\t\t\t\t\t\t\t\t\tcontext.set.cookie[name].value as any,\n\t\t\t\t\t\t\t\t\t\tsecret\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// @ts-expect-error\n\t\t\treturn mapResponse((context.response = response), context.set)\n\t\t} catch (error) {\n\t\t\tconst reportedError =\n\t\t\t\terror instanceof TransformDecodeError && error.error\n\t\t\t\t\t? error.error\n\t\t\t\t\t: error\n\n\t\t\t// ? Since error is reconciled in mergeResponseWithHeaders, this is not needed (if I'm not drunk)\n\t\t\t// if ((reportedError as ElysiaErrors).status)\n\t\t\t// \tset.status = (reportedError as ElysiaErrors).status\n\n\t\t\t// @ts-expect-error private\n\t\t\treturn app.handleError(context, reportedError)\n\t\t} finally {\n\t\t\tconst afterResponses = hooks!\n\t\t\t\t? hooks.afterResponse\n\t\t\t\t: app.event.afterResponse\n\n\t\t\tif (afterResponses) {\n\t\t\t\tif (hasSetImmediate)\n\t\t\t\t\tsetImmediate(async () => {\n\t\t\t\t\t\tfor (const afterResponse of afterResponses)\n\t\t\t\t\t\t\tawait afterResponse.fn(context as any)\n\t\t\t\t\t})\n\t\t\t\telse\n\t\t\t\t\tPromise.resolve().then(async () => {\n\t\t\t\t\t\tfor (const afterResponse of afterResponses)\n\t\t\t\t\t\t\tawait afterResponse.fn(context as any)\n\t\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport const createDynamicErrorHandler = (app: AnyElysia) => {\n\tconst { mapResponse } = app['~adapter'].handler\n\n\treturn async (\n\t\tcontext: Context & {\n\t\t\tresponse: unknown\n\t\t},\n\t\terror: ElysiaErrors\n\t) => {\n\t\tconst errorContext = Object.assign(context, { error, code: error.code })\n\t\terrorContext.set = context.set\n\n\t\tif (\n\t\t\t// @ts-expect-error\n\t\t\ttypeof error?.toResponse === 'function' &&\n\t\t\t!(error instanceof ValidationError) &&\n\t\t\t!(error instanceof TransformDecodeError)\n\t\t) {\n\t\t\ttry {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tlet raw = error.toResponse()\n\t\t\t\tif (typeof raw?.then === 'function') raw = await raw\n\t\t\t\tif (raw instanceof Response) context.set.status = raw.status\n\t\t\t\tcontext.response = raw\n\t\t\t} catch (toResponseError) {\n\t\t\t\t// If toResponse() throws, fall through to normal error handling\n\t\t\t\t// Don't set context.response so onError hooks will run\n\t\t\t}\n\t\t}\n\n\t\tif (!context.response && app.event.error)\n\t\t\tfor (let i = 0; i < app.event.error.length; i++) {\n\t\t\t\tconst hook = app.event.error[i]\n\t\t\t\tlet response = hook.fn(errorContext as any)\n\t\t\t\tif (response instanceof Promise) response = await response\n\t\t\t\tif (response !== undefined && response !== null)\n\t\t\t\t\treturn (context.response = mapResponse(\n\t\t\t\t\t\tresponse,\n\t\t\t\t\t\tcontext.set\n\t\t\t\t\t))\n\t\t\t}\n\n\t\tif (context.response) {\n\t\t\tif (app.event.mapResponse)\n\t\t\t\tfor (let i = 0; i < app.event.mapResponse.length; i++) {\n\t\t\t\t\tconst hook = app.event.mapResponse[i]\n\t\t\t\t\tlet response = hook.fn(errorContext as any)\n\t\t\t\t\tif (response instanceof Promise) response = await response\n\t\t\t\t\tif (response !== undefined && response !== null)\n\t\t\t\t\t\tcontext.response = response\n\t\t\t\t}\n\n\t\t\treturn mapResponse(context.response, context.set)\n\t\t}\n\n\t\tcontext.set.status = error.status ?? 500\n\t\treturn mapResponse(\n\t\t\ttypeof error.cause === 'string' ? error.cause : error.message,\n\t\t\tcontext.set\n\t\t)\n\t}\n}\n"
  },
  {
    "path": "src/error.ts",
    "content": "import type { TSchema } from '@sinclair/typebox'\nimport { Value } from '@sinclair/typebox/value'\nimport type {\n\tTypeCheck,\n\tValueError,\n\tValueErrorIterator\n} from '@sinclair/typebox/compiler'\n\nimport { StatusMap, InvertedStatusMap } from './utils'\nimport type { ElysiaTypeCheck } from './schema'\nimport { StandardSchemaV1Like } from './types'\n\n// ? Cloudflare worker support\nconst env =\n\ttypeof Bun !== 'undefined'\n\t\t? Bun.env\n\t\t: typeof process !== 'undefined'\n\t\t\t? process?.env\n\t\t\t: undefined\n\nexport const ERROR_CODE = Symbol('ElysiaErrorCode')\nexport type ERROR_CODE = typeof ERROR_CODE\n\nexport const isProduction = (env?.NODE_ENV ?? env?.ENV) === 'production'\n\nexport type ElysiaErrors =\n\t| InternalServerError\n\t| NotFoundError\n\t| ParseError\n\t| ValidationError\n\t| InvalidCookieSignature\n\nconst emptyHttpStatus = {\n\t101: undefined,\n\t204: undefined,\n\t205: undefined,\n\t304: undefined,\n\t307: undefined,\n\t308: undefined\n} as const\n\ntype CheckExcessProps<T, U> = 0 extends 1 & T\n\t? T // T is any\n\t: U extends U\n\t\t? Exclude<keyof T, keyof U> extends never\n\t\t\t? T\n\t\t\t: { [K in keyof U]: U[K] } & {\n\t\t\t\t\t[K in Exclude<keyof T, keyof U>]: never\n\t\t\t\t}\n\t\t: never\n\nexport type SelectiveStatus<in out Res> = <\n\tconst Code extends\n\t\t| keyof Res\n\t\t| InvertedStatusMap[Extract<keyof InvertedStatusMap, keyof Res>],\n\tT extends Code extends keyof Res\n\t\t? Res[Code]\n\t\t: Code extends keyof StatusMap\n\t\t\t? // @ts-ignore StatusMap[Code] always valid because Code generic check\n\t\t\t\tRes[StatusMap[Code]]\n\t\t\t: never\n>(\n\tcode: Code,\n\tresponse: CheckExcessProps<\n\t\tT,\n\t\tCode extends keyof Res\n\t\t\t? Res[Code]\n\t\t\t: Code extends keyof StatusMap\n\t\t\t\t? // @ts-ignore StatusMap[Code] always valid because Code generic check\n\t\t\t\t\tRes[StatusMap[Code]]\n\t\t\t\t: never\n\t>\n) => ElysiaCustomStatusResponse<\n\t// @ts-ignore trust me bro\n\tCode,\n\tT\n>\n\nexport class ElysiaCustomStatusResponse<\n\tconst in out Code extends number | keyof StatusMap,\n\t// no in out here so the response can be sub type of return type\n\tT = Code extends keyof InvertedStatusMap ? InvertedStatusMap[Code] : Code,\n\tconst in out Status extends Code extends keyof StatusMap\n\t\t? StatusMap[Code]\n\t\t: Code = Code extends keyof StatusMap ? StatusMap[Code] : Code\n> {\n\tcode: Status\n\tresponse: T\n\n\tconstructor(code: Code, response: T) {\n\t\tconst res =\n\t\t\tresponse ??\n\t\t\t(code in InvertedStatusMap\n\t\t\t\t? // @ts-expect-error Always correct\n\t\t\t\t\tInvertedStatusMap[code]\n\t\t\t\t: code)\n\n\t\t// @ts-ignore Trust me bro\n\t\tthis.code = StatusMap[code] ?? code\n\n\t\tif (code in emptyHttpStatus) this.response = undefined as any\n\t\telse\n\t\t\t// @ts-ignore Trust me bro\n\t\t\tthis.response = res\n\t}\n}\n\nexport const ElysiaStatus = ElysiaCustomStatusResponse\n\nexport const status = <\n\tconst Code extends number | keyof StatusMap,\n\tconst T = Code extends keyof InvertedStatusMap\n\t\t? InvertedStatusMap[Code]\n\t\t: Code\n>(\n\tcode: Code,\n\tresponse?: T\n) => new ElysiaCustomStatusResponse<Code, T>(code, response as T)\n\nexport class InternalServerError extends Error {\n\tcode = 'INTERNAL_SERVER_ERROR'\n\tstatus = 500\n\n\tconstructor(message?: string) {\n\t\tsuper(message ?? 'INTERNAL_SERVER_ERROR')\n\t}\n}\n\nexport class NotFoundError extends Error {\n\tcode = 'NOT_FOUND'\n\tstatus = 404\n\n\tconstructor(message?: string) {\n\t\tsuper(message ?? 'NOT_FOUND')\n\t}\n}\n\nexport class ParseError extends Error {\n\tcode = 'PARSE'\n\tstatus = 400\n\n\tconstructor(cause?: Error) {\n\t\tsuper('Bad Request', {\n\t\t\tcause\n\t\t})\n\t}\n}\n\nexport class InvalidCookieSignature extends Error {\n\tcode = 'INVALID_COOKIE_SIGNATURE'\n\tstatus = 400\n\n\tconstructor(\n\t\tpublic key: string,\n\t\tmessage?: string\n\t) {\n\t\tsuper(message ?? `\"${key}\" has invalid cookie signature`)\n\t}\n}\n\ninterface ValueErrorWithSummary extends ValueError {\n\tsummary?: string\n}\n\nexport const mapValueError = (\n\terror: ValueError | undefined\n): ValueErrorWithSummary | undefined => {\n\tif (!error) return error\n\n\tlet { message, path, value, type } = error\n\tif (Array.isArray(path)) path = path[0]\n\n\tconst property =\n\t\ttypeof path === 'string'\n\t\t\t? path.slice(1).replaceAll('/', '.')\n\t\t\t: 'unknown'\n\n\tconst isRoot = path === ''\n\n\tswitch (type) {\n\t\tcase 42:\n\t\t\treturn {\n\t\t\t\t...error,\n\t\t\t\tsummary: isRoot\n\t\t\t\t\t? `Value should not be provided`\n\t\t\t\t\t: `Property '${property}' should not be provided`\n\t\t\t}\n\n\t\tcase 45:\n\t\t\treturn {\n\t\t\t\t...error,\n\t\t\t\tsummary: isRoot\n\t\t\t\t\t? `Value is missing`\n\t\t\t\t\t: `Property '${property}' is missing`\n\t\t\t}\n\n\t\tcase 50:\n\t\t\t// Expected string to match 'email' format\n\t\t\tconst quoteIndex = message.indexOf(\"'\")!\n\t\t\tconst format = message.slice(\n\t\t\t\tquoteIndex + 1,\n\t\t\t\tmessage.indexOf(\"'\", quoteIndex + 1)\n\t\t\t)\n\n\t\t\treturn {\n\t\t\t\t...error,\n\t\t\t\tsummary: isRoot\n\t\t\t\t\t? `Value should be an email`\n\t\t\t\t\t: `Property '${property}' should be ${format}`\n\t\t\t}\n\n\t\tcase 54:\n\t\t\treturn {\n\t\t\t\t...error,\n\t\t\t\tsummary: `${message\n\t\t\t\t\t.slice(0, 9)\n\t\t\t\t\t.trim()} property '${property}' to be ${message\n\t\t\t\t\t.slice(8)\n\t\t\t\t\t.trim()} but found: ${value}`\n\t\t\t}\n\n\t\tcase 62:\n\t\t\tconst union = error.schema.anyOf\n\t\t\t\t.map((x: Record<string, unknown>) => `'${x?.format ?? x.type}'`)\n\t\t\t\t.join(', ')\n\n\t\t\treturn {\n\t\t\t\t...error,\n\t\t\t\tsummary: isRoot\n\t\t\t\t\t? `Value should be one of ${union}`\n\t\t\t\t\t: `Property '${property}' should be one of: ${union}`\n\t\t\t}\n\n\t\tdefault:\n\t\t\treturn { summary: message, ...error }\n\t}\n}\n\nexport class InvalidFileType extends Error {\n\tcode = 'INVALID_FILE_TYPE'\n\tstatus = 422\n\n\tconstructor(\n\t\tpublic property: string,\n\t\tpublic expected: string | string[],\n\t\tpublic message = `\"${property}\" has invalid file type`\n\t) {\n\t\tsuper(message)\n\n\t\tObject.setPrototypeOf(this, InvalidFileType.prototype)\n\t}\n\n\ttoResponse(headers?: Record<string, any>) {\n\t\tif (isProduction)\n\t\t\treturn new Response(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\ttype: 'validation',\n\t\t\t\t\ton: 'body'\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tstatus: 422,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t...headers,\n\t\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\treturn new Response(\n\t\t\tJSON.stringify({\n\t\t\t\ttype: 'validation',\n\t\t\t\ton: 'body',\n\t\t\t\tsummary: 'Invalid file type',\n\t\t\t\tmessage: this.message,\n\t\t\t\tproperty: this.property,\n\t\t\t\texpected: this.expected\n\t\t\t}),\n\t\t\t{\n\t\t\t\tstatus: 422,\n\t\t\t\theaders: {\n\t\t\t\t\t...headers,\n\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\t}\n}\n\nexport class ValidationError extends Error {\n\tcode = 'VALIDATION'\n\tstatus = 422\n\n\t/**\n\t * An actual value of `message`\n\t *\n\t * Since `message` is string\n\t * use this instead of message\n\t */\n\tvalueError?: ValueError\n\n\t/**\n\t * Alias of `valueError`\n\t */\n\tget messageValue() {\n\t\treturn this.valueError\n\t}\n\n\t/**\n\t * Expected value of the schema\n\t */\n\texpected?: unknown\n\n\t/**\n\t * Custom error if provided\n\t */\n\tcustomError?: unknown\n\n\tconstructor(\n\t\tpublic type: string,\n\t\tpublic validator:\n\t\t\t| TSchema\n\t\t\t| TypeCheck<any>\n\t\t\t| ElysiaTypeCheck<any>\n\t\t\t| StandardSchemaV1Like,\n\t\t/**\n\t\t * Input value\n\t\t */\n\t\tpublic value: unknown,\n\t\tprivate allowUnsafeValidationDetails = false,\n\t\terrors?: ValueErrorIterator\n\t) {\n\t\tlet message = ''\n\t\tlet error\n\t\tlet expected\n\t\tlet customError\n\n\t\tif (\n\t\t\t// @ts-ignore\n\t\t\tvalidator?.provider === 'standard' ||\n\t\t\t'~standard' in validator ||\n\t\t\t// @ts-ignore\n\t\t\t(validator.schema && '~standard' in validator.schema)\n\t\t) {\n\t\t\tconst standard = // @ts-ignore\n\t\t\t\t('~standard' in validator ? validator : validator.schema)[\n\t\t\t\t\t'~standard'\n\t\t\t\t]\n\n\t\t\tconst _errors = errors ?? standard.validate(value).issues\n\n\t\t\terror = _errors?.[0]\n\n\t\t\tif (isProduction && !allowUnsafeValidationDetails)\n\t\t\t\tmessage = JSON.stringify({\n\t\t\t\t\ttype: 'validation',\n\t\t\t\t\ton: type,\n\t\t\t\t\tfound: value\n\t\t\t\t})\n\t\t\telse\n\t\t\t\tmessage = JSON.stringify(\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'validation',\n\t\t\t\t\t\ton: type,\n\t\t\t\t\t\tproperty: error.path?.[0] || 'root',\n\t\t\t\t\t\tmessage: error?.message,\n\t\t\t\t\t\tsummary: error?.problem,\n\t\t\t\t\t\texpected,\n\t\t\t\t\t\tfound: value,\n\t\t\t\t\t\terrors\n\t\t\t\t\t},\n\t\t\t\t\tnull,\n\t\t\t\t\t2\n\t\t\t\t)\n\n\t\t\tcustomError = error?.message\n\t\t} else {\n\t\t\tif (\n\t\t\t\tvalue &&\n\t\t\t\ttypeof value === 'object' &&\n\t\t\t\tvalue instanceof ElysiaCustomStatusResponse\n\t\t\t)\n\t\t\t\tvalue = value.response\n\n\t\t\terror =\n\t\t\t\terrors?.First() ??\n\t\t\t\t('Errors' in validator\n\t\t\t\t\t? validator.Errors(value).First()\n\t\t\t\t\t: Value.Errors(validator, value).First())\n\n\t\t\tconst accessor = error?.path || 'root'\n\n\t\t\t// @ts-ignore private field\n\t\t\tconst schema = validator?.schema ?? validator\n\n\t\t\tif (!isProduction && !allowUnsafeValidationDetails)\n\t\t\t\ttry {\n\t\t\t\t\texpected = Value.Create(schema)\n\t\t\t\t} catch (error) {\n\t\t\t\t\texpected = {\n\t\t\t\t\t\ttype: 'Could not create expected value',\n\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\tmessage: error?.message,\n\t\t\t\t\t\terror\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tcustomError =\n\t\t\t\terror?.schema?.message || error?.schema?.error !== undefined\n\t\t\t\t\t? typeof error.schema.error === 'function'\n\t\t\t\t\t\t? error.schema.error(\n\t\t\t\t\t\t\t\tisProduction && !allowUnsafeValidationDetails\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\ttype: 'validation',\n\t\t\t\t\t\t\t\t\t\t\ton: type,\n\t\t\t\t\t\t\t\t\t\t\tfound: value\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\ttype: 'validation',\n\t\t\t\t\t\t\t\t\t\t\ton: type,\n\t\t\t\t\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\t\t\t\t\tproperty: accessor,\n\t\t\t\t\t\t\t\t\t\t\tmessage: error?.message,\n\t\t\t\t\t\t\t\t\t\t\tsummary:\n\t\t\t\t\t\t\t\t\t\t\t\tmapValueError(error)?.summary,\n\t\t\t\t\t\t\t\t\t\t\tfound: value,\n\t\t\t\t\t\t\t\t\t\t\texpected,\n\t\t\t\t\t\t\t\t\t\t\terrors:\n\t\t\t\t\t\t\t\t\t\t\t\t'Errors' in validator\n\t\t\t\t\t\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...validator.Errors(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t].map(mapValueError)\n\t\t\t\t\t\t\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...Value.Errors(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalidator,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t].map(mapValueError)\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tvalidator\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: error.schema.error\n\t\t\t\t\t: undefined\n\n\t\t\tif (customError !== undefined) {\n\t\t\t\tmessage =\n\t\t\t\t\ttypeof customError === 'object'\n\t\t\t\t\t\t? JSON.stringify(customError)\n\t\t\t\t\t\t: customError + ''\n\t\t\t} else if (isProduction && !allowUnsafeValidationDetails) {\n\t\t\t\tmessage = JSON.stringify({\n\t\t\t\t\ttype: 'validation',\n\t\t\t\t\ton: type,\n\t\t\t\t\tfound: value\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tmessage = JSON.stringify(\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'validation',\n\t\t\t\t\t\ton: type,\n\t\t\t\t\t\tproperty: accessor,\n\t\t\t\t\t\tmessage: error?.message,\n\t\t\t\t\t\tsummary: mapValueError(error)?.summary,\n\t\t\t\t\t\texpected,\n\t\t\t\t\t\tfound: value,\n\t\t\t\t\t\terrors:\n\t\t\t\t\t\t\t'Errors' in validator\n\t\t\t\t\t\t\t\t? [...validator.Errors(value)].map(\n\t\t\t\t\t\t\t\t\t\tmapValueError\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t: [...Value.Errors(validator, value)].map(\n\t\t\t\t\t\t\t\t\t\tmapValueError\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t},\n\t\t\t\t\tnull,\n\t\t\t\t\t2\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tsuper(message)\n\t\tthis.valueError = error\n\t\tthis.expected = expected\n\t\tthis.customError = customError\n\n\t\tObject.setPrototypeOf(this, ValidationError.prototype)\n\t}\n\n\tget all(): ValueErrorWithSummary[] {\n\t\t// Handle standard schema validators (Zod, Valibot, etc.)\n\t\tif (\n\t\t\t// @ts-ignore\n\t\t\tthis.validator?.provider === 'standard' ||\n\t\t\t'~standard' in this.validator ||\n\t\t\t// @ts-ignore\n\t\t\t('schema' in this.validator &&\n\t\t\t\t// @ts-ignore\n\t\t\t\tthis.validator.schema &&\n\t\t\t\t// @ts-ignore\n\t\t\t\t'~standard' in this.validator.schema)\n\t\t) {\n\t\t\tconst standard = // @ts-ignore\n\t\t\t\t(\n\t\t\t\t\t'~standard' in this.validator\n\t\t\t\t\t\t? this.validator\n\t\t\t\t\t\t: // @ts-ignore\n\t\t\t\t\t\t\tthis.validator.schema\n\t\t\t\t)['~standard']\n\n\t\t\tconst issues = standard.validate(this.value).issues\n\n\t\t\t// Map standard schema issues to the expected format\n\t\t\treturn (\n\t\t\t\tissues?.map((issue: any) => ({\n\t\t\t\t\tsummary: issue.message,\n\t\t\t\t\tpath: issue.path?.join('.') || 'root',\n\t\t\t\t\tmessage: issue.message,\n\t\t\t\t\tvalue: this.value\n\t\t\t\t})) || []\n\t\t\t)\n\t\t}\n\n\t\t// Handle TypeBox validators\n\t\treturn 'Errors' in this.validator\n\t\t\t? [...this.validator.Errors(this.value)]\n\t\t\t\t\t.filter((x) => x)\n\t\t\t\t\t.map((x) => mapValueError(x) as ValueErrorWithSummary)\n\t\t\t: // @ts-ignore\n\t\t\t\t[...Value.Errors(this.validator, this.value)].map(mapValueError)\n\t}\n\n\tstatic simplifyModel(\n\t\tvalidator: TSchema | TypeCheck<any> | ElysiaTypeCheck<any>\n\t) {\n\t\t// @ts-ignore\n\t\tconst model = 'schema' in validator ? validator.schema : validator\n\n\t\ttry {\n\t\t\treturn Value.Create(model)\n\t\t} catch {\n\t\t\treturn model\n\t\t}\n\t}\n\n\tget model() {\n\t\tif ('~standard' in this.validator) return this.validator\n\n\t\treturn ValidationError.simplifyModel(this.validator)\n\t}\n\n\ttoResponse(headers?: Record<string, any>) {\n\t\treturn new Response(this.message, {\n\t\t\tstatus: 400,\n\t\t\theaders: {\n\t\t\t\t...headers,\n\t\t\t\t'content-type': 'application/json'\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Utility function to inherit add custom error and keep the original Validation error\n\t *\n\t * @since 1.3.14\n\t *\n\t * @example\n\t * ```ts\n\t * new Elysia()\n\t *\t\t.onError(({ error, code }) => {\n\t *\t\t\tif (code === 'VALIDATION') return error.detail(error.message)\n\t *\t\t})\n\t *\t\t.post('/', () => 'Hello World!', {\n\t *\t\t\tbody: t.Object({\n\t *\t\t\t\tx: t.Number({\n\t *\t\t\t\t\terror: 'x must be a number'\n\t *\t\t\t\t})\n\t *\t\t\t})\n\t *\t\t})\n\t * ```\n\t */\n\tdetail(\n\t\tmessage: unknown,\n\t\tallowUnsafeValidatorDetails = this.allowUnsafeValidationDetails\n\t) {\n\t\tif (!this.customError) return this.message\n\n\t\tconst value = this.value\n\t\tconst expected = this.expected\n\t\tconst errors = this.all\n\n\t\treturn isProduction && !allowUnsafeValidatorDetails\n\t\t\t? {\n\t\t\t\t\ttype: 'validation',\n\t\t\t\t\ton: this.type,\n\t\t\t\t\tfound: value,\n\t\t\t\t\tmessage\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\ttype: 'validation',\n\t\t\t\t\ton: this.type,\n\t\t\t\t\tproperty: this.valueError?.path || 'root',\n\t\t\t\t\tmessage,\n\t\t\t\t\tsummary: mapValueError(this.valueError)?.summary,\n\t\t\t\t\tfound: value,\n\t\t\t\t\texpected,\n\t\t\t\t\terrors\n\t\t\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/formats.ts",
    "content": "/**\n * ? Fork of ajv-formats without ajv as dependencies\n *\n * @see https://github.com/ajv-validator/ajv-formats/blob/master/src/formats.ts\n **/\n\n/* eslint-disable no-control-regex */\nexport type FormatName =\n\t| 'date'\n\t| 'time'\n\t| 'date-time'\n\t| 'iso-time'\n\t| 'iso-date-time'\n\t| 'duration'\n\t| 'uri'\n\t| 'uri-reference'\n\t| 'uri-template'\n\t| 'url'\n\t| 'email'\n\t| 'hostname'\n\t| 'ipv4'\n\t| 'ipv6'\n\t| 'regex'\n\t| 'uuid'\n\t| 'json-pointer'\n\t| 'json-pointer-uri-fragment'\n\t| 'relative-json-pointer'\n\t| 'byte'\n\t| 'int32'\n\t| 'int64'\n\t| 'float'\n\t| 'double'\n\t| 'password'\n\t| 'binary'\n\nexport const fullFormats = {\n\t// date: http://tools.ietf.org/html/rfc3339#section-5.6\n\tdate,\n\t// date-time: http://tools.ietf.org/html/rfc3339#section-5.6\n\ttime: getTime(true),\n\t'date-time': getDateTime(true),\n\t'iso-time': getTime(false),\n\t'iso-date-time': getDateTime(false),\n\t// duration: https://tools.ietf.org/html/rfc3339#appendix-A\n\tduration:\n\t\t/^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$/,\n\turi,\n\t'uri-reference':\n\t\t/^(?:[a-z][a-z0-9+\\-.]*:)?(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'\"()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\\?(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,\n\t// uri-template: https://tools.ietf.org/html/rfc6570\n\t'uri-template':\n\t\t/^(?:(?:[^\\x00-\\x20\"'<>%\\\\^`{|}]|%[0-9a-f]{2})|\\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?)*\\})*$/i,\n\t// For the source: https://gist.github.com/dperini/729294\n\t// For test cases: https://mathiasbynens.be/demo/url-regex\n\turl: /^(?:https?|ftp):\\/\\/(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)(?:\\.(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)*(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$/iu,\n\temail: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,\n\thostname:\n\t\t/^(?=.{1,253}\\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\\.?$/i,\n\t// optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n\tipv4: /^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$/,\n\tipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))$/i,\n\tregex,\n\t// uuid: http://tools.ietf.org/html/rfc4122\n\tuuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,\n\t// JSON-pointer: https://tools.ietf.org/html/rfc6901\n\t// uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A\n\t'json-pointer': /^(?:\\/(?:[^~/]|~0|~1)*)*$/,\n\t'json-pointer-uri-fragment':\n\t\t/^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,\n\t// relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00\n\t'relative-json-pointer': /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/,\n\t// the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types\n\t// byte: https://github.com/miguelmota/is-base64\n\tbyte,\n\t// signed 32 bit integer\n\tint32: { type: 'number', validate: validateInt32 },\n\t// signed 64 bit integer\n\tint64: { type: 'number', validate: validateInt64 },\n\t// C-type float\n\tfloat: { type: 'number', validate: validateNumber },\n\t// C-type double\n\tdouble: { type: 'number', validate: validateNumber },\n\t// hint to the UI to hide input strings\n\tpassword: true,\n\t// unchecked string payload\n\tbinary: true\n} as const\n\nfunction isLeapYear(year: number): boolean {\n\t// https://tools.ietf.org/html/rfc3339#appendix-C\n\treturn year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)\n}\n\nconst DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\nfunction date(str: string): boolean {\n\t// full-date from http://tools.ietf.org/html/rfc3339#section-5.6\n\tconst matches: string[] | null = DATE.exec(str)\n\tif (!matches) return false\n\tconst year: number = +matches[1]\n\tconst month: number = +matches[2]\n\tconst day: number = +matches[3]\n\treturn (\n\t\tmonth >= 1 &&\n\t\tmonth <= 12 &&\n\t\tday >= 1 &&\n\t\tday <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month])\n\t)\n}\n\nconst TIME = /^(\\d\\d):(\\d\\d):(\\d\\d(?:\\.\\d+)?)(z|([+-])(\\d\\d)(?::?(\\d\\d))?)?$/i\n\nfunction getTime(strictTimeZone?: boolean): (str: string) => boolean {\n\treturn function time(str: string): boolean {\n\t\tconst matches: string[] | null = TIME.exec(str)\n\t\tif (!matches) return false\n\t\tconst hr: number = +matches[1]\n\t\tconst min: number = +matches[2]\n\t\tconst sec: number = +matches[3]\n\t\tconst tz: string | undefined = matches[4]\n\t\tconst tzSign: number = matches[5] === '-' ? -1 : 1\n\t\tconst tzH: number = +(matches[6] || 0)\n\t\tconst tzM: number = +(matches[7] || 0)\n\t\tif (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) return false\n\t\tif (hr <= 23 && min <= 59 && sec < 60) return true\n\t\t// leap second\n\t\tconst utcMin = min - tzM * tzSign\n\t\tconst utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0)\n\t\treturn (\n\t\t\t(utcHr === 23 || utcHr === -1) &&\n\t\t\t(utcMin === 59 || utcMin === -1) &&\n\t\t\tsec < 61\n\t\t)\n\t}\n}\n\nconst DATE_TIME_SEPARATOR = /t|\\s/i\nfunction getDateTime(strictTimeZone?: boolean): (str: string) => boolean {\n\tconst time = getTime(strictTimeZone)\n\n\treturn function date_time(str: string): boolean {\n\t\t// http://tools.ietf.org/html/rfc3339#section-5.6\n\t\tconst dateTime: string[] = str.split(DATE_TIME_SEPARATOR)\n\t\treturn dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1])\n\t}\n}\n\nconst NOT_URI_FRAGMENT = /\\/|:/\nconst URI =\n\t/^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\\?(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i\n\nfunction uri(str: string): boolean {\n\t// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required \".\"\n\treturn NOT_URI_FRAGMENT.test(str) && URI.test(str)\n}\n\nconst BYTE =\n\t/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm\n\nfunction byte(str: string): boolean {\n\tBYTE.lastIndex = 0\n\treturn BYTE.test(str)\n}\n\nconst MIN_INT32 = -(2 ** 31)\nconst MAX_INT32 = 2 ** 31 - 1\n\nfunction validateInt32(value: number): boolean {\n\treturn Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32\n}\n\nfunction validateInt64(value: number): boolean {\n\t// JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64\n\treturn Number.isInteger(value)\n}\n\nfunction validateNumber(): boolean {\n\treturn true\n}\n\nconst Z_ANCHOR = /[^\\\\]\\\\Z/\nfunction regex(str: string): boolean {\n\tif (Z_ANCHOR.test(str)) return false\n\ttry {\n\t\tnew RegExp(str)\n\t\treturn true\n\t} catch (e) {\n\t\treturn false\n\t}\n}\n\n/**\n * @license\n *\n * MIT License\n *\n * Copyright (c) 2020 Evgeny Poberezkin\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n"
  },
  {
    "path": "src/index.ts",
    "content": "import { Memoirist } from 'memoirist'\nimport {\n\tKind,\n\ttype TObject,\n\ttype TSchema,\n\ttype TModule,\n\ttype TRef,\n\ttype TAnySchema\n} from '@sinclair/typebox'\n\nimport fastDecodeURIComponent from 'fast-decode-uri-component'\nimport type { Context, PreContext } from './context'\n\nimport { t } from './type-system'\nimport { mergeInference, sucrose, type Sucrose } from './sucrose'\n\nimport type { WSLocalHook } from './ws/types'\n\nimport { BunAdapter } from './adapter/bun/index'\nimport { WebStandardAdapter } from './adapter/web-standard/index'\nimport type { ElysiaAdapter } from './adapter/types'\n\nimport { env } from './universal/env'\nimport type { ListenCallback, Serve, Server } from './universal/server'\n\nimport {\n\tcloneInference,\n\tdeduplicateChecksum,\n\tfnToContainer,\n\tgetLoosePath,\n\tlocalHookToLifeCycleStore,\n\tmergeDeep,\n\tmergeSchemaValidator,\n\tPromiseGroup,\n\tpromoteEvent,\n\tisNotEmpty,\n\tencodePath,\n\tlifeCycleToArray,\n\tsupportPerMethodInlineHandler,\n\tredirect,\n\temptySchema,\n\tinsertStandaloneValidator\n} from './utils'\n\nimport {\n\tgetSchemaValidator,\n\tgetResponseSchemaValidator,\n\tgetCookieValidator,\n\tElysiaTypeCheck,\n\thasType,\n\tresolveSchema\n} from './schema'\nimport {\n\tcomposeHandler,\n\tcomposeGeneralHandler,\n\tcomposeErrorHandler\n} from './compose'\n\nimport { createTracer } from './trace'\n\nimport {\n\tmergeHook,\n\tchecksum,\n\tmergeLifeCycle,\n\tfilterGlobalHook,\n\tasHookType,\n\treplaceUrlPath\n} from './utils'\n\nimport {\n\tcreateDynamicErrorHandler,\n\tcreateDynamicHandler,\n\ttype DynamicHandler\n} from './dynamic-handle'\n\nimport {\n\tstatus,\n\tERROR_CODE,\n\tValidationError,\n\ttype ParseError,\n\ttype NotFoundError,\n\ttype InternalServerError,\n\ttype ElysiaCustomStatusResponse\n} from './error'\n\nimport type { TraceHandler } from './trace'\n\nimport type {\n\tElysiaConfig,\n\tSingletonBase,\n\tDefinitionBase,\n\tHandler,\n\tComposedHandler,\n\tInputSchema,\n\tLocalHook,\n\tAnyLocalHook,\n\tMergeSchema,\n\tRouteSchema,\n\tUnwrapRoute,\n\tInternalRoute,\n\tHTTPMethod,\n\tSchemaValidator,\n\tPreHandler,\n\tBodyHandler,\n\tOptionalHandler,\n\tErrorHandler,\n\tLifeCycleStore,\n\tMaybePromise,\n\tPrettify,\n\tAddPrefix,\n\tAddSuffix,\n\tAddPrefixCapitalize,\n\tAddSuffixCapitalize,\n\tMaybeArray,\n\tGracefulHandler,\n\tMapResponse,\n\tChecksum,\n\tMacroManager,\n\tMacroToProperty,\n\tTransformHandler,\n\tMetadataBase,\n\tRouteBase,\n\tCreateEden,\n\tComposeElysiaResponse,\n\tInlineHandler,\n\tHookContainer,\n\tLifeCycleType,\n\tEphemeralType,\n\tExcludeElysiaResponse,\n\tModelValidator,\n\tContextAppendType,\n\tReconcile,\n\tAfterResponseHandler,\n\tHigherOrderFunction,\n\tResolvePath,\n\tJoinPath,\n\tValidatorLayer,\n\tMergeElysiaInstances,\n\tMacro,\n\tMacroToContext,\n\tStandaloneValidator,\n\tGuardSchemaType,\n\tOr,\n\tDocumentDecoration,\n\tAfterHandler,\n\tNonResolvableMacroKey,\n\tStandardSchemaV1Like,\n\tElysiaHandlerToResponseSchema,\n\tElysiaHandlerToResponseSchemas,\n\tExtractErrorFromHandle,\n\tElysiaHandlerToResponseSchemaAmbiguous,\n\tGuardLocalHook,\n\tPickIfExists,\n\tSimplifyToSchema,\n\tUnionResponseStatus,\n\tCreateEdenResponse,\n\tMacroProperty,\n\tMaybeValueOrVoidFunction,\n\tIntersectIfObject,\n\tIntersectIfObjectSchema,\n\tEmptyRouteSchema,\n\tUnknownRouteSchema,\n\tMaybeFunction,\n\tInlineHandlerNonMacro,\n\tRouter,\n} from './types'\nimport {\n\tcoercePrimitiveRoot,\n\tcoerceFormData,\n\tqueryCoercions,\n\tstringToStructureCoercions\n} from './replace-schema'\n\nexport type AnyElysia = Elysia<any, any, any, any, any, any, any>\n\n/**\n * ### Elysia Server\n * Main instance to create web server using Elysia\n *\n * ---\n * @example\n * ```typescript\n * import { Elysia } from 'elysia'\n *\n * new Elysia()\n *     .get(\"/\", () => \"Hello\")\n *     .listen(3000)\n * ```\n */\nexport default class Elysia<\n\tconst in out BasePath extends string = '',\n\tconst in out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tconst in out Definitions extends DefinitionBase = {\n\t\ttypebox: {}\n\t\terror: {}\n\t},\n\tconst in out Metadata extends MetadataBase = {\n\t\tschema: {}\n\t\tstandaloneSchema: {}\n\t\tmacro: {}\n\t\tmacroFn: {}\n\t\tparser: {}\n\t\tresponse: {}\n\t},\n\tconst in out Routes extends RouteBase = {},\n\t// ? scoped\n\tconst in out Ephemeral extends EphemeralType = {\n\t\tderive: {}\n\t\tresolve: {}\n\t\tschema: {}\n\t\tstandaloneSchema: {}\n\t\tresponse: {}\n\t},\n\t// ? local\n\tconst in out Volatile extends EphemeralType = {\n\t\tderive: {}\n\t\tresolve: {}\n\t\tschema: {}\n\t\tstandaloneSchema: {}\n\t\tresponse: {}\n\t}\n> {\n\tconfig: ElysiaConfig<BasePath>\n\n\tserver: Server | null = null\n\tprivate dependencies: { [key: string]: Checksum[] } = {}\n\n\t'~Prefix' = '' as BasePath\n\t'~Singleton' = null as unknown as Singleton\n\t'~Definitions' = null as unknown as Definitions\n\t'~Metadata' = null as unknown as Metadata\n\t'~Ephemeral' = null as unknown as Ephemeral\n\t'~Volatile' = null as unknown as Volatile\n\t'~Routes' = null as unknown as Routes\n\n\tprotected singleton = {\n\t\tdecorator: {},\n\t\tstore: {},\n\t\tderive: {},\n\t\tresolve: {}\n\t} as SingletonBase\n\n\tget store(): Singleton['store'] {\n\t\treturn this.singleton.store\n\t}\n\n\tget decorator(): Singleton['decorator'] {\n\t\treturn this.singleton.decorator\n\t}\n\n\tprotected definitions = {\n\t\ttypebox: t.Module({}),\n\t\ttype: {} as Record<string, TSchema | StandardSchemaV1Like>,\n\t\terror: {} as Record<string, Error>\n\t}\n\n\tprotected extender = {\n\t\tmacro: <Macro>{},\n\t\thigherOrderFunctions: <HookContainer<HigherOrderFunction>[]>[]\n\t}\n\n\tprotected validator: ValidatorLayer = {\n\t\tglobal: null,\n\t\tscoped: null,\n\t\tlocal: null,\n\t\tgetCandidate() {\n\t\t\tif (!this.global && !this.scoped && !this.local)\n\t\t\t\treturn {\n\t\t\t\t\tbody: undefined,\n\t\t\t\t\theaders: undefined,\n\t\t\t\t\tparams: undefined,\n\t\t\t\t\tquery: undefined,\n\t\t\t\t\tcookie: undefined,\n\t\t\t\t\tresponse: undefined\n\t\t\t\t}\n\n\t\t\treturn mergeSchemaValidator(\n\t\t\t\tmergeSchemaValidator(this.global, this.scoped),\n\t\t\t\tthis.local\n\t\t\t)\n\t\t}\n\t}\n\n\tprotected standaloneValidator: StandaloneValidator = {\n\t\tglobal: null,\n\t\tscoped: null,\n\t\tlocal: null\n\t}\n\n\tevent: Partial<LifeCycleStore> = {}\n\n\tprotected telemetry:\n\t\t| undefined\n\t\t| {\n\t\t\t\tstack: string | undefined\n\t\t  }\n\n\trouter = {\n\t\t'~http': undefined,\n\t\tget http() {\n\t\t\tif (!this['~http'])\n\t\t\t\tthis['~http'] = new Memoirist({\n\t\t\t\t\tlazy: true,\n\t\t\t\t\tonParam: fastDecodeURIComponent\n\t\t\t\t})\n\n\t\t\treturn this['~http']\n\t\t},\n\t\t'~dynamic': undefined,\n\t\t// Use in non-AOT mode\n\t\tget dynamic() {\n\t\t\tif (!this['~dynamic'])\n\t\t\t\tthis['~dynamic'] = new Memoirist({\n\t\t\t\t\tonParam: fastDecodeURIComponent\n\t\t\t\t})\n\n\t\t\treturn this['~dynamic']\n\t\t},\n\t\t// Static Router\n\t\tstatic: {},\n\t\t// Native Static Response\n\t\tresponse: {},\n\t\thistory: []\n\t} as Router\n\n\tprotected routeTree: Record<string, number> = {}\n\n\tget routes(): InternalRoute[] {\n\t\treturn this.router.history\n\t}\n\n\tprotected getGlobalRoutes(): InternalRoute[] {\n\t\treturn this.router.history\n\t}\n\n\tprotected getGlobalDefinitions() {\n\t\treturn this.definitions\n\t}\n\n\tprotected inference: Sucrose.Inference = {\n\t\tbody: false,\n\t\tcookie: false,\n\t\theaders: false,\n\t\tquery: false,\n\t\tset: false,\n\t\tserver: false,\n\t\tpath: false,\n\t\troute: false,\n\t\turl: false\n\t}\n\n\tprivate getServer() {\n\t\treturn this.server\n\t}\n\n\tprivate getParent(): Elysia | null {\n\t\treturn null\n\t}\n\n\t'~parser': { [K: string]: BodyHandler<any, any> } = {}\n\n\tprivate _promisedModules: PromiseGroup | undefined\n\tprivate get promisedModules() {\n\t\tif (!this._promisedModules)\n\t\t\tthis._promisedModules = new PromiseGroup(console.error, () => {\n\t\t\t\t// this.compile()\n\t\t\t})\n\n\t\treturn this._promisedModules\n\t}\n\n\tconstructor(config: ElysiaConfig<BasePath> = {}) {\n\t\tif (config.tags) {\n\t\t\tif (!config.detail)\n\t\t\t\tconfig.detail = {\n\t\t\t\t\ttags: config.tags\n\t\t\t\t}\n\t\t\telse config.detail.tags = config.tags\n\t\t}\n\n\t\tthis.config = {\n\t\t\taot: env.ELYSIA_AOT !== 'false',\n\t\t\tnativeStaticResponse: true,\n\t\t\tencodeSchema: true,\n\t\t\tnormalize: true,\n\t\t\t...config,\n\t\t\tprefix: config.prefix\n\t\t\t\t? config.prefix.charCodeAt(0) === 47\n\t\t\t\t\t? config.prefix\n\t\t\t\t\t: `/${config.prefix}`\n\t\t\t\t: (undefined as any),\n\t\t\tcookie: {\n\t\t\t\tpath: '/',\n\t\t\t\t...config?.cookie\n\t\t\t},\n\t\t\texperimental: config?.experimental ?? {},\n\t\t\tseed: config?.seed === undefined ? '' : config?.seed\n\t\t}\n\n\t\tthis['~adapter'] =\n\t\t\tconfig.adapter ??\n\t\t\t(typeof Bun !== 'undefined' ? BunAdapter : WebStandardAdapter)\n\n\t\tif (config?.analytic && (config?.name || config?.seed !== undefined))\n\t\t\tthis.telemetry = {\n\t\t\t\tstack: new Error().stack\n\t\t\t}\n\t}\n\n\t'~adapter': ElysiaAdapter\n\n\tenv(model: TObject, _env = env) {\n\t\tconst validator = getSchemaValidator(model, {\n\t\t\tmodules: this.definitions.typebox,\n\t\t\tdynamic: true,\n\t\t\tadditionalProperties: true,\n\t\t\tcoerce: true,\n\t\t\tsanitize: () => this.config.sanitize\n\t\t})\n\n\t\tif (validator.Check(_env) === false) {\n\t\t\tconst error = new ValidationError('env', model, _env)\n\n\t\t\tthrow new Error(error.all.map((x) => x.summary).join('\\n'))\n\t\t}\n\n\t\treturn this\n\t}\n\n\t/**\n\t * @private DO_NOT_USE_OR_YOU_WILL_BE_FIRED\n\t * @version 1.1.0\n\t *\n\t * ! Do not use unless you know exactly what you are doing\n\t * ? Add Higher order function to Elysia.fetch\n\t */\n\twrap(fn: HigherOrderFunction) {\n\t\tthis.extender.higherOrderFunctions.push({\n\t\t\tchecksum: checksum(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tname: this.config.name,\n\t\t\t\t\tseed: this.config.seed,\n\t\t\t\t\tcontent: fn.toString()\n\t\t\t\t})\n\t\t\t),\n\t\t\tfn\n\t\t})\n\n\t\treturn this\n\t}\n\n\tget models(): {\n\t\t[K in keyof Definitions['typebox']]: ModelValidator<\n\t\t\tDefinitions['typebox'][K]\n\t\t>\n\t} & {\n\t\tmodules:\n\t\t\t| TModule<Extract<Definitions['typebox'], TAnySchema>>\n\t\t\t| Extract<Definitions['typebox'], StandardSchemaV1Like>\n\t} {\n\t\tconst models: Record<string, ElysiaTypeCheck<TSchema>> = {}\n\n\t\tfor (const name of Object.keys(this.definitions.type))\n\t\t\tmodels[name] = getSchemaValidator(\n\t\t\t\tthis.definitions.typebox.Import(name as never),\n\t\t\t\t{\n\t\t\t\t\tmodels: this.definitions.type\n\t\t\t\t}\n\t\t\t)\n\n\t\t// @ts-expect-error\n\t\tmodels.modules = this.definitions.typebox\n\n\t\treturn models as any\n\t}\n\n\tprivate add(\n\t\tmethod: HTTPMethod,\n\t\tpath: string,\n\t\thandle: Handler<any, any, any> | any,\n\t\tlocalHook?: AnyLocalHook,\n\t\toptions?: {\n\t\t\tallowMeta?: boolean\n\t\t\tskipPrefix?: boolean\n\t\t}\n\t) {\n\t\tconst skipPrefix = options?.skipPrefix ?? false\n\t\tconst allowMeta = options?.allowMeta ?? false\n\n\t\tlocalHook ??= {}\n\n\t\tthis.applyMacro(localHook)\n\n\t\tlet standaloneValidators = [] as InputSchema[]\n\n\t\tif (localHook.standaloneValidator)\n\t\t\tstandaloneValidators = standaloneValidators.concat(\n\t\t\t\tlocalHook.standaloneValidator\n\t\t\t)\n\n\t\tif (this.standaloneValidator.local)\n\t\t\tstandaloneValidators = standaloneValidators.concat(\n\t\t\t\tthis.standaloneValidator.local\n\t\t\t)\n\n\t\tif (this.standaloneValidator.scoped)\n\t\t\tstandaloneValidators = standaloneValidators.concat(\n\t\t\t\tthis.standaloneValidator.scoped\n\t\t\t)\n\n\t\tif (this.standaloneValidator.global)\n\t\t\tstandaloneValidators = standaloneValidators.concat(\n\t\t\t\tthis.standaloneValidator.global\n\t\t\t)\n\n\t\tif (path !== '' && path.charCodeAt(0) !== 47) path = '/' + path\n\t\tif (this.config.prefix && !skipPrefix) path = this.config.prefix + path\n\n\t\tif (localHook?.type)\n\t\t\tswitch (localHook.type) {\n\t\t\t\tcase 'text':\n\t\t\t\t\tlocalHook.type = 'text/plain'\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'json':\n\t\t\t\t\tlocalHook.type = 'application/json'\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'formdata':\n\t\t\t\t\tlocalHook.type = 'multipart/form-data'\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'urlencoded':\n\t\t\t\t\tlocalHook.type = 'application/x-www-form-urlencoded'\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'arrayBuffer':\n\t\t\t\t\tlocalHook.type = 'application/octet-stream'\n\t\t\t\t\tbreak\n\n\t\t\t\tdefault:\n\t\t\t\t\tbreak\n\t\t\t}\n\n\t\tconst instanceValidator = this.validator.getCandidate()\n\n\t\tconst cloned = {\n\t\t\tbody: localHook?.body ?? (instanceValidator?.body as any),\n\t\t\theaders: localHook?.headers ?? (instanceValidator?.headers as any),\n\t\t\tparams: localHook?.params ?? (instanceValidator?.params as any),\n\t\t\tquery: localHook?.query ?? (instanceValidator?.query as any),\n\t\t\tcookie: localHook?.cookie ?? (instanceValidator?.cookie as any),\n\t\t\tresponse:\n\t\t\t\tlocalHook?.response ?? (instanceValidator?.response as any)\n\t\t}\n\n\t\tconst shouldPrecompile =\n\t\t\tthis.config.precompile === true ||\n\t\t\t(typeof this.config.precompile === 'object' &&\n\t\t\t\tthis.config.precompile.compose === true)\n\n\t\tconst createValidator = () => {\n\t\t\tconst models = this.definitions.type\n\t\t\tconst dynamic = !this.config.aot\n\n\t\t\tconst normalize = this.config.normalize\n\t\t\tconst modules = this.definitions.typebox\n\n\t\t\tconst sanitize = () => this.config.sanitize\n\n\t\t\tconst cookieValidator = () => {\n\t\t\t\tif (cloned.cookie || standaloneValidators.find((x) => x.cookie))\n\t\t\t\t\treturn getCookieValidator({\n\t\t\t\t\t\tmodules,\n\t\t\t\t\t\tvalidator: cloned.cookie,\n\t\t\t\t\t\tdefaultConfig: this.config.cookie,\n\t\t\t\t\t\tnormalize,\n\t\t\t\t\t\tconfig: cloned.cookie?.config ?? {},\n\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\tmodels,\n\t\t\t\t\t\tvalidators: standaloneValidators.map((x) => x.cookie),\n\t\t\t\t\t\tsanitize\n\t\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn shouldPrecompile\n\t\t\t\t? {\n\t\t\t\t\t\tbody: getSchemaValidator(cloned.body, {\n\t\t\t\t\t\t\tmodules,\n\t\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\tnormalize,\n\t\t\t\t\t\t\tadditionalCoerce: (() => {\n\t\t\t\t\t\t\t\tconst resolved = resolveSchema(\n\t\t\t\t\t\t\t\t\tcloned.body,\n\t\t\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\t\t\tmodules\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t// Only check for Files if resolved schema is a TypeBox schema (has Kind symbol)\n\t\t\t\t\t\t\t\treturn resolved &&\n\t\t\t\t\t\t\t\t\tKind in resolved &&\n\t\t\t\t\t\t\t\t\t(hasType('File', resolved) ||\n\t\t\t\t\t\t\t\t\t\thasType('Files', resolved))\n\t\t\t\t\t\t\t\t\t? coerceFormData()\n\t\t\t\t\t\t\t\t\t: coercePrimitiveRoot()\n\t\t\t\t\t\t\t})(),\n\t\t\t\t\t\t\tvalidators: standaloneValidators.map((x) => x.body),\n\t\t\t\t\t\t\tsanitize\n\t\t\t\t\t\t}),\n\t\t\t\t\t\theaders: getSchemaValidator(cloned.headers, {\n\t\t\t\t\t\t\tmodules,\n\t\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\tadditionalProperties: true,\n\t\t\t\t\t\t\tcoerce: true,\n\t\t\t\t\t\t\tadditionalCoerce: stringToStructureCoercions(),\n\t\t\t\t\t\t\tvalidators: standaloneValidators.map(\n\t\t\t\t\t\t\t\t(x) => x.headers\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tsanitize\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tparams: getSchemaValidator(cloned.params, {\n\t\t\t\t\t\t\tmodules,\n\t\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\tcoerce: true,\n\t\t\t\t\t\t\tadditionalCoerce: stringToStructureCoercions(),\n\t\t\t\t\t\t\tvalidators: standaloneValidators.map(\n\t\t\t\t\t\t\t\t(x) => x.params\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tsanitize\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tquery: getSchemaValidator(cloned.query, {\n\t\t\t\t\t\t\tmodules,\n\t\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\tnormalize,\n\t\t\t\t\t\t\tcoerce: true,\n\t\t\t\t\t\t\tadditionalCoerce: queryCoercions(),\n\t\t\t\t\t\t\tvalidators: standaloneValidators.map(\n\t\t\t\t\t\t\t\t(x) => x.query\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tsanitize\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tcookie: cookieValidator(),\n\t\t\t\t\t\tresponse: getResponseSchemaValidator(cloned.response, {\n\t\t\t\t\t\t\tmodules,\n\t\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\tnormalize,\n\t\t\t\t\t\t\tvalidators: standaloneValidators.map(\n\t\t\t\t\t\t\t\t(x) => x.response as any\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tsanitize\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t: ({\n\t\t\t\t\t\tcreateBody() {\n\t\t\t\t\t\t\tif (this.body) return this.body\n\n\t\t\t\t\t\t\treturn (this.body = getSchemaValidator(\n\t\t\t\t\t\t\t\tcloned.body,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmodules,\n\t\t\t\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\t\t\tnormalize,\n\t\t\t\t\t\t\t\t\tadditionalCoerce: (() => {\n\t\t\t\t\t\t\t\t\t\tconst resolved = resolveSchema(\n\t\t\t\t\t\t\t\t\t\t\tcloned.body,\n\t\t\t\t\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\t\t\t\t\tmodules\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t// Only check for Files if resolved schema is a TypeBox schema (has Kind symbol)\n\t\t\t\t\t\t\t\t\t\treturn resolved &&\n\t\t\t\t\t\t\t\t\t\t\tKind in resolved &&\n\t\t\t\t\t\t\t\t\t\t\t(hasType('File', resolved) ||\n\t\t\t\t\t\t\t\t\t\t\t\thasType('Files', resolved))\n\t\t\t\t\t\t\t\t\t\t\t? coerceFormData()\n\t\t\t\t\t\t\t\t\t\t\t: coercePrimitiveRoot()\n\t\t\t\t\t\t\t\t\t})(),\n\t\t\t\t\t\t\t\t\tvalidators: standaloneValidators.map(\n\t\t\t\t\t\t\t\t\t\t(x) => x.body\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tsanitize\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t))\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcreateHeaders() {\n\t\t\t\t\t\t\tif (this.headers) return this.headers\n\n\t\t\t\t\t\t\treturn (this.headers = getSchemaValidator(\n\t\t\t\t\t\t\t\tcloned.headers,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmodules,\n\t\t\t\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\t\t\tnormalize,\n\t\t\t\t\t\t\t\t\tadditionalProperties: !normalize,\n\t\t\t\t\t\t\t\t\tcoerce: true,\n\t\t\t\t\t\t\t\t\tadditionalCoerce:\n\t\t\t\t\t\t\t\t\t\tstringToStructureCoercions(),\n\t\t\t\t\t\t\t\t\tvalidators: standaloneValidators.map(\n\t\t\t\t\t\t\t\t\t\t(x) => x.headers\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tsanitize\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t))\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcreateParams() {\n\t\t\t\t\t\t\tif (this.params) return this.params\n\n\t\t\t\t\t\t\treturn (this.params = getSchemaValidator(\n\t\t\t\t\t\t\t\tcloned.params,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmodules,\n\t\t\t\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\t\t\tnormalize,\n\t\t\t\t\t\t\t\t\tcoerce: true,\n\t\t\t\t\t\t\t\t\tadditionalCoerce:\n\t\t\t\t\t\t\t\t\t\tstringToStructureCoercions(),\n\t\t\t\t\t\t\t\t\tvalidators: standaloneValidators.map(\n\t\t\t\t\t\t\t\t\t\t(x) => x.params\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tsanitize\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t))\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcreateQuery() {\n\t\t\t\t\t\t\tif (this.query) return this.query\n\n\t\t\t\t\t\t\treturn (this.query = getSchemaValidator(\n\t\t\t\t\t\t\t\tcloned.query,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmodules,\n\t\t\t\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\t\t\tnormalize,\n\t\t\t\t\t\t\t\t\tcoerce: true,\n\t\t\t\t\t\t\t\t\tadditionalCoerce: queryCoercions(),\n\t\t\t\t\t\t\t\t\tvalidators: standaloneValidators.map(\n\t\t\t\t\t\t\t\t\t\t(x) => x.query\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tsanitize\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t))\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcreateCookie() {\n\t\t\t\t\t\t\tif (this.cookie) return this.cookie\n\n\t\t\t\t\t\t\treturn (this.cookie = cookieValidator())\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcreateResponse() {\n\t\t\t\t\t\t\tif (this.response) return this.response\n\n\t\t\t\t\t\t\treturn (this.response = getResponseSchemaValidator(\n\t\t\t\t\t\t\t\tcloned.response,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmodules,\n\t\t\t\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\t\t\tnormalize,\n\t\t\t\t\t\t\t\t\tvalidators: standaloneValidators.map(\n\t\t\t\t\t\t\t\t\t\t(x) => x.response as any\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tsanitize\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t))\n\t\t\t\t\t\t}\n\t\t\t\t\t} as any)\n\t\t}\n\n\t\tif (\n\t\t\tinstanceValidator.body ||\n\t\t\tinstanceValidator.cookie ||\n\t\t\tinstanceValidator.headers ||\n\t\t\tinstanceValidator.params ||\n\t\t\tinstanceValidator.query ||\n\t\t\tinstanceValidator.response\n\t\t)\n\t\t\tlocalHook = mergeHook(localHook, instanceValidator)\n\n\t\tif (localHook.tags) {\n\t\t\tif (!localHook.detail)\n\t\t\t\tlocalHook.detail = {\n\t\t\t\t\ttags: localHook.tags\n\t\t\t\t}\n\t\t\telse localHook.detail.tags = localHook.tags\n\t\t}\n\n\t\tif (isNotEmpty(this.config.detail))\n\t\t\tlocalHook.detail = mergeDeep(\n\t\t\t\tObject.assign({}, this.config.detail!),\n\t\t\t\tlocalHook.detail\n\t\t\t)\n\n\t\tif (path === '/ip') {\n\t\t\t// console.log(path, this.event, localHookToLifeCycleStore(localHook))\n\t\t}\n\n\t\tconst hooks = isNotEmpty(this.event)\n\t\t\t? mergeHook(this.event, localHookToLifeCycleStore(localHook))\n\t\t\t: { ...lifeCycleToArray(localHookToLifeCycleStore(localHook)) }\n\n\t\tif (standaloneValidators.length)\n\t\t\tObject.assign(hooks, {\n\t\t\t\tstandaloneValidator: standaloneValidators\n\t\t\t})\n\n\t\tif (this.config.aot === false) {\n\t\t\tconst validator = createValidator()\n\n\t\t\tthis.router.dynamic.add(method, path, {\n\t\t\t\tvalidator,\n\t\t\t\thooks,\n\t\t\t\tcontent: localHook?.type as string,\n\t\t\t\thandle,\n\t\t\t\troute: path\n\t\t\t})\n\n\t\t\tconst encoded = encodePath(path, { dynamic: true })\n\t\t\tif (path !== encoded) {\n\t\t\t\tthis.router.dynamic.add(method, encoded, {\n\t\t\t\t\tvalidator,\n\t\t\t\t\thooks,\n\t\t\t\t\tcontent: localHook?.type as string,\n\t\t\t\t\thandle,\n\t\t\t\t\troute: path\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (!this.config.strictPath) {\n\t\t\t\tconst loosePath = getLoosePath(path)\n\t\t\t\tthis.router.dynamic.add(method, loosePath, {\n\t\t\t\t\tvalidator,\n\t\t\t\t\thooks,\n\t\t\t\t\tcontent: localHook?.type as string,\n\t\t\t\t\thandle,\n\t\t\t\t\troute: path\n\t\t\t\t})\n\n\t\t\t\tconst encoded = encodePath(loosePath)\n\t\t\t\tif (loosePath !== encoded)\n\t\t\t\t\tthis.router.dynamic.add(method, loosePath, {\n\t\t\t\t\t\tvalidator,\n\t\t\t\t\t\thooks,\n\t\t\t\t\t\tcontent: localHook?.type as string,\n\t\t\t\t\t\thandle,\n\t\t\t\t\t\troute: path\n\t\t\t\t\t})\n\t\t\t}\n\n\t\t\tthis.router.history.push({\n\t\t\t\tmethod,\n\t\t\t\tpath,\n\t\t\t\tcomposed: null,\n\t\t\t\thandler: handle,\n\t\t\t\tcompile: undefined as any,\n\t\t\t\thooks\n\t\t\t})\n\n\t\t\treturn\n\t\t}\n\n\t\tconst adapter = this['~adapter'].handler\n\n\t\tconst nativeStaticHandler =\n\t\t\ttypeof handle !== 'function'\n\t\t\t\t? () => {\n\t\t\t\t\t\tconst context: PreContext = {\n\t\t\t\t\t\t\tredirect,\n\t\t\t\t\t\t\trequest: this['~adapter'].isWebStandard\n\t\t\t\t\t\t\t\t? new Request(`http://ely.sia${path}`, {\n\t\t\t\t\t\t\t\t\t\tmethod\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t: (undefined as any as Request),\n\t\t\t\t\t\t\tserver: null,\n\t\t\t\t\t\t\tset: {\n\t\t\t\t\t\t\t\theaders: Object.assign({}, this.setHeaders)\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t\tstore: this.store\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tthis.event.request?.map((x) => {\n\t\t\t\t\t\t\t\tif (typeof x.fn === 'function')\n\t\t\t\t\t\t\t\t\treturn x.fn(context)\n\n\t\t\t\t\t\t\t\t// @ts-ignore just in case\n\t\t\t\t\t\t\t\tif (typeof x === 'function') return x(context)\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tlet res\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\tcontext.error = error\n\n\t\t\t\t\t\t\tthis.event.error?.some((x) => {\n\t\t\t\t\t\t\t\tif (typeof x.fn === 'function')\n\t\t\t\t\t\t\t\t\treturn (res = x.fn(context))\n\n\t\t\t\t\t\t\t\tif (typeof x === 'function')\n\t\t\t\t\t\t\t\t\t// @ts-ignore just in case\n\t\t\t\t\t\t\t\t\treturn (res = x(context))\n\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\tif (res !== undefined) handle = res\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst fn = adapter.createNativeStaticHandler?.(\n\t\t\t\t\t\t\thandle,\n\t\t\t\t\t\t\thooks,\n\t\t\t\t\t\t\tcontext.set as Context['set']\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\treturn fn instanceof Promise\n\t\t\t\t\t\t\t? fn.then((fn) => {\n\t\t\t\t\t\t\t\t\tif (fn) return fn\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t: fn?.()\n\t\t\t\t\t}\n\t\t\t\t: undefined\n\n\t\tconst useNativeStaticResponse =\n\t\t\tthis.config.nativeStaticResponse === true\n\n\t\tconst addResponsePath = (path: string) => {\n\t\t\tif (!useNativeStaticResponse || !nativeStaticHandler) return\n\n\t\t\tif (supportPerMethodInlineHandler) {\n\t\t\t\tif (this.router.response[path])\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tthis.router.response[path]![method] = nativeStaticHandler()\n\t\t\t\telse\n\t\t\t\t\tthis.router.response[path] = {\n\t\t\t\t\t\t[method]: nativeStaticHandler()\n\t\t\t\t\t}\n\t\t\t} else this.router.response[path] = nativeStaticHandler()\n\t\t}\n\n\t\taddResponsePath(path)\n\n\t\t// For pre-compilation stage, eg. Cloudflare Worker\n\t\tlet _compiled: ComposedHandler\n\t\tconst compile = () => {\n\t\t\tif (_compiled) return _compiled\n\n\t\t\tconst compiled = composeHandler({\n\t\t\t\tapp: this,\n\t\t\t\tpath,\n\t\t\t\tmethod,\n\t\t\t\thooks,\n\t\t\t\tvalidator: createValidator(),\n\t\t\t\thandler:\n\t\t\t\t\ttypeof handle !== 'function' &&\n\t\t\t\t\ttypeof adapter.createStaticHandler !== 'function'\n\t\t\t\t\t\t? () => handle\n\t\t\t\t\t\t: handle,\n\t\t\t\tallowMeta,\n\t\t\t\tinference: this.inference\n\t\t\t})\n\n\t\t\tif (this.router.history[index])\n\t\t\t\t_compiled = this.router.history[index].composed = compiled\n\n\t\t\treturn compiled\n\t\t}\n\n\t\tlet oldIndex: number | undefined\n\t\tif (`${method}_${path}` in this.routeTree)\n\t\t\tfor (let i = 0; i < this.router.history.length; i++) {\n\t\t\t\tconst route = this.router.history[i]\n\t\t\t\tif (route.path === path && route.method === method) {\n\t\t\t\t\toldIndex = i\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\telse this.routeTree[`${method}_${path}`] = this.router.history.length\n\n\t\tconst index = oldIndex ?? this.router.history.length\n\t\tconst route = this.router.history\n\n\t\tconst mainHandler = shouldPrecompile\n\t\t\t? compile()\n\t\t\t: (ctx: Context) =>\n\t\t\t\t\t_compiled\n\t\t\t\t\t\t? _compiled(ctx)\n\t\t\t\t\t\t: (\n\t\t\t\t\t\t\t\t(route[index].composed =\n\t\t\t\t\t\t\t\t\tcompile!()) as ComposedHandler\n\t\t\t\t\t\t\t)(ctx)\n\n\t\tif (oldIndex !== undefined)\n\t\t\tthis.router.history[oldIndex] = Object.assign(\n\t\t\t\t{\n\t\t\t\t\tmethod,\n\t\t\t\t\tpath,\n\t\t\t\t\tcomposed: mainHandler,\n\t\t\t\t\tcompile,\n\t\t\t\t\thandler: handle,\n\t\t\t\t\thooks\n\t\t\t\t},\n\t\t\t\tstandaloneValidators.length\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tstandaloneValidators\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t\tlocalHook.webSocket\n\t\t\t\t\t? { websocket: localHook.websocket as any }\n\t\t\t\t\t: undefined\n\t\t\t)\n\t\telse\n\t\t\tthis.router.history.push(\n\t\t\t\tObject.assign(\n\t\t\t\t\t{\n\t\t\t\t\t\tmethod,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tcomposed: mainHandler,\n\t\t\t\t\t\tcompile,\n\t\t\t\t\t\thandler: handle,\n\t\t\t\t\t\thooks\n\t\t\t\t\t},\n\t\t\t\t\tlocalHook.webSocket\n\t\t\t\t\t\t? { websocket: localHook.websocket as any }\n\t\t\t\t\t\t: undefined\n\t\t\t\t)\n\t\t\t)\n\n\t\tconst handler = {\n\t\t\thandler: shouldPrecompile\n\t\t\t\t? (route[index].composed as ComposedHandler)\n\t\t\t\t: undefined,\n\t\t\tcompile() {\n\t\t\t\treturn (this.handler = compile!())\n\t\t\t}\n\t\t}\n\n\t\tconst staticRouter = this.router.static\n\t\tconst isStaticPath =\n\t\t\tpath.indexOf(':') === -1 && path.indexOf('*') === -1\n\n\t\tif (method === 'WS') {\n\t\t\tif (isStaticPath) {\n\t\t\t\tif (path in staticRouter) staticRouter[path][method] = index\n\t\t\t\telse\n\t\t\t\t\tstaticRouter[path] = {\n\t\t\t\t\t\t[method]: index\n\t\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tthis.router.http.add('WS', path, handler)\n\n\t\t\tif (!this.config.strictPath)\n\t\t\t\tthis.router.http.add('WS', getLoosePath(path), handler)\n\n\t\t\tconst encoded = encodePath(path, { dynamic: true })\n\t\t\tif (path !== encoded) this.router.http.add('WS', encoded, handler)\n\n\t\t\t// Static path doesn't need encode as it's done in compilation process\n\n\t\t\treturn\n\t\t}\n\n\t\tif (isStaticPath) {\n\t\t\tif (path in staticRouter) staticRouter[path][method] = index\n\t\t\telse\n\t\t\t\tstaticRouter[path] = {\n\t\t\t\t\t[method]: index\n\t\t\t\t} as const\n\n\t\t\tif (!this.config.strictPath) addResponsePath(getLoosePath(path))\n\n\t\t\t// Static path doesn't need encode as it's done in compilation process\n\t\t} else {\n\t\t\tthis.router.http.add(method, path, handler)\n\n\t\t\tif (!this.config.strictPath) {\n\t\t\t\tconst loosePath = getLoosePath(path)\n\n\t\t\t\taddResponsePath(loosePath)\n\t\t\t\tthis.router.http.add(method, loosePath, handler)\n\t\t\t}\n\n\t\t\tconst encoded = encodePath(path, { dynamic: true })\n\t\t\tif (path !== encoded) {\n\t\t\t\tthis.router.http.add(method, encoded, handler)\n\n\t\t\t\taddResponsePath(encoded)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate setHeaders?: Context['set']['headers']\n\theaders(header: Context['set']['headers'] | undefined) {\n\t\tif (!header) return this\n\n\t\tif (!this.setHeaders) this.setHeaders = {}\n\n\t\tthis.setHeaders = mergeDeep(this.setHeaders, header)\n\n\t\treturn this\n\t}\n\n\t/**\n\t * ### start | Life cycle event\n\t * Called after server is ready for serving\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onStart(({ server }) => {\n\t *         console.log(\"Running at ${server?.url}:${server?.port}\")\n\t *     })\n\t *     .listen(3000)\n\t * ```\n\t */\n\tonStart(handler: MaybeArray<GracefulHandler<this>>) {\n\t\tthis.on('start', handler as any)\n\n\t\treturn this\n\t}\n\n\t/**\n\t * ### request | Life cycle event\n\t * Called on every new request is accepted\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onRequest(({ method, url }) => {\n\t *         saveToAnalytic({ method, url })\n\t *     })\n\t * ```\n\t */\n\tonRequest<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Handler extends PreHandler<\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t{\n\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\tstore: Singleton['store']\n\t\t\t\tderive: {}\n\t\t\t\tresolve: {}\n\t\t\t}\n\t\t>\n\t>(\n\t\thandler: Handler\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: Volatile['derive']\n\t\t\tresolve: Volatile['resolve']\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: UnionResponseStatus<\n\t\t\t\tVolatile['response'],\n\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t>\n\t\t}\n\t>\n\n\t/**\n\t * ### request | Life cycle event\n\t * Called on every new request is accepted\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onRequest(({ method, url }) => {\n\t *         saveToAnalytic({ method, url })\n\t *     })\n\t * ```\n\t */\n\tonRequest<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Handlers extends PreHandler<\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t{\n\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\tstore: Singleton['store']\n\t\t\t\tderive: {}\n\t\t\t\tresolve: {}\n\t\t\t}\n\t\t>[]\n\t>(\n\t\thandler: Handlers\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: Volatile['derive']\n\t\t\tresolve: Volatile['resolve']\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: UnionResponseStatus<\n\t\t\t\tVolatile['response'],\n\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t>\n\t\t}\n\t>\n\n\tonRequest(handler: MaybeArray<Handler>): any {\n\t\tthis.on('request', handler as any)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### parse | Life cycle event\n\t * Callback function to handle body parsing\n\t *\n\t * If truthy value is returned, will be assigned to `context.body`\n\t * Otherwise will skip the callback and look for the next one.\n\t *\n\t * Equivalent to Express's body parser\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onParse((request, contentType) => {\n\t *         if(contentType === \"application/json\")\n\t *             return request.json()\n\t *     })\n\t * ```\n\t */\n\tonParse<const Schema extends RouteSchema>(\n\t\tparser: MaybeArray<\n\t\t\tBodyHandler<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tSchema,\n\t\t\t\t\tMergeSchema<\n\t\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t\t>,\n\t\t\t\t\tBasePath\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\t{\n\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\tVolatile['derive']\n\t\t\t\t\tresolve: {}\n\t\t\t\t}\n\t\t\t>\n\t\t>\n\t): this\n\n\t/**\n\t * ### parse | Life cycle event\n\t * Callback function to handle body parsing\n\t *\n\t * If truthy value is returned, will be assigned to `context.body`\n\t * Otherwise will skip the callback and look for the next one.\n\t *\n\t * Equivalent to Express's body parser\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onParse((request, contentType) => {\n\t *         if(contentType === \"application/json\")\n\t *             return request.json()\n\t *     })\n\t * ```\n\t */\n\tonParse<const Schema extends RouteSchema, const Type extends LifeCycleType>(\n\t\toptions: { as: Type },\n\t\tparser: MaybeArray<\n\t\t\tBodyHandler<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tSchema,\n\t\t\t\t\tMergeSchema<\n\t\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t\t>,\n\t\t\t\t\tBasePath\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'] &\n\t\t\t\t\t'global' extends Type\n\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t\t: {},\n\t\t\t\t'global' extends Type\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\t\t\t\tPartial<\n\t\t\t\t\t\t\t\t\tEphemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\tresolve: {}\n\t\t\t\t\t\t}\n\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\t\t\tPartial<Volatile['derive']>\n\t\t\t\t\t\t\t\tresolve: {}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\t\t\tVolatile['derive']\n\t\t\t\t\t\t\t\tresolve: {}\n\t\t\t\t\t\t\t}\n\t\t\t>\n\t\t>\n\t): this\n\n\tonParse<const Parsers extends keyof Metadata['parser']>(\n\t\tparser: Parsers\n\t): this\n\n\tonParse(\n\t\toptions: { as: LifeCycleType } | MaybeArray<Function> | string,\n\t\thandler?: MaybeArray<Function>\n\t): unknown {\n\t\tif (!handler) {\n\t\t\tif (typeof options === 'string')\n\t\t\t\treturn this.on('parse', this['~parser'][options] as any)\n\n\t\t\treturn this.on('parse', options as any)\n\t\t}\n\n\t\treturn this.on(\n\t\t\toptions as { as: LifeCycleType },\n\t\t\t'parse',\n\t\t\thandler as any\n\t\t)\n\t}\n\n\t/**\n\t * ### parse | Life cycle event\n\t * Callback function to handle body parsing\n\t *\n\t * If truthy value is returned, will be assigned to `context.body`\n\t * Otherwise will skip the callback and look for the next one.\n\t *\n\t * Equivalent to Express's body parser\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onParse((request, contentType) => {\n\t *         if(contentType === \"application/json\")\n\t *             return request.json()\n\t *     })\n\t * ```\n\t */\n\tparser<\n\t\tconst Parser extends string,\n\t\tconst Schema extends RouteSchema,\n\t\tconst Handler extends BodyHandler<\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>,\n\t\t\t\tBasePath\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t{\n\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\tstore: Singleton['store']\n\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\tVolatile['derive']\n\t\t\t\tresolve: {}\n\t\t\t}\n\t\t>\n\t>(\n\t\tname: Parser,\n\t\tparser: Handler\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\t{\n\t\t\tschema: Metadata['schema']\n\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\tmacro: Metadata['macro']\n\t\t\tmacroFn: Metadata['macroFn']\n\t\t\tparser: Metadata['parser'] & { [K in Parser]: Handler }\n\t\t\tresponse: Metadata['response']\n\t\t},\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tthis['~parser'][name] = parser as any\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### transform | Life cycle event\n\t * Assign or transform anything related to context before validation.\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onTransform(({ params }) => {\n\t *         if(params.id)\n\t *             params.id = +params.id\n\t *     })\n\t * ```\n\t */\n\tonTransform<const Schema extends RouteSchema>(\n\t\thandler: MaybeArray<\n\t\t\tTransformHandler<\n\t\t\t\tUnknownRouteSchema<ResolvePath<BasePath>>,\n\t\t\t\t{\n\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\tVolatile['derive']\n\t\t\t\t\tresolve: {}\n\t\t\t\t}\n\t\t\t>\n\t\t>\n\t): this\n\n\t/**\n\t * ### transform | Life cycle event\n\t * Assign or transform anything related to context before validation.\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onTransform(({ params }) => {\n\t *         if(params.id)\n\t *             params.id = +params.id\n\t *     })\n\t * ```\n\t */\n\tonTransform<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Type extends LifeCycleType\n\t>(\n\t\toptions: { as: Type },\n\t\thandler: MaybeArray<\n\t\t\tTransformHandler<\n\t\t\t\tUnknownRouteSchema<\n\t\t\t\t\t'global' extends Type\n\t\t\t\t\t\t? { [name: string]: string | undefined }\n\t\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t\t? { [name: string]: string | undefined }\n\t\t\t\t\t\t\t: ResolvePath<BasePath>\n\t\t\t\t>,\n\t\t\t\t'global' extends Type\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\t\tVolatile['derive']\n\t\t\t\t\t\t\tresolve: {}\n\t\t\t\t\t\t}\n\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\t\t\tPartial<Volatile['derive']>\n\t\t\t\t\t\t\t\tresolve: {}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\t\t\t\t\tPartial<\n\t\t\t\t\t\t\t\t\t\tEphemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tresolve: {}\n\t\t\t\t\t\t\t}\n\t\t\t>\n\t\t>\n\t): this\n\n\tonTransform(\n\t\toptions: { as: LifeCycleType } | MaybeArray<Function>,\n\t\thandler?: MaybeArray<Function>\n\t) {\n\t\tif (!handler) return this.on('transform', options as any)\n\n\t\treturn this.on(\n\t\t\toptions as { as: LifeCycleType },\n\t\t\t'transform',\n\t\t\thandler as any\n\t\t)\n\t}\n\n\t/**\n\t * Derive new property for each request with access to `Context`.\n\t *\n\t * If error is thrown, the scope will skip to handling error instead.\n\t *\n\t * ---\n\t * @example\n\t * new Elysia()\n\t *     .state('counter', 1)\n\t *     .derive(({ store }) => ({\n\t *         increase() {\n\t *             store.counter++\n\t *         }\n\t *     }))\n\t */\n\tresolve<\n\t\tconst Resolver extends\n\t\t\t| Record<string, unknown>\n\t\t\t| ElysiaCustomStatusResponse<any, any, any>,\n\t\tconst Type extends LifeCycleType\n\t>(\n\t\toptions: { as: Type },\n\t\tresolver: (\n\t\t\tcontext: Context<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>,\n\t\t\t\t\tBasePath\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'] &\n\t\t\t\t\t'global' extends Type\n\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t\t: {},\n\t\t\t\tSingleton &\n\t\t\t\t\t('global' extends Type\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tderive: Partial<\n\t\t\t\t\t\t\t\t\tEphemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tresolve: Partial<\n\t\t\t\t\t\t\t\t\tEphemeral['resolve'] & Volatile['resolve']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\t\tPartial<Volatile['derive']>\n\t\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\t\tPartial<Volatile['resolve']>\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\t\tVolatile['derive']\n\t\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t\t\t})\n\t\t\t>\n\t\t) => MaybePromise<Resolver | void>\n\t): Type extends 'global'\n\t\t? Elysia<\n\t\t\t\tBasePath,\n\t\t\t\t{\n\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\tderive: Singleton['derive']\n\t\t\t\t\tresolve: Singleton['resolve'] &\n\t\t\t\t\t\tExcludeElysiaResponse<Resolver>\n\t\t\t\t},\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: Metadata['schema']\n\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\tExtractErrorFromHandle<Resolver>\n\t\t\t\t\t>\n\t\t\t\t},\n\t\t\t\tRoutes,\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t: Type extends 'scoped'\n\t\t\t? Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Ephemeral['derive']\n\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\tExcludeElysiaResponse<Resolver>\n\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\tExtractErrorFromHandle<Resolver>\n\t\t\t\t\t\t>\n\t\t\t\t\t},\n\t\t\t\t\tVolatile\n\t\t\t\t>\n\t\t\t: Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\tEphemeral,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Volatile['derive']\n\t\t\t\t\t\tresolve: Volatile['resolve'] &\n\t\t\t\t\t\t\tExcludeElysiaResponse<Resolver>\n\t\t\t\t\t\tschema: Volatile['schema']\n\t\t\t\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\tExtractErrorFromHandle<Resolver>\n\t\t\t\t\t\t>\n\t\t\t\t\t}\n\t\t\t\t>\n\n\t/**\n\t * Derive new property for each request with access to `Context`.\n\t *\n\t * If error is thrown, the scope will skip to handling error instead.\n\t *\n\t * ---\n\t * @example\n\t * new Elysia()\n\t *     .state('counter', 1)\n\t *     .derive(({ store }) => ({\n\t *         increase() {\n\t *             store.counter++\n\t *         }\n\t *     }))\n\t */\n\tresolve<\n\t\tconst Resolver extends\n\t\t\t| Record<string, unknown>\n\t\t\t| ElysiaCustomStatusResponse<any, any, any>\n\t\t\t| void\n\t>(\n\t\tresolver: (\n\t\t\tcontext: Context<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>,\n\t\t\t\t\tBasePath\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\tSingleton & {\n\t\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\t\t},\n\t\t\t\tBasePath\n\t\t\t>\n\t\t) => MaybePromise<Resolver | void>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: Volatile['derive']\n\t\t\tresolve: Volatile['resolve'] & ExcludeElysiaResponse<Resolver>\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: UnionResponseStatus<\n\t\t\t\tVolatile['response'],\n\t\t\t\tExtractErrorFromHandle<Resolver>\n\t\t\t>\n\t\t}\n\t>\n\n\tresolve(\n\t\toptionsOrResolve: { as: LifeCycleType } | Function,\n\t\tresolve?: Function\n\t) {\n\t\tif (!resolve) {\n\t\t\tresolve = optionsOrResolve as any\n\t\t\toptionsOrResolve = { as: 'local' }\n\t\t}\n\n\t\tconst hook: HookContainer = {\n\t\t\tsubType: 'resolve',\n\t\t\tfn: resolve!\n\t\t}\n\n\t\treturn this.onBeforeHandle(optionsOrResolve as any, hook as any) as any\n\t}\n\n\tmapResolve<\n\t\tconst NewResolver extends\n\t\t\t| Record<string, unknown>\n\t\t\t| ElysiaCustomStatusResponse<any, any, any>\n\t>(\n\t\tmapper: (\n\t\t\tcontext: Context<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tMetadata['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Volatile['schema']>\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\tSingleton & {\n\t\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\t\t},\n\t\t\t\tBasePath\n\t\t\t>\n\t\t) => MaybePromise<NewResolver | void>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: Volatile['derive']\n\t\t\tresolve: ExcludeElysiaResponse<NewResolver>\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: UnionResponseStatus<\n\t\t\t\tVolatile['response'],\n\t\t\t\tExtractErrorFromHandle<NewResolver>\n\t\t\t>\n\t\t}\n\t>\n\n\tmapResolve<\n\t\tconst NewResolver extends\n\t\t\t| Record<string, unknown>\n\t\t\t| ElysiaCustomStatusResponse<any, any, any>,\n\t\tconst Type extends LifeCycleType\n\t>(\n\t\toptions: { as: Type },\n\t\tmapper: (\n\t\t\tcontext: Context<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tMetadata['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Volatile['schema']>\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\tSingleton &\n\t\t\t\t\t('global' extends Type\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tderive: Partial<\n\t\t\t\t\t\t\t\t\tEphemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tresolve: Partial<\n\t\t\t\t\t\t\t\t\tEphemeral['resolve'] & Volatile['resolve']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\t\tPartial<Volatile['derive']>\n\t\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\t\tPartial<Volatile['resolve']>\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\t\tVolatile['derive']\n\t\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t\t\t})\n\t\t\t>\n\t\t) => MaybePromise<NewResolver | void>\n\t): Type extends 'global'\n\t\t? Elysia<\n\t\t\t\tBasePath,\n\t\t\t\t{\n\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\tderive: Singleton['derive']\n\t\t\t\t\tresolve: ExcludeElysiaResponse<NewResolver>\n\t\t\t\t},\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: Metadata['schema']\n\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\tExtractErrorFromHandle<NewResolver>\n\t\t\t\t\t>\n\t\t\t\t},\n\t\t\t\tRoutes,\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t: Type extends 'scoped'\n\t\t\t? Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Ephemeral['derive']\n\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\tExcludeElysiaResponse<NewResolver>\n\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\tExtractErrorFromHandle<NewResolver>\n\t\t\t\t\t\t>\n\t\t\t\t\t},\n\t\t\t\t\tVolatile\n\t\t\t\t>\n\t\t\t: Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\tEphemeral,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Volatile['derive']\n\t\t\t\t\t\tresolve: Volatile['resolve'] &\n\t\t\t\t\t\t\tExcludeElysiaResponse<NewResolver>\n\t\t\t\t\t\tschema: Volatile['schema']\n\t\t\t\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\tExtractErrorFromHandle<NewResolver>\n\t\t\t\t\t\t>\n\t\t\t\t\t}\n\t\t\t\t>\n\n\tmapResolve(\n\t\toptionsOrResolve: Function | { as: LifeCycleType },\n\t\tmapper?: Function\n\t) {\n\t\tif (!mapper) {\n\t\t\tmapper = optionsOrResolve as any\n\t\t\toptionsOrResolve = { as: 'local' }\n\t\t}\n\n\t\tconst hook: HookContainer = {\n\t\t\tsubType: 'mapResolve',\n\t\t\tfn: mapper!\n\t\t}\n\n\t\treturn this.onBeforeHandle(optionsOrResolve as any, hook as any) as any\n\t}\n\n\t/**\n\t * ### Before Handle | Life cycle event\n\t * Execute after validation and before the main route handler.\n\t *\n\t * If truthy value is returned, will be assigned as `Response` and skip the main handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onBeforeHandle(({ params: { id }, status }) => {\n\t *         if(id && !isExisted(id)) {\n\t * \t           status(401)\n\t *\n\t *             return \"Unauthorized\"\n\t * \t       }\n\t *     })\n\t * ```\n\t */\n\tonBeforeHandle<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Handler extends OptionalHandler<\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>,\n\t\t\t\tBasePath\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'],\n\t\t\tSingleton & {\n\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\t}\n\t\t>\n\t>(\n\t\thandler: Handler\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: Volatile['derive']\n\t\t\tresolve: Volatile['resolve']\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: UnionResponseStatus<\n\t\t\t\tVolatile['response'],\n\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t>\n\t\t}\n\t>\n\n\t/**\n\t * ### Before Handle | Life cycle event\n\t * Execute after validation and before the main route handler.\n\t *\n\t * If truthy value is returned, will be assigned as `Response` and skip the main handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onBeforeHandle(({ params: { id }, status }) => {\n\t *         if(id && !isExisted(id)) {\n\t * \t           status(401)\n\t *\n\t *             return \"Unauthorized\"\n\t * \t       }\n\t *     })\n\t * ```\n\t */\n\tonBeforeHandle<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Handlers extends OptionalHandler<\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>,\n\t\t\t\tBasePath\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'],\n\t\t\tSingleton & {\n\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\t}\n\t\t>[]\n\t>(\n\t\thandlers: Handlers\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: Volatile['derive']\n\t\t\tresolve: Volatile['resolve']\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: UnionResponseStatus<\n\t\t\t\tVolatile['response'],\n\t\t\t\tElysiaHandlerToResponseSchemas<Handlers>\n\t\t\t>\n\t\t}\n\t>\n\n\t/**\n\t * ### Before Handle | Life cycle event\n\t * Execute after validation and before the main route handler.\n\t *\n\t * If truthy value is returned, will be assigned as `Response` and skip the main handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onBeforeHandle(({ params: { id }, status }) => {\n\t *         if(id && !isExisted(id)) {\n\t * \t           status(401)\n\t *\n\t *             return \"Unauthorized\"\n\t * \t       }\n\t *     })\n\t * ```\n\t */\n\tonBeforeHandle<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Type extends LifeCycleType,\n\t\tconst Handler extends OptionalHandler<\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>,\n\t\t\t\tBasePath\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'] &\n\t\t\t\t'global' extends Type\n\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t: {},\n\t\t\tSingleton &\n\t\t\t\t('global' extends Type\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tderive: Partial<\n\t\t\t\t\t\t\t\tEphemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\tresolve: Partial<\n\t\t\t\t\t\t\t\tEphemeral['resolve'] & Volatile['resolve']\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t}\n\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\tPartial<Volatile['derive']>\n\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\tPartial<Volatile['resolve']>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t\t}),\n\t\t\tBasePath\n\t\t>\n\t>(\n\t\toptions: { as: Type },\n\t\thandler: Handler\n\t): Type extends 'global'\n\t\t? Elysia<\n\t\t\t\tBasePath,\n\t\t\t\tSingleton,\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: Metadata['schema']\n\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t\t\t>\n\t\t\t\t},\n\t\t\t\tRoutes,\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t: Type extends 'scoped'\n\t\t\t? Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Ephemeral['derive']\n\t\t\t\t\t\tresolve: Ephemeral['resolve']\n\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t\t\t\t>\n\t\t\t\t\t},\n\t\t\t\t\tVolatile\n\t\t\t\t>\n\t\t\t: Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\tEphemeral,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Volatile['derive']\n\t\t\t\t\t\tresolve: Volatile['resolve']\n\t\t\t\t\t\tschema: Volatile['schema']\n\t\t\t\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t\t\t\t>\n\t\t\t\t\t}\n\t\t\t\t>\n\n\t/**\n\t * ### Before Handle | Life cycle event\n\t * Execute after validation and before the main route handler.\n\t *\n\t * If truthy value is returned, will be assigned as `Response` and skip the main handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onBeforeHandle(({ params: { id }, status }) => {\n\t *         if(id && !isExisted(id)) {\n\t * \t           status(401)\n\t *\n\t *             return \"Unauthorized\"\n\t * \t       }\n\t *     })\n\t * ```\n\t */\n\tonBeforeHandle<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Type extends LifeCycleType,\n\t\tconst Handlers extends OptionalHandler<\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>,\n\t\t\t\tBasePath\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'] &\n\t\t\t\t'global' extends Type\n\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t: {},\n\t\t\tSingleton &\n\t\t\t\t('global' extends Type\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tderive: Partial<\n\t\t\t\t\t\t\t\tEphemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\tresolve: Partial<\n\t\t\t\t\t\t\t\tEphemeral['resolve'] & Volatile['resolve']\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t}\n\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\tPartial<Volatile['derive']>\n\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\tPartial<Volatile['resolve']>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t\t}),\n\t\t\tBasePath\n\t\t>[]\n\t>(\n\t\toptions: { as: Type },\n\t\thandlers: Handlers\n\t): Type extends 'global'\n\t\t? Elysia<\n\t\t\t\tBasePath,\n\t\t\t\tSingleton,\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: Metadata['schema']\n\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\tElysiaHandlerToResponseSchemas<Handlers>\n\t\t\t\t\t>\n\t\t\t\t},\n\t\t\t\tRoutes,\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t: Type extends 'scoped'\n\t\t\t? Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Ephemeral['derive']\n\t\t\t\t\t\tresolve: Ephemeral['resolve']\n\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchemas<Handlers>\n\t\t\t\t\t\t>\n\t\t\t\t\t},\n\t\t\t\t\tVolatile\n\t\t\t\t>\n\t\t\t: Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\tEphemeral,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Volatile['derive']\n\t\t\t\t\t\tresolve: Volatile['resolve']\n\t\t\t\t\t\tschema: Volatile['schema']\n\t\t\t\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchemas<Handlers>\n\t\t\t\t\t\t>\n\t\t\t\t\t}\n\t\t\t\t>\n\n\tonBeforeHandle(\n\t\toptions: { as: LifeCycleType } | MaybeArray<Function>,\n\t\thandler?: MaybeArray<Function>\n\t): any {\n\t\tif (!handler) return this.on('beforeHandle', options as any)\n\n\t\treturn this.on(\n\t\t\toptions as { as: LifeCycleType },\n\t\t\t'beforeHandle',\n\t\t\thandler as any\n\t\t)\n\t}\n\n\t/**\n\t * ### After Handle | Life cycle event\n\t * Intercept request **after** main handler is called.\n\t *\n\t * If truthy value is returned, will be assigned as `Response`\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onAfterHandle((context, response) => {\n\t *         if(typeof response === \"object\")\n\t *             return JSON.stringify(response)\n\t *     })\n\t * ```\n\t */\n\tonAfterHandle<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Handler extends AfterHandler<\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>,\n\t\t\t\tBasePath\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'],\n\t\t\tSingleton & {\n\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\t}\n\t\t>\n\t>(\n\t\thandler: Handler\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: Volatile['derive']\n\t\t\tresolve: Volatile['resolve']\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: UnionResponseStatus<\n\t\t\t\tVolatile['response'],\n\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t>\n\t\t}\n\t>\n\n\t/**\n\t * ### After Handle | Life cycle event\n\t * Intercept request **after** main handler is called.\n\t *\n\t * If truthy value is returned, will be assigned as `Response`\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onAfterHandle((context, response) => {\n\t *         if(typeof response === \"object\")\n\t *             return JSON.stringify(response)\n\t *     })\n\t * ```\n\t */\n\tonAfterHandle<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Handlers extends AfterHandler<\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>,\n\t\t\t\tBasePath\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'],\n\t\t\tSingleton & {\n\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\t}\n\t\t>[]\n\t>(\n\t\thandlers: Handlers\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: Volatile['derive']\n\t\t\tresolve: Volatile['resolve']\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: UnionResponseStatus<\n\t\t\t\tVolatile['response'],\n\t\t\t\tElysiaHandlerToResponseSchemas<Handlers>\n\t\t\t>\n\t\t}\n\t>\n\n\t/**\n\t * ### After Handle | Life cycle event\n\t * Intercept request **after** main handler is called.\n\t *\n\t * If truthy value is returned, will be assigned as `Response`\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onAfterHandle((context, response) => {\n\t *         if(typeof response === \"object\")\n\t *             return JSON.stringify(response)\n\t *     })\n\t * ```\n\t */\n\tonAfterHandle<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Type extends LifeCycleType,\n\t\tconst Handler extends AfterHandler<\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>,\n\t\t\t\tBasePath\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'] &\n\t\t\t\t'global' extends Type\n\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t: {},\n\t\t\tSingleton &\n\t\t\t\t('global' extends Type\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tderive: Partial<\n\t\t\t\t\t\t\t\tEphemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\tresolve: Partial<\n\t\t\t\t\t\t\t\tEphemeral['resolve'] & Volatile['resolve']\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t}\n\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\tPartial<Volatile['derive']>\n\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\tPartial<Volatile['resolve']>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t\t})\n\t\t>\n\t>(\n\t\toptions: { as: Type },\n\t\thandler: Handler\n\t): Type extends 'global'\n\t\t? Elysia<\n\t\t\t\tBasePath,\n\t\t\t\tSingleton,\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: Metadata['schema']\n\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t\t\t>\n\t\t\t\t},\n\t\t\t\tRoutes,\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t: Type extends 'scoped'\n\t\t\t? Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Ephemeral['derive']\n\t\t\t\t\t\tresolve: Ephemeral['resolve']\n\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t\t\t\t>\n\t\t\t\t\t},\n\t\t\t\t\tVolatile\n\t\t\t\t>\n\t\t\t: Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\tEphemeral,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Volatile['derive']\n\t\t\t\t\t\tresolve: Volatile['resolve']\n\t\t\t\t\t\tschema: Volatile['schema']\n\t\t\t\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t\t\t\t>\n\t\t\t\t\t}\n\t\t\t\t>\n\n\t/**\n\t * ### After Handle | Life cycle event\n\t * Intercept request **after** main handler is called.\n\t *\n\t * If truthy value is returned, will be assigned as `Response`\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onAfterHandle((context, response) => {\n\t *         if(typeof response === \"object\")\n\t *             return JSON.stringify(response)\n\t *     })\n\t * ```\n\t */\n\tonAfterHandle<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Type extends LifeCycleType,\n\t\tconst Handlers extends AfterHandler<\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>,\n\t\t\t\tBasePath\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'] &\n\t\t\t\t'global' extends Type\n\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t: {},\n\t\t\tSingleton &\n\t\t\t\t('global' extends Type\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tderive: Partial<\n\t\t\t\t\t\t\t\tEphemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\tresolve: Partial<\n\t\t\t\t\t\t\t\tEphemeral['resolve'] & Volatile['resolve']\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t}\n\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\tPartial<Volatile['derive']>\n\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\tPartial<Volatile['resolve']>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t\t})\n\t\t>[]\n\t>(\n\t\toptions: { as: Type },\n\t\thandler: Handlers\n\t): Type extends 'global'\n\t\t? Elysia<\n\t\t\t\tBasePath,\n\t\t\t\tSingleton,\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: Metadata['schema']\n\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\tElysiaHandlerToResponseSchemas<Handlers>\n\t\t\t\t\t>\n\t\t\t\t},\n\t\t\t\tRoutes,\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t: Type extends 'scoped'\n\t\t\t? Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Ephemeral['derive']\n\t\t\t\t\t\tresolve: Ephemeral['resolve']\n\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchemas<Handlers>\n\t\t\t\t\t\t>\n\t\t\t\t\t},\n\t\t\t\t\tVolatile\n\t\t\t\t>\n\t\t\t: Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\tEphemeral,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Volatile['derive']\n\t\t\t\t\t\tresolve: Volatile['resolve']\n\t\t\t\t\t\tschema: Volatile['schema']\n\t\t\t\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchemas<Handlers>\n\t\t\t\t\t\t>\n\t\t\t\t\t}\n\t\t\t\t>\n\n\tonAfterHandle(\n\t\toptions: { as: LifeCycleType } | MaybeArray<Function>,\n\t\thandler?: MaybeArray<Function>\n\t): any {\n\t\tif (!handler) return this.on('afterHandle', options as any)\n\n\t\treturn this.on(\n\t\t\toptions as { as: LifeCycleType },\n\t\t\t'afterHandle',\n\t\t\thandler as any\n\t\t)\n\t}\n\n\t/**\n\t * ### After Handle | Life cycle event\n\t * Intercept request **after** main handler is called.\n\t *\n\t * If truthy value is returned, will be assigned as `Response`\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .mapResponse((context, response) => {\n\t *         if(typeof response === \"object\")\n\t *             return JSON.stringify(response)\n\t *     })\n\t * ```\n\t */\n\tmapResponse<const Schema extends RouteSchema>(\n\t\thandler: MaybeArray<\n\t\t\tMapResponse<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tSchema,\n\t\t\t\t\tMergeSchema<\n\t\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t\t>,\n\t\t\t\t\tBasePath\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\tSingleton & {\n\t\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\t\t}\n\t\t\t>\n\t\t>\n\t): this\n\n\t/**\n\t * ### After Handle | Life cycle event\n\t * Intercept request **after** main handler is called.\n\t *\n\t * If truthy value is returned, will be assigned as `Response`\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .mapResponse((context, response) => {\n\t *         if(typeof response === \"object\")\n\t *             return JSON.stringify(response)\n\t *     })\n\t * ```\n\t */\n\tmapResponse<const Schema extends RouteSchema, Type extends LifeCycleType>(\n\t\toptions: { as: Type },\n\t\thandler: MaybeArray<\n\t\t\tMapResponse<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tSchema,\n\t\t\t\t\tMergeSchema<\n\t\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t\t>,\n\t\t\t\t\tBasePath\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'] &\n\t\t\t\t\t'global' extends Type\n\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t\t: {},\n\t\t\t\tSingleton &\n\t\t\t\t\t('global' extends Type\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tderive: Partial<\n\t\t\t\t\t\t\t\t\tEphemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tresolve: Partial<\n\t\t\t\t\t\t\t\t\tEphemeral['resolve'] & Volatile['resolve']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\t\tPartial<Volatile['derive']>\n\t\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\t\tPartial<Volatile['resolve']>\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\t\tVolatile['derive']\n\t\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t\t\t})\n\t\t\t>\n\t\t>\n\t): this\n\n\tmapResponse(\n\t\toptions: { as: LifeCycleType } | MaybeArray<Function>,\n\t\thandler?: MaybeArray<Function>\n\t) {\n\t\tif (!handler) return this.on('mapResponse', options as any)\n\n\t\treturn this.on(\n\t\t\toptions as { as: LifeCycleType },\n\t\t\t'mapResponse',\n\t\t\thandler as any\n\t\t)\n\t}\n\n\t/**\n\t * ### response | Life cycle event\n\t * Call AFTER main handler is executed\n\t * Good for analytic metrics\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onAfterResponse(() => {\n\t *         cleanup()\n\t *     })\n\t * ```\n\t */\n\tonAfterResponse<const Schema extends RouteSchema>(\n\t\thandler: MaybeArray<\n\t\t\tAfterResponseHandler<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tSchema,\n\t\t\t\t\tMergeSchema<\n\t\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t\t>,\n\t\t\t\t\tBasePath\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\tSingleton & {\n\t\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\t\t}\n\t\t\t>\n\t\t>\n\t): this\n\n\t/**\n\t * ### response | Life cycle event\n\t * Call AFTER main handler is executed\n\t * Good for analytic metrics\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onAfterResponse(() => {\n\t *         cleanup()\n\t * \t   })\n\t * ```\n\t */\n\n\tonAfterResponse<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Type extends LifeCycleType\n\t>(\n\t\toptions: { as: Type },\n\t\thandler: MaybeArray<\n\t\t\tAfterResponseHandler<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tSchema,\n\t\t\t\t\tMergeSchema<\n\t\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t\t>,\n\t\t\t\t\tBasePath\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'] &\n\t\t\t\t\t'global' extends Type\n\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t\t: {},\n\t\t\t\tSingleton &\n\t\t\t\t\t('global' extends Type\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tderive: Partial<\n\t\t\t\t\t\t\t\t\tEphemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tresolve: Partial<\n\t\t\t\t\t\t\t\t\tEphemeral['resolve'] & Volatile['resolve']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\t\tPartial<Volatile['derive']>\n\t\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\t\tPartial<Volatile['resolve']>\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\t\tVolatile['derive']\n\t\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t\t\t})\n\t\t\t>\n\t\t>\n\t): this\n\n\tonAfterResponse(\n\t\toptions: { as: LifeCycleType } | MaybeArray<Function>,\n\t\thandler?: MaybeArray<Function>\n\t) {\n\t\tif (!handler) return this.on('afterResponse', options as any)\n\n\t\treturn this.on(\n\t\t\toptions as { as: LifeCycleType },\n\t\t\t'afterResponse',\n\t\t\thandler as any\n\t\t)\n\t}\n\n\t/**\n\t * ### After Handle | Life cycle event\n\t * Intercept request **after** main handler is called.\n\t *\n\t * If truthy value is returned, will be assigned as `Response`\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onAfterHandle((context, response) => {\n\t *         if(typeof response === \"object\")\n\t *             return JSON.stringify(response)\n\t *     })\n\t * ```\n\t */\n\ttrace<const Schema extends RouteSchema>(\n\t\thandler: MaybeArray<TraceHandler<Schema, Singleton>>\n\t): this\n\n\t/**\n\t * ### After Handle | Life cycle event\n\t * Intercept request **after** main handler is called.\n\t *\n\t * If truthy value is returned, will be assigned as `Response`\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onAfterHandle((context, response) => {\n\t *         if(typeof response === \"object\")\n\t *             return JSON.stringify(response)\n\t *     })\n\t * ```\n\t */\n\ttrace<const Schema extends RouteSchema>(\n\t\toptions: { as: LifeCycleType },\n\t\thandler: MaybeArray<TraceHandler<Schema, Singleton>>\n\t): this\n\n\t/**\n\t * ### After Handle | Life cycle event\n\t * Intercept request **after** main handler is called.\n\t *\n\t * If truthy value is returned, will be assigned as `Response`\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onAfterHandle((context, response) => {\n\t *         if(typeof response === \"object\")\n\t *             return JSON.stringify(response)\n\t *     })\n\t * ```\n\t */\n\ttrace(\n\t\toptions: { as: LifeCycleType } | MaybeArray<Function>,\n\t\thandler?: MaybeArray<Function>\n\t) {\n\t\tif (!handler) {\n\t\t\thandler = options as MaybeArray<Function>\n\t\t\toptions = { as: 'local' }\n\t\t}\n\n\t\tif (!Array.isArray(handler)) handler = [handler] as Function[]\n\n\t\tfor (const fn of handler)\n\t\t\tthis.on(\n\t\t\t\toptions as { as: LifeCycleType },\n\t\t\t\t'trace',\n\t\t\t\tcreateTracer(fn as any) as any\n\t\t\t)\n\n\t\treturn this\n\t}\n\n\t/**\n\t * Register errors\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * class CustomError extends Error {\n\t *     constructor() {\n\t *         super()\n\t *     }\n\t * }\n\t *\n\t * new Elysia()\n\t *     .error('CUSTOM_ERROR', CustomError)\n\t * ```\n\t */\n\terror<\n\t\tconst Errors extends Record<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\tprototype: Error\n\t\t\t}\n\t\t>\n\t>(\n\t\terrors: Errors\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\t{\n\t\t\ttypebox: Definitions['typebox']\n\t\t\terror: Definitions['error'] & {\n\t\t\t\t[K in keyof Errors]: Errors[K] extends {\n\t\t\t\t\tprototype: infer LiteralError extends Error\n\t\t\t\t}\n\t\t\t\t\t? LiteralError\n\t\t\t\t\t: Errors[K]\n\t\t\t}\n\t\t},\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\t/**\n\t * Register errors\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * class CustomError extends Error {\n\t *     constructor() {\n\t *         super()\n\t *     }\n\t * }\n\t *\n\t * new Elysia()\n\t *     .error({\n\t *         CUSTOM_ERROR: CustomError\n\t *     })\n\t * ```\n\t */\n\terror<\n\t\tName extends string,\n\t\tconst CustomError extends {\n\t\t\tprototype: Error\n\t\t}\n\t>(\n\t\tname: Name,\n\t\terrors: CustomError\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\t{\n\t\t\ttypebox: Definitions['typebox']\n\t\t\terror: Definitions['error'] & {\n\t\t\t\t[name in Name]: CustomError extends {\n\t\t\t\t\tprototype: infer LiteralError extends Error\n\t\t\t\t}\n\t\t\t\t\t? LiteralError\n\t\t\t\t\t: CustomError\n\t\t\t}\n\t\t},\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\t/**\n\t * Register errors\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * class CustomError extends Error {\n\t *     constructor() {\n\t *         super()\n\t *     }\n\t * }\n\t *\n\t * new Elysia()\n\t *     .error('CUSTOM_ERROR', CustomError)\n\t * ```\n\t */\n\terror<const NewErrors extends Record<string, Error>>(\n\t\tmapper: (decorators: Definitions['error']) => NewErrors\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\t{\n\t\t\ttypebox: Definitions['typebox']\n\t\t\terror: {\n\t\t\t\t[K in keyof NewErrors]: NewErrors[K] extends {\n\t\t\t\t\tprototype: infer LiteralError extends Error\n\t\t\t\t}\n\t\t\t\t\t? LiteralError\n\t\t\t\t\t: never\n\t\t\t}\n\t\t},\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\terror(\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\tname:\n\t\t\t| string\n\t\t\t| Record<\n\t\t\t\t\tstring,\n\t\t\t\t\t{\n\t\t\t\t\t\tprototype: Error\n\t\t\t\t\t}\n\t\t\t  >\n\t\t\t| Function,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\terror?: {\n\t\t\tprototype: Error\n\t\t}\n\t): AnyElysia {\n\t\tswitch (typeof name) {\n\t\t\tcase 'string':\n\t\t\t\t// @ts-ignore\n\t\t\t\terror.prototype[ERROR_CODE] = name\n\n\t\t\t\t// @ts-ignore\n\t\t\t\tthis.definitions.error[name] = error\n\n\t\t\t\treturn this\n\n\t\t\tcase 'function':\n\t\t\t\tthis.definitions.error = name(this.definitions.error)\n\n\t\t\t\treturn this as any\n\t\t}\n\n\t\tfor (const [code, error] of Object.entries(name)) {\n\t\t\t// @ts-ignore\n\t\t\terror.prototype[ERROR_CODE] = code as any\n\n\t\t\tthis.definitions.error[code] = error as any\n\t\t}\n\n\t\treturn this\n\t}\n\n\t/**\n\t * ### Error | Life cycle event\n\t * Called when error is thrown during processing request\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onError(({ code }) => {\n\t *         if(code === \"NOT_FOUND\")\n\t *             return \"Path not found :(\"\n\t *     })\n\t * ```\n\t */\n\tonError<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Handler extends ErrorHandler<\n\t\t\tDefinitions['error'],\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'],\n\t\t\tSingleton,\n\t\t\tEphemeral,\n\t\t\tVolatile\n\t\t>\n\t>(\n\t\thandler: Handler\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: Volatile['derive']\n\t\t\tresolve: Volatile['resolve']\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: UnionResponseStatus<\n\t\t\t\tVolatile['response'],\n\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t>\n\t\t}\n\t>\n\n\t/**\n\t * ### Error | Life cycle event\n\t * Called when error is thrown during processing request\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onError(({ code }) => {\n\t *         if(code === \"NOT_FOUND\")\n\t *             return \"Path not found :(\"\n\t *     })\n\t * ```\n\t */\n\tonError<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Handlers extends ErrorHandler<\n\t\t\tDefinitions['error'],\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'],\n\t\t\tSingleton,\n\t\t\tEphemeral,\n\t\t\tVolatile\n\t\t>[]\n\t>(\n\t\thandler: Handlers\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: Volatile['derive']\n\t\t\tresolve: Volatile['resolve']\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: UnionResponseStatus<\n\t\t\t\tVolatile['response'],\n\t\t\t\tElysiaHandlerToResponseSchemas<Handlers>\n\t\t\t>\n\t\t}\n\t>\n\n\t/**\n\t * ### Error | Life cycle event\n\t * Called when error is thrown during processing request\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onError(({ code }) => {\n\t *         if(code === \"NOT_FOUND\")\n\t *             return \"Path not found :(\"\n\t *     })\n\t * ```\n\t */\n\tonError<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Type extends LifeCycleType,\n\t\tconst Handler extends ErrorHandler<\n\t\t\tDefinitions['error'],\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'],\n\t\t\tType extends 'global'\n\t\t\t\t? {\n\t\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\tVolatile['derive']\n\t\t\t\t\t\tresolve: Singleton['resolve'] &\n\t\t\t\t\t\t\tEphemeral['resolve'] &\n\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t}\n\t\t\t\t: Type extends 'scoped'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\t\t\tderive: Singleton['derive'] & Ephemeral['derive']\n\t\t\t\t\t\t\tresolve: Singleton['resolve'] & Ephemeral['resolve']\n\t\t\t\t\t\t}\n\t\t\t\t\t: Singleton,\n\t\t\tType extends 'global'\n\t\t\t\t? Ephemeral\n\t\t\t\t: {\n\t\t\t\t\t\tderive: Partial<Ephemeral['derive']>\n\t\t\t\t\t\tresolve: Partial<Ephemeral['resolve']>\n\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\tresponse: Ephemeral['response']\n\t\t\t\t\t},\n\t\t\tType extends 'global'\n\t\t\t\t? Ephemeral\n\t\t\t\t: Type extends 'scoped'\n\t\t\t\t\t? Ephemeral\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tderive: Partial<Ephemeral['derive']>\n\t\t\t\t\t\t\tresolve: Partial<Ephemeral['resolve']>\n\t\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\t\tresponse: Ephemeral['response']\n\t\t\t\t\t\t}\n\t\t>\n\t>(\n\t\toptions: { as: Type },\n\t\thandler: Handler\n\t): Type extends 'global'\n\t\t? Elysia<\n\t\t\t\tBasePath,\n\t\t\t\tSingleton,\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: Metadata['schema']\n\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t\t\t>\n\t\t\t\t},\n\t\t\t\tRoutes,\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t: Type extends 'scoped'\n\t\t\t? Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Ephemeral['derive']\n\t\t\t\t\t\tresolve: Ephemeral['resolve']\n\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t\t\t\t>\n\t\t\t\t\t},\n\t\t\t\t\tVolatile\n\t\t\t\t>\n\t\t\t: Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\tEphemeral,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Volatile['derive']\n\t\t\t\t\t\tresolve: Volatile['resolve']\n\t\t\t\t\t\tschema: Volatile['schema']\n\t\t\t\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchema<Handler>\n\t\t\t\t\t\t>\n\t\t\t\t\t}\n\t\t\t\t>\n\n\t/**\n\t * ### Error | Life cycle event\n\t * Called when error is thrown during processing request\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onError(({ code }) => {\n\t *         if(code === \"NOT_FOUND\")\n\t *             return \"Path not found :(\"\n\t *     })\n\t * ```\n\t */\n\tonError<\n\t\tconst Schema extends RouteSchema,\n\t\tconst Type extends LifeCycleType,\n\t\tconst Handlers extends ErrorHandler<\n\t\t\tDefinitions['error'],\n\t\t\tMergeSchema<\n\t\t\t\tSchema,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'],\n\t\t\tType extends 'global'\n\t\t\t\t? {\n\t\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\tVolatile['derive']\n\t\t\t\t\t\tresolve: Singleton['resolve'] &\n\t\t\t\t\t\t\tEphemeral['resolve'] &\n\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t}\n\t\t\t\t: Type extends 'scoped'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\t\t\tderive: Singleton['derive'] & Ephemeral['derive']\n\t\t\t\t\t\t\tresolve: Singleton['resolve'] & Ephemeral['resolve']\n\t\t\t\t\t\t}\n\t\t\t\t\t: Singleton,\n\t\t\tType extends 'global'\n\t\t\t\t? Ephemeral\n\t\t\t\t: {\n\t\t\t\t\t\tderive: Partial<Ephemeral['derive']>\n\t\t\t\t\t\tresolve: Partial<Ephemeral['resolve']>\n\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\tresponse: Ephemeral['response']\n\t\t\t\t\t},\n\t\t\tType extends 'global'\n\t\t\t\t? Ephemeral\n\t\t\t\t: Type extends 'scoped'\n\t\t\t\t\t? Ephemeral\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tderive: Partial<Ephemeral['derive']>\n\t\t\t\t\t\t\tresolve: Partial<Ephemeral['resolve']>\n\t\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\t\tresponse: Ephemeral['response']\n\t\t\t\t\t\t}\n\t\t>[]\n\t>(\n\t\toptions: { as: Type },\n\t\thandler: Handlers\n\t): Type extends 'global'\n\t\t? Elysia<\n\t\t\t\tBasePath,\n\t\t\t\tSingleton,\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: Metadata['schema']\n\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\tElysiaHandlerToResponseSchemas<Handlers>\n\t\t\t\t\t>\n\t\t\t\t},\n\t\t\t\tRoutes,\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t: Type extends 'scoped'\n\t\t\t? Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Ephemeral['derive']\n\t\t\t\t\t\tresolve: Ephemeral['resolve']\n\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchemas<Handlers>\n\t\t\t\t\t\t>\n\t\t\t\t\t},\n\t\t\t\t\tVolatile\n\t\t\t\t>\n\t\t\t: Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\tEphemeral,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Volatile['derive']\n\t\t\t\t\t\tresolve: Volatile['resolve']\n\t\t\t\t\t\tschema: Volatile['schema']\n\t\t\t\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchemas<Handlers>\n\t\t\t\t\t\t>\n\t\t\t\t\t}\n\t\t\t\t>\n\n\t/**\n\t * ### Error | Life cycle event\n\t * Called when error is thrown during processing request\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onError(({ code }) => {\n\t *         if(code === \"NOT_FOUND\")\n\t *             return \"Path not found :(\"\n\t *     })\n\t * ```\n\t */\n\tonError(\n\t\toptions: { as: LifeCycleType } | MaybeArray<Function>,\n\t\thandler?: MaybeArray<Function>\n\t): any {\n\t\tif (!handler) return this.on('error', options as any)\n\n\t\treturn this.on(\n\t\t\toptions as { as: LifeCycleType },\n\t\t\t'error',\n\t\t\thandler as any\n\t\t)\n\t}\n\n\t/**\n\t * ### stop | Life cycle event\n\t * Called after server stop serving request\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .onStop((app) => {\n\t *         cleanup()\n\t *     })\n\t * ```\n\t */\n\tonStop(handler: MaybeArray<GracefulHandler<this>>) {\n\t\tthis.on('stop', handler as any)\n\n\t\treturn this\n\t}\n\n\t/**\n\t * ### on\n\t * Syntax sugar for attaching life cycle event by name\n\t *\n\t * Does the exact same thing as `.on[Event]()`\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .on('error', ({ code }) => {\n\t *         if(code === \"NOT_FOUND\")\n\t *             return \"Path not found :(\"\n\t *     })\n\t * ```\n\t */\n\ton<Event extends keyof LifeCycleStore>(\n\t\ttype: Event,\n\t\thandlers: MaybeArray<\n\t\t\tExtract<LifeCycleStore[Event], HookContainer[]>[0]['fn']\n\t\t>\n\t): this\n\n\t/**\n\t * ### on\n\t * Syntax sugar for attaching life cycle event by name\n\t *\n\t * Does the exact same thing as `.on[Event]()`\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .on('error', ({ code }) => {\n\t *         if(code === \"NOT_FOUND\")\n\t *             return \"Path not found :(\"\n\t *     })\n\t * ```\n\t */\n\ton<const Event extends keyof LifeCycleStore>(\n\t\toptions: { as: LifeCycleType },\n\t\ttype: Event,\n\t\thandlers: MaybeArray<Extract<LifeCycleStore[Event], Function[]>[0]>\n\t): this\n\n\ton(\n\t\toptionsOrType: { as: LifeCycleType } | string,\n\t\ttypeOrHandlers: MaybeArray<Function | HookContainer> | string,\n\t\thandlers?: MaybeArray<Function | HookContainer>\n\t) {\n\t\tlet type: keyof LifeCycleStore\n\n\t\tswitch (typeof optionsOrType) {\n\t\t\tcase 'string':\n\t\t\t\ttype = optionsOrType as any\n\t\t\t\thandlers = typeOrHandlers as any\n\n\t\t\t\tbreak\n\n\t\t\tcase 'object':\n\t\t\t\ttype = typeOrHandlers as any\n\n\t\t\t\tif (\n\t\t\t\t\t!Array.isArray(typeOrHandlers) &&\n\t\t\t\t\ttypeof typeOrHandlers === 'object'\n\t\t\t\t)\n\t\t\t\t\thandlers = typeOrHandlers\n\n\t\t\t\tbreak\n\t\t}\n\n\t\tif (Array.isArray(handlers)) handlers = fnToContainer(handlers)\n\t\telse {\n\t\t\tif (typeof handlers === 'function')\n\t\t\t\thandlers = [\n\t\t\t\t\t{\n\t\t\t\t\t\tfn: handlers\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\telse handlers = [handlers!]\n\t\t}\n\n\t\tconst handles = handlers as HookContainer[]\n\n\t\tfor (const handle of handles) {\n\t\t\thandle.scope =\n\t\t\t\ttypeof optionsOrType === 'string'\n\t\t\t\t\t? 'local'\n\t\t\t\t\t: (optionsOrType?.as ?? 'local')\n\n\t\t\t// @ts-expect-error\n\t\t\tif (type === 'resolve' || type === 'derive') handle.subType = type\n\t\t}\n\n\t\tif (type !== 'trace')\n\t\t\tthis.inference = sucrose(\n\t\t\t\t{\n\t\t\t\t\t[type]: handles.map((x) => x.fn)\n\t\t\t\t},\n\t\t\t\tthis.inference,\n\t\t\t\tthis.config.sucrose\n\t\t\t)\n\n\t\tfor (const handle of handles) {\n\t\t\tconst fn = asHookType(handle, 'global', { skipIfHasType: true })\n\t\t\tif (this.config.name || this.config.seed)\n\t\t\t\tfn.checksum = checksum(\n\t\t\t\t\tthis.config.name + JSON.stringify(this.config.seed)\n\t\t\t\t)\n\n\t\t\tswitch (type) {\n\t\t\t\tcase 'start':\n\t\t\t\t\tthis.event.start ??= []\n\t\t\t\t\tthis.event.start.push(fn as any)\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'request':\n\t\t\t\t\tthis.event.request ??= []\n\t\t\t\t\tthis.event.request.push(fn as any)\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'parse':\n\t\t\t\t\tthis.event.parse ??= []\n\t\t\t\t\tthis.event.parse.push(fn as any)\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'transform':\n\t\t\t\t\tthis.event.transform ??= []\n\t\t\t\t\tthis.event.transform.push(fn as any)\n\t\t\t\t\tbreak\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\tcase 'derive':\n\t\t\t\t\tthis.event.transform ??= []\n\t\t\t\t\tthis.event.transform.push(\n\t\t\t\t\t\tfnToContainer(fn as any, 'derive') as any\n\t\t\t\t\t)\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'beforeHandle':\n\t\t\t\t\tthis.event.beforeHandle ??= []\n\t\t\t\t\tthis.event.beforeHandle.push(fn as any)\n\t\t\t\t\tbreak\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\t// eslint-disable-next-line sonarjs/no-duplicated-branches\n\t\t\t\tcase 'resolve':\n\t\t\t\t\tthis.event.beforeHandle ??= []\n\t\t\t\t\tthis.event.beforeHandle.push(\n\t\t\t\t\t\tfnToContainer(fn as any, 'resolve') as any\n\t\t\t\t\t)\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'afterHandle':\n\t\t\t\t\tthis.event.afterHandle ??= []\n\t\t\t\t\tthis.event.afterHandle.push(fn as any)\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'mapResponse':\n\t\t\t\t\tthis.event.mapResponse ??= []\n\t\t\t\t\tthis.event.mapResponse.push(fn as any)\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'afterResponse':\n\t\t\t\t\tthis.event.afterResponse ??= []\n\t\t\t\t\tthis.event.afterResponse.push(fn as any)\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'trace':\n\t\t\t\t\tthis.event.trace ??= []\n\t\t\t\t\tthis.event.trace.push(fn as any)\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'error':\n\t\t\t\t\tthis.event.error ??= []\n\t\t\t\t\tthis.event.error.push(fn as any)\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'stop':\n\t\t\t\t\tthis.event.stop ??= []\n\t\t\t\t\tthis.event.stop.push(fn as any)\n\t\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\treturn this\n\t}\n\n\tas(type: 'global'): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator']\n\t\t\tstore: Singleton['store']\n\t\t\tderive: Singleton['derive'] &\n\t\t\t\tEphemeral['derive'] &\n\t\t\t\tVolatile['derive']\n\t\t\tresolve: Singleton['resolve'] &\n\t\t\t\tEphemeral['resolve'] &\n\t\t\t\tVolatile['resolve']\n\t\t},\n\t\tDefinitions,\n\t\t{\n\t\t\tschema: MergeSchema<\n\t\t\t\tMergeSchema<Volatile['schema'], Ephemeral['schema']>,\n\t\t\t\tMetadata['schema']\n\t\t\t>\n\t\t\tstandaloneSchema: Metadata['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema']\n\t\t\tmacro: Metadata['macro']\n\t\t\tmacroFn: Metadata['macroFn']\n\t\t\tparser: Metadata['parser']\n\t\t\tresponse: Metadata['response'] &\n\t\t\t\tEphemeral['response'] &\n\t\t\t\tVolatile['response']\n\t\t},\n\t\tRoutes,\n\t\t{\n\t\t\tderive: {}\n\t\t\tresolve: {}\n\t\t\tschema: {}\n\t\t\tstandaloneSchema: {}\n\t\t\tresponse: {}\n\t\t},\n\t\t{\n\t\t\tderive: {}\n\t\t\tresolve: {}\n\t\t\tschema: {}\n\t\t\tstandaloneSchema: {}\n\t\t\tresponse: {}\n\t\t}\n\t>\n\n\tas(type: 'scoped'): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\t{\n\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\tschema: MergeSchema<Volatile['schema'], Ephemeral['schema']>\n\t\t\tstandaloneSchema: Volatile['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema']\n\t\t\tresponse: Volatile['response'] & Ephemeral['response']\n\t\t},\n\t\t{\n\t\t\tderive: {}\n\t\t\tresolve: {}\n\t\t\tschema: {}\n\t\t\tstandaloneSchema: {}\n\t\t\tresponse: {}\n\t\t}\n\t>\n\n\tas(type: 'global' | 'scoped') {\n\t\tpromoteEvent(this.event.parse, type)\n\t\tpromoteEvent(this.event.transform, type)\n\t\tpromoteEvent(this.event.beforeHandle, type)\n\t\tpromoteEvent(this.event.afterHandle, type)\n\t\tpromoteEvent(this.event.mapResponse, type)\n\t\tpromoteEvent(this.event.afterResponse, type)\n\t\tpromoteEvent(this.event.trace, type)\n\t\tpromoteEvent(this.event.error, type)\n\n\t\tif (type === 'scoped') {\n\t\t\tthis.validator.scoped = mergeSchemaValidator(\n\t\t\t\tthis.validator.scoped,\n\t\t\t\tthis.validator.local\n\t\t\t)\n\t\t\tthis.validator.local = null\n\n\t\t\tif (this.standaloneValidator.local !== null) {\n\t\t\t\tthis.standaloneValidator.scoped ||= []\n\t\t\t\tthis.standaloneValidator.scoped.push(\n\t\t\t\t\t...this.standaloneValidator.local\n\t\t\t\t)\n\t\t\t\tthis.standaloneValidator.local = null\n\t\t\t}\n\t\t} else if (type === 'global') {\n\t\t\tthis.validator.global = mergeSchemaValidator(\n\t\t\t\tthis.validator.global,\n\t\t\t\tmergeSchemaValidator(\n\t\t\t\t\tthis.validator.scoped,\n\t\t\t\t\tthis.validator.local\n\t\t\t\t) as SchemaValidator\n\t\t\t) as SchemaValidator\n\n\t\t\tthis.validator.scoped = null\n\t\t\tthis.validator.local = null\n\n\t\t\tif (this.standaloneValidator.local !== null) {\n\t\t\t\tthis.standaloneValidator.scoped ||= []\n\t\t\t\tthis.standaloneValidator.scoped.push(\n\t\t\t\t\t...this.standaloneValidator.local\n\t\t\t\t)\n\t\t\t\tthis.standaloneValidator.local = null\n\t\t\t}\n\t\t\tif (this.standaloneValidator.scoped !== null) {\n\t\t\t\tthis.standaloneValidator.global ||= []\n\t\t\t\tthis.standaloneValidator.global.push(\n\t\t\t\t\t...this.standaloneValidator.scoped\n\t\t\t\t)\n\t\t\t\tthis.standaloneValidator.scoped = null\n\t\t\t}\n\t\t}\n\n\t\treturn this as any\n\t}\n\n\tgroup<const Prefix extends string, const NewElysia extends AnyElysia>(\n\t\tprefix: Prefix,\n\t\trun: (\n\t\t\tgroup: Elysia<\n\t\t\t\tPrefix extends '' ? BasePath : JoinPath<BasePath, Prefix>,\n\t\t\t\tSingleton,\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: MergeSchema<\n\t\t\t\t\t\tUnwrapRoute<{}, Definitions['typebox']>,\n\t\t\t\t\t\tMetadata['schema']\n\t\t\t\t\t>\n\t\t\t\t\tstandaloneSchema: UnwrapRoute<{}, Definitions['typebox']> &\n\t\t\t\t\t\tMetadata['standaloneSchema']\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: Metadata['response']\n\t\t\t\t},\n\t\t\t\t{},\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t) => NewElysia\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes & NewElysia['~Routes'],\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\tgroup<\n\t\tconst Prefix extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends MergeSchema<\n\t\t\tUnwrapRoute<\n\t\t\t\tInput,\n\t\t\t\tDefinitions['typebox'],\n\t\t\t\tJoinPath<BasePath, Prefix>\n\t\t\t>,\n\t\t\tMergeSchema<\n\t\t\t\tVolatile['schema'],\n\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t>\n\t\t> &\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\tEphemeral['standaloneSchema'] &\n\t\t\tVolatile['standaloneSchema'],\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst BeforeHandle extends MaybeArray<\n\t\t\tOptionalHandler<Schema, Singleton>\n\t\t>,\n\t\tconst AfterHandle extends MaybeArray<AfterHandler<Schema, Singleton>>,\n\t\tconst ErrorHandle extends MaybeArray<\n\t\t\tErrorHandler<Definitions['error'], Schema, Singleton>\n\t\t>,\n\t\tconst NewElysia extends AnyElysia\n\t>(\n\t\tprefix: Prefix,\n\t\tschema: GuardLocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tSingleton & {\n\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\tVolatile['resolve'] &\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tMacroContext['response']\n\t\t\t},\n\t\t\tkeyof Metadata['parser'],\n\t\t\tBeforeHandle,\n\t\t\tAfterHandle,\n\t\t\tErrorHandle\n\t\t>,\n\t\trun: (\n\t\t\tgroup: Elysia<\n\t\t\t\tJoinPath<BasePath, Prefix>,\n\t\t\t\t{\n\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\tderive: Singleton['derive']\n\t\t\t\t\tresolve: Singleton['resolve'] &\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tMacroContext['resolve']\n\t\t\t\t},\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: Schema\n\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema'] &\n\t\t\t\t\t\tSchema &\n\t\t\t\t\t\tMacroContext\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: Metadata['response'] &\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tMacroContext['response'] &\n\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<BeforeHandle> &\n\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<AfterHandle> &\n\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<ErrorHandle>\n\t\t\t\t},\n\t\t\t\t{},\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t) => NewElysia\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes & NewElysia['~Routes'],\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\t/**\n\t * ### group\n\t * Encapsulate and group path with prefix\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .group('/v1', app => app\n\t *         .get('/', () => 'Hi')\n\t *         .get('/name', () => 'Elysia')\n\t *     })\n\t * ```\n\t */\n\tgroup(\n\t\tprefix: string,\n\t\tschemaOrRun: AnyLocalHook | ((group: AnyElysia) => AnyElysia),\n\t\trun?: (group: AnyElysia) => AnyElysia\n\t): AnyElysia {\n\t\tconst instance = new Elysia({\n\t\t\t...this.config,\n\t\t\tprefix: ''\n\t\t})\n\n\t\tinstance.singleton = { ...this.singleton }\n\t\tinstance.definitions = { ...this.definitions }\n\t\tinstance.getServer = () => this.getServer()\n\t\tinstance.inference = cloneInference(this.inference)\n\t\tinstance.extender = { ...this.extender }\n\t\tinstance['~parser'] = this['~parser']\n\t\tinstance.standaloneValidator = {\n\t\t\tlocal: [...(this.standaloneValidator.local ?? [])],\n\t\t\tscoped: [...(this.standaloneValidator.scoped ?? [])],\n\t\t\tglobal: [...(this.standaloneValidator.global ?? [])]\n\t\t}\n\n\t\tconst isSchema = typeof schemaOrRun === 'object'\n\t\tconst sandbox = (isSchema ? run! : schemaOrRun)(instance)\n\t\tthis.singleton = mergeDeep(this.singleton, instance.singleton) as any\n\t\tthis.definitions = mergeDeep(this.definitions, instance.definitions)\n\n\t\tif (sandbox.event.request?.length)\n\t\t\tthis.event.request = [\n\t\t\t\t...(this.event.request || []),\n\t\t\t\t...((sandbox.event.request || []) as any)\n\t\t\t]\n\n\t\tif (sandbox.event.mapResponse?.length)\n\t\t\tthis.event.mapResponse = [\n\t\t\t\t...(this.event.mapResponse || []),\n\t\t\t\t...((sandbox.event.mapResponse || []) as any)\n\t\t\t]\n\n\t\tthis.model(sandbox.definitions.type)\n\n\t\tObject.values(instance.router.history).forEach(\n\t\t\t({ method, path, handler, hooks }) => {\n\t\t\t\tpath =\n\t\t\t\t\t(isSchema ? '' : (this.config.prefix ?? '')) + prefix + path\n\n\t\t\t\tif (isSchema) {\n\t\t\t\t\tconst {\n\t\t\t\t\t\tbody,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tquery,\n\t\t\t\t\t\tparams,\n\t\t\t\t\t\tcookie,\n\t\t\t\t\t\tresponse,\n\t\t\t\t\t\t...hook\n\t\t\t\t\t} = schemaOrRun\n\t\t\t\t\tconst localHook = hooks as AnyLocalHook\n\n\t\t\t\t\t// Apply macros to expand group options before merging\n\t\t\t\t\t// This ensures macro-defined hooks run before nested plugin hooks\n\t\t\t\t\tthis.applyMacro(hook)\n\n\t\t\t\t\tconst hasStandaloneSchema =\n\t\t\t\t\t\tbody || headers || query || params || cookie || response\n\n\t\t\t\t\tthis.add(\n\t\t\t\t\t\tmethod,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\thandler,\n\t\t\t\t\t\tmergeHook(hook, {\n\t\t\t\t\t\t\t...(localHook || {}),\n\t\t\t\t\t\t\terror: !localHook.error\n\t\t\t\t\t\t\t\t? sandbox.event.error\n\t\t\t\t\t\t\t\t: Array.isArray(localHook.error)\n\t\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t\t...(localHook.error ?? []),\n\t\t\t\t\t\t\t\t\t\t\t...(sandbox.event.error ?? [])\n\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t\t\tlocalHook.error,\n\t\t\t\t\t\t\t\t\t\t\t...(sandbox.event.error ?? [])\n\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t// Merge macro's standaloneValidator with local and group schema\n\t\t\t\t\t\t\tstandaloneValidator:\n\t\t\t\t\t\t\t\thook.standaloneValidator ||\n\t\t\t\t\t\t\t\tlocalHook.standaloneValidator ||\n\t\t\t\t\t\t\t\thasStandaloneSchema\n\t\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t\t...(hook.standaloneValidator ?? []),\n\t\t\t\t\t\t\t\t\t\t\t...(localHook.standaloneValidator ??\n\t\t\t\t\t\t\t\t\t\t\t\t[]),\n\t\t\t\t\t\t\t\t\t\t\t...(hasStandaloneSchema\n\t\t\t\t\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbody,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tquery,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tparams,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tresponse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t\t\t\t\t: [])\n\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tundefined\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tthis.add(\n\t\t\t\t\t\tmethod,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\thandler,\n\t\t\t\t\t\tmergeHook(hooks as AnyLocalHook, {\n\t\t\t\t\t\t\terror: sandbox.event.error\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tskipPrefix: true\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### guard\n\t * Encapsulate and pass hook into all child handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .guard({\n\t *         body: t.Object({\n\t *             username: t.String(),\n\t *             password: t.String()\n\t *         })\n\t *     })\n\t * ```\n\t */\n\tguard<\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends MergeSchema<\n\t\t\tUnwrapRoute<Input, Definitions['typebox'], BasePath>,\n\t\t\tMetadata['schema']\n\t\t>,\n\t\tconst MacroContext extends MacroToContext<\n\t\t\tMetadata['macroFn'],\n\t\t\tOmit<Input, NonResolvableMacroKey | 'as'>,\n\t\t\tDefinitions['typebox']\n\t\t>,\n\t\tconst GuardType extends GuardSchemaType,\n\t\tconst AsType extends LifeCycleType,\n\t\tconst BeforeHandle extends MaybeArray<\n\t\t\tOptionalHandler<Schema, Singleton>\n\t\t>,\n\t\tconst AfterHandle extends MaybeArray<AfterHandler<Schema, Singleton>>,\n\t\tconst ErrorHandle extends MaybeArray<\n\t\t\tErrorHandler<Definitions['error'], Schema, Singleton>\n\t\t>\n\t>(\n\t\thook: GuardLocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tSingleton & {\n\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\tVolatile['resolve'] &\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tMacroContext['response']\n\t\t\t},\n\t\t\tkeyof Metadata['parser'],\n\t\t\tBeforeHandle,\n\t\t\tAfterHandle,\n\t\t\tErrorHandle,\n\t\t\tGuardType,\n\t\t\tAsType\n\t\t>\n\t): Or<\n\t\tGuardSchemaType extends GuardType ? true : false,\n\t\tGuardType extends 'override' ? true : false\n\t> extends true\n\t\t? Or<\n\t\t\t\tLifeCycleType extends AsType ? true : false,\n\t\t\t\tAsType extends 'local' ? true : false\n\t\t\t> extends true\n\t\t\t? Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\tEphemeral,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Volatile['derive']\n\t\t\t\t\t\tresolve: Volatile['resolve'] &\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\tMacroContext['resolve']\n\t\t\t\t\t\tschema: {} extends PickIfExists<\n\t\t\t\t\t\t\tInput,\n\t\t\t\t\t\t\tkeyof InputSchema\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t? Volatile['schema']\n\t\t\t\t\t\t\t: MergeSchema<\n\t\t\t\t\t\t\t\t\tUnwrapRoute<Input, Definitions['typebox']>,\n\t\t\t\t\t\t\t\t\tMetadata['schema']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\tstandaloneSchema: Volatile['standaloneSchema'] &\n\t\t\t\t\t\t\tSimplifyToSchema<MacroContext>\n\t\t\t\t\t\tresponse: Volatile['response'] &\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<BeforeHandle> &\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<AfterHandle> &\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<ErrorHandle> &\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\tMacroContext['return']\n\t\t\t\t\t}\n\t\t\t\t>\n\t\t\t: AsType extends 'global'\n\t\t\t\t? Elysia<\n\t\t\t\t\t\tBasePath,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\t\t\tderive: Singleton['derive']\n\t\t\t\t\t\t\tresolve: Singleton['resolve'] &\n\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\tMacroContext['resolve']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tDefinitions,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tschema: {} extends PickIfExists<\n\t\t\t\t\t\t\t\tInput,\n\t\t\t\t\t\t\t\tkeyof InputSchema\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t? Metadata['schema']\n\t\t\t\t\t\t\t\t: MergeSchema<\n\t\t\t\t\t\t\t\t\t\tUnwrapRoute<\n\t\t\t\t\t\t\t\t\t\t\tInput,\n\t\t\t\t\t\t\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\t\t\t\t\t\t\tBasePath\n\t\t\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\t\t\tMetadata['schema']\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema'] &\n\t\t\t\t\t\t\t\tSimplifyToSchema<MacroContext>\n\t\t\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\t\t\tresponse: Metadata['response'] &\n\t\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<BeforeHandle> &\n\t\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<AfterHandle> &\n\t\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<ErrorHandle> &\n\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\tMacroContext['return']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tRoutes,\n\t\t\t\t\t\tEphemeral,\n\t\t\t\t\t\tVolatile\n\t\t\t\t\t>\n\t\t\t\t: Elysia<\n\t\t\t\t\t\tBasePath,\n\t\t\t\t\t\tSingleton,\n\t\t\t\t\t\tDefinitions,\n\t\t\t\t\t\tMetadata,\n\t\t\t\t\t\tRoutes,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tderive: Ephemeral['derive']\n\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\tMacroContext['resolve']\n\t\t\t\t\t\t\tschema: {} extends PickIfExists<\n\t\t\t\t\t\t\t\tInput,\n\t\t\t\t\t\t\t\tkeyof InputSchema\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t? EphemeralType['schema']\n\t\t\t\t\t\t\t\t: MergeSchema<\n\t\t\t\t\t\t\t\t\t\tUnwrapRoute<\n\t\t\t\t\t\t\t\t\t\t\tInput,\n\t\t\t\t\t\t\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\t\t\tMetadata['schema'] & Ephemeral['schema']\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\tSimplifyToSchema<MacroContext>\n\t\t\t\t\t\t\tresponse: Ephemeral['response'] &\n\t\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<BeforeHandle> &\n\t\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<AfterHandle> &\n\t\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<ErrorHandle> &\n\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\tMacroContext['return']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tVolatile\n\t\t\t\t\t>\n\t\t: Or<\n\t\t\t\t\tLifeCycleType extends AsType ? true : false,\n\t\t\t\t\tAsType extends 'local' ? true : false\n\t\t\t  > extends true\n\t\t\t? Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\tEphemeral,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Volatile['derive']\n\t\t\t\t\t\tresolve: Volatile['resolve'] &\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\tMacroContext['resolve']\n\t\t\t\t\t\tschema: Volatile['schema']\n\t\t\t\t\t\tstandaloneSchema: SimplifyToSchema<MacroContext> &\n\t\t\t\t\t\t\t({} extends PickIfExists<Input, keyof InputSchema>\n\t\t\t\t\t\t\t\t? Volatile['standaloneSchema']\n\t\t\t\t\t\t\t\t: Volatile['standaloneSchema'] &\n\t\t\t\t\t\t\t\t\t\tUnwrapRoute<\n\t\t\t\t\t\t\t\t\t\t\tInput,\n\t\t\t\t\t\t\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t\t\t\t\t\t\t>)\n\t\t\t\t\t\tresponse: Volatile['response'] &\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<BeforeHandle> &\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<AfterHandle> &\n\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<ErrorHandle> &\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\tMacroContext['return']\n\t\t\t\t\t}\n\t\t\t\t>\n\t\t\t: AsType extends 'global'\n\t\t\t\t? Elysia<\n\t\t\t\t\t\tBasePath,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\t\t\tderive: Singleton['derive']\n\t\t\t\t\t\t\tresolve: Singleton['resolve'] &\n\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\tMacroContext['resolve']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tDefinitions,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tschema: Metadata['schema']\n\t\t\t\t\t\t\tstandaloneSchema: SimplifyToSchema<MacroContext> &\n\t\t\t\t\t\t\t\t({} extends PickIfExists<\n\t\t\t\t\t\t\t\t\tInput,\n\t\t\t\t\t\t\t\t\tkeyof InputSchema\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t? Metadata['standaloneSchema']\n\t\t\t\t\t\t\t\t\t: UnwrapRoute<\n\t\t\t\t\t\t\t\t\t\t\tInput,\n\t\t\t\t\t\t\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\t\t\t\t\t\t\tBasePath\n\t\t\t\t\t\t\t\t\t\t> &\n\t\t\t\t\t\t\t\t\t\t\tMetadata['standaloneSchema'])\n\t\t\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\t\t\tresponse: Metadata['response'] &\n\t\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<BeforeHandle> &\n\t\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<AfterHandle> &\n\t\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<ErrorHandle> &\n\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\tMacroContext['return']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tRoutes,\n\t\t\t\t\t\tEphemeral,\n\t\t\t\t\t\tVolatile\n\t\t\t\t\t>\n\t\t\t\t: Elysia<\n\t\t\t\t\t\tBasePath,\n\t\t\t\t\t\tSingleton,\n\t\t\t\t\t\tDefinitions,\n\t\t\t\t\t\tMetadata,\n\t\t\t\t\t\tRoutes,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tderive: Ephemeral['derive']\n\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\tMacroContext['resolve']\n\t\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\t\tstandaloneSchema: SimplifyToSchema<MacroContext> &\n\t\t\t\t\t\t\t\t({} extends PickIfExists<\n\t\t\t\t\t\t\t\t\tInput,\n\t\t\t\t\t\t\t\t\tkeyof InputSchema\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t? Ephemeral['standaloneSchema']\n\t\t\t\t\t\t\t\t\t: Ephemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\t\t\t\tUnwrapRoute<\n\t\t\t\t\t\t\t\t\t\t\t\tInput,\n\t\t\t\t\t\t\t\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t\t\t\t\t\t\t\t>)\n\t\t\t\t\t\t\tresponse: Ephemeral['response'] &\n\t\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<BeforeHandle> &\n\t\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<AfterHandle> &\n\t\t\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<ErrorHandle> &\n\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\tMacroContext['return']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tVolatile\n\t\t\t\t\t>\n\n\tguard<\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends MergeSchema<\n\t\t\tUnwrapRoute<Input, Definitions['typebox'], BasePath>,\n\t\t\tMergeSchema<\n\t\t\t\tVolatile['schema'],\n\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t>\n\t\t> &\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\tEphemeral['standaloneSchema'] &\n\t\t\tVolatile['standaloneSchema'],\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey | 'as'>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst BeforeHandle extends MaybeArray<\n\t\t\tOptionalHandler<Schema, Singleton>\n\t\t>,\n\t\tconst AfterHandle extends MaybeArray<AfterHandler<Schema, Singleton>>,\n\t\tconst ErrorHandle extends MaybeArray<\n\t\t\tErrorHandler<any, Schema, Singleton>\n\t\t>,\n\t\tconst NewElysia extends AnyElysia\n\t>(\n\t\tschema: GuardLocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tSingleton & {\n\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\t},\n\t\t\tkeyof Metadata['parser'],\n\t\t\tBeforeHandle,\n\t\t\tAfterHandle,\n\t\t\tErrorHandle\n\t\t>,\n\t\trun: (\n\t\t\tgroup: Elysia<\n\t\t\t\tBasePath,\n\t\t\t\t{\n\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\tderive: Singleton['derive']\n\t\t\t\t\tresolve: Singleton['resolve'] &\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tMacroContext['resolve']\n\t\t\t\t},\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: Schema\n\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema'] &\n\t\t\t\t\t\tSchema &\n\t\t\t\t\t\tMacroContext\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: Metadata['response'] &\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tMacroContext['response'] &\n\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<BeforeHandle> &\n\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<AfterHandle> &\n\t\t\t\t\t\tElysiaHandlerToResponseSchemaAmbiguous<ErrorHandle>\n\t\t\t\t},\n\t\t\t\t{},\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t) => NewElysia\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes & NewElysia['~Routes'],\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: Volatile['derive']\n\t\t\tresolve: Volatile['resolve'] &\n\t\t\t\t// @ts-ignore\n\t\t\t\tMacroContext['resolve']\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: Volatile['response'] &\n\t\t\t\t// @ts-ignore\n\t\t\t\tMacroContext['response']\n\t\t}\n\t>\n\n\t/**\n\t * ### guard\n\t * Encapsulate and pass hook into all child handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .guard({\n\t *          body: t.Object({\n\t *              username: t.String(),\n\t *              password: t.String()\n\t *          })\n\t *     }, app => app\n\t *         .get(\"/\", () => 'Hi')\n\t *         .get(\"/name\", () => 'Elysia')\n\t *     })\n\t * ```\n\t */\n\tguard(\n\t\thook:\n\t\t\t| (AnyLocalHook & {\n\t\t\t\t\tas: LifeCycleType\n\t\t\t  })\n\t\t\t| ((group: AnyElysia) => AnyElysia),\n\t\trun?: (group: AnyElysia) => AnyElysia\n\t): AnyElysia {\n\t\tif (!run) {\n\t\t\tif (typeof hook === 'object') {\n\t\t\t\tthis.applyMacro(hook)\n\n\t\t\t\tif (hook.detail) {\n\t\t\t\t\tif (this.config.detail)\n\t\t\t\t\t\tthis.config.detail = mergeDeep(\n\t\t\t\t\t\t\tObject.assign({}, this.config.detail),\n\t\t\t\t\t\t\thook.detail\n\t\t\t\t\t\t)\n\t\t\t\t\telse this.config.detail = hook.detail\n\t\t\t\t}\n\n\t\t\t\tif (hook.tags) {\n\t\t\t\t\tif (!this.config.detail)\n\t\t\t\t\t\tthis.config.detail = {\n\t\t\t\t\t\t\ttags: hook.tags\n\t\t\t\t\t\t}\n\t\t\t\t\telse this.config.detail.tags = hook.tags\n\t\t\t\t}\n\n\t\t\t\tconst type: LifeCycleType = hook.as ?? 'local'\n\n\t\t\t\tif (hook.schema === 'standalone') {\n\t\t\t\t\tif (!this.standaloneValidator[type])\n\t\t\t\t\t\tthis.standaloneValidator[type] = []\n\n\t\t\t\t\tconst response = !hook?.response\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: typeof hook.response === 'string' ||\n\t\t\t\t\t\t\t  Kind in hook.response ||\n\t\t\t\t\t\t\t  '~standard' in hook.response\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t200: hook.response\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: hook?.response\n\n\t\t\t\t\tthis.standaloneValidator[type].push({\n\t\t\t\t\t\tbody: hook.body,\n\t\t\t\t\t\theaders: hook.headers,\n\t\t\t\t\t\tparams: hook.params,\n\t\t\t\t\t\tquery: hook.query,\n\t\t\t\t\t\tresponse,\n\t\t\t\t\t\tcookie: hook.cookie\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tthis.validator[type] = {\n\t\t\t\t\t\tbody: hook.body ?? this.validator[type]?.body,\n\t\t\t\t\t\theaders: hook.headers ?? this.validator[type]?.headers,\n\t\t\t\t\t\tparams: hook.params ?? this.validator[type]?.params,\n\t\t\t\t\t\tquery: hook.query ?? this.validator[type]?.query,\n\t\t\t\t\t\tresponse:\n\t\t\t\t\t\t\thook.response ?? this.validator[type]?.response,\n\t\t\t\t\t\tcookie: hook.cookie ?? this.validator[type]?.cookie\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (hook.parse) this.on({ as: type }, 'parse', hook.parse)\n\t\t\t\tif (hook.transform)\n\t\t\t\t\tthis.on({ as: type }, 'transform', hook.transform)\n\t\t\t\t// @ts-expect-error\n\t\t\t\tif (hook.derive) this.on({ as: type }, 'derive', hook.derive)\n\t\t\t\tif (hook.beforeHandle)\n\t\t\t\t\tthis.on({ as: type }, 'beforeHandle', hook.beforeHandle)\n\t\t\t\t// @ts-expect-error\n\t\t\t\tif (hook.resolve) this.on({ as: type }, 'resolve', hook.resolve)\n\t\t\t\tif (hook.afterHandle)\n\t\t\t\t\tthis.on({ as: type }, 'afterHandle', hook.afterHandle)\n\t\t\t\tif (hook.mapResponse)\n\t\t\t\t\tthis.on({ as: type }, 'mapResponse', hook.mapResponse)\n\t\t\t\tif (hook.afterResponse)\n\t\t\t\t\tthis.on({ as: type }, 'afterResponse', hook.afterResponse)\n\t\t\t\tif (hook.error) this.on({ as: type }, 'error', hook.error)\n\n\t\t\t\treturn this\n\t\t\t}\n\n\t\t\treturn this.guard({} as any, hook)\n\t\t}\n\n\t\tconst instance = new Elysia({\n\t\t\t...this.config,\n\t\t\tprefix: ''\n\t\t})\n\t\tinstance.singleton = { ...this.singleton }\n\t\tinstance.definitions = { ...this.definitions }\n\t\tinstance.inference = cloneInference(this.inference)\n\t\tinstance.extender = { ...this.extender }\n\t\tinstance.getServer = () => this.getServer()\n\n\t\tconst sandbox = run(instance)\n\t\tthis.singleton = mergeDeep(this.singleton, instance.singleton) as any\n\t\tthis.definitions = mergeDeep(this.definitions, instance.definitions)\n\n\t\t// ? Inject getServer for websocket and trace (important, do not remove)\n\t\tsandbox.getServer = () => this.server\n\n\t\tif (sandbox.event.request?.length)\n\t\t\tthis.event.request = [\n\t\t\t\t...(this.event.request || []),\n\t\t\t\t...(sandbox.event.request || [])\n\t\t\t]\n\n\t\tif (sandbox.event.mapResponse?.length)\n\t\t\tthis.event.mapResponse = [\n\t\t\t\t...(this.event.mapResponse || []),\n\t\t\t\t...(sandbox.event.mapResponse || [])\n\t\t\t]\n\n\t\tthis.model(sandbox.definitions.type)\n\n\t\tObject.values(instance.router.history).forEach(\n\t\t\t({ method, path, handler, hooks: localHook }) => {\n\t\t\t\tconst {\n\t\t\t\t\tbody,\n\t\t\t\t\theaders,\n\t\t\t\t\tquery,\n\t\t\t\t\tparams,\n\t\t\t\t\tcookie,\n\t\t\t\t\tresponse,\n\t\t\t\t\t...guardHook\n\t\t\t\t} = hook\n\n\t\t\t\tconst hasStandaloneSchema =\n\t\t\t\t\tbody || headers || query || params || cookie || response\n\n\t\t\t\tthis.add(\n\t\t\t\t\tmethod,\n\t\t\t\t\tpath,\n\t\t\t\t\thandler,\n\t\t\t\t\tmergeHook(guardHook as AnyLocalHook, {\n\t\t\t\t\t\t...((localHook || {}) as AnyLocalHook),\n\t\t\t\t\t\terror: !localHook.error\n\t\t\t\t\t\t\t? sandbox.event.error\n\t\t\t\t\t\t\t: Array.isArray(localHook.error)\n\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t...(localHook.error ?? []),\n\t\t\t\t\t\t\t\t\t\t...(sandbox.event.error ?? [])\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t\tlocalHook.error,\n\t\t\t\t\t\t\t\t\t\t...(sandbox.event.error ?? [])\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\tstandaloneValidator: !hasStandaloneSchema\n\t\t\t\t\t\t\t? localHook.standaloneValidator\n\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t...(localHook.standaloneValidator ?? []),\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tbody,\n\t\t\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\t\t\tquery,\n\t\t\t\t\t\t\t\t\t\tparams,\n\t\t\t\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\t\t\t\tresponse\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\t// Handle dynamic imports (Promises) used inside guard callback\n\t\tif (instance.promisedModules.size > 0) {\n\t\t\tlet processedUntil = instance.router.history.length\n\n\t\t\tfor (const promise of instance.promisedModules.promises) {\n\t\t\t\tthis.promisedModules.add(\n\t\t\t\t\tpromise.then(() => {\n\t\t\t\t\t\tconst {\n\t\t\t\t\t\t\tbody,\n\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\tquery,\n\t\t\t\t\t\t\tparams,\n\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\tresponse,\n\t\t\t\t\t\t\t...guardHook\n\t\t\t\t\t\t} = hook\n\n\t\t\t\t\t\tconst hasStandaloneSchema =\n\t\t\t\t\t\t\tbody || headers || query || params || cookie || response\n\n\t\t\t\t\t\tconst startIndex = processedUntil\n\t\t\t\t\t\tprocessedUntil = instance.router.history.length\n\n\t\t\t\t\t\tfor (\n\t\t\t\t\t\t\tlet i = startIndex;\n\t\t\t\t\t\t\ti < instance.router.history.length;\n\t\t\t\t\t\t\ti++\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst {\n\t\t\t\t\t\t\t\tmethod,\n\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\thandler,\n\t\t\t\t\t\t\t\thooks: localHook\n\t\t\t\t\t\t\t} = instance.router.history[i]\n\n\t\t\t\t\t\t\tthis.add(\n\t\t\t\t\t\t\t\tmethod,\n\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\thandler,\n\t\t\t\t\t\t\t\tmergeHook(guardHook as AnyLocalHook, {\n\t\t\t\t\t\t\t\t\t...((localHook || {}) as AnyLocalHook),\n\t\t\t\t\t\t\t\t\terror: !localHook.error\n\t\t\t\t\t\t\t\t\t\t? sandbox.event.error\n\t\t\t\t\t\t\t\t\t\t: Array.isArray(localHook.error)\n\t\t\t\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t\t\t\t...(localHook.error ?? []),\n\t\t\t\t\t\t\t\t\t\t\t\t\t...(sandbox.event.error ?? [])\n\t\t\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t\t\t\t\tlocalHook.error,\n\t\t\t\t\t\t\t\t\t\t\t\t\t...(sandbox.event.error ?? [])\n\t\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tstandaloneValidator: !hasStandaloneSchema\n\t\t\t\t\t\t\t\t\t\t? localHook.standaloneValidator\n\t\t\t\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t\t\t\t...(localHook.standaloneValidator ??\n\t\t\t\t\t\t\t\t\t\t\t\t\t[]),\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tbody,\n\t\t\t\t\t\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\t\t\t\t\t\tquery,\n\t\t\t\t\t\t\t\t\t\t\t\t\tparams,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\t\t\t\t\t\t\tresponse\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * Entire Instance\n\t **/\n\tuse<const NewElysia extends AnyElysia>(\n\t\tinstance: MaybePromise<NewElysia>\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator'] &\n\t\t\t\tNewElysia['~Singleton']['decorator']\n\t\t\tstore: Prettify<\n\t\t\t\tSingleton['store'] & NewElysia['~Singleton']['store']\n\t\t\t>\n\t\t\tderive: Singleton['derive'] & NewElysia['~Singleton']['derive']\n\t\t\tresolve: Singleton['resolve'] & NewElysia['~Singleton']['resolve']\n\t\t},\n\t\tDefinitions & NewElysia['~Definitions'],\n\t\tMetadata & NewElysia['~Metadata'],\n\t\tBasePath extends ``\n\t\t\t? Routes & NewElysia['~Routes']\n\t\t\t: Routes & CreateEden<BasePath, NewElysia['~Routes']>,\n\t\tEphemeral,\n\t\tVolatile & NewElysia['~Ephemeral']\n\t>\n\n\t/**\n\t * Entire multiple Instance\n\t **/\n\tuse<const Instances extends AnyElysia[]>(\n\t\tinstance: MaybePromise<Instances>\n\t): MergeElysiaInstances<Instances, BasePath>\n\n\t/**\n\t * Import fn\n\t */\n\tuse<const NewElysia extends AnyElysia>(\n\t\tplugin: Promise<{\n\t\t\tdefault: (elysia: AnyElysia) => MaybePromise<NewElysia>\n\t\t}>\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator'] &\n\t\t\t\tNewElysia['~Singleton']['decorator']\n\t\t\tstore: Prettify<\n\t\t\t\tSingleton['store'] & NewElysia['~Singleton']['store']\n\t\t\t>\n\t\t\tderive: Singleton['derive'] & NewElysia['~Singleton']['derive']\n\t\t\tresolve: Singleton['resolve'] & NewElysia['~Singleton']['resolve']\n\t\t},\n\t\tDefinitions & NewElysia['~Definitions'],\n\t\tMetadata & NewElysia['~Metadata'],\n\t\tBasePath extends ``\n\t\t\t? Routes & NewElysia['~Routes']\n\t\t\t: Routes & CreateEden<BasePath, NewElysia['~Routes']>,\n\t\tEphemeral & NewElysia['~Ephemeral'],\n\t\tVolatile & NewElysia['~Volatile']\n\t>\n\n\t/**\n\t * Import entire instance\n\t */\n\tuse<const LazyLoadElysia extends AnyElysia>(\n\t\tplugin: Promise<{\n\t\t\tdefault: LazyLoadElysia\n\t\t}>\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator'] &\n\t\t\t\tPartial<LazyLoadElysia['~Singleton']['decorator']>\n\t\t\tstore: Prettify<\n\t\t\t\tSingleton['store'] &\n\t\t\t\t\tPartial<LazyLoadElysia['~Singleton']['store']>\n\t\t\t>\n\t\t\tderive: Singleton['derive'] &\n\t\t\t\tPartial<LazyLoadElysia['~Singleton']['derive']>\n\t\t\tresolve: Singleton['resolve'] &\n\t\t\t\tPartial<LazyLoadElysia['~Singleton']['resolve']>\n\t\t},\n\t\tDefinitions & LazyLoadElysia['~Definitions'],\n\t\tMetadata & LazyLoadElysia['~Metadata'],\n\t\tBasePath extends ``\n\t\t\t? Routes & LazyLoadElysia['~Routes']\n\t\t\t: Routes & CreateEden<BasePath, LazyLoadElysia['~Routes']>,\n\t\tEphemeral,\n\t\t{\n\t\t\tschema: Volatile['schema'] &\n\t\t\t\tPartial<LazyLoadElysia['~Ephemeral']['schema']>\n\t\t\tstandaloneSchema: Volatile['standaloneSchema'] &\n\t\t\t\tPartial<LazyLoadElysia['~Ephemeral']['standaloneSchema']>\n\t\t\tresolve: Volatile['resolve'] &\n\t\t\t\tPartial<LazyLoadElysia['~Ephemeral']['resolve']>\n\t\t\tderive: Volatile['derive'] &\n\t\t\t\tPartial<LazyLoadElysia['~Ephemeral']['derive']>\n\t\t\tresponse: Volatile['response'] &\n\t\t\t\tLazyLoadElysia['~Ephemeral']['response']\n\t\t}\n\t>\n\n\t/**\n\t * Inline fn\n\t */\n\tuse<\n\t\tconst NewElysia extends AnyElysia,\n\t\tconst Param extends AnyElysia = this\n\t>(\n\t\tplugin: (app: Param) => NewElysia\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator'] &\n\t\t\t\tNewElysia['~Singleton']['decorator']\n\t\t\tstore: Prettify<\n\t\t\t\tSingleton['store'] & NewElysia['~Singleton']['store']\n\t\t\t>\n\t\t\tderive: Singleton['derive'] & NewElysia['~Singleton']['derive']\n\t\t\tresolve: Singleton['resolve'] & NewElysia['~Singleton']['resolve']\n\t\t},\n\t\tDefinitions & NewElysia['~Definitions'],\n\t\tMetadata & NewElysia['~Metadata'],\n\t\tBasePath extends ``\n\t\t\t? Routes & NewElysia['~Routes']\n\t\t\t: Routes & CreateEden<BasePath, NewElysia['~Routes']>,\n\t\tEphemeral & NewElysia['~Ephemeral'],\n\t\tVolatile & NewElysia['~Volatile']\n\t>\n\n\t/**\n\t * Inline async fn\n\t */\n\tuse<\n\t\tconst NewElysia extends AnyElysia,\n\t\tconst Param extends AnyElysia = this\n\t>(\n\t\tplugin:\n\t\t\t| ((app: Param) => Promise<NewElysia>)\n\t\t\t| Promise<(app: Param) => NewElysia>\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator'] &\n\t\t\t\tPartial<NewElysia['~Singleton']['decorator']>\n\t\t\tstore: Prettify<\n\t\t\t\tSingleton['store'] & Partial<NewElysia['~Singleton']['store']>\n\t\t\t>\n\t\t\tderive: Singleton['derive'] &\n\t\t\t\tPartial<NewElysia['~Singleton']['derive']>\n\t\t\tresolve: Singleton['resolve'] &\n\t\t\t\tPartial<NewElysia['~Singleton']['resolve']>\n\t\t},\n\t\tDefinitions & NewElysia['~Definitions'],\n\t\tMetadata & NewElysia['~Metadata'],\n\t\tBasePath extends ``\n\t\t\t? Routes & NewElysia['~Routes']\n\t\t\t: Routes & CreateEden<BasePath, NewElysia['~Routes']>,\n\t\t{\n\t\t\tschema: Ephemeral['schema'] &\n\t\t\t\tPartial<NewElysia['~Ephemeral']['schema']>\n\t\t\tstandaloneSchema: Ephemeral['standaloneSchema'] &\n\t\t\t\tPartial<NewElysia['~Ephemeral']['standaloneSchema']>\n\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\tPartial<NewElysia['~Ephemeral']['resolve']>\n\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\tPartial<NewElysia['~Ephemeral']['derive']>\n\t\t\tresponse: Ephemeral['response'] &\n\t\t\t\tNewElysia['~Ephemeral']['response']\n\t\t},\n\t\t{\n\t\t\tschema: Volatile['schema'] &\n\t\t\t\tPartial<NewElysia['~Volatile']['schema']>\n\t\t\tstandaloneSchema: Volatile['standaloneSchema'] &\n\t\t\t\tPartial<NewElysia['~Volatile']['standaloneSchema']>\n\t\t\tresolve: Volatile['resolve'] &\n\t\t\t\tPartial<NewElysia['~Volatile']['resolve']>\n\t\t\tderive: Volatile['derive'] &\n\t\t\t\tPartial<NewElysia['~Volatile']['derive']>\n\t\t\tresponse: Volatile['response'] & NewElysia['~Volatile']['response']\n\t\t}\n\t>\n\n\t/**\n\t * conditional undefined ignore type\n\t */\n\tuse(\n\t\tinstance:\n\t\t\t| MaybeArray<MaybePromise<AnyElysia>>\n\t\t\t| MaybePromise<\n\t\t\t\t\tAnyElysia | ((app: AnyElysia) => MaybePromise<AnyElysia>)\n\t\t\t  >\n\t\t\t| Promise<{\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t| AnyElysia\n\t\t\t\t\t\t| ((app: AnyElysia) => MaybePromise<AnyElysia>)\n\t\t\t  }>\n\t\t\t| undefined\n\t\t\t| false\n\t): this\n\n\t/**\n\t * ### use\n\t * Merge separate logic of Elysia with current\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * const plugin = (app: Elysia) => app\n\t *     .get('/plugin', () => 'hi')\n\t *\n\t * new Elysia()\n\t *     .use(plugin)\n\t * ```\n\t */\n\tuse(\n\t\tplugin:\n\t\t\t| MaybeArray<MaybePromise<AnyElysia>>\n\t\t\t| MaybePromise<\n\t\t\t\t\tAnyElysia | ((app: AnyElysia) => MaybePromise<AnyElysia>)\n\t\t\t  >\n\t\t\t| Promise<{\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t| AnyElysia\n\t\t\t\t\t\t| ((app: AnyElysia) => MaybePromise<AnyElysia>)\n\t\t\t  }>\n\t\t\t| undefined\n\t\t\t| false\n\t): AnyElysia {\n\t\tif (!plugin) return this\n\n\t\tif (Array.isArray(plugin)) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-this-alias\n\t\t\tlet app = this\n\t\t\tfor (const p of plugin) app = app.use(p) as any\n\t\t\treturn app\n\t\t}\n\n\t\tif (plugin instanceof Promise) {\n\t\t\tthis.promisedModules.add(\n\t\t\t\tplugin\n\t\t\t\t\t.then((plugin) => {\n\t\t\t\t\t\tif (typeof plugin === 'function') return plugin(this)\n\n\t\t\t\t\t\tif (plugin instanceof Elysia)\n\t\t\t\t\t\t\treturn this._use(plugin).compile()\n\n\t\t\t\t\t\tif (plugin.constructor?.name === 'Elysia')\n\t\t\t\t\t\t\treturn this._use(\n\t\t\t\t\t\t\t\tplugin as unknown as Elysia\n\t\t\t\t\t\t\t).compile()\n\n\t\t\t\t\t\tif (typeof plugin.default === 'function')\n\t\t\t\t\t\t\treturn plugin.default(this)\n\n\t\t\t\t\t\tif (plugin.default instanceof Elysia)\n\t\t\t\t\t\t\treturn this._use(plugin.default)\n\n\t\t\t\t\t\tif (plugin.constructor?.name === 'Elysia')\n\t\t\t\t\t\t\treturn this._use(plugin.default)\n\n\t\t\t\t\t\tif (plugin.constructor?.name === '_Elysia')\n\t\t\t\t\t\t\treturn this._use(plugin.default)\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn this._use(plugin.default)\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\t'Invalid plugin type. Expected Elysia instance, function, or module with \"default\" as Elysia instance or function that returns Elysia instance.'\n\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\tthrow error\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.then((v) => {\n\t\t\t\t\t\tif (v && typeof v.compile === 'function') v.compile()\n\n\t\t\t\t\t\treturn v\n\t\t\t\t\t})\n\t\t\t)\n\n\t\t\treturn this\n\t\t}\n\n\t\treturn this._use(plugin)\n\t}\n\n\tprivate propagatePromiseModules(plugin: Elysia) {\n\t\tif (plugin.promisedModules.size <= 0) return this\n\n\t\tfor (const promise of plugin.promisedModules.promises)\n\t\t\tthis.promisedModules.add(\n\t\t\t\tpromise.then((v) => {\n\t\t\t\t\tif (!v) return\n\n\t\t\t\t\tconst t = this._use(v)\n\t\t\t\t\tif (t instanceof Promise)\n\t\t\t\t\t\treturn t.then((v2) => {\n\t\t\t\t\t\t\tif (v2) v2.compile()\n\t\t\t\t\t\t\telse v.compile()\n\t\t\t\t\t\t})\n\n\t\t\t\t\treturn v.compile()\n\t\t\t\t})\n\t\t\t)\n\n\t\treturn this\n\t}\n\n\tprivate _use(\n\t\tplugin: AnyElysia | ((app: AnyElysia) => MaybePromise<AnyElysia>)\n\t) {\n\t\tif (typeof plugin === 'function') {\n\t\t\tconst instance = plugin(this as unknown as any) as unknown as any\n\n\t\t\tif (instance instanceof Promise) {\n\t\t\t\tthis.promisedModules.add(\n\t\t\t\t\tinstance\n\t\t\t\t\t\t.then((plugin) => {\n\t\t\t\t\t\t\tif (plugin instanceof Elysia) {\n\t\t\t\t\t\t\t\tplugin.getServer = () => this.getServer()\n\t\t\t\t\t\t\t\tplugin.getGlobalRoutes = () =>\n\t\t\t\t\t\t\t\t\tthis.getGlobalRoutes()\n\t\t\t\t\t\t\t\tplugin.getGlobalDefinitions = () =>\n\t\t\t\t\t\t\t\t\tthis.getGlobalDefinitions()\n\n\t\t\t\t\t\t\t\t/**\n\t\t\t\t\t\t\t\t * Model and error is required for Swagger generation\n\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t\tplugin.model(this.definitions.type as any)\n\t\t\t\t\t\t\t\tplugin.error(this.definitions.error as any)\n\n\t\t\t\t\t\t\t\t// Recompile async plugin routes\n\t\t\t\t\t\t\t\tfor (const {\n\t\t\t\t\t\t\t\t\tmethod,\n\t\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\t\thandler,\n\t\t\t\t\t\t\t\t\thooks\n\t\t\t\t\t\t\t\t} of Object.values(plugin.router.history))\n\t\t\t\t\t\t\t\t\tthis.add(\n\t\t\t\t\t\t\t\t\t\tmethod,\n\t\t\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\t\t\thandler,\n\t\t\t\t\t\t\t\t\t\thooks,\n\t\t\t\t\t\t\t\t\t\tundefined\n\t\t\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\tif (plugin === this) return\n\n\t\t\t\t\t\t\t\tthis.propagatePromiseModules(plugin)\n\n\t\t\t\t\t\t\t\treturn plugin\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (typeof plugin === 'function')\n\t\t\t\t\t\t\t\treturn plugin(\n\t\t\t\t\t\t\t\t\tthis as unknown as any\n\t\t\t\t\t\t\t\t) as unknown as Elysia\n\n\t\t\t\t\t\t\tif (typeof plugin.default === 'function')\n\t\t\t\t\t\t\t\treturn plugin.default(\n\t\t\t\t\t\t\t\t\tthis as unknown as any\n\t\t\t\t\t\t\t\t) as unknown as Elysia\n\n\t\t\t\t\t\t\treturn this._use(plugin)\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.then((v) => {\n\t\t\t\t\t\t\tif (v && typeof v.compile === 'function')\n\t\t\t\t\t\t\t\tv.compile()\n\n\t\t\t\t\t\t\treturn v\n\t\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\treturn this as unknown as any\n\t\t\t}\n\n\t\t\treturn instance\n\t\t}\n\n\t\tthis.propagatePromiseModules(plugin)\n\n\t\tconst name = plugin.config.name\n\t\tconst seed = plugin.config.seed\n\n\t\tplugin.getParent = () => this as any\n\t\tplugin.getServer = () => this.getServer()\n\t\tplugin.getGlobalRoutes = () => this.getGlobalRoutes()\n\t\tplugin.getGlobalDefinitions = () => this.getGlobalDefinitions()\n\n\t\tif (plugin.standaloneValidator?.scoped) {\n\t\t\tif (this.standaloneValidator.local)\n\t\t\t\tthis.standaloneValidator.local =\n\t\t\t\t\tthis.standaloneValidator.local.concat(\n\t\t\t\t\t\tplugin.standaloneValidator.scoped\n\t\t\t\t\t)\n\t\t\telse\n\t\t\t\tthis.standaloneValidator.local =\n\t\t\t\t\tplugin.standaloneValidator.scoped\n\t\t}\n\n\t\tif (plugin.standaloneValidator?.global) {\n\t\t\tif (this.standaloneValidator.global)\n\t\t\t\tthis.standaloneValidator.global =\n\t\t\t\t\tthis.standaloneValidator.global.concat(\n\t\t\t\t\t\tplugin.standaloneValidator.global\n\t\t\t\t\t)\n\t\t\telse\n\t\t\t\tthis.standaloneValidator.global =\n\t\t\t\t\tplugin.standaloneValidator.global\n\t\t}\n\n\t\t/**\n\t\t * Model and error is required for Swagger generation\n\t\t */\n\t\t// plugin.model(this.definitions.type as any)\n\t\t// plugin.error(this.definitions.error as any)\n\n\t\tif (isNotEmpty(plugin['~parser']))\n\t\t\tthis['~parser'] = {\n\t\t\t\t...plugin['~parser'],\n\t\t\t\t...this['~parser']\n\t\t\t}\n\n\t\tif (plugin.setHeaders) this.headers(plugin.setHeaders)\n\n\t\tif (name) {\n\t\t\tif (!(name in this.dependencies)) this.dependencies[name] = []\n\n\t\t\tconst current =\n\t\t\t\tseed !== undefined ? checksum(name + JSON.stringify(seed)) : 0\n\n\t\t\tif (\n\t\t\t\t!this.dependencies[name].some(\n\t\t\t\t\t({ checksum }) => current === checksum\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tthis.extender.macro = {\n\t\t\t\t\t...this.extender.macro,\n\t\t\t\t\t...plugin.extender.macro\n\t\t\t\t}\n\n\t\t\t\tthis.extender.higherOrderFunctions =\n\t\t\t\t\tthis.extender.higherOrderFunctions.concat(\n\t\t\t\t\t\tplugin.extender.higherOrderFunctions\n\t\t\t\t\t)\n\t\t\t}\n\t\t} else {\n\t\t\tif (isNotEmpty(plugin.extender.macro))\n\t\t\t\tthis.extender.macro = {\n\t\t\t\t\t...this.extender.macro,\n\t\t\t\t\t...plugin.extender.macro\n\t\t\t\t}\n\n\t\t\tif (plugin.extender.higherOrderFunctions.length)\n\t\t\t\tthis.extender.higherOrderFunctions =\n\t\t\t\t\tthis.extender.higherOrderFunctions.concat(\n\t\t\t\t\t\tplugin.extender.higherOrderFunctions\n\t\t\t\t\t)\n\t\t}\n\n\t\tif (plugin.extender.higherOrderFunctions.length) {\n\t\t\tdeduplicateChecksum(this.extender.higherOrderFunctions)\n\n\t\t\t// ! Deduplicate current instance\n\t\t\tconst hofHashes: number[] = []\n\t\t\tfor (\n\t\t\t\tlet i = 0;\n\t\t\t\ti < this.extender.higherOrderFunctions.length;\n\t\t\t\ti++\n\t\t\t) {\n\t\t\t\tconst hof = this.extender.higherOrderFunctions[i]\n\n\t\t\t\tif (hof.checksum) {\n\t\t\t\t\tif (hofHashes.includes(hof.checksum)) {\n\t\t\t\t\t\tthis.extender.higherOrderFunctions.splice(i, 1)\n\t\t\t\t\t\ti--\n\t\t\t\t\t}\n\n\t\t\t\t\thofHashes.push(hof.checksum)\n\t\t\t\t}\n\t\t\t}\n\t\t\thofHashes.length = 0\n\t\t}\n\n\t\tthis.inference = mergeInference(this.inference, plugin.inference)\n\n\t\tif (isNotEmpty(plugin.singleton.decorator))\n\t\t\tthis.decorate(plugin.singleton.decorator)\n\n\t\tif (isNotEmpty(plugin.singleton.store))\n\t\t\tthis.state(plugin.singleton.store)\n\n\t\tif (isNotEmpty(plugin.definitions.type))\n\t\t\tthis.model(plugin.definitions.type)\n\n\t\tif (isNotEmpty(plugin.definitions.error))\n\t\t\tthis.error(plugin.definitions.error as any)\n\n\t\tif (isNotEmpty(plugin.extender.macro))\n\t\t\tthis.extender.macro = {\n\t\t\t\t...this.extender.macro,\n\t\t\t\t...plugin.extender.macro\n\t\t\t}\n\n\t\tfor (const { method, path, handler, hooks } of Object.values(\n\t\t\tplugin.router.history\n\t\t))\n\t\t\tthis.add(method, path, handler, hooks)\n\n\t\tif (name) {\n\t\t\tif (!(name in this.dependencies)) this.dependencies[name] = []\n\n\t\t\tconst current =\n\t\t\t\tseed !== undefined ? checksum(name + JSON.stringify(seed)) : 0\n\n\t\t\tif (\n\t\t\t\tthis.dependencies[name].some(\n\t\t\t\t\t({ checksum }) => current === checksum\n\t\t\t\t)\n\t\t\t)\n\t\t\t\treturn this\n\n\t\t\tthis.dependencies[name].push(\n\t\t\t\tthis.config?.analytic\n\t\t\t\t\t? ({\n\t\t\t\t\t\t\tname: plugin.config.name,\n\t\t\t\t\t\t\tseed: plugin.config.seed,\n\t\t\t\t\t\t\tchecksum: current,\n\t\t\t\t\t\t\tdependencies: plugin.dependencies,\n\t\t\t\t\t\t\tstack: plugin.telemetry?.stack,\n\t\t\t\t\t\t\troutes: plugin.router.history,\n\t\t\t\t\t\t\tdecorators: plugin.singleton,\n\t\t\t\t\t\t\tstore: plugin.singleton.store,\n\t\t\t\t\t\t\terror: plugin.definitions.error,\n\t\t\t\t\t\t\tderive: plugin.event.transform\n\t\t\t\t\t\t\t\t?.filter((x) => x?.subType === 'derive')\n\t\t\t\t\t\t\t\t.map((x) => ({\n\t\t\t\t\t\t\t\t\tfn: x.toString(),\n\t\t\t\t\t\t\t\t\tstack: new Error().stack ?? ''\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\tresolve: plugin.event.transform\n\t\t\t\t\t\t\t\t?.filter((x) => x?.subType === 'resolve')\n\t\t\t\t\t\t\t\t.map((x) => ({\n\t\t\t\t\t\t\t\t\tfn: x.toString(),\n\t\t\t\t\t\t\t\t\tstack: new Error().stack ?? ''\n\t\t\t\t\t\t\t\t}))\n\t\t\t\t\t\t} as any)\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tname: plugin.config.name,\n\t\t\t\t\t\t\tseed: plugin.config.seed,\n\t\t\t\t\t\t\tchecksum: current,\n\t\t\t\t\t\t\tdependencies: plugin.dependencies\n\t\t\t\t\t\t}\n\t\t\t)\n\n\t\t\tif (isNotEmpty(plugin.event))\n\t\t\t\tthis.event = mergeLifeCycle(\n\t\t\t\t\tthis.event,\n\t\t\t\t\tfilterGlobalHook(plugin.event),\n\t\t\t\t\tcurrent\n\t\t\t\t)\n\t\t} else {\n\t\t\tif (isNotEmpty(plugin.event))\n\t\t\t\tthis.event = mergeLifeCycle(\n\t\t\t\t\tthis.event,\n\t\t\t\t\tfilterGlobalHook(plugin.event)\n\t\t\t\t)\n\t\t}\n\n\t\tif (plugin.validator.global)\n\t\t\t// @ts-ignore\n\t\t\tthis.validator.global = mergeHook(this.validator.global, {\n\t\t\t\t...plugin.validator.global\n\t\t\t}) as any\n\n\t\tif (plugin.validator.scoped)\n\t\t\t// @ts-ignore\n\t\t\tthis.validator.local = mergeHook(this.validator.local, {\n\t\t\t\t...plugin.validator.scoped\n\t\t\t})\n\n\t\treturn this\n\t}\n\n\tmacro<\n\t\tconst Name extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends MergeSchema<\n\t\t\tUnwrapRoute<Input, Definitions['typebox'], BasePath>,\n\t\t\tMergeSchema<\n\t\t\t\tVolatile['schema'],\n\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t> &\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema']\n\t\t>,\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst Property extends MaybeValueOrVoidFunction<\n\t\t\tMacroProperty<\n\t\t\t\tMetadata['macro'] &\n\t\t\t\t\tInputSchema<keyof Definitions['typebox'] & string> & {\n\t\t\t\t\t\t[name in Name]?: boolean\n\t\t\t\t\t},\n\t\t\t\tSchema & MacroContext,\n\t\t\t\tSingleton & {\n\t\t\t\t\tderive: Partial<Ephemeral['derive'] & Volatile['derive']>\n\t\t\t\t\tresolve: Partial<\n\t\t\t\t\t\tEphemeral['resolve'] & Volatile['resolve']\n\t\t\t\t\t> &\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tMacroContext['resolve']\n\t\t\t\t},\n\t\t\t\tDefinitions['error']\n\t\t\t>\n\t\t>\n\t>(\n\t\tname: Name,\n\t\tmacro: (Input extends any ? Input : Prettify<Input>) & Property\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\t{\n\t\t\tschema: Metadata['schema']\n\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\tmacro: Metadata['macro'] & {\n\t\t\t\t[name in Name]?: Property extends (a: infer Params) => any\n\t\t\t\t\t? Params\n\t\t\t\t\t: boolean\n\t\t\t}\n\t\t\tmacroFn: Metadata['macroFn'] & {\n\t\t\t\t[name in Name]: Property\n\t\t\t}\n\t\t\tparser: Metadata['parser']\n\t\t\tresponse: Metadata['response']\n\t\t},\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\tmacro<\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst NewMacro extends Macro<\n\t\t\tMetadata['macro'] &\n\t\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\t\tInput,\n\t\t\tIntersectIfObjectSchema<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tUnwrapRoute<Input, Definitions['typebox'], BasePath>,\n\t\t\t\t\tMergeSchema<\n\t\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t\t>\n\t\t\t\t>,\n\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema']\n\t\t\t>,\n\t\t\tSingleton & {\n\t\t\t\tderive: Partial<Ephemeral['derive'] & Volatile['derive']>\n\t\t\t\tresolve: Partial<Ephemeral['resolve'] & Volatile['resolve']>\n\t\t\t},\n\t\t\tDefinitions['error']\n\t\t>\n\t>(\n\t\tmacro: NewMacro\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\t{\n\t\t\tschema: Metadata['schema']\n\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\tmacro: Metadata['macro'] & Partial<MacroToProperty<NewMacro>>\n\t\t\tmacroFn: Metadata['macroFn'] & NewMacro\n\t\t\tparser: Metadata['parser']\n\t\t\tresponse: Metadata['response']\n\t\t},\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\tmacro<\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst NewMacro extends MaybeFunction<\n\t\t\tMacro<\n\t\t\t\tInput,\n\t\t\t\t// @ts-ignore trust me bro\n\t\t\t\tIntersectIfObjectSchema<\n\t\t\t\t\tMergeSchema<\n\t\t\t\t\t\tUnwrapRoute<Input, Definitions['typebox'], BasePath>,\n\t\t\t\t\t\tMergeSchema<\n\t\t\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t\t\t>\n\t\t\t\t\t>,\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\t\tVolatile['standaloneSchema']\n\t\t\t\t>,\n\t\t\t\tSingleton & {\n\t\t\t\t\tderive: Partial<Ephemeral['derive'] & Volatile['derive']>\n\t\t\t\t\tresolve: Partial<Ephemeral['resolve'] & Volatile['resolve']>\n\t\t\t\t},\n\t\t\t\tDefinitions['error']\n\t\t\t>\n\t\t>\n\t>(\n\t\tmacro: NewMacro\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\t{\n\t\t\tschema: Metadata['schema']\n\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\tmacro: Metadata['macro'] & Partial<MacroToProperty<NewMacro>>\n\t\t\tmacroFn: Metadata['macroFn'] & NewMacro\n\t\t\tparser: Metadata['parser']\n\t\t\tresponse: Metadata['response']\n\t\t},\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\tmacro(macroOrName: string | Macro, macro?: Macro) {\n\t\tif (typeof macroOrName === 'string' && !macro)\n\t\t\tthrow new Error('Macro function is required')\n\n\t\tif (typeof macroOrName === 'string')\n\t\t\tthis.extender.macro[macroOrName] = macro!\n\t\telse\n\t\t\tthis.extender.macro = {\n\t\t\t\t...this.extender.macro,\n\t\t\t\t...macroOrName\n\t\t\t}\n\n\t\treturn this as any\n\t}\n\n\tprivate applyMacro(\n\t\tlocalHook: AnyLocalHook,\n\t\tappliable: AnyLocalHook = localHook,\n\t\t{\n\t\t\titeration = 0,\n\t\t\tapplied = {}\n\t\t}: { iteration?: number; applied?: { [key: number]: true } } = {}\n\t) {\n\t\tif (iteration >= 16) return\n\t\tconst macro = this.extender.macro\n\n\t\tfor (let [key, value] of Object.entries(appliable)) {\n\t\t\tif (key in macro === false) continue\n\n\t\t\tconst macroHook =\n\t\t\t\ttypeof macro[key] === 'function'\n\t\t\t\t\t? macro[key](value)\n\t\t\t\t\t: macro[key]\n\n\t\t\tif (\n\t\t\t\t!macroHook ||\n\t\t\t\t(typeof macro[key] === 'object' && value === false)\n\t\t\t)\n\t\t\t\treturn\n\n\t\t\tconst seed = checksum(key + JSON.stringify(macroHook.seed ?? value))\n\t\t\tif (seed in applied) continue\n\n\t\t\tapplied[seed] = true\n\n\t\t\tfor (let [k, value] of Object.entries(macroHook)) {\n\t\t\t\tif (k === 'seed') continue\n\n\t\t\t\tif (k in emptySchema) {\n\t\t\t\t\tinsertStandaloneValidator(\n\t\t\t\t\t\tlocalHook,\n\t\t\t\t\t\tk as keyof RouteSchema,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t)\n\t\t\t\t\tdelete localHook[key]\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif (k === 'introspect') {\n\t\t\t\t\tvalue?.(localHook)\n\n\t\t\t\t\tdelete localHook[key]\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif (k === 'detail') {\n\t\t\t\t\tif (!localHook.detail) localHook.detail = {}\n\t\t\t\t\tlocalHook.detail = mergeDeep(localHook.detail, value, {\n\t\t\t\t\t\tmergeArray: true\n\t\t\t\t\t})\n\n\t\t\t\t\tdelete localHook[key]\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif (k in macro) {\n\t\t\t\t\tthis.applyMacro(\n\t\t\t\t\t\tlocalHook,\n\t\t\t\t\t\t{ [k]: value },\n\t\t\t\t\t\t{ applied, iteration: iteration + 1 }\n\t\t\t\t\t)\n\n\t\t\t\t\tdelete localHook[key]\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t(k === 'derive' || k === 'resolve') &&\n\t\t\t\t\ttypeof value === 'function'\n\t\t\t\t)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tvalue = {\n\t\t\t\t\t\tfn: value,\n\t\t\t\t\t\tsubType: k\n\t\t\t\t\t} as HookContainer\n\n\t\t\t\tswitch (typeof localHook[k]) {\n\t\t\t\t\tcase 'function':\n\t\t\t\t\t\tlocalHook[k] = [localHook[k], value]\n\t\t\t\t\t\tbreak\n\n\t\t\t\t\tcase 'object':\n\t\t\t\t\t\tif (Array.isArray(localHook[k]))\n\t\t\t\t\t\t\t(localHook[k] as any[]).push(value)\n\t\t\t\t\t\telse localHook[k] = [localHook[k], value]\n\t\t\t\t\t\tbreak\n\n\t\t\t\t\tcase 'undefined':\n\t\t\t\t\t\tlocalHook[k] = value\n\t\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tdelete localHook[key]\n\t\t\t}\n\t\t}\n\t}\n\n\tmount(\n\t\thandle: ((request: Request) => MaybePromise<Response>) | AnyElysia,\n\t\tdetail?: { detail?: DocumentDecoration }\n\t): this\n\tmount(\n\t\tpath: string,\n\t\thandle: ((request: Request) => MaybePromise<Response>) | AnyElysia,\n\t\tdetail?: { detail?: DocumentDecoration }\n\t): this\n\n\tmount(\n\t\tpath:\n\t\t\t| string\n\t\t\t| ((request: Request) => MaybePromise<Response>)\n\t\t\t| AnyElysia,\n\t\thandleOrConfig?:\n\t\t\t| ((request: Request) => MaybePromise<Response>)\n\t\t\t| AnyElysia\n\t\t\t| { detail?: DocumentDecoration },\n\t\tconfig?: { detail?: DocumentDecoration }\n\t) {\n\t\tif (\n\t\t\tpath instanceof Elysia ||\n\t\t\ttypeof path === 'function' ||\n\t\t\tpath.length === 0 ||\n\t\t\tpath === '/'\n\t\t) {\n\t\t\tconst run =\n\t\t\t\ttypeof path === 'function'\n\t\t\t\t\t? path\n\t\t\t\t\t: path instanceof Elysia\n\t\t\t\t\t\t? path.compile().fetch\n\t\t\t\t\t\t: handleOrConfig instanceof Elysia\n\t\t\t\t\t\t\t? handleOrConfig.compile().fetch\n\t\t\t\t\t\t\t: typeof handleOrConfig === 'function'\n\t\t\t\t\t\t\t\t? handleOrConfig\n\t\t\t\t\t\t\t\t: (() => {\n\t\t\t\t\t\t\t\t\t\tthrow new Error('Invalid handler')\n\t\t\t\t\t\t\t\t\t})()\n\n\t\t\tconst handler: Handler = ({ request, path }) =>\n\t\t\t\trun(new Request(replaceUrlPath(request.url, path), request))\n\n\t\t\tthis.route('ALL', '/*', handler as any, {\n\t\t\t\tparse: 'none',\n\t\t\t\t...config,\n\t\t\t\tdetail: {\n\t\t\t\t\t...config?.detail,\n\t\t\t\t\thide: true\n\t\t\t\t},\n\t\t\t\tconfig: {\n\t\t\t\t\tmount: run\n\t\t\t\t}\n\t\t\t})\n\n\t\t\treturn this\n\t\t}\n\n\t\tconst handle =\n\t\t\thandleOrConfig instanceof Elysia\n\t\t\t\t? handleOrConfig.compile().fetch\n\t\t\t\t: typeof handleOrConfig === 'function'\n\t\t\t\t\t? handleOrConfig\n\t\t\t\t\t: (() => {\n\t\t\t\t\t\t\tthrow new Error('Invalid handler')\n\t\t\t\t\t\t})()\n\n\t\tconst fullPath =\n\t\t\ttypeof path === 'string' && this.config.prefix\n\t\t\t\t? this.config.prefix + path\n\t\t\t\t: path\n\n\t\tconst length = fullPath.length - (path.endsWith('*') ? 1 : 0)\n\t\tconst handler: Handler = ({ request, path }) =>\n\t\t\thandle(\n\t\t\t\tnew Request(\n\t\t\t\t\treplaceUrlPath(request.url, path.slice(length) || '/'),\n\t\t\t\t\trequest\n\t\t\t\t)\n\t\t\t)\n\n\t\tthis.route('ALL', path, handler as any, {\n\t\t\tparse: 'none',\n\t\t\t...config,\n\t\t\tdetail: {\n\t\t\t\t...config?.detail,\n\t\t\t\thide: true\n\t\t\t},\n\t\t\tconfig: {\n\t\t\t\tmount: handle\n\t\t\t}\n\t\t})\n\n\t\tthis.route(\n\t\t\t'ALL',\n\t\t\tpath + (path.endsWith('/') ? '*' : '/*'),\n\t\t\thandler as any,\n\t\t\t{\n\t\t\t\tparse: 'none',\n\t\t\t\t...config,\n\t\t\t\tdetail: {\n\t\t\t\t\t...config?.detail,\n\t\t\t\t\thide: true\n\t\t\t\t},\n\t\t\t\tconfig: {\n\t\t\t\t\tmount: handle\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\treturn this\n\t}\n\n\t/**\n\t * ### get\n\t * Register handler for path with method [GET]\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { Elysia, t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .get('/', () => 'hi')\n\t *     .get('/with-hook', () => 'hi', {\n\t *         response: t.String()\n\t *     })\n\t * ```\n\t */\n\tget<\n\t\tconst Path extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends IntersectIfObjectSchema<\n\t\t\tMergeSchema<\n\t\t\t\tUnwrapRoute<\n\t\t\t\t\tInput,\n\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\tJoinPath<BasePath, Path>\n\t\t\t\t>,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t>,\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema']\n\t\t>,\n\t\tconst Decorator extends Singleton & {\n\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t},\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst Handle extends {} extends MacroContext\n\t\t\t? InlineHandlerNonMacro<NoInfer<Schema>, NoInfer<Decorator>>\n\t\t\t: InlineHandler<\n\t\t\t\t\tNoInfer<Schema>,\n\t\t\t\t\tNoInfer<Decorator>,\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tMacroContext\n\t\t\t\t>\n\t>(\n\t\tpath: Path,\n\t\t// handler: (a: { a: MacroContext }) => any,\n\t\thandler: Handle,\n\t\thook?: LocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tDecorator,\n\t\t\tDefinitions['error'],\n\t\t\tkeyof Metadata['parser']\n\t\t>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes &\n\t\t\tCreateEden<\n\t\t\t\tJoinPath<BasePath, Path>,\n\t\t\t\t{\n\t\t\t\t\tget: CreateEdenResponse<\n\t\t\t\t\t\tPath,\n\t\t\t\t\t\tSchema,\n\t\t\t\t\t\tMacroContext,\n\t\t\t\t\t\tComposeElysiaResponse<\n\t\t\t\t\t\t\tSchema &\n\t\t\t\t\t\t\t\tMacroContext &\n\t\t\t\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\t\t\t\tHandle,\n\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\tMacroContext['return'] & {}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t}\n\t\t\t>,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tthis.add('GET', path, handler as any, hook)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### post\n\t * Register handler for path with method [POST]\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { Elysia, t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .post('/', () => 'hi')\n\t *     .post('/with-hook', () => 'hi', {\n\t *         response: t.String()\n\t *     })\n\t * ```\n\t */\n\tpost<\n\t\tconst Path extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends IntersectIfObjectSchema<\n\t\t\tMergeSchema<\n\t\t\t\tUnwrapRoute<\n\t\t\t\t\tInput,\n\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\tJoinPath<BasePath, Path>\n\t\t\t\t>,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t>,\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema']\n\t\t>,\n\t\tconst Decorator extends Singleton & {\n\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t},\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst Handle extends {} extends MacroContext\n\t\t\t? InlineHandlerNonMacro<NoInfer<Schema>, NoInfer<Decorator>>\n\t\t\t: InlineHandler<\n\t\t\t\t\tNoInfer<Schema>,\n\t\t\t\t\tNoInfer<Decorator>,\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tMacroContext\n\t\t\t\t>\n\t>(\n\t\tpath: Path,\n\t\thandler: Handle,\n\t\thook?: LocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tDecorator,\n\t\t\tDefinitions['error'],\n\t\t\tkeyof Metadata['parser']\n\t\t>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes &\n\t\t\tCreateEden<\n\t\t\t\tJoinPath<BasePath, Path>,\n\t\t\t\t{\n\t\t\t\t\tpost: CreateEdenResponse<\n\t\t\t\t\t\tPath,\n\t\t\t\t\t\tSchema,\n\t\t\t\t\t\tMacroContext,\n\t\t\t\t\t\tComposeElysiaResponse<\n\t\t\t\t\t\t\tSchema &\n\t\t\t\t\t\t\t\tMacroContext &\n\t\t\t\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\t\t\t\tHandle,\n\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\tMacroContext['return'] & {}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t}\n\t\t\t>,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tthis.add('POST', path, handler as any, hook)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### put\n\t * Register handler for path with method [PUT]\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { Elysia, t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .put('/', () => 'hi')\n\t *     .put('/with-hook', () => 'hi', {\n\t *         response: t.String()\n\t *     })\n\t * ```\n\t */\n\tput<\n\t\tconst Path extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends IntersectIfObjectSchema<\n\t\t\tMergeSchema<\n\t\t\t\tUnwrapRoute<\n\t\t\t\t\tInput,\n\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\tJoinPath<BasePath, Path>\n\t\t\t\t>,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t>,\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema']\n\t\t>,\n\t\tconst Decorator extends Singleton & {\n\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t},\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst Handle extends {} extends MacroContext\n\t\t\t? InlineHandlerNonMacro<NoInfer<Schema>, NoInfer<Decorator>>\n\t\t\t: InlineHandler<\n\t\t\t\t\tNoInfer<Schema>,\n\t\t\t\t\tNoInfer<Decorator>,\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tMacroContext\n\t\t\t\t>\n\t>(\n\t\tpath: Path,\n\t\thandler: Handle,\n\t\thook?: LocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tDecorator,\n\t\t\tDefinitions['error'],\n\t\t\tkeyof Metadata['parser']\n\t\t>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes &\n\t\t\tCreateEden<\n\t\t\t\tJoinPath<BasePath, Path>,\n\t\t\t\t{\n\t\t\t\t\tput: CreateEdenResponse<\n\t\t\t\t\t\tPath,\n\t\t\t\t\t\tSchema,\n\t\t\t\t\t\tMacroContext,\n\t\t\t\t\t\tComposeElysiaResponse<\n\t\t\t\t\t\t\tSchema &\n\t\t\t\t\t\t\t\tMacroContext &\n\t\t\t\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\t\t\t\tHandle,\n\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\tMacroContext['return'] & {}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t}\n\t\t\t>,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tthis.add('PUT', path, handler as any, hook)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### patch\n\t * Register handler for path with method [PATCH]\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { Elysia, t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .patch('/', () => 'hi')\n\t *     .patch('/with-hook', () => 'hi', {\n\t *         response: t.String()\n\t *     })\n\t * ```\n\t */\n\tpatch<\n\t\tconst Path extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends IntersectIfObjectSchema<\n\t\t\tMergeSchema<\n\t\t\t\tUnwrapRoute<\n\t\t\t\t\tInput,\n\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\tJoinPath<BasePath, Path>\n\t\t\t\t>,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t>,\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema']\n\t\t>,\n\t\tconst Decorator extends Singleton & {\n\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t},\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst Handle extends InlineHandler<\n\t\t\tNoInfer<Schema>,\n\t\t\tNoInfer<Decorator>,\n\t\t\t// @ts-ignore\n\t\t\tMacroContext\n\t\t>\n\t>(\n\t\tpath: Path,\n\t\thandler: Handle,\n\t\thook?: LocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tDecorator,\n\t\t\tDefinitions['error'],\n\t\t\tkeyof Metadata['parser']\n\t\t>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes &\n\t\t\tCreateEden<\n\t\t\t\tJoinPath<BasePath, Path>,\n\t\t\t\t{\n\t\t\t\t\tpatch: CreateEdenResponse<\n\t\t\t\t\t\tPath,\n\t\t\t\t\t\tSchema,\n\t\t\t\t\t\tMacroContext,\n\t\t\t\t\t\tComposeElysiaResponse<\n\t\t\t\t\t\t\tSchema &\n\t\t\t\t\t\t\t\tMacroContext &\n\t\t\t\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\t\t\t\tHandle,\n\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\tMacroContext['return'] & {}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t}\n\t\t\t>,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tthis.add('PATCH', path, handler as any, hook)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### delete\n\t * Register handler for path with method [DELETE]\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { Elysia, t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .delete('/', () => 'hi')\n\t *     .delete('/with-hook', () => 'hi', {\n\t *         response: t.String()\n\t *     })\n\t * ```\n\t */\n\tdelete<\n\t\tconst Path extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends IntersectIfObjectSchema<\n\t\t\tMergeSchema<\n\t\t\t\tUnwrapRoute<\n\t\t\t\t\tInput,\n\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\tJoinPath<BasePath, Path>\n\t\t\t\t>,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t>,\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema']\n\t\t>,\n\t\tconst Decorator extends Singleton & {\n\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t},\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst Handle extends InlineHandler<\n\t\t\tNoInfer<Schema>,\n\t\t\tNoInfer<Decorator>,\n\t\t\t// @ts-ignore\n\t\t\tMacroContext\n\t\t>\n\t>(\n\t\tpath: Path,\n\t\thandler: Handle,\n\t\thook?: LocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tDecorator,\n\t\t\tDefinitions['error'],\n\t\t\tkeyof Metadata['parser']\n\t\t>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes &\n\t\t\tCreateEden<\n\t\t\t\tJoinPath<BasePath, Path>,\n\t\t\t\t{\n\t\t\t\t\tdelete: CreateEdenResponse<\n\t\t\t\t\t\tPath,\n\t\t\t\t\t\tSchema,\n\t\t\t\t\t\tMacroContext,\n\t\t\t\t\t\tComposeElysiaResponse<\n\t\t\t\t\t\t\tSchema &\n\t\t\t\t\t\t\t\tMacroContext &\n\t\t\t\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\t\t\t\tHandle,\n\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\tMacroContext['return'] & {}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t}\n\t\t\t>,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tthis.add('DELETE', path, handler as any, hook)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### options\n\t * Register handler for path with method [POST]\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { Elysia, t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .options('/', () => 'hi')\n\t *     .options('/with-hook', () => 'hi', {\n\t *         response: t.String()\n\t *     })\n\t * ```\n\t */\n\toptions<\n\t\tconst Path extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends IntersectIfObjectSchema<\n\t\t\tMergeSchema<\n\t\t\t\tUnwrapRoute<\n\t\t\t\t\tInput,\n\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\tJoinPath<BasePath, Path>\n\t\t\t\t>,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t>,\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema']\n\t\t>,\n\t\tconst Decorator extends Singleton & {\n\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t},\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst Handle extends InlineHandler<\n\t\t\tNoInfer<Schema>,\n\t\t\tNoInfer<Decorator>,\n\t\t\t// @ts-ignore\n\t\t\tMacroContext\n\t\t>\n\t>(\n\t\tpath: Path,\n\t\thandler: Handle,\n\t\thook?: LocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tDecorator,\n\t\t\tDefinitions['error'],\n\t\t\tkeyof Metadata['parser']\n\t\t>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes &\n\t\t\tCreateEden<\n\t\t\t\tJoinPath<BasePath, Path>,\n\t\t\t\t{\n\t\t\t\t\toptions: CreateEdenResponse<\n\t\t\t\t\t\tPath,\n\t\t\t\t\t\tSchema,\n\t\t\t\t\t\tMacroContext,\n\t\t\t\t\t\tComposeElysiaResponse<\n\t\t\t\t\t\t\tSchema &\n\t\t\t\t\t\t\t\tMacroContext &\n\t\t\t\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\t\t\t\tHandle,\n\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\tMacroContext['return'] & {}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t}\n\t\t\t>,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tthis.add('OPTIONS', path, handler as any, hook)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### all\n\t * Register handler for path with method [ALL]\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { Elysia, t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .all('/', () => 'hi')\n\t *     .all('/with-hook', () => 'hi', {\n\t *         response: t.String()\n\t *     })\n\t * ```\n\t */\n\tall<\n\t\tconst Path extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends IntersectIfObjectSchema<\n\t\t\tMergeSchema<\n\t\t\t\tUnwrapRoute<\n\t\t\t\t\tInput,\n\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\tJoinPath<BasePath, Path>\n\t\t\t\t>,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t>,\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema']\n\t\t>,\n\t\tconst Decorator extends Singleton & {\n\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t},\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst Handle extends InlineHandler<\n\t\t\tNoInfer<Schema>,\n\t\t\tNoInfer<Decorator>,\n\t\t\t// @ts-ignore\n\t\t\tMacroContext\n\t\t>\n\t>(\n\t\tpath: Path,\n\t\thandler: Handle,\n\t\thook?: LocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tDecorator,\n\t\t\tDefinitions['error'],\n\t\t\tkeyof Metadata['parser']\n\t\t>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes &\n\t\t\tCreateEden<\n\t\t\t\tJoinPath<BasePath, Path>,\n\t\t\t\t{\n\t\t\t\t\t[method in string]: CreateEdenResponse<\n\t\t\t\t\t\tPath,\n\t\t\t\t\t\tSchema,\n\t\t\t\t\t\tMacroContext,\n\t\t\t\t\t\tComposeElysiaResponse<\n\t\t\t\t\t\t\tSchema &\n\t\t\t\t\t\t\t\tMacroContext &\n\t\t\t\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\t\t\t\tHandle,\n\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\tMacroContext['return'] & {}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t}\n\t\t\t>,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tthis.add('ALL', path, handler as any, hook)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### head\n\t * Register handler for path with method [HEAD]\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { Elysia, t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .head('/', () => 'hi')\n\t *     .head('/with-hook', () => 'hi', {\n\t *         response: t.String()\n\t *     })\n\t * ```\n\t */\n\thead<\n\t\tconst Path extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends IntersectIfObjectSchema<\n\t\t\tMergeSchema<\n\t\t\t\tUnwrapRoute<\n\t\t\t\t\tInput,\n\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\tJoinPath<BasePath, Path>\n\t\t\t\t>,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t>,\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema']\n\t\t>,\n\t\tconst Decorator extends Singleton & {\n\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t},\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst Handle extends InlineHandler<\n\t\t\tNoInfer<Schema>,\n\t\t\tNoInfer<Decorator>,\n\t\t\t// @ts-ignore\n\t\t\tMacroContext\n\t\t>\n\t>(\n\t\tpath: Path,\n\t\thandler: Handle,\n\t\thook?: LocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tDecorator,\n\t\t\tDefinitions['error'],\n\t\t\tkeyof Metadata['parser']\n\t\t>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes &\n\t\t\tCreateEden<\n\t\t\t\tJoinPath<BasePath, Path>,\n\t\t\t\t{\n\t\t\t\t\thead: CreateEdenResponse<\n\t\t\t\t\t\tPath,\n\t\t\t\t\t\tSchema,\n\t\t\t\t\t\tMacroContext,\n\t\t\t\t\t\tComposeElysiaResponse<\n\t\t\t\t\t\t\tSchema &\n\t\t\t\t\t\t\t\tMacroContext &\n\t\t\t\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\t\t\t\tHandle,\n\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\tMacroContext['return'] & {}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t}\n\t\t\t>,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tthis.add('HEAD', path, handler as any, hook)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### connect\n\t * Register handler for path with method [CONNECT]\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { Elysia, t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .connect('/', () => 'hi')\n\t *     .connect('/with-hook', () => 'hi', {\n\t *         response: t.String()\n\t *     })\n\t * ```\n\t */\n\tconnect<\n\t\tconst Path extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends IntersectIfObjectSchema<\n\t\t\tMergeSchema<\n\t\t\t\tUnwrapRoute<\n\t\t\t\t\tInput,\n\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\tJoinPath<BasePath, Path>\n\t\t\t\t>,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t>,\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema']\n\t\t>,\n\t\tconst Decorator extends Singleton & {\n\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t},\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst Handle extends InlineHandler<\n\t\t\tNoInfer<Schema>,\n\t\t\tNoInfer<Decorator>,\n\t\t\t// @ts-ignore\n\t\t\tMacroContext\n\t\t>\n\t>(\n\t\tpath: Path,\n\t\thandler: Handle,\n\t\thook?: LocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tDecorator,\n\t\t\tDefinitions['error'],\n\t\t\tkeyof Metadata['parser']\n\t\t>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes &\n\t\t\tCreateEden<\n\t\t\t\tJoinPath<BasePath, Path>,\n\t\t\t\t{\n\t\t\t\t\tconnect: CreateEdenResponse<\n\t\t\t\t\t\tPath,\n\t\t\t\t\t\tSchema,\n\t\t\t\t\t\tMacroContext,\n\t\t\t\t\t\tComposeElysiaResponse<\n\t\t\t\t\t\t\tSchema &\n\t\t\t\t\t\t\t\tMacroContext &\n\t\t\t\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\t\t\t\tHandle,\n\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\tMacroContext['return'] & {}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t}\n\t\t\t>,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tthis.add('CONNECT', path, handler as any, hook)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### route\n\t * Register handler for path with method [ROUTE]\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { Elysia, t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .route('/', () => 'hi')\n\t *     .route('/with-hook', () => 'hi', {\n\t *         response: t.String()\n\t *     })\n\t * ```\n\t */\n\troute<\n\t\tconst Method extends HTTPMethod,\n\t\tconst Path extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends IntersectIfObjectSchema<\n\t\t\tMergeSchema<\n\t\t\t\tUnwrapRoute<\n\t\t\t\t\tInput,\n\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\tJoinPath<BasePath, Path>\n\t\t\t\t>,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t>,\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema']\n\t\t>,\n\t\tconst Decorator extends Singleton & {\n\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t},\n\t\tconst MacroContext extends {} extends Metadata['macroFn']\n\t\t\t? {}\n\t\t\t: MacroToContext<\n\t\t\t\t\tMetadata['macroFn'],\n\t\t\t\t\tOmit<Input, NonResolvableMacroKey>,\n\t\t\t\t\tDefinitions['typebox']\n\t\t\t\t>,\n\t\tconst Handle extends InlineHandler<\n\t\t\tNoInfer<Schema>,\n\t\t\tNoInfer<Decorator>,\n\t\t\t// @ts-ignore\n\t\t\tMacroContext\n\t\t>\n\t>(\n\t\tmethod: Method,\n\t\tpath: Path,\n\t\thandler: Handle,\n\t\thook?: LocalHook<\n\t\t\tInput,\n\t\t\t// @ts-ignore\n\t\t\tSchema & MacroContext,\n\t\t\tDecorator,\n\t\t\tDefinitions['error'],\n\t\t\tkeyof Metadata['parser']\n\t\t> & {\n\t\t\tconfig?: {\n\t\t\t\tallowMeta?: boolean\n\t\t\t\tmount?: Function\n\t\t\t}\n\t\t}\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes &\n\t\t\tCreateEden<\n\t\t\t\tJoinPath<BasePath, Path>,\n\t\t\t\t{\n\t\t\t\t\t[method in Method]: CreateEdenResponse<\n\t\t\t\t\t\tPath,\n\t\t\t\t\t\tSchema,\n\t\t\t\t\t\tMacroContext,\n\t\t\t\t\t\tComposeElysiaResponse<\n\t\t\t\t\t\t\tSchema &\n\t\t\t\t\t\t\t\tMacroContext &\n\t\t\t\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\t\t\t\tHandle,\n\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\tMacroContext['return'] & {}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t}\n\t\t\t>,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tthis.add(method.toUpperCase(), path, handler as any, hook, hook?.config)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### ws\n\t * Register handler for path with method [ws]\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * import { Elysia, t } from 'elysia'\n\t *\n\t * new Elysia()\n\t *     .ws('/', {\n\t *         message(ws, message) {\n\t *             ws.send(message)\n\t *         }\n\t *     })\n\t * ```\n\t */\n\tws<\n\t\tconst Path extends string,\n\t\tconst Input extends Metadata['macro'] &\n\t\t\tInputSchema<keyof Definitions['typebox'] & string>,\n\t\tconst Schema extends IntersectIfObjectSchema<\n\t\t\tMergeSchema<\n\t\t\t\tUnwrapRoute<\n\t\t\t\t\tInput,\n\t\t\t\t\tDefinitions['typebox'],\n\t\t\t\t\tJoinPath<BasePath, Path>\n\t\t\t\t>,\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>\n\t\t\t\t>\n\t\t\t>,\n\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\tVolatile['standaloneSchema']\n\t\t>,\n\t\tconst MacroContext extends MacroToContext<\n\t\t\tMetadata['macroFn'],\n\t\t\tOmit<Input, NonResolvableMacroKey>\n\t\t>\n\t>(\n\t\tpath: Path,\n\t\toptions: WSLocalHook<\n\t\t\tInput,\n\t\t\tSchema,\n\t\t\tSingleton & {\n\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\tVolatile['resolve'] &\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tMacroContext['resolve']\n\t\t\t}\n\t\t>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes &\n\t\t\tCreateEden<\n\t\t\t\tJoinPath<BasePath, Path>,\n\t\t\t\t{\n\t\t\t\t\tsubscribe: CreateEdenResponse<\n\t\t\t\t\t\tPath,\n\t\t\t\t\t\tSchema,\n\t\t\t\t\t\tMacroContext,\n\t\t\t\t\t\tComposeElysiaResponse<\n\t\t\t\t\t\t\tSchema &\n\t\t\t\t\t\t\t\tMacroContext &\n\t\t\t\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\t\t\t\t{} extends Schema['response']\n\t\t\t\t\t\t\t\t? unknown\n\t\t\t\t\t\t\t\t: Schema['response'] extends { [200]: any }\n\t\t\t\t\t\t\t\t\t? Schema['response'][200]\n\t\t\t\t\t\t\t\t\t: unknown,\n\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\t\t\tUnionResponseStatus<\n\t\t\t\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t\t\tMacroContext['return'] & {}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t}\n\t\t\t>,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tif (this['~adapter'].ws) this['~adapter'].ws(this, path, options as any)\n\t\telse console.warn(`Current adapter doesn't support WebSocket`)\n\n\t\treturn this as any\n\t}\n\n\t/**\n\t * ### state\n\t * Assign global mutatable state accessible for all handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .state('counter', 0)\n\t *     .get('/', (({ counter }) => ++counter)\n\t * ```\n\t */\n\tstate<const Name extends string | number | symbol, Value>(\n\t\tname: Name,\n\t\tvalue: Value\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator']\n\t\t\tstore: Prettify<\n\t\t\t\tSingleton['store'] & {\n\t\t\t\t\t[name in Name]: Value\n\t\t\t\t}\n\t\t\t>\n\t\t\tderive: Singleton['derive']\n\t\t\tresolve: Singleton['resolve']\n\t\t},\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\t/**\n\t * ### state\n\t * Assign global mutatable state accessible for all handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .state({ counter: 0 })\n\t *     .get('/', (({ counter }) => ++counter)\n\t * ```\n\t */\n\tstate<Store extends Record<string, unknown>>(\n\t\tstore: Store\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator']\n\t\t\tstore: Prettify<Singleton['store'] & Store>\n\t\t\tderive: Singleton['derive']\n\t\t\tresolve: Singleton['resolve']\n\t\t},\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\t/**\n\t * ### state\n\t * Assign global mutatable state accessible for all handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .state('counter', 0)\n\t *     .get('/', (({ counter }) => ++counter)\n\t * ```\n\t */\n\tstate<\n\t\tconst Type extends ContextAppendType,\n\t\tconst Name extends string | number | symbol,\n\t\tValue\n\t>(\n\t\toptions: { as: Type },\n\t\tname: Name,\n\t\tvalue: Value\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator']\n\t\t\tstore: Type extends 'override'\n\t\t\t\t? Reconcile<\n\t\t\t\t\t\tSingleton['store'],\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t[name in Name]: Value\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttrue\n\t\t\t\t\t>\n\t\t\t\t: Prettify<\n\t\t\t\t\t\tSingleton['store'] & {\n\t\t\t\t\t\t\t[name in Name]: Value\n\t\t\t\t\t\t}\n\t\t\t\t\t>\n\t\t\tderive: Singleton['derive']\n\t\t\tresolve: Singleton['resolve']\n\t\t},\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\t/**\n\t * ### state\n\t * Assign global mutatable state accessible for all handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .state({ counter: 0 })\n\t *     .get('/', (({ counter }) => ++counter)\n\t * ```\n\t */\n\tstate<\n\t\tconst Type extends ContextAppendType,\n\t\tStore extends Record<string, unknown>\n\t>(\n\t\toptions: { as: Type },\n\t\tstore: Store\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator']\n\t\t\tstore: Type extends 'override'\n\t\t\t\t? Reconcile<Singleton['store'], Store>\n\t\t\t\t: Prettify<Singleton['store'] & Store>\n\t\t\tderive: Singleton['derive']\n\t\t\tresolve: Singleton['resolve']\n\t\t},\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\tstate<NewStore extends Record<string, unknown>>(\n\t\tmapper: (decorators: Singleton['store']) => NewStore\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator']\n\t\t\tstore: NewStore\n\t\t\tderive: Singleton['derive']\n\t\t\tresolve: Singleton['resolve']\n\t\t},\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\t/**\n\t * ### state\n\t * Assign global mutatable state accessible for all handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .state('counter', 0)\n\t *     .get('/', (({ counter }) => ++counter)\n\t * ```\n\t */\n\tstate(\n\t\toptions:\n\t\t\t| { as: ContextAppendType }\n\t\t\t| string\n\t\t\t| Record<string, unknown>\n\t\t\t| Function,\n\t\tname?:\n\t\t\t| string\n\t\t\t| Record<string, unknown>\n\t\t\t| Function\n\t\t\t| { as: ContextAppendType },\n\t\tvalue?: unknown\n\t) {\n\t\tif (name === undefined) {\n\t\t\t/**\n\t\t\t * Using either\n\t\t\t * - decorate({ name: value })\n\t\t\t */\n\t\t\tvalue = options\n\t\t\toptions = { as: 'append' }\n\t\t\tname = ''\n\t\t} else if (value === undefined) {\n\t\t\t/**\n\t\t\t * Using either\n\t\t\t * - decorate({ as: 'override' }, { name: value })\n\t\t\t * - decorate('name', value)\n\t\t\t */\n\n\t\t\t// decorate('name', value)\n\t\t\tif (typeof options === 'string') {\n\t\t\t\tvalue = name\n\t\t\t\tname = options\n\t\t\t\toptions = { as: 'append' }\n\t\t\t} else if (typeof options === 'object') {\n\t\t\t\t// decorate({ as: 'override' }, { name: value })\n\t\t\t\tvalue = name\n\t\t\t\tname = ''\n\t\t\t}\n\t\t}\n\n\t\tconst { as } = options as { as: ContextAppendType }\n\n\t\tif (typeof name !== 'string') return this\n\n\t\tswitch (typeof value) {\n\t\t\tcase 'object':\n\t\t\t\tif (!value || !isNotEmpty(value)) return this\n\n\t\t\t\tif (name) {\n\t\t\t\t\tif (name in this.singleton.store)\n\t\t\t\t\t\tthis.singleton.store[name] = mergeDeep(\n\t\t\t\t\t\t\tthis.singleton.store[name] as any,\n\t\t\t\t\t\t\tvalue!,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\toverride: as === 'override'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t)\n\t\t\t\t\telse this.singleton.store[name] = value\n\n\t\t\t\t\treturn this\n\t\t\t\t}\n\n\t\t\t\tif (value === null) return this\n\n\t\t\t\tthis.singleton.store = mergeDeep(this.singleton.store, value, {\n\t\t\t\t\toverride: as === 'override'\n\t\t\t\t})\n\n\t\t\t\treturn this as any\n\n\t\t\tcase 'function':\n\t\t\t\tif (name) {\n\t\t\t\t\tif (as === 'override' || !(name in this.singleton.store))\n\t\t\t\t\t\tthis.singleton.store[name] = value\n\t\t\t\t} else this.singleton.store = value(this.singleton.store)\n\n\t\t\t\treturn this as any\n\n\t\t\tdefault:\n\t\t\t\tif (as === 'override' || !(name in this.singleton.store))\n\t\t\t\t\tthis.singleton.store[name] = value\n\n\t\t\t\treturn this\n\t\t}\n\t}\n\n\t/**\n\t * ### decorate\n\t * Define custom method to `Context` accessible for all handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .decorate('getDate', () => Date.now())\n\t *     .get('/', (({ getDate }) => getDate())\n\t * ```\n\t */\n\tdecorate<const Name extends string, Value>(\n\t\tname: Name,\n\t\tvalue: Value\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator'] & {\n\t\t\t\t[name in Name]: Value\n\t\t\t}\n\t\t\tstore: Singleton['store']\n\t\t\tderive: Singleton['derive']\n\t\t\tresolve: Singleton['resolve']\n\t\t},\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\t/**\n\t * ### decorate\n\t * Define custom method to `Context` accessible for all handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .decorate('getDate', () => Date.now())\n\t *     .get('/', (({ getDate }) => getDate())\n\t * ```\n\t */\n\tdecorate<NewDecorators extends Record<string, unknown>>(\n\t\tdecorators: NewDecorators\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Singleton['decorator'] & NewDecorators\n\t\t\tstore: Singleton['store']\n\t\t\tderive: Singleton['derive']\n\t\t\tresolve: Singleton['resolve']\n\t\t},\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\tdecorate<NewDecorators extends Record<string, unknown>>(\n\t\tmapper: (decorators: Singleton['decorator']) => NewDecorators\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: NewDecorators\n\t\t\tstore: Singleton['store']\n\t\t\tderive: Singleton['derive']\n\t\t\tresolve: Singleton['resolve']\n\t\t},\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\t/**\n\t * ### decorate\n\t * Define custom method to `Context` accessible for all handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .decorate({ as: 'override' }, 'getDate', () => Date.now())\n\t *     .get('/', (({ getDate }) => getDate())\n\t * ```\n\t */\n\tdecorate<\n\t\tconst Type extends ContextAppendType,\n\t\tconst Name extends string,\n\t\tValue\n\t>(\n\t\toptions: { as: Type },\n\t\tname: Name,\n\t\tvalue: Value\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Type extends 'override'\n\t\t\t\t? Reconcile<\n\t\t\t\t\t\tSingleton['decorator'],\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t[name in Name]: Value\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttrue\n\t\t\t\t\t>\n\t\t\t\t: Singleton['decorator'] & {\n\t\t\t\t\t\t[name in Name]: Value\n\t\t\t\t\t}\n\t\t\tstore: Singleton['store']\n\t\t\tderive: Singleton['derive']\n\t\t\tresolve: Singleton['resolve']\n\t\t},\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\t/**\n\t * ### decorate\n\t * Define custom method to `Context` accessible for all handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .decorate('getDate', () => Date.now())\n\t *     .get('/', (({ getDate }) => getDate())\n\t * ```\n\t */\n\tdecorate<\n\t\tconst Type extends ContextAppendType,\n\t\tNewDecorators extends Record<string, unknown>\n\t>(\n\t\toptions: { as: Type },\n\t\tdecorators: NewDecorators\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Type extends 'override'\n\t\t\t\t? Reconcile<Singleton['decorator'], NewDecorators, true>\n\t\t\t\t: Singleton['decorator'] & NewDecorators\n\t\t\tstore: Singleton['store']\n\t\t\tderive: Singleton['derive']\n\t\t\tresolve: Singleton['resolve']\n\t\t},\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\t/**\n\t * ### decorate\n\t * Define custom method to `Context` accessible for all handler\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .decorate('getDate', () => Date.now())\n\t *     .get('/', (({ getDate }) => getDate())\n\t * ```\n\t */\n\tdecorate(\n\t\toptions:\n\t\t\t| { as: ContextAppendType }\n\t\t\t| string\n\t\t\t| Record<string, unknown>\n\t\t\t| Function,\n\t\tname?:\n\t\t\t| string\n\t\t\t| Record<string, unknown>\n\t\t\t| Function\n\t\t\t| { as: ContextAppendType },\n\t\tvalue?: unknown\n\t) {\n\t\tif (name === undefined) {\n\t\t\t/**\n\t\t\t * Using either\n\t\t\t * - decorate({ name: value })\n\t\t\t */\n\t\t\tvalue = options\n\t\t\toptions = { as: 'append' }\n\t\t\tname = ''\n\t\t} else if (value === undefined) {\n\t\t\t/**\n\t\t\t * Using either\n\t\t\t * - decorate({ as: 'override' }, { name: value })\n\t\t\t * - decorate('name', value)\n\t\t\t */\n\n\t\t\t// decorate('name', value)\n\t\t\tif (typeof options === 'string') {\n\t\t\t\tvalue = name\n\t\t\t\tname = options\n\t\t\t\toptions = { as: 'append' }\n\t\t\t} else if (typeof options === 'object') {\n\t\t\t\t// decorate({ as: 'override' }, { name: value })\n\t\t\t\tvalue = name\n\t\t\t\tname = ''\n\t\t\t}\n\t\t}\n\n\t\tconst { as } = options as { as: ContextAppendType }\n\n\t\tif (typeof name !== 'string') return this\n\n\t\tswitch (typeof value) {\n\t\t\tcase 'object':\n\t\t\t\tif (name) {\n\t\t\t\t\tif (name in this.singleton.decorator)\n\t\t\t\t\t\tthis.singleton.decorator[name] = mergeDeep(\n\t\t\t\t\t\t\tthis.singleton.decorator[name] as any,\n\t\t\t\t\t\t\tvalue!,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\toverride: as === 'override'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t)\n\t\t\t\t\telse this.singleton.decorator[name] = value\n\n\t\t\t\t\treturn this\n\t\t\t\t}\n\n\t\t\t\tif (value === null) return this\n\n\t\t\t\tthis.singleton.decorator = mergeDeep(\n\t\t\t\t\tthis.singleton.decorator,\n\t\t\t\t\tvalue,\n\t\t\t\t\t{\n\t\t\t\t\t\toverride: as === 'override'\n\t\t\t\t\t}\n\t\t\t\t)\n\n\t\t\t\treturn this as any\n\n\t\t\tcase 'function':\n\t\t\t\tif (name) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tas === 'override' ||\n\t\t\t\t\t\t!(name in this.singleton.decorator)\n\t\t\t\t\t)\n\t\t\t\t\t\tthis.singleton.decorator[name] = value\n\t\t\t\t} else\n\t\t\t\t\tthis.singleton.decorator = value(this.singleton.decorator)\n\n\t\t\t\treturn this as any\n\n\t\t\tdefault:\n\t\t\t\tif (as === 'override' || !(name in this.singleton.decorator))\n\t\t\t\t\tthis.singleton.decorator[name] = value\n\n\t\t\t\treturn this\n\t\t}\n\t}\n\n\t/**\n\t * Derive new property for each request with access to `Context`.\n\t *\n\t * If error is thrown, the scope will skip to handling error instead.\n\t *\n\t * ---\n\t * @example\n\t * new Elysia()\n\t *     .state('counter', 1)\n\t *     .derive(({ store }) => ({\n\t *         increase() {\n\t *             store.counter++\n\t *         }\n\t *     }))\n\t */\n\tderive<\n\t\tconst Derivative extends\n\t\t\t| Record<string, unknown>\n\t\t\t| ElysiaCustomStatusResponse<any, any, any>\n\t\t\t| void\n\t>(\n\t\ttransform: (\n\t\t\tcontext: Context<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>,\n\t\t\t\t\tBasePath\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\tSingleton & {\n\t\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\t\t}\n\t\t\t>\n\t\t) => MaybePromise<Derivative>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: Volatile['derive'] & ExcludeElysiaResponse<Derivative>\n\t\t\tresolve: Volatile['resolve']\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: UnionResponseStatus<\n\t\t\t\tVolatile['response'],\n\t\t\t\tExtractErrorFromHandle<Derivative>\n\t\t\t>\n\t\t}\n\t>\n\n\t/**\n\t * Derive new property for each request with access to `Context`.\n\t *\n\t * If error is thrown, the scope will skip to handling error instead.\n\t *\n\t * ---\n\t * @example\n\t * new Elysia()\n\t *     .state('counter', 1)\n\t *     .derive(({ store }) => ({\n\t *         increase() {\n\t *             store.counter++\n\t *         }\n\t *     }))\n\t */\n\tderive<\n\t\tconst Derivative extends\n\t\t\t| Record<string, unknown>\n\t\t\t| ElysiaCustomStatusResponse<any, any, any>\n\t\t\t| void,\n\t\tconst Type extends LifeCycleType\n\t>(\n\t\toptions: { as: Type },\n\t\ttransform: (\n\t\t\tcontext: Context<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tVolatile['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Metadata['schema']>,\n\t\t\t\t\tBasePath\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'] &\n\t\t\t\t\t'global' extends Type\n\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t? { params: { [name: string]: string | undefined } }\n\t\t\t\t\t\t: {},\n\t\t\t\tSingleton &\n\t\t\t\t\t('global' extends Type\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tderive: Partial<\n\t\t\t\t\t\t\t\t\tEphemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tresolve: Partial<\n\t\t\t\t\t\t\t\t\tEphemeral['resolve'] & Volatile['resolve']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\t\tPartial<Volatile['derive']>\n\t\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\t\tPartial<Volatile['resolve']>\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\t\tVolatile['derive']\n\t\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t\t\t}),\n\t\t\t\tBasePath\n\t\t\t>\n\t\t) => MaybePromise<Derivative>\n\t): Type extends 'global'\n\t\t? Elysia<\n\t\t\t\tBasePath,\n\t\t\t\t{\n\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\t\tExcludeElysiaResponse<Derivative>\n\t\t\t\t\tresolve: Singleton['resolve']\n\t\t\t\t},\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: Metadata['schema']\n\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\tExtractErrorFromHandle<Derivative>\n\t\t\t\t\t>\n\t\t\t\t},\n\t\t\t\tRoutes,\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t: Type extends 'scoped'\n\t\t\t? Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\tExcludeElysiaResponse<Derivative>\n\t\t\t\t\t\tresolve: Ephemeral['resolve']\n\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\tExtractErrorFromHandle<Derivative>\n\t\t\t\t\t\t>\n\t\t\t\t\t},\n\t\t\t\t\tVolatile\n\t\t\t\t>\n\t\t\t: Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\tEphemeral,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Volatile['derive'] &\n\t\t\t\t\t\t\tExcludeElysiaResponse<Derivative>\n\t\t\t\t\t\tresolve: Ephemeral['resolve']\n\t\t\t\t\t\tschema: Volatile['schema']\n\t\t\t\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\tExtractErrorFromHandle<Derivative>\n\t\t\t\t\t\t>\n\t\t\t\t\t}\n\t\t\t\t>\n\n\tderive(\n\t\toptionsOrTransform: { as: LifeCycleType } | Function,\n\t\ttransform?: Function\n\t) {\n\t\tif (!transform) {\n\t\t\ttransform = optionsOrTransform as any\n\t\t\toptionsOrTransform = { as: 'local' }\n\t\t}\n\n\t\tconst hook: HookContainer = {\n\t\t\tsubType: 'derive',\n\t\t\tfn: transform!\n\t\t}\n\n\t\treturn this.onTransform(optionsOrTransform as any, hook as any) as any\n\t}\n\n\tmodel<\n\t\tconst Name extends string,\n\t\tconst Model extends TSchema | StandardSchemaV1Like\n\t>(\n\t\tname: Name,\n\t\tmodel: Model\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\t{\n\t\t\ttypebox: Definitions['typebox'] & {\n\t\t\t\t[name in Name]: Model\n\t\t\t}\n\t\t\terror: Definitions['error']\n\t\t},\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\tmodel<\n\t\tconst Recorder extends Record<string, TSchema | StandardSchemaV1Like>\n\t>(\n\t\trecord: Recorder\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\t{\n\t\t\ttypebox: Definitions['typebox'] & Recorder\n\t\t\terror: Definitions['error']\n\t\t},\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\tmodel<const NewType extends Record<string, TSchema | StandardSchemaV1Like>>(\n\t\tmapper: (\n\t\t\tdecorators: Definitions['typebox'] extends infer Models\n\t\t\t\t? {\n\t\t\t\t\t\t[Name in keyof Models]: Models[Name] extends TSchema\n\t\t\t\t\t\t\t? TRef<Name & string>\n\t\t\t\t\t\t\t: Models[Name]\n\t\t\t\t\t}\n\t\t\t\t: {}\n\t\t) => NewType\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\t{\n\t\t\ttypebox: {\n\t\t\t\t[Name in keyof NewType]: NewType[Name] extends TRef<\n\t\t\t\t\tName & string\n\t\t\t\t>\n\t\t\t\t\t? // @ts-ignore\n\t\t\t\t\t\tDefinitions['typebox'][Name]\n\t\t\t\t\t: NewType[Name]\n\t\t\t}\n\t\t\terror: Definitions['error']\n\t\t},\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t>\n\n\tmodel(\n\t\tname:\n\t\t\t| string\n\t\t\t| Record<string, TAnySchema | StandardSchemaV1Like>\n\t\t\t| Function,\n\t\tmodel?: TAnySchema | StandardSchemaV1Like\n\t): AnyElysia {\n\t\tconst onlyTypebox = <\n\t\t\tA extends Record<string, TAnySchema | StandardSchemaV1Like>\n\t\t>(\n\t\t\ta: A\n\t\t): Extract<A, TAnySchema> => {\n\t\t\tconst res = {} as Record<string, TAnySchema>\n\t\t\tfor (const key in a) if (!('~standard' in a[key])) res[key] = a[key]\n\t\t\treturn res as Extract<A, TAnySchema>\n\t\t}\n\n\t\tswitch (typeof name) {\n\t\t\tcase 'object':\n\t\t\t\tconst parsedTypebox = {} as Record<\n\t\t\t\t\tstring,\n\t\t\t\t\tTSchema | StandardSchemaV1Like\n\t\t\t\t>\n\n\t\t\t\tconst kvs = Object.entries(name)\n\n\t\t\t\tif (!kvs.length) return this\n\n\t\t\t\tfor (const [key, value] of kvs) {\n\t\t\t\t\tif (key in this.definitions.type) continue\n\n\t\t\t\t\tif ('~standard' in value) {\n\t\t\t\t\t\tthis.definitions.type[key] = value\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparsedTypebox[key] = this.definitions.type[key] = value\n\t\t\t\t\t\tparsedTypebox[key].$id ??= `#/components/schemas/${key}`\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\tthis.definitions.typebox = t.Module({\n\t\t\t\t\t...(this.definitions.typebox['$defs'] as TModule<{}>),\n\t\t\t\t\t...parsedTypebox\n\t\t\t\t} as any)\n\n\t\t\t\treturn this\n\n\t\t\tcase 'function':\n\t\t\t\tconst result = name(this.definitions.type)\n\t\t\t\tthis.definitions.type = result\n\t\t\t\tthis.definitions.typebox = t.Module(onlyTypebox(result))\n\n\t\t\t\treturn this\n\n\t\t\tcase 'string':\n\t\t\t\tif (!model) break\n\n\t\t\t\tthis.definitions.type[name] = model\n\n\t\t\t\tif ('~standard' in model) return this\n\n\t\t\t\tconst newModel = {\n\t\t\t\t\t...model,\n\t\t\t\t\tid: model.$id ?? `#/components/schemas/${name}`\n\t\t\t\t}\n\n\t\t\t\tthis.definitions.typebox = t.Module({\n\t\t\t\t\t...(this.definitions.typebox['$defs'] as TModule<{}>),\n\t\t\t\t\t...newModel\n\t\t\t\t} as any)\n\n\t\t\t\treturn this\n\t\t}\n\n\t\tif (!model) return this\n\n\t\tthis.definitions.type[name] = model!\n\t\tif ('~standard' in model) return this\n\n\t\tthis.definitions.typebox = t.Module({\n\t\t\t...this.definitions.typebox['$defs'],\n\t\t\t[name]: model!\n\t\t})\n\n\t\treturn this\n\t}\n\n\tRef<K extends keyof Extract<Definitions['typebox'], TAnySchema> & string>(\n\t\tkey: K\n\t) {\n\t\treturn t.Ref(key)\n\t}\n\n\tmapDerive<\n\t\tconst NewDerivative extends\n\t\t\t| Record<string, unknown>\n\t\t\t| ElysiaCustomStatusResponse<any, any, any>\n\t>(\n\t\tmapper: (\n\t\t\tcontext: Context<\n\t\t\t\t{},\n\t\t\t\tSingleton & {\n\t\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\t\t},\n\t\t\t\tBasePath\n\t\t\t>\n\t\t) => MaybePromise<NewDerivative>\n\t): Elysia<\n\t\tBasePath,\n\t\tSingleton,\n\t\tDefinitions,\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\t{\n\t\t\tderive: ExcludeElysiaResponse<NewDerivative>\n\t\t\tresolve: Volatile['resolve']\n\t\t\tschema: Volatile['schema']\n\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\tresponse: UnionResponseStatus<\n\t\t\t\tVolatile['response'],\n\t\t\t\tExtractErrorFromHandle<NewDerivative>\n\t\t\t>\n\t\t}\n\t>\n\n\tmapDerive<\n\t\tconst NewDerivative extends\n\t\t\t| Record<string, unknown>\n\t\t\t| ElysiaCustomStatusResponse<any, any, any>,\n\t\tconst Type extends LifeCycleType\n\t>(\n\t\toptions: { as: Type },\n\t\tmapper: (\n\t\t\tcontext: Context<\n\t\t\t\t{},\n\t\t\t\tSingleton &\n\t\t\t\t\t('global' extends Type\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tderive: Partial<\n\t\t\t\t\t\t\t\t\tEphemeral['derive'] & Volatile['derive']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tresolve: Partial<\n\t\t\t\t\t\t\t\t\tEphemeral['resolve'] & Volatile['resolve']\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: 'scoped' extends Type\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\t\tPartial<Volatile['derive']>\n\t\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\t\tPartial<Volatile['resolve']>\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\t\t\t\tVolatile['derive']\n\t\t\t\t\t\t\t\t\tresolve: Ephemeral['resolve'] &\n\t\t\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t\t\t}),\n\t\t\t\tBasePath\n\t\t\t>\n\t\t) => MaybePromise<NewDerivative>\n\t): Type extends 'global'\n\t\t? Elysia<\n\t\t\t\tBasePath,\n\t\t\t\t{\n\t\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\t\tstore: Singleton['store']\n\t\t\t\t\tderive: Singleton['derive'] &\n\t\t\t\t\t\tExcludeElysiaResponse<NewDerivative>\n\t\t\t\t\tresolve: Singleton['resolve']\n\t\t\t\t},\n\t\t\t\tDefinitions,\n\t\t\t\t{\n\t\t\t\t\tschema: Metadata['schema']\n\t\t\t\t\tstandaloneSchema: Metadata['standaloneSchema']\n\t\t\t\t\tmacro: Metadata['macro']\n\t\t\t\t\tmacroFn: Metadata['macroFn']\n\t\t\t\t\tparser: Metadata['parser']\n\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\tMetadata['response'],\n\t\t\t\t\t\tExtractErrorFromHandle<NewDerivative>\n\t\t\t\t\t>\n\t\t\t\t},\n\t\t\t\tRoutes,\n\t\t\t\tEphemeral,\n\t\t\t\tVolatile\n\t\t\t>\n\t\t: Type extends 'scoped'\n\t\t\t? Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Ephemeral['derive'] &\n\t\t\t\t\t\t\tExcludeElysiaResponse<NewDerivative>\n\t\t\t\t\t\tresolve: Ephemeral['resolve']\n\t\t\t\t\t\tschema: Ephemeral['schema']\n\t\t\t\t\t\tstandaloneSchema: Ephemeral['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tEphemeral['response'],\n\t\t\t\t\t\t\tExtractErrorFromHandle<NewDerivative>\n\t\t\t\t\t\t>\n\t\t\t\t\t},\n\t\t\t\t\tVolatile\n\t\t\t\t>\n\t\t\t: Elysia<\n\t\t\t\t\tBasePath,\n\t\t\t\t\tSingleton,\n\t\t\t\t\tDefinitions,\n\t\t\t\t\tMetadata,\n\t\t\t\t\tRoutes,\n\t\t\t\t\tEphemeral,\n\t\t\t\t\t{\n\t\t\t\t\t\tderive: Volatile['derive']\n\t\t\t\t\t\tresolve: Volatile['resolve'] &\n\t\t\t\t\t\t\tExcludeElysiaResponse<NewDerivative>\n\t\t\t\t\t\tschema: Volatile['schema']\n\t\t\t\t\t\tstandaloneSchema: Volatile['standaloneSchema']\n\t\t\t\t\t\tresponse: UnionResponseStatus<\n\t\t\t\t\t\t\tVolatile['response'],\n\t\t\t\t\t\t\tExtractErrorFromHandle<NewDerivative>\n\t\t\t\t\t\t>\n\t\t\t\t\t}\n\t\t\t\t>\n\n\tmapDerive(\n\t\toptionsOrDerive: { as: LifeCycleType } | Function,\n\t\tmapper?: Function\n\t) {\n\t\tif (!mapper) {\n\t\t\tmapper = optionsOrDerive as any\n\t\t\toptionsOrDerive = { as: 'local' }\n\t\t}\n\n\t\tconst hook: HookContainer = {\n\t\t\tsubType: 'mapDerive',\n\t\t\tfn: mapper!\n\t\t}\n\n\t\treturn this.onTransform(optionsOrDerive as any, hook as any) as any\n\t}\n\n\taffix<\n\t\tconst Base extends 'prefix' | 'suffix',\n\t\tconst Type extends 'all' | 'decorator' | 'state' | 'model' | 'error',\n\t\tconst Word extends string\n\t>(\n\t\tbase: Base,\n\t\ttype: Type,\n\t\tword: Word\n\t): Elysia<\n\t\tBasePath,\n\t\t{\n\t\t\tdecorator: Type extends 'decorator' | 'all'\n\t\t\t\t? 'prefix' extends Base\n\t\t\t\t\t? Word extends `${string}${'_' | '-' | ' '}`\n\t\t\t\t\t\t? AddPrefix<Word, Singleton['decorator']>\n\t\t\t\t\t\t: AddPrefixCapitalize<Word, Singleton['decorator']>\n\t\t\t\t\t: AddSuffixCapitalize<Word, Singleton['decorator']>\n\t\t\t\t: Singleton['decorator']\n\t\t\tstore: Type extends 'state' | 'all'\n\t\t\t\t? 'prefix' extends Base\n\t\t\t\t\t? Word extends `${string}${'_' | '-' | ' '}`\n\t\t\t\t\t\t? AddPrefix<Word, Singleton['store']>\n\t\t\t\t\t\t: AddPrefixCapitalize<Word, Singleton['store']>\n\t\t\t\t\t: AddSuffix<Word, Singleton['store']>\n\t\t\t\t: Singleton['store']\n\t\t\tderive: Type extends 'decorator' | 'all'\n\t\t\t\t? 'prefix' extends Base\n\t\t\t\t\t? Word extends `${string}${'_' | '-' | ' '}`\n\t\t\t\t\t\t? AddPrefix<Word, Singleton['derive']>\n\t\t\t\t\t\t: AddPrefixCapitalize<Word, Singleton['derive']>\n\t\t\t\t\t: AddSuffixCapitalize<Word, Singleton['derive']>\n\t\t\t\t: Singleton['derive']\n\t\t\tresolve: Type extends 'decorator' | 'all'\n\t\t\t\t? 'prefix' extends Base\n\t\t\t\t\t? Word extends `${string}${'_' | '-' | ' '}`\n\t\t\t\t\t\t? AddPrefix<Word, Singleton['resolve']>\n\t\t\t\t\t\t: AddPrefixCapitalize<Word, Singleton['resolve']>\n\t\t\t\t\t: AddSuffixCapitalize<Word, Singleton['resolve']>\n\t\t\t\t: Singleton['resolve']\n\t\t},\n\t\t{\n\t\t\ttypebox: Type extends 'model' | 'all'\n\t\t\t\t? 'prefix' extends Base\n\t\t\t\t\t? Word extends `${string}${'_' | '-' | ' '}`\n\t\t\t\t\t\t? AddPrefix<Word, Definitions['typebox']>\n\t\t\t\t\t\t: AddPrefixCapitalize<Word, Definitions['typebox']>\n\t\t\t\t\t: AddSuffixCapitalize<Word, Definitions['typebox']>\n\t\t\t\t: Definitions['typebox']\n\t\t\terror: Type extends 'error' | 'all'\n\t\t\t\t? 'prefix' extends Base\n\t\t\t\t\t? Word extends `${string}${'_' | '-' | ' '}`\n\t\t\t\t\t\t? AddPrefix<Word, Definitions['error']>\n\t\t\t\t\t\t: AddPrefixCapitalize<Word, Definitions['error']>\n\t\t\t\t\t: AddSuffixCapitalize<Word, Definitions['error']>\n\t\t\t\t: Definitions['error']\n\t\t},\n\t\tMetadata,\n\t\tRoutes,\n\t\tEphemeral,\n\t\tVolatile\n\t> {\n\t\tif (word === '') return this as any\n\n\t\tconst delimieter = ['_', '-', ' ']\n\t\tconst capitalize = (word: string) =>\n\t\t\tword[0].toUpperCase() + word.slice(1)\n\n\t\tconst joinKey =\n\t\t\tbase === 'prefix'\n\t\t\t\t? (prefix: string, word: string) =>\n\t\t\t\t\t\tdelimieter.includes(prefix.at(-1) ?? '')\n\t\t\t\t\t\t\t? prefix + word\n\t\t\t\t\t\t\t: prefix + capitalize(word)\n\t\t\t\t: delimieter.includes(word.at(-1) ?? '')\n\t\t\t\t\t? (suffix: string, word: string) => word + suffix\n\t\t\t\t\t: (suffix: string, word: string) =>\n\t\t\t\t\t\t\tword + capitalize(suffix)\n\n\t\tconst remap = (type: 'decorator' | 'state' | 'model' | 'error') => {\n\t\t\tconst store: Record<string, any> = {}\n\n\t\t\tswitch (type) {\n\t\t\t\tcase 'decorator':\n\t\t\t\t\tfor (const key in this.singleton.decorator) {\n\t\t\t\t\t\tstore[joinKey(word, key)] =\n\t\t\t\t\t\t\tthis.singleton.decorator[key]\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.singleton.decorator = store\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'state':\n\t\t\t\t\tfor (const key in this.singleton.store)\n\t\t\t\t\t\tstore[joinKey(word, key)] = this.singleton.store[key]\n\n\t\t\t\t\tthis.singleton.store = store\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'model':\n\t\t\t\t\tfor (const key in this.definitions.type)\n\t\t\t\t\t\tstore[joinKey(word, key)] = this.definitions.type[key]\n\n\t\t\t\t\tthis.definitions.type = store\n\t\t\t\t\tbreak\n\n\t\t\t\tcase 'error':\n\t\t\t\t\tfor (const key in this.definitions.error)\n\t\t\t\t\t\tstore[joinKey(word, key)] = this.definitions.error[key]\n\n\t\t\t\t\tthis.definitions.error = store\n\t\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tconst types = Array.isArray(type) ? type : [type]\n\n\t\tfor (const type of types.some((x) => x === 'all')\n\t\t\t? ['decorator', 'state', 'model', 'error']\n\t\t\t: types)\n\t\t\tremap(type as 'decorator')\n\n\t\treturn this as any\n\t}\n\n\tprefix<\n\t\tconst Type extends 'all' | 'decorator' | 'state' | 'model' | 'error',\n\t\tconst Word extends string\n\t>(type: Type, word: Word) {\n\t\treturn this.affix('prefix', type, word)\n\t}\n\n\tsuffix<\n\t\tconst Type extends 'all' | 'decorator' | 'state' | 'model' | 'error',\n\t\tconst Word extends string\n\t>(type: Type, word: Word) {\n\t\treturn this.affix('suffix', type, word)\n\t}\n\n\tcompile() {\n\t\tthis['~adapter'].beforeCompile?.(this)\n\n\t\tif (this['~adapter'].isWebStandard) {\n\t\t\tthis._handle = this.config.aot\n\t\t\t\t? composeGeneralHandler(this)\n\t\t\t\t: createDynamicHandler(this)\n\n\t\t\tObject.defineProperty(this, 'fetch', {\n\t\t\t\tvalue: this._handle,\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true\n\t\t\t})\n\n\t\t\tif (typeof this.server?.reload === 'function')\n\t\t\t\tthis.server.reload({\n\t\t\t\t\t...(this.server || {}),\n\t\t\t\t\tfetch: this.fetch\n\t\t\t\t})\n\n\t\t\treturn this\n\t\t}\n\n\t\tif (typeof this.server?.reload === 'function')\n\t\t\tthis.server.reload(this.server || {})\n\n\t\tthis._handle = composeGeneralHandler(this)\n\n\t\treturn this\n\t}\n\n\thandle = async (request: Request) => this.fetch(request)\n\n\t/**\n\t * Use handle can be either sync or async to save performance.\n\t *\n\t * Beside benchmark purpose, please use 'handle' instead.\n\t */\n\tget fetch(): (request: Request) => MaybePromise<Response> {\n\t\tconst fetch = this.config.aot\n\t\t\t? composeGeneralHandler(this)\n\t\t\t: createDynamicHandler(this)\n\n\t\tObject.defineProperty(this, 'fetch', {\n\t\t\tvalue: fetch,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t})\n\n\t\treturn fetch\n\t}\n\n\t/**\n\t * Custom handle written by adapter\n\t */\n\tprotected _handle?(...a: unknown[]): unknown\n\n\tprotected handleError = async (\n\t\tcontext: Partial<\n\t\t\tContext<\n\t\t\t\tMergeSchema<\n\t\t\t\t\tMetadata['schema'],\n\t\t\t\t\tMergeSchema<Ephemeral['schema'], Volatile['schema']>\n\t\t\t\t> &\n\t\t\t\t\tMetadata['standaloneSchema'] &\n\t\t\t\t\tEphemeral['standaloneSchema'] &\n\t\t\t\t\tVolatile['standaloneSchema'],\n\t\t\t\tSingleton & {\n\t\t\t\t\tderive: Ephemeral['derive'] & Volatile['derive']\n\t\t\t\t\tresolve: Ephemeral['resolve'] & Volatile['resolve']\n\t\t\t\t},\n\t\t\t\tBasePath\n\t\t\t>\n\t\t> & {\n\t\t\trequest: Request\n\t\t},\n\t\terror:\n\t\t\t| Error\n\t\t\t| ValidationError\n\t\t\t| ParseError\n\t\t\t| NotFoundError\n\t\t\t| InternalServerError\n\t) => {\n\t\treturn (this.handleError = this.config.aot\n\t\t\t? composeErrorHandler(this)\n\t\t\t: createDynamicErrorHandler(this))(context, error)\n\t}\n\n\t/**\n\t * ### listen\n\t * Assign current instance to port and start serving\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * new Elysia()\n\t *     .get(\"/\", () => 'hi')\n\t *     .listen(3000)\n\t * ```\n\t */\n\tlisten = (\n\t\toptions: string | number | Partial<Serve>,\n\t\tcallback?: ListenCallback\n\t) => {\n\t\tthis['~adapter'].listen(this)(options, callback)\n\n\t\treturn this\n\t}\n\n\t/**\n\t * ### stop\n\t * Stop server from serving\n\t *\n\t * ---\n\t * @example\n\t * ```typescript\n\t * const app = new Elysia()\n\t *     .get(\"/\", () => 'hi')\n\t *     .listen(3000)\n\t *\n\t * // Sometime later\n\t * app.stop()\n\t * ```\n\t *\n\t * @example\n\t * ```typescript\n\t * const app = new Elysia()\n\t *     .get(\"/\", () => 'hi')\n\t *     .listen(3000)\n\t *\n\t * app.stop(true) // Abruptly any requests inflight\n\t * ```\n\t */\n\tstop = async (closeActiveConnections?: boolean) => {\n\t\tawait this['~adapter'].stop?.(this, closeActiveConnections)\n\n\t\treturn this\n\t};\n\n\t[Symbol.dispose] = () => {\n\t\tif (this.server) this.stop()\n\t}\n\n\t/**\n\t * Wait until all lazy loaded modules all load is fully\n\t */\n\tget modules() {\n\t\treturn this.promisedModules\n\t}\n}\n\nexport { Elysia }\n\nexport { t } from './type-system'\nexport { validationDetail, fileType } from './type-system/utils'\nexport type {\n\tElysiaTypeCustomError,\n\tElysiaTypeCustomErrorCallback\n} from './type-system/types'\n\nexport { serializeCookie, Cookie, type CookieOptions } from './cookies'\nexport type { Context, PreContext, ErrorContext } from './context'\nexport {\n\tELYSIA_TRACE,\n\ttype TraceEvent,\n\ttype TraceListener,\n\ttype TraceHandler,\n\ttype TraceProcess,\n\ttype TraceStream\n} from './trace'\n\nexport { getSchemaValidator, getResponseSchemaValidator } from './schema'\nexport { replaceSchemaTypeFromManyOptions as replaceSchemaType } from './replace-schema'\n\nexport {\n\tmergeHook,\n\tmergeObjectArray,\n\tredirect,\n\tStatusMap,\n\tInvertedStatusMap,\n\tform,\n\treplaceUrlPath,\n\tchecksum,\n\tcloneInference,\n\tdeduplicateChecksum,\n\tELYSIA_FORM_DATA,\n\tELYSIA_REQUEST_ID,\n\tsse\n} from './utils'\n\nexport {\n\tstatus,\n\tmapValueError,\n\tParseError,\n\tNotFoundError,\n\tValidationError,\n\tInvalidFileType,\n\tInternalServerError,\n\tInvalidCookieSignature,\n\tERROR_CODE,\n\tElysiaStatus,\n\tElysiaCustomStatusResponse,\n\ttype SelectiveStatus\n} from './error'\n\nexport type {\n\tEphemeralType,\n\tCreateEden,\n\tComposeElysiaResponse,\n\tElysiaConfig,\n\tSingletonBase,\n\tDefinitionBase,\n\tRouteBase,\n\tHandler,\n\tComposedHandler,\n\tInputSchema,\n\tLocalHook,\n\tMergeSchema,\n\tRouteSchema,\n\tUnwrapRoute,\n\tInternalRoute,\n\tHTTPMethod,\n\tSchemaValidator,\n\tVoidHandler,\n\tPreHandler,\n\tBodyHandler,\n\tOptionalHandler,\n\tAfterResponseHandler,\n\tErrorHandler,\n\tLifeCycleEvent,\n\tLifeCycleStore,\n\tLifeCycleType,\n\tMaybePromise,\n\tUnwrapSchema,\n\tAnySchema,\n\tModelsToTypes,\n\tChecksum,\n\tDocumentDecoration,\n\tInferContext,\n\tInferHandler,\n\tResolvePath,\n\tMapResponse,\n\tBaseMacro,\n\tMacroManager,\n\tMacroToProperty,\n\tMergeElysiaInstances,\n\tMaybeArray,\n\tModelValidator,\n\tMetadataBase,\n\tUnwrapBodySchema,\n\tUnwrapGroupGuardRoute,\n\tModelValidatorError,\n\tExcludeElysiaResponse,\n\tSSEPayload,\n\tStandaloneInputSchema,\n\tMergeStandaloneSchema,\n\tMergeTypeModule,\n\tGracefulHandler,\n\tAfterHandler,\n\tInlineHandler,\n\tResolveHandler,\n\tTransformHandler,\n\tHTTPHeaders,\n\tEmptyRouteSchema,\n\tExtractErrorFromHandle\n} from './types'\n\nexport { env } from './universal/env'\nexport { file, ElysiaFile } from './universal/file'\nexport type { ElysiaAdapter } from './adapter'\n\nexport { TypeSystemPolicy } from '@sinclair/typebox/system'\nexport type { Static, TSchema } from '@sinclair/typebox'\n"
  },
  {
    "path": "src/manifest.ts",
    "content": "// import { stat, mkdir, writeFile } from 'fs/promises'\n// import type { AnyElysia } from '.'\n// import { checksum } from './utils'\n\n// const mkdirIfNotExists = async (path: string) => {\n// \tif (\n// \t\tawait stat(path)\n// \t\t\t.then(() => false)\n// \t\t\t.catch(() => true)\n// \t)\n// \t\tawait mkdir(path)\n// }\n\n// export const manifest = async (app: AnyElysia) => {\n// \tawait app.modules\n\n// \tapp.compile()\n\n// \tconsole.log(process.cwd())\n\n// \tawait mkdirIfNotExists('.elysia')\n// \tawait mkdirIfNotExists('.elysia/routes')\n\n// \tconst ops = <Promise<void>[]>[]\n\n// \tlet appChecksum = 0\n\n// \tfor (const route of app.routes) {\n// \t\tconst { path, method } = route\n\n// \t\tconst code = route.compile().toString()\n// \t\tconst name = `.elysia/routes/${path === '' ? 'index' : path.endsWith('/') ? path.replace(/\\//g, '_') + 'index' : path.replace(/\\//g, '_')}.${method.toLowerCase()}.js`\n\n// \t\tappChecksum = checksum(appChecksum + path + method + code)\n\n// \t\tops.push(writeFile(name, '//' + checksum(code) + '\\n' + code))\n// \t}\n\n// \tconst code = app.fetch.toString()\n// \tappChecksum = checksum(appChecksum + code)\n\n// \tops.push(writeFile(`.elysia/handler.js`, '//' + appChecksum + '\\n' + code))\n\n// \tawait Promise.all(ops)\n\n// \tconsole.log('DONE')\n// }\n"
  },
  {
    "path": "src/parse-query.ts",
    "content": "import decode from 'fast-decode-uri-component'\n\n// bit flags\nconst KEY_HAS_PLUS = 1\nconst KEY_NEEDS_DECODE = 2\nconst VALUE_HAS_PLUS = 4\nconst VALUE_NEEDS_DECODE = 8\n\n// Parse query without array\nexport function parseQueryFromURL(\n\tinput: string,\n\tstartIndex: number = 0,\n\tarray?: { [key: string]: 1 },\n\tobject?: { [key: string]: 1 }\n): Record<string, string> {\n\tconst result = Object.create(null)\n\n\tlet flags = 0\n\n\tconst inputLength = input.length\n\tlet startingIndex = startIndex - 1\n\tlet equalityIndex = startingIndex\n\n\tfor (let i = 0; i < inputLength; i++)\n\t\tswitch (input.charCodeAt(i)) {\n\t\t\t// '&'\n\t\t\tcase 38:\n\t\t\t\tprocessKeyValuePair(input, i)\n\n\t\t\t\t// Reset state variables\n\t\t\t\tstartingIndex = i\n\t\t\t\tequalityIndex = i\n\t\t\t\tflags = 0\n\n\t\t\t\tbreak\n\n\t\t\t// '='\n\t\t\tcase 61:\n\t\t\t\tif (equalityIndex <= startingIndex) equalityIndex = i\n\t\t\t\t// If '=' character occurs again, we should decode the input\n\t\t\t\telse flags |= VALUE_NEEDS_DECODE\n\n\t\t\t\tbreak\n\n\t\t\t// '+'\n\t\t\tcase 43:\n\t\t\t\tif (equalityIndex > startingIndex) flags |= VALUE_HAS_PLUS\n\t\t\t\telse flags |= KEY_HAS_PLUS\n\n\t\t\t\tbreak\n\n\t\t\t// '%'\n\t\t\tcase 37:\n\t\t\t\tif (equalityIndex > startingIndex) flags |= VALUE_NEEDS_DECODE\n\t\t\t\telse flags |= KEY_NEEDS_DECODE\n\n\t\t\t\tbreak\n\t\t}\n\n\t// Process the last pair if needed\n\tif (startingIndex < inputLength) processKeyValuePair(input, inputLength)\n\n\treturn result\n\n\tfunction processKeyValuePair(input: string, endIndex: number) {\n\t\tconst hasBothKeyValuePair = equalityIndex > startingIndex\n\t\tconst effectiveEqualityIndex = hasBothKeyValuePair\n\t\t\t? equalityIndex\n\t\t\t: endIndex\n\n\t\tconst keySlice = input.slice(startingIndex + 1, effectiveEqualityIndex)\n\n\t\t// Skip processing if key is empty\n\t\tif (!hasBothKeyValuePair && keySlice.length === 0) return\n\n\t\tlet finalKey = keySlice\n\t\tif (flags & KEY_HAS_PLUS) finalKey = finalKey.replace(/\\+/g, ' ')\n\t\tif (flags & KEY_NEEDS_DECODE) finalKey = decode(finalKey) || finalKey\n\n\t\tlet finalValue = ''\n\t\tif (hasBothKeyValuePair) {\n\t\t\tlet valueSlice = input.slice(equalityIndex + 1, endIndex)\n\t\t\tif (flags & VALUE_HAS_PLUS)\n\t\t\t\tvalueSlice = valueSlice.replace(/\\+/g, ' ')\n\t\t\tif (flags & VALUE_NEEDS_DECODE)\n\t\t\t\tvalueSlice = decode(valueSlice) || valueSlice\n\t\t\tfinalValue = valueSlice\n\t\t}\n\n\t\tconst currentValue = result[finalKey]\n\n\t\tif (array && array?.[finalKey]) {\n\t\t\tif (finalValue.charCodeAt(0) === 91) {\n\t\t\t\tif (object && object?.[finalKey])\n\t\t\t\t\tfinalValue = JSON.parse(finalValue) as any\n\t\t\t\telse finalValue = finalValue.slice(1, -1).split(',') as any\n\n\t\t\t\tif (currentValue === undefined) result[finalKey] = finalValue\n\t\t\t\telse if (Array.isArray(currentValue))\n\t\t\t\t\tcurrentValue.push(...finalValue)\n\t\t\t\telse {\n\t\t\t\t\tresult[finalKey] = finalValue\n\t\t\t\t\tresult[finalKey].unshift(currentValue)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (currentValue === undefined) result[finalKey] = finalValue\n\t\t\t\telse if (Array.isArray(currentValue))\n\t\t\t\t\tcurrentValue.push(finalValue)\n\t\t\t\telse result[finalKey] = [currentValue, finalValue]\n\t\t\t}\n\t\t} else {\n\t\t\tresult[finalKey] = finalValue\n\t\t}\n\t}\n}\n\n/**\n * @callback parse\n * @param {string} input\n */\nexport function parseQueryStandardSchema(\n\tinput: string,\n\tstartIndex: number = 0\n) {\n\tconst result = Object.create(null) as Record<string, string | string[]>\n\n\tlet flags = 0\n\n\tconst inputLength = input.length\n\tlet startingIndex = startIndex - 1\n\tlet equalityIndex = startingIndex\n\n\tfor (let i = 0; i < inputLength; i++)\n\t\tswitch (input.charCodeAt(i)) {\n\t\t\t// '&'\n\t\t\tcase 38:\n\t\t\t\tprocessKeyValuePair(input, i)\n\n\t\t\t\t// Reset state variables\n\t\t\t\tstartingIndex = i\n\t\t\t\tequalityIndex = i\n\t\t\t\tflags = 0\n\n\t\t\t\tbreak\n\n\t\t\t// '='\n\t\t\tcase 61:\n\t\t\t\tif (equalityIndex <= startingIndex) equalityIndex = i\n\t\t\t\t// If '=' character occurs again, we should decode the input\n\t\t\t\telse flags |= VALUE_NEEDS_DECODE\n\n\t\t\t\tbreak\n\n\t\t\t// '+'\n\t\t\tcase 43:\n\t\t\t\tif (equalityIndex > startingIndex) flags |= VALUE_HAS_PLUS\n\t\t\t\telse flags |= KEY_HAS_PLUS\n\n\t\t\t\tbreak\n\n\t\t\t// '%'\n\t\t\tcase 37:\n\t\t\t\tif (equalityIndex > startingIndex) flags |= VALUE_NEEDS_DECODE\n\t\t\t\telse flags |= KEY_NEEDS_DECODE\n\n\t\t\t\tbreak\n\t\t}\n\n\t// Process the last pair if needed\n\tif (startingIndex < inputLength) processKeyValuePair(input, inputLength)\n\n\treturn result\n\n\tfunction processKeyValuePair(input: string, endIndex: number) {\n\t\tconst hasBothKeyValuePair = equalityIndex > startingIndex\n\t\tconst effectiveEqualityIndex = hasBothKeyValuePair\n\t\t\t? equalityIndex\n\t\t\t: endIndex\n\n\t\tconst keySlice = input.slice(startingIndex + 1, effectiveEqualityIndex)\n\n\t\t// Skip processing if key is empty\n\t\tif (!hasBothKeyValuePair && keySlice.length === 0) return\n\n\t\tlet finalKey = keySlice\n\t\tif (flags & KEY_HAS_PLUS) finalKey = finalKey.replace(/\\+/g, ' ')\n\t\tif (flags & KEY_NEEDS_DECODE) finalKey = decode(finalKey) || finalKey\n\n\t\tlet finalValue = ''\n\t\tif (hasBothKeyValuePair) {\n\t\t\tlet valueSlice = input.slice(equalityIndex + 1, endIndex)\n\t\t\tif (flags & VALUE_HAS_PLUS)\n\t\t\t\tvalueSlice = valueSlice.replace(/\\+/g, ' ')\n\t\t\tif (flags & VALUE_NEEDS_DECODE)\n\t\t\t\tvalueSlice = decode(valueSlice) || valueSlice\n\t\t\tfinalValue = valueSlice\n\t\t}\n\n\t\tconst currentValue = result[finalKey]\n\n\t\tif (\n\t\t\tfinalValue.charCodeAt(0) === 91 &&\n\t\t\tfinalValue.charCodeAt(finalValue.length - 1) === 93\n\t\t) {\n\t\t\ttry {\n\t\t\t\t// @ts-ignore\n\t\t\t\tfinalValue = JSON.parse(finalValue)\n\t\t\t} catch {\n\t\t\t\t// If JSON parsing fails, treat it as a regular string\n\t\t\t}\n\n\t\t\tif (currentValue === undefined) result[finalKey] = finalValue\n\t\t\telse if (Array.isArray(currentValue)) currentValue.push(finalValue)\n\t\t\telse result[finalKey] = [currentValue, finalValue]\n\t\t} else if (\n\t\t\tfinalValue.charCodeAt(0) === 123 &&\n\t\t\tfinalValue.charCodeAt(finalValue.length - 1) === 125\n\t\t) {\n\t\t\ttry {\n\t\t\t\t// @ts-ignore\n\t\t\t\tfinalValue = JSON.parse(finalValue)\n\t\t\t} catch {\n\t\t\t\t// If JSON parsing fails, treat it as a regular string\n\t\t\t}\n\n\t\t\tif (currentValue === undefined) result[finalKey] = finalValue\n\t\t\telse if (Array.isArray(currentValue)) currentValue.push(finalValue)\n\t\t\telse result[finalKey] = [currentValue, finalValue]\n\t\t} else {\n\t\t\tif (finalValue.includes(','))\n\t\t\t\t// @ts-ignore\n\t\t\t\tfinalValue = finalValue.split(',')\n\n\t\t\tif (currentValue === undefined) result[finalKey] = finalValue\n\t\t\telse if (Array.isArray(currentValue)) currentValue.push(finalValue)\n\t\t\telse result[finalKey] = [currentValue, finalValue]\n\t\t}\n\t}\n}\n\n/**\n * @callback parse\n * @param {string} input\n */\nexport function parseQuery(input: string) {\n\tconst result = Object.create(null) as Record<string, string | string[]>\n\n\tlet flags = 0\n\n\tconst inputLength = input.length\n\tlet startingIndex = -1\n\tlet equalityIndex = -1\n\n\tfor (let i = 0; i < inputLength; i++)\n\t\tswitch (input.charCodeAt(i)) {\n\t\t\t// '&'\n\t\t\tcase 38:\n\t\t\t\tprocessKeyValuePair(input, i)\n\n\t\t\t\t// Reset state variables\n\t\t\t\tstartingIndex = i\n\t\t\t\tequalityIndex = i\n\t\t\t\tflags = 0\n\n\t\t\t\tbreak\n\n\t\t\t// '='\n\t\t\tcase 61:\n\t\t\t\tif (equalityIndex <= startingIndex) equalityIndex = i\n\t\t\t\t// If '=' character occurs again, we should decode the input\n\t\t\t\telse flags |= VALUE_NEEDS_DECODE\n\n\t\t\t\tbreak\n\n\t\t\t// '+'\n\t\t\tcase 43:\n\t\t\t\tif (equalityIndex > startingIndex) flags |= VALUE_HAS_PLUS\n\t\t\t\telse flags |= KEY_HAS_PLUS\n\n\t\t\t\tbreak\n\n\t\t\t// '%'\n\t\t\tcase 37:\n\t\t\t\tif (equalityIndex > startingIndex) flags |= VALUE_NEEDS_DECODE\n\t\t\t\telse flags |= KEY_NEEDS_DECODE\n\n\t\t\t\tbreak\n\t\t}\n\n\t// Process the last pair if needed\n\tif (startingIndex < inputLength) processKeyValuePair(input, inputLength)\n\n\treturn result\n\n\tfunction processKeyValuePair(input: string, endIndex: number) {\n\t\tconst hasBothKeyValuePair = equalityIndex > startingIndex\n\t\tconst effectiveEqualityIndex = hasBothKeyValuePair\n\t\t\t? equalityIndex\n\t\t\t: endIndex\n\n\t\tconst keySlice = input.slice(startingIndex + 1, effectiveEqualityIndex)\n\n\t\t// Skip processing if key is empty\n\t\tif (!hasBothKeyValuePair && keySlice.length === 0) return\n\n\t\tlet finalKey = keySlice\n\t\tif (flags & KEY_HAS_PLUS) finalKey = finalKey.replace(/\\+/g, ' ')\n\t\tif (flags & KEY_NEEDS_DECODE) finalKey = decode(finalKey) || finalKey\n\n\t\tlet finalValue = ''\n\t\tif (hasBothKeyValuePair) {\n\t\t\tlet valueSlice = input.slice(equalityIndex + 1, endIndex)\n\t\t\tif (flags & VALUE_HAS_PLUS)\n\t\t\t\tvalueSlice = valueSlice.replace(/\\+/g, ' ')\n\t\t\tif (flags & VALUE_NEEDS_DECODE)\n\t\t\t\tvalueSlice = decode(valueSlice) || valueSlice\n\t\t\tfinalValue = valueSlice\n\t\t}\n\n\t\tconst currentValue = result[finalKey]\n\t\tif (currentValue === undefined) result[finalKey] = finalValue\n\t\telse if (Array.isArray(currentValue)) currentValue.push(finalValue)\n\t\telse result[finalKey] = [currentValue, finalValue]\n\t}\n}\n"
  },
  {
    "path": "src/replace-schema.ts",
    "content": "import { Kind, type TAnySchema, type TSchema } from \"@sinclair/typebox\";\nimport { t } from \"./type-system\";\nimport type { MaybeArray } from \"./types\";\n\nexport interface ReplaceSchemaTypeOptions {\n\tfrom: TSchema;\n\tto(schema: TSchema): TSchema | null;\n\texcludeRoot?: boolean;\n\trootOnly?: boolean;\n\toriginal?: TAnySchema;\n\t/**\n\t * Traverse until object is found except root object\n\t **/\n\tuntilObjectFound?: boolean;\n\t/**\n\t * Only replace first object type, can be paired with excludeRoot\n\t **/\n\tonlyFirst?: \"object\" | \"array\" | (string & {});\n}\n\n/**\n * Replace schema types with custom transformation\n *\n * @param schema - The schema to transform\n * @param options - Transformation options (single or array)\n * @returns Transformed schema\n *\n * @example\n * // Transform Object to ObjectString\n * replaceSchemaType(schema, {\n *   from: t.Object({}),\n *   to: (s) => t.ObjectString(s.properties || {}, s),\n *   excludeRoot: true,\n *   onlyFirst: 'object'\n * })\n */\nexport const replaceSchemaTypeFromManyOptions = (\n\tschema: TSchema,\n\toptions: MaybeArray<ReplaceSchemaTypeOptions>,\n): TSchema => {\n\tif (Array.isArray(options)) {\n\t\tlet result = schema;\n\t\tfor (const option of options) {\n\t\t\tresult = replaceSchemaTypeFromOption(result, option);\n\t\t}\n\t\treturn result;\n\t}\n\n\treturn replaceSchemaTypeFromOption(schema, options);\n};\n\nconst replaceSchemaTypeFromOption = (\n\tschema: TSchema,\n\toption: ReplaceSchemaTypeOptions,\n): TSchema => {\n\tif (option.rootOnly && option.excludeRoot) {\n\t\tthrow new Error(\"Can't set both rootOnly and excludeRoot\");\n\t}\n\tif (option.rootOnly && option.onlyFirst) {\n\t\tthrow new Error(\"Can't set both rootOnly and onlyFirst\");\n\t}\n\tif (option.rootOnly && option.untilObjectFound) {\n\t\tthrow new Error(\"Can't set both rootOnly and untilObjectFound\");\n\t}\n\n\ttype WalkProps = { s: TSchema; isRoot: boolean; treeLvl: number };\n\tconst walk = ({ s, isRoot, treeLvl }: WalkProps): TSchema => {\n\t\tif (!s) return s;\n\t\t// console.log(\"walk iteration\", { s, isRoot, treeLvl, transformTo: option.to.toString() })\n\n\t\tconst skipRoot = isRoot && option.excludeRoot;\n\t\tconst fromKind = option.from[Kind];\n\n\t\t// Double-wrapping check\n\t\tif (s.elysiaMeta) {\n\t\t\tconst fromElysiaMeta = option.from.elysiaMeta;\n\t\t\tif (fromElysiaMeta === s.elysiaMeta && !skipRoot) {\n\t\t\t\treturn option.to(s) as TSchema;\n\t\t\t}\n\t\t\treturn s;\n\t\t}\n\n\t\tconst shouldTransform = fromKind && s[Kind] === fromKind;\n\t\tif (!skipRoot && option.onlyFirst && s.type === option.onlyFirst) {\n\t\t\tif (shouldTransform) {\n\t\t\t\treturn option.to(s) as TSchema;\n\t\t\t}\n            return s;\n\t\t}\n\n\t\tif (isRoot && option.rootOnly) {\n\t\t\tif (shouldTransform) {\n\t\t\t\treturn option.to(s) as TSchema;\n\t\t\t}\n\t\t\treturn s;\n\t\t}\n\n\t\tif (!isRoot && option.untilObjectFound && s.type === \"object\") {\n\t\t\treturn s;\n\t\t}\n\n\t\tconst newWalkInput = { isRoot: false, treeLvl: treeLvl + 1 };\n\t\tconst withTransformedChildren = { ...s };\n\n\t\tif (s.oneOf) {\n\t\t\twithTransformedChildren.oneOf = s.oneOf.map((x: TSchema) =>\n\t\t\t\twalk({ ...newWalkInput, s: x }),\n\t\t\t);\n\t\t}\n\t\tif (s.anyOf) {\n\t\t\twithTransformedChildren.anyOf = s.anyOf.map((x: TSchema) =>\n\t\t\t\twalk({ ...newWalkInput, s: x }),\n\t\t\t);\n\t\t}\n\t\tif (s.allOf) {\n\t\t\twithTransformedChildren.allOf = s.allOf.map((x: TSchema) =>\n\t\t\t\twalk({ ...newWalkInput, s: x }),\n\t\t\t);\n\t\t}\n\t\tif (s.not) {\n\t\t\twithTransformedChildren.not = walk({ ...newWalkInput, s: s.not });\n\t\t}\n\n\t\tif (s.properties) {\n\t\t\twithTransformedChildren.properties = {};\n\t\t\tfor (const [k, v] of Object.entries(s.properties)) {\n\t\t\t\twithTransformedChildren.properties[k] = walk({\n\t\t\t\t\t...newWalkInput,\n\t\t\t\t\ts: v as TSchema,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (s.items) {\n\t\t\tconst items = s.items;\n\t\t\twithTransformedChildren.items = Array.isArray(items)\n\t\t\t\t? items.map((x: TSchema) => walk({ ...newWalkInput, s: x }))\n\t\t\t\t: walk({ ...newWalkInput, s: items as TSchema });\n\t\t}\n\n\t\t// Transform THIS node (with children already transformed)\n\t\tconst shouldTransformThis =\n\t\t\t!skipRoot && fromKind && withTransformedChildren[Kind] === fromKind;\n\t\tif (shouldTransformThis) {\n\t\t\treturn option.to(withTransformedChildren) as TSchema;\n\t\t}\n\n\t\treturn withTransformedChildren;\n\t};\n\n\treturn walk({ s: schema, isRoot: true, treeLvl: 0 });\n};\n\n/**\n * Helper: Extract plain Object from ObjectString\n *\n * @example\n * ObjectString structure:\n * {\n *   elysiaMeta: \"ObjectString\",\n *   anyOf: [\n *     { type: \"string\", format: \"ObjectString\" },  // ← String branch\n *     { type: \"object\", properties: {...} }        // ← Object branch (we want this)\n *   ]\n * }\n * ArrayString structure:\n * {\n *   elysiaMeta: \"ArrayString\",\n *   anyOf: [\n *     { type: \"string\", format: \"ArrayString\" },  // ← String branch\n *     { type: \"array\", items: {...} }             // ← Array branch (we want this)\n *   ]\n * }\n */\nexport const revertObjAndArrStr = (schema: TSchema): TSchema => {\n\tif (schema.elysiaMeta !== \"ObjectString\" && schema.elysiaMeta !== \"ArrayString\")\n\t    return schema;\n\n\tconst anyOf = schema.anyOf;\n\tif (!anyOf?.[1]) return schema;\n\n\t// anyOf[1] is the object branch (already clean, no elysiaMeta)\n\treturn anyOf[1];\n};\n\nlet _stringToStructureCoercions: ReplaceSchemaTypeOptions[];\n\nexport const stringToStructureCoercions = () => {\n\tif (!_stringToStructureCoercions) {\n\t\t_stringToStructureCoercions = [\n\t\t\t{\n\t\t\t\tfrom: t.Object({}),\n\t\t\t\tto: (schema) => t.ObjectString(schema.properties || {}, schema),\n\t\t\t\texcludeRoot: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tfrom: t.Array(t.Any()),\n\t\t\t\tto: (schema) => t.ArrayString(schema.items || t.Any(), schema),\n\t\t\t},\n\t\t] satisfies ReplaceSchemaTypeOptions[];\n\t}\n\n\treturn _stringToStructureCoercions;\n};\n\nlet _queryCoercions: ReplaceSchemaTypeOptions[];\n\nexport const queryCoercions = () => {\n\tif (!_queryCoercions) {\n\t\t_queryCoercions = [\n\t\t\t{\n\t\t\t\tfrom: t.Object({}),\n\t\t\t\tto: (schema) => t.ObjectString(schema.properties ?? {}, schema),\n\t\t\t\texcludeRoot: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tfrom: t.Array(t.Any()),\n\t\t\t\tto: (schema) => t.ArrayQuery(schema.items ?? t.Any(), schema),\n\t\t\t},\n\t\t] satisfies ReplaceSchemaTypeOptions[];\n\t}\n\n\treturn _queryCoercions;\n};\n\nlet _coercePrimitiveRoot: ReplaceSchemaTypeOptions[];\n\nexport const coercePrimitiveRoot = () => {\n\tif (!_coercePrimitiveRoot)\n\t\t_coercePrimitiveRoot = [\n\t\t\t{\n\t\t\t\tfrom: t.Number(),\n\t\t\t\tto: (schema) => t.Numeric(schema),\n\t\t\t\trootOnly: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tfrom: t.Boolean(),\n\t\t\t\tto: (schema) => t.BooleanString(schema),\n\t\t\t\trootOnly: true,\n\t\t\t},\n\t\t] satisfies ReplaceSchemaTypeOptions[];\n\n\treturn _coercePrimitiveRoot;\n};\n\nlet _coerceFormData: ReplaceSchemaTypeOptions[];\n\nexport const coerceFormData = () => {\n\tif (!_coerceFormData)\n\t\t_coerceFormData = [\n\t\t\t{\n\t\t\t\tfrom: t.Object({}),\n\t\t\t\tto: (schema) => t.ObjectString(schema.properties ?? {}, schema),\n\t\t\t\tonlyFirst: 'object',\n\t\t\t\texcludeRoot: true\n\t\t\t},\n\t\t\t{\n\t\t\t\tfrom: t.Array(t.Any()),\n\t\t\t\tto: (schema) => t.ArrayString(schema.items ?? t.Any(), schema),\n\t\t\t\tonlyFirst: 'array',\n\t\t\t\texcludeRoot: true\n\t\t\t},\n\t\t] satisfies ReplaceSchemaTypeOptions[];\n\n\treturn _coerceFormData;\n};\n"
  },
  {
    "path": "src/schema.ts",
    "content": "/* eslint-disable sonarjs/no-duplicate-string */\nimport {\n\tKind,\n\tOptionalKind,\n\tTModule,\n\tTObject,\n\tTransformKind,\n\tTSchema,\n\ttype TAnySchema\n} from '@sinclair/typebox'\nimport { Value } from '@sinclair/typebox/value'\nimport { TypeCompiler } from '@sinclair/typebox/compiler'\n\nimport {\n\tcreateMirror,\n\ttype Instruction as ExactMirrorInstruction\n} from 'exact-mirror'\n\nimport { t, type TypeCheck } from './type-system'\n\nimport { mergeCookie, mergeDeep, randomId } from './utils'\nimport { mapValueError } from './error'\n\nimport type { CookieOptions } from './cookies'\nimport type {\n\tAnySchema,\n\tElysiaConfig,\n\tInputSchema,\n\tIsAny,\n\tMaybeArray,\n\tStandaloneInputSchema,\n\tStandardSchemaV1LikeValidate,\n\tUnwrapSchema\n} from './types'\n\nimport type { StandardSchemaV1Like } from './types'\nimport {\n\treplaceSchemaTypeFromManyOptions,\n\ttype ReplaceSchemaTypeOptions,\n\tstringToStructureCoercions\n} from './replace-schema'\n\ntype MapValueError = ReturnType<typeof mapValueError>\n\nexport interface ElysiaTypeCheck<T extends AnySchema>\n\textends Omit<TypeCheck<TSchema>, 'schema' | 'Check'> {\n\tprovider: 'typebox' | 'standard'\n\tschema: T\n\tconfig: Object\n\tCheck(value: unknown): T extends TSchema\n\t\t? boolean\n\t\t:\n\t\t\t\t| {\n\t\t\t\t\t\tvalue: UnwrapSchema<T>\n\t\t\t\t  }\n\t\t\t\t| { issues: unknown[] }\n\tClean?(v: unknown): UnwrapSchema<T>\n\tparse(v: unknown): UnwrapSchema<T>\n\tsafeParse(v: unknown):\n\t\t| { success: true; data: UnwrapSchema<T>; error: null }\n\t\t| {\n\t\t\t\tsuccess: false\n\t\t\t\tdata: null\n\t\t\t\terror: string | undefined\n\t\t\t\terrors: MapValueError[]\n\t\t  }\n\thasAdditionalProperties: boolean\n\t'~hasAdditionalProperties'?: boolean\n\thasDefault: boolean\n\t'~hasDefault'?: boolean\n\tisOptional: boolean\n\t'~isOptional'?: boolean\n\thasTransform: boolean\n\t'~hasTransform'?: boolean\n\thasRef: boolean\n\t'~hasRef'?: boolean\n}\n\nexport const isOptional = (\n\tschema?: TSchema | TypeCheck<any> | ElysiaTypeCheck<any>\n) => {\n\tif (!schema) return false\n\n\t// @ts-ignore\n\tif (schema?.[Kind] === 'Import' && schema.References)\n\t\treturn schema.References().some(isOptional as any)\n\n\t// @ts-expect-error private property\n\tif (schema.schema)\n\t\t// @ts-expect-error private property\n\t\tschema = schema.schema\n\n\treturn !!schema && OptionalKind in schema\n}\n\nexport const hasAdditionalProperties = (\n\t_schema: TAnySchema | TypeCheck<any> | ElysiaTypeCheck<any>\n): boolean => {\n\tif (!_schema) return false\n\n\t// @ts-expect-error private property\n\tconst schema: TAnySchema = (_schema as TypeCheck<any>)?.schema ?? _schema\n\n\tif (schema[Kind] === 'Import' && _schema.References)\n\t\treturn _schema.References().some(hasAdditionalProperties)\n\n\tif (schema.anyOf) return schema.anyOf.some(hasAdditionalProperties)\n\tif (schema.someOf) return schema.someOf.some(hasAdditionalProperties)\n\tif (schema.allOf) return schema.allOf.some(hasAdditionalProperties)\n\tif (schema.not) return schema.not.some(hasAdditionalProperties)\n\n\tif (schema.type === 'object') {\n\t\tconst properties = schema.properties as Record<string, TAnySchema>\n\n\t\tif ('additionalProperties' in schema) return schema.additionalProperties\n\t\tif ('patternProperties' in schema) return false\n\n\t\tfor (const key of Object.keys(properties)) {\n\t\t\tconst property = properties[key]\n\n\t\t\tif (property.type === 'object') {\n\t\t\t\tif (hasAdditionalProperties(property)) return true\n\t\t\t} else if (property.anyOf) {\n\t\t\t\tfor (let i = 0; i < property.anyOf.length; i++)\n\t\t\t\t\tif (hasAdditionalProperties(property.anyOf[i])) return true\n\t\t\t}\n\n\t\t\treturn property.additionalProperties\n\t\t}\n\n\t\treturn false\n\t}\n\n\tif (schema.type === 'array' && schema.items && !Array.isArray(schema.items))\n\t\treturn hasAdditionalProperties(schema.items)\n\n\treturn false\n}\n\n/**\n * Resolve a schema that might be a model reference (string) to the actual schema\n */\nexport const resolveSchema = (\n\tschema: TAnySchema | string | undefined,\n\tmodels?: Record<string, TAnySchema | StandardSchemaV1Like>,\n\tmodules?: TModule<any, any>\n): TAnySchema | StandardSchemaV1Like | undefined => {\n\tif (!schema) return undefined\n\tif (typeof schema !== 'string') return schema\n\n\t// Check modules first (higher priority)\n\t// @ts-expect-error private property\n\tif (modules && schema in modules.$defs) {\n\t\treturn (modules as TModule<{}, {}>).Import(schema as never)\n\t}\n\n\t// Then check models\n\treturn models?.[schema]\n}\n\nexport const hasType = (type: string, schema: TAnySchema): boolean => {\n\tif (!schema) return false\n\n\tif (Kind in schema && schema[Kind] === type) return true\n\n\t// Handle Import/Ref schemas (unwrap)\n\tif (Kind in schema && schema[Kind] === 'Import') {\n\t\tif (schema.$defs && schema.$ref) {\n\t\t\tconst ref = schema.$ref.replace('#/$defs/', '')\n\t\t\tif (schema.$defs[ref]) {\n\t\t\t\treturn hasType(type, schema.$defs[ref])\n\t\t\t}\n\t\t}\n\t}\n\n\tif (schema.anyOf) return schema.anyOf.some((s: TSchema) => hasType(type, s))\n\tif (schema.oneOf) return schema.oneOf.some((s: TSchema) => hasType(type, s))\n\tif (schema.allOf) return schema.allOf.some((s: TSchema) => hasType(type, s))\n\n\tif (schema.type === 'array' && schema.items) {\n\t\tif (\n\t\t\ttype === 'Files' &&\n\t\t\tKind in schema.items &&\n\t\t\tschema.items[Kind] === 'File'\n\t\t) {\n\t\t\treturn true\n\t\t}\n\t\treturn hasType(type, schema.items)\n\t}\n\n\tif (schema.type === 'object') {\n\t\tconst properties = schema.properties as Record<string, TAnySchema>\n\t\tif (!properties) return false\n\n\t\tfor (const key of Object.keys(properties)) {\n\t\t\tif (hasType(type, properties[key])) return true\n\t\t}\n\t}\n\n\treturn false\n}\n\nexport const hasElysiaMeta = (meta: string, _schema: TAnySchema): boolean => {\n\tif (!_schema) return false\n\n\t// @ts-expect-error private property\n\tconst schema: TAnySchema = (_schema as TypeCheck<any>)?.schema ?? _schema\n\n\tif (schema.elysiaMeta === meta) return true\n\n\tif (schema[Kind] === 'Import' && _schema.References)\n\t\treturn _schema\n\t\t\t.References()\n\t\t\t.some((schema: TSchema) => hasElysiaMeta(meta, schema))\n\n\tif (schema.anyOf)\n\t\treturn schema.anyOf.some((schema: TSchema) =>\n\t\t\thasElysiaMeta(meta, schema)\n\t\t)\n\tif (schema.someOf)\n\t\treturn schema.someOf.some((schema: TSchema) =>\n\t\t\thasElysiaMeta(meta, schema)\n\t\t)\n\tif (schema.allOf)\n\t\treturn schema.allOf.some((schema: TSchema) =>\n\t\t\thasElysiaMeta(meta, schema)\n\t\t)\n\tif (schema.not)\n\t\treturn schema.not.some((schema: TSchema) => hasElysiaMeta(meta, schema))\n\n\tif (schema.type === 'object') {\n\t\tconst properties = schema.properties as Record<string, TAnySchema>\n\t\tif (!properties) return false\n\n\t\tfor (const key of Object.keys(properties)) {\n\t\t\tconst property = properties[key]\n\n\t\t\tif (property.type === 'object') {\n\t\t\t\tif (hasElysiaMeta(meta, property)) return true\n\t\t\t} else if (property.anyOf) {\n\t\t\t\tfor (let i = 0; i < property.anyOf.length; i++)\n\t\t\t\t\tif (hasElysiaMeta(meta, property.anyOf[i])) return true\n\t\t\t}\n\n\t\t\treturn schema.elysiaMeta === meta\n\t\t}\n\n\t\treturn false\n\t}\n\n\tif (schema.type === 'array' && schema.items && !Array.isArray(schema.items))\n\t\treturn hasElysiaMeta(meta, schema.items)\n\n\treturn false\n}\n\nexport const hasProperty = (\n\texpectedProperty: string,\n\t_schema: TAnySchema | TypeCheck<any> | ElysiaTypeCheck<any>\n): boolean => {\n\tif (!_schema) return false\n\n\t// @ts-expect-error private property\n\tconst schema = _schema.schema ?? _schema\n\n\tif (schema[Kind] === 'Import' && _schema.References)\n\t\treturn _schema\n\t\t\t.References()\n\t\t\t.some((schema: TAnySchema) => hasProperty(expectedProperty, schema))\n\n\tif (schema.anyOf)\n\t\treturn schema.anyOf.some((s: TSchema) =>\n\t\t\thasProperty(expectedProperty, s)\n\t\t)\n\tif (schema.allOf)\n\t\treturn schema.allOf.some((s: TSchema) =>\n\t\t\thasProperty(expectedProperty, s)\n\t\t)\n\tif (schema.oneOf)\n\t\treturn schema.oneOf.some((s: TSchema) =>\n\t\t\thasProperty(expectedProperty, s)\n\t\t)\n\n\tif (schema.type === 'object') {\n\t\tconst properties = schema.properties as Record<string, TAnySchema>\n\n\t\tif (!properties) return false\n\n\t\tfor (const key of Object.keys(properties)) {\n\t\t\tconst property = properties[key]\n\n\t\t\tif (expectedProperty in property) return true\n\n\t\t\tif (property.type === 'object') {\n\t\t\t\tif (hasProperty(expectedProperty, property)) return true\n\t\t\t} else if (property.anyOf)\n\t\t\t\tfor (let i = 0; i < property.anyOf.length; i++)\n\t\t\t\t\tif (hasProperty(expectedProperty, property.anyOf[i]))\n\t\t\t\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t}\n\n\treturn expectedProperty in schema\n}\n\nexport const hasRef = (schema: TAnySchema): boolean => {\n\tif (!schema) return false\n\n\tif (schema.oneOf)\n\t\tfor (let i = 0; i < schema.oneOf.length; i++)\n\t\t\tif (hasRef(schema.oneOf[i])) return true\n\n\tif (schema.anyOf)\n\t\tfor (let i = 0; i < schema.anyOf.length; i++)\n\t\t\tif (hasRef(schema.anyOf[i])) return true\n\n\tif (schema.oneOf)\n\t\tfor (let i = 0; i < schema.oneOf.length; i++)\n\t\t\tif (hasRef(schema.oneOf[i])) return true\n\n\tif (schema.allOf)\n\t\tfor (let i = 0; i < schema.allOf.length; i++)\n\t\t\tif (hasRef(schema.allOf[i])) return true\n\n\tif (schema.not && hasRef(schema.not)) return true\n\n\tif (schema.type === 'object' && schema.properties) {\n\t\tconst properties = schema.properties as Record<string, TAnySchema>\n\n\t\tfor (const key of Object.keys(properties)) {\n\t\t\tconst property = properties[key]\n\n\t\t\tif (hasRef(property)) return true\n\n\t\t\tif (\n\t\t\t\tproperty.type === 'array' &&\n\t\t\t\tproperty.items &&\n\t\t\t\thasRef(property.items)\n\t\t\t)\n\t\t\t\treturn true\n\t\t}\n\t}\n\n\tif (schema.type === 'array' && schema.items && hasRef(schema.items))\n\t\treturn true\n\n\treturn schema[Kind] === 'Ref' && '$ref' in schema\n}\n\nexport const hasTransform = (schema: TAnySchema): boolean => {\n\tif (!schema) return false\n\n\tif (\n\t\tschema.$ref &&\n\t\tschema.$defs &&\n\t\tschema.$ref in schema.$defs &&\n\t\thasTransform(schema.$defs[schema.$ref])\n\t)\n\t\treturn true\n\n\tif (schema.oneOf)\n\t\tfor (let i = 0; i < schema.oneOf.length; i++)\n\t\t\tif (hasTransform(schema.oneOf[i])) return true\n\n\tif (schema.anyOf)\n\t\tfor (let i = 0; i < schema.anyOf.length; i++)\n\t\t\tif (hasTransform(schema.anyOf[i])) return true\n\n\tif (schema.allOf)\n\t\tfor (let i = 0; i < schema.allOf.length; i++)\n\t\t\tif (hasTransform(schema.allOf[i])) return true\n\n\tif (schema.not && hasTransform(schema.not)) return true\n\n\tif (schema.type === 'object' && schema.properties) {\n\t\tconst properties = schema.properties as Record<string, TAnySchema>\n\n\t\tfor (const key of Object.keys(properties)) {\n\t\t\tconst property = properties[key]\n\n\t\t\tif (hasTransform(property)) return true\n\n\t\t\tif (\n\t\t\t\tproperty.type === 'array' &&\n\t\t\t\tproperty.items &&\n\t\t\t\thasTransform(property.items)\n\t\t\t)\n\t\t\t\treturn true\n\t\t}\n\t}\n\n\tif (schema.type === 'array' && schema.items && hasTransform(schema.items))\n\t\treturn true\n\n\treturn TransformKind in schema\n}\n\nconst createCleaner = (schema: TAnySchema) => (value: unknown) => {\n\tif (typeof value === 'object')\n\t\ttry {\n\t\t\treturn Value.Clean(schema, value)\n\t\t} catch {}\n\n\treturn value\n}\n\n// const caches = <Record<string, ElysiaTypeCheck<any>>>{}\n\nexport const getSchemaValidator = <T extends AnySchema | string | undefined>(\n\ts: T,\n\t{\n\t\tmodels = {},\n\t\tdynamic = false,\n\t\tmodules,\n\t\tnormalize = false,\n\t\tadditionalProperties = false,\n\t\tforceAdditionalProperties = false,\n\t\tcoerce = false,\n\t\tadditionalCoerce = [],\n\t\tvalidators,\n\t\tsanitize\n\t}: {\n\t\tmodels?: Record<string, AnySchema>\n\t\tmodules?: TModule<any, any>\n\t\tadditionalProperties?: boolean\n\t\tforceAdditionalProperties?: boolean\n\t\tdynamic?: boolean\n\t\tnormalize?: ElysiaConfig<''>['normalize']\n\t\tcoerce?: boolean\n\t\tadditionalCoerce?: MaybeArray<ReplaceSchemaTypeOptions>\n\t\tvalidators?: InputSchema['body'][]\n\t\tsanitize?: () => ExactMirrorInstruction['sanitize']\n\t} = {}\n): IsAny<T> extends true\n\t? ElysiaTypeCheck<TAnySchema>\n\t: undefined extends T\n\t\t? undefined\n\t\t: ElysiaTypeCheck<NonNullable<Exclude<T, string>>> => {\n\tvalidators = validators?.filter((x) => x)\n\n\tif (!s) {\n\t\tif (!validators?.length) return undefined as any\n\n\t\ts = validators[0] as any\n\t\tvalidators = validators.slice(1)\n\t}\n\n\tlet doesHaveRef: boolean | undefined = undefined\n\n\tconst replaceSchema = (schema: TAnySchema): TAnySchema => {\n\t\tif (coerce)\n\t\t\treturn replaceSchemaTypeFromManyOptions(schema, [\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Number(),\n\t\t\t\t\tto: (options) => t.Numeric(options),\n\t\t\t\t\tuntilObjectFound: true\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Boolean(),\n\t\t\t\t\tto: (options) => t.BooleanString(options),\n\t\t\t\t\tuntilObjectFound: true\n\t\t\t\t},\n\t\t\t\t...(Array.isArray(additionalCoerce)\n\t\t\t\t\t? additionalCoerce\n\t\t\t\t\t: [additionalCoerce])\n\t\t\t])\n\n\t\treturn replaceSchemaTypeFromManyOptions(schema, additionalCoerce)\n\t}\n\n\tconst mapSchema = (\n\t\ts: string | TSchema | StandardSchemaV1Like | undefined\n\t): TSchema | StandardSchemaV1Like => {\n\t\tif (s && typeof s !== 'string' && '~standard' in s)\n\t\t\treturn s as StandardSchemaV1Like\n\n\t\tif (!s) return undefined as any\n\n\t\tlet schema: TSchema | StandardSchemaV1Like\n\n\t\tif (typeof s !== 'string') schema = s\n\t\telse {\n\t\t\tschema =\n\t\t\t\t// @ts-expect-error private property\n\t\t\t\tmodules && s in modules.$defs\n\t\t\t\t\t? (modules as TModule<{}, {}>).Import(s as never)\n\t\t\t\t\t: models[s]\n\n\t\t\tif (!schema) return undefined as any\n\t\t}\n\n\t\tconst hasAdditionalCoerce = Array.isArray(additionalCoerce)\n\t\t\t? additionalCoerce.length > 0\n\t\t\t: !!additionalCoerce\n\n\t\tif (Kind in schema) {\n\t\t\tif (schema[Kind] === 'Import') {\n\t\t\t\tif (!hasRef(schema.$defs[schema.$ref])) {\n\t\t\t\t\tschema = schema.$defs[schema.$ref] ?? models[schema.$ref]\n\n\t\t\t\t\tif (coerce || hasAdditionalCoerce) {\n\t\t\t\t\t\tschema = replaceSchema(schema as TSchema)\n\n\t\t\t\t\t\tif ('$id' in schema && !schema.$defs)\n\t\t\t\t\t\t\tschema.$id = `${schema.$id}_coerced_${randomId()}`\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (hasRef(schema)) {\n\t\t\t\t\tconst id = randomId()\n\n\t\t\t\t\tconst model: any = t.Module({\n\t\t\t\t\t\t// @ts-expect-error private property\n\t\t\t\t\t\t...modules?.$defs,\n\t\t\t\t\t\t[id]: schema\n\t\t\t\t\t})\n\n\t\t\t\t\tschema = model.Import(id)\n\t\t\t\t} else if (coerce || hasAdditionalCoerce)\n\t\t\t\t\tschema = replaceSchema(schema as TSchema)\n\t\t\t}\n\t\t}\n\n\t\treturn schema\n\t}\n\n\tlet schema = mapSchema(s)\n\t// console.log([s, schema])\n\tlet _validators = validators\n\n\tif (\n\t\t'~standard' in schema ||\n\t\t(validators?.length &&\n\t\t\tvalidators.some(\n\t\t\t\t(x) => x && typeof x !== 'string' && '~standard' in x\n\t\t\t))\n\t) {\n\t\tconst typeboxSubValidator = (\n\t\t\tschema: TSchema\n\t\t): StandardSchemaV1LikeValidate => {\n\t\t\tlet mirror: Function\n\t\t\tif (normalize === true || normalize === 'exactMirror')\n\t\t\t\ttry {\n\t\t\t\t\tmirror = createMirror(schema as TSchema, {\n\t\t\t\t\t\tTypeCompiler,\n\t\t\t\t\t\tsanitize: sanitize?.(),\n\t\t\t\t\t\tmodules\n\t\t\t\t\t})\n\t\t\t\t} catch {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t'Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues'\n\t\t\t\t\t)\n\t\t\t\t\tconsole.warn(schema)\n\t\t\t\t\tmirror = createCleaner(schema as TSchema)\n\t\t\t\t}\n\n\t\t\tconst vali = getSchemaValidator(schema, {\n\t\t\t\tmodels,\n\t\t\t\tmodules,\n\t\t\t\tdynamic,\n\t\t\t\tnormalize,\n\t\t\t\tadditionalProperties: true,\n\t\t\t\tforceAdditionalProperties: true,\n\t\t\t\tcoerce,\n\t\t\t\tadditionalCoerce\n\t\t\t})!\n\n\t\t\t// @ts-ignore\n\t\t\tvali.Decode = mirror\n\n\t\t\treturn {\n\t\t\t\t// @ts-ignore\n\t\t\t\tvalidate: (v) => {\n\t\t\t\t\tif (vali.Check(v))\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tvalue: mirror ? mirror(v) : v\n\t\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tissues: [...vali.Errors(v)]\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst mainCheck = schema['~standard']\n\t\t\t? schema['~standard']\n\t\t\t: typeboxSubValidator(schema as TSchema)\n\n\t\tlet checkers = <StandardSchemaV1LikeValidate[]>[]\n\t\tif (validators?.length)\n\t\t\tfor (const validator of validators) {\n\t\t\t\tif (!validator) continue\n\t\t\t\tif (typeof validator === 'string') continue\n\n\t\t\t\tif (validator?.['~standard']) {\n\t\t\t\t\tcheckers.push(validator['~standard'])\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif (Kind in validator) {\n\t\t\t\t\tcheckers.push(typeboxSubValidator(validator))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\tfunction Check(\n\t\t\tvalue: unknown,\n\t\t\tvalidated = false\n\t\t): value is UnwrapSchema<T> {\n\t\t\tlet v = validated ? value : mainCheck.validate(value)\n\n\t\t\tif (v instanceof Promise)\n\t\t\t\treturn v.then((v) => Check(v, true)) as any\n\n\t\t\tif (v.issues) return v\n\n\t\t\tconst values = <(Record<string, unknown> | unknown[])[]>[]\n\t\t\tif (v && typeof v === 'object') values.push(v.value as any)\n\n\t\t\treturn runCheckers(value, 0, values, v)\n\t\t}\n\n\t\tfunction runCheckers(\n\t\t\tvalue: unknown,\n\t\t\tstartIndex: number,\n\t\t\tvalues: (Record<string, unknown> | unknown[])[],\n\t\t\tlastV: any\n\t\t): any {\n\t\t\tfor (let i = startIndex; i < checkers.length; i++) {\n\t\t\t\t// @ts-ignore\n\t\t\t\tlet v = checkers[i].validate(value)\n\n\t\t\t\tif (v instanceof Promise)\n\t\t\t\t\treturn v.then((resolved) => {\n\t\t\t\t\t\tif (resolved.issues) return resolved\n\n\t\t\t\t\t\tconst nextValues = [...values]\n\n\t\t\t\t\t\tif (resolved && typeof resolved === 'object')\n\t\t\t\t\t\t\tnextValues.push(resolved.value)\n\n\t\t\t\t\t\treturn runCheckers(value, i + 1, nextValues, resolved)\n\t\t\t\t\t})\n\n\t\t\t\tif (v.issues) return v\n\t\t\t\t// @ts-ignore\n\t\t\t\tif (v && typeof v === 'object') values.push(v.value)\n\t\t\t\tlastV = v\n\t\t\t}\n\n\t\t\treturn mergeValues(values, lastV)\n\t\t}\n\n\t\tfunction mergeValues(\n\t\t\tvalues: (Record<string, unknown> | unknown[])[],\n\t\t\tlastV: any\n\t\t) {\n\t\t\tif (!values.length) return { value: lastV }\n\t\t\tif (values.length === 1) return { value: values[0] }\n\t\t\tif (values.length === 2)\n\t\t\t\treturn { value: mergeDeep(values[0], values[1]) }\n\n\t\t\tlet newValue = mergeDeep(values[0], values[1])\n\t\t\tfor (let i = 2; i < values.length; i++)\n\t\t\t\tnewValue = mergeDeep(newValue, values[i])\n\n\t\t\treturn { value: newValue }\n\t\t}\n\n\t\tconst validator: ElysiaTypeCheck<any> = {\n\t\t\tprovider: 'standard',\n\t\t\tschema,\n\t\t\treferences: '',\n\t\t\tcheckFunc: () => {},\n\t\t\tcode: '',\n\t\t\t// @ts-ignore\n\t\t\tCheck,\n\t\t\t// @ts-ignore\n\t\t\tErrors: (value: unknown) => Check(value)?.then?.((x) => x?.issues),\n\t\t\tCode: () => '',\n\t\t\t// @ts-ignore\n\t\t\tDecode: Check,\n\t\t\t// @ts-ignore\n\t\t\tEncode: (value: unknown) => value,\n\t\t\thasAdditionalProperties: false,\n\t\t\thasDefault: false,\n\t\t\tisOptional: false,\n\t\t\thasTransform: false,\n\t\t\thasRef: false\n\t\t}\n\n\t\tvalidator.parse = (v) => {\n\t\t\ttry {\n\t\t\t\treturn validator.Decode(validator.Clean?.(v) ?? v)\n\t\t\t} catch (error) {\n\t\t\t\tthrow [...validator.Errors(v)].map(mapValueError)\n\t\t\t}\n\t\t}\n\n\t\tvalidator.safeParse = (v) => {\n\t\t\ttry {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tdata: validator.Decode(validator.Clean?.(v) ?? v),\n\t\t\t\t\terror: null\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst errors = [...compiled.Errors(v)].map(mapValueError)\n\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\tdata: null,\n\t\t\t\t\terror: errors[0]?.summary,\n\t\t\t\t\terrors\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn validator as any\n\t} else if (validators?.length) {\n\t\tlet hasAdditional = false\n\n\t\tconst validators = _validators as TSchema[]\n\n\t\tconst { schema: mergedObjectSchema, notObjects } = mergeObjectSchemas([\n\t\t\tschema,\n\t\t\t...(validators.map(mapSchema) as TSchema[])\n\t\t])\n\n\t\tif (notObjects) {\n\t\t\tschema = t.Intersect([\n\t\t\t\t...(mergedObjectSchema ? [mergedObjectSchema] : []),\n\t\t\t\t...notObjects.map((x) => {\n\t\t\t\t\tconst schema = mapSchema(x) as TSchema\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tschema.type === 'object' &&\n\t\t\t\t\t\t'additionalProperties' in schema\n\t\t\t\t\t) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!hasAdditional &&\n\t\t\t\t\t\t\tschema.additionalProperties === false\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\thasAdditional = true\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdelete schema.additionalProperties\n\t\t\t\t\t}\n\n\t\t\t\t\treturn schema\n\t\t\t\t})\n\t\t\t])\n\n\t\t\tif (schema.type === 'object' && hasAdditional)\n\t\t\t\tschema.additionalProperties = false\n\t\t}\n\t} else {\n\t\tif (\n\t\t\tschema.type === 'object' &&\n\t\t\t('additionalProperties' in schema === false ||\n\t\t\t\tforceAdditionalProperties)\n\t\t)\n\t\t\tschema.additionalProperties = additionalProperties\n\t\telse\n\t\t\tschema = replaceSchemaTypeFromManyOptions(schema, {\n\t\t\t\tonlyFirst: 'object',\n\t\t\t\tfrom: t.Object({}),\n\t\t\t\tto(schema) {\n\t\t\t\t\tif (!schema.properties) return schema\n\t\t\t\t\tif ('additionalProperties' in schema) return schema\n\n\t\t\t\t\treturn t.Object(schema.properties, {\n\t\t\t\t\t\t...schema,\n\t\t\t\t\t\tadditionalProperties: false\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t}\n\n\tif (dynamic) {\n\t\tif (Kind in schema) {\n\t\t\tconst validator: ElysiaTypeCheck<any> = {\n\t\t\t\tprovider: 'typebox',\n\t\t\t\tschema,\n\t\t\t\t// @ts-ignore\n\t\t\t\treferences: '',\n\t\t\t\tcheckFunc: () => {},\n\t\t\t\tcode: '',\n\t\t\t\tCheck: (value: unknown) => Value.Check(schema, value),\n\t\t\t\tErrors: (value: unknown) => Value.Errors(schema, value),\n\t\t\t\tCode: () => '',\n\t\t\t\tClean: createCleaner(schema),\n\t\t\t\tDecode: (value: unknown) => Value.Decode(schema, value),\n\t\t\t\tEncode: (value: unknown) => Value.Encode(schema, value),\n\t\t\t\tget hasAdditionalProperties() {\n\t\t\t\t\tif ('~hasAdditionalProperties' in this)\n\t\t\t\t\t\treturn this['~hasAdditionalProperties'] as boolean\n\n\t\t\t\t\treturn (this['~hasAdditionalProperties'] =\n\t\t\t\t\t\thasAdditionalProperties(schema))\n\t\t\t\t},\n\t\t\t\tget hasDefault() {\n\t\t\t\t\tif ('~hasDefault' in this) return this['~hasDefault']!\n\n\t\t\t\t\treturn (this['~hasDefault'] = hasProperty(\n\t\t\t\t\t\t'default',\n\t\t\t\t\t\tschema\n\t\t\t\t\t))\n\t\t\t\t},\n\t\t\t\tget isOptional() {\n\t\t\t\t\tif ('~isOptional' in this) return this['~isOptional']!\n\n\t\t\t\t\treturn (this['~isOptional'] = isOptional(schema))\n\t\t\t\t},\n\t\t\t\tget hasTransform() {\n\t\t\t\t\tif ('~hasTransform' in this) return this['~hasTransform']!\n\n\t\t\t\t\treturn (this['~hasTransform'] = hasTransform(schema))\n\t\t\t\t},\n\t\t\t\t'~hasRef': doesHaveRef,\n\t\t\t\tget hasRef() {\n\t\t\t\t\tif ('~hasRef' in this) return this['~hasRef']!\n\n\t\t\t\t\treturn (this['~hasRef'] = hasTransform(schema))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (schema.config) {\n\t\t\t\tvalidator.config = schema.config\n\n\t\t\t\tif (validator?.schema?.config) delete validator.schema.config\n\t\t\t}\n\n\t\t\tif (normalize && schema.additionalProperties === false) {\n\t\t\t\tif (normalize === true || normalize === 'exactMirror') {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tvalidator.Clean = createMirror(schema, {\n\t\t\t\t\t\t\tTypeCompiler,\n\t\t\t\t\t\t\tsanitize: sanitize?.(),\n\t\t\t\t\t\t\tmodules\n\t\t\t\t\t\t})\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t'Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues'\n\t\t\t\t\t\t)\n\t\t\t\t\t\tconsole.warn(schema)\n\t\t\t\t\t\tvalidator.Clean = createCleaner(schema)\n\t\t\t\t\t}\n\t\t\t\t} else validator.Clean = createCleaner(schema)\n\t\t\t}\n\n\t\t\tvalidator.parse = (v) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn validator.Decode(validator.Clean?.(v) ?? v)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthrow [...validator.Errors(v)].map(mapValueError)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvalidator.safeParse = (v) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\tdata: validator.Decode(validator.Clean?.(v) ?? v),\n\t\t\t\t\t\terror: null\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst errors = [...compiled.Errors(v)].map(mapValueError)\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\terror: errors[0]?.summary,\n\t\t\t\t\t\terrors\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// if (cacheKey) caches[cacheKey] = validator\n\n\t\t\treturn validator as any\n\t\t} else {\n\t\t\tconst validator: ElysiaTypeCheck<any> = {\n\t\t\t\tprovider: 'standard',\n\t\t\t\tschema,\n\t\t\t\treferences: '',\n\t\t\t\tcheckFunc: () => {},\n\t\t\t\tcode: '',\n\t\t\t\t// @ts-ignore\n\t\t\t\tCheck: (v) => schema['~standard'].validate(v),\n\t\t\t\t// @ts-ignore\n\t\t\t\tErrors(value: unknown) {\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tconst response = schema['~standard'].validate(value)\n\n\t\t\t\t\tif (response instanceof Promise)\n\t\t\t\t\t\tthrow Error(\n\t\t\t\t\t\t\t'Async validation is not supported in non-dynamic schema'\n\t\t\t\t\t\t)\n\n\t\t\t\t\treturn response.issues\n\t\t\t\t},\n\t\t\t\tCode: () => '',\n\t\t\t\t// @ts-ignore\n\t\t\t\tDecode(value) {\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tconst response = schema['~standard'].validate(value)\n\n\t\t\t\t\tif (response instanceof Promise)\n\t\t\t\t\t\tthrow Error(\n\t\t\t\t\t\t\t'Async validation is not supported in non-dynamic schema'\n\t\t\t\t\t\t)\n\n\t\t\t\t\treturn response\n\t\t\t\t},\n\t\t\t\t// @ts-ignore\n\t\t\t\tEncode: (value: unknown) => value,\n\t\t\t\thasAdditionalProperties: false,\n\t\t\t\thasDefault: false,\n\t\t\t\tisOptional: false,\n\t\t\t\thasTransform: false,\n\t\t\t\thasRef: false\n\t\t\t}\n\n\t\t\tvalidator.parse = (v) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn validator.Decode(validator.Clean?.(v) ?? v)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthrow [...validator.Errors(v)].map(mapValueError)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvalidator.safeParse = (v) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\tdata: validator.Decode(validator.Clean?.(v) ?? v),\n\t\t\t\t\t\terror: null\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst errors = [...compiled.Errors(v)].map(mapValueError)\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\terror: errors[0]?.summary,\n\t\t\t\t\t\terrors\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// if (cacheKey) caches[cacheKey] = validator\n\n\t\t\treturn validator as any\n\t\t}\n\t}\n\n\tlet compiled: ElysiaTypeCheck<any>\n\n\tif (Kind in schema) {\n\t\tcompiled = TypeCompiler.Compile(\n\t\t\tschema,\n\t\t\tObject.values(models).filter((x) => Kind in x)\n\t\t) as any\n\t\tcompiled.provider = 'typebox'\n\n\t\tif (schema.config) {\n\t\t\tcompiled.config = schema.config\n\n\t\t\tif (compiled?.schema?.config) delete compiled.schema.config\n\t\t}\n\n\t\tif (normalize === true || normalize === 'exactMirror') {\n\t\t\ttry {\n\t\t\t\tcompiled.Clean = createMirror(schema, {\n\t\t\t\t\tTypeCompiler,\n\t\t\t\t\tsanitize: sanitize?.(),\n\t\t\t\t\tmodules\n\t\t\t\t})\n\t\t\t} catch (error) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues'\n\t\t\t\t)\n\t\t\t\tconsole.dir(schema, {\n\t\t\t\t\tdepth: null\n\t\t\t\t})\n\n\t\t\t\tcompiled.Clean = createCleaner(schema)\n\t\t\t}\n\t\t} else if (normalize === 'typebox')\n\t\t\tcompiled.Clean = createCleaner(schema)\n\t} else {\n\t\tcompiled = {\n\t\t\tprovider: 'standard',\n\t\t\tschema,\n\t\t\treferences: '',\n\t\t\tcheckFunc(value: unknown) {\n\t\t\t\t// @ts-ignore\n\t\t\t\tconst response = schema['~standard'].validate(value)\n\n\t\t\t\tif (response instanceof Promise)\n\t\t\t\t\tthrow Error(\n\t\t\t\t\t\t'Async validation is not supported in non-dynamic schema'\n\t\t\t\t\t)\n\n\t\t\t\treturn response\n\t\t\t},\n\t\t\tcode: '',\n\t\t\t// @ts-ignore\n\t\t\tCheck: (v) => schema['~standard'].validate(v),\n\t\t\t// @ts-ignore\n\t\t\tErrors(value: unknown) {\n\t\t\t\t// @ts-ignore\n\t\t\t\tconst response = schema['~standard'].validate(value)\n\n\t\t\t\tif (response instanceof Promise)\n\t\t\t\t\tthrow Error(\n\t\t\t\t\t\t'Async validation is not supported in non-dynamic schema'\n\t\t\t\t\t)\n\n\t\t\t\treturn response.issues\n\t\t\t},\n\t\t\tCode: () => '',\n\t\t\t// @ts-ignore\n\t\t\tDecode(value) {\n\t\t\t\t// @ts-ignore\n\t\t\t\tconst response = schema['~standard'].validate(value)\n\n\t\t\t\tif (response instanceof Promise)\n\t\t\t\t\tthrow Error(\n\t\t\t\t\t\t'Async validation is not supported in non-dynamic schema'\n\t\t\t\t\t)\n\n\t\t\t\treturn response\n\t\t\t},\n\t\t\t// @ts-ignore\n\t\t\tEncode: (value: unknown) => value,\n\t\t\thasAdditionalProperties: false,\n\t\t\thasDefault: false,\n\t\t\tisOptional: false,\n\t\t\thasTransform: false,\n\t\t\thasRef: false\n\t\t}\n\t}\n\n\tcompiled.parse = (v) => {\n\t\ttry {\n\t\t\treturn compiled.Decode(compiled.Clean?.(v) ?? v)\n\t\t} catch (error) {\n\t\t\tthrow [...compiled.Errors(v)].map(mapValueError)\n\t\t}\n\t}\n\n\tcompiled.safeParse = (v) => {\n\t\ttry {\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: compiled.Decode(compiled.Clean?.(v) ?? v),\n\t\t\t\terror: null\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst errors = [...compiled.Errors(v)].map(mapValueError)\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdata: null,\n\t\t\t\terror: errors[0]?.summary,\n\t\t\t\terrors\n\t\t\t}\n\t\t}\n\t}\n\n\tif (Kind in schema)\n\t\tObject.assign(compiled, {\n\t\t\tget hasAdditionalProperties() {\n\t\t\t\tif ('~hasAdditionalProperties' in this)\n\t\t\t\t\treturn this['~hasAdditionalProperties']\n\n\t\t\t\treturn (this['~hasAdditionalProperties'] =\n\t\t\t\t\thasAdditionalProperties(compiled))\n\t\t\t},\n\t\t\tget hasDefault() {\n\t\t\t\tif ('~hasDefault' in this) return this['~hasDefault']\n\n\t\t\t\treturn (this['~hasDefault'] = hasProperty('default', compiled))\n\t\t\t},\n\t\t\tget isOptional() {\n\t\t\t\tif ('~isOptional' in this) return this['~isOptional']!\n\n\t\t\t\treturn (this['~isOptional'] = isOptional(compiled))\n\t\t\t},\n\t\t\tget hasTransform() {\n\t\t\t\tif ('~hasTransform' in this) return this['~hasTransform']!\n\n\t\t\t\treturn (this['~hasTransform'] = hasTransform(schema))\n\t\t\t},\n\t\t\tget hasRef() {\n\t\t\t\tif ('~hasRef' in this) return this['~hasRef']!\n\n\t\t\t\treturn (this['~hasRef'] = hasRef(schema))\n\t\t\t},\n\t\t\t'~hasRef': doesHaveRef\n\t\t} as ElysiaTypeCheck<any>)\n\n\t// if (cacheKey) caches[cacheKey] = compiled\n\n\treturn compiled as any\n}\n\nexport const isUnion = (schema: TSchema) =>\n\tschema[Kind] === 'Union' || (!schema.schema && !!schema.anyOf)\n\n// Returns all properties as a flat map, handling Union/Intersect\n// See: https://github.com/sinclairzx81/typebox/blob/0.34.3/src/type/indexed/indexed.ts#L152-L162\nexport const getSchemaProperties = (\n\tschema: TAnySchema | undefined\n): Record<string, TAnySchema> | undefined => {\n\tif (!schema) return undefined\n\n\tif (schema.properties) return schema.properties\n\n\tconst members = schema.allOf ?? schema.anyOf ?? schema.oneOf\n\tif (members) {\n\t\tconst result: Record<string, TAnySchema> = {}\n\t\tfor (const member of members) {\n\t\t\tconst props = getSchemaProperties(member)\n\t\t\tif (props) Object.assign(result, props)\n\t\t}\n\t\treturn Object.keys(result).length > 0 ? result : undefined\n\t}\n\n\treturn undefined\n}\n\nexport const mergeObjectSchemas = (\n\tschemas: TSchema[]\n): {\n\tschema: TObject | undefined\n\tnotObjects: TSchema[]\n} => {\n\tif (schemas.length === 0) {\n\t\treturn {\n\t\t\tschema: undefined,\n\t\t\tnotObjects: []\n\t\t}\n\t}\n\tif (schemas.length === 1)\n\t\treturn schemas[0].type === 'object'\n\t\t\t? {\n\t\t\t\t\tschema: schemas[0] as TObject,\n\t\t\t\t\tnotObjects: []\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tschema: undefined,\n\t\t\t\t\tnotObjects: schemas\n\t\t\t\t}\n\n\tlet newSchema: TObject\n\tconst notObjects = <TSchema[]>[]\n\n\tlet additionalPropertiesIsTrue = false\n\tlet additionalPropertiesIsFalse = false\n\n\tfor (const schema of schemas) {\n\t\tif (schema.type !== 'object') {\n\t\t\tnotObjects.push(schema)\n\t\t\tcontinue\n\t\t}\n\n\t\tif ('additionalProperties' in schema) {\n\t\t\tif (schema.additionalProperties === true)\n\t\t\t\tadditionalPropertiesIsTrue = true\n\t\t\telse if (schema.additionalProperties === false)\n\t\t\t\tadditionalPropertiesIsFalse = true\n\t\t}\n\n\t\tif (!newSchema!) {\n\t\t\tnewSchema = schema as TObject\n\t\t\tcontinue\n\t\t}\n\n\t\tnewSchema = {\n\t\t\t...newSchema,\n\t\t\t...schema,\n\t\t\tproperties: {\n\t\t\t\t...newSchema.properties,\n\t\t\t\t...schema.properties\n\t\t\t},\n\t\t\trequired: [\n\t\t\t\t...(newSchema?.required ?? []),\n\t\t\t\t...(schema.required ?? [])\n\t\t\t]\n\t\t} as TObject\n\t}\n\n\tif (newSchema!) {\n\t\tif (newSchema.required)\n\t\t\tnewSchema.required = [...new Set(newSchema.required)]\n\n\t\tif (additionalPropertiesIsFalse) newSchema.additionalProperties = false\n\t\telse if (additionalPropertiesIsTrue)\n\t\t\tnewSchema.additionalProperties = true\n\t}\n\n\treturn {\n\t\tschema: newSchema!,\n\t\tnotObjects\n\t}\n}\n\nexport const getResponseSchemaValidator = (\n\ts: InputSchema['response'] | undefined,\n\t{\n\t\tmodels = {},\n\t\tmodules,\n\t\tdynamic = false,\n\t\tnormalize = false,\n\t\tadditionalProperties = false,\n\t\tvalidators = [],\n\t\tsanitize\n\t}: {\n\t\tmodules: TModule<any, any>\n\t\tmodels?: Record<string, TSchema | StandardSchemaV1Like>\n\t\tadditionalProperties?: boolean\n\t\tdynamic?: boolean\n\t\tnormalize?: ElysiaConfig<''>['normalize']\n\t\tvalidators?: StandaloneInputSchema['response'][]\n\t\tsanitize?: () => ExactMirrorInstruction['sanitize']\n\t}\n): Record<number, ElysiaTypeCheck<any>> | undefined => {\n\tvalidators = validators.filter((x) => x)\n\n\tif (!s) {\n\t\tif (!validators?.length) return undefined as any\n\n\t\ts = validators[0] as any\n\t\tvalidators = validators.slice(1)\n\t}\n\n\tlet maybeSchemaOrRecord:\n\t\t| TSchema\n\t\t| StandardSchemaV1Like\n\t\t| Record<number, string | TSchema | StandardSchemaV1Like>\n\n\t// @ts-ignore\n\tif (typeof s !== 'string') maybeSchemaOrRecord = s!\n\telse {\n\t\tmaybeSchemaOrRecord = // @ts-expect-error private property\n\t\t\tmodules && s in modules.$defs\n\t\t\t\t? (modules as TModule<{}, {}>).Import(s as never)\n\t\t\t\t: models[s]\n\n\t\tif (!maybeSchemaOrRecord) return undefined as any\n\t}\n\n\tif (!maybeSchemaOrRecord) return\n\n\tif (Kind in maybeSchemaOrRecord || '~standard' in maybeSchemaOrRecord)\n\t\treturn {\n\t\t\t200: getSchemaValidator(\n\t\t\t\tmaybeSchemaOrRecord as TSchema | StandardSchemaV1Like,\n\t\t\t\t{\n\t\t\t\t\tmodules,\n\t\t\t\t\tmodels,\n\t\t\t\t\tadditionalProperties,\n\t\t\t\t\tdynamic,\n\t\t\t\t\tnormalize,\n\t\t\t\t\tcoerce: false,\n\t\t\t\t\tadditionalCoerce: [],\n\t\t\t\t\tvalidators: validators.map((x) => x![200]),\n\t\t\t\t\tsanitize\n\t\t\t\t}\n\t\t\t)!\n\t\t}\n\n\tconst record: Record<number, ElysiaTypeCheck<any>> = {}\n\n\tObject.keys(maybeSchemaOrRecord).forEach((status): TSchema | undefined => {\n\t\tif (isNaN(+status)) return\n\n\t\tconst maybeNameOrSchema = maybeSchemaOrRecord[+status]\n\n\t\tif (typeof maybeNameOrSchema === 'string') {\n\t\t\tif (maybeNameOrSchema in models) {\n\t\t\t\tconst schema = models[maybeNameOrSchema]\n\n\t\t\t\tif (!schema) return\n\n\t\t\t\t// Inherits model maybe already compiled\n\t\t\t\trecord[+status] =\n\t\t\t\t\tKind in schema || '~standard' in schema\n\t\t\t\t\t\t? getSchemaValidator(schema as TSchema, {\n\t\t\t\t\t\t\t\tmodules,\n\t\t\t\t\t\t\t\tmodels,\n\t\t\t\t\t\t\t\tadditionalProperties,\n\t\t\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\t\t\tnormalize,\n\t\t\t\t\t\t\t\tcoerce: false,\n\t\t\t\t\t\t\t\tadditionalCoerce: [],\n\t\t\t\t\t\t\t\tvalidators: validators.map((x) => x![+status]),\n\t\t\t\t\t\t\t\tsanitize\n\t\t\t\t\t\t\t})!\n\t\t\t\t\t\t: (schema as ElysiaTypeCheck<any>)\n\t\t\t}\n\n\t\t\treturn undefined\n\t\t}\n\n\t\t// Inherits model maybe already compiled\n\t\trecord[+status] =\n\t\t\tKind in maybeNameOrSchema || '~standard' in maybeNameOrSchema\n\t\t\t\t? getSchemaValidator(maybeNameOrSchema as TSchema, {\n\t\t\t\t\t\tmodules,\n\t\t\t\t\t\tmodels,\n\t\t\t\t\t\tadditionalProperties,\n\t\t\t\t\t\tdynamic,\n\t\t\t\t\t\tnormalize,\n\t\t\t\t\t\tcoerce: false,\n\t\t\t\t\t\tadditionalCoerce: [],\n\t\t\t\t\t\tvalidators: validators.map((x) => x![+status]),\n\t\t\t\t\t\tsanitize\n\t\t\t\t\t})\n\t\t\t\t: (maybeNameOrSchema as ElysiaTypeCheck<any>)\n\t})\n\n\treturn record\n}\n\nexport const getCookieValidator = ({\n\tvalidator,\n\tmodules,\n\tdefaultConfig = {},\n\tconfig,\n\tdynamic,\n\tnormalize = false,\n\tmodels,\n\tvalidators,\n\tsanitize\n}: {\n\tvalidator:\n\t\t| TSchema\n\t\t| StandardSchemaV1Like\n\t\t| ElysiaTypeCheck<any>\n\t\t| string\n\t\t| undefined\n\tmodules: TModule<any, any>\n\tdefaultConfig: CookieOptions | undefined\n\tconfig: CookieOptions\n\tdynamic: boolean\n\tnormalize: ElysiaConfig<''>['normalize'] | undefined\n\tmodels: Record<string, TSchema | StandardSchemaV1Like> | undefined\n\tvalidators?: InputSchema['cookie'][]\n\tsanitize?: () => ExactMirrorInstruction['sanitize']\n}) => {\n\tlet cookieValidator =\n\t\t// @ts-ignore\n\t\tvalidator?.provider\n\t\t\t? (validator as ElysiaTypeCheck<any>)\n\t\t\t: // @ts-ignore\n\t\t\t\tgetSchemaValidator(validator, {\n\t\t\t\t\tmodules,\n\t\t\t\t\tdynamic,\n\t\t\t\t\tmodels,\n\t\t\t\t\tnormalize,\n\t\t\t\t\tadditionalProperties: true,\n\t\t\t\t\tcoerce: true,\n\t\t\t\t\tadditionalCoerce: stringToStructureCoercions(),\n\t\t\t\t\tvalidators,\n\t\t\t\t\tsanitize\n\t\t\t\t})\n\n\tif (cookieValidator)\n\t\tcookieValidator.config = mergeCookie(cookieValidator.config, config)\n\telse {\n\t\tcookieValidator = getSchemaValidator(t.Cookie(t.Any()), {\n\t\t\tmodules,\n\t\t\tdynamic,\n\t\t\tmodels,\n\t\t\tadditionalProperties: true,\n\t\t\tvalidators,\n\t\t\tsanitize\n\t\t})\n\n\t\tcookieValidator.config = defaultConfig\n\t}\n\n\treturn cookieValidator\n}\n\n/**\n * This function will return the type of unioned if all unioned type is the same.\n * It's intent to use for content-type mapping only\n *\n * ```ts\n * t.Union([\n *   t.Object({\n *     password: t.String()\n *   }),\n *   t.Object({\n *     token: t.String()\n *   })\n * ])\n * ```\n */\n// const getUnionedType = (validator: TypeCheck<any> | undefined) => {\n// \tif (!validator) return\n\n// \t// @ts-ignore\n// \tconst schema = validator?.schema ?? validator\n\n// \tif (schema && 'anyOf' in schema) {\n// \t\tlet foundDifference = false\n// \t\tconst type: string = schema.anyOf[0].type\n\n// \t\tfor (const validator of schema.anyOf as { type: string }[]) {\n// \t\t\tif (validator.type !== type) {\n// \t\t\t\tfoundDifference = true\n// \t\t\t\tbreak\n// \t\t\t}\n// \t\t}\n\n// \t\tif (!foundDifference) return type\n// \t}\n\n// \t// @ts-ignore\n// \treturn validator.schema?.type\n// }\n\nexport const unwrapImportSchema = (schema: TSchema): TSchema =>\n\tschema &&\n\tschema[Kind] === 'Import' &&\n\tschema.$defs[schema.$ref][Kind] === 'Object'\n\t\t? schema.$defs[schema.$ref]\n\t\t: schema\n"
  },
  {
    "path": "src/sucrose.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-constant-condition */\nimport { checksum } from './utils'\nimport { isBun, isCloudflareWorker } from './universal/utils'\n\nimport type { Handler, HookContainer, LifeCycleStore } from './types'\n\nexport namespace Sucrose {\n\texport interface Inference {\n\t\tquery: boolean\n\t\theaders: boolean\n\t\tbody: boolean\n\t\tcookie: boolean\n\t\tset: boolean\n\t\tserver: boolean\n\t\troute: boolean\n\t\turl: boolean\n\t\tpath: boolean\n\t}\n\n\texport interface LifeCycle extends Partial<LifeCycleStore> {\n\t\thandler?: Handler\n\t}\n\n\texport interface Settings {\n\t\t/**\n\t\t * If no sucrose usage is found in time\n\t\t * it's likely that server is either idle or\n\t\t * no new compilation is happening\n\t\t * clear the cache to free up memory\n\t\t *\n\t\t * @default 4 * 60 * 1000 + 55 * 1000 (4 minutes 55 seconds)\n\t\t */\n\t\tgcTime?: number | null\n\t}\n}\n\n/**\n * Separate stringified function body and parameter\n *\n * @example\n * ```typescript\n * separateFunction('async ({ hello }) => { return hello }') // => ['({ hello })', '{ return hello }']\n * ```\n */\nexport const separateFunction = (\n\tcode: string\n): [string, string, { isArrowReturn: boolean }] => {\n\t// Remove async keyword without removing space (both minify and non-minify)\n\tif (code.startsWith('async')) code = code.slice(5)\n\tcode = code.trimStart()\n\n\tlet index = -1\n\n\t// JSC: Starts with '(', is an arrow function\n\tif (code.charCodeAt(0) === 40) {\n\t\tindex = code.indexOf('=>', code.indexOf(')'))\n\n\t\tif (index !== -1) {\n\t\t\tlet bracketEndIndex = index\n\t\t\t// Walk back to find bracket end\n\t\t\twhile (bracketEndIndex > 0)\n\t\t\t\tif (code.charCodeAt(--bracketEndIndex) === 41) break\n\n\t\t\tlet body = code.slice(index + 2)\n\t\t\tif (body.charCodeAt(0) === 32) body = body.trimStart()\n\n\t\t\treturn [\n\t\t\t\tcode.slice(1, bracketEndIndex),\n\t\t\t\tbody,\n\t\t\t\t{\n\t\t\t\t\tisArrowReturn: body.charCodeAt(0) !== 123\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t}\n\n\t// V8: bracket is removed for 1 parameter arrow function\n\tif (/^(\\w+)=>/g.test(code)) {\n\t\tindex = code.indexOf('=>')\n\n\t\tif (index !== -1) {\n\t\t\tlet body = code.slice(index + 2)\n\t\t\tif (body.charCodeAt(0) === 32) body = body.trimStart()\n\n\t\t\treturn [\n\t\t\t\tcode.slice(0, index),\n\t\t\t\tbody,\n\t\t\t\t{\n\t\t\t\t\tisArrowReturn: body.charCodeAt(0) !== 123\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t}\n\n\t// Using function keyword\n\tif (code.startsWith('function')) {\n\t\tindex = code.indexOf('(')\n\t\tconst end = code.indexOf(')')\n\n\t\treturn [\n\t\t\tcode.slice(index + 1, end),\n\t\t\tcode.slice(end + 2),\n\t\t\t{\n\t\t\t\tisArrowReturn: false\n\t\t\t}\n\t\t]\n\t}\n\n\t// Probably Declare as method\n\tconst start = code.indexOf('(')\n\n\tif (start !== -1) {\n\t\tconst sep = code.indexOf('\\n', 2)\n\t\tconst parameter = code.slice(0, sep)\n\t\tconst end = parameter.lastIndexOf(')') + 1\n\n\t\tconst body = code.slice(sep + 1)\n\n\t\treturn [\n\t\t\tparameter.slice(start, end),\n\t\t\t'{' + body,\n\t\t\t{\n\t\t\t\tisArrowReturn: false\n\t\t\t}\n\t\t]\n\t}\n\n\t// Unknown case\n\tconst x = code.split('\\n', 2)\n\n\treturn [x[0], x[1], { isArrowReturn: false }]\n}\n\n/**\n * Get range between bracket pair\n *\n * @example\n * ```typescript\n * bracketPairRange('hello: { world: { a } }, elysia') // [6, 20]\n * ```\n */\nexport const bracketPairRange = (parameter: string): [number, number] => {\n\tconst start = parameter.indexOf('{')\n\tif (start === -1) return [-1, 0]\n\n\tlet end = start + 1\n\tlet deep = 1\n\n\tfor (; end < parameter.length; end++) {\n\t\tconst char = parameter.charCodeAt(end)\n\n\t\t// Open bracket\n\t\tif (char === 123) deep++\n\t\t// Close bracket\n\t\telse if (char === 125) deep--\n\n\t\tif (deep === 0) break\n\t}\n\n\tif (deep !== 0) return [0, parameter.length]\n\n\treturn [start, end + 1]\n}\n\n/**\n * Similar to `bracketPairRange` but in reverse order\n * Get range between bracket pair from end to beginning\n *\n * @example\n * ```typescript\n * bracketPairRange('hello: { world: { a } }, elysia') // [6, 20]\n * ```\n */\nexport const bracketPairRangeReverse = (\n\tparameter: string\n): [number, number] => {\n\tconst end = parameter.lastIndexOf('}')\n\tif (end === -1) return [-1, 0]\n\n\tlet start = end - 1\n\tlet deep = 1\n\n\tfor (; start >= 0; start--) {\n\t\tconst char = parameter.charCodeAt(start)\n\n\t\t// Open bracket\n\t\tif (char === 125) deep++\n\t\t// Close bracket\n\t\telse if (char === 123) deep--\n\n\t\tif (deep === 0) break\n\t}\n\n\tif (deep !== 0) return [-1, 0]\n\n\treturn [start, end + 1]\n}\n\nexport const removeColonAlias = (parameter: string) => {\n\twhile (true) {\n\t\tconst start = parameter.indexOf(':')\n\t\tif (start === -1) break\n\n\t\tlet end = parameter.indexOf(',', start)\n\t\tif (end === -1) end = parameter.indexOf('}', start) - 1\n\t\tif (end === -2) end = parameter.length\n\n\t\tparameter = parameter.slice(0, start) + parameter.slice(end)\n\t}\n\n\treturn parameter\n}\n\n/**\n * Retrieve only root parameters of a function\n *\n * @example\n * ```typescript\n * retrieveRootParameters('({ hello: { world: { a } }, elysia })') // => {\n *   parameters: ['hello', 'elysia'],\n *   hasParenthesis: true\n * }\n * ```\n */\nexport const retrieveRootparameters = (parameter: string) => {\n\tlet hasParenthesis = false\n\n\t// Remove () from parameter\n\tif (parameter.charCodeAt(0) === 40) parameter = parameter.slice(1, -1)\n\n\t// Remove {} from parameter\n\tif (parameter.charCodeAt(0) === 123) {\n\t\thasParenthesis = true\n\t\tparameter = parameter.slice(1, -1)\n\t}\n\n\tparameter = parameter.replace(/( |\\t|\\n)/g, '').trim()\n\tlet parameters = <string[]>[]\n\n\t// Object destructuring\n\twhile (true) {\n\t\t// eslint-disable-next-line prefer-const\n\t\tlet [start, end] = bracketPairRange(parameter)\n\t\tif (start === -1) break\n\n\t\t// Remove colon from object structuring cast\n\t\tparameters.push(parameter.slice(0, start - 1))\n\t\tif (parameter.charCodeAt(end) === 44) end++\n\t\tparameter = parameter.slice(end)\n\t}\n\n\tparameter = removeColonAlias(parameter)\n\tif (parameter) parameters = parameters.concat(parameter.split(','))\n\n\tconst parameterMap: Record<string, true> = Object.create(null)\n\tfor (const p of parameters) {\n\t\tif (p.indexOf(',') === -1) {\n\t\t\tparameterMap[p] = true\n\t\t\tcontinue\n\t\t}\n\n\t\tfor (const q of p.split(',')) parameterMap[q.trim()] = true\n\t}\n\n\treturn {\n\t\thasParenthesis,\n\t\tparameters: parameterMap\n\t}\n}\n\n/**\n * Find inference from parameter\n *\n * @param parameter stringified parameter\n */\nexport const findParameterReference = (\n\tparameter: string,\n\tinference: Sucrose.Inference\n) => {\n\tconst { parameters, hasParenthesis } = retrieveRootparameters(parameter)\n\n\t// Check if root is an object destructuring\n\tif (parameters.query) inference.query = true\n\tif (parameters.headers) inference.headers = true\n\tif (parameters.body) inference.body = true\n\tif (parameters.cookie) inference.cookie = true\n\tif (parameters.set) inference.set = true\n\tif (parameters.server) inference.server = true\n\tif (parameters.route) inference.route = true\n\tif (parameters.url) inference.url = true\n\tif (parameters.path) inference.path = true\n\n\tif (hasParenthesis) return `{ ${Object.keys(parameters).join(', ')} }`\n\n\treturn Object.keys(parameters).join(', ')\n}\n\nconst findEndIndex = (\n\ttype: string,\n\tcontent: string,\n\tindex?: number | undefined\n) => {\n\tconst regex = new RegExp(\n\t\t`${type.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}[\\\\n\\\\t,; ]`\n\t)\n\n\tif (index !== undefined) regex.lastIndex = index\n\n\tconst match = regex.exec(content)\n\n\treturn match ? match.index : -1\n}\n\nconst findEndQueryBracketIndex = (\n\ttype: string,\n\tcontent: string,\n\tindex?: number | undefined\n) => {\n\tconst bracketEndIndex = content.indexOf(type + ']', index)\n\tconst singleQuoteIndex = content.indexOf(type + \"'\", index)\n\tconst doubleQuoteIndex = content.indexOf(type + '\"', index)\n\n\t// Pick the smallest index that is not -1 or 0\n\treturn (\n\t\t[bracketEndIndex, singleQuoteIndex, doubleQuoteIndex]\n\t\t\t.filter((i) => i > 0)\n\t\t\t.sort((a, b) => a - b)[0] || -1\n\t)\n}\n\n/**\n * Find alias of variable from function body\n *\n * @example\n * ```typescript\n * findAlias('body', '{ const a = body, b = body }') // => ['a', 'b']\n * ```\n */\nexport const findAlias = (type: string, body: string, depth = 0) => {\n\tif (depth > 5) return []\n\n\tconst aliases: string[] = []\n\n\tlet content = body\n\n\twhile (true) {\n\t\tlet index = findEndIndex(' = ' + type, content)\n\t\t// V8 engine minified the code\n\t\tif (index === -1) index = findEndIndex('=' + type, content)\n\n\t\tif (index === -1) {\n\t\t\t/**\n\t\t\t * Check if pattern is at the end of the string\n\t\t\t *\n\t\t\t * @example\n\t\t\t * ```typescript\n\t\t\t * 'const a = body' // true\n\t\t\t * ```\n\t\t\t **/\n\t\t\tlet lastIndex = content.indexOf(' = ' + type)\n\t\t\tif (lastIndex === -1) lastIndex = content.indexOf('=' + type)\n\n\t\t\tif (lastIndex + 3 + type.length !== content.length) break\n\n\t\t\tindex = lastIndex\n\t\t}\n\n\t\tconst part = content.slice(0, index)\n\n\t\t// V8 engine minified the code\n\t\tconst lastPart = part.lastIndexOf(' ')\n\t\t/**\n\t\t * aliased variable last character\n\t\t *\n\t\t * @example\n\t\t * ```typescript\n\t\t * const { hello } = body // } is the last character\n\t\t * ```\n\t\t **/\n\t\tlet variable = part.slice(lastPart !== -1 ? lastPart + 1 : -1)\n\n\t\t// Variable is using object destructuring, find the bracket pair\n\t\tif (variable === '}') {\n\t\t\tconst [start, end] = bracketPairRangeReverse(part)\n\n\t\t\taliases.push(removeColonAlias(content.slice(start, end)))\n\n\t\t\tcontent = content.slice(index + 3 + type.length)\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// Remove comma\n\t\twhile (variable.charCodeAt(0) === 44) variable = variable.slice(1)\n\t\twhile (variable.charCodeAt(0) === 9) variable = variable.slice(1)\n\n\t\tif (!variable.includes('(')) aliases.push(variable)\n\n\t\tcontent = content.slice(index + 3 + type.length)\n\t}\n\n\tfor (const alias of aliases) {\n\t\tif (alias.charCodeAt(0) === 123) continue\n\n\t\tconst deepAlias = findAlias(alias, body)\n\t\tif (deepAlias.length > 0) aliases.push(...deepAlias)\n\t}\n\n\treturn aliases\n}\n\n// ? This is normalized to dot notation in Bun\n// const accessor = <T extends string, P extends string>(parent: T, prop: P) =>\n// \t[\n// \t\tparent + '.' + prop,\n// \t\tparent + '[\"' + prop + '\"]',\n// \t\tparent + \"['\" + prop + \"']\"\n// \t] as const\n\nexport const extractMainParameter = (parameter: string) => {\n\tif (!parameter) return\n\n\tif (parameter.charCodeAt(0) !== 123) return parameter\n\n\tparameter = parameter.slice(2, -2)\n\n\tconst hasComma = parameter.includes(',')\n\tif (!hasComma) {\n\t\tconst index = parameter.indexOf('...')\n\t\t// This happens when spread operator is used as the only parameter\n\t\tif (index !== -1) return parameter.slice(parameter.indexOf('...') + 3)\n\n\t\treturn\n\t}\n\n\tconst spreadIndex = parameter.indexOf('...')\n\tif (spreadIndex === -1) return\n\n\t// Spread parameter is always the last parameter, no need for further checking\n\treturn parameter.slice(spreadIndex + 3).trimEnd()\n}\n\n/**\n * Analyze if context is mentioned in body\n */\nexport const inferBodyReference = (\n\tcode: string,\n\taliases: string[],\n\tinference: Sucrose.Inference\n) => {\n\tconst access = (type: string, alias: string) =>\n\t\tnew RegExp(\n\t\t\t`${alias}\\\\.(${type})|${alias}\\\\[\"${type}\"\\\\]|${alias}\\\\['${type}'\\\\]`\n\t\t).test(code)\n\n\tfor (const alias of aliases) {\n\t\tif (!alias) continue\n\n\t\t// Scan object destructured property\n\t\tif (alias.charCodeAt(0) === 123) {\n\t\t\tconst parameters = retrieveRootparameters(alias).parameters\n\n\t\t\tif (parameters.query) inference.query = true\n\t\t\tif (parameters.headers) inference.headers = true\n\t\t\tif (parameters.body) inference.body = true\n\t\t\tif (parameters.cookie) inference.cookie = true\n\t\t\tif (parameters.set) inference.set = true\n\t\t\tif (parameters.server) inference.server = true\n\t\t\tif (parameters.url) inference.url = true\n\t\t\tif (parameters.route) inference.route = true\n\t\t\tif (parameters.path) inference.path = true\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (\n\t\t\t!inference.query &&\n\t\t\t(access('query', alias) ||\n\t\t\t\tcode.includes('return ' + alias) ||\n\t\t\t\tcode.includes('return ' + alias + '.query'))\n\t\t)\n\t\t\tinference.query = true\n\n\t\tif (!inference.headers && access('headers', alias))\n\t\t\tinference.headers = true\n\n\t\tif (!inference.body && access('body', alias)) inference.body = true\n\n\t\tif (!inference.cookie && access('cookie', alias))\n\t\t\tinference.cookie = true\n\n\t\tif (!inference.set && access('set', alias)) inference.set = true\n\t\tif (!inference.server && access('server', alias))\n\t\t\tinference.server = true\n\n\t\tif (!inference.route && access('route', alias)) inference.route = true\n\t\tif (!inference.url && access('url', alias)) inference.url = true\n\t\tif (!inference.path && access('path', alias)) inference.path = true\n\n\t\tif (\n\t\t\tinference.query &&\n\t\t\tinference.headers &&\n\t\t\tinference.body &&\n\t\t\tinference.cookie &&\n\t\t\tinference.set &&\n\t\t\tinference.server &&\n\t\t\tinference.route &&\n\t\t\tinference.url &&\n\t\t\tinference.path\n\t\t)\n\t\t\tbreak\n\t}\n\n\treturn aliases\n}\n\nexport const removeDefaultParameter = (parameter: string) => {\n\twhile (true) {\n\t\tconst index = parameter.indexOf('=')\n\t\tif (index === -1) break\n\n\t\tconst commaIndex = parameter.indexOf(',', index)\n\t\tconst bracketIndex = parameter.indexOf('}', index)\n\n\t\tconst end =\n\t\t\t[commaIndex, bracketIndex]\n\t\t\t\t.filter((i) => i > 0)\n\t\t\t\t.sort((a, b) => a - b)[0] || -1\n\n\t\tif (end === -1) {\n\t\t\tparameter = parameter.slice(0, index)\n\n\t\t\tbreak\n\t\t}\n\n\t\tparameter = parameter.slice(0, index) + parameter.slice(end)\n\t}\n\n\treturn parameter\n\t\t.split(',')\n\t\t.map((i) => i.trim())\n\t\t.join(', ')\n}\n\nexport const isContextPassToFunction = (\n\tcontext: string,\n\tbody: string,\n\tinference: Sucrose.Inference\n) => {\n\t// ! Function is passed to another function, assume as all is accessed\n\ttry {\n\t\tconst captureFunction = new RegExp(\n\t\t\t`\\\\w\\\\((?:.*?)?${context}(?:.*?)?\\\\)`,\n\t\t\t'gs'\n\t\t)\n\t\tconst exactParameter = new RegExp(`${context}(,|\\\\))`, 'gs')\n\n\t\tconst length = body.length\n\t\tlet fn\n\n\t\tfn = captureFunction.exec(body) + ''\n\t\twhile (\n\t\t\tcaptureFunction.lastIndex !== 0 &&\n\t\t\tcaptureFunction.lastIndex < length + (fn ? fn.length : 0)\n\t\t) {\n\t\t\tif (fn && exactParameter.test(fn)) {\n\t\t\t\tinference.query = true\n\t\t\t\tinference.headers = true\n\t\t\t\tinference.body = true\n\t\t\t\tinference.cookie = true\n\t\t\t\tinference.set = true\n\t\t\t\tinference.server = true\n\t\t\t\tinference.url = true\n\t\t\t\tinference.route = true\n\t\t\t\tinference.path = true\n\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tfn = captureFunction.exec(body) + ''\n\t\t}\n\n\t\t/*\n\t\tSince JavaScript engine already format the code (removing whitespace, newline, etc.),\n\t\twe can safely assume that the next character is either a closing bracket or a comma\n\t\tif the function is passed to another function\n\t\t*/\n\t\tconst nextChar = body.charCodeAt(captureFunction.lastIndex)\n\n\t\tif (nextChar === 41 || nextChar === 44) {\n\t\t\tinference.query = true\n\t\t\tinference.headers = true\n\t\t\tinference.body = true\n\t\t\tinference.cookie = true\n\t\t\tinference.set = true\n\t\t\tinference.server = true\n\t\t\tinference.url = true\n\t\t\tinference.route = true\n\t\t\tinference.path = true\n\n\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t} catch (error) {\n\t\tconsole.log(\n\t\t\t'[Sucrose] warning: unexpected isContextPassToFunction error, you may continue development as usual but please report the following to maintainers:'\n\t\t)\n\t\tconsole.log('--- body ---')\n\t\tconsole.log(body)\n\t\tconsole.log('--- context ---')\n\t\tconsole.log(context)\n\n\t\treturn true\n\t}\n}\n\nlet pendingGC: Timer | undefined\nlet caches = <Record<number, Sucrose.Inference>>{}\n\nexport const clearSucroseCache = (delay: Sucrose.Settings['gcTime']) => {\n\t// Can't setTimeout outside fetch in Cloudflare Worker\n\tif (delay === null || isCloudflareWorker()) return\n\tif (delay === undefined) delay = 4 * 60 * 1000 + 55 * 1000\n\n\tif (pendingGC) clearTimeout(pendingGC)\n\n\tpendingGC = setTimeout(() => {\n\t\tcaches = {}\n\n\t\tpendingGC = undefined\n\t\tif (isBun) Bun.gc(false)\n\t}, delay)\n\n\tpendingGC.unref?.()\n}\n\nexport const mergeInference = (a: Sucrose.Inference, b: Sucrose.Inference) => {\n\treturn {\n\t\tbody: a.body || b.body,\n\t\tcookie: a.cookie || b.cookie,\n\t\theaders: a.headers || b.headers,\n\t\tquery: a.query || b.query,\n\t\tset: a.set || b.set,\n\t\tserver: a.server || b.server,\n\t\turl: a.url || b.url,\n\t\troute: a.route || b.route,\n\t\tpath: a.path || b.path\n\t}\n}\n\nexport const sucrose = (\n\tlifeCycle: Sucrose.LifeCycle,\n\tinference: Sucrose.Inference = {\n\t\tquery: false,\n\t\theaders: false,\n\t\tbody: false,\n\t\tcookie: false,\n\t\tset: false,\n\t\tserver: false,\n\t\turl: false,\n\t\troute: false,\n\t\tpath: false\n\t},\n\tsettings: Sucrose.Settings = {}\n): Sucrose.Inference => {\n\tconst events = <(Handler | HookContainer)[]>[]\n\n\tif (lifeCycle.request?.length) events.push(...lifeCycle.request)\n\tif (lifeCycle.beforeHandle?.length) events.push(...lifeCycle.beforeHandle)\n\tif (lifeCycle.parse?.length) events.push(...lifeCycle.parse)\n\tif (lifeCycle.error?.length) events.push(...lifeCycle.error)\n\tif (lifeCycle.transform?.length) events.push(...lifeCycle.transform)\n\tif (lifeCycle.afterHandle?.length) events.push(...lifeCycle.afterHandle)\n\tif (lifeCycle.mapResponse?.length) events.push(...lifeCycle.mapResponse)\n\tif (lifeCycle.afterResponse?.length) events.push(...lifeCycle.afterResponse)\n\n\tif (lifeCycle.handler && typeof lifeCycle.handler === 'function')\n\t\tevents.push(lifeCycle.handler as Handler)\n\n\tfor (let i = 0; i < events.length; i++) {\n\t\tconst e = events[i]\n\t\tif (!e) continue\n\n\t\tconst event = typeof e === 'object' ? e.fn : e\n\n\t\t// parse can be either a function or string\n\t\tif (typeof event !== 'function') continue\n\n\t\tconst content = event.toString()\n\t\tconst key = checksum(content)\n\t\tconst cachedInference = caches[key]\n\t\tif (cachedInference) {\n\t\t\tinference = mergeInference(inference, cachedInference)\n\t\t\tcontinue\n\t\t}\n\n\t\t// If no sucrose usage is found in 4:55 minutes\n\t\t// it's likely that server is either idle or\n\t\t// no new compilation is happening\n\t\t// Clear the cache to free up memory\n\t\tclearSucroseCache(settings.gcTime)\n\n\t\tconst fnInference: Sucrose.Inference = {\n\t\t\tquery: false,\n\t\t\theaders: false,\n\t\t\tbody: false,\n\t\t\tcookie: false,\n\t\t\tset: false,\n\t\t\tserver: false,\n\t\t\turl: false,\n\t\t\troute: false,\n\t\t\tpath: false\n\t\t}\n\n\t\tconst [parameter, body] = separateFunction(content)\n\n\t\tconst rootParameters = findParameterReference(parameter, fnInference)\n\t\tconst mainParameter = extractMainParameter(rootParameters)\n\n\t\tif (mainParameter) {\n\t\t\tconst aliases = findAlias(mainParameter, body.slice(1, -1))\n\t\t\taliases.splice(0, -1, mainParameter)\n\n\t\t\tlet code = body\n\n\t\t\tif (\n\t\t\t\tcode.charCodeAt(0) === 123 &&\n\t\t\t\tcode.charCodeAt(body.length - 1) === 125\n\t\t\t)\n\t\t\t\tcode = code.slice(1, -1).trim()\n\n\t\t\tif (!isContextPassToFunction(mainParameter, code, fnInference))\n\t\t\t\tinferBodyReference(code, aliases, fnInference)\n\n\t\t\tif (\n\t\t\t\t!fnInference.query &&\n\t\t\t\tcode.includes('return ' + mainParameter + '.query')\n\t\t\t)\n\t\t\t\tfnInference.query = true\n\t\t}\n\n\t\tif (!caches[key]) caches[key] = fnInference\n\n\t\tinference = mergeInference(inference, fnInference)\n\n\t\tif (\n\t\t\tinference.query &&\n\t\t\tinference.headers &&\n\t\t\tinference.body &&\n\t\t\tinference.cookie &&\n\t\t\tinference.set &&\n\t\t\tinference.server &&\n\t\t\tinference.url &&\n\t\t\tinference.route &&\n\t\t\tinference.path\n\t\t)\n\t\t\tbreak\n\t}\n\n\treturn inference\n}\n"
  },
  {
    "path": "src/trace.ts",
    "content": "import { ELYSIA_REQUEST_ID } from './utils'\n\nimport type { Context } from './context'\nimport type { Prettify, RouteSchema, SingletonBase } from './types'\n\nexport type TraceEvent =\n\t| 'request'\n\t| 'parse'\n\t| 'transform'\n\t| 'beforeHandle'\n\t| 'handle'\n\t| 'afterHandle'\n\t| 'mapResponse'\n\t| 'afterResponse'\n\t| 'error'\n\nexport type TraceStream = {\n\tid: number\n\tevent: TraceEvent\n\ttype: 'begin' | 'end'\n\tbegin: number\n\tname?: string\n\ttotal?: number\n}\n\ntype TraceEndDetail = {\n\t/**\n\t * Timestamp of a function after it's executed since the server start\n\t */\n\tend: TraceProcess<'end'>\n\t/**\n\t * Error that was thrown in the lifecycle\n\t */\n\terror: Error | null\n\t/**\n\t * Elapsed time of the lifecycle\n\t */\n\telapsed: number\n}\n\nexport type TraceProcess<\n\tType extends 'begin' | 'end' = 'begin' | 'end',\n\tWithChildren extends boolean = true\n> = Type extends 'begin'\n\t? Prettify<\n\t\t\t{\n\t\t\t\t/**\n\t\t\t\t * Function name\n\t\t\t\t */\n\t\t\t\tname: string\n\t\t\t\t/**\n\t\t\t\t * Timestamp of a function is called since the server start\n\t\t\t\t */\n\t\t\t\tbegin: number\n\t\t\t\t/**\n\t\t\t\t * Timestamp of a function after it's executed since the server start\n\t\t\t\t */\n\t\t\t\tend: Promise<number>\n\t\t\t\t/**\n\t\t\t\t * Error that was thrown in the lifecycle\n\t\t\t\t */\n\t\t\t\terror: Promise<Error | null>\n\t\t\t\t/**\n\t\t\t\t * Listener to intercept the end of the lifecycle\n\t\t\t\t *\n\t\t\t\t * If you want to mutate the context, you must do it in this function\n\t\t\t\t * as there's a lock mechanism to ensure the context is mutate successfully\n\t\t\t\t */\n\t\t\t\tonStop(\n\t\t\t\t\t/**\n\t\t\t\t\t * A callback function that will be called when the function ends\n\t\t\t\t\t *\n\t\t\t\t\t * If you want to mutate the context, you must do it in this function\n\t\t\t\t\t * as there's a lock mechanism to ensure the context is mutate successfully\n\t\t\t\t\t */\n\t\t\t\t\tcallback?: (detail: TraceEndDetail) => unknown\n\t\t\t\t): Promise<void>\n\t\t\t} & (WithChildren extends true\n\t\t\t\t? {\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t * total number of lifecycle's children and\n\t\t\t\t\t\t * total number of `onEvent` will be called\n\t\t\t\t\t\t * if there were no early exists or error thrown\n\t\t\t\t\t\t */\n\t\t\t\t\t\ttotal: number\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t * Listener to intercept each child lifecycle\n\t\t\t\t\t\t */\n\t\t\t\t\t\tonEvent(\n\t\t\t\t\t\t\t/**\n\t\t\t\t\t\t\t * Callback function that will be called for when each child start\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tcallback?: (\n\t\t\t\t\t\t\t\tprocess: TraceProcess<'begin', false>\n\t\t\t\t\t\t\t) => unknown\n\t\t\t\t\t\t): Promise<void>\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t * Index of the child event\n\t\t\t\t\t\t */\n\t\t\t\t\t\tindex: number\n\t\t\t\t\t})\n\t\t>\n\t: number\n\nexport type TraceListener = (\n\tcallback?: (process: TraceProcess<'begin'>) => unknown\n) => Promise<TraceProcess<'begin'>>\n\nexport type TraceHandler<\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t}\n> = {\n\t(\n\t\tlifecycle: Prettify<\n\t\t\t{\n\t\t\t\tid: number\n\t\t\t\tcontext: Context<Route, Singleton>\n\t\t\t\tset: Context['set']\n\t\t\t\ttime: number\n\t\t\t\tstore: Singleton['store']\n\t\t\t\tresponse: unknown\n\t\t\t} & {\n\t\t\t\t[x in `on${Capitalize<TraceEvent>}`]: TraceListener\n\t\t\t}\n\t\t>\n\t): unknown\n}\n\nexport const ELYSIA_TRACE = Symbol('ElysiaTrace')\n\nconst createProcess = () => {\n\tconst { promise, resolve } = Promise.withResolvers<TraceProcess>()\n\tconst { promise: end, resolve: resolveEnd } =\n\t\tPromise.withResolvers<number>()\n\tconst { promise: error, resolve: resolveError } =\n\t\tPromise.withResolvers<Error | null>()\n\n\tconst callbacks = <Function[]>[]\n\tconst callbacksEnd = <Function[]>[]\n\n\treturn [\n\t\t(callback?: Function) => {\n\t\t\tif (callback) callbacks.push(callback)\n\n\t\t\treturn promise\n\t\t},\n\t\t(process: TraceStream) => {\n\t\t\tconst processes = <((callback?: Function) => Promise<void>)[]>[]\n\t\t\tconst resolvers = <((process: TraceStream) => () => void)[]>[]\n\n\t\t\t// When error is return but not thrown\n\t\t\tlet groupError: Error | null = null\n\n\t\t\tfor (let i = 0; i < (process.total ?? 0); i++) {\n\t\t\t\tconst { promise, resolve } = Promise.withResolvers<void>()\n\t\t\t\tconst { promise: end, resolve: resolveEnd } =\n\t\t\t\t\tPromise.withResolvers<number>()\n\t\t\t\tconst { promise: error, resolve: resolveError } =\n\t\t\t\t\tPromise.withResolvers<Error | null>()\n\n\t\t\t\tconst callbacks = <Function[]>[]\n\t\t\t\tconst callbacksEnd = <Function[]>[]\n\n\t\t\t\tprocesses.push((callback?: Function) => {\n\t\t\t\t\tif (callback) callbacks.push(callback)\n\n\t\t\t\t\treturn promise\n\t\t\t\t})\n\n\t\t\t\tresolvers.push((process: TraceStream) => {\n\t\t\t\t\tconst result = {\n\t\t\t\t\t\t...process,\n\t\t\t\t\t\tend,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tindex: i,\n\t\t\t\t\t\tonStop(callback?: Function) {\n\t\t\t\t\t\t\tif (callback) callbacksEnd.push(callback)\n\n\t\t\t\t\t\t\treturn end\n\t\t\t\t\t\t}\n\t\t\t\t\t} as any\n\n\t\t\t\t\tresolve(result)\n\t\t\t\t\tfor (let i = 0; i < callbacks.length; i++)\n\t\t\t\t\t\tcallbacks[i](result)\n\n\t\t\t\t\treturn (error: Error | null = null) => {\n\t\t\t\t\t\tconst end = performance.now()\n\n\t\t\t\t\t\t// Catch return error\n\t\t\t\t\t\tif (error) groupError = error\n\n\t\t\t\t\t\tconst detail = {\n\t\t\t\t\t\t\tend,\n\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\tget elapsed() {\n\t\t\t\t\t\t\t\treturn end - process.begin\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (let i = 0; i < callbacksEnd.length; i++)\n\t\t\t\t\t\t\tcallbacksEnd[i](detail)\n\n\t\t\t\t\t\tresolveEnd(end)\n\t\t\t\t\t\tresolveError(error)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst result = {\n\t\t\t\t...process,\n\t\t\t\tend,\n\t\t\t\terror,\n\t\t\t\tonEvent(callback?: Function) {\n\t\t\t\t\tfor (let i = 0; i < processes.length; i++)\n\t\t\t\t\t\tprocesses[i](callback)\n\t\t\t\t},\n\t\t\t\tonStop(callback?: Function) {\n\t\t\t\t\tif (callback) callbacksEnd.push(callback)\n\n\t\t\t\t\treturn end\n\t\t\t\t}\n\t\t\t} as any\n\n\t\t\tresolve(result)\n\t\t\tfor (let i = 0; i < callbacks.length; i++) callbacks[i](result)\n\n\t\t\treturn {\n\t\t\t\tresolveChild: resolvers,\n\t\t\t\tresolve(error: Error | null = null) {\n\t\t\t\t\tconst end = performance.now()\n\n\t\t\t\t\t// If error is return, parent group will not catch an error\n\t\t\t\t\t// but the child group will catch the error\n\t\t\t\t\tif (!error && groupError) error = groupError\n\n\t\t\t\t\tconst detail = {\n\t\t\t\t\t\tend,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tget elapsed() {\n\t\t\t\t\t\t\treturn end - process.begin\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (let i = 0; i < callbacksEnd.length; i++)\n\t\t\t\t\t\tcallbacksEnd[i](detail)\n\n\t\t\t\t\tresolveEnd(end)\n\t\t\t\t\tresolveError(error)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t] as const\n}\n\nexport const createTracer = (traceListener: TraceHandler) => {\n\treturn (context: Context) => {\n\t\tconst [onRequest, resolveRequest] = createProcess()\n\t\tconst [onParse, resolveParse] = createProcess()\n\t\tconst [onTransform, resolveTransform] = createProcess()\n\t\tconst [onBeforeHandle, resolveBeforeHandle] = createProcess()\n\t\tconst [onHandle, resolveHandle] = createProcess()\n\t\tconst [onAfterHandle, resolveAfterHandle] = createProcess()\n\t\tconst [onError, resolveError] = createProcess()\n\t\tconst [onMapResponse, resolveMapResponse] = createProcess()\n\t\tconst [onAfterResponse, resolveAfterResponse] = createProcess()\n\n\t\ttraceListener({\n\t\t\t// @ts-ignore\n\t\t\tid: context[ELYSIA_REQUEST_ID],\n\t\t\tcontext,\n\t\t\tset: context.set,\n\t\t\t// @ts-ignore\n\t\t\tonRequest,\n\t\t\t// @ts-ignore\n\t\t\tonParse,\n\t\t\t// @ts-ignore\n\t\t\tonTransform,\n\t\t\t// @ts-ignore\n\t\t\tonBeforeHandle,\n\t\t\t// @ts-ignore\n\t\t\tonHandle,\n\t\t\t// @ts-ignore\n\t\t\tonAfterHandle,\n\t\t\t// @ts-ignore\n\t\t\tonMapResponse,\n\t\t\t// @ts-ignore\n\t\t\tonAfterResponse,\n\t\t\t// @ts-ignore\n\t\t\tonError,\n\t\t\ttime: Date.now(),\n\t\t\tstore: context.store\n\t\t})\n\n\t\t// ? This is pass to compiler\n\t\treturn {\n\t\t\trequest: resolveRequest,\n\t\t\tparse: resolveParse,\n\t\t\ttransform: resolveTransform,\n\t\t\tbeforeHandle: resolveBeforeHandle,\n\t\t\thandle: resolveHandle,\n\t\t\tafterHandle: resolveAfterHandle,\n\t\t\terror: resolveError,\n\t\t\tmapResponse: resolveMapResponse,\n\t\t\tafterResponse: resolveAfterResponse\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/type-system/format.ts",
    "content": "import { FormatRegistry } from '@sinclair/typebox'\n\n/**\n * ? Fork of ajv-formats without ajv as dependencies\n *\n * @see https://github.com/ajv-validator/ajv-formats/blob/master/src/formats.ts\n **/\n\n/* eslint-disable no-control-regex */\nexport type FormatName =\n\t| 'date'\n\t| 'time'\n\t| 'date-time'\n\t| 'iso-time'\n\t| 'iso-date-time'\n\t| 'duration'\n\t| 'uri'\n\t| 'uri-reference'\n\t| 'uri-template'\n\t| 'url'\n\t| 'email'\n\t| 'hostname'\n\t| 'ipv4'\n\t| 'ipv6'\n\t| 'regex'\n\t| 'uuid'\n\t| 'json-pointer'\n\t| 'json-pointer-uri-fragment'\n\t| 'relative-json-pointer'\n\t| 'byte'\n\t| 'int32'\n\t| 'int64'\n\t| 'float'\n\t| 'double'\n\t| 'password'\n\t| 'binary'\n\nexport const fullFormats = {\n\t// date: http://tools.ietf.org/html/rfc3339#section-5.6\n\tdate,\n\t// date-time: http://tools.ietf.org/html/rfc3339#section-5.6\n\ttime: getTime(true),\n\t'date-time': getDateTime(true),\n\t'iso-time': getTime(false),\n\t'iso-date-time': getDateTime(false),\n\t// duration: https://tools.ietf.org/html/rfc3339#appendix-A\n\tduration:\n\t\t/^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$/,\n\turi,\n\t'uri-reference':\n\t\t/^(?:[a-z][a-z0-9+\\-.]*:)?(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'\"()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\\?(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,\n\t// uri-template: https://tools.ietf.org/html/rfc6570\n\t'uri-template':\n\t\t/^(?:(?:[^\\x00-\\x20\"'<>%\\\\^`{|}]|%[0-9a-f]{2})|\\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?)*\\})*$/i,\n\t// For the source: https://gist.github.com/dperini/729294\n\t// For test cases: https://mathiasbynens.be/demo/url-regex\n\turl: /^(?:https?|ftp):\\/\\/(?:[^\\s:@]+(?::[^\\s@]*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)(?:\\.(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)*(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$/iu,\n\temail: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,\n\thostname:\n\t\t/^(?=.{1,253}\\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\\.?$/i,\n\t// optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n\tipv4: /^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$/,\n\tipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))$/i,\n\tregex,\n\t// uuid: http://tools.ietf.org/html/rfc4122\n\tuuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,\n\t// JSON-pointer: https://tools.ietf.org/html/rfc6901\n\t// uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A\n\t'json-pointer': /^(?:\\/(?:[^~/]|~0|~1)*)*$/,\n\t'json-pointer-uri-fragment':\n\t\t/^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,\n\t// relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00\n\t'relative-json-pointer': /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/,\n\t// the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types\n\t// byte: https://github.com/miguelmota/is-base64\n\tbyte,\n\t// signed 32 bit integer\n\tint32: { type: 'number', validate: validateInt32 },\n\t// signed 64 bit integer\n\tint64: { type: 'number', validate: validateInt64 },\n\t// C-type float\n\tfloat: { type: 'number', validate: validateNumber },\n\t// C-type double\n\tdouble: { type: 'number', validate: validateNumber },\n\t// hint to the UI to hide input strings\n\tpassword: true,\n\t// unchecked string payload\n\tbinary: true\n} as const\n\nfunction isLeapYear(year: number): boolean {\n\t// https://tools.ietf.org/html/rfc3339#appendix-C\n\treturn year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)\n}\n\nconst DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\nfunction date(str: string): boolean {\n\t// full-date from http://tools.ietf.org/html/rfc3339#section-5.6\n\tconst matches: string[] | null = DATE.exec(str)\n\tif (!matches) return false\n\tconst year: number = +matches[1]\n\tconst month: number = +matches[2]\n\tconst day: number = +matches[3]\n\treturn (\n\t\tmonth >= 1 &&\n\t\tmonth <= 12 &&\n\t\tday >= 1 &&\n\t\tday <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month])\n\t)\n}\n\nconst TIME = /^(\\d\\d):(\\d\\d):(\\d\\d(?:\\.\\d+)?)(z|([+-])(\\d\\d)(?::?(\\d\\d))?)?$/i\n\nfunction getTime(strictTimeZone?: boolean): (str: string) => boolean {\n\treturn function time(str: string): boolean {\n\t\tconst matches: string[] | null = TIME.exec(str)\n\t\tif (!matches) return false\n\t\tconst hr: number = +matches[1]\n\t\tconst min: number = +matches[2]\n\t\tconst sec: number = +matches[3]\n\t\tconst tz: string | undefined = matches[4]\n\t\tconst tzSign: number = matches[5] === '-' ? -1 : 1\n\t\tconst tzH: number = +(matches[6] || 0)\n\t\tconst tzM: number = +(matches[7] || 0)\n\t\tif (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) return false\n\t\tif (hr <= 23 && min <= 59 && sec < 60) return true\n\t\t// leap second\n\t\tconst utcMin = min - tzM * tzSign\n\t\tconst utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0)\n\t\treturn (\n\t\t\t(utcHr === 23 || utcHr === -1) &&\n\t\t\t(utcMin === 59 || utcMin === -1) &&\n\t\t\tsec < 61\n\t\t)\n\t}\n}\n\nexport const parseDateTimeEmptySpace = (str: string) => {\n\tif (str.charCodeAt(str.length - 6) === 32)\n\t\treturn str.slice(0, -6) + '+' + str.slice(-5)\n\n\treturn str\n}\n\nconst DATE_TIME_SEPARATOR = /t|\\s/i\nfunction getDateTime(strictTimeZone?: boolean): (str: string) => boolean {\n\tconst time = getTime(strictTimeZone)\n\n\treturn function date_time(str: string): boolean {\n\t\t// http://tools.ietf.org/html/rfc3339#section-5.6\n\t\tconst dateTime: string[] = str.split(DATE_TIME_SEPARATOR)\n\n\t\treturn dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1])\n\t}\n}\n\nconst NOT_URI_FRAGMENT = /\\/|:/\nconst URI =\n\t/^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\\?(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i\n\nfunction uri(str: string): boolean {\n\t// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required \".\"\n\treturn NOT_URI_FRAGMENT.test(str) && URI.test(str)\n}\n\nconst BYTE =\n\t/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm\n\nfunction byte(str: string): boolean {\n\tBYTE.lastIndex = 0\n\treturn BYTE.test(str)\n}\n\nconst MIN_INT32 = -(2 ** 31)\nconst MAX_INT32 = 2 ** 31 - 1\n\nfunction validateInt32(value: number): boolean {\n\treturn Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32\n}\n\nfunction validateInt64(value: number): boolean {\n\t// JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64\n\treturn Number.isInteger(value)\n}\n\nfunction validateNumber(): boolean {\n\treturn true\n}\n\nconst Z_ANCHOR = /[^\\\\]\\\\Z/\nfunction regex(str: string): boolean {\n\tif (Z_ANCHOR.test(str)) return false\n\ttry {\n\t\tnew RegExp(str)\n\t\treturn true\n\t} catch (e) {\n\t\treturn false\n\t}\n}\n\n/**\n * @license\n *\n * MIT License\n *\n * Copyright (c) 2020 Evgeny Poberezkin\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nconst isISO8601 =\n\t/(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z))|(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z))|(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z))/\n\nconst isFormalDate =\n\t/(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s\\d{2}\\s\\d{4}\\s\\d{2}:\\d{2}:\\d{2}\\sGMT(?:\\+|-)\\d{4}\\s\\([^)]+\\)/\n\nconst isShortenDate =\n\t/^(?:(?:(?:(?:0?[1-9]|[12][0-9]|3[01])[/\\s-](?:0?[1-9]|1[0-2])[/\\s-](?:19|20)\\d{2})|(?:(?:19|20)\\d{2}[/\\s-](?:0?[1-9]|1[0-2])[/\\s-](?:0?[1-9]|[12][0-9]|3[01]))))(?:\\s(?:1[012]|0?[1-9]):[0-5][0-9](?::[0-5][0-9])?(?:\\s[AP]M)?)?$/\n\nconst _validateDate = fullFormats.date\nconst _validateDateTime = fullFormats['date-time']\n\nif (!FormatRegistry.Has('date'))\n\tFormatRegistry.Set('date', (value: string) => {\n\t\t// Remove quote from stringified date\n\t\tconst temp = parseDateTimeEmptySpace(value).replace(/\"/g, '')\n\n\t\tif (\n\t\t\tisISO8601.test(temp) ||\n\t\t\tisFormalDate.test(temp) ||\n\t\t\tisShortenDate.test(temp) ||\n\t\t\t_validateDate(temp)\n\t\t) {\n\t\t\tconst date = new Date(temp)\n\t\t\tif (!Number.isNaN(date.getTime())) return true\n\t\t}\n\n\t\treturn false\n\t})\n\nif (!FormatRegistry.Has('date-time'))\n\tFormatRegistry.Set('date-time', (value: string) => {\n\t\t// Remove quote from stringified date\n\t\tconst temp = value.replace(/\"/g, '')\n\n\t\tif (\n\t\t\tisISO8601.test(temp) ||\n\t\t\tisFormalDate.test(temp) ||\n\t\t\tisShortenDate.test(temp) ||\n\t\t\t_validateDateTime(temp)\n\t\t) {\n\t\t\tconst date = new Date(temp)\n\t\t\tif (!Number.isNaN(date.getTime())) return true\n\t\t}\n\n\t\treturn false\n\t})\n\nObject.entries(fullFormats).forEach((formatEntry) => {\n\tconst [formatName, formatValue] = formatEntry\n\n\tif (!FormatRegistry.Has(formatName)) {\n\t\tif (formatValue instanceof RegExp)\n\t\t\tFormatRegistry.Set(formatName, (value) => formatValue.test(value))\n\t\telse if (typeof formatValue === 'function')\n\t\t\tFormatRegistry.Set(formatName, formatValue)\n\t}\n})\n\nif (!FormatRegistry.Has('numeric'))\n\tFormatRegistry.Set('numeric', (value) => !!value && !isNaN(+value))\n\nif (!FormatRegistry.Has('integer'))\n\tFormatRegistry.Set(\n\t\t'integer',\n\t\t(value) => !!value && Number.isInteger(+value)\n\t)\n\nif (!FormatRegistry.Has('boolean'))\n\tFormatRegistry.Set(\n\t\t'boolean',\n\t\t(value) => value === 'true' || value === 'false'\n\t)\n\nif (!FormatRegistry.Has('ObjectString'))\n\tFormatRegistry.Set('ObjectString', (value) => {\n\t\tlet start = value.charCodeAt(0)\n\n\t\t// If starts with ' ', '\\t', '\\n', then trim first\n\t\tif (start === 9 || start === 10 || start === 32)\n\t\t\tstart = value.trimStart().charCodeAt(0)\n\n\t\tif (start !== 123 && start !== 91) return false\n\n\t\ttry {\n\t\t\tJSON.parse(value)\n\n\t\t\treturn true\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t})\n\nif (!FormatRegistry.Has('ArrayString'))\n\tFormatRegistry.Set('ArrayString', (value) => {\n\t\tlet start = value.charCodeAt(0)\n\n\t\t// If starts with ' ', '\\t', '\\n', then trim first\n\t\tif (start === 9 || start === 10 || start === 32)\n\t\t\tstart = value.trimStart().charCodeAt(0)\n\n\t\tif (start !== 123 && start !== 91) return false\n\n\t\ttry {\n\t\t\tJSON.parse(value)\n\n\t\t\treturn true\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t})\n"
  },
  {
    "path": "src/type-system/index.ts",
    "content": "import { Type, Kind } from '@sinclair/typebox'\nimport type {\n\tArrayOptions,\n\tDateOptions,\n\tIntegerOptions,\n\tObjectOptions,\n\tSchemaOptions,\n\tTAnySchema,\n\tTArray,\n\tTBoolean,\n\tTDate,\n\tTEnumValue,\n\tTInteger,\n\tTNumber,\n\tTObject,\n\tTProperties,\n\tTSchema,\n\tTString,\n\tNumberOptions,\n\tJavaScriptTypeBuilder,\n\tStringOptions,\n\tTUnsafe,\n\tUint8ArrayOptions,\n\tTEnum\n} from '@sinclair/typebox'\n\nimport {\n\tcompile,\n\tcreateType,\n\tloadFileType,\n\ttryParse,\n\tvalidateFile\n} from './utils'\nimport {\n\tCookieValidatorOptions,\n\tTFile,\n\tTFiles,\n\tFileOptions,\n\tFilesOptions,\n\tNonEmptyArray,\n\tTForm,\n\tTUnionEnum,\n\tElysiaTransformDecodeBuilder,\n\tTArrayBuffer,\n\tAssertNumericEnum\n} from './types'\n\nimport { ELYSIA_FORM_DATA, form } from '../utils'\nimport { ValidationError } from '../error'\nimport { parseDateTimeEmptySpace } from './format'\n\nconst t = Object.assign({}, Type) as unknown as Omit<\n\tJavaScriptTypeBuilder,\n\t'String' | 'Transform'\n> &\n\ttypeof ElysiaType & {\n\t\tTransform<Type extends TSchema>(\n\t\t\ttype: Type\n\t\t): ElysiaTransformDecodeBuilder<Type>\n\t}\n\ncreateType<TUnionEnum>(\n\t'UnionEnum',\n\t(schema, value) =>\n\t\t(typeof value === 'number' ||\n\t\t\ttypeof value === 'string' ||\n\t\t\tvalue === null) &&\n\t\tschema.enum.includes(value as never)\n)\n\ncreateType<TArrayBuffer>(\n\t'ArrayBuffer',\n\t(schema, value) => value instanceof ArrayBuffer\n)\n\nconst internalFiles = createType<FilesOptions, File[]>(\n\t'Files',\n\t(options, value) => {\n\t\tif (options.minItems && options.minItems > 1 && !Array.isArray(value))\n\t\t\treturn false\n\n\t\tif (!Array.isArray(value)) return validateFile(options, value)\n\n\t\tif (options.minItems && value.length < options.minItems) return false\n\t\tif (options.maxItems && value.length > options.maxItems) return false\n\n\t\tfor (let i = 0; i < value.length; i++)\n\t\t\tif (!validateFile(options, value[i])) return false\n\n\t\treturn true\n\t}\n) as unknown as TFiles\n\nconst internalFormData = createType<TForm, FormData>(\n\t'ElysiaForm',\n\t({ compiler, ...schema }, value) => {\n\t\tif (!(value instanceof FormData)) return false\n\n\t\tif (compiler) {\n\t\t\tif (!(ELYSIA_FORM_DATA in value))\n\t\t\t\tthrow new ValidationError('property', schema, value)\n\n\t\t\tif (!compiler.Check(value[ELYSIA_FORM_DATA]))\n\t\t\t\tthrow compiler.Error(value[ELYSIA_FORM_DATA])\n\t\t}\n\n\t\treturn true\n\t}\n) as unknown as TForm\n\ninterface ElysiaStringOptions extends StringOptions {\n\t/**\n\t * Whether the value include JSON escape sequences or not\n\t *\n\t * When using JSON Accelerator, this will bypass the JSON escape sequence validation\n\t *\n\t * Set to `true` if the value doesn't include JSON escape sequences\n\t *\n\t * @default false\n\t */\n\ttrusted?: boolean\n}\n\nexport const ElysiaType = {\n\t// @ts-ignore\n\tString: (property?: ElysiaStringOptions) => Type.String(property),\n\tNumeric: (property?: NumberOptions) => {\n\t\tconst schema = Type.Number(property)\n\t\tconst compiler = compile(schema)\n\n\t\treturn t\n\t\t\t.Transform(\n\t\t\t\tt.Union(\n\t\t\t\t\t[\n\t\t\t\t\t\tt.String({\n\t\t\t\t\t\t\tformat: 'numeric',\n\t\t\t\t\t\t\tdefault: 0\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tt.Number(property)\n\t\t\t\t\t],\n\t\t\t\t\tproperty\n\t\t\t\t)\n\t\t\t)\n\t\t\t.Decode((value) => {\n\t\t\t\tconst number = +value\n\t\t\t\tif (isNaN(number)) return value\n\n\t\t\t\tif (property && !compiler.Check(number))\n\t\t\t\t\tthrow compiler.Error(number)\n\n\t\t\t\treturn number\n\t\t\t})\n\t\t\t.Encode((value) => value) as any as TNumber\n\t},\n\n\tNumericEnum<T extends AssertNumericEnum<T>>(\n\t\titem: T,\n\t\tproperty?: SchemaOptions\n\t) {\n\t\tconst schema = Type.Enum(item, property)\n\t\tconst compiler = compile(schema)\n\n\t\treturn t\n\t\t\t.Transform(\n\t\t\t\tt.Union([t.String({ format: 'numeric' }), t.Number()], property)\n\t\t\t)\n\t\t\t.Decode((value) => {\n\t\t\t\tconst number = +value\n\t\t\t\tif (isNaN(number)) throw compiler.Error(number)\n\t\t\t\tif (!compiler.Check(number)) throw compiler.Error(number)\n\t\t\t\treturn number\n\t\t\t})\n\t\t\t.Encode((value) => value) as any as TEnum<T>\n\t},\n\n\tInteger: (property?: IntegerOptions): TInteger => {\n\t\tconst schema = Type.Integer(property)\n\t\tconst compiler = compile(schema)\n\n\t\treturn t\n\t\t\t.Transform(\n\t\t\t\tt.Union(\n\t\t\t\t\t[\n\t\t\t\t\t\tt.String({\n\t\t\t\t\t\t\tformat: 'integer',\n\t\t\t\t\t\t\tdefault: 0\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tType.Integer(property)\n\t\t\t\t\t],\n\t\t\t\t\tproperty\n\t\t\t\t)\n\t\t\t)\n\t\t\t.Decode((value) => {\n\t\t\t\tconst number = +value\n\n\t\t\t\tif (!compiler.Check(number)) throw compiler.Error(number)\n\n\t\t\t\treturn number\n\t\t\t})\n\t\t\t.Encode((value) => value) as any as TInteger\n\t},\n\n\tDate: (property?: DateOptions) => {\n\t\tconst schema = Type.Date(property)\n\t\tconst compiler = compile(schema)\n\n\t\tconst _default = property?.default\n\t\t\t? new Date(property.default) // in case the default is an ISO string or milliseconds from epoch\n\t\t\t: undefined\n\n\t\treturn t\n\t\t\t.Transform(\n\t\t\t\tt.Union(\n\t\t\t\t\t[\n\t\t\t\t\t\tType.Date(property),\n\t\t\t\t\t\tt.String({\n\t\t\t\t\t\t\tformat: 'date-time',\n\t\t\t\t\t\t\tdefault: _default?.toISOString()\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tt.String({\n\t\t\t\t\t\t\tformat: 'date',\n\t\t\t\t\t\t\tdefault: _default?.toISOString()\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tt.Number({ default: _default?.getTime() })\n\t\t\t\t\t],\n\t\t\t\t\tproperty\n\t\t\t\t)\n\t\t\t)\n\t\t\t.Decode((value) => {\n\t\t\t\tif (typeof value === 'number') {\n\t\t\t\t\tconst date = new Date(value)\n\n\t\t\t\t\tif (!compiler.Check(date)) throw compiler.Error(date)\n\n\t\t\t\t\treturn date\n\t\t\t\t}\n\n\t\t\t\tif (value instanceof Date) return value\n\n\t\t\t\tconst date = new Date(parseDateTimeEmptySpace(value))\n\n\t\t\t\tif (!date || isNaN(date.getTime()))\n\t\t\t\t\tthrow new ValidationError('property', schema, date)\n\n\t\t\t\tif (!compiler.Check(date)) throw compiler.Error(date)\n\n\t\t\t\treturn date\n\t\t\t})\n\t\t\t.Encode((value) => {\n\t\t\t\tif (value instanceof Date) return value.toISOString()\n\t\t\t\tif (typeof value === 'string') {\n\t\t\t\t\tconst parsed = new Date(parseDateTimeEmptySpace(value))\n\n\t\t\t\t\tif (isNaN(parsed.getTime()))\n\t\t\t\t\t\tthrow new ValidationError('property', schema, value)\n\n\t\t\t\t\treturn parsed.toISOString()\n\t\t\t\t}\n\n\t\t\t\tif (!compiler.Check(value)) throw compiler.Error(value)\n\n\t\t\t\treturn value\n\t\t\t}) as any as TDate\n\t},\n\n\tBooleanString: (property?: SchemaOptions) => {\n\t\tconst schema = Type.Boolean(property)\n\t\tconst compiler = compile(schema)\n\n\t\treturn t\n\t\t\t.Transform(\n\t\t\t\tt.Union(\n\t\t\t\t\t[\n\t\t\t\t\t\tt.Boolean(property),\n\t\t\t\t\t\tt.String({\n\t\t\t\t\t\t\tformat: 'boolean',\n\t\t\t\t\t\t\tdefault: false\n\t\t\t\t\t\t})\n\t\t\t\t\t],\n\t\t\t\t\tproperty\n\t\t\t\t)\n\t\t\t)\n\t\t\t.Decode((value) => {\n\t\t\t\tif (typeof value === 'string') return value === 'true'\n\n\t\t\t\tif (value !== undefined && !compiler.Check(value))\n\t\t\t\t\tthrow compiler.Error(value)\n\n\t\t\t\treturn value\n\t\t\t})\n\t\t\t.Encode((value) => value) as any as TBoolean\n\t},\n\n\tObjectString: <T extends TProperties>(\n\t\tproperties: T,\n\t\toptions?: ObjectOptions\n\t) => {\n\t\tconst schema = t.Object(properties, options)\n\t\tconst compiler = compile(schema)\n\n\t\treturn t\n\t\t\t.Transform(\n\t\t\t\tt.Union(\n\t\t\t\t\t[\n\t\t\t\t\t\tt.String({\n\t\t\t\t\t\t\tformat: 'ObjectString',\n\t\t\t\t\t\t\tdefault: options?.default\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tschema\n\t\t\t\t\t],\n\t\t\t\t\t{\n\t\t\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t)\n\t\t\t.Decode((value) => {\n\t\t\t\tif (typeof value === 'string') {\n\t\t\t\t\tif (value.charCodeAt(0) !== 123)\n\t\t\t\t\t\tthrow new ValidationError('property', schema, value)\n\n\t\t\t\t\tif (!compiler.Check((value = tryParse(value, schema))))\n\t\t\t\t\t\tthrow compiler.Error(value)\n\n\t\t\t\t\treturn compiler.Decode(value)\n\t\t\t\t}\n\n\t\t\t\treturn value\n\t\t\t})\n\t\t\t.Encode((value) => {\n\t\t\t\tlet original\n\t\t\t\tif (typeof value === 'string')\n\t\t\t\t\tvalue = tryParse((original = value), schema)\n\n\t\t\t\tif (!compiler.Check(value)) throw compiler.Error(value)\n\n\t\t\t\treturn original ?? JSON.stringify(value)\n\t\t\t}) as any as TObject<T>\n\t},\n\n\tArrayString: <T extends TSchema = TString>(\n\t\tchildren: T = t.String() as any,\n\t\toptions?: ArrayOptions\n\t) => {\n\t\tconst schema = t.Array(children, options)\n\t\tconst compiler = compile(schema)\n\n\t\tconst decode = (value: string, isProperty = false) => {\n\t\t\tif (value.charCodeAt(0) === 91) {\n\t\t\t\tif (!compiler.Check((value = tryParse(value, schema))))\n\t\t\t\t\tthrow compiler.Error(value)\n\n\t\t\t\treturn compiler.Decode(value)\n\t\t\t}\n\n\t\t\t// has , (as used in nuqs)\n\t\t\t// if (value.indexOf(',') !== -1) {\n\t\t\t// \t// const newValue = value.split(',').map((v) => v.trim())\n\n\t\t\t// \tif (!compiler.Check(value)) throw compiler.Error(value)\n\n\t\t\t// \treturn compiler.Decode(value)\n\t\t\t// }\n\n\t\t\tif (isProperty) return value\n\n\t\t\tthrow new ValidationError('property', schema, value)\n\t\t}\n\n\t\treturn t\n\t\t\t.Transform(\n\t\t\t\tt.Union(\n\t\t\t\t\t[\n\t\t\t\t\t\tt.String({\n\t\t\t\t\t\t\tformat: 'ArrayString',\n\t\t\t\t\t\t\tdefault: options?.default\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tschema\n\t\t\t\t\t],\n\t\t\t\t\t{\n\t\t\t\t\t\telysiaMeta: 'ArrayString'\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t)\n\t\t\t.Decode((value) => {\n\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\tlet values = <unknown[]>[]\n\n\t\t\t\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\t\t\t\tconst v = value[i]\n\t\t\t\t\t\tif (typeof v === 'string') {\n\t\t\t\t\t\t\tconst t = decode(v, true)\n\t\t\t\t\t\t\tif (Array.isArray(t)) values = values.concat(t)\n\t\t\t\t\t\t\telse values.push(t)\n\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvalues.push(v)\n\t\t\t\t\t}\n\n\t\t\t\t\treturn values\n\t\t\t\t}\n\n\t\t\t\tif (typeof value === 'string') return decode(value)\n\n\t\t\t\t// Is probably transformed, unable to check schema\n\t\t\t\treturn value\n\t\t\t})\n\t\t\t.Encode((value) => {\n\t\t\t\tlet original\n\t\t\t\tif (typeof value === 'string')\n\t\t\t\t\tvalue = tryParse((original = value), schema)\n\n\t\t\t\tif (!compiler.Check(value))\n\t\t\t\t\tthrow new ValidationError('property', schema, value)\n\n\t\t\t\treturn original ?? JSON.stringify(value)\n\t\t\t}) as any as TArray<T>\n\t},\n\n\tArrayQuery: <T extends TSchema = TString>(\n\t\tchildren: T = t.String() as any,\n\t\toptions?: ArrayOptions\n\t) => {\n\t\tconst schema = t.Array(children, options)\n\t\tconst compiler = compile(schema)\n\n\t\tconst decode = (value: string) => {\n\t\t\t// has , (as used in nuqs)\n\t\t\tif (value.indexOf(',') !== -1)\n\t\t\t\treturn compiler.Decode(value.split(','))\n\n\t\t\treturn compiler.Decode([value])\n\t\t}\n\n\t\treturn t\n\t\t\t.Transform(\n\t\t\t\tt.Union(\n\t\t\t\t\t[\n\t\t\t\t\t\tt.String({\n\t\t\t\t\t\t\tdefault: options?.default\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tschema\n\t\t\t\t\t],\n\t\t\t\t\t{\n\t\t\t\t\t\telysiaMeta: 'ArrayQuery'\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t)\n\t\t\t.Decode((value) => {\n\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\tlet values = <unknown[]>[]\n\n\t\t\t\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\t\t\t\tconst v = value[i]\n\t\t\t\t\t\tif (typeof v === 'string') {\n\t\t\t\t\t\t\tconst t = decode(v)\n\t\t\t\t\t\t\tif (Array.isArray(t)) values = values.concat(t)\n\t\t\t\t\t\t\telse values.push(t)\n\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvalues.push(v)\n\t\t\t\t\t}\n\n\t\t\t\t\treturn values\n\t\t\t\t}\n\n\t\t\t\tif (typeof value === 'string') return decode(value)\n\n\t\t\t\t// Is probably transformed, unable to check schema\n\t\t\t\treturn value\n\t\t\t})\n\t\t\t.Encode((value) => {\n\t\t\t\tlet original\n\t\t\t\tif (typeof value === 'string')\n\t\t\t\t\tvalue = tryParse((original = value), schema)\n\n\t\t\t\tif (!compiler.Check(value))\n\t\t\t\t\tthrow new ValidationError('property', schema, value)\n\n\t\t\t\treturn original ?? JSON.stringify(value)\n\t\t\t}) as any as TArray<T>\n\t},\n\n\tFile: createType<FileOptions, File>(\n\t\t'File',\n\t\tvalidateFile\n\t) as unknown as TFile,\n\n\tFiles: (options: FilesOptions = {}): TUnsafe<File[]> =>\n\t\tt\n\t\t\t.Transform(internalFiles(options))\n\t\t\t.Decode((value) => {\n\t\t\t\tif (Array.isArray(value)) return value\n\t\t\t\treturn [value]\n\t\t\t})\n\t\t\t.Encode((value) => value) as unknown as TUnsafe<File[]>,\n\n\tNullable: <T extends TSchema>(schema: T, options?: SchemaOptions) =>\n\t\tt.Union([schema, t.Null()], {\n\t\t\t...options,\n\t\t\tnullable: true\n\t\t}),\n\n\t/**\n\t * Allow Optional, Nullable and Undefined\n\t */\n\tMaybeEmpty: <T extends TSchema>(schema: T, options?: SchemaOptions) =>\n\t\tt.Union([schema, t.Null(), t.Undefined()], options),\n\n\tCookie: <T extends TProperties>(\n\t\tproperties: T,\n\t\t{\n\t\t\tdomain,\n\t\t\texpires,\n\t\t\thttpOnly,\n\t\t\tmaxAge,\n\t\t\tpath,\n\t\t\tpriority,\n\t\t\tsameSite,\n\t\t\tsecure,\n\t\t\tsecrets,\n\t\t\tsign,\n\t\t\t...options\n\t\t}: CookieValidatorOptions<T> = {}\n\t) => {\n\t\tconst v = t.Object(properties, options)\n\n\t\tv.config = {\n\t\t\tdomain,\n\t\t\texpires,\n\t\t\thttpOnly,\n\t\t\tmaxAge,\n\t\t\tpath,\n\t\t\tpriority,\n\t\t\tsameSite,\n\t\t\tsecure,\n\t\t\tsecrets,\n\t\t\tsign\n\t\t}\n\n\t\treturn v\n\t},\n\n\tUnionEnum: <\n\t\tconst T extends\n\t\t\t| NonEmptyArray<TEnumValue>\n\t\t\t| Readonly<NonEmptyArray<TEnumValue>>\n\t>(\n\t\tvalues: T,\n\t\toptions: SchemaOptions = {}\n\t) => {\n\t\tconst type = values.every((value) => typeof value === 'string')\n\t\t\t? { type: 'string' }\n\t\t\t: values.every((value) => typeof value === 'number')\n\t\t\t\t? { type: 'number' }\n\t\t\t\t: values.every((value) => value === null)\n\t\t\t\t\t? { type: 'null' }\n\t\t\t\t\t: {}\n\n\t\tif (values.some((x) => typeof x === 'object' && x !== null))\n\t\t\tthrow new Error('This type does not support objects or arrays')\n\n\t\treturn {\n\t\t\t// default is need for generating error message\n\t\t\tdefault: values[0],\n\t\t\t...options,\n\t\t\t[Kind]: 'UnionEnum',\n\t\t\t...type,\n\t\t\tenum: values\n\t\t} as any as TUnionEnum<T>\n\t},\n\n\tNoValidate: <T extends TAnySchema>(v: T, enabled = true) => {\n\t\tv.noValidate = enabled\n\n\t\treturn v\n\t},\n\n\tForm: <T extends TProperties>(\n\t\tv: T,\n\t\toptions: ObjectOptions = {}\n\t): TForm<T> => {\n\t\tconst schema = t.Object(v, {\n\t\t\tdefault: form({}),\n\t\t\t...options\n\t\t})\n\t\tconst compiler = compile(schema)\n\n\t\treturn t.Union([\n\t\t\tschema,\n\t\t\t// @ts-expect-error\n\t\t\tinternalFormData({\n\t\t\t\tcompiler\n\t\t\t})\n\t\t])\n\t},\n\n\tArrayBuffer(options: TArrayBuffer = {}) {\n\t\treturn {\n\t\t\t// default is need for generating error message\n\t\t\tdefault: [1, 2, 3],\n\t\t\t...options,\n\t\t\t[Kind]: 'ArrayBuffer'\n\t\t} as any as TUnsafe<ArrayBuffer>\n\t},\n\n\tUint8Array: (options: Uint8ArrayOptions) => {\n\t\tconst schema = Type.Uint8Array(options)\n\t\tconst compiler = compile(schema)\n\n\t\treturn t\n\t\t\t.Transform(t.Union([t.ArrayBuffer(), Type.Uint8Array(options)]))\n\t\t\t.Decode((value) => {\n\t\t\t\tif (value instanceof ArrayBuffer) {\n\t\t\t\t\tif (!compiler.Check((value = new Uint8Array(value))))\n\t\t\t\t\t\tthrow compiler.Error(value)\n\n\t\t\t\t\treturn value\n\t\t\t\t}\n\n\t\t\t\treturn value\n\t\t\t})\n\t\t\t.Encode((value) => value) as any as TUnsafe<Uint8Array>\n\t}\n}\n\nt.BooleanString = ElysiaType.BooleanString\nt.ObjectString = ElysiaType.ObjectString\nt.ArrayString = ElysiaType.ArrayString\nt.ArrayQuery = ElysiaType.ArrayQuery\nt.Numeric = ElysiaType.Numeric\nt.NumericEnum = ElysiaType.NumericEnum\nt.Integer = ElysiaType.Integer\n\nt.File = (arg) => {\n\tif (arg?.type) loadFileType()\n\n\treturn ElysiaType.File({\n\t\tdefault: 'File',\n\t\t...arg,\n\t\textension: arg?.type,\n\t\ttype: 'string',\n\t\tformat: 'binary'\n\t})\n}\n\nt.Files = (arg) => {\n\tif (arg?.type) loadFileType()\n\n\treturn ElysiaType.Files({\n\t\t...arg,\n\t\telysiaMeta: 'Files',\n\t\tdefault: 'Files',\n\t\textension: arg?.type,\n\t\ttype: 'array',\n\t\titems: {\n\t\t\t...arg,\n\t\t\tdefault: 'Files',\n\t\t\ttype: 'string',\n\t\t\tformat: 'binary'\n\t\t}\n\t})\n}\n\nt.Nullable = ElysiaType.Nullable\nt.MaybeEmpty = ElysiaType.MaybeEmpty\nt.Cookie = ElysiaType.Cookie\nt.Date = ElysiaType.Date\nt.UnionEnum = ElysiaType.UnionEnum\nt.NoValidate = ElysiaType.NoValidate\nt.Form = ElysiaType.Form\n\nt.ArrayBuffer = ElysiaType.ArrayBuffer\nt.Uint8Array = ElysiaType.Uint8Array as any\n\nexport { t }\n\nexport {\n\tTypeSystemPolicy,\n\tTypeSystem,\n\tTypeSystemDuplicateFormat,\n\tTypeSystemDuplicateTypeKind\n} from '@sinclair/typebox/system'\nexport { TypeRegistry, FormatRegistry } from '@sinclair/typebox'\nexport { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler'\n"
  },
  {
    "path": "src/type-system/types.ts",
    "content": "import type {\n\tKind,\n\tObjectOptions,\n\tSchemaOptions,\n\tStaticDecode,\n\tTObject,\n\tTProperties,\n\tTransformKind,\n\tTSchema,\n\tTUnsafe,\n\tUint8ArrayOptions\n} from '@sinclair/typebox'\nimport type { ValueError } from '@sinclair/typebox/errors'\nimport type { TypeCheck } from '@sinclair/typebox/compiler'\n\nimport type { ElysiaFormData } from '../utils'\nimport type { CookieOptions } from '../cookies'\nimport type { MaybeArray } from '../types'\n\nexport type FileUnit = number | `${number}${'k' | 'm'}`\n\nexport type StrictFileType =\n\t| 'image'\n\t| 'image/*'\n\t| 'image/jpeg'\n\t| 'image/png'\n\t| 'image/gif'\n\t| 'image/tiff'\n\t| 'image/x-icon'\n\t| 'image/svg'\n\t| 'image/webp'\n\t| 'image/avif'\n\t| 'audio'\n\t| 'audio/*'\n\t| 'audio/aac'\n\t| 'audio/mpeg'\n\t| 'audio/x-ms-wma'\n\t| 'audio/vnd.rn-realaudio'\n\t| 'audio/x-wav'\n\t| 'video'\n\t| 'video/*'\n\t| 'video/mpeg'\n\t| 'video/mp4'\n\t| 'video/quicktime'\n\t| 'video/x-ms-wmv'\n\t| 'video/x-msvideo'\n\t| 'video/x-flv'\n\t| 'video/webm'\n\t| 'text'\n\t| 'text/*'\n\t| 'text/css'\n\t| 'text/csv'\n\t| 'text/html'\n\t| 'text/javascript'\n\t| 'text/plain'\n\t| 'text/xml'\n\t| 'application'\n\t| 'application/*'\n\t| 'application/graphql'\n\t| 'application/graphql-response+json'\n\t| 'application/ogg'\n\t| 'application/pdf'\n\t| 'application/xhtml'\n\t| 'application/xhtml+html'\n\t| 'application/xml-dtd'\n\t| 'application/html'\n\t| 'application/json'\n\t| 'application/ld+json'\n\t| 'application/xml'\n\t| 'application/zip'\n\t| 'font'\n\t| 'font/*'\n\t| 'font/woff2'\n\t| 'font/woff'\n\t| 'font/ttf'\n\t| 'font/otf'\n\nexport type FileType = (string & {}) | StrictFileType\n\nexport interface FileOptions extends SchemaOptions {\n\ttype?: MaybeArray<FileType>\n\t/**\n\t * Each file must be at least the specified size.\n\t *\n\t * @example '600k' (600 kilobytes), '3m' (3 megabytes)\n\t */\n\tminSize?: FileUnit\n\t/**\n\t * Each file must be less than or equal to the specified size.\n\t *\n\t * @example '3m' (3 megabytes), '600k' (600 kilobytes)\n\t */\n\tmaxSize?: FileUnit\n}\n\nexport interface FilesOptions extends FileOptions {\n\tminItems?: number\n\tmaxItems?: number\n}\n\nexport interface CookieValidatorOptions<T extends Object = {}>\n\textends ObjectOptions,\n\t\tCookieOptions {\n\t/**\n\t * Secret key for signing cookie\n\t *\n\t * If array is passed, will use Key Rotation.\n\t *\n\t * Key rotation is when an encryption key is retired\n\t * and replaced by generating a new cryptographic key.\n\t */\n\tsecrets?: string | string[]\n\t/**\n\t * Specified cookie name to be signed globally\n\t */\n\tsign?: Readonly<(keyof T | (string & {}))[]>\n}\n\nexport type TFile = (\n\toptions?: Partial<FileOptions> | undefined\n) => TUnsafe<File>\n\nexport type TFiles = (\n\toptions?: Partial<FilesOptions> | undefined\n) => TUnsafe<File[]>\n\nexport type NonEmptyArray<T> = [T, ...T[]]\n\nexport type TEnumValue = number | string | null\n\nexport interface TUnionEnum<\n\tT extends\n\t\t| NonEmptyArray<TEnumValue>\n\t\t| Readonly<NonEmptyArray<TEnumValue>> = [TEnumValue]\n> extends TSchema {\n\ttype?: 'number' | 'string' | 'null'\n\t[Kind]: 'UnionEnum'\n\tstatic: T[number]\n\tenum: T\n}\n\nexport interface TArrayBuffer extends Uint8ArrayOptions {}\n\nexport type TForm<T extends TProperties = TProperties> = TUnsafe<\n\tElysiaFormData<TObject<T>['static']>\n>\n\n/**\n * !important\n * @see https://github.com/elysiajs/elysia/pull/1613\n *\n * Augment this interface to extend allowed values for SchemaOptions['error'].\n * Defining custom string templates will add autocomplete while allowing any arbitrary string, number, etc.\n *\n * The names of keys only used to map to the values, unless you globally augment a specific key.\n *\n * ```ts\n * declare module 'elysia/type-system/types' {\n *   interface ElysiaTypeCustomErrors {\n *     myPlugin: 'my.plugin.error' | `my.plugin.${string}`\n *   }\n * }\n *\n * const schema = t.String({ error: 'my.plugin.hello' })\n * ```\n */\nexport interface ElysiaTypeCustomErrors {\n  /**\n   * The default error types that the library supports.\n   *\n   * `string & {}` `number & {}` are used to allow string templates and numbers respectively.\n   */\n  default: (string & {}) | boolean | (number & {}) | ElysiaTypeCustomErrorCallback\n}\n\nexport type ElysiaTypeCustomError = ElysiaTypeCustomErrors[keyof ElysiaTypeCustomErrors]\n\nexport type ElysiaTypeCustomErrorCallback = (\n\terror: {\n\t\t/**\n\t\t * Error type\n\t\t */\n\t\ttype: 'validation'\n\t\t/**\n\t\t * Where the error was found\n\t\t */\n\t\ton: 'body' | 'query' | 'params' | 'headers' | 'cookie' | 'response'\n\t\tfound: unknown\n\t\t/**\n\t\t * Value that caused the error\n\t\t */\n\t\tvalue: unknown\n\t\t/**\n\t\t * Human readable summary of the error\n\t\t * (omitted on production)\n\t\t */\n\t\tsummary?: string\n\t\t/**\n\t\t * Property that caused the error\n\t\t * (omitted on production)\n\t\t */\n\t\tproperty?: string\n\t\t/**\n\t\t * Error message\n\t\t * (omitted on production)\n\t\t */\n\t\tmessage?: string\n\t\t/**\n\t\t * Expected value\n\t\t * (omitted on production)\n\t\t */\n\t\texpected?: unknown\n\t\t/**\n\t\t * Array of validation errors\n\t\t * (omitted on production)\n\t\t */\n\t\terrors: ValueError[]\n\t},\n\tvalidator: TypeCheck<any>\n) => unknown\n\ndeclare module '@sinclair/typebox' {\n\tinterface SchemaOptions {\n\t\terror?: ElysiaTypeCustomError\n\t}\n}\n\nexport declare class ElysiaTransformDecodeBuilder<T extends TSchema> {\n\tprivate readonly schema\n\tconstructor(schema: T)\n\tDecode<U extends unknown, D extends TransformFunction<StaticDecode<T>, U>>(\n\t\tdecode: D\n\t): ElysiaTransformEncodeBuilder<T, D>\n}\nexport declare class ElysiaTransformEncodeBuilder<\n\tT extends TSchema,\n\tD extends TransformFunction\n> {\n\tprivate readonly schema\n\tprivate readonly decode\n\tconstructor(schema: T, decode: D)\n\tprivate EncodeTransform\n\tprivate EncodeSchema\n\tEncode<E extends TransformFunction<ReturnType<D>, StaticDecode<T>>>(\n\t\tencode: E\n\t): TTransform<T, ReturnType<D>>\n}\nexport type TransformFunction<T = any, U = any> = (value: T) => U\nexport interface TransformOptions<\n\tI extends TSchema = TSchema,\n\tO extends unknown = unknown\n> {\n\tDecode: TransformFunction<StaticDecode<I>, O>\n\tEncode: TransformFunction<O, StaticDecode<I>>\n}\nexport interface TTransform<\n\tI extends TSchema = TSchema,\n\tO extends unknown = unknown\n> extends TSchema {\n\tstatic: O\n\t[TransformKind]: TransformOptions<I, O>\n\t[key: string]: any\n}\n\nexport type AssertNumericEnum<T extends Record<string, string | number>> = {\n\t[K in keyof T]: K extends number\n\t\t? string\n\t\t: K extends `${number}`\n\t\t\t? string\n\t\t\t: K extends string\n\t\t\t\t? number\n\t\t\t\t: never\n}\n"
  },
  {
    "path": "src/type-system/utils.ts",
    "content": "import {\n\tKind,\n\tTUnsafe,\n\tTypeRegistry,\n\tUnsafe,\n\ttype TAnySchema\n} from '@sinclair/typebox'\nimport { Value } from '@sinclair/typebox/value'\nimport { TypeCheck, TypeCompiler } from '@sinclair/typebox/compiler'\n\nimport { ElysiaFile } from '../universal/file'\nimport { InvalidFileType, ValidationError } from '../error'\nimport type {\n\tElysiaTypeCustomErrorCallback,\n\tFileOptions,\n\tFileUnit,\n\tFileType\n} from './types'\nimport type { MaybeArray } from '../types'\n\nexport const tryParse = (v: unknown, schema: TAnySchema) => {\n\ttry {\n\t\treturn JSON.parse(v as string)\n\t} catch {\n\t\tthrow new ValidationError('property', schema, v)\n\t}\n}\n\nexport function createType<TSchema = unknown, TReturn = unknown>(\n\tkind: string,\n\tfunc: TypeRegistry.TypeRegistryValidationFunction<TSchema>\n): TUnsafe<TReturn> {\n\tif (!TypeRegistry.Has(kind)) TypeRegistry.Set<TSchema>(kind, func)\n\n\treturn ((options = {}) => Unsafe({ ...options, [Kind]: kind })) as any\n}\n\nexport const compile = <T extends TAnySchema>(schema: T) => {\n\ttry {\n\t\tconst compiler = TypeCompiler.Compile(schema) as TypeCheck<T> & {\n\t\t\tCreate(): T['static']\n\t\t\tError(v: unknown): asserts v is T['static']\n\t\t}\n\n\t\tcompiler.Create = () => Value.Create(schema)\n\t\tcompiler.Error = (v: unknown) =>\n\t\t\t// @ts-ignore\n\t\t\tnew ValidationError('property', schema, v, compiler.Errors(v))\n\n\t\treturn compiler\n\t} catch {\n\t\treturn {\n\t\t\tCheck: (v: unknown) => Value.Check(schema, v),\n\t\t\tCheckThrow: (v: unknown) => {\n\t\t\t\tif (!Value.Check(schema, v))\n\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t'property',\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\tv,\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tValue.Errors(schema, v)\n\t\t\t\t\t)\n\t\t\t},\n\t\t\tDecode: (v: unknown) => Value.Decode(schema, v),\n\t\t\tCreate: () => Value.Create(schema),\n\t\t\tError: (v: unknown) =>\n\t\t\t\tnew ValidationError(\n\t\t\t\t\t'property',\n\t\t\t\t\tschema,\n\t\t\t\t\tv,\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tValue.Errors(schema, v)\n\t\t\t\t)\n\t\t}\n\t}\n}\n\nexport const parseFileUnit = (size: FileUnit) => {\n\tif (typeof size === 'string')\n\t\tswitch (size.slice(-1)) {\n\t\t\tcase 'k':\n\t\t\t\treturn +size.slice(0, size.length - 1) * 1024\n\n\t\t\tcase 'm':\n\t\t\t\treturn +size.slice(0, size.length - 1) * 1048576\n\n\t\t\tdefault:\n\t\t\t\treturn +size\n\t\t}\n\n\treturn size\n}\n\nexport const checkFileExtension = (type: string, extension: string) => {\n\tif (type.startsWith(extension)) return true\n\n\treturn (\n\t\textension.charCodeAt(extension.length - 1) === 42 &&\n\t\textension.charCodeAt(extension.length - 2) === 47 &&\n\t\ttype.startsWith(extension.slice(0, -1))\n\t)\n}\n\nlet _fileTypeFromBlobWarn = false\nconst warnIfFileTypeIsNotInstalled = () => {\n\tif (!_fileTypeFromBlobWarn) {\n\t\tconsole.warn(\n\t\t\t\"[Elysia] Attempt to validate file type without 'file-type'. This may lead to security risks. We recommend installing 'file-type' to properly validate file extension.\"\n\t\t)\n\t\t_fileTypeFromBlobWarn = true\n\t}\n}\n\nexport const loadFileType = async () =>\n\timport('file-type')\n\t\t.then((x) => {\n\t\t\t_fileTypeFromBlob = x.fileTypeFromBlob\n\t\t\treturn _fileTypeFromBlob\n\t\t})\n\t\t.catch(warnIfFileTypeIsNotInstalled)\n\nlet _fileTypeFromBlob: Function\nexport const fileTypeFromBlob = (file: Blob | File) => {\n\tif (_fileTypeFromBlob) return _fileTypeFromBlob(file)\n\n\treturn loadFileType().then((mod) => {\n\t\tif (mod) return mod(file)\n\t})\n}\n\nexport const fileType = async (\n\tfile: MaybeArray<Blob | File | undefined>,\n\textension: FileType | FileType[],\n\t// @ts-ignore\n\tname = file?.name ?? ''\n): Promise<boolean> => {\n\tif (Array.isArray(file)) {\n\t\tawait Promise.all(file.map((f) => fileType(f, extension, name)))\n\n\t\treturn true\n\t}\n\n\tif (!file) return false\n\n\tconst result = await fileTypeFromBlob(file)\n\tif (!result) throw new InvalidFileType(name, extension)\n\n\tif (typeof extension === 'string')\n\t\tif (!checkFileExtension(result.mime, extension))\n\t\t\tthrow new InvalidFileType(name, extension)\n\n\tfor (let i = 0; i < extension.length; i++)\n\t\tif (checkFileExtension(result.mime, extension[i])) return true\n\n\tthrow new InvalidFileType(name, extension)\n}\n\n/**\n * This only check file extension based on it's name / mimetype\n * to actual check the file type, use `validateFileExtension` instead\n */\nexport const validateFile = (options: FileOptions, value: any) => {\n\tif (value instanceof ElysiaFile) return true\n\n\tif (!(value instanceof Blob)) return false\n\n\tif (options.minSize && value.size < parseFileUnit(options.minSize))\n\t\treturn false\n\n\tif (options.maxSize && value.size > parseFileUnit(options.maxSize))\n\t\treturn false\n\n\tif (options.extension) {\n\t\tif (typeof options.extension === 'string')\n\t\t\treturn checkFileExtension(value.type, options.extension)\n\n\t\tfor (let i = 0; i < options.extension.length; i++)\n\t\t\tif (checkFileExtension(value.type, options.extension[i]))\n\t\t\t\treturn true\n\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n/**\n * Utility function to inherit add custom error and keep the original Validation error\n *\n * @since 1.3.14\n *\n * @example\n * ```ts\n * import { Elysia, t, errorWithDetail } from 'elysia'\n *\n * new Elysia()\n *\t\t.post('/', () => 'Hello World!', {\n *\t\t\tbody: t.Object({\n *\t\t\t\tx: t.Number({\n *\t\t\t\t\terror: validationDetail('x must be a number')\n *\t\t\t\t})\n *\t\t\t})\n *\t\t})\n */\nexport const validationDetail =\n\t<T>(message: T) =>\n\t(error: Parameters<ElysiaTypeCustomErrorCallback>[0]) => ({\n\t\t...error,\n\t\tmessage\n\t})\n"
  },
  {
    "path": "src/types.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport type { Elysia, AnyElysia, InvertedStatusMap } from './index'\nimport type { ElysiaFile } from './universal/file'\nimport type { Serve } from './universal/server'\n\nimport {\n\tTSchema,\n\tTAnySchema,\n\tOptionalKind,\n\tTModule,\n\tTImport,\n\tTProperties\n} from '@sinclair/typebox'\nimport type { TypeCheck, ValueError } from '@sinclair/typebox/compiler'\n\nimport type { OpenAPIV3 } from 'openapi-types'\n\nimport type { ElysiaAdapter } from './adapter'\nimport type { ElysiaTypeCheck } from './schema'\nimport type { Context, ErrorContext, PreContext } from './context'\nimport type { ComposerGeneralHandlerOptions } from './compose'\nimport type { CookieOptions } from './cookies'\nimport type { TraceHandler } from './trace'\nimport type {\n\tElysiaCustomStatusResponse,\n\tInternalServerError,\n\tInvalidCookieSignature,\n\tInvalidFileType,\n\tNotFoundError,\n\tParseError,\n\tValidationError\n} from './error'\n\nimport type { AnyWSLocalHook } from './ws/types'\nimport type { WebSocketHandler } from './ws/bun'\n\nimport type { Instruction as ExactMirrorInstruction } from 'exact-mirror'\nimport { BunHTMLBundlelike } from './universal/types'\nimport { Sucrose } from './sucrose'\nimport type Memoirist from 'memoirist'\nimport type { DynamicHandler } from './dynamic-handle'\n\nexport type Equal<X, Y> =\n\t(<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2\n\t\t? true\n\t\t: false\n\nexport type IsNever<T> = [T] extends [never] ? true : false\n\nexport type PickIfExists<T, K extends string> = {} extends T\n\t? {}\n\t: {\n\t\t\t// @ts-ignore\n\t\t\t[P in K as P extends keyof T ? P : never]: T[P]\n\t\t}\n\n// Standard Schema reduce to bare minimum to save inference time\nexport interface StandardSchemaV1Like<\n\tin out Input = unknown,\n\tin out Output = Input\n> {\n\treadonly '~standard': {\n\t\treadonly types?:\n\t\t\t| {\n\t\t\t\t\treadonly input: Input\n\t\t\t\t\treadonly output: Output\n\t\t\t  }\n\t\t\t| undefined\n\t}\n}\n\n// ? Fast check if the generic is enforced to StandardSchemaV1Like\nexport interface FastStandardSchemaV1Like {\n\treadonly '~standard': {}\n}\n\nexport type StandardSchemaV1LikeValidate = <T>(\n\tv: T\n) => MaybePromise<\n\t{ value: T; issues?: never } | { value?: never; issues: unknown[] }\n>\n\nexport type AnySchema = TSchema | StandardSchemaV1Like\nexport type FastAnySchema = TAnySchema | FastStandardSchemaV1Like\n\nexport interface ElysiaConfig<in out Prefix extends string | undefined> {\n\t/**\n\t * @default BunAdapter\n\t * @since 1.1.11\n\t */\n\tadapter?: ElysiaAdapter\n\t/**\n\t * Path prefix of the instance\n\t *\n\t * @default '''\n\t */\n\tprefix?: Prefix\n\t/**\n\t * Name of the instance for debugging, and plugin deduplication purpose\n\t */\n\tname?: string\n\t/**\n\t * Seed for generating checksum for plugin deduplication\n\t *\n\t * @see https://elysiajs.com/essential/plugin.html#plugin-deduplication\n\t */\n\tseed?: unknown\n\t/**\n\t * Bun serve\n\t *\n\t * @see https://bun.sh/docs/api/http\n\t */\n\tserve?: Partial<Serve>\n\t/**\n\t * OpenAPI documentation (use in Swagger)\n\t *\n\t * @see https://swagger.io/specification/\n\t */\n\tdetail?: DocumentDecoration\n\t/**\n\t * OpenAPI tags\n\t *\n\t * current instance' routes with tags\n\t *\n\t * @see https://swagger.io/specification/#tag-object\n\t */\n\ttags?: DocumentDecoration['tags']\n\t/**\n\t * Warm up Elysia before starting the server\n\t *\n\t * This will perform Ahead of Time compilation and generate code for route handlers\n\t *\n\t * If set to false, Elysia will perform Just in Time compilation\n\t *\n\t * Only required for root instance (instance which use listen) to effect\n\t *\n\t * ! If performing a benchmark, it's recommended to set this to `true`\n\t *\n\t * @default false\n\t */\n\tprecompile?:\n\t\t| boolean\n\t\t| {\n\t\t\t\t/**\n\t\t\t\t * Perform dynamic code generation for route handlers before starting the server\n\t\t\t\t *\n\t\t\t\t * @default false\n\t\t\t\t */\n\t\t\t\tcompose?: boolean\n\t\t\t\t/**\n\t\t\t\t * Perform Ahead of Time compilation for schema before starting the server\n\t\t\t\t *\n\t\t\t\t * @default false\n\t\t\t\t */\n\t\t\t\tschema?: boolean\n\t\t  }\n\t/**\n\t * Enable Ahead of Time compilation\n\t *\n\t * Trade significant performance with slightly faster startup time and reduced memory usage\n\t */\n\taot?: boolean\n\t/**\n\t * Whether should Elysia tolerate suffix '/' or vice-versa\n\t *\n\t * @default false\n\t */\n\tstrictPath?: boolean\n\t/**\n\t * Override websocket configuration\n\t *\n\t * @see https://bun.sh/docs/api/websockets\n\t */\n\twebsocket?: Omit<\n\t\tWebSocketHandler<any>,\n\t\t'open' | 'close' | 'message' | 'drain'\n\t>\n\tcookie?: CookieOptions & {\n\t\t/**\n\t\t * Specified cookie name to be signed globally\n\t\t */\n\t\tsign?: true | string | string[]\n\t}\n\t/**\n\t * Capture more detail information for each dependencies\n\t */\n\tanalytic?: boolean\n\t/**\n\t * If enabled, the schema with `t.Transform` will call `Encode` before sending the response\n\t *\n\t * @default true\n\t * @since 1.3.0\n\t * @since 1.2.16 (experimental)\n\t **/\n\tencodeSchema?: boolean\n\t/**\n\t * Enable experimental features\n\t */\n\texperimental?: {}\n\t/**\n\t * If enabled, Elysia will attempt to coerce value to defined type on incoming and outgoing bodies.\n\t *\n\t * This allows for sending unknown or disallowed properties in the bodies. These will simply be filtered out instead of failing the request.\n\t * This has no effect when the schemas allow additional properties.\n\t * Since this uses dynamic schema it may have an impact on performance.\n\t *\n\t * options:\n\t * - true: use 'exactMirror'\n\t * - false: do not normalize the value\n\t * - 'exactMirror': use Elysia's custom exact-mirror which precompile a schema\n\t * - 'typebox': Since this uses dynamic Value.Clean, it have performance impact\n\t *\n\t * Note: This option only works when Elysia schema is provided, doesn't work with Standard Schema\n\t *\n\t * @default true\n\t */\n\tnormalize?: boolean | 'exactMirror' | 'typebox'\n\thandler?: ComposerGeneralHandlerOptions\n\t/**\n\t * Enable Bun static response\n\t *\n\t * @default true\n\t * @since 1.1.11\n\t */\n\tnativeStaticResponse?: boolean\n\t/**\n\t * Use runtime/framework provided router if possible\n\t *\n\t * @default true\n\t * @since 1.3.0\n\t */\n\tsystemRouter?: boolean\n\t/**\n\t * Array of callback function to transform a string value defined in a schema\n\t *\n\t * This option only works when `sanitlize` is `exactMirror`\n\t *\n\t * This only works when set on the main instance\n\t *\n\t * @default true\n\t * @since 1.3.0\n\t */\n\tsanitize?: ExactMirrorInstruction['sanitize']\n\t/**\n\t * Sucrose (Static Code Analysis) configuration\n\t */\n\tsucrose?: Sucrose.Settings\n\n\t/**\n\t * Allow unsafe validation details in errors thrown by Elysia's schema validator (422 status code)\n\t *\n\t * Ideally, this should only be used in development environment or public APIs\n\t * This may leak sensitive information about the server implementation and should be used with caution in production environments.\n\t *\n\t * @default false\n\t */\n\tallowUnsafeValidationDetails?: boolean\n}\n\nexport interface ValidatorLayer {\n\tglobal: SchemaValidator | null\n\tscoped: SchemaValidator | null\n\tlocal: SchemaValidator | null\n\tgetCandidate(): SchemaValidator\n}\n\nexport interface StandaloneInputSchema<Name extends string = string> {\n\tbody?: AnySchema | Name | `${Name}[]`\n\theaders?: AnySchema | Name | `${Name}[]`\n\tquery?: AnySchema | Name | `${Name}[]`\n\tparams?: AnySchema | Name | `${Name}[]`\n\tcookie?: AnySchema | Name | `${Name}[]`\n\tresponse?: {\n\t\t[status in number]: `${Name}[]` | Name | AnySchema\n\t}\n}\n\nexport interface StandaloneValidator {\n\tglobal: InputSchema[] | null\n\tscoped: InputSchema[] | null\n\tlocal: InputSchema[] | null\n}\n\nexport type MaybeArray<T> = T | T[]\nexport type MaybeReadonlyArray<T> = T | readonly T[]\nexport type MaybePromise<T> = T | Promise<T>\n\nexport type ObjectValues<T extends object> = T[keyof T]\n\ntype IsPathParameter<Part extends string> = Part extends `:${infer Parameter}`\n\t? Parameter\n\t: Part extends `*`\n\t\t? '*'\n\t\t: never\n\nexport type GetPathParameter<Path extends string> =\n\tPath extends `${infer A}/${infer B}`\n\t\t? IsPathParameter<A> | GetPathParameter<B>\n\t\t: IsPathParameter<Path>\n\ntype _ResolvePath<Path extends string> = {\n\t[Param in GetPathParameter<Path> as Param extends `${string}?`\n\t\t? never\n\t\t: Param]: string\n} & {\n\t[Param in GetPathParameter<Path> as Param extends `${infer OptionalParam}?`\n\t\t? OptionalParam\n\t\t: never]?: string\n}\n\nexport type ResolvePath<Path extends string> = Path extends ''\n\t? {}\n\t: Path extends PathParameterLike\n\t\t? _ResolvePath<Path>\n\t\t: {}\n\nexport type Or<T1 extends boolean, T2 extends boolean> = T1 extends true\n\t? true\n\t: T2 extends true\n\t\t? true\n\t\t: false\n\n// https://twitter.com/mattpocockuk/status/1622730173446557697?s=20\nexport type Prettify<in out T> = {\n\t[K in keyof T]: T[K]\n} & {}\n\nexport type NeverKey<in out T> = {\n\t[K in keyof T]?: never\n} & {}\n\ntype IsBothObject<A, B> =\n\tA extends Record<keyof any, any>\n\t\t? B extends Record<keyof any, any>\n\t\t\t? IsClass<A> extends false\n\t\t\t\t? IsClass<B> extends false\n\t\t\t\t\t? true\n\t\t\t\t\t: false\n\t\t\t\t: false\n\t\t\t: false\n\t\t: false\n\ntype IsClass<V> = V extends abstract new (...args: any) => any ? true : false\ntype And<A, B> = A extends true ? (B extends true ? true : false) : false\n\nexport type Reconcile<\n\tA extends Object,\n\tB extends Object,\n\tOverride extends boolean = false,\n\t// Detect Stack limit, eg. circular dependency\n\tStack extends number[] = []\n> = Stack['length'] extends 16\n\t? A\n\t: Override extends true\n\t\t? {\n\t\t\t\t[key in keyof A as key extends keyof B ? never : key]: A[key]\n\t\t\t} extends infer Collision\n\t\t\t? {} extends Collision\n\t\t\t\t? {\n\t\t\t\t\t\t[key in keyof B]: IsBothObject<\n\t\t\t\t\t\t\t// @ts-ignore trust me bro\n\t\t\t\t\t\t\tA[key],\n\t\t\t\t\t\t\tB[key]\n\t\t\t\t\t\t> extends true\n\t\t\t\t\t\t\t? Reconcile<\n\t\t\t\t\t\t\t\t\t// @ts-ignore trust me bro\n\t\t\t\t\t\t\t\t\tA[key],\n\t\t\t\t\t\t\t\t\tB[key],\n\t\t\t\t\t\t\t\t\tOverride,\n\t\t\t\t\t\t\t\t\t[0, ...Stack]\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t: B[key]\n\t\t\t\t\t}\n\t\t\t\t: Prettify<\n\t\t\t\t\t\tCollision & {\n\t\t\t\t\t\t\t[key in keyof B]: B[key]\n\t\t\t\t\t\t}\n\t\t\t\t\t>\n\t\t\t: never\n\t\t: {\n\t\t\t\t\t[key in keyof B as key extends keyof A\n\t\t\t\t\t\t? never\n\t\t\t\t\t\t: key]: B[key]\n\t\t\t  } extends infer Collision\n\t\t\t? {} extends Collision\n\t\t\t\t? {\n\t\t\t\t\t\t[key in keyof A]: IsBothObject<\n\t\t\t\t\t\t\tA[key],\n\t\t\t\t\t\t\t// @ts-ignore trust me bro\n\t\t\t\t\t\t\tB[key]\n\t\t\t\t\t\t> extends true\n\t\t\t\t\t\t\t? Reconcile<\n\t\t\t\t\t\t\t\t\t// @ts-ignore trust me bro\n\t\t\t\t\t\t\t\t\tA[key],\n\t\t\t\t\t\t\t\t\t// @ts-ignore trust me bro\n\t\t\t\t\t\t\t\t\tB[key],\n\t\t\t\t\t\t\t\t\tOverride,\n\t\t\t\t\t\t\t\t\t[0, ...Stack]\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t: A[key]\n\t\t\t\t\t}\n\t\t\t\t: Prettify<\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t[key in keyof A]: A[key]\n\t\t\t\t\t\t} & Collision\n\t\t\t\t\t>\n\t\t\t: never\n\nexport interface SingletonBase {\n\tdecorator: Record<string, unknown>\n\tstore: Record<string, unknown>\n\tderive: Record<string, unknown>\n\tresolve: Record<string, unknown>\n}\n\nexport interface PossibleResponse {\n\t[status: number]: unknown\n}\n\nexport interface EphemeralType {\n\tderive: SingletonBase['derive']\n\tresolve: SingletonBase['resolve']\n\tschema: MetadataBase['schema']\n\tstandaloneSchema: MetadataBase['schema']\n\tresponse: PossibleResponse\n}\n\nexport interface DefinitionBase {\n\ttypebox: Record<string, AnySchema>\n\terror: Record<string, Error>\n}\n\nexport type RouteBase = Record<string, unknown>\n\nexport interface MetadataBase {\n\tschema: RouteSchema\n\tstandaloneSchema: MetadataBase['schema']\n\tmacro: BaseMacro\n\tmacroFn: Macro\n\tparser: Record<string, BodyHandler<any, any>>\n\tresponse: PossibleResponse\n}\n\nexport interface RouteSchema {\n\tbody?: unknown\n\theaders?: unknown\n\tquery?: unknown\n\tparams?: unknown\n\tcookie?: unknown\n\tresponse?: unknown\n}\n\ninterface OptionalField {\n\t[OptionalKind]: 'Optional'\n}\n\nexport type UnwrapSchema<\n\tSchema extends AnySchema | string | undefined,\n\tDefinitions extends DefinitionBase['typebox'] = {}\n> = Schema extends undefined\n\t? unknown\n\t: Schema extends TSchema\n\t\t? Schema extends OptionalField\n\t\t\t? Partial<\n\t\t\t\t\tTImport<\n\t\t\t\t\t\t// @ts-expect-error Internal typebox already filter for TSchema\n\t\t\t\t\t\tDefinitions & {\n\t\t\t\t\t\t\treadonly __elysia: Schema\n\t\t\t\t\t\t},\n\t\t\t\t\t\t'__elysia'\n\t\t\t\t\t>['static']\n\t\t\t\t>\n\t\t\t: TImport<\n\t\t\t\t\t// @ts-expect-error Internal typebox already filter for TSchema\n\t\t\t\t\tDefinitions & {\n\t\t\t\t\t\treadonly __elysia: Schema\n\t\t\t\t\t},\n\t\t\t\t\t'__elysia'\n\t\t\t\t>['static']\n\t\t: Schema extends FastStandardSchemaV1Like\n\t\t\t? // @ts-ignore Schema is StandardSchemaV1Like\n\t\t\t\tNonNullable<Schema['~standard']['types']>['output']\n\t\t\t: Schema extends string\n\t\t\t\t? Schema extends keyof Definitions\n\t\t\t\t\t? Definitions[Schema] extends TAnySchema\n\t\t\t\t\t\t? TImport<\n\t\t\t\t\t\t\t\t// @ts-expect-error Internal typebox already filter for TSchema\n\t\t\t\t\t\t\t\tDefinitions,\n\t\t\t\t\t\t\t\tSchema\n\t\t\t\t\t\t\t>['static']\n\t\t\t\t\t\t: NonNullable<\n\t\t\t\t\t\t\t\tDefinitions[Schema]['~standard']['types']\n\t\t\t\t\t\t\t>['output']\n\t\t\t\t\t: unknown\n\t\t\t\t: unknown\n\nexport type UnwrapBodySchema<\n\tSchema extends AnySchema | string | undefined,\n\tDefinitions extends DefinitionBase['typebox'] = {}\n> = undefined extends Schema\n\t? unknown\n\t: Schema extends TSchema\n\t\t? Schema extends OptionalField\n\t\t\t? Partial<\n\t\t\t\t\tTImport<\n\t\t\t\t\t\t// @ts-expect-error Internal typebox already filter for TSchema\n\t\t\t\t\t\tDefinitions & {\n\t\t\t\t\t\t\treadonly __elysia: Schema\n\t\t\t\t\t\t},\n\t\t\t\t\t\t'__elysia'\n\t\t\t\t\t>['static']\n\t\t\t\t> | null\n\t\t\t: TImport<\n\t\t\t\t\t// @ts-expect-error Internal typebox already filter for TSchema\n\t\t\t\t\tDefinitions & {\n\t\t\t\t\t\treadonly __elysia: Schema\n\t\t\t\t\t},\n\t\t\t\t\t'__elysia'\n\t\t\t\t>['static']\n\t\t: Schema extends FastStandardSchemaV1Like\n\t\t\t? // @ts-ignore Schema is StandardSchemaV1Like\n\t\t\t\tNonNullable<Schema['~standard']['types']>['output']\n\t\t\t: Schema extends string\n\t\t\t\t? Schema extends keyof Definitions\n\t\t\t\t\t? Definitions[Schema] extends TAnySchema\n\t\t\t\t\t\t? TImport<\n\t\t\t\t\t\t\t\t// @ts-expect-error Internal typebox already filter for TSchema\n\t\t\t\t\t\t\t\tDefinitions,\n\t\t\t\t\t\t\t\tSchema\n\t\t\t\t\t\t\t>['static']\n\t\t\t\t\t\t: // @ts-ignore Schema is StandardSchemaV1Like\n\t\t\t\t\t\t\tNonNullable<\n\t\t\t\t\t\t\t\tDefinitions[Schema]['~standard']['types']\n\t\t\t\t\t\t\t>['output']\n\t\t\t\t\t: unknown\n\t\t\t\t: unknown\n\nexport interface UnwrapRoute<\n\tin out Schema extends InputSchema<any>,\n\tin out Definitions extends DefinitionBase['typebox'] = {},\n\tin out Path extends string = ''\n> {\n\tbody: UnwrapBodySchema<Schema['body'], Definitions>\n\theaders: UnwrapSchema<Schema['headers'], Definitions>\n\tquery: UnwrapSchema<Schema['query'], Definitions>\n\tparams: {} extends Schema['params']\n\t\t? ResolvePath<Path>\n\t\t: {} extends Schema\n\t\t\t? ResolvePath<Path>\n\t\t\t: UnwrapSchema<Schema['params'], Definitions>\n\tcookie: UnwrapSchema<Schema['cookie'], Definitions>\n\tresponse: Schema['response'] extends FastAnySchema | string\n\t\t? {\n\t\t\t\t200: UnwrapSchema<\n\t\t\t\t\tSchema['response'],\n\t\t\t\t\tDefinitions\n\t\t\t\t> extends infer A\n\t\t\t\t\t? A extends File\n\t\t\t\t\t\t? File | ElysiaFile\n\t\t\t\t\t\t: A\n\t\t\t\t\t: unknown\n\t\t\t}\n\t\t: Schema['response'] extends {\n\t\t\t\t\t[status in number]: FastAnySchema | string\n\t\t\t  }\n\t\t\t? {\n\t\t\t\t\t[k in keyof Schema['response']]: UnwrapSchema<\n\t\t\t\t\t\tSchema['response'][k],\n\t\t\t\t\t\tDefinitions\n\t\t\t\t\t> extends infer A\n\t\t\t\t\t\t? A extends File\n\t\t\t\t\t\t\t? File | ElysiaFile\n\t\t\t\t\t\t\t: A\n\t\t\t\t\t\t: unknown\n\t\t\t\t}\n\t\t\t: unknown | void\n}\n\nexport interface UnwrapGroupGuardRoute<\n\tin out Schema extends InputSchema<any>,\n\tin out Definitions extends DefinitionBase['typebox'] = {},\n\tPath extends string | undefined = undefined\n> {\n\tbody: UnwrapBodySchema<Schema['body'], Definitions>\n\theaders: UnwrapSchema<\n\t\tSchema['headers'],\n\t\tDefinitions\n\t> extends infer A extends Record<string, any>\n\t\t? A\n\t\t: undefined\n\tquery: UnwrapSchema<Schema['query'], Definitions> extends infer A extends\n\t\tRecord<string, any>\n\t\t? A\n\t\t: undefined\n\tparams: UnwrapSchema<Schema['params'], Definitions> extends infer A extends\n\t\tRecord<string, any>\n\t\t? A\n\t\t: Path extends PathParameterLike\n\t\t\t? Record<GetPathParameter<Path>, string>\n\t\t\t: never\n\tcookie: UnwrapSchema<Schema['cookie'], Definitions> extends infer A extends\n\t\tRecord<string, any>\n\t\t? A\n\t\t: undefined\n\tresponse: Schema['response'] extends TSchema | string\n\t\t? UnwrapSchema<Schema['response'], Definitions>\n\t\t: Schema['response'] extends {\n\t\t\t\t\t[k in string]: TSchema | string\n\t\t\t  }\n\t\t\t? UnwrapSchema<\n\t\t\t\t\tSchema['response'][keyof Schema['response']],\n\t\t\t\t\tDefinitions\n\t\t\t\t>\n\t\t\t: unknown | void\n}\n\nexport type HookContainer<T extends Function = Function> = {\n\tchecksum?: number\n\tscope?: LifeCycleType\n\tsubType?: 'derive' | 'resolve' | 'mapDerive' | 'mapResolve' | (string & {})\n\tfn: T\n\tisAsync?: boolean\n\thasReturn?: boolean\n}\n\nexport interface LifeCycleStore {\n\ttype?: ContentType\n\tstart: HookContainer<GracefulHandler<any>>[]\n\trequest: HookContainer<PreHandler<any, any>>[]\n\tparse: HookContainer<BodyHandler<any, any>>[]\n\ttransform: HookContainer<TransformHandler<any, any>>[]\n\tbeforeHandle: HookContainer<OptionalHandler<any, any>>[]\n\tafterHandle: HookContainer<OptionalHandler<any, any>>[]\n\tmapResponse: HookContainer<MapResponse<any, any>>[]\n\tafterResponse: HookContainer<AfterResponseHandler<any, any>>[]\n\ttrace: HookContainer<TraceHandler<any, any>>[]\n\terror: HookContainer<ErrorHandler<any, any, any>>[]\n\tstop: HookContainer<GracefulHandler<any>>[]\n}\n\nexport type LifeCycleEvent =\n\t| 'start'\n\t| 'request'\n\t| 'parse'\n\t| 'transform'\n\t| 'beforeHandle'\n\t| 'afterHandle'\n\t| 'response'\n\t| 'error'\n\t| 'stop'\n\nexport type ContentType = MaybeArray<\n\t| 'none'\n\t| 'text'\n\t| 'json'\n\t| 'formdata'\n\t| 'urlencoded'\n\t| 'arrayBuffer'\n\t| 'text/plain'\n\t| 'application/json'\n\t| 'multipart/form-data'\n\t| 'application/x-www-form-urlencoded'\n\t| 'application/octet-stream'\n>\n\nexport type HTTPMethod =\n\t| (string & {})\n\t| 'ACL'\n\t| 'BIND'\n\t| 'CHECKOUT'\n\t| 'CONNECT'\n\t| 'COPY'\n\t| 'DELETE'\n\t| 'GET'\n\t| 'HEAD'\n\t| 'LINK'\n\t| 'LOCK'\n\t| 'M-SEARCH'\n\t| 'MERGE'\n\t| 'MKACTIVITY'\n\t| 'MKCALENDAR'\n\t| 'MKCOL'\n\t| 'MOVE'\n\t| 'NOTIFY'\n\t| 'OPTIONS'\n\t| 'PATCH'\n\t| 'POST'\n\t| 'PROPFIND'\n\t| 'PROPPATCH'\n\t| 'PURGE'\n\t| 'PUT'\n\t| 'REBIND'\n\t| 'REPORT'\n\t| 'SEARCH'\n\t| 'SOURCE'\n\t| 'SUBSCRIBE'\n\t| 'TRACE'\n\t| 'UNBIND'\n\t| 'UNLINK'\n\t| 'UNLOCK'\n\t| 'UNSUBSCRIBE'\n\t| 'ALL'\n\nexport interface InputSchema<in out Name extends string = string> {\n\tbody?: AnySchema | Name\n\theaders?: AnySchema | Name\n\tquery?: AnySchema | Name\n\tparams?: AnySchema | Name\n\tcookie?: AnySchema | Name\n\tresponse?:\n\t\t| AnySchema\n\t\t| { [status in number]: AnySchema }\n\t\t| Name\n\t\t| {\n\t\t\t\t[status in number]: Name | AnySchema\n\t\t  }\n}\n\ntype PathParameterLike = `${string}/${':' | '*'}${string}`\n\nexport type IntersectIfObject<A, B> =\n\tA extends Record<any, any>\n\t\t? B extends Record<any, any>\n\t\t\t? A & B\n\t\t\t: A\n\t\t: B extends Record<any, any>\n\t\t\t? B\n\t\t\t: A\n\nexport interface IntersectIfObjectSchema<\n\tA extends RouteSchema,\n\tB extends RouteSchema\n> {\n\tbody: IntersectIfObject<A['body'], B['body']>\n\theaders: IntersectIfObject<A['headers'], B['headers']>\n\tquery: IntersectIfObject<A['query'], B['query']>\n\tparams: IntersectIfObject<A['params'], B['params']>\n\tcookie: IntersectIfObject<A['cookie'], B['cookie']>\n\tresponse: IntersectIfObject<A['response'], B['response']>\n}\n\nexport type MergeSchema<\n\tA extends RouteSchema,\n\tB extends RouteSchema,\n\tPath extends string = ''\n> = {} extends A\n\t? Path extends PathParameterLike\n\t\t? Omit<B, 'params'> & { params: ResolvePath<Path> }\n\t\t: B\n\t: {} extends B\n\t\t? Path extends PathParameterLike\n\t\t\t? Omit<A, 'params'> & { params: ResolvePath<Path> }\n\t\t\t: A\n\t\t: {\n\t\t\t\tbody: undefined extends A['body'] ? B['body'] : A['body']\n\t\t\t\theaders: undefined extends A['headers']\n\t\t\t\t\t? B['headers']\n\t\t\t\t\t: A['headers']\n\t\t\t\tquery: undefined extends A['query'] ? B['query'] : A['query']\n\t\t\t\tparams: IsNever<keyof A['params']> extends true\n\t\t\t\t\t? IsNever<keyof B['params']> extends true\n\t\t\t\t\t\t? ResolvePath<Path>\n\t\t\t\t\t\t: B['params']\n\t\t\t\t\t: IsNever<keyof B['params']> extends true\n\t\t\t\t\t\t? A['params']\n\t\t\t\t\t\t: Prettify<\n\t\t\t\t\t\t\t\tB['params'] &\n\t\t\t\t\t\t\t\t\tOmit<A['params'], keyof B['params']>\n\t\t\t\t\t\t\t>\n\t\t\t\tcookie: undefined extends A['cookie']\n\t\t\t\t\t? B['cookie']\n\t\t\t\t\t: A['cookie']\n\t\t\t\tresponse: {} extends A['response']\n\t\t\t\t\t? {} extends B['response']\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: B['response']\n\t\t\t\t\t: {} extends B['response']\n\t\t\t\t\t\t? A['response']\n\t\t\t\t\t\t: A['response'] &\n\t\t\t\t\t\t\t\tOmit<B['response'], keyof A['response']>\n\t\t\t}\n\nexport interface MergeStandaloneSchema<\n\tin out A extends RouteSchema,\n\tin out B extends RouteSchema,\n\tPath extends string = ''\n> {\n\tbody: undefined extends A['body']\n\t\t? undefined extends B['body']\n\t\t\t? undefined\n\t\t\t: B['body']\n\t\t: undefined extends B['body']\n\t\t\t? A['body']\n\t\t\t: Prettify<A['body'] & B['body']>\n\theaders: undefined extends A['headers']\n\t\t? undefined extends B['headers']\n\t\t\t? undefined\n\t\t\t: B['headers']\n\t\t: undefined extends B['headers']\n\t\t\t? A['headers']\n\t\t\t: Prettify<A['headers'] & B['headers']>\n\tquery: undefined extends A['query']\n\t\t? undefined extends B['query']\n\t\t\t? undefined\n\t\t\t: B['query']\n\t\t: undefined extends B['query']\n\t\t\t? A['query']\n\t\t\t: Prettify<A['query'] & B['query']>\n\tparams: IsNever<keyof A['params']> extends true\n\t\t? IsNever<keyof B['params']> extends true\n\t\t\t? ResolvePath<Path>\n\t\t\t: B['params']\n\t\t: IsNever<keyof B['params']> extends true\n\t\t\t? A['params']\n\t\t\t: Prettify<A['params'] & B['params']>\n\tcookie: undefined extends A['cookie']\n\t\t? undefined extends B['cookie']\n\t\t\t? undefined\n\t\t\t: B['cookie']\n\t\t: undefined extends B['cookie']\n\t\t\t? A['cookie']\n\t\t\t: Prettify<A['cookie'] & B['cookie']>\n\tresponse: {} extends A['response']\n\t\t? {} extends B['response']\n\t\t\t? {}\n\t\t\t: B['response']\n\t\t: {} extends B['response']\n\t\t\t? A['response']\n\t\t\t: Prettify<A['response'] & B['response']>\n}\n\nexport type Handler<\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tPath extends string | undefined = undefined\n> = (\n\tcontext: Context<Route, Singleton, Path>\n) => MaybePromise<\n\t{} extends Route['response']\n\t\t? unknown\n\t\t: Route['response'][keyof Route['response']]\n>\n\nexport type IsAny<T> = 0 extends 1 & T ? true : false\n\nexport type Replace<Original, Target, With> =\n\tIsAny<Target> extends true\n\t\t? Original\n\t\t: Original extends Record<string, unknown>\n\t\t\t? {\n\t\t\t\t\t[K in keyof Original]: Original[K] extends Target\n\t\t\t\t\t\t? With\n\t\t\t\t\t\t: Original[K]\n\t\t\t\t}\n\t\t\t: Original extends Target\n\t\t\t\t? With\n\t\t\t\t: Original\n\nexport type CoExist<Original, Target, With> =\n\tIsAny<Target> extends true\n\t\t? Original\n\t\t: Original extends Record<string, unknown>\n\t\t\t? {\n\t\t\t\t\t[K in keyof Original]: Original[K] extends Target\n\t\t\t\t\t\t? Original[K] | With\n\t\t\t\t\t\t: Original[K]\n\t\t\t\t}\n\t\t\t: Original extends Target\n\t\t\t\t? Original | With\n\t\t\t\t: Original\n\n// These properties shall not be resolve in macro\nexport type MacroContextBlacklistKey =\n\t| 'type'\n\t| 'detail'\n\t| 'parse'\n\t| 'transform'\n\t| 'resolve'\n\t| 'beforeHandle'\n\t| 'afterHandle'\n\t| 'mapResponse'\n\t| 'afterResponse'\n\t| 'error'\n\t| 'tags'\n\t| keyof RouteSchema\n\ntype ReturnTypeIfPossible<T, Enabled = true> = false extends Enabled\n\t? {}\n\t: T extends (...a: any) => infer R\n\t\t? R\n\t\t: T\n\ntype AnyElysiaCustomStatusResponse = ElysiaCustomStatusResponse<any, any, any>\n\ntype FunctionArrayReturnType<T> =\n\t// If nothing is provided, it will be resolved as any\n\tany[] extends T\n\t\t? never\n\t\t: T extends any[]\n\t\t\t? _FunctionArrayReturnType<T>\n\t\t\t: // @ts-ignore\n\t\t\t\tAwaited<ReturnType<T>>\n\ntype _FunctionArrayReturnType<T, Carry = undefined> = T extends [\n\tinfer Fn,\n\t...infer Rest\n]\n\t? _FunctionArrayReturnType<\n\t\t\tRest,\n\t\t\tAwaited<\n\t\t\t\t// @ts-ignore Trust me bro\n\t\t\t\tReturnType<Fn>\n\t\t\t> extends infer A\n\t\t\t\t? IsNever<A> extends true\n\t\t\t\t\t? Carry\n\t\t\t\t\t: A | Carry\n\t\t\t\t: Carry\n\t\t>\n\t: Carry\n\ntype FunctionArrayReturnTypeNonNullable<T> =\n\t// If nothing is provided, it will be resolved as any\n\tany[] extends T\n\t\t? never\n\t\t: T extends any[]\n\t\t\t? _FunctionArrayReturnTypeNonNullable<T>\n\t\t\t: // @ts-ignore\n\t\t\t\tNonNullable<Awaited<ReturnType<T>>>\n\ntype _FunctionArrayReturnTypeNonNullable<T, Carry = undefined> = T extends [\n\tinfer Fn,\n\t...infer Rest\n]\n\t? _FunctionArrayReturnTypeNonNullable<\n\t\t\tRest,\n\t\t\tNonNullable<\n\t\t\t\tAwaited<\n\t\t\t\t\t// @ts-ignore Trust me bro\n\t\t\t\t\tReturnType<Fn>\n\t\t\t\t>\n\t\t\t> extends infer A\n\t\t\t\t? IsNever<A> extends true\n\t\t\t\t\t? Carry\n\t\t\t\t\t: A | Carry\n\t\t\t\t: Carry\n\t\t>\n\t: Carry\n\ntype ExtractResolveFromMacro<A> =\n\tIsNever<A> extends true\n\t\t? {}\n\t\t: A extends AnyElysiaCustomStatusResponse\n\t\t\t? A\n\t\t\t: Exclude<A, AnyElysiaCustomStatusResponse> extends infer A\n\t\t\t\t? IsAny<A> extends true\n\t\t\t\t\t? {}\n\t\t\t\t\t: A\n\t\t\t\t: {}\n\ntype ExtractOnlyResponseFromMacro<A> =\n\tIsNever<A> extends true\n\t\t? {}\n\t\t: Extract<A, AnyElysiaCustomStatusResponse> extends infer A\n\t\t\t? IsNever<A> extends true\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\treturn: MergeResponseStatus<A>\n\t\t\t\t\t}\n\t\t\t: {}\n\ntype MergeResponseStatus<A> = {\n\t[status in keyof UnionToIntersect<\n\t\t// Must be using generic to separate literal from Box<T>\n\t\tA extends ElysiaCustomStatusResponse<any, any, infer Status>\n\t\t\t? { [A in Status]: 1 }\n\t\t\t: never\n\t\t// @ts-ignore A is checked in key computation\n\t>]: Extract<A, { code: status }>['response'] extends infer Value\n\t\t? IsAny<Value> extends true\n\t\t\t? // @ts-ignore status is always in Status Map\n\t\t\t\tInvertedStatusMap[status]\n\t\t\t: Value\n\t\t: never\n}\n\ntype MergeAllStatus<T> = {\n\t[K in T extends any ? keyof T : never]: T extends Record<K, infer V>\n\t\t? V\n\t\t: never\n}\n\ntype ExtractAllResponseFromMacro<A> =\n\tIsNever<A> extends true\n\t\t? {}\n\t\t: {\n\t\t\t\t// Merge all status to single object first\n\t\t\t\treturn: MergeResponseStatus<A> &\n\t\t\t\t\t(Exclude<A, AnyElysiaCustomStatusResponse> extends infer A\n\t\t\t\t\t\t? IsAny<A> extends true\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: IsNever<A> extends true\n\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t: // FunctionArrayReturnType\n\t\t\t\t\t\t\t\t\tNonNullable<void> extends A\n\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t: undefined extends A\n\t\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\t\t200: A\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {})\n\t\t\t}\n\ntype FlattenMacroResponse<T> = T extends object\n\t? '_' extends keyof T\n\t\t? MergeFlattenMacroResponse<\n\t\t\t\tOmit<T, '_'>,\n\t\t\t\tFlattenMacroResponse<MergeAllStatus<T['_']>>\n\t\t\t>\n\t\t: T\n\t: T\n\ntype MergeFlattenMacroResponse<A, B> = {\n\t[K in keyof A | keyof B]: K extends keyof A\n\t\t? K extends keyof B\n\t\t\t? A[K] | B[K]\n\t\t\t: A[K]\n\t\t: K extends keyof B\n\t\t\t? B[K]\n\t\t\t: never\n}\ntype UnionMacroContext<A> = UnionToIntersect<{\n\t[K in Exclude<keyof A, 'return'>]: A[K]\n}> & {\n\t// @ts-ignore Allow recursive Macro.return without collapse into\n\treturn: { _: A['return'] }\n}\n\nexport type MacroToContext<\n\tin out MacroFn extends Macro = {},\n\tin out SelectedMacro extends BaseMacro = {},\n\tin out Definitions extends DefinitionBase['typebox'] = {},\n\tin out R extends 1[] = []\n> = Prettify<\n\tInnerMacroToContext<\n\t\tMacroFn,\n\t\tPick<SelectedMacro, Extract<keyof MacroFn, keyof SelectedMacro>>,\n\t\tDefinitions,\n\t\tR\n\t> extends infer A\n\t\t? {\n\t\t\t\t[K in Exclude<keyof A, 'return'>]: UnionToIntersect<A[K]>\n\t\t\t} & Prettify<{\n\t\t\t\t// @ts-ignore\n\t\t\t\treturn: FlattenMacroResponse<A['return']>\n\t\t\t}>\n\t\t: {}\n>\n\n// There's only resolve that can add new properties to Context\ntype InnerMacroToContext<\n\tMacroFn extends Macro = {},\n\tSelectedMacro extends BaseMacro = {},\n\tDefinitions extends DefinitionBase['typebox'] = {},\n\tR extends 1[] = []\n> = {} extends SelectedMacro\n\t? {}\n\t: R['length'] extends 15\n\t\t? {}\n\t\t: UnionMacroContext<\n\t\t\t\t{\n\t\t\t\t\t[key in keyof SelectedMacro]: ReturnTypeIfPossible<\n\t\t\t\t\t\tMacroFn[key],\n\t\t\t\t\t\tSelectedMacro[key]\n\t\t\t\t\t> extends infer Value\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tresolve: ExtractResolveFromMacro<\n\t\t\t\t\t\t\t\t\tExtract<\n\t\t\t\t\t\t\t\t\t\tExclude<\n\t\t\t\t\t\t\t\t\t\t\tFunctionArrayReturnType<\n\t\t\t\t\t\t\t\t\t\t\t\t// @ts-ignore Trust me bro\n\t\t\t\t\t\t\t\t\t\t\t\tValue['resolve']\n\t\t\t\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\t\t\t\tAnyElysiaCustomStatusResponse\n\t\t\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\t\t\tRecord<any, unknown>\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t} & UnwrapMacroSchema<\n\t\t\t\t\t\t\t\t// @ts-ignore Trust me bro\n\t\t\t\t\t\t\t\tValue,\n\t\t\t\t\t\t\t\tDefinitions\n\t\t\t\t\t\t\t> &\n\t\t\t\t\t\t\t\tExtractAllResponseFromMacro<\n\t\t\t\t\t\t\t\t\tFunctionArrayReturnTypeNonNullable<\n\t\t\t\t\t\t\t\t\t\t// @ts-expect-error type is checked in key mapping\n\t\t\t\t\t\t\t\t\t\tValue['beforeHandle']\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t> &\n\t\t\t\t\t\t\t\tExtractAllResponseFromMacro<\n\t\t\t\t\t\t\t\t\tFunctionArrayReturnTypeNonNullable<\n\t\t\t\t\t\t\t\t\t\t// @ts-expect-error type is checked in key mapping\n\t\t\t\t\t\t\t\t\t\tValue['afterHandle']\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t> &\n\t\t\t\t\t\t\t\tExtractAllResponseFromMacro<\n\t\t\t\t\t\t\t\t\t// @ts-expect-error type is checked in key mapping\n\t\t\t\t\t\t\t\t\tFunctionArrayReturnType<Value['error']>\n\t\t\t\t\t\t\t\t> &\n\t\t\t\t\t\t\t\tExtractOnlyResponseFromMacro<\n\t\t\t\t\t\t\t\t\tFunctionArrayReturnTypeNonNullable<\n\t\t\t\t\t\t\t\t\t\t// @ts-expect-error type is checked in key mapping\n\t\t\t\t\t\t\t\t\t\tValue['resolve']\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t> &\n\t\t\t\t\t\t\t\tInnerMacroToContext<\n\t\t\t\t\t\t\t\t\tMacroFn,\n\t\t\t\t\t\t\t\t\t// @ts-ignore trust me bro\n\t\t\t\t\t\t\t\t\tPick<\n\t\t\t\t\t\t\t\t\t\tValue,\n\t\t\t\t\t\t\t\t\t\tExtract<keyof MacroFn, keyof Value>\n\t\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\t\tDefinitions,\n\t\t\t\t\t\t\t\t\t[...R, 1]\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t: {}\n\t\t\t\t}[keyof SelectedMacro]\n\t\t\t>\n\ntype UnwrapMacroSchema<\n\tT extends Partial<InputSchema<any>>,\n\tDefinitions extends DefinitionBase['typebox'] = {}\n> = UnwrapRoute<\n\t{\n\t\tbody: 'body' extends keyof T ? T['body'] : undefined\n\t\theaders: 'headers' extends keyof T ? T['headers'] : undefined\n\t\tquery: 'query' extends keyof T ? T['query'] : undefined\n\t\tparams: 'params' extends keyof T ? T['params'] : undefined\n\t\tcookie: 'cookie' extends keyof T ? T['cookie'] : undefined\n\t\tresponse: 'response' extends keyof T ? T['response'] : undefined\n\t},\n\tDefinitions\n>\n\nexport type SimplifyToSchema<T extends InputSchema<any>> =\n\tIsUnknown<T['body']> extends false\n\t\t? _SimplifyToSchema<T>\n\t\t: IsUnknown<T['headers']> extends false\n\t\t\t? _SimplifyToSchema<T>\n\t\t\t: IsUnknown<T['query']> extends false\n\t\t\t\t? _SimplifyToSchema<T>\n\t\t\t\t: IsUnknown<T['params']> extends false\n\t\t\t\t\t? _SimplifyToSchema<T>\n\t\t\t\t\t: IsUnknown<T['cookie']> extends false\n\t\t\t\t\t\t? _SimplifyToSchema<T>\n\t\t\t\t\t\t: IsUnknown<T['response']> extends false\n\t\t\t\t\t\t\t? _SimplifyToSchema<T>\n\t\t\t\t\t\t\t: {}\n\nexport type _SimplifyToSchema<T extends InputSchema<any>> = Omit<\n\t{\n\t\tbody: T['body']\n\t\theaders: T['headers']\n\t\tquery: T['query']\n\t\tparams: T['params']\n\t\tcookie: T['cookie']\n\t\tresponse: T['response']\n\t},\n\t| ('body' extends keyof T ? never : 'body')\n\t| ('headers' extends keyof T ? never : 'headers')\n\t| ('query' extends keyof T ? never : 'query')\n\t| ('params' extends keyof T ? never : 'params')\n\t| ('cookie' extends keyof T ? never : 'cookie')\n\t| ('response' extends keyof T ? never : 'response')\n>\n\ntype InlineHandlerResponse<Route extends RouteSchema['response']> = {\n\t[Status in keyof Route]: ElysiaCustomStatusResponse<\n\t\t// @ts-ignore Status is always a number\n\t\tStatus,\n\t\tRoute[Status],\n\t\tStatus\n\t>\n}[keyof Route]\n\ntype InlineResponse =\n\t| string\n\t| number\n\t| boolean\n\t| Record<any, unknown>\n\t| Response\n\t| AnyElysiaCustomStatusResponse\n\t| ElysiaFile\n\t| Record<any, unknown>\n\t| BunHTMLBundlelike\n\ntype LastOf<T> =\n\tUnionToIntersect<T extends any ? () => T : never> extends () => infer R\n\t\t? R\n\t\t: never\n\ntype Push<T extends any[], V> = [...T, V]\n\ntype TuplifyUnion<\n\tT,\n\tL = LastOf<T>,\n\tN = [T] extends [never] ? true : false\n> = true extends N ? [] : Push<TuplifyUnion<Exclude<T, L>>, L>\n\nexport type Tuple<\n\tT,\n\tA extends T[] = []\n> = TuplifyUnion<T>['length'] extends A['length'] ? [...A] : Tuple<T, [T, ...A]>\n\nexport type InlineHandler<\n\tRoute extends RouteSchema = {},\n\tSingleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tMacroContext extends {\n\t\tresponse: PossibleResponse\n\t\treturn: PossibleResponse\n\t\tresolve: Record<string, unknown>\n\t} = {\n\t\tresponse: {}\n\t\treturn: {}\n\t\tresolve: {}\n\t}\n> =\n\t| MaybePromise<InlineResponse>\n\t| ((\n\t\t\tcontext: Context<\n\t\t\t\tRoute & MacroContext,\n\t\t\t\tSingleton & { resolve: MacroContext['resolve'] }\n\t\t\t>\n\t  ) =>\n\t\t\t| MaybePromise<Response>\n\t\t\t| MaybePromise<\n\t\t\t\t\t{} extends Route['response']\n\t\t\t\t\t\t? unknown\n\t\t\t\t\t\t:\n\t\t\t\t\t\t\t\t| (Route['response'] extends {\n\t\t\t\t\t\t\t\t\t\t200: any\n\t\t\t\t\t\t\t\t  }\n\t\t\t\t\t\t\t\t\t\t?\n\t\t\t\t\t\t\t\t\t\t\t\t| Route['response'][200]\n\t\t\t\t\t\t\t\t\t\t\t\t| ElysiaCustomStatusResponse<\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t200,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRoute['response'][200],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t200\n\t\t\t\t\t\t\t\t\t\t\t\t  >\n\t\t\t\t\t\t\t\t\t\t\t\t| Generator<\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRoute['response'][200]\n\t\t\t\t\t\t\t\t\t\t\t\t  >\n\t\t\t\t\t\t\t\t\t\t\t\t| AsyncGenerator<\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRoute['response'][200]\n\t\t\t\t\t\t\t\t\t\t\t\t  >\n\t\t\t\t\t\t\t\t\t\t: unknown)\n\t\t\t\t\t\t\t\t// This could be possible because of set.status\n\t\t\t\t\t\t\t\t| Route['response'][keyof Route['response']]\n\t\t\t\t\t\t\t\t| InlineHandlerResponse<\n\t\t\t\t\t\t\t\t\t\tRoute['response'] &\n\t\t\t\t\t\t\t\t\t\t\tMacroContext['response']\n\t\t\t\t\t\t\t\t  >\n\t\t\t  >)\n\nexport type InlineHandlerNonMacro<\n\tRoute extends RouteSchema = {},\n\tSingleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t}\n> =\n\t| MaybePromise<InlineResponse>\n\t| ((context: Context<Route, Singleton>) =>\n\t\t\t| MaybePromise<Response>\n\t\t\t| MaybePromise<\n\t\t\t\t\t{} extends Route['response']\n\t\t\t\t\t\t? unknown\n\t\t\t\t\t\t:\n\t\t\t\t\t\t\t\t| (Route['response'] extends {\n\t\t\t\t\t\t\t\t\t\t200: any\n\t\t\t\t\t\t\t\t  }\n\t\t\t\t\t\t\t\t\t\t?\n\t\t\t\t\t\t\t\t\t\t\t\t| Route['response'][200]\n\t\t\t\t\t\t\t\t\t\t\t\t| ElysiaCustomStatusResponse<\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t200,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRoute['response'][200],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t200\n\t\t\t\t\t\t\t\t\t\t\t\t  >\n\t\t\t\t\t\t\t\t\t\t\t\t| Generator<\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRoute['response'][200]\n\t\t\t\t\t\t\t\t\t\t\t\t  >\n\t\t\t\t\t\t\t\t\t\t\t\t| AsyncGenerator<\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRoute['response'][200]\n\t\t\t\t\t\t\t\t\t\t\t\t  >\n\t\t\t\t\t\t\t\t\t\t: unknown)\n\t\t\t\t\t\t\t\t// This could be possible because of set.status\n\t\t\t\t\t\t\t\t| Route['response'][keyof Route['response']]\n\t\t\t\t\t\t\t\t| InlineHandlerResponse<Route['response']>\n\t\t\t  >)\n\nexport type OptionalHandler<\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tPath extends string | undefined = undefined\n> = (\n\tcontext: Context<Route, Singleton, Path>\n) => MaybePromise<\n\t{} extends Route['response']\n\t\t? unknown\n\t\t:\n\t\t\t\t| Route['response'][keyof Route['response']]\n\t\t\t\t| InlineHandlerResponse<Route['response']>\n\t\t\t\t| void\n>\n\nexport type AfterHandler<\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tPath extends string | undefined = undefined\n> = (\n\tcontext: Context<Route, Singleton, Path> & {\n\t\tresponseValue: {} extends Route['response']\n\t\t\t? unknown\n\t\t\t: Route['response'][keyof Route['response']]\n\t\t/**\n\t\t * @deprecated use `context.responseValue` instead\n\t\t */\n\t\tresponse: {} extends Route['response']\n\t\t\t? unknown\n\t\t\t: Route['response'][keyof Route['response']]\n\t}\n) => MaybePromise<\n\t{} extends Route['response']\n\t\t? unknown\n\t\t:\n\t\t\t\t| Route['response'][keyof Route['response']]\n\t\t\t\t| InlineHandlerResponse<Route['response']>\n\t\t\t\t| void\n>\n\nexport type MapResponse<\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tPath extends string | undefined = undefined\n> = (\n\tcontext: Context<Route, Singleton, Path> & {\n\t\tresponseValue: {} extends Route['response']\n\t\t\t? unknown\n\t\t\t: Route['response'][keyof Route['response']]\n\t\t/**\n\t\t * @deprecated use `context.responseValue` instead\n\t\t */\n\t\tresponse: {} extends Route['response']\n\t\t\t? unknown\n\t\t\t: Route['response'][keyof Route['response']]\n\t}\n) => MaybePromise<Response | void>\n\n// Handler<\n// \tOmit<Route, 'response'> & {},\n// \tSingleton & {\n// \t\tderive: {\n// \t\t\tresponse: {} extends Route['response'] ? unknown : Route['response']\n// \t\t}\n// \t},\n// \tPath\n// >\n\nexport type VoidHandler<\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t}\n> = (context: Context<Route, Singleton>) => MaybePromise<void>\n\nexport type TransformHandler<\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tPath extends string | undefined = undefined\n> = (\n\tcontext: Context<\n\t\tRoute,\n\t\tOmit<Singleton, 'resolve'> & {\n\t\t\tresolve: {}\n\t\t},\n\t\tPath\n\t>\n) => MaybePromise<void>\n\nexport type BodyHandler<\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tPath extends string | undefined = undefined\n> = (\n\tcontext: Context<\n\t\tRoute,\n\t\tSingleton & {\n\t\t\tdecorator: {\n\t\t\t\tcontentType: string\n\t\t\t}\n\t\t},\n\t\tPath\n\t>,\n\t/**\n\t * @deprecated\n\t *\n\t * use `context.contentType` instead\n\t *\n\t * @example\n\t * ```ts\n\t * new Elysia()\n\t * \t   .onParse(({ contentType, request }) => {\n\t * \t\t     if (contentType === 'application/json')\n\t * \t\t\t     return request.json()\n\t *     })\n\t * ```\n\t */\n\tcontentType: string\n) => MaybePromise<any>\n\nexport type PreHandler<\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t}\n> = (\n\tcontext: PreContext<Singleton>\n) => MaybePromise<\n\tRoute['response'] | InlineHandlerResponse<Route['response']> | void\n>\n\nexport type AfterResponseHandler<\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t}\n> = (\n\tcontext: Context<Route, Singleton> & {\n\t\tresponseValue: {} extends Route['response']\n\t\t\t? unknown\n\t\t\t: Route['response'][keyof Route['response']]\n\t\t/**\n\t\t * @deprecated use `context.responseValue` instead\n\t\t */\n\t\tresponse: {} extends Route['response']\n\t\t\t? unknown\n\t\t\t:\n\t\t\t\t\t| Route['response'][keyof Route['response']]\n\t\t\t\t\t| InlineHandlerResponse<Route['response']>\n\t}\n) => MaybePromise<unknown>\n\nexport type GracefulHandler<in Instance extends AnyElysia> = (\n\tdata: Instance\n) => any\n\nexport type ErrorHandler<\n\tin out T extends Record<string, Error> = {},\n\tin out Route extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\t// ? scoped\n\tin out Ephemeral extends EphemeralType = {\n\t\tderive: {}\n\t\tresolve: {}\n\t\tschema: {}\n\t\tstandaloneSchema: {}\n\t\tresponse: {}\n\t},\n\t// ? local\n\tin out Volatile extends EphemeralType = {\n\t\tderive: {}\n\t\tresolve: {}\n\t\tschema: {}\n\t\tstandaloneSchema: {}\n\t\tresponse: {}\n\t}\n> = (\n\tcontext: ErrorContext<\n\t\tRoute,\n\t\t{\n\t\t\tstore: Singleton['store']\n\t\t\tdecorator: Singleton['decorator']\n\t\t\tderive: {}\n\t\t\tresolve: {}\n\t\t}\n\t> &\n\t\t(\n\t\t\t| Prettify<\n\t\t\t\t\t{\n\t\t\t\t\t\trequest: Request\n\t\t\t\t\t\tcode: 'UNKNOWN'\n\t\t\t\t\t\terror: Readonly<Error>\n\t\t\t\t\t\tset: Context['set']\n\t\t\t\t\t} & Partial<\n\t\t\t\t\t\tSingleton['derive'] &\n\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\tVolatile['derive'] &\n\t\t\t\t\t\t\tSingleton['resolve'] &\n\t\t\t\t\t\t\tEphemeral['resolve'] &\n\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t>\n\t\t\t  >\n\t\t\t| Prettify<\n\t\t\t\t\t{\n\t\t\t\t\t\trequest: Request\n\t\t\t\t\t\tcode: 'VALIDATION'\n\t\t\t\t\t\terror: Readonly<ValidationError>\n\t\t\t\t\t\tset: Context['set']\n\t\t\t\t\t} & Singleton['derive'] &\n\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\tVolatile['derive'] &\n\t\t\t\t\t\tNeverKey<\n\t\t\t\t\t\t\tSingleton['resolve'] &\n\t\t\t\t\t\t\t\tEphemeral['resolve'] &\n\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t>\n\t\t\t  >\n\t\t\t| Prettify<\n\t\t\t\t\t{\n\t\t\t\t\t\trequest: Request\n\t\t\t\t\t\tcode: 'NOT_FOUND'\n\t\t\t\t\t\terror: Readonly<NotFoundError>\n\t\t\t\t\t\tset: Context['set']\n\t\t\t\t\t} & NeverKey<\n\t\t\t\t\t\tSingleton['derive'] &\n\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\tVolatile['derive'] &\n\t\t\t\t\t\t\tSingleton['resolve'] &\n\t\t\t\t\t\t\tEphemeral['resolve'] &\n\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t>\n\t\t\t  >\n\t\t\t| Prettify<\n\t\t\t\t\t{\n\t\t\t\t\t\trequest: Request\n\t\t\t\t\t\tcode: 'PARSE'\n\t\t\t\t\t\terror: Readonly<ParseError>\n\t\t\t\t\t\tset: Context['set']\n\t\t\t\t\t} & NeverKey<\n\t\t\t\t\t\tSingleton['derive'] &\n\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\tVolatile['derive'] &\n\t\t\t\t\t\t\tSingleton['resolve'] &\n\t\t\t\t\t\t\tEphemeral['resolve'] &\n\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t>\n\t\t\t  >\n\t\t\t| Prettify<\n\t\t\t\t\t{\n\t\t\t\t\t\trequest: Request\n\t\t\t\t\t\tcode: 'INTERNAL_SERVER_ERROR'\n\t\t\t\t\t\terror: Readonly<InternalServerError>\n\t\t\t\t\t\tset: Context['set']\n\t\t\t\t\t} & Partial<\n\t\t\t\t\t\tSingleton['derive'] &\n\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\tVolatile['derive'] &\n\t\t\t\t\t\t\tSingleton['resolve'] &\n\t\t\t\t\t\t\tEphemeral['resolve'] &\n\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t>\n\t\t\t  >\n\t\t\t| Prettify<\n\t\t\t\t\t{\n\t\t\t\t\t\trequest: Request\n\t\t\t\t\t\tcode: 'INVALID_COOKIE_SIGNATURE'\n\t\t\t\t\t\terror: Readonly<InvalidCookieSignature>\n\t\t\t\t\t\tset: Context['set']\n\t\t\t\t\t} & NeverKey<\n\t\t\t\t\t\tSingleton['derive'] &\n\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\tVolatile['derive'] &\n\t\t\t\t\t\t\tSingleton['resolve'] &\n\t\t\t\t\t\t\tEphemeral['resolve'] &\n\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t>\n\t\t\t  >\n\t\t\t| Prettify<\n\t\t\t\t\t{\n\t\t\t\t\t\trequest: Request\n\t\t\t\t\t\tcode: 'INVALID_FILE_TYPE'\n\t\t\t\t\t\terror: Readonly<InvalidFileType>\n\t\t\t\t\t\tset: Context['set']\n\t\t\t\t\t} & Singleton['derive'] &\n\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\tVolatile['derive'] &\n\t\t\t\t\t\tNeverKey<\n\t\t\t\t\t\t\tSingleton['resolve'] &\n\t\t\t\t\t\t\t\tEphemeral['resolve'] &\n\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t>\n\t\t\t  >\n\t\t\t| Prettify<\n\t\t\t\t\t{\n\t\t\t\t\t\trequest: Request\n\t\t\t\t\t\tcode: number\n\t\t\t\t\t\terror: Readonly<ElysiaCustomStatusResponse<number>>\n\t\t\t\t\t\tset: Context['set']\n\t\t\t\t\t} & Partial<\n\t\t\t\t\t\tSingleton['derive'] &\n\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\tVolatile['derive'] &\n\t\t\t\t\t\t\tSingleton['resolve'] &\n\t\t\t\t\t\t\tEphemeral['resolve'] &\n\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t>\n\t\t\t  >\n\t\t\t| Prettify<\n\t\t\t\t\t{\n\t\t\t\t\t\t[K in keyof T]: {\n\t\t\t\t\t\t\trequest: Request\n\t\t\t\t\t\t\tcode: K\n\t\t\t\t\t\t\terror: Readonly<T[K]>\n\t\t\t\t\t\t\tset: Context['set']\n\t\t\t\t\t\t}\n\t\t\t\t\t}[keyof T] &\n\t\t\t\t\t\tPartial<\n\t\t\t\t\t\t\tSingleton['derive'] &\n\t\t\t\t\t\t\t\tEphemeral['derive'] &\n\t\t\t\t\t\t\t\tVolatile['derive'] &\n\t\t\t\t\t\t\t\tSingleton['resolve'] &\n\t\t\t\t\t\t\t\tEphemeral['resolve'] &\n\t\t\t\t\t\t\t\tVolatile['resolve']\n\t\t\t\t\t\t>\n\t\t\t  >\n\t\t)\n) => any | Promise<any>\n\nexport interface DocumentDecoration extends Partial<OpenAPIV3.OperationObject> {\n\t/**\n\t * Pass `true` to hide route from OpenAPI/swagger document\n\t * */\n\thide?: boolean\n}\n\nexport type ResolveHandler<\n\tin out Route extends RouteSchema,\n\tin out Singleton extends SingletonBase,\n\tDerivative extends\n\t\t| Record<string, unknown>\n\t\t| AnyElysiaCustomStatusResponse\n\t\t| void = Record<string, unknown> | AnyElysiaCustomStatusResponse | void\n> = (context: Context<Route, Singleton>) => MaybePromise<Derivative>\n\nexport type ResolveReturnType<T extends MaybeArray<unknown>> =\n\t// If no macro are provided, it will be resolved as any\n\tany[] extends T\n\t\t? {}\n\t\t: // Is any, return\n\t\t\tT extends any[]\n\t\t\t? _ResolveReturnTypeArray<// @ts-ignore Trust me bro\n\t\t\t\tT>\n\t\t\t: Exclude<\n\t\t\t\t\t\t// @ts-ignore Trust me bro\n\t\t\t\t\t\tAwaited<ReturnType<T>>,\n\t\t\t\t\t\tAnyElysiaCustomStatusResponse\n\t\t\t\t  > extends infer Value extends Record<any, unknown>\n\t\t\t\t? Value\n\t\t\t\t: {}\n\ntype _ResolveReturnTypeArray<T, Carry = {}> = T extends [\n\tinfer Fn,\n\t...infer Rest\n]\n\t? Exclude<\n\t\t\t// @ts-ignore Trust me bro\n\t\t\tAwaited<ReturnType<Fn>>,\n\t\t\tAnyElysiaCustomStatusResponse\n\t\t> extends infer Value extends Record<any, unknown>\n\t\t? _ResolveReturnTypeArray<Rest, Value & Carry>\n\t\t: _ResolveReturnTypeArray<Rest, Carry & {}>\n\t: Prettify<Carry>\n\nexport type AnyLocalHook = LocalHook<any, any, any, any, any>\n\nexport interface BaseHookLifeCycle<\n\tin out Schema extends RouteSchema,\n\tin out Singleton extends SingletonBase,\n\tin out Errors extends { [key in string]: Error },\n\tin out Parser extends keyof any = ''\n> {\n\tdetail?: DocumentDecoration\n\t/**\n\t * Short for 'Content-Type'\n\t *\n\t * Available:\n\t * - 'none': do not parse body\n\t * - 'text' / 'text/plain': parse body as string\n\t * - 'json' / 'application/json': parse body as json\n\t * - 'formdata' / 'multipart/form-data': parse body as form-data\n\t * - 'urlencoded' / 'application/x-www-form-urlencoded: parse body as urlencoded\n\t * - 'arraybuffer': parse body as readable stream\n\t */\n\tparse?: MaybeArray<BodyHandler<Schema, Singleton> | ContentType | Parser>\n\t/**\n\t * Transform context's value\n\t */\n\ttransform?: MaybeArray<TransformHandler<Schema, Singleton>>\n\t/**\n\t * Execute before main handler\n\t */\n\tbeforeHandle?: MaybeArray<OptionalHandler<Schema, Singleton>>\n\t/**\n\t * Execute after main handler\n\t */\n\tafterHandle?: MaybeArray<AfterHandler<Schema, Singleton>>\n\t/**\n\t * Execute after main handler\n\t */\n\tmapResponse?: MaybeArray<MapResponse<Schema, Singleton>>\n\t/**\n\t * Execute after response is sent\n\t */\n\tafterResponse?: MaybeArray<AfterResponseHandler<Schema, Singleton>>\n\t/**\n\t * Catch error\n\t */\n\terror?: MaybeArray<ErrorHandler<Errors, Schema, Singleton>>\n\ttags?: DocumentDecoration['tags']\n}\n\nexport type CreateDecorator<\n\tSingleton extends SingletonBase,\n\tEphemeral extends EphemeralType,\n\tVolatile extends EphemeralType\n> = {} extends Ephemeral\n\t? {} extends Volatile\n\t\t? Singleton\n\t\t: Singleton & Volatile\n\t: {} extends Volatile\n\t\t? Singleton & Ephemeral\n\t\t: Singleton & Ephemeral & Volatile\n\nexport type AnyBaseHookLifeCycle = BaseHookLifeCycle<any, any, any, any>\n\nexport type NonResolvableMacroKey =\n\t| keyof AnyBaseHookLifeCycle\n\t| keyof InputSchema\n\t| 'resolve'\n\ninterface RouteSchemaWithResolvedMacro extends RouteSchema {\n\tresponse: PossibleResponse\n\treturn: PossibleResponse\n\tresolve: Record<string, unknown>\n}\n\nexport type LocalHook<\n\tInput extends BaseMacro,\n\tSchema extends RouteSchemaWithResolvedMacro,\n\tSingleton extends SingletonBase,\n\tErrors extends { [key in string]: Error },\n\tParser extends keyof any = ''\n> = {\n\tdetail?: DocumentDecoration\n\t/**\n\t * Short for 'Content-Type'\n\t *\n\t * Available:\n\t * - 'none': do not parse body\n\t * - 'text' / 'text/plain': parse body as string\n\t * - 'json' / 'application/json': parse body as json\n\t * - 'formdata' / 'multipart/form-data': parse body as form-data\n\t * - 'urlencoded' / 'application/x-www-form-urlencoded: parse body as urlencoded\n\t * - 'arraybuffer': parse body as readable stream\n\t */\n\tparse?: MaybeArray<\n\t\t| BodyHandler<Schema, Singleton & { resolve: Schema['resolve'] }>\n\t\t| ContentType\n\t\t| Parser\n\t>\n\t/**\n\t * Transform context's value\n\t */\n\ttransform?: MaybeArray<\n\t\tTransformHandler<Schema, Singleton & { resolve: Schema['resolve'] }>\n\t>\n\t/**\n\t * Execute before main handler\n\t */\n\tbeforeHandle?: MaybeArray<\n\t\tOptionalHandler<Schema, Singleton & { resolve: Schema['resolve'] }>\n\t>\n\t/**\n\t * Execute after main handler\n\t */\n\tafterHandle?: MaybeArray<\n\t\tAfterHandler<Schema, Singleton & { resolve: Schema['resolve'] }>\n\t>\n\t/**\n\t * Execute after main handler\n\t */\n\tmapResponse?: MaybeArray<\n\t\tMapResponse<Schema, Singleton & { resolve: Schema['resolve'] }>\n\t>\n\t/**\n\t * Execute after response is sent\n\t */\n\tafterResponse?: MaybeArray<\n\t\tAfterResponseHandler<Schema, Singleton & { resolve: Schema['resolve'] }>\n\t>\n\t/**\n\t * Catch error\n\t */\n\terror?: MaybeArray<\n\t\tErrorHandler<Errors, Schema, Singleton & { resolve: Schema['resolve'] }>\n\t>\n\ttags?: DocumentDecoration['tags']\n} & (Input extends any ? Input : Prettify<Input>)\n\nexport type GuardLocalHook<\n\tInput extends BaseMacro | undefined,\n\tSchema extends RouteSchema,\n\tSingleton extends SingletonBase,\n\tParser extends keyof any,\n\tBeforeHandle extends MaybeArray<OptionalHandler<any, any>>,\n\tAfterHandle extends MaybeArray<AfterHandler<any, any>>,\n\tErrorHandle extends MaybeArray<ErrorHandler<any, any, any>>,\n\tGuardType extends GuardSchemaType = 'standalone',\n\tAsType extends LifeCycleType = 'local'\n> = (Input extends any ? Input : Prettify<Input>) & {\n\t/**\n\t * @default 'override'\n\t */\n\tas?: AsType\n\t/**\n\t * @default 'standalone'\n\t * @since 1.3.0\n\t */\n\tschema?: GuardType\n\n\tdetail?: DocumentDecoration\n\t/**\n\t * Short for 'Content-Type'\n\t *\n\t * Available:\n\t * - 'none': do not parse body\n\t * - 'text' / 'text/plain': parse body as string\n\t * - 'json' / 'application/json': parse body as json\n\t * - 'formdata' / 'multipart/form-data': parse body as form-data\n\t * - 'urlencoded' / 'application/x-www-form-urlencoded: parse body as urlencoded\n\t * - 'arraybuffer': parse body as readable stream\n\t */\n\tparse?: MaybeArray<BodyHandler<Schema, Singleton> | ContentType | Parser>\n\t/**\n\t * Transform context's value\n\t */\n\ttransform?: MaybeArray<TransformHandler<Schema, Singleton>>\n\t/**\n\t * Execute before main handler\n\t */\n\tbeforeHandle?: BeforeHandle\n\t/**\n\t * Execute after main handler\n\t */\n\tafterHandle?: AfterHandle\n\t/**\n\t * Execute after main handler\n\t */\n\tmapResponse?: MaybeArray<MapResponse<Schema, Singleton>>\n\t/**\n\t * Execute after response is sent\n\t */\n\tafterResponse?: MaybeArray<AfterResponseHandler<Schema, Singleton>>\n\t/**\n\t * Catch error\n\t */\n\terror?: ErrorHandle\n\ttags?: DocumentDecoration['tags']\n}\n\nexport type ComposedHandler = (context: Context) => MaybePromise<Response>\n\nexport interface InternalRoute {\n\tmethod: HTTPMethod\n\tpath: string\n\tcomposed: ComposedHandler | Response | null\n\tcompile(): ComposedHandler\n\thandler: Handler\n\thooks: AnyLocalHook\n\twebsocket?: AnyWSLocalHook\n}\n\nexport interface SchemaValidator {\n\tcreateBody?(): ElysiaTypeCheck<any>\n\tcreateHeaders?(): ElysiaTypeCheck<any>\n\tcreateQuery?(): ElysiaTypeCheck<any>\n\tcreateParams?(): ElysiaTypeCheck<any>\n\tcreateCookie?(): ElysiaTypeCheck<any>\n\tcreateResponse?(): Record<number, ElysiaTypeCheck<any>>\n\tbody?: ElysiaTypeCheck<any>\n\theaders?: ElysiaTypeCheck<any>\n\tquery?: ElysiaTypeCheck<any>\n\tparams?: ElysiaTypeCheck<any>\n\tcookie?: ElysiaTypeCheck<any>\n\tresponse?: Record<number, ElysiaTypeCheck<any>>\n}\n\nexport type AddPrefix<in out Prefix extends string, in out T> = {\n\t[K in keyof T as Prefix extends string ? `${Prefix}${K & string}` : K]: T[K]\n}\n\nexport type AddPrefixCapitalize<in out Prefix extends string, in out T> = {\n\t[K in keyof T as `${Prefix}${Capitalize<K & string>}`]: T[K]\n}\n\nexport type AddSuffix<in out Suffix extends string, in out T> = {\n\t[K in keyof T as `${K & string}${Suffix}`]: T[K]\n}\n\nexport type AddSuffixCapitalize<in out Suffix extends string, in out T> = {\n\t[K in keyof T as `${K & string}${Capitalize<Suffix>}`]: T[K]\n}\n\nexport interface Checksum {\n\tname?: string\n\tseed?: unknown\n\tchecksum: number\n\tstack?: string\n\troutes?: InternalRoute[]\n\tdecorators?: SingletonBase['decorator']\n\tstore?: SingletonBase['store']\n\terror?: DefinitionBase['error']\n\tdependencies?: Record<string, Checksum[]>\n\tderive?: {\n\t\tfn: string\n\t\tstack: string\n\t}[]\n\tresolve?: {\n\t\tfn: string\n\t\tstack: string\n\t}[]\n}\n\nexport type BaseMacro = Record<\n\tstring,\n\tstring | number | boolean | Object | undefined | null\n>\n\nexport type MaybeValueOrVoidFunction<T> = T | ((...a: any) => void | T)\n\nexport interface MacroProperty<\n\tin out Macro extends BaseMacro = {},\n\tin out TypedRoute extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tin out Errors extends Record<string, Error> = {}\n> {\n\t/**\n\t * Deduplication similar to Elysia.constructor.seed\n\t */\n\tseed?: unknown\n\tparse?: MaybeArray<BodyHandler<TypedRoute, Singleton>>\n\ttransform?: MaybeArray<VoidHandler<TypedRoute, Singleton>>\n\tbeforeHandle?: MaybeArray<OptionalHandler<TypedRoute, Singleton>>\n\tafterHandle?: MaybeArray<AfterHandler<TypedRoute, Singleton>>\n\terror?: MaybeArray<ErrorHandler<Errors, TypedRoute, Singleton>>\n\tmapResponse?: MaybeArray<MapResponse<TypedRoute, Singleton>>\n\tafterResponse?: MaybeArray<AfterResponseHandler<TypedRoute, Singleton>>\n\tresolve?: MaybeArray<ResolveHandler<TypedRoute, Singleton>>\n\tdetail?: DocumentDecoration\n\t/**\n\t * Introspect hook option for documentation generation or analysis\n\t *\n\t * @param option\n\t */\n\tintrospect?(option: Prettify<Macro>): unknown\n}\n\nexport interface Macro<\n\tin out Macro extends BaseMacro = {},\n\tin out Input extends BaseMacro = {},\n\tin out TypedRoute extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tin out Errors extends Record<string, Error> = {}\n> {\n\t[K: keyof any]: MaybeValueOrVoidFunction<\n\t\tInput & MacroProperty<Macro, TypedRoute, Singleton, Errors>\n\t>\n}\n\nexport type MaybeFunction<T> = T | ((...args: any[]) => T)\n\nexport type MacroToProperty<in out T extends Macro<any, any, any, any>> =\n\tPrettify<{\n\t\t[K in keyof T]: T[K] extends Function\n\t\t\t? T[K] extends (a: infer Params) => any\n\t\t\t\t? Params\n\t\t\t\t: boolean\n\t\t\t: boolean\n\t}>\n\ninterface MacroOptions {\n\tinsert?: 'before' | 'after'\n\tstack?: 'global' | 'local'\n}\n\nexport interface MacroManager<\n\tin out TypedRoute extends RouteSchema = {},\n\tin out Singleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tin out Errors extends Record<string, Error> = {}\n> {\n\tbody(schema: InputSchema['body']): unknown\n\theaders(schema: InputSchema['headers']): unknown\n\tquery(schema: InputSchema['query']): unknown\n\tparams(schema: InputSchema['params']): unknown\n\tcookie(schema: InputSchema['cookie']): unknown\n\tresponse(schema: InputSchema['response']): unknown\n\n\tdetail(detail: DocumentDecoration): unknown\n\n\tonParse(fn: MaybeArray<BodyHandler<TypedRoute, Singleton>>): unknown\n\tonParse(\n\t\toptions: MacroOptions,\n\t\tfn: MaybeArray<BodyHandler<TypedRoute, Singleton>>\n\t): unknown\n\n\tonTransform(fn: MaybeArray<VoidHandler<TypedRoute, Singleton>>): unknown\n\tonTransform(\n\t\toptions: MacroOptions,\n\t\tfn: MaybeArray<VoidHandler<TypedRoute, Singleton>>\n\t): unknown\n\n\tonBeforeHandle(\n\t\tfn: MaybeArray<OptionalHandler<TypedRoute, Singleton>>\n\t): unknown\n\tonBeforeHandle(\n\t\toptions: MacroOptions,\n\t\tfn: MaybeArray<OptionalHandler<TypedRoute, Singleton>>\n\t): unknown\n\n\tonAfterHandle(fn: MaybeArray<AfterHandler<TypedRoute, Singleton>>): unknown\n\tonAfterHandle(\n\t\toptions: MacroOptions,\n\t\tfn: MaybeArray<AfterHandler<TypedRoute, Singleton>>\n\t): unknown\n\n\tonError(\n\t\tfn: MaybeArray<ErrorHandler<Errors, TypedRoute, Singleton>>\n\t): unknown\n\tonError(\n\t\toptions: MacroOptions,\n\t\tfn: MaybeArray<ErrorHandler<Errors, TypedRoute, Singleton>>\n\t): unknown\n\n\tmapResponse(fn: MaybeArray<MapResponse<TypedRoute, Singleton>>): unknown\n\tmapResponse(\n\t\toptions: MacroOptions,\n\t\tfn: MaybeArray<MapResponse<TypedRoute, Singleton>>\n\t): unknown\n\n\tonAfterResponse(\n\t\tfn: MaybeArray<AfterResponseHandler<TypedRoute, Singleton>>\n\t): unknown\n\tonAfterResponse(\n\t\toptions: MacroOptions,\n\t\tfn: MaybeArray<AfterResponseHandler<TypedRoute, Singleton>>\n\t): unknown\n\n\tevents: {\n\t\tglobal: Partial<LifeCycleStore & RouteSchema>\n\t\tlocal: Partial<LifeCycleStore & RouteSchema>\n\t}\n}\n\ntype _CreateEden<\n\tPath extends string,\n\tProperty extends Record<string, unknown> = {}\n> = Path extends `${infer Start}/${infer Rest}`\n\t? {\n\t\t\t[x in Start]: _CreateEden<Rest, Property>\n\t\t}\n\t: Path extends ''\n\t\t? Property\n\t\t: {\n\t\t\t\t[x in Path]: Property\n\t\t\t}\n\ntype RemoveStartingSlash<T> = T extends `/${infer Rest}` ? Rest : T\n\nexport type CreateEden<\n\tPath extends string,\n\tProperty extends Record<string, unknown> = {}\n> = Path extends `/${infer Rest}`\n\t? _CreateEden<Rest, Property>\n\t: Path extends '' | '/'\n\t\t? Property\n\t\t: _CreateEden<Path, Property>\n\nexport interface EmptyRouteSchema {\n\tbody: unknown\n\theaders: unknown\n\tquery: unknown\n\tparams: {}\n\tcookie: unknown\n\tresponse: unknown\n}\n\nexport interface UnknownRouteSchema<\n\tParams = { [name: string]: string | undefined }\n> {\n\tbody: unknown\n\theaders: { [name: string]: string | undefined }\n\tquery: { [name: string]: string | undefined }\n\tparams: Params\n\tcookie: {}\n\tresponse: unknown\n}\n\ntype Extract200<T> = T extends AnyElysiaCustomStatusResponse\n\t?\n\t\t\t| Exclude<T, AnyElysiaCustomStatusResponse>\n\t\t\t| Extract<T, ElysiaCustomStatusResponse<200, any, 200>>['response']\n\t: T\n\nexport type IsUnknown<T> = [unknown] extends [T]\n\t? IsAny<T> extends true\n\t\t? false\n\t\t: true\n\t: false\n\nexport type ValueToResponseSchema<Value> = ExtractErrorFromHandle<Value> &\n\t(Extract200<Value> extends infer R200\n\t\t? undefined extends R200\n\t\t\t? {}\n\t\t\t: IsNever<R200> extends true\n\t\t\t\t? {}\n\t\t\t\t: { 200: R200 }\n\t\t: {})\n\nexport type ValueOrFunctionToResponseSchema<T> = T extends (\n\t...a: any\n) => MaybePromise<infer R>\n\t? ValueToResponseSchema<R>\n\t: ValueToResponseSchema<T>\n\nexport type ElysiaHandlerToResponseSchema<in out Handle extends Function> =\n\tPrettify<\n\t\tHandle extends (...a: any) => MaybePromise<infer R>\n\t\t\t? ValueToResponseSchema<Exclude<R, undefined>>\n\t\t\t: {}\n\t>\n\nexport type ElysiaHandlerToResponseSchemas<\n\tHandle extends Function[],\n\tCarry extends PossibleResponse = {}\n> = Handle extends [infer Current, ...infer Rest]\n\t? ElysiaHandlerToResponseSchemas<\n\t\t\t// @ts-ignore Trust me bro\n\t\t\tRest,\n\t\t\t// @ts-ignore trust me bro\n\t\t\tUnionResponseStatus<ElysiaHandlerToResponseSchema<Current>, Carry>\n\t\t>\n\t: Prettify<Carry>\n\nexport type ElysiaHandlerToResponseSchemaAmbiguous<\n\tSchemas extends MaybeArray<Function>\n> =\n\tMaybeArray<(...a: any) => any> extends Schemas\n\t\t? {}\n\t\t: Schemas extends Function\n\t\t\t? ElysiaHandlerToResponseSchema<Schemas>\n\t\t\t: Schemas extends Function[]\n\t\t\t\t? ElysiaHandlerToResponseSchemas<Schemas>\n\t\t\t\t: {}\n\ntype ReconcileStatus<\n\tin out A extends Record<number, unknown>,\n\tin out B extends Record<number, unknown>\n> = {\n\t// @ts-ignore Trust me bro\n\t[K in keyof A | keyof B]: K extends keyof A ? A[K] : B[K]\n}\n\nexport type ComposeElysiaResponse<\n\tSchema extends RouteSchema,\n\tHandle,\n\tPossibility extends PossibleResponse\n> = ReconcileStatus<\n\t// @ts-ignore\n\tSchema['response'],\n\tUnionResponseStatus<\n\t\tValueOrFunctionToResponseSchema<Handle>,\n\t\tPossibility &\n\t\t\t(EmptyRouteSchema extends Pick<Schema, keyof EmptyRouteSchema>\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\t422: {\n\t\t\t\t\t\t\ttype: 'validation'\n\t\t\t\t\t\t\ton: string\n\t\t\t\t\t\t\tsummary?: string\n\t\t\t\t\t\t\tmessage?: string\n\t\t\t\t\t\t\tfound?: unknown\n\t\t\t\t\t\t\tproperty?: string\n\t\t\t\t\t\t\texpected?: string\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t>\n>\n\nexport type ExtractErrorFromHandle<in out Handle> = {\n\t[ErrorResponse in Extract<\n\t\tHandle,\n\t\tAnyElysiaCustomStatusResponse\n\t> as ErrorResponse extends AnyElysiaCustomStatusResponse\n\t\t? ErrorResponse['code']\n\t\t: never]: Prettify<ErrorResponse['response']>\n}\n\nexport type MergeElysiaInstances<\n\tInstances extends AnyElysia[] = [],\n\tPrefix extends string = '',\n\tSingleton extends SingletonBase = {\n\t\tdecorator: {}\n\t\tstore: {}\n\t\tderive: {}\n\t\tresolve: {}\n\t},\n\tDefinitions extends DefinitionBase = {\n\t\ttypebox: {}\n\t\terror: {}\n\t},\n\tMetadata extends MetadataBase = {\n\t\tschema: {}\n\t\tstandaloneSchema: {}\n\t\tmacro: {}\n\t\tmacroFn: {}\n\t\tparser: {}\n\t\tresponse: {}\n\t},\n\tEphemeral extends EphemeralType = {\n\t\tderive: {}\n\t\tresolve: {}\n\t\tschema: {}\n\t\tstandaloneSchema: {}\n\t\tresponse: {}\n\t},\n\tVolatile extends EphemeralType = {\n\t\tderive: {}\n\t\tresolve: {}\n\t\tschema: {}\n\t\tstandaloneSchema: {}\n\t\tresponse: {}\n\t},\n\tRoutes extends RouteBase = {}\n> = Instances extends [\n\tinfer Current extends AnyElysia,\n\t...infer Rest extends AnyElysia[]\n]\n\t? MergeElysiaInstances<\n\t\t\tRest,\n\t\t\tPrefix,\n\t\t\tSingleton & Current['~Singleton'],\n\t\t\tDefinitions & Current['~Definitions'],\n\t\t\tMetadata & Current['~Metadata'],\n\t\t\tEphemeral,\n\t\t\tVolatile & Current['~Ephemeral'],\n\t\t\tRoutes &\n\t\t\t\t(Prefix extends ``\n\t\t\t\t\t? Current['~Routes']\n\t\t\t\t\t: CreateEden<Prefix, Current['~Routes']>)\n\t\t>\n\t: Elysia<\n\t\t\tPrefix,\n\t\t\t{\n\t\t\t\tdecorator: Singleton['decorator']\n\t\t\t\tstore: Prettify<Singleton['store']>\n\t\t\t\tderive: Singleton['derive']\n\t\t\t\tresolve: Singleton['resolve']\n\t\t\t},\n\t\t\tDefinitions,\n\t\t\tMetadata,\n\t\t\tRoutes,\n\t\t\tEphemeral,\n\t\t\tVolatile\n\t\t>\n\nexport type LifeCycleType = 'global' | 'local' | 'scoped'\nexport type GuardSchemaType = 'override' | 'standalone'\n\ntype PartialIf<T, Condition extends boolean> = Condition extends true\n\t? Partial<T>\n\t: T\n\n// Exclude return error()\nexport type ExcludeElysiaResponse<T> = PartialIf<\n\tExclude<Awaited<T>, AnyElysiaCustomStatusResponse> extends infer A\n\t\t? IsNever<A & {}> extends true\n\t\t\t? {}\n\t\t\t: // Intersect all union and fallback never to {}\n\t\t\t\tA & {}\n\t\t: {},\n\tundefined extends Awaited<T> ? true : false\n>\n\n/**\n * @deprecated\n */\nexport type InferContext<\n\tT extends AnyElysia,\n\tPath extends string = T['~Prefix'],\n\tSchema extends RouteSchema = T['~Metadata']['schema']\n> = Context<\n\tMergeSchema<Schema, T['~Metadata']['schema']>,\n\tT['~Singleton'] & {\n\t\tderive: T['~Ephemeral']['derive'] & T['~Volatile']['derive']\n\t\tresolve: T['~Ephemeral']['resolve'] & T['~Volatile']['resolve']\n\t},\n\tPath\n>\n\n/**\n * @deprecated\n */\nexport type InferHandler<\n\tT extends AnyElysia,\n\tPath extends string = T['~Prefix'],\n\tSchema extends RouteSchema = T['~Metadata']['schema']\n> = InlineHandler<\n\tMergeSchema<Schema, T['~Metadata']['schema'], Path>,\n\tT['~Singleton'] & {\n\t\tderive: T['~Ephemeral']['derive'] & T['~Volatile']['derive']\n\t\tresolve: T['~Ephemeral']['resolve'] & T['~Volatile']['resolve']\n\t}\n>\n\nexport interface ModelValidatorError extends ValueError {\n\tsummary: string\n}\n\n// @ts-ignore trust me bro\nexport interface ModelValidator<T> extends TypeCheck<T> {\n\tschema: T\n\tparse(a: T): T\n\tsafeParse(a: T):\n\t\t| { success: true; data: T; error: null }\n\t\t| {\n\t\t\t\tsuccess: true\n\t\t\t\tdata: null\n\t\t\t\terror: string\n\t\t\t\terrors: ModelValidatorError[]\n\t\t  }\n}\n\nexport type UnionToIntersect<U> = (\n\tU extends unknown ? (arg: U) => 0 : never\n) extends (arg: infer I) => 0\n\t? I\n\t: never\n\nexport type ContextAppendType = 'append' | 'override'\n\n// new Elysia()\n// \t.wrap((fn) => {\n// \t\treturn fn()\n// \t})\nexport type HigherOrderFunction<\n\tT extends (...arg: unknown[]) => Function = (...arg: unknown[]) => Function\n> = (fn: T, request: Request) => ReturnType<T>\n\ntype SetContentType =\n\t| 'application/octet-stream'\n\t| 'application/vnd.ms-fontobject'\n\t| 'application/epub+zip'\n\t| 'application/gzip'\n\t| 'application/json'\n\t| 'application/ld+json'\n\t| 'application/ogg'\n\t| 'application/pdf'\n\t| 'application/rtf'\n\t| 'application/wasm'\n\t| 'application/xhtml+xml'\n\t| 'application/xml'\n\t| 'application/zip'\n\t| 'text/css'\n\t| 'text/csv'\n\t| 'text/calendar'\n\t| 'text/event-stream'\n\t| 'text/html'\n\t| 'text/javascript'\n\t| 'text/plain'\n\t| 'text/xml'\n\t| 'image/avif'\n\t| 'image/bmp'\n\t| 'image/gif'\n\t| 'image/x-icon'\n\t| 'image/jpeg'\n\t| 'image/png'\n\t| 'image/svg+xml'\n\t| 'image/tiff'\n\t| 'image/webp'\n\t| 'multipart/mixed'\n\t| 'multipart/alternative'\n\t| 'multipart/form-data'\n\t| 'audio/aac'\n\t| 'audio/x-midi'\n\t| 'audio/mpeg'\n\t| 'audio/ogg'\n\t| 'audio/opus'\n\t| 'audio/webm'\n\t| 'video/x-msvideo'\n\t| 'video/quicktime'\n\t| 'video/x-ms-wmv'\n\t| 'video/x-msvideo'\n\t| 'video/x-flv'\n\t| 'video/av1'\n\t| 'video/mp4'\n\t| 'video/mpeg'\n\t| 'video/ogg'\n\t| 'video/mp2t'\n\t| 'video/webm'\n\t| 'video/3gpp'\n\t| 'video/3gpp2'\n\t| 'font/otf'\n\t| 'font/ttf'\n\t| 'font/woff'\n\t| 'font/woff2'\n\t| 'model/gltf+json'\n\t| 'model/gltf-binary'\n\nexport type HTTPHeaders = Record<string, string | number> & {\n\t// Authentication\n\t'www-authenticate'?: string\n\tauthorization?: string\n\t'proxy-authenticate'?: string\n\t'proxy-authorization'?: string\n\n\t// Caching\n\tage?: string\n\t'cache-control'?: string\n\t'clear-site-data'?: string\n\texpires?: string\n\t'no-vary-search'?: string\n\tpragma?: string\n\n\t// Conditionals\n\t'last-modified'?: string\n\tetag?: string\n\t'if-match'?: string\n\t'if-none-match'?: string\n\t'if-modified-since'?: string\n\t'if-unmodified-since'?: string\n\tvary?: string\n\n\t// Connection management\n\tconnection?: string\n\t'keep-alive'?: string\n\n\t// Content negotiation\n\taccept?: string\n\t'accept-encoding'?: string\n\t'accept-language'?: string\n\n\t// Controls\n\texpect?: string\n\t'max-forwards'?: string\n\n\t// Cokies\n\tcookie?: string\n\t'set-cookie'?: string | string[]\n\n\t// CORS\n\t'access-control-allow-origin'?: string\n\t'access-control-allow-credentials'?: string\n\t'access-control-allow-headers'?: string\n\t'access-control-allow-methods'?: string\n\t'access-control-expose-headers'?: string\n\t'access-control-max-age'?: string\n\t'access-control-request-headers'?: string\n\t'access-control-request-method'?: string\n\torigin?: string\n\t'timing-allow-origin'?: string\n\n\t// Downloads\n\t'content-disposition'?: string\n\n\t// Message body information\n\t'content-length'?: string | number\n\t'content-type'?: SetContentType | (string & {})\n\t'content-encoding'?: string\n\t'content-language'?: string\n\t'content-location'?: string\n\n\t// Proxies\n\tforwarded?: string\n\tvia?: string\n\n\t// Redirects\n\tlocation?: string\n\trefresh?: string\n\n\t// Request context\n\t// from?: string\n\t// host?: string\n\t// referer?: string\n\t// 'user-agent'?: string\n\n\t// Response context\n\tallow?: string\n\tserver?: 'Elysia' | (string & {})\n\n\t// Range requests\n\t'accept-ranges'?: string\n\trange?: string\n\t'if-range'?: string\n\t'content-range'?: string\n\n\t// Security\n\t'content-security-policy'?: string\n\t'content-security-policy-report-only'?: string\n\t'cross-origin-embedder-policy'?: string\n\t'cross-origin-opener-policy'?: string\n\t'cross-origin-resource-policy'?: string\n\t'expect-ct'?: string\n\t'permission-policy'?: string\n\t'strict-transport-security'?: string\n\t'upgrade-insecure-requests'?: string\n\t'x-content-type-options'?: string\n\t'x-frame-options'?: string\n\t'x-xss-protection'?: string\n\n\t// Server-sent events\n\t'last-event-id'?: string\n\t'ping-from'?: string\n\t'ping-to'?: string\n\t'report-to'?: string\n\n\t// Transfer coding\n\tte?: string\n\ttrailer?: string\n\t'transfer-encoding'?: string\n\n\t// Other\n\t'alt-svg'?: string\n\t'alt-used'?: string\n\tdate?: string\n\tdnt?: string\n\t'early-data'?: string\n\t'large-allocation'?: string\n\tlink?: string\n\t'retry-after'?: string\n\t'service-worker-allowed'?: string\n\t'source-map'?: string\n\tupgrade?: string\n\n\t// Non-standard\n\t'x-dns-prefetch-control'?: string\n\t'x-forwarded-for'?: string\n\t'x-forwarded-host'?: string\n\t'x-forwarded-proto'?: string\n\t'x-powered-by'?: 'Elysia' | (string & {})\n\t'x-request-id'?: string\n\t'x-requested-with'?: string\n\t'x-robots-tag'?: string\n\t'x-ua-compatible'?: string\n}\n\nexport type JoinPath<\n\tA extends string,\n\tB extends string\n> = B extends `/${string}` ? `${A}${B}` : `${A}/${B}`\n\nexport type UnwrapTypeModule<Module extends TModule<any, any>> =\n\tModule extends TModule<infer Type extends TProperties, any> ? Type : {}\n\nexport type MergeTypeModule<\n\tA extends TModule<any, any>,\n\tB extends TModule<any, any>\n> = TModule<Prettify<UnwrapTypeModule<A> & UnwrapTypeModule<B>>>\n\nexport type SSEPayload<\n\tData extends unknown = unknown,\n\tEvent extends string | undefined = string | undefined\n> = {\n\t/** id of the event */\n\tid?: string | number | null\n\t/** event name */\n\tevent?: Event\n\t/** retry in millisecond */\n\tretry?: number\n\t/** data to send */\n\tdata?: Data\n}\n\nexport type UnionResponseStatus<A, B> = {} extends A\n\t? B\n\t: {} extends B\n\t\t? A\n\t\t: {\n\t\t\t\t[key in keyof A | keyof B]: key extends keyof A\n\t\t\t\t\t? key extends keyof B\n\t\t\t\t\t\t? A[key] | B[key]\n\t\t\t\t\t\t: A[key]\n\t\t\t\t\t: key extends keyof B\n\t\t\t\t\t\t? B[key]\n\t\t\t\t\t\t: never\n\t\t\t}\n\nexport type CreateEdenResponse<\n\tPath extends string,\n\tSchema extends RouteSchema,\n\tMacroContext extends RouteSchema,\n\t// This should be handled by ComposeElysiaResponse\n\tRes extends PossibleResponse\n> = RouteSchema extends MacroContext\n\t? {\n\t\t\tbody: Schema['body']\n\t\t\tparams: IsNever<keyof Schema['params']> extends true\n\t\t\t\t? ResolvePath<Path>\n\t\t\t\t: Schema['params']\n\t\t\tquery: Schema['query']\n\t\t\theaders: Schema['headers']\n\t\t\tresponse: Prettify<Res>\n\t\t}\n\t: {\n\t\t\tbody: Prettify<Schema['body'] & MacroContext['body']>\n\t\t\tparams: IsNever<\n\t\t\t\tkeyof (Schema['params'] & MacroContext['params'])\n\t\t\t> extends true\n\t\t\t\t? ResolvePath<Path>\n\t\t\t\t: Prettify<Schema['params'] & MacroContext['params']>\n\t\t\tquery: Prettify<Schema['query'] & MacroContext['query']>\n\t\t\theaders: Prettify<Schema['headers'] & MacroContext['headers']>\n\t\t\tresponse: Prettify<Res>\n\t\t}\n\nexport interface Router {\n\t'~http':\n\t\t| Memoirist<{\n\t\t\t\tcompile: Function\n\t\t\t\thandler?: ComposedHandler\n\t\t  }>\n\t\t| undefined\n\tget http(): Memoirist<{\n\t\tcompile: Function\n\t\thandler?: ComposedHandler\n\t}>\n\t'~dynamic': Memoirist<DynamicHandler> | undefined\n\tget dynamic(): Memoirist<DynamicHandler>\n\t// Static Router\n\tstatic: { [path: string]: { [method: string]: number } }\n\t// Native Static Response\n\tresponse: {\n\t\t[path: string]:\n\t\t\t| MaybePromise<Response | undefined>\n\t\t\t| { [method: string]: MaybePromise<Response | undefined> }\n\t}\n\thistory: InternalRoute[]\n}\n\nexport type ModelsToTypes<T extends Record<keyof any, AnySchema>> = {\n\t[K in keyof T]: UnwrapSchema<T[K]>\n}\n"
  },
  {
    "path": "src/universal/env.ts",
    "content": "import { isBun } from './utils'\n\nexport const env = isBun\n\t? Bun.env\n\t: typeof process !== 'undefined' && process?.env\n\t\t? process.env\n\t\t: {}\n"
  },
  {
    "path": "src/universal/file.ts",
    "content": "/* eslint-disable sonarjs/no-duplicate-string */\nimport { type createReadStream as CreateReadStream } from 'fs'\nimport { type stat as Stat } from 'fs/promises'\nimport type { BunFile } from 'bun'\n\nimport { isBun } from './utils'\n\nexport const mime = {\n\taac: 'audio/aac',\n\tabw: 'application/x-abiword',\n\tai: 'application/postscript',\n\tarc: 'application/octet-stream',\n\tavi: 'video/x-msvideo',\n\tazw: 'application/vnd.amazon.ebook',\n\tbin: 'application/octet-stream',\n\tbz: 'application/x-bzip',\n\tbz2: 'application/x-bzip2',\n\tcsh: 'application/x-csh',\n\tcss: 'text/css',\n\tcsv: 'text/csv',\n\tdoc: 'application/msword',\n\tdll: 'application/octet-stream',\n\teot: 'application/vnd.ms-fontobject',\n\tepub: 'application/epub+zip',\n\tgif: 'image/gif',\n\thtm: 'text/html',\n\thtml: 'text/html',\n\tico: 'image/x-icon',\n\tics: 'text/calendar',\n\tjar: 'application/java-archive',\n\tjpeg: 'image/jpeg',\n\tjpg: 'image/jpeg',\n\tjs: 'application/javascript',\n\tjson: 'application/json',\n\tmid: 'audio/midi',\n\tmidi: 'audio/midi',\n\tmp2: 'audio/mpeg',\n\tmp3: 'audio/mpeg',\n\tmp4: 'video/mp4',\n\tmpa: 'video/mpeg',\n\tmpe: 'video/mpeg',\n\tmpeg: 'video/mpeg',\n\tmpkg: 'application/vnd.apple.installer+xml',\n\todp: 'application/vnd.oasis.opendocument.presentation',\n\tods: 'application/vnd.oasis.opendocument.spreadsheet',\n\todt: 'application/vnd.oasis.opendocument.text',\n\toga: 'audio/ogg',\n\togv: 'video/ogg',\n\togx: 'application/ogg',\n\totf: 'font/otf',\n\tpng: 'image/png',\n\tpdf: 'application/pdf',\n\tppt: 'application/vnd.ms-powerpoint',\n\trar: 'application/x-rar-compressed',\n\trtf: 'application/rtf',\n\tsh: 'application/x-sh',\n\tsvg: 'image/svg+xml',\n\tswf: 'application/x-shockwave-flash',\n\ttar: 'application/x-tar',\n\ttif: 'image/tiff',\n\ttiff: 'image/tiff',\n\tts: 'application/typescript',\n\tttf: 'font/ttf',\n\ttxt: 'text/plain',\n\tvsd: 'application/vnd.visio',\n\twav: 'audio/x-wav',\n\tweba: 'audio/webm',\n\twebm: 'video/webm',\n\twebp: 'image/webp',\n\twoff: 'font/woff',\n\twoff2: 'font/woff2',\n\txhtml: 'application/xhtml+xml',\n\txls: 'application/vnd.ms-excel',\n\txlsx: 'application/vnd.ms-excel',\n\txlsx_OLD:\n\t\t'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n\txml: 'application/xml',\n\txul: 'application/vnd.mozilla.xul+xml',\n\tzip: 'application/zip',\n\t'3gp': 'video/3gpp',\n\t'3gp_DOES_NOT_CONTAIN_VIDEO': 'audio/3gpp',\n\t'3gp2': 'video/3gpp2',\n\t'3gp2_DOES_NOT_CONTAIN_VIDEO': 'audio/3gpp2',\n\t'7z': 'application/x-7z-compressed'\n} as const\n\nexport const getFileExtension = (path: string) => {\n\tconst index = path.lastIndexOf('.')\n\tif (index === -1) return ''\n\n\treturn path.slice(index + 1)\n}\n\nexport const file = (path: string) => new ElysiaFile(path)\n\nlet createReadStream: typeof CreateReadStream\nlet stat: typeof Stat\n\nexport class ElysiaFile {\n\treadonly value: unknown\n\treadonly stats: ReturnType<typeof Stat> | undefined\n\n\tconstructor(public path: string) {\n\t\tif (isBun) this.value = Bun.file(path)\n\t\telse {\n\t\t\t// Browser\n\t\t\t// @ts-ignore\n\t\t\tif (!createReadStream || !stat) {\n\t\t\t\t// @ts-ignore\n\t\t\t\tif (typeof window !== 'undefined') {\n\t\t\t\t\tconsole.warn('Browser environment does not support file')\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst warnMissing = (name?: string) =>\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`[elysia] \\`file\\` require \\`fs${name ? '.' + name : ''}\\` ${name?.includes('.') ? 'module ' : ''}which is not available in this environment`\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\n\t\t\t\tif (\n\t\t\t\t\ttypeof process === 'undefined' ||\n\t\t\t\t\ttypeof process.getBuiltinModule !== 'function'\n\t\t\t\t) {\n\t\t\t\t\twarnMissing()\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst fs = process.getBuiltinModule('fs')\n\t\t\t\tif (!fs) {\n\t\t\t\t\twarnMissing()\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif (typeof fs.createReadStream !== 'function') {\n\t\t\t\t\twarnMissing()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (typeof fs.promises?.stat !== 'function') {\n\t\t\t\t\twarnMissing()\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tcreateReadStream = fs.createReadStream\n\t\t\t\tstat = fs.promises.stat\n\t\t\t}\n\n\t\t\t// Readstream can be only readonce\n\t\t\t// IIFE to ensure it's created immediately\n\t\t\tthis.value = (() => createReadStream(path))()\n\t\t\tthis.stats = stat(path)!\n\t\t}\n\t}\n\n\tget type() {\n\t\treturn (\n\t\t\t// @ts-ignore\n\t\t\tmime[getFileExtension(this.path)] || 'application/octet-stream'\n\t\t)\n\t}\n\n\tget length() {\n\t\tif (isBun) return (this.value as BunFile).size\n\n\t\treturn this.stats?.then((x) => x.size) ?? 0\n\t}\n}\n"
  },
  {
    "path": "src/universal/index.ts",
    "content": "export { env } from './env'\nexport { file } from './file'\nexport type {\n\tErrorLike,\n\tGenericServeOptions,\n\tServe,\n\tServeOptions,\n\tServer,\n\tServerWebSocketSendStatus,\n\tSocketAddress\n} from './server'\n"
  },
  {
    "path": "src/universal/request.ts",
    "content": "import type {\n\tHeadersInit,\n\tRequestCache,\n\tRequestCredentials,\n\tRequestDestination,\n\tRequestDuplex,\n\tRequestInfo,\n\tRequestInit,\n\tRequestMode,\n\tRequestRedirect,\n\tWebStandardRequest\n} from './types'\n\nexport class ElysiaRequest implements WebStandardRequest {\n\tconstructor(\n\t\tprivate input: RequestInfo,\n\t\tprivate init?: RequestInit\n\t) {\n\t\tif (typeof input === 'string') this.url = input\n\t\telse if (input instanceof URL) this.url = input.href\n\t\telse if (input instanceof Request) this.url = input.url\n\t\telse throw new TypeError('Invalid url')\n\n\t\tif (init) {\n\t\t\tif (init.method) this.method = init.method\n\t\t\tif (init.keepalive) this.keepalive = init.keepalive\n\t\t\tif (init.redirect) this.redirect = init.redirect\n\t\t\tif (init.integrity) this.integrity = init.integrity\n\t\t\tif (init.signal) this._signal = init.signal\n\t\t\tif (init.credentials) this.credentials = init.credentials\n\t\t\tif (init.mode) this.mode = init.mode\n\t\t\tif (init.referrerPolicy) this.referrerPolicy = init.referrerPolicy\n\t\t\tif (init.duplex) this.duplex = init.duplex\n\t\t}\n\t}\n\n\treadonly cache = 'default' as RequestCache\n\treadonly credentials = 'omit' as RequestCredentials\n\treadonly destination = '' as RequestDestination\n\treadonly integrity: string = ''\n\treadonly method: string = 'GET'\n\treadonly mode = 'no-cors' as RequestMode\n\treadonly redirect = 'manual' as RequestRedirect\n\treadonly referrerPolicy: string = ''\n\treadonly url: string\n\n\tprivate _headers: Headers | undefined\n\tget headers() {\n\t\tif (this._headers) return this._headers\n\n\t\t// @ts-ignore Bun\n\t\tif (!this.init?.headers) return (this._headers = new Headers())\n\n\t\tconst headers = this.init.headers\n\n\t\tif (Array.isArray(headers))\n\t\t\t// @ts-ignore Bun\n\t\t\treturn (this._headers = new Headers(headers))\n\n\t\tif (headers instanceof Headers)\n\t\t\t// @ts-ignore Bun\n\t\t\treturn (this._headers = headers)\n\n\t\tif (headers)\n\t\t\t// @ts-ignore Bun\n\t\t\treturn (this._headers = new Headers(headers as HeadersInit))\n\n\t\treturn (this._headers = new Headers() as Headers)\n\t}\n\n\treadonly keepalive: boolean = false\n\tprivate _signal: AbortSignal | undefined\n\tget signal() {\n\t\tif (this._signal) return this._signal\n\n\t\treturn (this._signal = new AbortController().signal)\n\t}\n\treadonly duplex = 'half' as RequestDuplex\n\treadonly bodyUsed: boolean = false\n\n\tget body(): ReadableStream | null {\n\t\tif (this.method === 'GET' || this.method === 'HEAD' || !this.init?.body)\n\t\t\treturn null\n\n\t\tconst body = this.init.body\n\n\t\tif (body instanceof ReadableStream) return body\n\n\t\tif (body instanceof ArrayBuffer)\n\t\t\treturn new ReadableStream({\n\t\t\t\tstart(controller) {\n\t\t\t\t\tcontroller.enqueue(body)\n\t\t\t\t\tcontroller.close()\n\t\t\t\t}\n\t\t\t})\n\n\t\tif (body instanceof Blob) return body.stream()\n\n\t\tif (typeof body === 'string')\n\t\t\treturn new ReadableStream({\n\t\t\t\tstart(controller) {\n\t\t\t\t\tcontroller.enqueue(new TextEncoder().encode(body))\n\t\t\t\t\tcontroller.close()\n\t\t\t\t}\n\t\t\t})\n\n\t\tif (body instanceof URLSearchParams || body instanceof FormData)\n\t\t\treturn new ReadableStream({\n\t\t\t\tstart(controller) {\n\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\tnew TextEncoder().encode(body.toString())\n\t\t\t\t\t)\n\t\t\t\t\tcontroller.close()\n\t\t\t\t}\n\t\t\t})\n\n\t\tif (body instanceof DataView)\n\t\t\treturn new ReadableStream({\n\t\t\t\tstart(controller) {\n\t\t\t\t\tcontroller.enqueue(body.buffer)\n\t\t\t\t\tcontroller.close()\n\t\t\t\t}\n\t\t\t})\n\n\t\tif (Symbol.iterator in body)\n\t\t\treturn new ReadableStream({\n\t\t\t\tstart(controller) {\n\t\t\t\t\tfor (const chunk of body) controller.enqueue(chunk)\n\n\t\t\t\t\tcontroller.close()\n\t\t\t\t}\n\t\t\t})\n\n\t\tif (Symbol.asyncIterator in body)\n\t\t\treturn new ReadableStream({\n\t\t\t\tasync start(controller) {\n\t\t\t\t\tfor await (const chunk of body) controller.enqueue(chunk)\n\n\t\t\t\t\tcontroller.close()\n\t\t\t\t}\n\t\t\t})\n\n\t\treturn null\n\t}\n\n\tasync arrayBuffer() {\n\t\tif (this.init?.body instanceof ArrayBuffer) return this.init.body\n\t\tif (!this.body) return new ArrayBuffer(0)\n\n\t\tconst chunks = []\n\n\t\tfor await (const chunk of this.body) chunks.push(chunk)\n\n\t\treturn Buffer.concat(chunks) as unknown as ArrayBuffer\n\t}\n\n\tasync blob() {\n\t\tif (this.init?.body instanceof Blob) return this.init.body\n\n\t\tconst buffer = await this.arrayBuffer()\n\t\treturn new Blob([buffer]) as Blob\n\t}\n\n\tasync formData() {\n\t\tif (this.init?.body instanceof FormData) return this.init.body\n\n\t\tthrow new Error('Unable to parse body as FormData')\n\t}\n\n\tasync json() {\n\t\tif (this.init?.body instanceof ReadableStream)\n\t\t\treturn JSON.parse(await readableStreamToString(this.init.body))\n\n\t\tif (typeof this.init?.body === 'string')\n\t\t\treturn JSON.parse(this.init.body)\n\n\t\tif (this.init?.body instanceof ArrayBuffer)\n\t\t\treturn JSON.parse(Buffer.from(this.init.body).toString())\n\n\t\treturn JSON.parse(Buffer.from(await this.arrayBuffer()).toString())\n\t}\n\n\tasync text() {\n\t\tif (this.init?.body instanceof ReadableStream)\n\t\t\treturn readableStreamToString(this.init.body)\n\n\t\tif (typeof this.init?.body === 'string') return this.init.body\n\n\t\tif (this.init?.body instanceof ArrayBuffer)\n\t\t\treturn Buffer.from(this.init.body).toString()\n\n\t\tconst buffer = await this.arrayBuffer()\n\t\treturn Buffer.from(buffer).toString()\n\t}\n\n\t// @ts-ignore\n\tclone(): ElysiaRequest {\n\t\treturn new ElysiaRequest(this.input, this.init)\n\t}\n}\n\nasync function readableStreamToString(stream: ReadableStream) {\n\tconst chunks = <Uint8Array[]>[]\n\tfor await (const chunk of stream) chunks.push(chunk)\n\n\t// @ts-ignore this is intentional, it works\n\treturn Buffer.from(Buffer.concat(chunks)).toString()\n}\n"
  },
  {
    "path": "src/universal/server.ts",
    "content": "import { Serve as BunServe, type Server as BunServer } from 'bun'\nimport type { Equal, MaybePromise } from '../types'\n\nexport interface ErrorLike extends Error {\n\tcode?: string\n\terrno?: number\n\tsyscall?: string\n}\n\nexport interface GenericServeOptions {\n\t/**\n\t * What URI should be used to make {@link Request.url} absolute?\n\t *\n\t * By default, looks at {@link hostname}, {@link port}, and whether or not SSL is enabled to generate one\n\t *\n\t * @example\n\t * ```js\n\t * \"http://my-app.com\"\n\t * ```\n\t *\n\t * @example\n\t * ```js\n\t * \"https://wongmjane.com/\"\n\t * ```\n\t *\n\t * This should be the public, absolute URL – include the protocol and {@link hostname}. If the port isn't 80 or 443, then include the {@link port} too.\n\t *\n\t * @example\n\t * \"http://localhost:3000\"\n\t */\n\t// baseURI?: string;\n\n\t/**\n\t * What is the maximum size of a request body? (in bytes)\n\t * @default 1024 * 1024 * 128 // 128MB\n\t */\n\tmaxRequestBodySize?: number\n\n\t/**\n\t * Render contextual errors? This enables bun's error page\n\t * @default process.env.NODE_ENV !== 'production'\n\t */\n\tdevelopment?: boolean\n\n\terror?: (\n\t\tthis: Server,\n\t\trequest: ErrorLike\n\t) => Response | Promise<Response> | undefined | Promise<undefined>\n\n\t/**\n\t * Uniquely identify a server instance with an ID\n\t *\n\t * ### When bun is started with the `--hot` flag\n\t *\n\t * This string will be used to hot reload the server without interrupting\n\t * pending requests or websockets. If not provided, a value will be\n\t * generated. To disable hot reloading, set this value to `null`.\n\t *\n\t * ### When bun is not started with the `--hot` flag\n\t *\n\t * This string will currently do nothing. But in the future it could be useful for logs or metrics.\n\t */\n\tid?: string | null\n}\n\nexport interface ServeOptions extends GenericServeOptions {\n\t/**\n\t * What port should the server listen on?\n\t * @default process.env.PORT || \"3000\"\n\t */\n\tport?: string | number\n\n\t/**\n\t * If the `SO_REUSEPORT` flag should be set.\n\t *\n\t * This allows multiple processes to bind to the same port, which is useful for load balancing.\n\t *\n\t * @default false\n\t */\n\treusePort?: boolean\n\n\t/**\n\t * What hostname should the server listen on?\n\t *\n\t * @default\n\t * ```js\n\t * \"0.0.0.0\" // listen on all interfaces\n\t * ```\n\t * @example\n\t *  ```js\n\t * \"127.0.0.1\" // Only listen locally\n\t * ```\n\t * @example\n\t * ```js\n\t * \"remix.run\" // Only listen on remix.run\n\t * ````\n\t *\n\t * note: hostname should not include a {@link port}\n\t */\n\thostname?: string\n\n\t/**\n\t * If set, the HTTP server will listen on a unix socket instead of a port.\n\t * (Cannot be used with hostname+port)\n\t */\n\tunix?: never\n\n\t/**\n\t * Handle HTTP requests\n\t *\n\t * Respond to {@link Request} objects with a {@link Response} object.\n\t */\n\tfetch(\n\t\tthis: Server,\n\t\trequest: Request,\n\t\tserver: Server\n\t): Response | Promise<Response>\n\n\troutes: Record<\n\t\tstring,\n\t\tFunction | Response | Record<string, Function | Response>\n\t>\n}\n\nexport type Serve =\n\tEqual<BunServe.Options<unknown>, unknown> extends false\n\t\t? BunServe.Options<unknown>\n\t\t: ServeOptions\nexport type Server =\n\tEqual<BunServer<unknown>, unknown> extends false\n\t\t? BunServer<unknown>\n\t\t: ServerOptions\n\nexport type ServerWebSocketSendStatus = number\n\nexport interface SocketAddress {\n\t/**\n\t * The IP address of the client.\n\t */\n\taddress: string\n\t/**\n\t * The port of the client.\n\t */\n\tport: number\n\t/**\n\t * The IP family (\"IPv4\" or \"IPv6\").\n\t */\n\tfamily: 'IPv4' | 'IPv6'\n}\n\nexport interface ServerOptions extends Disposable {\n\t/**\n\t * Stop listening to prevent new connections from being accepted.\n\t *\n\t * By default, it does not cancel in-flight requests or websockets. That means it may take some time before all network activity stops.\n\t *\n\t * @param closeActiveConnections Immediately terminate in-flight requests, websockets, and stop accepting new connections.\n\t * @default false\n\t */\n\tstop(closeActiveConnections?: boolean): void\n\n\t/**\n\t * Update the `fetch` and `error` handlers without restarting the server.\n\t *\n\t * This is useful if you want to change the behavior of your server without\n\t * restarting it or for hot reloading.\n\t *\n\t * @example\n\t *\n\t * ```js\n\t * // create the server\n\t * const server = Bun.serve({\n\t *  fetch(request) {\n\t *    return new Response(\"Hello World v1\")\n\t *  }\n\t * });\n\t *\n\t * // Update the server to return a different response\n\t * server.reload({\n\t *   fetch(request) {\n\t *     return new Response(\"Hello World v2\")\n\t *   }\n\t * });\n\t * ```\n\t *\n\t * Passing other options such as `port` or `hostname` won't do anything.\n\t */\n\treload(options: Serve): void\n\n\t/**\n\t * Mock the fetch handler for a running server.\n\t *\n\t * This feature is not fully implemented yet. It doesn't normalize URLs\n\t * consistently in all cases and it doesn't yet call the `error` handler\n\t * consistently. This needs to be fixed\n\t */\n\tfetch(request: Request | string): Response | Promise<Response>\n\n\t/**\n\t * Upgrade a {@link Request} to a {@link ServerWebSocket}\n\t *\n\t * @param request The {@link Request} to upgrade\n\t * @param options Pass headers or attach data to the {@link ServerWebSocket}\n\t *\n\t * @returns `true` if the upgrade was successful and `false` if it failed\n\t *\n\t * @example\n\t * ```js\n\t * import { serve } from \"bun\";\n\t *  serve({\n\t *    websocket: {\n\t *      open: (ws) => {\n\t *        console.log(\"Client connected\");\n\t *      },\n\t *      message: (ws, message) => {\n\t *        console.log(\"Client sent message\", message);\n\t *      },\n\t *      close: (ws) => {\n\t *        console.log(\"Client disconnected\");\n\t *      },\n\t *    },\n\t *    fetch(req, server) {\n\t *      const url = new URL(req.url);\n\t *      if (url.pathname === \"/chat\") {\n\t *        const upgraded = server.upgrade(req);\n\t *        if (!upgraded) {\n\t *          return new Response(\"Upgrade failed\", { status: 400 });\n\t *        }\n\t *      }\n\t *      return new Response(\"Hello World\");\n\t *    },\n\t *  });\n\t * ```\n\t *  What you pass to `data` is available on the {@link ServerWebSocket.data} property\n\t */\n\tupgrade<T = undefined>(\n\t\trequest: Request,\n\t\toptions?: {\n\t\t\t/**\n\t\t\t * Send any additional headers while upgrading, like cookies\n\t\t\t */\n\t\t\theaders?: Bun.HeadersInit\n\t\t\t/**\n\t\t\t * This value is passed to the {@link ServerWebSocket.data} property\n\t\t\t */\n\t\t\tdata?: T\n\t\t}\n\t): boolean\n\n\t/**\n\t * Send a message to all connected {@link ServerWebSocket} subscribed to a topic\n\t *\n\t * @param topic The topic to publish to\n\t * @param data The data to send\n\t * @param compress Should the data be compressed? Ignored if the client does not support compression.\n\t *\n\t * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.\n\t *\n\t * @example\n\t *\n\t * ```js\n\t * server.publish(\"chat\", \"Hello World\");\n\t * ```\n\t *\n\t * @example\n\t * ```js\n\t * server.publish(\"chat\", new Uint8Array([1, 2, 3, 4]));\n\t * ```\n\t *\n\t * @example\n\t * ```js\n\t * server.publish(\"chat\", new ArrayBuffer(4), true);\n\t * ```\n\t *\n\t * @example\n\t * ```js\n\t * server.publish(\"chat\", new DataView(new ArrayBuffer(4)));\n\t * ```\n\t */\n\tpublish(\n\t\ttopic: string,\n\t\tdata: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,\n\t\tcompress?: boolean\n\t): ServerWebSocketSendStatus\n\n\t/**\n\t * Returns the client IP address and port of the given Request. If the request was closed or is a unix socket, returns null.\n\t *\n\t * @example\n\t * ```js\n\t * export default {\n\t *  async fetch(request, server) {\n\t *    return new Response(server.requestIP(request));\n\t *  }\n\t * }\n\t * ```\n\t */\n\trequestIP(request: Request): SocketAddress | null\n\n\t/**\n\t * Reset the idleTimeout of the given Request to the number in seconds. 0 means no timeout.\n\t *\n\t * @example\n\t * ```js\n\t * export default {\n\t *  async fetch(request, server) {\n\t *    server.timeout(request, 60);\n\t *    await Bun.sleep(30000);\n\t *    return new Response(\"30 seconds have passed\");\n\t *  }\n\t * }\n\t * ```\n\t */\n\ttimeout(request: Request, seconds: number): void\n\n\t/**\n\t * Undo a call to {@link Server.unref}\n\t *\n\t * If the Server has already been stopped, this does nothing.\n\t *\n\t * If {@link Server.ref} is called multiple times, this does nothing. Think of it as a boolean toggle.\n\t */\n\tref(): void\n\n\t/**\n\t * Don't keep the process alive if this server is the only thing left.\n\t * Active connections may continue to keep the process alive.\n\t *\n\t * By default, the server is ref'd.\n\t *\n\t * To prevent new connections from being accepted, use {@link Server.stop}\n\t */\n\tunref(): void\n\n\t/**\n\t * How many requests are in-flight right now?\n\t */\n\treadonly pendingRequests: number\n\n\t/**\n\t * How many {@link ServerWebSocket}s are in-flight right now?\n\t */\n\treadonly pendingWebSockets: number\n\n\treadonly url: URL\n\n\treadonly port: number\n\t/**\n\t * The hostname the server is listening on. Does not include the port\n\t * @example\n\t * ```js\n\t * \"localhost\"\n\t * ```\n\t */\n\treadonly hostname: string\n\t/**\n\t * Is the server running in development mode?\n\t *\n\t * In development mode, `Bun.serve()` returns rendered error messages with\n\t * stack traces instead of a generic 500 error. This makes debugging easier,\n\t * but development mode shouldn't be used in production or you will risk\n\t * leaking sensitive information.\n\t */\n\treadonly development: boolean\n\n\t/**\n\t * An identifier of the server instance\n\t *\n\t * When bun is started with the `--hot` flag, this ID is used to hot reload the server without interrupting pending requests or websockets.\n\t *\n\t * When bun is not started with the `--hot` flag, this ID is currently unused.\n\t */\n\treadonly id: string\n}\n\nexport type ListenCallback = (server: Server) => MaybePromise<void>\n"
  },
  {
    "path": "src/universal/types.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\n// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license)\n// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license)\nexport type RequestInfo = string | URL | Request\n\nexport declare function fetch(\n\tinput: RequestInfo,\n\tinit?: RequestInit\n): Promise<Response>\n\nexport type BodyInit =\n\t| ArrayBuffer\n\t| AsyncIterable<Uint8Array>\n\t| Blob\n\t| FormData\n\t| Iterable<Uint8Array>\n\t| NodeJS.ArrayBufferView\n\t| URLSearchParams\n\t| null\n\t| string\n\nexport interface BodyMixin {\n\treadonly body: ReadableStream | null\n\treadonly bodyUsed: boolean\n\n\treadonly arrayBuffer: () => Promise<ArrayBuffer>\n\treadonly blob: () => Promise<Blob>\n\treadonly formData: () => Promise<FormData>\n\treadonly json: () => Promise<unknown>\n\treadonly text: () => Promise<string>\n}\n\nexport interface SpecIterator<T, TReturn = any, TNext = undefined> {\n\tnext(...args: [] | [TNext]): IteratorResult<T, TReturn>\n}\n\nexport interface SpecIterableIterator<T> extends SpecIterator<T> {\n\t[Symbol.iterator](): SpecIterableIterator<T>\n}\n\nexport interface SpecIterable<T> {\n\t[Symbol.iterator](): SpecIterator<T>\n}\n\nexport type HeadersInit =\n\t| string[][]\n\t| Record<string, string | ReadonlyArray<string>>\n\t| Headers\n\nexport declare class Headers implements SpecIterable<[string, string]> {\n\tconstructor(init?: HeadersInit)\n\treadonly append: (name: string, value: string) => void\n\treadonly delete: (name: string) => void\n\treadonly get: (name: string) => string | null\n\treadonly has: (name: string) => boolean\n\treadonly set: (name: string, value: string) => void\n\treadonly getSetCookie: () => string[]\n\treadonly forEach: (\n\t\tcallbackfn: (value: string, key: string, iterable: Headers) => void,\n\t\tthisArg?: unknown\n\t) => void\n\n\treadonly keys: () => SpecIterableIterator<string>\n\treadonly values: () => SpecIterableIterator<string>\n\treadonly entries: () => SpecIterableIterator<[string, string]>\n\treadonly [Symbol.iterator]: () => SpecIterator<[string, string]>\n}\n\nexport type RequestCache =\n\t| 'default'\n\t| 'force-cache'\n\t| 'no-cache'\n\t| 'no-store'\n\t| 'only-if-cached'\n\t| 'reload'\n\nexport type RequestCredentials = 'omit' | 'include' | 'same-origin'\n\nexport type RequestDestination =\n\t| ''\n\t| 'audio'\n\t| 'audioworklet'\n\t| 'document'\n\t| 'embed'\n\t| 'font'\n\t| 'image'\n\t| 'manifest'\n\t| 'object'\n\t| 'paintworklet'\n\t| 'report'\n\t| 'script'\n\t| 'sharedworker'\n\t| 'style'\n\t| 'track'\n\t| 'video'\n\t| 'worker'\n\t| 'xslt'\n\nexport interface RequestInit {\n\tmethod?: string\n\tkeepalive?: boolean\n\theaders?: HeadersInit\n\tbody?: BodyInit\n\tredirect?: RequestRedirect\n\tintegrity?: string\n\tsignal?: AbortSignal\n\tcredentials?: RequestCredentials\n\tmode?: RequestMode\n\treferrer?: string\n\treferrerPolicy?: ReferrerPolicy\n\twindow?: null\n\tdispatcher?: unknown\n\tduplex?: RequestDuplex\n}\n\nexport type ReferrerPolicy =\n\t| ''\n\t| 'no-referrer'\n\t| 'no-referrer-when-downgrade'\n\t| 'origin'\n\t| 'origin-when-cross-origin'\n\t| 'same-origin'\n\t| 'strict-origin'\n\t| 'strict-origin-when-cross-origin'\n\t| 'unsafe-url'\n\nexport type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin'\n\nexport type RequestRedirect = 'error' | 'follow' | 'manual'\n\nexport type RequestDuplex = 'half'\n\nexport abstract class WebStandardRequest implements BodyMixin {\n\tabstract readonly cache: RequestCache\n\tabstract readonly credentials: RequestCredentials\n\tabstract readonly destination: RequestDestination\n\tabstract readonly headers: Headers\n\tabstract readonly integrity: string\n\tabstract readonly method: string\n\tabstract readonly mode: RequestMode\n\tabstract readonly redirect: RequestRedirect\n\tabstract readonly referrerPolicy: string\n\tabstract readonly url: string\n\n\tabstract readonly keepalive: boolean\n\tabstract readonly signal: AbortSignal\n\tabstract readonly duplex: RequestDuplex\n\n\tabstract readonly body: ReadableStream | null\n\tabstract readonly bodyUsed: boolean\n\n\tabstract readonly arrayBuffer: () => Promise<ArrayBuffer>\n\tabstract readonly blob: () => Promise<Blob>\n\tabstract readonly formData: () => Promise<FormData>\n\tabstract readonly json: () => Promise<unknown>\n\tabstract readonly text: () => Promise<string>\n\n\tabstract readonly clone: () => Request\n}\n\nexport interface ResponseInit {\n\treadonly status?: number\n\treadonly statusText?: string\n\treadonly headers?: HeadersInit\n}\n\nexport type ResponseType =\n\t| 'basic'\n\t| 'cors'\n\t| 'default'\n\t| 'error'\n\t| 'opaque'\n\t| 'opaqueredirect'\n\nexport type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308\n\nexport abstract class WebStandardResponse implements BodyMixin {\n\tconstructor(body?: BodyInit, init?: ResponseInit) {}\n\n\tabstract readonly headers: Headers\n\tabstract readonly ok: boolean\n\tabstract readonly status: number\n\tabstract readonly statusText: string\n\tabstract readonly type: ResponseType\n\tabstract readonly url: string\n\tabstract readonly redirected: boolean\n\n\tabstract readonly body: ReadableStream | null\n\tabstract readonly bodyUsed: boolean\n\n\tabstract readonly arrayBuffer: () => Promise<ArrayBuffer>\n\tabstract readonly blob: () => Promise<Blob>\n\tabstract readonly formData: () => Promise<FormData>\n\tabstract readonly json: () => Promise<unknown>\n\tabstract readonly text: () => Promise<string>\n\n\tabstract readonly clone: () => Response\n\n\tstatic error() {\n\t\treturn Response.error()\n\t}\n\tstatic json(data: any, init?: ResponseInit) {\n\t\treturn Response.json(data, init as any)\n\t}\n\tstatic redirect(url: string, status: ResponseRedirectStatus) {\n\t\treturn Response.redirect(url, status)\n\t}\n}\n\nexport interface BunHTMLBundlelike {\n\tindex: string\n\tfiles?: {\n\t\tinput?: string\n\t\tpath: string\n\t\tloader: any\n\t\tisEntry: boolean\n\t\theaders: {\n\t\t\tetag: string\n\t\t\t'content-type': string\n\t\t\t[key: string]: string\n\t\t}\n\t}[]\n}\n"
  },
  {
    "path": "src/universal/utils.ts",
    "content": "// @ts-ignore\nexport const isBun = typeof Bun !== 'undefined'\n// @ts-ignore\nexport const isDeno = typeof Deno !== 'undefined'\n\nexport function isCloudflareWorker() {\n\ttry {\n\t\t// Check for the presence of caches.default, which is a global in Workers\n\t\tif (\n\t\t\t// @ts-ignore\n\t\t\ttypeof caches !== 'undefined' &&\n\t\t\t// @ts-ignore\n\t\t\ttypeof caches.default !== 'undefined'\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tif (typeof WebSocketPair !== 'undefined') return true\n\t} catch {\n\t\treturn false\n\t}\n\n\treturn false\n}\n"
  },
  {
    "path": "src/utils.ts",
    "content": "import type { Sucrose } from './sucrose'\nimport type { TraceHandler } from './trace'\n\nimport type {\n\tLifeCycleStore,\n\tMaybeArray,\n\tInputSchema,\n\tLifeCycleType,\n\tHookContainer,\n\tGracefulHandler,\n\tPreHandler,\n\tBodyHandler,\n\tTransformHandler,\n\tOptionalHandler,\n\tMapResponse,\n\tErrorHandler,\n\tReplace,\n\tAfterResponseHandler,\n\tSchemaValidator,\n\tAnyLocalHook,\n\tSSEPayload,\n\tPrettify,\n\tRouteSchema\n} from './types'\nimport { ElysiaFile } from './universal/file'\nimport { isBun, isCloudflareWorker } from './universal/utils'\n\nexport const replaceUrlPath = (url: string, pathname: string) => {\n\tconst pathStartIndex = url.indexOf('/', 11)\n\tconst queryIndex = url.indexOf('?', pathStartIndex)\n\n\tif (queryIndex === -1)\n\t\treturn `${url.slice(0, pathStartIndex)}${pathname.charCodeAt(0) === 47 ? '' : '/'}${pathname}`\n\n\treturn `${url.slice(0, pathStartIndex)}${pathname.charCodeAt(0) === 47 ? '' : '/'}${pathname}${url.slice(queryIndex)}`\n}\n\nexport const isClass = (v: Object) =>\n\t(typeof v === 'function' && /^\\s*class\\s+/.test(v.toString())) ||\n\t// Handle Object.create(null)\n\t(v.toString &&\n\t\t// Handle import * as Sentry from '@sentry/bun'\n\t\t// This also handle [object Date], [object Array]\n\t\t// and FFI value like [object Prisma]\n\t\tv.toString().startsWith('[object ') &&\n\t\tv.toString() !== '[object Object]') ||\n\t// If object prototype is not pure, then probably a class-like object\n\tisNotEmpty(Object.getPrototypeOf(v))\n\nconst isObject = (item: any): item is Object =>\n\titem && typeof item === 'object' && !Array.isArray(item)\n\nexport const mergeDeep = <\n\tA extends Record<string, any>,\n\tB extends Record<string, any>\n>(\n\ttarget: A,\n\tsource: B,\n\toptions?: {\n\t\tskipKeys?: string[]\n\t\toverride?: boolean\n\t\tmergeArray?: boolean\n\t\tseen?: WeakSet<object>\n\t}\n): A & B => {\n\tconst skipKeys = options?.skipKeys\n\tconst override = options?.override ?? true\n\tconst mergeArray = options?.mergeArray ?? false\n\tconst seen = options?.seen ?? new WeakSet<object>()\n\n\tif (!isObject(target) || !isObject(source)) return target as A & B\n\n\tif (seen.has(source)) return target as A & B\n\tseen.add(source)\n\n\tfor (const [key, value] of Object.entries(source)) {\n\t\tif (\n\t\t\tskipKeys?.includes(key) ||\n\t\t\t['__proto__', 'constructor', 'prototype'].includes(key)\n\t\t)\n\t\t\tcontinue\n\n\t\tif (mergeArray && Array.isArray(value)) {\n\t\t\ttarget[key as keyof typeof target] = Array.isArray(\n\t\t\t\t(target as any)[key]\n\t\t\t)\n\t\t\t\t? [...(target as any)[key], ...value]\n\t\t\t\t: (target[key as keyof typeof target] = value as any)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (!isObject(value) || !(key in target) || isClass(value)) {\n\t\t\tif ((override || !(key in target)) && !Object.isFrozen(target))\n\t\t\t\ttry {\n\t\t\t\t\ttarget[key as keyof typeof target] = value\n\t\t\t\t} catch {}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (!Object.isFrozen(target[key]))\n\t\t\ttry {\n\t\t\t\ttarget[key as keyof typeof target] = mergeDeep(\n\t\t\t\t\t(target as any)[key] as any,\n\t\t\t\t\tvalue,\n\t\t\t\t\t{ skipKeys, override, mergeArray, seen }\n\t\t\t\t)\n\t\t\t} catch {}\n\t}\n\n\tseen.delete(source)\n\n\treturn target as A & B\n}\nexport const mergeCookie = <const A extends Object, const B extends Object>(\n\ta: A,\n\tb: B\n): A & B => {\n\tconst v = mergeDeep(Object.assign({}, a), b, {\n\t\tskipKeys: ['properties'],\n\t\tmergeArray: false\n\t}) as A & B\n\n\t// @ts-expect-error\n\tif (v.properties) delete v.properties\n\n\treturn v\n}\n\nexport const mergeObjectArray = <T extends HookContainer>(\n\ta: T | T[] | undefined,\n\tb: T | T[] | undefined\n): T[] | undefined => {\n\tif (!b) return a as any\n\n\t// ! Must copy to remove side-effect\n\tconst array = <T[]>[]\n\tconst checksums = <(number | undefined)[]>[]\n\n\tif (a) {\n\t\tif (!Array.isArray(a)) a = [a]\n\t\tfor (const item of a) {\n\t\t\tarray.push(item)\n\n\t\t\tif (item.checksum) checksums.push(item.checksum)\n\t\t}\n\t}\n\n\tif (b) {\n\t\tif (!Array.isArray(b)) b = [b]\n\t\tfor (const item of b)\n\t\t\tif (!checksums.includes(item.checksum)) array.push(item)\n\t}\n\n\treturn array\n}\n\nexport const primitiveHooks = [\n\t'start',\n\t'request',\n\t'parse',\n\t'transform',\n\t'resolve',\n\t'beforeHandle',\n\t'afterHandle',\n\t'mapResponse',\n\t'afterResponse',\n\t'trace',\n\t'error',\n\t'stop',\n\t'body',\n\t'headers',\n\t'params',\n\t'query',\n\t'response',\n\t'type',\n\t'detail'\n] as const\n\nconst primitiveHookMap = primitiveHooks.reduce(\n\t(acc, x) => ((acc[x] = true), acc),\n\t{} as Record<string, boolean>\n)\n\n// If both are Record<number, ...> then merge them,\n// giving preference to b.\ntype RecordNumber = Record<number, any>\nconst isRecordNumber = (\n\tx: Record<keyof object, unknown> | undefined\n): x is RecordNumber =>\n\ttypeof x === 'object' && Object.keys(x).every((x) => !isNaN(+x))\n\nexport const mergeResponse = (\n\ta: InputSchema['response'],\n\tb: InputSchema['response']\n) => {\n\tif (isRecordNumber(a) && isRecordNumber(b))\n\t\t// Prevent side effect\n\t\treturn Object.assign({}, a, b)\n\telse if (a && !isRecordNumber(a) && isRecordNumber(b))\n\t\treturn Object.assign({ 200: a }, b)\n\n\treturn b ?? a\n}\n\nexport const mergeSchemaValidator = (\n\ta?: SchemaValidator | null,\n\tb?: SchemaValidator | null\n): SchemaValidator => {\n\tif (!a && !b)\n\t\treturn {\n\t\t\tbody: undefined,\n\t\t\theaders: undefined,\n\t\t\tparams: undefined,\n\t\t\tquery: undefined,\n\t\t\tcookie: undefined,\n\t\t\tresponse: undefined\n\t\t}\n\n\treturn {\n\t\tbody: b?.body ?? a?.body,\n\t\theaders: b?.headers ?? a?.headers,\n\t\tparams: b?.params ?? a?.params,\n\t\tquery: b?.query ?? a?.query,\n\t\tcookie: b?.cookie ?? a?.cookie,\n\t\t// @ts-ignore ? This order is correct - SaltyAom\n\t\tresponse: mergeResponse(\n\t\t\t// @ts-ignore\n\t\t\ta?.response,\n\t\t\t// @ts-ignore\n\t\t\tb?.response\n\t\t)\n\t}\n}\n\nexport const mergeHook = (\n\ta?: Partial<LifeCycleStore>,\n\tb?: AnyLocalHook\n\t// { allowMacro = false }: { allowMacro?: boolean } = {}\n): LifeCycleStore => {\n\t// In case if merging union is need\n\t// const customAStore: Record<string, unknown> = {}\n\t// const customBStore: Record<string, unknown> = {}\n\n\t// for (const [key, value] of Object.entries(a)) {\n\t// \tif (primitiveHooks.includes(key as any)) continue\n\n\t// \tcustomAStore[key] = value\n\t// }\n\n\t// for (const [key, value] of Object.entries(b)) {\n\t// \tif (primitiveHooks.includes(key as any)) continue\n\n\t// \tcustomBStore[key] = value\n\t// }\n\n\t// const unioned = Object.keys(customAStore).filter((x) =>\n\t// \tObject.keys(customBStore).includes(x)\n\t// )\n\n\t// // Must provide empty object to prevent reference side-effect\n\t// const customStore = Object.assign({}, customAStore, customBStore)\n\n\t// for (const union of unioned)\n\t// \tcustomStore[union] = mergeObjectArray(\n\t// \t\tcustomAStore[union],\n\t// \t\tcustomBStore[union]\n\t// \t)\n\n\tif (!b) return (a as any) ?? {}\n\tif (!a) return b ?? {}\n\n\tif (!Object.values(b).find((x) => x !== undefined && x !== null))\n\t\treturn { ...a } as any\n\n\tconst hook = {\n\t\t...a,\n\t\t...b,\n\t\t// Merge local hook first\n\t\t// @ts-ignore\n\t\tbody: b.body ?? a.body,\n\t\t// @ts-ignore\n\t\theaders: b.headers ?? a.headers,\n\t\t// @ts-ignore\n\t\tparams: b.params ?? a.params,\n\t\t// @ts-ignore\n\t\tquery: b.query ?? a.query,\n\t\t// @ts-ignore\n\t\tcookie: b.cookie ?? a.cookie,\n\t\t// ? This order is correct - SaltyAom\n\t\tresponse: mergeResponse(\n\t\t\t// @ts-ignore\n\t\t\ta.response,\n\t\t\t// @ts-ignore\n\t\t\tb.response\n\t\t),\n\t\ttype: a.type || b.type,\n\t\tdetail: mergeDeep(\n\t\t\t// @ts-ignore\n\t\t\tb.detail ?? {},\n\t\t\t// @ts-ignore\n\t\t\ta.detail ?? {}\n\t\t),\n\t\tparse: mergeObjectArray(a.parse as any, b.parse),\n\t\ttransform: mergeObjectArray(a.transform, b.transform),\n\t\tbeforeHandle: mergeObjectArray(\n\t\t\tmergeObjectArray(\n\t\t\t\t// @ts-ignore\n\t\t\t\tfnToContainer(a.resolve, 'resolve'),\n\t\t\t\ta.beforeHandle\n\t\t\t),\n\t\t\tmergeObjectArray(\n\t\t\t\tfnToContainer(b.resolve, 'resolve'),\n\t\t\t\tb.beforeHandle\n\t\t\t)\n\t\t),\n\t\tafterHandle: mergeObjectArray(a.afterHandle, b.afterHandle),\n\t\tmapResponse: mergeObjectArray(a.mapResponse, b.mapResponse) as any,\n\t\tafterResponse: mergeObjectArray(\n\t\t\ta.afterResponse,\n\t\t\tb.afterResponse\n\t\t) as any,\n\t\ttrace: mergeObjectArray(a.trace, b.trace) as any,\n\t\terror: mergeObjectArray(a.error, b.error),\n\t\t// @ts-ignore\n\t\tstandaloneSchema:\n\t\t\t// @ts-ignore\n\t\t\ta.standaloneSchema || b.standaloneSchema\n\t\t\t\t? // @ts-ignore\n\n\t\t\t\t\ta.standaloneSchema && !b.standaloneSchema\n\t\t\t\t\t? // @ts-ignore\n\n\t\t\t\t\t\ta.standaloneSchema\n\t\t\t\t\t: // @ts-ignore\n\n\t\t\t\t\t\tb.standaloneSchema && !a.standaloneSchema\n\t\t\t\t\t\t? b.standaloneSchema\n\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\t\t...(a.standaloneSchema ?? []),\n\t\t\t\t\t\t\t\t...(b.standaloneSchema ?? [])\n\t\t\t\t\t\t\t]\n\t\t\t\t: undefined\n\t}\n\n\tif (hook.resolve) delete hook.resolve\n\n\treturn hook\n}\n\nexport const lifeCycleToArray = (a: LifeCycleStore) => {\n\tif (a.parse && !Array.isArray(a.parse)) a.parse = [a.parse]\n\n\tif (a.transform && !Array.isArray(a.transform)) a.transform = [a.transform]\n\n\tif (a.afterHandle && !Array.isArray(a.afterHandle))\n\t\ta.afterHandle = [a.afterHandle]\n\n\tif (a.mapResponse && !Array.isArray(a.mapResponse))\n\t\ta.mapResponse = [a.mapResponse]\n\n\tif (a.afterResponse && !Array.isArray(a.afterResponse))\n\t\ta.afterResponse = [a.afterResponse]\n\n\tif (a.trace && !Array.isArray(a.trace)) a.trace = [a.trace]\n\tif (a.error && !Array.isArray(a.error)) a.error = [a.error]\n\n\tlet beforeHandle = []\n\n\t// @ts-expect-error\n\tif (a.resolve) {\n\t\tbeforeHandle = fnToContainer(\n\t\t\t// @ts-expect-error\n\t\t\tArray.isArray(a.resolve) ? a.resolve : [a.resolve],\n\t\t\t'resolve'\n\t\t) as any[]\n\n\t\t// @ts-expect-error\n\t\tdelete a.resolve\n\t}\n\n\tif (a.beforeHandle) {\n\t\tif (beforeHandle.length)\n\t\t\tbeforeHandle = beforeHandle.concat(\n\t\t\t\tArray.isArray(a.beforeHandle)\n\t\t\t\t\t? a.beforeHandle\n\t\t\t\t\t: [a.beforeHandle]\n\t\t\t)\n\t\telse\n\t\t\tbeforeHandle = Array.isArray(a.beforeHandle)\n\t\t\t\t? a.beforeHandle\n\t\t\t\t: [a.beforeHandle]\n\t}\n\n\tif (beforeHandle.length) a.beforeHandle = beforeHandle\n\n\treturn a\n}\n\nexport const hasHeaderShorthand = isBun ? 'toJSON' in new Headers() : false\nexport const hasSetImmediate = typeof setImmediate === 'function'\n\n// https://stackoverflow.com/a/52171480\nexport const checksum = (s: string) => {\n\tlet h = 9\n\n\tfor (let i = 0; i < s.length; ) h = Math.imul(h ^ s.charCodeAt(i++), 9 ** 9)\n\n\treturn (h = h ^ (h >>> 9))\n}\n\nexport const injectChecksum = (\n\tchecksum: number | undefined,\n\tx: MaybeArray<HookContainer> | undefined\n) => {\n\tif (!x) return\n\n\tif (!Array.isArray(x)) {\n\t\t// ? clone fn is required to prevent side-effect from changing hookType\n\t\tconst fn = x\n\n\t\tif (checksum && !fn.checksum) fn.checksum = checksum\n\t\tif (fn.scope === 'scoped') fn.scope = 'local'\n\n\t\treturn fn\n\t}\n\n\t// ? clone fns is required to prevent side-effect from changing hookType\n\tconst fns = [...x]\n\n\tfor (const fn of fns) {\n\t\tif (checksum && !fn.checksum) fn.checksum = checksum\n\n\t\tif (fn.scope === 'scoped') fn.scope = 'local'\n\t}\n\n\treturn fns\n}\n\nexport const mergeLifeCycle = (\n\ta: Partial<LifeCycleStore>,\n\tb: Partial<LifeCycleStore | AnyLocalHook>,\n\tchecksum?: number\n): LifeCycleStore => {\n\treturn {\n\t\tstart: mergeObjectArray(\n\t\t\ta.start,\n\t\t\tinjectChecksum(checksum, b?.start)\n\t\t) as HookContainer<GracefulHandler<any>>[],\n\t\trequest: mergeObjectArray(\n\t\t\ta.request,\n\t\t\tinjectChecksum(checksum, b?.request)\n\t\t) as HookContainer<PreHandler<any, any>>[],\n\t\tparse: mergeObjectArray(\n\t\t\ta.parse,\n\t\t\tinjectChecksum(checksum, b?.parse)\n\t\t) as HookContainer<BodyHandler<any, any>>[],\n\t\ttransform: mergeObjectArray(\n\t\t\ta.transform,\n\t\t\tinjectChecksum(checksum, b?.transform)\n\t\t) as HookContainer<TransformHandler<any, any>>[],\n\t\tbeforeHandle: mergeObjectArray(\n\t\t\tmergeObjectArray(\n\t\t\t\t// @ts-ignore\n\t\t\t\tfnToContainer(a.resolve, 'resolve'),\n\t\t\t\ta.beforeHandle\n\t\t\t),\n\t\t\tinjectChecksum(\n\t\t\t\tchecksum,\n\t\t\t\tmergeObjectArray(\n\t\t\t\t\tfnToContainer(b?.resolve, 'resolve'),\n\t\t\t\t\tb?.beforeHandle\n\t\t\t\t)\n\t\t\t)\n\t\t) as HookContainer<OptionalHandler<any, any>>[],\n\t\tafterHandle: mergeObjectArray(\n\t\t\ta.afterHandle,\n\t\t\tinjectChecksum(checksum, b?.afterHandle)\n\t\t) as HookContainer<OptionalHandler<any, any>>[],\n\t\tmapResponse: mergeObjectArray(\n\t\t\ta.mapResponse,\n\t\t\tinjectChecksum(checksum, b?.mapResponse)\n\t\t) as HookContainer<MapResponse<any, any>>[],\n\t\tafterResponse: mergeObjectArray(\n\t\t\ta.afterResponse,\n\t\t\tinjectChecksum(checksum, b?.afterResponse)\n\t\t) as HookContainer<AfterResponseHandler<any, any>>[],\n\t\t// Already merged on Elysia._use, also logic is more complicated, can't directly merge\n\t\ttrace: mergeObjectArray(\n\t\t\ta.trace,\n\t\t\tinjectChecksum(checksum, b?.trace)\n\t\t) as HookContainer<TraceHandler<any, any>>[],\n\t\terror: mergeObjectArray(\n\t\t\ta.error,\n\t\t\tinjectChecksum(checksum, b?.error)\n\t\t) as HookContainer<ErrorHandler<any, any, any>>[],\n\t\tstop: mergeObjectArray(\n\t\t\ta.stop,\n\t\t\tinjectChecksum(checksum, b?.stop)\n\t\t) as HookContainer<GracefulHandler<any>>[]\n\t}\n}\n\nexport const asHookType = (\n\tfn: HookContainer,\n\tinject: LifeCycleType,\n\t{ skipIfHasType = false }: { skipIfHasType?: boolean }\n) => {\n\tif (!fn) return fn\n\n\tif (!Array.isArray(fn)) {\n\t\tif (skipIfHasType) fn.scope ??= inject\n\t\telse fn.scope = inject\n\n\t\treturn fn\n\t}\n\n\tfor (const x of fn)\n\t\tif (skipIfHasType) x.scope ??= inject\n\t\telse x.scope = inject\n\n\treturn fn\n}\n\nconst filterGlobal = (fn: MaybeArray<HookContainer>) => {\n\tif (!fn) return fn\n\n\tif (!Array.isArray(fn))\n\t\tswitch (fn.scope) {\n\t\t\tcase 'global':\n\t\t\tcase 'scoped':\n\t\t\t\treturn { ...fn }\n\n\t\t\tdefault:\n\t\t\t\treturn { fn }\n\t\t}\n\n\tconst array = <any>[]\n\n\tfor (const x of fn)\n\t\tswitch (x.scope) {\n\t\t\tcase 'global':\n\t\t\tcase 'scoped':\n\t\t\t\tarray.push({\n\t\t\t\t\t...x\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t}\n\n\treturn array\n}\n\nexport const filterGlobalHook = (hook: AnyLocalHook): AnyLocalHook => {\n\treturn {\n\t\t// rest is validator\n\t\t...hook,\n\t\ttype: hook?.type,\n\t\tdetail: hook?.detail,\n\t\tparse: filterGlobal(hook?.parse),\n\t\ttransform: filterGlobal(hook?.transform),\n\t\tbeforeHandle: filterGlobal(hook?.beforeHandle),\n\t\tafterHandle: filterGlobal(hook?.afterHandle),\n\t\tmapResponse: filterGlobal(hook?.mapResponse),\n\t\tafterResponse: filterGlobal(hook?.afterResponse),\n\t\terror: filterGlobal(hook?.error),\n\t\ttrace: filterGlobal(hook?.trace)\n\t}\n}\n\nexport const StatusMap = {\n\tContinue: 100,\n\t'Switching Protocols': 101,\n\tProcessing: 102,\n\t'Early Hints': 103,\n\tOK: 200,\n\tCreated: 201,\n\tAccepted: 202,\n\t'Non-Authoritative Information': 203,\n\t'No Content': 204,\n\t'Reset Content': 205,\n\t'Partial Content': 206,\n\t'Multi-Status': 207,\n\t'Already Reported': 208,\n\t'Multiple Choices': 300,\n\t'Moved Permanently': 301,\n\tFound: 302,\n\t'See Other': 303,\n\t'Not Modified': 304,\n\t'Temporary Redirect': 307,\n\t'Permanent Redirect': 308,\n\t'Bad Request': 400,\n\tUnauthorized: 401,\n\t'Payment Required': 402,\n\tForbidden: 403,\n\t'Not Found': 404,\n\t'Method Not Allowed': 405,\n\t'Not Acceptable': 406,\n\t'Proxy Authentication Required': 407,\n\t'Request Timeout': 408,\n\tConflict: 409,\n\tGone: 410,\n\t'Length Required': 411,\n\t'Precondition Failed': 412,\n\t'Payload Too Large': 413,\n\t'URI Too Long': 414,\n\t'Unsupported Media Type': 415,\n\t'Range Not Satisfiable': 416,\n\t'Expectation Failed': 417,\n\t\"I'm a teapot\": 418,\n\t'Enhance Your Calm': 420,\n\t'Misdirected Request': 421,\n\t'Unprocessable Content': 422,\n\tLocked: 423,\n\t'Failed Dependency': 424,\n\t'Too Early': 425,\n\t'Upgrade Required': 426,\n\t'Precondition Required': 428,\n\t'Too Many Requests': 429,\n\t'Request Header Fields Too Large': 431,\n\t'Unavailable For Legal Reasons': 451,\n\t'Internal Server Error': 500,\n\t'Not Implemented': 501,\n\t'Bad Gateway': 502,\n\t'Service Unavailable': 503,\n\t'Gateway Timeout': 504,\n\t'HTTP Version Not Supported': 505,\n\t'Variant Also Negotiates': 506,\n\t'Insufficient Storage': 507,\n\t'Loop Detected': 508,\n\t'Not Extended': 510,\n\t'Network Authentication Required': 511\n} as const\n\nexport const InvertedStatusMap = Object.fromEntries(\n\tObject.entries(StatusMap).map(([k, v]) => [v, k])\n) as {\n\t[K in keyof StatusMap as StatusMap[K]]: K\n}\n\nexport type StatusMap = typeof StatusMap\nexport type InvertedStatusMap = typeof InvertedStatusMap\n\nfunction removeTrailingEquals(digest: string): string {\n\tlet trimmedDigest = digest\n\n\twhile (trimmedDigest.endsWith('='))\n\t\ttrimmedDigest = trimmedDigest.slice(0, -1)\n\n\treturn trimmedDigest\n}\n\nconst encoder = new TextEncoder()\n\nexport const signCookie = async (val: string, secret: string | null) => {\n\tif (typeof val === 'object') val = JSON.stringify(val)\n\telse if (typeof val !== 'string') val = val + ''\n\n\tif (secret === null || secret === undefined)\n\t\tthrow new TypeError('Secret key must be provided')\n\n\tconst secretKey = await crypto.subtle.importKey(\n\t\t'raw',\n\t\tencoder.encode(secret),\n\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\tfalse,\n\t\t['sign']\n\t)\n\n\tconst hmacBuffer = await crypto.subtle.sign(\n\t\t'HMAC',\n\t\tsecretKey,\n\t\tencoder.encode(val)\n\t)\n\n\t// console.log({\n\t// \tval,\n\t// \tsecret,\n\t// \thash: removeTrailingEquals(Buffer.from(hmacBuffer).toString('base64'))\n\t// })\n\n\treturn (\n\t\tval +\n\t\t'.' +\n\t\tremoveTrailingEquals(Buffer.from(hmacBuffer).toString('base64'))\n\t)\n}\n\nconst constantTimeEqual =\n\ttypeof crypto?.timingSafeEqual === 'function'\n\t\t? (a: string, b: string) => {\n\t\t\t\t// Compare as UTF-8 bytes; timingSafeEqual requires equal length\n\t\t\t\tconst ab = Buffer.from(a, 'utf8')\n\t\t\t\tconst bb = Buffer.from(b, 'utf8')\n\n\t\t\t\tif (ab.length !== bb.length) return false\n\t\t\t\treturn crypto.timingSafeEqual(ab, bb)\n\t\t\t}\n\t\t: (a: string, b: string) => a === b\n\nexport const unsignCookie = async (input: string, secret: string | null) => {\n\tif (typeof input !== 'string')\n\t\tthrow new TypeError('Signed cookie string must be provided.')\n\n\tconst dot = input.lastIndexOf('.')\n\tif (dot === -1) {\n\t\tif (secret === null) return input\n\n\t\treturn false\n\t}\n\n\tconst tentativeValue = input.slice(0, dot)\n\tconst expectedInput = await signCookie(tentativeValue, secret)\n\n\treturn constantTimeEqual(expectedInput, input) ? tentativeValue : false\n}\n\nexport const insertStandaloneValidator = <const Name extends keyof InputSchema>(\n\thook: { standaloneValidator: InputSchema[] },\n\tname: Name,\n\tvalue: InputSchema[Name]\n) => {\n\tif (\n\t\t!hook.standaloneValidator?.length ||\n\t\t!Array.isArray(hook.standaloneValidator)\n\t) {\n\t\thook.standaloneValidator = [\n\t\t\t{\n\t\t\t\t[name]: value\n\t\t\t}\n\t\t]\n\t\treturn\n\t}\n\n\tconst last = hook.standaloneValidator[hook.standaloneValidator.length - 1]\n\n\tif (name in last)\n\t\thook.standaloneValidator.push({\n\t\t\t[name]: value\n\t\t})\n\telse last[name] = value\n}\n\nconst parseNumericString = (message: string | number): number | null => {\n\tif (typeof message === 'number') return message\n\n\tif (message.length < 16) {\n\t\tif (message.trim().length === 0) return null\n\n\t\tconst length = Number(message)\n\t\tif (Number.isNaN(length)) return null\n\n\t\treturn length\n\t}\n\n\t// if 16 digit but less then 9,007,199,254,740,991 then can be parsed\n\tif (message.length === 16) {\n\t\tif (message.trim().length === 0) return null\n\n\t\tconst number = Number(message)\n\t\tif (Number.isNaN(number) || number.toString() !== message) return null\n\n\t\treturn number\n\t}\n\n\treturn null\n}\n\nexport const isNumericString = (message: string | number): boolean =>\n\tparseNumericString(message) !== null\n\nexport class PromiseGroup implements PromiseLike<void> {\n\troot: Promise<any> | null = null\n\tpromises: Promise<any>[] = []\n\n\tconstructor(\n\t\tpublic onError: (error: any) => void = console.error,\n\t\tpublic onFinally: () => void = () => {}\n\t) {}\n\n\t/**\n\t * The number of promises still being awaited.\n\t */\n\tget size() {\n\t\treturn this.promises.length\n\t}\n\n\t/**\n\t * Add a promise to the group.\n\t * @returns The promise that was added.\n\t */\n\tadd<T>(promise: Promise<T>) {\n\t\tthis.promises.push(promise)\n\t\tthis.root ||= this.drain()\n\n\t\tif (this.promises.length === 1) this.then(this.onFinally)\n\t\treturn promise\n\t}\n\n\tprivate async drain() {\n\t\twhile (this.promises.length > 0) {\n\t\t\ttry {\n\t\t\t\tawait this.promises[0]\n\t\t\t} catch (error) {\n\t\t\t\tthis.onError(error)\n\t\t\t}\n\t\t\tthis.promises.shift()\n\t\t}\n\t\tthis.root = null\n\t}\n\n\t// Allow the group to be awaited.\n\tthen<TResult1 = void, TResult2 = never>(\n\t\tonfulfilled?:\n\t\t\t| ((value: void) => TResult1 | PromiseLike<TResult1>)\n\t\t\t| undefined\n\t\t\t| null,\n\t\tonrejected?:\n\t\t\t| ((reason: any) => TResult2 | PromiseLike<TResult2>)\n\t\t\t| undefined\n\t\t\t| null\n\t): PromiseLike<TResult1 | TResult2> {\n\t\treturn (this.root ?? Promise.resolve()).then(onfulfilled, onrejected)\n\t}\n}\n\nexport const fnToContainer = (\n\tfn: MaybeArray<Function | HookContainer>,\n\t/** Only add subType to non contained fn */\n\tsubType?: HookContainer['subType']\n): MaybeArray<HookContainer> => {\n\tif (!fn) return fn\n\n\tif (!Array.isArray(fn)) {\n\t\t// parse can be a label since 1.2.0\n\t\tif (typeof fn === 'function' || typeof fn === 'string')\n\t\t\treturn subType ? { fn, subType } : { fn }\n\t\telse if ('fn' in fn) return fn\n\t}\n\n\tconst fns = <HookContainer[]>[]\n\tfor (const x of fn) {\n\t\t// parse can be a label since 1.2.0\n\t\tif (typeof x === 'function' || typeof x === 'string')\n\t\t\tfns.push(subType ? { fn: x, subType } : { fn: x })\n\t\telse if ('fn' in x) fns.push(x)\n\t}\n\n\treturn fns\n}\n\nexport const localHookToLifeCycleStore = (a: AnyLocalHook): LifeCycleStore => {\n\tif (a.start) a.start = fnToContainer(a.start)\n\tif (a.request) a.request = fnToContainer(a.request)\n\tif (a.parse) a.parse = fnToContainer(a.parse)\n\tif (a.transform) a.transform = fnToContainer(a.transform)\n\tif (a.beforeHandle) a.beforeHandle = fnToContainer(a.beforeHandle)\n\tif (a.afterHandle) a.afterHandle = fnToContainer(a.afterHandle)\n\tif (a.mapResponse) a.mapResponse = fnToContainer(a.mapResponse)\n\tif (a.afterResponse) a.afterResponse = fnToContainer(a.afterResponse)\n\tif (a.trace) a.trace = fnToContainer(a.trace)\n\tif (a.error) a.error = fnToContainer(a.error)\n\tif (a.stop) a.stop = fnToContainer(a.stop)\n\n\treturn a\n}\n\nexport const lifeCycleToFn = (a: Partial<LifeCycleStore>): AnyLocalHook => {\n\tconst lifecycle = Object.create(null)\n\n\tif (a.start?.map) lifecycle.start = a.start.map((x) => x.fn)\n\tif (a.request?.map) lifecycle.request = a.request.map((x) => x.fn)\n\tif (a.parse?.map) lifecycle.parse = a.parse.map((x) => x.fn)\n\tif (a.transform?.map) lifecycle.transform = a.transform.map((x) => x.fn)\n\tif (a.beforeHandle?.map)\n\t\tlifecycle.beforeHandle = a.beforeHandle.map((x) => x.fn)\n\tif (a.afterHandle?.map)\n\t\tlifecycle.afterHandle = a.afterHandle.map((x) => x.fn)\n\tif (a.mapResponse?.map)\n\t\tlifecycle.mapResponse = a.mapResponse.map((x) => x.fn)\n\tif (a.afterResponse?.map)\n\t\tlifecycle.afterResponse = a.afterResponse.map((x) => x.fn)\n\tif (a.error?.map) lifecycle.error = a.error.map((x) => x.fn)\n\tif (a.stop?.map) lifecycle.stop = a.stop.map((x) => x.fn)\n\n\tif (a.trace?.map) lifecycle.trace = a.trace.map((x) => x.fn)\n\telse lifecycle.trace = []\n\n\treturn lifecycle\n}\n\nexport const cloneInference = (inference: Sucrose.Inference) =>\n\t({\n\t\tbody: inference.body,\n\t\tcookie: inference.cookie,\n\t\theaders: inference.headers,\n\t\tquery: inference.query,\n\t\tset: inference.set,\n\t\tserver: inference.server,\n\t\tpath: inference.path,\n\t\troute: inference.route,\n\t\turl: inference.url\n\t}) satisfies Sucrose.Inference\n\n/**\n *\n * @param url URL to redirect to\n * @param HTTP status code to send,\n */\nexport const redirect = (\n\turl: string,\n\tstatus: 301 | 302 | 303 | 307 | 308 = 302\n) => Response.redirect(url, status)\n\nexport type redirect = typeof redirect\n\nexport const ELYSIA_FORM_DATA = Symbol('ElysiaFormData')\nexport type ELYSIA_FORM_DATA = typeof ELYSIA_FORM_DATA\n\ntype IsTuple<T> = T extends readonly any[]\n\t? number extends T['length']\n\t\t? false\n\t\t: true\n\t: false\n\nexport type ElysiaFormData<T extends Record<keyof any, unknown>> = FormData & {\n\t[ELYSIA_FORM_DATA]: Replace<T, Blob | ElysiaFile, File> extends infer A\n\t\t? {\n\t\t\t\t[key in keyof A]: IsTuple<A[key]> extends true\n\t\t\t\t\t? // @ts-ignore Trust me bro\n\t\t\t\t\t\tA[key][number] extends Blob | ElysiaFile\n\t\t\t\t\t\t? File[]\n\t\t\t\t\t\t: A[key]\n\t\t\t\t\t: A[key]\n\t\t\t}\n\t\t: T\n}\n\nexport const ELYSIA_REQUEST_ID = Symbol('ElysiaRequestId')\nexport type ELYSIA_REQUEST_ID = typeof ELYSIA_REQUEST_ID\n\nexport const form = <const T extends Record<keyof any, unknown>>(\n\titems: T\n): ElysiaFormData<T> => {\n\tconst formData = new FormData()\n\t// @ts-ignore\n\tformData[ELYSIA_FORM_DATA] = {}\n\n\tif (items)\n\t\tfor (const [key, value] of Object.entries(items)) {\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tformData[ELYSIA_FORM_DATA][key] = []\n\n\t\t\t\tfor (const v of value) {\n\t\t\t\t\tif (value instanceof File)\n\t\t\t\t\t\tformData.append(key, value, value.name)\n\t\t\t\t\telse if (value instanceof ElysiaFile)\n\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\tformData.append(key, value.value, value.value?.name)\n\t\t\t\t\telse formData.append(key, value as any)\n\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tformData[ELYSIA_FORM_DATA][key].push(value)\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (value instanceof File) formData.append(key, value, value.name)\n\t\t\telse if (value instanceof ElysiaFile)\n\t\t\t\t// @ts-expect-error\n\t\t\t\tformData.append(key, value.value, value.value?.name)\n\t\t\telse formData.append(key, value as any)\n\t\t\t// @ts-expect-error\n\t\t\tformData[ELYSIA_FORM_DATA][key] = value\n\t\t}\n\n\treturn formData as any\n}\n\n/**\n * Generates a random ID for schema identification.\n *\n * Uses crypto.randomUUID() when available, with a Math.random() fallback\n * for environments where crypto.randomUUID() throws an error\n * (e.g., Cloudflare Workers global scope).\n *\n * @see https://developers.cloudflare.com/workers/runtime-apis/handlers/\n */\nexport const randomId =\n\ttypeof crypto === 'undefined' || isCloudflareWorker()\n\t\t? (): string => {\n\t\t\t\tlet result = ''\n\n\t\t\t\tconst characters =\n\t\t\t\t\t'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n\n\t\t\t\tfor (let i = 0; i < 16; i++)\n\t\t\t\t\tresult += characters.charAt(\n\t\t\t\t\t\t// 62 is characters.length\n\t\t\t\t\t\tMath.floor(Math.random() * 62)\n\t\t\t\t\t)\n\n\t\t\t\treturn result\n\t\t\t}\n\t\t: (): string => {\n\t\t\t\tconst uuid = crypto.randomUUID()\n\t\t\t\treturn uuid.slice(0, 8) + uuid.slice(24, 32)\n\t\t\t}\n\n// ! Deduplicate current instance\nexport const deduplicateChecksum = <T extends Function>(\n\tarray: HookContainer<T>[]\n): HookContainer<T>[] => {\n\tif (!array.length) return []\n\n\tconst hashes: number[] = []\n\n\tfor (let i = 0; i < array.length; i++) {\n\t\tconst item = array[i]\n\n\t\tif (item.checksum) {\n\t\t\tif (hashes.includes(item.checksum)) {\n\t\t\t\tarray.splice(i, 1)\n\t\t\t\ti--\n\t\t\t}\n\n\t\t\thashes.push(item.checksum)\n\t\t}\n\t}\n\n\treturn array\n}\n\n/**\n * Since it's a plugin, which means that ephemeral is demoted to volatile.\n * Which  means there's no volatile and all previous ephemeral become volatile\n * We can just promote back without worry\n */\nexport const promoteEvent = (\n\tevents?: (HookContainer | Function)[],\n\tas: 'scoped' | 'global' = 'scoped'\n): void => {\n\tif (!events) return\n\n\tif (as === 'scoped') {\n\t\tfor (const event of events)\n\t\t\tif ('scope' in event && event.scope === 'local')\n\t\t\t\tevent.scope = 'scoped'\n\n\t\treturn\n\t}\n\n\tfor (const event of events) if ('scope' in event) event.scope = 'global'\n}\n\n// type PropertyKeys<T> = {\n// \t[K in keyof T]: T[K] extends (...args: any[]) => any ? never : K\n// }[keyof T]\n\n// type PropertiesOnly<T> = Pick<T, PropertyKeys<T>>\n\n// export const classToObject = <T>(\n// \tinstance: T,\n// \tprocessed: WeakMap<object, object> = new WeakMap()\n// ): T extends object ? PropertiesOnly<T> : T => {\n// \tif (typeof instance !== 'object' || instance === null)\n// \t\treturn instance as any\n\n// \tif (Array.isArray(instance))\n// \t\treturn instance.map((x) => classToObject(x, processed)) as any\n\n// \tif (processed.has(instance)) return processed.get(instance) as any\n\n// \tconst result: Partial<T> = {}\n\n// \tfor (const key of Object.keys(instance) as Array<keyof T>) {\n// \t\tconst value = instance[key]\n// \t\tif (typeof value === 'object' && value !== null)\n// \t\t\tresult[key] = classToObject(value, processed) as T[keyof T]\n// \t\telse result[key] = value\n// \t}\n\n// \tconst prototype = Object.getPrototypeOf(instance)\n// \tif (!prototype) return result as any\n\n// \tconst properties = Object.getOwnPropertyNames(prototype)\n\n// \tfor (const property of properties) {\n// \t\tconst descriptor = Object.getOwnPropertyDescriptor(\n// \t\t\tObject.getPrototypeOf(instance),\n// \t\t\tproperty\n// \t\t)\n\n// \t\tif (descriptor && typeof descriptor.get === 'function') {\n// \t\t\t// ? Very important to prevent prototype pollution\n// \t\t\tif (property === '__proto__') continue\n\n// \t\t\t;(result as any)[property as keyof typeof instance] = classToObject(\n// \t\t\t\tinstance[property as keyof typeof instance]\n// \t\t\t)\n// \t\t}\n// \t}\n\n// \treturn result as any\n// }\n\nexport const getLoosePath = (path: string) => {\n\tif (path.charCodeAt(path.length - 1) === 47)\n\t\treturn path.slice(0, path.length - 1)\n\n\treturn path + '/'\n}\n\nexport const isNotEmpty = (obj?: Object) => {\n\tif (!obj) return false\n\n\tfor (const _ in obj) return true\n\n\treturn false\n}\n\nexport const encodePath = (path: string, { dynamic = false } = {}) => {\n\tlet encoded = encodeURIComponent(path).replace(/%2F/g, '/')\n\n\tif (dynamic) encoded = encoded.replace(/%3A/g, ':').replace(/%3F/g, '?')\n\n\treturn encoded\n}\n\nexport const supportPerMethodInlineHandler = (() => {\n\tif (typeof Bun === 'undefined') return true\n\n\tif (Bun.semver?.satisfies?.(Bun.version, '>=1.2.14')) return true\n\n\treturn false\n})()\n\ntype FormatSSEPayload<T = unknown> = T extends string\n\t? { readonly data: T }\n\t: Prettify<SSEPayload<T>>\n\n/**\n * Return a Server Sent Events (SSE) payload\n *\n * @example\n * ```ts\n * import { sse } from 'elysia'\n *\n * new Elysia()\n *   .get('/sse', function*() {\n *     yield sse('Hello, world!')\n *     yield sse({\n *       event: 'message',\n *       data: { message: 'This is a JSON object' }\n *     })\n *   }\n */\nexport const sse = <\n\tconst T extends\n\t\t| string\n\t\t| SSEPayload\n\t\t| Generator\n\t\t| AsyncGenerator\n\t\t| ReadableStream\n>(\n\t_payload: T\n): T extends string\n\t? { readonly data: T }\n\t: T extends SSEPayload\n\t\t? T\n\t\t: T extends ReadableStream<infer A>\n\t\t\t? ReadableStream<FormatSSEPayload<A>>\n\t\t\t: T extends Generator<infer A, infer B, infer C>\n\t\t\t\t? Generator<FormatSSEPayload<A>, B, C>\n\t\t\t\t: T extends AsyncGenerator<infer A, infer B, infer C>\n\t\t\t\t\t? AsyncGenerator<FormatSSEPayload<A>, B, C>\n\t\t\t\t\t: T => {\n\tif (_payload instanceof ReadableStream) {\n\t\t// @ts-expect-error\n\t\t_payload.sse = true\n\t\treturn _payload as any\n\t}\n\n\tconst payload: SSEPayload =\n\t\ttypeof _payload === 'string'\n\t\t\t? { data: _payload }\n\t\t\t: (_payload as SSEPayload)\n\n\t// if (payload.id === undefined) payload.id = randomId()\n\n\t// @ts-ignore\n\tpayload.sse = true\n\n\t// @ts-ignore\n\tpayload.toSSE = () => {\n\t\tlet payloadString = ''\n\n\t\tif (payload.id !== undefined && payload.id !== null)\n\t\t\tpayloadString += `id: ${payload.id}\\n`\n\t\tif (payload.event) payloadString += `event: ${payload.event}\\n`\n\t\tif (payload.retry !== undefined)\n\t\t\tpayloadString += `retry: ${payload.retry}\\n`\n\n\t\tif (payload.data === null) payloadString += 'data: null\\n'\n\t\telse if (typeof payload.data === 'string')\n\t\t\tpayloadString += `data: ${payload.data}\\n`\n\t\telse if (typeof payload.data === 'object')\n\t\t\tpayloadString += `data: ${JSON.stringify(payload.data)}\\n`\n\n\t\tif (payloadString) payloadString += '\\n'\n\n\t\treturn payloadString\n\t}\n\n\treturn payload as any\n}\n\nexport async function getResponseLength(response: Response) {\n\tif (response.bodyUsed || !response.body) return 0\n\n\tlet length = 0\n\tconst reader = response.body.getReader()\n\n\twhile (true) {\n\t\tconst { done, value } = await reader.read()\n\t\tif (done) break\n\t\tlength += value.byteLength\n\t}\n\n\treturn length\n}\n\nexport const emptySchema = {\n\theaders: true,\n\tcookie: true,\n\tquery: true,\n\tparams: true,\n\tbody: true,\n\tresponse: true\n} as const satisfies RouteSchema\n\nexport function deepClone<T>(source: T, weak = new WeakMap<object, any>()): T {\n\tif (\n\t\tsource === null ||\n\t\ttypeof source !== 'object' ||\n\t\ttypeof source === 'function'\n\t)\n\t\treturn source\n\n\t// Circular‑reference guard\n\tif (weak.has(source as object)) return weak.get(source as object)\n\n\tif (Array.isArray(source)) {\n\t\tconst copy: any[] = new Array(source.length)\n\t\tweak.set(source, copy)\n\n\t\tfor (let i = 0; i < source.length; i++)\n\t\t\tcopy[i] = deepClone(source[i], weak)\n\n\t\treturn copy as any\n\t}\n\n\tif (typeof source === 'object') {\n\t\tconst keys = Object.keys(source).concat(\n\t\t\tObject.getOwnPropertySymbols(source) as any[]\n\t\t)\n\n\t\tconst cloned: Partial<T> = {}\n\n\t\tweak.set(source as object, cloned)\n\t\tfor (const key of keys)\n\t\t\tcloned[key as keyof T] = deepClone((source as any)[key], weak)\n\n\t\treturn cloned as T\n\t}\n\n\treturn source\n}\n"
  },
  {
    "path": "src/ws/bun.ts",
    "content": "// ? Copy from bun.d.ts for universal runtime support\n\ntype TypedArray =\n\t| Uint8Array\n\t| Uint8ClampedArray\n\t| Uint16Array\n\t| Uint32Array\n\t| Int8Array\n\t| Int16Array\n\t| Int32Array\n\t| BigUint64Array\n\t| BigInt64Array\n\t| Float32Array\n\t| Float64Array\n\nexport type BufferSource = TypedArray | DataView | ArrayBufferLike\n\n/**\n * A status that represents the outcome of a sent message.\n *\n * - if **0**, the message was **dropped**.\n * - if **-1**, there is **backpressure** of messages.\n * - if **>0**, it represents the **number of bytes sent**.\n *\n * @example\n * ```js\n * const status = ws.send(\"Hello!\");\n * if (status === 0) {\n *   console.log(\"Message was dropped\");\n * } else if (status === -1) {\n *   console.log(\"Backpressure was applied\");\n * } else {\n *   console.log(`Success! Sent ${status} bytes`);\n * }\n * ```\n */\nexport type ServerWebSocketSendStatus = number\n\n/**\n * A state that represents if a WebSocket is connected.\n *\n * - `WebSocket.CONNECTING` is `0`, the connection is pending.\n * - `WebSocket.OPEN` is `1`, the connection is established and `send()` is possible.\n * - `WebSocket.CLOSING` is `2`, the connection is closing.\n * - `WebSocket.CLOSED` is `3`, the connection is closed or couldn't be opened.\n *\n * @link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState\n */\nexport type WebSocketReadyState = 0 | 1 | 2 | 3\n\n/**\n * A fast WebSocket designed for servers.\n *\n * Features:\n * - **Message compression** - Messages can be compressed\n * - **Backpressure** - If the client is not ready to receive data, the server will tell you.\n * - **Dropped messages** - If the client cannot receive data, the server will tell you.\n * - **Topics** - Messages can be {@link ServerWebSocket.publish}ed to a specific topic and the client can {@link ServerWebSocket.subscribe} to topics\n *\n * This is slightly different than the browser {@link WebSocket} which Bun supports for clients.\n *\n * Powered by [uWebSockets](https://github.com/uNetworking/uWebSockets).\n *\n * @example\n * import { serve } from \"bun\";\n *\n * serve({\n *   websocket: {\n *     open(ws) {\n *       console.log(\"Connected\", ws.remoteAddress);\n *     },\n *     message(ws, data) {\n *       console.log(\"Received\", data);\n *       ws.send(data);\n *     },\n *     close(ws, code, reason) {\n *       console.log(\"Disconnected\", code, reason);\n *     },\n *   }\n * });\n */\nexport interface ServerWebSocket<T = undefined> {\n\t/**\n\t * Sends a message to the client.\n\t *\n\t * @param data The data to send.\n\t * @param compress Should the data be compressed? If the client does not support compression, this is ignored.\n\t * @example\n\t * ws.send(\"Hello!\");\n\t * ws.send(\"Compress this.\", true);\n\t * ws.send(new Uint8Array([1, 2, 3, 4]));\n\t */\n\tsend(\n\t\tdata: string | BufferSource,\n\t\tcompress?: boolean\n\t): ServerWebSocketSendStatus\n\n\t/**\n\t * Sends a text message to the client.\n\t *\n\t * @param data The data to send.\n\t * @param compress Should the data be compressed? If the client does not support compression, this is ignored.\n\t * @example\n\t * ws.send(\"Hello!\");\n\t * ws.send(\"Compress this.\", true);\n\t */\n\tsendText(data: string, compress?: boolean): ServerWebSocketSendStatus\n\n\t/**\n\t * Sends a binary message to the client.\n\t *\n\t * @param data The data to send.\n\t * @param compress Should the data be compressed? If the client does not support compression, this is ignored.\n\t * @example\n\t * ws.send(new TextEncoder().encode(\"Hello!\"));\n\t * ws.send(new Uint8Array([1, 2, 3, 4]), true);\n\t */\n\tsendBinary(\n\t\tdata: BufferSource,\n\t\tcompress?: boolean\n\t): ServerWebSocketSendStatus\n\n\t/**\n\t * Closes the connection.\n\t *\n\t * Here is a list of close codes:\n\t * - `1000` means \"normal closure\" **(default)**\n\t * - `1009` means a message was too big and was rejected\n\t * - `1011` means the server encountered an error\n\t * - `1012` means the server is restarting\n\t * - `1013` means the server is too busy or the client is rate-limited\n\t * - `4000` through `4999` are reserved for applications (you can use it!)\n\t *\n\t * To close the connection abruptly, use `terminate()`.\n\t *\n\t * @param code The close code to send\n\t * @param reason The close reason to send\n\t */\n\tclose(code?: number, reason?: string): void\n\n\t/**\n\t * Abruptly close the connection.\n\t *\n\t * To gracefully close the connection, use `close()`.\n\t */\n\tterminate(): void\n\n\t/**\n\t * Sends a ping.\n\t *\n\t * @param data The data to send\n\t */\n\tping(data?: string | BufferSource): ServerWebSocketSendStatus\n\n\t/**\n\t * Sends a pong.\n\t *\n\t * @param data The data to send\n\t */\n\tpong(data?: string | BufferSource): ServerWebSocketSendStatus\n\n\t/**\n\t * Sends a message to subscribers of the topic.\n\t *\n\t * @param topic The topic name.\n\t * @param data The data to send.\n\t * @param compress Should the data be compressed? If the client does not support compression, this is ignored.\n\t * @example\n\t * ws.publish(\"chat\", \"Hello!\");\n\t * ws.publish(\"chat\", \"Compress this.\", true);\n\t * ws.publish(\"chat\", new Uint8Array([1, 2, 3, 4]));\n\t */\n\tpublish(\n\t\ttopic: string,\n\t\tdata: string | BufferSource,\n\t\tcompress?: boolean\n\t): ServerWebSocketSendStatus\n\n\t/**\n\t * Sends a text message to subscribers of the topic.\n\t *\n\t * @param topic The topic name.\n\t * @param data The data to send.\n\t * @param compress Should the data be compressed? If the client does not support compression, this is ignored.\n\t * @example\n\t * ws.publish(\"chat\", \"Hello!\");\n\t * ws.publish(\"chat\", \"Compress this.\", true);\n\t */\n\tpublishText(\n\t\ttopic: string,\n\t\tdata: string,\n\t\tcompress?: boolean\n\t): ServerWebSocketSendStatus\n\n\t/**\n\t * Sends a binary message to subscribers of the topic.\n\t *\n\t * @param topic The topic name.\n\t * @param data The data to send.\n\t * @param compress Should the data be compressed? If the client does not support compression, this is ignored.\n\t * @example\n\t * ws.publish(\"chat\", new TextEncoder().encode(\"Hello!\"));\n\t * ws.publish(\"chat\", new Uint8Array([1, 2, 3, 4]), true);\n\t */\n\tpublishBinary(\n\t\ttopic: string,\n\t\tdata: BufferSource,\n\t\tcompress?: boolean\n\t): ServerWebSocketSendStatus\n\n\t/**\n\t * Subscribes a client to the topic.\n\t *\n\t * @param topic The topic name.\n\t * @example\n\t * ws.subscribe(\"chat\");\n\t */\n\tsubscribe(topic: string): void\n\n\t/**\n\t * Unsubscribes a client to the topic.\n\t *\n\t * @param topic The topic name.\n\t * @example\n\t * ws.unsubscribe(\"chat\");\n\t */\n\tunsubscribe(topic: string): void\n\n\t/**\n\t * Is the client subscribed to a topic?\n\t *\n\t * @param topic The topic name.\n\t * @example\n\t * ws.subscribe(\"chat\");\n\t * console.log(ws.isSubscribed(\"chat\")); // true\n\t */\n\tisSubscribed(topic: string): boolean\n\n\t/**\n\t * Returns an array of all topics the client is currently subscribed to.\n\t *\n\t * @example\n\t * ws.subscribe(\"chat\");\n\t * ws.subscribe(\"notifications\");\n\t * console.log(ws.subscriptions); // [\"chat\", \"notifications\"]\n\t */\n\treadonly subscriptions: string[]\n\n\t/**\n\t * Batches `send()` and `publish()` operations, which makes it faster to send data.\n\t *\n\t * The `message`, `open`, and `drain` callbacks are automatically corked, so\n\t * you only need to call this if you are sending messages outside of those\n\t * callbacks or in async functions.\n\t *\n\t * @param callback The callback to run.\n\t * @example\n\t * ws.cork((ctx) => {\n\t *   ctx.send(\"These messages\");\n\t *   ctx.sendText(\"are sent\");\n\t *   ctx.sendBinary(new TextEncoder().encode(\"together!\"));\n\t * });\n\t */\n\tcork<T = unknown>(callback: (ws: ServerWebSocket<T>) => T): T\n\n\t/**\n\t * The IP address of the client.\n\t *\n\t * @example\n\t * console.log(socket.remoteAddress); // \"127.0.0.1\"\n\t */\n\treadonly remoteAddress: string\n\n\t/**\n\t * The ready state of the client.\n\t *\n\t * - if `0`, the client is connecting.\n\t * - if `1`, the client is connected.\n\t * - if `2`, the client is closing.\n\t * - if `3`, the client is closed.\n\t *\n\t * @example\n\t * console.log(socket.readyState); // 1\n\t */\n\treadonly readyState: WebSocketReadyState\n\n\t/**\n\t * Sets how binary data is returned in events.\n\t *\n\t * - if `nodebuffer`, binary data is returned as `Buffer` objects. **(default)**\n\t * - if `arraybuffer`, binary data is returned as `ArrayBuffer` objects.\n\t * - if `uint8array`, binary data is returned as `Uint8Array` objects.\n\t *\n\t * @example\n\t * let ws: WebSocket;\n\t * ws.binaryType = \"uint8array\";\n\t * ws.addEventListener(\"message\", ({ data }) => {\n\t *   console.log(data instanceof Uint8Array); // true\n\t * });\n\t */\n\tbinaryType?: 'nodebuffer' | 'arraybuffer' | 'uint8array'\n\n\t/**\n\t * Custom data that you can assign to a client, can be read and written at any time.\n\t *\n\t * @example\n\t * import { serve } from \"bun\";\n\t *\n\t * serve({\n\t *   fetch(request, server) {\n\t *     const data = {\n\t *       accessToken: request.headers.get(\"Authorization\"),\n\t *     };\n\t *     if (server.upgrade(request, { data })) {\n\t *       return;\n\t *     }\n\t *     return new Response();\n\t *   },\n\t *   websocket: {\n\t *     open(ws) {\n\t *       console.log(ws.data.accessToken);\n\t *     }\n\t *   }\n\t * });\n\t */\n\tdata: T\n}\n\n/**\n * Compression options for WebSocket messages.\n */\nexport type WebSocketCompressor =\n\t| 'disable'\n\t| 'shared'\n\t| 'dedicated'\n\t| '3KB'\n\t| '4KB'\n\t| '8KB'\n\t| '16KB'\n\t| '32KB'\n\t| '64KB'\n\t| '128KB'\n\t| '256KB'\n\n/**\n * Create a server-side {@link ServerWebSocket} handler for use with {@link Bun.serve}\n *\n * @example\n * ```ts\n * import { websocket, serve } from \"bun\";\n *\n * serve<{name: string}>({\n *   port: 3000,\n *   websocket: {\n *     open: (ws) => {\n *       console.log(\"Client connected\");\n *    },\n *     message: (ws, message) => {\n *       console.log(`${ws.data.name}: ${message}`);\n *    },\n *     close: (ws) => {\n *       console.log(\"Client disconnected\");\n *    },\n *  },\n *\n *   fetch(req, server) {\n *     const url = new URL(req.url);\n *     if (url.pathname === \"/chat\") {\n *       const upgraded = server.upgrade(req, {\n *         data: {\n *           name: new URL(req.url).searchParams.get(\"name\"),\n *        },\n *      });\n *       if (!upgraded) {\n *         return new Response(\"Upgrade failed\", { status: 400 });\n *      }\n *      return;\n *    }\n *     return new Response(\"Hello World\");\n *  },\n * });\n * ```\n */\nexport interface WebSocketHandler<in out T = undefined> {\n\t/**\n\t * Called when the server receives an incoming message.\n\t *\n\t * If the message is not a `string`, its type is based on the value of `binaryType`.\n\t * - if `nodebuffer`, then the message is a `Buffer`.\n\t * - if `arraybuffer`, then the message is an `ArrayBuffer`.\n\t * - if `uint8array`, then the message is a `Uint8Array`.\n\t *\n\t * @param ws The websocket that sent the message\n\t * @param message The message received\n\t */\n\tmessage(\n\t\tws: ServerWebSocket<T>,\n\t\tmessage: string | Buffer\n\t): void | Promise<void>\n\n\t/**\n\t * Called when a connection is opened.\n\t *\n\t * @param ws The websocket that was opened\n\t */\n\topen?(ws: ServerWebSocket<T>): void | Promise<void>\n\n\t/**\n\t * Called when a connection was previously under backpressure,\n\t * meaning it had too many queued messages, but is now ready to receive more data.\n\t *\n\t * @param ws The websocket that is ready for more data\n\t */\n\tdrain?(ws: ServerWebSocket<T>): void | Promise<void>\n\n\t/**\n\t * Called when a connection is closed.\n\t *\n\t * @param ws The websocket that was closed\n\t * @param code The close code\n\t * @param message The close message\n\t */\n\tclose?(\n\t\tws: ServerWebSocket<T>,\n\t\tcode: number,\n\t\treason: string\n\t): void | Promise<void>\n\n\t/**\n\t * Called when a ping is sent.\n\t *\n\t * @param ws The websocket that received the ping\n\t * @param data The data sent with the ping\n\t */\n\tping?(ws: ServerWebSocket<T>, data: Buffer): void | Promise<void>\n\n\t/**\n\t * Called when a pong is received.\n\t *\n\t * @param ws The websocket that received the ping\n\t * @param data The data sent with the ping\n\t */\n\tpong?(ws: ServerWebSocket<T>, data: Buffer): void | Promise<void>\n\n\t/**\n\t * Sets the maximum size of messages in bytes.\n\t *\n\t * Default is 16 MB, or `1024 * 1024 * 16` in bytes.\n\t */\n\tmaxPayloadLength?: number\n\n\t/**\n\t * Sets the maximum number of bytes that can be buffered on a single connection.\n\t *\n\t * Default is 16 MB, or `1024 * 1024 * 16` in bytes.\n\t */\n\tbackpressureLimit?: number\n\n\t/**\n\t * Sets if the connection should be closed if `backpressureLimit` is reached.\n\t *\n\t * Default is `false`.\n\t */\n\tcloseOnBackpressureLimit?: boolean\n\n\t/**\n\t * Sets the the number of seconds to wait before timing out a connection\n\t * due to no messages or pings.\n\t *\n\t * Default is 2 minutes, or `120` in seconds.\n\t */\n\tidleTimeout?: number\n\n\t/**\n\t * Should `ws.publish()` also send a message to `ws` (itself), if it is subscribed?\n\t *\n\t * Default is `false`.\n\t */\n\tpublishToSelf?: boolean\n\n\t/**\n\t * Should the server automatically send and respond to pings to clients?\n\t *\n\t * Default is `true`.\n\t */\n\tsendPings?: boolean\n\n\t/**\n\t * Sets the compression level for messages, for clients that supports it. By default, compression is disabled.\n\t *\n\t * Default is `false`.\n\t */\n\tperMessageDeflate?:\n\t\t| boolean\n\t\t| {\n\t\t\t\t/**\n\t\t\t\t * Sets the compression level.\n\t\t\t\t */\n\t\t\t\tcompress?: WebSocketCompressor | boolean\n\t\t\t\t/**\n\t\t\t\t * Sets the decompression level.\n\t\t\t\t */\n\t\t\t\tdecompress?: WebSocketCompressor | boolean\n\t\t  }\n}\n"
  },
  {
    "path": "src/ws/index.ts",
    "content": "import { isNumericString } from '../utils'\n\nimport type {\n\tServerWebSocket,\n\tServerWebSocketSendStatus,\n\tBufferSource,\n\tWebSocketHandler\n} from './bun'\n\nimport type { TSchema } from '@sinclair/typebox'\nimport type { TypeCheck } from '../type-system'\nimport type { ElysiaTypeCheck } from '../schema'\n\nimport type { FlattenResponse, WSParseHandler } from './types'\nimport type { MaybeArray, Prettify, RouteSchema } from '../types'\nimport { ValidationError } from '../error'\n\nexport const websocket: WebSocketHandler<any> = {\n\topen(ws) {\n\t\tws.data.open?.(ws)\n\t},\n\tmessage(ws, message) {\n\t\tws.data.message?.(ws, message)\n\t},\n\tdrain(ws) {\n\t\tws.data.drain?.(ws)\n\t},\n\tclose(ws, code, reason) {\n\t\tws.data.close?.(ws, code, reason)\n\t},\n\tping(ws) {\n\t\tws.data.ping?.(ws)\n\t},\n\tpong(ws) {\n\t\tws.data.pong?.(ws)\n\t}\n}\n\ntype ElysiaServerWebSocket = Omit<\n\tServerWebSocket<unknown>,\n\t'send' | 'ping' | 'pong' | 'publish'\n>\n\nexport class ElysiaWS<Context = unknown, Route extends RouteSchema = {}>\n\timplements ElysiaServerWebSocket\n{\n\tconstructor(\n\t\tpublic raw: ServerWebSocket<{\n\t\t\tid?: string\n\t\t\tvalidator?: TypeCheck<TSchema>\n\t\t}>,\n\t\tpublic data: Prettify<\n\t\t\tOmit<Context, 'body' | 'error' | 'status' | 'redirect'>\n\t\t>,\n\t\tpublic body: Route['body'] = undefined\n\t) {\n\t\tthis.validator = raw.data?.validator\n\n\t\tthis.sendText = raw.sendText.bind(raw)\n\t\tthis.sendBinary = raw.sendBinary.bind(raw)\n\t\tthis.close = raw.close.bind(raw)\n\t\tthis.terminate = raw.terminate.bind(raw)\n\t\tthis.publishText = raw.publishText.bind(raw)\n\t\tthis.publishBinary = raw.publishBinary.bind(raw)\n\t\tthis.subscribe = raw.subscribe.bind(raw)\n\t\tthis.unsubscribe = raw.unsubscribe.bind(raw)\n\t\tthis.isSubscribed = raw.isSubscribed.bind(raw)\n\t\tthis.cork = raw.cork.bind(raw)\n\t\tthis.remoteAddress = raw.remoteAddress\n\t\tthis.binaryType = raw.binaryType\n\t\tthis.data = raw.data as any\n\t\tthis.subscriptions = raw.subscriptions\n\n\t\tthis.send = this.send.bind(this)\n\t\tthis.ping = this.ping.bind(this)\n\t\tthis.pong = this.pong.bind(this)\n\t\tthis.publish = this.publish.bind(this)\n\t}\n\n\t/**\n\t * Sends a message to the client.\n\t *\n\t * @param data The data to send.\n\t * @param compress Should the data be compressed? If the client does not support compression, this is ignored.\n\t * @example\n\t * ws.send(\"Hello!\");\n\t * ws.send(\"Compress this.\", true);\n\t * ws.send(new Uint8Array([1, 2, 3, 4]));\n\t */\n\tsend(\n\t\tdata: FlattenResponse<Route['response']> | BufferSource,\n\t\tcompress?: boolean\n\t): ServerWebSocketSendStatus {\n\t\tif (Buffer.isBuffer(data))\n\t\t\treturn this.raw.send(data as unknown as BufferSource, compress)\n\n\t\tif (this.validator?.Check(data) === false)\n\t\t\treturn this.raw.send(\n\t\t\t\tnew ValidationError('message', this.validator, data).message\n\t\t\t)\n\n\t\tif (typeof data === 'object') data = JSON.stringify(data) as any\n\n\t\treturn this.raw.send(data as unknown as string, compress)\n\t}\n\n\t/**\n\t * Sends a ping.\n\t *\n\t * @param data The data to send\n\t */\n\tping(\n\t\tdata?: FlattenResponse<Route['response']> | BufferSource\n\t): ServerWebSocketSendStatus {\n\t\tif (Buffer.isBuffer(data))\n\t\t\treturn this.raw.ping(data as unknown as BufferSource)\n\n\t\tif (this.validator?.Check(data) === false)\n\t\t\treturn this.raw.send(\n\t\t\t\tnew ValidationError('message', this.validator, data).message\n\t\t\t)\n\n\t\tif (typeof data === 'object') data = JSON.stringify(data) as any\n\n\t\treturn this.raw.ping(data as string)\n\t}\n\n\t/**\n\t * Sends a pong.\n\t *\n\t * @param data The data to send\n\t */\n\tpong(\n\t\tdata?: FlattenResponse<Route['response']> | BufferSource\n\t): ServerWebSocketSendStatus {\n\t\tif (Buffer.isBuffer(data))\n\t\t\treturn this.raw.pong(data as unknown as BufferSource)\n\n\t\tif (this.validator?.Check(data) === false)\n\t\t\treturn this.raw.send(\n\t\t\t\tnew ValidationError('message', this.validator, data).message\n\t\t\t)\n\n\t\tif (typeof data === 'object') data = JSON.stringify(data) as any\n\n\t\treturn this.raw.pong(data as string)\n\t}\n\n\t/**\n\t * Sends a message to subscribers of the topic.\n\t *\n\t * @param topic The topic name.\n\t * @param data The data to send.\n\t * @param compress Should the data be compressed? If the client does not support compression, this is ignored.\n\t * @example\n\t * ws.publish(\"chat\", \"Hello!\");\n\t * ws.publish(\"chat\", \"Compress this.\", true);\n\t * ws.publish(\"chat\", new Uint8Array([1, 2, 3, 4]));\n\t */\n\tpublish(\n\t\ttopic: string,\n\t\tdata: FlattenResponse<Route['response']> | BufferSource,\n\t\tcompress?: boolean\n\t): ServerWebSocketSendStatus {\n\t\tif (Buffer.isBuffer(data))\n\t\t\treturn this.raw.publish(\n\t\t\t\ttopic,\n\t\t\t\tdata as unknown as BufferSource,\n\t\t\t\tcompress\n\t\t\t)\n\n\t\tif (this.validator?.Check(data) === false)\n\t\t\treturn this.raw.send(\n\t\t\t\tnew ValidationError('message', this.validator, data).message\n\t\t\t)\n\n\t\tif (typeof data === 'object') data = JSON.stringify(data) as any\n\n\t\treturn this.raw.publish(topic, data as unknown as string, compress)\n\t}\n\n\tsendText: ServerWebSocket['sendText']\n\tsendBinary: ServerWebSocket['sendBinary']\n\tclose: ServerWebSocket['close']\n\tterminate: ServerWebSocket['terminate']\n\tpublishText: ServerWebSocket['publishText']\n\tpublishBinary: ServerWebSocket['publishBinary']\n\tsubscribe: ServerWebSocket['subscribe']\n\tunsubscribe: ServerWebSocket['unsubscribe']\n\tisSubscribed: ServerWebSocket['isSubscribed']\n\tcork: ServerWebSocket['cork']\n\tremoteAddress: ServerWebSocket['remoteAddress']\n\tbinaryType: ServerWebSocket['binaryType']\n\tsubscriptions: ServerWebSocket['subscriptions']\n\n\tget readyState() {\n\t\treturn this.raw.readyState\n\t}\n\n\tvalidator?: TypeCheck<TSchema>;\n\t['~types']?: {\n\t\tvalidator: Prettify<Route>\n\t}\n\n\tget id(): string {\n\t\t// @ts-ignore\n\t\treturn this.data.id\n\t}\n}\n\nexport const createWSMessageParser = (\n\tparse: MaybeArray<WSParseHandler<any>>\n) => {\n\tconst parsers = typeof parse === 'function' ? [parse] : parse\n\n\treturn async function parseMessage(ws: ServerWebSocket<any>, message: any) {\n\t\tif (typeof message === 'string') {\n\t\t\tconst start = message?.charCodeAt(0)\n\n\t\t\tif (start === 34 || start === 47 || start === 91 || start === 123)\n\t\t\t\ttry {\n\t\t\t\t\tmessage = JSON.parse(message)\n\t\t\t\t} catch {\n\t\t\t\t\t// Not empty\n\t\t\t\t}\n\t\t\telse if (isNumericString(message)) message = +message\n\t\t\telse if (message === 'true') message = true\n\t\t\telse if (message === 'false') message = false\n\t\t\telse if (message === 'null') message = null\n\t\t}\n\n\t\tif (parsers)\n\t\t\tfor (let i = 0; i < parsers.length; i++) {\n\t\t\t\tlet temp = parsers[i](ws as any, message)\n\t\t\t\tif (temp instanceof Promise) temp = await temp\n\n\t\t\t\tif (temp !== undefined) return temp\n\t\t\t}\n\n\t\treturn message\n\t}\n}\n\nexport const createHandleWSResponse = (\n\tresponseValidator: TypeCheck<any> | ElysiaTypeCheck<any> | undefined\n) => {\n\tconst handleWSResponse = (\n\t\tws: ServerWebSocket<any>,\n\t\tdata: unknown\n\t): unknown => {\n\t\tif (data instanceof Promise)\n\t\t\treturn data.then((data) => handleWSResponse(ws, data))\n\n\t\tif (Buffer.isBuffer(data)) return ws.send(data.toString())\n\n\t\tif (data === undefined) return\n\n\t\tconst validateResponse = responseValidator\n\t\t\t? // @ts-ignore\n\t\t\t\tresponseValidator.provider === 'standard'\n\t\t\t\t? (data: unknown) =>\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tresponseValidator.schema['~standard'].validate(data)\n\t\t\t\t\t\t\t.issues\n\t\t\t\t: (data: unknown) => responseValidator.Check(data) === false\n\t\t\t: undefined\n\n\t\tconst send = (datum: unknown) => {\n\t\t\tif (validateResponse && validateResponse(datum) === false)\n\t\t\t\treturn ws.send(\n\t\t\t\t\tnew ValidationError('message', responseValidator!, datum)\n\t\t\t\t\t\t.message\n\t\t\t\t)\n\n\t\t\tif (typeof datum === 'object') return ws.send(JSON.stringify(datum))\n\n\t\t\tws.send(datum as any)\n\t\t}\n\n\t\tif (typeof (data as Generator)?.next !== 'function')\n\t\t\treturn void send(data)\n\n\t\tconst init = (data as Generator | AsyncGenerator).next()\n\n\t\tif (init instanceof Promise)\n\t\t\treturn (async () => {\n\t\t\t\tconst first = await init\n\n\t\t\t\tif (validateResponse && validateResponse(first))\n\t\t\t\t\treturn ws.send(\n\t\t\t\t\t\tnew ValidationError(\n\t\t\t\t\t\t\t'message',\n\t\t\t\t\t\t\tresponseValidator!,\n\t\t\t\t\t\t\tfirst\n\t\t\t\t\t\t).message\n\t\t\t\t\t)\n\n\t\t\t\tsend(first.value as any)\n\n\t\t\t\tif (!first.done)\n\t\t\t\t\tfor await (const datum of data as Generator) send(datum)\n\t\t\t})()\n\n\t\tsend(init.value)\n\n\t\tif (!init.done) for (const datum of data as Generator) send(datum)\n\t}\n\n\treturn handleWSResponse\n}\n\nexport type { WSLocalHook } from './types'\n"
  },
  {
    "path": "src/ws/types.ts",
    "content": "import { TSchema } from '@sinclair/typebox'\n\nimport type { ElysiaWS } from './index'\nimport { WebSocketHandler } from './bun'\n\nimport type { Context } from '../context'\nimport {\n\tAfterResponseHandler,\n\tBaseMacro,\n\tDocumentDecoration,\n\tErrorHandler,\n\tInputSchema,\n\tMacroToContext,\n\tMapResponse,\n\tMaybeArray,\n\tMaybePromise,\n\tMetadataBase,\n\tOptionalHandler,\n\tPrettify,\n\tRouteSchema,\n\tSingletonBase,\n\tTransformHandler,\n\tUnwrapSchema\n} from '../types'\n\ntype TypedWebSocketMethod =\n\t| 'open'\n\t| 'message'\n\t| 'drain'\n\t| 'close'\n\t| 'ping'\n\t| 'pong'\n\nexport type FlattenResponse<Response extends RouteSchema['response']> =\n\t{} extends Response ? unknown : Response[keyof Response]\n\ninterface TypedWebSocketHandler<\n\tin out Context,\n\tin out Route extends RouteSchema = {}\n> extends Omit<WebSocketHandler<Context>, TypedWebSocketMethod> {\n\topen?(\n\t\tws: Prettify<ElysiaWS<Context, Omit<Route, 'body'> & { body: never }>>\n\t): MaybePromise<FlattenResponse<Route['response']> | void>\n\tmessage?(\n\t\tws: Prettify<ElysiaWS<Context, Route>>,\n\t\tmessage: Route['body']\n\t): MaybePromise<\n\t\t| FlattenResponse<Route['response']>\n\t\t| void\n\t\t| Generator<\n\t\t\t\tFlattenResponse<Route['response']>,\n\t\t\t\tvoid | FlattenResponse<Route['response']>\n\t\t  >\n\t\t| AsyncGenerator<\n\t\t\t\tFlattenResponse<Route['response']>,\n\t\t\t\tvoid | FlattenResponse<Route['response']>\n\t\t  >\n\t>\n\tdrain?(\n\t\tws: Prettify<ElysiaWS<Context, Omit<Route, 'body'> & { body: never }>>\n\t): MaybePromise<\n\t\t| FlattenResponse<Route['response']>\n\t\t| void\n\t\t| Generator<\n\t\t\t\tFlattenResponse<Route['response']>,\n\t\t\t\tvoid | FlattenResponse<Route['response']>\n\t\t  >\n\t\t| AsyncGenerator<\n\t\t\t\tFlattenResponse<Route['response']>,\n\t\t\t\tvoid | FlattenResponse<Route['response']>\n\t\t  >\n\t>\n\tclose?(\n\t\tws: Prettify<ElysiaWS<Context, Omit<Route, 'body'> & { body: never }>>,\n\t\tcode: number,\n\t\treason: string\n\t): MaybePromise<\n\t\t| FlattenResponse<Route['response']>\n\t\t| void\n\t\t| Generator<\n\t\t\t\tFlattenResponse<Route['response']>,\n\t\t\t\tvoid | FlattenResponse<Route['response']>\n\t\t  >\n\t\t| AsyncGenerator<\n\t\t\t\tFlattenResponse<Route['response']>,\n\t\t\t\tvoid | FlattenResponse<Route['response']>\n\t\t  >\n\t>\n\tping?(\n\t\tws: Prettify<ElysiaWS<Context>>,\n\t\tmessage: Route['body']\n\t): MaybePromise<\n\t\t| FlattenResponse<Route['response']>\n\t\t| void\n\t\t| Generator<\n\t\t\t\tFlattenResponse<Route['response']>,\n\t\t\t\tvoid | FlattenResponse<Route['response']>\n\t\t  >\n\t\t| AsyncGenerator<\n\t\t\t\tFlattenResponse<Route['response']>,\n\t\t\t\tvoid | FlattenResponse<Route['response']>\n\t\t  >\n\t>\n\tpong?(\n\t\tws: Prettify<ElysiaWS<Context>>,\n\t\tmessage: Route['body']\n\t): MaybePromise<\n\t\t| FlattenResponse<Route['response']>\n\t\t| void\n\t\t| Generator<\n\t\t\t\tFlattenResponse<Route['response']>,\n\t\t\t\tvoid | FlattenResponse<Route['response']>\n\t\t  >\n\t\t| AsyncGenerator<\n\t\t\t\tFlattenResponse<Route['response']>,\n\t\t\t\tvoid | FlattenResponse<Route['response']>\n\t\t  >\n\t>\n}\n\nexport type WSParseHandler<Route extends RouteSchema, Context = {}> = (\n\tws: Prettify<ElysiaWS<Context, Omit<Route, 'body'> & { body: unknown }>>,\n\tmessage: unknown\n) => MaybePromise<Route['body'] | void | undefined>\n\nexport type AnyWSLocalHook = WSLocalHook<any, any, any>\n\nexport type WSLocalHook<\n\tInput extends BaseMacro,\n\tSchema extends RouteSchema,\n\tSingleton extends SingletonBase\n> = Prettify<Input> & {\n\tdetail?: DocumentDecoration\n\t/**\n\t * Headers to register to websocket before `upgrade`\n\t */\n\tupgrade?: Record<string, unknown> | ((context: Context) => unknown)\n\tparse?: MaybeArray<WSParseHandler<Schema>>\n\n\t/**\n\t * Transform context's value\n\t */\n\ttransform?: MaybeArray<TransformHandler<Schema, Singleton>>\n\t/**\n\t * Execute before main handler\n\t */\n\tbeforeHandle?: MaybeArray<OptionalHandler<Schema, Singleton>>\n\t/**\n\t * Execute after main handler\n\t */\n\tafterHandle?: MaybeArray<OptionalHandler<Schema, Singleton>>\n\t/**\n\t * Execute after main handler\n\t */\n\tmapResponse?: MaybeArray<MapResponse<Schema, Singleton>>\n\t/**\n\t * Execute after response is sent\n\t */\n\tafterResponse?: MaybeArray<AfterResponseHandler<Schema, Singleton>>\n\t/**\n\t * Catch error\n\t */\n\terror?: MaybeArray<ErrorHandler<{}, Schema, Singleton>>\n\ttags?: DocumentDecoration['tags']\n} & TypedWebSocketHandler<\n\t\tOmit<Context<Schema, Singleton>, 'body'> & {\n\t\t\tbody: never\n\t\t},\n\t\tSchema\n\t>\n"
  },
  {
    "path": "test/adapter/bun/index.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { Elysia, t } from '../../../src'\n\ndescribe('Bun adapter', () => {\n\tit('handle query guard', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tquery: t.Object({ a: t.String() })\n\t\t\t})\n\t\t\t.get('/works-with', ({ query }) => 'Works' + query.a)\n\t\t\t.get('/works-without', () => 'Works without')\n\t\t\t.listen(0)\n\n\t\tconst query = await fetch(\n\t\t\t`http://localhost:${app.server!.port}/works-with?a=with`\n\t\t).then((x) => x.text())\n\n\t\texpect(query).toEqual('Workswith')\n\n\t\tconst query2 = await fetch(\n\t\t\t`http://localhost:${app.server!.port}/works-without?a=1`\n\t\t).then((x) => x.text())\n\n\t\texpect(query2).toEqual('Works without')\n\t})\n\n\tit('handle standalone query guard', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tquery: t.Object({ a: t.String() }),\n\t\t\t\tschema: 'standalone'\n\t\t\t})\n\t\t\t.get('/works-with', ({ query }) => 'Works' + query.a)\n\t\t\t.get('/works-without', () => 'Works without')\n\t\t\t.listen(0)\n\n\t\tconst query = await fetch(\n\t\t\t`http://localhost:${app.server!.port}/works-with?a=with`\n\t\t).then((x) => x.text())\n\n\t\texpect(query).toEqual('Workswith')\n\n\t\tconst query2 = await fetch(\n\t\t\t`http://localhost:${app.server!.port}/works-without?a=1`\n\t\t).then((x) => x.text())\n\n\t\texpect(query2).toEqual('Works without')\n\t})\n\n\tit('handle static response with onRequest and onError', async () => {\n\t\tlet caughtError: Error\n\t\tlet onErrorCalled = false\n\t\tlet onRequestCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ error }) => {\n\t\t\t\tcaughtError = error as Error\n\n\t\t\t\treturn 'handled'\n\t\t\t})\n\t\t\t.onRequest(({ set }) => {\n\t\t\t\tset.headers['x-header'] = 'test'\n\t\t\t\tset.status = 400\n\n\t\t\t\tthrow new Error('A')\n\t\t\t})\n\t\t\t.get('/', 'yay')\n\t\t\t.listen(0)\n\n\t\tconst response = await fetch(`http://localhost:${app.server!.port}`)\n\n\t\tconst text = await response.text()\n\n\t\texpect(text).toBe('handled')\n\t\texpect(response.status).toBe(400)\n\t\texpect(response.headers.get('x-header')).toBe('test')\n\t\texpect(caughtError!.message).toBe('A')\n\t})\n\n\tit('handle non-ASCII path', async () => {\n\t\tconst app = new Elysia().get('/สวัสดี', 'สบายดีไหม').listen(0)\n\n\t\tconst response = await fetch(\n\t\t\t`http://localhost:${app.server!.port}/สวัสดี`\n\t\t)\n\t\tconst text = await response.text()\n\t\texpect(text).toBe('สบายดีไหม')\n\t})\n})\n"
  },
  {
    "path": "test/adapter/web-standard/cookie-to-header.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { serializeCookie } from '../../../src/cookies'\n\ndescribe('Web Standard - Cookie to Header', () => {\n\tit('return undefined on empty object', () => {\n\t\tconst cookies = {}\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('correctly serialize a single value cookie', () => {\n\t\tconst cookies = {\n\t\t\tcookie1: {\n\t\t\t\tvalue: 'value1'\n\t\t\t}\n\t\t}\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toEqual('cookie1=value1')\n\t})\n\n\tit('correctly serialize a multi-value cookie', () => {\n\t\tconst cookies = {\n\t\t\tcookie1: {\n\t\t\t\tvalue: ['value1', 'value2']\n\t\t\t}\n\t\t}\n\n\t\t// @ts-ignore\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toEqual('cookie1=%5B%22value1%22%2C%22value2%22%5D')\n\t})\n\n\tit('return undefined when the input is undefined', () => {\n\t\tconst cookies = undefined\n\t\t// @ts-ignore\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when the input is null', () => {\n\t\tconst cookies = null\n\t\t// @ts-ignore\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when the input is not an object', () => {\n\t\tconst cookies = 'invalid'\n\t\t// @ts-ignore\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when the input is an empty object', () => {\n\t\tconst cookies = {}\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when the input is an empty object', () => {\n\t\tconst cookies = {}\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when the input is an object with null values', () => {\n\t\tconst cookies = {\n\t\t\tcookie1: null,\n\t\t\tcookie2: null\n\t\t}\n\n\t\t// @ts-ignore\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when the input is an empty object', () => {\n\t\tconst cookies = {}\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when the input is an object with non-string or non-array values', () => {\n\t\tconst cookies = {\n\t\t\tkey1: 123,\n\t\t\tkey2: true,\n\t\t\tkey3: { prop: 'value' },\n\t\t\tkey4: [1, 2, 3]\n\t\t}\n\t\t// @ts-ignore\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when the input is an empty object', () => {\n\t\tconst cookies = {}\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when the input is an empty object', () => {\n\t\tconst cookies = {}\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when the input is an empty object', () => {\n\t\tconst cookies = {}\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when the input is an object with non-string keys', () => {\n\t\tconst cookies = { 1: 'value1', 2: 'value2' }\n\t\t// @ts-ignore\n\t\tconst result = serializeCookie(cookies)\n\t\texpect(result).toBeUndefined()\n\t})\n})\n"
  },
  {
    "path": "test/adapter/web-standard/map-compact-response.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\n\nimport { mapCompactResponse } from '../../../src/adapter/web-standard/handler'\nimport { form } from '../../../src/utils'\nimport { Passthrough } from './utils'\n\nclass Student {\n\tconstructor(public name: string) {}\n\n\ttoString() {\n\t\treturn JSON.stringify({\n\t\t\tname: this.name\n\t\t})\n\t}\n}\n\nclass CustomResponse extends Response {}\n\ndescribe('Web Standard - Map Compact Response', () => {\n\tit('map string', async () => {\n\t\tconst response = mapCompactResponse('Shiroko')\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toBe('Shiroko')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map number', async () => {\n\t\tconst response = mapCompactResponse(1)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toBe('1')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map boolean', async () => {\n\t\tconst response = mapCompactResponse(true)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toBe('true')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map object', async () => {\n\t\tconst body = {\n\t\t\tname: 'Shiroko'\n\t\t}\n\n\t\tconst response = mapCompactResponse(body)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.json()).toEqual(body)\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map function', async () => {\n\t\tconst response = mapCompactResponse(() => 1)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toBe('1')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map undefined', async () => {\n\t\tconst response = mapCompactResponse(undefined)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map null', async () => {\n\t\tconst response = mapCompactResponse(null)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map Blob', async () => {\n\t\tconst file = Bun.file('./test/images/aris-yuzu.jpg')\n\n\t\tconst response = mapCompactResponse(file)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.arrayBuffer()).toEqual(await file.arrayBuffer())\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map File', async () => {\n\t\tconst file = new File(['Hello'], 'hello.txt', { type: 'text/plain' })\n\n\t\tconst response = mapCompactResponse(file)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Hello')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map Promise', async () => {\n\t\tconst body = {\n\t\t\tname: 'Shiroko'\n\t\t}\n\n\t\tconst response = await mapCompactResponse(\n\t\t\tnew Promise((resolve) => resolve(body))\n\t\t)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.json()).toEqual(body)\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map Error', async () => {\n\t\tconst response = mapCompactResponse(new Error('Hello'))\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.json()).toEqual({\n\t\t\tname: 'Error',\n\t\t\tmessage: 'Hello'\n\t\t})\n\t\texpect(response.status).toBe(500)\n\t})\n\n\tit('map Response', async () => {\n\t\tconst response = mapCompactResponse(new Response('Shiroko'))\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Shiroko')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map custom Response', async () => {\n\t\tconst response = mapCompactResponse(new CustomResponse('Shiroko'))\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Shiroko')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map custom class', async () => {\n\t\tconst response = mapCompactResponse(new Student('Himari'))\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.json()).toEqual({\n\t\t\tname: 'Himari'\n\t\t})\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map Response and merge Headers', async () => {\n\t\tconst response = await mapCompactResponse(\n\t\t\tnew Response('Shiroko', {\n\t\t\t\theaders: {\n\t\t\t\t\tName: 'Himari'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\t// @ts-ignore\n\t\tconst headers = response.headers.toJSON()\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Shiroko')\n\t\t// @ts-ignore\n\t\texpect(response.headers.toJSON()).toEqual({\n\t\t\t...headers,\n\t\t\tname: 'Himari'\n\t\t})\n\t})\n\n\tit('map toResponse', async () => {\n\t\tconst response = mapCompactResponse(new Passthrough())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('hi')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map video content-range', async () => {\n\t\tconst kyuukararin = Bun.file('test/kyuukurarin.mp4')\n\n\t\tconst response = mapCompactResponse(kyuukararin)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(response.headers.get('accept-ranges')).toEqual('bytes')\n\t\texpect(response.headers.get('content-range')).toEqual(\n\t\t\t`bytes 0-${kyuukararin.size - 1}/${kyuukararin.size}`\n\t\t)\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map formdata', async () => {\n\t\tconst response = mapCompactResponse(\n\t\t\tform({\n\t\t\t\ta: Bun.file('test/kyuukurarin.mp4')\n\t\t\t})\n\t\t)!\n\n\t\texpect(response.headers.get('content-type')).toStartWith(\n\t\t\t'multipart/form-data'\n\t\t)\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.formData()).toBeInstanceOf(FormData)\n\t})\n\n\tit('map custom thenable', async () => {\n\t\t// Custom thenable object (e.g., like some ORMs return such as Drizzle)\n\t\t// Using a class to avoid being caught by the 'Object' case\n\t\tclass CustomThenable {\n\t\t\tthen(onFulfilled: (value: any) => any) {\n\t\t\t\tconst data = { name: 'Shiroko', id: 42 }\n\t\t\t\treturn Promise.resolve(data).then(onFulfilled)\n\t\t\t}\n\t\t}\n\n\t\tconst customThenable = new CustomThenable()\n\t\tconst responsePromise = mapCompactResponse(customThenable)\n\t\texpect(responsePromise).toBeInstanceOf(Promise)\n\t\t\n\t\tconst response = await responsePromise\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\tconst body = await response.text()\n\t\tconst parsed = JSON.parse(body)\n\t\texpect(parsed).toEqual({ name: 'Shiroko', id: 42 })\n\t\texpect(response.status).toBe(200)\n\t})\n})\n"
  },
  {
    "path": "test/adapter/web-standard/map-early-response.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\n\nimport { mapEarlyResponse } from '../../../src/adapter/web-standard/handler'\nimport { form, redirect } from '../../../src/utils'\nimport { Passthrough } from './utils'\n\nconst defaultContext = {\n\theaders: {},\n\tstatus: 200,\n\tcookie: {}\n}\n\nconst createContext = () => ({\n\theaders: {\n\t\t'x-powered-by': 'Elysia',\n\t\t'coffee-scheme': 'Coffee'\n\t},\n\tstatus: 418,\n\tcookie: {}\n})\n\nclass Student {\n\tconstructor(public name: string) {}\n\n\ttoString() {\n\t\treturn JSON.stringify({\n\t\t\tname: this.name\n\t\t})\n\t}\n}\n\nclass CustomResponse extends Response {}\n\ndescribe('Web Standard - Map Early Response', () => {\n\tit('map string', async () => {\n\t\tconst response = mapEarlyResponse('Shiroko', defaultContext)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toBe('Shiroko')\n\t\texpect(response?.status).toBe(200)\n\t})\n\n\tit('map number', async () => {\n\t\tconst response = mapEarlyResponse(1, defaultContext)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toBe('1')\n\t\texpect(response?.status).toBe(200)\n\t})\n\n\tit('map boolean', async () => {\n\t\tconst response = mapEarlyResponse(true, defaultContext)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toBe('true')\n\t\texpect(response?.status).toBe(200)\n\t})\n\n\tit('map object', async () => {\n\t\tconst body = {\n\t\t\tname: 'Shiroko'\n\t\t}\n\n\t\tconst response = mapEarlyResponse(body, defaultContext)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.json()).toEqual(body)\n\t\texpect(response?.status).toBe(200)\n\t})\n\n\tit('map function', async () => {\n\t\tconst response = mapEarlyResponse(() => 1, defaultContext)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toBe('1')\n\t\texpect(response?.status).toBe(200)\n\t})\n\n\tit('map Blob', async () => {\n\t\tconst file = Bun.file('./test/images/aris-yuzu.jpg')\n\n\t\tconst response = mapEarlyResponse(file, defaultContext)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.arrayBuffer()).toEqual(await file.arrayBuffer())\n\t\texpect(response?.status).toBe(200)\n\t})\n\n\tit('map File', async () => {\n\t\tconst file = new File(['Hello'], 'hello.txt', { type: 'text/plain' })\n\n\t\tconst response = mapEarlyResponse(file, defaultContext)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toEqual('Hello')\n\t\texpect(response?.status).toBe(200)\n\t})\n\n\tit('map Promise', async () => {\n\t\tconst body = {\n\t\t\tname: 'Shiroko'\n\t\t}\n\n\t\tconst response = await mapEarlyResponse(\n\t\t\tnew Promise((resolve) => resolve(body)),\n\t\t\tdefaultContext\n\t\t)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.json()).toEqual(body)\n\t\texpect(response?.status).toBe(200)\n\t})\n\n\tit('map Response', async () => {\n\t\tconst response = mapEarlyResponse(\n\t\t\tnew Response('Shiroko'),\n\t\t\tdefaultContext\n\t\t)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toEqual('Shiroko')\n\t\texpect(response?.status).toBe(200)\n\t})\n\n\tit('map custom Response', async () => {\n\t\tconst response = mapEarlyResponse(\n\t\t\tnew CustomResponse('Shiroko'),\n\t\t\tdefaultContext\n\t\t)!\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Shiroko')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map custom Response with custom headers', async () => {\n\t\tconst response = mapEarlyResponse(new CustomResponse('Shiroko'), {\n\t\t\t...defaultContext,\n\t\t\theaders: {\n\t\t\t\t'content-type': 'text/html; charset=utf8'\n\t\t\t}\n\t\t})!\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Shiroko')\n\t\texpect(response.status).toBe(200)\n\t\texpect(response.headers.get('content-type')).toBe(\n\t\t\t'text/html; charset=utf8'\n\t\t)\n\t})\n\n\tit('map custom class', async () => {\n\t\tconst response = mapEarlyResponse(new Student('Himari'), defaultContext)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.json()).toEqual({\n\t\t\tname: 'Himari'\n\t\t})\n\t\texpect(response?.status).toBe(200)\n\t})\n\n\tit('map primitive with custom context', async () => {\n\t\tconst context = createContext()\n\t\tconst response = mapEarlyResponse('Shiroko', context)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toBe('Shiroko')\n\t\texpect(response?.headers.toJSON()).toEqual(context.headers)\n\t\texpect(response?.status).toBe(418)\n\t})\n\n\tit('map Function with custom context', async () => {\n\t\tconst context = createContext()\n\t\tconst response = await mapEarlyResponse(() => 1, context)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toEqual('1')\n\t\texpect(response?.headers.toJSON()).toEqual({\n\t\t\t...context.headers\n\t\t})\n\t\texpect(response?.status).toBe(418)\n\t})\n\n\tit('map Promise with custom context', async () => {\n\t\tconst context = createContext()\n\n\t\tconst body = {\n\t\t\tname: 'Shiroko'\n\t\t}\n\n\t\tconst response = await mapEarlyResponse(\n\t\t\tnew Promise((resolve) => resolve(body)),\n\t\t\tcontext\n\t\t)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.json()).toEqual(body)\n\t\texpect(response?.headers.toJSON()).toEqual({\n\t\t\t...context.headers,\n\t\t\t'content-type': 'application/json'\n\t\t})\n\t\texpect(response?.status).toBe(418)\n\t})\n\n\tit('map Error with custom context', async () => {\n\t\tconst context = createContext()\n\t\tconst response = mapEarlyResponse(new Error('Hello'), context)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.json()).toEqual({\n\t\t\tname: 'Error',\n\t\t\tmessage: 'Hello'\n\t\t})\n\t\texpect(response?.headers.toJSON()).toEqual(context.headers)\n\t\texpect(response?.status).toBe(418)\n\t})\n\n\tit('map Response with custom context', async () => {\n\t\tconst context = createContext()\n\t\tconst response = await mapEarlyResponse(\n\t\t\tnew Response('Shiroko'),\n\t\t\tcontext\n\t\t)\n\t\tconst headers = response?.headers.toJSON()\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toEqual('Shiroko')\n\t\texpect(response?.headers.toJSON()).toEqual(headers as any)\n\t})\n\n\tit('map Response and merge Headers', async () => {\n\t\tconst context = createContext()\n\n\t\tconst response = await mapEarlyResponse(\n\t\t\tnew Response('Shiroko', {\n\t\t\t\theaders: {\n\t\t\t\t\tName: 'Himari'\n\t\t\t\t}\n\t\t\t}),\n\t\t\tcontext\n\t\t)\n\t\tconst headers = response?.headers.toJSON()\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toEqual('Shiroko')\n\t\t// @ts-ignore\n\t\texpect(response?.headers.toJSON()).toEqual({\n\t\t\t...headers,\n\t\t\tname: 'Himari'\n\t\t})\n\t})\n\n\tit('map named status', async () => {\n\t\tconst response = mapEarlyResponse('Shiroko', {\n\t\t\tstatus: \"I'm a teapot\",\n\t\t\theaders: {},\n\t\t\tcookie: {}\n\t\t})\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toBe('Shiroko')\n\t\texpect(response?.status).toBe(418)\n\t})\n\n\tit('map redirect', async () => {\n\t\tconst response = mapEarlyResponse(redirect('https://cunny.school'), {\n\t\t\tstatus: \"I'm a teapot\",\n\t\t\tcookie: {},\n\t\t\theaders: {\n\t\t\t\tName: 'Sorasaki Hina'\n\t\t\t},\n\t\t\tredirect: 'https://cunny.school'\n\t\t})\n\t\texpect(response).toBeInstanceOf(Response)\n\t\t// expect(await response?.text()).toEqual('Shiroko')\n\t\texpect(response?.headers.toJSON()).toEqual({\n\t\t\tname: 'Sorasaki Hina',\n\t\t\tlocation: 'https://cunny.school'\n\t\t})\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(response?.status).toBe(302)\n\t})\n\n\tit('map undefined', async () => {\n\t\tconst response = mapEarlyResponse(undefined, defaultContext)\n\n\t\texpect(response).toBeUndefined()\n\t})\n\n\tit('map null', async () => {\n\t\tconst response = mapEarlyResponse(null, defaultContext)\n\n\t\texpect(response).toBeUndefined()\n\t})\n\n\tit('set cookie', async () => {\n\t\tconst response = mapEarlyResponse('Hina', {\n\t\t\tstatus: 200,\n\t\t\theaders: {\n\t\t\t\tName: 'Sorasaki Hina'\n\t\t\t},\n\t\t\tcookie: {\n\t\t\t\tname: {\n\t\t\t\t\tvalue: 'hina'\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toEqual('Hina')\n\t\texpect(response?.headers.get('name')).toEqual('Sorasaki Hina')\n\t\texpect(response?.headers.getAll('set-cookie')).toEqual(['name=hina'])\n\t})\n\n\tit('set multiple cookie', async () => {\n\t\tconst response = mapEarlyResponse('Hina', {\n\t\t\tstatus: 200,\n\t\t\theaders: {\n\t\t\t\tName: 'Sorasaki Hina'\n\t\t\t},\n\t\t\tcookie: {\n\t\t\t\tname: {\n\t\t\t\t\tvalue: 'hina'\n\t\t\t\t},\n\t\t\t\taffiliation: {\n\t\t\t\t\tvalue: 'gehenna'\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toEqual('Hina')\n\t\texpect(response?.headers.get('name')).toEqual('Sorasaki Hina')\n\t\texpect(response?.headers.getAll('set-cookie')).toEqual([\n\t\t\t'name=hina',\n\t\t\t'affiliation=gehenna'\n\t\t])\n\t})\n\n\tit('map toResponse', async () => {\n\t\tconst response = mapEarlyResponse(new Passthrough(), defaultContext)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response?.text()).toEqual('hi')\n\t\texpect(response?.status).toBe(200)\n\t})\n\n\tit('map video content-range', async () => {\n\t\tconst kyuukararin = Bun.file('test/kyuukurarin.mp4')\n\n\t\tconst response = mapEarlyResponse(kyuukararin, defaultContext)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(response?.headers.get('accept-ranges')).toEqual('bytes')\n\t\texpect(response?.headers.get('content-range')).toEqual(\n\t\t\t`bytes 0-${kyuukararin.size - 1}/${kyuukararin.size}`\n\t\t)\n\t\texpect(response?.status).toBe(200)\n\t})\n\n\tit('skip content-range on not modified', async () => {\n\t\tconst kyuukararin = Bun.file('test/kyuukurarin.mp4')\n\n\t\tconst response = mapEarlyResponse(kyuukararin, {\n\t\t\t...defaultContext,\n\t\t\tstatus: 304\n\t\t})\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(response?.headers.get('accept-ranges')).toBeNull()\n\t\texpect(response?.headers.get('content-range')).toBeNull()\n\t\texpect(response?.status).toBe(304)\n\t})\n\n\tit('map formdata', async () => {\n\t\tconst response = mapEarlyResponse(\n\t\t\tform({\n\t\t\t\ta: Bun.file('test/kyuukurarin.mp4')\n\t\t\t}),\n\t\t\tdefaultContext\n\t\t)!\n\n\t\texpect(response.headers.get('content-type')).toStartWith(\n\t\t\t'multipart/form-data'\n\t\t)\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.formData()).toBeInstanceOf(FormData)\n\t})\n})\n"
  },
  {
    "path": "test/adapter/web-standard/map-response.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\n\nimport { Elysia, form, redirect } from '../../../src'\n\nimport { mapResponse } from '../../../src/adapter/web-standard/handler'\nimport { Passthrough } from './utils'\nimport { req } from '../../utils'\n\nconst createContext = () => ({\n\tcookie: {},\n\theaders: {},\n\tstatus: 200\n})\n\nclass Student {\n\tconstructor(public name: string) {}\n\n\ttoString() {\n\t\treturn JSON.stringify({\n\t\t\tname: this.name\n\t\t})\n\t}\n}\n\nclass CustomResponse extends Response {}\n\ndescribe('Web Standard - Map Response', () => {\n\tit('map string', async () => {\n\t\tconst response = mapResponse('Shiroko', createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toBe('Shiroko')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map number', async () => {\n\t\tconst response = mapResponse(1, createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toBe('1')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map boolean', async () => {\n\t\tconst response = mapResponse(true, createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toBe('true')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map object', async () => {\n\t\tconst body = {\n\t\t\tname: 'Shiroko'\n\t\t}\n\n\t\tconst response = mapResponse(body, createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.json()).toEqual(body)\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map function', async () => {\n\t\tconst response = mapResponse(() => 1, createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toBe('1')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map undefined', async () => {\n\t\tconst response = mapResponse(undefined, createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map null', async () => {\n\t\tconst response = mapResponse(null, createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map Blob', async () => {\n\t\tconst file = Bun.file('./test/images/aris-yuzu.jpg')\n\n\t\tconst response = mapResponse(file, createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.arrayBuffer()).toEqual(await file.arrayBuffer())\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map File', async () => {\n\t\tconst file = new File(['Hello'], 'hello.txt', { type: 'text/plain' })\n\n\t\tconst response = mapResponse(file, createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Hello')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map Promise', async () => {\n\t\tconst body = {\n\t\t\tname: 'Shiroko'\n\t\t}\n\n\t\tconst response = await mapResponse(\n\t\t\tnew Promise((resolve) => resolve(body)),\n\t\t\tcreateContext()\n\t\t)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.json()).toEqual(body)\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map Error', async () => {\n\t\tconst response = mapResponse(new Error('Hello'), createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.json()).toEqual({\n\t\t\tname: 'Error',\n\t\t\tmessage: 'Hello'\n\t\t})\n\t\texpect(response.status).toBe(500)\n\t})\n\n\tit('map Response', async () => {\n\t\tconst response = mapResponse(new Response('Shiroko'), createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Shiroko')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map custom Response', async () => {\n\t\tconst response = mapResponse(\n\t\t\tnew CustomResponse('Shiroko'),\n\t\t\tcreateContext()\n\t\t)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Shiroko')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map custom Response with custom headers', async () => {\n\t\tconst response = mapResponse(new CustomResponse('Shiroko'), {\n\t\t\t...createContext(),\n\t\t\theaders: {\n\t\t\t\t'content-type': 'text/html; charset=utf8'\n\t\t\t}\n\t\t})\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Shiroko')\n\t\texpect(response.status).toBe(200)\n\t\texpect(response.headers.get('content-type')).toBe(\n\t\t\t'text/html; charset=utf8'\n\t\t)\n\t})\n\n\tit('map custom class', async () => {\n\t\tconst response = mapResponse(new Student('Himari'), createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.json()).toEqual({\n\t\t\tname: 'Himari'\n\t\t})\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map primitive with custom context', async () => {\n\t\tconst context = createContext()\n\t\tconst response = mapResponse('Shiroko', context)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toBe('Shiroko')\n\t\texpect(response.headers.toJSON()).toEqual(context.headers)\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map undefined with context', async () => {\n\t\tconst context = createContext()\n\t\tconst response = mapResponse(undefined, context)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('')\n\t\texpect(response.headers.toJSON()).toEqual(context.headers)\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map null with custom context', async () => {\n\t\tconst context = createContext()\n\t\tconst response = mapResponse(null, context)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('')\n\t\texpect(response.headers.toJSON()).toEqual(context.headers)\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map Function with custom context', async () => {\n\t\tconst context = createContext()\n\t\tconst response = await mapResponse(() => 1, context)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('1')\n\t\texpect(response.headers.toJSON()).toEqual({\n\t\t\t...context.headers\n\t\t})\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map Promise with custom context', async () => {\n\t\tconst context = createContext()\n\n\t\tconst body = {\n\t\t\tname: 'Shiroko'\n\t\t}\n\n\t\tconst response = await mapResponse(\n\t\t\tnew Promise((resolve) => resolve(body)),\n\t\t\tcontext\n\t\t)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.json()).toEqual(body)\n\t\texpect(response.headers.toJSON()).toEqual({\n\t\t\t...context.headers,\n\t\t\t'content-type': 'application/json'\n\t\t})\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map Error with custom context', async () => {\n\t\tconst context = createContext()\n\n\t\tconst response = mapResponse(new Error('Hello'), context)\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.json()).toEqual({\n\t\t\tname: 'Error',\n\t\t\tmessage: 'Hello'\n\t\t})\n\t\texpect(response.headers.toJSON()).toEqual(context.headers)\n\t\texpect(response.status).toBe(500)\n\t})\n\n\tit('map Response with custom context', async () => {\n\t\tconst context = createContext()\n\n\t\tconst response = await mapResponse(new Response('Shiroko'), context)\n\t\tconst headers = response.headers.toJSON()\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Shiroko')\n\t\texpect(response.headers.toJSON()).toEqual(headers)\n\t})\n\n\tit('map Response and merge Headers', async () => {\n\t\tconst context = createContext()\n\n\t\tconst response = await mapResponse(\n\t\t\tnew Response('Shiroko', {\n\t\t\t\theaders: {\n\t\t\t\t\tName: 'Himari'\n\t\t\t\t}\n\t\t\t}),\n\t\t\tcontext\n\t\t)\n\t\tconst headers = response.headers.toJSON()\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Shiroko')\n\t\t// @ts-ignore\n\t\texpect(response.headers.toJSON()).toEqual({\n\t\t\t...headers,\n\t\t\tname: 'Himari'\n\t\t})\n\t})\n\n\tit('map named status', async () => {\n\t\tconst response = mapResponse('Shiroko', {\n\t\t\tstatus: \"I'm a teapot\",\n\t\t\theaders: {},\n\t\t\tcookie: {}\n\t\t})\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toBe('Shiroko')\n\t\texpect(response.status).toBe(418)\n\t})\n\n\tit('map redirect', async () => {\n\t\tconst response = mapResponse(redirect('https://cunny.school', 302), {\n\t\t\tstatus: \"I'm a teapot\",\n\t\t\theaders: {\n\t\t\t\tName: 'Sorasaki Hina'\n\t\t\t},\n\t\t\tredirect: 'https://cunny.school',\n\t\t\tcookie: {}\n\t\t})\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(response.status).toBe(302)\n\t\t// expect(await response.text()).toEqual('Shiroko')\n\t\texpect(response.headers.toJSON()).toEqual({\n\t\t\tname: 'Sorasaki Hina',\n\t\t\tlocation: 'https://cunny.school'\n\t\t})\n\t})\n\n\tit('set cookie', async () => {\n\t\tconst response = mapResponse('Hina', {\n\t\t\tstatus: 200,\n\t\t\theaders: {\n\t\t\t\tName: 'Sorasaki Hina'\n\t\t\t},\n\t\t\tcookie: {\n\t\t\t\tname: {\n\t\t\t\t\tvalue: 'hina'\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Hina')\n\t\texpect(response.headers.get('name')).toEqual('Sorasaki Hina')\n\t\texpect(response.headers.getAll('set-cookie')).toEqual(['name=hina'])\n\t})\n\n\tit('set multiple cookie', async () => {\n\t\tconst response = mapResponse('Hina', {\n\t\t\tstatus: 200,\n\t\t\theaders: {\n\t\t\t\tName: 'Sorasaki Hina'\n\t\t\t},\n\t\t\tcookie: {\n\t\t\t\tname: {\n\t\t\t\t\tvalue: 'hina'\n\t\t\t\t},\n\t\t\t\taffiliation: {\n\t\t\t\t\tvalue: 'gehenna'\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('Hina')\n\t\texpect(response.headers.get('name')).toEqual('Sorasaki Hina')\n\t\texpect(response.headers.getAll('set-cookie')).toEqual([\n\t\t\t'name=hina',\n\t\t\t'affiliation=gehenna'\n\t\t])\n\t})\n\n\tit('map toResponse', async () => {\n\t\tconst response = mapResponse(new Passthrough(), createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(await response.text()).toEqual('hi')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map video content-range', async () => {\n\t\tconst kyuukararin = Bun.file('test/kyuukurarin.mp4')\n\n\t\tconst response = mapResponse(kyuukararin, createContext())\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(response.headers.get('accept-ranges')).toEqual('bytes')\n\t\texpect(response.headers.get('content-range')).toEqual(\n\t\t\t`bytes 0-${kyuukararin.size - 1}/${kyuukararin.size}`\n\t\t)\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('skip content-range on not modified', async () => {\n\t\tconst kyuukararin = Bun.file('test/kyuukurarin.mp4')\n\n\t\tconst response = mapResponse(kyuukararin, {\n\t\t\t...createContext(),\n\t\t\tstatus: 304\n\t\t})\n\n\t\texpect(response).toBeInstanceOf(Response)\n\t\texpect(response.headers.get('accept-ranges')).toBeNull()\n\t\texpect(response.headers.get('content-range')).toBeNull()\n\t\texpect(response.status).toBe(304)\n\t})\n\n\tit('map formdata', async () => {\n\t\tconst response = mapResponse(\n\t\t\tform({\n\t\t\t\ta: Bun.file('test/kyuukurarin.mp4')\n\t\t\t}),\n\t\t\tcreateContext()\n\t\t)\n\n\t\texpect(await response.formData()).toBeInstanceOf(FormData)\n\t\t// ? Auto appended by Bun\n\t\t// expect(response.headers.get('content-type')).toStartWith(\n\t\t// \t'multipart/form-data'\n\t\t// )\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('map beforeHandle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.mapResponse(() => {\n\t\t\t\treturn new Response('b')\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tbeforeHandle() {\n\t\t\t\t\treturn 'a'\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('b')\n\t})\n\n\tit('map afterHandle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.mapResponse(() => {\n\t\t\t\treturn new Response('b')\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tbeforeHandle() {\n\t\t\t\t\treturn 'a'\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('b')\n\t})\n\n\tit('respect set.headers on string response', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onAfterHandle(({ set }) => {\n\t\t\t\tset.headers['content-type'] = 'text/html; charset=utf8'\n\n\t\t\t\treturn '<h1>Hina</h1>'\n\t\t\t})\n\t\t\t.get('/', () => 'a')\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.headers.get('content-type')).toBe(\n\t\t\t'text/html; charset=utf8'\n\t\t)\n\t})\n})\n"
  },
  {
    "path": "test/adapter/web-standard/set-cookie.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { parseSetCookies } from '../../../src/adapter/utils'\n\ndescribe('Web Standard - Parse Set Cookie', () => {\n\tit('should handle empty arrays', () => {\n\t\tconst headers = new Headers([])\n\t\tconst setCookie: string[] = []\n\t\tconst result = parseSetCookies(headers, setCookie)\n\t\texpect(result).toEqual(headers)\n\t})\n\n\tit('should handle a setCookie array with one element containing a single key-value pair', () => {\n\t\tconst headers = new Headers([])\n\t\tconst setCookie = ['key=value']\n\t\tconst result = parseSetCookies(headers, setCookie)\n\t\texpect(result.get('Set-Cookie')).toEqual('key=value')\n\t})\n\n\tit('should handle a setCookie array with multiple elements, each containing a single key-value pair', () => {\n\t\tconst headers = new Headers([])\n\t\tconst setCookie = ['key1=value1', 'key2=value2']\n\t\tconst result = parseSetCookies(headers, setCookie)\n\t\texpect(result.get('Set-Cookie')).toEqual('key1=value1, key2=value2')\n\t})\n\n\tit('should handle a setCookie array with one element containing multiple key-value pairs', () => {\n\t\tconst headers = new Headers([])\n\t\tconst setCookie = ['key1=value1; key2=value2']\n\t\tconst result = parseSetCookies(headers, setCookie)\n\t\texpect(result.get('Set-Cookie')).toEqual('key1=value1; key2=value2')\n\t})\n\n\tit('should handle a setCookie array with multiple elements, each containing multiple key-value pairs', () => {\n\t\tconst headers = new Headers([])\n\t\tconst setCookie = [\n\t\t\t'key1=value1; key2=value2',\n\t\t\t'key3=value3; key4=value4'\n\t\t]\n\t\tconst result = parseSetCookies(headers, setCookie)\n\t\texpect(result.get('Set-Cookie')).toEqual(\n\t\t\t'key1=value1; key2=value2, key3=value3; key4=value4'\n\t\t)\n\t})\n\n\tit('should handle null values', () => {\n\t\tconst headers = null\n\t\tconst setCookie = null\n\t\t// @ts-ignore\n\t\tconst result = parseSetCookies(headers, setCookie)\n\t\texpect(result).toBeNull()\n\t})\n})\n"
  },
  {
    "path": "test/adapter/web-standard/utils.ts",
    "content": "export class Passthrough {\n    toResponse() {\n        return this.custom\n    }\n\n    get custom() {\n        return 'hi'\n    }\n}"
  },
  {
    "path": "test/aot/analysis.test.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { post, req } from '../utils'\nimport { hasType } from '../../src/schema'\n\nconst payload = { hello: 'world' }\n\ndescribe('Static code analysis', () => {\n\tit('parse object destructuring', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body)\n\n\t\tconst res = await app.handle(post('/', payload)).then((x) => x.json())\n\n\t\texpect(res).toEqual(payload)\n\t})\n\n\tit('parse context access', async () => {\n\t\tconst app = new Elysia().post('/', (context) => context.body)\n\n\t\tconst res = await app.handle(post('/', payload)).then((x) => x.json())\n\n\t\texpect(res).toEqual(payload)\n\t})\n\n\tit('parse context access using square bracket', async () => {\n\t\tconst app = new Elysia().post('/', (context) => context['body'])\n\n\t\tconst res = await app.handle(post('/', payload)).then((x) => x.json())\n\n\t\texpect(res).toEqual(payload)\n\t})\n\n\tit('parse assignment', async () => {\n\t\tconst app = new Elysia().post('/', (context) => {\n\t\t\tconst a = context.body\n\n\t\t\treturn a\n\t\t})\n\n\t\tconst res = await app.handle(post('/', payload)).then((x) => x.json())\n\n\t\texpect(res).toEqual(payload)\n\t})\n\n\tit('parse multiple assignment', async () => {\n\t\tconst app = new Elysia().post('/', (context) => {\n\t\t\tconst _ = 1,\n\t\t\t\tb = context.body\n\n\t\t\treturn b\n\t\t})\n\n\t\tconst res = await app.handle(post('/', payload)).then((x) => x.json())\n\n\t\texpect(res).toEqual(payload)\n\t})\n\n\tit('parse multiple assignment with object destructuring', async () => {\n\t\tconst app = new Elysia().post('/', (context) => {\n\t\t\tconst _ = 1,\n\t\t\t\t{ body } = context\n\n\t\t\treturn body\n\t\t})\n\n\t\tconst res = await app.handle(post('/', payload)).then((x) => x.json())\n\n\t\texpect(res).toEqual(payload)\n\t})\n\n\tit('parse lazy object destructuring', async () => {\n\t\tconst app = new Elysia().post('/', (context) => {\n\t\t\tconst { body: a } = context\n\n\t\t\treturn a\n\t\t})\n\n\t\tconst res = await app.handle(post('/', payload)).then((x) => x.json())\n\n\t\texpect(res).toEqual(payload)\n\t})\n\n\tit('parse headers', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers)\n\n\t\tconst res = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\theaders: payload\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(res).toEqual(payload)\n\t})\n\n\tit('parse body type json', async () => {\n\t\tconst body = {\n\t\t\tmessage: 'Rikuhachima Aru'\n\t\t}\n\n\t\tconst app = new Elysia().post('/json', (c) => c.body, {\n\t\t\tparse: 'json'\n\t\t})\n\n\t\tconst res = await app.handle(post('/json', body)).then((x) => x.json())\n\n\t\texpect(res).toEqual(body)\n\t})\n\n\tit('find nested Elysia Schema', () => {\n\t\tconst schema = t.Object({\n\t\t\ta: t.Object({\n\t\t\t\tb: t.Object({\n\t\t\t\t\tc: t.File()\n\t\t\t\t}),\n\t\t\t\td: t.String()\n\t\t\t}),\n\t\t\tid: t.Numeric(),\n\t\t\tb: t.Object({\n\t\t\t\tc: t.File()\n\t\t\t})\n\t\t})\n\n\t\texpect(hasType('File', schema)).toBeTrue()\n\t})\n\n\tit('find Elysia Schema on root', () => {\n\t\tconst schema = t.Numeric()\n\n\t\texpect(hasType('Numeric', schema)).toBeTrue\n\t})\n\n\tit('find return null if Elysia Schema is not found', () => {\n\t\tconst schema = t.Object({\n\t\t\ta: t.Object({\n\t\t\t\tb: t.Object({\n\t\t\t\t\tc: t.Number()\n\t\t\t\t}),\n\t\t\t\td: t.String()\n\t\t\t}),\n\t\t\tid: t.Number(),\n\t\t\tb: t.Object({\n\t\t\t\tc: t.Number()\n\t\t\t})\n\t\t})\n\n\t\texpect(hasType('File', schema)).toBeFalse()\n\t})\n\n\tit('restart server once analyze', async () => {\n\t\tconst plugin = async () => {\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1))\n\n\t\t\treturn (app: Elysia) => app.get('/', () => 'hi')\n\t\t}\n\n\t\tconst app = new Elysia().use(plugin())\n\n\t\tawait new Promise((resolve) => setTimeout(resolve, 25))\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('hi')\n\t})\n\n\tit('parse custom parser with schema', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onParse((request, contentType) => {\n\t\t\t\tif (contentType === 'application/elysia') return 'hi'\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tbody: t.String()\n\t\t\t})\n\n\t\tawait new Promise((resolve) => setTimeout(resolve, 25))\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'content-type': 'application/elysia'\n\t\t\t\t\t},\n\t\t\t\t\tbody: 'need correction'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe('hi')\n\t})\n\n\tit('handle multiple numeric type', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/', () => 'Hello Elysia1')\n\t\t\t.get(\n\t\t\t\t'/products',\n\t\t\t\t({ query }) =>\n\t\t\t\t\t`pageIndex=${query.pageIndex}; pageSize=${query.pageSize}`,\n\t\t\t\t{\n\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\tpageIndex: t.Numeric(),\n\t\t\t\t\t\tpageSize: t.Numeric()\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(req('/products?pageIndex=1&pageSize=2'))\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe(`pageIndex=1; pageSize=2`)\n\t})\n\n\tit('break out of switch map when path is not found', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.options('/', () => 'hi')\n\t\t\t.get('/games', () => 'games')\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\tmethod: 'OPTIONS'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe('hi')\n\t})\n\n\tit('handle accurate trie properties', async () => {\n\t\tconst app = new Elysia().get('/what', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tstee: t.Optional(t.Literal('on')),\n\t\t\t\tmtee: t.Optional(t.Literal('on')),\n\t\t\t\tltee: t.Optional(t.Literal('on')),\n\t\t\t\txltee: t.Optional(t.Literal('on')),\n\t\t\t\txxltee: t.Optional(t.Literal('on')),\n\t\t\t\txxxltee: t.Optional(t.Literal('on'))\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(req('/what?xxltee=on'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\txxltee: 'on'\n\t\t})\n\t})\n})\n"
  },
  {
    "path": "test/aot/generation.test.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { describe, it, expect } from 'bun:test'\nimport { Context, Elysia, t } from '../../src'\nimport { post, req } from '../utils'\n\ndescribe('code generation', () => {\n\tit('fallback query if not presented', async () => {\n\t\tconst app = new Elysia().get('/', () => 'hi', {\n\t\t\tquery: t.Object({\n\t\t\t\tid: t.Optional(t.Number())\n\t\t\t})\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('process isFnUse', async () => {\n\t\tconst body = { hello: 'Wanderschaffen' }\n\n\t\tconst app = new Elysia()\n\t\t\t.post('/1', ({ body }) => body)\n\t\t\t.post('/2', function ({ body }) {\n\t\t\t\treturn body\n\t\t\t})\n\t\t\t.post('/3', (context) => {\n\t\t\t\treturn context.body\n\t\t\t})\n\t\t\t.post('/4', (context) => {\n\t\t\t\tconst c = context\n\t\t\t\tconst { body } = c\n\n\t\t\t\treturn body\n\t\t\t})\n\t\t\t.post('/5', (context) => {\n\t\t\t\tconst _ = context,\n\t\t\t\t\ta = context\n\t\t\t\tconst { body } = a\n\n\t\t\t\treturn body\n\t\t\t})\n\t\t\t.post('/6', () => body, {\n\t\t\t\ttransform({ body }) {\n\t\t\t\t\t// not empty\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/7', () => body, {\n\t\t\t\tbeforeHandle({ body }) {\n\t\t\t\t\t// not empty\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/8', () => body, {\n\t\t\t\tafterHandle({ body }) {\n\t\t\t\t\t// not empty\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/9', ({ ...rest }) => rest.body)\n\n\t\tconst from = (number: number) =>\n\t\t\tapp.handle(post(`/${number}`, body)).then((r) => r.json())\n\n\t\tconst cases = Promise.all(\n\t\t\tArray(9)\n\t\t\t\t.fill(null)\n\t\t\t\t.map((_, i) => from(i + 1))\n\t\t)\n\n\t\tfor (const unit of await cases) expect(unit).toEqual(body)\n\t})\n\n\tit('process isContextPassToUnknown', async () => {\n\t\tconst body = { hello: 'Wanderschaffen' }\n\n\t\tconst handle = (context: Context<any, any>) => context.body\n\n\t\tconst app = new Elysia()\n\t\t\t.post('/1', (context) => handle(context))\n\t\t\t.post('/2', function (context) {\n\t\t\t\treturn handle(context)\n\t\t\t})\n\t\t\t.post('/3', (context) => {\n\t\t\t\tconst c = context\n\n\t\t\t\treturn handle(c)\n\t\t\t})\n\t\t\t.post('/4', (context) => {\n\t\t\t\tconst _ = context,\n\t\t\t\t\ta = context\n\n\t\t\t\treturn handle(a)\n\t\t\t})\n\t\t\t.post('/5', () => '', {\n\t\t\t\tbeforeHandle(context) {\n\t\t\t\t\treturn handle(context)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/6', () => body, {\n\t\t\t\tafterHandle(context) {\n\t\t\t\t\treturn handle(context)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/7', ({ ...rest }) => handle(rest))\n\n\t\tconst from = (number: number) =>\n\t\t\tapp.handle(post(`/${number}`, body)).then((r) => r.json())\n\n\t\tconst cases = Promise.all(\n\t\t\tArray(7)\n\t\t\t\t.fill(null)\n\t\t\t\t.map((_, i) => from(i + 1))\n\t\t)\n\n\t\tfor (const unit of await cases) expect(unit).toEqual(body)\n\t})\n})\n"
  },
  {
    "path": "test/aot/has-transform.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\n\nimport { t } from '../../src'\nimport { hasTransform } from '../../src/schema'\n\ndescribe('Has Transform', () => {\n\tit('find primitive', () => {\n\t\tconst schema = t\n\t\t\t.Transform(t.String())\n\t\t\t.Decode((v) => v)\n\t\t\t.Encode((v) => v)\n\n\t\texpect(hasTransform(schema)).toBe(true)\n\t})\n\n\tit('find in root object', () => {\n\t\tconst schema = t.Object({\n\t\t\tliyue: t\n\t\t\t\t.Transform(t.String())\n\t\t\t\t.Decode((v) => v)\n\t\t\t\t.Encode((v) => v)\n\t\t})\n\n\t\texpect(hasTransform(schema)).toBe(true)\n\t})\n\n\tit('find in nested object', () => {\n\t\tconst schema = t.Object({\n\t\t\tliyue: t.Object({\n\t\t\t\tid: t\n\t\t\t\t\t.Transform(t.String())\n\t\t\t\t\t.Decode((v) => v)\n\t\t\t\t\t.Encode((v) => v)\n\t\t\t})\n\t\t})\n\n\t\texpect(hasTransform(schema)).toBe(true)\n\t})\n\n\tit('find in Optional', () => {\n\t\tconst schema = t.Optional(\n\t\t\tt.Object({\n\t\t\t\tprop1: t\n\t\t\t\t\t.Transform(t.String())\n\t\t\t\t\t.Decode((v) => v)\n\t\t\t\t\t.Encode((v) => v)\n\t\t\t})\n\t\t)\n\n\t\texpect(hasTransform(schema)).toBe(true)\n\t})\n\n\tit('find on multiple transform', () => {\n\t\tconst schema = t.Object({\n\t\t\tid: t\n\t\t\t\t.Transform(t.String())\n\t\t\t\t.Decode((v) => v)\n\t\t\t\t.Encode((v) => v),\n\t\t\tname: t\n\t\t\t\t.Transform(t.String())\n\t\t\t\t.Decode((v) => v)\n\t\t\t\t.Encode((v) => v)\n\t\t})\n\n\t\texpect(hasTransform(schema)).toBe(true)\n\t})\n\n\tit('return false on not found', () => {\n\t\tconst schema = t.Object({\n\t\t\tname: t.String(),\n\t\t\tage: t.Number()\n\t\t})\n\n\t\texpect(hasTransform(schema)).toBe(false)\n\t})\n\n\tit('found on Union', () => {\n\t\tconst schema = t.Object({\n\t\t\tid: t.Number(),\n\t\t\tliyue: t.Union([\n\t\t\t\tt\n\t\t\t\t\t.Transform(t.String())\n\t\t\t\t\t.Decode((v) => v)\n\t\t\t\t\t.Encode((v) => v),\n\t\t\t\tt.Number()\n\t\t\t])\n\t\t})\n\n\t\texpect(hasTransform(schema)).toBe(true)\n\t})\n\n\tit('Found t.Numeric', () => {\n\t\tconst schema = t.Object({\n\t\t\tid: t.Numeric(),\n\t\t\tliyue: t.String()\n\t\t})\n\n\t\texpect(hasTransform(schema)).toBe(true)\n\t})\n\n\tit('Found t.NumericEnum', () => {\n\t\tconst schema = t.Object({\n\t\t\tgender: t.NumericEnum({ UNKNOWN: 0, MALE: 1, FEMALE: 2 }),\n\t\t\tliyue: t.String()\n\t\t})\n\n\t\texpect(hasTransform(schema)).toBe(true)\n\t})\n\n\tit('Found t.ObjectString', () => {\n\t\tconst schema = t.Object({\n\t\t\tid: t.String(),\n\t\t\tliyue: t.ObjectString({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\n\t\texpect(hasTransform(schema)).toBe(true)\n\t})\n})\n"
  },
  {
    "path": "test/aot/has-type.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\n\nimport { t } from '../../src'\nimport { hasType } from '../../src/schema'\n\ndescribe('Has Transform', () => {\n\tit('find primitive', () => {\n\t\tconst schema = t\n\t\t\t.Transform(t.File())\n\t\t\t.Decode((v) => v)\n\t\t\t.Encode((v) => v)\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n\n\tit('find in root object', () => {\n\t\tconst schema = t.Object({\n\t\t\tliyue: t.File()\n\t\t})\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n\n\tit('find in nested object', () => {\n\t\tconst schema = t.Object({\n\t\t\tliyue: t.Object({\n\t\t\t\tid: t.File()\n\t\t\t})\n\t\t})\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n\n\tit('find in Optional', () => {\n\t\tconst schema = t.Optional(\n\t\t\tt.Object({\n\t\t\t\tprop1: t.File()\n\t\t\t})\n\t\t)\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n\n\tit('find on multiple transform', () => {\n\t\tconst schema = t.Object({\n\t\t\tid: t.File(),\n\t\t\tname: t.File()\n\t\t})\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n\n\tit('return false on not found', () => {\n\t\tconst schema = t.Object({\n\t\t\tname: t.String(),\n\t\t\tage: t.Number()\n\t\t})\n\n\t\texpect(hasType('File', schema)).toBe(false)\n\t})\n\n\tit('found on Union', () => {\n\t\tconst schema = t.Object({\n\t\t\tid: t.Number(),\n\t\t\tliyue: t.Union([t.Number(), t.File()])\n\t\t})\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n\n\tit('found on direct Union', () => {\n\t\tconst schema = t.Union([\n\t\t\tt.Object({\n\t\t\t    id: t.Number(),\n\t\t\t    liyue: t.File()\n\t\t\t}),\n\t\t\tt.Object({\n\t\t\t    id: t.Number(),\n\t\t\t    liyue: t.Number(),\n\t\t\t}),\n\t\t])\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n\n\tit('find in Import wrapping File', () => {\n\t\tconst schema = t.Module({\n\t\t\tAvatar: t.File()\n\t\t}).Import('Avatar')\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n\n\tit('find in Import wrapping Object with File', () => {\n\t\tconst schema = t.Module({\n\t\t\tUpload: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tfile: t.File()\n\t\t\t})\n\t\t}).Import('Upload')\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n\n\tit('return false for Import wrapping Object without File', () => {\n\t\tconst schema = t.Module({\n\t\t\tUser: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tage: t.Number()\n\t\t\t})\n\t\t}).Import('User')\n\n\t\texpect(hasType('File', schema)).toBe(false)\n\t})\n\n\tit('find in Import wrapping Union with File', () => {\n\t\tconst schema = t.Module({\n\t\t\tData: t.Union([\n\t\t\t\tt.Object({ file: t.File() }),\n\t\t\t\tt.Null()\n\t\t\t])\n\t\t}).Import('Data')\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n\n\tit('find in Import wrapping Array of Files', () => {\n\t\tconst schema = t.Module({\n\t\t\tUploads: t.Array(t.File())\n\t\t}).Import('Uploads')\n\n\t\texpect(hasType('Files', schema)).toBe(true)\n\t})\n\n\tit('find in Import wrapping Array of Files using t.Files', () => {\n\t\tconst schema = t.Module({\n\t\t\tUploads: t.Files()\n\t\t}).Import('Uploads')\n\n\t\texpect(hasType('Files', schema)).toBe(true)\n\t})\n\n\tit('find in Array of Files (direct)', () => {\n\t\tconst schema = t.Array(t.File())\n\n\t\texpect(hasType('Files', schema)).toBe(true)\n\t})\n\n\tit('find in Array of Files using t.Files (direct)', () => {\n\t\tconst schema = t.Files()\n\n\t\texpect(hasType('Files', schema)).toBe(true)\n\t})\n\n\t// Intersect schema tests\n\tit('find on direct Intersect', () => {\n\t\tconst schema = t.Intersect([\n\t\t\tt.Object({\n\t\t\t\tid: t.Number()\n\t\t\t}),\n\t\t\tt.Object({\n\t\t\t\tfile: t.File()\n\t\t\t})\n\t\t])\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n\n\tit('do not find on Intersect without File', () => {\n\t\tconst schema = t.Intersect([\n\t\t\tt.Object({\n\t\t\t\tid: t.Number()\n\t\t\t}),\n\t\t\tt.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t])\n\n\t\texpect(hasType('File', schema)).toBe(false)\n\t})\n\n\tit('find on nested Union in Intersect', () => {\n\t\tconst schema = t.Intersect([\n\t\t\tt.Object({\n\t\t\t\tid: t.Number()\n\t\t\t}),\n\t\t\tt.Union([t.Object({ file: t.File() }), t.Null()])\n\t\t])\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n\n\tit('find File in Intersect referenced via Module.Import()', () => {\n\t\tconst schema = t\n\t\t\t.Module({\n\t\t\t\tData: t.Intersect([\n\t\t\t\t\tt.Object({ id: t.Number() }),\n\t\t\t\t\tt.Object({ file: t.File() })\n\t\t\t\t])\n\t\t\t})\n\t\t\t.Import('Data')\n\n\t\texpect(hasType('File', schema)).toBe(true)\n\t})\n})\n"
  },
  {
    "path": "test/aot/response.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Elysia, t } from '../../src'\nimport { req } from '../utils'\nimport { signCookie } from '../../src/utils'\n\nconst secrets = 'We long for the seven wailings. We bear the koan of Jericho.'\n\nconst getCookies = (response: Response) =>\n\tresponse.headers.getAll('Set-Cookie').map((x) => {\n\t\treturn decodeURIComponent(x)\n\t})\n\nconst app = new Elysia()\n\t.get(\n\t\t'/council',\n\t\t({ cookie: { council } }) =>\n\t\t\t(council.value = [\n\t\t\t\t{\n\t\t\t\t\tname: 'Rin',\n\t\t\t\t\taffilation: 'Administration'\n\t\t\t\t}\n\t\t\t])\n\t)\n\t.get('/create', ({ cookie: { name } }) => (name.value = 'Himari'))\n\t.get('/multiple', ({ cookie: { name, president } }) => {\n\t\tname.value = 'Himari'\n\t\tpresident.value = 'Rio'\n\n\t\treturn 'ok'\n\t})\n\t.get(\n\t\t'/update',\n\t\t({ cookie: { name } }) => {\n\t\t\tname.value = 'seminar: Himari'\n\n\t\t\treturn name.value\n\t\t},\n\t\t{\n\t\t\tcookie: t.Cookie(\n\t\t\t\t{\n\t\t\t\t\tname: t.Optional(t.String())\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tsecrets,\n\t\t\t\t\tsign: ['name']\n\t\t\t\t}\n\t\t\t)\n\t\t}\n\t)\n\t.get('/remove', ({ cookie }) => {\n\t\tfor (const self of Object.values(cookie)) self.remove()\n\n\t\treturn 'Deleted'\n\t})\n\ndescribe('Dynamic Cookie Response', () => {\n\tit('set cookie', async () => {\n\t\tconst response = await app.handle(req('/create'))\n\n\t\texpect(getCookies(response)).toEqual(['name=Himari; Path=/'])\n\t})\n\n\tit('set multiple cookie', async () => {\n\t\tconst response = await app.handle(req('/multiple'))\n\n\t\texpect(getCookies(response)).toEqual([\n\t\t\t'name=Himari; Path=/',\n\t\t\t'president=Rio; Path=/'\n\t\t])\n\t})\n\n\tit('set JSON cookie', async () => {\n\t\tconst response = await app.handle(req('/council'))\n\n\t\texpect(getCookies(response)).toEqual([\n\t\t\t'council=[{\"name\":\"Rin\",\"affilation\":\"Administration\"}]; Path=/'\n\t\t])\n\t})\n\n\tit('write cookie on difference value', async () => {\n\t\tconst response = await app.handle(\n\t\t\treq('/council', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie:\n\t\t\t\t\t\t'council=' +\n\t\t\t\t\t\tencodeURIComponent(\n\t\t\t\t\t\t\tJSON.stringify([\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tname: 'Aoi',\n\t\t\t\t\t\t\t\t\taffilation: 'Financial'\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t) +\n\t\t\t\t\t\t'; Path=/'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(getCookies(response)).toEqual([\n\t\t\t'council=[{\"name\":\"Rin\",\"affilation\":\"Administration\"}]; Path=/'\n\t\t])\n\t})\n\n\tit('remove cookie', async () => {\n\t\tconst response = await app.handle(\n\t\t\treq('/remove', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie:\n\t\t\t\t\t\t'council=' +\n\t\t\t\t\t\tencodeURIComponent(\n\t\t\t\t\t\t\tJSON.stringify([\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tname: 'Rin',\n\t\t\t\t\t\t\t\t\taffilation: 'Administration'\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(getCookies(response)[0]).toInclude(\n\t\t\t`council=; Max-Age=0; Path=/; Expires=${new Date(0).toUTCString()}`\n\t\t)\n\t})\n\n\tit('sign cookie', async () => {\n\t\tconst response = await app.handle(req('/update'))\n\n\t\texpect(getCookies(response)).toEqual([\n\t\t\t`name=${await signCookie('seminar: Himari', secrets)}; Path=/`\n\t\t])\n\t})\n\n\tit('sign/unsign cookie', async () => {\n\t\tconst response = await app.handle(\n\t\t\treq('/update', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: `name=${await signCookie(\n\t\t\t\t\t\t'seminar: Himari',\n\t\t\t\t\t\tsecrets\n\t\t\t\t\t)}`\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('inherits cookie settings', async () => {\n\t\tconst app = new Elysia({\n\t\t\tcookie: {\n\t\t\t\tsecrets,\n\t\t\t\tsign: ['name']\n\t\t\t}\n\t\t}).get(\n\t\t\t'/update',\n\t\t\t({ cookie: { name } }) => {\n\t\t\t\tif (!name.value) name.value = 'seminar: Himari'\n\n\t\t\t\treturn name.value\n\t\t\t},\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tname: t.Optional(t.String())\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\treq('/update', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: `name=${await signCookie(\n\t\t\t\t\t\t'seminar: Himari',\n\t\t\t\t\t\tsecrets\n\t\t\t\t\t)}`\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('sign all cookie', async () => {\n\t\tconst app = new Elysia({\n\t\t\tcookie: {\n\t\t\t\tsecrets,\n\t\t\t\tsign: true\n\t\t\t}\n\t\t}).get(\n\t\t\t'/update',\n\t\t\t({ cookie: { name } }) => {\n\t\t\t\tif (!name.value) name.value = 'seminar: Himari'\n\n\t\t\t\treturn name.value\n\t\t\t},\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tname: t.Optional(t.String())\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\treq('/update', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: `name=${await signCookie('seminar: Himari', secrets)}`\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit(\"don't share context between race condition\", async () => {\n\t\tconst resolver = Promise.withResolvers()\n\n\t\tconst app = new Elysia({ aot: false })\n\t\t\t.onRequest(() => new Promise((resolve) => setTimeout(resolve, 1)))\n\t\t\t.get('/test', ({ request }) => {\n\t\t\t\tresolver.resolve(request.url)\n\t\t\t})\n\n\t\tapp.handle(new Request('http://localhost:1025/test'))\n\t\tapp.handle(new Request('http://localhost:1025/bad'))\n\n\t\texpect(await resolver.promise).toBe('http://localhost:1025/test')\n\t})\n})\n"
  },
  {
    "path": "test/bun/router.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { Elysia, ELYSIA_REQUEST_ID, t } from '../../src'\nimport { req } from '../utils'\n\ndescribe('Bun router', () => {\n\tit('works', async () => {\n\t\tlet trace = false\n\t\tlet wrapped = false\n\t\tlet onRequest = false\n\t\tlet traceOnRequest = false\n\n\t\tconst app = new Elysia({ systemRouter: true })\n\t\t\t.trace(({ onHandle, onRequest }) => {\n\t\t\t\tonRequest(() => {\n\t\t\t\t\ttraceOnRequest = true\n\t\t\t\t})\n\n\t\t\t\tonHandle(() => {\n\t\t\t\t\ttrace = true\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onRequest(() => {\n\t\t\t\tonRequest = true\n\t\t\t})\n\t\t\t.decorate('decorated', 'decorated')\n\t\t\t.state('state', 'state')\n\t\t\t.derive(() => ({ derived: 'derived' }))\n\t\t\t.resolve(() => ({ resolved: 'resolved' }))\n\t\t\t.get('/', ({ store, decorated, derived, resolved }) => ({\n\t\t\t\tstore,\n\t\t\t\tdecorated,\n\t\t\t\tderived,\n\t\t\t\tresolved\n\t\t\t}))\n\t\t\t.wrap((fn) => {\n\t\t\t\twrapped = true\n\n\t\t\t\treturn fn\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst response = await fetch(\n\t\t\t`http://localhost:${app.server!.port}`\n\t\t).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tstore: {\n\t\t\t\tstate: 'state'\n\t\t\t},\n\t\t\tdecorated: 'decorated',\n\t\t\tderived: 'derived',\n\t\t\tresolved: 'resolved'\n\t\t})\n\n\t\texpect(wrapped).toEqual(true)\n\t\texpect(trace).toBe(true)\n\t\texpect(onRequest).toBe(true)\n\t\texpect(traceOnRequest).toBe(true)\n\t})\n\n\tit('handle params and query', async () => {\n\t\tconst app = new Elysia({ systemRouter: true })\n\t\t\t.get('/id/:id', ({ query, params }) => ({\n\t\t\t\tquery,\n\t\t\t\tparams\n\t\t\t}))\n\t\t\t.listen(0)\n\n\t\tconst query = await fetch(\n\t\t\t`http://localhost:${app.server!.port}/id/1?q=s`\n\t\t).then((x) => x.json())\n\n\t\texpect(query).toEqual({\n\t\t\tquery: {\n\t\t\t\tq: 's'\n\t\t\t},\n\t\t\tparams: {\n\t\t\t\tid: '1'\n\t\t\t}\n\t\t})\n\t})\n\n\tit('handle optional params', async () => {\n\t\tconst app = new Elysia({ systemRouter: false })\n\t\t\t.get('/id/:id?/:name?', ({ params }) => params)\n\t\t\t.listen(0)\n\n\t\tconst query = await Promise.all([\n\t\t\tfetch(`http://localhost:${app.server!.port}/id`).then((x) =>\n\t\t\t\tx.json()\n\t\t\t),\n\t\t\tfetch(`http://localhost:${app.server!.port}/id/1`).then((x) =>\n\t\t\t\tx.json()\n\t\t\t),\n\t\t\tfetch(`http://localhost:${app.server!.port}/id/1/saltyaom`).then(\n\t\t\t\t(x) => x.json()\n\t\t\t)\n\t\t])\n\n\t\texpect(query).toEqual([{}, { id: '1' }, { id: '1', name: 'saltyaom' }])\n\t})\n\n\tit('handle async static route', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get(\n\t\t\t\t'/',\n\t\t\t\tPromise.resolve(\n\t\t\t\t\tnew Response(`<h1>Hello World</h1>`, {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'Content-Type': 'text/html'\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t)\n\t\t\t.listen(0)\n\n\t\tawait Bun.sleep(20)\n\n\t\tconst response = await fetch(\n\t\t\t`http://localhost:${app.server!.port}`\n\t\t).then((x) => x.text())\n\n\t\texpect(response).toEqual('<h1>Hello World</h1>')\n\t})\n\n\tit('handle mount', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.mount((request: Request) => new Response(request.url))\n\t\t\t.mount('/prefix', (request: Request) => new Response(request.url))\n\t\t\t.listen(0)\n\n\t\tconst response = await Promise.all([\n\t\t\tfetch(`http://localhost:${app.server?.port}/a`),\n\t\t\tfetch(`http://localhost:${app.server?.port}/prefix/a`)\n\t\t])\n\n\t\texpect(response[0].status).toBe(200)\n\t\texpect(response[1].status).toBe(200)\n\t})\n\n\tit('handle trace url', async () => {\n\t\tlet url = ''\n\t\tlet hasRequestId = false\n\n\t\tconst app = new Elysia()\n\t\t\t.trace((a) => {\n\t\t\t\ta.onHandle(() => {\n\t\t\t\t\t// @ts-expect-error private property\n\t\t\t\t\turl = a.context.url\n\n\t\t\t\t\t// @ts-expect-error private property\n\t\t\t\t\thasRequestId = !!a.context[ELYSIA_REQUEST_ID]\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'ok')\n\t\t\t.listen(0)\n\n\t\tawait fetch(`http://localhost:${app.server!.port}/`)\n\n\t\texpect(url).toBe(`http://localhost:${app.server!.port}/`)\n\t\texpect(hasRequestId).toBe(true)\n\t})\n\n\tit('handle wrap in mount', async () => {\n\t\tlet url = ''\n\t\tlet hasWrap = false\n\n\t\tconst app = new Elysia()\n\t\t\t.wrap((fn) => {\n\t\t\t\thasWrap = true\n\n\t\t\t\treturn fn\n\t\t\t})\n\t\t\t.mount('/', (request) => new Response((url = request.url)))\n\t\t\t.listen(0)\n\n\t\tawait fetch(`http://localhost:${app.server!.port}/`)\n\n\t\texpect(url).toBe(`http://localhost:${app.server!.port}/`)\n\t\texpect(hasWrap).toBe(true)\n\t})\n\n\tit('handle trace url with wrap', async () => {\n\t\tlet url = ''\n\t\tlet hasRequestId = false\n\t\tlet hasWrap = false\n\n\t\tconst app = new Elysia()\n\t\t\t.wrap((fn) => {\n\t\t\t\thasWrap = true\n\n\t\t\t\treturn fn\n\t\t\t})\n\t\t\t.trace((a) => {\n\t\t\t\ta.onHandle(() => {\n\t\t\t\t\t// @ts-expect-error private property\n\t\t\t\t\turl = a.context.url\n\n\t\t\t\t\t// @ts-expect-error private property\n\t\t\t\t\thasRequestId = !!a.context[ELYSIA_REQUEST_ID]\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'ok')\n\t\t\t.listen(0)\n\n\t\tawait fetch(`http://localhost:${app.server!.port}/`)\n\n\t\texpect(url).toBe(`http://localhost:${app.server!.port}/`)\n\t\texpect(hasWrap).toBe(true)\n\t\texpect(hasRequestId).toBe(true)\n\t})\n\n\tit('handle mount', async () => {\n\t\tlet url = ''\n\t\tlet hasRequestId = false\n\t\tlet hasWrap = false\n\n\t\tconst app = new Elysia()\n\t\t\t.wrap((fn) => {\n\t\t\t\thasWrap = true\n\n\t\t\t\treturn fn\n\t\t\t})\n\t\t\t.trace((a) => {\n\t\t\t\ta.onHandle(() => {\n\t\t\t\t\t// @ts-expect-error private property\n\t\t\t\t\turl = a.context.url\n\n\t\t\t\t\t// @ts-expect-error private property\n\t\t\t\t\thasRequestId = !!a.context[ELYSIA_REQUEST_ID]\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'ok')\n\t\t\t.listen(0)\n\n\t\tawait fetch(`http://localhost:${app.server!.port}/`)\n\n\t\texpect(url).toBe(`http://localhost:${app.server!.port}/`)\n\t\texpect(hasWrap).toBe(true)\n\t\texpect(hasRequestId).toBe(true)\n\t})\n\n\tit('handle async plugin', async () => {\n\t\tconst asyncPlugin = async () =>\n\t\t\tnew Elysia({ name: 'async' })\n\t\t\t\t.get('/router', () => 'OK')\n\t\t\t\t.get('/static', 'OK')\n\n\t\tconst app = new Elysia({ name: 'main' }).use(asyncPlugin).listen(0)\n\n\t\tconst [router, _static] = await Promise.all([\n\t\t\tfetch(`http://localhost:${app.server?.port}/router`).then((x) =>\n\t\t\t\tx.text()\n\t\t\t),\n\t\t\tfetch(`http://localhost:${app.server?.port}/static`).then((x) =>\n\t\t\t\tx.text()\n\t\t\t)\n\t\t])\n\n\t\texpect(router).toBe('OK')\n\t\texpect(_static).toBe('OK')\n\t})\n\n\tit('handle async request', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onRequest(async () => {})\n\t\t\t.mount('/auth', () => new Response('OK'))\n\t\t\t.listen(0)\n\n\t\tconst response = await fetch(\n\t\t\t`http://localhost:${app.server?.port}/auth`\n\t\t).then((x) => x.text())\n\n\t\texpect(response).toBe('OK')\n\t})\n\n\tit('handle wildcard', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/hi/:id', ({ params }) => params)\n\t\t\t.get('/hi/*', ({ params }) => params)\n\t\t\t.listen(0)\n\n\t\tconst [response1, response2] = await Promise.all([\n\t\t\tfetch(\n\t\t\t\t`http://${app.server?.hostname}:${app.server?.port}/hi/saltyaom`\n\t\t\t).then((x) => x.json()),\n\t\t\tfetch(\n\t\t\t\t`http://${app.server?.hostname}:${app.server?.port}/hi/salty/aom`\n\t\t\t).then((x) => x.json())\n\t\t])\n\n\t\texpect(response1).toEqual({\n\t\t\tid: 'saltyaom'\n\t\t})\n\n\t\texpect(response2).toEqual({\n\t\t\t'*': 'salty/aom'\n\t\t})\n\t})\n\n\tit('mapEarlyResponse onRequest', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onRequest(() => 'OK!! XD')\n\t\t\t.get('/', () => '')\n\t\t\t.listen(0)\n\n\t\tconst response = await fetch(\n\t\t\t`http://localhost:${app.server?.port}/auth`\n\t\t).then((x) => x.text())\n\n\t\texpect(response).toBe('OK!! XD')\n\t})\n\n\t// https://github.com/elysiajs/elysia/issues/1752\n\tit('trailing slash should be consistent with non-trailing slash', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/items/types/', () => '/items/types')\n\t\t\t.get('/items/types/:id', () => '/items/types/:id')\n\t\t\t.get('/items/:id', () => '/items/:id')\n\t\t\t.listen(0)\n\n\t\texpect(\n\t\t\tfetch(`http://localhost:${app.server?.port}/items/types`).then(\n\t\t\t\t(x) => x.text()\n\t\t\t)\n\t\t).resolves.toBe('/items/types')\n\n\t\texpect(\n\t\t\tfetch(`http://localhost:${app.server?.port}/items/types/`).then(\n\t\t\t\t(x) => x.text()\n\t\t\t)\n\t\t).resolves.toBe('/items/types')\n\n\t\texpect(\n\t\t\tfetch(`http://localhost:${app.server?.port}/items/1`).then((x) =>\n\t\t\t\tx.text()\n\t\t\t)\n\t\t).resolves.toBe('/items/:id')\n\n\t\texpect(\n\t\t\tfetch(`http://localhost:${app.server?.port}/items/types/a`).then(\n\t\t\t\t(x) => x.text()\n\t\t\t)\n\t\t).resolves.toBe('/items/types/:id')\n\t})\n})\n"
  },
  {
    "path": "test/bun/sql.test.ts",
    "content": "import { SQL } from 'bun'\nimport { describe, it, expect } from 'bun:test'\n\nimport Elysia from '../../src'\nimport { req } from '../utils'\n\ndescribe('Bun.SQL', () => {\n\tit('serialize custom array-like custom class with array sub class', async () => {\n\t\tconst sql = new SQL(':memory:')\n\n\t\tawait sql`CREATE TABLE elysia_repro_users (id SERIAL PRIMARY KEY, name TEXT)`\n\t\tconst { count } =\n\t\t\tawait sql`SELECT COUNT(*) as count FROM elysia_repro_users`.then(\n\t\t\t\t(x) => x[0]\n\t\t\t)\n\n\t\tif (!count)\n\t\t\tawait sql`INSERT INTO elysia_repro_users (name) VALUES ('Alice'), ('Bob')`\n\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => sql`SELECT * FROM elysia_repro_users`\n\t\t)\n\n\t\tconst value = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(value).toEqual([\n\t\t\t{\n\t\t\t\tid: null,\n\t\t\t\tname: 'Alice'\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: null,\n\t\t\t\tname: 'Bob'\n\t\t\t}\n\t\t])\n\t})\n})\n"
  },
  {
    "path": "test/cloudflare/.gitignore",
    "content": "node_modules/\r\npackage-lock.json\r\n.wrangler\r\n"
  },
  {
    "path": "test/cloudflare/package.json",
    "content": "{\n\t\"name\": \"elysia-cf\",\n\t\"version\": \"0.0.0\",\n\t\"private\": true,\n\t\"scripts\": {\n\t\t\"dev\": \"wrangler dev\",\n\t\t\"start\": \"wrangler dev\",\n\t\t\"test\": \"bun script/test.ts\",\n\t\t\"cf-typegen\": \"wrangler types\"\n\t},\n\t\"devDependencies\": {\n\t\t\"typescript\": \"^5.8.2\",\n\t\t\"wrangler\": \"^4.40.2\"\n\t},\n\t\"dependencies\": {\n\t\t\"elysia\": \"../../\"\n\t},\n\t\"overrides\": {\n\t\t\"esbuild\": \"0.25.4\"\n\t}\n}\n"
  },
  {
    "path": "test/cloudflare/script/test.ts",
    "content": "const server = Bun.spawn({\n\tcmd: ['bunx', 'wrangler', 'dev', '--port', '8787', '--local'],\n})\n\nBun.sleepSync(750)\n\nsetInterval(async () => {\n\tconst response = await fetch('http://localhost:8787').catch(() => {})\n\tif (!response) return\n\n\tconst value = await response.text()\n\n\tif (value === 'Elysia on Cloudflare Worker!' && response.status) {\n\t\tconsole.log('✅ Cloudflare Worker works')\n\t\tserver.kill('SIGKILL')\n\t\tprocess.exit(0)\n\t}\n}, 500)\n\nsetTimeout(() => {\n\tconsole.log(\"❌ Cloudflare Worker doesn't work\")\n\tserver.kill('SIGKILL')\n\tprocess.exit(1)\n}, 8000)\n"
  },
  {
    "path": "test/cloudflare/src/index.ts",
    "content": "import { Elysia, t } from 'elysia'\nimport { CloudflareAdapter } from 'elysia/adapter/cloudflare-worker'\n\nconst sub = new Elysia().get('/test', () => 'hello')\n\nexport default new Elysia({ adapter: CloudflareAdapter })\n\t.get('/', () => 'Elysia on Cloudflare Worker!')\n\t.use(sub)\n\t.compile()\n"
  },
  {
    "path": "test/cloudflare/tsconfig.json",
    "content": "{\n\t\"compilerOptions\": {\n\t\t/* Visit https://aka.ms/tsconfig.json to read more about this file */\n\n\t\t/* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */\n\t\t\"target\": \"es2021\",\n\t\t/* Specify a set of bundled library declaration files that describe the target runtime environment. */\n\t\t\"lib\": [\"es2021\"],\n\t\t/* Specify what JSX code is generated. */\n\t\t\"jsx\": \"react-jsx\",\n\n\t\t/* Specify what module code is generated. */\n\t\t\"module\": \"es2022\",\n\t\t/* Specify how TypeScript looks up a file from a given module specifier. */\n\t\t\"moduleResolution\": \"Bundler\",\n\t\t/* Enable importing .json files */\n\t\t\"resolveJsonModule\": true,\n\n\t\t/* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */\n\t\t\"allowJs\": true,\n\t\t/* Enable error reporting in type-checked JavaScript files. */\n\t\t\"checkJs\": false,\n\n\t\t/* Disable emitting files from a compilation. */\n\t\t\"noEmit\": true,\n\n\t\t/* Ensure that each file can be safely transpiled without relying on other imports. */\n\t\t\"isolatedModules\": true,\n\t\t/* Allow 'import x from y' when a module doesn't have a default export. */\n\t\t\"allowSyntheticDefaultImports\": true,\n\t\t/* Ensure that casing is correct in imports. */\n\t\t\"forceConsistentCasingInFileNames\": true,\n\n\t\t/* Enable all strict type-checking options. */\n\t\t\"strict\": true,\n\n\t\t/* Skip type checking all .d.ts files. */\n\t\t\"skipLibCheck\": true,\n\t\t\"types\": [\n\t\t\t\"./worker-configuration.d.ts\"\n\t\t]\n\t},\n\t\"exclude\": [\"test\"],\n\t\"include\": [\"worker-configuration.d.ts\", \"src/**/*.ts\"]\n}\n"
  },
  {
    "path": "test/cloudflare/worker-configuration.d.ts",
    "content": "/* eslint-disable */\n// Generated by Wrangler by running `wrangler types` (hash: b739a9c19cff1463949c4db47674ed86)\n// Runtime types generated with workerd@1.20250924.0 2025-09-06 \ndeclare namespace Cloudflare {\n\tinterface GlobalProps {\n\t\tmainModule: typeof import(\"./src/index\");\n\t}\n\tinterface Env {\n\t}\n}\ninterface Env extends Cloudflare.Env {}\n\n// Begin runtime types\n/*! *****************************************************************************\nCopyright (c) Cloudflare. All rights reserved.\nCopyright (c) Microsoft Corporation. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABLITY OR NON-INFRINGEMENT.\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n/* eslint-disable */\n// noinspection JSUnusedGlobalSymbols\ndeclare var onmessage: never;\n/**\n * An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException)\n */\ndeclare class DOMException extends Error {\n    constructor(message?: string, name?: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */\n    readonly message: string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */\n    readonly name: string;\n    /**\n     * @deprecated\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code)\n     */\n    readonly code: number;\n    static readonly INDEX_SIZE_ERR: number;\n    static readonly DOMSTRING_SIZE_ERR: number;\n    static readonly HIERARCHY_REQUEST_ERR: number;\n    static readonly WRONG_DOCUMENT_ERR: number;\n    static readonly INVALID_CHARACTER_ERR: number;\n    static readonly NO_DATA_ALLOWED_ERR: number;\n    static readonly NO_MODIFICATION_ALLOWED_ERR: number;\n    static readonly NOT_FOUND_ERR: number;\n    static readonly NOT_SUPPORTED_ERR: number;\n    static readonly INUSE_ATTRIBUTE_ERR: number;\n    static readonly INVALID_STATE_ERR: number;\n    static readonly SYNTAX_ERR: number;\n    static readonly INVALID_MODIFICATION_ERR: number;\n    static readonly NAMESPACE_ERR: number;\n    static readonly INVALID_ACCESS_ERR: number;\n    static readonly VALIDATION_ERR: number;\n    static readonly TYPE_MISMATCH_ERR: number;\n    static readonly SECURITY_ERR: number;\n    static readonly NETWORK_ERR: number;\n    static readonly ABORT_ERR: number;\n    static readonly URL_MISMATCH_ERR: number;\n    static readonly QUOTA_EXCEEDED_ERR: number;\n    static readonly TIMEOUT_ERR: number;\n    static readonly INVALID_NODE_TYPE_ERR: number;\n    static readonly DATA_CLONE_ERR: number;\n    get stack(): any;\n    set stack(value: any);\n}\ntype WorkerGlobalScopeEventMap = {\n    fetch: FetchEvent;\n    scheduled: ScheduledEvent;\n    queue: QueueEvent;\n    unhandledrejection: PromiseRejectionEvent;\n    rejectionhandled: PromiseRejectionEvent;\n};\ndeclare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> {\n    EventTarget: typeof EventTarget;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */\ninterface Console {\n    \"assert\"(condition?: boolean, ...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */\n    clear(): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */\n    count(label?: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */\n    countReset(label?: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */\n    debug(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */\n    dir(item?: any, options?: any): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */\n    dirxml(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */\n    error(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */\n    group(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */\n    groupCollapsed(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */\n    groupEnd(): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */\n    info(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */\n    log(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */\n    table(tabularData?: any, properties?: string[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */\n    time(label?: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */\n    timeEnd(label?: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */\n    timeLog(label?: string, ...data: any[]): void;\n    timeStamp(label?: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */\n    trace(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */\n    warn(...data: any[]): void;\n}\ndeclare const console: Console;\ntype BufferSource = ArrayBufferView | ArrayBuffer;\ntype TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;\ndeclare namespace WebAssembly {\n    class CompileError extends Error {\n        constructor(message?: string);\n    }\n    class RuntimeError extends Error {\n        constructor(message?: string);\n    }\n    type ValueType = \"anyfunc\" | \"externref\" | \"f32\" | \"f64\" | \"i32\" | \"i64\" | \"v128\";\n    interface GlobalDescriptor {\n        value: ValueType;\n        mutable?: boolean;\n    }\n    class Global {\n        constructor(descriptor: GlobalDescriptor, value?: any);\n        value: any;\n        valueOf(): any;\n    }\n    type ImportValue = ExportValue | number;\n    type ModuleImports = Record<string, ImportValue>;\n    type Imports = Record<string, ModuleImports>;\n    type ExportValue = Function | Global | Memory | Table;\n    type Exports = Record<string, ExportValue>;\n    class Instance {\n        constructor(module: Module, imports?: Imports);\n        readonly exports: Exports;\n    }\n    interface MemoryDescriptor {\n        initial: number;\n        maximum?: number;\n        shared?: boolean;\n    }\n    class Memory {\n        constructor(descriptor: MemoryDescriptor);\n        readonly buffer: ArrayBuffer;\n        grow(delta: number): number;\n    }\n    type ImportExportKind = \"function\" | \"global\" | \"memory\" | \"table\";\n    interface ModuleExportDescriptor {\n        kind: ImportExportKind;\n        name: string;\n    }\n    interface ModuleImportDescriptor {\n        kind: ImportExportKind;\n        module: string;\n        name: string;\n    }\n    abstract class Module {\n        static customSections(module: Module, sectionName: string): ArrayBuffer[];\n        static exports(module: Module): ModuleExportDescriptor[];\n        static imports(module: Module): ModuleImportDescriptor[];\n    }\n    type TableKind = \"anyfunc\" | \"externref\";\n    interface TableDescriptor {\n        element: TableKind;\n        initial: number;\n        maximum?: number;\n    }\n    class Table {\n        constructor(descriptor: TableDescriptor, value?: any);\n        readonly length: number;\n        get(index: number): any;\n        grow(delta: number, value?: any): number;\n        set(index: number, value?: any): void;\n    }\n    function instantiate(module: Module, imports?: Imports): Promise<Instance>;\n    function validate(bytes: BufferSource): boolean;\n}\n/**\n * This ServiceWorker API interface represents the global execution context of a service worker.\n * Available only in secure contexts.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope)\n */\ninterface ServiceWorkerGlobalScope extends WorkerGlobalScope {\n    DOMException: typeof DOMException;\n    WorkerGlobalScope: typeof WorkerGlobalScope;\n    btoa(data: string): string;\n    atob(data: string): string;\n    setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;\n    setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;\n    clearTimeout(timeoutId: number | null): void;\n    setInterval(callback: (...args: any[]) => void, msDelay?: number): number;\n    setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;\n    clearInterval(timeoutId: number | null): void;\n    queueMicrotask(task: Function): void;\n    structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;\n    reportError(error: any): void;\n    fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;\n    self: ServiceWorkerGlobalScope;\n    crypto: Crypto;\n    caches: CacheStorage;\n    scheduler: Scheduler;\n    performance: Performance;\n    Cloudflare: Cloudflare;\n    readonly origin: string;\n    Event: typeof Event;\n    ExtendableEvent: typeof ExtendableEvent;\n    CustomEvent: typeof CustomEvent;\n    PromiseRejectionEvent: typeof PromiseRejectionEvent;\n    FetchEvent: typeof FetchEvent;\n    TailEvent: typeof TailEvent;\n    TraceEvent: typeof TailEvent;\n    ScheduledEvent: typeof ScheduledEvent;\n    MessageEvent: typeof MessageEvent;\n    CloseEvent: typeof CloseEvent;\n    ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader;\n    ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader;\n    ReadableStream: typeof ReadableStream;\n    WritableStream: typeof WritableStream;\n    WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter;\n    TransformStream: typeof TransformStream;\n    ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy;\n    CountQueuingStrategy: typeof CountQueuingStrategy;\n    ErrorEvent: typeof ErrorEvent;\n    MessageChannel: typeof MessageChannel;\n    MessagePort: typeof MessagePort;\n    EventSource: typeof EventSource;\n    ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest;\n    ReadableStreamDefaultController: typeof ReadableStreamDefaultController;\n    ReadableByteStreamController: typeof ReadableByteStreamController;\n    WritableStreamDefaultController: typeof WritableStreamDefaultController;\n    TransformStreamDefaultController: typeof TransformStreamDefaultController;\n    CompressionStream: typeof CompressionStream;\n    DecompressionStream: typeof DecompressionStream;\n    TextEncoderStream: typeof TextEncoderStream;\n    TextDecoderStream: typeof TextDecoderStream;\n    Headers: typeof Headers;\n    Body: typeof Body;\n    Request: typeof Request;\n    Response: typeof Response;\n    WebSocket: typeof WebSocket;\n    WebSocketPair: typeof WebSocketPair;\n    WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair;\n    AbortController: typeof AbortController;\n    AbortSignal: typeof AbortSignal;\n    TextDecoder: typeof TextDecoder;\n    TextEncoder: typeof TextEncoder;\n    navigator: Navigator;\n    Navigator: typeof Navigator;\n    URL: typeof URL;\n    URLSearchParams: typeof URLSearchParams;\n    URLPattern: typeof URLPattern;\n    Blob: typeof Blob;\n    File: typeof File;\n    FormData: typeof FormData;\n    Crypto: typeof Crypto;\n    SubtleCrypto: typeof SubtleCrypto;\n    CryptoKey: typeof CryptoKey;\n    CacheStorage: typeof CacheStorage;\n    Cache: typeof Cache;\n    FixedLengthStream: typeof FixedLengthStream;\n    IdentityTransformStream: typeof IdentityTransformStream;\n    HTMLRewriter: typeof HTMLRewriter;\n}\ndeclare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;\ndeclare function removeEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;\n/**\n * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)\n */\ndeclare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */\ndeclare function btoa(data: string): string;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */\ndeclare function atob(data: string): string;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */\ndeclare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */\ndeclare function setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */\ndeclare function clearTimeout(timeoutId: number | null): void;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */\ndeclare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */\ndeclare function setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */\ndeclare function clearInterval(timeoutId: number | null): void;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */\ndeclare function queueMicrotask(task: Function): void;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */\ndeclare function structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */\ndeclare function reportError(error: any): void;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */\ndeclare function fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;\ndeclare const self: ServiceWorkerGlobalScope;\n/**\n* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.\n* The Workers runtime implements the full surface of this API, but with some differences in\n* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)\n* compared to those implemented in most browsers.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)\n*/\ndeclare const crypto: Crypto;\n/**\n* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)\n*/\ndeclare const caches: CacheStorage;\ndeclare const scheduler: Scheduler;\n/**\n* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,\n* as well as timing of subrequests and other operations.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)\n*/\ndeclare const performance: Performance;\ndeclare const Cloudflare: Cloudflare;\ndeclare const origin: string;\ndeclare const navigator: Navigator;\ninterface TestController {\n}\ninterface ExecutionContext<Props = unknown> {\n    waitUntil(promise: Promise<any>): void;\n    passThroughOnException(): void;\n    readonly props: Props;\n}\ntype ExportedHandlerFetchHandler<Env = unknown, CfHostMetadata = unknown> = (request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, env: Env, ctx: ExecutionContext) => Response | Promise<Response>;\ntype ExportedHandlerTailHandler<Env = unknown> = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise<void>;\ntype ExportedHandlerTraceHandler<Env = unknown> = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise<void>;\ntype ExportedHandlerTailStreamHandler<Env = unknown> = (event: TailStream.TailEvent<TailStream.Onset>, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise<TailStream.TailEventHandlerType>;\ntype ExportedHandlerScheduledHandler<Env = unknown> = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise<void>;\ntype ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = (batch: MessageBatch<Message>, env: Env, ctx: ExecutionContext) => void | Promise<void>;\ntype ExportedHandlerTestHandler<Env = unknown> = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise<void>;\ninterface ExportedHandler<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown> {\n    fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>;\n    tail?: ExportedHandlerTailHandler<Env>;\n    trace?: ExportedHandlerTraceHandler<Env>;\n    tailStream?: ExportedHandlerTailStreamHandler<Env>;\n    scheduled?: ExportedHandlerScheduledHandler<Env>;\n    test?: ExportedHandlerTestHandler<Env>;\n    email?: EmailExportedHandler<Env>;\n    queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>;\n}\ninterface StructuredSerializeOptions {\n    transfer?: any[];\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) */\ndeclare abstract class PromiseRejectionEvent extends Event {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */\n    readonly promise: Promise<any>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */\n    readonly reason: any;\n}\ndeclare abstract class Navigator {\n    sendBeacon(url: string, body?: (ReadableStream | string | (ArrayBuffer | ArrayBufferView) | Blob | FormData | URLSearchParams | URLSearchParams)): boolean;\n    readonly userAgent: string;\n    readonly hardwareConcurrency: number;\n    readonly language: string;\n    readonly languages: string[];\n}\ninterface AlarmInvocationInfo {\n    readonly isRetry: boolean;\n    readonly retryCount: number;\n}\ninterface Cloudflare {\n    readonly compatibilityFlags: Record<string, boolean>;\n}\ninterface DurableObject {\n    fetch(request: Request): Response | Promise<Response>;\n    alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;\n    webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;\n    webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;\n    webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;\n}\ntype DurableObjectStub<T extends Rpc.DurableObjectBranded | undefined = undefined> = Fetcher<T, \"alarm\" | \"webSocketMessage\" | \"webSocketClose\" | \"webSocketError\"> & {\n    readonly id: DurableObjectId;\n    readonly name?: string;\n};\ninterface DurableObjectId {\n    toString(): string;\n    equals(other: DurableObjectId): boolean;\n    readonly name?: string;\n}\ndeclare abstract class DurableObjectNamespace<T extends Rpc.DurableObjectBranded | undefined = undefined> {\n    newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId;\n    idFromName(name: string): DurableObjectId;\n    idFromString(id: string): DurableObjectId;\n    get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;\n    getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;\n    jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace<T>;\n}\ntype DurableObjectJurisdiction = \"eu\" | \"fedramp\" | \"fedramp-high\";\ninterface DurableObjectNamespaceNewUniqueIdOptions {\n    jurisdiction?: DurableObjectJurisdiction;\n}\ntype DurableObjectLocationHint = \"wnam\" | \"enam\" | \"sam\" | \"weur\" | \"eeur\" | \"apac\" | \"oc\" | \"afr\" | \"me\";\ninterface DurableObjectNamespaceGetDurableObjectOptions {\n    locationHint?: DurableObjectLocationHint;\n}\ninterface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> {\n}\ninterface DurableObjectState<Props = unknown> {\n    waitUntil(promise: Promise<any>): void;\n    readonly props: Props;\n    readonly id: DurableObjectId;\n    readonly storage: DurableObjectStorage;\n    container?: Container;\n    blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>;\n    acceptWebSocket(ws: WebSocket, tags?: string[]): void;\n    getWebSockets(tag?: string): WebSocket[];\n    setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void;\n    getWebSocketAutoResponse(): WebSocketRequestResponsePair | null;\n    getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null;\n    setHibernatableWebSocketEventTimeout(timeoutMs?: number): void;\n    getHibernatableWebSocketEventTimeout(): number | null;\n    getTags(ws: WebSocket): string[];\n    abort(reason?: string): void;\n}\ninterface DurableObjectTransaction {\n    get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;\n    get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;\n    list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;\n    put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;\n    put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;\n    delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;\n    delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;\n    rollback(): void;\n    getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;\n    setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;\n    deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;\n}\ninterface DurableObjectStorage {\n    get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;\n    get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;\n    list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;\n    put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;\n    put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;\n    delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;\n    delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;\n    deleteAll(options?: DurableObjectPutOptions): Promise<void>;\n    transaction<T>(closure: (txn: DurableObjectTransaction) => Promise<T>): Promise<T>;\n    getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;\n    setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;\n    deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;\n    sync(): Promise<void>;\n    sql: SqlStorage;\n    kv: SyncKvStorage;\n    transactionSync<T>(closure: () => T): T;\n    getCurrentBookmark(): Promise<string>;\n    getBookmarkForTime(timestamp: number | Date): Promise<string>;\n    onNextSessionRestoreBookmark(bookmark: string): Promise<string>;\n}\ninterface DurableObjectListOptions {\n    start?: string;\n    startAfter?: string;\n    end?: string;\n    prefix?: string;\n    reverse?: boolean;\n    limit?: number;\n    allowConcurrency?: boolean;\n    noCache?: boolean;\n}\ninterface DurableObjectGetOptions {\n    allowConcurrency?: boolean;\n    noCache?: boolean;\n}\ninterface DurableObjectGetAlarmOptions {\n    allowConcurrency?: boolean;\n}\ninterface DurableObjectPutOptions {\n    allowConcurrency?: boolean;\n    allowUnconfirmed?: boolean;\n    noCache?: boolean;\n}\ninterface DurableObjectSetAlarmOptions {\n    allowConcurrency?: boolean;\n    allowUnconfirmed?: boolean;\n}\ndeclare class WebSocketRequestResponsePair {\n    constructor(request: string, response: string);\n    get request(): string;\n    get response(): string;\n}\ninterface AnalyticsEngineDataset {\n    writeDataPoint(event?: AnalyticsEngineDataPoint): void;\n}\ninterface AnalyticsEngineDataPoint {\n    indexes?: ((ArrayBuffer | string) | null)[];\n    doubles?: number[];\n    blobs?: ((ArrayBuffer | string) | null)[];\n}\n/**\n * An event which takes place in the DOM.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event)\n */\ndeclare class Event {\n    constructor(type: string, init?: EventInit);\n    /**\n     * Returns the type of event, e.g. \"click\", \"hashchange\", or \"submit\".\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type)\n     */\n    get type(): string;\n    /**\n     * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase)\n     */\n    get eventPhase(): number;\n    /**\n     * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed)\n     */\n    get composed(): boolean;\n    /**\n     * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles)\n     */\n    get bubbles(): boolean;\n    /**\n     * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable)\n     */\n    get cancelable(): boolean;\n    /**\n     * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented)\n     */\n    get defaultPrevented(): boolean;\n    /**\n     * @deprecated\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue)\n     */\n    get returnValue(): boolean;\n    /**\n     * Returns the object whose event listener's callback is currently being invoked.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget)\n     */\n    get currentTarget(): EventTarget | undefined;\n    /**\n     * Returns the object to which event is dispatched (its target).\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target)\n     */\n    get target(): EventTarget | undefined;\n    /**\n     * @deprecated\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement)\n     */\n    get srcElement(): EventTarget | undefined;\n    /**\n     * Returns the event's timestamp as the number of milliseconds measured relative to the time origin.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp)\n     */\n    get timeStamp(): number;\n    /**\n     * Returns true if event was dispatched by the user agent, and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted)\n     */\n    get isTrusted(): boolean;\n    /**\n     * @deprecated\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)\n     */\n    get cancelBubble(): boolean;\n    /**\n     * @deprecated\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)\n     */\n    set cancelBubble(value: boolean);\n    /**\n     * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation)\n     */\n    stopImmediatePropagation(): void;\n    /**\n     * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault)\n     */\n    preventDefault(): void;\n    /**\n     * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation)\n     */\n    stopPropagation(): void;\n    /**\n     * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is \"closed\" that are not reachable from event's currentTarget.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath)\n     */\n    composedPath(): EventTarget[];\n    static readonly NONE: number;\n    static readonly CAPTURING_PHASE: number;\n    static readonly AT_TARGET: number;\n    static readonly BUBBLING_PHASE: number;\n}\ninterface EventInit {\n    bubbles?: boolean;\n    cancelable?: boolean;\n    composed?: boolean;\n}\ntype EventListener<EventType extends Event = Event> = (event: EventType) => void;\ninterface EventListenerObject<EventType extends Event = Event> {\n    handleEvent(event: EventType): void;\n}\ntype EventListenerOrEventListenerObject<EventType extends Event = Event> = EventListener<EventType> | EventListenerObject<EventType>;\n/**\n * EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget)\n */\ndeclare class EventTarget<EventMap extends Record<string, Event> = Record<string, Event>> {\n    constructor();\n    /**\n     * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.\n     *\n     * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.\n     *\n     * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.\n     *\n     * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.\n     *\n     * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.\n     *\n     * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.\n     *\n     * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener)\n     */\n    addEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;\n    /**\n     * Removes the event listener in target's event listener list with the same type, callback, and options.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener)\n     */\n    removeEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;\n    /**\n     * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)\n     */\n    dispatchEvent(event: EventMap[keyof EventMap]): boolean;\n}\ninterface EventTargetEventListenerOptions {\n    capture?: boolean;\n}\ninterface EventTargetAddEventListenerOptions {\n    capture?: boolean;\n    passive?: boolean;\n    once?: boolean;\n    signal?: AbortSignal;\n}\ninterface EventTargetHandlerObject {\n    handleEvent: (event: Event) => any | undefined;\n}\n/**\n * A controller object that allows you to abort one or more DOM requests as and when desired.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController)\n */\ndeclare class AbortController {\n    constructor();\n    /**\n     * Returns the AbortSignal object associated with this object.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal)\n     */\n    get signal(): AbortSignal;\n    /**\n     * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort)\n     */\n    abort(reason?: any): void;\n}\n/**\n * A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal)\n */\ndeclare abstract class AbortSignal extends EventTarget {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */\n    static abort(reason?: any): AbortSignal;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */\n    static timeout(delay: number): AbortSignal;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) */\n    static any(signals: AbortSignal[]): AbortSignal;\n    /**\n     * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted)\n     */\n    get aborted(): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */\n    get reason(): any;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */\n    get onabort(): any | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */\n    set onabort(value: any | null);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */\n    throwIfAborted(): void;\n}\ninterface Scheduler {\n    wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>;\n}\ninterface SchedulerWaitOptions {\n    signal?: AbortSignal;\n}\n/**\n * Extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent)\n */\ndeclare abstract class ExtendableEvent extends Event {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */\n    waitUntil(promise: Promise<any>): void;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */\ndeclare class CustomEvent<T = any> extends Event {\n    constructor(type: string, init?: CustomEventCustomEventInit);\n    /**\n     * Returns any custom data event was created with. Typically used for synthetic events.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail)\n     */\n    get detail(): T;\n}\ninterface CustomEventCustomEventInit {\n    bubbles?: boolean;\n    cancelable?: boolean;\n    composed?: boolean;\n    detail?: any;\n}\n/**\n * A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob)\n */\ndeclare class Blob {\n    constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */\n    get size(): number;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */\n    get type(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */\n    slice(start?: number, end?: number, type?: string): Blob;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */\n    arrayBuffer(): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) */\n    bytes(): Promise<Uint8Array>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */\n    text(): Promise<string>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */\n    stream(): ReadableStream;\n}\ninterface BlobOptions {\n    type?: string;\n}\n/**\n * Provides information about files and allows JavaScript in a web page to access their content.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File)\n */\ndeclare class File extends Blob {\n    constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */\n    get name(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */\n    get lastModified(): number;\n}\ninterface FileOptions {\n    type?: string;\n    lastModified?: number;\n}\n/**\n* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)\n*/\ndeclare abstract class CacheStorage {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */\n    open(cacheName: string): Promise<Cache>;\n    readonly default: Cache;\n}\n/**\n* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)\n*/\ndeclare abstract class Cache {\n    /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */\n    delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;\n    /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */\n    match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;\n    /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */\n    put(request: RequestInfo | URL, response: Response): Promise<void>;\n}\ninterface CacheQueryOptions {\n    ignoreMethod?: boolean;\n}\n/**\n* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.\n* The Workers runtime implements the full surface of this API, but with some differences in\n* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)\n* compared to those implemented in most browsers.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)\n*/\ndeclare abstract class Crypto {\n    /**\n     * Available only in secure contexts.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle)\n     */\n    get subtle(): SubtleCrypto;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */\n    getRandomValues<T extends Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | BigInt64Array | BigUint64Array>(buffer: T): T;\n    /**\n     * Available only in secure contexts.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID)\n     */\n    randomUUID(): string;\n    DigestStream: typeof DigestStream;\n}\n/**\n * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto).\n * Available only in secure contexts.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto)\n */\ndeclare abstract class SubtleCrypto {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) */\n    encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) */\n    decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) */\n    sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) */\n    verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise<boolean>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) */\n    digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */\n    generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey | CryptoKeyPair>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */\n    deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) */\n    deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */\n    importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) */\n    exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) */\n    wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */\n    unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;\n    timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean;\n}\n/**\n * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key.\n * Available only in secure contexts.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey)\n */\ndeclare abstract class CryptoKey {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */\n    readonly type: string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */\n    readonly extractable: boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */\n    readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */\n    readonly usages: string[];\n}\ninterface CryptoKeyPair {\n    publicKey: CryptoKey;\n    privateKey: CryptoKey;\n}\ninterface JsonWebKey {\n    kty: string;\n    use?: string;\n    key_ops?: string[];\n    alg?: string;\n    ext?: boolean;\n    crv?: string;\n    x?: string;\n    y?: string;\n    d?: string;\n    n?: string;\n    e?: string;\n    p?: string;\n    q?: string;\n    dp?: string;\n    dq?: string;\n    qi?: string;\n    oth?: RsaOtherPrimesInfo[];\n    k?: string;\n}\ninterface RsaOtherPrimesInfo {\n    r?: string;\n    d?: string;\n    t?: string;\n}\ninterface SubtleCryptoDeriveKeyAlgorithm {\n    name: string;\n    salt?: (ArrayBuffer | ArrayBufferView);\n    iterations?: number;\n    hash?: (string | SubtleCryptoHashAlgorithm);\n    $public?: CryptoKey;\n    info?: (ArrayBuffer | ArrayBufferView);\n}\ninterface SubtleCryptoEncryptAlgorithm {\n    name: string;\n    iv?: (ArrayBuffer | ArrayBufferView);\n    additionalData?: (ArrayBuffer | ArrayBufferView);\n    tagLength?: number;\n    counter?: (ArrayBuffer | ArrayBufferView);\n    length?: number;\n    label?: (ArrayBuffer | ArrayBufferView);\n}\ninterface SubtleCryptoGenerateKeyAlgorithm {\n    name: string;\n    hash?: (string | SubtleCryptoHashAlgorithm);\n    modulusLength?: number;\n    publicExponent?: (ArrayBuffer | ArrayBufferView);\n    length?: number;\n    namedCurve?: string;\n}\ninterface SubtleCryptoHashAlgorithm {\n    name: string;\n}\ninterface SubtleCryptoImportKeyAlgorithm {\n    name: string;\n    hash?: (string | SubtleCryptoHashAlgorithm);\n    length?: number;\n    namedCurve?: string;\n    compressed?: boolean;\n}\ninterface SubtleCryptoSignAlgorithm {\n    name: string;\n    hash?: (string | SubtleCryptoHashAlgorithm);\n    dataLength?: number;\n    saltLength?: number;\n}\ninterface CryptoKeyKeyAlgorithm {\n    name: string;\n}\ninterface CryptoKeyAesKeyAlgorithm {\n    name: string;\n    length: number;\n}\ninterface CryptoKeyHmacKeyAlgorithm {\n    name: string;\n    hash: CryptoKeyKeyAlgorithm;\n    length: number;\n}\ninterface CryptoKeyRsaKeyAlgorithm {\n    name: string;\n    modulusLength: number;\n    publicExponent: ArrayBuffer | ArrayBufferView;\n    hash?: CryptoKeyKeyAlgorithm;\n}\ninterface CryptoKeyEllipticKeyAlgorithm {\n    name: string;\n    namedCurve: string;\n}\ninterface CryptoKeyArbitraryKeyAlgorithm {\n    name: string;\n    hash?: CryptoKeyKeyAlgorithm;\n    namedCurve?: string;\n    length?: number;\n}\ndeclare class DigestStream extends WritableStream<ArrayBuffer | ArrayBufferView> {\n    constructor(algorithm: string | SubtleCryptoHashAlgorithm);\n    readonly digest: Promise<ArrayBuffer>;\n    get bytesWritten(): number | bigint;\n}\n/**\n * A decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, etc. A decoder takes a stream of bytes as input and emits a stream of code points. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder)\n */\ndeclare class TextDecoder {\n    constructor(label?: string, options?: TextDecoderConstructorOptions);\n    /**\n     * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments.\n     *\n     * ```\n     * var string = \"\", decoder = new TextDecoder(encoding), buffer;\n     * while(buffer = next_chunk()) {\n     *   string += decoder.decode(buffer, {stream:true});\n     * }\n     * string += decoder.decode(); // end-of-queue\n     * ```\n     *\n     * If the error mode is \"fatal\" and encoding's decoder returns error, throws a TypeError.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode)\n     */\n    decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string;\n    get encoding(): string;\n    get fatal(): boolean;\n    get ignoreBOM(): boolean;\n}\n/**\n * TextEncoder takes a stream of code points as input and emits a stream of bytes. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder)\n */\ndeclare class TextEncoder {\n    constructor();\n    /**\n     * Returns the result of running UTF-8's encoder.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode)\n     */\n    encode(input?: string): Uint8Array;\n    /**\n     * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto)\n     */\n    encodeInto(input: string, buffer: ArrayBuffer | ArrayBufferView): TextEncoderEncodeIntoResult;\n    get encoding(): string;\n}\ninterface TextDecoderConstructorOptions {\n    fatal: boolean;\n    ignoreBOM: boolean;\n}\ninterface TextDecoderDecodeOptions {\n    stream: boolean;\n}\ninterface TextEncoderEncodeIntoResult {\n    read: number;\n    written: number;\n}\n/**\n * Events providing information related to errors in scripts or in files.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent)\n */\ndeclare class ErrorEvent extends Event {\n    constructor(type: string, init?: ErrorEventErrorEventInit);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */\n    get filename(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */\n    get message(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */\n    get lineno(): number;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */\n    get colno(): number;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */\n    get error(): any;\n}\ninterface ErrorEventErrorEventInit {\n    message?: string;\n    filename?: string;\n    lineno?: number;\n    colno?: number;\n    error?: any;\n}\n/**\n * A message received by a target object.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent)\n */\ndeclare class MessageEvent extends Event {\n    constructor(type: string, initializer: MessageEventInit);\n    /**\n     * Returns the data of the message.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data)\n     */\n    readonly data: any;\n    /**\n     * Returns the origin of the message, for server-sent events and cross-document messaging.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin)\n     */\n    readonly origin: string | null;\n    /**\n     * Returns the last event ID string, for server-sent events.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId)\n     */\n    readonly lastEventId: string;\n    /**\n     * Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source)\n     */\n    readonly source: MessagePort | null;\n    /**\n     * Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports)\n     */\n    readonly ports: MessagePort[];\n}\ninterface MessageEventInit {\n    data: ArrayBuffer | string;\n}\n/**\n * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to \"multipart/form-data\".\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData)\n */\ndeclare class FormData {\n    constructor();\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */\n    append(name: string, value: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */\n    append(name: string, value: Blob, filename?: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) */\n    delete(name: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) */\n    get(name: string): (File | string) | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) */\n    getAll(name: string): (File | string)[];\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */\n    has(name: string): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */\n    set(name: string, value: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */\n    set(name: string, value: Blob, filename?: string): void;\n    /* Returns an array of key, value pairs for every entry in the list. */\n    entries(): IterableIterator<[\n        key: string,\n        value: File | string\n    ]>;\n    /* Returns a list of keys in the list. */\n    keys(): IterableIterator<string>;\n    /* Returns a list of values in the list. */\n    values(): IterableIterator<(File | string)>;\n    forEach<This = unknown>(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void;\n    [Symbol.iterator](): IterableIterator<[\n        key: string,\n        value: File | string\n    ]>;\n}\ninterface ContentOptions {\n    html?: boolean;\n}\ndeclare class HTMLRewriter {\n    constructor();\n    on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter;\n    onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter;\n    transform(response: Response): Response;\n}\ninterface HTMLRewriterElementContentHandlers {\n    element?(element: Element): void | Promise<void>;\n    comments?(comment: Comment): void | Promise<void>;\n    text?(element: Text): void | Promise<void>;\n}\ninterface HTMLRewriterDocumentContentHandlers {\n    doctype?(doctype: Doctype): void | Promise<void>;\n    comments?(comment: Comment): void | Promise<void>;\n    text?(text: Text): void | Promise<void>;\n    end?(end: DocumentEnd): void | Promise<void>;\n}\ninterface Doctype {\n    readonly name: string | null;\n    readonly publicId: string | null;\n    readonly systemId: string | null;\n}\ninterface Element {\n    tagName: string;\n    readonly attributes: IterableIterator<string[]>;\n    readonly removed: boolean;\n    readonly namespaceURI: string;\n    getAttribute(name: string): string | null;\n    hasAttribute(name: string): boolean;\n    setAttribute(name: string, value: string): Element;\n    removeAttribute(name: string): Element;\n    before(content: string | ReadableStream | Response, options?: ContentOptions): Element;\n    after(content: string | ReadableStream | Response, options?: ContentOptions): Element;\n    prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element;\n    append(content: string | ReadableStream | Response, options?: ContentOptions): Element;\n    replace(content: string | ReadableStream | Response, options?: ContentOptions): Element;\n    remove(): Element;\n    removeAndKeepContent(): Element;\n    setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element;\n    onEndTag(handler: (tag: EndTag) => void | Promise<void>): void;\n}\ninterface EndTag {\n    name: string;\n    before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;\n    after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;\n    remove(): EndTag;\n}\ninterface Comment {\n    text: string;\n    readonly removed: boolean;\n    before(content: string, options?: ContentOptions): Comment;\n    after(content: string, options?: ContentOptions): Comment;\n    replace(content: string, options?: ContentOptions): Comment;\n    remove(): Comment;\n}\ninterface Text {\n    readonly text: string;\n    readonly lastInTextNode: boolean;\n    readonly removed: boolean;\n    before(content: string | ReadableStream | Response, options?: ContentOptions): Text;\n    after(content: string | ReadableStream | Response, options?: ContentOptions): Text;\n    replace(content: string | ReadableStream | Response, options?: ContentOptions): Text;\n    remove(): Text;\n}\ninterface DocumentEnd {\n    append(content: string, options?: ContentOptions): DocumentEnd;\n}\n/**\n * This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent)\n */\ndeclare abstract class FetchEvent extends ExtendableEvent {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */\n    readonly request: Request;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */\n    respondWith(promise: Response | Promise<Response>): void;\n    passThroughOnException(): void;\n}\ntype HeadersInit = Headers | Iterable<Iterable<string>> | Record<string, string>;\n/**\n * This Fetch API interface allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.  You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers)\n */\ndeclare class Headers {\n    constructor(init?: HeadersInit);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) */\n    get(name: string): string | null;\n    getAll(name: string): string[];\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) */\n    getSetCookie(): string[];\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) */\n    has(name: string): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) */\n    set(name: string, value: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) */\n    append(name: string, value: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) */\n    delete(name: string): void;\n    forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void;\n    /* Returns an iterator allowing to go through all key/value pairs contained in this object. */\n    entries(): IterableIterator<[\n        key: string,\n        value: string\n    ]>;\n    /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */\n    keys(): IterableIterator<string>;\n    /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */\n    values(): IterableIterator<string>;\n    [Symbol.iterator](): IterableIterator<[\n        key: string,\n        value: string\n    ]>;\n}\ntype BodyInit = ReadableStream<Uint8Array> | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData;\ndeclare abstract class Body {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */\n    get body(): ReadableStream | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */\n    get bodyUsed(): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */\n    arrayBuffer(): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */\n    bytes(): Promise<Uint8Array>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */\n    text(): Promise<string>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */\n    json<T>(): Promise<T>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */\n    formData(): Promise<FormData>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */\n    blob(): Promise<Blob>;\n}\n/**\n * This Fetch API interface represents the response to a request.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)\n */\ndeclare var Response: {\n    prototype: Response;\n    new (body?: BodyInit | null, init?: ResponseInit): Response;\n    error(): Response;\n    redirect(url: string, status?: number): Response;\n    json(any: any, maybeInit?: (ResponseInit | Response)): Response;\n};\n/**\n * This Fetch API interface represents the response to a request.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)\n */\ninterface Response extends Body {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */\n    clone(): Response;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */\n    status: number;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */\n    statusText: string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */\n    headers: Headers;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */\n    ok: boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */\n    redirected: boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */\n    url: string;\n    webSocket: WebSocket | null;\n    cf: any | undefined;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) */\n    type: \"default\" | \"error\";\n}\ninterface ResponseInit {\n    status?: number;\n    statusText?: string;\n    headers?: HeadersInit;\n    cf?: any;\n    webSocket?: (WebSocket | null);\n    encodeBody?: \"automatic\" | \"manual\";\n}\ntype RequestInfo<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> = Request<CfHostMetadata, Cf> | string;\n/**\n * This Fetch API interface represents a resource request.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)\n */\ndeclare var Request: {\n    prototype: Request;\n    new <CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>>(input: RequestInfo<CfProperties> | URL, init?: RequestInit<Cf>): Request<CfHostMetadata, Cf>;\n};\n/**\n * This Fetch API interface represents a resource request.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)\n */\ninterface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> extends Body {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */\n    clone(): Request<CfHostMetadata, Cf>;\n    /**\n     * Returns request's HTTP method, which is \"GET\" by default.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method)\n     */\n    method: string;\n    /**\n     * Returns the URL of request as a string.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url)\n     */\n    url: string;\n    /**\n     * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the \"Host\" header.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers)\n     */\n    headers: Headers;\n    /**\n     * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect)\n     */\n    redirect: string;\n    fetcher: Fetcher | null;\n    /**\n     * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal)\n     */\n    signal: AbortSignal;\n    cf: Cf | undefined;\n    /**\n     * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI]\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity)\n     */\n    integrity: string;\n    /**\n     * Returns a boolean indicating whether or not request can outlive the global in which it was created.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive)\n     */\n    keepalive: boolean;\n    /**\n     * Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache)\n     */\n    cache?: \"no-store\" | \"no-cache\";\n}\ninterface RequestInit<Cf = CfProperties> {\n    /* A string to set request's method. */\n    method?: string;\n    /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */\n    headers?: HeadersInit;\n    /* A BodyInit object or null to set request's body. */\n    body?: BodyInit | null;\n    /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */\n    redirect?: string;\n    fetcher?: (Fetcher | null);\n    cf?: Cf;\n    /* A string indicating how the request will interact with the browser's cache to set request's cache. */\n    cache?: \"no-store\" | \"no-cache\";\n    /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */\n    integrity?: string;\n    /* An AbortSignal to set request's signal. */\n    signal?: (AbortSignal | null);\n    encodeResponseBody?: \"automatic\" | \"manual\";\n}\ntype Service<T extends (new (...args: any[]) => Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler<any, any, any> | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher<InstanceType<T>> : T extends Rpc.WorkerEntrypointBranded ? Fetcher<T> : T extends Exclude<Rpc.EntrypointBranded, Rpc.WorkerEntrypointBranded> ? never : Fetcher<undefined>;\ntype Fetcher<T extends Rpc.EntrypointBranded | undefined = undefined, Reserved extends string = never> = (T extends Rpc.EntrypointBranded ? Rpc.Provider<T, Reserved | \"fetch\" | \"connect\"> : unknown) & {\n    fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;\n    connect(address: SocketAddress | string, options?: SocketOptions): Socket;\n};\ninterface KVNamespaceListKey<Metadata, Key extends string = string> {\n    name: Key;\n    expiration?: number;\n    metadata?: Metadata;\n}\ntype KVNamespaceListResult<Metadata, Key extends string = string> = {\n    list_complete: false;\n    keys: KVNamespaceListKey<Metadata, Key>[];\n    cursor: string;\n    cacheStatus: string | null;\n} | {\n    list_complete: true;\n    keys: KVNamespaceListKey<Metadata, Key>[];\n    cacheStatus: string | null;\n};\ninterface KVNamespace<Key extends string = string> {\n    get(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<string | null>;\n    get(key: Key, type: \"text\"): Promise<string | null>;\n    get<ExpectedValue = unknown>(key: Key, type: \"json\"): Promise<ExpectedValue | null>;\n    get(key: Key, type: \"arrayBuffer\"): Promise<ArrayBuffer | null>;\n    get(key: Key, type: \"stream\"): Promise<ReadableStream | null>;\n    get(key: Key, options?: KVNamespaceGetOptions<\"text\">): Promise<string | null>;\n    get<ExpectedValue = unknown>(key: Key, options?: KVNamespaceGetOptions<\"json\">): Promise<ExpectedValue | null>;\n    get(key: Key, options?: KVNamespaceGetOptions<\"arrayBuffer\">): Promise<ArrayBuffer | null>;\n    get(key: Key, options?: KVNamespaceGetOptions<\"stream\">): Promise<ReadableStream | null>;\n    get(key: Array<Key>, type: \"text\"): Promise<Map<string, string | null>>;\n    get<ExpectedValue = unknown>(key: Array<Key>, type: \"json\"): Promise<Map<string, ExpectedValue | null>>;\n    get(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, string | null>>;\n    get(key: Array<Key>, options?: KVNamespaceGetOptions<\"text\">): Promise<Map<string, string | null>>;\n    get<ExpectedValue = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<\"json\">): Promise<Map<string, ExpectedValue | null>>;\n    list<Metadata = unknown>(options?: KVNamespaceListOptions): Promise<KVNamespaceListResult<Metadata, Key>>;\n    put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise<void>;\n    getWithMetadata<Metadata = unknown>(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Key, type: \"text\"): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;\n    getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, type: \"json\"): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Key, type: \"arrayBuffer\"): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Key, type: \"stream\"): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<\"text\">): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;\n    getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<\"json\">): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<\"arrayBuffer\">): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<\"stream\">): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Array<Key>, type: \"text\"): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;\n    getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, type: \"json\"): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;\n    getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;\n    getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<\"text\">): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;\n    getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<\"json\">): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;\n    delete(key: Key): Promise<void>;\n}\ninterface KVNamespaceListOptions {\n    limit?: number;\n    prefix?: (string | null);\n    cursor?: (string | null);\n}\ninterface KVNamespaceGetOptions<Type> {\n    type: Type;\n    cacheTtl?: number;\n}\ninterface KVNamespacePutOptions {\n    expiration?: number;\n    expirationTtl?: number;\n    metadata?: (any | null);\n}\ninterface KVNamespaceGetWithMetadataResult<Value, Metadata> {\n    value: Value | null;\n    metadata: Metadata | null;\n    cacheStatus: string | null;\n}\ntype QueueContentType = \"text\" | \"bytes\" | \"json\" | \"v8\";\ninterface Queue<Body = unknown> {\n    send(message: Body, options?: QueueSendOptions): Promise<void>;\n    sendBatch(messages: Iterable<MessageSendRequest<Body>>, options?: QueueSendBatchOptions): Promise<void>;\n}\ninterface QueueSendOptions {\n    contentType?: QueueContentType;\n    delaySeconds?: number;\n}\ninterface QueueSendBatchOptions {\n    delaySeconds?: number;\n}\ninterface MessageSendRequest<Body = unknown> {\n    body: Body;\n    contentType?: QueueContentType;\n    delaySeconds?: number;\n}\ninterface QueueRetryOptions {\n    delaySeconds?: number;\n}\ninterface Message<Body = unknown> {\n    readonly id: string;\n    readonly timestamp: Date;\n    readonly body: Body;\n    readonly attempts: number;\n    retry(options?: QueueRetryOptions): void;\n    ack(): void;\n}\ninterface QueueEvent<Body = unknown> extends ExtendableEvent {\n    readonly messages: readonly Message<Body>[];\n    readonly queue: string;\n    retryAll(options?: QueueRetryOptions): void;\n    ackAll(): void;\n}\ninterface MessageBatch<Body = unknown> {\n    readonly messages: readonly Message<Body>[];\n    readonly queue: string;\n    retryAll(options?: QueueRetryOptions): void;\n    ackAll(): void;\n}\ninterface R2Error extends Error {\n    readonly name: string;\n    readonly code: number;\n    readonly message: string;\n    readonly action: string;\n    readonly stack: any;\n}\ninterface R2ListOptions {\n    limit?: number;\n    prefix?: string;\n    cursor?: string;\n    delimiter?: string;\n    startAfter?: string;\n    include?: (\"httpMetadata\" | \"customMetadata\")[];\n}\ndeclare abstract class R2Bucket {\n    head(key: string): Promise<R2Object | null>;\n    get(key: string, options: R2GetOptions & {\n        onlyIf: R2Conditional | Headers;\n    }): Promise<R2ObjectBody | R2Object | null>;\n    get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>;\n    put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & {\n        onlyIf: R2Conditional | Headers;\n    }): Promise<R2Object | null>;\n    put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise<R2Object>;\n    createMultipartUpload(key: string, options?: R2MultipartOptions): Promise<R2MultipartUpload>;\n    resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload;\n    delete(keys: string | string[]): Promise<void>;\n    list(options?: R2ListOptions): Promise<R2Objects>;\n}\ninterface R2MultipartUpload {\n    readonly key: string;\n    readonly uploadId: string;\n    uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise<R2UploadedPart>;\n    abort(): Promise<void>;\n    complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>;\n}\ninterface R2UploadedPart {\n    partNumber: number;\n    etag: string;\n}\ndeclare abstract class R2Object {\n    readonly key: string;\n    readonly version: string;\n    readonly size: number;\n    readonly etag: string;\n    readonly httpEtag: string;\n    readonly checksums: R2Checksums;\n    readonly uploaded: Date;\n    readonly httpMetadata?: R2HTTPMetadata;\n    readonly customMetadata?: Record<string, string>;\n    readonly range?: R2Range;\n    readonly storageClass: string;\n    readonly ssecKeyMd5?: string;\n    writeHttpMetadata(headers: Headers): void;\n}\ninterface R2ObjectBody extends R2Object {\n    get body(): ReadableStream;\n    get bodyUsed(): boolean;\n    arrayBuffer(): Promise<ArrayBuffer>;\n    bytes(): Promise<Uint8Array>;\n    text(): Promise<string>;\n    json<T>(): Promise<T>;\n    blob(): Promise<Blob>;\n}\ntype R2Range = {\n    offset: number;\n    length?: number;\n} | {\n    offset?: number;\n    length: number;\n} | {\n    suffix: number;\n};\ninterface R2Conditional {\n    etagMatches?: string;\n    etagDoesNotMatch?: string;\n    uploadedBefore?: Date;\n    uploadedAfter?: Date;\n    secondsGranularity?: boolean;\n}\ninterface R2GetOptions {\n    onlyIf?: (R2Conditional | Headers);\n    range?: (R2Range | Headers);\n    ssecKey?: (ArrayBuffer | string);\n}\ninterface R2PutOptions {\n    onlyIf?: (R2Conditional | Headers);\n    httpMetadata?: (R2HTTPMetadata | Headers);\n    customMetadata?: Record<string, string>;\n    md5?: ((ArrayBuffer | ArrayBufferView) | string);\n    sha1?: ((ArrayBuffer | ArrayBufferView) | string);\n    sha256?: ((ArrayBuffer | ArrayBufferView) | string);\n    sha384?: ((ArrayBuffer | ArrayBufferView) | string);\n    sha512?: ((ArrayBuffer | ArrayBufferView) | string);\n    storageClass?: string;\n    ssecKey?: (ArrayBuffer | string);\n}\ninterface R2MultipartOptions {\n    httpMetadata?: (R2HTTPMetadata | Headers);\n    customMetadata?: Record<string, string>;\n    storageClass?: string;\n    ssecKey?: (ArrayBuffer | string);\n}\ninterface R2Checksums {\n    readonly md5?: ArrayBuffer;\n    readonly sha1?: ArrayBuffer;\n    readonly sha256?: ArrayBuffer;\n    readonly sha384?: ArrayBuffer;\n    readonly sha512?: ArrayBuffer;\n    toJSON(): R2StringChecksums;\n}\ninterface R2StringChecksums {\n    md5?: string;\n    sha1?: string;\n    sha256?: string;\n    sha384?: string;\n    sha512?: string;\n}\ninterface R2HTTPMetadata {\n    contentType?: string;\n    contentLanguage?: string;\n    contentDisposition?: string;\n    contentEncoding?: string;\n    cacheControl?: string;\n    cacheExpiry?: Date;\n}\ntype R2Objects = {\n    objects: R2Object[];\n    delimitedPrefixes: string[];\n} & ({\n    truncated: true;\n    cursor: string;\n} | {\n    truncated: false;\n});\ninterface R2UploadPartOptions {\n    ssecKey?: (ArrayBuffer | string);\n}\ndeclare abstract class ScheduledEvent extends ExtendableEvent {\n    readonly scheduledTime: number;\n    readonly cron: string;\n    noRetry(): void;\n}\ninterface ScheduledController {\n    readonly scheduledTime: number;\n    readonly cron: string;\n    noRetry(): void;\n}\ninterface QueuingStrategy<T = any> {\n    highWaterMark?: (number | bigint);\n    size?: (chunk: T) => number | bigint;\n}\ninterface UnderlyingSink<W = any> {\n    type?: string;\n    start?: (controller: WritableStreamDefaultController) => void | Promise<void>;\n    write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise<void>;\n    abort?: (reason: any) => void | Promise<void>;\n    close?: () => void | Promise<void>;\n}\ninterface UnderlyingByteSource {\n    type: \"bytes\";\n    autoAllocateChunkSize?: number;\n    start?: (controller: ReadableByteStreamController) => void | Promise<void>;\n    pull?: (controller: ReadableByteStreamController) => void | Promise<void>;\n    cancel?: (reason: any) => void | Promise<void>;\n}\ninterface UnderlyingSource<R = any> {\n    type?: \"\" | undefined;\n    start?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;\n    pull?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;\n    cancel?: (reason: any) => void | Promise<void>;\n    expectedLength?: (number | bigint);\n}\ninterface Transformer<I = any, O = any> {\n    readableType?: string;\n    writableType?: string;\n    start?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;\n    transform?: (chunk: I, controller: TransformStreamDefaultController<O>) => void | Promise<void>;\n    flush?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;\n    cancel?: (reason: any) => void | Promise<void>;\n    expectedLength?: number;\n}\ninterface StreamPipeOptions {\n    /**\n     * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.\n     *\n     * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n     *\n     * Errors and closures of the source and destination streams propagate as follows:\n     *\n     * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination.\n     *\n     * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source.\n     *\n     * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error.\n     *\n     * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source.\n     *\n     * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set.\n     */\n    preventClose?: boolean;\n    preventAbort?: boolean;\n    preventCancel?: boolean;\n    signal?: AbortSignal;\n}\ntype ReadableStreamReadResult<R = any> = {\n    done: false;\n    value: R;\n} | {\n    done: true;\n    value?: undefined;\n};\n/**\n * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)\n */\ninterface ReadableStream<R = any> {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */\n    get locked(): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */\n    cancel(reason?: any): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */\n    getReader(): ReadableStreamDefaultReader<R>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */\n    getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */\n    pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */\n    pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */\n    tee(): [\n        ReadableStream<R>,\n        ReadableStream<R>\n    ];\n    values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;\n    [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;\n}\n/**\n * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)\n */\ndeclare const ReadableStream: {\n    prototype: ReadableStream;\n    new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy<Uint8Array>): ReadableStream<Uint8Array>;\n    new <R = any>(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;\n};\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) */\ndeclare class ReadableStreamDefaultReader<R = any> {\n    constructor(stream: ReadableStream);\n    get closed(): Promise<void>;\n    cancel(reason?: any): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */\n    read(): Promise<ReadableStreamReadResult<R>>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */\n    releaseLock(): void;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */\ndeclare class ReadableStreamBYOBReader {\n    constructor(stream: ReadableStream);\n    get closed(): Promise<void>;\n    cancel(reason?: any): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */\n    read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamReadResult<T>>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */\n    releaseLock(): void;\n    readAtLeast<T extends ArrayBufferView>(minElements: number, view: T): Promise<ReadableStreamReadResult<T>>;\n}\ninterface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions {\n    min?: number;\n}\ninterface ReadableStreamGetReaderOptions {\n    /**\n     * Creates a ReadableStreamBYOBReader and locks the stream to the new reader.\n     *\n     * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation.\n     */\n    mode: \"byob\";\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */\ndeclare abstract class ReadableStreamBYOBRequest {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */\n    get view(): Uint8Array | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */\n    respond(bytesWritten: number): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */\n    respondWithNewView(view: ArrayBuffer | ArrayBufferView): void;\n    get atLeast(): number | null;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */\ndeclare abstract class ReadableStreamDefaultController<R = any> {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */\n    get desiredSize(): number | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */\n    close(): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */\n    enqueue(chunk?: R): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */\n    error(reason: any): void;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */\ndeclare abstract class ReadableByteStreamController {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */\n    get byobRequest(): ReadableStreamBYOBRequest | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */\n    get desiredSize(): number | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */\n    close(): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */\n    enqueue(chunk: ArrayBuffer | ArrayBufferView): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */\n    error(reason: any): void;\n}\n/**\n * This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController)\n */\ndeclare abstract class WritableStreamDefaultController {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */\n    get signal(): AbortSignal;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */\n    error(reason?: any): void;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */\ndeclare abstract class TransformStreamDefaultController<O = any> {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */\n    get desiredSize(): number | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */\n    enqueue(chunk?: O): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */\n    error(reason: any): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */\n    terminate(): void;\n}\ninterface ReadableWritablePair<R = any, W = any> {\n    /**\n     * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use.\n     *\n     * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n     */\n    writable: WritableStream<W>;\n    readable: ReadableStream<R>;\n}\n/**\n * This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream)\n */\ndeclare class WritableStream<W = any> {\n    constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */\n    get locked(): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */\n    abort(reason?: any): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */\n    close(): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */\n    getWriter(): WritableStreamDefaultWriter<W>;\n}\n/**\n * This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter)\n */\ndeclare class WritableStreamDefaultWriter<W = any> {\n    constructor(stream: WritableStream);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */\n    get closed(): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */\n    get ready(): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */\n    get desiredSize(): number | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */\n    abort(reason?: any): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */\n    close(): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */\n    write(chunk?: W): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */\n    releaseLock(): void;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) */\ndeclare class TransformStream<I = any, O = any> {\n    constructor(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */\n    get readable(): ReadableStream<O>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */\n    get writable(): WritableStream<I>;\n}\ndeclare class FixedLengthStream extends IdentityTransformStream {\n    constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy);\n}\ndeclare class IdentityTransformStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {\n    constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy);\n}\ninterface IdentityTransformStreamQueuingStrategy {\n    highWaterMark?: (number | bigint);\n}\ninterface ReadableStreamValuesOptions {\n    preventCancel?: boolean;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */\ndeclare class CompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {\n    constructor(format: \"gzip\" | \"deflate\" | \"deflate-raw\");\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */\ndeclare class DecompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {\n    constructor(format: \"gzip\" | \"deflate\" | \"deflate-raw\");\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) */\ndeclare class TextEncoderStream extends TransformStream<string, Uint8Array> {\n    constructor();\n    get encoding(): string;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) */\ndeclare class TextDecoderStream extends TransformStream<ArrayBuffer | ArrayBufferView, string> {\n    constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit);\n    get encoding(): string;\n    get fatal(): boolean;\n    get ignoreBOM(): boolean;\n}\ninterface TextDecoderStreamTextDecoderStreamInit {\n    fatal?: boolean;\n    ignoreBOM?: boolean;\n}\n/**\n * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy)\n */\ndeclare class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferView> {\n    constructor(init: QueuingStrategyInit);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */\n    get highWaterMark(): number;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */\n    get size(): (chunk?: any) => number;\n}\n/**\n * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy)\n */\ndeclare class CountQueuingStrategy implements QueuingStrategy {\n    constructor(init: QueuingStrategyInit);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */\n    get highWaterMark(): number;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */\n    get size(): (chunk?: any) => number;\n}\ninterface QueuingStrategyInit {\n    /**\n     * Creates a new ByteLengthQueuingStrategy with the provided high water mark.\n     *\n     * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw.\n     */\n    highWaterMark: number;\n}\ninterface ScriptVersion {\n    id?: string;\n    tag?: string;\n    message?: string;\n}\ndeclare abstract class TailEvent extends ExtendableEvent {\n    readonly events: TraceItem[];\n    readonly traces: TraceItem[];\n}\ninterface TraceItem {\n    readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null;\n    readonly eventTimestamp: number | null;\n    readonly logs: TraceLog[];\n    readonly exceptions: TraceException[];\n    readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[];\n    readonly scriptName: string | null;\n    readonly entrypoint?: string;\n    readonly scriptVersion?: ScriptVersion;\n    readonly dispatchNamespace?: string;\n    readonly scriptTags?: string[];\n    readonly durableObjectId?: string;\n    readonly outcome: string;\n    readonly executionModel: string;\n    readonly truncated: boolean;\n    readonly cpuTime: number;\n    readonly wallTime: number;\n}\ninterface TraceItemAlarmEventInfo {\n    readonly scheduledTime: Date;\n}\ninterface TraceItemCustomEventInfo {\n}\ninterface TraceItemScheduledEventInfo {\n    readonly scheduledTime: number;\n    readonly cron: string;\n}\ninterface TraceItemQueueEventInfo {\n    readonly queue: string;\n    readonly batchSize: number;\n}\ninterface TraceItemEmailEventInfo {\n    readonly mailFrom: string;\n    readonly rcptTo: string;\n    readonly rawSize: number;\n}\ninterface TraceItemTailEventInfo {\n    readonly consumedEvents: TraceItemTailEventInfoTailItem[];\n}\ninterface TraceItemTailEventInfoTailItem {\n    readonly scriptName: string | null;\n}\ninterface TraceItemFetchEventInfo {\n    readonly response?: TraceItemFetchEventInfoResponse;\n    readonly request: TraceItemFetchEventInfoRequest;\n}\ninterface TraceItemFetchEventInfoRequest {\n    readonly cf?: any;\n    readonly headers: Record<string, string>;\n    readonly method: string;\n    readonly url: string;\n    getUnredacted(): TraceItemFetchEventInfoRequest;\n}\ninterface TraceItemFetchEventInfoResponse {\n    readonly status: number;\n}\ninterface TraceItemJsRpcEventInfo {\n    readonly rpcMethod: string;\n}\ninterface TraceItemHibernatableWebSocketEventInfo {\n    readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError;\n}\ninterface TraceItemHibernatableWebSocketEventInfoMessage {\n    readonly webSocketEventType: string;\n}\ninterface TraceItemHibernatableWebSocketEventInfoClose {\n    readonly webSocketEventType: string;\n    readonly code: number;\n    readonly wasClean: boolean;\n}\ninterface TraceItemHibernatableWebSocketEventInfoError {\n    readonly webSocketEventType: string;\n}\ninterface TraceLog {\n    readonly timestamp: number;\n    readonly level: string;\n    readonly message: any;\n}\ninterface TraceException {\n    readonly timestamp: number;\n    readonly message: string;\n    readonly name: string;\n    readonly stack?: string;\n}\ninterface TraceDiagnosticChannelEvent {\n    readonly timestamp: number;\n    readonly channel: string;\n    readonly message: any;\n}\ninterface TraceMetrics {\n    readonly cpuTime: number;\n    readonly wallTime: number;\n}\ninterface UnsafeTraceMetrics {\n    fromTrace(item: TraceItem): TraceMetrics;\n}\n/**\n * The URL interface represents an object providing static methods used for creating object URLs.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL)\n */\ndeclare class URL {\n    constructor(url: string | URL, base?: string | URL);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */\n    get origin(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */\n    get href(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */\n    set href(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */\n    get protocol(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */\n    set protocol(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */\n    get username(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */\n    set username(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */\n    get password(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */\n    set password(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */\n    get host(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */\n    set host(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */\n    get hostname(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */\n    set hostname(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */\n    get port(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */\n    set port(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */\n    get pathname(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */\n    set pathname(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */\n    get search(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */\n    set search(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */\n    get hash(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */\n    set hash(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */\n    get searchParams(): URLSearchParams;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */\n    toJSON(): string;\n    /*function toString() { [native code] }*/\n    toString(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */\n    static canParse(url: string, base?: string): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) */\n    static parse(url: string, base?: string): URL | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) */\n    static createObjectURL(object: File | Blob): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) */\n    static revokeObjectURL(object_url: string): void;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) */\ndeclare class URLSearchParams {\n    constructor(init?: (Iterable<Iterable<string>> | Record<string, string> | string));\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) */\n    get size(): number;\n    /**\n     * Appends a specified key/value pair as a new search parameter.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append)\n     */\n    append(name: string, value: string): void;\n    /**\n     * Deletes the given search parameter, and its associated value, from the list of all search parameters.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete)\n     */\n    delete(name: string, value?: string): void;\n    /**\n     * Returns the first value associated to the given search parameter.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get)\n     */\n    get(name: string): string | null;\n    /**\n     * Returns all the values association with a given search parameter.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll)\n     */\n    getAll(name: string): string[];\n    /**\n     * Returns a Boolean indicating if such a search parameter exists.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has)\n     */\n    has(name: string, value?: string): boolean;\n    /**\n     * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set)\n     */\n    set(name: string, value: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) */\n    sort(): void;\n    /* Returns an array of key, value pairs for every entry in the search params. */\n    entries(): IterableIterator<[\n        key: string,\n        value: string\n    ]>;\n    /* Returns a list of keys in the search params. */\n    keys(): IterableIterator<string>;\n    /* Returns a list of values in the search params. */\n    values(): IterableIterator<string>;\n    forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void;\n    /*function toString() { [native code] } Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */\n    toString(): string;\n    [Symbol.iterator](): IterableIterator<[\n        key: string,\n        value: string\n    ]>;\n}\ndeclare class URLPattern {\n    constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions);\n    get protocol(): string;\n    get username(): string;\n    get password(): string;\n    get hostname(): string;\n    get port(): string;\n    get pathname(): string;\n    get search(): string;\n    get hash(): string;\n    get hasRegExpGroups(): boolean;\n    test(input?: (string | URLPatternInit), baseURL?: string): boolean;\n    exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null;\n}\ninterface URLPatternInit {\n    protocol?: string;\n    username?: string;\n    password?: string;\n    hostname?: string;\n    port?: string;\n    pathname?: string;\n    search?: string;\n    hash?: string;\n    baseURL?: string;\n}\ninterface URLPatternComponentResult {\n    input: string;\n    groups: Record<string, string>;\n}\ninterface URLPatternResult {\n    inputs: (string | URLPatternInit)[];\n    protocol: URLPatternComponentResult;\n    username: URLPatternComponentResult;\n    password: URLPatternComponentResult;\n    hostname: URLPatternComponentResult;\n    port: URLPatternComponentResult;\n    pathname: URLPatternComponentResult;\n    search: URLPatternComponentResult;\n    hash: URLPatternComponentResult;\n}\ninterface URLPatternOptions {\n    ignoreCase?: boolean;\n}\n/**\n * A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent)\n */\ndeclare class CloseEvent extends Event {\n    constructor(type: string, initializer?: CloseEventInit);\n    /**\n     * Returns the WebSocket connection close code provided by the server.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code)\n     */\n    readonly code: number;\n    /**\n     * Returns the WebSocket connection close reason provided by the server.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason)\n     */\n    readonly reason: string;\n    /**\n     * Returns true if the connection closed cleanly; false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean)\n     */\n    readonly wasClean: boolean;\n}\ninterface CloseEventInit {\n    code?: number;\n    reason?: string;\n    wasClean?: boolean;\n}\ntype WebSocketEventMap = {\n    close: CloseEvent;\n    message: MessageEvent;\n    open: Event;\n    error: ErrorEvent;\n};\n/**\n * Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)\n */\ndeclare var WebSocket: {\n    prototype: WebSocket;\n    new (url: string, protocols?: (string[] | string)): WebSocket;\n    readonly READY_STATE_CONNECTING: number;\n    readonly CONNECTING: number;\n    readonly READY_STATE_OPEN: number;\n    readonly OPEN: number;\n    readonly READY_STATE_CLOSING: number;\n    readonly CLOSING: number;\n    readonly READY_STATE_CLOSED: number;\n    readonly CLOSED: number;\n};\n/**\n * Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)\n */\ninterface WebSocket extends EventTarget<WebSocketEventMap> {\n    accept(): void;\n    /**\n     * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send)\n     */\n    send(message: (ArrayBuffer | ArrayBufferView) | string): void;\n    /**\n     * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close)\n     */\n    close(code?: number, reason?: string): void;\n    serializeAttachment(attachment: any): void;\n    deserializeAttachment(): any | null;\n    /**\n     * Returns the state of the WebSocket object's connection. It can have the values described below.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState)\n     */\n    readyState: number;\n    /**\n     * Returns the URL that was used to establish the WebSocket connection.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url)\n     */\n    url: string | null;\n    /**\n     * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol)\n     */\n    protocol: string | null;\n    /**\n     * Returns the extensions selected by the server, if any.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions)\n     */\n    extensions: string | null;\n}\ndeclare const WebSocketPair: {\n    new (): {\n        0: WebSocket;\n        1: WebSocket;\n    };\n};\ninterface SqlStorage {\n    exec<T extends Record<string, SqlStorageValue>>(query: string, ...bindings: any[]): SqlStorageCursor<T>;\n    get databaseSize(): number;\n    Cursor: typeof SqlStorageCursor;\n    Statement: typeof SqlStorageStatement;\n}\ndeclare abstract class SqlStorageStatement {\n}\ntype SqlStorageValue = ArrayBuffer | string | number | null;\ndeclare abstract class SqlStorageCursor<T extends Record<string, SqlStorageValue>> {\n    next(): {\n        done?: false;\n        value: T;\n    } | {\n        done: true;\n        value?: never;\n    };\n    toArray(): T[];\n    one(): T;\n    raw<U extends SqlStorageValue[]>(): IterableIterator<U>;\n    columnNames: string[];\n    get rowsRead(): number;\n    get rowsWritten(): number;\n    [Symbol.iterator](): IterableIterator<T>;\n}\ninterface Socket {\n    get readable(): ReadableStream;\n    get writable(): WritableStream;\n    get closed(): Promise<void>;\n    get opened(): Promise<SocketInfo>;\n    get upgraded(): boolean;\n    get secureTransport(): \"on\" | \"off\" | \"starttls\";\n    close(): Promise<void>;\n    startTls(options?: TlsOptions): Socket;\n}\ninterface SocketOptions {\n    secureTransport?: string;\n    allowHalfOpen: boolean;\n    highWaterMark?: (number | bigint);\n}\ninterface SocketAddress {\n    hostname: string;\n    port: number;\n}\ninterface TlsOptions {\n    expectedServerHostname?: string;\n}\ninterface SocketInfo {\n    remoteAddress?: string;\n    localAddress?: string;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) */\ndeclare class EventSource extends EventTarget {\n    constructor(url: string, init?: EventSourceEventSourceInit);\n    /**\n     * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)\n     */\n    close(): void;\n    /**\n     * Returns the URL providing the event stream.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)\n     */\n    get url(): string;\n    /**\n     * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to \"include\", and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)\n     */\n    get withCredentials(): boolean;\n    /**\n     * Returns the state of this EventSource object's connection. It can have the values described below.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)\n     */\n    get readyState(): number;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */\n    get onopen(): any | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */\n    set onopen(value: any | null);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */\n    get onmessage(): any | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */\n    set onmessage(value: any | null);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */\n    get onerror(): any | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */\n    set onerror(value: any | null);\n    static readonly CONNECTING: number;\n    static readonly OPEN: number;\n    static readonly CLOSED: number;\n    static from(stream: ReadableStream): EventSource;\n}\ninterface EventSourceEventSourceInit {\n    withCredentials?: boolean;\n    fetcher?: Fetcher;\n}\ninterface Container {\n    get running(): boolean;\n    start(options?: ContainerStartupOptions): void;\n    monitor(): Promise<void>;\n    destroy(error?: any): Promise<void>;\n    signal(signo: number): void;\n    getTcpPort(port: number): Fetcher;\n}\ninterface ContainerStartupOptions {\n    entrypoint?: string[];\n    enableInternet: boolean;\n    env?: Record<string, string>;\n}\n/**\n * This Channel Messaging API interface represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort)\n */\ndeclare abstract class MessagePort extends EventTarget {\n    /**\n     * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side.\n     *\n     * Throws a \"DataCloneError\" DOMException if transfer contains duplicate objects or port, or if message could not be cloned.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage)\n     */\n    postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void;\n    /**\n     * Disconnects the port, so that it is no longer active.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close)\n     */\n    close(): void;\n    /**\n     * Begins dispatching messages received on the port.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start)\n     */\n    start(): void;\n    get onmessage(): any | null;\n    set onmessage(value: any | null);\n}\n/**\n * This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel)\n */\ndeclare class MessageChannel {\n    constructor();\n    /**\n     * Returns the first MessagePort object.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1)\n     */\n    readonly port1: MessagePort;\n    /**\n     * Returns the second MessagePort object.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2)\n     */\n    readonly port2: MessagePort;\n}\ninterface MessagePortPostMessageOptions {\n    transfer?: any[];\n}\ntype LoopbackForExport<T extends (new (...args: any[]) => Rpc.EntrypointBranded) | ExportedHandler<any, any, any> | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub<InstanceType<T>> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass<InstanceType<T>> : T extends ExportedHandler<any, any, any> ? LoopbackServiceStub<undefined> : undefined;\ntype LoopbackServiceStub<T extends Rpc.WorkerEntrypointBranded | undefined = undefined> = Fetcher<T> & (T extends CloudflareWorkersModule.WorkerEntrypoint<any, infer Props> ? (opts: {\n    props?: Props;\n}) => Fetcher<T> : (opts: {\n    props?: any;\n}) => Fetcher<T>);\ntype LoopbackDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined = undefined> = DurableObjectClass<T> & (T extends CloudflareWorkersModule.DurableObject<any, infer Props> ? (opts: {\n    props?: Props;\n}) => DurableObjectClass<T> : (opts: {\n    props?: any;\n}) => DurableObjectClass<T>);\ninterface SyncKvStorage {\n    get<T = unknown>(key: string): T | undefined;\n    list<T = unknown>(options?: SyncKvListOptions): Iterable<[\n        string,\n        T\n    ]>;\n    put<T>(key: string, value: T): void;\n    delete(key: string): boolean;\n}\ninterface SyncKvListOptions {\n    start?: string;\n    startAfter?: string;\n    end?: string;\n    prefix?: string;\n    reverse?: boolean;\n    limit?: number;\n}\ninterface WorkerStub {\n    getEntrypoint<T extends Rpc.WorkerEntrypointBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): Fetcher<T>;\n}\ninterface WorkerStubEntrypointOptions {\n    props?: any;\n}\ninterface WorkerLoader {\n    get(name: string, getCode: () => WorkerLoaderWorkerCode | Promise<WorkerLoaderWorkerCode>): WorkerStub;\n}\ninterface WorkerLoaderModule {\n    js?: string;\n    cjs?: string;\n    text?: string;\n    data?: ArrayBuffer;\n    json?: any;\n    py?: string;\n}\ninterface WorkerLoaderWorkerCode {\n    compatibilityDate: string;\n    compatibilityFlags?: string[];\n    allowExperimental?: boolean;\n    mainModule: string;\n    modules: Record<string, WorkerLoaderModule | string>;\n    env?: any;\n    globalOutbound?: (Fetcher | null);\n    tails?: Fetcher[];\n    streamingTails?: Fetcher[];\n}\n/**\n* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,\n* as well as timing of subrequests and other operations.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)\n*/\ndeclare abstract class Performance {\n    /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */\n    get timeOrigin(): number;\n    /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */\n    now(): number;\n}\ntype AiImageClassificationInput = {\n    image: number[];\n};\ntype AiImageClassificationOutput = {\n    score?: number;\n    label?: string;\n}[];\ndeclare abstract class BaseAiImageClassification {\n    inputs: AiImageClassificationInput;\n    postProcessedOutputs: AiImageClassificationOutput;\n}\ntype AiImageToTextInput = {\n    image: number[];\n    prompt?: string;\n    max_tokens?: number;\n    temperature?: number;\n    top_p?: number;\n    top_k?: number;\n    seed?: number;\n    repetition_penalty?: number;\n    frequency_penalty?: number;\n    presence_penalty?: number;\n    raw?: boolean;\n    messages?: RoleScopedChatInput[];\n};\ntype AiImageToTextOutput = {\n    description: string;\n};\ndeclare abstract class BaseAiImageToText {\n    inputs: AiImageToTextInput;\n    postProcessedOutputs: AiImageToTextOutput;\n}\ntype AiImageTextToTextInput = {\n    image: string;\n    prompt?: string;\n    max_tokens?: number;\n    temperature?: number;\n    ignore_eos?: boolean;\n    top_p?: number;\n    top_k?: number;\n    seed?: number;\n    repetition_penalty?: number;\n    frequency_penalty?: number;\n    presence_penalty?: number;\n    raw?: boolean;\n    messages?: RoleScopedChatInput[];\n};\ntype AiImageTextToTextOutput = {\n    description: string;\n};\ndeclare abstract class BaseAiImageTextToText {\n    inputs: AiImageTextToTextInput;\n    postProcessedOutputs: AiImageTextToTextOutput;\n}\ntype AiMultimodalEmbeddingsInput = {\n    image: string;\n    text: string[];\n};\ntype AiIMultimodalEmbeddingsOutput = {\n    data: number[][];\n    shape: number[];\n};\ndeclare abstract class BaseAiMultimodalEmbeddings {\n    inputs: AiImageTextToTextInput;\n    postProcessedOutputs: AiImageTextToTextOutput;\n}\ntype AiObjectDetectionInput = {\n    image: number[];\n};\ntype AiObjectDetectionOutput = {\n    score?: number;\n    label?: string;\n}[];\ndeclare abstract class BaseAiObjectDetection {\n    inputs: AiObjectDetectionInput;\n    postProcessedOutputs: AiObjectDetectionOutput;\n}\ntype AiSentenceSimilarityInput = {\n    source: string;\n    sentences: string[];\n};\ntype AiSentenceSimilarityOutput = number[];\ndeclare abstract class BaseAiSentenceSimilarity {\n    inputs: AiSentenceSimilarityInput;\n    postProcessedOutputs: AiSentenceSimilarityOutput;\n}\ntype AiAutomaticSpeechRecognitionInput = {\n    audio: number[];\n};\ntype AiAutomaticSpeechRecognitionOutput = {\n    text?: string;\n    words?: {\n        word: string;\n        start: number;\n        end: number;\n    }[];\n    vtt?: string;\n};\ndeclare abstract class BaseAiAutomaticSpeechRecognition {\n    inputs: AiAutomaticSpeechRecognitionInput;\n    postProcessedOutputs: AiAutomaticSpeechRecognitionOutput;\n}\ntype AiSummarizationInput = {\n    input_text: string;\n    max_length?: number;\n};\ntype AiSummarizationOutput = {\n    summary: string;\n};\ndeclare abstract class BaseAiSummarization {\n    inputs: AiSummarizationInput;\n    postProcessedOutputs: AiSummarizationOutput;\n}\ntype AiTextClassificationInput = {\n    text: string;\n};\ntype AiTextClassificationOutput = {\n    score?: number;\n    label?: string;\n}[];\ndeclare abstract class BaseAiTextClassification {\n    inputs: AiTextClassificationInput;\n    postProcessedOutputs: AiTextClassificationOutput;\n}\ntype AiTextEmbeddingsInput = {\n    text: string | string[];\n};\ntype AiTextEmbeddingsOutput = {\n    shape: number[];\n    data: number[][];\n};\ndeclare abstract class BaseAiTextEmbeddings {\n    inputs: AiTextEmbeddingsInput;\n    postProcessedOutputs: AiTextEmbeddingsOutput;\n}\ntype RoleScopedChatInput = {\n    role: \"user\" | \"assistant\" | \"system\" | \"tool\" | (string & NonNullable<unknown>);\n    content: string;\n    name?: string;\n};\ntype AiTextGenerationToolLegacyInput = {\n    name: string;\n    description: string;\n    parameters?: {\n        type: \"object\" | (string & NonNullable<unknown>);\n        properties: {\n            [key: string]: {\n                type: string;\n                description?: string;\n            };\n        };\n        required: string[];\n    };\n};\ntype AiTextGenerationToolInput = {\n    type: \"function\" | (string & NonNullable<unknown>);\n    function: {\n        name: string;\n        description: string;\n        parameters?: {\n            type: \"object\" | (string & NonNullable<unknown>);\n            properties: {\n                [key: string]: {\n                    type: string;\n                    description?: string;\n                };\n            };\n            required: string[];\n        };\n    };\n};\ntype AiTextGenerationFunctionsInput = {\n    name: string;\n    code: string;\n};\ntype AiTextGenerationResponseFormat = {\n    type: string;\n    json_schema?: any;\n};\ntype AiTextGenerationInput = {\n    prompt?: string;\n    raw?: boolean;\n    stream?: boolean;\n    max_tokens?: number;\n    temperature?: number;\n    top_p?: number;\n    top_k?: number;\n    seed?: number;\n    repetition_penalty?: number;\n    frequency_penalty?: number;\n    presence_penalty?: number;\n    messages?: RoleScopedChatInput[];\n    response_format?: AiTextGenerationResponseFormat;\n    tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable<unknown>);\n    functions?: AiTextGenerationFunctionsInput[];\n};\ntype AiTextGenerationToolLegacyOutput = {\n    name: string;\n    arguments: unknown;\n};\ntype AiTextGenerationToolOutput = {\n    id: string;\n    type: \"function\";\n    function: {\n        name: string;\n        arguments: string;\n    };\n};\ntype UsageTags = {\n    prompt_tokens: number;\n    completion_tokens: number;\n    total_tokens: number;\n};\ntype AiTextGenerationOutput = {\n    response?: string;\n    tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[];\n    usage?: UsageTags;\n};\ndeclare abstract class BaseAiTextGeneration {\n    inputs: AiTextGenerationInput;\n    postProcessedOutputs: AiTextGenerationOutput;\n}\ntype AiTextToSpeechInput = {\n    prompt: string;\n    lang?: string;\n};\ntype AiTextToSpeechOutput = Uint8Array | {\n    audio: string;\n};\ndeclare abstract class BaseAiTextToSpeech {\n    inputs: AiTextToSpeechInput;\n    postProcessedOutputs: AiTextToSpeechOutput;\n}\ntype AiTextToImageInput = {\n    prompt: string;\n    negative_prompt?: string;\n    height?: number;\n    width?: number;\n    image?: number[];\n    image_b64?: string;\n    mask?: number[];\n    num_steps?: number;\n    strength?: number;\n    guidance?: number;\n    seed?: number;\n};\ntype AiTextToImageOutput = ReadableStream<Uint8Array>;\ndeclare abstract class BaseAiTextToImage {\n    inputs: AiTextToImageInput;\n    postProcessedOutputs: AiTextToImageOutput;\n}\ntype AiTranslationInput = {\n    text: string;\n    target_lang: string;\n    source_lang?: string;\n};\ntype AiTranslationOutput = {\n    translated_text?: string;\n};\ndeclare abstract class BaseAiTranslation {\n    inputs: AiTranslationInput;\n    postProcessedOutputs: AiTranslationOutput;\n}\ntype Ai_Cf_Baai_Bge_Base_En_V1_5_Input = {\n    text: string | string[];\n    /**\n     * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.\n     */\n    pooling?: \"mean\" | \"cls\";\n} | {\n    /**\n     * Batch of the embeddings requests to run using async-queue\n     */\n    requests: {\n        text: string | string[];\n        /**\n         * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.\n         */\n        pooling?: \"mean\" | \"cls\";\n    }[];\n};\ntype Ai_Cf_Baai_Bge_Base_En_V1_5_Output = {\n    shape?: number[];\n    /**\n     * Embeddings of the requested text values\n     */\n    data?: number[][];\n    /**\n     * The pooling method used in the embedding process.\n     */\n    pooling?: \"mean\" | \"cls\";\n} | AsyncResponse;\ninterface AsyncResponse {\n    /**\n     * The async request id that can be used to obtain the results.\n     */\n    request_id?: string;\n}\ndeclare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 {\n    inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input;\n    postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output;\n}\ntype Ai_Cf_Openai_Whisper_Input = string | {\n    /**\n     * An array of integers that represent the audio data constrained to 8-bit unsigned integer values\n     */\n    audio: number[];\n};\ninterface Ai_Cf_Openai_Whisper_Output {\n    /**\n     * The transcription\n     */\n    text: string;\n    word_count?: number;\n    words?: {\n        word?: string;\n        /**\n         * The second this word begins in the recording\n         */\n        start?: number;\n        /**\n         * The ending second when the word completes\n         */\n        end?: number;\n    }[];\n    vtt?: string;\n}\ndeclare abstract class Base_Ai_Cf_Openai_Whisper {\n    inputs: Ai_Cf_Openai_Whisper_Input;\n    postProcessedOutputs: Ai_Cf_Openai_Whisper_Output;\n}\ntype Ai_Cf_Meta_M2M100_1_2B_Input = {\n    /**\n     * The text to be translated\n     */\n    text: string;\n    /**\n     * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified\n     */\n    source_lang?: string;\n    /**\n     * The language code to translate the text into (e.g., 'es' for Spanish)\n     */\n    target_lang: string;\n} | {\n    /**\n     * Batch of the embeddings requests to run using async-queue\n     */\n    requests: {\n        /**\n         * The text to be translated\n         */\n        text: string;\n        /**\n         * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified\n         */\n        source_lang?: string;\n        /**\n         * The language code to translate the text into (e.g., 'es' for Spanish)\n         */\n        target_lang: string;\n    }[];\n};\ntype Ai_Cf_Meta_M2M100_1_2B_Output = {\n    /**\n     * The translated text in the target language\n     */\n    translated_text?: string;\n} | AsyncResponse;\ndeclare abstract class Base_Ai_Cf_Meta_M2M100_1_2B {\n    inputs: Ai_Cf_Meta_M2M100_1_2B_Input;\n    postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output;\n}\ntype Ai_Cf_Baai_Bge_Small_En_V1_5_Input = {\n    text: string | string[];\n    /**\n     * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.\n     */\n    pooling?: \"mean\" | \"cls\";\n} | {\n    /**\n     * Batch of the embeddings requests to run using async-queue\n     */\n    requests: {\n        text: string | string[];\n        /**\n         * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.\n         */\n        pooling?: \"mean\" | \"cls\";\n    }[];\n};\ntype Ai_Cf_Baai_Bge_Small_En_V1_5_Output = {\n    shape?: number[];\n    /**\n     * Embeddings of the requested text values\n     */\n    data?: number[][];\n    /**\n     * The pooling method used in the embedding process.\n     */\n    pooling?: \"mean\" | \"cls\";\n} | AsyncResponse;\ndeclare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 {\n    inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input;\n    postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output;\n}\ntype Ai_Cf_Baai_Bge_Large_En_V1_5_Input = {\n    text: string | string[];\n    /**\n     * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.\n     */\n    pooling?: \"mean\" | \"cls\";\n} | {\n    /**\n     * Batch of the embeddings requests to run using async-queue\n     */\n    requests: {\n        text: string | string[];\n        /**\n         * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.\n         */\n        pooling?: \"mean\" | \"cls\";\n    }[];\n};\ntype Ai_Cf_Baai_Bge_Large_En_V1_5_Output = {\n    shape?: number[];\n    /**\n     * Embeddings of the requested text values\n     */\n    data?: number[][];\n    /**\n     * The pooling method used in the embedding process.\n     */\n    pooling?: \"mean\" | \"cls\";\n} | AsyncResponse;\ndeclare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 {\n    inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input;\n    postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output;\n}\ntype Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | {\n    /**\n     * The input text prompt for the model to generate a response.\n     */\n    prompt?: string;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n    image: number[] | (string & NonNullable<unknown>);\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n};\ninterface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output {\n    description?: string;\n}\ndeclare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M {\n    inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input;\n    postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output;\n}\ntype Ai_Cf_Openai_Whisper_Tiny_En_Input = string | {\n    /**\n     * An array of integers that represent the audio data constrained to 8-bit unsigned integer values\n     */\n    audio: number[];\n};\ninterface Ai_Cf_Openai_Whisper_Tiny_En_Output {\n    /**\n     * The transcription\n     */\n    text: string;\n    word_count?: number;\n    words?: {\n        word?: string;\n        /**\n         * The second this word begins in the recording\n         */\n        start?: number;\n        /**\n         * The ending second when the word completes\n         */\n        end?: number;\n    }[];\n    vtt?: string;\n}\ndeclare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En {\n    inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input;\n    postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output;\n}\ninterface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input {\n    /**\n     * Base64 encoded value of the audio data.\n     */\n    audio: string;\n    /**\n     * Supported tasks are 'translate' or 'transcribe'.\n     */\n    task?: string;\n    /**\n     * The language of the audio being transcribed or translated.\n     */\n    language?: string;\n    /**\n     * Preprocess the audio with a voice activity detection model.\n     */\n    vad_filter?: boolean;\n    /**\n     * A text prompt to help provide context to the model on the contents of the audio.\n     */\n    initial_prompt?: string;\n    /**\n     * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result.\n     */\n    prefix?: string;\n}\ninterface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output {\n    transcription_info?: {\n        /**\n         * The language of the audio being transcribed or translated.\n         */\n        language?: string;\n        /**\n         * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1.\n         */\n        language_probability?: number;\n        /**\n         * The total duration of the original audio file, in seconds.\n         */\n        duration?: number;\n        /**\n         * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds.\n         */\n        duration_after_vad?: number;\n    };\n    /**\n     * The complete transcription of the audio.\n     */\n    text: string;\n    /**\n     * The total number of words in the transcription.\n     */\n    word_count?: number;\n    segments?: {\n        /**\n         * The starting time of the segment within the audio, in seconds.\n         */\n        start?: number;\n        /**\n         * The ending time of the segment within the audio, in seconds.\n         */\n        end?: number;\n        /**\n         * The transcription of the segment.\n         */\n        text?: string;\n        /**\n         * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs.\n         */\n        temperature?: number;\n        /**\n         * The average log probability of the predictions for the words in this segment, indicating overall confidence.\n         */\n        avg_logprob?: number;\n        /**\n         * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process.\n         */\n        compression_ratio?: number;\n        /**\n         * The probability that the segment contains no speech, represented as a decimal between 0 and 1.\n         */\n        no_speech_prob?: number;\n        words?: {\n            /**\n             * The individual word transcribed from the audio.\n             */\n            word?: string;\n            /**\n             * The starting time of the word within the audio, in seconds.\n             */\n            start?: number;\n            /**\n             * The ending time of the word within the audio, in seconds.\n             */\n            end?: number;\n        }[];\n    }[];\n    /**\n     * The transcription in WebVTT format, which includes timing and text information for use in subtitles.\n     */\n    vtt?: string;\n}\ndeclare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo {\n    inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input;\n    postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output;\n}\ntype Ai_Cf_Baai_Bge_M3_Input = BGEM3InputQueryAndContexts | BGEM3InputEmbedding | {\n    /**\n     * Batch of the embeddings requests to run using async-queue\n     */\n    requests: (BGEM3InputQueryAndContexts1 | BGEM3InputEmbedding1)[];\n};\ninterface BGEM3InputQueryAndContexts {\n    /**\n     * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts\n     */\n    query?: string;\n    /**\n     * List of provided contexts. Note that the index in this array is important, as the response will refer to it.\n     */\n    contexts: {\n        /**\n         * One of the provided context content\n         */\n        text?: string;\n    }[];\n    /**\n     * When provided with too long context should the model error out or truncate the context to fit?\n     */\n    truncate_inputs?: boolean;\n}\ninterface BGEM3InputEmbedding {\n    text: string | string[];\n    /**\n     * When provided with too long context should the model error out or truncate the context to fit?\n     */\n    truncate_inputs?: boolean;\n}\ninterface BGEM3InputQueryAndContexts1 {\n    /**\n     * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts\n     */\n    query?: string;\n    /**\n     * List of provided contexts. Note that the index in this array is important, as the response will refer to it.\n     */\n    contexts: {\n        /**\n         * One of the provided context content\n         */\n        text?: string;\n    }[];\n    /**\n     * When provided with too long context should the model error out or truncate the context to fit?\n     */\n    truncate_inputs?: boolean;\n}\ninterface BGEM3InputEmbedding1 {\n    text: string | string[];\n    /**\n     * When provided with too long context should the model error out or truncate the context to fit?\n     */\n    truncate_inputs?: boolean;\n}\ntype Ai_Cf_Baai_Bge_M3_Output = BGEM3OuputQuery | BGEM3OutputEmbeddingForContexts | BGEM3OuputEmbedding | AsyncResponse;\ninterface BGEM3OuputQuery {\n    response?: {\n        /**\n         * Index of the context in the request\n         */\n        id?: number;\n        /**\n         * Score of the context under the index.\n         */\n        score?: number;\n    }[];\n}\ninterface BGEM3OutputEmbeddingForContexts {\n    response?: number[][];\n    shape?: number[];\n    /**\n     * The pooling method used in the embedding process.\n     */\n    pooling?: \"mean\" | \"cls\";\n}\ninterface BGEM3OuputEmbedding {\n    shape?: number[];\n    /**\n     * Embeddings of the requested text values\n     */\n    data?: number[][];\n    /**\n     * The pooling method used in the embedding process.\n     */\n    pooling?: \"mean\" | \"cls\";\n}\ndeclare abstract class Base_Ai_Cf_Baai_Bge_M3 {\n    inputs: Ai_Cf_Baai_Bge_M3_Input;\n    postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output;\n}\ninterface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input {\n    /**\n     * A text description of the image you want to generate.\n     */\n    prompt: string;\n    /**\n     * The number of diffusion steps; higher values can improve quality but take longer.\n     */\n    steps?: number;\n}\ninterface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output {\n    /**\n     * The generated image in Base64 format.\n     */\n    image?: string;\n}\ndeclare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell {\n    inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input;\n    postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output;\n}\ntype Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages;\ninterface Prompt {\n    /**\n     * The input text prompt for the model to generate a response.\n     */\n    prompt: string;\n    image?: number[] | (string & NonNullable<unknown>);\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n    /**\n     * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.\n     */\n    lora?: string;\n}\ninterface Messages {\n    /**\n     * An array of message objects representing the conversation history.\n     */\n    messages: {\n        /**\n         * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').\n         */\n        role?: string;\n        /**\n         * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001\n         */\n        tool_call_id?: string;\n        content?: string | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        }[] | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        };\n    }[];\n    image?: number[] | (string & NonNullable<unknown>);\n    functions?: {\n        name: string;\n        code: string;\n    }[];\n    /**\n     * A list of tools available for the assistant to use.\n     */\n    tools?: ({\n        /**\n         * The name of the tool. More descriptive the better.\n         */\n        name: string;\n        /**\n         * A brief description of what the tool does.\n         */\n        description: string;\n        /**\n         * Schema defining the parameters accepted by the tool.\n         */\n        parameters: {\n            /**\n             * The type of the parameters object (usually 'object').\n             */\n            type: string;\n            /**\n             * List of required parameter names.\n             */\n            required?: string[];\n            /**\n             * Definitions of each parameter.\n             */\n            properties: {\n                [k: string]: {\n                    /**\n                     * The data type of the parameter.\n                     */\n                    type: string;\n                    /**\n                     * A description of the expected parameter.\n                     */\n                    description: string;\n                };\n            };\n        };\n    } | {\n        /**\n         * Specifies the type of tool (e.g., 'function').\n         */\n        type: string;\n        /**\n         * Details of the function tool.\n         */\n        function: {\n            /**\n             * The name of the function.\n             */\n            name: string;\n            /**\n             * A brief description of what the function does.\n             */\n            description: string;\n            /**\n             * Schema defining the parameters accepted by the function.\n             */\n            parameters: {\n                /**\n                 * The type of the parameters object (usually 'object').\n                 */\n                type: string;\n                /**\n                 * List of required parameter names.\n                 */\n                required?: string[];\n                /**\n                 * Definitions of each parameter.\n                 */\n                properties: {\n                    [k: string]: {\n                        /**\n                         * The data type of the parameter.\n                         */\n                        type: string;\n                        /**\n                         * A description of the expected parameter.\n                         */\n                        description: string;\n                    };\n                };\n            };\n        };\n    })[];\n    /**\n     * If true, the response will be streamed back incrementally.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ntype Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = {\n    /**\n     * The generated text response from the model\n     */\n    response?: string;\n    /**\n     * An array of tool calls requests made during the response generation\n     */\n    tool_calls?: {\n        /**\n         * The arguments passed to be passed to the tool call request\n         */\n        arguments?: object;\n        /**\n         * The name of the tool to be called\n         */\n        name?: string;\n    }[];\n};\ndeclare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct {\n    inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input;\n    postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output;\n}\ntype Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | AsyncBatch;\ninterface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt {\n    /**\n     * The input text prompt for the model to generate a response.\n     */\n    prompt: string;\n    /**\n     * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.\n     */\n    lora?: string;\n    response_format?: JSONMode;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ninterface JSONMode {\n    type?: \"json_object\" | \"json_schema\";\n    json_schema?: unknown;\n}\ninterface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages {\n    /**\n     * An array of message objects representing the conversation history.\n     */\n    messages: {\n        /**\n         * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').\n         */\n        role: string;\n        /**\n         * The content of the message as a string.\n         */\n        content: string;\n    }[];\n    functions?: {\n        name: string;\n        code: string;\n    }[];\n    /**\n     * A list of tools available for the assistant to use.\n     */\n    tools?: ({\n        /**\n         * The name of the tool. More descriptive the better.\n         */\n        name: string;\n        /**\n         * A brief description of what the tool does.\n         */\n        description: string;\n        /**\n         * Schema defining the parameters accepted by the tool.\n         */\n        parameters: {\n            /**\n             * The type of the parameters object (usually 'object').\n             */\n            type: string;\n            /**\n             * List of required parameter names.\n             */\n            required?: string[];\n            /**\n             * Definitions of each parameter.\n             */\n            properties: {\n                [k: string]: {\n                    /**\n                     * The data type of the parameter.\n                     */\n                    type: string;\n                    /**\n                     * A description of the expected parameter.\n                     */\n                    description: string;\n                };\n            };\n        };\n    } | {\n        /**\n         * Specifies the type of tool (e.g., 'function').\n         */\n        type: string;\n        /**\n         * Details of the function tool.\n         */\n        function: {\n            /**\n             * The name of the function.\n             */\n            name: string;\n            /**\n             * A brief description of what the function does.\n             */\n            description: string;\n            /**\n             * Schema defining the parameters accepted by the function.\n             */\n            parameters: {\n                /**\n                 * The type of the parameters object (usually 'object').\n                 */\n                type: string;\n                /**\n                 * List of required parameter names.\n                 */\n                required?: string[];\n                /**\n                 * Definitions of each parameter.\n                 */\n                properties: {\n                    [k: string]: {\n                        /**\n                         * The data type of the parameter.\n                         */\n                        type: string;\n                        /**\n                         * A description of the expected parameter.\n                         */\n                        description: string;\n                    };\n                };\n            };\n        };\n    })[];\n    response_format?: JSONMode;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ninterface AsyncBatch {\n    requests?: {\n        /**\n         * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique.\n         */\n        external_reference?: string;\n        /**\n         * Prompt for the text generation model\n         */\n        prompt?: string;\n        /**\n         * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n         */\n        stream?: boolean;\n        /**\n         * The maximum number of tokens to generate in the response.\n         */\n        max_tokens?: number;\n        /**\n         * Controls the randomness of the output; higher values produce more random results.\n         */\n        temperature?: number;\n        /**\n         * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n         */\n        top_p?: number;\n        /**\n         * Random seed for reproducibility of the generation.\n         */\n        seed?: number;\n        /**\n         * Penalty for repeated tokens; higher values discourage repetition.\n         */\n        repetition_penalty?: number;\n        /**\n         * Decreases the likelihood of the model repeating the same lines verbatim.\n         */\n        frequency_penalty?: number;\n        /**\n         * Increases the likelihood of the model introducing new topics.\n         */\n        presence_penalty?: number;\n        response_format?: JSONMode;\n    }[];\n}\ntype Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = {\n    /**\n     * The generated text response from the model\n     */\n    response: string;\n    /**\n     * Usage statistics for the inference request\n     */\n    usage?: {\n        /**\n         * Total number of tokens in input\n         */\n        prompt_tokens?: number;\n        /**\n         * Total number of tokens in output\n         */\n        completion_tokens?: number;\n        /**\n         * Total number of input and output tokens\n         */\n        total_tokens?: number;\n    };\n    /**\n     * An array of tool calls requests made during the response generation\n     */\n    tool_calls?: {\n        /**\n         * The arguments passed to be passed to the tool call request\n         */\n        arguments?: object;\n        /**\n         * The name of the tool to be called\n         */\n        name?: string;\n    }[];\n} | string | AsyncResponse;\ndeclare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast {\n    inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input;\n    postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output;\n}\ninterface Ai_Cf_Meta_Llama_Guard_3_8B_Input {\n    /**\n     * An array of message objects representing the conversation history.\n     */\n    messages: {\n        /**\n         * The role of the message sender must alternate between 'user' and 'assistant'.\n         */\n        role: \"user\" | \"assistant\";\n        /**\n         * The content of the message as a string.\n         */\n        content: string;\n    }[];\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Dictate the output format of the generated response.\n     */\n    response_format?: {\n        /**\n         * Set to json_object to process and output generated text as JSON.\n         */\n        type?: string;\n    };\n}\ninterface Ai_Cf_Meta_Llama_Guard_3_8B_Output {\n    response?: string | {\n        /**\n         * Whether the conversation is safe or not.\n         */\n        safe?: boolean;\n        /**\n         * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe.\n         */\n        categories?: string[];\n    };\n    /**\n     * Usage statistics for the inference request\n     */\n    usage?: {\n        /**\n         * Total number of tokens in input\n         */\n        prompt_tokens?: number;\n        /**\n         * Total number of tokens in output\n         */\n        completion_tokens?: number;\n        /**\n         * Total number of input and output tokens\n         */\n        total_tokens?: number;\n    };\n}\ndeclare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B {\n    inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input;\n    postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output;\n}\ninterface Ai_Cf_Baai_Bge_Reranker_Base_Input {\n    /**\n     * A query you wish to perform against the provided contexts.\n     */\n    /**\n     * Number of returned results starting with the best score.\n     */\n    top_k?: number;\n    /**\n     * List of provided contexts. Note that the index in this array is important, as the response will refer to it.\n     */\n    contexts: {\n        /**\n         * One of the provided context content\n         */\n        text?: string;\n    }[];\n}\ninterface Ai_Cf_Baai_Bge_Reranker_Base_Output {\n    response?: {\n        /**\n         * Index of the context in the request\n         */\n        id?: number;\n        /**\n         * Score of the context under the index.\n         */\n        score?: number;\n    }[];\n}\ndeclare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base {\n    inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input;\n    postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output;\n}\ntype Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Qwen2_5_Coder_32B_Instruct_Prompt | Qwen2_5_Coder_32B_Instruct_Messages;\ninterface Qwen2_5_Coder_32B_Instruct_Prompt {\n    /**\n     * The input text prompt for the model to generate a response.\n     */\n    prompt: string;\n    /**\n     * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.\n     */\n    lora?: string;\n    response_format?: JSONMode;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ninterface Qwen2_5_Coder_32B_Instruct_Messages {\n    /**\n     * An array of message objects representing the conversation history.\n     */\n    messages: {\n        /**\n         * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').\n         */\n        role: string;\n        /**\n         * The content of the message as a string.\n         */\n        content: string;\n    }[];\n    functions?: {\n        name: string;\n        code: string;\n    }[];\n    /**\n     * A list of tools available for the assistant to use.\n     */\n    tools?: ({\n        /**\n         * The name of the tool. More descriptive the better.\n         */\n        name: string;\n        /**\n         * A brief description of what the tool does.\n         */\n        description: string;\n        /**\n         * Schema defining the parameters accepted by the tool.\n         */\n        parameters: {\n            /**\n             * The type of the parameters object (usually 'object').\n             */\n            type: string;\n            /**\n             * List of required parameter names.\n             */\n            required?: string[];\n            /**\n             * Definitions of each parameter.\n             */\n            properties: {\n                [k: string]: {\n                    /**\n                     * The data type of the parameter.\n                     */\n                    type: string;\n                    /**\n                     * A description of the expected parameter.\n                     */\n                    description: string;\n                };\n            };\n        };\n    } | {\n        /**\n         * Specifies the type of tool (e.g., 'function').\n         */\n        type: string;\n        /**\n         * Details of the function tool.\n         */\n        function: {\n            /**\n             * The name of the function.\n             */\n            name: string;\n            /**\n             * A brief description of what the function does.\n             */\n            description: string;\n            /**\n             * Schema defining the parameters accepted by the function.\n             */\n            parameters: {\n                /**\n                 * The type of the parameters object (usually 'object').\n                 */\n                type: string;\n                /**\n                 * List of required parameter names.\n                 */\n                required?: string[];\n                /**\n                 * Definitions of each parameter.\n                 */\n                properties: {\n                    [k: string]: {\n                        /**\n                         * The data type of the parameter.\n                         */\n                        type: string;\n                        /**\n                         * A description of the expected parameter.\n                         */\n                        description: string;\n                    };\n                };\n            };\n        };\n    })[];\n    response_format?: JSONMode;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ntype Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = {\n    /**\n     * The generated text response from the model\n     */\n    response: string;\n    /**\n     * Usage statistics for the inference request\n     */\n    usage?: {\n        /**\n         * Total number of tokens in input\n         */\n        prompt_tokens?: number;\n        /**\n         * Total number of tokens in output\n         */\n        completion_tokens?: number;\n        /**\n         * Total number of input and output tokens\n         */\n        total_tokens?: number;\n    };\n    /**\n     * An array of tool calls requests made during the response generation\n     */\n    tool_calls?: {\n        /**\n         * The arguments passed to be passed to the tool call request\n         */\n        arguments?: object;\n        /**\n         * The name of the tool to be called\n         */\n        name?: string;\n    }[];\n};\ndeclare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct {\n    inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input;\n    postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output;\n}\ntype Ai_Cf_Qwen_Qwq_32B_Input = Qwen_Qwq_32B_Prompt | Qwen_Qwq_32B_Messages;\ninterface Qwen_Qwq_32B_Prompt {\n    /**\n     * The input text prompt for the model to generate a response.\n     */\n    prompt: string;\n    /**\n     * JSON schema that should be fulfilled for the response.\n     */\n    guided_json?: object;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ninterface Qwen_Qwq_32B_Messages {\n    /**\n     * An array of message objects representing the conversation history.\n     */\n    messages: {\n        /**\n         * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').\n         */\n        role?: string;\n        /**\n         * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001\n         */\n        tool_call_id?: string;\n        content?: string | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        }[] | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        };\n    }[];\n    functions?: {\n        name: string;\n        code: string;\n    }[];\n    /**\n     * A list of tools available for the assistant to use.\n     */\n    tools?: ({\n        /**\n         * The name of the tool. More descriptive the better.\n         */\n        name: string;\n        /**\n         * A brief description of what the tool does.\n         */\n        description: string;\n        /**\n         * Schema defining the parameters accepted by the tool.\n         */\n        parameters: {\n            /**\n             * The type of the parameters object (usually 'object').\n             */\n            type: string;\n            /**\n             * List of required parameter names.\n             */\n            required?: string[];\n            /**\n             * Definitions of each parameter.\n             */\n            properties: {\n                [k: string]: {\n                    /**\n                     * The data type of the parameter.\n                     */\n                    type: string;\n                    /**\n                     * A description of the expected parameter.\n                     */\n                    description: string;\n                };\n            };\n        };\n    } | {\n        /**\n         * Specifies the type of tool (e.g., 'function').\n         */\n        type: string;\n        /**\n         * Details of the function tool.\n         */\n        function: {\n            /**\n             * The name of the function.\n             */\n            name: string;\n            /**\n             * A brief description of what the function does.\n             */\n            description: string;\n            /**\n             * Schema defining the parameters accepted by the function.\n             */\n            parameters: {\n                /**\n                 * The type of the parameters object (usually 'object').\n                 */\n                type: string;\n                /**\n                 * List of required parameter names.\n                 */\n                required?: string[];\n                /**\n                 * Definitions of each parameter.\n                 */\n                properties: {\n                    [k: string]: {\n                        /**\n                         * The data type of the parameter.\n                         */\n                        type: string;\n                        /**\n                         * A description of the expected parameter.\n                         */\n                        description: string;\n                    };\n                };\n            };\n        };\n    })[];\n    /**\n     * JSON schema that should be fufilled for the response.\n     */\n    guided_json?: object;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ntype Ai_Cf_Qwen_Qwq_32B_Output = {\n    /**\n     * The generated text response from the model\n     */\n    response: string;\n    /**\n     * Usage statistics for the inference request\n     */\n    usage?: {\n        /**\n         * Total number of tokens in input\n         */\n        prompt_tokens?: number;\n        /**\n         * Total number of tokens in output\n         */\n        completion_tokens?: number;\n        /**\n         * Total number of input and output tokens\n         */\n        total_tokens?: number;\n    };\n    /**\n     * An array of tool calls requests made during the response generation\n     */\n    tool_calls?: {\n        /**\n         * The arguments passed to be passed to the tool call request\n         */\n        arguments?: object;\n        /**\n         * The name of the tool to be called\n         */\n        name?: string;\n    }[];\n};\ndeclare abstract class Base_Ai_Cf_Qwen_Qwq_32B {\n    inputs: Ai_Cf_Qwen_Qwq_32B_Input;\n    postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output;\n}\ntype Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Mistral_Small_3_1_24B_Instruct_Prompt | Mistral_Small_3_1_24B_Instruct_Messages;\ninterface Mistral_Small_3_1_24B_Instruct_Prompt {\n    /**\n     * The input text prompt for the model to generate a response.\n     */\n    prompt: string;\n    /**\n     * JSON schema that should be fulfilled for the response.\n     */\n    guided_json?: object;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ninterface Mistral_Small_3_1_24B_Instruct_Messages {\n    /**\n     * An array of message objects representing the conversation history.\n     */\n    messages: {\n        /**\n         * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').\n         */\n        role?: string;\n        /**\n         * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001\n         */\n        tool_call_id?: string;\n        content?: string | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        }[] | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        };\n    }[];\n    functions?: {\n        name: string;\n        code: string;\n    }[];\n    /**\n     * A list of tools available for the assistant to use.\n     */\n    tools?: ({\n        /**\n         * The name of the tool. More descriptive the better.\n         */\n        name: string;\n        /**\n         * A brief description of what the tool does.\n         */\n        description: string;\n        /**\n         * Schema defining the parameters accepted by the tool.\n         */\n        parameters: {\n            /**\n             * The type of the parameters object (usually 'object').\n             */\n            type: string;\n            /**\n             * List of required parameter names.\n             */\n            required?: string[];\n            /**\n             * Definitions of each parameter.\n             */\n            properties: {\n                [k: string]: {\n                    /**\n                     * The data type of the parameter.\n                     */\n                    type: string;\n                    /**\n                     * A description of the expected parameter.\n                     */\n                    description: string;\n                };\n            };\n        };\n    } | {\n        /**\n         * Specifies the type of tool (e.g., 'function').\n         */\n        type: string;\n        /**\n         * Details of the function tool.\n         */\n        function: {\n            /**\n             * The name of the function.\n             */\n            name: string;\n            /**\n             * A brief description of what the function does.\n             */\n            description: string;\n            /**\n             * Schema defining the parameters accepted by the function.\n             */\n            parameters: {\n                /**\n                 * The type of the parameters object (usually 'object').\n                 */\n                type: string;\n                /**\n                 * List of required parameter names.\n                 */\n                required?: string[];\n                /**\n                 * Definitions of each parameter.\n                 */\n                properties: {\n                    [k: string]: {\n                        /**\n                         * The data type of the parameter.\n                         */\n                        type: string;\n                        /**\n                         * A description of the expected parameter.\n                         */\n                        description: string;\n                    };\n                };\n            };\n        };\n    })[];\n    /**\n     * JSON schema that should be fufilled for the response.\n     */\n    guided_json?: object;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ntype Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = {\n    /**\n     * The generated text response from the model\n     */\n    response: string;\n    /**\n     * Usage statistics for the inference request\n     */\n    usage?: {\n        /**\n         * Total number of tokens in input\n         */\n        prompt_tokens?: number;\n        /**\n         * Total number of tokens in output\n         */\n        completion_tokens?: number;\n        /**\n         * Total number of input and output tokens\n         */\n        total_tokens?: number;\n    };\n    /**\n     * An array of tool calls requests made during the response generation\n     */\n    tool_calls?: {\n        /**\n         * The arguments passed to be passed to the tool call request\n         */\n        arguments?: object;\n        /**\n         * The name of the tool to be called\n         */\n        name?: string;\n    }[];\n};\ndeclare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct {\n    inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input;\n    postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output;\n}\ntype Ai_Cf_Google_Gemma_3_12B_It_Input = Google_Gemma_3_12B_It_Prompt | Google_Gemma_3_12B_It_Messages;\ninterface Google_Gemma_3_12B_It_Prompt {\n    /**\n     * The input text prompt for the model to generate a response.\n     */\n    prompt: string;\n    /**\n     * JSON schema that should be fufilled for the response.\n     */\n    guided_json?: object;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ninterface Google_Gemma_3_12B_It_Messages {\n    /**\n     * An array of message objects representing the conversation history.\n     */\n    messages: {\n        /**\n         * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').\n         */\n        role?: string;\n        content?: string | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        }[] | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        };\n    }[];\n    functions?: {\n        name: string;\n        code: string;\n    }[];\n    /**\n     * A list of tools available for the assistant to use.\n     */\n    tools?: ({\n        /**\n         * The name of the tool. More descriptive the better.\n         */\n        name: string;\n        /**\n         * A brief description of what the tool does.\n         */\n        description: string;\n        /**\n         * Schema defining the parameters accepted by the tool.\n         */\n        parameters: {\n            /**\n             * The type of the parameters object (usually 'object').\n             */\n            type: string;\n            /**\n             * List of required parameter names.\n             */\n            required?: string[];\n            /**\n             * Definitions of each parameter.\n             */\n            properties: {\n                [k: string]: {\n                    /**\n                     * The data type of the parameter.\n                     */\n                    type: string;\n                    /**\n                     * A description of the expected parameter.\n                     */\n                    description: string;\n                };\n            };\n        };\n    } | {\n        /**\n         * Specifies the type of tool (e.g., 'function').\n         */\n        type: string;\n        /**\n         * Details of the function tool.\n         */\n        function: {\n            /**\n             * The name of the function.\n             */\n            name: string;\n            /**\n             * A brief description of what the function does.\n             */\n            description: string;\n            /**\n             * Schema defining the parameters accepted by the function.\n             */\n            parameters: {\n                /**\n                 * The type of the parameters object (usually 'object').\n                 */\n                type: string;\n                /**\n                 * List of required parameter names.\n                 */\n                required?: string[];\n                /**\n                 * Definitions of each parameter.\n                 */\n                properties: {\n                    [k: string]: {\n                        /**\n                         * The data type of the parameter.\n                         */\n                        type: string;\n                        /**\n                         * A description of the expected parameter.\n                         */\n                        description: string;\n                    };\n                };\n            };\n        };\n    })[];\n    /**\n     * JSON schema that should be fufilled for the response.\n     */\n    guided_json?: object;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ntype Ai_Cf_Google_Gemma_3_12B_It_Output = {\n    /**\n     * The generated text response from the model\n     */\n    response: string;\n    /**\n     * Usage statistics for the inference request\n     */\n    usage?: {\n        /**\n         * Total number of tokens in input\n         */\n        prompt_tokens?: number;\n        /**\n         * Total number of tokens in output\n         */\n        completion_tokens?: number;\n        /**\n         * Total number of input and output tokens\n         */\n        total_tokens?: number;\n    };\n    /**\n     * An array of tool calls requests made during the response generation\n     */\n    tool_calls?: {\n        /**\n         * The arguments passed to be passed to the tool call request\n         */\n        arguments?: object;\n        /**\n         * The name of the tool to be called\n         */\n        name?: string;\n    }[];\n};\ndeclare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It {\n    inputs: Ai_Cf_Google_Gemma_3_12B_It_Input;\n    postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output;\n}\ntype Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Prompt | Ai_Cf_Meta_Llama_4_Messages | Ai_Cf_Meta_Llama_4_Async_Batch;\ninterface Ai_Cf_Meta_Llama_4_Prompt {\n    /**\n     * The input text prompt for the model to generate a response.\n     */\n    prompt: string;\n    /**\n     * JSON schema that should be fulfilled for the response.\n     */\n    guided_json?: object;\n    response_format?: JSONMode;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ninterface Ai_Cf_Meta_Llama_4_Messages {\n    /**\n     * An array of message objects representing the conversation history.\n     */\n    messages: {\n        /**\n         * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').\n         */\n        role?: string;\n        /**\n         * The tool call id. If you don't know what to put here you can fall back to 000000001\n         */\n        tool_call_id?: string;\n        content?: string | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        }[] | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        };\n    }[];\n    functions?: {\n        name: string;\n        code: string;\n    }[];\n    /**\n     * A list of tools available for the assistant to use.\n     */\n    tools?: ({\n        /**\n         * The name of the tool. More descriptive the better.\n         */\n        name: string;\n        /**\n         * A brief description of what the tool does.\n         */\n        description: string;\n        /**\n         * Schema defining the parameters accepted by the tool.\n         */\n        parameters: {\n            /**\n             * The type of the parameters object (usually 'object').\n             */\n            type: string;\n            /**\n             * List of required parameter names.\n             */\n            required?: string[];\n            /**\n             * Definitions of each parameter.\n             */\n            properties: {\n                [k: string]: {\n                    /**\n                     * The data type of the parameter.\n                     */\n                    type: string;\n                    /**\n                     * A description of the expected parameter.\n                     */\n                    description: string;\n                };\n            };\n        };\n    } | {\n        /**\n         * Specifies the type of tool (e.g., 'function').\n         */\n        type: string;\n        /**\n         * Details of the function tool.\n         */\n        function: {\n            /**\n             * The name of the function.\n             */\n            name: string;\n            /**\n             * A brief description of what the function does.\n             */\n            description: string;\n            /**\n             * Schema defining the parameters accepted by the function.\n             */\n            parameters: {\n                /**\n                 * The type of the parameters object (usually 'object').\n                 */\n                type: string;\n                /**\n                 * List of required parameter names.\n                 */\n                required?: string[];\n                /**\n                 * Definitions of each parameter.\n                 */\n                properties: {\n                    [k: string]: {\n                        /**\n                         * The data type of the parameter.\n                         */\n                        type: string;\n                        /**\n                         * A description of the expected parameter.\n                         */\n                        description: string;\n                    };\n                };\n            };\n        };\n    })[];\n    response_format?: JSONMode;\n    /**\n     * JSON schema that should be fufilled for the response.\n     */\n    guided_json?: object;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ninterface Ai_Cf_Meta_Llama_4_Async_Batch {\n    requests: (Ai_Cf_Meta_Llama_4_Prompt_Inner | Ai_Cf_Meta_Llama_4_Messages_Inner)[];\n}\ninterface Ai_Cf_Meta_Llama_4_Prompt_Inner {\n    /**\n     * The input text prompt for the model to generate a response.\n     */\n    prompt: string;\n    /**\n     * JSON schema that should be fulfilled for the response.\n     */\n    guided_json?: object;\n    response_format?: JSONMode;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ninterface Ai_Cf_Meta_Llama_4_Messages_Inner {\n    /**\n     * An array of message objects representing the conversation history.\n     */\n    messages: {\n        /**\n         * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').\n         */\n        role?: string;\n        /**\n         * The tool call id. If you don't know what to put here you can fall back to 000000001\n         */\n        tool_call_id?: string;\n        content?: string | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        }[] | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        };\n    }[];\n    functions?: {\n        name: string;\n        code: string;\n    }[];\n    /**\n     * A list of tools available for the assistant to use.\n     */\n    tools?: ({\n        /**\n         * The name of the tool. More descriptive the better.\n         */\n        name: string;\n        /**\n         * A brief description of what the tool does.\n         */\n        description: string;\n        /**\n         * Schema defining the parameters accepted by the tool.\n         */\n        parameters: {\n            /**\n             * The type of the parameters object (usually 'object').\n             */\n            type: string;\n            /**\n             * List of required parameter names.\n             */\n            required?: string[];\n            /**\n             * Definitions of each parameter.\n             */\n            properties: {\n                [k: string]: {\n                    /**\n                     * The data type of the parameter.\n                     */\n                    type: string;\n                    /**\n                     * A description of the expected parameter.\n                     */\n                    description: string;\n                };\n            };\n        };\n    } | {\n        /**\n         * Specifies the type of tool (e.g., 'function').\n         */\n        type: string;\n        /**\n         * Details of the function tool.\n         */\n        function: {\n            /**\n             * The name of the function.\n             */\n            name: string;\n            /**\n             * A brief description of what the function does.\n             */\n            description: string;\n            /**\n             * Schema defining the parameters accepted by the function.\n             */\n            parameters: {\n                /**\n                 * The type of the parameters object (usually 'object').\n                 */\n                type: string;\n                /**\n                 * List of required parameter names.\n                 */\n                required?: string[];\n                /**\n                 * Definitions of each parameter.\n                 */\n                properties: {\n                    [k: string]: {\n                        /**\n                         * The data type of the parameter.\n                         */\n                        type: string;\n                        /**\n                         * A description of the expected parameter.\n                         */\n                        description: string;\n                    };\n                };\n            };\n        };\n    })[];\n    response_format?: JSONMode;\n    /**\n     * JSON schema that should be fufilled for the response.\n     */\n    guided_json?: object;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ntype Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = {\n    /**\n     * The generated text response from the model\n     */\n    response: string;\n    /**\n     * Usage statistics for the inference request\n     */\n    usage?: {\n        /**\n         * Total number of tokens in input\n         */\n        prompt_tokens?: number;\n        /**\n         * Total number of tokens in output\n         */\n        completion_tokens?: number;\n        /**\n         * Total number of input and output tokens\n         */\n        total_tokens?: number;\n    };\n    /**\n     * An array of tool calls requests made during the response generation\n     */\n    tool_calls?: {\n        /**\n         * The tool call id.\n         */\n        id?: string;\n        /**\n         * Specifies the type of tool (e.g., 'function').\n         */\n        type?: string;\n        /**\n         * Details of the function tool.\n         */\n        function?: {\n            /**\n             * The name of the tool to be called\n             */\n            name?: string;\n            /**\n             * The arguments passed to be passed to the tool call request\n             */\n            arguments?: object;\n        };\n    }[];\n};\ndeclare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct {\n    inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input;\n    postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output;\n}\ninterface Ai_Cf_Deepgram_Nova_3_Input {\n    audio: {\n        body: object;\n        contentType: string;\n    };\n    /**\n     * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param.\n     */\n    custom_topic_mode?: \"extended\" | \"strict\";\n    /**\n     * Custom topics you want the model to detect within your input audio or text if present Submit up to 100\n     */\n    custom_topic?: string;\n    /**\n     * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param\n     */\n    custom_intent_mode?: \"extended\" | \"strict\";\n    /**\n     * Custom intents you want the model to detect within your input audio if present\n     */\n    custom_intent?: string;\n    /**\n     * Identifies and extracts key entities from content in submitted audio\n     */\n    detect_entities?: boolean;\n    /**\n     * Identifies the dominant language spoken in submitted audio\n     */\n    detect_language?: boolean;\n    /**\n     * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0\n     */\n    diarize?: boolean;\n    /**\n     * Identify and extract key entities from content in submitted audio\n     */\n    dictation?: boolean;\n    /**\n     * Specify the expected encoding of your submitted audio\n     */\n    encoding?: \"linear16\" | \"flac\" | \"mulaw\" | \"amr-nb\" | \"amr-wb\" | \"opus\" | \"speex\" | \"g729\";\n    /**\n     * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing\n     */\n    extra?: string;\n    /**\n     * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um'\n     */\n    filler_words?: boolean;\n    /**\n     * Key term prompting can boost or suppress specialized terminology and brands.\n     */\n    keyterm?: string;\n    /**\n     * Keywords can boost or suppress specialized terminology and brands.\n     */\n    keywords?: string;\n    /**\n     * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available.\n     */\n    language?: string;\n    /**\n     * Spoken measurements will be converted to their corresponding abbreviations.\n     */\n    measurements?: boolean;\n    /**\n     * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip.\n     */\n    mip_opt_out?: boolean;\n    /**\n     * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio\n     */\n    mode?: \"general\" | \"medical\" | \"finance\";\n    /**\n     * Transcribe each audio channel independently.\n     */\n    multichannel?: boolean;\n    /**\n     * Numerals converts numbers from written format to numerical format.\n     */\n    numerals?: boolean;\n    /**\n     * Splits audio into paragraphs to improve transcript readability.\n     */\n    paragraphs?: boolean;\n    /**\n     * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely.\n     */\n    profanity_filter?: boolean;\n    /**\n     * Add punctuation and capitalization to the transcript.\n     */\n    punctuate?: boolean;\n    /**\n     * Redaction removes sensitive information from your transcripts.\n     */\n    redact?: string;\n    /**\n     * Search for terms or phrases in submitted audio and replaces them.\n     */\n    replace?: string;\n    /**\n     * Search for terms or phrases in submitted audio.\n     */\n    search?: string;\n    /**\n     * Recognizes the sentiment throughout a transcript or text.\n     */\n    sentiment?: boolean;\n    /**\n     * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability.\n     */\n    smart_format?: boolean;\n    /**\n     * Detect topics throughout a transcript or text.\n     */\n    topics?: boolean;\n    /**\n     * Segments speech into meaningful semantic units.\n     */\n    utterances?: boolean;\n    /**\n     * Seconds to wait before detecting a pause between words in submitted audio.\n     */\n    utt_split?: number;\n    /**\n     * The number of channels in the submitted audio\n     */\n    channels?: number;\n    /**\n     * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets.\n     */\n    interim_results?: boolean;\n    /**\n     * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing\n     */\n    endpointing?: string;\n    /**\n     * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets.\n     */\n    vad_events?: boolean;\n    /**\n     * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets.\n     */\n    utterance_end_ms?: boolean;\n}\ninterface Ai_Cf_Deepgram_Nova_3_Output {\n    results?: {\n        channels?: {\n            alternatives?: {\n                confidence?: number;\n                transcript?: string;\n                words?: {\n                    confidence?: number;\n                    end?: number;\n                    start?: number;\n                    word?: string;\n                }[];\n            }[];\n        }[];\n        summary?: {\n            result?: string;\n            short?: string;\n        };\n        sentiments?: {\n            segments?: {\n                text?: string;\n                start_word?: number;\n                end_word?: number;\n                sentiment?: string;\n                sentiment_score?: number;\n            }[];\n            average?: {\n                sentiment?: string;\n                sentiment_score?: number;\n            };\n        };\n    };\n}\ndeclare abstract class Base_Ai_Cf_Deepgram_Nova_3 {\n    inputs: Ai_Cf_Deepgram_Nova_3_Input;\n    postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output;\n}\ntype Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = {\n    /**\n     * readable stream with audio data and content-type specified for that data\n     */\n    audio: {\n        body: object;\n        contentType: string;\n    };\n    /**\n     * type of data PCM data that's sent to the inference server as raw array\n     */\n    dtype?: \"uint8\" | \"float32\" | \"float64\";\n} | {\n    /**\n     * base64 encoded audio data\n     */\n    audio: string;\n    /**\n     * type of data PCM data that's sent to the inference server as raw array\n     */\n    dtype?: \"uint8\" | \"float32\" | \"float64\";\n};\ninterface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output {\n    /**\n     * if true, end-of-turn was detected\n     */\n    is_complete?: boolean;\n    /**\n     * probability of the end-of-turn detection\n     */\n    probability?: number;\n}\ndeclare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 {\n    inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input;\n    postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output;\n}\ntype Ai_Cf_Openai_Gpt_Oss_120B_Input = GPT_OSS_120B_Responses | GPT_OSS_120B_Responses_Async;\ninterface GPT_OSS_120B_Responses {\n    /**\n     * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types\n     */\n    input: string | unknown[];\n    reasoning?: {\n        /**\n         * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response.\n         */\n        effort?: \"low\" | \"medium\" | \"high\";\n        /**\n         * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed.\n         */\n        summary?: \"auto\" | \"concise\" | \"detailed\";\n    };\n}\ninterface GPT_OSS_120B_Responses_Async {\n    requests: {\n        /**\n         * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types\n         */\n        input: string | unknown[];\n        reasoning?: {\n            /**\n             * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response.\n             */\n            effort?: \"low\" | \"medium\" | \"high\";\n            /**\n             * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed.\n             */\n            summary?: \"auto\" | \"concise\" | \"detailed\";\n        };\n    }[];\n}\ntype Ai_Cf_Openai_Gpt_Oss_120B_Output = {} | (string & NonNullable<unknown>);\ndeclare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B {\n    inputs: Ai_Cf_Openai_Gpt_Oss_120B_Input;\n    postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_120B_Output;\n}\ntype Ai_Cf_Openai_Gpt_Oss_20B_Input = GPT_OSS_20B_Responses | GPT_OSS_20B_Responses_Async;\ninterface GPT_OSS_20B_Responses {\n    /**\n     * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types\n     */\n    input: string | unknown[];\n    reasoning?: {\n        /**\n         * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response.\n         */\n        effort?: \"low\" | \"medium\" | \"high\";\n        /**\n         * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed.\n         */\n        summary?: \"auto\" | \"concise\" | \"detailed\";\n    };\n}\ninterface GPT_OSS_20B_Responses_Async {\n    requests: {\n        /**\n         * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types\n         */\n        input: string | unknown[];\n        reasoning?: {\n            /**\n             * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response.\n             */\n            effort?: \"low\" | \"medium\" | \"high\";\n            /**\n             * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed.\n             */\n            summary?: \"auto\" | \"concise\" | \"detailed\";\n        };\n    }[];\n}\ntype Ai_Cf_Openai_Gpt_Oss_20B_Output = {} | (string & NonNullable<unknown>);\ndeclare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B {\n    inputs: Ai_Cf_Openai_Gpt_Oss_20B_Input;\n    postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_20B_Output;\n}\ninterface Ai_Cf_Leonardo_Phoenix_1_0_Input {\n    /**\n     * A text description of the image you want to generate.\n     */\n    prompt: string;\n    /**\n     * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt\n     */\n    guidance?: number;\n    /**\n     * Random seed for reproducibility of the image generation\n     */\n    seed?: number;\n    /**\n     * The height of the generated image in pixels\n     */\n    height?: number;\n    /**\n     * The width of the generated image in pixels\n     */\n    width?: number;\n    /**\n     * The number of diffusion steps; higher values can improve quality but take longer\n     */\n    num_steps?: number;\n    /**\n     * Specify what to exclude from the generated images\n     */\n    negative_prompt?: string;\n}\n/**\n * The generated image in JPEG format\n */\ntype Ai_Cf_Leonardo_Phoenix_1_0_Output = string;\ndeclare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 {\n    inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input;\n    postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output;\n}\ninterface Ai_Cf_Leonardo_Lucid_Origin_Input {\n    /**\n     * A text description of the image you want to generate.\n     */\n    prompt: string;\n    /**\n     * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt\n     */\n    guidance?: number;\n    /**\n     * Random seed for reproducibility of the image generation\n     */\n    seed?: number;\n    /**\n     * The height of the generated image in pixels\n     */\n    height?: number;\n    /**\n     * The width of the generated image in pixels\n     */\n    width?: number;\n    /**\n     * The number of diffusion steps; higher values can improve quality but take longer\n     */\n    num_steps?: number;\n    /**\n     * The number of diffusion steps; higher values can improve quality but take longer\n     */\n    steps?: number;\n}\ninterface Ai_Cf_Leonardo_Lucid_Origin_Output {\n    /**\n     * The generated image in Base64 format.\n     */\n    image?: string;\n}\ndeclare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin {\n    inputs: Ai_Cf_Leonardo_Lucid_Origin_Input;\n    postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output;\n}\ninterface Ai_Cf_Deepgram_Aura_1_Input {\n    /**\n     * Speaker used to produce the audio.\n     */\n    speaker?: \"angus\" | \"asteria\" | \"arcas\" | \"orion\" | \"orpheus\" | \"athena\" | \"luna\" | \"zeus\" | \"perseus\" | \"helios\" | \"hera\" | \"stella\";\n    /**\n     * Encoding of the output audio.\n     */\n    encoding?: \"linear16\" | \"flac\" | \"mulaw\" | \"alaw\" | \"mp3\" | \"opus\" | \"aac\";\n    /**\n     * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..\n     */\n    container?: \"none\" | \"wav\" | \"ogg\";\n    /**\n     * The text content to be converted to speech\n     */\n    text: string;\n    /**\n     * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable\n     */\n    sample_rate?: number;\n    /**\n     * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.\n     */\n    bit_rate?: number;\n}\n/**\n * The generated audio in MP3 format\n */\ntype Ai_Cf_Deepgram_Aura_1_Output = string;\ndeclare abstract class Base_Ai_Cf_Deepgram_Aura_1 {\n    inputs: Ai_Cf_Deepgram_Aura_1_Input;\n    postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output;\n}\ninterface AiModels {\n    \"@cf/huggingface/distilbert-sst-2-int8\": BaseAiTextClassification;\n    \"@cf/stabilityai/stable-diffusion-xl-base-1.0\": BaseAiTextToImage;\n    \"@cf/runwayml/stable-diffusion-v1-5-inpainting\": BaseAiTextToImage;\n    \"@cf/runwayml/stable-diffusion-v1-5-img2img\": BaseAiTextToImage;\n    \"@cf/lykon/dreamshaper-8-lcm\": BaseAiTextToImage;\n    \"@cf/bytedance/stable-diffusion-xl-lightning\": BaseAiTextToImage;\n    \"@cf/myshell-ai/melotts\": BaseAiTextToSpeech;\n    \"@cf/google/embeddinggemma-300m\": BaseAiTextEmbeddings;\n    \"@cf/microsoft/resnet-50\": BaseAiImageClassification;\n    \"@cf/meta/llama-2-7b-chat-int8\": BaseAiTextGeneration;\n    \"@cf/mistral/mistral-7b-instruct-v0.1\": BaseAiTextGeneration;\n    \"@cf/meta/llama-2-7b-chat-fp16\": BaseAiTextGeneration;\n    \"@hf/thebloke/llama-2-13b-chat-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/mistral-7b-instruct-v0.1-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/zephyr-7b-beta-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/openhermes-2.5-mistral-7b-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/neural-chat-7b-v3-1-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/llamaguard-7b-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/deepseek-coder-6.7b-base-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/deepseek-coder-6.7b-instruct-awq\": BaseAiTextGeneration;\n    \"@cf/deepseek-ai/deepseek-math-7b-instruct\": BaseAiTextGeneration;\n    \"@cf/defog/sqlcoder-7b-2\": BaseAiTextGeneration;\n    \"@cf/openchat/openchat-3.5-0106\": BaseAiTextGeneration;\n    \"@cf/tiiuae/falcon-7b-instruct\": BaseAiTextGeneration;\n    \"@cf/thebloke/discolm-german-7b-v1-awq\": BaseAiTextGeneration;\n    \"@cf/qwen/qwen1.5-0.5b-chat\": BaseAiTextGeneration;\n    \"@cf/qwen/qwen1.5-7b-chat-awq\": BaseAiTextGeneration;\n    \"@cf/qwen/qwen1.5-14b-chat-awq\": BaseAiTextGeneration;\n    \"@cf/tinyllama/tinyllama-1.1b-chat-v1.0\": BaseAiTextGeneration;\n    \"@cf/microsoft/phi-2\": BaseAiTextGeneration;\n    \"@cf/qwen/qwen1.5-1.8b-chat\": BaseAiTextGeneration;\n    \"@cf/mistral/mistral-7b-instruct-v0.2-lora\": BaseAiTextGeneration;\n    \"@hf/nousresearch/hermes-2-pro-mistral-7b\": BaseAiTextGeneration;\n    \"@hf/nexusflow/starling-lm-7b-beta\": BaseAiTextGeneration;\n    \"@hf/google/gemma-7b-it\": BaseAiTextGeneration;\n    \"@cf/meta-llama/llama-2-7b-chat-hf-lora\": BaseAiTextGeneration;\n    \"@cf/google/gemma-2b-it-lora\": BaseAiTextGeneration;\n    \"@cf/google/gemma-7b-it-lora\": BaseAiTextGeneration;\n    \"@hf/mistral/mistral-7b-instruct-v0.2\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3-8b-instruct\": BaseAiTextGeneration;\n    \"@cf/fblgit/una-cybertron-7b-v2-bf16\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3-8b-instruct-awq\": BaseAiTextGeneration;\n    \"@hf/meta-llama/meta-llama-3-8b-instruct\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3.1-8b-instruct-fp8\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3.1-8b-instruct-awq\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3.2-3b-instruct\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3.2-1b-instruct\": BaseAiTextGeneration;\n    \"@cf/deepseek-ai/deepseek-r1-distill-qwen-32b\": BaseAiTextGeneration;\n    \"@cf/facebook/bart-large-cnn\": BaseAiSummarization;\n    \"@cf/llava-hf/llava-1.5-7b-hf\": BaseAiImageToText;\n    \"@cf/baai/bge-base-en-v1.5\": Base_Ai_Cf_Baai_Bge_Base_En_V1_5;\n    \"@cf/openai/whisper\": Base_Ai_Cf_Openai_Whisper;\n    \"@cf/meta/m2m100-1.2b\": Base_Ai_Cf_Meta_M2M100_1_2B;\n    \"@cf/baai/bge-small-en-v1.5\": Base_Ai_Cf_Baai_Bge_Small_En_V1_5;\n    \"@cf/baai/bge-large-en-v1.5\": Base_Ai_Cf_Baai_Bge_Large_En_V1_5;\n    \"@cf/unum/uform-gen2-qwen-500m\": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M;\n    \"@cf/openai/whisper-tiny-en\": Base_Ai_Cf_Openai_Whisper_Tiny_En;\n    \"@cf/openai/whisper-large-v3-turbo\": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo;\n    \"@cf/baai/bge-m3\": Base_Ai_Cf_Baai_Bge_M3;\n    \"@cf/black-forest-labs/flux-1-schnell\": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell;\n    \"@cf/meta/llama-3.2-11b-vision-instruct\": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct;\n    \"@cf/meta/llama-3.3-70b-instruct-fp8-fast\": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast;\n    \"@cf/meta/llama-guard-3-8b\": Base_Ai_Cf_Meta_Llama_Guard_3_8B;\n    \"@cf/baai/bge-reranker-base\": Base_Ai_Cf_Baai_Bge_Reranker_Base;\n    \"@cf/qwen/qwen2.5-coder-32b-instruct\": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct;\n    \"@cf/qwen/qwq-32b\": Base_Ai_Cf_Qwen_Qwq_32B;\n    \"@cf/mistralai/mistral-small-3.1-24b-instruct\": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct;\n    \"@cf/google/gemma-3-12b-it\": Base_Ai_Cf_Google_Gemma_3_12B_It;\n    \"@cf/meta/llama-4-scout-17b-16e-instruct\": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct;\n    \"@cf/deepgram/nova-3\": Base_Ai_Cf_Deepgram_Nova_3;\n    \"@cf/pipecat-ai/smart-turn-v2\": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2;\n    \"@cf/openai/gpt-oss-120b\": Base_Ai_Cf_Openai_Gpt_Oss_120B;\n    \"@cf/openai/gpt-oss-20b\": Base_Ai_Cf_Openai_Gpt_Oss_20B;\n    \"@cf/leonardo/phoenix-1.0\": Base_Ai_Cf_Leonardo_Phoenix_1_0;\n    \"@cf/leonardo/lucid-origin\": Base_Ai_Cf_Leonardo_Lucid_Origin;\n    \"@cf/deepgram/aura-1\": Base_Ai_Cf_Deepgram_Aura_1;\n}\ntype AiOptions = {\n    /**\n     * Send requests as an asynchronous batch job, only works for supported models\n     * https://developers.cloudflare.com/workers-ai/features/batch-api\n     */\n    queueRequest?: boolean;\n    /**\n     * Establish websocket connections, only works for supported models\n     */\n    websocket?: boolean;\n    gateway?: GatewayOptions;\n    returnRawResponse?: boolean;\n    prefix?: string;\n    extraHeaders?: object;\n};\ntype ConversionResponse = {\n    name: string;\n    mimeType: string;\n    format: \"markdown\";\n    tokens: number;\n    data: string;\n};\ntype AiModelsSearchParams = {\n    author?: string;\n    hide_experimental?: boolean;\n    page?: number;\n    per_page?: number;\n    search?: string;\n    source?: number;\n    task?: string;\n};\ntype AiModelsSearchObject = {\n    id: string;\n    source: number;\n    name: string;\n    description: string;\n    task: {\n        id: string;\n        name: string;\n        description: string;\n    };\n    tags: string[];\n    properties: {\n        property_id: string;\n        value: string;\n    }[];\n};\ninterface InferenceUpstreamError extends Error {\n}\ninterface AiInternalError extends Error {\n}\ntype AiModelListType = Record<string, any>;\ndeclare abstract class Ai<AiModelList extends AiModelListType = AiModels> {\n    aiGatewayLogId: string | null;\n    gateway(gatewayId: string): AiGateway;\n    autorag(autoragId: string): AutoRAG;\n    run<Name extends keyof AiModelList, Options extends AiOptions, InputOptions extends AiModelList[Name][\"inputs\"]>(model: Name, inputs: InputOptions, options?: Options): Promise<Options extends {\n        returnRawResponse: true;\n    } | {\n        websocket: true;\n    } ? Response : InputOptions extends {\n        stream: true;\n    } ? ReadableStream : AiModelList[Name][\"postProcessedOutputs\"]>;\n    models(params?: AiModelsSearchParams): Promise<AiModelsSearchObject[]>;\n    toMarkdown(files: {\n        name: string;\n        blob: Blob;\n    }[], options?: {\n        gateway?: GatewayOptions;\n        extraHeaders?: object;\n    }): Promise<ConversionResponse[]>;\n    toMarkdown(files: {\n        name: string;\n        blob: Blob;\n    }, options?: {\n        gateway?: GatewayOptions;\n        extraHeaders?: object;\n    }): Promise<ConversionResponse>;\n}\ntype GatewayRetries = {\n    maxAttempts?: 1 | 2 | 3 | 4 | 5;\n    retryDelayMs?: number;\n    backoff?: 'constant' | 'linear' | 'exponential';\n};\ntype GatewayOptions = {\n    id: string;\n    cacheKey?: string;\n    cacheTtl?: number;\n    skipCache?: boolean;\n    metadata?: Record<string, number | string | boolean | null | bigint>;\n    collectLog?: boolean;\n    eventId?: string;\n    requestTimeoutMs?: number;\n    retries?: GatewayRetries;\n};\ntype UniversalGatewayOptions = Exclude<GatewayOptions, 'id'> & {\n    /**\n     ** @deprecated\n     */\n    id?: string;\n};\ntype AiGatewayPatchLog = {\n    score?: number | null;\n    feedback?: -1 | 1 | null;\n    metadata?: Record<string, number | string | boolean | null | bigint> | null;\n};\ntype AiGatewayLog = {\n    id: string;\n    provider: string;\n    model: string;\n    model_type?: string;\n    path: string;\n    duration: number;\n    request_type?: string;\n    request_content_type?: string;\n    status_code: number;\n    response_content_type?: string;\n    success: boolean;\n    cached: boolean;\n    tokens_in?: number;\n    tokens_out?: number;\n    metadata?: Record<string, number | string | boolean | null | bigint>;\n    step?: number;\n    cost?: number;\n    custom_cost?: boolean;\n    request_size: number;\n    request_head?: string;\n    request_head_complete: boolean;\n    response_size: number;\n    response_head?: string;\n    response_head_complete: boolean;\n    created_at: Date;\n};\ntype AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly';\ntype AIGatewayHeaders = {\n    'cf-aig-metadata': Record<string, number | string | boolean | null | bigint> | string;\n    'cf-aig-custom-cost': {\n        per_token_in?: number;\n        per_token_out?: number;\n    } | {\n        total_cost?: number;\n    } | string;\n    'cf-aig-cache-ttl': number | string;\n    'cf-aig-skip-cache': boolean | string;\n    'cf-aig-cache-key': string;\n    'cf-aig-event-id': string;\n    'cf-aig-request-timeout': number | string;\n    'cf-aig-max-attempts': number | string;\n    'cf-aig-retry-delay': number | string;\n    'cf-aig-backoff': string;\n    'cf-aig-collect-log': boolean | string;\n    Authorization: string;\n    'Content-Type': string;\n    [key: string]: string | number | boolean | object;\n};\ntype AIGatewayUniversalRequest = {\n    provider: AIGatewayProviders | string; // eslint-disable-line\n    endpoint: string;\n    headers: Partial<AIGatewayHeaders>;\n    query: unknown;\n};\ninterface AiGatewayInternalError extends Error {\n}\ninterface AiGatewayLogNotFound extends Error {\n}\ndeclare abstract class AiGateway {\n    patchLog(logId: string, data: AiGatewayPatchLog): Promise<void>;\n    getLog(logId: string): Promise<AiGatewayLog>;\n    run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: {\n        gateway?: UniversalGatewayOptions;\n        extraHeaders?: object;\n    }): Promise<Response>;\n    getUrl(provider?: AIGatewayProviders | string): Promise<string>; // eslint-disable-line\n}\ninterface AutoRAGInternalError extends Error {\n}\ninterface AutoRAGNotFoundError extends Error {\n}\ninterface AutoRAGUnauthorizedError extends Error {\n}\ninterface AutoRAGNameNotSetError extends Error {\n}\ntype ComparisonFilter = {\n    key: string;\n    type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte';\n    value: string | number | boolean;\n};\ntype CompoundFilter = {\n    type: 'and' | 'or';\n    filters: ComparisonFilter[];\n};\ntype AutoRagSearchRequest = {\n    query: string;\n    filters?: CompoundFilter | ComparisonFilter;\n    max_num_results?: number;\n    ranking_options?: {\n        ranker?: string;\n        score_threshold?: number;\n    };\n    rewrite_query?: boolean;\n};\ntype AutoRagAiSearchRequest = AutoRagSearchRequest & {\n    stream?: boolean;\n    system_prompt?: string;\n};\ntype AutoRagAiSearchRequestStreaming = Omit<AutoRagAiSearchRequest, 'stream'> & {\n    stream: true;\n};\ntype AutoRagSearchResponse = {\n    object: 'vector_store.search_results.page';\n    search_query: string;\n    data: {\n        file_id: string;\n        filename: string;\n        score: number;\n        attributes: Record<string, string | number | boolean | null>;\n        content: {\n            type: 'text';\n            text: string;\n        }[];\n    }[];\n    has_more: boolean;\n    next_page: string | null;\n};\ntype AutoRagListResponse = {\n    id: string;\n    enable: boolean;\n    type: string;\n    source: string;\n    vectorize_name: string;\n    paused: boolean;\n    status: string;\n}[];\ntype AutoRagAiSearchResponse = AutoRagSearchResponse & {\n    response: string;\n};\ndeclare abstract class AutoRAG {\n    list(): Promise<AutoRagListResponse>;\n    search(params: AutoRagSearchRequest): Promise<AutoRagSearchResponse>;\n    aiSearch(params: AutoRagAiSearchRequestStreaming): Promise<Response>;\n    aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse>;\n    aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse | Response>;\n}\ninterface BasicImageTransformations {\n    /**\n     * Maximum width in image pixels. The value must be an integer.\n     */\n    width?: number;\n    /**\n     * Maximum height in image pixels. The value must be an integer.\n     */\n    height?: number;\n    /**\n     * Resizing mode as a string. It affects interpretation of width and height\n     * options:\n     *  - scale-down: Similar to contain, but the image is never enlarged. If\n     *    the image is larger than given width or height, it will be resized.\n     *    Otherwise its original size will be kept.\n     *  - contain: Resizes to maximum size that fits within the given width and\n     *    height. If only a single dimension is given (e.g. only width), the\n     *    image will be shrunk or enlarged to exactly match that dimension.\n     *    Aspect ratio is always preserved.\n     *  - cover: Resizes (shrinks or enlarges) to fill the entire area of width\n     *    and height. If the image has an aspect ratio different from the ratio\n     *    of width and height, it will be cropped to fit.\n     *  - crop: The image will be shrunk and cropped to fit within the area\n     *    specified by width and height. The image will not be enlarged. For images\n     *    smaller than the given dimensions it's the same as scale-down. For\n     *    images larger than the given dimensions, it's the same as cover.\n     *    See also trim.\n     *  - pad: Resizes to the maximum size that fits within the given width and\n     *    height, and then fills the remaining area with a background color\n     *    (white by default). Use of this mode is not recommended, as the same\n     *    effect can be more efficiently achieved with the contain mode and the\n     *    CSS object-fit: contain property.\n     *  - squeeze: Stretches and deforms to the width and height given, even if it\n     *    breaks aspect ratio\n     */\n    fit?: \"scale-down\" | \"contain\" | \"cover\" | \"crop\" | \"pad\" | \"squeeze\";\n    /**\n     * Image segmentation using artificial intelligence models. Sets pixels not\n     * within selected segment area to transparent e.g \"foreground\" sets every\n     * background pixel as transparent.\n     */\n    segment?: \"foreground\";\n    /**\n     * When cropping with fit: \"cover\", this defines the side or point that should\n     * be left uncropped. The value is either a string\n     * \"left\", \"right\", \"top\", \"bottom\", \"auto\", or \"center\" (the default),\n     * or an object {x, y} containing focal point coordinates in the original\n     * image expressed as fractions ranging from 0.0 (top or left) to 1.0\n     * (bottom or right), 0.5 being the center. {fit: \"cover\", gravity: \"top\"} will\n     * crop bottom or left and right sides as necessary, but won’t crop anything\n     * from the top. {fit: \"cover\", gravity: {x:0.5, y:0.2}} will crop each side to\n     * preserve as much as possible around a point at 20% of the height of the\n     * source image.\n     */\n    gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates;\n    /**\n     * Background color to add underneath the image. Applies only to images with\n     * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…),\n     * hsl(…), etc.)\n     */\n    background?: string;\n    /**\n     * Number of degrees (90, 180, 270) to rotate the image by. width and height\n     * options refer to axes after rotation.\n     */\n    rotate?: 0 | 90 | 180 | 270 | 360;\n}\ninterface BasicImageTransformationsGravityCoordinates {\n    x?: number;\n    y?: number;\n    mode?: 'remainder' | 'box-center';\n}\n/**\n * In addition to the properties you can set in the RequestInit dict\n * that you pass as an argument to the Request constructor, you can\n * set certain properties of a `cf` object to control how Cloudflare\n * features are applied to that new Request.\n *\n * Note: Currently, these properties cannot be tested in the\n * playground.\n */\ninterface RequestInitCfProperties extends Record<string, unknown> {\n    cacheEverything?: boolean;\n    /**\n     * A request's cache key is what determines if two requests are\n     * \"the same\" for caching purposes. If a request has the same cache key\n     * as some previous request, then we can serve the same cached response for\n     * both. (e.g. 'some-key')\n     *\n     * Only available for Enterprise customers.\n     */\n    cacheKey?: string;\n    /**\n     * This allows you to append additional Cache-Tag response headers\n     * to the origin response without modifications to the origin server.\n     * This will allow for greater control over the Purge by Cache Tag feature\n     * utilizing changes only in the Workers process.\n     *\n     * Only available for Enterprise customers.\n     */\n    cacheTags?: string[];\n    /**\n     * Force response to be cached for a given number of seconds. (e.g. 300)\n     */\n    cacheTtl?: number;\n    /**\n     * Force response to be cached for a given number of seconds based on the Origin status code.\n     * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 })\n     */\n    cacheTtlByStatus?: Record<string, number>;\n    scrapeShield?: boolean;\n    apps?: boolean;\n    image?: RequestInitCfPropertiesImage;\n    minify?: RequestInitCfPropertiesImageMinify;\n    mirage?: boolean;\n    polish?: \"lossy\" | \"lossless\" | \"off\";\n    r2?: RequestInitCfPropertiesR2;\n    /**\n     * Redirects the request to an alternate origin server. You can use this,\n     * for example, to implement load balancing across several origins.\n     * (e.g.us-east.example.com)\n     *\n     * Note - For security reasons, the hostname set in resolveOverride must\n     * be proxied on the same Cloudflare zone of the incoming request.\n     * Otherwise, the setting is ignored. CNAME hosts are allowed, so to\n     * resolve to a host under a different domain or a DNS only domain first\n     * declare a CNAME record within your own zone’s DNS mapping to the\n     * external hostname, set proxy on Cloudflare, then set resolveOverride\n     * to point to that CNAME record.\n     */\n    resolveOverride?: string;\n}\ninterface RequestInitCfPropertiesImageDraw extends BasicImageTransformations {\n    /**\n     * Absolute URL of the image file to use for the drawing. It can be any of\n     * the supported file formats. For drawing of watermarks or non-rectangular\n     * overlays we recommend using PNG or WebP images.\n     */\n    url: string;\n    /**\n     * Floating-point number between 0 (transparent) and 1 (opaque).\n     * For example, opacity: 0.5 makes overlay semitransparent.\n     */\n    opacity?: number;\n    /**\n     * - If set to true, the overlay image will be tiled to cover the entire\n     *   area. This is useful for stock-photo-like watermarks.\n     * - If set to \"x\", the overlay image will be tiled horizontally only\n     *   (form a line).\n     * - If set to \"y\", the overlay image will be tiled vertically only\n     *   (form a line).\n     */\n    repeat?: true | \"x\" | \"y\";\n    /**\n     * Position of the overlay image relative to a given edge. Each property is\n     * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10\n     * positions left side of the overlay 10 pixels from the left edge of the\n     * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom\n     * of the background image.\n     *\n     * Setting both left & right, or both top & bottom is an error.\n     *\n     * If no position is specified, the image will be centered.\n     */\n    top?: number;\n    left?: number;\n    bottom?: number;\n    right?: number;\n}\ninterface RequestInitCfPropertiesImage extends BasicImageTransformations {\n    /**\n     * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it\n     * easier to specify higher-DPI sizes in <img srcset>.\n     */\n    dpr?: number;\n    /**\n     * Allows you to trim your image. Takes dpr into account and is performed before\n     * resizing or rotation.\n     *\n     * It can be used as:\n     * - left, top, right, bottom - it will specify the number of pixels to cut\n     *   off each side\n     * - width, height - the width/height you'd like to end up with - can be used\n     *   in combination with the properties above\n     * - border - this will automatically trim the surroundings of an image based on\n     *   it's color. It consists of three properties:\n     *    - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit)\n     *    - tolerance: difference from color to treat as color\n     *    - keep: the number of pixels of border to keep\n     */\n    trim?: \"border\" | {\n        top?: number;\n        bottom?: number;\n        left?: number;\n        right?: number;\n        width?: number;\n        height?: number;\n        border?: boolean | {\n            color?: string;\n            tolerance?: number;\n            keep?: number;\n        };\n    };\n    /**\n     * Quality setting from 1-100 (useful values are in 60-90 range). Lower values\n     * make images look worse, but load faster. The default is 85. It applies only\n     * to JPEG and WebP images. It doesn’t have any effect on PNG.\n     */\n    quality?: number | \"low\" | \"medium-low\" | \"medium-high\" | \"high\";\n    /**\n     * Output format to generate. It can be:\n     *  - avif: generate images in AVIF format.\n     *  - webp: generate images in Google WebP format. Set quality to 100 to get\n     *    the WebP-lossless format.\n     *  - json: instead of generating an image, outputs information about the\n     *    image, in JSON format. The JSON object will contain image size\n     *    (before and after resizing), source image’s MIME type, file size, etc.\n     * - jpeg: generate images in JPEG format.\n     * - png: generate images in PNG format.\n     */\n    format?: \"avif\" | \"webp\" | \"json\" | \"jpeg\" | \"png\" | \"baseline-jpeg\" | \"png-force\" | \"svg\";\n    /**\n     * Whether to preserve animation frames from input files. Default is true.\n     * Setting it to false reduces animations to still images. This setting is\n     * recommended when enlarging images or processing arbitrary user content,\n     * because large GIF animations can weigh tens or even hundreds of megabytes.\n     * It is also useful to set anim:false when using format:\"json\" to get the\n     * response quicker without the number of frames.\n     */\n    anim?: boolean;\n    /**\n     * What EXIF data should be preserved in the output image. Note that EXIF\n     * rotation and embedded color profiles are always applied (\"baked in\" into\n     * the image), and aren't affected by this option. Note that if the Polish\n     * feature is enabled, all metadata may have been removed already and this\n     * option may have no effect.\n     *  - keep: Preserve most of EXIF metadata, including GPS location if there's\n     *    any.\n     *  - copyright: Only keep the copyright tag, and discard everything else.\n     *    This is the default behavior for JPEG files.\n     *  - none: Discard all invisible EXIF metadata. Currently WebP and PNG\n     *    output formats always discard metadata.\n     */\n    metadata?: \"keep\" | \"copyright\" | \"none\";\n    /**\n     * Strength of sharpening filter to apply to the image. Floating-point\n     * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a\n     * recommended value for downscaled images.\n     */\n    sharpen?: number;\n    /**\n     * Radius of a blur filter (approximate gaussian). Maximum supported radius\n     * is 250.\n     */\n    blur?: number;\n    /**\n     * Overlays are drawn in the order they appear in the array (last array\n     * entry is the topmost layer).\n     */\n    draw?: RequestInitCfPropertiesImageDraw[];\n    /**\n     * Fetching image from authenticated origin. Setting this property will\n     * pass authentication headers (Authorization, Cookie, etc.) through to\n     * the origin.\n     */\n    \"origin-auth\"?: \"share-publicly\";\n    /**\n     * Adds a border around the image. The border is added after resizing. Border\n     * width takes dpr into account, and can be specified either using a single\n     * width property, or individually for each side.\n     */\n    border?: {\n        color: string;\n        width: number;\n    } | {\n        color: string;\n        top: number;\n        right: number;\n        bottom: number;\n        left: number;\n    };\n    /**\n     * Increase brightness by a factor. A value of 1.0 equals no change, a value\n     * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright.\n     * 0 is ignored.\n     */\n    brightness?: number;\n    /**\n     * Increase contrast by a factor. A value of 1.0 equals no change, a value of\n     * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is\n     * ignored.\n     */\n    contrast?: number;\n    /**\n     * Increase exposure by a factor. A value of 1.0 equals no change, a value of\n     * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored.\n     */\n    gamma?: number;\n    /**\n     * Increase contrast by a factor. A value of 1.0 equals no change, a value of\n     * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is\n     * ignored.\n     */\n    saturation?: number;\n    /**\n     * Flips the images horizontally, vertically, or both. Flipping is applied before\n     * rotation, so if you apply flip=h,rotate=90 then the image will be flipped\n     * horizontally, then rotated by 90 degrees.\n     */\n    flip?: 'h' | 'v' | 'hv';\n    /**\n     * Slightly reduces latency on a cache miss by selecting a\n     * quickest-to-compress file format, at a cost of increased file size and\n     * lower image quality. It will usually override the format option and choose\n     * JPEG over WebP or AVIF. We do not recommend using this option, except in\n     * unusual circumstances like resizing uncacheable dynamically-generated\n     * images.\n     */\n    compression?: \"fast\";\n}\ninterface RequestInitCfPropertiesImageMinify {\n    javascript?: boolean;\n    css?: boolean;\n    html?: boolean;\n}\ninterface RequestInitCfPropertiesR2 {\n    /**\n     * Colo id of bucket that an object is stored in\n     */\n    bucketColoId?: number;\n}\n/**\n * Request metadata provided by Cloudflare's edge.\n */\ntype IncomingRequestCfProperties<HostMetadata = unknown> = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield;\ninterface IncomingRequestCfPropertiesBase extends Record<string, unknown> {\n    /**\n     * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request.\n     *\n     * @example 395747\n     */\n    asn?: number;\n    /**\n     * The organization which owns the ASN of the incoming request.\n     *\n     * @example \"Google Cloud\"\n     */\n    asOrganization?: string;\n    /**\n     * The original value of the `Accept-Encoding` header if Cloudflare modified it.\n     *\n     * @example \"gzip, deflate, br\"\n     */\n    clientAcceptEncoding?: string;\n    /**\n     * The number of milliseconds it took for the request to reach your worker.\n     *\n     * @example 22\n     */\n    clientTcpRtt?: number;\n    /**\n     * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code)\n     * airport code of the data center that the request hit.\n     *\n     * @example \"DFW\"\n     */\n    colo: string;\n    /**\n     * Represents the upstream's response to a\n     * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html)\n     * from cloudflare.\n     *\n     * For workers with no upstream, this will always be `1`.\n     *\n     * @example 3\n     */\n    edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus;\n    /**\n     * The HTTP Protocol the request used.\n     *\n     * @example \"HTTP/2\"\n     */\n    httpProtocol: string;\n    /**\n     * The browser-requested prioritization information in the request object.\n     *\n     * If no information was set, defaults to the empty string `\"\"`\n     *\n     * @example \"weight=192;exclusive=0;group=3;group-weight=127\"\n     * @default \"\"\n     */\n    requestPriority: string;\n    /**\n     * The TLS version of the connection to Cloudflare.\n     * In requests served over plaintext (without TLS), this property is the empty string `\"\"`.\n     *\n     * @example \"TLSv1.3\"\n     */\n    tlsVersion: string;\n    /**\n     * The cipher for the connection to Cloudflare.\n     * In requests served over plaintext (without TLS), this property is the empty string `\"\"`.\n     *\n     * @example \"AEAD-AES128-GCM-SHA256\"\n     */\n    tlsCipher: string;\n    /**\n     * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake.\n     *\n     * If the incoming request was served over plaintext (without TLS) this field is undefined.\n     */\n    tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata;\n}\ninterface IncomingRequestCfPropertiesBotManagementBase {\n    /**\n     * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot,\n     * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human).\n     *\n     * @example 54\n     */\n    score: number;\n    /**\n     * A boolean value that is true if the request comes from a good bot, like Google or Bing.\n     * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots).\n     */\n    verifiedBot: boolean;\n    /**\n     * A boolean value that is true if the request originates from a\n     * Cloudflare-verified proxy service.\n     */\n    corporateProxy: boolean;\n    /**\n     * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources.\n     */\n    staticResource: boolean;\n    /**\n     * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request).\n     */\n    detectionIds: number[];\n}\ninterface IncomingRequestCfPropertiesBotManagement {\n    /**\n     * Results of Cloudflare's Bot Management analysis\n     */\n    botManagement: IncomingRequestCfPropertiesBotManagementBase;\n    /**\n     * Duplicate of `botManagement.score`.\n     *\n     * @deprecated\n     */\n    clientTrustScore: number;\n}\ninterface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement {\n    /**\n     * Results of Cloudflare's Bot Management analysis\n     */\n    botManagement: IncomingRequestCfPropertiesBotManagementBase & {\n        /**\n         * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients\n         * across different destination IPs, Ports, and X509 certificates.\n         */\n        ja3Hash: string;\n    };\n}\ninterface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> {\n    /**\n     * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/).\n     *\n     * This field is only present if you have Cloudflare for SaaS enabled on your account\n     * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)).\n     */\n    hostMetadata?: HostMetadata;\n}\ninterface IncomingRequestCfPropertiesCloudflareAccessOrApiShield {\n    /**\n     * Information about the client certificate presented to Cloudflare.\n     *\n     * This is populated when the incoming request is served over TLS using\n     * either Cloudflare Access or API Shield (mTLS)\n     * and the presented SSL certificate has a valid\n     * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number)\n     * (i.e., not `null` or `\"\"`).\n     *\n     * Otherwise, a set of placeholder values are used.\n     *\n     * The property `certPresented` will be set to `\"1\"` when\n     * the object is populated (i.e. the above conditions were met).\n     */\n    tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder;\n}\n/**\n * Metadata about the request's TLS handshake\n */\ninterface IncomingRequestCfPropertiesExportedAuthenticatorMetadata {\n    /**\n     * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal\n     *\n     * @example \"44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d\"\n     */\n    clientHandshake: string;\n    /**\n     * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal\n     *\n     * @example \"44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d\"\n     */\n    serverHandshake: string;\n    /**\n     * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal\n     *\n     * @example \"084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b\"\n     */\n    clientFinished: string;\n    /**\n     * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal\n     *\n     * @example \"084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b\"\n     */\n    serverFinished: string;\n}\n/**\n * Geographic data about the request's origin.\n */\ninterface IncomingRequestCfPropertiesGeographicInformation {\n    /**\n     * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from.\n     *\n     * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `\"T1\"`, indicating a request that originated over TOR.\n     *\n     * If Cloudflare is unable to determine where the request originated this property is omitted.\n     *\n     * The country code `\"T1\"` is used for requests originating on TOR.\n     *\n     * @example \"GB\"\n     */\n    country?: Iso3166Alpha2Code | \"T1\";\n    /**\n     * If present, this property indicates that the request originated in the EU\n     *\n     * @example \"1\"\n     */\n    isEUCountry?: \"1\";\n    /**\n     * A two-letter code indicating the continent the request originated from.\n     *\n     * @example \"AN\"\n     */\n    continent?: ContinentCode;\n    /**\n     * The city the request originated from\n     *\n     * @example \"Austin\"\n     */\n    city?: string;\n    /**\n     * Postal code of the incoming request\n     *\n     * @example \"78701\"\n     */\n    postalCode?: string;\n    /**\n     * Latitude of the incoming request\n     *\n     * @example \"30.27130\"\n     */\n    latitude?: string;\n    /**\n     * Longitude of the incoming request\n     *\n     * @example \"-97.74260\"\n     */\n    longitude?: string;\n    /**\n     * Timezone of the incoming request\n     *\n     * @example \"America/Chicago\"\n     */\n    timezone?: string;\n    /**\n     * If known, the ISO 3166-2 name for the first level region associated with\n     * the IP address of the incoming request\n     *\n     * @example \"Texas\"\n     */\n    region?: string;\n    /**\n     * If known, the ISO 3166-2 code for the first-level region associated with\n     * the IP address of the incoming request\n     *\n     * @example \"TX\"\n     */\n    regionCode?: string;\n    /**\n     * Metro code (DMA) of the incoming request\n     *\n     * @example \"635\"\n     */\n    metroCode?: string;\n}\n/** Data about the incoming request's TLS certificate */\ninterface IncomingRequestCfPropertiesTLSClientAuth {\n    /** Always `\"1\"`, indicating that the certificate was presented */\n    certPresented: \"1\";\n    /**\n     * Result of certificate verification.\n     *\n     * @example \"FAILED:self signed certificate\"\n     */\n    certVerified: Exclude<CertVerificationStatus, \"NONE\">;\n    /** The presented certificate's revokation status.\n     *\n     * - A value of `\"1\"` indicates the certificate has been revoked\n     * - A value of `\"0\"` indicates the certificate has not been revoked\n     */\n    certRevoked: \"1\" | \"0\";\n    /**\n     * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)\n     *\n     * @example \"CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare\"\n     */\n    certIssuerDN: string;\n    /**\n     * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)\n     *\n     * @example \"CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare\"\n     */\n    certSubjectDN: string;\n    /**\n     * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)\n     *\n     * @example \"CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare\"\n     */\n    certIssuerDNRFC2253: string;\n    /**\n     * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)\n     *\n     * @example \"CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare\"\n     */\n    certSubjectDNRFC2253: string;\n    /** The certificate issuer's distinguished name (legacy policies) */\n    certIssuerDNLegacy: string;\n    /** The certificate subject's distinguished name (legacy policies) */\n    certSubjectDNLegacy: string;\n    /**\n     * The certificate's serial number\n     *\n     * @example \"00936EACBE07F201DF\"\n     */\n    certSerial: string;\n    /**\n     * The certificate issuer's serial number\n     *\n     * @example \"2489002934BDFEA34\"\n     */\n    certIssuerSerial: string;\n    /**\n     * The certificate's Subject Key Identifier\n     *\n     * @example \"BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4\"\n     */\n    certSKI: string;\n    /**\n     * The certificate issuer's Subject Key Identifier\n     *\n     * @example \"BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4\"\n     */\n    certIssuerSKI: string;\n    /**\n     * The certificate's SHA-1 fingerprint\n     *\n     * @example \"6b9109f323999e52259cda7373ff0b4d26bd232e\"\n     */\n    certFingerprintSHA1: string;\n    /**\n     * The certificate's SHA-256 fingerprint\n     *\n     * @example \"acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea\"\n     */\n    certFingerprintSHA256: string;\n    /**\n     * The effective starting date of the certificate\n     *\n     * @example \"Dec 22 19:39:00 2018 GMT\"\n     */\n    certNotBefore: string;\n    /**\n     * The effective expiration date of the certificate\n     *\n     * @example \"Dec 22 19:39:00 2018 GMT\"\n     */\n    certNotAfter: string;\n}\n/** Placeholder values for TLS Client Authorization */\ninterface IncomingRequestCfPropertiesTLSClientAuthPlaceholder {\n    certPresented: \"0\";\n    certVerified: \"NONE\";\n    certRevoked: \"0\";\n    certIssuerDN: \"\";\n    certSubjectDN: \"\";\n    certIssuerDNRFC2253: \"\";\n    certSubjectDNRFC2253: \"\";\n    certIssuerDNLegacy: \"\";\n    certSubjectDNLegacy: \"\";\n    certSerial: \"\";\n    certIssuerSerial: \"\";\n    certSKI: \"\";\n    certIssuerSKI: \"\";\n    certFingerprintSHA1: \"\";\n    certFingerprintSHA256: \"\";\n    certNotBefore: \"\";\n    certNotAfter: \"\";\n}\n/** Possible outcomes of TLS verification */\ndeclare type CertVerificationStatus = \n/** Authentication succeeded */\n\"SUCCESS\"\n/** No certificate was presented */\n | \"NONE\"\n/** Failed because the certificate was self-signed */\n | \"FAILED:self signed certificate\"\n/** Failed because the certificate failed a trust chain check */\n | \"FAILED:unable to verify the first certificate\"\n/** Failed because the certificate not yet valid */\n | \"FAILED:certificate is not yet valid\"\n/** Failed because the certificate is expired */\n | \"FAILED:certificate has expired\"\n/** Failed for another unspecified reason */\n | \"FAILED\";\n/**\n * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare.\n */\ndeclare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */\n/** ISO 3166-1 Alpha-2 codes */\ndeclare type Iso3166Alpha2Code = \"AD\" | \"AE\" | \"AF\" | \"AG\" | \"AI\" | \"AL\" | \"AM\" | \"AO\" | \"AQ\" | \"AR\" | \"AS\" | \"AT\" | \"AU\" | \"AW\" | \"AX\" | \"AZ\" | \"BA\" | \"BB\" | \"BD\" | \"BE\" | \"BF\" | \"BG\" | \"BH\" | \"BI\" | \"BJ\" | \"BL\" | \"BM\" | \"BN\" | \"BO\" | \"BQ\" | \"BR\" | \"BS\" | \"BT\" | \"BV\" | \"BW\" | \"BY\" | \"BZ\" | \"CA\" | \"CC\" | \"CD\" | \"CF\" | \"CG\" | \"CH\" | \"CI\" | \"CK\" | \"CL\" | \"CM\" | \"CN\" | \"CO\" | \"CR\" | \"CU\" | \"CV\" | \"CW\" | \"CX\" | \"CY\" | \"CZ\" | \"DE\" | \"DJ\" | \"DK\" | \"DM\" | \"DO\" | \"DZ\" | \"EC\" | \"EE\" | \"EG\" | \"EH\" | \"ER\" | \"ES\" | \"ET\" | \"FI\" | \"FJ\" | \"FK\" | \"FM\" | \"FO\" | \"FR\" | \"GA\" | \"GB\" | \"GD\" | \"GE\" | \"GF\" | \"GG\" | \"GH\" | \"GI\" | \"GL\" | \"GM\" | \"GN\" | \"GP\" | \"GQ\" | \"GR\" | \"GS\" | \"GT\" | \"GU\" | \"GW\" | \"GY\" | \"HK\" | \"HM\" | \"HN\" | \"HR\" | \"HT\" | \"HU\" | \"ID\" | \"IE\" | \"IL\" | \"IM\" | \"IN\" | \"IO\" | \"IQ\" | \"IR\" | \"IS\" | \"IT\" | \"JE\" | \"JM\" | \"JO\" | \"JP\" | \"KE\" | \"KG\" | \"KH\" | \"KI\" | \"KM\" | \"KN\" | \"KP\" | \"KR\" | \"KW\" | \"KY\" | \"KZ\" | \"LA\" | \"LB\" | \"LC\" | \"LI\" | \"LK\" | \"LR\" | \"LS\" | \"LT\" | \"LU\" | \"LV\" | \"LY\" | \"MA\" | \"MC\" | \"MD\" | \"ME\" | \"MF\" | \"MG\" | \"MH\" | \"MK\" | \"ML\" | \"MM\" | \"MN\" | \"MO\" | \"MP\" | \"MQ\" | \"MR\" | \"MS\" | \"MT\" | \"MU\" | \"MV\" | \"MW\" | \"MX\" | \"MY\" | \"MZ\" | \"NA\" | \"NC\" | \"NE\" | \"NF\" | \"NG\" | \"NI\" | \"NL\" | \"NO\" | \"NP\" | \"NR\" | \"NU\" | \"NZ\" | \"OM\" | \"PA\" | \"PE\" | \"PF\" | \"PG\" | \"PH\" | \"PK\" | \"PL\" | \"PM\" | \"PN\" | \"PR\" | \"PS\" | \"PT\" | \"PW\" | \"PY\" | \"QA\" | \"RE\" | \"RO\" | \"RS\" | \"RU\" | \"RW\" | \"SA\" | \"SB\" | \"SC\" | \"SD\" | \"SE\" | \"SG\" | \"SH\" | \"SI\" | \"SJ\" | \"SK\" | \"SL\" | \"SM\" | \"SN\" | \"SO\" | \"SR\" | \"SS\" | \"ST\" | \"SV\" | \"SX\" | \"SY\" | \"SZ\" | \"TC\" | \"TD\" | \"TF\" | \"TG\" | \"TH\" | \"TJ\" | \"TK\" | \"TL\" | \"TM\" | \"TN\" | \"TO\" | \"TR\" | \"TT\" | \"TV\" | \"TW\" | \"TZ\" | \"UA\" | \"UG\" | \"UM\" | \"US\" | \"UY\" | \"UZ\" | \"VA\" | \"VC\" | \"VE\" | \"VG\" | \"VI\" | \"VN\" | \"VU\" | \"WF\" | \"WS\" | \"YE\" | \"YT\" | \"ZA\" | \"ZM\" | \"ZW\";\n/** The 2-letter continent codes Cloudflare uses */\ndeclare type ContinentCode = \"AF\" | \"AN\" | \"AS\" | \"EU\" | \"NA\" | \"OC\" | \"SA\";\ntype CfProperties<HostMetadata = unknown> = IncomingRequestCfProperties<HostMetadata> | RequestInitCfProperties;\ninterface D1Meta {\n    duration: number;\n    size_after: number;\n    rows_read: number;\n    rows_written: number;\n    last_row_id: number;\n    changed_db: boolean;\n    changes: number;\n    /**\n     * The region of the database instance that executed the query.\n     */\n    served_by_region?: string;\n    /**\n     * True if-and-only-if the database instance that executed the query was the primary.\n     */\n    served_by_primary?: boolean;\n    timings?: {\n        /**\n         * The duration of the SQL query execution by the database instance. It doesn't include any network time.\n         */\n        sql_duration_ms: number;\n    };\n    /**\n     * Number of total attempts to execute the query, due to automatic retries.\n     * Note: All other fields in the response like `timings` only apply to the last attempt.\n     */\n    total_attempts?: number;\n}\ninterface D1Response {\n    success: true;\n    meta: D1Meta & Record<string, unknown>;\n    error?: never;\n}\ntype D1Result<T = unknown> = D1Response & {\n    results: T[];\n};\ninterface D1ExecResult {\n    count: number;\n    duration: number;\n}\ntype D1SessionConstraint = \n// Indicates that the first query should go to the primary, and the rest queries\n// using the same D1DatabaseSession will go to any replica that is consistent with\n// the bookmark maintained by the session (returned by the first query).\n'first-primary'\n// Indicates that the first query can go anywhere (primary or replica), and the rest queries\n// using the same D1DatabaseSession will go to any replica that is consistent with\n// the bookmark maintained by the session (returned by the first query).\n | 'first-unconstrained';\ntype D1SessionBookmark = string;\ndeclare abstract class D1Database {\n    prepare(query: string): D1PreparedStatement;\n    batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;\n    exec(query: string): Promise<D1ExecResult>;\n    /**\n     * Creates a new D1 Session anchored at the given constraint or the bookmark.\n     * All queries executed using the created session will have sequential consistency,\n     * meaning that all writes done through the session will be visible in subsequent reads.\n     *\n     * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session.\n     */\n    withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession;\n    /**\n     * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases.\n     */\n    dump(): Promise<ArrayBuffer>;\n}\ndeclare abstract class D1DatabaseSession {\n    prepare(query: string): D1PreparedStatement;\n    batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;\n    /**\n     * @returns The latest session bookmark across all executed queries on the session.\n     *          If no query has been executed yet, `null` is returned.\n     */\n    getBookmark(): D1SessionBookmark | null;\n}\ndeclare abstract class D1PreparedStatement {\n    bind(...values: unknown[]): D1PreparedStatement;\n    first<T = unknown>(colName: string): Promise<T | null>;\n    first<T = Record<string, unknown>>(): Promise<T | null>;\n    run<T = Record<string, unknown>>(): Promise<D1Result<T>>;\n    all<T = Record<string, unknown>>(): Promise<D1Result<T>>;\n    raw<T = unknown[]>(options: {\n        columnNames: true;\n    }): Promise<[\n        string[],\n        ...T[]\n    ]>;\n    raw<T = unknown[]>(options?: {\n        columnNames?: false;\n    }): Promise<T[]>;\n}\n// `Disposable` was added to TypeScript's standard lib types in version 5.2.\n// To support older TypeScript versions, define an empty `Disposable` interface.\n// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2,\n// but this will ensure type checking on older versions still passes.\n// TypeScript's interface merging will ensure our empty interface is effectively\n// ignored when `Disposable` is included in the standard lib.\ninterface Disposable {\n}\n/**\n * An email message that can be sent from a Worker.\n */\ninterface EmailMessage {\n    /**\n     * Envelope From attribute of the email message.\n     */\n    readonly from: string;\n    /**\n     * Envelope To attribute of the email message.\n     */\n    readonly to: string;\n}\n/**\n * An email message that is sent to a consumer Worker and can be rejected/forwarded.\n */\ninterface ForwardableEmailMessage extends EmailMessage {\n    /**\n     * Stream of the email message content.\n     */\n    readonly raw: ReadableStream<Uint8Array>;\n    /**\n     * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).\n     */\n    readonly headers: Headers;\n    /**\n     * Size of the email message content.\n     */\n    readonly rawSize: number;\n    /**\n     * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason.\n     * @param reason The reject reason.\n     * @returns void\n     */\n    setReject(reason: string): void;\n    /**\n     * Forward this email message to a verified destination address of the account.\n     * @param rcptTo Verified destination address.\n     * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).\n     * @returns A promise that resolves when the email message is forwarded.\n     */\n    forward(rcptTo: string, headers?: Headers): Promise<void>;\n    /**\n     * Reply to the sender of this email message with a new EmailMessage object.\n     * @param message The reply message.\n     * @returns A promise that resolves when the email message is replied.\n     */\n    reply(message: EmailMessage): Promise<void>;\n}\n/**\n * A binding that allows a Worker to send email messages.\n */\ninterface SendEmail {\n    send(message: EmailMessage): Promise<void>;\n}\ndeclare abstract class EmailEvent extends ExtendableEvent {\n    readonly message: ForwardableEmailMessage;\n}\ndeclare type EmailExportedHandler<Env = unknown> = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise<void>;\ndeclare module \"cloudflare:email\" {\n    let _EmailMessage: {\n        prototype: EmailMessage;\n        new (from: string, to: string, raw: ReadableStream | string): EmailMessage;\n    };\n    export { _EmailMessage as EmailMessage };\n}\n/**\n * Hello World binding to serve as an explanatory example. DO NOT USE\n */\ninterface HelloWorldBinding {\n    /**\n     * Retrieve the current stored value\n     */\n    get(): Promise<{\n        value: string;\n        ms?: number;\n    }>;\n    /**\n     * Set a new stored value\n     */\n    set(value: string): Promise<void>;\n}\ninterface Hyperdrive {\n    /**\n     * Connect directly to Hyperdrive as if it's your database, returning a TCP socket.\n     *\n     * Calling this method returns an idential socket to if you call\n     * `connect(\"host:port\")` using the `host` and `port` fields from this object.\n     * Pick whichever approach works better with your preferred DB client library.\n     *\n     * Note that this socket is not yet authenticated -- it's expected that your\n     * code (or preferably, the client library of your choice) will authenticate\n     * using the information in this class's readonly fields.\n     */\n    connect(): Socket;\n    /**\n     * A valid DB connection string that can be passed straight into the typical\n     * client library/driver/ORM. This will typically be the easiest way to use\n     * Hyperdrive.\n     */\n    readonly connectionString: string;\n    /*\n     * A randomly generated hostname that is only valid within the context of the\n     * currently running Worker which, when passed into `connect()` function from\n     * the \"cloudflare:sockets\" module, will connect to the Hyperdrive instance\n     * for your database.\n     */\n    readonly host: string;\n    /*\n     * The port that must be paired the the host field when connecting.\n     */\n    readonly port: number;\n    /*\n     * The username to use when authenticating to your database via Hyperdrive.\n     * Unlike the host and password, this will be the same every time\n     */\n    readonly user: string;\n    /*\n     * The randomly generated password to use when authenticating to your\n     * database via Hyperdrive. Like the host field, this password is only valid\n     * within the context of the currently running Worker instance from which\n     * it's read.\n     */\n    readonly password: string;\n    /*\n     * The name of the database to connect to.\n     */\n    readonly database: string;\n}\n// Copyright (c) 2024 Cloudflare, Inc.\n// Licensed under the Apache 2.0 license found in the LICENSE file or at:\n//     https://opensource.org/licenses/Apache-2.0\ntype ImageInfoResponse = {\n    format: 'image/svg+xml';\n} | {\n    format: string;\n    fileSize: number;\n    width: number;\n    height: number;\n};\ntype ImageTransform = {\n    width?: number;\n    height?: number;\n    background?: string;\n    blur?: number;\n    border?: {\n        color?: string;\n        width?: number;\n    } | {\n        top?: number;\n        bottom?: number;\n        left?: number;\n        right?: number;\n    };\n    brightness?: number;\n    contrast?: number;\n    fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop';\n    flip?: 'h' | 'v' | 'hv';\n    gamma?: number;\n    segment?: 'foreground';\n    gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | {\n        x?: number;\n        y?: number;\n        mode: 'remainder' | 'box-center';\n    };\n    rotate?: 0 | 90 | 180 | 270;\n    saturation?: number;\n    sharpen?: number;\n    trim?: 'border' | {\n        top?: number;\n        bottom?: number;\n        left?: number;\n        right?: number;\n        width?: number;\n        height?: number;\n        border?: boolean | {\n            color?: string;\n            tolerance?: number;\n            keep?: number;\n        };\n    };\n};\ntype ImageDrawOptions = {\n    opacity?: number;\n    repeat?: boolean | string;\n    top?: number;\n    left?: number;\n    bottom?: number;\n    right?: number;\n};\ntype ImageInputOptions = {\n    encoding?: 'base64';\n};\ntype ImageOutputOptions = {\n    format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba';\n    quality?: number;\n    background?: string;\n    anim?: boolean;\n};\ninterface ImagesBinding {\n    /**\n     * Get image metadata (type, width and height)\n     * @throws {@link ImagesError} with code 9412 if input is not an image\n     * @param stream The image bytes\n     */\n    info(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): Promise<ImageInfoResponse>;\n    /**\n     * Begin applying a series of transformations to an image\n     * @param stream The image bytes\n     * @returns A transform handle\n     */\n    input(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): ImageTransformer;\n}\ninterface ImageTransformer {\n    /**\n     * Apply transform next, returning a transform handle.\n     * You can then apply more transformations, draw, or retrieve the output.\n     * @param transform\n     */\n    transform(transform: ImageTransform): ImageTransformer;\n    /**\n     * Draw an image on this transformer, returning a transform handle.\n     * You can then apply more transformations, draw, or retrieve the output.\n     * @param image The image (or transformer that will give the image) to draw\n     * @param options The options configuring how to draw the image\n     */\n    draw(image: ReadableStream<Uint8Array> | ImageTransformer, options?: ImageDrawOptions): ImageTransformer;\n    /**\n     * Retrieve the image that results from applying the transforms to the\n     * provided input\n     * @param options Options that apply to the output e.g. output format\n     */\n    output(options: ImageOutputOptions): Promise<ImageTransformationResult>;\n}\ntype ImageTransformationOutputOptions = {\n    encoding?: 'base64';\n};\ninterface ImageTransformationResult {\n    /**\n     * The image as a response, ready to store in cache or return to users\n     */\n    response(): Response;\n    /**\n     * The content type of the returned image\n     */\n    contentType(): string;\n    /**\n     * The bytes of the response\n     */\n    image(options?: ImageTransformationOutputOptions): ReadableStream<Uint8Array>;\n}\ninterface ImagesError extends Error {\n    readonly code: number;\n    readonly message: string;\n    readonly stack?: string;\n}\n/**\n * Media binding for transforming media streams.\n * Provides the entry point for media transformation operations.\n */\ninterface MediaBinding {\n    /**\n     * Creates a media transformer from an input stream.\n     * @param media - The input media bytes\n     * @returns A MediaTransformer instance for applying transformations\n     */\n    input(media: ReadableStream<Uint8Array>): MediaTransformer;\n}\n/**\n * Media transformer for applying transformation operations to media content.\n * Handles sizing, fitting, and other input transformation parameters.\n */\ninterface MediaTransformer {\n    /**\n     * Applies transformation options to the media content.\n     * @param transform - Configuration for how the media should be transformed\n     * @returns A generator for producing the transformed media output\n     */\n    transform(transform: MediaTransformationInputOptions): MediaTransformationGenerator;\n}\n/**\n * Generator for producing media transformation results.\n * Configures the output format and parameters for the transformed media.\n */\ninterface MediaTransformationGenerator {\n    /**\n     * Generates the final media output with specified options.\n     * @param output - Configuration for the output format and parameters\n     * @returns The final transformation result containing the transformed media\n     */\n    output(output: MediaTransformationOutputOptions): MediaTransformationResult;\n}\n/**\n * Result of a media transformation operation.\n * Provides multiple ways to access the transformed media content.\n */\ninterface MediaTransformationResult {\n    /**\n     * Returns the transformed media as a readable stream of bytes.\n     * @returns A stream containing the transformed media data\n     */\n    media(): ReadableStream<Uint8Array>;\n    /**\n     * Returns the transformed media as an HTTP response object.\n     * @returns The transformed media as a Response, ready to store in cache or return to users\n     */\n    response(): Response;\n    /**\n     * Returns the MIME type of the transformed media.\n     * @returns The content type string (e.g., 'image/jpeg', 'video/mp4')\n     */\n    contentType(): string;\n}\n/**\n * Configuration options for transforming media input.\n * Controls how the media should be resized and fitted.\n */\ntype MediaTransformationInputOptions = {\n    /** How the media should be resized to fit the specified dimensions */\n    fit?: 'contain' | 'cover' | 'scale-down';\n    /** Target width in pixels */\n    width?: number;\n    /** Target height in pixels */\n    height?: number;\n};\n/**\n * Configuration options for Media Transformations output.\n * Controls the format, timing, and type of the generated output.\n */\ntype MediaTransformationOutputOptions = {\n    /**\n     * Output mode determining the type of media to generate\n     */\n    mode?: 'video' | 'spritesheet' | 'frame' | 'audio';\n    /** Whether to include audio in the output */\n    audio?: boolean;\n    /**\n     * Starting timestamp for frame extraction or start time for clips. (e.g. '2s').\n     */\n    time?: string;\n    /**\n     * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s').\n     */\n    duration?: string;\n    /**\n     * Output format for the generated media.\n     */\n    format?: 'jpg' | 'png' | 'm4a';\n};\n/**\n * Error object for media transformation operations.\n * Extends the standard Error interface with additional media-specific information.\n */\ninterface MediaError extends Error {\n    readonly code: number;\n    readonly message: string;\n    readonly stack?: string;\n}\ntype Params<P extends string = any> = Record<P, string | string[]>;\ntype EventContext<Env, P extends string, Data> = {\n    request: Request<unknown, IncomingRequestCfProperties<unknown>>;\n    functionPath: string;\n    waitUntil: (promise: Promise<any>) => void;\n    passThroughOnException: () => void;\n    next: (input?: Request | string, init?: RequestInit) => Promise<Response>;\n    env: Env & {\n        ASSETS: {\n            fetch: typeof fetch;\n        };\n    };\n    params: Params<P>;\n    data: Data;\n};\ntype PagesFunction<Env = unknown, Params extends string = any, Data extends Record<string, unknown> = Record<string, unknown>> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>;\ntype EventPluginContext<Env, P extends string, Data, PluginArgs> = {\n    request: Request<unknown, IncomingRequestCfProperties<unknown>>;\n    functionPath: string;\n    waitUntil: (promise: Promise<any>) => void;\n    passThroughOnException: () => void;\n    next: (input?: Request | string, init?: RequestInit) => Promise<Response>;\n    env: Env & {\n        ASSETS: {\n            fetch: typeof fetch;\n        };\n    };\n    params: Params<P>;\n    data: Data;\n    pluginArgs: PluginArgs;\n};\ntype PagesPluginFunction<Env = unknown, Params extends string = any, Data extends Record<string, unknown> = Record<string, unknown>, PluginArgs = unknown> = (context: EventPluginContext<Env, Params, Data, PluginArgs>) => Response | Promise<Response>;\ndeclare module \"assets:*\" {\n    export const onRequest: PagesFunction;\n}\n// Copyright (c) 2022-2023 Cloudflare, Inc.\n// Licensed under the Apache 2.0 license found in the LICENSE file or at:\n//     https://opensource.org/licenses/Apache-2.0\ndeclare module \"cloudflare:pipelines\" {\n    export abstract class PipelineTransformationEntrypoint<Env = unknown, I extends PipelineRecord = PipelineRecord, O extends PipelineRecord = PipelineRecord> {\n        protected env: Env;\n        protected ctx: ExecutionContext;\n        constructor(ctx: ExecutionContext, env: Env);\n        /**\n         * run recieves an array of PipelineRecord which can be\n         * transformed and returned to the pipeline\n         * @param records Incoming records from the pipeline to be transformed\n         * @param metadata Information about the specific pipeline calling the transformation entrypoint\n         * @returns A promise containing the transformed PipelineRecord array\n         */\n        public run(records: I[], metadata: PipelineBatchMetadata): Promise<O[]>;\n    }\n    export type PipelineRecord = Record<string, unknown>;\n    export type PipelineBatchMetadata = {\n        pipelineId: string;\n        pipelineName: string;\n    };\n    export interface Pipeline<T extends PipelineRecord = PipelineRecord> {\n        /**\n         * The Pipeline interface represents the type of a binding to a Pipeline\n         *\n         * @param records The records to send to the pipeline\n         */\n        send(records: T[]): Promise<void>;\n    }\n}\n// PubSubMessage represents an incoming PubSub message.\n// The message includes metadata about the broker, the client, and the payload\n// itself.\n// https://developers.cloudflare.com/pub-sub/\ninterface PubSubMessage {\n    // Message ID\n    readonly mid: number;\n    // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT\n    readonly broker: string;\n    // The MQTT topic the message was sent on.\n    readonly topic: string;\n    // The client ID of the client that published this message.\n    readonly clientId: string;\n    // The unique identifier (JWT ID) used by the client to authenticate, if token\n    // auth was used.\n    readonly jti?: string;\n    // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker\n    // received the message from the client.\n    readonly receivedAt: number;\n    // An (optional) string with the MIME type of the payload, if set by the\n    // client.\n    readonly contentType: string;\n    // Set to 1 when the payload is a UTF-8 string\n    // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063\n    readonly payloadFormatIndicator: number;\n    // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays.\n    // You can use payloadFormatIndicator to inspect this before decoding.\n    payload: string | Uint8Array;\n}\n// JsonWebKey extended by kid parameter\ninterface JsonWebKeyWithKid extends JsonWebKey {\n    // Key Identifier of the JWK\n    readonly kid: string;\n}\ninterface RateLimitOptions {\n    key: string;\n}\ninterface RateLimitOutcome {\n    success: boolean;\n}\ninterface RateLimit {\n    /**\n     * Rate limit a request based on the provided options.\n     * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/\n     * @returns A promise that resolves with the outcome of the rate limit.\n     */\n    limit(options: RateLimitOptions): Promise<RateLimitOutcome>;\n}\n// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need\n// to referenced by `Fetcher`. This is included in the \"importable\" version of the types which\n// strips all `module` blocks.\ndeclare namespace Rpc {\n    // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.\n    // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.\n    // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to\n    // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape)\n    export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND';\n    export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';\n    export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND';\n    export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND';\n    export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND';\n    export interface RpcTargetBranded {\n        [__RPC_TARGET_BRAND]: never;\n    }\n    export interface WorkerEntrypointBranded {\n        [__WORKER_ENTRYPOINT_BRAND]: never;\n    }\n    export interface DurableObjectBranded {\n        [__DURABLE_OBJECT_BRAND]: never;\n    }\n    export interface WorkflowEntrypointBranded {\n        [__WORKFLOW_ENTRYPOINT_BRAND]: never;\n    }\n    export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded;\n    // Types that can be used through `Stub`s\n    export type Stubable = RpcTargetBranded | ((...args: any[]) => any);\n    // Types that can be passed over RPC\n    // The reason for using a generic type here is to build a serializable subset of structured\n    //   cloneable composite types. This allows types defined with the \"interface\" keyword to pass the\n    //   serializable check as well. Otherwise, only types defined with the \"type\" keyword would pass.\n    type Serializable<T> = \n    // Structured cloneables\n    BaseType\n    // Structured cloneable composites\n     | Map<T extends Map<infer U, unknown> ? Serializable<U> : never, T extends Map<unknown, infer U> ? Serializable<U> : never> | Set<T extends Set<infer U> ? Serializable<U> : never> | ReadonlyArray<T extends ReadonlyArray<infer U> ? Serializable<U> : never> | {\n        [K in keyof T]: K extends number | string ? Serializable<T[K]> : never;\n    }\n    // Special types\n     | Stub<Stubable>\n    // Serialized as stubs, see `Stubify`\n     | Stubable;\n    // Base type for all RPC stubs, including common memory management methods.\n    // `T` is used as a marker type for unwrapping `Stub`s later.\n    interface StubBase<T extends Stubable> extends Disposable {\n        [__RPC_STUB_BRAND]: T;\n        dup(): this;\n    }\n    export type Stub<T extends Stubable> = Provider<T> & StubBase<T>;\n    // This represents all the types that can be sent as-is over an RPC boundary\n    type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream<Uint8Array> | WritableStream<Uint8Array> | Request | Response | Headers;\n    // Recursively rewrite all `Stubable` types with `Stub`s\n    // prettier-ignore\n    type Stubify<T> = T extends Stubable ? Stub<T> : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T : T extends {\n        [key: string | number]: any;\n    } ? {\n        [K in keyof T]: Stubify<T[K]>;\n    } : T;\n    // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.\n    // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:\n    // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.\n    // prettier-ignore\n    type Unstubify<T> = T extends StubBase<infer V> ? V : T extends Map<infer K, infer V> ? Map<Unstubify<K>, Unstubify<V>> : T extends Set<infer V> ? Set<Unstubify<V>> : T extends Array<infer V> ? Array<Unstubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Unstubify<V>> : T extends BaseType ? T : T extends {\n        [key: string | number]: unknown;\n    } ? {\n        [K in keyof T]: Unstubify<T[K]>;\n    } : T;\n    type UnstubifyAll<A extends any[]> = {\n        [I in keyof A]: Unstubify<A[I]>;\n    };\n    // Utility type for adding `Provider`/`Disposable`s to `object` types only.\n    // Note `unknown & T` is equivalent to `T`.\n    type MaybeProvider<T> = T extends object ? Provider<T> : unknown;\n    type MaybeDisposable<T> = T extends object ? Disposable : unknown;\n    // Type for method return or property on an RPC interface.\n    // - Stubable types are replaced by stubs.\n    // - Serializable types are passed by value, with stubable types replaced by stubs\n    //   and a top-level `Disposer`.\n    // Everything else can't be passed over PRC.\n    // Technically, we use custom thenables here, but they quack like `Promise`s.\n    // Intersecting with `(Maybe)Provider` allows pipelining.\n    // prettier-ignore\n    type Result<R> = R extends Stubable ? Promise<Stub<R>> & Provider<R> : R extends Serializable<R> ? Promise<Stubify<R> & MaybeDisposable<R>> & MaybeProvider<R> : never;\n    // Type for method or property on an RPC interface.\n    // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.\n    // Unwrapping `Stub`s allows calling with `Stubable` arguments.\n    // For properties, rewrite types to be `Result`s.\n    // In each case, unwrap `Promise`s.\n    type MethodOrProperty<V> = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>;\n    // Type for the callable part of an `Provider` if `T` is callable.\n    // This is intersected with methods/properties.\n    type MaybeCallableProvider<T> = T extends (...args: any[]) => any ? MethodOrProperty<T> : unknown;\n    // Base type for all other types providing RPC-like interfaces.\n    // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.\n    // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC.\n    export type Provider<T extends object, Reserved extends string = never> = MaybeCallableProvider<T> & {\n        [K in Exclude<keyof T, Reserved | symbol | keyof StubBase<never>>]: MethodOrProperty<T[K]>;\n    };\n}\ndeclare namespace Cloudflare {\n    // Type of `env`.\n    //\n    // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript\n    // will merge all declarations.\n    //\n    // You can use `wrangler types` to generate the `Env` type automatically.\n    interface Env {\n    }\n    // Project-specific parameters used to inform types.\n    //\n    // This interface is, again, intended to be declared in project-specific files, and then that\n    // declaration will be merged with this one.\n    //\n    // A project should have a declaration like this:\n    //\n    //     interface GlobalProps {\n    //       // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type\n    //       // of `ctx.exports`.\n    //       mainModule: typeof import(\"my-main-module\");\n    //\n    //       // Declares which of the main module's exports are configured with durable storage, and\n    //       // thus should behave as Durable Object namsepace bindings.\n    //       durableNamespaces: \"MyDurableObject\" | \"AnotherDurableObject\";\n    //     }\n    //\n    // You can use `wrangler types` to generate `GlobalProps` automatically.\n    interface GlobalProps {\n    }\n    // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not\n    // present.\n    type GlobalProp<K extends string, Default> = K extends keyof GlobalProps ? GlobalProps[K] : Default;\n    // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the\n    // `mainModule` property.\n    type MainModule = GlobalProp<\"mainModule\", {}>;\n    // The type of ctx.exports, which contains loopback bindings for all top-level exports.\n    type Exports = {\n        [K in keyof MainModule]: LoopbackForExport<MainModule[K]>\n        // If the export is listed in `durableNamespaces`, then it is also a\n        // DurableObjectNamespace.\n         & (K extends GlobalProp<\"durableNamespaces\", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace<DoInstance> : DurableObjectNamespace<undefined> : DurableObjectNamespace<undefined> : {});\n    };\n}\ndeclare module 'cloudflare:node' {\n    export interface DefaultHandler {\n        fetch?(request: Request): Response | Promise<Response>;\n        tail?(events: TraceItem[]): void | Promise<void>;\n        trace?(traces: TraceItem[]): void | Promise<void>;\n        scheduled?(controller: ScheduledController): void | Promise<void>;\n        queue?(batch: MessageBatch<unknown>): void | Promise<void>;\n        test?(controller: TestController): void | Promise<void>;\n    }\n    export function httpServerHandler(options: {\n        port: number;\n    }, handlers?: Omit<DefaultHandler, 'fetch'>): DefaultHandler;\n}\ndeclare namespace CloudflareWorkersModule {\n    export type RpcStub<T extends Rpc.Stubable> = Rpc.Stub<T>;\n    export const RpcStub: {\n        new <T extends Rpc.Stubable>(value: T): Rpc.Stub<T>;\n    };\n    export abstract class RpcTarget implements Rpc.RpcTargetBranded {\n        [Rpc.__RPC_TARGET_BRAND]: never;\n    }\n    // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC\n    export abstract class WorkerEntrypoint<Env = Cloudflare.Env, Props = {}> implements Rpc.WorkerEntrypointBranded {\n        [Rpc.__WORKER_ENTRYPOINT_BRAND]: never;\n        protected ctx: ExecutionContext<Props>;\n        protected env: Env;\n        constructor(ctx: ExecutionContext, env: Env);\n        fetch?(request: Request): Response | Promise<Response>;\n        tail?(events: TraceItem[]): void | Promise<void>;\n        trace?(traces: TraceItem[]): void | Promise<void>;\n        scheduled?(controller: ScheduledController): void | Promise<void>;\n        queue?(batch: MessageBatch<unknown>): void | Promise<void>;\n        test?(controller: TestController): void | Promise<void>;\n    }\n    export abstract class DurableObject<Env = Cloudflare.Env, Props = {}> implements Rpc.DurableObjectBranded {\n        [Rpc.__DURABLE_OBJECT_BRAND]: never;\n        protected ctx: DurableObjectState<Props>;\n        protected env: Env;\n        constructor(ctx: DurableObjectState, env: Env);\n        fetch?(request: Request): Response | Promise<Response>;\n        alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;\n        webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;\n        webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;\n        webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;\n    }\n    export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';\n    export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;\n    export type WorkflowDelayDuration = WorkflowSleepDuration;\n    export type WorkflowTimeoutDuration = WorkflowSleepDuration;\n    export type WorkflowRetentionDuration = WorkflowSleepDuration;\n    export type WorkflowBackoff = 'constant' | 'linear' | 'exponential';\n    export type WorkflowStepConfig = {\n        retries?: {\n            limit: number;\n            delay: WorkflowDelayDuration | number;\n            backoff?: WorkflowBackoff;\n        };\n        timeout?: WorkflowTimeoutDuration | number;\n    };\n    export type WorkflowEvent<T> = {\n        payload: Readonly<T>;\n        timestamp: Date;\n        instanceId: string;\n    };\n    export type WorkflowStepEvent<T> = {\n        payload: Readonly<T>;\n        timestamp: Date;\n        type: string;\n    };\n    export abstract class WorkflowStep {\n        do<T extends Rpc.Serializable<T>>(name: string, callback: () => Promise<T>): Promise<T>;\n        do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfig, callback: () => Promise<T>): Promise<T>;\n        sleep: (name: string, duration: WorkflowSleepDuration) => Promise<void>;\n        sleepUntil: (name: string, timestamp: Date | number) => Promise<void>;\n        waitForEvent<T extends Rpc.Serializable<T>>(name: string, options: {\n            type: string;\n            timeout?: WorkflowTimeoutDuration | number;\n        }): Promise<WorkflowStepEvent<T>>;\n    }\n    export abstract class WorkflowEntrypoint<Env = unknown, T extends Rpc.Serializable<T> | unknown = unknown> implements Rpc.WorkflowEntrypointBranded {\n        [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never;\n        protected ctx: ExecutionContext;\n        protected env: Env;\n        constructor(ctx: ExecutionContext, env: Env);\n        run(event: Readonly<WorkflowEvent<T>>, step: WorkflowStep): Promise<unknown>;\n    }\n    export function waitUntil(promise: Promise<unknown>): void;\n    export const env: Cloudflare.Env;\n}\ndeclare module 'cloudflare:workers' {\n    export = CloudflareWorkersModule;\n}\ninterface SecretsStoreSecret {\n    /**\n     * Get a secret from the Secrets Store, returning a string of the secret value\n     * if it exists, or throws an error if it does not exist\n     */\n    get(): Promise<string>;\n}\ndeclare module \"cloudflare:sockets\" {\n    function _connect(address: string | SocketAddress, options?: SocketOptions): Socket;\n    export { _connect as connect };\n}\ndeclare namespace TailStream {\n    interface Header {\n        readonly name: string;\n        readonly value: string;\n    }\n    interface FetchEventInfo {\n        readonly type: \"fetch\";\n        readonly method: string;\n        readonly url: string;\n        readonly cfJson?: object;\n        readonly headers: Header[];\n    }\n    interface JsRpcEventInfo {\n        readonly type: \"jsrpc\";\n    }\n    interface ScheduledEventInfo {\n        readonly type: \"scheduled\";\n        readonly scheduledTime: Date;\n        readonly cron: string;\n    }\n    interface AlarmEventInfo {\n        readonly type: \"alarm\";\n        readonly scheduledTime: Date;\n    }\n    interface QueueEventInfo {\n        readonly type: \"queue\";\n        readonly queueName: string;\n        readonly batchSize: number;\n    }\n    interface EmailEventInfo {\n        readonly type: \"email\";\n        readonly mailFrom: string;\n        readonly rcptTo: string;\n        readonly rawSize: number;\n    }\n    interface TraceEventInfo {\n        readonly type: \"trace\";\n        readonly traces: (string | null)[];\n    }\n    interface HibernatableWebSocketEventInfoMessage {\n        readonly type: \"message\";\n    }\n    interface HibernatableWebSocketEventInfoError {\n        readonly type: \"error\";\n    }\n    interface HibernatableWebSocketEventInfoClose {\n        readonly type: \"close\";\n        readonly code: number;\n        readonly wasClean: boolean;\n    }\n    interface HibernatableWebSocketEventInfo {\n        readonly type: \"hibernatableWebSocket\";\n        readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage;\n    }\n    interface CustomEventInfo {\n        readonly type: \"custom\";\n    }\n    interface FetchResponseInfo {\n        readonly type: \"fetch\";\n        readonly statusCode: number;\n    }\n    type EventOutcome = \"ok\" | \"canceled\" | \"exception\" | \"unknown\" | \"killSwitch\" | \"daemonDown\" | \"exceededCpu\" | \"exceededMemory\" | \"loadShed\" | \"responseStreamDisconnected\" | \"scriptNotFound\";\n    interface ScriptVersion {\n        readonly id: string;\n        readonly tag?: string;\n        readonly message?: string;\n    }\n    interface Onset {\n        readonly type: \"onset\";\n        readonly attributes: Attribute[];\n        // id for the span being opened by this Onset event.\n        readonly spanId: string;\n        readonly dispatchNamespace?: string;\n        readonly entrypoint?: string;\n        readonly executionModel: string;\n        readonly scriptName?: string;\n        readonly scriptTags?: string[];\n        readonly scriptVersion?: ScriptVersion;\n        readonly info: FetchEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo;\n    }\n    interface Outcome {\n        readonly type: \"outcome\";\n        readonly outcome: EventOutcome;\n        readonly cpuTime: number;\n        readonly wallTime: number;\n    }\n    interface SpanOpen {\n        readonly type: \"spanOpen\";\n        readonly name: string;\n        // id for the span being opened by this SpanOpen event.\n        readonly spanId: string;\n        readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes;\n    }\n    interface SpanClose {\n        readonly type: \"spanClose\";\n        readonly outcome: EventOutcome;\n    }\n    interface DiagnosticChannelEvent {\n        readonly type: \"diagnosticChannel\";\n        readonly channel: string;\n        readonly message: any;\n    }\n    interface Exception {\n        readonly type: \"exception\";\n        readonly name: string;\n        readonly message: string;\n        readonly stack?: string;\n    }\n    interface Log {\n        readonly type: \"log\";\n        readonly level: \"debug\" | \"error\" | \"info\" | \"log\" | \"warn\";\n        readonly message: object;\n    }\n    // This marks the worker handler return information.\n    // This is separate from Outcome because the worker invocation can live for a long time after\n    // returning. For example - Websockets that return an http upgrade response but then continue\n    // streaming information or SSE http connections.\n    interface Return {\n        readonly type: \"return\";\n        readonly info?: FetchResponseInfo;\n    }\n    interface Attribute {\n        readonly name: string;\n        readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[];\n    }\n    interface Attributes {\n        readonly type: \"attributes\";\n        readonly info: Attribute[];\n    }\n    type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Attributes;\n    // Context in which this trace event lives.\n    interface SpanContext {\n        // Single id for the entire top-level invocation\n        // This should be a new traceId for the first worker stage invoked in the eyeball request and then\n        // same-account service-bindings should reuse the same traceId but cross-account service-bindings\n        // should use a new traceId.\n        readonly traceId: string;\n        // spanId in which this event is handled\n        // for Onset and SpanOpen events this would be the parent span id\n        // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events\n        // For Hibernate and Mark this would be the span under which they were emitted.\n        // spanId is not set ONLY if:\n        //  1. This is an Onset event\n        //  2. We are not inherting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation)\n        readonly spanId?: string;\n    }\n    interface TailEvent<Event extends EventType> {\n        // invocation id of the currently invoked worker stage.\n        // invocation id will always be unique to every Onset event and will be the same until the Outcome event.\n        readonly invocationId: string;\n        // Inherited spanContext for this event.\n        readonly spanContext: SpanContext;\n        readonly timestamp: Date;\n        readonly sequence: number;\n        readonly event: Event;\n    }\n    type TailEventHandler<Event extends EventType = EventType> = (event: TailEvent<Event>) => void | Promise<void>;\n    type TailEventHandlerObject = {\n        outcome?: TailEventHandler<Outcome>;\n        spanOpen?: TailEventHandler<SpanOpen>;\n        spanClose?: TailEventHandler<SpanClose>;\n        diagnosticChannel?: TailEventHandler<DiagnosticChannelEvent>;\n        exception?: TailEventHandler<Exception>;\n        log?: TailEventHandler<Log>;\n        return?: TailEventHandler<Return>;\n        attributes?: TailEventHandler<Attributes>;\n    };\n    type TailEventHandlerType = TailEventHandler | TailEventHandlerObject;\n}\n// Copyright (c) 2022-2023 Cloudflare, Inc.\n// Licensed under the Apache 2.0 license found in the LICENSE file or at:\n//     https://opensource.org/licenses/Apache-2.0\n/**\n * Data types supported for holding vector metadata.\n */\ntype VectorizeVectorMetadataValue = string | number | boolean | string[];\n/**\n * Additional information to associate with a vector.\n */\ntype VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record<string, VectorizeVectorMetadataValue>;\ntype VectorFloatArray = Float32Array | Float64Array;\ninterface VectorizeError {\n    code?: number;\n    error: string;\n}\n/**\n * Comparison logic/operation to use for metadata filtering.\n *\n * This list is expected to grow as support for more operations are released.\n */\ntype VectorizeVectorMetadataFilterOp = \"$eq\" | \"$ne\";\n/**\n * Filter criteria for vector metadata used to limit the retrieved query result set.\n */\ntype VectorizeVectorMetadataFilter = {\n    [field: string]: Exclude<VectorizeVectorMetadataValue, string[]> | null | {\n        [Op in VectorizeVectorMetadataFilterOp]?: Exclude<VectorizeVectorMetadataValue, string[]> | null;\n    };\n};\n/**\n * Supported distance metrics for an index.\n * Distance metrics determine how other \"similar\" vectors are determined.\n */\ntype VectorizeDistanceMetric = \"euclidean\" | \"cosine\" | \"dot-product\";\n/**\n * Metadata return levels for a Vectorize query.\n *\n * Default to \"none\".\n *\n * @property all      Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data.\n * @property indexed  Return all metadata fields configured for indexing in the vector return set. This level of retrieval is \"free\" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings).\n * @property none     No indexed metadata will be returned.\n */\ntype VectorizeMetadataRetrievalLevel = \"all\" | \"indexed\" | \"none\";\ninterface VectorizeQueryOptions {\n    topK?: number;\n    namespace?: string;\n    returnValues?: boolean;\n    returnMetadata?: boolean | VectorizeMetadataRetrievalLevel;\n    filter?: VectorizeVectorMetadataFilter;\n}\n/**\n * Information about the configuration of an index.\n */\ntype VectorizeIndexConfig = {\n    dimensions: number;\n    metric: VectorizeDistanceMetric;\n} | {\n    preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity\n};\n/**\n * Metadata about an existing index.\n *\n * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.\n * See {@link VectorizeIndexInfo} for its post-beta equivalent.\n */\ninterface VectorizeIndexDetails {\n    /** The unique ID of the index */\n    readonly id: string;\n    /** The name of the index. */\n    name: string;\n    /** (optional) A human readable description for the index. */\n    description?: string;\n    /** The index configuration, including the dimension size and distance metric. */\n    config: VectorizeIndexConfig;\n    /** The number of records containing vectors within the index. */\n    vectorsCount: number;\n}\n/**\n * Metadata about an existing index.\n */\ninterface VectorizeIndexInfo {\n    /** The number of records containing vectors within the index. */\n    vectorCount: number;\n    /** Number of dimensions the index has been configured for. */\n    dimensions: number;\n    /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */\n    processedUpToDatetime: number;\n    /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */\n    processedUpToMutation: number;\n}\n/**\n * Represents a single vector value set along with its associated metadata.\n */\ninterface VectorizeVector {\n    /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */\n    id: string;\n    /** The vector values */\n    values: VectorFloatArray | number[];\n    /** The namespace this vector belongs to. */\n    namespace?: string;\n    /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */\n    metadata?: Record<string, VectorizeVectorMetadata>;\n}\n/**\n * Represents a matched vector for a query along with its score and (if specified) the matching vector information.\n */\ntype VectorizeMatch = Pick<Partial<VectorizeVector>, \"values\"> & Omit<VectorizeVector, \"values\"> & {\n    /** The score or rank for similarity, when returned as a result */\n    score: number;\n};\n/**\n * A set of matching {@link VectorizeMatch} for a particular query.\n */\ninterface VectorizeMatches {\n    matches: VectorizeMatch[];\n    count: number;\n}\n/**\n * Results of an operation that performed a mutation on a set of vectors.\n * Here, `ids` is a list of vectors that were successfully processed.\n *\n * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.\n * See {@link VectorizeAsyncMutation} for its post-beta equivalent.\n */\ninterface VectorizeVectorMutation {\n    /* List of ids of vectors that were successfully processed. */\n    ids: string[];\n    /* Total count of the number of processed vectors. */\n    count: number;\n}\n/**\n * Result type indicating a mutation on the Vectorize Index.\n * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation.\n */\ninterface VectorizeAsyncMutation {\n    /** The unique identifier for the async mutation operation containing the changeset. */\n    mutationId: string;\n}\n/**\n * A Vectorize Vector Search Index for querying vectors/embeddings.\n *\n * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.\n * See {@link Vectorize} for its new implementation.\n */\ndeclare abstract class VectorizeIndex {\n    /**\n     * Get information about the currently bound index.\n     * @returns A promise that resolves with information about the current index.\n     */\n    public describe(): Promise<VectorizeIndexDetails>;\n    /**\n     * Use the provided vector to perform a similarity search across the index.\n     * @param vector Input vector that will be used to drive the similarity search.\n     * @param options Configuration options to massage the returned data.\n     * @returns A promise that resolves with matched and scored vectors.\n     */\n    public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;\n    /**\n     * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.\n     * @param vectors List of vectors that will be inserted.\n     * @returns A promise that resolves with the ids & count of records that were successfully processed.\n     */\n    public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;\n    /**\n     * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.\n     * @param vectors List of vectors that will be upserted.\n     * @returns A promise that resolves with the ids & count of records that were successfully processed.\n     */\n    public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;\n    /**\n     * Delete a list of vectors with a matching id.\n     * @param ids List of vector ids that should be deleted.\n     * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted).\n     */\n    public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>;\n    /**\n     * Get a list of vectors with a matching id.\n     * @param ids List of vector ids that should be returned.\n     * @returns A promise that resolves with the raw unscored vectors matching the id set.\n     */\n    public getByIds(ids: string[]): Promise<VectorizeVector[]>;\n}\n/**\n * A Vectorize Vector Search Index for querying vectors/embeddings.\n *\n * Mutations in this version are async, returning a mutation id.\n */\ndeclare abstract class Vectorize {\n    /**\n     * Get information about the currently bound index.\n     * @returns A promise that resolves with information about the current index.\n     */\n    public describe(): Promise<VectorizeIndexInfo>;\n    /**\n     * Use the provided vector to perform a similarity search across the index.\n     * @param vector Input vector that will be used to drive the similarity search.\n     * @param options Configuration options to massage the returned data.\n     * @returns A promise that resolves with matched and scored vectors.\n     */\n    public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;\n    /**\n     * Use the provided vector-id to perform a similarity search across the index.\n     * @param vectorId Id for a vector in the index against which the index should be queried.\n     * @param options Configuration options to massage the returned data.\n     * @returns A promise that resolves with matched and scored vectors.\n     */\n    public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise<VectorizeMatches>;\n    /**\n     * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.\n     * @param vectors List of vectors that will be inserted.\n     * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset.\n     */\n    public insert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;\n    /**\n     * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.\n     * @param vectors List of vectors that will be upserted.\n     * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset.\n     */\n    public upsert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;\n    /**\n     * Delete a list of vectors with a matching id.\n     * @param ids List of vector ids that should be deleted.\n     * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset.\n     */\n    public deleteByIds(ids: string[]): Promise<VectorizeAsyncMutation>;\n    /**\n     * Get a list of vectors with a matching id.\n     * @param ids List of vector ids that should be returned.\n     * @returns A promise that resolves with the raw unscored vectors matching the id set.\n     */\n    public getByIds(ids: string[]): Promise<VectorizeVector[]>;\n}\n/**\n * The interface for \"version_metadata\" binding\n * providing metadata about the Worker Version using this binding.\n */\ntype WorkerVersionMetadata = {\n    /** The ID of the Worker Version using this binding */\n    id: string;\n    /** The tag of the Worker Version using this binding */\n    tag: string;\n    /** The timestamp of when the Worker Version was uploaded */\n    timestamp: string;\n};\ninterface DynamicDispatchLimits {\n    /**\n     * Limit CPU time in milliseconds.\n     */\n    cpuMs?: number;\n    /**\n     * Limit number of subrequests.\n     */\n    subRequests?: number;\n}\ninterface DynamicDispatchOptions {\n    /**\n     * Limit resources of invoked Worker script.\n     */\n    limits?: DynamicDispatchLimits;\n    /**\n     * Arguments for outbound Worker script, if configured.\n     */\n    outbound?: {\n        [key: string]: any;\n    };\n}\ninterface DispatchNamespace {\n    /**\n    * @param name Name of the Worker script.\n    * @param args Arguments to Worker script.\n    * @param options Options for Dynamic Dispatch invocation.\n    * @returns A Fetcher object that allows you to send requests to the Worker script.\n    * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown.\n    */\n    get(name: string, args?: {\n        [key: string]: any;\n    }, options?: DynamicDispatchOptions): Fetcher;\n}\ndeclare module 'cloudflare:workflows' {\n    /**\n     * NonRetryableError allows for a user to throw a fatal error\n     * that makes a Workflow instance fail immediately without triggering a retry\n     */\n    export class NonRetryableError extends Error {\n        public constructor(message: string, name?: string);\n    }\n}\ndeclare abstract class Workflow<PARAMS = unknown> {\n    /**\n     * Get a handle to an existing instance of the Workflow.\n     * @param id Id for the instance of this Workflow\n     * @returns A promise that resolves with a handle for the Instance\n     */\n    public get(id: string): Promise<WorkflowInstance>;\n    /**\n     * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown.\n     * @param options Options when creating an instance including id and params\n     * @returns A promise that resolves with a handle for the Instance\n     */\n    public create(options?: WorkflowInstanceCreateOptions<PARAMS>): Promise<WorkflowInstance>;\n    /**\n     * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown.\n     * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached.\n     * @param batch List of Options when creating an instance including name and params\n     * @returns A promise that resolves with a list of handles for the created instances.\n     */\n    public createBatch(batch: WorkflowInstanceCreateOptions<PARAMS>[]): Promise<WorkflowInstance[]>;\n}\ntype WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';\ntype WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;\ntype WorkflowRetentionDuration = WorkflowSleepDuration;\ninterface WorkflowInstanceCreateOptions<PARAMS = unknown> {\n    /**\n     * An id for your Workflow instance. Must be unique within the Workflow.\n     */\n    id?: string;\n    /**\n     * The event payload the Workflow instance is triggered with\n     */\n    params?: PARAMS;\n    /**\n     * The retention policy for Workflow instance.\n     * Defaults to the maximum retention period available for the owner's account.\n     */\n    retention?: {\n        successRetention?: WorkflowRetentionDuration;\n        errorRetention?: WorkflowRetentionDuration;\n    };\n}\ntype InstanceStatus = {\n    status: 'queued' // means that instance is waiting to be started (see concurrency limits)\n     | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running\n     | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish\n     | 'waitingForPause' // instance is finishing the current work to pause\n     | 'unknown';\n    error?: string;\n    output?: object;\n};\ninterface WorkflowError {\n    code?: number;\n    message: string;\n}\ndeclare abstract class WorkflowInstance {\n    public id: string;\n    /**\n     * Pause the instance.\n     */\n    public pause(): Promise<void>;\n    /**\n     * Resume the instance. If it is already running, an error will be thrown.\n     */\n    public resume(): Promise<void>;\n    /**\n     * Terminate the instance. If it is errored, terminated or complete, an error will be thrown.\n     */\n    public terminate(): Promise<void>;\n    /**\n     * Restart the instance.\n     */\n    public restart(): Promise<void>;\n    /**\n     * Returns the current status of the instance.\n     */\n    public status(): Promise<InstanceStatus>;\n    /**\n     * Send an event to this instance.\n     */\n    public sendEvent({ type, payload, }: {\n        type: string;\n        payload: unknown;\n    }): Promise<void>;\n}\n"
  },
  {
    "path": "test/cloudflare/wrangler.jsonc",
    "content": "/**\n * For more details on how to configure Wrangler, refer to:\n * https://developers.cloudflare.com/workers/wrangler/configuration/\n */\n{\n\t\"$schema\": \"node_modules/wrangler/config-schema.json\",\n\t\"name\": \"elysia-cf\",\n\t\"main\": \"src/index.ts\",\n\t\"compatibility_date\": \"2025-09-06\"\n}\n"
  },
  {
    "path": "test/cookie/explicit.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Cookie, createCookieJar } from '../../src/cookies'\nimport type { Context } from '../../src'\n\nconst create = () => {\n\tconst set: Context['set'] = {\n\t\tcookie: {},\n\t\theaders: {}\n\t}\n\n\tconst cookie = createCookieJar(set, {})\n\n\treturn {\n\t\tcookie,\n\t\tset\n\t}\n}\n\ndescribe('Explicit Cookie', () => {\n\tit('create cookie', () => {\n\t\tconst { cookie, set } = create()\n\t\tcookie.name.value = 'himari'\n\n\t\texpect(set.cookie?.name).toEqual({\n\t\t\tvalue: 'himari'\n\t\t})\n\t})\n\n\tit('add cookie attribute', () => {\n\t\tconst { cookie, set } = create()\n\t\tcookie.name.value = 'himari'\n\n\t\tcookie.name.update({\n\t\t\tdomain: 'millennium.sh'\n\t\t})\n\n\t\texpect(set.cookie?.name).toEqual({\n\t\t\tvalue: 'himari',\n\t\t\tdomain: 'millennium.sh'\n\t\t})\n\t})\n\n\tit('add cookie attribute without overwrite entire property', () => {\n\t\tconst { cookie, set } = create()\n\t\tcookie.name.value = 'himari'\n\t\tcookie.name.domain = 'millennium.sh'\n\n\t\tcookie.name.update({\n\t\t\thttpOnly: true,\n\t\t\tpath: '/'\n\t\t})\n\n\t\texpect(set.cookie?.name).toEqual({\n\t\t\tvalue: 'himari',\n\t\t\tdomain: 'millennium.sh',\n\t\t\thttpOnly: true,\n\t\t\tpath: '/'\n\t\t})\n\t})\n\n\tit('set cookie attribute', () => {\n\t\tconst { cookie, set } = create()\n\t\tcookie.name.value = 'himari'\n\t\tcookie.name.domain = 'millennium.sh'\n\n\t\tcookie.name.set({\n\t\t\thttpOnly: true,\n\t\t\tpath: '/'\n\t\t})\n\n\t\texpect(set.cookie?.name).toEqual({\n\t\t\thttpOnly: true,\n\t\t\tpath: '/',\n\t\t\tvalue: 'himari'\n\t\t})\n\t})\n\n\tit('add cookie overwrite attribute if duplicated', () => {\n\t\tconst { cookie, set } = create()\n\t\tcookie.name.set({\n\t\t\tvalue: 'aru',\n\t\t\tdomain: 'millennium.sh',\n\t\t\thttpOnly: true\n\t\t})\n\n\t\tcookie.name.update({\n\t\t\tdomain: 'gehenna.sh'\n\t\t})\n\n\t\texpect(set.cookie?.name).toEqual({\n\t\t\tvalue: 'aru',\n\t\t\tdomain: 'gehenna.sh',\n\t\t\thttpOnly: true\n\t\t})\n\t})\n\n\tit('default undefined cookie with undefined', () => {\n\t\tconst { cookie, set } = create()\n\t\tcookie.name\n\n\t\texpect(cookie?.name?.value).toEqual(undefined)\n\t})\n\n\tit('overwrite existing cookie', () => {\n\t\tconst { cookie, set } = create()\n\t\tcookie.name.value = 'aru'\n\t\tcookie.name.value = 'himari'\n\n\t\texpect(set.cookie?.name).toEqual({ value: 'himari' })\n\t})\n\n\tit('remove cookie', () => {\n\t\tconst { cookie, set } = create()\n\t\tcookie.name.value = 'himari'\n\t\tcookie.name.remove()\n\n\t\texpect(set.cookie?.name.expires?.getTime()).toBeLessThanOrEqual(\n\t\t\tDate.now()\n\t\t)\n\t})\n})\n"
  },
  {
    "path": "test/cookie/implicit.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { createCookieJar } from '../../src/cookies'\nimport type { Context } from '../../src'\n\nconst create = () => {\n\tconst set: Context['set'] = {\n\t\tcookie: {},\n\t\theaders: {}\n\t}\n\n\tconst cookie = createCookieJar(set, {})\n\n\treturn {\n\t\tcookie,\n\t\tset\n\t}\n}\n\ndescribe('Implicit Cookie', () => {\n\tit('create cookie using setter', () => {\n\t\tconst {\n\t\t\tcookie: { name },\n\t\t\tset\n\t\t} = create()\n\n\t\tname.value = 'himari'\n\n\t\texpect(set.cookie?.name).toEqual({\n\t\t\tvalue: 'himari'\n\t\t})\n\t})\n\n\tit('create cookie set function', () => {\n\t\tconst {\n\t\t\tcookie: { name },\n\t\t\tset\n\t\t} = create()\n\n\t\tname.set({\n\t\t\tvalue: 'himari'\n\t\t})\n\n\t\texpect(set.cookie?.name).toEqual({\n\t\t\tvalue: 'himari'\n\t\t})\n\t})\n\n\tit('add cookie attribute using setter', () => {\n\t\tconst {\n\t\t\tcookie: { name },\n\t\t\tset\n\t\t} = create()\n\n\t\tname.value = 'himari'\n\t\tname.domain = 'millennium.sh'\n\n\t\texpect(set.cookie?.name).toEqual({\n\t\t\tvalue: 'himari',\n\t\t\tdomain: 'millennium.sh'\n\t\t})\n\t})\n\n\tit('add cookie attribute using setter', () => {\n\t\tconst {\n\t\t\tcookie: { name },\n\t\t\tset\n\t\t} = create()\n\n\t\tname.value = 'himari'\n\t\tname.update({\n\t\t\tdomain: 'millennium.sh'\n\t\t})\n\n\t\texpect(set.cookie?.name).toEqual({\n\t\t\tvalue: 'himari',\n\t\t\tdomain: 'millennium.sh'\n\t\t})\n\t})\n\n\tit('add cookie attribute without overwrite entire property', () => {\n\t\tconst {\n\t\t\tcookie: { name },\n\t\t\tset\n\t\t} = create()\n\n\t\tname.set({\n\t\t\tvalue: 'himari',\n\t\t\tdomain: 'millennium.sh'\n\t\t}).update({\n\t\t\thttpOnly: true,\n\t\t\tpath: '/'\n\t\t})\n\n\t\texpect(set.cookie?.name).toEqual({\n\t\t\tvalue: 'himari',\n\t\t\tdomain: 'millennium.sh',\n\t\t\thttpOnly: true,\n\t\t\tpath: '/'\n\t\t})\n\t})\n\n\tit('set cookie attribute', () => {\n\t\tconst {\n\t\t\tcookie: { name },\n\t\t\tset\n\t\t} = create()\n\n\t\tname.set({\n\t\t\tvalue: 'himari',\n\t\t\tdomain: 'millennium.sh'\n\t\t}).set({\n\t\t\thttpOnly: true,\n\t\t\tpath: '/'\n\t\t})\n\n\t\texpect(set.cookie?.name).toEqual({\n\t\t\thttpOnly: true,\n\t\t\tpath: '/',\n\t\t\tvalue: 'himari',\n\t\t})\n\t})\n\n\tit('add cookie overwrite attribute if duplicated', () => {\n\t\tconst {\n\t\t\tcookie: { name },\n\t\t\tset\n\t\t} = create()\n\n\t\tname.set({\n\t\t\tvalue: 'aru',\n\t\t\tdomain: 'millennium.sh',\n\t\t\thttpOnly: true\n\t\t}).update({\n\t\t\tdomain: 'gehenna.sh'\n\t\t})\n\n\t\texpect(set.cookie?.name).toEqual({\n\t\t\tvalue: 'aru',\n\t\t\tdomain: 'gehenna.sh',\n\t\t\thttpOnly: true\n\t\t})\n\t})\n\n\tit('create cookie with empty string', () => {\n\t\tconst {\n\t\t\tcookie: { name },\n\t\t\tset\n\t\t} = create()\n\n\t\tname.value = ''\n\n\t\texpect(set.cookie?.name).toEqual({ value: '' })\n\t})\n\n\tit('Remove cookie', () => {\n\t\tconst {\n\t\t\tcookie: { name },\n\t\t\tset\n\t\t} = create()\n\n\t\tname.value = 'himari'\n\t\tname.remove()\n\n\t\texpect(set.cookie?.name.expires?.getTime()).toBeLessThanOrEqual(\n\t\t\tDate.now()\n\t\t)\n\t})\n})\n"
  },
  {
    "path": "test/cookie/response.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Elysia, t } from '../../src'\nimport { req } from '../utils'\nimport { signCookie } from '../../src/utils'\n\nconst secrets = 'We long for the seven wailings. We bear the koan of Jericho.'\n\nconst getCookies = (response: Response) =>\n\t// @ts-ignore\n\tresponse.headers.getAll('Set-Cookie').map((x) => {\n\t\tconst value = decodeURIComponent(x)\n\n\t\treturn value\n\t})\n\nconst app = new Elysia()\n\t.get(\n\t\t'/council',\n\t\t({ cookie: { council } }) =>\n\t\t\t(council.value = [\n\t\t\t\t{\n\t\t\t\t\tname: 'Rin',\n\t\t\t\t\taffilation: 'Administration'\n\t\t\t\t}\n\t\t\t]),\n\t\t{\n\t\t\tcookie: t.Cookie({\n\t\t\t\tcouncil: t.Optional(\n\t\t\t\t\tt.Array(\n\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\tname: t.String(),\n\t\t\t\t\t\t\taffilation: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t})\n\t\t}\n\t)\n\t.get('/create', ({ cookie: { name } }) => (name.value = 'Himari'))\n\t.get('/multiple', ({ cookie: { name, president } }) => {\n\t\tname.value = 'Himari'\n\t\tpresident.value = 'Rio'\n\n\t\treturn 'ok'\n\t})\n\t.get(\n\t\t'/update',\n\t\t({ cookie: { name } }) => {\n\t\t\tname.value = 'seminar: Himari'\n\n\t\t\treturn name.value\n\t\t},\n\t\t{\n\t\t\tcookie: t.Cookie(\n\t\t\t\t{\n\t\t\t\t\tname: t.Optional(t.String())\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tsecrets,\n\t\t\t\t\tsign: ['name']\n\t\t\t\t}\n\t\t\t)\n\t\t}\n\t)\n\t.get('/remove', ({ cookie }) => {\n\t\tfor (const self of Object.values(cookie)) self.remove()\n\n\t\treturn 'Deleted'\n\t})\n\t.get('/remove-with-options', ({ cookie }) => {\n\t\tfor (const self of Object.values(cookie)) self.remove()\n\n\t\treturn 'Deleted'\n\t})\n\t.get('/set', ({ cookie: { session } }) => {\n\t\tsession.value = 'rin'\n\t\tsession.set({\n\t\t\tpath: '/'\n\t\t})\n\t})\n\ndescribe('Cookie Response', () => {\n\tit('set cookie', async () => {\n\t\tconst response = await app.handle(req('/create'))\n\n\t\texpect(getCookies(response)).toEqual(['name=Himari; Path=/'])\n\t})\n\n\tit('set multiple cookie', async () => {\n\t\tconst response = await app.handle(req('/multiple'))\n\n\t\texpect(getCookies(response)).toEqual([\n\t\t\t'name=Himari; Path=/',\n\t\t\t'president=Rio; Path=/'\n\t\t])\n\t})\n\n\tit('set JSON cookie', async () => {\n\t\tconst response = await app.handle(req('/council'))\n\n\t\texpect(getCookies(response)).toEqual([\n\t\t\t'council=[{\"name\":\"Rin\",\"affilation\":\"Administration\"}]; Path=/'\n\t\t])\n\t})\n\n\tit('write cookie on different value', async () => {\n\t\tconst response = await app.handle(\n\t\t\treq('/council', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie:\n\t\t\t\t\t\t'council=' +\n\t\t\t\t\t\tencodeURIComponent(\n\t\t\t\t\t\t\tJSON.stringify([\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tname: 'Aoi',\n\t\t\t\t\t\t\t\t\taffilation: 'Financial'\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(getCookies(response)).toEqual([\n\t\t\t'council=[{\"name\":\"Rin\",\"affilation\":\"Administration\"}]; Path=/'\n\t\t])\n\t})\n\n\tit('remove cookie', async () => {\n\t\tconst response = await app.handle(\n\t\t\treq('/remove', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie:\n\t\t\t\t\t\t'council=' +\n\t\t\t\t\t\tencodeURIComponent(\n\t\t\t\t\t\t\tJSON.stringify([\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tname: 'Rin',\n\t\t\t\t\t\t\t\t\taffilation: 'Administration'\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(getCookies(response)[0]).toInclude(\n\t\t\t`council=; Max-Age=0; Path=/; Expires=${new Date(0).toUTCString()}`\n\t\t)\n\t})\n\n\tit('sign cookie', async () => {\n\t\tconst response = await app.handle(req('/update'))\n\n\t\texpect(getCookies(response)).toEqual([\n\t\t\t`name=${await signCookie('seminar: Himari', secrets)}; Path=/`\n\t\t])\n\t})\n\n\tit('sign/unsign cookie', async () => {\n\t\tconst response = await app.handle(\n\t\t\treq('/update', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: `name=${await signCookie(\n\t\t\t\t\t\t'seminar: Himari',\n\t\t\t\t\t\tsecrets\n\t\t\t\t\t)}`\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('inherits cookie settings', async () => {\n\t\tconst app = new Elysia({\n\t\t\tcookie: {\n\t\t\t\tsecrets,\n\t\t\t\tsign: ['name']\n\t\t\t}\n\t\t}).get(\n\t\t\t'/update',\n\t\t\t({ cookie: { name } }) => {\n\t\t\t\tif (!name.value) name.value = 'seminar: Himari'\n\n\t\t\t\treturn name.value\n\t\t\t},\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tname: t.Optional(t.String())\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\treq('/update', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: `name=${await signCookie(\n\t\t\t\t\t\t'seminar: Himari',\n\t\t\t\t\t\tsecrets\n\t\t\t\t\t)}`\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('sign all cookie', async () => {\n\t\tconst app = new Elysia({\n\t\t\tcookie: {\n\t\t\t\tsecrets,\n\t\t\t\tsign: true\n\t\t\t}\n\t\t}).get(\n\t\t\t'/update',\n\t\t\t({ cookie: { name } }) => {\n\t\t\t\tif (!name.value) name.value = 'seminar: Himari'\n\n\t\t\t\treturn name.value\n\t\t\t},\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tname: t.Optional(t.String())\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\treq('/update', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: `name=${await signCookie(\n\t\t\t\t\t\t'seminar: Himari',\n\t\t\t\t\t\tsecrets\n\t\t\t\t\t)}`\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('set cookie property from constructor', async () => {\n\t\tconst app = new Elysia({\n\t\t\tcookie: {\n\t\t\t\thttpOnly: true,\n\t\t\t\tpath: ''\n\t\t\t}\n\t\t}).get('/create', ({ cookie: { name } }) => (name.value = 'Himari'))\n\n\t\tconst response = await app.handle(req('/create'))\n\n\t\texpect(response.headers.getAll('Set-Cookie')).toEqual([\n\t\t\t'name=Himari; Path=/; HttpOnly'\n\t\t])\n\t})\n\n\tit('retain cookie value when using set if not provided', async () => {\n\t\tconst response = await app.handle(req('/set'))\n\n\t\texpect(response.headers.getAll('Set-Cookie')).toEqual([\n\t\t\t'session=rin; Path=/'\n\t\t])\n\t})\n\n\tit('parse object cookie', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/council',\n\t\t\t({ cookie: { council } }) => council.value,\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tcouncil: t.Object({\n\t\t\t\t\t\tname: t.String(),\n\t\t\t\t\t\taffilation: t.String()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst expected = {\n\t\t\tname: 'Rin',\n\t\t\taffilation: 'Administration'\n\t\t}\n\n\t\tconst response = await app.handle(\n\t\t\treq('/council', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: 'council=' + JSON.stringify(expected)\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.json()).toEqual(expected)\n\t})\n\n\t// this is removed there's no way to accurately determine object on Standard Schema\n\t// it(\"don't parse cookie type unless specified\", async () => {\n\t// \tlet value: unknown\n\n\t// \tconst app = new Elysia().get(\n\t// \t\t'/council',\n\t// \t\t({ cookie: { council } }) => (value = council.value)\n\t// \t)\n\n\t// \tconst expected = {\n\t// \t\tname: 'Rin',\n\t// \t\taffilation: 'Administration'\n\t// \t}\n\n\t// \tconst response = await app.handle(\n\t// \t\treq('/council', {\n\t// \t\t\theaders: {\n\t// \t\t\t\tcookie:\n\t// \t\t\t\t\t'council=' +\n\t// \t\t\t\t\tencodeURIComponent(JSON.stringify(expected))\n\t// \t\t\t}\n\t// \t\t})\n\t// \t)\n\n\t// \texpect(response.status).toBe(200)\n\t// \texpect(value).toEqual(JSON.stringify(expected))\n\t// })\n\n\tit('handle optional at root', async () => {\n\t\tconst app = new Elysia().get('/', ({ cookie: { id } }) => id.value, {\n\t\t\tcookie: t.Optional(\n\t\t\t\tt.Object({\n\t\t\t\t\tid: t.Numeric()\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/')).then((x) => x.text()),\n\t\t\tapp\n\t\t\t\t.handle(\n\t\t\t\t\treq('/', {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tcookie: 'id=1'\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t.then((x) => x.text())\n\t\t])\n\n\t\texpect(res).toEqual(['', '1'])\n\t})\n\n\tit(\"don't set cookie if new value is undefined\", async () => {\n\t\tconst app = new Elysia().get('/', ({ cookie: { id } }) => {\n\t\t\tid.value = undefined\n\n\t\t\treturn 'a'\n\t\t})\n\n\t\tconst res = app.handle(req('/')).then((x) => x.headers.toJSON())\n\n\t\t// @ts-expect-error\n\t\texpect(res).toEqual({})\n\t})\n\n\tit('set cookie attribute before value', async () => {\n\t\tconst date = new Date(Date.now() + 1000 * 60 * 60 * 24)\n\n\t\tconst app = new Elysia().get('/', ({ cookie }) => {\n\t\t\tcookie.my_cookie.expires = date\n\t\t\tcookie.my_cookie.value = 'my_cookie_value'\n\n\t\t\treturn 'HI'\n\t\t})\n\n\t\tconst setCookie = await app\n\t\t\t.handle(new Request('http://localhost'))\n\t\t\t.then((x) => x.headers.getSetCookie())\n\n\t\texpect(setCookie).toEqual([\n\t\t\t`my_cookie=my_cookie_value; Path=/; Expires=${date.toUTCString()}`\n\t\t])\n\t})\n\n\tit('should not set if value is duplicated', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.derive(({ cookie: { test } }) => {\n\t\t\t\tif (!test.value) {\n\t\t\t\t\ttest.value = 'Hello, world!'\n\t\t\t\t}\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello, world!')\n\n\t\tconst res = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost:3000/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tcookie: 'test=Hello, world!'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.headers)\n\n\t\texpect(res.getSetCookie()).toEqual([])\n\t})\n})\n"
  },
  {
    "path": "test/cookie/signature.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { parseCookie, Cookie } from '../../src/cookies'\nimport { signCookie } from '../../src/utils'\n\ndescribe('Parse Cookie', () => {\n\tit('handle empty cookie', async () => {\n\t\tconst set = {\n\t\t\theaders: {},\n\t\t\tcookie: {}\n\t\t}\n\t\tconst cookieString = ''\n\t\tconst result = await parseCookie(set, cookieString)\n\n\t\texpect(result).toEqual({})\n\t})\n\n\tit('create cookie jar from cookie string', async () => {\n\t\tconst set = {\n\t\t\theaders: {},\n\t\t\tcookie: {}\n\t\t}\n\t\tconst cookieString = 'fischl=Princess; eula=Noble; amber=Knight'\n\t\tconst result = await parseCookie(set, cookieString)\n\t\texpect(result).toEqual({\n\t\t\tfischl: expect.any(Cookie),\n\t\t\teula: expect.any(Cookie),\n\t\t\tamber: expect.any(Cookie)\n\t\t})\n\t})\n\n\tit('unsign cookie signature', async () => {\n\t\tconst set = {\n\t\t\theaders: {},\n\t\t\tcookie: {}\n\t\t}\n\n\t\tconst secrets = 'Fischl von Luftschloss Narfidort'\n\n\t\tconst fischl = await signCookie('fischl', secrets)\n\t\tconst cookieString = `fischl=${fischl}`\n\t\tconst result = await parseCookie(set, cookieString, {\n\t\t\tsecrets,\n\t\t\tsign: ['fischl']\n\t\t})\n\n\t\texpect(result.fischl.value).toEqual('fischl')\n\t})\n\n\tit('unsign multiple signature', async () => {\n\t\tconst set = {\n\t\t\theaders: {},\n\t\t\tcookie: {}\n\t\t}\n\n\t\tconst secrets = 'Fischl von Luftschloss Narfidort'\n\n\t\tconst fischl = await signCookie('fischl', secrets)\n\t\tconst eula = await signCookie('eula', secrets)\n\n\t\tconst cookieString = `fischl=${fischl}; eula=${eula}`\n\t\tconst result = await parseCookie(set, cookieString, {\n\t\t\tsecrets,\n\t\t\tsign: ['fischl', 'eula']\n\t\t})\n\n\t\texpect(result.fischl.value).toEqual('fischl')\n\t\texpect(result.eula.value).toEqual('eula')\n\t})\n\n\t// it('parse JSON value', async () => {\n\t// \tconst set = {\n\t// \t\theaders: {},\n\t// \t\tcookie: {}\n\t// \t}\n\n\t// \tconst value = {\n\t// \t\teula: 'Vengeance will be mine'\n\t// \t}\n\n\t// \tconst cookieString = `letter=${encodeURIComponent(\n\t// \t\tJSON.stringify(value)\n\t// \t)}`\n\t// \tconst result = await parseCookie(set, cookieString)\n\t// \texpect(result.letter.value).toEqual(value)\n\t// })\n\n\t// it('parse true', async () => {\n\t// \tconst set = {\n\t// \t\theaders: {},\n\t// \t\tcookie: {}\n\t// \t}\n\n\t// \tconst cookieString = `letter=true`\n\t// \tconst result = await parseCookie(set, cookieString)\n\t// \texpect(result.letter.value).toEqual(true)\n\t// })\n\n\t// it('parse false', async () => {\n\t// \tconst set = {\n\t// \t\theaders: {},\n\t// \t\tcookie: {}\n\t// \t}\n\n\t// \tconst cookieString = `letter=false`\n\t// \tconst result = await parseCookie(set, cookieString)\n\t// \texpect(result.letter.value).toEqual(false)\n\t// })\n\n\t// it('parse number', async () => {\n\t// \tconst set = {\n\t// \t\theaders: {},\n\t// \t\tcookie: {}\n\t// \t}\n\n\t// \tconst cookieString = `letter=123`\n\t// \tconst result = await parseCookie(set, cookieString)\n\t// \texpect(result.letter.value).toEqual(123)\n\t// })\n\n\tit('Unsign signature via secret rotation', async () => {\n\t\tconst set = {\n\t\t\theaders: {},\n\t\t\tcookie: {}\n\t\t}\n\n\t\tconst secret = 'Fischl von Luftschloss Narfidort'\n\n\t\tconst fischl = await signCookie('fischl', secret)\n\t\tconst cookieString = `fischl=${fischl}`\n\t\tconst result = await parseCookie(set, cookieString, {\n\t\t\tsecrets: ['New Secret', secret],\n\t\t\tsign: ['fischl']\n\t\t})\n\n\t\texpect(result.fischl.value).toEqual('fischl')\n\t})\n})\n"
  },
  {
    "path": "test/cookie/unchanged.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { Elysia, t } from '../../src'\n\ndescribe('Cookie - Unchanged Values', () => {\n\tit('should not send set-cookie header when cookie is only read', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tvalue: t.Optional(\n\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\ta: t.String(),\n\t\t\t\t\t\t\tb: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/cookie', ({ cookie: { value } }) => value.value)\n\t\t\t.post('/cookie', ({ cookie: { value } }) => {\n\t\t\t\tvalue.value = { a: '1', b: '2' }\n\t\t\t\treturn 'ok'\n\t\t\t})\n\n\t\t// POST request should set cookie\n\t\tconst postResponse = await app.handle(\n\t\t\tnew Request('http://localhost/cookie', {\n\t\t\t\tmethod: 'POST'\n\t\t\t})\n\t\t)\n\n\t\tconst setCookieHeaders = postResponse.headers.getAll('set-cookie')\n\t\texpect(setCookieHeaders.length).toBeGreaterThan(0)\n\n\t\t// GET request should NOT set cookie (only reading)\n\t\tconst getResponse = await app.handle(\n\t\t\tnew Request('http://localhost/cookie', {\n\t\t\t\tmethod: 'GET',\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: setCookieHeaders[0].split(';')[0]\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\tconst getSetCookieHeaders = getResponse.headers.getAll('set-cookie')\n\t\texpect(getSetCookieHeaders.length).toBe(0)\n\t})\n\n\tit('should not send set-cookie header when cookie value is accessed but not modified', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/read', ({ cookie: { session } }) => {\n\t\t\t\t// Just reading the value\n\t\t\t\tconst val = session.value\n\t\t\t\treturn { read: val }\n\t\t\t})\n\t\t\t.get('/write', ({ cookie: { session } }) => {\n\t\t\t\t// Writing the value\n\t\t\t\tsession.value = 'test'\n\t\t\t\treturn { written: true }\n\t\t\t})\n\n\t\t// Read endpoint should not set cookie\n\t\tconst readResponse = await app.handle(\n\t\t\tnew Request('http://localhost/read')\n\t\t)\n\t\texpect(readResponse.headers.getAll('set-cookie').length).toBe(0)\n\n\t\t// Write endpoint should set cookie\n\t\tconst writeResponse = await app.handle(\n\t\t\tnew Request('http://localhost/write')\n\t\t)\n\t\texpect(\n\t\t\twriteResponse.headers.getAll('set-cookie').length\n\t\t).toBeGreaterThan(0)\n\t})\n\n\t// Fine by using FNV-1a hash\n\t// it('should send set-cookie header when setting same value', async () => {\n\t// \tconst app = new Elysia().get('/same', ({ cookie: { session } }) => {\n\t// \t\t// Setting the same value that came from request\n\t// \t\tsession.value = 'existing'\n\t// \t\treturn 'ok'\n\t// \t})\n\n\t// \tconst response = await app.handle(\n\t// \t\tnew Request('http://localhost/same', {\n\t// \t\t\theaders: {\n\t// \t\t\t\tcookie: 'session=existing'\n\t// \t\t\t}\n\t// \t\t})\n\t// \t)\n\n\t// \texpect(response.headers.getAll('set-cookie').length).toBeGreaterThan(0)\n\t// })\n\n\tit('should send set-cookie header when value actually changes', async () => {\n\t\tconst app = new Elysia().get('/change', ({ cookie: { session } }) => {\n\t\t\tsession.value = 'new-value'\n\t\t\treturn 'ok'\n\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/change', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: 'session=old-value'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.headers.getAll('set-cookie').length).toBeGreaterThan(0)\n\t})\n\n\tit('should not send set-cookie header when setting same object value as incoming cookie', async () => {\n\t\tconst app = new Elysia().post('/update', ({ cookie: { data } }) => {\n\t\t\t// Set to same value as incoming cookie\n\t\t\tdata.value = { id: 123, name: 'test' }\n\t\t\treturn 'ok'\n\t\t})\n\n\t\t// First request: set the cookie\n\t\tconst firstRes = await app.handle(\n\t\t\tnew Request('http://localhost/update', { method: 'POST' })\n\t\t)\n\t\tconst setCookie = firstRes.headers.get('set-cookie')\n\t\texpect(setCookie).toBeTruthy()\n\n\t\t// Second request: send cookie back and set to same value\n\t\tconst secondRes = await app.handle(\n\t\t\tnew Request('http://localhost/update', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: setCookie!.split(';')[0]\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\t// Should not send Set-Cookie since value didn't change\n\t\texpect(secondRes.headers.getAll('set-cookie').length).toBe(0)\n\t})\n\n\tit('should not send set-cookie header for large unchanged object values', async () => {\n\t\tconst large = {\n\t\t\tusers: Array.from({ length: 100 }, (_, i) => ({\n\t\t\t\tid: i,\n\t\t\t\tname: `User ${i}`\n\t\t\t}))\n\t\t}\n\n\t\tconst app = new Elysia().post('/update', ({ cookie: { data } }) => {\n\t\t\tdata.value = large\n\t\t\treturn 'ok'\n\t\t})\n\n\t\t// First request: set the cookie\n\t\tconst firstRes = await app.handle(\n\t\t\tnew Request('http://localhost/update', { method: 'POST' })\n\t\t)\n\t\tconst setCookie = firstRes.headers.get('set-cookie')\n\t\texpect(setCookie).toBeTruthy()\n\n\t\t// Second request: send cookie back and set to same value\n\t\tconst secondRes = await app.handle(\n\t\t\tnew Request('http://localhost/update', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: setCookie!.split(';')[0]\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\t// Should not send Set-Cookie since value didn't change\n\t\texpect(secondRes.headers.getAll('set-cookie').length).toBe(0)\n\t})\n\n\tit('should optimize multiple assignments of same object in single request', async () => {\n\t\tconst app = new Elysia().post('/multi', ({ cookie: { data } }) => {\n\t\t\t// Multiple assignments of the same value\n\t\t\tdata.value = { id: 123, name: 'test' }\n\t\t\tdata.value = { id: 123, name: 'test' }\n\t\t\tdata.value = { id: 123, name: 'test' }\n\t\t\treturn 'ok'\n\t\t})\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/multi', { method: 'POST' })\n\t\t)\n\n\t\t// Should only produce one Set-Cookie header\n\t\texpect(res.headers.getAll('set-cookie').length).toBe(1)\n\t})\n\n\tit('should invalidate hash cache when using update() method', async () => {\n\t\tconst app = new Elysia().post('/cache-invalidation', ({ cookie: { data } }) => {\n\t\t\t// Set initial value\n\t\t\tdata.value = { id: 1, name: 'first' }\n\n\t\t\t// Modify via update() - should invalidate cache\n\t\t\tdata.update({ value: { id: 2, name: 'second' } })\n\n\t\t\t// Set to the updated value again - should detect as unchanged\n\t\t\tdata.value = { id: 2, name: 'second' }\n\n\t\t\treturn 'ok'\n\t\t})\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/cache-invalidation', { method: 'POST' })\n\t\t)\n\n\t\t// Should only have one Set-Cookie header (for final value)\n\t\tconst setCookieHeaders = res.headers.getAll('set-cookie')\n\t\texpect(setCookieHeaders.length).toBe(1)\n\t\texpect(setCookieHeaders[0]).toContain('id')\n\t})\n\n\tit('should invalidate hash cache when using set() method', async () => {\n\t\tconst app = new Elysia().post('/cache-set', ({ cookie: { data } }) => {\n\t\t\t// Set initial value\n\t\t\tdata.value = { id: 1 }\n\n\t\t\t// Modify via set() - should invalidate cache\n\t\t\tdata.set({ value: { id: 2 } })\n\n\t\t\t// Set to the updated value again - should detect as unchanged\n\t\t\tdata.value = { id: 2 }\n\n\t\t\treturn 'ok'\n\t\t})\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/cache-set', { method: 'POST' })\n\t\t)\n\n\t\t// Should only have one Set-Cookie header\n\t\texpect(res.headers.getAll('set-cookie').length).toBe(1)\n\t})\n})\n"
  },
  {
    "path": "test/core/aot-strictpath.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Elysia } from '../../src'\n\nconst req = (path: string) => new Request(`http://localhost${path}`)\n\ndescribe('AOT and strictPath interaction', () => {\n\tit('should respect default strictPath:false when aot:false', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false\n\t\t})\n\t\t\t.get('/ping', () => 'pong')\n\t\t\t.group('/api', (app) =>\n\t\t\t\tapp.get('/ping', () => 'pong')\n\t\t\t)\n\n\t\t// All these should return 200 with default strictPath: false\n\t\texpect(await app.handle(req('/ping')).then((x) => x.status)).toBe(200)\n\t\texpect(await app.handle(req('/ping/')).then((x) => x.status)).toBe(200)\n\t\texpect(await app.handle(req('/api/ping')).then((x) => x.status)).toBe(200)\n\t\texpect(await app.handle(req('/api/ping/')).then((x) => x.status)).toBe(200)\n\t})\n\n\tit('should respect explicit strictPath:false when aot:false', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false,\n\t\t\tstrictPath: false\n\t\t})\n\t\t\t.get('/ping', () => 'pong')\n\n\t\texpect(await app.handle(req('/ping')).then((x) => x.status)).toBe(200)\n\t\texpect(await app.handle(req('/ping/')).then((x) => x.status)).toBe(200)\n\t})\n\n\tit('should respect strictPath:true when aot:false', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false,\n\t\t\tstrictPath: true\n\t\t})\n\t\t\t.get('/ping', () => 'pong')\n\n\t\texpect(await app.handle(req('/ping')).then((x) => x.status)).toBe(200)\n\t\texpect(await app.handle(req('/ping/')).then((x) => x.status)).toBe(404)\n\t})\n\n\tit('should handle group routes with default strictPath when aot:false', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false\n\t\t}).group('/api', (app) =>\n\t\t\tapp.get('/', () => 'Hello Elysia')\n\t\t)\n\n\t\t// Both /api and /api/ should work with default strictPath\n\t\texpect(await app.handle(req('/api')).then((x) => x.status)).toBe(200)\n\t\texpect(await app.handle(req('/api/')).then((x) => x.status)).toBe(200)\n\t})\n})\n"
  },
  {
    "path": "test/core/as.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { Elysia, t } from '../../src'\nimport { req } from '../utils'\n\ndescribe('as', () => {\n\tit('scoped', async () => {\n\t\tconst subPlugin1 = new Elysia()\n\t\t\t.derive(() => {\n\t\t\t\treturn {\n\t\t\t\t\thi: 'hi'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.as('scoped')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(subPlugin1)\n\t\t\t.get('/inner', ({ hi }) => hi)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t// @ts-ignore\n\t\t\t.get('/', ({ hi }) => hi ?? 'none')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/')).then((x) => x.text()),\n\t\t\tapp.handle(req('/inner')).then((x) => x.text())\n\t\t])\n\n\t\texpect(res).toEqual(['none', 'hi'])\n\t})\n\n\tit('global', async () => {\n\t\tconst subPlugin1 = new Elysia()\n\t\t\t.derive(() => {\n\t\t\t\treturn {\n\t\t\t\t\thi: 'hi'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(subPlugin1)\n\t\t\t.get('/inner', ({ hi }) => hi)\n\n\t\tconst app = new Elysia().use(plugin).get('/', ({ hi }) => hi ?? 'none')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/')).then((x) => x.text()),\n\t\t\tapp.handle(req('/inner')).then((x) => x.text())\n\t\t])\n\n\t\texpect(res).toEqual(['hi', 'hi'])\n\t})\n\n\tit('global on scoped event', async () => {\n\t\tconst subPlugin1 = new Elysia()\n\t\t\t.derive({ as: 'scoped' }, () => {\n\t\t\t\treturn {\n\t\t\t\t\thi: 'hi'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(subPlugin1)\n\t\t\t.get('/inner', ({ hi }) => hi)\n\n\t\tconst app = new Elysia().use(plugin).get('/', ({ hi }) => hi ?? 'none')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/')).then((x) => x.text()),\n\t\t\tapp.handle(req('/inner')).then((x) => x.text())\n\t\t])\n\n\t\texpect(res).toEqual(['hi', 'hi'])\n\t})\n\n\tit('handle as global', async () => {\n\t\tlet called = 0\n\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number(),\n\t\t\t})\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\tcalled++\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/plugin', () => true)\n\n\t\t// @ts-expect-error\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/inner')).then((x) => x.status),\n\t\t\tapp.handle(req('/plugin')).then((x) => x.status),\n\t\t\tapp.handle(req('/')).then((x) => x.status)\n\t\t])\n\n\t\texpect(called).toBe(3)\n\t\texpect(response).toEqual([422, 422, 422])\n\t})\n\n\tit('handle as global with local override', async () => {\n\t\tlet called = 0\n\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number()\n\t\t\t})\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\tcalled++\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t.guard({\n\t\t\t\tresponse: t.Boolean()\n\t\t\t})\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\tcalled++\n\t\t\t})\n\t\t\t.get('/plugin', () => true)\n\n\t\t// @ts-expect-error\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/inner')).then((x) => x.status),\n\t\t\tapp.handle(req('/plugin')).then((x) => x.status),\n\t\t\tapp.handle(req('/')).then((x) => x.status)\n\t\t])\n\n\t\texpect(called).toBe(4)\n\t\texpect(response).toEqual([422, 200, 422])\n\t})\n\n\tit('handle as global with scoped override', async () => {\n\t\tlet called = 0\n\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number()\n\t\t\t})\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\tcalled++\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tresponse: t.String()\n\t\t\t})\n            .onBeforeHandle({ as: 'scoped' }, () => {\n\t\t\t\tcalled++\n\t\t\t})\n\t\t\t.get('/plugin', () => 'ok')\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/inner')).then((x) => x.status),\n\t\t\tapp.handle(req('/plugin')).then((x) => x.status),\n\t\t\tapp.handle(req('/')).then((x) => x.status)\n\t\t])\n\n\t\texpect(called).toBe(5)\n\t\texpect(response).toEqual([422, 200, 200])\n\t})\n\n\tit('handle as scoped', async () => {\n\t\tlet called = 0\n\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number()\n\t\t\t})\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\tcalled++\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('scoped')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/plugin', () => true)\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/inner')).then((x) => x.status),\n\t\t\tapp.handle(req('/plugin')).then((x) => x.status),\n\t\t\tapp.handle(req('/')).then((x) => x.status)\n\t\t])\n\n\t\texpect(called).toBe(2)\n\t\texpect(response).toEqual([422, 422, 200])\n\t})\n\n\tit('handle as scoped twice', async () => {\n\t\tlet called = 0\n\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number()\n\t\t\t})\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\tcalled++\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('scoped')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/plugin', () => true)\n\t\t\t.as('scoped')\n\n\t\t// @ts-expect-error\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/inner')).then((x) => x.status),\n\t\t\tapp.handle(req('/plugin')).then((x) => x.status),\n\t\t\tapp.handle(req('/')).then((x) => x.status)\n\t\t])\n\n\t\texpect(called).toBe(3)\n\t\texpect(response).toEqual([422, 422, 422])\n\t})\n})\n"
  },
  {
    "path": "test/core/before-handle-arrow.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Elysia } from '../../src'\n\ndescribe('beforeHandle with arrow functions', () => {\n\tit('should execute beforeHandle with arrow function expression', async () => {\n\t\tlet beforeHandleCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.get('/test', () => 'ok', {\n\t\t\t\t// Arrow function expression (no braces) - this was broken with minified code\n\t\t\t\tbeforeHandle: () => {\n\t\t\t\t\tbeforeHandleCalled = true\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst response = await app.handle(new Request('http://localhost/test'))\n\t\texpect(response.status).toBe(200)\n\t\texpect(beforeHandleCalled).toBe(true)\n\t})\n\n\tit('should execute beforeHandle with arrow function returning value', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/test', () => 'should not reach', {\n\t\t\t\t// Arrow function expression that returns early\n\t\t\t\tbeforeHandle: () => 'intercepted'\n\t\t\t})\n\n\t\tconst response = await app.handle(new Request('http://localhost/test'))\n\t\texpect(await response.text()).toBe('intercepted')\n\t})\n\n\tit('should execute async beforeHandle with arrow function expression', async () => {\n\t\tlet beforeHandleCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.get('/test', () => 'ok', {\n\t\t\t\t// Async arrow function expression\n\t\t\t\tbeforeHandle: async () => {\n\t\t\t\t\tbeforeHandleCalled = true\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst response = await app.handle(new Request('http://localhost/test'))\n\t\texpect(response.status).toBe(200)\n\t\texpect(beforeHandleCalled).toBe(true)\n\t})\n\n\tit('should execute beforeHandle with complex arrow expression', async () => {\n\t\tlet validatorCalled = false\n\t\tconst validator = () => {\n\t\t\tvalidatorCalled = true\n\t\t}\n\n\t\tconst app = new Elysia()\n\t\t\t.get('/test', () => 'ok', {\n\t\t\t\t// Complex arrow expression like: async ({status}) => requireSignature()({status})\n\t\t\t\t// This pattern was broken when code is minified\n\t\t\t\tbeforeHandle: () => validator()\n\t\t\t})\n\n\t\tconst response = await app.handle(new Request('http://localhost/test'))\n\t\texpect(response.status).toBe(200)\n\t\texpect(validatorCalled).toBe(true)\n\t})\n\n\tit('should execute beforeHandle with arrow function block', async () => {\n\t\tlet beforeHandleCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.get('/test', () => 'ok', {\n\t\t\t\t// Arrow function with block (this always worked)\n\t\t\t\tbeforeHandle: () => {\n\t\t\t\t\tbeforeHandleCalled = true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst response = await app.handle(new Request('http://localhost/test'))\n\t\texpect(response.status).toBe(200)\n\t\texpect(beforeHandleCalled).toBe(true)\n\t})\n\n\tit('should handle multiple beforeHandle hooks with arrow expressions', async () => {\n\t\tconst callOrder: number[] = []\n\n\t\tconst app = new Elysia()\n\t\t\t.get('/test', () => 'ok', {\n\t\t\t\tbeforeHandle: [\n\t\t\t\t\t() => {\n\t\t\t\t\t\tcallOrder.push(1)\n\t\t\t\t\t},\n\t\t\t\t\t() => {\n\t\t\t\t\t\tcallOrder.push(2)\n\t\t\t\t\t},\n\t\t\t\t\t() => {\n\t\t\t\t\t\tcallOrder.push(3)\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t})\n\n\t\tconst response = await app.handle(new Request('http://localhost/test'))\n\t\texpect(response.status).toBe(200)\n\t\texpect(callOrder).toEqual([1, 2, 3])\n\t})\n\n\t// Test with truly minified code (no spaces around arrow)\n\t// This simulates what happens when code is bundled and minified\n\tit('should execute beforeHandle with truly minified arrow function (no spaces)', async () => {\n\t\t// Construct a function with no spaces: async()=>'intercepted'\n\t\t// This is what real minifiers produce\n\t\tconst minifiedHandler = Function(\"return async()=>'intercepted'\")()\n\n\t\tconst app = new Elysia().get('/test', () => 'should not reach', {\n\t\t\tbeforeHandle: minifiedHandler\n\t\t})\n\n\t\tconst response = await app.handle(new Request('http://localhost/test'))\n\t\texpect(await response.text()).toBe('intercepted')\n\t})\n\n\t// Test with actual HTTP server (not just app.handle)\n\tit('should work with live server', async () => {\n\t\tlet beforeHandleCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.get('/test', () => 'ok', {\n\t\t\t\tbeforeHandle: () => {\n\t\t\t\t\tbeforeHandleCalled = true\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\ttry {\n\t\t\tconst response = await fetch(\n\t\t\t\t`http://localhost:${app.server?.port}/test`\n\t\t\t)\n\t\t\texpect(response.status).toBe(200)\n\t\t\texpect(beforeHandleCalled).toBe(true)\n\t\t} finally {\n\t\t\tawait app.stop()\n\t\t}\n\t})\n})\n"
  },
  {
    "path": "test/core/compose.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Type } from '@sinclair/typebox'\nimport { hasAdditionalProperties } from '../../src/schema'\n\ndescribe('hasAdditionalProperties', () => {\n\tit('should handle object schemas without properties key', () => {\n\t\tconst schema = Type.Intersect([\n\t\t\tType.Object({ a: Type.String() }),\n\t\t\t// Record schemas does not have properties key, instead it has patternProperties\n\t\t\tType.Record(Type.Number(), Type.String())\n\t\t])\n\t\texpect(hasAdditionalProperties(schema)).toBe(false)\n\t})\n})\n"
  },
  {
    "path": "test/core/config.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { Elysia, t } from '../../src'\n\ndescribe('config', () => {\n\tit('standard hostname', async () => {\n\t\tconst app = new Elysia({ handler: { standardHostname: false } }).get(\n\t\t\t'/a',\n\t\t\t'a'\n\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(new Request('http://a/a'))\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe('a')\n\t})\n\n\tit('append prefix / if not provided', () => {\n\t\tconst plugin = new Elysia({ prefix: 'v1' }).get('thing', 'thing')\n\n\t\tconst app = new Elysia({ prefix: 'api' }).use(plugin)\n\n\t\texpect(app.routes[0].path).toBe('/api/v1/thing')\n\n\t\t// This should not error\n\t\tapp['~Routes']?.api.v1.thing\n\t})\n})\n"
  },
  {
    "path": "test/core/context.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Elysia } from '../../src'\nimport { req } from '../utils'\n\ndescribe('context', () => {\n\tdescribe('return route', () => {\n\t\tit('on aot=true', async () => {\n\t\t\tconst app = new Elysia().get('/hi/:id', ({ route }) => route)\n\t\t\tconst res = await app.handle(req('/hi/123')).then((x) => x.text())\n\t\t\texpect(res).toBe('/hi/:id')\n\t\t})\n\n\t\tit('on aot=false', async () => {\n\t\t\tconst app = new Elysia({ aot: false }).get(\n\t\t\t\t'/hi/:id',\n\t\t\t\t({ route }) => route\n\t\t\t)\n\t\t\tconst res = await app.handle(req('/hi/123')).then((x) => x.text())\n\t\t\texpect(res).toBe('/hi/:id')\n\t\t})\n\t})\n\n\tdescribe('early return on macros with route data', () => {\n\t\tit('on aot=true', async () => {\n\t\t\tconst app = new Elysia()\n\t\t\t\t.macro({\n\t\t\t\t\ttest: {\n\t\t\t\t\t\tbeforeHandle({ route }) {\n\t\t\t\t\t\t\treturn route\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.get('/hi/:id', () => 'should not returned', {\n\t\t\t\t\ttest: true\n\t\t\t\t})\n\t\t\tconst res = await app.handle(req('/hi/123')).then((x) => x.text())\n\t\t\texpect(res).toBe('/hi/:id')\n\t\t})\n\n\t\tit('on aot=false', async () => {\n\t\t\tconst app = new Elysia({ aot: false })\n\t\t\t\t.macro({\n\t\t\t\t\ttest: {\n\t\t\t\t\t\tbeforeHandle({ route }) {\n\t\t\t\t\t\t\treturn route\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.get('/hi/:id', () => 'should not returned', {\n\t\t\t\t\ttest: true\n\t\t\t\t})\n\t\t\tconst res = await app.handle(req('/hi/123')).then((x) => x.text())\n\t\t\texpect(res).toBe('/hi/:id')\n\t\t})\n\t})\n})\n"
  },
  {
    "path": "test/core/dynamic.test.ts",
    "content": "import { Elysia, NotFoundError, status, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { post, req } from '../utils'\n\ndescribe('Dynamic Mode', () => {\n\tit('handle path', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false\n\t\t}).get('/', () => 'Hi')\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\t\texpect(res).toBe('Hi')\n\t})\n\n\tit('handle literal', async () => {\n\t\tconst app = new Elysia({ aot: false }).get('/', 'Hi')\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('Hi')\n\t})\n\n\tit('handle body', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false\n\t\t}).post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\n\t\tconst body = {\n\t\t\tname: 'saltyaom'\n\t\t} as const\n\n\t\tconst res = (await app\n\t\t\t.handle(post('/', body))\n\t\t\t.then((x) => x.json())) as typeof body\n\n\t\tconst invalid = await app.handle(post('/', {})).then((x) => x.status)\n\n\t\texpect(res.name).toBe(body.name)\n\t\texpect(invalid).toBe(422)\n\t})\n\n\tit('handle dynamic all method', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false\n\t\t}).all('/all/*', () => 'ALL')\n\n\t\tconst res = await app.handle(req('/all/world')).then((x) => x.text())\n\t\texpect(res).toBe('ALL')\n\t})\n\n\tit('inherits plugin', async () => {\n\t\tconst plugin = new Elysia().decorate('hi', () => 'hi')\n\n\t\tconst app = new Elysia({\n\t\t\taot: false\n\t\t})\n\t\t\t.use(plugin)\n\t\t\t.get('/', ({ hi }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('use custom error', async () => {\n\t\tconst res = await new Elysia({\n\t\t\taot: false\n\t\t})\n\t\t\t.get('/', () => 'Hi')\n\t\t\t.onError(({ code }) => {\n\t\t\t\tif (code === 'NOT_FOUND')\n\t\t\t\t\treturn new Response(\"I'm a teapot\", {\n\t\t\t\t\t\tstatus: 418\n\t\t\t\t\t})\n\t\t\t})\n\t\t\t.handle(req('/not-found'))\n\n\t\texpect(await res.text()).toBe(\"I'm a teapot\")\n\t\texpect(res.status).toBe(418)\n\t})\n\n\tit('inject headers to error', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false\n\t\t})\n\t\t\t.onRequest(({ set }) => {\n\t\t\t\tset.headers['Access-Control-Allow-Origin'] = '*'\n\t\t\t})\n\t\t\t.get('/', () => {\n\t\t\t\tthrow new NotFoundError()\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')\n\t\texpect(res.status).toBe(404)\n\t})\n\n\tit('transform any to error', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false\n\t\t})\n\t\t\t.get('/', () => {\n\t\t\t\tthrow new NotFoundError()\n\t\t\t})\n\t\t\t.onError(async ({ set }) => {\n\t\t\t\tset.status = 418\n\n\t\t\t\treturn 'aw man'\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('aw man')\n\t\texpect(res.status).toBe(418)\n\t})\n\n\tit('derive', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false\n\t\t})\n\t\t\t.derive(() => {\n\t\t\t\treturn {\n\t\t\t\t\tA: 'A'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', ({ A }) => A)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('A')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('resolve', async () => {\n\t\tconst app = new Elysia({ aot: false })\n\t\t\t.resolve(() => {\n\t\t\t\treturn {\n\t\t\t\t\thello: 'Sunday'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', ({ hello }) => hello)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('Sunday')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate', async () => {\n\t\tconst app = new Elysia({ aot: false }).post(\n\t\t\t'/',\n\t\t\t({ query: { id, arr } }) => `${id} - ${arr}`,\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tusername: t.String(),\n\t\t\t\t\tpassword: t.String()\n\t\t\t\t}),\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tid: t.String(),\n\t\t\t\t\tarr: t.Array(t.String())\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.String()\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app\n\t\t\t.handle(\n\t\t\t\tpost('/?id=me&arr=v1&arr=v2', {\n\t\t\t\t\tusername: 'username',\n\t\t\t\t\tpassword: 'password'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.text())\n\n\t\texpect(res).toBe('me - v1,v2')\n\t})\n\n\tit('default value', async () => {\n\t\tconst app = new Elysia({ aot: false }).get(\n\t\t\t'/:propParams?',\n\t\t\t({\n\t\t\t\tparams: { propParams },\n\t\t\t\theaders: { propHeader },\n\t\t\t\tquery: { propQuery }\n\t\t\t}) => `${propParams} ${propHeader} ${propQuery}`,\n\t\t\t{\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tpropParams: t.String({\n\t\t\t\t\t\tdefault: 'params-default'\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\theaders: t.Object({\n\t\t\t\t\tpropHeader: t.String({\n\t\t\t\t\t\tdefault: 'header-default'\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tpropQuery: t.String({\n\t\t\t\t\t\tdefault: 'query-default'\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(new Request('http://localhost'))\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe('params-default header-default query-default')\n\t})\n\n\tit('handle non query fallback', async () => {\n\t\tconst app = new Elysia({ aot: false }).get('/', () => 'hi', {\n\t\t\tquery: t.Object({\n\t\t\t\tredirect_uri: t.Optional(t.String())\n\t\t\t})\n\t\t})\n\n\t\tconst res1 = await app.handle(req('/'))\n\t\tconst res2 = await app.handle(req('/?'))\n\t\tconst res3 = await app.handle(req('/?redirect_uri=a'))\n\n\t\texpect(res1.status).toBe(200)\n\t\texpect(res2.status).toBe(200)\n\t\texpect(res3.status).toBe(200)\n\t})\n\n\tit('handle local parse event', async () => {\n\t\tconst app = new Elysia({ aot: false }).post('/', (ctx) => ctx.body, {\n\t\t\tparse: (ctx, contentType) => {\n\t\t\t\treturn contentType\n\t\t\t},\n\t\t\tbody: t.String()\n\t\t})\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: 'yay',\n\t\t\t\theaders: { 'content-type': 'text/plain' }\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.text()).toBe('text/plain')\n\t})\n\n\tit('handle async resolve', async () => {\n\t\tconst app = new Elysia({ aot: false })\n\t\t\t.resolve(() => status(418, 'Chocominto yorimo anata!'))\n\t\t\t.post('/ruby-chan', () => 'Hai!')\n\n\t\tconst res = await app.handle(post('/ruby-chan', 'nani ga suki!'))\n\n\t\texpect(await res.text()).toBe('Chocominto yorimo anata!')\n\t\texpect(res.status).toBe(418)\n\t})\n\n\tit('set default header', async () => {\n\t\tconst app = new Elysia({ aot: false })\n\t\t\t.headers({\n\t\t\t\t'X-Powered-By': 'Elysia'\n\t\t\t})\n\t\t\t.get('/', () => 'Hello')\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.headers.get('X-Powered-By')).toBe('Elysia')\n\t})\n\n\tit('handle local cookie signing', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false\n\t\t}).get(\n\t\t\t'/',\n\t\t\t({ cookie: { profile } }) => {\n\t\t\t\tprofile.value = {\n\t\t\t\t\tid: 617,\n\t\t\t\t\tname: 'Summoning 101'\n\t\t\t\t}\n\n\t\t\t\treturn profile.value\n\t\t\t},\n\t\t\t{\n\t\t\t\tcookie: t.Cookie(\n\t\t\t\t\t{\n\t\t\t\t\t\tprofile: t.Optional(\n\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\tid: t.Numeric(),\n\t\t\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tsecrets: 'Fischl von Luftschloss Narfidort',\n\t\t\t\t\t\tsign: ['profile']\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tid: 617,\n\t\t\tname: 'Summoning 101'\n\t\t})\n\t})\n\n\tit('handle global cookie signing', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false,\n\t\t\tcookie: {\n\t\t\t\tsecrets: 'Fischl von Luftschloss Narfidort',\n\t\t\t\tsign: ['profile']\n\t\t\t}\n\t\t}).get(\n\t\t\t'/',\n\t\t\t({ cookie: { profile } }) => {\n\t\t\t\tprofile.value = {\n\t\t\t\t\tid: 617,\n\t\t\t\t\tname: 'Summoning 101'\n\t\t\t\t}\n\n\t\t\t\treturn profile.value\n\t\t\t},\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tprofile: t.Optional(\n\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\tid: t.Numeric(),\n\t\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tid: 617,\n\t\t\tname: 'Summoning 101'\n\t\t})\n\t})\n\n\tit('handle optional cookie', async () => {\n\t\tconst app = new Elysia({\n\t\t\taot: false\n\t\t}).get(\n\t\t\t'/',\n\t\t\t({ cookie: { profile } }) => {\n\t\t\t\tprofile.value = {\n\t\t\t\t\tid: 617,\n\t\t\t\t\tname: 'Summoning 101'\n\t\t\t\t}\n\n\t\t\t\treturn profile.value\n\t\t\t},\n\t\t\t{\n\t\t\t\tcookie: t.Optional(\n\t\t\t\t\tt.Cookie(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprofile: t.Optional(\n\t\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\t\tid: t.Numeric(),\n\t\t\t\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsecrets: 'Fischl von Luftschloss Narfidort',\n\t\t\t\t\t\t\tsign: ['profile']\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tid: 617,\n\t\t\tname: 'Summoning 101'\n\t\t})\n\t})\n\n\tit('use built-in name parser (text)', async () => {\n\t\tconst app = new Elysia({ aot: false }).post(\n\t\t\t'/',\n\t\t\t({ body }) => typeof body,\n\t\t\t{\n\t\t\t\tparse: 'text'\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({ hello: 'world' })\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe('string')\n\t})\n\n\tit('use built-in name parser (text/plain)', async () => {\n\t\tconst app = new Elysia({ aot: false }).post(\n\t\t\t'/',\n\t\t\t({ body }) => typeof body,\n\t\t\t{\n\t\t\t\tparse: 'text/plain'\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({ hello: 'world' })\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe('string')\n\t})\n\n\tit('use built-in name parser (json)', async () => {\n\t\tconst app = new Elysia({ aot: false }).post(\n\t\t\t'/',\n\t\t\t({ body }) => typeof body,\n\t\t\t{\n\t\t\t\tparse: 'json'\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'content-type': 'text/plain'\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({ hello: 'world' })\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe('object')\n\t})\n\n\tit('use custom name parser', async () => {\n\t\tconst app = new Elysia({ aot: false })\n\t\t\t.parser('thing', () => {\n\t\t\t\treturn true\n\t\t\t})\n\t\t\t.post('/', ({ body }) => typeof body, {\n\t\t\t\tparse: 'thing'\n\t\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'content-type': 'text/plain'\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({ hello: 'world' })\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe('boolean')\n\t})\n\n\tit('validate response', async () => {\n\t\tconst app = new Elysia({ aot: false })\n\t\t\t// @ts-ignore\n\t\t\t.get('/invalid', () => ({ name: 'Jane Doe' }), {\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tfoo: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/invalid-201',\n\t\t\t\t// @ts-ignore\n\t\t\t\t({ status }) => status(201, { name: 'Jane Doe' }),\n\t\t\t\t{\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t201: t.Object({\n\t\t\t\t\t\t\tfoo: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\t\t\t.get('/valid', () => ({ foo: 'bar' }), {\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tfoo: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/valid-201', ({ status }) => status(201, { foo: 'bar' }), {\n\t\t\t\tresponse: {\n\t\t\t\t\t201: t.Object({\n\t\t\t\t\t\tfoo: t.String()\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst invalid = await app.handle(req('/invalid')).then((x) => x.status)\n\t\tconst invalid201 = await app\n\t\t\t.handle(req('/invalid-201'))\n\t\t\t.then((x) => x.status)\n\t\tconst valid = await app.handle(req('/valid')).then((x) => x.status)\n\t\tconst valid201 = await app\n\t\t\t.handle(req('/valid-201'))\n\t\t\t.then((x) => x.status)\n\n\t\texpect(invalid).toBe(422)\n\t\texpect(invalid201).toBe(422)\n\t\texpect(valid).toBe(200)\n\t\texpect(valid201).toBe(201)\n\t})\n\n\tit('clean response', async () => {\n\t\tconst app = new Elysia({ aot: false })\n\t\t\t// @ts-ignore\n\t\t\t.get('/invalid', () => ({ name: 'Jane Doe' }), {\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tfoo: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/valid', () => ({ foo: 'bar', a: 'b' }), {\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tfoo: t.String()\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst invalid = await app.handle(req('/invalid')).then((x) => x.status)\n\t\tconst valid = await app.handle(req('/valid')).then((x) => x.json())\n\n\t\texpect(invalid).toBe(422)\n\t\texpect(valid).toEqual({\n\t\t\tfoo: 'bar'\n\t\t})\n\t})\n\n\tit('validate after handle', async () => {\n\t\tconst app = new Elysia({ aot: false })\n\t\t\t// @ts-ignore\n\t\t\t.get('/invalid', () => '', {\n\t\t\t\tafterHandle: () => ({ name: 'Jane Doe' }),\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tfoo: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/invalid-201',\n\t\t\t\t// @ts-ignore\n\t\t\t\t() => '',\n\t\t\t\t{\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tafterHandle: ({ status }) =>\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tstatus(201, { name: 'Jane Doe' }),\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t201: t.Object({\n\t\t\t\t\t\t\tfoo: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\t\t\t// @ts-ignore\n\t\t\t.get('/valid', () => '', {\n\t\t\t\tafterHandle: () => ({ foo: 'bar' }),\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tfoo: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/valid-201', () => '', {\n\t\t\t\tafterHandle: ({ status }) => status(201, { foo: 'bar' }),\n\t\t\t\tresponse: {\n\t\t\t\t\t201: t.Object({\n\t\t\t\t\t\tfoo: t.String()\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst invalid = await app.handle(req('/invalid')).then((x) => x.status)\n\t\tconst invalid201 = await app\n\t\t\t.handle(req('/invalid-201'))\n\t\t\t.then((x) => x.status)\n\t\tconst valid = await app.handle(req('/valid')).then((x) => x.status)\n\t\tconst valid201 = await app\n\t\t\t.handle(req('/valid-201'))\n\t\t\t.then((x) => x.status)\n\n\t\texpect(invalid).toBe(422)\n\t\texpect(invalid201).toBe(422)\n\t\texpect(valid).toBe(200)\n\t\texpect(valid201).toBe(201)\n\t})\n\n\tit('clean afterHandle', async () => {\n\t\tconst app = new Elysia({ aot: false })\n\t\t\t// @ts-ignore\n\t\t\t.get('/invalid', () => '', {\n\t\t\t\tafterHandle: () => ({ name: 'Jane Doe' }),\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tfoo: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t\t// @ts-ignore\n\t\t\t.get('/valid', () => '', {\n\t\t\t\tafterHandle: () => ({ foo: 'bar', a: 'b' }),\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tfoo: t.String()\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst invalid = await app.handle(req('/invalid')).then((x) => x.status)\n\t\tconst valid = await app.handle(req('/valid')).then((x) => x.json())\n\n\t\texpect(invalid).toBe(422)\n\t\texpect(valid).toEqual({\n\t\t\tfoo: 'bar'\n\t\t})\n\t})\n\n\tit('handle single query array', async () => {\n\t\tconst app = new Elysia({ aot: false }).get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tnames: t.Array(t.String())\n\t\t\t})\n\t\t})\n\n\t\tconst data = await app\n\t\t\t.handle(req('/?name=neon&names=rapi'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(data).toEqual({\n\t\t\tname: 'neon',\n\t\t\tnames: ['rapi']\n\t\t})\n\t})\n\n\tit('handle multiple query array in nuqs format', async () => {\n\t\tconst app = new Elysia({ aot: false }).get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tnames: t.Array(t.String())\n\t\t\t})\n\t\t})\n\n\t\tconst data = await app\n\t\t\t.handle(req('/?name=neon&names=rapi,anis'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(data).toEqual({\n\t\t\tname: 'neon',\n\t\t\tnames: ['rapi', 'anis']\n\t\t})\n\t})\n\n\tit('handle multiple query array in nuqs format', async () => {\n\t\tconst app = new Elysia({ aot: false }).get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tnames: t.Array(t.String())\n\t\t\t})\n\t\t})\n\n\t\tconst data = await app\n\t\t\t.handle(req('/?name=neon&names=rapi,anis'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(data).toEqual({\n\t\t\tname: 'neon',\n\t\t\tnames: ['rapi', 'anis']\n\t\t})\n\t})\n\n\tit('call local afterResponse on aot: false', async () => {\n\t\tlet called = false\n\n\t\tconst app = new Elysia({ aot: false })\n\t\t\t.guard(\n\t\t\t\t{\n\t\t\t\t\tafterResponse: () => {\n\t\t\t\t\t\tcalled = true\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t(app) => app.get('/test', () => 'afterResponse')\n\t\t\t)\n\t\t\t.get('/', () => 'hi')\n\n\t\tconst value = await app.handle(req('/test')).then((x) => x.text())\n\t\tawait Bun.sleep(6.7)\n\n\t\texpect(value).toBe('afterResponse')\n\t\texpect(called).toBeTrue()\n\t})\n\n\t// it('handle query array reference in multiple reference format', async () => {\n\t// \tconst IdsModel = new Elysia().model({\n\t// \t\tname: t.Object({\n\t// \t\t\tname: t.Array(t.String())\n\t// \t\t})\n\t// \t})\n\n\t// \tconst app = new Elysia({ aot: false })\n\t// \t\t.use(IdsModel)\n\t// \t\t.get('/', ({ query }) => query, {\n\t// \t\t\tquery: 'name'\n\t// \t\t})\n\n\t// \tconst data = await app\n\t// \t\t.handle(req('/?names=rapi&names=anis'))\n\t// \t\t.then((x) => x.json())\n\n\t// \texpect(data).toEqual({\n\t// \t\tnames: ['rapi', 'anis']\n\t// \t})\n\t// })\n\n\t// it('handle query array reference in multiple reference format', async () => {\n\t// \tconst IdsModel = new Elysia().model({\n\t// \t\tname: t.Object({\n\t// \t\t\tname: t.Array(t.String())\n\t// \t\t})\n\t// \t})\n\n\t// \tconst app = new Elysia({ aot: false })\n\t// \t\t.use(IdsModel)\n\t// \t\t.get('/', ({ query }) => query, {\n\t// \t\t\tquery: 'name'\n\t// \t\t})\n\n\t// \tconst data = await app\n\t// \t\t.handle(req('/?names=rapi&names=anis'))\n\t// \t\t.then((x) => x.json())\n\n\t// \texpect(data).toEqual({\n\t// \t\tnames: ['rapi', 'anis']\n\t// \t})\n\t// })\n\n\t// Union schema test - verifies getSchemaProperties handles Union without crashing\n\tit('handle Union query schema', async () => {\n\t\tconst app = new Elysia({ aot: false }).get(\n\t\t\t'/',\n\t\t\t({ query }) => query,\n\t\t\t{\n\t\t\t\tquery: t.Union([\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tsearch: t.String()\n\t\t\t\t\t}),\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tid: t.Numeric()\n\t\t\t\t\t})\n\t\t\t\t])\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(req('/?search=test'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response.search).toBe('test')\n\t})\n})\n"
  },
  {
    "path": "test/core/elysia.test.ts",
    "content": "import { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\nimport z from 'zod'\n\ndescribe('Edge Case', () => {\n\tit('handle state', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state('a', 'a')\n\t\t\t.get('/', ({ store: { a } }) => a)\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('a')\n\t})\n\n\t// https://github.com/oven-sh/bun/issues/1523\n\tit(\"don't return HTTP 10\", async () => {\n\t\tconst app = new Elysia().get('/', ({ set }) => {\n\t\t\tset.headers.Server = 'Elysia'\n\n\t\t\treturn 'hi'\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('has no side-effect', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/1', ({ set }) => {\n\t\t\t\tset.headers['x-server'] = 'Elysia'\n\n\t\t\t\treturn 'hi'\n\t\t\t})\n\t\t\t.get('/2', () => 'hi')\n\n\t\tconst res1 = await app.handle(req('/1'))\n\t\tconst res2 = await app.handle(req('/2'))\n\n\t\texpect(res1.headers.get('x-server')).toBe('Elysia')\n\t\texpect(res2.headers.get('x-server')).toBe(null)\n\t})\n\n\tit('return Promise', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => new Promise((resolve) => resolve('h'))\n\t\t)\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\t\texpect(res).toBe('h')\n\t})\n\n\tit('handle dynamic all method', async () => {\n\t\tconst app = new Elysia().all('/all/*', () => 'ALL')\n\n\t\tconst res = await app.handle(req('/all/world')).then((x) => x.text())\n\t\texpect(res).toBe('ALL')\n\t})\n\n\t// ? since different runtime expected to have different implementation of new Response\n\t// ? we can't handle all the case\n\t// it('handle object of class', async () => {\n\t// \tclass SomeResponse {\n\t// \t\tconstructor(public message: string) {}\n\t// \t}\n\n\t// \tconst app = new Elysia().get(\n\t// \t\t'/',\n\t// \t\t() => new SomeResponse('Hello, world!')\n\t// \t)\n\n\t// \tconst res = await app.handle(req('/')).then((x) => x.json())\n\t// \texpect(res).toStrictEqual({\n\t// \t\tmessage: 'Hello, world!'\n\t// \t})\n\t// })\n\n\t// it('handle object of class (async)', async () => {\n\t// \tclass SomeResponse {\n\t// \t\tconstructor(public message: string) {}\n\t// \t}\n\n\t// \tconst app = new Elysia().get('/', async () => {\n\t// \t\tawait Bun.sleep(1)\n\t// \t\treturn new SomeResponse('Hello, world!')\n\t// \t})\n\n\t// \tconst res = await app.handle(req('/')).then((x) => x.json())\n\t// \texpect(res).toStrictEqual({\n\t// \t\tmessage: 'Hello, world!'\n\t// \t})\n\t// })\n\n\tit('handle strict path and loose path', async () => {\n\t\tconst loose = new Elysia().group('/a', (app) =>\n\t\t\tapp.get('/', () => 'Hi')\n\t\t)\n\n\t\texpect(await loose.handle(req('/a')).then((x) => x.status)).toBe(200)\n\t\texpect(await loose.handle(req('/a/')).then((x) => x.status)).toBe(200)\n\n\t\tconst strict = new Elysia({\n\t\t\tstrictPath: true\n\t\t}).group('/a', (app) => app.get('/', () => 'Hi'))\n\n\t\texpect(await strict.handle(req('/a')).then((x) => x.status)).toBe(404)\n\t\texpect(await strict.handle(req('/a/')).then((x) => x.status)).toBe(200)\n\t})\n\n\tit('return cookie with file', async () => {\n\t\tconst kyuukararin = Bun.file('test/kyuukurarin.mp4')\n\n\t\tconst app = new Elysia().get('/', ({ cookie: { name } }) => {\n\t\t\tname.set({\n\t\t\t\tvalue: 'Rikuhachima Aru',\n\t\t\t\tmaxAge: new Date().setFullYear(new Date().getFullYear() + 1),\n\t\t\t\thttpOnly: true\n\t\t\t})\n\n\t\t\treturn kyuukararin\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(req('/'))\n\t\t\t.then((x) => x.headers.toJSON())\n\n\t\texpect(response['set-cookie']).toHaveLength(1)\n\t\texpect(response['content-type']).toBe('video/mp4')\n\t})\n\n\tit('return multiple cookies with file', async () => {\n\t\tconst kyuukararin = Bun.file('test/kyuukurarin.mp4')\n\n\t\tconst app = new Elysia().get('/', ({ cookie: { name, school } }) => {\n\t\t\tname.value = 'Rikuhachima Aru'\n\t\t\tschool.value = 'Gehenna'\n\n\t\t\treturn kyuukararin\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.headers.get('content-type')).toBe('video/mp4')\n\t\texpect(response.headers.getSetCookie()).toEqual([\n\t\t\t'name=Rikuhachima%20Aru; Path=/',\n\t\t\t'school=Gehenna; Path=/'\n\t\t])\n\t})\n\n\tit('preserve correct index order of routes if duplicated', () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/0', () => '0')\n\t\t\t.get('/1', () => '1')\n\t\t\t.get('/2', () => '2')\n\t\t\t.get('/3', () => '3')\n\t\t\t.get('/1', () => '-')\n\t\t\t.get('/4', () => '4')\n\n\t\t// @ts-expect-error\n\t\texpect(app.routeTree['GET_/0']).toEqual(0)\n\t\t// @ts-expect-error\n\t\texpect(app.routeTree['GET_/4']).toEqual(4)\n\t})\n\n\tit('preserve correct index order of routes if duplicated from plugin', () => {\n\t\tconst plugin = new Elysia()\n\t\t\t.get('/3', () => '3')\n\t\t\t.get('/1', () => '-')\n\t\t\t.get('/4', () => '4')\n\n\t\tconst app = new Elysia()\n\t\t\t.get('/0', () => '0')\n\t\t\t.get('/1', () => '1')\n\t\t\t.get('/2', () => '2')\n\t\t\t.use(plugin)\n\n\t\t// @ts-expect-error\n\t\texpect(app.routeTree['GET_/0']).toEqual(0)\n\t\t// @ts-expect-error\n\t\texpect(app.routeTree['GET_/4']).toEqual(4)\n\t})\n\n\tit('get getGlobalRoutes', () => {\n\t\tconst plugin = new Elysia().get('/', () => 'hello')\n\n\t\tconst main = new Elysia().use(plugin).get('/2', () => 'hi')\n\n\t\t// @ts-expect-error private property\n\t\texpect(main.getGlobalRoutes().length).toBe(2)\n\t})\n\n\tdescribe('value returned from transform has priority over the default value from schema', () => {\n\t\tconst route = new Elysia().get(\n\t\t\t'/:propParams?',\n\t\t\t({ params: { propParams } }) => propParams,\n\t\t\t{\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tpropParams: t.String({\n\t\t\t\t\t\tdefault: 'params-default'\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\ttransform({ params }) {\n\t\t\t\t\tparams.propParams = 'params-transform'\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tit('aot is on', async () => {\n\t\t\tconst app = new Elysia().use(route)\n\n\t\t\tconst response = await app\n\t\t\t\t.handle(new Request('http://localhost'))\n\t\t\t\t.then((x) => x.text())\n\n\t\t\texpect(response).toBe('params-transform')\n\t\t})\n\n\t\tit('aot is off', async () => {\n\t\t\tconst app = new Elysia({ aot: false }).use(route)\n\n\t\t\tconst response = await app\n\t\t\t\t.handle(new Request('http://localhost'))\n\t\t\t\t.then((x) => x.text())\n\n\t\t\texpect(response).toBe('params-transform')\n\t\t})\n\t})\n\n\tit('handle duplicated static route may cause index conflict correctly', async () => {\n\t\tconst Path = new Elysia({ name: 'auth' })\n\t\t\t.mount('/AB', (request) => new Response('AB'))\n\t\t\t.mount('/BA', (request) => new Response('BA'))\n\n\t\tconst Module = new Elysia().use(Path)\n\n\t\tconst app = new Elysia({ name: 'main' }).use(Path).use(Module)\n\n\t\tconst responses = await Promise.all([\n\t\t\tapp.handle(req('/AB')).then((x) => x.text()),\n\t\t\tapp.handle(req('/BA')).then((x) => x.text())\n\t\t])\n\n\t\texpect(responses).toEqual(['AB', 'BA'])\n\t})\n\n\tit('handle complex union with json exact mirror, and sanitize', async () => {\n\t\tconst app = new Elysia({\n\t\t\tsanitize: (v) => v && 'Elysia'\n\t\t}).get(\n\t\t\t'/',\n\t\t\t// @ts-ignore\n\t\t\t() => ({\n\t\t\t\ttype: 'ok',\n\t\t\t\tdata: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'cool',\n\t\t\t\t\t\tdata: null\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'yea',\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\ttype: 'aight',\n\t\t\t\t\t\t\tdata: null\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Recursive((This) =>\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\ttype: t.String(),\n\t\t\t\t\t\tdata: t.Union([t.Nullable(This), t.Array(This)])\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\ttype: 'Elysia',\n\t\t\tdata: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'Elysia',\n\t\t\t\t\tdata: null\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ttype: 'Elysia',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\ttype: 'Elysia',\n\t\t\t\t\t\tdata: null\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t]\n\t\t})\n\t})\n\n\tit('clone hooks before mapping it to usable function while compose', async () => {\n\t\tconst group = new Elysia()\n\t\t\t.macro({\n\t\t\t\tuser: (enabled: true) => ({\n\t\t\t\t\tresolve() {\n\t\t\t\t\t\tif (!enabled) return\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tuser: 'a'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/',\n\t\t\t\t({ user, status }) => {\n\t\t\t\t\tif (!user) return status(401)\n\n\t\t\t\t\treturn { hello: 'hanabi' }\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tuser: true\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst app = new Elysia({\n\t\t\tprecompile: true\n\t\t}).group('/group', (app) => app.use(group))\n\n\t\tconst response = await app.handle(req('/group')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\thello: 'hanabi'\n\t\t})\n\t})\n\n\tit('decode URI of path parameter', async () => {\n\t\tconst api = new Elysia().get('/:id', ({ params }) => params, {\n\t\t\tparams: t.Object({\n\t\t\t\tid: t.String()\n\t\t\t})\n\t\t})\n\n\t\tconst value = await api\n\t\t\t.handle(new Request('http://localhost:3000/hello world'))\n\t\t\t.then((response) => response.json())\n\n\t\texpect(value).toEqual({\n\t\t\tid: 'hello world'\n\t\t})\n\t})\n\n\tit('clean non-root additionalProperties', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => ({\n\t\t\t\tkeys: [{ a: 1, b: 2 }],\n\t\t\t\textra: true\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object(\n\t\t\t\t\t{ keys: t.Array(t.Object({ a: t.Number() })) },\n\t\t\t\t\t{ additionalProperties: true }\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst value = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(value).toEqual({\n\t\t\tkeys: [{ a: 1 }],\n\t\t\textra: true\n\t\t})\n\t})\n\n\tit('prevent side-effect from guard merge', async () => {\n\t\tconst app = new Elysia().guard(\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t403: t.String()\n\t\t\t\t}\n\t\t\t},\n\t\t\t(app) =>\n\t\t\t\tapp\n\t\t\t\t\t.get('/foo', () => 'bar', { response: { 200: t.String() } })\n\t\t\t\t\t.get('/bar', () => 12, { response: { 200: t.Integer() } })\n\t\t)\n\n\t\tconst response = await app.handle(req('/foo'))\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('automatically handle HEAD request for GET static path', async () => {\n\t\tconst app = new Elysia().get('/', () => 'hello world')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost', {\n\t\t\t\tmethod: 'HEAD'\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(response.headers.toJSON()).toEqual({\n\t\t\t'content-length': '11'\n\t\t})\n\t})\n\n\tit('automatically handle HEAD request for GET dynamic path', async () => {\n\t\tconst app = new Elysia().get('/:id', () => 'hello world')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/1', {\n\t\t\t\tmethod: 'HEAD'\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(response.headers.toJSON()).toEqual({\n\t\t\t'content-length': '11'\n\t\t})\n\t})\n\n\tit('handle arbitrary code execution from cookie', async () => {\n\t\tconst app = new Elysia({\n\t\t\tcookie: {\n\t\t\t\tsecrets: `\\` + console.log(c.q='pwn') + \\``,\n\t\t\t\tdomain: process.env.COOKIE_DOMAIN || 'localhost'\n\t\t\t}\n\t\t}).get(\n\t\t\t'/',\n\t\t\t(c) =>\n\t\t\t\t// @ts-ignore\n\t\t\t\tc.q ?? 'safe',\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tfoo: t.Optional(t.Any())\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(req('/?name=saltyaom'))\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe('safe')\n\t})\n\n\tit('prototype pollution from input', () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: z.object({\n\t\t\t\t\tdata: z.any()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => ({\n\t\t\t\t\tbody,\n\t\t\t\t\twin:\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t{}.foo\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tbody: z.object({\n\t\t\t\t\t\tdata: z.object({\n\t\t\t\t\t\t\tmessageId: z.string('pollute-me')\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\n\t\tapp.handle(\n\t\t\tnew Request('http://localhost:3000/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t},\n\t\t\t\tbody: `{\n\t\t\t\t\t\"data\": {\n\t\t\t\t\t\t\"messageId\": \"pollute-me\",\n\t\t\t\t\t\t\"__proto__\": {\n\t\t\t\t\t\t\t\"foo\": \"bar\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}`\n\t\t\t})\n\t\t).then((x) => x.json())\n\t})\n})\n"
  },
  {
    "path": "test/core/formdata.test.ts",
    "content": "import { Elysia, t, form, file } from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('Form Data', () => {\n\tit('return Bun.file', async () => {\n\t\tconst app = new Elysia().get('/', () =>\n\t\t\tform({\n\t\t\t\ta: 'hello',\n\t\t\t\tb: Bun.file('test/kyuukurarin.mp4')\n\t\t\t})\n\t\t)\n\n\t\tconst contentType = await app\n\t\t\t.handle(req('/'))\n\t\t\t.then((x) => x.headers.get('content-type'))\n\n\t\texpect(contentType).toStartWith('multipart/form-data')\n\t})\n\n\tit('return Elysia.file', async () => {\n\t\tconst app = new Elysia().get('/', () =>\n\t\t\tform({\n\t\t\t\ta: 'hello',\n\t\t\t\tb: file('test/kyuukurarin.mp4')\n\t\t\t})\n\t\t)\n\n\t\tconst contentType = await app\n\t\t\t.handle(req('/'))\n\t\t\t.then((x) => x.headers.get('content-type'))\n\n\t\texpect(contentType).toStartWith('multipart/form-data')\n\t})\n\n\tit('return Elysia.file', async () => {\n\t\tconst app = new Elysia().get('/', () =>\n\t\t\tform({\n\t\t\t\ta: 'hello',\n\t\t\t\tb: file('test/kyuukurarin.mp4')\n\t\t\t})\n\t\t)\n\n\t\tconst contentType = await app\n\t\t\t.handle(req('/'))\n\t\t\t.then((x) => x.headers.get('content-type'))\n\n\t\texpect(contentType).toStartWith('multipart/form-data')\n\t})\n\n\tit('validate formdata', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() =>\n\t\t\t\tform({\n\t\t\t\t\ta: 'hello',\n\t\t\t\t\tb: file('test/kyuukurarin.mp4')\n\t\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Form({\n\t\t\t\t\ta: t.String(),\n\t\t\t\t\tb: t.File()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(response.headers.get('content-type')).toStartWith(\n\t\t\t'multipart/form-data'\n\t\t)\n\t})\n\n\tit('return single file', async () => {\n\t\tconst app = new Elysia().get('/', () => file('test/kyuukurarin.mp4'))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(response.headers.get('content-type')).toStartWith('video/mp4')\n\t})\n\n\tit('inline single file', async () => {\n\t\tconst app = new Elysia().get('/', file('test/kyuukurarin.mp4'))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(response.headers.get('content-type')).toStartWith('video/mp4')\n\t})\n})\n"
  },
  {
    "path": "test/core/handle-error.test.ts",
    "content": "import { Elysia, InternalServerError, NotFoundError, status, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\nconst request = new Request('http://localhost:8080')\n\ndescribe('Handle Error', () => {\n\tit('handle NOT_FOUND', async () => {\n\t\tconst res = await new Elysia()\n\t\t\t.get('/', () => 'Hi')\n\t\t\t// @ts-expect-error private\n\t\t\t.handleError(\n\t\t\t\t{\n\t\t\t\t\trequest,\n\t\t\t\t\tset: {\n\t\t\t\t\t\theaders: {}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tnew NotFoundError()\n\t\t\t)\n\n\t\texpect(await res.text()).toBe('NOT_FOUND')\n\t\texpect(res.status).toBe(404)\n\t})\n\n\tit('handle INTERNAL_SERVER_ERROR', async () => {\n\t\tconst res = await new Elysia()\n\t\t\t.get('/', () => 'Hi')\n\t\t\t// @ts-expect-error private\n\t\t\t.handleError(\n\t\t\t\t{\n\t\t\t\t\trequest,\n\t\t\t\t\tset: {\n\t\t\t\t\t\theaders: {}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tnew InternalServerError()\n\t\t\t)\n\n\t\texpect(await res.text()).toBe('INTERNAL_SERVER_ERROR')\n\t\texpect(res.status).toBe(500)\n\t})\n\n\tit('handle VALIDATION', async () => {\n\t\tconst res = await new Elysia()\n\t\t\t.get('/', () => 'Hi', {\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.handle(req('/'))\n\n\t\texpect(res.status).toBe(422)\n\t})\n\n\tit('use custom error', async () => {\n\t\tconst res = await new Elysia()\n\t\t\t.get('/', () => 'Hi')\n\t\t\t.onError(({ code }) => {\n\t\t\t\tif (code === 'NOT_FOUND')\n\t\t\t\t\treturn new Response(\"I'm a teapot\", {\n\t\t\t\t\t\tstatus: 418\n\t\t\t\t\t})\n\t\t\t})\n\t\t\t.handle(req('/not-found'))\n\n\t\texpect(await res.text()).toBe(\"I'm a teapot\")\n\t\texpect(res.status).toBe(418)\n\t})\n\n\tit('inject headers to error', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onRequest(({ set }) => {\n\t\t\t\tset.headers['Access-Control-Allow-Origin'] = '*'\n\t\t\t})\n\t\t\t.get('/', () => {\n\t\t\t\tthrow new NotFoundError()\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')\n\t\texpect(res.status).toBe(404)\n\t})\n\n\tit('transform any to error', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(async ({ set }) => {\n\t\t\t\tset.status = 418\n\n\t\t\t\treturn 'aw man'\n\t\t\t})\n\t\t\t.get('/', () => {\n\t\t\t\tthrow new NotFoundError()\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('aw man')\n\t\texpect(res.status).toBe(418)\n\t})\n\n\tit('handle error in group', async () => {\n\t\tconst authenticate = new Elysia().group('/group', (group) =>\n\t\t\tgroup\n\t\t\t\t.get('/inner', () => {\n\t\t\t\t\tthrow new Error('A')\n\t\t\t\t})\n\t\t\t\t.onError(() => {\n\t\t\t\t\treturn 'handled'\n\t\t\t\t})\n\t\t)\n\n\t\tconst app = new Elysia().use(authenticate)\n\n\t\tconst response = await app.handle(req('/group/inner'))\n\n\t\texpect(await response.text()).toEqual('handled')\n\t\texpect(response.status).toEqual(500)\n\t})\n\n\tit('handle error status in group', async () => {\n\t\tconst authenticate = new Elysia().group('/group', (group) =>\n\t\t\tgroup\n\t\t\t\t.get('/inner', ({ set }) => {\n\t\t\t\t\tset.status = 418\n\n\t\t\t\t\tthrow new Error('A')\n\t\t\t\t})\n\t\t\t\t.onError(() => {\n\t\t\t\t\treturn 'handled'\n\t\t\t\t})\n\t\t)\n\n\t\tconst app = new Elysia().use(authenticate)\n\n\t\tconst response = await app.handle(req('/group/inner'))\n\n\t\texpect(await response.text()).toEqual('handled')\n\t\texpect(response.status).toEqual(418)\n\t})\n\n\tit('handle thrown error function', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => {\n\t\t\tthrow status(404, 'Not Found :(')\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(await response.text()).toEqual('Not Found :(')\n\t\texpect(response.status).toEqual(404)\n\t})\n\n\tit('handle thrown Response', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => {\n\t\t\tthrow status(404, 'Not Found :(')\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(await response.text()).toEqual('Not Found :(')\n\t\texpect(response.status).toEqual(404)\n\t})\n\n\tit('handle error code in request', async () => {\n\t\tclass APIError extends Error {\n\t\t\tpublic readonly message: string\n\t\t\tpublic readonly status: number\n\n\t\t\tconstructor(\n\t\t\t\tstatus: number,\n\t\t\t\tmessage: string,\n\t\t\t\toptions?: ErrorOptions\n\t\t\t) {\n\t\t\t\tsuper(message, options)\n\n\t\t\t\tthis.status = status\n\t\t\t\tthis.message = message\n\t\t\t\tthis.name = 'APIError'\n\n\t\t\t\tObject.setPrototypeOf(this, APIError.prototype)\n\t\t\t\tError.captureStackTrace(this)\n\t\t\t}\n\t\t}\n\n\t\tconst errors = new Elysia()\n\t\t\t.error({ APIError })\n\t\t\t.onError({ as: 'global' }, ({ code }) => {\n\t\t\t\treturn code\n\t\t\t})\n\n\t\tconst requestHandler = new Elysia()\n\t\t\t.onTransform(() => {\n\t\t\t\tthrow new APIError(403, 'Not authorized')\n\t\t\t})\n\t\t\t.get('/', () => 'a')\n\n\t\tconst app = new Elysia().use(errors).use(requestHandler)\n\n\t\texpect(await app.handle(req('/')).then((req) => req.text())).toBe(\n\t\t\t'APIError'\n\t\t)\n\t})\n\n\tit('parse headers', async () => {\n\t\tconst headers = await new Elysia()\n\t\t\t.get('/', ({ headers }) => headers)\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost:3000', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t\t'X-Test': 'Nagi'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(headers).toEqual({\n\t\t\t'content-type': 'application/json',\n\t\t\t'x-test': 'Nagi'\n\t\t})\n\t})\n\n\tit('handle error in Transform', async () => {\n\t\tconst route = new Elysia().get('/', ({ query: { aid } }) => aid, {\n\t\t\tquery: t.Object({\n\t\t\t\taid: t\n\t\t\t\t\t.Transform(t.String())\n\t\t\t\t\t.Decode((value) => {\n\t\t\t\t\t\tthrow new NotFoundError('foo')\n\t\t\t\t\t})\n\t\t\t\t\t.Encode((value) => `1`)\n\t\t\t})\n\t\t})\n\n\t\tlet response = await new Elysia({ aot: false })\n\t\t\t.use(route)\n\t\t\t.handle(req('/?aid=a'))\n\n\t\texpect(response.status).toEqual(404)\n\t\texpect(await response.text()).toEqual('foo')\n\n\t\tresponse = await new Elysia({ aot: true })\n\t\t\t.use(route)\n\t\t\t.handle(req('/?aid=a'))\n\t\texpect(response.status).toEqual(404)\n\t\texpect(await response.text()).toEqual('foo')\n\t})\n\n\tit('map status error to response', async () => {\n\t\tconst value = { message: 'meow!' }\n\n\t\tconst response: Response = await new Elysia()\n\t\t\t.get('/', () => 'Hello', {\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tthrow status(\"I'm a teapot\", { message: 'meow!' })\n\t\t\t\t}\n\t\t\t})\n\t\t\t// @ts-expect-error private property\n\t\t\t.handleError(\n\t\t\t\t{\n\t\t\t\t\trequest: new Request('http://localhost/'),\n\t\t\t\t\tset: {\n\t\t\t\t\t\theaders: {}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tstatus(422, value) as any\n\t\t\t)\n\n\t\texpect(await response.json()).toEqual(value)\n\t\texpect(response.headers.get('content-type')).toStartWith(\n\t\t\t'application/json'\n\t\t)\n\t\texpect(response.status).toEqual(422)\n\t})\n\n\tit('map status error with custom mapResponse', async () => {\n\t\tconst value = { message: 'meow!' }\n\n\t\tconst response: Response = await new Elysia()\n\t\t\t.mapResponse(({ responseValue }) => {\n\t\t\t\tif (typeof responseValue === 'object')\n\t\t\t\t\treturn new Response('Don Quixote', {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'content-type': 'text/plain'\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'Hello', {\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tthrow status(\"I'm a teapot\", { message: 'meow!' })\n\t\t\t\t}\n\t\t\t})\n\t\t\t// @ts-expect-error private property\n\t\t\t.handleError(\n\t\t\t\t{\n\t\t\t\t\trequest: new Request('http://localhost/'),\n\t\t\t\t\tset: {\n\t\t\t\t\t\theaders: {}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tstatus(422, value) as any\n\t\t\t)\n\n\t\texpect(await response.text()).toBe('Don Quixote')\n\t\texpect(response.headers.get('content-type')).toStartWith('text/plain')\n\t\texpect(response.status).toEqual(422)\n\t})\n\n\tit('handle generic error', async () => {\n\t\tconst res = await new Elysia()\n\t\t\t.get('/', () => 'Hi')\n\t\t\t// @ts-expect-error private\n\t\t\t.handleError(\n\t\t\t\t{\n\t\t\t\t\trequest,\n\t\t\t\t\tset: {\n\t\t\t\t\t\theaders: {}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t// https://youtube.com/shorts/PbIWVPKHfrQ\n\t\t\t\tnew Error('a')\n\t\t\t)\n\n\t\texpect(await res.text()).toBe('a')\n\t\texpect(res.status).toBe(500)\n\t})\n\n\tit('handle generic error when thrown in handler', async () => {\n\t\tconst app = new Elysia().get('/', () => {\n\t\t\tthrow new Error('a')\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('a')\n\t\texpect(res.status).toBe(500)\n\t})\n\n\tit('handle Error with toResponse() when returned', async () => {\n\t\tclass ErrorA extends Error {\n\t\t\ttoResponse() {\n\t\t\t\treturn Response.json({ error: 'hello' }, { status: 418 })\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().get('/A', () => {\n\t\t\treturn new ErrorA()\n\t\t})\n\n\t\tconst res = await app.handle(req('/A'))\n\n\t\texpect(await res.json()).toEqual({ error: 'hello' })\n\t\texpect(res.status).toBe(418)\n\t})\n\n\tit('handle Error with toResponse() when thrown', async () => {\n\t\tclass ErrorA extends Error {\n\t\t\ttoResponse() {\n\t\t\t\treturn Response.json({ error: 'hello' }, { status: 418 })\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().get('/A', () => {\n\t\t\tthrow new ErrorA()\n\t\t})\n\n\t\tconst res = await app.handle(req('/A'))\n\n\t\texpect(await res.json()).toEqual({ error: 'hello' })\n\t\texpect(res.status).toBe(418)\n\t})\n\n\tit('handle non-Error with toResponse() when returned', async () => {\n\t\tclass ErrorB {\n\t\t\ttoResponse() {\n\t\t\t\treturn Response.json({ error: 'hello' }, { status: 418 })\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().get('/B', () => {\n\t\t\treturn new ErrorB()\n\t\t})\n\n\t\tconst res = await app.handle(req('/B'))\n\n\t\texpect(await res.json()).toEqual({ error: 'hello' })\n\t\texpect(res.status).toBe(418)\n\t})\n\n\tit('handle non-Error with toResponse() when thrown', async () => {\n\t\tclass ErrorB {\n\t\t\ttoResponse() {\n\t\t\t\treturn Response.json({ error: 'hello' }, { status: 418 })\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().get('/B', () => {\n\t\t\tthrow new ErrorB()\n\t\t})\n\n\t\tconst res = await app.handle(req('/B'))\n\n\t\texpect(await res.json()).toEqual({ error: 'hello' })\n\t\texpect(res.status).toBe(418)\n\t})\n\n\tit('handle Error with toResponse() that includes custom headers', async () => {\n\t\tclass ErrorWithHeaders extends Error {\n\t\t\ttoResponse() {\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{ error: 'custom error' },\n\t\t\t\t\t{\n\t\t\t\t\t\tstatus: 418,\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'X-Custom-Header': 'custom-value',\n\t\t\t\t\t\t\t'Content-Type': 'application/json; charset=utf-8'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().get('/', () => {\n\t\t\tthrow new ErrorWithHeaders()\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.json()).toEqual({ error: 'custom error' })\n\t\texpect(res.status).toBe(418)\n\t\texpect(res.headers.get('X-Custom-Header')).toBe('custom-value')\n\t})\n\n\tit('handle async toResponse() when thrown', async () => {\n\t\tclass AsyncError extends Error {\n\t\t\tasync toResponse() {\n\t\t\t\t// Simulate async operation\n\t\t\t\tawait new Promise(resolve => setTimeout(resolve, 10))\n\t\t\t\treturn Response.json({ error: 'async error' }, { status: 418 })\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().get('/', () => {\n\t\t\tthrow new AsyncError()\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.json()).toEqual({ error: 'async error' })\n\t\texpect(res.status).toBe(418)\n\t})\n\n\tit('handle async toResponse() when returned', async () => {\n\t\tclass AsyncError extends Error {\n\t\t\tasync toResponse() {\n\t\t\t\t// Simulate async operation\n\t\t\t\tawait new Promise(resolve => setTimeout(resolve, 10))\n\t\t\t\treturn Response.json({ error: 'async error' }, { status: 418 })\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().get('/', () => {\n\t\t\treturn new AsyncError()\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.json()).toEqual({ error: 'async error' })\n\t\texpect(res.status).toBe(418)\n\t})\n\n\tit('handle async toResponse() with custom headers', async () => {\n\t\tclass AsyncErrorWithHeaders extends Error {\n\t\t\tasync toResponse() {\n\t\t\t\tawait new Promise(resolve => setTimeout(resolve, 10))\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{ error: 'async with headers' },\n\t\t\t\t\t{\n\t\t\t\t\t\tstatus: 419,\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'X-Async-Header': 'async-value'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().get('/', () => {\n\t\t\tthrow new AsyncErrorWithHeaders()\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.json()).toEqual({ error: 'async with headers' })\n\t\texpect(res.status).toBe(419)\n\t\texpect(res.headers.get('X-Async-Header')).toBe('async-value')\n\t})\n\n\tit('handle non-Error with async toResponse()', async () => {\n\t\tclass AsyncNonError {\n\t\t\tasync toResponse() {\n\t\t\t\tawait new Promise(resolve => setTimeout(resolve, 10))\n\t\t\t\treturn Response.json({ error: 'non-error async' }, { status: 418 })\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().get('/', () => {\n\t\t\tthrow new AsyncNonError()\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.json()).toEqual({ error: 'non-error async' })\n\t\texpect(res.status).toBe(418)\n\t})\n\n\tit('handle toResponse() that throws an error', async () => {\n\t\tclass BrokenError extends Error {\n\t\t\ttoResponse() {\n\t\t\t\tthrow new Error('toResponse failed')\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().get('/', () => {\n\t\t\tthrow new BrokenError('original error')\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(500)\n\t\texpect(await res.text()).toBe('original error')\n\t})\n\n\tit('handle async toResponse() that throws an error', async () => {\n\t\tclass BrokenAsyncError extends Error {\n\t\t\tasync toResponse() {\n\t\t\t\tthrow new Error('async toResponse failed')\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().get('/', () => {\n\t\t\tthrow new BrokenAsyncError('original error')\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(500)\n\t\texpect(await res.text()).toBe('original error')\n\t})\n\n\tit('send set-cookie header when error is thrown', async () => {\n\t\tconst app = new Elysia().get('/', ({ cookie }) => {\n\t\t\tcookie.session.value = 'test-session-id'\n\t\t\tthrow new Error('test error')\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(500)\n\t\texpect(res.headers.get('set-cookie')).toContain('session=test-session-id')\n\t})\n\n\tit('send set-cookie header when response validation error occurs', async () => {\n\t\tconst app = new Elysia().get('/', ({ cookie }) => {\n\t\t\tcookie.session.value = 'test-session-id'\n\t\t\treturn 'invalid response'\n\t\t}, {\n\t\t\tresponse: t.Number()\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(422)\n\t\texpect(res.headers.get('set-cookie')).toContain('session=test-session-id')\n\t})\n\n\tit('send set-cookie header when error is thrown with onError hook', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ error }) => {\n\t\t\t\treturn error.message\n\t\t\t})\n\t\t\t.get('/', ({ cookie }) => {\n\t\t\t\tcookie.session.value = 'test-session-id'\n\t\t\t\tthrow new Error('custom error')\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(500)\n\t\texpect(await res.text()).toBe('custom error')\n\t\texpect(res.headers.get('set-cookie')).toContain('session=test-session-id')\n\t})\n\n\tit('send set-cookie header when NotFoundError is thrown', async () => {\n\t\tconst app = new Elysia().get('/', ({ cookie }) => {\n\t\t\tcookie.session.value = 'test-session-id'\n\t\t\tthrow new NotFoundError()\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(404)\n\t\texpect(res.headers.get('set-cookie')).toContain('session=test-session-id')\n\t})\n\n\tit('send set-cookie header when InternalServerError is thrown', async () => {\n\t\tconst app = new Elysia().get('/', ({ cookie }) => {\n\t\t\tcookie.session.value = 'test-session-id'\n\t\t\tthrow new InternalServerError()\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(500)\n\t\texpect(res.headers.get('set-cookie')).toContain('session=test-session-id')\n\t})\n\n\tit('send set-cookie header in AOT mode when error is thrown', async () => {\n\t\tconst app = new Elysia({ aot: true }).get('/', ({ cookie }) => {\n\t\t\tcookie.session.value = 'test-session-id'\n\t\t\tthrow new Error('test error')\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(500)\n\t\texpect(res.headers.get('set-cookie')).toContain('session=test-session-id')\n\t})\n\n\tit('preserve multiple cookies when error is thrown', async () => {\n\t\tconst app = new Elysia().get('/', ({ cookie }) => {\n\t\t\tcookie.session.value = 'session-123'\n\t\t\tcookie.user.value = 'user-456'\n\t\t\tthrow new Error('test error')\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(500)\n\t\tconst setCookie = res.headers.get('set-cookie')\n\t\texpect(setCookie).toContain('session=session-123')\n\t\texpect(setCookie).toContain('user=user-456')\n\t})\n\n\tit('send set-cookie header when error has custom headers', async () => {\n\t\tconst app = new Elysia().get('/', ({ cookie, set }) => {\n\t\t\tcookie.session.value = 'test-session-id'\n\t\t\tset.headers['x-custom'] = 'value'\n\t\t\tthrow new Error('test error')\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.headers.get('set-cookie')).toContain('session=test-session-id')\n\t\texpect(res.headers.get('x-custom')).toBe('value')\n\t})\n})\n"
  },
  {
    "path": "test/core/macro-lifecycle.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Elysia } from '../../src'\n\ndescribe('macro beforeHandle lifecycle order', () => {\n\tit('should run macro beforeHandle before nested plugin resolve', async () => {\n\t\tconst executionOrder: string[] = []\n\n\t\t// Auth service with resolve + macro\n\t\tconst authService = new Elysia({ name: 'auth-service' })\n\t\t\t.resolve(() => {\n\t\t\t\texecutionOrder.push('authService.resolve')\n\t\t\t\treturn { userId: undefined } // Simulating no auth\n\t\t\t})\n\t\t\t.macro({\n\t\t\t\tisSignedIn: {\n\t\t\t\t\tbeforeHandle({ userId }) {\n\t\t\t\t\t\texecutionOrder.push('isSignedIn.beforeHandle')\n\t\t\t\t\t\tif (!userId) throw new Error('Unauthorized')\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.as('scoped')\n\n\t\t// DB client that requires userId\n\t\tconst dbClient = new Elysia({ name: 'db-client' })\n\t\t\t.resolve((ctx) => {\n\t\t\t\texecutionOrder.push('dbClient.resolve')\n\t\t\t\tconst userId = (ctx as { userId?: string }).userId\n\t\t\t\tif (!userId) throw new Error('User ID is required')\n\t\t\t\treturn { db: { userId } }\n\t\t\t})\n\t\t\t.as('scoped')\n\n\t\t// Feature module using dbClient\n\t\tconst feature = new Elysia({ name: 'feature' })\n\t\t\t.use(dbClient)\n\t\t\t.get('/', ({ db }) => `Hello ${db.userId}`)\n\n\t\t// Main app\n\t\tconst app = new Elysia()\n\t\t\t.use(authService)\n\t\t\t.group('/v1', { isSignedIn: true }, (app) => app.use(feature))\n\n\t\tconst response = await app.handle(new Request('http://localhost/v1/'))\n\n\t\t// The macro's beforeHandle should run BEFORE dbClient's resolve\n\t\t// So we should get \"Unauthorized\" error, not \"User ID is required\"\n\t\tconst body = await response.text()\n\n\t\t// console.log('Execution order:', executionOrder)\n\t\t// console.log('Response:', body)\n\n\t\t// Expected order: authService.resolve -> isSignedIn.beforeHandle (throws)\n\t\t// dbClient.resolve should NOT run because beforeHandle throws first\n\t\texpect(executionOrder).toContain('authService.resolve')\n\t\texpect(executionOrder).toContain('isSignedIn.beforeHandle')\n\t\texpect(executionOrder).not.toContain('dbClient.resolve')\n\t\texpect(body).toContain('Unauthorized')\n\t})\n\n\tit('should run hooks in registration order within same queue', async () => {\n\t\tconst executionOrder: string[] = []\n\n\t\tconst app = new Elysia()\n\t\t\t.resolve(() => {\n\t\t\t\texecutionOrder.push('resolve1')\n\t\t\t\treturn { val1: 1 }\n\t\t\t})\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\texecutionOrder.push('beforeHandle1')\n\t\t\t})\n\t\t\t.resolve(() => {\n\t\t\t\texecutionOrder.push('resolve2')\n\t\t\t\treturn { val2: 2 }\n\t\t\t})\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\texecutionOrder.push('beforeHandle2')\n\t\t\t})\n\t\t\t.get('/', () => 'ok')\n\n\t\tawait app.handle(new Request('http://localhost/'))\n\n\t\t// console.log('Execution order:', executionOrder)\n\n\t\t// According to docs, resolve and beforeHandle share the same queue\n\t\t// Order should be: resolve1 -> beforeHandle1 -> resolve2 -> beforeHandle2\n\t\texpect(executionOrder).toEqual([\n\t\t\t'resolve1',\n\t\t\t'beforeHandle1',\n\t\t\t'resolve2',\n\t\t\t'beforeHandle2'\n\t\t])\n\t})\n\n\tit('should demonstrate the issue with macro in group', async () => {\n\t\tconst executionOrder: string[] = []\n\t\tlet errorMessage = ''\n\n\t\tconst authPlugin = new Elysia({ name: 'auth' })\n\t\t\t.resolve(() => {\n\t\t\t\texecutionOrder.push('auth.resolve')\n\t\t\t\treturn { userId: 'user123' } // Auth succeeds\n\t\t\t})\n\t\t\t.macro({\n\t\t\t\trequireAuth: {\n\t\t\t\t\tbeforeHandle({ userId }) {\n\t\t\t\t\t\texecutionOrder.push('requireAuth.beforeHandle')\n\t\t\t\t\t\tif (!userId) throw new Error('Unauthorized')\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.as('scoped')\n\n\t\tconst dataPlugin = new Elysia({ name: 'data' })\n\t\t\t.resolve((ctx) => {\n\t\t\t\texecutionOrder.push('data.resolve')\n\t\t\t\treturn { data: 'some data' }\n\t\t\t})\n\t\t\t.as('scoped')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(authPlugin)\n\t\t\t.onError(({ error }) => {\n\t\t\t\t// @ts-ignore\n\t\t\t\terrorMessage = error.message\n\t\t\t\treturn errorMessage\n\t\t\t})\n\t\t\t.group('/api', { requireAuth: true }, (app) =>\n\t\t\t\tapp.use(dataPlugin).get('/', ({ data }) => data)\n\t\t\t)\n\n\t\tconst response = await app.handle(new Request('http://localhost/api/'))\n\n\t\t// console.log('Execution order:', executionOrder)\n\t\t// console.log('Error:', errorMessage)\n\n\t\t// With auth succeeding (userId = 'user123'), all should run\n\t\t// Expected: auth.resolve -> requireAuth.beforeHandle -> data.resolve\n\t\texpect(executionOrder).toEqual([\n\t\t\t'auth.resolve',\n\t\t\t'requireAuth.beforeHandle',\n\t\t\t'data.resolve'\n\t\t])\n\t})\n\n\tit('should preserve macro schema when merging with nested plugin hooks', async () => {\n\t\tconst { t } = await import('../../src')\n\n\t\t// Macro that adds both beforeHandle and body schema\n\t\tconst validatedMacro = new Elysia({ name: 'validated-macro' })\n\t\t\t.macro({\n\t\t\t\tvalidatePayload: {\n\t\t\t\t\tbody: t.Object({\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t}),\n\t\t\t\t\tbeforeHandle() {\n\t\t\t\t\t\t// Macro's beforeHandle\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.as('scoped')\n\n\t\tconst nestedPlugin = new Elysia({ name: 'nested' })\n\t\t\t.resolve(() => ({ nested: true }))\n\t\t\t.as('scoped')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(validatedMacro)\n\t\t\t.group('/api', { validatePayload: true }, (app) =>\n\t\t\t\tapp.use(nestedPlugin).post('/', ({ body }) => body.name)\n\t\t\t)\n\n\t\t// Valid request - should pass validation\n\t\tconst validResponse = await app.handle(\n\t\t\tnew Request('http://localhost/api/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\tbody: JSON.stringify({ name: 'test' })\n\t\t\t})\n\t\t)\n\t\texpect(validResponse.status).toBe(200)\n\t\texpect(await validResponse.text()).toBe('test')\n\n\t\t// Invalid request - should fail validation (macro schema should be preserved)\n\t\tconst invalidResponse = await app.handle(\n\t\t\tnew Request('http://localhost/api/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\tbody: JSON.stringify({ invalid: 'data' })\n\t\t\t})\n\t\t)\n\t\t// If macro schema is lost, this would be 200 instead of 422\n\t\texpect(invalidResponse.status).toBe(422)\n\t})\n})\n"
  },
  {
    "path": "test/core/modules.test.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { Elysia } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\nimport { sleep } from 'bun'\n\nconst asyncPlugin = async (app: Elysia) => app.get('/async', () => 'async')\nconst lazyPlugin = import('../modules')\nconst lazyNamed = lazyPlugin.then((x) => x.lazy)\n\ndescribe('Modules', () => {\n\tit('inline async', async () => {\n\t\tconst app = new Elysia().use(async (app) =>\n\t\t\tapp.get('/async', () => 'async')\n\t\t)\n\n\t\tawait app.modules\n\n\t\tconst res = await app.handle(req('/async')).then((r) => r.text())\n\n\t\texpect(res).toBe('async')\n\t})\n\n\tit('async', async () => {\n\t\tconst app = new Elysia().use(asyncPlugin)\n\n\t\tawait app.modules\n\n\t\tconst res = await app.handle(req('/async')).then((r) => r.text())\n\n\t\texpect(res).toBe('async')\n\t})\n\n\tit('inline import', async () => {\n\t\tconst app = new Elysia().use(import('../modules'))\n\n\t\tawait app.modules\n\n\t\tconst res = await app.handle(req('/lazy')).then((r) => r.text())\n\n\t\texpect(res).toBe('lazy')\n\t})\n\n\tit('import', async () => {\n\t\tconst app = new Elysia().use(lazyPlugin)\n\n\t\tawait app.modules\n\n\t\tconst res = await app.handle(req('/lazy')).then((r) => r.text())\n\n\t\texpect(res).toBe('lazy')\n\t})\n\n\tit('import non default', async () => {\n\t\tconst app = new Elysia().use(lazyNamed)\n\n\t\tawait app.modules\n\n\t\tconst res = await app.handle(req('/lazy')).then((r) => r.text())\n\n\t\texpect(res).toBe('lazy')\n\t})\n\n\tit('inline import non default', async () => {\n\t\tconst app = new Elysia().use(import('../modules'))\n\n\t\tawait app.modules\n\n\t\tconst res = await app.handle(req('/lazy')).then((r) => r.text())\n\n\t\texpect(res).toBe('lazy')\n\t})\n\n\tit('register async and lazy path', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.use(import('../modules'))\n\t\t\t.use(asyncPlugin)\n\t\t\t.get('/', () => 'hi')\n\n\t\tawait app.modules\n\n\t\tconst res = await app.handle(req('/async'))\n\n\t\texpect(res.status).toEqual(200)\n\t})\n\n\tit('handle other routes while lazy load', async () => {\n\t\tconst app = new Elysia().use(import('../timeout')).get('/', () => 'hi')\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.text())\n\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('handle deferred import', async () => {\n\t\tconst app = new Elysia().use(import('../modules'))\n\n\t\tawait app.modules\n\n\t\tconst res = await app.handle(req('/lazy')).then((x) => x.text())\n\n\t\texpect(res).toBe('lazy')\n\t})\n\n\tit('re-compile on async plugin', async () => {\n\t\tconst app = new Elysia().use(async (app) => {\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1))\n\n\t\t\treturn app.get('/', () => 'hi')\n\t\t})\n\n\t\tawait app.modules\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('handle async plugin', async () => {\n\t\tconst a =\n\t\t\t(config = {}) =>\n\t\t\tasync (app: Elysia) => {\n\t\t\t\tawait sleep(0)\n\t\t\t\treturn app.derive(() => ({\n\t\t\t\t\tderived: 'async'\n\t\t\t\t}))\n\t\t\t}\n\n\t\tconst app = new Elysia().use(a()).get('/', ({ derived }) => derived)\n\n\t\tawait app.modules\n\n\t\tconst resRoot = await app.handle(req('/')).then((r) => r.text())\n\t\texpect(resRoot).toBe('async')\n\t})\n\n\tit('do not duplicate functional async plugin lifecycle', async () => {\n\t\tconst plugin = async (app: Elysia) => app.get('/', () => 'yay')\n\n\t\tlet fired = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.onRequest(() => {\n\t\t\t\tfired++\n\t\t\t})\n\t\t\t.compile()\n\n\t\tawait app.modules\n\t\tawait app.handle(req('/'))\n\n\t\texpect(fired).toBe(1)\n\t})\n\n\tit('do not duplicate instance async plugin lifecycle', async () => {\n\t\tconst plugin = async () => new Elysia().get('/', () => 'yay')\n\n\t\tlet fired = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin())\n\t\t\t.onRequest(() => {\n\t\t\t\tfired++\n\t\t\t})\n\t\t\t.compile()\n\n\t\tawait app.modules\n\t\tawait app.handle(req('/'))\n\n\t\texpect(fired).toBe(1)\n\t})\n\n\tit('handle nested async plugin', async () => {\n\t\tconst yay = async () => {\n\t\t\tawait Bun.sleep(2)\n\n\t\t\treturn new Elysia({ name: 'yay' }).get('/yay', 'yay')\n\t\t}\n\n\t\tconst wrapper = new Elysia({ name: 'wrapper' }).use(yay())\n\n\t\tconst app = new Elysia().use(wrapper)\n\n\t\tawait app.modules\n\n\t\tconst response = await app.handle(req('/yay'))\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('handle recursive nested async plugins', async () => {\n\t\tconst delay = <T extends (...args: any) => any>(\n\t\t\tcallback: T,\n\t\t\tms = 617\n\t\t): Promise<ReturnType<T>> => Bun.sleep(ms).then(() => callback())\n\n\t\tconst yay = () => delay(() => new Elysia().get('/nested', 'hi!'), 1)\n\t\tconst yay2 = () => delay(() => new Elysia().use(yay), 5)\n\t\tconst yay3 = () => delay(() => new Elysia().use(yay2), 10)\n\t\tconst wrapper = new Elysia().use(async () => delay(() => yay3(), 6.17))\n\n\t\tconst app = new Elysia().use(wrapper)\n\n\t\tawait app.modules\n\n\t\tconst response = await app.handle(req('/nested'))\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('recompile nested async plugin once registered', async () => {\n\t\tconst asyncPlugin = Promise.resolve(new Elysia({ name: 'AsyncPlugin' }))\n\n\t\tconst plugin = new Elysia({ name: 'Plugin' })\n\t\t\t.use(asyncPlugin)\n\t\t\t.get('/plugin', () => 'GET /plugin')\n\n\t\tconst app = new Elysia({ name: 'App' })\n\t\t\t.use(plugin)\n\t\t\t.get('/foo', () => 'GET /foo')\n\n\t\tconst response = await app\n\t\t\t.handle(new Request('http://localhost/plugin'))\n\t\t\t.then((x) => x.text())\n\n\t\t// https://github.com/elysiajs/elysia/issues/1067\n\t\t// If the plugin doesn't recompile, route index\n\t\t// would be pointed to /foo instead of /plugin\n\t\texpect(response).toEqual('GET /plugin')\n\t})\n\n\tit('recompile not nested async plugin once registered', async () => {\n\t\tconst asyncPlugin = Promise.resolve(new Elysia({ name: 'AsyncPlugin' }))\n\n\t\tconst plugin = new Elysia({ name: 'Plugin' })\n\t\t\t.use(asyncPlugin)\n\t\t\t.get('/plugin', () => 'GET /plugin')\n\n\t\tconst app = new Elysia({ name: 'App' })\n\t\t\t.use(plugin)\n\t\t\t.get('/foo', () => 'GET /foo')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/plugin')\n\t\t)\n\n\t\tconst text = await response.text()\n\t\texpect(text).toEqual('GET /plugin')\n\t})\n\n\tit('register dynamic import routes inside guard', async () => {\n\t\tconst app = new Elysia().guard(\n\t\t\t{},\n\t\t\t(app) => app.use(import('../modules').then((m) => m.lazyInstance))\n\t\t)\n\n\t\tawait app.modules\n\n\t\tconst res = await app.handle(req('/lazy-instance'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('lazy-instance')\n\t})\n\n\tit('register multiple dynamic import routes inside guard', async () => {\n\t\tconst lazyA = Promise.resolve(new Elysia().get('/a', () => 'a'))\n\t\tconst lazyB = Promise.resolve(new Elysia().get('/b', () => 'b'))\n\n\t\tlet hookCalls = 0\n\n\t\tconst app = new Elysia().guard(\n\t\t\t{ beforeHandle: () => { hookCalls++ } },\n\t\t\t(app) => app.use(lazyA).use(lazyB)\n\t\t)\n\n\t\tawait app.modules\n\n\t\texpect((await app.handle(req('/a'))).status).toBe(200)\n\t\texpect((await app.handle(req('/b'))).status).toBe(200)\n\t\texpect(hookCalls).toBe(2)\n\t})\n\n\tit('register dynamic import routes inside guard with hook', async () => {\n\t\tlet called = false\n\n\t\tconst app = new Elysia().guard(\n\t\t\t{\n\t\t\t\tbeforeHandle: () => {\n\t\t\t\t\tcalled = true\n\t\t\t\t}\n\t\t\t},\n\t\t\t(app) => app.use(import('../modules').then((m) => m.lazyInstance))\n\t\t)\n\n\t\tawait app.modules\n\n\t\tawait app.handle(req('/lazy-instance'))\n\n\t\texpect(called).toBe(true)\n\t})\n})\n"
  },
  {
    "path": "test/core/mount.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\n\nimport { Elysia } from '../../src'\n\ndescribe('Mount', () => {\n\tit('preserve request URL', async () => {\n\t\tconst plugin = new Elysia().get('/', ({ request }) => request.url)\n\n\t\tconst app = new Elysia().mount('/mount', plugin.handle)\n\n\t\texpect(\n\t\t\tawait app\n\t\t\t\t.handle(new Request('http://elysiajs.com/mount/'))\n\t\t\t\t.then((x) => x.text())\n\t\t).toBe('http://elysiajs.com/')\n\t})\n\n\tit('preserve request URL with query', async () => {\n\t\tconst plugin = new Elysia().get('/', ({ request }) => request.url)\n\n\t\tconst app = new Elysia().mount('/mount', plugin.handle)\n\n\t\texpect(\n\t\t\tawait app\n\t\t\t\t.handle(new Request('http://elysiajs.com/mount/?a=1'))\n\t\t\t\t.then((x) => x.text())\n\t\t).toBe('http://elysiajs.com/?a=1')\n\t})\n\n\tit('preserve body', async () => {\n\t\tconst handler = async (req: Request) => {\n\t\t\treturn new Response(await req.text())\n\t\t}\n\n\t\tconst app = new Elysia()\n\t\t\t.mount('/mount', (req) => handler(req))\n\t\t\t.post('/not-mount', ({ body }) => body)\n\n\t\tconst options = {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'content-type': 'text/plain'\n\t\t\t},\n\t\t\tbody: 'sucrose'\n\t\t}\n\n\t\tconst res = await Promise.all([\n\t\t\tapp\n\t\t\t\t.handle(new Request('http://elysiajs.com/mount', options))\n\t\t\t\t.then((x) => x.text()),\n\t\t\tapp\n\t\t\t\t.handle(new Request('http://elysiajs.com/not-mount', options))\n\t\t\t\t.then((x) => x.text())\n\t\t])\n\n\t\texpect(res).toEqual(['sucrose', 'sucrose'])\n\t})\n\n\tit('remove wildcard path', async () => {\n\t\tconst app = new Elysia().mount('/v1/*', (request) => {\n\t\t\treturn Response.json({\n\t\t\t\tpath: request.url\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(new Request('http://localhost/v1/hello'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tpath: 'http://localhost/hello'\n\t\t})\n\t})\n\n\tit('preserve method', async () => {\n\t\tconst app = new Elysia().mount((request) => {\n\t\t\treturn Response.json({\n\t\t\t\tmethod: request.method,\n\t\t\t\tpath: request.url\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/v1/hello', {\n\t\t\t\t\tmethod: 'PUT'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tmethod: 'PUT',\n\t\t\tpath: 'http://localhost/v1/hello'\n\t\t})\n\t})\n\n\t// https://github.com/elysiajs/elysia/issues/1070\n\tit('preserve method with prefix', async () => {\n\t\tconst app = new Elysia().mount('/v1/*', (request) => {\n\t\t\treturn Response.json({\n\t\t\t\tmethod: request.method,\n\t\t\t\tpath: request.url\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/v1/hello', {\n\t\t\t\t\tmethod: 'PUT'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tmethod: 'PUT',\n\t\t\tpath: 'http://localhost/hello'\n\t\t})\n\t})\n\n\tit('preserve headers', async () => {\n\t\tconst app = new Elysia().mount((request) => {\n\t\t\treturn Response.json(request.headers.toJSON())\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/v1/hello', {\n\t\t\t\t\tmethod: 'PUT',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'x-test': 'test'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\t'x-test': 'test'\n\t\t})\n\t})\n\n\tit('without prefix - strips mount path', async () => {\n\t\tconst app = new Elysia().mount('/sdk/problems-domain', (request) => {\n\t\t\treturn Response.json({ path: new URL(request.url).pathname })\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/sdk/problems-domain/problems')\n\t\t\t)\n\t\t\t.then((x) => x.json() as Promise<{ path: string }>)\n\n\t\texpect(response.path).toBe('/problems')\n\t})\n\n\tit('with prefix - should strip both prefix and mount path', async () => {\n\t\tconst sdkApp = new Elysia({ prefix: '/sdk' }).mount(\n\t\t\t'/problems-domain',\n\t\t\t(request) => {\n\t\t\t\treturn Response.json({ path: new URL(request.url).pathname })\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia().use(sdkApp)\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/sdk/problems-domain/problems')\n\t\t\t)\n\t\t\t.then((x) => x.json() as Promise<{ path: string }>)\n\n\t\texpect(response.path).toBe('/problems')\n\t})\n\n\tit('handle body in aot: false', async () => {\n\t\tconst app = new Elysia({ aot: false }).mount('/api', async (request) =>\n\t\t\tResponse.json(await request.json())\n\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/api', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({ message: 'hello world' })\n\t\t\t\t})\n\t\t\t)\n\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tmessage: 'hello world'\n\t\t})\n\t})\n\n\tit('preserve set-cookie headers from Response with CORS', async () => {\n\t\tconst handler = async () => {\n\t\t\tconst headers = new Headers()\n\t\t\theaders.set('location', '/redirect')\n\t\t\theaders.append('set-cookie', 'session=abc123; Path=/; HttpOnly')\n\t\t\theaders.append('set-cookie', 'token=xyz789; Path=/; Secure')\n\n\t\t\treturn new Response('OK', {\n\t\t\t\tstatus: 302,\n\t\t\t\theaders\n\t\t\t})\n\t\t}\n\n\t\tconst app = new Elysia()\n\t\t\t.use((app) =>\n\t\t\t\tapp.onBeforeHandle(({ set }) => {\n\t\t\t\t\tset.headers['access-control-allow-origin'] = '*'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.mount('/auth', handler)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/auth/login', {\n\t\t\t\tmethod: 'POST'\n\t\t\t})\n\t\t)\n\n\t\tconst cookies = response.headers.getSetCookie()\n\t\texpect(cookies).toHaveLength(2)\n\t\texpect(cookies).toContain('session=abc123; Path=/; HttpOnly')\n\t\texpect(cookies).toContain('token=xyz789; Path=/; Secure')\n\t\texpect(response.status).toBe(302)\n\t\texpect(response.headers.get('location')).toBe('/redirect')\n\t})\n})\n"
  },
  {
    "path": "test/core/native-static.test.ts",
    "content": "// @ts-nocheck\nimport { Elysia } from '../../src'\nimport { describe, expect, it } from 'bun:test'\n\ndescribe('Native Static Response', () => {\n\tit('work', async () => {\n\t\tconst app = new Elysia().get('/', 'Static Content')\n\n\t\texpect(app.router.response['/'].GET).toBeInstanceOf(Response)\n\t\texpect(await app.router.response['/'].GET.text()).toEqual('Static Content')\n\t})\n\n\tit('handle plugin', async () => {\n\t\tconst plugin = new Elysia().get('/plugin', 'Plugin')\n\n\t\tconst app = new Elysia().use(plugin).get('/', 'Static Content')\n\n\t\texpect(app.router.response['/'].GET).toBeInstanceOf(Response)\n\t\texpect(await app.router.response['/'].GET.text()).toEqual('Static Content')\n\n\t\texpect(app.router.response['/plugin'].GET).toBeInstanceOf(Response)\n\t\texpect(await app.router.response['/plugin'].GET.text()).toEqual('Plugin')\n\t})\n\n\tit('handle default header', async () => {\n\t\tconst plugin = new Elysia().get('/plugin', 'Plugin')\n\n\t\tconst app = new Elysia()\n\t\t\t.headers({ server: 'Elysia' })\n\t\t\t.use(plugin)\n\t\t\t.get('/', 'Static Content')\n\n\t\texpect(app.router.response['/'].GET).toBeInstanceOf(Response)\n\t\texpect(app.router.response['/'].GET.headers.get('server')).toBe('Elysia')\n\t\texpect(await app.router.response['/'].GET.text()).toEqual('Static Content')\n\n\t\texpect(app.router.response['/plugin'].GET).toBeInstanceOf(Response)\n\t\texpect(app.router.response['/plugin'].GET.headers.get('server')).toBe('Elysia')\n\t\texpect(await app.router.response['/plugin'].GET.text()).toEqual('Plugin')\n\t})\n\n\tit('turn off by config', async () => {\n\t\tconst app = new Elysia({ nativeStaticResponse: false }).get(\n\t\t\t'/',\n\t\t\t'Static Content'\n\t\t)\n\n\t\texpect(app.router.response).not.toHaveProperty('/')\n\t})\n\n\tit('handle loose path', async () => {\n\t\tconst plugin = new Elysia().get('/plugin', 'Plugin')\n\n\t\tconst app = new Elysia().use(plugin).get('/', 'Static Content')\n\n\t\texpect(app.router.response['/'].GET).toBeInstanceOf(Response)\n\t\texpect(await app.router.response['/'].GET.text()).toEqual('Static Content')\n\n\t\texpect(app.router.response[''].GET).toBeInstanceOf(Response)\n\t\texpect(await app.router.response[''].GET.text()).toEqual('Static Content')\n\n\t\texpect(app.router.response['/plugin'].GET).toBeInstanceOf(Response)\n\t\texpect(await app.router.response['/plugin'].GET.text()).toEqual('Plugin')\n\n\t\texpect(app.router.response['/plugin/'].GET).toBeInstanceOf(Response)\n\t\texpect(await app.router.response['/plugin/'].GET.text()).toEqual('Plugin')\n\n\t\tconst strict = new Elysia({ strictPath: true })\n\t\t\t.use(plugin)\n\t\t\t.get('/', 'Static Content')\n\n\t\texpect(strict.router.response['/'].GET).toBeInstanceOf(Response)\n\t\texpect(await strict.router.response['/'].GET.text()).toEqual(\n\t\t\t'Static Content'\n\t\t)\n\t\texpect(strict.router.response).not.toHaveProperty('')\n\n\t\texpect(strict.router.response['/plugin'].GET).toBeInstanceOf(Response)\n\t\texpect(await strict.router.response['/plugin'].GET.text()).toEqual('Plugin')\n\t\texpect(strict.router.response).not.toHaveProperty('/plugin/')\n\t})\n})\n"
  },
  {
    "path": "test/core/normalize.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { Elysia, t } from '../../src'\nimport { post, req } from '../utils'\n\ndescribe('Normalize', () => {\n\tit('normalize response', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => {\n\t\t\t\treturn {\n\t\t\t\t\thello: 'world',\n\t\t\t\t\ta: 'b'\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\thello: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\thello: 'world'\n\t\t})\n\t})\n\n\tit('normalize optional response', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => {\n\t\t\t\treturn {\n\t\t\t\t\thello: 'world',\n\t\t\t\t\ta: 'b'\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: t.Optional(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\thello: t.String()\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\thello: 'world'\n\t\t})\n\t})\n\n\tit('strictly validate response if not normalize', async () => {\n\t\tconst app = new Elysia({ normalize: false }).get(\n\t\t\t'/',\n\t\t\t() => {\n\t\t\t\treturn {\n\t\t\t\t\thello: 'world',\n\t\t\t\t\ta: 'b'\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\thello: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toEqual(422)\n\t})\n\n\tit('normalize multiple response', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t// @ts-ignore\n\t\t\t({ status }) => status(418, { name: 'Nagisa', hifumi: 'daisuki' }),\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.Object({\n\t\t\t\t\t\thello: t.String()\n\t\t\t\t\t}),\n\t\t\t\t\t418: t.Object({\n\t\t\t\t\t\tname: t.Literal('Nagisa')\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tname: 'Nagisa'\n\t\t})\n\t})\n\n\tit('strictly validate multiple response', async () => {\n\t\tconst app = new Elysia({\n\t\t\tnormalize: false\n\t\t}).get(\n\t\t\t'/',\n\t\t\t// @ts-ignore\n\t\t\t({ status }) => status(418, { name: 'Nagisa', hifumi: 'daisuki' }),\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.Object({\n\t\t\t\t\t\thello: t.String()\n\t\t\t\t\t}),\n\t\t\t\t\t418: t.Object({\n\t\t\t\t\t\tname: t.Literal('Nagisa')\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toEqual(422)\n\t})\n\n\tit('normalize multiple response using 200', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => {\n\t\t\t\treturn {\n\t\t\t\t\thello: 'Nagisa',\n\t\t\t\t\thifumi: 'daisuki'\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.Object({\n\t\t\t\t\t\thello: t.String()\n\t\t\t\t\t}),\n\t\t\t\t\t418: t.Object({\n\t\t\t\t\t\tname: t.Literal('Nagisa')\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\thello: 'Nagisa'\n\t\t})\n\t})\n\n\tit('strictly validate multiple response using 200 if not normalize', async () => {\n\t\tconst app = new Elysia({ normalize: false }).get(\n\t\t\t'/',\n\t\t\t() => {\n\t\t\t\treturn {\n\t\t\t\t\thello: 'Nagisa',\n\t\t\t\t\thifumi: 'daisuki'\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.Object({\n\t\t\t\t\t\thello: t.String()\n\t\t\t\t\t}),\n\t\t\t\t\t418: t.Object({\n\t\t\t\t\t\tname: t.Literal('Nagisa')\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toEqual(422)\n\t})\n\n\tit('do not normalize response when allowing additional properties', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => {\n\t\t\t\treturn {\n\t\t\t\t\thello: 'world',\n\t\t\t\t\ta: 'b'\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: t.Object(\n\t\t\t\t\t{\n\t\t\t\t\t\thello: t.String()\n\t\t\t\t\t},\n\t\t\t\t\t{ additionalProperties: true }\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\thello: 'world',\n\t\t\ta: 'b'\n\t\t})\n\t})\n\n\tit('normalize body', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tpost('/', {\n\t\t\t\t\tname: 'nagisa',\n\t\t\t\t\thifumi: 'daisuki'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tname: 'nagisa'\n\t\t})\n\t})\n\n\tit('normalize optional body', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Optional(\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tpost('/', {\n\t\t\t\t\tname: 'nagisa',\n\t\t\t\t\thifumi: 'daisuki'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tname: 'nagisa'\n\t\t})\n\t})\n\n\tit('strictly validate body if not normalize', async () => {\n\t\tconst app = new Elysia({ normalize: false }).post(\n\t\t\t'/',\n\t\t\t({ body }) => body,\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'nagisa',\n\t\t\t\thifumi: 'daisuki'\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\t})\n\n\tit('loosely validate body if not normalize and has additionalProperties', async () => {\n\t\tconst app = new Elysia({ normalize: false }).post(\n\t\t\t'/',\n\t\t\t({ body }) => body,\n\t\t\t{\n\t\t\t\tbody: t.Object(\n\t\t\t\t\t{\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tadditionalProperties: true\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'nagisa',\n\t\t\t\thifumi: 'daisuki'\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.json()).toEqual({\n\t\t\tname: 'nagisa',\n\t\t\thifumi: 'daisuki'\n\t\t})\n\t})\n\n\tit('normalize query', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(req('/?name=nagisa&hifumi=daisuki'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tname: 'nagisa'\n\t\t})\n\t})\n\n\tit(\"don't normalize query on additionalProperties\", async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String()\n\t\t\t\t},\n\t\t\t\t{ additionalProperties: true }\n\t\t\t)\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(req('/?name=nagisa&hifumi=daisuki'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tname: 'nagisa',\n\t\t\thifumi: 'daisuki'\n\t\t})\n\t})\n\n\tit('normalize based on property when normalized is disabled', async () => {\n\t\tconst app = new Elysia({ normalize: false }).get(\n\t\t\t'/',\n\t\t\t({ query }) => query,\n\t\t\t{\n\t\t\t\tquery: t.Object(\n\t\t\t\t\t{\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tadditionalProperties: true\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(req('/?name=nagisa&hifumi=daisuki'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tname: 'nagisa',\n\t\t\thifumi: 'daisuki'\n\t\t})\n\t})\n\n\tit('normalize headers', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tname: 'nagisa',\n\t\t\t\t\t\thifumi: 'daisuki'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tname: 'nagisa'\n\t\t})\n\t})\n\n\tit('loosely validate headers by default if not normalized', async () => {\n\t\tconst app = new Elysia({ normalize: false }).get(\n\t\t\t'/',\n\t\t\t({ headers }) => headers,\n\t\t\t{\n\t\t\t\theaders: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst headers = {\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist'\n\t\t}\n\t\tconst res = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual(headers)\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('strictly validate headers if not normalized and additionalProperties is false', async () => {\n\t\tconst app = new Elysia({ normalize: false }).get(\n\t\t\t'/',\n\t\t\t({ headers }) => headers,\n\t\t\t{\n\t\t\t\theaders: t.Object(\n\t\t\t\t\t{\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tadditionalProperties: false\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tname: 'nagisa',\n\t\t\t\t\thifumi: 'daisuki'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\t})\n\n\tit('response normalization does not mutate', async () => {\n\t\t// Long-lived object has a `token` property\n\t\tconst service = {\n\t\t\tname: 'nagisa',\n\t\t\tstatus: 'online',\n\t\t\ttoken: 'secret'\n\t\t}\n\n\t\t// ...but this property is hidden by the response schema\n\t\tconst responseSchema = t.Object({\n\t\t\tname: t.String(),\n\t\t\tstatus: t.String()\n\t\t})\n\n\t\tconst app = new Elysia({\n\t\t\tnormalize: true\n\t\t}).get('/test', () => service, {\n\t\t\tresponse: responseSchema\n\t\t})\n\n\t\texpect(service).toHaveProperty('token')\n\t\tconst origService = structuredClone(service)\n\n\t\tconst response = await app.handle(new Request('http://localhost/test'))\n\t\texpect(response.body).not.toHaveProperty('token')\n\n\t\t// Expect the `token` property to remain present after `service` object was used in a response\n\t\texpect(service).toHaveProperty('token')\n\n\t\t// In fact, expect the `service` to not be mutated at all\n\t\texpect(service).toEqual(origService)\n\t})\n\n\tit('normalize nested schema', async () => {\n\t\tconst type = t.Array(\n\t\t\tt.Object({\n\t\t\t\tid: t.String(),\n\t\t\t\tdate: t.Date(),\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t)\n\t\tconst date = new Date('2025-07-11T00:00:00.000Z')\n\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => {\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: 'testId',\n\t\t\t\t\t\tdate,\n\t\t\t\t\t\tname: 'testName',\n\t\t\t\t\t\tneedNormalize: 'yes'\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t200: type\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst response = (await app\n\t\t\t.handle(new Request('http://localhost:3000/'))\n\t\t\t.then((x) => x.json())) as typeof type.static\n\n\t\texpect(response).toEqual([\n\t\t\t{\n\t\t\t\tid: 'testId',\n\t\t\t\t// @ts-ignore date is normalized to ISO string by default\n\t\t\t\tdate: date.toISOString(),\n\t\t\t\tname: 'testName'\n\t\t\t}\n\t\t])\n\t})\n\n\tit('normalize encodeSchema with Transform', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => ({\n\t\t\t\thasMore: true,\n\t\t\t\ttotal: 1,\n\t\t\t\toffset: 0,\n\t\t\t\ttotalPages: 1,\n\t\t\t\tcurrentPage: 1,\n\t\t\t\titems: [{ username: 'Bob', secret: 'shhh' }]\n\t\t\t}),\n\t\t\t{\n\t\t\t\t// I don't know why but it must be this exact shape\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\thasMore: t.Boolean(),\n\t\t\t\t\titems: t.Array(\n\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\tusername: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t),\n\t\t\t\t\ttotal: t\n\t\t\t\t\t\t.Transform(t.Number())\n\t\t\t\t\t\t.Decode((x) => x)\n\t\t\t\t\t\t.Encode((x) => x),\n\t\t\t\t\toffset: t.Number({ minimum: 0 }),\n\t\t\t\t\ttotalPages: t.Number(),\n\t\t\t\t\tcurrentPage: t.Number({ minimum: 1 })\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst data = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(data).toEqual({\n\t\t\thasMore: true,\n\t\t\titems: [\n\t\t\t\t{\n\t\t\t\t\tusername: 'Bob'\n\t\t\t\t}\n\t\t\t],\n\t\t\ttotal: 1,\n\t\t\toffset: 0,\n\t\t\ttotalPages: 1,\n\t\t\tcurrentPage: 1\n\t\t})\n\t})\n\n\t// it('normalize response with getter fields on class', async () => {\n\t// \tconst app = new Elysia({\n\t// \t\tnormalize: true\n\t// \t}).get(\n\t// \t\t'/',\n\t// \t\t() => {\n\t// \t\t\tclass MyTest {\n\t// \t\t\t\tconstructor(hello: string) {\n\t// \t\t\t\t\tthis.one = hello\n\t// \t\t\t\t\tthis.two = hello\n\t// \t\t\t\t}\n\t// \t\t\t\tpublic one: string\n\t// \t\t\t\tpublic two: string\n\n\t// \t\t\t\tget oneGet() {\n\t// \t\t\t\t\treturn this.one\n\t// \t\t\t\t}\n\n\t// \t\t\t\tget twoGet() {\n\t// \t\t\t\t\treturn this.two\n\t// \t\t\t\t}\n\t// \t\t\t}\n\n\t// \t\t\tconst res = new MyTest('world')\n\t// \t\t\treturn res\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tresponse: t.Object(\n\t// \t\t\t\t{\n\t// \t\t\t\t\tone: t.String(),\n\t// \t\t\t\t\toneGet: t.String()\n\t// \t\t\t\t},\n\t// \t\t\t\t{ additionalProperties: false }\n\t// \t\t\t)\n\t// \t\t}\n\t// \t)\n\n\t// \tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t// \texpect(response).toEqual({\n\t// \t\tone: 'world',\n\t// \t\toneGet: 'world'\n\t// \t})\n\t// })\n\n\t// it('normalize response with getter fields on simple object', async () => {\n\t// \tconst app = new Elysia({\n\t// \t\tnormalize: true\n\t// \t}).get(\n\t// \t\t'/',\n\t// \t\t() => {\n\t// \t\t\treturn {\n\t// \t\t\t\tone: 'world',\n\t// \t\t\t\tget oneGet() {\n\t// \t\t\t\t\treturn 'world'\n\t// \t\t\t\t},\n\t// \t\t\t\ttwo: 'world',\n\t// \t\t\t\tget twoGet() {\n\t// \t\t\t\t\treturn 'world'\n\t// \t\t\t\t}\n\t// \t\t\t}\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tresponse: t.Object(\n\t// \t\t\t\t{\n\t// \t\t\t\t\tone: t.String(),\n\t// \t\t\t\t\toneGet: t.String()\n\t// \t\t\t\t},\n\t// \t\t\t\t{ additionalProperties: false }\n\t// \t\t\t)\n\t// \t\t}\n\t// \t)\n\n\t// \tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t// \texpect(response).toEqual({\n\t// \t\tone: 'world',\n\t// \t\toneGet: 'world'\n\t// \t})\n\t// })\n\n\t// it('normalize response with getter fields on class array', async () => {\n\t// \tconst app = new Elysia({\n\t// \t\tnormalize: true\n\t// \t}).get(\n\t// \t\t'/',\n\t// \t\t() => {\n\t// \t\t\tclass MyTest {\n\t// \t\t\t\tconstructor(hello: string) {\n\t// \t\t\t\t\tthis.one = hello\n\t// \t\t\t\t\tthis.two = hello\n\t// \t\t\t\t}\n\t// \t\t\t\tpublic one: string\n\t// \t\t\t\tpublic two: string\n\n\t// \t\t\t\tget oneGet() {\n\t// \t\t\t\t\treturn this.one\n\t// \t\t\t\t}\n\n\t// \t\t\t\tget twoGet() {\n\t// \t\t\t\t\treturn this.two\n\t// \t\t\t\t}\n\t// \t\t\t}\n\n\t// \t\t\tconst res = new MyTest('world')\n\t// \t\t\treturn [res]\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tresponse: t.Array(\n\t// \t\t\t\tt.Object(\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\tone: t.String(),\n\t// \t\t\t\t\t\toneGet: t.String()\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\t{ additionalProperties: false }\n\t// \t\t\t\t)\n\t// \t\t\t)\n\t// \t\t}\n\t// \t)\n\n\t// \tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t// \texpect(response).toEqual([\n\t// \t\t{\n\t// \t\t\tone: 'world',\n\t// \t\t\toneGet: 'world'\n\t// \t\t}\n\t// \t])\n\t// })\n\n\t// it('normalize response with getter fields on simple object array', async () => {\n\t// \tconst app = new Elysia({\n\t// \t\tnormalize: true\n\t// \t}).get(\n\t// \t\t'/',\n\t// \t\t() => {\n\t// \t\t\treturn [\n\t// \t\t\t\t{\n\t// \t\t\t\t\tone: 'world',\n\t// \t\t\t\t\tget oneGet() {\n\t// \t\t\t\t\t\treturn 'world'\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\ttwo: 'world',\n\t// \t\t\t\t\tget twoGet() {\n\t// \t\t\t\t\t\treturn 'world'\n\t// \t\t\t\t\t}\n\t// \t\t\t\t}\n\t// \t\t\t]\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tresponse: t.Array(\n\t// \t\t\t\tt.Object(\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\tone: t.String(),\n\t// \t\t\t\t\t\toneGet: t.String()\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\t{ additionalProperties: false }\n\t// \t\t\t\t)\n\t// \t\t\t)\n\t// \t\t}\n\t// \t)\n\n\t// \tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t// \texpect(response).toEqual([\n\t// \t\t{\n\t// \t\t\tone: 'world',\n\t// \t\t\toneGet: 'world'\n\t// \t\t}\n\t// \t])\n\t// })\n\n\t// it('normalize response with getter fields on class array with nested arrays', async () => {\n\t// \tconst app = new Elysia({\n\t// \t\tnormalize: true\n\t// \t}).get(\n\t// \t\t'/',\n\t// \t\t() => {\n\t// \t\t\tclass MyTest {\n\t// \t\t\t\tconstructor(hello: string) {\n\t// \t\t\t\t\tthis.one = hello\n\t// \t\t\t\t\tthis.two = hello\n\t// \t\t\t\t}\n\t// \t\t\t\tpublic one: string\n\t// \t\t\t\tpublic two: string\n\n\t// \t\t\t\tget oneGet() {\n\t// \t\t\t\t\treturn this.one\n\t// \t\t\t\t}\n\n\t// \t\t\t\tget twoGet() {\n\t// \t\t\t\t\treturn this.two\n\t// \t\t\t\t}\n\t// \t\t\t}\n\n\t// \t\t\tclass MyTest2 {\n\t// \t\t\t\tconstructor(hello: string) {\n\t// \t\t\t\t\tthis.one = hello\n\t// \t\t\t\t\tthis.two = hello\n\t// \t\t\t\t\tthis.three = [new MyTest(hello)]\n\t// \t\t\t\t\tthis.four = [new MyTest(hello)]\n\t// \t\t\t\t}\n\n\t// \t\t\t\tpublic one: string\n\t// \t\t\t\tpublic two: string\n\t// \t\t\t\tpublic three: MyTest[]\n\t// \t\t\t\tpublic four: MyTest[]\n\n\t// \t\t\t\tget oneGet() {\n\t// \t\t\t\t\treturn this.one\n\t// \t\t\t\t}\n\n\t// \t\t\t\tget twoGet() {\n\t// \t\t\t\t\treturn this.two\n\t// \t\t\t\t}\n\n\t// \t\t\t\tget threeGet() {\n\t// \t\t\t\t\treturn this.three\n\t// \t\t\t\t}\n\n\t// \t\t\t\tget fourGet() {\n\t// \t\t\t\t\treturn this.four\n\t// \t\t\t\t}\n\t// \t\t\t}\n\n\t// \t\t\tconst res = new MyTest2('world')\n\n\t// \t\t\treturn [res]\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tresponse: t.Array(\n\t// \t\t\t\tt.Object(\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\tone: t.String(),\n\t// \t\t\t\t\t\toneGet: t.String(),\n\t// \t\t\t\t\t\tthree: t.Array(\n\t// \t\t\t\t\t\t\tt.Object(\n\t// \t\t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\t\tone: t.String(),\n\t// \t\t\t\t\t\t\t\t\toneGet: t.String()\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t{ additionalProperties: false }\n\t// \t\t\t\t\t\t\t)\n\t// \t\t\t\t\t\t),\n\t// \t\t\t\t\t\tthreeGet: t.Array(\n\t// \t\t\t\t\t\t\tt.Object(\n\t// \t\t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\t\tone: t.String(),\n\t// \t\t\t\t\t\t\t\t\toneGet: t.String()\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t{ additionalProperties: false }\n\t// \t\t\t\t\t\t\t)\n\t// \t\t\t\t\t\t)\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\t{ additionalProperties: false }\n\t// \t\t\t\t)\n\t// \t\t\t)\n\t// \t\t}\n\t// \t)\n\n\t// \tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t// \texpect(response).toEqual([\n\t// \t\t{\n\t// \t\t\tone: 'world',\n\t// \t\t\toneGet: 'world',\n\t// \t\t\tthree: [\n\t// \t\t\t\t{\n\t// \t\t\t\t\tone: 'world',\n\t// \t\t\t\t\toneGet: 'world'\n\t// \t\t\t\t}\n\t// \t\t\t],\n\t// \t\t\tthreeGet: [\n\t// \t\t\t\t{\n\t// \t\t\t\t\tone: 'world',\n\t// \t\t\t\t\toneGet: 'world'\n\t// \t\t\t\t}\n\t// \t\t\t]\n\t// \t\t}\n\t// \t])\n\t// })\n\n\t// it('normalize response with getter fields on simple object array with nested arrays', async () => {\n\t// \tconst app = new Elysia({\n\t// \t\tnormalize: true\n\t// \t}).get(\n\t// \t\t'/',\n\t// \t\t() => {\n\t// \t\t\tconst o = [\n\t// \t\t\t\t{\n\t// \t\t\t\t\tone: 'world',\n\t// \t\t\t\t\tget oneGet() {\n\t// \t\t\t\t\t\treturn 'world'\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\ttwo: 'world',\n\t// \t\t\t\t\tget twoGet() {\n\t// \t\t\t\t\t\treturn 'world'\n\t// \t\t\t\t\t}\n\t// \t\t\t\t}\n\t// \t\t\t]\n\t// \t\t\treturn [\n\t// \t\t\t\t{\n\t// \t\t\t\t\tone: 'world',\n\t// \t\t\t\t\tget oneGet() {\n\t// \t\t\t\t\t\treturn 'world'\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\ttwo: 'world',\n\t// \t\t\t\t\tget twoGet() {\n\t// \t\t\t\t\t\treturn 'world'\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tthree: o,\n\t// \t\t\t\t\tget threeGet() {\n\t// \t\t\t\t\t\treturn o\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tfour: o,\n\t// \t\t\t\t\tget fourGet() {\n\t// \t\t\t\t\t\treturn o\n\t// \t\t\t\t\t}\n\t// \t\t\t\t}\n\t// \t\t\t]\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tresponse: t.Array(\n\t// \t\t\t\tt.Object(\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\tone: t.String(),\n\t// \t\t\t\t\t\toneGet: t.String(),\n\t// \t\t\t\t\t\tthree: t.Array(\n\t// \t\t\t\t\t\t\tt.Object(\n\t// \t\t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\t\tone: t.String(),\n\t// \t\t\t\t\t\t\t\t\toneGet: t.String()\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t{ additionalProperties: false }\n\t// \t\t\t\t\t\t\t)\n\t// \t\t\t\t\t\t),\n\t// \t\t\t\t\t\tthreeGet: t.Array(\n\t// \t\t\t\t\t\t\tt.Object(\n\t// \t\t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\t\tone: t.String(),\n\t// \t\t\t\t\t\t\t\t\toneGet: t.String()\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t{ additionalProperties: false }\n\t// \t\t\t\t\t\t\t)\n\t// \t\t\t\t\t\t)\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\t{ additionalProperties: false }\n\t// \t\t\t\t)\n\t// \t\t\t)\n\t// \t\t}\n\t// \t)\n\n\t// \tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t// \texpect(response).toEqual([\n\t// \t\t{\n\t// \t\t\tone: 'world',\n\t// \t\t\toneGet: 'world',\n\t// \t\t\tthree: [\n\t// \t\t\t\t{\n\t// \t\t\t\t\tone: 'world',\n\t// \t\t\t\t\toneGet: 'world'\n\t// \t\t\t\t}\n\t// \t\t\t],\n\t// \t\t\tthreeGet: [\n\t// \t\t\t\t{\n\t// \t\t\t\t\tone: 'world',\n\t// \t\t\t\t\toneGet: 'world'\n\t// \t\t\t\t}\n\t// \t\t\t]\n\t// \t\t}\n\t// \t])\n\t// })\n\n\t// it('normalize getter field', async () => {\n\t// \tclass Example {\n\t// \t\tfield1: string\n\t// \t\tfield3?: string\n\n\t// \t\tconstructor(\n\t// \t\t\tprivate field2: string,\n\t// \t\t\tfield1: string,\n\t// \t\t\tfield3?: string\n\t// \t\t) {\n\t// \t\t\tthis.field1 = field1\n\t// \t\t\tthis.field3 = field3\n\t// \t\t}\n\n\t// \t\tget getterField() {\n\t// \t\t\treturn this.field2\n\t// \t\t}\n\t// \t}\n\n\t// \tconst app = new Elysia().get(\n\t// \t\t'/',\n\t// \t\t() => new Example('field2', 'field1'),\n\t// \t\t{\n\t// \t\t\tresponse: t.Object({\n\t// \t\t\t\tfield1: t.String(),\n\t// \t\t\t\tfield3: t.Optional(t.String()),\n\t// \t\t\t\tgetterField: t.String()\n\t// \t\t\t})\n\t// \t\t}\n\t// \t)\n\n\t// \tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t// \texpect(response).toEqual({\n\t// \t\tfield1: 'field1',\n\t// \t\tgetterField: 'field2'\n\t// \t})\n\t// })\n})\n"
  },
  {
    "path": "test/core/path.test.ts",
    "content": "import { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\n\ndescribe('handle path with spaces', () => {\n\tit('AOT on: static path', async () => {\n\t\tconst PATH = '/y a y'\n\n\t\tconst app = new Elysia().get(\n\t\t\tPATH,\n\t\t\t() => 'result from a path wirh spaces'\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request(`http://localhost${PATH}`)\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('AOT off: static path', async () => {\n\t\tconst PATH = '/y a y'\n\n\t\tconst app = new Elysia({ aot: false }).get(\n\t\t\tPATH,\n\t\t\t() => 'result from a path wirh spaces'\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request(`http://localhost${PATH}`)\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('AOT on: dynamic path', async () => {\n\t\tconst app = new Elysia().get('/y a y/:id', ({ params: { id } }) => id)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request(`http://localhost/y a y/1`)\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.text()).toBe('1')\n\t})\n\n\tit('AOT off: dynamic path', async () => {\n\t\tconst app = new Elysia({ aot: false }).get(\n\t\t\t'/y a y/:id',\n\t\t\t({ params: { id } }) => id\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request(`http://localhost/y a y/1`)\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.text()).toBe('1')\n\t})\n\n\tit('AOT on: optional dynamic path', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/y a y/:id?',\n\t\t\t({ params: { id } }) => id ?? 0\n\t\t)\n\n\t\tconst response = await Promise.all(\n\t\t\t[\n\t\t\t\tnew Request(`http://localhost/y a y`),\n\t\t\t\tnew Request(`http://localhost/y a y/1`)\n\t\t\t].map(app.handle)\n\t\t)\n\n\t\texpect(response[0].status).toBe(200)\n\t\texpect(response[1].status).toBe(200)\n\n\t\tconst value = await Promise.all(response.map((x) => x.text()))\n\n\t\texpect(value[0]).toBe('0')\n\t\texpect(value[1]).toBe('1')\n\t})\n\n\tit('AOT off: optional dynamic path', async () => {\n\t\tconst app = new Elysia({ aot: false }).get(\n\t\t\t'/y a y/:id?',\n\t\t\t({ params: { id } }) => id ?? 0\n\t\t)\n\n\t\tconst response = await Promise.all(\n\t\t\t[\n\t\t\t\tnew Request(`http://localhost/y a y`),\n\t\t\t\tnew Request(`http://localhost/y a y/1`)\n\t\t\t].map(app.handle)\n\t\t)\n\n\t\texpect(response[0].status).toBe(200)\n\t\texpect(response[1].status).toBe(200)\n\n\t\tconst value = await Promise.all(response.map((x) => x.text()))\n\n\t\texpect(value[0]).toBe('0')\n\t\texpect(value[1]).toBe('1')\n\t})\n\n\tit('handle optional path parameters after required', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/api/:required/:optional?',\n\t\t\t({ params }) => params.required\n\t\t)\n\n\t\tconst required = await app.handle(\n\t\t\tnew Request('http://localhost/api/yay')\n\t\t)\n\n\t\texpect(required.status).toBe(200)\n\t\texpect(await required.text()).toEqual('yay')\n\n\t\tconst optional = await app.handle(\n\t\t\tnew Request('http://localhost/api/yay/ok')\n\t\t)\n\n\t\texpect(optional.status).toBe(200)\n\t\texpect(await optional.text()).toEqual('yay')\n\t})\n})\n"
  },
  {
    "path": "test/core/redirect.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Elysia } from '../../src'\nimport { req } from '../utils'\n\ndescribe('Redirect', () => {\n\tit('handles redirect without explicit status', async () => {\n\t\tconst app = new Elysia().get('/', ({ set, redirect }) =>\n\t\t\tredirect('/hello')\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\t\texpect(res.status).toBe(302)\n\t\texpect(res.headers.get('location')).toBe('/hello')\n\t})\n\n\tit('handles redirect with explicit status', async () => {\n\t\tconst app = new Elysia().get('/', ({ set, redirect }) =>\n\t\t\tredirect('/hello', 303)\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\t\texpect(res.status).toBe(303)\n\t\texpect(res.headers.get('location')).toBe('/hello')\n\t})\n})\n"
  },
  {
    "path": "test/core/sanitize.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\n\nimport { Elysia, t } from '../../src'\nimport { post } from '../utils'\n\ndescribe('Sanitize', () => {\n\tit('handle single sanitize', async () => {\n\t\tconst app = new Elysia({\n\t\t\tsanitize: (v) => (v === 'a' ? 'ok' : v)\n\t\t}).post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\ta: t.String(),\n\t\t\t\tb: t.String(),\n\t\t\t\tc: t.String()\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tpost('/', {\n\t\t\t\t\ta: 'a',\n\t\t\t\t\tb: 'b',\n\t\t\t\t\tc: 'c'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({ a: 'ok', b: 'b', c: 'c' })\n\t})\n\n\tit('multiple sanitize', async () => {\n\t\tconst app = new Elysia({\n\t\t\tsanitize: [\n\t\t\t\t(v) => (v === 'a' ? 'ok' : v),\n\t\t\t\t(v) => (v === 'b' ? 'ok' : v)\n\t\t\t]\n\t\t}).post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\ta: t.String(),\n\t\t\t\tb: t.String(),\n\t\t\t\tc: t.String()\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tpost('/', {\n\t\t\t\t\ta: 'a',\n\t\t\t\t\tb: 'b',\n\t\t\t\t\tc: 'c'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({ a: 'ok', b: 'ok', c: 'c' })\n\t})\n\n\tit('handle sanitize in plugin from main', async () => {\n\t\tconst plugin = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\ta: t.String(),\n\t\t\t\tb: t.String(),\n\t\t\t\tc: t.String()\n\t\t\t})\n\t\t})\n\n\t\tconst app = new Elysia({\n\t\t\tsanitize: (v) => (v === 'a' ? 'ok' : v)\n\t\t}).use(plugin)\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tpost('/', {\n\t\t\t\t\ta: 'a',\n\t\t\t\t\tb: 'b',\n\t\t\t\t\tc: 'c'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({ a: 'ok', b: 'b', c: 'c' })\n\t})\n\n\tit('handle top-level string', async () => {\n\t\tconst app = new Elysia({\n\t\t\tsanitize: (v) => (v === 'a' ? 'ok' : v)\n\t\t}).post('/', ({ body }) => body, {\n\t\t\tbody: t.String()\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'text/plain'\n\t\t\t\t\t},\n\t\t\t\t\tbody: 'a'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe('ok')\n\t})\n})\n"
  },
  {
    "path": "test/core/status.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\n\nimport Elysia, { t } from '../../src'\nimport { req } from '../utils'\n\ndescribe('Status', () => {\n\tit('work', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(201))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(201)\n\t\texpect(await response.text()).toBe('Created')\n\t})\n\n\t// Bun support 101 or >= 200 status\n\tit('ignore response body of 101', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(101))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(101)\n\t\texpect(await response.text()).toBe('')\n\t})\n\n\tit('ignore explicit response body of 101', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(101, 'Hello'))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(101)\n\t\texpect(await response.text()).toBe('')\n\t})\n\n\tit('ignore response body of 204', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(204))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(204)\n\t\texpect(await response.text()).toBe('')\n\t})\n\n\tit('ignore explicit response body of 204', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(204, 'Hello'))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(204)\n\t\texpect(await response.text()).toBe('')\n\t})\n\n\tit('ignore response body of 205', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(205))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(205)\n\t\texpect(await response.text()).toBe('')\n\t})\n\n\tit('ignore explicit response body of 205', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(205, 'Hello'))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(205)\n\t\texpect(await response.text()).toBe('')\n\t})\n\n\tit('ignore response body of 304', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(304))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(304)\n\t\texpect(await response.text()).toBe('')\n\t})\n\n\tit('ignore explicit response body of 304', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(304, 'Hello'))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(304)\n\t\texpect(await response.text()).toBe('')\n\t})\n\n\tit('ignore response body of 307', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(307))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(307)\n\t\texpect(await response.text()).toBe('')\n\t})\n\n\tit('ignore explicit response body of 307', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(307, 'Hello'))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(307)\n\t\texpect(await response.text()).toBe('')\n\t})\n\n\tit('ignore response body of 308', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(308))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(308)\n\t\texpect(await response.text()).toBe('')\n\t})\n\n\tit('ignore explicit response body of 308', async () => {\n\t\tconst app = new Elysia().get('/', ({ status }) => status(308, 'Hello'))\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(308)\n\t\texpect(await response.text()).toBe('')\n\t})\n})\n"
  },
  {
    "path": "test/core/stop.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\n\nimport { Elysia } from '../../src'\n\ndescribe('Stop', () => {\n\tit('shuts down the server when stop(true) is called', async () => {\n\t\tconst app = new Elysia()\n\t\tapp.get('/health', 'hi')\n\n\t\tconst port = 8080\n\t\tconst server = app.listen(port)\n\n\t\tawait fetch(`http://localhost:${port}/health`)\n\n\t\tawait server.stop(true)\n\n\t\t// Check if the server is still running\n\t\ttry {\n\t\t\tawait fetch(`http://localhost:${port}/health`)\n\t\t\tthrow new Error('Server is still running after teardown')\n\t\t} catch (error) {\n\t\t\texpect((error as Error).message).toContain('Unable to connect')\n\t\t}\n\t})\n\n\tit('does not shut down the server when stop(false) is called', async () => {\n\t\tconst app = new Elysia()\n\t\tapp.get('/health', 'hi')\n\n\t\tconst port = 8081\n\t\tconst server = app.listen(port)\n\n\t\tawait fetch(`http://localhost:${port}/health`)\n\n\t\tawait server.stop(false)\n\n\t\t// Check if the server is still running\n\t\ttry {\n\t\t\tconst response = await fetch(`http://localhost:${port}/health`)\n\t\t\texpect(response.status).toBe(200)\n\t\t\texpect(await response.text()).toBe('hi')\n\t\t} catch (error) {\n\t\t\tthrow new Error('Server unexpectedly shut down')\n\t\t}\n\t})\n})\n"
  },
  {
    "path": "test/extends/decorators.test.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { describe, it, expect } from 'bun:test'\nimport { Elysia } from '../../src'\nimport { req } from '../utils'\n\ndescribe('Decorate', () => {\n\tit('decorate primitive', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate('name', 'Ina')\n\t\t\t.decorate('name', 'Tako')\n\n\t\texpect(app.decorator.name).toBe('Ina')\n\t})\n\n\tit('decorate multiple', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate('name', 'Ina')\n\t\t\t.decorate('job', 'artist')\n\n\t\texpect(app.decorator).toEqual({\n\t\t\tname: 'Ina',\n\t\t\tjob: 'artist'\n\t\t})\n\t})\n\n\tit('decorate object', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate({\n\t\t\t\tname: 'Ina',\n\t\t\t\tjob: 'artist'\n\t\t\t})\n\t\t\t.decorate({ as: 'override' }, {\n\t\t\t\tname: 'Fubuki'\n\t\t\t})\n\n\t\texpect(app.decorator).toEqual({\n\t\t\tname: 'Fubuki',\n\t\t\tjob: 'artist'\n\t\t})\n\t})\n\n\tit('remap object', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate({\n\t\t\t\tname: 'Ina',\n\t\t\t\tjob: 'artist'\n\t\t\t})\n\t\t\t.decorate(({ job, ...rest }) => ({\n\t\t\t\t...rest,\n\t\t\t\tjob: 'streamer'\n\t\t\t}))\n\n\t\texpect(app.decorator).toEqual({\n\t\t\tname: 'Ina',\n\t\t\tjob: 'streamer'\n\t\t})\n\t})\n\n\tit('inherits functional plugin', async () => {\n\t\tconst plugin = () => (app: Elysia) => app.decorate('hi', () => 'hi')\n\n\t\tconst app = new Elysia().use(plugin()).get('/', ({ hi }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('inherits instance plugin', async () => {\n\t\tconst plugin = new Elysia().decorate('hi', () => 'hi')\n\n\t\tconst app = new Elysia().use(plugin).get('/', ({ hi }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('accepts any type', async () => {\n\t\tconst app = new Elysia().decorate('hi', {\n\t\t\tthere: {\n\t\t\t\thello: 'world'\n\t\t\t}\n\t\t})\n\n\t\texpect(app.decorator.hi.there.hello).toBe('world')\n\t})\n\n\tit('remap', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate('job', 'artist')\n\t\t\t.decorate('name', 'Ina')\n\t\t\t.decorate(({ job, ...decorators }) => ({\n\t\t\t\t...decorators,\n\t\t\t\tjob: 'vtuber'\n\t\t\t}))\n\n\t\texpect(app.decorator.job).toBe('vtuber')\n\t})\n\n\tit('handle class deduplication', async () => {\n\t\tlet _i = 0\n\n\t\tclass A {\n\t\t\tpublic i: number\n\n\t\t\tconstructor() {\n\t\t\t\tthis.i = _i++\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().decorate('a', new A()).decorate('a', new A())\n\n\t\texpect(app.decorator.a.i).toBe(0)\n\t})\n\n\tit('handle nested object deduplication', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate('a', {\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Tako'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.decorate('a', {\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Ina',\n\t\t\t\t\tcookie: 'wah!'\n\t\t\t\t}\n\t\t\t})\n\n\t\texpect(app.decorator).toEqual({\n\t\t\ta: {\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Tako',\n\t\t\t\t\tcookie: 'wah!'\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t})\n\n\tit('override primitive', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate('name', 'Ina')\n\t\t\t.decorate({ as: 'override' }, 'name', 'Tako')\n\n\t\texpect(app.decorator.name).toBe('Tako')\n\t})\n\n\tit('override object', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate({\n\t\t\t\tname: 'Ina',\n\t\t\t\tjob: 'artist'\n\t\t\t})\n\t\t\t.decorate(\n\t\t\t\t{ as: 'override' },\n\t\t\t\t{\n\t\t\t\t\tname: 'Fubuki'\n\t\t\t\t}\n\t\t\t)\n\n\t\texpect(app.decorator).toEqual({\n\t\t\tname: 'Fubuki',\n\t\t\tjob: 'artist'\n\t\t})\n\t})\n\n\tit('override handle class', async () => {\n\t\tlet _i = 0\n\n\t\tclass A {\n\t\t\tpublic i: number\n\n\t\t\tconstructor() {\n\t\t\t\tthis.i = _i++\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia()\n\t\t\t.decorate('a', new A())\n\t\t\t.decorate({ as: 'override' }, 'a', new A())\n\n\t\texpect(app.decorator.a.i).toBe(1)\n\t})\n\n\tit('override nested object deduplication using name', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate('a', {\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Tako'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.decorate({ as: 'override' }, 'a', {\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Ina',\n\t\t\t\t\tcookie: 'wah!'\n\t\t\t\t}\n\t\t\t})\n\n\t\texpect(app.decorator.a.hello).toEqual({\n\t\t\tworld: 'Ina',\n\t\t\tcookie: 'wah!'\n\t\t})\n\t})\n\n\tit('override nested object deduplication using value', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate({\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Tako'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.decorate(\n\t\t\t\t{ as: 'override' },\n\t\t\t\t{\n\t\t\t\t\thello: {\n\t\t\t\t\t\tworld: 'Ina',\n\t\t\t\t\t\tcookie: 'wah!'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\texpect(app.decorator.hello).toEqual({\n\t\t\tworld: 'Ina',\n\t\t\tcookie: 'wah!'\n\t\t})\n\t})\n\n\tit('handle escaped name', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate('name ina', 'Ina')\n\n\t\texpect(app.decorator['name ina']).toBe('Ina')\n\t})\n})\n"
  },
  {
    "path": "test/extends/error.test.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { post, req } from '../utils'\nimport z from 'zod'\n\nclass CustomError extends Error {\n\tconstructor() {\n\t\tsuper()\n\t}\n}\n\nconst getErrors = (app: Elysia<any, any, any, any, any>) =>\n\t// @ts-ignore\n\tObject.keys(app.definitions.error)\n\ndescribe('Error', () => {\n\tit('add single', async () => {\n\t\tconst app = new Elysia().error('CUSTOM_ERROR', CustomError)\n\n\t\texpect(getErrors(app)).toEqual(['CUSTOM_ERROR'])\n\t})\n\n\tit('add multiple', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.error('CUSTOM_ERROR', CustomError)\n\t\t\t.error('CUSTOM_ERROR_2', CustomError)\n\n\t\texpect(getErrors(app)).toEqual(['CUSTOM_ERROR', 'CUSTOM_ERROR_2'])\n\t})\n\n\tit('add object', async () => {\n\t\tconst app = new Elysia().error({\n\t\t\tCUSTOM_ERROR: CustomError,\n\t\t\tCUSTOM_ERROR_2: CustomError\n\t\t})\n\n\t\texpect(getErrors(app)).toEqual(['CUSTOM_ERROR', 'CUSTOM_ERROR_2'])\n\t})\n\n\t// it('remap error', async () => {\n\t// \tconst app = new Elysia()\n\t// \t\t.error({\n\t// \t\t\tCUSTOM_ERROR: CustomError,\n\t// \t\t\tCUSTOM_ERROR_2: CustomError\n\t// \t\t})\n\t// \t\t.error(({ CUSTOM_ERROR, ...rest }) => ({\n\t// \t\t\t...rest,\n\t// \t\t\tCUSTOM_ERROR_3: CustomError\n\t// \t\t}))\n\n\t// \texpect(getErrors(app)).toEqual(['CUSTOM_ERROR', 'CUSTOM_ERROR_2'])\n\t// })\n\n\tit('inherits functional plugin', async () => {\n\t\tconst plugin = (app: Elysia) => app.error('CUSTOM_ERROR', CustomError)\n\n\t\tconst app = new Elysia().use(plugin)\n\n\t\texpect(getErrors(app)).toEqual(['CUSTOM_ERROR'])\n\t})\n\n\tit('inherits instance plugin', async () => {\n\t\tconst plugin = new Elysia().error('CUSTOM_ERROR', CustomError)\n\n\t\tconst app = new Elysia().use(plugin)\n\n\t\texpect(getErrors(app)).toEqual(['CUSTOM_ERROR'])\n\t})\n\n\tit('preserve status code base on error if not set', async () => {\n\t\tconst app = new Elysia().onError(({ code }) => {\n\t\t\tif (code === 'NOT_FOUND') return 'UwU'\n\t\t})\n\n\t\tconst response = await app.handle(req('/not/found'))\n\n\t\texpect(await response.text()).toBe('UwU')\n\t\texpect(response.status).toBe(404)\n\t})\n\n\tit('validation error should be application/json', async () => {\n\t\t// @ts-expect-error\n\t\tconst app = new Elysia().get('/', () => '1', {\n\t\t\tresponse: t.Null()\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(422)\n\t\texpect(response.headers.get('content-type')).toBe('application/json')\n\t})\n\n\tit('validation error should handle Standard Schema with error.detail', async () => {\n\t\tconst sendOtpEmailSchema = z.object({\n\t\t\tchannel: z.literal('email'),\n\t\t\totpTo: z.email({ error: 'Must be a valid email address' })\n\t\t})\n\n\t\tconst sendOtpSmsSchema = z.object({\n\t\t\tchannel: z.literal('sms'),\n\t\t\totpTo: z.e164({\n\t\t\t\terror: 'Must be a valid phone number with country code'\n\t\t\t})\n\t\t})\n\n\t\tconst sendOtpSchema = z.discriminatedUnion('channel', [\n\t\t\tsendOtpEmailSchema,\n\t\t\tsendOtpSmsSchema\n\t\t])\n\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ code, error, status }) => {\n\t\t\t\tswitch (code) {\n\t\t\t\t\tcase 'VALIDATION':\n\t\t\t\t\t\treturn error.detail(error.message)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body, set }) => 'ok', {\n\t\t\t\tbody: sendOtpSchema\n\t\t\t})\n\n\t\tconst response = await app.handle(post('/', {}))\n\n\t\texpect(response.status).toBe(422)\n\t})\n})\n"
  },
  {
    "path": "test/extends/models.test.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { post, req } from '../utils'\n\ndescribe('Model', () => {\n\tit('add single', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model('string', t.String())\n\t\t\t// @ts-ignore\n\t\t\t.route('GET', '/', (context) => Object.keys(context.defs), {\n\t\t\t\tconfig: {\n\t\t\t\t\tallowMeta: true\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.json())\n\t\texpect(res).toEqual(['string'])\n\t})\n\n\tit('add multiple', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model('string', t.String())\n\t\t\t.model('number', t.Number())\n\t\t\t// @ts-ignore\n\t\t\t.route('GET', '/', (context) => Object.keys(context.defs), {\n\t\t\t\tconfig: {\n\t\t\t\t\tallowMeta: true\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.json())\n\t\texpect(res).toEqual(['string', 'number'])\n\t})\n\n\tit('add object', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tstring: t.String(),\n\t\t\t\tnumber: t.Number()\n\t\t\t})\n\t\t\t// @ts-ignore\n\t\t\t.route('GET', '/', (context) => Object.keys(context.defs), {\n\t\t\t\tconfig: {\n\t\t\t\t\tallowMeta: true\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.json())\n\t\texpect(res).toEqual(['string', 'number'])\n\t})\n\n\tit('add object', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tstring: t.String(),\n\t\t\t\tnumber: t.Number()\n\t\t\t})\n\t\t\t.model(({ number, ...rest }) => ({\n\t\t\t\t...rest,\n\t\t\t\tboolean: t.Boolean()\n\t\t\t}))\n\t\t\t// @ts-ignore\n\t\t\t.route('GET', '/', (context) => Object.keys(context.defs), {\n\t\t\t\tconfig: {\n\t\t\t\t\tallowMeta: true\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.json())\n\t\texpect(res).toEqual(['string', 'boolean'])\n\t})\n\n\tit('inherits functional plugin', async () => {\n\t\tconst plugin = () => (app: Elysia) => app.model('string', t.String())\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin())\n\t\t\t// @ts-ignore\n\t\t\t.route('GET', '/', (context) => Object.keys(context.defs), {\n\t\t\t\tconfig: {\n\t\t\t\t\tallowMeta: true\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.json())\n\t\texpect(res).toEqual(['string'])\n\t})\n\n\tit('inherits instance plugin', async () => {\n\t\tconst plugin = () => (app: Elysia) => app.model('string', t.String())\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin())\n\t\t\t// @ts-ignore\n\t\t\t.route('GET', '/', (context) => Object.keys(context.defs), {\n\t\t\t\tconfig: {\n\t\t\t\t\tallowMeta: true\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.json())\n\t\texpect(res).toEqual(['string'])\n\t})\n\n\tit('inherits instance plugin', async () => {\n\t\tconst plugin = new Elysia().decorate('hi', () => 'hi')\n\n\t\tconst app = new Elysia().use(plugin).get('/', ({ hi }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('validate reference model', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tnumber: t.Number()\n\t\t\t})\n\t\t\t.post('/', ({ body: { data } }) => data, {\n\t\t\t\tresponse: 'number',\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tdata: t.Number()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post('/arr', ({ body }) => body, {\n\t\t\t\tresponse: 'number',\n\t\t\t\tbody: 'number'\n\t\t\t})\n\n\t\tconst correct = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tdata: 1\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\n\t\tconst correctArr = await app.handle(\n\t\t\tnew Request('http://localhost/arr', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t},\n\t\t\t\tbody: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(correctArr.status).toBe(200)\n\n\t\tconst wrong = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tdata: true\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\n\t\texpect(wrong.status).toBe(422)\n\n\t\tconst wrongArr = await app.handle(\n\t\t\tnew Request('http://localhost/arr', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tdata: true\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\n\t\texpect(wrongArr.status).toBe(422)\n\t})\n\n\tit('remap', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model('string', t.String())\n\t\t\t.model('number', t.Number())\n\t\t\t.model(({ number, ...rest }) => ({\n\t\t\t\t...rest,\n\t\t\t\tnumba: number\n\t\t\t}))\n\t\t\t// @ts-ignore\n\t\t\t.route('GET', '/', (context) => Object.keys(context.defs), {\n\t\t\t\tconfig: {\n\t\t\t\t\tallowMeta: true\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.json())\n\t\texpect(res).toEqual(['string', 'numba'])\n\t})\n\n\tit('use reference model', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tstring: t.Object({\n\t\t\t\t\tdata: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tbody: 'string'\n\t\t\t})\n\n\t\tconst error = await app.handle(post('/'))\n\t\texpect(error.status).toBe(422)\n\n\t\tconst correct = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tdata: 'hi'\n\t\t\t})\n\t\t)\n\t\texpect(correct.status).toBe(200)\n\t})\n\n\t// it('use coerce with reference model', async () => {\n\t// \tconst app = new Elysia()\n\t// \t\t.model({\n\t// \t\t\tnumber: t.Number(),\n\t// \t\t\toptionalNumber: t.Optional(t.Ref('number'))\n\t// \t\t})\n\t// \t\t.post('/', ({ body }) => body, {\n\t// \t\t\tbody: 'optionalNumber'\n\t// \t\t})\n\n\t// \tconst error = await app.handle(post('/'))\n\t// \texpect(error.status).toBe(422)\n\n\t// \tconst correct = await app.handle(\n\t// \t\tnew Request('http://localhost/', {\n\t// \t\t\tmethod: 'POST',\n\t// \t\t\theaders: {\n\t// \t\t\t\t'content-type': 'text/plain; charset=utf-8'\n\t// \t\t\t},\n\t// \t\t\tbody: '0'\n\t// \t\t})\n\t// \t)\n\t// \texpect(correct.status).toBe(200)\n\t// })\n\n\tit('create default value with nested reference model', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tnumber: t.Numeric({ default: 0 }),\n\t\t\t\toptionalNumber: t.Optional(t.Ref('number'))\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tbody: t.Optional(t.Ref('number'))\n\t\t\t})\n\n\t\tconst result = await app.handle(post('/')).then((x) => x.text())\n\n\t\texpect(result).toBe('0')\n\t})\n\n\tit('create default value with reference model', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tnumber: t.Number({ default: 0 }),\n\t\t\t\toptionalNumber: t.Optional(t.Ref('number'))\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, { body: 'optionalNumber' })\n\n\t\tconst result = await app.handle(post('/')).then((x) => x.text())\n\n\t\texpect(result).toBe('0')\n\t})\n\n\tit('use reference model with cookie', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tsession: t.Cookie({ token: t.Numeric() }),\n\t\t\t\toptionalSession: t.Optional(t.Ref('session'))\n\t\t\t})\n\t\t\t.get('/', () => 'Hello Elysia', { cookie: 'optionalSession' })\n\n\t\tconst error = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: 'token=string'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\t\texpect(error.status).toBe(422)\n\n\t\tconst correct = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: 'token=1'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\t\texpect(correct.status).toBe(200)\n\t})\n\n\tit('use reference model with response', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tres: t.String()\n\t\t\t})\n\t\t\t.get('/correct', () => 'Hello Elysia', { response: 'res' })\n\t\t\t// @ts-expect-error\n\t\t\t.get('/error', () => 1, { response: 'res' })\n\n\t\tconst error = await app.handle(req('/error'))\n\t\texpect(error.status).toBe(422)\n\n\t\tconst correct = await app.handle(req('/correct'))\n\t\texpect(correct.status).toBe(200)\n\t})\n\n\tit('use reference model with response per status', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tres: t.String()\n\t\t\t})\n\t\t\t.get('/correct', () => 'Hello Elysia', {\n\t\t\t\tresponse: {\n\t\t\t\t\t200: 'res',\n\t\t\t\t\t400: 'res'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/400', ({ status }) => status(400, 'ok'), {\n\t\t\t\tresponse: {\n\t\t\t\t\t200: 'res',\n\t\t\t\t\t400: 'res'\n\t\t\t\t}\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/error', ({ status }) => status(400, 1), {\n\t\t\t\tresponse: {\n\t\t\t\t\t200: 'res',\n\t\t\t\t\t400: 'res'\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst error = await app.handle(req('/error'))\n\t\texpect(error.status).toBe(422)\n\n\t\tconst correct = await app.handle(req('/correct'))\n\t\texpect(correct.status).toBe(200)\n\n\t\tconst correct400 = await app.handle(req('/400'))\n\t\texpect(correct400.status).toBe(400)\n\t})\n\n\tit(\"coerce model when there's no reference\", async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tidParam: t.Object({\n\t\t\t\t\tid: t.Union([\n\t\t\t\t\t\tt.String({ format: 'uuid' }),\n\t\t\t\t\t\tt.Number({\n\t\t\t\t\t\t\tminimum: 1,\n\t\t\t\t\t\t\tmaximum: Number.MAX_SAFE_INTEGER\n\t\t\t\t\t\t})\n\t\t\t\t\t])\n\t\t\t\t}),\n\t\t\t\tresponse200: t.Object({\n\t\t\t\t\tmessage: t.String(),\n\t\t\t\t\tcontent: t.Array(\n\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\tid: t.Union([t.String(), t.Number()])\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/:id',\n\t\t\t\t({ params: { id } }) => ({\n\t\t\t\t\tmessage: 'ok',\n\t\t\t\t\tcontent: [{ id }]\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tparams: 'idParam',\n\t\t\t\t\tresponse: 'response200'\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst value = await app\n\t\t\t.handle(new Request('http://localhost/3'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({ message: 'ok', content: [{ id: 3 }] })\n\t})\n})\n"
  },
  {
    "path": "test/extends/store.test.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { describe, it, expect } from 'bun:test'\nimport { Elysia } from '../../src'\nimport { req } from '../utils'\n\ndescribe('State', () => {\n\tit('decorate primitive', async () => {\n\t\tconst app = new Elysia().state('name', 'Ina').state('name', 'Tako')\n\n\t\texpect(app.store.name).toBe('Ina')\n\t})\n\n\tit('decorate multiple', async () => {\n\t\tconst app = new Elysia().state('name', 'Ina').state('job', 'artist')\n\n\t\texpect(app.store).toEqual({\n\t\t\tname: 'Ina',\n\t\t\tjob: 'artist'\n\t\t})\n\t})\n\n\tit('decorate object', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state({\n\t\t\t\tname: 'Ina',\n\t\t\t\tjob: 'artist'\n\t\t\t})\n\t\t\t.state({\n\t\t\t\tname: 'Fubuki'\n\t\t\t})\n\n\t\texpect(app.store).toEqual({\n\t\t\tname: 'Ina',\n\t\t\tjob: 'artist'\n\t\t})\n\t})\n\n\tit('remap object', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state({\n\t\t\t\tname: 'Ina',\n\t\t\t\tjob: 'artist'\n\t\t\t})\n\t\t\t.state(({ job, ...rest }) => ({\n\t\t\t\t...rest,\n\t\t\t\tjob: 'streamer'\n\t\t\t}))\n\n\t\texpect(app.store).toEqual({\n\t\t\tname: 'Ina',\n\t\t\tjob: 'streamer'\n\t\t})\n\t})\n\n\tit('inherits functional plugin', async () => {\n\t\tconst plugin = () => (app: Elysia) => app.state('hi', () => 'hi')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin())\n\t\t\t.get('/', ({ store: { hi } }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('inherits instance plugin', async () => {\n\t\tconst plugin = new Elysia().state('hi', () => 'hi')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.get('/', ({ store: { hi } }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((r) => r.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('accepts any type', async () => {\n\t\tconst app = new Elysia().state('hi', {\n\t\t\tthere: {\n\t\t\t\thello: 'world'\n\t\t\t}\n\t\t})\n\n\t\texpect(app.store.hi.there.hello).toBe('world')\n\t})\n\n\tit('remap', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state('job', 'artist')\n\t\t\t.state('name', 'Ina')\n\t\t\t.state(({ job, ...decorators }) => ({\n\t\t\t\t...decorators,\n\t\t\t\tjob: 'vtuber'\n\t\t\t}))\n\n\t\texpect(app.store.job).toBe('vtuber')\n\t})\n\n\tit('handle class deduplication', async () => {\n\t\tlet _i = 0\n\n\t\tclass A {\n\t\t\tpublic i: number\n\n\t\t\tconstructor() {\n\t\t\t\tthis.i = _i++\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().state('a', new A()).state('a', new A())\n\n\t\texpect(app.store.a.i).toBe(0)\n\t})\n\n\tit('handle nested object deduplication', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state('a', {\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Tako'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.state('a', {\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Ina',\n\t\t\t\t\tcookie: 'wah!'\n\t\t\t\t}\n\t\t\t})\n\n\t\texpect(app.store).toEqual({\n\t\t\ta: {\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Tako',\n\t\t\t\t\tcookie: 'wah!'\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t})\n\n\tit('override primitive', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state('name', 'Ina')\n\t\t\t.state({ as: 'override' }, 'name', 'Tako')\n\n\t\texpect(app.store.name).toBe('Tako')\n\t})\n\n\tit('override object', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state({\n\t\t\t\tname: 'Ina',\n\t\t\t\tjob: 'artist'\n\t\t\t})\n\t\t\t.state(\n\t\t\t\t{ as: 'override' },\n\t\t\t\t{\n\t\t\t\t\tname: 'Fubuki'\n\t\t\t\t}\n\t\t\t)\n\n\t\texpect(app.store).toEqual({\n\t\t\tname: 'Fubuki',\n\t\t\tjob: 'artist'\n\t\t})\n\t})\n\n\tit('override handle class', async () => {\n\t\tlet _i = 0\n\n\t\tclass A {\n\t\t\tpublic i: number\n\n\t\t\tconstructor() {\n\t\t\t\tthis.i = _i++\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia()\n\t\t\t.state('a', new A())\n\t\t\t.state({ as: 'override' }, 'a', new A())\n\n\t\texpect(app.store.a.i).toBe(1)\n\t})\n\n\tit('override nested object deduplication using name', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state('a', {\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Tako'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.state({ as: 'override' }, 'a', {\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Ina',\n\t\t\t\t\tcookie: 'wah!'\n\t\t\t\t}\n\t\t\t})\n\n\t\texpect(app.store.a.hello).toEqual({\n\t\t\tworld: 'Ina',\n\t\t\tcookie: 'wah!'\n\t\t})\n\t})\n\n\tit('override nested object deduplication using value', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state({\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Tako'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.state(\n\t\t\t\t{ as: 'override' },\n\t\t\t\t{\n\t\t\t\t\thello: {\n\t\t\t\t\t\tworld: 'Ina',\n\t\t\t\t\t\tcookie: 'wah!'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\texpect(app.store.hello).toEqual({\n\t\t\tworld: 'Ina',\n\t\t\tcookie: 'wah!'\n\t\t})\n\t})\n})\n"
  },
  {
    "path": "test/hoc/index.test.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { describe, it, expect } from 'bun:test'\nimport { Elysia } from '../../src'\nimport { req } from '../utils'\n\ndescribe('HOC', () => {\n\tit('work', async () => {\n\t\tlet called = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.wrap((fn) => {\n\t\t\t\tcalled++\n\n\t\t\t\treturn fn\n\t\t\t})\n\t\t\t.get('/', () => 'ok')\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(called).toBe(1)\n\t})\n\n\tit('deduplicate', async () => {\n\t\tconst plugin = new Elysia().wrap((fn) => fn)\n\t\tconst plugin2 = new Elysia({ name: 'plugin2' }).wrap((fn) => fn)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.use(plugin)\n\t\t\t.use(plugin)\n\t\t\t.use(plugin2)\n\t\t\t.use(plugin2)\n\t\t\t.get('/', () => 'ok')\n\n\t\t// @ts-expect-error\n\t\texpect(app.extender.higherOrderFunctions.length).toBe(2)\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/after-handle.test.ts",
    "content": "import { Elysia } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('After Handle', () => {\n\tit('work global', async () => {\n\t\tconst app = new Elysia().onAfterHandle(() => 'A').get('/', () => 'NOOP')\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('A')\n\t})\n\n\tit('work local', async () => {\n\t\tconst app = new Elysia().get('/', () => 'NOOP', {\n\t\t\tafterHandle() {\n\t\t\t\treturn 'A'\n\t\t\t}\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('A')\n\t})\n\n\tit('inherits from plugin', async () => {\n\t\tconst transformType = new Elysia().onAfterHandle(\n\t\t\t{ as: 'global' },\n\t\t\t({ response }) => {\n\t\t\t\tif (response === 'string') return 'number'\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(transformType)\n\t\t\t.get('/id/:id', ({ params: { id } }) => typeof id)\n\n\t\tconst res = await app.handle(req('/id/1'))\n\n\t\texpect(await res.text()).toBe('number')\n\t})\n\n\tit('not inherits plugin on local', async () => {\n\t\tconst transformType = new Elysia().onAfterHandle(({ response }) => {\n\t\t\tif (response === 'string') return 'number'\n\t\t})\n\n\t\tconst app = new Elysia()\n\t\t\t.use(transformType)\n\t\t\t.get('/id/:id', ({ params: { id } }) => typeof id)\n\n\t\tconst res = await app.handle(req('/id/1'))\n\n\t\texpect(await res.text()).toBe('string')\n\t})\n\n\tit('register using on', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.on('transform', (request) => {\n\t\t\t\tif (request.params?.id) request.params.id = +request.params.id\n\t\t\t})\n\t\t\t.get('/id/:id', ({ params: { id } }) => typeof id)\n\n\t\tconst res = await app.handle(req('/id/1'))\n\n\t\texpect(await res.text()).toBe('number')\n\t})\n\n\tit('after handle in order', async () => {\n\t\tlet order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.onAfterHandle(() => {\n\t\t\t\torder.push('A')\n\t\t\t})\n\t\t\t.onAfterHandle(() => {\n\t\t\t\torder.push('B')\n\t\t\t})\n\t\t\t.get('/', () => '')\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(order).toEqual(['A', 'B'])\n\t})\n\n\tit('accept response', async () => {\n\t\tconst app = new Elysia().get('/', () => 'NOOP', {\n\t\t\tafterHandle({ response }) {\n\t\t\t\treturn response\n\t\t\t},\n\t\t\tmapResponse() {\n\n\t\t\t}\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('NOOP')\n\t})\n\n\tit('accept responseValue', async () => {\n\t\tconst app = new Elysia().get('/', () => 'NOOP', {\n\t\t\tafterHandle({ responseValue }) {\n\t\t\t\treturn responseValue\n\t\t\t},\n\t\t\tmapResponse() {\n\n\t\t\t}\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('NOOP')\n\t})\n\n\tit('as global', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onAfterHandle({ as: 'global' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner', '/outer'])\n\t})\n\n\tit('as local', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onAfterHandle({ as: 'local' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner'])\n\t})\n\n\tit('support array', async () => {\n\t\tlet total = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.onAfterHandle([\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t}\n\t\t\t])\n\t\t\t.get('/', () => 'NOOP')\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(total).toEqual(2)\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/after-response.test.ts",
    "content": "import { Elysia } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('After Handle', () => {\n\tit('set response status', async () => {\n\t\tlet status: number\n\n\t\tconst app = new Elysia()\n\t\t\t.onAfterResponse(({ set }) => {\n\t\t\t\tstatus = set.status as number\n\t\t\t})\n\t\t\t.get('/error', (c) => c.status(401, { error: 'Unauthorized' }))\n\n\t\tconst res = await app.handle(req('/error')).then((x) => x.json())\n\t\texpect(res).toEqual({ error: 'Unauthorized' })\n\n\t\tawait Bun.sleep(1)\n\t\texpect(status!).toBe(401)\n\t})\n\n\tit('set response status for default 404', async () => {\n\t\tlet status: number\n\n\t\tconst app = new Elysia().onAfterResponse(({ set }) => {\n\t\t\tstatus = set.status as number\n\t\t})\n\n\t\tconst res = await app.handle(req('/error'))\n\t\texpect(res.status).toEqual(404)\n\n\t\tawait Bun.sleep(1)\n\t\texpect(status!).toBe(404)\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/before-handle.test.ts",
    "content": "import { Elysia } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { delay, req } from '../utils'\n\ndescribe('Before Handle', () => {\n\tit('globally skip main handler', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onBeforeHandle<{\n\t\t\t\tparams: {\n\t\t\t\t\tname?: string\n\t\t\t\t}\n\t\t\t}>(({ params: { name } }) => {\n\t\t\t\tif (name === 'Fubuki') return 'Cat'\n\t\t\t})\n\t\t\t.get('/name/:name', ({ params: { name } }) => name)\n\n\t\tconst res = await app.handle(req('/name/Fubuki'))\n\n\t\texpect(await res.text()).toBe('Cat')\n\t})\n\n\tit('locally skip main handler', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/name/:name',\n\t\t\t({ params: { name } }) => name,\n\t\t\t{\n\t\t\t\tbeforeHandle: ({ params: { name } }) => {\n\t\t\t\t\tif (name === 'Fubuki') return 'Cat'\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/name/Fubuki'))\n\n\t\texpect(await res.text()).toBe('Cat')\n\t})\n\n\tit('group before handler', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.group('/type', (app) =>\n\t\t\t\tapp\n\t\t\t\t\t.onBeforeHandle<{\n\t\t\t\t\t\tparams: {\n\t\t\t\t\t\t\tname?: string\n\t\t\t\t\t\t}\n\t\t\t\t\t}>(({ params: { name } }) => {\n\t\t\t\t\t\tif (name === 'fubuki') return 'cat'\n\t\t\t\t\t})\n\t\t\t\t\t.get('/name/:name', ({ params: { name } }) => name)\n\t\t\t)\n\t\t\t.get('/name/:name', ({ params: { name } }) => name)\n\n\t\tconst base = await app.handle(req('/name/fubuki'))\n\t\tconst scoped = await app.handle(req('/type/name/fubuki'))\n\n\t\texpect(await base.text()).toBe('fubuki')\n\t\texpect(await scoped.text()).toBe('cat')\n\t})\n\n\tit('inherits from plugin', async () => {\n\t\tconst transformId = new Elysia().onBeforeHandle(\n\t\t\t{ as: 'global' },\n\t\t\t({ params: { name } }) => {\n\t\t\t\tif (name === 'Fubuki') return 'Cat'\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(transformId)\n\t\t\t.get('/name/:name', ({ params: { name } }) => name)\n\n\t\tconst res = await app.handle(req('/name/Fubuki'))\n\n\t\texpect(await res.text()).toBe('Cat')\n\t})\n\n\tit('not inherits plugin on local', async () => {\n\t\tconst beforeHandle = new Elysia().onBeforeHandle(\n\t\t\t({ params: { name } }) => {\n\t\t\t\tif (name === 'Fubuki') return 'Cat'\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(beforeHandle)\n\t\t\t.get('/name/:name', ({ params: { name } }) => name)\n\n\t\tconst res = await app.handle(req('/name/Fubuki'))\n\n\t\texpect(await res.text()).toBe('Fubuki')\n\t})\n\n\tit('before handle in order', async () => {\n\t\tlet order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\torder.push('A')\n\t\t\t})\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\torder.push('B')\n\t\t\t})\n\t\t\t.get('/', () => '')\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(order).toEqual(['A', 'B'])\n\t})\n\n\tit('globally and locally before handle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onBeforeHandle<{\n\t\t\t\tparams: {\n\t\t\t\t\tname?: string\n\t\t\t\t}\n\t\t\t}>(({ params: { name } }) => {\n\t\t\t\tif (name === 'fubuki') return 'cat'\n\t\t\t})\n\t\t\t.get('/name/:name', ({ params: { name } }) => name, {\n\t\t\t\tbeforeHandle: ({ params: { name } }) => {\n\t\t\t\t\tif (name === 'korone') return 'dog'\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst fubuki = await app.handle(req('/name/fubuki'))\n\t\tconst korone = await app.handle(req('/name/korone'))\n\n\t\texpect(await fubuki.text()).toBe('cat')\n\t\texpect(await korone.text()).toBe('dog')\n\t})\n\n\tit('accept multiple before handler', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onBeforeHandle<{\n\t\t\t\tparams: {\n\t\t\t\t\tname?: string\n\t\t\t\t}\n\t\t\t}>(({ params: { name } }) => {\n\t\t\t\tif (name === 'fubuki') return 'cat'\n\t\t\t})\n\t\t\t.onBeforeHandle<{\n\t\t\t\tparams: {\n\t\t\t\t\tname?: string\n\t\t\t\t}\n\t\t\t}>(({ params: { name } }) => {\n\t\t\t\tif (name === 'korone') return 'dog'\n\t\t\t})\n\t\t\t.get('/name/:name', ({ params: { name } }) => name)\n\n\t\tconst fubuki = await app.handle(req('/name/fubuki'))\n\t\tconst korone = await app.handle(req('/name/korone'))\n\n\t\texpect(await fubuki.text()).toBe('cat')\n\t\texpect(await korone.text()).toBe('dog')\n\t})\n\n\tit('handle async', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/name/:name',\n\t\t\t({ params: { name } }) => name,\n\t\t\t{\n\t\t\t\tbeforeHandle: async ({ params: { name } }) => {\n\t\t\t\t\tawait delay(5)\n\n\t\t\t\t\tif (name === 'Watame') return 'Warukunai yo ne'\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/name/Watame'))\n\n\t\texpect(await res.text()).toBe('Warukunai yo ne')\n\t})\n\n\tit(\"handle on('beforeHandle')\", async () => {\n\t\tconst app = new Elysia()\n\t\t\t.on('beforeHandle', async ({ params: { name } }) => {\n\t\t\t\tawait new Promise<void>((resolve) =>\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tresolve()\n\t\t\t\t\t}, 1)\n\t\t\t\t)\n\n\t\t\t\tif (name === 'Watame') return 'Warukunai yo ne'\n\t\t\t})\n\t\t\t.get('/name/:name', ({ params: { name } }) => name)\n\n\t\tconst res = await app.handle(req('/name/Watame'))\n\n\t\texpect(await res.text()).toBe('Warukunai yo ne')\n\t})\n\n\tit('execute afterHandle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onBeforeHandle<{\n\t\t\t\tparams: {\n\t\t\t\t\tname?: string\n\t\t\t\t}\n\t\t\t}>(({ params: { name } }) => {\n\t\t\t\tif (name === 'Fubuki') return 'Cat'\n\t\t\t})\n\t\t\t.onAfterHandle((context) => {\n\t\t\t\tif (context.response === 'Cat') return 'Not cat'\n\t\t\t})\n\t\t\t.get('/name/:name', ({ params: { name } }) => name)\n\n\t\tconst res = await app.handle(req('/name/Fubuki'))\n\n\t\texpect(await res.text()).toBe('Not cat')\n\t})\n\n\tit('as global', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onBeforeHandle({ as: 'global' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner', '/outer'])\n\t})\n\n\tit('as local', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onBeforeHandle({ as: 'local' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner'])\n\t})\n\n\tit('support array', async () => {\n\t\tlet total = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.onAfterHandle([\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t}\n\t\t\t])\n\t\t\t.get('/', () => 'NOOP')\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(total).toEqual(2)\n\t})\n\n\tit('add responseValue to afterHandle, and afterResponse when beforeHandle returns a value', async () => {\n\t\tlet hasAfterHandleResponse = false\n\t\tlet hasAfterResponseResponse = false\n\n\t\tconst app = new Elysia().get(\n\t\t\t'/handler',\n\t\t\t({ status }) => {\n\t\t\t\treturn status(401, 'unauthorized handler')\n\t\t\t},\n\t\t\t{\n\t\t\t\tafterHandle: ({ responseValue }) => {\n\t\t\t\t\thasAfterHandleResponse = !!responseValue\n\t\t\t\t},\n\t\t\t\tbeforeHandle: ({ status }) =>\n\t\t\t\t\tstatus(401, 'unauthorized beforeHandle'),\n\t\t\t\tafterResponse: ({ responseValue }) => {\n\t\t\t\t\thasAfterResponseResponse = !!responseValue\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tawait app.handle(req('/handler'))\n\t\tawait delay(10)\n\n\t\texpect(hasAfterHandleResponse).toBe(true)\n\t\texpect(hasAfterResponseResponse).toBe(true)\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/derive.test.ts",
    "content": "import { Elysia } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('derive', () => {\n\tit('work', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.derive(() => ({\n\t\t\t\thi: () => 'hi'\n\t\t\t}))\n\t\t\t.get('/', ({ hi }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('inherits plugin', async () => {\n\t\tconst plugin = new Elysia().derive({ as: 'global' }, () => ({\n\t\t\thi: () => 'hi'\n\t\t}))\n\n\t\tconst app = new Elysia().use(plugin).get('/', ({ hi }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('inherits plugin on local', async () => {\n\t\tconst plugin = new Elysia().derive(() => ({\n\t\t\thi: () => 'hi'\n\t\t}))\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/', ({ hi }) => typeof hi === 'undefined')\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('true')\n\t})\n\n\tit('derive in order', async () => {\n\t\tlet order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.derive(() => {\n\t\t\t\torder.push('A')\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.derive(() => {\n\t\t\t\torder.push('B')\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/', () => '')\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(order).toEqual(['A', 'B'])\n\t})\n\n\tit('can mutate store', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state('counter', 1)\n\t\t\t.derive(({ store }) => ({\n\t\t\t\tincrease: () => store.counter++\n\t\t\t}))\n\t\t\t.get('/', ({ store, increase }) => {\n\t\t\t\tincrease()\n\n\t\t\t\treturn store.counter\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('2')\n\t})\n\n\tit('derive with static analysis', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.derive(({ headers: { name } }) => ({\n\t\t\t\tname\n\t\t\t}))\n\t\t\t.get('/', ({ name }) => name)\n\n\t\tconst res = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tname: 'Elysia'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((t) => t.text())\n\n\t\texpect(res).toBe('Elysia')\n\t})\n\n\tit('as global', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.derive({ as: 'global' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner', '/outer'])\n\t})\n\n\tit('as local', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.derive({ as: 'local' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner'])\n\t})\n\n\tit('as scoped', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.derive({ as: 'scoped' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst middle = new Elysia().use(plugin).get('/middle', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(middle).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/middle')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner', '/middle'])\n\t})\n\n\tit('support array', async () => {\n\t\tlet total = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.onAfterHandle([\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t}\n\t\t\t])\n\t\t\t.get('/', () => 'NOOP')\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(total).toEqual(2)\n\t})\n\n\tit('handle error', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.derive(({ status }) => status(418))\n\t\t\t.get('/', () => '')\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toEqual(\"I'm a teapot\")\n\t})\n\n\t// it('work inline', async () => {\n\t// \tconst app = new Elysia().get('/', ({ hi }) => hi(), {\n\t// \t\tderive: () => ({\n\t// \t\t\thi: () => 'hi'\n\t// \t\t})\n\t// \t})\n\n\t// \tconst res = await app.handle(req('/')).then((t) => t.text())\n\t// \texpect(res).toBe('hi')\n\t// })\n\n\t// it('work inline array', async () => {\n\t// \tconst app = new Elysia().get(\n\t// \t\t'/',\n\t// \t\t({ first, last }) => [last, first].join(' '),\n\t// \t\t{\n\t// \t\t\tderive: [\n\t// \t\t\t\t() => ({\n\t// \t\t\t\t\tfirst: 'himari'\n\t// \t\t\t\t}),\n\t// \t\t\t\t() => ({ last: 'akeboshi' })\n\t// \t\t\t]\n\t// \t\t}\n\t// \t)\n\n\t// \tconst res = await app.handle(req('/')).then((t) => t.text())\n\t// \texpect(res).toBe('akeboshi himari')\n\t// })\n\n\t// it('work group guard', async () => {\n\t// \tconst app = new Elysia()\n\t// \t\t.guard(\n\t// \t\t\t{\n\t// \t\t\t\tderive: () => ({ hi: () => 'hi' })\n\t// \t\t\t},\n\t// \t\t\t(app) => app.get('/', ({ hi }) => hi())\n\t// \t\t)\n\t// \t\t// @ts-expect-error\n\t// \t\t.get('/nope', ({ hi }) => hi?.() ?? 'nope')\n\n\t// \tconst res = await app.handle(req('/')).then((t) => t.text())\n\t// \texpect(res).toBe('hi')\n\n\t// \tconst nope = await app.handle(req('/nope')).then((t) => t.text())\n\t// \texpect(nope).toBe('nope')\n\t// })\n\n\t// it('work group array guard', async () => {\n\t// \tconst app = new Elysia()\n\t// \t\t.guard(\n\t// \t\t\t{\n\t// \t\t\t\tderive: [\n\t// \t\t\t\t\t() => ({ first: 'himari' }),\n\t// \t\t\t\t\t() => ({ last: 'akeboshi' })\n\t// \t\t\t\t]\n\t// \t\t\t},\n\t// \t\t\t(app) =>\n\t// \t\t\t\tapp.get('/', ({ first, last }) => [last, first].join(' '))\n\t// \t\t)\n\t// \t\t// @ts-expect-error\n\t// \t\t.get('/nope', ({ first, last }) => [last, first].join(''))\n\n\t// \tconst res = await app.handle(req('/')).then((t) => t.text())\n\t// \texpect(res).toBe('akeboshi himari')\n\n\t// \tconst nope = await app.handle(req('/nope')).then((t) => t.text())\n\t// \texpect(nope).toBe('')\n\t// })\n\n\t// it('work local guard', async () => {\n\t// \tconst app = new Elysia()\n\t// \t\t.guard({\n\t// \t\t\tderive: () => ({ hi: () => 'hi' })\n\t// \t\t})\n\t// \t\t.get('/', ({ hi }) => hi())\n\n\t// \tconst res = await app.handle(req('/')).then((t) => t.text())\n\t// \texpect(res).toBe('hi')\n\t// })\n\n\t// it('work local array guard', async () => {\n\t// \tconst app = new Elysia()\n\t// \t\t.guard({\n\t// \t\t\tderive: [\n\t// \t\t\t\t() => ({\n\t// \t\t\t\t\tfirst: 'himari'\n\t// \t\t\t\t}),\n\t// \t\t\t\t() => ({ last: 'akeboshi' })\n\t// \t\t\t]\n\t// \t\t})\n\t// \t\t.get('/', ({ first, last }) => [last, first].join(' '))\n\n\t// \tconst res = await app.handle(req('/')).then((t) => t.text())\n\t// \texpect(res).toBe('akeboshi himari')\n\t// })\n\n\t// it('work scoped guard', async () => {\n\t// \tconst plugin = new Elysia().guard({\n\t// \t\tas: 'scoped',\n\t// \t\tderive: () => ({ hi: () => 'hi' })\n\t// \t})\n\n\t// \tconst app = new Elysia().use(plugin).get('/', ({ hi }) => hi())\n\n\t// \tconst root = new Elysia()\n\t// \t\t.use(app)\n\t// \t\t// @ts-expect-error\n\t// \t\t.get('/root', ({ hi }) => hi?.() ?? 'nope')\n\n\t// \tconst res = await app.handle(req('/')).then((t) => t.text())\n\t// \texpect(res).toBe('hi')\n\n\t// \tconst res2 = await root.handle(req('/root')).then((t) => t.text())\n\t// \texpect(res2).toBe('nope')\n\t// })\n\n\t// it('work global guard', async () => {\n\t// \tconst plugin = new Elysia().guard({\n\t// \t\tas: 'global',\n\t// \t\tderive: () => ({ hi: () => 'hi' })\n\t// \t})\n\n\t// \tconst app = new Elysia().use(plugin).get('/', ({ hi }) => hi())\n\n\t// \tconst root = new Elysia()\n\t// \t\t.use(app)\n\t// \t\t.get('/root', ({ hi }) => hi?.() ?? 'nope')\n\n\t// \tconst res = await app.handle(req('/')).then((t) => t.text())\n\t// \texpect(res).toBe('hi')\n\n\t// \tconst res2 = await root.handle(req('/root')).then((t) => t.text())\n\t// \texpect(res2).toBe('hi')\n\t// })\n\n\tit('handle return derive without throw', async () => {\n\t\tlet isOnErrorCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.onError(() => {\n\t\t\t\tisOnErrorCalled = true\n\t\t\t})\n\t\t\t.derive(({ status }) => status(418))\n\t\t\t.get('/', () => '')\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(isOnErrorCalled).toBe(false)\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/error.test.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport {\n\tElysia,\n\tInternalServerError,\n\tParseError,\n\tValidationError,\n\tt,\n\tvalidationDetail\n} from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { post, req } from '../utils'\nimport * as z from 'zod'\n\ndescribe('error', () => {\n\tit('use custom 404', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/', () => 'hello')\n\t\t\t.onError(({ code, set }) => {\n\t\t\t\tif (code === 'NOT_FOUND') {\n\t\t\t\t\tset.status = 404\n\n\t\t\t\t\treturn 'UwU'\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst root = await app.handle(req('/')).then((x) => x.text())\n\t\tconst notFound = await app\n\t\t\t.handle(req('/not/found'))\n\t\t\t.then((x) => x.text())\n\n\t\texpect(root).toBe('hello')\n\t\texpect(notFound).toBe('UwU')\n\t})\n\n\tit('handle parse error', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ code }) => {\n\t\t\t\tif (code === 'PARSE') return 'Why you no proper type'\n\t\t\t})\n\t\t\t.post('/', () => {\n\t\t\t\tthrow new ParseError()\n\t\t\t})\n\n\t\tconst root = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: 'A',\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await root.text()).toBe('Why you no proper type')\n\t\texpect(root.status).toBe(400)\n\t})\n\n\tit('custom validation error', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ code, error, set }) => {\n\t\t\t\tif (code === 'VALIDATION') {\n\t\t\t\t\tset.status = 400\n\n\t\t\t\t\treturn error.all.map((i) =>\n\t\t\t\t\t\ti.summary\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tfiled: i.path.slice(1) || 'root',\n\t\t\t\t\t\t\t\t\treason: i.message\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/login', ({ body }) => body, {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tusername: t.String(),\n\t\t\t\t\tpassword: t.String()\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst res = await app.handle(post('/login', {}))\n\t\tconst data = await res.json()\n\n\t\texpect(data).toBeArray()\n\t\texpect(res.status).toBe(400)\n\t})\n\n\tit('inherits plugin', async () => {\n\t\tconst plugin = new Elysia().onError({ as: 'global' }, () => 'hi')\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => {\n\t\t\tthrow new Error('')\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('not inherits plugin on local', async () => {\n\t\tconst plugin = new Elysia().onError(() => 'hi')\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => {\n\t\t\tthrow new Error('')\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).not.toBe('hi')\n\t})\n\n\tit('custom 500', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ code }) => {\n\t\t\t\tif (code === 'INTERNAL_SERVER_ERROR') {\n\t\t\t\t\treturn 'UwU'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => {\n\t\t\t\tthrow new InternalServerError()\n\t\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(await response.text()).toBe('UwU')\n\t\texpect(response.status).toBe(500)\n\t})\n\n\tit.each([true, false])(\n\t\t'return correct number status on error function with aot: %p',\n\t\tasync (aot) => {\n\t\t\tconst app = new Elysia({ aot }).get('/', ({ status }) =>\n\t\t\t\tstatus(418, 'I am a teapot')\n\t\t\t)\n\n\t\t\tconst response = await app.handle(req('/'))\n\n\t\t\texpect(response.status).toBe(418)\n\t\t}\n\t)\n\n\tit.each([true, false])(\n\t\t'return correct named status on error function with aot: %p',\n\t\tasync (aot) => {\n\t\t\tconst app = new Elysia({ aot }).get('/', ({ status }) =>\n\t\t\t\tstatus(\"I'm a teapot\", 'I am a teapot')\n\t\t\t)\n\n\t\t\tconst response = await app.handle(req('/'))\n\n\t\t\texpect(response.status).toBe(418)\n\t\t}\n\t)\n\n\tit.each([true, false])(\n\t\t'return correct number status without value on error function with aot: %p',\n\t\tasync (aot) => {\n\t\t\tconst app = new Elysia({ aot }).get('/', ({ status }) => status(418))\n\n\t\t\tconst response = await app.handle(req('/'))\n\n\t\t\texpect(response.status).toBe(418)\n\t\t\texpect(await response.text()).toBe(\"I'm a teapot\")\n\t\t}\n\t)\n\n\tit.each([true, false])(\n\t\t'return correct named status without value on error function with aot: %p',\n\t\tasync (aot) => {\n\t\t\tconst app = new Elysia({ aot }).get('/', ({ status }) =>\n\t\t\t\tstatus(\"I'm a teapot\")\n\t\t\t)\n\n\t\t\tconst response = await app.handle(req('/'))\n\n\t\t\texpect(response.status).toBe(418)\n\t\t\texpect(await response.text()).toBe(\"I'm a teapot\")\n\t\t}\n\t)\n\n\tit('handle error in order', async () => {\n\t\tlet order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.onError(() => {\n\t\t\t\torder.push('A')\n\t\t\t})\n\t\t\t.onError(() => {\n\t\t\t\torder.push('B')\n\t\t\t})\n\t\t\t.get('/', () => {\n\t\t\t\tthrow new Error('A')\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(order).toEqual(['A', 'B'])\n\t})\n\n\tit('as global', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onError({ as: 'global' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/inner', () => {\n\t\t\t\tthrow new Error('A')\n\t\t\t})\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => {\n\t\t\tthrow new Error('A')\n\t\t})\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner', '/outer'])\n\t})\n\n\tit('as local', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onError({ as: 'local' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/inner', () => {\n\t\t\t\tthrow new Error('A')\n\t\t\t})\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => {\n\t\t\tthrow new Error('A')\n\t\t})\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner'])\n\t})\n\n\tit('support array', async () => {\n\t\tlet total = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.onAfterHandle([\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t}\n\t\t\t])\n\t\t\t.get('/', () => 'NOOP')\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(total).toEqual(2)\n\t})\n\n\tit('handle custom error thrown in onRequest', async () => {\n\t\tclass SomeCustomError extends Error {\n\t\t\tasJSON() {\n\t\t\t\treturn JSON.stringify({\n\t\t\t\t\tsomePretty: 'json'\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ error }) => {\n\t\t\t\tif (error instanceof SomeCustomError) return error.asJSON()\n\t\t\t})\n\t\t\t.onRequest(() => {\n\t\t\t\tthrow new SomeCustomError()\n\t\t\t})\n\t\t\t.get('/', () => '')\n\n\t\tconst body = await app\n\t\t\t.handle(new Request('https://localhost/'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(body).toEqual({\n\t\t\tsomePretty: 'json'\n\t\t})\n\t})\n\n\tit('handle cookie signature error', async () => {\n\t\tconst app = new Elysia({\n\t\t\tcookie: { secrets: 'secrets', sign: ['session'] }\n\t\t})\n\t\t\t.onError(({ code, error }) => {\n\t\t\t\tif (code === 'INVALID_COOKIE_SIGNATURE')\n\t\t\t\t\treturn 'Where is the signature?'\n\t\t\t})\n\t\t\t.get('/', ({ cookie: { session } }) => '')\n\n\t\tconst root = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\theaders: {\n\t\t\t\t\tCookie: 'session=1234'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await root.text()).toBe('Where is the signature?')\n\t\texpect(root.status).toBe(400)\n\t})\n\n\tit(\"don't duplicate error from plugin\", async () => {\n\t\tlet i = 0\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onError(() => {\n\t\t\t\ti++\n\t\t\t})\n\t\t\t.get('/', ({ status }) => {\n\t\t\t\tthrow status(401)\n\t\t\t})\n\n\t\tconst app = new Elysia().use(plugin)\n\n\t\tconst response = await app.handle(req('/'))\n\t\texpect(response.status).toBe(401)\n\t\texpect(await response.text()).toBe('Unauthorized')\n\t\texpect(i).toBe(1)\n\t})\n\n\tit('404 should parse query if infer', async () => {\n\t\tconst app = new Elysia().onError(({ query }) => query)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost?hello=world')\n\t\t)\n\n\t\texpect(response.status).toBe(404)\n\t\texpect(await response.json()).toEqual({ hello: 'world' })\n\t})\n\n\tit('handle inline custom error message', async () => {\n\t\tconst app = new Elysia().post('/', () => 'Hello World!', {\n\t\t\tbody: t.Object({\n\t\t\t\tx: t.Number({\n\t\t\t\t\terror: 'x must be a number'\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify({ x: 'hi!' }),\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\n\t\tconst value = await response.text()\n\t\texpect(value).toBe('x must be a number')\n\t})\n\n\tit('handle inline custom error message with validationDetail', async () => {\n\t\tconst app = new Elysia().post('/', () => 'Hello World!', {\n\t\t\tbody: t.Object({\n\t\t\t\tx: t.Number({\n\t\t\t\t\terror: validationDetail('x must be a number')\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify({ x: 'hi!' }),\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\n\t\tconst value = (await response.json()) as Record<string, unknown>\n\t\texpect(value.type).toBe('validation')\n\t\texpect(value.message).toBe('x must be a number')\n\t})\n\n\tit('handle custom error message globally', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ error, code }) => {\n\t\t\t\tif (code === 'VALIDATION') return error.detail(error.message)\n\t\t\t})\n\t\t\t.post('/', () => 'Hello World!', {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tx: t.Number({\n\t\t\t\t\t\terror: 'x must be a number'\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify({ x: 'hi!' }),\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\n\t\tconst value = (await response.json()) as Record<string, unknown>\n\t\texpect(value.type).toBe('validation')\n\t\texpect(value.message).toBe('x must be a number')\n\t})\n\n\tit('ValidationError.detail only handle custom error', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ error, code }) => {\n\t\t\t\tif (code === 'VALIDATION') return error.detail(error.message)\n\t\t\t})\n\t\t\t.post('/', () => 'Hello World!', {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tx: t.Number()\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify({ x: 'hi!' }),\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\n\t\tconst value = (await response.json()) as Record<string, unknown>\n\t\texpect(value.type).toBe('validation')\n\t\texpect(value.message).not.toStartWith('{')\n\t})\n\n\tit('ValidationError.all works with Zod validators', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ error, code }) => {\n\t\t\t\tif (error instanceof ValidationError) {\n\t\t\t\t\tconst errors = error.all\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tmessage: 'Validation failed',\n\t\t\t\t\t\terrors: errors\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/login', ({ body }) => body, {\n\t\t\t\tbody: z.object({\n\t\t\t\t\tusername: z.string(),\n\t\t\t\t\tpassword: z.string()\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst res = await app.handle(post('/login', {}))\n\t\tconst data = (await res.json()) as any\n\n\t\texpect(data).toHaveProperty('message', 'Validation failed')\n\t\texpect(data).toHaveProperty('errors')\n\t\texpect(data.errors).toBeArray()\n\t\texpect(data.errors.length).toBeGreaterThan(0)\n\t\texpect(res.status).toBe(422)\n\t})\n\n\tit('ValidationError.all provides error details with Zod validators', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ error, code }) => {\n\t\t\t\texpect(code).toBe('VALIDATION')\n\t\t\t\tif (error instanceof ValidationError) {\n\t\t\t\t\tconst errors = error.all\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tmessage: 'Validation failed',\n\t\t\t\t\t\terrors: errors.map((e: any) => ({\n\t\t\t\t\t\t\tpath: e.path,\n\t\t\t\t\t\t\tmessage: e.message,\n\t\t\t\t\t\t\tsummary: e.summary\n\t\t\t\t\t\t}))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/user', ({ body }) => body, {\n\t\t\t\tbody: z.object({\n\t\t\t\t\tname: z.string().min(3),\n\t\t\t\t\temail: z.string(),\n\t\t\t\t\tage: z.number().min(18)\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst res = await app.handle(\n\t\t\tpost('/user', {\n\t\t\t\tname: 'ab',\n\t\t\t\temail: 'invalid',\n\t\t\t\tage: 10\n\t\t\t})\n\t\t)\n\t\tconst data = (await res.json()) as any\n\n\t\texpect(data).toHaveProperty('message', 'Validation failed')\n\t\texpect(data).toHaveProperty('errors')\n\t\texpect(data.errors).toBeArray()\n\t\texpect(data.errors.length).toBeGreaterThan(0)\n\n\t\tfor (const error of data.errors) {\n\t\t\texpect(error).toHaveProperty('path')\n\t\t\texpect(error).toHaveProperty('message')\n\t\t\texpect(error).toHaveProperty('summary')\n\t\t}\n\n\t\texpect(res.status).toBe(422)\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/hook-types.test.ts",
    "content": "import { Elysia } from '../../src'\nimport { req } from '../../test/utils'\nimport { describe, it, expect } from 'bun:test'\n\n// ? Some hooks type are already tested in there respective lifecycle tests\n// ? This files is to verify weird behavior of hook type in general\ndescribe('Hook Types', () => {\n\tit('should clone function to prevent hookType link', async () => {\n\t\tconst plugin = new Elysia({ name: 'plugin' }).derive(\n\t\t\t{ as: 'scoped' },\n\t\t\t() => {\n\t\t\t\treturn { id: 1 }\n\t\t\t}\n\t\t)\n\n\t\texpect(plugin.event.transform?.[0].scope).toBe('scoped')\n\n\t\tconst a = new Elysia().use(plugin).get('/foo', ({ id }) => {\n\t\t\treturn { id, name: 'foo' }\n\t\t})\n\n\t\texpect(plugin.event.transform?.[0].scope).toBe('scoped')\n\n\t\tconst b = new Elysia().use(plugin).get('/bar', ({ id }) => {\n\t\t\treturn { id, name: 'bar' }\n\t\t})\n\n\t\texpect(plugin.event.transform?.[0].scope).toBe('scoped')\n\n\t\tconst [res1, res2] = await Promise.all([\n\t\t\ta.handle(req('/foo')).then((x) => x.json()),\n\t\t\tb.handle(req('/bar')).then((x) => x.json())\n\t\t])\n\n\t\texpect(res1).toEqual({ id: 1, name: 'foo' })\n\t\texpect(res2).toEqual({ id: 1, name: 'bar' })\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/map-derive.test.ts",
    "content": "import { Elysia } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('map derive', () => {\n\tit('work', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.derive(() => ({\n\t\t\t\thi: () => 'hi'\n\t\t\t}))\n\t\t\t.mapDerive((derivatives) => ({\n\t\t\t\t...derivatives,\n\t\t\t\thi2: () => 'hi'\n\t\t\t}))\n\t\t\t.get('/', ({ hi }) => hi())\n\t\t\t.get('/h2', ({ hi2 }) => hi2())\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\tconst res2 = await app.handle(req('/h2')).then((t) => t.text())\n\n\t\texpect(res).toBe('hi')\n\t\texpect(res2).toBe('hi')\n\t})\n\n\tit('inherits plugin', async () => {\n\t\tconst plugin = new Elysia()\n\t\t\t.derive({ as: 'global' }, () => ({\n\t\t\t\thi: () => 'hi'\n\t\t\t}))\n\t\t\t.mapDerive((derivatives) => ({\n\t\t\t\t...derivatives,\n\t\t\t\thi2: () => 'hi'\n\t\t\t}))\n\t\t\t.get('/h2', ({ hi2 }) => hi2())\n\n\t\tconst app = new Elysia().use(plugin).get('/', ({ hi }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\tconst res2 = await app.handle(req('/h2')).then((t) => t.text())\n\n\t\texpect(res).toBe('hi')\n\t\texpect(res2).toBe('hi')\n\t})\n\n\tit('not inherits plugin on local', async () => {\n\t\tconst plugin = new Elysia()\n\t\t\t.derive(() => ({\n\t\t\t\thi: () => 'hi'\n\t\t\t}))\n\t\t\t.mapDerive((derivatives) => ({\n\t\t\t\t...derivatives,\n\t\t\t\thi2: () => 'hi'\n\t\t\t}))\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/', ({ hi2 }) => typeof hi2 === 'undefined')\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('true')\n\t})\n\n\tit('can mutate store', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state('counter', 1)\n\t\t\t.mapDerive(({ store }) => ({\n\t\t\t\tincrease: () => store.counter++\n\t\t\t}))\n\t\t\t.get('/', ({ store, increase }) => {\n\t\t\t\tincrease()\n\n\t\t\t\treturn store.counter\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('2')\n\t})\n\n\tit('derive with static analysis', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.mapDerive(({ headers: { name } }) => ({\n\t\t\t\tname\n\t\t\t}))\n\t\t\t.get('/', ({ name }) => name)\n\n\t\tconst res = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tname: 'Elysia'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((t) => t.text())\n\n\t\texpect(res).toBe('Elysia')\n\t})\n\n\tit('store in the same stack as transform', async () => {\n\t\tconst stack: number[] = []\n\n\t\tconst app = new Elysia()\n\t\t\t.onTransform(() => {\n\t\t\t\tstack.push(1)\n\t\t\t})\n\t\t\t.mapDerive(() => {\n\t\t\t\tstack.push(2)\n\n\t\t\t\treturn { name: 'Ina' }\n\t\t\t})\n\t\t\t.get('/', ({ name }) => name, {\n\t\t\t\ttransform() {\n\t\t\t\t\tstack.push(3)\n\t\t\t\t}\n\t\t\t})\n\n\t\tawait app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\theaders: {\n\t\t\t\t\tname: 'Elysia'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(stack).toEqual([1, 2, 3])\n\t})\n\n\tit('map derive in order', async () => {\n\t\tlet order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.mapDerive(() => {\n\t\t\t\torder.push('A')\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.mapDerive(() => {\n\t\t\t\torder.push('B')\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/', () => '')\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(order).toEqual(['A', 'B'])\n\t})\n\n\tit('as local', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.mapDerive({ as: 'local' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner'])\n\t})\n\n\tit('as global', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.mapDerive({ as: 'global' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner', '/outer'])\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/map-resolve.test.ts",
    "content": "import { Elysia } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('map resolve', () => {\n\tit('work', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.resolve(() => ({\n\t\t\t\thi: () => 'hi'\n\t\t\t}))\n\t\t\t.mapResolve((resolvers) => ({\n\t\t\t\t...resolvers,\n\t\t\t\thi2: () => 'hi'\n\t\t\t}))\n\t\t\t.get('/', ({ hi }) => hi())\n\t\t\t.get('/h2', ({ hi2 }) => hi2())\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\tconst res2 = await app.handle(req('/h2')).then((t) => t.text())\n\n\t\texpect(res).toBe('hi')\n\t\texpect(res2).toBe('hi')\n\t})\n\n\tit('inherits plugin', async () => {\n\t\tconst plugin = new Elysia()\n\t\t\t.resolve({ as: 'global' }, () => ({\n\t\t\t\thi: () => 'hi'\n\t\t\t}))\n\t\t\t// .mapResolve((resolvers) => ({\n\t\t\t// \t...resolvers,\n\t\t\t// \thi2: () => 'hi'\n\t\t\t// }))\n\t\t\t// .get('/h2', ({ hi2 }) => hi2())\n\n\t\tconst app = new Elysia().use(plugin).get('/', ({ hi }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\t// const res2 = await app.handle(req('/h2')).then((t) => t.text())\n\n\t\texpect(res).toBe('hi')\n\t\t// expect(res2).toBe('hi')\n\t})\n\n\tit('not inherits plugin', async () => {\n\t\tconst plugin = new Elysia()\n\t\t\t.resolve(() => ({\n\t\t\t\thi: () => 'hi'\n\t\t\t}))\n\t\t\t.mapResolve((resolvers) => ({\n\t\t\t\t...resolvers,\n\t\t\t\thi2: () => 'hi'\n\t\t\t}))\n\t\t\t.get('/h2', ({ hi2 }) => hi2())\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/', ({ hi2 }) => typeof hi2 === \"undefined\")\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\tconst res2 = await app.handle(req('/h2')).then((t) => t.text())\n\n\t\texpect(res).toBe('true')\n\t\texpect(res2).toBe('hi')\n\t})\n\n\tit('map resolve in order', async () => {\n\t\tlet order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.mapResolve(() => {\n\t\t\t\torder.push('A')\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.mapResolve(() => {\n\t\t\t\torder.push('B')\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/', () => '')\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(order).toEqual(['A', 'B'])\n\t})\n\n\tit('can mutate store', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state('counter', 1)\n\t\t\t.mapResolve(({ store }) => ({\n\t\t\t\tincrease: () => store.counter++\n\t\t\t}))\n\t\t\t.get('/', ({ store, increase }) => {\n\t\t\t\tincrease()\n\n\t\t\t\treturn store.counter\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('2')\n\t})\n\n\tit('resolve with static analysis', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.mapResolve(({ headers: { name } }) => ({\n\t\t\t\tname\n\t\t\t}))\n\t\t\t.get('/', ({ name }) => name)\n\n\t\tconst res = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tname: 'Elysia'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((t) => t.text())\n\n\t\texpect(res).toBe('Elysia')\n\t})\n\n\tit('store in the same stack as before handle', async () => {\n\t\tconst stack: number[] = []\n\n\t\tconst app = new Elysia()\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\tstack.push(1)\n\t\t\t})\n\t\t\t.mapResolve(() => {\n\t\t\t\tstack.push(2)\n\n\t\t\t\treturn { name: 'Ina' }\n\t\t\t})\n\t\t\t.get('/', ({ name }) => name, {\n\t\t\t\tbeforeHandle() {\n\t\t\t\t\tstack.push(3)\n\t\t\t\t}\n\t\t\t})\n\n\t\tawait app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\theaders: {\n\t\t\t\t\tname: 'Elysia'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(stack).toEqual([1, 2, 3])\n\t})\n\n\tit('as global', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.mapResolve({ as: 'global' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner', '/outer'])\n\t})\n\n\tit('as local', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.mapResolve({ as: 'local' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner'])\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/map-response.test.ts",
    "content": "import { Elysia, form } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('Map Response', () => {\n\tit('work global', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.mapResponse(() => new Response('A'))\n\t\t\t.get('/', () => 'Hutao')\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('A')\n\t})\n\n\tit('work local', async () => {\n\t\tconst app = new Elysia().get('/', () => 'Hutao', {\n\t\t\tmapResponse() {\n\t\t\t\treturn new Response('A')\n\t\t\t}\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('A')\n\t})\n\n\tit('set header', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ set }) => {\n\t\t\t\tset.headers['X-Powered-By'] = 'Elysia'\n\n\t\t\t\treturn 'a'\n\t\t\t},\n\t\t\t{\n\t\t\t\tmapResponse() {\n\t\t\t\t\treturn new Response('A', {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'X-Test': 'OK'\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst headers = await app.handle(req('/')).then((x) => x.headers)\n\n\t\texpect(headers.get('X-Test')).toContain('OK')\n\t\texpect(headers.get('X-Powered-By')).toContain('Elysia')\n\t})\n\n\tit('inherits plugin', async () => {\n\t\tconst plugin = new Elysia().mapResponse(\n\t\t\t{ as: 'global' },\n\t\t\t() => new Response('Fubuki')\n\t\t)\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'a')\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('Fubuki')\n\t})\n\n\tit('not inherits plugin on local', async () => {\n\t\tconst plugin = new Elysia().mapResponse(() => new Response('Fubuki'))\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'a')\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('a')\n\t})\n\n\tit('map response only once', async () => {\n\t\tconst app = new Elysia().get('/', () => 'Hutao', {\n\t\t\tmapResponse: [\n\t\t\t\t() => {},\n\t\t\t\t() => {\n\t\t\t\t\treturn new Response('A')\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\treturn new Response('B')\n\t\t\t\t}\n\t\t\t]\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('A')\n\t})\n\n\tit('inherit response', async () => {\n\t\tconst app = new Elysia().get('/', () => 'Hu', {\n\t\t\tmapResponse({ response }) {\n\t\t\t\tif (typeof response === 'string')\n\t\t\t\t\treturn new Response(response + 'tao')\n\t\t\t}\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('Hutao')\n\t})\n\n\tit('inherit response using responseValue', async () => {\n\t\tconst app = new Elysia().get('/', () => 'Hu', {\n\t\t\tmapResponse({ responseValue }) {\n\t\t\t\tif (typeof responseValue === 'string')\n\t\t\t\t\treturn new Response(responseValue + 'tao')\n\t\t\t}\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('Hutao')\n\t})\n\n\tit('inherit set', async () => {\n\t\tconst app = new Elysia().get('/', () => 'Hu', {\n\t\t\tmapResponse({ response, set }) {\n\t\t\t\tset.headers['X-Powered-By'] = 'Elysia'\n\n\t\t\t\tif (typeof response === 'string')\n\t\t\t\t\treturn new Response(response + 'tao', {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'X-Series': 'Genshin'\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t}\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.headers)\n\n\t\texpect(res.get('X-Powered-By')).toBe('Elysia')\n\t\texpect(res.get('X-Series')).toBe('Genshin')\n\t})\n\n\tit('inherit set using responseValue', async () => {\n\t\tconst app = new Elysia().get('/', () => 'Hu', {\n\t\t\tmapResponse({ responseValue, set }) {\n\t\t\t\tset.headers['X-Powered-By'] = 'Elysia'\n\n\t\t\t\tif (typeof responseValue === 'string')\n\t\t\t\t\treturn new Response(responseValue + 'tao', {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'X-Series': 'Genshin'\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t}\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.headers)\n\n\t\texpect(res.get('X-Powered-By')).toBe('Elysia')\n\t\texpect(res.get('X-Series')).toBe('Genshin')\n\t})\n\n\tit('return async', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.mapResponse(async () => new Response('A'))\n\t\t\t.get('/', () => 'Hutao')\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('A')\n\t})\n\n\tit('skip async', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.mapResponse(async () => {})\n\t\t\t.get('/', () => 'Hutao')\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('Hutao')\n\t})\n\n\tit('map response in order', async () => {\n\t\tlet order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.mapResponse(() => {\n\t\t\t\torder.push('A')\n\t\t\t})\n\t\t\t.mapResponse(() => {\n\t\t\t\torder.push('B')\n\t\t\t})\n\t\t\t.get('/', () => '')\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(order).toEqual(['A', 'B'])\n\t})\n\n\tit('as global', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.mapResponse({ as: 'global' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner', '/outer'])\n\t})\n\n\tit('as local', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.mapResponse({ as: 'local' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner'])\n\t})\n\n\tit('support array', async () => {\n\t\tlet total = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.mapResponse([\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t}\n\t\t\t])\n\t\t\t.get('/', () => 'NOOP')\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(total).toEqual(2)\n\t})\n\n\tit('mapResponse in error', async () => {\n\t\tclass CustomClass {\n\t\t\tconstructor(public name: string) {}\n\t\t}\n\n\t\tconst app = new Elysia()\n\t\t\t.trace(() => {})\n\t\t\t.onError(() => new CustomClass('aru'))\n\t\t\t.mapResponse(({ response }) => {\n\t\t\t\tif (response instanceof CustomClass)\n\t\t\t\t\treturn new Response(response.name)\n\t\t\t})\n\t\t\t.get('/', () => {\n\t\t\t\tthrow new Error('Hello')\n\t\t\t})\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('aru')\n\t})\n\n\tit('mapResponse in error using responseValue', async () => {\n\t\tclass CustomClass {\n\t\t\tconstructor(public name: string) {}\n\t\t}\n\n\t\tconst app = new Elysia()\n\t\t\t.trace(() => {})\n\t\t\t.onError(() => new CustomClass('aru'))\n\t\t\t.mapResponse(({ responseValue }) => {\n\t\t\t\tif (responseValue instanceof CustomClass)\n\t\t\t\t\treturn new Response(responseValue.name)\n\t\t\t})\n\t\t\t.get('/', () => {\n\t\t\t\tthrow new Error('Hello')\n\t\t\t})\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('aru')\n\t})\n\n\t// https://github.com/elysiajs/elysia/issues/965\n\tit('mapResponse with after handle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onAfterHandle(() => {})\n\t\t\t.mapResponse((context) => {\n\t\t\t\treturn new Response(context.response + '')\n\t\t\t})\n\t\t\t.get('/', async () => 'aru')\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('aru')\n\t})\n\n\tit('mapResponse with after handle using responseValue', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onAfterHandle(() => {})\n\t\t\t.mapResponse((context) => {\n\t\t\t\treturn new Response(context.responseValue + '')\n\t\t\t})\n\t\t\t.get('/', async () => 'aru')\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('aru')\n\t})\n\n\tit('mapResponse with onError', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(() => {})\n\t\t\t.mapResponse(() => {})\n\t\t\t.get('/', () => 'ok')\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('ok')\n\t})\n\n\tit('handle set in mapResonse', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.mapResponse(({ set }) => {\n\t\t\t\tset.headers['x-powered-by'] = 'Elysia'\n\t\t\t})\n\t\t\t.get('/', new Response('ok'))\n\n\t\tconst response = await app.handle(req('/'))\n\t\tconst value = await response.text()\n\n\t\texpect(value).toBe('ok')\n\t\texpect(response.headers.get('x-powered-by')).toBe('Elysia')\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/parser.test.ts",
    "content": "import { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { post } from '../utils'\n\ndescribe('Parser', () => {\n\tit('handle onParse', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onParse((context, contentType) => {\n\t\t\t\tswitch (contentType) {\n\t\t\t\t\tcase 'application/Elysia':\n\t\t\t\t\t\treturn 'A'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body)\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: ':D',\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/Elysia',\n\t\t\t\t\t'content-length': '2'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.text()).toBe('A')\n\t})\n\n\tit('register using on', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.on('parse', (context, contentType) => {\n\t\t\t\tswitch (contentType) {\n\t\t\t\t\tcase 'application/Elysia':\n\t\t\t\t\t\treturn context.request.text()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body)\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: ':D',\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/Elysia',\n\t\t\t\t\t'content-length': '2'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.text()).toBe(':D')\n\t})\n\n\tit('overwrite default parser', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onParse((context, contentType) => {\n\t\t\t\tswitch (contentType) {\n\t\t\t\t\tcase 'text/plain':\n\t\t\t\t\t\treturn 'Overwrited'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body)\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: ':D',\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'text/plain',\n\t\t\t\t\t'content-length': '2'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.text()).toBe('Overwrited')\n\t})\n\n\tit('parse x-www-form-urlencoded', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body)\n\n\t\tconst body = {\n\t\t\tusername: 'salty aom',\n\t\t\tpassword: '12345678'\n\t\t}\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: `username=${body.username}&password=${body.password}`,\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/x-www-form-urlencoded'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual(body)\n\t})\n\n\tit('parse with extra content-type attribute', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body)\n\n\t\tconst body = {\n\t\t\tusername: 'salty aom',\n\t\t\tpassword: '12345678'\n\t\t}\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/json;charset=utf-8'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual(body)\n\t})\n\n\tit('inline parse', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tparse({ request }) {\n\t\t\t\treturn request.text().then(() => 'hi')\n\t\t\t}\n\t\t})\n\n\t\tconst res = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tbody: 'ok',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.text())\n\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('map parser in order', async () => {\n\t\tlet order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.onParse({ as: 'global' }, ({ path }) => {\n\t\t\t\torder.push('A')\n\t\t\t})\n\t\t\t.onParse({ as: 'global' }, ({ path }) => {\n\t\t\t\torder.push('B')\n\t\t\t})\n\t\t\t.post('/', ({ body }) => 'NOOP')\n\n\t\tconst res = await app.handle(post('/', {}))\n\n\t\texpect(order).toEqual(['A', 'B'])\n\t})\n\n\tit('inherits plugin', async () => {\n\t\tconst plugin = new Elysia().onParse({ as: 'global' }, () => 'Kozeki Ui')\n\n\t\tconst app = new Elysia().use(plugin).post('/', ({ body }) => body)\n\n\t\tconst res = await app.handle(post('/', {})).then((t) => t.text())\n\t\texpect(res).toBe('Kozeki Ui')\n\t})\n\n\tit('not inherits plugin on local', async () => {\n\t\tconst plugin = new Elysia().onParse(() => 'Kozeki Ui')\n\n\t\tconst app = new Elysia().use(plugin).post('/', ({ body }) => body)\n\n\t\tconst res = await app\n\t\t\t.handle(post('/', { name: 'Kozeki Ui' }))\n\t\t\t.then((t) => t.json())\n\n\t\texpect(res).toEqual({ name: 'Kozeki Ui' })\n\t})\n\n\tit('as global', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onParse({ as: 'global' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\t\t\t})\n\t\t\t.post('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).post('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(post('/inner', {})),\n\t\t\tapp.handle(post('/outer', {}))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner', '/outer'])\n\t})\n\n\tit('as local', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onParse({ as: 'local' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\t\t\t})\n\t\t\t.post('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).post('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(post('/inner', {})),\n\t\t\tapp.handle(post('/outer', {}))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner'])\n\t})\n\n\tit('support array', async () => {\n\t\tlet total = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.onParse([\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t}\n\t\t\t])\n\t\t\t.post('/', ({ body }) => 'NOOP')\n\n\t\tconst res = await app.handle(post('/', {}))\n\n\t\texpect(total).toEqual(2)\n\t})\n\n\tit('handle type with validator with custom parse', async () => {\n\t\tconst app = new Elysia().post('/json', ({ body: { name } }) => name, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t}),\n\t\t\tparse: [\n\t\t\t\t({ contentType }) => {\n\t\t\t\t\tif (contentType === 'custom') return { name: 'Mutsuki' }\n\t\t\t\t},\n\t\t\t\t'json'\n\t\t\t]\n\t\t})\n\n\t\tconst [correct, incorrect, custom] = await Promise.all([\n\t\t\tapp.handle(post('/json', { name: 'Aru' })).then((x) => x.text()),\n\t\t\tapp\n\t\t\t\t.handle(post('/json', { school: 'Gehenna' }))\n\t\t\t\t.then((x) => x.status),\n\t\t\tapp\n\t\t\t\t.handle(\n\t\t\t\t\tnew Request('http://localhost/json', {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\tbody: JSON.stringify({ name: 'Aru' }),\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'content-type': 'custom'\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t.then((x) => x.text())\n\t\t])\n\n\t\texpect(correct).toBe('Aru')\n\t\texpect(incorrect).toBe(422)\n\t\texpect(custom).toBe('Mutsuki')\n\t})\n\n\tit('handle name parser', async () => {\n\t\tconst app = new Elysia().post('/json', ({ body }) => body, {\n\t\t\tparse: ['json']\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost:3000/json', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tbody: JSON.stringify({ name: 'Aru' })\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({ name: 'Aru' })\n\t})\n\n\tit('handle custom parser then fallback to named default', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.parser('custom', ({ contentType, request }) => {\n\t\t\t\tif (contentType.startsWith('application/x-elysia'))\n\t\t\t\t\treturn { name: 'Eden' }\n\t\t\t})\n\t\t\t.post('/json', ({ body }) => body, {\n\t\t\t\tparse: ['custom', 'json']\n\t\t\t})\n\n\t\tconst response = await Promise.all([\n\t\t\tapp\n\t\t\t\t.handle(\n\t\t\t\t\tnew Request('http://localhost:3000/json', {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\tbody: JSON.stringify({ name: 'Aru' })\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t.then((x) => x.json()),\n\t\t\tapp\n\t\t\t\t.handle(\n\t\t\t\t\tnew Request('http://localhost:3000/json', {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'content-type': 'application/x-elysia'\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbody: JSON.stringify({ name: 'Aru' })\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t.then((x) => x.json())\n\t\t])\n\n\t\texpect(response).toEqual([{ name: 'Aru' }, { name: 'Eden' }])\n\t})\n\n\tit('handle custom parser then fallback to unknown', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.parser('custom', ({ contentType, request }) => {\n\t\t\t\tif (contentType.startsWith('application/x-elysia'))\n\t\t\t\t\treturn { name: 'Eden' }\n\t\t\t})\n\t\t\t.post('/json', ({ body }) => body, {\n\t\t\t\tparse: ['custom']\n\t\t\t})\n\n\t\tconst response = await Promise.all([\n\t\t\tapp\n\t\t\t\t.handle(\n\t\t\t\t\tnew Request('http://localhost:3000/json', {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbody: JSON.stringify({ name: 'Aru' })\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t.then((x) => x.json()),\n\t\t\tapp\n\t\t\t\t.handle(\n\t\t\t\t\tnew Request('http://localhost:3000/json', {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'content-type': 'application/x-elysia'\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbody: JSON.stringify({ name: 'Aru' })\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t.then((x) => x.json())\n\t\t])\n\n\t\texpect(response).toEqual([{ name: 'Aru' }, { name: 'Eden' }])\n\t})\n\n\tit('handle parser from plugin', async () => {\n\t\tconst plugin = new Elysia().parser(\n\t\t\t'custom',\n\t\t\t({ contentType, request }) => {\n\t\t\t\tif (contentType === 'application/x-elysia')\n\t\t\t\t\treturn { name: 'Eden' }\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.parser('custom2', ({ contentType, request }) => {\n\t\t\t\tif (contentType === 'application/x-elysia-2')\n\t\t\t\t\treturn { name: 'Pardofelis' }\n\t\t\t})\n\t\t\t.post('/json', ({ body }) => body, {\n\t\t\t\tparse: ['custom', 'custom2']\n\t\t\t})\n\n\t\tconst response = await Promise.all([\n\t\t\tapp\n\t\t\t\t.handle(\n\t\t\t\t\tnew Request('http://localhost:3000/json', {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbody: JSON.stringify({ name: 'Aru' })\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t.then((x) => x.json()),\n\t\t\tapp\n\t\t\t\t.handle(\n\t\t\t\t\tnew Request('http://localhost:3000/json', {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'content-type': 'application/x-elysia'\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbody: JSON.stringify({ name: 'Aru' })\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t.then((x) => x.json()),\n\t\t\tapp\n\t\t\t\t.handle(\n\t\t\t\t\tnew Request('http://localhost:3000/json', {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t'content-type': 'application/x-elysia-2'\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbody: JSON.stringify({ name: 'Aru' })\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t.then((x) => x.json())\n\t\t])\n\n\t\texpect(response).toEqual([\n\t\t\t{ name: 'Aru' },\n\t\t\t{ name: 'Eden' },\n\t\t\t{ name: 'Pardofelis' }\n\t\t])\n\t})\n\n\tit('should get parse error', async () => {\n\t\tlet code: string | undefined\n\n\t\tconst app = new Elysia()\n\t\t\t.onError((ctx) => {\n\t\t\t\t// @ts-ignore\n\t\t\t\tcode = ctx.code\n\t\t\t})\n\t\t\t.post('/', () => '', {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\ttest: t.String()\n\t\t\t\t})\n\t\t\t})\n\n\t\tawait app.modules\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request(`http://localhost`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\tbody: ''\n\t\t\t})\n\t\t)\n\n\t\texpect(code).toBe('PARSE')\n\t\texpect(response.status).toBe(400)\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/request.test.ts",
    "content": "import { Elysia } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req, delay } from '../utils'\n\ndescribe('On Request', () => {\n\tit('inject headers to response', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onRequest(({ set }) => {\n\t\t\t\tset.headers['Access-Control-Allow-Origin'] = '*'\n\t\t\t})\n\t\t\t.get('/', () => 'hi')\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')\n\t})\n\n\tit('handle async', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onRequest(async ({ set }) => {\n\t\t\t\tawait delay(5)\n\t\t\t\tset.headers.name = 'llama'\n\t\t\t})\n\t\t\t.get('/', () => 'hi')\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.headers.get('name')).toBe('llama')\n\t})\n\n\tit('early return', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onRequest(({ set }) => {\n\t\t\t\tset.status = 401\n\t\t\t\treturn 'Unauthorized'\n\t\t\t})\n\t\t\t.get('/', () => {\n\t\t\t\tconsole.log(\"This shouldn't be run\")\n\t\t\t\treturn \"You shouldn't see this\"\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\t\texpect(await res.text()).toBe('Unauthorized')\n\t\texpect(res.status).toBe(401)\n\t})\n\n\tit('support array', async () => {\n\t\tlet total = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.onRequest([\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t}\n\t\t\t])\n\t\t\t.get('/', () => 'NOOP')\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(total).toEqual(2)\n\t})\n\n\tit('request in order', async () => {\n\t\tlet order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.onRequest(() => {\n\t\t\t\torder.push('A')\n\t\t\t})\n\t\t\t.onRequest(() => {\n\t\t\t\torder.push('B')\n\t\t\t})\n\t\t\t.get('/', () => '')\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(order).toEqual(['A', 'B'])\n\t})\n\n\tit('has qi', async () => {\n\t\tlet queryIndex\n\n\t\tconst app = new Elysia()\n\t\t\t// @ts-ignore\n\t\t\t.onRequest(({ qi }) => {\n\t\t\t\tqueryIndex = qi\n\t\t\t})\n\t\t\t.get('/', () => 'ok')\n\t\t\t.listen(0)\n\n\t\tawait fetch(`http://localhost:${app.server?.port}`)\n\n\t\texpect(queryIndex).toBeTypeOf('number')\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/resolve.test.ts",
    "content": "import { Elysia } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('resolve', () => {\n\tit('work', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.resolve(() => ({\n\t\t\t\thi: () => 'hi'\n\t\t\t}))\n\t\t\t.get('/', ({ hi }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('inherits plugin', async () => {\n\t\tconst plugin = new Elysia().resolve({ as: 'global' }, () => ({\n\t\t\thi: () => 'hi'\n\t\t}))\n\n\t\tconst app = new Elysia().use(plugin).get('/', ({ hi }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('not inherits plugin on local', async () => {\n\t\tconst plugin = new Elysia().resolve(() => ({\n\t\t\thi: () => 'hi'\n\t\t}))\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/', ({ hi }) => typeof hi === 'undefined')\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('true')\n\t})\n\n\tit('can mutate store', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.state('counter', 1)\n\t\t\t.resolve(({ store }) => ({\n\t\t\t\tincrease: () => store.counter++\n\t\t\t}))\n\t\t\t.get('/', ({ store, increase }) => {\n\t\t\t\tincrease()\n\n\t\t\t\treturn store.counter\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('2')\n\t})\n\n\tit('derive with static analysis', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.resolve(({ headers: { name } }) => ({\n\t\t\t\tname\n\t\t\t}))\n\t\t\t.get('/', ({ name }) => name)\n\n\t\tconst res = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tname: 'Elysia'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((t) => t.text())\n\n\t\texpect(res).toBe('Elysia')\n\t})\n\n\tit('store in the same stack as before handle', async () => {\n\t\tconst stack: number[] = []\n\n\t\tconst app = new Elysia()\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\tstack.push(1)\n\t\t\t})\n\t\t\t.resolve(() => {\n\t\t\t\tstack.push(2)\n\n\t\t\t\treturn { name: 'Ina' }\n\t\t\t})\n\t\t\t.get('/', ({ name }) => name, {\n\t\t\t\tbeforeHandle() {\n\t\t\t\t\tstack.push(3)\n\t\t\t\t}\n\t\t\t})\n\n\t\tawait app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\theaders: {\n\t\t\t\t\tname: 'Elysia'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(stack).toEqual([1, 2, 3])\n\t})\n\n\tit('resolve in order', async () => {\n\t\tlet order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.resolve(() => {\n\t\t\t\torder.push('A')\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.resolve(() => {\n\t\t\t\torder.push('B')\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/', () => '')\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(order).toEqual(['A', 'B'])\n\t})\n\n\tit('as global', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.resolve({ as: 'global' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner', '/outer'])\n\t})\n\n\tit('as scoped', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.resolve({ as: 'scoped' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst middle = new Elysia().use(plugin).get('/middle', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(middle).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/middle')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner', '/middle'])\n\t})\n\n\tit('as local', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.resolve({ as: 'local' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\n\t\t\t\treturn {}\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner'])\n\t})\n\n\tit('support array', async () => {\n\t\tlet total = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.onAfterHandle([\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t}\n\t\t\t])\n\t\t\t.get('/', () => 'NOOP')\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(total).toEqual(2)\n\t})\n\n\tit('handle error', async () => {\n\t\tconst route = new Elysia()\n\t\t\t.resolve(({ status }) => {\n\t\t\t\treturn status(418)\n\t\t\t})\n\t\t\t.get('/', () => '')\n\n\t\tconst res = await new Elysia({ aot: true }).use(route).handle(req('/'))\n\t\texpect(await res.status).toEqual(418)\n\t\texpect(await res.text()).toEqual(\"I'm a teapot\")\n\n\t\tconst res2 = await new Elysia({ aot: false })\n\t\t\t.use(route)\n\t\t\t.handle(req('/'))\n\t\texpect(await res2.status).toEqual(418)\n\t\texpect(await res2.text()).toEqual(\"I'm a teapot\")\n\t})\n\n\t/** These work but there's no support for type\n\tit('work inline', async () => {\n\t\tconst app = new Elysia().get('/', ({ hi }) => hi(), {\n\t\t\tresolve: () => ({\n\t\t\t\thi: () => 'hi'\n\t\t\t})\n\t\t})\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('work inline array', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ first, last }) => [last, first].join(' '),\n\t\t\t{\n\t\t\t\tresolve: [\n\t\t\t\t\t() => ({\n\t\t\t\t\t\tfirst: 'himari'\n\t\t\t\t\t}),\n\t\t\t\t\t() => ({ last: 'akeboshi' })\n\t\t\t\t]\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('akeboshi himari')\n\t})\n\n\tit('work group guard', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard(\n\t\t\t\t{\n\t\t\t\t\tresolve: () => ({ hi: () => 'hi' })\n\t\t\t\t},\n\t\t\t\t(app) => app.get('/', ({ hi }) => hi())\n\t\t\t)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/nope', ({ hi }) => hi?.() ?? 'nope')\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('hi')\n\n\t\tconst nope = await app.handle(req('/nope')).then((t) => t.text())\n\t\texpect(nope).toBe('nope')\n\t})\n\n\tit('work group array guard', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard(\n\t\t\t\t{\n\t\t\t\t\tresolve: [\n\t\t\t\t\t\t() => ({ first: 'himari' }),\n\t\t\t\t\t\t() => ({ last: 'akeboshi' })\n\t\t\t\t\t]\n\t\t\t\t},\n\t\t\t\t(app) =>\n\t\t\t\t\tapp.get('/', ({ first, last }) => [last, first].join(' '))\n\t\t\t)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/nope', ({ first, last }) => [last, first].join(''))\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('akeboshi himari')\n\n\t\tconst nope = await app.handle(req('/nope')).then((t) => t.text())\n\t\texpect(nope).toBe('')\n\t})\n\n\tit('work local guard', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresolve: () => ({ hi: () => 'hi' })\n\t\t\t})\n\t\t\t.get('/', ({ hi }) => hi())\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('hi')\n\t})\n\n\tit('work local array guard', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresolve: [\n\t\t\t\t\t() => ({\n\t\t\t\t\t\tfirst: 'himari'\n\t\t\t\t\t}),\n\t\t\t\t\t() => ({ last: 'akeboshi' })\n\t\t\t\t]\n\t\t\t})\n\t\t\t.get('/', ({ first, last }) => [last, first].join(' '))\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('akeboshi himari')\n\t})\n\n\tit('work scoped guard', async () => {\n\t\tconst plugin = new Elysia().guard({\n\t\t\tas: 'scoped',\n\t\t\tresolve: () => ({ hi: () => 'hi' })\n\t\t})\n\n\t\tconst app = new Elysia().use(plugin).get('/', ({ hi }) => hi())\n\n\t\tconst root = new Elysia()\n\t\t\t.use(app)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/root', ({ hi }) => hi?.() ?? 'nope')\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('hi')\n\n\t\tconst res2 = await root.handle(req('/root')).then((t) => t.text())\n\t\texpect(res2).toBe('nope')\n\t})\n\n\tit('work global guard', async () => {\n\t\tconst plugin = new Elysia().guard({\n\t\t\tas: 'global',\n\t\t\tresolve: () => ({ hi: () => 'hi' })\n\t\t})\n\n\t\tconst app = new Elysia().use(plugin).get('/', ({ hi }) => hi())\n\n\t\tconst root = new Elysia()\n\t\t\t.use(app)\n\t\t\t.get('/root', ({ hi }) => hi?.() ?? 'nope')\n\n\t\tconst res = await app.handle(req('/')).then((t) => t.text())\n\t\texpect(res).toBe('hi')\n\n\t\tconst res2 = await root.handle(req('/root')).then((t) => t.text())\n\t\texpect(res2).toBe('hi')\n\t})\n\t */\n\n\tit('handle return resolve without throw', async () => {\n\t\tlet isOnErrorCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.onError(() => {\n\t\t\t\tisOnErrorCalled = true\n\t\t\t})\n\t\t\t.resolve(({ status }) => status(418))\n\t\t\t.get('/', () => '')\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(isOnErrorCalled).toBe(false)\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/response.test.ts",
    "content": "import { Elysia, InternalServerError, t } from '../../src'\n\nimport { beforeEach, describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('On After Response', () => {\n\tit('call after response in error', async () => {\n\t\tlet isAfterResponseCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.onAfterResponse(() => {\n\t\t\t\tisAfterResponseCalled = true\n\t\t\t})\n\t\t\t.onError(() => {\n\t\t\t\treturn new Response('a', {\n\t\t\t\t\tstatus: 401,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tawd: 'b'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\t\t// wait for next tick\n\t\tawait Bun.sleep(1)\n\n\t\texpect(isAfterResponseCalled).toBeTrue()\n\t})\n\n\tit('call after response on not found without error handler', async () => {\n\t\tlet isAfterResponseCalled = false\n\n\t\tconst app = new Elysia().onAfterResponse(() => {\n\t\t\tisAfterResponseCalled = true\n\t\t})\n\n\t\tawait app.handle(req('/'))\n\t\t// wait for next tick\n\t\tawait Bun.sleep(1)\n\n\t\texpect(isAfterResponseCalled).toBeTrue()\n\t})\n\n\tit('response in order', async () => {\n\t\tlet order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.onAfterResponse(() => {\n\t\t\t\torder.push('A')\n\t\t\t})\n\t\t\t.onAfterResponse(() => {\n\t\t\t\torder.push('B')\n\t\t\t})\n\t\t\t.get('/', () => '')\n\n\t\tawait app.handle(req('/'))\n\t\t// wait for next tick\n\t\tawait Bun.sleep(1)\n\n\t\texpect(order).toEqual(['A', 'B'])\n\t})\n\n\tit('inherits from plugin', async () => {\n\t\tlet type = ''\n\n\t\tconst afterResponse = new Elysia().onAfterResponse(\n\t\t\t{ as: 'global' },\n\t\t\t({ response }) => {\n\t\t\t\ttype = typeof response\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(afterResponse)\n\t\t\t.get('/id/:id', ({ params: { id } }) => id, {\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tid: t.Number()\n\t\t\t\t})\n\t\t\t})\n\n\t\tawait app.handle(req('/id/1'))\n\n\t\t// wait for next tick\n\t\tawait Bun.sleep(1)\n\n\t\texpect(type).toBe('number')\n\t})\n\n\tit('inherits from plugin using responseValue', async () => {\n\t\tlet type = ''\n\n\t\tconst afterResponse = new Elysia().onAfterResponse(\n\t\t\t{ as: 'global' },\n\t\t\t({ responseValue }) => {\n\t\t\t\ttype = typeof responseValue\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(afterResponse)\n\t\t\t.get('/id/:id', ({ params: { id } }) => id, {\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tid: t.Number()\n\t\t\t\t})\n\t\t\t})\n\n\t\tawait app.handle(req('/id/1'))\n\n\t\t// wait for next tick\n\t\tawait Bun.sleep(1)\n\n\t\texpect(type).toBe('number')\n\t})\n\n\tit('as global', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onAfterResponse({ as: 'global' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tawait Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\t\t// wait for next tick\n\t\tawait Bun.sleep(1)\n\n\t\texpect(called).toEqual(['/inner', '/outer'])\n\t})\n\n\tit('as local', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onAfterResponse({ as: 'local' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tawait Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\t\t// wait for next tick\n\t\tawait Bun.sleep(1)\n\n\t\texpect(called).toEqual(['/inner'])\n\t})\n\n\tit('support array', async () => {\n\t\tlet total = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.onAfterHandle([\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t}\n\t\t\t])\n\t\t\t.get('/', () => 'NOOP')\n\n\t\tconst res = await app.handle(req('/'))\n\t\t// wait for next tick\n\t\tawait Bun.sleep(1)\n\n\t\texpect(total).toEqual(2)\n\t})\n})\n\ndescribe('On After Response Error', () => {\n\tconst newReq = (params?: {\n\t\tpath?: string\n\t\theaders?: Record<string, string>\n\t\tmethod?: string\n\t\tbody?: string\n\t}) => new Request(`http://localhost${params?.path ?? '/'}`, params)\n\n\tclass CustomError extends Error {}\n\n\tlet isOnResponseCalled: boolean\n\tlet onResponseCalledCounter = 0\n\n\tbeforeEach(() => {\n\t\tisOnResponseCalled = false\n\t\tonResponseCalledCounter = 0\n\t})\n\n\tconst app = new Elysia()\n\t\t.onAfterResponse(() => {\n\t\t\tisOnResponseCalled = true\n\t\t\tonResponseCalledCounter++\n\t\t})\n\t\t.post('/', () => 'yay', {\n\t\t\tbody: t.Object({\n\t\t\t\ttest: t.String()\n\t\t\t})\n\t\t})\n\t\t.get('/customError', () => {\n\t\t\tthrow new CustomError('whelp')\n\t\t})\n\t\t.get('/internalError', () => {\n\t\t\tthrow new InternalServerError('whelp')\n\t\t})\n\n\tit.each([\n\t\t['NotFoundError', newReq({ path: '/notFound' })],\n\t\t[\n\t\t\t'ParseError',\n\t\t\tnewReq({\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\tbody: ''\n\t\t\t})\n\t\t],\n\t\t[\n\t\t\t'ValidationError',\n\t\t\tnewReq({\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\tbody: JSON.stringify({})\n\t\t\t})\n\t\t],\n\t\t['CustomError', newReq({ path: '/customError' })],\n\t\t['InternalServerError', newReq({ path: '/internalError' })]\n\t])('%s should call onResponse', async (_name, request) => {\n\t\texpect(isOnResponseCalled).toBeFalse()\n\n\t\tawait app.handle(request)\n\n\t\t// wait for next tick\n\t\tawait Bun.sleep(1)\n\n\t\texpect(isOnResponseCalled).toBeTrue()\n\t\texpect(onResponseCalledCounter).toBe(1)\n\t})\n\n\tit.each([\n\t\t{ aot: true, withOnError: true },\n\t\t{ aot: true, withOnError: false },\n\n\t\t{ aot: false, withOnError: true },\n\t\t{ aot: false, withOnError: false }\n\t])(\n\t\t'should execute onAfterResponse once during NotFoundError aot=$aot,\\twithOnError=$withOnError',\n\t\tasync ({ aot, withOnError }) => {\n\t\t\tlet counter = 0\n\n\t\t\tconst app = new Elysia({ aot }).onAfterResponse(() => {\n\t\t\t\tcounter++\n\t\t\t})\n\n\t\t\tif (withOnError) app.onError(() => {})\n\n\t\t\tconst req = new Request('http://localhost/notFound')\n\t\t\tawait app.handle(req)\n\t\t\tawait Bun.sleep(1)\n\n\t\t\texpect(counter).toBe(1)\n\t\t}\n\t)\n\n\tit.each([\n\t\t{ aot: true, onErrorReturnsValue: \"error handled\" },\n\t\t{ aot: false, onErrorReturnsValue: \"error handled\" },\n\n\t\t{ aot: true, onErrorReturnsValue: { message: \"error handled\" } },\n\t\t{ aot: false, onErrorReturnsValue: { message: \"error handled\" } },\n\t])('should execute onAfterResponse when onError returns a value aot=$aot,\\tonErrorReturnsValue=$onErrorReturnsValue', async ({ aot, onErrorReturnsValue }) => {\n\t\tlet counter = 0\n\n\t\tconst app = new Elysia({ aot })\n\t\t\t.onError(() => {\n\t\t\t\treturn onErrorReturnsValue\n\t\t\t})\n\t\t\t.onAfterResponse(() => {\n\t\t\t\tcounter++\n\t\t\t})\n\t\t\t.get('/error', () => {\n\t\t\t\tthrow new Error('test error')\n\t\t\t})\n\n\t\texpect(counter).toBe(0)\n\n\t\tconst req = new Request('http://localhost/error')\n\t\tconst res = await app.handle(req)\n\t\tconst text = await res.text()\n\n\t\texpect(text).toStrictEqual(\n\t\t\ttypeof onErrorReturnsValue === 'string'\n\t\t\t\t? onErrorReturnsValue\n\t\t\t\t: JSON.stringify(onErrorReturnsValue)\n\t\t)\n\n\t\tawait Bun.sleep(1)\n\n\t\texpect(counter).toBe(1)\n\t})\n})\n"
  },
  {
    "path": "test/lifecycle/transform.test.ts",
    "content": "import { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('Transform', () => {\n\tit('globally Transform', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onTransform<{\n\t\t\t\tparams: {\n\t\t\t\t\tid: number\n\t\t\t\t} | null\n\t\t\t}>((request) => {\n\t\t\t\tif (request.params?.id) request.params.id = +request.params.id\n\t\t\t})\n\t\t\t.get('/id/:id', ({ params: { id } }) => typeof id)\n\n\t\tconst res = await app.handle(req('/id/1'))\n\n\t\texpect(await res.text()).toBe('number')\n\t})\n\n\tit('locally transform', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/id/:id',\n\t\t\t({ params: { id } }) => typeof id,\n\t\t\t{\n\t\t\t\ttransform: (request) => {\n\t\t\t\t\tif (request.params?.id)\n\t\t\t\t\t\trequest.params.id = +request.params.id\n\t\t\t\t},\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tid: t.Number()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\tconst res = await app.handle(req('/id/1'))\n\n\t\texpect(await res.text()).toBe('number')\n\t})\n\n\tit('group transform', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.group('/scoped/id/:id', (app) =>\n\t\t\t\tapp\n\t\t\t\t\t.onTransform(({ params }) => {\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tif (params.id) params.id = +params.id\n\t\t\t\t\t})\n\t\t\t\t\t.get('', ({ params: { id } }) => typeof id)\n\t\t\t)\n\t\t\t.get('/id/:id', ({ params: { id } }) => typeof id)\n\n\t\tconst base = await app.handle(req('/id/1'))\n\t\tconst scoped = await app.handle(req('/scoped/id/1'))\n\n\t\texpect(await base.text()).toBe('string')\n\t\texpect(await scoped.text()).toBe('number')\n\t})\n\n\tit('transform from plugin', async () => {\n\t\tconst transformId = new Elysia().onTransform<\n\t\t\t{\n\t\t\t\tparams: {\n\t\t\t\t\tid: number\n\t\t\t\t} | null\n\t\t\t},\n\t\t\t'global'\n\t\t>({ as: 'global' }, (request) => {\n\t\t\t// @ts-ignore\n\t\t\tif (request.params?.id) request.params.id = +request.params.id\n\t\t})\n\n\t\tconst app = new Elysia()\n\t\t\t.use(transformId)\n\t\t\t.get('/id/:id', ({ params: { id } }) => typeof id)\n\n\t\tconst res = await app.handle(req('/id/1'))\n\n\t\texpect(await res.text()).toBe('number')\n\t})\n\n\tit('transform from on', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.on('transform', (request) => {\n\t\t\t\tif (request.params?.id) request.params.id = +request.params.id\n\t\t\t})\n\t\t\t.get('/id/:id', ({ params: { id } }) => typeof id)\n\n\t\tconst res = await app.handle(req('/id/1'))\n\n\t\texpect(await res.text()).toBe('number')\n\t})\n\n\tit('transform in order', async () => {\n\t\tlet order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.onTransform(() => {\n\t\t\t\torder.push('A')\n\t\t\t})\n\t\t\t.onTransform(() => {\n\t\t\t\torder.push('B')\n\t\t\t})\n\t\t\t.get('/', () => '')\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(order).toEqual(['A', 'B'])\n\t})\n\n\tit('globally and locally pre handle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onTransform<{\n\t\t\t\tparams: {\n\t\t\t\t\tid: number\n\t\t\t\t} | null\n\t\t\t}>((request) => {\n\t\t\t\tif (request.params?.id) request.params.id = +request.params.id\n\t\t\t})\n\t\t\t.get('/id/:id', ({ params: { id } }) => id, {\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tid: t.Number()\n\t\t\t\t}),\n\t\t\t\ttransform: (request) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\trequest.params?.id &&\n\t\t\t\t\t\ttypeof request.params?.id === 'number'\n\t\t\t\t\t)\n\t\t\t\t\t\trequest.params.id = request.params.id + 1\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/id/1'))\n\n\t\texpect(await res.text()).toBe('2')\n\t})\n\n\tit('accept multiple transform', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onTransform<{\n\t\t\t\tparams: {\n\t\t\t\t\tid: number\n\t\t\t\t} | null\n\t\t\t}>((request) => {\n\t\t\t\tif (request.params?.id) request.params.id = +request.params.id\n\t\t\t})\n\t\t\t.onTransform<{\n\t\t\t\tparams: {\n\t\t\t\t\tid: number\n\t\t\t\t} | null\n\t\t\t}>((request) => {\n\t\t\t\tif (\n\t\t\t\t\trequest.params?.id &&\n\t\t\t\t\ttypeof request.params?.id === 'number'\n\t\t\t\t)\n\t\t\t\t\trequest.params.id = request.params.id + 1\n\t\t\t})\n\t\t\t.get('/id/:id', ({ params: { id } }) => id)\n\n\t\tconst res = await app.handle(req('/id/1'))\n\n\t\texpect(await res.text()).toBe('2')\n\t})\n\n\tit('transform async', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/id/:id',\n\t\t\t({ params: { id } }) => typeof id,\n\t\t\t{\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tid: t.Number()\n\t\t\t\t}),\n\t\t\t\ttransform: async ({ params }) => {\n\t\t\t\t\tawait new Promise<void>((resolve) =>\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tresolve()\n\t\t\t\t\t\t}, 1)\n\t\t\t\t\t)\n\n\t\t\t\t\tif (params?.id) params.id = +params.id\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/id/1'))\n\n\t\texpect(await res.text()).toBe('number')\n\t})\n\n\tit('map returned value', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onTransform<{\n\t\t\t\tparams: {\n\t\t\t\t\tid: number\n\t\t\t\t} | null\n\t\t\t}>((request) => {\n\t\t\t\tif (request.params?.id) request.params.id = +request.params.id\n\t\t\t})\n\t\t\t.get('/id/:id', ({ params: { id } }) => typeof id)\n\n\t\tconst res = await app.handle(req('/id/1'))\n\t\texpect(await res.text()).toBe('number')\n\t})\n\n\tit('validate property', async () => {\n\t\tconst app = new Elysia().get('/id/:id', ({ params: { id } }) => id, {\n\t\t\tparams: t.Object({\n\t\t\t\tid: t.Numeric({ minimum: 0 })\n\t\t\t})\n\t\t})\n\n\t\tconst correct = await app.handle(req('/id/1')).then((x) => x.status)\n\t\texpect(correct).toBe(200)\n\n\t\tconst invalid = await app.handle(req('/id/-1')).then((x) => x.status)\n\t\texpect(invalid).toBe(422)\n\t})\n\n\tit('inherits from plugin', async () => {\n\t\tconst transformId = new Elysia().onTransform<\n\t\t\t{\n\t\t\t\tparams: {\n\t\t\t\t\tname: string\n\t\t\t\t} | null\n\t\t\t},\n\t\t\t'global'\n\t\t>({ as: 'global' }, ({ params }) => {\n\t\t\tif (params?.name === 'Fubuki') params.name = 'Cat'\n\t\t})\n\n\t\tconst app = new Elysia()\n\t\t\t.use(transformId)\n\t\t\t.get('/name/:name', ({ params: { name } }) => name)\n\n\t\tconst res = await app.handle(req('/name/Fubuki'))\n\n\t\texpect(await res.text()).toBe('Cat')\n\t})\n\n\tit('not inherits plugin on local', async () => {\n\t\tconst transformId = new Elysia().onTransform<{\n\t\t\tparams: {\n\t\t\t\tname: string\n\t\t\t} | null\n\t\t}>(({ params }) => {\n\t\t\tif (params?.name === 'Fubuki') params.name = 'Cat'\n\t\t})\n\n\t\tconst app = new Elysia()\n\t\t\t.use(transformId)\n\t\t\t.get('/name/:name', ({ params: { name } }) => name)\n\n\t\tconst res = await app.handle(req('/name/Fubuki'))\n\n\t\texpect(await res.text()).toBe('Fubuki')\n\t})\n\n\tit('global true', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onTransform({ as: 'global' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner', '/outer'])\n\t})\n\n\tit('global false', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onTransform({ as: 'local' }, ({ path }) => {\n\t\t\t\tcalled.push(path)\n\t\t\t})\n\t\t\t.get('/inner', () => 'NOOP')\n\n\t\tconst app = new Elysia().use(plugin).get('/outer', () => 'NOOP')\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/inner')),\n\t\t\tapp.handle(req('/outer'))\n\t\t])\n\n\t\texpect(called).toEqual(['/inner'])\n\t})\n\n\tit('support array', async () => {\n\t\tlet total = 0\n\n\t\tconst app = new Elysia()\n\t\t\t.onTransform([\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\ttotal++\n\t\t\t\t}\n\t\t\t])\n\t\t\t.get('/', () => 'NOOP')\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(total).toEqual(2)\n\t})\n})\n"
  },
  {
    "path": "test/macro/macro.test.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { describe, it, expect } from 'bun:test'\nimport { Elysia, t, status } from '../../src'\nimport { post, req } from '../utils'\n\ndescribe('Macro', () => {\n\tit('trace back', async () => {\n\t\tlet answer: string | undefined\n\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(config: string) {\n\t\t\t\t\tanswer = config\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: 'Hello World'\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(answer).toBe('Hello World')\n\t})\n\n\tit('work', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(beforeHandle: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tbeforeHandle\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => 'Hello World'\n\t\t\t})\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('Hello World')\n\t})\n\n\tit('appends parse', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(fn: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tparse: fn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => {}\n\t\t\t})\n\n\t\texpect(app.router.history[0].hooks.parse?.length).toEqual(1)\n\t})\n\n\tit('appends parse array', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(fn: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tparse: [fn, () => {}]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => {}\n\t\t\t})\n\n\t\texpect(app.router.history[0].hooks.parse?.length).toEqual(2)\n\t})\n\n\tit('appends transform', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(fn: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttransform: fn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => {}\n\t\t\t})\n\n\t\texpect(app.router.history[0].hooks.transform?.length).toEqual(1)\n\t})\n\n\tit('appends transform array', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(fn: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttransform: [fn, () => {}]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => {}\n\t\t\t})\n\n\t\texpect(app.router.history[0].hooks.transform?.length).toEqual(2)\n\t})\n\n\tit('appends beforeHandle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(fn: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tbeforeHandle: fn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => {}\n\t\t\t})\n\n\t\texpect(app.router.history[0].hooks.beforeHandle?.length).toEqual(1)\n\t})\n\n\tit('appends beforeHandle array', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(fn: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tbeforeHandle: [fn, () => {}]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => {}\n\t\t\t})\n\n\t\texpect(app.router.history[0].hooks.beforeHandle?.length).toEqual(2)\n\t})\n\n\tit('appends afterHandle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(fn: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tafterHandle: fn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => {}\n\t\t\t})\n\n\t\texpect(app.router.history[0].hooks.afterHandle?.length).toEqual(1)\n\t})\n\n\tit('appends afterHandle array', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(fn: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tafterHandle: [fn, () => {}]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => {}\n\t\t\t})\n\n\t\texpect(app.router.history[0].hooks.afterHandle?.length).toEqual(2)\n\t})\n\n\tit('appends error', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(fn: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: fn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => {}\n\t\t\t})\n\n\t\texpect(app.router.history[0].hooks.error?.length).toEqual(1)\n\t})\n\n\tit('appends error array', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(fn: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: [fn, () => {}]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => {}\n\t\t\t})\n\n\t\texpect(app.router.history[0].hooks.error?.length).toEqual(2)\n\t})\n\n\tit('appends afterResponse', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(fn: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tafterResponse: fn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => {}\n\t\t\t})\n\n\t\texpect(app.router.history[0].hooks.afterResponse?.length).toEqual(1)\n\t})\n\n\tit('appends afterResponse array', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\thi(fn: () => any) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tafterResponse: [fn, () => {}]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: () => {}\n\t\t\t})\n\n\t\texpect(app.router.history[0].hooks.afterResponse?.length).toEqual(2)\n\t})\n\n\tit('handle deduplication', async () => {\n\t\tlet call = 0\n\n\t\tconst a = new Elysia({ name: 'a', seed: 'awdawd' }).macro({\n\t\t\ta: {\n\t\t\t\tbeforeHandle() {\n\t\t\t\t\tcall++\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tconst b = new Elysia({ name: 'b', seed: 'add' })\n\t\t\t.use(a)\n\t\t\t.decorate('b', 'b')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(a)\n\t\t\t.use(b)\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\ta: true\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(call).toBe(1)\n\t})\n\n\tit('propagate macro without inaccurate deduplication in guard', async () => {\n\t\tlet call = 0\n\n\t\tconst base = new Elysia({ name: 'base' }).macro({\n\t\t\tauth(role: 'teacher' | 'student' | 'admin' | 'noLogin') {\n\t\t\t\treturn {\n\t\t\t\t\tbeforeHandle() {\n\t\t\t\t\t\tcall++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tconst app = new Elysia()\n\t\t\t// ? Deduplication check\n\t\t\t.use(base)\n\t\t\t.use(base)\n\t\t\t.use(base)\n\t\t\t.use(base)\n\t\t\t.guard({ auth: 'admin' }, (route) =>\n\t\t\t\troute\n\t\t\t\t\t.get('/test1', () => 'test1')\n\t\t\t\t\t.get('/test2', () => 'test2')\n\t\t\t\t\t.get('/test3', () => 'hello test3')\n\t\t\t)\n\t\t\t.get('/hello', () => 'hello', { auth: 'teacher' })\n\n\t\tawait Promise.all(\n\t\t\t['/test1', '/test2', '/test3'].map((x) => app.handle(req(x)))\n\t\t)\n\n\t\texpect(call).toBe(3)\n\t})\n\n\tit('inherits macro from plugin without name', async () => {\n\t\tlet called = 0\n\n\t\tconst plugin = new Elysia().macro({\n\t\t\thi(_: string) {\n\t\t\t\tcalled++\n\t\t\t}\n\t\t})\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.use(plugin)\n\t\t\t.use(plugin)\n\t\t\t.get('/', () => 'Hello World', {\n\t\t\t\thi: 'Hello World'\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(called).toBe(1)\n\t})\n\n\tit('handle macro from plugin', async () => {\n\t\tconst authGuard = new Elysia().macro({\n\t\t\trequiredUser(value: boolean) {\n\t\t\t\treturn {\n\t\t\t\t\tbeforeHandle: async () => {\n\t\t\t\t\t\tif (value)\n\t\t\t\t\t\t\treturn status(401, {\n\t\t\t\t\t\t\t\tcode: 'S000002',\n\t\t\t\t\t\t\t\tmessage: 'Unauthorized'\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tconst testRoute = new Elysia({\n\t\t\tprefix: '/test',\n\t\t\tname: 'testRoute'\n\t\t})\n\t\t\t.use(authGuard)\n\t\t\t.guard({\n\t\t\t\trequiredUser: true\n\t\t\t})\n\t\t\t.get('/', () => 'Ely')\n\n\t\tconst app = new Elysia().use(testRoute).get('/', () => 'Ely')\n\n\t\tconst ok = await app.handle(req('/')).then((t) => t.text())\n\t\tconst err = await app.handle(req('/test')).then((t) => t.text())\n\n\t\texpect(ok).toBe('Ely')\n\t\texpect(err).not.toBe('Ely')\n\t\texpect(err).not.toBe('NOT_FOUND')\n\t})\n\n\tit(\"don't duplicate call on as plugin\", async () => {\n\t\tlet called = 0\n\n\t\tconst plugin = new Elysia()\n\t\t\t.macro({\n\t\t\t\tcount(_: boolean) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tbeforeHandle(ctx) {\n\t\t\t\t\t\t\tcalled++\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => 'hi', {\n\t\t\t\tcount: true\n\t\t\t})\n\n\t\tconst app = new Elysia().use(plugin).get('/foo', () => 'foo', {\n\t\t\tcount: true\n\t\t})\n\n\t\tawait app.handle(req('/'))\n\t})\n\n\tit('inherits macro in group', async () => {\n\t\tconst authGuard = new Elysia().macro({\n\t\t\tisAuth(shouldAuth: boolean) {\n\t\t\t\tif (shouldAuth)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tbeforeHandle({ cookie: { session }, status }) {\n\t\t\t\t\t\t\tif (!session.value) return status(418)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tconst app = new Elysia().use(authGuard).group('/posts', (app) =>\n\t\t\tapp.get('/', () => 'a', {\n\t\t\t\tisAuth: true\n\t\t\t})\n\t\t)\n\n\t\tconst status = await app.handle(req('/posts')).then((x) => x.status)\n\n\t\texpect(status).toBe(418)\n\t})\n\n\tit('inherits macro in guard', async () => {\n\t\tconst authGuard = new Elysia().macro({\n\t\t\tisAuth(shouldAuth: boolean) {\n\t\t\t\tif (shouldAuth)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tbeforeHandle({ cookie: { session }, status }) {\n\t\t\t\t\t\t\tif (!session.value) return status(418)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tconst app = new Elysia().use(authGuard).guard({}, (app) =>\n\t\t\tapp.get('/posts', () => 'a', {\n\t\t\t\tisAuth: true\n\t\t\t})\n\t\t)\n\n\t\tconst status = await app.handle(req('/posts')).then((x) => x.status)\n\n\t\texpect(status).toBe(418)\n\t})\n\n\tit('inherits macro from plugin', async () => {\n\t\tconst authGuard = new Elysia().macro({\n\t\t\tisAuth(shouldAuth: boolean) {\n\t\t\t\tif (shouldAuth)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tbeforeHandle({ cookie: { session }, status }) {\n\t\t\t\t\t\t\tif (!session.value) return status(418)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tconst app = new Elysia().use(authGuard).use((app) =>\n\t\t\tapp.get('/posts', () => 'a', {\n\t\t\t\tisAuth: true\n\t\t\t})\n\t\t)\n\n\t\tconst status = await app.handle(req('/posts')).then((x) => x.status)\n\n\t\texpect(status).toBe(418)\n\t})\n\n\tit(\"don't inherits macro to plugin without type reference\", () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst plugin = new Elysia().get('/hello', () => 'hello', {\n\t\t\t// @ts-ignore\n\t\t\thello: 'nagisa'\n\t\t})\n\n\t\tnew Elysia()\n\t\t\t.macro({\n\t\t\t\thello(a: string) {\n\t\t\t\t\tcalled.push(a)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.use(plugin)\n\t\t\t.get('/', () => 'a', {\n\t\t\t\thello: 'hifumi'\n\t\t\t})\n\n\t\texpect(called).toEqual(['nagisa', 'hifumi'])\n\t})\n\n\tit(\"don't duplicate macro call\", async () => {\n\t\tlet registered = 0\n\t\tlet called = 0\n\n\t\tconst a = new Elysia({ name: 'a' }).macro({\n\t\t\tisSignIn() {\n\t\t\t\tregistered++\n\n\t\t\t\treturn {\n\t\t\t\t\tbeforeHandle() {\n\t\t\t\t\t\tcalled++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tconst b = new Elysia({ name: 'b' }).use(a)\n\t\tconst c = new Elysia().use(b).get('/', () => 'ok', {\n\t\t\tisSignIn: true\n\t\t})\n\n\t\tconst app = new Elysia().use(c)\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(registered).toBe(1)\n\t\texpect(called).toBe(1)\n\t})\n\n\tit('accept resolve', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tuser: (enabled: boolean) => ({\n\t\t\t\t\tresolve: ({ query: { name = 'anon' } }) => ({\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\tname\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', ({ user }) => user, {\n\t\t\t\tuser: true\n\t\t\t})\n\n\t\tconst [a, b] = await Promise.all([\n\t\t\tapp.handle(req('/')).then((x) => x.json()),\n\t\t\tapp.handle(req('/?name=hoshino')).then((x) => x.json())\n\t\t])\n\n\t\texpect(a).toEqual({ name: 'anon' })\n\t\texpect(b).toEqual({ name: 'hoshino' })\n\t})\n\n\tit('accept async resolve', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tuser: (enabled: boolean) => ({\n\t\t\t\t\tresolve: async ({ query: { name = 'anon' } }) => ({\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\tname\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', ({ user }) => user, {\n\t\t\t\tuser: true\n\t\t\t})\n\n\t\tconst [a, b] = await Promise.all([\n\t\t\tapp.handle(req('/')).then((x) => x.json()),\n\t\t\tapp.handle(req('/?name=hoshino')).then((x) => x.json())\n\t\t])\n\n\t\texpect(a).toEqual({ name: 'anon' })\n\t\texpect(b).toEqual({ name: 'hoshino' })\n\t})\n\n\tit('guard handle resolve macro', async () => {\n\t\tconst plugin = new Elysia()\n\t\t\t.macro({\n\t\t\t\taccount: (a: boolean) => ({\n\t\t\t\t\tresolve: () => ({\n\t\t\t\t\t\taccount: 'A'\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\taccount: true\n\t\t\t})\n\t\t\t.get('/local', ({ account }) => account === 'A')\n\n\t\tconst parent = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.get('/plugin', (context) => !('account' in context))\n\n\t\tconst app = new Elysia()\n\t\t\t.use(parent)\n\t\t\t.get('/global', (context) => !('account' in context))\n\n\t\texpect(\n\t\t\tawait Promise.all(\n\t\t\t\t['/local', '/plugin', '/global'].map((path) =>\n\t\t\t\t\tapp\n\t\t\t\t\t\t.handle(req(path))\n\t\t\t\t\t\t.then((x) => x.text())\n\t\t\t\t\t\t.then((x) => x === 'true')\n\t\t\t\t)\n\t\t\t)\n\t\t).toEqual([true, true, true])\n\t})\n\n\tit('guard handle resolve macro with scoped', async () => {\n\t\tconst plugin = new Elysia()\n\t\t\t.macro({\n\t\t\t\taccount: (a: boolean) => ({\n\t\t\t\t\tresolve: () => ({\n\t\t\t\t\t\taccount: 'A'\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\taccount: true\n\t\t\t})\n\t\t\t.get('/local', ({ account }) => account === 'A')\n\n\t\tconst parent = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.get('/plugin', ({ account }) => account === 'A')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(parent)\n\t\t\t.get('/global', (context) => !('account' in context))\n\n\t\texpect(\n\t\t\tawait Promise.all(\n\t\t\t\t['/local', '/plugin', '/global'].map((path) =>\n\t\t\t\t\tapp\n\t\t\t\t\t\t.handle(req(path))\n\t\t\t\t\t\t.then((x) => x.text())\n\t\t\t\t\t\t.then((x) => x === 'true')\n\t\t\t\t)\n\t\t\t)\n\t\t).toEqual([true, true, true])\n\t})\n\n\tit('guard handle resolve macro with global', async () => {\n\t\tconst plugin = new Elysia()\n\t\t\t.macro({\n\t\t\t\taccount: (a: boolean) => ({\n\t\t\t\t\tresolve: () => ({\n\t\t\t\t\t\taccount: 'A'\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\taccount: true\n\t\t\t})\n\t\t\t.get('/local', ({ account }) => account === 'A')\n\n\t\tconst parent = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.get('/plugin', ({ account }) => account === 'A')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(parent)\n\t\t\t.get('/global', ({ account }) => account === 'A')\n\n\t\texpect(\n\t\t\tawait Promise.all(\n\t\t\t\t['/local', '/plugin', '/global'].map((path) =>\n\t\t\t\t\tapp\n\t\t\t\t\t\t.handle(req(path))\n\t\t\t\t\t\t.then((x) => x.text())\n\t\t\t\t\t\t.then((x) => x === 'true')\n\t\t\t\t)\n\t\t\t)\n\t\t).toEqual([true, true, true])\n\t})\n\n\tit('guard handle resolve macro with local', async () => {\n\t\tconst plugin = new Elysia()\n\t\t\t.macro({\n\t\t\t\taccount: (a: boolean) => ({\n\t\t\t\t\tresolve: () => ({\n\t\t\t\t\t\taccount: 'A'\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tas: 'local',\n\t\t\t\taccount: true\n\t\t\t})\n\t\t\t.get('/local', ({ account }) => account === 'A')\n\n\t\tconst parent = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.get('/plugin', (context) => !('account' in context))\n\n\t\tconst app = new Elysia()\n\t\t\t.use(parent)\n\t\t\t.get('/global', (context) => !('account' in context))\n\n\t\texpect(\n\t\t\tawait Promise.all(\n\t\t\t\t['/local', '/plugin', '/global'].map((path) =>\n\t\t\t\t\tapp\n\t\t\t\t\t\t.handle(req(path))\n\t\t\t\t\t\t.then((x) => x.text())\n\t\t\t\t\t\t.then((x) => x === 'true')\n\t\t\t\t)\n\t\t\t)\n\t\t).toEqual([true, true, true])\n\t})\n\n\tit('guard handle resolve macro with error', async () => {\n\t\tconst plugin = new Elysia()\n\t\t\t.macro({\n\t\t\t\taccount: (a: boolean) => ({\n\t\t\t\t\tresolve: () => {\n\t\t\t\t\t\tif (Math.random() > 2) return status(401)\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\taccount: 'A'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\taccount: true\n\t\t\t})\n\t\t\t.get('/local', ({ account }) => account === 'A')\n\n\t\tconst parent = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.get('/plugin', (context) => !('account' in context))\n\n\t\tconst app = new Elysia()\n\t\t\t.use(parent)\n\t\t\t.get('/global', (context) => !('account' in context))\n\n\t\texpect(\n\t\t\tawait Promise.all(\n\t\t\t\t['/local', '/plugin', '/global'].map((path) =>\n\t\t\t\t\tapp\n\t\t\t\t\t\t.handle(req(path))\n\t\t\t\t\t\t.then((x) => x.text())\n\t\t\t\t\t\t.then((x) => x === 'true')\n\t\t\t\t)\n\t\t\t)\n\t\t).toEqual([true, true, true])\n\t})\n\n\tit('guard handle resolve macro with async', async () => {\n\t\tconst plugin = new Elysia()\n\t\t\t.macro({\n\t\t\t\taccount: (a: boolean) => ({\n\t\t\t\t\tresolve: async () => {\n\t\t\t\t\t\tif (Math.random() > 2) return status(401)\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\taccount: 'A'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\taccount: true\n\t\t\t})\n\t\t\t.get('/local', ({ account }) => account === 'A')\n\n\t\tconst parent = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.get('/plugin', ({ account }) => account === 'A')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(parent)\n\t\t\t.get('/global', (context) => !('account' in context))\n\n\t\texpect(\n\t\t\tawait Promise.all(\n\t\t\t\t['/local', '/plugin', '/global'].map((path) =>\n\t\t\t\t\tapp\n\t\t\t\t\t\t.handle(req(path))\n\t\t\t\t\t\t.then((x) => x.text())\n\t\t\t\t\t\t.then((x) => x === 'true')\n\t\t\t\t)\n\t\t\t)\n\t\t).toEqual([true, true, true])\n\t})\n\n\t// It may look duplicate to the test case above, but it occurs for some reason\n\tit('handle macro resolve', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tuser: (enabled: true) => ({\n\t\t\t\t\tresolve() {\n\t\t\t\t\t\tif (!enabled) return\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tuser: 'a'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/',\n\t\t\t\t({ user, status }) => {\n\t\t\t\t\tif (!user) return status(401)\n\n\t\t\t\t\treturn { hello: 'hanabi' }\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tuser: true\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\thello: 'hanabi'\n\t\t})\n\t})\n\n\tit('handle function macro shorthand property', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tuser: {\n\t\t\t\t\tresolve: ({ query: { name = 'anon' } }) => ({\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\tname\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', ({ user }) => user, {\n\t\t\t\tuser: true\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/no-macro', (context) => context?.user ?? { name: 'none' }, {\n\t\t\t\tuser: false\n\t\t\t})\n\n\t\tconst [a, b, c, d] = await Promise.all([\n\t\t\tapp.handle(req('/')).then((x) => x.json()),\n\t\t\tapp.handle(req('/?name=hoshino')).then((x) => x.json()),\n\t\t\tapp.handle(req('/no-macro')).then((x) => x.json()),\n\t\t\tapp.handle(req('/no-macro?name=hoshino')).then((x) => x.json())\n\t\t])\n\n\t\texpect(a).toEqual({ name: 'anon' })\n\t\texpect(b).toEqual({ name: 'hoshino' })\n\t\texpect(c).toEqual({ name: 'none' })\n\t\texpect(d).toEqual({ name: 'none' })\n\t})\n\n\tit('handle multiple macros in a route handler', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\ta: {\n\t\t\t\t\tresolve: () => ({ a: 'a' as const })\n\t\t\t\t},\n\t\t\t\tb: {\n\t\t\t\t\tresolve: () => ({ b: 'b' as const })\n\t\t\t\t},\n\t\t\t\tc: (n: number) => ({\n\t\t\t\t\tresolve: () => ({ c: n })\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/a', ({ a }) => ({ a }), {\n\t\t\t\ta: true,\n\t\t\t\tresponse: t.Object({ a: t.Literal('a') })\n\t\t\t})\n\t\t\t.get('/b', ({ b }) => ({ b }), {\n\t\t\t\tb: true,\n\t\t\t\tresponse: t.Object({ b: t.Literal('b') })\n\t\t\t})\n\t\t\t.get('/c', ({ a, b }) => ({ a, b }), {\n\t\t\t\ta: true,\n\t\t\t\tb: true,\n\t\t\t\tresponse: t.Object({ a: t.Literal('a'), b: t.Literal('b') })\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/d',\n\t\t\t\t({\n\t\t\t\t\ta,\n\t\t\t\t\t// @ts-expect-error Property `b` does not exist\n\t\t\t\t\tb\n\t\t\t\t}) => ({ a, b }),\n\t\t\t\t{\n\t\t\t\t\ta: true,\n\t\t\t\t\tb: false,\n\t\t\t\t\tresponse: t.Object({ a: t.Literal('a'), b: t.Undefined() })\n\t\t\t\t}\n\t\t\t)\n\t\t\t.get(\n\t\t\t\t'/e',\n\t\t\t\t({\n\t\t\t\t\t// @ts-expect-error Property `a` does not exist\n\t\t\t\t\ta,\n\t\t\t\t\tb,\n\t\t\t\t\t// @ts-expect-error Property `c` does not exist\n\t\t\t\t\tc\n\t\t\t\t}) => ({ a, b, c }),\n\t\t\t\t{\n\t\t\t\t\tb: true,\n\t\t\t\t\tc: 10,\n\t\t\t\t\tresponse: t.Object({\n\t\t\t\t\t\ta: t.Undefined(),\n\t\t\t\t\t\tb: t.Literal('b'),\n\t\t\t\t\t\tc: t.Number()\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst [a, b, c, d, e] = await Promise.all([\n\t\t\tapp.handle(req('/a')).then((x) => x.json()),\n\t\t\tapp.handle(req('/b')).then((x) => x.json()),\n\t\t\tapp.handle(req('/c')).then((x) => x.json()),\n\t\t\tapp.handle(req('/d')).then((x) => x.json()),\n\t\t\tapp.handle(req('/e')).then((x) => x.json())\n\t\t])\n\n\t\texpect(a).toEqual({ a: 'a' })\n\t\texpect(b).toEqual({ b: 'b' })\n\t\texpect(c).toEqual({ a: 'a', b: 'b' })\n\t\texpect(d).toEqual({ a: 'a', b: undefined })\n\t\texpect(e).toEqual({ a: undefined, b: 'b', c: 10 })\n\t})\n\n\tit('validate', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tsartre: {\n\t\t\t\t\tparams: t.Object({ sartre: t.Literal('Sartre') })\n\t\t\t\t},\n\t\t\t\tfocou: {\n\t\t\t\t\tquery: t.Object({ focou: t.Literal('Focou') })\n\t\t\t\t},\n\t\t\t\tlilith: {\n\t\t\t\t\tbody: t.Object({ lilith: t.Literal('Lilith') })\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/:sartre', ({ body }) => body, {\n\t\t\t\tsartre: true,\n\t\t\t\tfocou: true,\n\t\t\t\tlilith: true\n\t\t\t})\n\n\t\texpect(app.routes[0].hooks.standaloneValidator.length).toBe(1)\n\n\t\tconst valid = await app.handle(\n\t\t\tpost('/Sartre?focou=Focou', {\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(valid.status).toBe(200)\n\t\texpect(await valid.json()).toEqual({\n\t\t\tlilith: 'Lilith'\n\t\t})\n\n\t\tconst invalid1 = await app.handle(\n\t\t\tpost('/Sartre?focou=Focou', {\n\t\t\t\tlilith: 'Not Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid1.status).toBe(422)\n\n\t\tconst invalid2 = await app.handle(\n\t\t\tpost('/Not Sartre?focou=Focou', {\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid2.status).toBe(422)\n\n\t\tconst invalid3 = await app.handle(\n\t\t\tpost('/Sartre?focou=Not Focou', {\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid3.status).toBe(422)\n\t})\n\n\tit('merge validation', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tsartre: {\n\t\t\t\t\tbody: t.Object({ sartre: t.Literal('Sartre') })\n\t\t\t\t},\n\t\t\t\tfocou: {\n\t\t\t\t\tbody: t.Object({ focou: t.Literal('Focou') })\n\t\t\t\t},\n\t\t\t\tlilith: {\n\t\t\t\t\tbody: t.Object({ lilith: t.Literal('Lilith') })\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tsartre: true,\n\t\t\t\tfocou: true,\n\t\t\t\tlilith: true\n\t\t\t})\n\n\t\texpect(app.routes[0].hooks.standaloneValidator.length).toBe(3)\n\n\t\tconst response = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tsartre: 'Sartre',\n\t\t\t\tfocou: 'Focou',\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.json()).toEqual({\n\t\t\tsartre: 'Sartre',\n\t\t\tfocou: 'Focou',\n\t\t\tlilith: 'Lilith'\n\t\t})\n\n\t\tconst invalid1 = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tsartre: 'Not Sartre',\n\t\t\t\tfocou: 'Focou',\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid1.status).toBe(422)\n\n\t\tconst invalid2 = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tsartre: 'Sartre',\n\t\t\t\tfocou: 'Not Focou',\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid2.status).toBe(422)\n\n\t\tconst invalid3 = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tsartre: 'Sartre',\n\t\t\t\tfocou: 'Focou',\n\t\t\t\tlilith: 'Not Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid3.status).toBe(422)\n\t})\n\n\tit('extends', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tsartre: {\n\t\t\t\t\tbody: t.Object({ sartre: t.Literal('Sartre') })\n\t\t\t\t},\n\t\t\t\tfocou: {\n\t\t\t\t\tbody: t.Object({ focou: t.Literal('Focou') })\n\t\t\t\t},\n\t\t\t\tlilith: {\n\t\t\t\t\tsartre: true,\n\t\t\t\t\tfocou: true,\n\t\t\t\t\tbody: t.Object({ lilith: t.Literal('Lilith') })\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tlilith: true\n\t\t\t})\n\n\t\texpect(app.routes[0].hooks.standaloneValidator.length).toBe(3)\n\n\t\tconst response = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tsartre: 'Sartre',\n\t\t\t\tfocou: 'Focou',\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.json()).toEqual({\n\t\t\tsartre: 'Sartre',\n\t\t\tfocou: 'Focou',\n\t\t\tlilith: 'Lilith'\n\t\t})\n\n\t\tconst invalid1 = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tsartre: 'Not Sartre',\n\t\t\t\tfocou: 'Focou',\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid1.status).toBe(422)\n\n\t\tconst invalid2 = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tsartre: 'Sartre',\n\t\t\t\tfocou: 'Not Focou',\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid2.status).toBe(422)\n\n\t\tconst invalid3 = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tsartre: 'Sartre',\n\t\t\t\tfocou: 'Focou',\n\t\t\t\tlilith: 'Not Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid3.status).toBe(422)\n\t})\n\n\tit('create detail if not exists', () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tlilith: {\n\t\t\t\t\tdetail: {\n\t\t\t\t\t\tsummary: 'Lilith',\n\t\t\t\t\t\tdescription: 'Lilith description'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tlilith: true\n\t\t\t})\n\n\t\tconst route = app.routes[0]\n\n\t\texpect(route.hooks.detail).toEqual({\n\t\t\tsummary: 'Lilith',\n\t\t\tdescription: 'Lilith description'\n\t\t})\n\t})\n\n\tit('modify detail', () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tlilith: {\n\t\t\t\t\tdetail: {\n\t\t\t\t\t\tsummary: 'Lilith'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tlilith: true,\n\t\t\t\tdetail: {\n\t\t\t\t\tdescription: 'Lilith description'\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst route = app.routes[0]\n\n\t\texpect(route.hooks.detail).toEqual({\n\t\t\tsummary: 'Lilith',\n\t\t\tdescription: 'Lilith description'\n\t\t})\n\t})\n\n\tit('deduplicate static object default', () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tsartre: {\n\t\t\t\t\tbody: t.Object({ sartre: t.Literal('Sartre') })\n\t\t\t\t},\n\t\t\t\tfocou: {\n\t\t\t\t\tsartre: true,\n\t\t\t\t\tbody: t.Object({ focou: t.Literal('Focou') })\n\t\t\t\t},\n\t\t\t\tlilith: {\n\t\t\t\t\tsartre: true,\n\t\t\t\t\tfocou: true,\n\t\t\t\t\tbody: t.Object({ lilith: t.Literal('Lilith') })\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tlilith: true\n\t\t\t})\n\n\t\tconst route = app.routes[0]\n\n\t\texpect(route.hooks.standaloneValidator.length).toBe(3)\n\t})\n\n\tit('deduplicate function macro by default', () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tsartre(enabled: boolean) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tbody: t.Object({ sartre: t.Literal('Sartre') })\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tfocou: {\n\t\t\t\t\tsartre: true,\n\t\t\t\t\tbody: t.Object({ focou: t.Literal('Focou') })\n\t\t\t\t},\n\t\t\t\tlilith: {\n\t\t\t\t\tsartre: true,\n\t\t\t\t\tfocou: true,\n\t\t\t\t\tbody: t.Object({ lilith: t.Literal('Lilith') })\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tlilith: true,\n\t\t\t\tsartre: false\n\t\t\t})\n\n\t\tconst route = app.routes[0]\n\n\t\t// This is 4 because\n\t\t// 1. lilith\n\t\t// 2. focou\n\t\t// 3. sartre from focou\n\t\t// 4. sartre with false flag\n\t\texpect(route.hooks.standaloneValidator.length).toBe(4)\n\t})\n\n\tit('deduplicate function macro when argument is similar', () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tsartre(enabled: boolean) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tbody: t.Object({ sartre: t.Literal('Sartre') })\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tfocou: {\n\t\t\t\t\tsartre: true,\n\t\t\t\t\tbody: t.Object({ focou: t.Literal('Focou') })\n\t\t\t\t},\n\t\t\t\tlilith: {\n\t\t\t\t\tsartre: true,\n\t\t\t\t\tfocou: true,\n\t\t\t\t\tbody: t.Object({ lilith: t.Literal('Lilith') })\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tlilith: true,\n\t\t\t\tsartre: true\n\t\t\t})\n\n\t\tconst route = app.routes[0]\n\n\t\t// This is 4 because\n\t\t// 1. lilith\n\t\t// 2. focou\n\t\t// 3. sartre from focou\n\t\texpect(route.hooks.standaloneValidator.length).toBe(3)\n\t})\n\n\tit('deduplicate programmatically', () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro({\n\t\t\t\tsartre(tag: string) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tseed: tag,\n\t\t\t\t\t\tbody: t.Object({ sartre: t.Literal('Sartre') }),\n\t\t\t\t\t\tdetail: {\n\t\t\t\t\t\t\ttags: [tag]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tfocou: {\n\t\t\t\t\tsartre: 'npc',\n\t\t\t\t\tbody: t.Object({ focou: t.Literal('Focou') })\n\t\t\t\t},\n\t\t\t\tlilith: {\n\t\t\t\t\tsartre: 'philosopher',\n\t\t\t\t\tfocou: true,\n\t\t\t\t\tbody: t.Object({ lilith: t.Literal('Lilith') })\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tlilith: true\n\t\t\t})\n\n\t\tconst route = app.routes[0]\n\n\t\texpect(route.hooks.standaloneValidator.length).toBe(4)\n\t\texpect(route.hooks.detail).toEqual({\n\t\t\ttags: ['philosopher', 'npc']\n\t\t})\n\t})\n\n\tit('handle macro name', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro('sartre', {\n\t\t\t\tparams: t.Object({ sartre: t.Literal('Sartre') })\n\t\t\t})\n\t\t\t.macro({\n\t\t\t\tfocou: {\n\t\t\t\t\tquery: t.Object({ focou: t.Literal('Focou') })\n\t\t\t\t},\n\t\t\t\tlilith: {\n\t\t\t\t\tbody: t.Object({ lilith: t.Literal('Lilith') })\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/:sartre', ({ body }) => body, {\n\t\t\t\tsartre: true,\n\t\t\t\tfocou: true,\n\t\t\t\tlilith: true\n\t\t\t})\n\n\t\texpect(app.routes[0].hooks.standaloneValidator.length).toBe(1)\n\n\t\tconst valid = await app.handle(\n\t\t\tpost('/Sartre?focou=Focou', {\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(valid.status).toBe(200)\n\t\texpect(await valid.json()).toEqual({\n\t\t\tlilith: 'Lilith'\n\t\t})\n\n\t\tconst invalid1 = await app.handle(\n\t\t\tpost('/Sartre?focou=Focou', {\n\t\t\t\tlilith: 'Not Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid1.status).toBe(422)\n\n\t\tconst invalid2 = await app.handle(\n\t\t\tpost('/Not Sartre?focou=Focou', {\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid2.status).toBe(422)\n\n\t\tconst invalid3 = await app.handle(\n\t\t\tpost('/Sartre?focou=Not Focou', {\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid3.status).toBe(422)\n\t})\n\n\tit('handle macro name with function', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro('sartre', (_: boolean) => ({\n\t\t\t\tparams: t.Object({ sartre: t.Literal('Sartre') })\n\t\t\t}))\n\t\t\t.macro({\n\t\t\t\tfocou: {\n\t\t\t\t\tquery: t.Object({ focou: t.Literal('Focou') })\n\t\t\t\t},\n\t\t\t\tlilith: {\n\t\t\t\t\tbody: t.Object({ lilith: t.Literal('Lilith') })\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/:sartre', ({ body }) => body, {\n\t\t\t\tsartre: true,\n\t\t\t\tfocou: true,\n\t\t\t\tlilith: true\n\t\t\t})\n\n\t\texpect(app.routes[0].hooks.standaloneValidator.length).toBe(1)\n\n\t\tconst valid = await app.handle(\n\t\t\tpost('/Sartre?focou=Focou', {\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(valid.status).toBe(200)\n\t\texpect(await valid.json()).toEqual({\n\t\t\tlilith: 'Lilith'\n\t\t})\n\n\t\tconst invalid1 = await app.handle(\n\t\t\tpost('/Sartre?focou=Focou', {\n\t\t\t\tlilith: 'Not Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid1.status).toBe(422)\n\n\t\tconst invalid2 = await app.handle(\n\t\t\tpost('/Not Sartre?focou=Focou', {\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid2.status).toBe(422)\n\n\t\tconst invalid3 = await app.handle(\n\t\t\tpost('/Sartre?focou=Not Focou', {\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid3.status).toBe(422)\n\t})\n\n\tit('handle macro name extends', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.macro('sartre', {\n\t\t\t\tbody: t.Object({ sartre: t.Literal('Sartre') })\n\t\t\t})\n\t\t\t.macro({\n\t\t\t\tfocou: {\n\t\t\t\t\tsartre: true,\n\t\t\t\t\tbody: t.Object({ focou: t.Literal('Focou') })\n\t\t\t\t},\n\t\t\t\tlilith: {\n\t\t\t\t\tfocou: true,\n\t\t\t\t\tbody: t.Object({ lilith: t.Literal('Lilith') })\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tlilith: true\n\t\t\t})\n\n\t\texpect(app.routes[0].hooks.standaloneValidator.length).toBe(3)\n\n\t\tconst response = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tsartre: 'Sartre',\n\t\t\t\tfocou: 'Focou',\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.json()).toEqual({\n\t\t\tsartre: 'Sartre',\n\t\t\tfocou: 'Focou',\n\t\t\tlilith: 'Lilith'\n\t\t})\n\n\t\tconst invalid1 = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tsartre: 'Not Sartre',\n\t\t\t\tfocou: 'Focou',\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid1.status).toBe(422)\n\n\t\tconst invalid2 = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tsartre: 'Sartre',\n\t\t\t\tfocou: 'Not Focou',\n\t\t\t\tlilith: 'Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid2.status).toBe(422)\n\n\t\tconst invalid3 = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tsartre: 'Sartre',\n\t\t\t\tfocou: 'Focou',\n\t\t\t\tlilith: 'Not Lilith'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid3.status).toBe(422)\n\t})\n})\n"
  },
  {
    "path": "test/modules.ts",
    "content": "import { Elysia } from '../src'\n\nexport const lazy = async (app: Elysia) => app.get('/lazy', () => 'lazy')\n\nexport const lazyInstance = new Elysia().get('/lazy-instance', () => 'lazy-instance')\n\nexport default lazy\n"
  },
  {
    "path": "test/node/.gitignore",
    "content": "node_modules/\r\npackage-lock.json"
  },
  {
    "path": "test/node/cjs/index.js",
    "content": "if ('Bun' in globalThis) {\r\n\tthrow new Error('❌ Use Node.js to run this test!')\r\n}\r\n\r\nsetTimeout(() => {\r\n\tconsole.log('❌ CJS Node.js timed out')\r\n\tprocess.exit(1)\r\n}, 5000)\r\n\r\nconst { Elysia, t } = require('elysia')\r\n\r\nconst app = new Elysia().get('/', () => 'Node.js', {\r\n\tresponse: t.String()\r\n})\r\n\r\nconst main = async () => {\r\n\tconst response = await app.handle(new Request('http://localhost'))\r\n\r\n\tif ((await response.text()) !== 'Node.js') {\r\n\t\tthrow new Error('❌ CommonJS Node.js failed')\r\n\t}\r\n\r\n\tconsole.log('✅ CommonJS Node.js works!')\r\n\r\n\tprocess.exit()\r\n}\r\nmain()\r\n"
  },
  {
    "path": "test/node/cjs/package.json",
    "content": "{\r\n    \"type\": \"commonjs\",\r\n    \"dependencies\": {\r\n        \"elysia\": \"../../..\"\r\n    }\r\n}"
  },
  {
    "path": "test/node/esm/index.js",
    "content": "import { Elysia, t } from 'elysia'\r\n\r\nif ('Bun' in globalThis) {\r\n\tthrow new Error('❌ Use Node.js to run this test!')\r\n}\r\n\r\nsetTimeout(() => {\r\n\tconsole.log('❌ ESM Node.js timed out')\r\n\tprocess.exit(1)\r\n}, 5000)\r\n\r\nconst app = new Elysia().get('/', () => 'Node.js', {\r\n\tresponse: t.String()\r\n})\r\n\r\nconst response = await app.handle(new Request('http://localhost'))\r\n\r\nif ((await response.text()) !== 'Node.js') {\r\n\tthrow new Error('❌ ESM Node.js failed')\r\n}\r\n\r\nconsole.log('✅ ESM Node.js works!')\r\n\r\nprocess.exit()\r\n"
  },
  {
    "path": "test/node/esm/package.json",
    "content": "{\r\n    \"type\": \"module\",\r\n    \"dependencies\": {\r\n        \"elysia\": \"../../..\"\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/path/group.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { Elysia, t } from '../../src'\nimport { post, req } from '../utils'\n\ndescribe('group', () => {\n\tit('delegate onRequest', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/', () => 'A')\n\t\t\t.group('/counter', (app) =>\n\t\t\t\tapp\n\t\t\t\t\t.state('counter', 0)\n\t\t\t\t\t.onRequest(({ store }) => {\n\t\t\t\t\t\tstore.counter++\n\t\t\t\t\t})\n\t\t\t\t\t.get('', ({ store: { counter } }) => counter)\n\t\t\t)\n\n\t\tawait app.handle(req('/'))\n\t\tconst res = await app.handle(req('/counter')).then((r) => r.text())\n\n\t\texpect(res).toBe('2')\n\t})\n\n\tit('decorate group', async () => {\n\t\tconst app = new Elysia().group('/v1', (app) =>\n\t\t\tapp.decorate('a', 'b').get('/', ({ a }) => a)\n\t\t)\n\n\t\tconst res = await app.handle(req('/v1/')).then((x) => x.text())\n\n\t\texpect(res).toBe('b')\n\t})\n\n\tit('validate headers', async () => {\n\t\tconst app = new Elysia().group(\n\t\t\t'/v1',\n\t\t\t{\n\t\t\t\theaders: t.Object({\n\t\t\t\t\tauthorization: t.String()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) => app.get('', () => 'Hello')\n\t\t)\n\n\t\tconst error = await app.handle(req('/v1'))\n\t\tconst correct = await app.handle(\n\t\t\tnew Request('http://localhost/v1', {\n\t\t\t\theaders: {\n\t\t\t\t\tauthorization: 'Bearer'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(error.status).toBe(422)\n\t})\n\n\tit('validate params', async () => {\n\t\tconst app = new Elysia().group(\n\t\t\t'/v1',\n\t\t\t{\n\t\t\t\ttransform({ params }) {\n\t\t\t\t\tif (!+Number.isNaN(params.id)) params.id = +params.id\n\t\t\t\t},\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tid: t.Number()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) => app.get('/id/:id', () => 'Hello')\n\t\t)\n\n\t\tconst error = await app.handle(req('/v1/id/a'))\n\t\tconst correct = await app.handle(req('/v1/id/1'))\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(error.status).toBe(422)\n\t})\n\n\tit('validate query', async () => {\n\t\tconst app = new Elysia().group(\n\t\t\t'/v1',\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) => app.get('', () => 'Hello')\n\t\t)\n\n\t\tconst error = await app.handle(req('/v1?id=1'))\n\t\tconst correct = await app.handle(req('/v1?name=a'))\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(error.status).toBe(422)\n\t})\n\n\tit('validate body', async () => {\n\t\tconst app = new Elysia().group(\n\t\t\t'/v1',\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) => app.post('', ({ body }) => body)\n\t\t)\n\n\t\tconst error = await app.handle(\n\t\t\tpost('/v1', {\n\t\t\t\tid: 'hi'\n\t\t\t})\n\t\t)\n\t\tconst correct = await app.handle(\n\t\t\tpost('/v1', {\n\t\t\t\tname: 'hi'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(error.status).toBe(422)\n\t})\n\n\tit('validate response', async () => {\n\t\tconst app = new Elysia().group(\n\t\t\t'/v1',\n\t\t\t{\n\t\t\t\tresponse: t.String()\n\t\t\t},\n\t\t\t(app) =>\n\t\t\t\t// @ts-ignore\n\t\t\t\tapp\n\t\t\t\t\t.get('/correct', () => 'Hello')\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t.get('/error', () => 1)\n\t\t)\n\n\t\tconst error = await app.handle(req('/v1/error'))\n\t\tconst correct = await app.handle(req('/v1/correct'))\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(error.status).toBe(422)\n\t})\n\n\tit('validate request with prefix', async () => {\n\t\tconst app = new Elysia({ prefix: '/api' }).group('/v1', (app) =>\n\t\t\tapp.get('', () => 'Hello')\n\t\t)\n\n\t\tconst res = await app.handle(req('/api/v1'))\n\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('handle nested prefix with group', () => {\n\t\tconst plugin = new Elysia({ prefix: '/v1' }).group('/course', (app) =>\n\t\t\tapp\n\t\t\t\t.get('', () => '')\n\t\t\t\t.put('/new', () => '')\n\t\t\t\t.group(\n\t\t\t\t\t'/id/:courseId',\n\t\t\t\t\t{\n\t\t\t\t\t\tparams: t.Object({\n\t\t\t\t\t\t\tcourseId: t.Numeric()\n\t\t\t\t\t\t})\n\t\t\t\t\t},\n\t\t\t\t\t(app) =>\n\t\t\t\t\t\tapp.group('/chapter', (app) =>\n\t\t\t\t\t\t\tapp.get(\n\t\t\t\t\t\t\t\t'/hello',\n\t\t\t\t\t\t\t\t({ params: { courseId } }) => courseId\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t)\n\t\t)\n\n\t\tconst app = new Elysia().use(plugin)\n\n\t\texpect(app.router.history.map((x) => x.path)).toEqual([\n\t\t\t'/v1/course',\n\t\t\t'/v1/course/new',\n\t\t\t'/v1/course/id/:courseId/chapter/hello'\n\t\t])\n\t})\n\n\tit(\"skip don't duplicate prefix on group with hooks\", () => {\n\t\tconst a = new Elysia({ prefix: '/course' }).group(\n\t\t\t'/id/:courseId',\n\t\t\t{\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tcourseId: t.Numeric()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) => app.get('/b', () => 'A')\n\t\t)\n\n\t\tconst b = new Elysia({ prefix: '/test' }).group(\n\t\t\t'/id/:courseId',\n\t\t\t(app) => app.get('/b', () => 'A')\n\t\t)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(a)\n\t\t\t.use(b)\n\t\t\t.get('/', () => 'a')\n\n\t\texpect(app.router.history.map((x) => x.path)).toEqual([\n\t\t\t'/course/id/:courseId/b',\n\t\t\t'/test/id/:courseId/b',\n\t\t\t'/'\n\t\t])\n\t})\n\n\tit('inherits singleton / definitions and re-meregd on main', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate({ a: 'a' })\n\t\t\t.state({ a: 'a' })\n\t\t\t.model('a', t.String())\n\t\t\t.error('a', Error)\n\t\t\t.group('/posts', (app) => {\n\t\t\t\t// @ts-expect-error\n\t\t\t\texpect(Object.keys(app.singleton.decorator)).toEqual(['a'])\n\t\t\t\t// @ts-expect-error\n\t\t\t\texpect(Object.keys(app.singleton.store)).toEqual(['a'])\n\t\t\t\t// @ts-expect-error\n\t\t\t\texpect(Object.keys(app.definitions.type)).toEqual(['a'])\n\t\t\t\t// @ts-expect-error\n\t\t\t\texpect(Object.keys(app.definitions.error)).toEqual(['a'])\n\n\t\t\t\treturn app\n\t\t\t\t\t.decorate({ b: 'b' })\n\t\t\t\t\t.state({ b: 'b' })\n\t\t\t\t\t.model('b', t.String())\n\t\t\t\t\t.error('b', Error)\n\t\t\t\t\t.get('/', ({ a }) => a ?? 'Aint no response')\n\t\t\t})\n\n\t\t// @ts-expect-error\n\t\texpect(Object.keys(app.singleton.decorator)).toEqual(['a', 'b'])\n\t\t// @ts-expect-error\n\t\texpect(Object.keys(app.singleton.store)).toEqual(['a', 'b'])\n\t\t// @ts-expect-error\n\t\texpect(Object.keys(app.definitions.type)).toEqual(['a', 'b'])\n\t\t// @ts-expect-error\n\t\texpect(Object.keys(app.definitions.error)).toEqual(['a', 'b'])\n\n\t\tconst response = await app.handle(req('/posts')).then((x) => x.text())\n\n\t\texpect(response).toEqual('a')\n\t})\n\n\tit('cast callback function schema to standaloneValidator', async () => {\n\t\tconst app = new Elysia().group(\n\t\t\t'/group/:id',\n\t\t\t{ params: t.Object({ id: t.Number() }) },\n\t\t\t(app) =>\n\t\t\t\tapp.get('/:name', ({ params }) => params, {\n\t\t\t\t\tparams: t.Object({ name: t.String() })\n\t\t\t\t})\n\t\t)\n\n\t\tconst valid = app.handle(req('/group/1/saltyaom')).then((x) => x.json())\n\t\tconst invalid = app\n\t\t\t.handle(req('/group/a/saltyaom'))\n\t\t\t.then((x) => x.status)\n\n\t\texpect(await valid).toEqual({ id: 1, name: 'saltyaom' })\n\t\texpect(await invalid).toBe(422)\n\t})\n\n\tit('handle multiple nested guard group', async () => {\n\t\tconst app = new Elysia().group('', {}, (app) =>\n\t\t\tapp.group('', {}, (app) =>\n\t\t\t\tapp.get('/', ({ query }) => query, {\n\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\tplaying: t.Boolean(),\n\t\t\t\t\t\tlimit: t.Number()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t)\n\t\t)\n\n\t\tconst value = await app\n\t\t\t.handle(req('/?playing=true&limit=10'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({\n\t\t\tplaying: true,\n\t\t\tlimit: 10\n\t\t})\n\t})\n\n\tit('handle multiple nested guard with schema', async () => {\n\t\tconst app = new Elysia().group(\n\t\t\t'',\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) =>\n\t\t\t\tapp.group(\n\t\t\t\t\t'',\n\t\t\t\t\t{\n\t\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\t\tlimit: t.Number()\n\t\t\t\t\t\t})\n\t\t\t\t\t},\n\t\t\t\t\t(app) =>\n\t\t\t\t\t\tapp.get('/', ({ query }) => query, {\n\t\t\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\t\t\tplaying: t.Boolean()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t})\n\t\t\t\t)\n\t\t)\n\n\t\tconst value = await app\n\t\t\t.handle(req('/?name=lilith&playing=true&limit=10'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({\n\t\t\tname: 'lilith',\n\t\t\tplaying: true,\n\t\t\tlimit: 10\n\t\t})\n\n\t\tconst error = await app\n\t\t\t.handle(req('/?name=lilith&playing=true'))\n\t\t\t.then((x) => x.status)\n\n\t\texpect(error).toBe(422)\n\t})\n})\n"
  },
  {
    "path": "test/path/guard.test.ts",
    "content": "import { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { post, req } from '../utils'\n\ndescribe('guard', () => {\n\tit('inherits global', async () => {\n\t\tconst app = new Elysia().state('counter', 0).guard(\n\t\t\t{\n\t\t\t\ttransform: ({ store }) => {\n\t\t\t\t\tstore.counter++\n\t\t\t\t}\n\t\t\t},\n\t\t\t(app) =>\n\t\t\t\tapp.get('/', ({ store: { counter } }) => counter, {\n\t\t\t\t\ttransform: ({ store }) => {\n\t\t\t\t\t\tstore.counter++\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t)\n\n\t\tconst valid = await app.handle(req('/'))\n\n\t\texpect(await valid.text()).toBe('2')\n\t})\n\n\tit('delegate onRequest', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/', () => 'A')\n\t\t\t.guard({}, (app) =>\n\t\t\t\tapp\n\t\t\t\t\t.state('counter', 0)\n\t\t\t\t\t.onRequest(({ store }) => {\n\t\t\t\t\t\tstore.counter++\n\t\t\t\t\t})\n\t\t\t\t\t.get('/counter', ({ store: { counter } }) => counter)\n\t\t\t)\n\n\t\tawait app.handle(req('/'))\n\t\tconst res = await app.handle(req('/counter')).then((r) => r.text())\n\n\t\texpect(res).toBe('2')\n\t})\n\n\tit('decorate guard', async () => {\n\t\tconst app = new Elysia().guard({}, (app) =>\n\t\t\tapp.decorate('a', 'b').get('/', ({ a }) => a)\n\t\t)\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(res).toBe('b')\n\t})\n\n\tit('validate headers', async () => {\n\t\tconst app = new Elysia().guard(\n\t\t\t{\n\t\t\t\theaders: t.Object({\n\t\t\t\t\tauthorization: t.String()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) => app.get('/', () => 'Hello')\n\t\t)\n\n\t\tconst error = await app.handle(req('/'))\n\t\tconst correct = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\theaders: {\n\t\t\t\t\tauthorization: 'Bearer'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(error.status).toBe(422)\n\t})\n\n\tit('validate params', async () => {\n\t\tconst app = new Elysia().guard(\n\t\t\t{\n\t\t\t\ttransform({ params }) {\n\t\t\t\t\tif (!+Number.isNaN(params.id)) params.id = +params.id\n\t\t\t\t},\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tid: t.Number()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) => app.get('/id/:id', () => 'Hello')\n\t\t)\n\n\t\tconst error = await app.handle(req('/id/a'))\n\t\tconst correct = await app.handle(req('/id/1'))\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(error.status).toBe(422)\n\t})\n\n\tit('validate query', async () => {\n\t\tconst app = new Elysia().guard(\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) => app.get('/', () => 'Hello')\n\t\t)\n\n\t\tconst error = await app.handle(req('/?id=1'))\n\t\tconst correct = await app.handle(req('/?name=a'))\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(error.status).toBe(422)\n\t})\n\n\tit('validate body', async () => {\n\t\tconst app = new Elysia().guard(\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) => app.post('/', ({ body }) => body)\n\t\t)\n\n\t\tconst error = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tid: 'hi'\n\t\t\t})\n\t\t)\n\t\tconst correct = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'hi'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(error.status).toBe(422)\n\t})\n\n\tit('validate response', async () => {\n\t\tconst app = new Elysia().guard(\n\t\t\t{\n\t\t\t\tresponse: t.String()\n\t\t\t},\n\t\t\t(app) =>\n\t\t\t\t// @ts-ignore\n\t\t\t\tapp.get('/correct', () => 'Hello').get('/error', () => 1)\n\t\t)\n\n\t\tconst error = await app.handle(req('/error'))\n\t\tconst correct = await app.handle(req('/correct'))\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(error.status).toBe(422)\n\t})\n\n\tit('apply guard globally', async () => {\n\t\t// @ts-ignore\n\t\tconst app = new Elysia({ precompile: false })\n\t\t\t.guard({\n\t\t\t\tresponse: t.String()\n\t\t\t})\n\t\t\t.get('/correct', () => 'Hello')\n\t\t\t// @ts-expect-error\n\t\t\t.get('/error', () => 1)\n\n\t\tconst error = await app.handle(req('/error'))\n\t\tconst correct = await app.handle(req('/correct'))\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(error.status).toBe(422)\n\t})\n\n\tit('inherits singleton / definitions and re-meregd on main', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.decorate({ a: 'a' })\n\t\t\t.state({ a: 'a' })\n\t\t\t.model('a', t.String())\n\t\t\t.error('a', Error)\n\t\t\t.group('/posts', (app) => {\n\t\t\t\t// @ts-expect-error\n\t\t\t\texpect(Object.keys(app.singleton.decorator)).toEqual(['a'])\n\t\t\t\t// @ts-expect-error\n\t\t\t\texpect(Object.keys(app.singleton.store)).toEqual(['a'])\n\t\t\t\t// @ts-expect-error\n\t\t\t\texpect(Object.keys(app.definitions.type)).toEqual(['a'])\n\t\t\t\t// @ts-expect-error\n\t\t\t\texpect(Object.keys(app.definitions.error)).toEqual(['a'])\n\n\t\t\t\treturn app\n\t\t\t\t\t.decorate({ b: 'b' })\n\t\t\t\t\t.state({ b: 'b' })\n\t\t\t\t\t.model('b', t.String())\n\t\t\t\t\t.error('b', Error)\n\t\t\t\t\t.get('/', ({ a }) => a ?? 'Aint no response')\n\t\t\t})\n\n\t\t// @ts-expect-error\n\t\texpect(Object.keys(app.singleton.decorator)).toEqual(['a', 'b'])\n\t\t// @ts-expect-error\n\t\texpect(Object.keys(app.singleton.store)).toEqual(['a', 'b'])\n\t\t// @ts-expect-error\n\t\texpect(Object.keys(app.definitions.type)).toEqual(['a', 'b'])\n\t\t// @ts-expect-error\n\t\texpect(Object.keys(app.definitions.error)).toEqual(['a', 'b'])\n\n\t\tconst response = await app.handle(req('/posts')).then((x) => x.text())\n\n\t\texpect(response).toEqual('a')\n\t})\n\n\tit('handle as global', async () => {\n\t\tlet called = 0\n\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tresponse: t.Number(),\n\t\t\t\ttransform() {\n\t\t\t\t\tcalled++\n\t\t\t\t}\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/plugin', () => true)\n\n\t\t// @ts-expect-error\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/inner')).then((x) => x.status),\n\t\t\tapp.handle(req('/plugin')).then((x) => x.status),\n\t\t\tapp.handle(req('/')).then((x) => x.status)\n\t\t])\n\n\t\texpect(called).toBe(3)\n\t\texpect(response).toEqual([422, 422, 422])\n\t})\n\n\tit('handle as global with local override', async () => {\n\t\tlet called = 0\n\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tresponse: t.Number(),\n\t\t\t\ttransform() {\n\t\t\t\t\tcalled++\n\t\t\t\t}\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t.guard({\n\t\t\t\tresponse: t.Boolean(),\n\t\t\t\ttransform() {\n\t\t\t\t\tcalled++\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/plugin', () => true)\n\n\t\t// @ts-expect-error\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/inner')).then((x) => x.status),\n\t\t\tapp.handle(req('/plugin')).then((x) => x.status),\n\t\t\tapp.handle(req('/')).then((x) => x.status)\n\t\t])\n\n\t\texpect(called).toBe(4)\n\t\texpect(response).toEqual([422, 200, 422])\n\t})\n\n\tit('handle as global with scoped override', async () => {\n\t\tlet called = 0\n\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tresponse: t.Number(),\n\t\t\t\ttransform() {\n\t\t\t\t\tcalled++\n\t\t\t\t}\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tresponse: t.String(),\n\t\t\t\ttransform() {\n\t\t\t\t\tcalled++\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/plugin', () => 'ok')\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/inner')).then((x) => x.status),\n\t\t\tapp.handle(req('/plugin')).then((x) => x.status),\n\t\t\tapp.handle(req('/')).then((x) => x.status)\n\t\t])\n\n\t\texpect(called).toBe(5)\n\t\texpect(response).toEqual([422, 200, 200])\n\t})\n\n\tit('handle as scoped', async () => {\n\t\tlet called = 0\n\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tresponse: t.Number(),\n\t\t\t\ttransform() {\n\t\t\t\t\tcalled++\n\t\t\t\t}\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/plugin', () => true)\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/inner')).then((x) => x.status),\n\t\t\tapp.handle(req('/plugin')).then((x) => x.status),\n\t\t\tapp.handle(req('/')).then((x) => x.status)\n\t\t])\n\n\t\texpect(called).toBe(2)\n\t\texpect(response).toEqual([422, 422, 200])\n\t})\n\n\tit('handle as local', async () => {\n\t\tlet called = 0\n\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'local',\n\t\t\t\tresponse: t.Number(),\n\t\t\t\ttransform() {\n\t\t\t\t\tcalled++\n\t\t\t\t}\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\n\t\tconst plugin = new Elysia().use(inner).get('/plugin', () => true)\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/inner')).then((x) => x.status),\n\t\t\tapp.handle(req('/plugin')).then((x) => x.status),\n\t\t\tapp.handle(req('/')).then((x) => x.status)\n\t\t])\n\n\t\texpect(called).toBe(1)\n\t\texpect(response).toEqual([422, 200, 200])\n\t})\n\n\tit('only cast guard', async () => {\n\t\tlet called = 0\n\n\t\tconst plugin = new Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tresponse: t.Number(),\n\t\t\t\ttransform() {\n\t\t\t\t\tcalled++\n\t\t\t\t}\n\t\t\t})\n\t\t\t.onTransform(() => {\n\t\t\t\tcalled++\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 1)\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/inner')).then((x) => x.status),\n\t\t\tapp.handle(req('/')).then((x) => x.status)\n\t\t])\n\n\t\texpect(called).toBe(3)\n\t\texpect(response).toEqual([422, 200])\n\t})\n\n\tit('handle merge guard and hook on non-specified responses status', () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: {\n\t\t\t\t\t400: t.String(),\n\t\t\t\t\t500: t.String()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', () => '', {\n\t\t\t\tresponse: t.String()\n\t\t\t})\n\n\t\texpect(Object.keys(app.routes[0].hooks.response)).toEqual([\n\t\t\t'200',\n\t\t\t'400',\n\t\t\t'500'\n\t\t])\n\t})\n\n\tit('cast callback function schema to standaloneValidator', async () => {\n\t\tconst app = new Elysia().guard(\n\t\t\t{ params: t.Object({ id: t.Number() }) },\n\t\t\t(app) =>\n\t\t\t\tapp.get('/guard/:id/:name', ({ params }) => params, {\n\t\t\t\t\tparams: t.Object({ name: t.String() })\n\t\t\t\t})\n\t\t)\n\n\t\tconst valid = app.handle(req('/guard/1/saltyaom')).then((x) => x.json())\n\t\tconst invalid = app\n\t\t\t.handle(req('/guard/a/saltyaom'))\n\t\t\t.then((x) => x.status)\n\n\t\texpect(await valid).toEqual({ id: 1, name: 'saltyaom' })\n\t\texpect(await invalid).toBe(422)\n\t})\n\n\tit('handle multiple nested guard with schema', async () => {\n\t\tconst app = new Elysia().guard(\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) =>\n\t\t\t\tapp.guard(\n\t\t\t\t\t{\n\t\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\t\tlimit: t.Number()\n\t\t\t\t\t\t})\n\t\t\t\t\t},\n\t\t\t\t\t(app) =>\n\t\t\t\t\t\tapp.get('/', ({ query }) => query, {\n\t\t\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\t\t\tplaying: t.Boolean()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t})\n\t\t\t\t)\n\t\t)\n\n\t\tconst value = await app\n\t\t\t.handle(req('/?name=lilith&playing=true&limit=10'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({\n\t\t\tname: 'lilith',\n\t\t\tplaying: true,\n\t\t\tlimit: 10\n\t\t})\n\n\t\tconst error = await app\n\t\t\t.handle(req('/?name=lilith&playing=true'))\n\t\t\t.then((x) => x.status)\n\n\t\texpect(error).toBe(422)\n\t})\n})\n"
  },
  {
    "path": "test/path/path.test.ts",
    "content": "import { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { post, req } from '../utils'\n\ndescribe('Path', () => {\n\tit('handle root', async () => {\n\t\tconst app = new Elysia().get('/', () => 'Hi')\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('Hi')\n\t})\n\n\tit('handle multiple level', async () => {\n\t\tconst app = new Elysia().get('/this/is/my/deep/nested/root', () => 'Ok')\n\t\tconst res = await app.handle(req('/this/is/my/deep/nested/root'))\n\n\t\texpect(await res.text()).toBe('Ok')\n\t})\n\n\tit('return boolean', async () => {\n\t\tconst app = new Elysia().get('/', () => true)\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('true')\n\t})\n\n\tit('return number', async () => {\n\t\tconst app = new Elysia().get('/', () => 617)\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('617')\n\t})\n\n\tit('return json', async () => {\n\t\tconst app = new Elysia().get('/', () => ({\n\t\t\tname: 'takodachi'\n\t\t}))\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(JSON.stringify(await res.json())).toBe(\n\t\t\tJSON.stringify({\n\t\t\t\tname: 'takodachi'\n\t\t\t})\n\t\t)\n\t\texpect(res.headers.get('content-type')).toContain('application/json')\n\t})\n\n\tit('return response', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() =>\n\t\t\t\tnew Response('Shuba Shuba', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tduck: 'shuba duck'\n\t\t\t\t\t},\n\t\t\t\t\tstatus: 418\n\t\t\t\t})\n\t\t)\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('Shuba Shuba')\n\t\texpect(res.status).toBe(418)\n\t\texpect(res.headers.get('duck')).toBe('shuba duck')\n\t})\n\n\tit('parse single param', async () => {\n\t\tconst app = new Elysia().get('/id/:id', ({ params: { id } }) => id)\n\t\tconst res = await app.handle(req('/id/123'))\n\n\t\texpect(await res.text()).toBe('123')\n\t})\n\n\tit('parse multiple params', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/id/:id/:name',\n\t\t\t({ params: { id, name } }) => `${id}/${name}`\n\t\t)\n\t\tconst res = await app.handle(req('/id/fubuki/Elysia'))\n\n\t\texpect(await res.text()).toBe('fubuki/Elysia')\n\t})\n\n\tit('parse optional params', async () => {\n\t\tconst app = new Elysia().get('/id/:id?', ({ params: { id } }) => id)\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/id')).then((x) => x.text()),\n\t\t\tapp.handle(req('/id/fubuki')).then((x) => x.text())\n\t\t])\n\n\t\texpect(res).toEqual(['', 'fubuki'])\n\t})\n\n\tit('parse multiple optional params', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/id/:id?/:name?',\n\t\t\t({ params: { id = '', name = '' } }) => `${id}/${name}`\n\t\t)\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/id')).then((x) => x.text()),\n\t\t\tapp.handle(req('/id/fubuki')).then((x) => x.text()),\n\t\t\tapp.handle(req('/id/fubuki/shirakami')).then((x) => x.text())\n\t\t])\n\n\t\texpect(res).toEqual(['/', 'fubuki/', 'fubuki/shirakami'])\n\t})\n\n\tit('accept wildcard', async () => {\n\t\tconst app = new Elysia().get('/wildcard/*', () => 'Wildcard')\n\n\t\tconst res = await app.handle(req('/wildcard/okayu'))\n\n\t\texpect(await res.text()).toBe('Wildcard')\n\t})\n\n\tit('custom error', async () => {\n\t\tconst app = new Elysia().onError((error) => {\n\t\t\tif (error.code === 'NOT_FOUND')\n\t\t\t\treturn new Response('Not Stonk :(', {\n\t\t\t\t\tstatus: 404\n\t\t\t\t})\n\t\t})\n\n\t\tconst res = await app.handle(req('/wildcard/okayu'))\n\n\t\texpect(await res.text()).toBe('Not Stonk :(')\n\t\texpect(res.status).toBe(404)\n\t})\n\n\tit('parse a querystring', async () => {\n\t\tconst app = new Elysia().get('/', ({ query: { id } }) => id)\n\t\tconst res = await app.handle(req('/?id=123'))\n\n\t\texpect(await res.text()).toBe('123')\n\t})\n\n\tit('parse multiple querystrings', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ query: { first, last } }) => `${last} ${first}`,\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tfirst: t.String(),\n\t\t\t\t\tlast: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\tconst res = await app.handle(req('/?first=Fubuki&last=Shirakami'))\n\n\t\texpect(await res.text()).toBe('Shirakami Fubuki')\n\t})\n\n\tit('parse a querystring with a space', async () => {\n\t\tconst app = new Elysia().get('/', ({ query: { id } }) => id)\n\t\tconst res = await app.handle(req('/?id=test+123%2B'))\n\n\t\texpect(await res.text()).toBe('test 123+')\n\t})\n\n\tit('handle body', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.String()\n\t\t})\n\n\t\tconst body = 'Botan'\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody,\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'text/plain',\n\t\t\t\t\t'content-length': body.length.toString()\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.text()).toBe('Botan')\n\t})\n\n\tit('parse JSON body', async () => {\n\t\tconst body = JSON.stringify({\n\t\t\tname: 'Okayu'\n\t\t})\n\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody,\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/json',\n\t\t\t\t\t'content-length': body.length.toString()\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(JSON.stringify(await res.json())).toBe(body)\n\t})\n\n\tit('parse headers', async () => {\n\t\tconst app = new Elysia().post('/', ({ request }) =>\n\t\t\trequest.headers.get('x-powered-by')\n\t\t)\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'x-powered-by': 'Elysia'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.text()).toBe('Elysia')\n\t})\n\n\tit('handle group', async () => {\n\t\tconst app = new Elysia().group('/gamer', (app) =>\n\t\t\tapp.get('/korone', () => 'Yubi Yubi!')\n\t\t)\n\n\t\tconst res = await app.handle(req('/gamer/korone')).then((r) => r.text())\n\n\t\texpect(await res).toBe('Yubi Yubi!')\n\t})\n\n\tit('handle plugin', async () => {\n\t\tconst plugin = (app: Elysia) => app.get('/korone', () => 'Yubi Yubi!')\n\t\tconst app = new Elysia().use(plugin)\n\n\t\tconst res = await app.handle(req('/korone'))\n\n\t\texpect(await res.text()).toBe('Yubi Yubi!')\n\t})\n\n\tit('handle error', async () => {\n\t\tconst error = 'Pardun?'\n\n\t\tconst plugin = (app: Elysia) =>\n\t\t\tapp.get('/error', () => new Error(error))\n\t\tconst app = new Elysia().use(plugin)\n\n\t\tconst res = await app.handle(req('/error'))\n\t\tconst { message } = (await res.json()) as unknown as {\n\t\t\tmessage: string\n\t\t}\n\n\t\texpect(message).toBe(error)\n\t})\n\n\tit('handle async', async () => {\n\t\tconst app = new Elysia().get('/async', async () => {\n\t\t\tawait new Promise<void>((resolve) =>\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tresolve()\n\t\t\t\t}, 1)\n\t\t\t)\n\n\t\t\treturn 'Hi'\n\t\t})\n\n\t\tconst res = await app.handle(req('/async'))\n\t\texpect(await res.text()).toBe('Hi')\n\t})\n\n\tit('handle absolute path', async () => {\n\t\tconst app = new Elysia().get('/', () => 'Hi')\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('Hi')\n\t})\n\n\tit('handle route which start with same letter', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/aa', () => 'route 1')\n\t\t\t.get('/ab', () => 'route 2')\n\n\t\tconst response = await app.handle(req('/ab'))\n\t\tconst text = await response.text()\n\t\texpect(text).toBe('route 2')\n\t})\n\n\tit('handle route which start with same letter', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/aa', () => 'route 1')\n\t\t\t.get('/ab', () => 'route 2')\n\n\t\tconst response = await app.handle(req('/ab'))\n\t\tconst text = await response.text()\n\t\texpect(text).toBe('route 2')\n\t})\n\n\tit('return file', async () => {\n\t\tconst app = new Elysia().get('/', ({ set }) => {\n\t\t\tset.headers.server = 'Elysia'\n\n\t\t\treturn Bun.file('./example/takodachi.png')\n\t\t})\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect((await res.text()).length).toBe(\n\t\t\t(await Bun.file('./example/takodachi.png').text()).length\n\t\t)\n\t\texpect(res.headers.get('Server')).toBe('Elysia')\n\t})\n\n\tit('return web api\\'s File', async () => {\n\t\tconst app = new Elysia().get('/', () => new File(['Hello'], 'hello.txt', { type: 'text/plain' }))\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.headers.get('content-type')).toBe('text/plain;charset=utf-8')\n\t\texpect(await res.text()).toBe('Hello')\n\t\texpect(res.status).toBe(200)\n\t\texpect(res.headers.get('accept-ranges')).toBe('bytes')\n\t\texpect(res.headers.get('content-range')).toBe('bytes 0-4/5')\n\n\t})\n\n\tit('handle *', async () => {\n\t\tconst app = new Elysia().get('/*', () => 'Hi')\n\t\tconst get = await app.handle(req('/')).then((r) => r.text())\n\t\tconst post = await app\n\t\t\t.handle(req('/anything/should/match'))\n\t\t\t.then((r) => r.text())\n\n\t\texpect(get).toBe('Hi')\n\t\texpect(post).toBe('Hi')\n\t})\n\n\tit('handle * on multiple methods', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/part', () => 'Part')\n\t\t\t.options('*', () => 'Hi')\n\n\t\tconst get = await app.handle(req('/part')).then((r) => r.text())\n\t\tconst options = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/part', {\n\t\t\t\t\tmethod: 'OPTIONS'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((r) => r.text())\n\n\t\texpect(get).toBe('Part')\n\t\texpect(options).toBe('Hi')\n\t})\n\n\tit('decode uri', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query)\n\n\t\tconst res = await app\n\t\t\t.handle(req('/?name=a%20b&c=d%20e'))\n\t\t\t.then((r) => r.json())\n\n\t\texpect(res).toEqual({\n\t\t\tname: 'a b',\n\t\t\tc: 'd e'\n\t\t})\n\t})\n\n\tit('handle all method', async () => {\n\t\tconst app = new Elysia().all('/', () => 'Hi')\n\t\tconst res1 = await app.handle(req('/')).then((res) => res.text())\n\t\tconst res2 = await app.handle(post('/', {})).then((res) => res.text())\n\n\t\texpect(res1).toBe('Hi')\n\t\texpect(res2).toBe('Hi')\n\t})\n\n\tit('add path if onRequest is used', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onRequest(() => {})\n\t\t\t.onAfterHandle(({ path }) => {\n\t\t\t\treturn path\n\t\t\t})\n\t\t\t.get('/', () => 'Hi')\n\n\t\tconst res = await app.handle(req('/')).then((res) => res.text())\n\n\t\texpect(res).toBe('/')\n\t})\n\n\t// it('handle array route - GET', async () => {\n\t// \tconst paths = ['/', '/test', '/other/nested']\n\t// \tconst app = new Elysia().get(paths, ({ path }) => {\n\t// \t\treturn path\n\t// \t})\n\n\t// \tfor (const path of paths) {\n\t// \t\tconst res = await app.handle(req(path))\n\t// \t\texpect(await res.text()).toBe(path)\n\t// \t}\n\t// })\n\n\t// it('handle array route - POST', async () => {\n\t// \tconst paths = ['/', '/test', '/other/nested']\n\t// \tconst app = new Elysia().post(paths, ({ path }) => {\n\t// \t\treturn path\n\t// \t})\n\n\t// \tfor (const path of paths) {\n\t// \t\tconst res = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'POST'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\texpect(await res.text()).toBe(path)\n\t// \t}\n\t// })\n\n\t// it('handle array route - PUT', async () => {\n\t// \tconst paths = ['/', '/test', '/other/nested']\n\t// \tconst app = new Elysia().put(paths, ({ path }) => {\n\t// \t\treturn path\n\t// \t})\n\n\t// \tfor (const path of paths) {\n\t// \t\tconst res = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'PUT'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\texpect(await res.text()).toBe(path)\n\t// \t}\n\t// })\n\n\t// it('handle array route - DELETE', async () => {\n\t// \tconst paths = ['/', '/test', '/other/nested']\n\t// \tconst app = new Elysia().delete(paths, ({ path }) => {\n\t// \t\treturn path\n\t// \t})\n\n\t// \tfor (const path of paths) {\n\t// \t\tconst res = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'DELETE'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\texpect(await res.text()).toBe(path)\n\t// \t}\n\t// })\n\n\t// it('handle array route - PATCH', async () => {\n\t// \tconst paths = ['/', '/test', '/other/nested']\n\t// \tconst app = new Elysia().patch(paths, ({ path }) => {\n\t// \t\treturn path\n\t// \t})\n\n\t// \tfor (const path of paths) {\n\t// \t\tconst res = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'PATCH'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\texpect(await res.text()).toBe(path)\n\t// \t}\n\t// })\n\n\t// it('handle array route - HEAD', async () => {\n\t// \tconst paths = ['/', '/test', '/other/nested']\n\t// \tconst app = new Elysia().head(paths, ({ path }) => {\n\t// \t\treturn path\n\t// \t})\n\n\t// \tfor (const path of paths) {\n\t// \t\tconst res = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'HEAD'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\texpect(await res.text()).toBe(path)\n\t// \t}\n\t// })\n\n\t// it('handle array route - OPTIONS', async () => {\n\t// \tconst paths = ['/', '/test', '/other/nested']\n\t// \tconst app = new Elysia().options(paths, ({ path }) => {\n\t// \t\treturn path\n\t// \t})\n\n\t// \tfor (const path of paths) {\n\t// \t\tconst res = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'OPTIONS'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\texpect(await res.text()).toBe(path)\n\t// \t}\n\t// })\n\n\t// it('handle array route - CONNECT', async () => {\n\t// \tconst paths = ['/', '/test', '/other/nested']\n\t// \tconst app = new Elysia().connect(paths, ({ path }) => {\n\t// \t\treturn path\n\t// \t})\n\n\t// \tfor (const path of paths) {\n\t// \t\tconst res = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'CONNECT'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\texpect(await res.text()).toBe(path)\n\t// \t}\n\t// })\n\n\t// it('handle array route - all', async () => {\n\t// \tconst paths = ['/', '/test', '/other/nested'] as const\n\t// \tconst app = new Elysia().all(paths, ({ path }) => {\n\t// \t\treturn path\n\t// \t})\n\n\t// \tfor (const path of paths) {\n\t// \t\tconst getRes = await app.handle(req(path))\n\t// \t\tconst postRes = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'POST'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\tconst putRes = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'PUT'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\tconst deleteRes = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'DELETE'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\tconst patchRes = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'PATCH'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\tconst headRes = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'HEAD'\n\t// \t\t\t})\n\t// \t\t)\n\n\t// \t\texpect(await getRes.text()).toBe(path)\n\t// \t\texpect(await postRes.text()).toBe(path)\n\t// \t\texpect(await putRes.text()).toBe(path)\n\t// \t\texpect(await deleteRes.text()).toBe(path)\n\t// \t\texpect(await patchRes.text()).toBe(path)\n\t// \t\texpect(await headRes.text()).toBe(path)\n\t// \t}\n\t// })\n\n\t// it('handle array route - custom method', async () => {\n\t// \tconst paths = ['/', '/test', '/other/nested'] as const\n\t// \t// @ts-ignore\n\t// \tconst app = new Elysia().route('NOTIFY', paths, ({ path }) => {\n\t// \t\treturn path\n\t// \t})\n\n\t// \tfor (const path of paths) {\n\t// \t\tconst res = await app.handle(\n\t// \t\t\tnew Request('http://localhost' + path, {\n\t// \t\t\t\tmethod: 'NOTIFY'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\texpect(await res.text()).toBe(path)\n\t// \t}\n\t// })\n})\n"
  },
  {
    "path": "test/plugins/affix.test.ts",
    "content": "// @ts-nocheck\nimport { Elysia, t } from '../../src'\nimport { describe, it, expect } from 'bun:test'\n\nconst setup = new Elysia()\n\t.decorate('decorate', 'decorate')\n\t.state('state', 'state')\n\t.model('model', t.String())\n\t.error('error', Error)\n\ndescribe('affix', () => {\n\tit('should add prefix to all decorators, states, models, and errors', () => {\n\t\tconst app = new Elysia().use(setup).affix('prefix', 'all', 'p')\n\n\t\texpect(app.singleton.decorator).toHaveProperty('pDecorate')\n\t\texpect(app.singleton.store).toHaveProperty('pState')\n\n\t\texpect(app.definitions.type).toHaveProperty('pModel')\n\n\t\texpect(app.definitions.error).toHaveProperty('pError')\n\t})\n\n\tit('should add suffix to all decorators, states, models, and errors', () => {\n\t\tconst app = new Elysia().use(setup).affix('suffix', 'all', 'p')\n\n\t\texpect(app.singleton.decorator).toHaveProperty('decorateP')\n\n\t\texpect(app.singleton.store).toHaveProperty('stateP')\n\n\t\texpect(app.definitions.type).toHaveProperty('modelP')\n\n\t\texpect(app.definitions.error).toHaveProperty('errorP')\n\t})\n\n\tit('should add suffix to all states', () => {\n\t\tconst app = new Elysia().use(setup).suffix('state', 'p')\n\n\t\texpect(app.singleton.store).toHaveProperty('stateP')\n\t})\n\n\tit('should add prefix to all decorators and errors', () => {\n\t\tconst app = new Elysia()\n\t\t\t.use(setup)\n\t\t\t.prefix('decorator', 'p')\n\t\t\t.prefix('error', 'p')\n\n\t\texpect(app.singleton.decorator).toHaveProperty('pDecorate')\n\n\t\texpect(app.definitions.error).toHaveProperty('pError')\n\t})\n\n\tit('should add suffix to all decorators and errors', () => {\n\t\tconst app = new Elysia()\n\t\t\t.use(setup)\n\t\t\t.suffix('decorator', 'p')\n\t\t\t.suffix('error', 'p')\n\n\t\texpect(app.singleton.decorator).toHaveProperty('decorateP')\n\n\t\texpect(app.definitions.error).toHaveProperty('errorP')\n\t})\n\n\tit('should add prefix to all models', () => {\n\t\tconst app = new Elysia().use(setup).prefix('model', 'p')\n\n\t\texpect(app.definitions.type).toHaveProperty('pModel')\n\t})\n\n\tit('should add suffix to all models', () => {\n\t\tconst app = new Elysia().use(setup).affix('suffix', 'model', 'p')\n\n\t\texpect(app.definitions.type).toHaveProperty('modelP')\n\t})\n\n\tit('should skip on empty', () => {\n\t\tconst app = new Elysia().use(setup).suffix('all', '')\n\n\t\texpect(app.singleton.decorator).toHaveProperty('decorate')\n\t\texpect(app.singleton.store).toHaveProperty('state')\n\n\t\texpect(app.definitions.type).toHaveProperty('model')\n\n\t\texpect(app.definitions.error).toHaveProperty('error')\n\t})\n})\n"
  },
  {
    "path": "test/plugins/checksum.test.ts",
    "content": "import { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('Checksum', () => {\n\tit('deduplicate plugin', async () => {\n\t\tconst cookie = (options?: Record<string, unknown>) =>\n\t\t\tnew Elysia({\n\t\t\t\tname: '@elysiajs/cookie',\n\t\t\t\tseed: options\n\t\t\t}).onTransform({ as: 'global' }, () => {})\n\n\t\tconst group = new Elysia().use(cookie({})).get('/a', () => 'Hi')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(cookie({}))\n\t\t\t.use(group)\n\t\t\t.get('/cookie', () => 'Hi')\n\n\t\tconst [a, b] = app.router.history\n\n\t\texpect(a.hooks.transform!.length).toBe(1)\n\t\texpect(b.hooks.transform!.length).toBe(1)\n\t})\n\n\tit('Set default checksum if not provided when name is set', async () => {\n\t\tconst cookie = (options?: Record<string, unknown>) =>\n\t\t\tnew Elysia({\n\t\t\t\tname: '@elysiajs/cookie',\n\t\t\t\tseed: options\n\t\t\t}).onTransform({ as: 'global' }, () => {})\n\n\t\tconst group = new Elysia().use(cookie()).get('/a', () => 'Hi')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(cookie())\n\t\t\t.use(group)\n\t\t\t.get('/cookie', () => 'Hi')\n\n\t\tconst [a, b] = app.router.history\n\n\t\texpect(a.hooks.transform!.length).toBe(1)\n\t\texpect(b.hooks.transform!.length).toBe(1)\n\t})\n\n\tit('Accept plugin when on different different', async () => {\n\t\tconst cookie = (options?: Record<string, unknown>) =>\n\t\t\tnew Elysia({\n\t\t\t\tname: '@elysiajs/cookie',\n\t\t\t\tseed: options\n\t\t\t}).onTransform({ as: 'global' }, () => {})\n\n\t\tconst group = new Elysia().use(cookie({})).get('/a', () => 'Hi')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(group)\n\t\t\t.use(\n\t\t\t\tcookie({\n\t\t\t\t\thello: 'world'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.get('/cookie', () => 'Hi')\n\n\t\tconst [a, b] = app.router.history\n\n\t\texpect(\n\t\t\tMath.abs(a.hooks.transform!.length - b.hooks.transform!.length)\n\t\t).toBe(1)\n\t})\n\n\tit('Deduplicate global hook on use', async () => {\n\t\tconst cookie = (options?: Record<string, unknown>) =>\n\t\t\tnew Elysia({\n\t\t\t\tname: '@elysiajs/cookie',\n\t\t\t\tseed: options\n\t\t\t}).onTransform({ as: 'global' }, () => {})\n\n\t\tconst group = new Elysia().use(cookie()).get('/a', () => 'Hi')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(cookie())\n\t\t\t.use(group)\n\t\t\t.get('/cookie', () => 'Hi')\n\n\t\tconst [a, b] = app.router.history\n\n\t\texpect(\n\t\t\tMath.abs(a.hooks.transform!.length - b.hooks.transform!.length)\n\t\t).toBe(0)\n\t})\n\n\tit('Filter inline hook', async () => {\n\t\tconst cookie = (options?: Record<string, unknown>) =>\n\t\t\tnew Elysia({\n\t\t\t\tname: '@elysiajs/cookie',\n\t\t\t\tseed: options\n\t\t\t}).onTransform({ as: 'global' }, () => {})\n\n\t\tconst group = new Elysia().use(cookie()).get('/a', () => 'Hi', {\n\t\t\ttransform() {}\n\t\t})\n\n\t\tconst app = new Elysia()\n\t\t\t.use(cookie())\n\t\t\t.use(group)\n\t\t\t.get('/cookie', () => 'Hi')\n\n\t\tconst [a, b] = app.router.history\n\n\t\texpect(\n\t\t\tMath.abs(a.hooks.transform!.length - b.hooks.transform!.length)\n\t\t).toBe(1)\n\t})\n\n\tit('Merge global hook', async () => {\n\t\tlet count = 0\n\n\t\tconst cookie = (options?: Record<string, unknown>) =>\n\t\t\tnew Elysia({\n\t\t\t\tname: '@elysiajs/cookie',\n\t\t\t\tseed: options\n\t\t\t}).onTransform({ as: 'global' }, () => {})\n\n\t\tconst group = new Elysia()\n\t\t\t.use(cookie())\n\t\t\t.onTransform({ as: 'global' }, () => {\n\t\t\t\tcount++\n\t\t\t})\n\t\t\t.get('/a', () => 'Hi')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(cookie())\n\t\t\t.use(group)\n\t\t\t.get('/cookie', () => 'Hi')\n\n\t\tawait Promise.all(['/a', '/cookie'].map((x) => app.handle(req(x))))\n\n\t\texpect(count).toBe(2)\n\t})\n\n\tit('Deduplicate guard hook', async () => {\n\t\tconst guard = new Elysia({ prefix: '/guard' }).guard(\n\t\t\t{\n\t\t\t\tparams: t.Object({ id: t.Number() }),\n\t\t\t\ttransform({ params }) {\n\t\t\t\t\tconst id = +params.id\n\t\t\t\t\tif (!Number.isNaN(id)) params.id = id\n\t\t\t\t}\n\t\t\t},\n\t\t\t(app) => app.get('/id/:id', ({ params: { id } }) => id)\n\t\t)\n\n\t\tconst app = new Elysia().use(guard)\n\t\tconst res = await app.handle(req('/guard/id/123'))\n\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('deduplicate in new instance', async () => {\n\t\tconst cookie = (options?: Record<string, unknown>) =>\n\t\t\tnew Elysia({\n\t\t\t\tname: '@elysiajs/cookie',\n\t\t\t\tseed: options\n\t\t\t}).derive({ as: 'global' }, () => {\n\t\t\t\treturn {\n\t\t\t\t\tcookie: 'mock'\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst plugin = new Elysia({ prefix: '/v1' })\n\t\t\t.use(cookie())\n\t\t\t.get('/plugin', ({ cookie }) => cookie)\n\n\t\tconst plugin2 = new Elysia({ prefix: '/v2' })\n\t\t\t.use(cookie())\n\t\t\t.get('/plugin', ({ cookie }) => cookie)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(cookie())\n\t\t\t.use(plugin)\n\t\t\t.use(plugin2)\n\t\t\t.get('/root', ({ cookie }) => cookie)\n\n\t\tconst res1 = await app.handle(req('/v1/plugin')).then((x) => x.text())\n\t\texpect(res1).toBe('mock')\n\n\t\tconst res2 = await app.handle(req('/v1/plugin')).then((x) => x.text())\n\t\texpect(res2).toBe('mock')\n\n\t\tconst root = await app.handle(req('/root')).then((x) => x.text())\n\t\texpect(root).toBe('mock')\n\t})\n\n\tit('Filter global event', async () => {\n\t\tlet x = 0\n\t\tlet a = 0\n\t\tlet b = 0\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onBeforeHandle({ as: 'global' }, () => {\n\t\t\t\tx++\n\t\t\t})\n\t\t\t.group('/v1', (app) =>\n\t\t\t\tapp\n\t\t\t\t\t.onBeforeHandle(() => {\n\t\t\t\t\t\ta++\n\t\t\t\t\t})\n\t\t\t\t\t.get('', () => 'A')\n\t\t\t\t\t.group('/v1', (app) =>\n\t\t\t\t\t\tapp\n\t\t\t\t\t\t\t.onBeforeHandle(() => {\n\t\t\t\t\t\t\t\tb++\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.get('/', () => 'B')\n\t\t\t\t\t)\n\t\t\t)\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'A')\n\n\t\tawait Promise.all(\n\t\t\t['/v1', '/v1/v1', '/'].map((path) => app.handle(req(path)))\n\t\t)\n\n\t\texpect(x).toBe(3)\n\t\texpect(a).toBe(2)\n\t\texpect(b).toBe(1)\n\t})\n\n\tit('invalidate non-root lifecycle', async () => {\n\t\tlet a = 0\n\t\tlet b = 0\n\t\tlet c = 0\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(\n\t\t\t\tnew Elysia()\n\t\t\t\t\t.derive({ as: 'global' }, () => {\n\t\t\t\t\t\ta++\n\n\t\t\t\t\t\treturn {}\n\t\t\t\t\t})\n\t\t\t\t\t.get('/1', () => 'asdf')\n\t\t\t)\n\t\t\t.use(\n\t\t\t\tnew Elysia()\n\t\t\t\t\t.derive({ as: 'global' }, () => {\n\t\t\t\t\t\tb++\n\n\t\t\t\t\t\treturn { test: 'test' }\n\t\t\t\t\t})\n\t\t\t\t\t.get('/2', ({ test }) => test)\n\t\t\t\t\t.use(\n\t\t\t\t\t\tnew Elysia()\n\t\t\t\t\t\t\t.derive({ as: 'global' }, () => {\n\t\t\t\t\t\t\t\tc++\n\n\t\t\t\t\t\t\t\treturn { test: 'test' }\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.get('/3', ({ test }) => test)\n\t\t\t\t\t)\n\t\t\t)\n\n\t\tconst app = new Elysia()\n\t\t\t.get('/root', () => 'A')\n\t\t\t.use(plugin)\n\t\t\t.get('/all', () => 'A')\n\n\t\tawait Promise.all(\n\t\t\t['/root', '/1', '/2', '/3', '/all'].map((path) =>\n\t\t\t\tapp.handle(req(path))\n\t\t\t)\n\t\t)\n\n\t\texpect(a).toBe(4)\n\t\texpect(b).toBe(3)\n\t\texpect(c).toBe(2)\n\t})\n\n\tit('read lifecylce top-down', async () => {\n\t\tlet i = 0\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(new Elysia({ prefix: '/not-call' }).get('/', () => 'asdf'))\n\t\t\t.use(\n\t\t\t\tnew Elysia({ prefix: '/call' })\n\t\t\t\t\t.derive({ as: 'global' }, () => {\n\t\t\t\t\t\ti++ // <-- should not be called, when requesting /asdf\n\t\t\t\t\t\treturn { test: 'test' }\n\t\t\t\t\t})\n\t\t\t\t\t.get('/', ({ test }) => test)\n\t\t\t)\n\n\t\tconst app = new Elysia().use(plugin)\n\n\t\tawait Promise.all(\n\t\t\t['/not-call', '/call'].map((path) => app.handle(req(path)))\n\t\t)\n\n\t\texpect(i).toBe(1)\n\t})\n\n\tit('scope plugin', async () => {\n\t\tlet i = 0\n\n\t\tconst plugin = new Elysia().use(\n\t\t\tnew Elysia({ prefix: '/call' })\n\t\t\t\t.derive(() => {\n\t\t\t\t\ti++ // <-- should not be called, when requesting /asdf\n\t\t\t\t\treturn { test: 'test' }\n\t\t\t\t})\n\t\t\t\t.get('/', ({ test }) => test)\n\t\t\t\t.use(new Elysia({ prefix: '/not-call' }).get('/', () => 'asdf'))\n\t\t)\n\n\t\tconst app = new Elysia().use(plugin)\n\n\t\tawait Promise.all(\n\t\t\t['/not-call', '/call'].map((path) => app.handle(req(path)))\n\t\t)\n\n\t\texpect(i).toBe(1)\n\t})\n\n\tit('handle reference parent-child', async () => {\n\t\tconst parent = new Elysia({ name: 'parent' }).derive(\n\t\t\t{ as: 'global' },\n\t\t\t() => ({\n\t\t\t\tbye: () => 'bye'\n\t\t\t})\n\t\t)\n\n\t\tconst child = new Elysia({ name: 'child' })\n\t\t\t.use(parent)\n\t\t\t.derive({ as: 'global' }, ({ bye }) => ({\n\t\t\t\thi: () => `hi + ${bye()}`\n\t\t\t}))\n\n\t\tconst app = new Elysia()\n\t\t\t.use(parent)\n\t\t\t.use(child)\n\t\t\t.get('/', ({ hi }) => hi())\n\n\t\tconst response = await app.handle(req('/')).then((res) => res.text())\n\n\t\texpect(response).toBe('hi + bye')\n\t})\n\n\tit('deduplicate local handler from global event', () => {\n\t\tconst ip = new Elysia({ name: 'ip', seed: 'ip' })\n\t\t\t.derive({ as: 'global' }, ({ server, request }) => {\n\t\t\t\treturn {\n\t\t\t\t\tip: server?.requestIP(request)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.onBeforeHandle(() => {\n\t\t\t\tconsole.log('11')\n\t\t\t})\n\t\t\t.get('/ip', ({ ip }) => ip)\n\n\t\tconst router1 = new Elysia({ name: 'ip1', seed: 'ip1' })\n\t\t\t.use(ip)\n\t\t\t.get('/ip-1', ({ ip }) => ip)\n\n\t\tconst router2 = new Elysia({ name: 'ip2', seed: 'ip2' })\n\t\t\t.use(ip)\n\t\t\t.get('/ip-2', ({ ip }) => ip)\n\n\t\tconst router3 = new Elysia({ name: 'ip2', seed: 'ip2' })\n\t\t\t.use(ip)\n\t\t\t.get('/ip-3', ({ ip }) => ip)\n\n\t\tconst server = new Elysia({ name: 'server' }).use(router1).use(router2)\n\n\t\texpect(\n\t\t\tserver.routes.find((x) => x.path === '/ip')?.hooks.transform\n\t\t).toHaveLength(1)\n\t})\n})\n"
  },
  {
    "path": "test/plugins/error-propagation.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Elysia } from '../../src'\nimport { req } from '../utils'\n\ndescribe('Error correctly passed to outer elysia instance', () => {\n\tit('Global error handler is run', async () => {\n\t\tlet globalHandlerRun = false\n\n\t\tconst mainApp = new Elysia().onError(() => {\n\t\t\tglobalHandlerRun = true\n\t\t\treturn 'Fail'\n\t\t})\n\n\t\tconst plugin = new Elysia().get('/foo', () => {\n\t\t\tthrow new Error('Error')\n\t\t})\n\n\t\tmainApp.use(plugin)\n\n\t\tconst res = await (await mainApp.handle(req('/foo'))).text()\n\n\t\texpect(res).toBe('Fail')\n\t\texpect(globalHandlerRun).toBeTrue()\n\t})\n\n\tit('Plugin global handler is executed before plugin handler', async () => {\n\t\t//I would expect the plugin error handler to be executed\n\t\tlet globalHandlerRun = false\n\t\tlet localHandlerRun = false\n\n\t\tconst plugin = new Elysia({\n\t\t\tprefix: '/a'\n\t\t})\n\t\t\t.onError({ as: 'global' }, () => {\n\t\t\t\tlocalHandlerRun = true\n\t\t\t\treturn 'FailPlugin'\n\t\t\t})\n\t\t\t.get('/foo', () => {\n\t\t\t\tthrow new Error('Error')\n\t\t\t})\n\n\t\tconst mainApp = new Elysia()\n\t\t\t.onError(() => {\n\t\t\t\tglobalHandlerRun = true\n\n\t\t\t\treturn 'Fail'\n\t\t\t})\n\t\t\t.use(plugin)\n\n\t\tconst res = await mainApp.handle(req('/a/foo')).then((x) => x.text())\n\n\t\texpect(res).toBe('Fail')\n\t\texpect(localHandlerRun).toBeFalse()\n\t\texpect(globalHandlerRun).toBeTrue()\n\t})\n})\n"
  },
  {
    "path": "test/plugins/plugin.test.ts",
    "content": "import { Elysia } from '../../src'\r\n\r\nimport { describe, expect, it } from 'bun:test'\r\nimport { req } from '../utils'\r\n\r\ndescribe('Plugin', () => {\r\n\tit('await async nested plugin', async () => {\r\n\t\tconst yay = async () => {\r\n\t\t\tawait Bun.sleep(2)\r\n\r\n\t\t\treturn new Elysia({ name: 'yay' }).get('/yay', 'yay')\r\n\t\t}\r\n\r\n\t\tconst wrapper = new Elysia({ name: 'wrapper' }).use(yay())\r\n\r\n\t\tconst app = new Elysia().use(wrapper)\r\n\r\n\t\tawait app.modules\r\n\r\n\t\tconst response = await app.handle(req('/yay'))\r\n\r\n\t\texpect(response.status).toBe(200)\r\n\t})\r\n})\r\n"
  },
  {
    "path": "test/production/index.test.ts",
    "content": "import { Elysia, t } from '../../src'\nimport { describe, it, expect, beforeEach } from 'bun:test'\n\ndescribe('NODE_ENV=production', () => {\n\tbeforeEach(() => {\n\t\tprocess.env.NODE_ENV = 'production'\n\t})\n\n\tit('omit error summary', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.post('/', () => 'yay', {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: ''\n\t\t\t})\n\t\t)\n\n\t\tconst text = await response.text()\n\t\texpect(text).not.toEqual(\n\t\t\t'Right side of assignment cannot be destructured'\n\t\t)\n\t})\n})\n"
  },
  {
    "path": "test/response/custom-response.test.ts",
    "content": "import { Elysia } from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\n\nclass CustomResponse extends Response { }\n\ndescribe('Custom Response Type', () => {\n    it('returns custom response when set headers is not empty', async () => {\n        const app = new Elysia()\n            .get('/', ({ set }) => {\n                set.headers['X-POWERED-BY'] = 'Elysia'\n                return new CustomResponse('Shuba Shuba', {\n                    headers: {\n                        duck: 'shuba duck'\n                    },\n                    status: 418\n                })\n            })\n\n        const response = await app.handle(req('/'))\n\n        expect(await response.text()).toBe('Shuba Shuba')\n        expect(response.headers.get('duck')).toBe('shuba duck')\n        expect(response.headers.get('X-POWERED-BY')).toBe('Elysia')\n        expect(response.status).toBe(418)\n    })\n\n    it('returns custom response when set headers is empty', async () => {\n        const app = new Elysia()\n            .get('/', () => {\n                return new CustomResponse('Shuba Shuba')\n            })\n\n        const response = await app.handle(req('/'))\n\n        expect(await response.text()).toBe('Shuba Shuba')\n    })\n\n    it('Response headers take precedence, set.headers merge non-conflicting', async () => {\n        const app = new Elysia()\n            .onRequest(({ set }) => {\n                set.headers['Content-Type'] = 'application/json'\n                set.headers['X-Framework'] = 'Elysia'\n            })\n            .get('/', () => {\n                return new Response('{\"message\":\"hello\"}', {\n                    headers: {\n                        'Content-Type': 'text/plain',\n                        'X-Custom': 'custom-value'\n                    }\n                })\n            })\n\n        const response = await app.handle(req('/'))\n\n        // Response's Content-Type takes precedence\n        expect(response.headers.get('Content-Type')).toBe('text/plain')\n        // set.headers adds non-conflicting headers\n        expect(response.headers.get('X-Framework')).toBe('Elysia')\n        // Response's own headers are preserved\n        expect(response.headers.get('X-Custom')).toBe('custom-value')\n    })\n})\n"
  },
  {
    "path": "test/response/headers.test.ts",
    "content": "import { Elysia } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('Response Headers', () => {\n\tit('add response headers', async () => {\n\t\tconst app = new Elysia().get('/', ({ set }) => {\n\t\t\tset.headers['x-powered-by'] = 'Elysia'\n\n\t\t\treturn 'Hi'\n\t\t})\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.headers.get('x-powered-by')).toBe('Elysia')\n\t})\n\n\tit('add headers from hook', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onTransform(({ set }) => {\n\t\t\t\tset.headers['x-powered-by'] = 'Elysia'\n\t\t\t})\n\t\t\t.get('/', () => 'Hi')\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.headers.get('x-powered-by')).toBe('Elysia')\n\t})\n\n\tit('add headers from plugin', async () => {\n\t\tconst plugin = (app: Elysia) =>\n\t\t\tapp.onTransform(({ set }) => {\n\t\t\t\tset.headers['x-powered-by'] = 'Elysia'\n\t\t\t})\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'Hi')\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.headers.get('x-powered-by')).toBe('Elysia')\n\t})\n\n\tit('add headers to Response', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onTransform(({ set }) => {\n\t\t\t\tset.headers['x-powered-by'] = 'Elysia'\n\t\t\t})\n\t\t\t.get('/', () => new Response('Hi'))\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.headers.get('x-powered-by')).toBe('Elysia')\n\t})\n\n\tit('add status to Response', async () => {\n\t\tconst app = new Elysia().get('/', ({ set }) => {\n\t\t\tset.status = 401\n\n\t\t\treturn 'Hi'\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('Hi')\n\t\texpect(res.status).toBe(401)\n\t})\n\n\tit('create static header', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.headers({\n\t\t\t\t'x-powered-by': 'Elysia'\n\t\t\t})\n\t\t\t.get('/', () => 'hi')\n\n\t\tconst headers = await app.handle(req('/')).then((x) => x.headers)\n\n\t\texpect(headers.get('x-powered-by')).toBe('Elysia')\n\t})\n\n\tit('accept header from plugin', async () => {\n\t\tconst plugin = new Elysia().headers({\n\t\t\t'x-powered-by': 'Elysia'\n\t\t})\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'hi')\n\n\t\tconst headers = await app.handle(req('/')).then((x) => x.headers)\n\n\t\texpect(headers.get('x-powered-by')).toBe('Elysia')\n\t})\n})\n"
  },
  {
    "path": "test/response/range.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\n\nimport { Elysia } from '../../src'\nimport { req } from '../utils'\n\n// Regression test for https://github.com/elysiajs/elysia/issues/1790\n// Range header was ignored; always returned bytes 0-N/N instead of the requested slice.\ndescribe('Range header', () => {\n\tconst content = '12345'\n\tconst app = new Elysia().get('/file', () => new Blob([content]))\n\n\tit('returns full file without Range header', async () => {\n\t\tconst res = await app.handle(req('/file'))\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe(content)\n\t})\n\n\tit('handles bytes=start- (open-ended range)', async () => {\n\t\tconst res = await app.handle(\n\t\t\treq('/file', { headers: { range: 'bytes=3-' } })\n\t\t)\n\t\texpect(res.status).toBe(206)\n\t\texpect(res.headers.get('content-range')).toBe('bytes 3-4/5')\n\t\texpect(res.headers.get('content-length')).toBe('2')\n\t\texpect(await res.text()).toBe('45')\n\t})\n\n\tit('handles bytes=start-end (bounded range)', async () => {\n\t\tconst res = await app.handle(\n\t\t\treq('/file', { headers: { range: 'bytes=1-3' } })\n\t\t)\n\t\texpect(res.status).toBe(206)\n\t\texpect(res.headers.get('content-range')).toBe('bytes 1-3/5')\n\t\texpect(res.headers.get('content-length')).toBe('3')\n\t\texpect(await res.text()).toBe('234')\n\t})\n\n\tit('handles bytes=-suffix (last N bytes)', async () => {\n\t\tconst res = await app.handle(\n\t\t\treq('/file', { headers: { range: 'bytes=-2' } })\n\t\t)\n\t\texpect(res.status).toBe(206)\n\t\texpect(res.headers.get('content-range')).toBe('bytes 3-4/5')\n\t\texpect(res.headers.get('content-length')).toBe('2')\n\t\texpect(await res.text()).toBe('45')\n\t})\n\n\tit('clamps end beyond file size to last byte', async () => {\n\t\tconst res = await app.handle(\n\t\t\treq('/file', { headers: { range: 'bytes=2-999' } })\n\t\t)\n\t\texpect(res.status).toBe(206)\n\t\texpect(res.headers.get('content-range')).toBe('bytes 2-4/5')\n\t\texpect(await res.text()).toBe('345')\n\t})\n\n\tit('returns 416 when start is out of range', async () => {\n\t\tconst res = await app.handle(\n\t\t\treq('/file', { headers: { range: 'bytes=99-' } })\n\t\t)\n\t\texpect(res.status).toBe(416)\n\t\texpect(res.headers.get('content-range')).toBe('bytes */5')\n\t})\n\n\tit('returns 416 for invalid \"bytes=-\" (both positions empty)', async () => {\n\t\tconst res = await app.handle(\n\t\t\treq('/file', { headers: { range: 'bytes=-' } })\n\t\t)\n\t\texpect(res.status).toBe(416)\n\t\texpect(res.headers.get('content-range')).toBe('bytes */5')\n\t})\n\n\tit('ignores subsequent ranges in multi-range requests, uses first range only', async () => {\n\t\t// Multi-range (e.g. bytes=0-1,3-4) is not supported; only the first range is applied.\n\t\tconst res = await app.handle(\n\t\t\treq('/file', { headers: { range: 'bytes=0-1,3-4' } })\n\t\t)\n\t\texpect(res.status).toBe(206)\n\t\texpect(res.headers.get('content-range')).toBe('bytes 0-1/5')\n\t\texpect(await res.text()).toBe('12')\n\t})\n})\n"
  },
  {
    "path": "test/response/redirect.test.ts",
    "content": "import { Elysia } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('Response Redirect', () => {\n\tit('handle redirect', async () => {\n\t\tconst app = new Elysia().get('/', ({ redirect }) => redirect('/skadi'))\n\n\t\tconst { headers, status } = await app.handle(req('/'))\n\n\t\texpect(status).toBe(302)\n\t\texpect(headers.toJSON()).toEqual({\n\t\t\tlocation: '/skadi'\n\t\t})\n\t})\n\n\tit('handle redirect status', async () => {\n\t\tconst app = new Elysia().get('/', ({ redirect }) =>\n\t\t\tredirect('/skadi', 301)\n\t\t)\n\n\t\tconst { headers, status } = await app.handle(req('/'))\n\n\t\texpect(status).toBe(301)\n\t\texpect(headers.toJSON()).toEqual({\n\t\t\tlocation: '/skadi'\n\t\t})\n\t})\n\n\tit('add set.headers to redirect', async () => {\n\t\tconst app = new Elysia().get('/', ({ redirect, set }) => {\n\t\t\tset.headers.alias = 'Abyssal Hunter'\n\n\t\t\treturn redirect('/skadi')\n\t\t})\n\n\t\tconst { headers, status } = await app.handle(req('/'))\n\n\t\texpect(status).toBe(302)\n\t\texpect(headers.toJSON()).toEqual({\n\t\t\tlocation: '/skadi',\n\t\t\talias: 'Abyssal Hunter'\n\t\t})\n\t})\n\n\tit('set multiple cookie on redirect', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { name, name2 }, redirect }) => {\n\t\t\t\tname.value = 'a'\n\t\t\t\tname2.value = 'b'\n\n\t\t\t\treturn redirect('/skadi')\n\t\t\t}\n\t\t)\n\n\t\tconst { headers, status } = await app.handle(req('/'))\n\n\t\texpect(status).toBe(302)\n\t\t// @ts-expect-error\n\t\texpect(headers.toJSON()).toEqual({\n\t\t\tlocation: '/skadi',\n\t\t\t'set-cookie': ['name=a; Path=/', 'name2=b; Path=/']\n\t\t})\n\t})\n})\n"
  },
  {
    "path": "test/response/sse-double-wrap.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { Elysia } from '../../src'\n\ndescribe('SSE - Response Double Wrapping', () => {\n\tit('should not double-wrap SSE data when returning pre-formatted Response', async () => {\n\t\tconst app = new Elysia().get('/', ({ set }) => {\n\t\t\tset.headers.hello = 'world'\n\n\t\t\treturn new Response('data: hello\\n\\ndata: world\\n\\n', {\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'text/event-stream',\n\t\t\t\t\t'transfer-encoding': 'chunked'\n\t\t\t\t},\n\t\t\t\tstatus: 200\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(new Request('http://localhost/')).then(r => r.text())\n\n\t\t// Should NOT double-wrap with \"data: data:\"\n\t\texpect(response).toBe('data: hello\\n\\ndata: world\\n\\n')\n\t\texpect(response).not.toContain('data: data:')\n\t})\n\n\tit('should not double-wrap SSE when using set.headers with pre-formatted content', async () => {\n\t\tconst app = new Elysia().get('/', ({ set }) => {\n\t\t\tset.headers['x-custom'] = 'test'\n\t\t\tset.headers['content-type'] = 'text/event-stream'\n\n\t\t\treturn new Response('data: message1\\n\\ndata: message2\\n\\n', {\n\t\t\t\theaders: {\n\t\t\t\t\t'transfer-encoding': 'chunked'\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(new Request('http://localhost/')).then(r => r.text())\n\n\t\texpect(response).toBe('data: message1\\n\\ndata: message2\\n\\n')\n\t\texpect(response).not.toContain('data: data:')\n\t})\n\n\tit('should properly format SSE for generator functions', async () => {\n\t\tconst app = new Elysia().get('/', function* () {\n\t\t\tyield 'hello'\n\t\t\tyield 'world'\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(new Request('http://localhost/'))\n\t\t\t.then((r) => r.text())\n\n\t\t// Generator without explicit SSE should format as plain text\n\t\texpect(response).toContain('hello')\n\t\texpect(response).toContain('world')\n\t\t// Verify it's NOT SSE formatted\n\t\texpect(response).not.toContain('data: hello')\n\t\texpect(response).not.toContain('data: world')\n\t})\n\n\tit('should format SSE correctly for generators with explicit SSE configuration', async () => {\n\t\tconst { sse } = await import('../../src')\n\t\t\n\t\tconst app = new Elysia().get('/', ({ set }) => {\n\t\t\tset.headers['content-type'] = 'text/event-stream'\n\t\t\t\n\t\t\treturn (async function* () {\n\t\t\t\tyield sse({ data: 'first message' })\n\t\t\t\tyield sse({ data: 'second message' })\n\t\t\t})()\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(new Request('http://localhost/'))\n\t\t\t.then((r) => r.text())\n\n\t\t// Generator WITH explicit SSE markers should get properly formatted\n\t\texpect(response).toContain('data: first message\\n\\n')\n\t\texpect(response).toContain('data: second message\\n\\n')\n\t\t// Should NOT double-wrap\n\t\texpect(response).not.toContain('data: data:')\n\t})\n})\n"
  },
  {
    "path": "test/response/static.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\n\nimport { Elysia } from '../../src'\nimport { req } from '../utils'\n\ndescribe('Static Content', () => {\n\tit('work', async () => {\n\t\tconst app = new Elysia().get('/', 'Static Content')\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('Static Content')\n\t})\n\n\tit('handle onRequest', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onRequest(() => 'request')\n\t\t\t.get('/', 'Static Content')\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('request')\n\t})\n\n\tit('inline life-cycle', async () => {\n\t\tconst app = new Elysia().get('/', 'Static Content', {\n\t\t\tbeforeHandle() {\n\t\t\t\treturn 'beforeHandle'\n\t\t\t}\n\t\t})\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('beforeHandle')\n\t})\n\n\tit('mutate context', async () => {\n\t\tconst app = new Elysia().get('/', 'Static Content', {\n\t\t\tbeforeHandle({ set }) {\n\t\t\t\tset.headers['X-Powered-By'] = 'Elysia'\n\t\t\t}\n\t\t})\n\n\t\tconst headers = await app.handle(req('/')).then((x) => x.headers)\n\n\t\texpect(headers.get('X-Powered-By')).toBe('Elysia')\n\t})\n\n\tit('set default header', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.headers({\n\t\t\t\t'X-Powered-By': 'Elysia'\n\t\t\t})\n\t\t\t.get('/', 'Static Content')\n\n\t\tconst headers = await app.handle(req('/')).then((x) => x.headers)\n\n\t\texpect(headers.get('X-Powered-By')).toBe('Elysia')\n\t})\n\n\tit('handle errror after routing', async () => {\n\t\tconst app = new Elysia().get('/', 'Static Content', {\n\t\t\tbeforeHandle() {\n\t\t\t\tthrow new Error('error')\n\t\t\t},\n\t\t\terror() {\n\t\t\t\treturn 'handled'\n\t\t\t}\n\t\t})\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('handled')\n\t})\n\n\tit('handle errror after routing', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(() => 'handled')\n\t\t\t.onRequest(() => {\n\t\t\t\tthrow new Error('error')\n\t\t\t})\n\t\t\t.get('/', 'Static Content')\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.text())\n\n\t\texpect(response).toBe('handled')\n\t})\n\n\tit('clone content', async () => {\n\t\tconst app = new Elysia().get('/', 'Static Content', {\n\t\t\tbeforeHandle({ set }) {\n\t\t\t\tset.headers['X-Powered-By'] = 'Elysia'\n\t\t\t}\n\t\t})\n\n\t\tawait app.handle(req('/'))\n\t\tawait app.handle(req('/'))\n\t\tconst headers = await app.handle(req('/')).then((x) => x.headers)\n\n\t\texpect(headers.get('X-Powered-By')).toBe('Elysia')\n\t})\n})\n"
  },
  {
    "path": "test/response/stream.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\nimport { Elysia, sse } from '../../src'\nimport { streamResponse } from '../../src/adapter/utils'\nimport { randomId } from '../../src/utils'\n\ndescribe('Stream', () => {\n\tit('handle stream', async () => {\n\t\tconst expected = ['a', 'b', 'c']\n\n\t\tconst app = new Elysia().get('/', async function* () {\n\t\t\tyield 'a'\n\t\t\tawait Bun.sleep(10)\n\n\t\t\tyield 'b'\n\t\t\tawait Bun.sleep(10)\n\n\t\t\tyield 'c'\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(req('/'))\n\t\t\t.then((x) => x.body)\n\t\t\t.then((x) => {\n\t\t\t\tif (!x) return\n\n\t\t\t\tconst reader = x?.getReader()\n\n\t\t\t\tlet acc = ''\n\t\t\t\tconst { promise, resolve } = Promise.withResolvers()\n\n\t\t\t\treader.read().then(function pump({ done, value }): unknown {\n\t\t\t\t\tif (done) return resolve(acc)\n\n\t\t\t\t\texpect(value.toString()).toBe(expected.shift()!)\n\n\t\t\t\t\tacc += value.toString()\n\t\t\t\t\treturn reader.read().then(pump)\n\t\t\t\t})\n\n\t\t\t\treturn promise\n\t\t\t})\n\n\t\texpect(expected).toHaveLength(0)\n\t\texpect(response).toBe('abc')\n\t})\n\n\tit('stop stream on canceled request', async () => {\n\t\tconst expected = ['a', 'b']\n\n\t\tconst app = new Elysia().get('/', async function* () {\n\t\t\tyield 'a'\n\t\t\tawait Bun.sleep(10)\n\n\t\t\tyield 'b'\n\t\t\tawait Bun.sleep(10)\n\n\t\t\tyield 'c'\n\t\t})\n\n\t\tconst controller = new AbortController()\n\n\t\tsetTimeout(() => {\n\t\t\tcontroller.abort()\n\t\t}, 15)\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://e.ly', {\n\t\t\t\t\tsignal: controller.signal\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.body)\n\t\t\t.then((x) => {\n\t\t\t\tif (!x) return\n\n\t\t\t\tconst reader = x?.getReader()\n\n\t\t\t\tlet acc = ''\n\t\t\t\tconst { promise, resolve } = Promise.withResolvers()\n\n\t\t\t\treader.read().then(function pump({ done, value }): unknown {\n\t\t\t\t\tif (done) return resolve(acc)\n\n\t\t\t\t\texpect(value.toString()).toBe(expected.shift()!)\n\n\t\t\t\t\tacc += value.toString()\n\t\t\t\t\treturn reader.read().then(pump)\n\t\t\t\t})\n\n\t\t\t\treturn promise\n\t\t\t})\n\n\t\texpect(expected).toHaveLength(0)\n\t\texpect(response).toBe('ab')\n\t})\n\n\tit('include multiple set-cookie headers in streamed response', async () => {\n\t\tconst app = new Elysia().get('/', async function* (context) {\n\t\t\tcontext.cookie['cookie1'].set({\n\t\t\t\tvalue: 'value1'\n\t\t\t})\n\t\t\tcontext.cookie['cookie2'].set({\n\t\t\t\tvalue: 'value2'\n\t\t\t})\n\n\t\t\tyield sse({ event: 'test', data: { count: 1 } })\n\t\t\tyield sse({ event: 'test', data: { count: 2 } })\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\tconst cookieHeaders = response.headers.getSetCookie()\n\t\texpect(cookieHeaders).toHaveLength(2)\n\t\texpect(cookieHeaders.some((h) => h.includes('cookie1=value1'))).toBe(\n\t\t\ttrue\n\t\t)\n\t\texpect(cookieHeaders.some((h) => h.includes('cookie2=value2'))).toBe(\n\t\t\ttrue\n\t\t)\n\t})\n\n\tit('mutate set before yield is called', async () => {\n\t\tconst expected = ['a', 'b', 'c']\n\n\t\tconst app = new Elysia().get('/', function* ({ set }) {\n\t\t\tset.headers['access-control-allow-origin'] = 'http://saltyaom.com'\n\n\t\t\tyield 'a'\n\t\t\tyield 'b'\n\t\t\tyield 'c'\n\t\t})\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.headers)\n\n\t\texpect(response.get('access-control-allow-origin')).toBe(\n\t\t\t'http://saltyaom.com'\n\t\t)\n\t})\n\n\tit('mutate set before yield is called', async () => {\n\t\tconst expected = ['a', 'b', 'c']\n\n\t\tconst app = new Elysia().get('/', function* ({ set }) {\n\t\t\tset.headers['access-control-allow-origin'] = 'http://saltyaom.com'\n\n\t\t\tyield 'a'\n\t\t\tyield 'b'\n\t\t\tyield 'c'\n\t\t})\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.headers)\n\n\t\texpect(response.get('access-control-allow-origin')).toBe(\n\t\t\t'http://saltyaom.com'\n\t\t)\n\t})\n\n\tit('async mutate set before yield is called', async () => {\n\t\tconst expected = ['a', 'b', 'c']\n\n\t\tconst app = new Elysia().get('/', async function* ({ set }) {\n\t\t\tset.headers['access-control-allow-origin'] = 'http://saltyaom.com'\n\n\t\t\tyield 'a'\n\t\t\tyield 'b'\n\t\t\tyield 'c'\n\t\t})\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.headers)\n\n\t\texpect(response.get('access-control-allow-origin')).toBe(\n\t\t\t'http://saltyaom.com'\n\t\t)\n\t})\n\n\tit('return value if not yield', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/', function* ({ set }) {\n\t\t\t\treturn 'hello'\n\t\t\t})\n\t\t\t.get('/json', function* ({ set }) {\n\t\t\t\treturn { hello: 'world' }\n\t\t\t})\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/')),\n\t\t\tapp.handle(req('/json'))\n\t\t])\n\n\t\texpect(await response[0].text()).toBe('hello')\n\t\texpect(await response[1].json()).toEqual({\n\t\t\thello: 'world'\n\t\t})\n\t})\n\n\tit('return async value if not yield', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/', function* ({ set }) {\n\t\t\t\treturn 'hello'\n\t\t\t})\n\t\t\t.get('/json', function* ({ set }) {\n\t\t\t\treturn { hello: 'world' }\n\t\t\t})\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/')),\n\t\t\tapp.handle(req('/json'))\n\t\t])\n\n\t\texpect(await response[0].text()).toBe('hello')\n\t\texpect(await response[1].json()).toEqual({\n\t\t\thello: 'world'\n\t\t})\n\t})\n\n\tit('handle object and array', async () => {\n\t\tconst expected = [{ a: 'b' }, ['a'], ['a', 1, { a: 'b' }]]\n\t\tconst expectedResponse = JSON.stringify([...expected])\n\t\tlet i = 0\n\n\t\tconst app = new Elysia().get('/', async function* () {\n\t\t\tyield expected[0]\n\t\t\tawait Bun.sleep(10)\n\n\t\t\tyield expected[1]\n\t\t\tawait Bun.sleep(10)\n\n\t\t\tyield expected[2]\n\t\t})\n\n\t\tapp.handle(req('/'))\n\t\t\t.then((x) => x.body)\n\t\t\t.then((x) => {\n\t\t\t\tif (!x) return\n\n\t\t\t\tconst reader = x?.getReader()\n\n\t\t\t\tconst { promise, resolve } = Promise.withResolvers()\n\n\t\t\t\treader.read().then(function pump({ done, value }): unknown {\n\t\t\t\t\tif (done) return resolve()\n\n\t\t\t\t\texpect(value.toString()).toBe(JSON.stringify(expected[i++]))\n\n\t\t\t\t\treturn reader.read().then(pump)\n\t\t\t\t})\n\n\t\t\t\treturn promise\n\t\t\t})\n\t})\n\n\tit('proxy fetch stream', async () => {\n\t\tconst expected = ['a', 'b', 'c']\n\t\tlet i = 0\n\n\t\tconst app = new Elysia().get('/', async function* () {\n\t\t\tyield 'a'\n\t\t\tawait Bun.sleep(10)\n\t\t\tyield 'b'\n\t\t\tawait Bun.sleep(10)\n\t\t\tyield 'c'\n\t\t})\n\n\t\tconst proxy = new Elysia().get('/', () =>\n\t\t\tapp.handle(new Request('http://e.ly'))\n\t\t)\n\n\t\tproxy\n\t\t\t.handle(req('/'))\n\t\t\t.then((x) => x.body)\n\t\t\t.then((x) => {\n\t\t\t\tif (!x) return\n\n\t\t\t\tconst reader = x?.getReader()\n\n\t\t\t\tconst { promise, resolve } = Promise.withResolvers()\n\n\t\t\t\treader.read().then(function pump({ done, value }): unknown {\n\t\t\t\t\tif (done) return resolve()\n\n\t\t\t\t\texpect(value.toString()).toBe(expected[i++])\n\n\t\t\t\t\treturn reader.read().then(pump)\n\t\t\t\t})\n\n\t\t\t\treturn promise\n\t\t\t})\n\t})\n\n\tit('handle sse with id', () => {\n\t\tconst app = new Elysia().get('/sse', async function* () {\n\t\t\tfor (let i = 0; i < 3; i++) {\n\t\t\t\tyield sse({\n\t\t\t\t\tid: randomId(),\n\t\t\t\t\tdata: `message ${i}`\n\t\t\t\t})\n\t\t\t\tawait Bun.sleep(10)\n\t\t\t}\n\t\t})\n\n\t\treturn app\n\t\t\t.handle(req('/sse'))\n\t\t\t.then((x) => x.body)\n\t\t\t.then((x) => {\n\t\t\t\tif (!x) return\n\n\t\t\t\tconst reader = x?.getReader()\n\n\t\t\t\tlet acc = ''\n\t\t\t\tconst { promise, resolve } = Promise.withResolvers()\n\n\t\t\t\treader.read().then(function pump({ done, value }): unknown {\n\t\t\t\t\tif (done) return resolve(acc)\n\n\t\t\t\t\tacc += value.toString()\n\t\t\t\t\treturn reader.read().then(pump)\n\t\t\t\t})\n\n\t\t\t\treturn promise\n\t\t\t})\n\t\t\t.then((response) => {\n\t\t\t\tif (typeof response !== 'string')\n\t\t\t\t\treturn void expect(response).toBeTypeOf('string')\n\n\t\t\t\tresponse\n\t\t\t\t\t.split('\\n\\n')\n\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t.forEach((x, i) => {\n\t\t\t\t\t\texpect(x).toInclude(`data: message ${i}`)\n\t\t\t\t\t\texpect(x).toInclude('id: ')\n\t\t\t\t\t})\n\t\t\t})\n\t})\n\n\tit('handle sse with event, retry and custom id', () => {\n\t\tconst app = new Elysia().get('/sse', async function* () {\n\t\t\tfor (let i = 0; i < 3; i++) {\n\t\t\t\tyield sse({\n\t\t\t\t\tdata: `message ${i}`,\n\t\t\t\t\tevent: 'message',\n\t\t\t\t\tretry: 1000,\n\t\t\t\t\tid: i\n\t\t\t\t})\n\t\t\t\tawait Bun.sleep(10)\n\t\t\t}\n\t\t})\n\n\t\treturn app\n\t\t\t.handle(req('/sse'))\n\t\t\t.then((x) => x.body)\n\t\t\t.then((x) => {\n\t\t\t\tif (!x) return\n\n\t\t\t\tconst reader = x?.getReader()\n\n\t\t\t\tlet acc = ''\n\t\t\t\tconst { promise, resolve } = Promise.withResolvers()\n\n\t\t\t\treader.read().then(function pump({ done, value }): unknown {\n\t\t\t\t\tif (done) return resolve(acc)\n\n\t\t\t\t\tacc += value.toString()\n\t\t\t\t\treturn reader.read().then(pump)\n\t\t\t\t})\n\n\t\t\t\treturn promise\n\t\t\t})\n\t\t\t.then((response) => {\n\t\t\t\tif (typeof response !== 'string')\n\t\t\t\t\treturn void expect(response).toBeTypeOf('string')\n\n\t\t\t\tresponse\n\t\t\t\t\t.split('\\n\\n')\n\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t.forEach((x, i) => {\n\t\t\t\t\t\texpect(x).toInclude(`data: message ${i}`)\n\t\t\t\t\t\texpect(x).toInclude('event: message')\n\t\t\t\t\t\texpect(x).toInclude('retry: 1000')\n\t\t\t\t\t\texpect(x).toInclude(`id: ${i}`)\n\t\t\t\t\t})\n\t\t\t})\n\t})\n\n\tit('handle sse without id', () => {\n\t\tconst app = new Elysia().get('/sse', async function* () {\n\t\t\tfor (let i = 0; i < 3; i++) {\n\t\t\t\tyield sse({\n\t\t\t\t\tid: null,\n\t\t\t\t\tdata: `message ${i}`\n\t\t\t\t})\n\t\t\t\tawait Bun.sleep(10)\n\t\t\t}\n\t\t})\n\n\t\treturn app\n\t\t\t.handle(req('/sse'))\n\t\t\t.then((x) => x.body)\n\t\t\t.then((x) => {\n\t\t\t\tif (!x) return\n\n\t\t\t\tconst reader = x?.getReader()\n\n\t\t\t\tlet acc = ''\n\t\t\t\tconst { promise, resolve } = Promise.withResolvers()\n\n\t\t\t\treader.read().then(function pump({ done, value }): unknown {\n\t\t\t\t\tif (done) return resolve(acc)\n\n\t\t\t\t\tacc += value.toString()\n\t\t\t\t\treturn reader.read().then(pump)\n\t\t\t\t})\n\n\t\t\t\treturn promise\n\t\t\t})\n\t\t\t.then((response) => {\n\t\t\t\texpect(response).toBe(\n\t\t\t\t\t'data: message 0\\n\\ndata: message 1\\n\\ndata: message 2\\n\\n'\n\t\t\t\t)\n\t\t\t})\n\t})\n\n\tit('handle sse short-form', () => {\n\t\tconst app = new Elysia().get('/sse', async function* () {\n\t\t\tfor (let i = 0; i < 3; i++) {\n\t\t\t\tyield sse(`message ${i}`)\n\t\t\t\tawait Bun.sleep(10)\n\t\t\t}\n\t\t})\n\n\t\treturn app\n\t\t\t.handle(req('/sse'))\n\t\t\t.then((x) => x.body)\n\t\t\t.then((x) => {\n\t\t\t\tif (!x) return\n\n\t\t\t\tconst reader = x?.getReader()\n\n\t\t\t\tlet acc = ''\n\t\t\t\tconst { promise, resolve } = Promise.withResolvers()\n\n\t\t\t\treader.read().then(function pump({ done, value }): unknown {\n\t\t\t\t\tif (done) return resolve(acc)\n\n\t\t\t\t\tacc += value.toString()\n\t\t\t\t\treturn reader.read().then(pump)\n\t\t\t\t})\n\n\t\t\t\treturn promise\n\t\t\t})\n\t\t\t.then((response) => {\n\t\t\t\tif (typeof response !== 'string')\n\t\t\t\t\treturn void expect(response).toBeTypeOf('string')\n\n\t\t\t\tresponse\n\t\t\t\t\t.split('\\n\\n')\n\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t.forEach((x, i) => {\n\t\t\t\t\t\texpect(x).toInclude(`data: message ${i}`)\n\t\t\t\t\t})\n\t\t\t})\n\t})\n\n\tit('stream ReadableStream', async () => {\n\t\tconst app = new Elysia().get('/', function () {\n\t\t\treturn new ReadableStream({\n\t\t\t\tasync start(controller) {\n\t\t\t\t\tcontroller.enqueue('Elysia')\n\t\t\t\t\tawait Bun.sleep(1)\n\n\t\t\t\t\tcontroller.enqueue('Eden')\n\t\t\t\t\tawait Bun.sleep(1)\n\n\t\t\t\t\tcontroller.close()\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\tconst result = []\n\n\t\tfor await (const a of streamResponse(response)) result.push(a)\n\n\t\texpect(result).toEqual(['Elysia', 'Eden'])\n\t})\n\n\tit('stream ReadableStream return from generator function', async () => {\n\t\tconst app = new Elysia().get('/', function* () {\n\t\t\treturn new ReadableStream({\n\t\t\t\tasync start(controller) {\n\t\t\t\t\tcontroller.enqueue('Elysia')\n\t\t\t\t\tawait Bun.sleep(1)\n\n\t\t\t\t\tcontroller.enqueue('Eden')\n\t\t\t\t\tawait Bun.sleep(1)\n\n\t\t\t\t\tcontroller.close()\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\tconst result = []\n\n\t\tfor await (const a of streamResponse(response)) result.push(a)\n\n\t\texpect(result).toEqual(['Elysia', 'Eden'])\n\t})\n\n\tit('stream ReadableStream return from async generator function', async () => {\n\t\tconst app = new Elysia().get('/', async function* () {\n\t\t\treturn new ReadableStream({\n\t\t\t\tasync start(controller) {\n\t\t\t\t\tcontroller.enqueue('Elysia')\n\t\t\t\t\tawait Bun.sleep(1)\n\n\t\t\t\t\tcontroller.enqueue('Eden')\n\t\t\t\t\tawait Bun.sleep(1)\n\n\t\t\t\t\tcontroller.close()\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\tconst result = []\n\n\t\tfor await (const a of streamResponse(response)) result.push(a)\n\n\t\texpect(result).toEqual(['Elysia', 'Eden'])\n\t})\n\n\tit('stream ReadableStream with sse', async () => {\n\t\tconst app = new Elysia().get('/', async function* () {\n\t\t\treturn sse(\n\t\t\t\tnew ReadableStream({\n\t\t\t\t\tasync start(controller) {\n\t\t\t\t\t\tcontroller.enqueue('Elysia')\n\t\t\t\t\t\tawait Bun.sleep(1)\n\n\t\t\t\t\t\tcontroller.enqueue('Eden')\n\t\t\t\t\t\tawait Bun.sleep(1)\n\n\t\t\t\t\t\tcontroller.close()\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\tconst result = []\n\n\t\tfor await (const a of streamResponse(response)) result.push(a)\n\n\t\texpect(result).toEqual(['Elysia', 'Eden'].map((x) => `data: ${x}\\n\\n`))\n\t\texpect(response.headers.get('content-type')).toBe('text/event-stream')\n\t})\n\n\t// Issue #1677: Throwing from AsyncGenerator should preserve headers\n\tit('should preserve headers when throwing from async generator', async () => {\n\t\tconst { status: statusFn } = await import('../../src')\n\n\t\tconst app = new Elysia().get('/', async function* ({ set }) {\n\t\t\tset.headers['access-control-allow-origin'] = '*'\n\t\t\tset.headers['x-custom-header'] = 'test-value'\n\t\t\t// Throw before yielding - this is the bug scenario from #1677\n\t\t\tif (true) throw statusFn(500)\n\t\t\tyield 'unreachable'\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(500)\n\t\texpect(response.headers.get('access-control-allow-origin')).toBe('*')\n\t\texpect(response.headers.get('x-custom-header')).toBe('test-value')\n\t})\n\n\t// Issue #1677: onError hook should be called when throwing from generator\n\tit('should call onError hook when throwing from async generator', async () => {\n\t\tconst { status: statusFn } = await import('../../src')\n\t\tlet onErrorCalled = false\n\t\tlet errorCode: string | number | undefined\n\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ code }) => {\n\t\t\t\tonErrorCalled = true\n\t\t\t\terrorCode = code\n\t\t\t})\n\t\t\t.get('/', async function* ({ set }) {\n\t\t\t\tset.headers['x-custom-header'] = 'test-value'\n\t\t\t\t// Throw before yielding - this is the bug scenario from #1677\n\t\t\t\tif (true) throw statusFn(500)\n\t\t\t\tyield 'unreachable'\n\t\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(500)\n\t\texpect(onErrorCalled).toBe(true)\n\t\texpect(errorCode).toBe(500)\n\t\texpect(response.headers.get('x-custom-header')).toBe('test-value')\n\t})\n\n\tit('handle sse with plugin global hooks and trace', async () => {\n\t\tconst PluginA = () =>\n\t\t\tnew Elysia({ name: 'PluginA' })\n\t\t\t\t.onBeforeHandle(() => {})\n\t\t\t\t.onAfterHandle(() => {})\n\t\t\t\t.onParse(() => {})\n\t\t\t\t.onTransform(() => {})\n\t\t\t\t.onError(() => {})\n\t\t\t\t.onAfterResponse(() => {})\n\t\t\t\t.onStart(() => {})\n\t\t\t\t.onStop(() => {})\n\t\t\t\t.onRequest(() => {})\n\t\t\t\t.trace(() => {})\n\t\t\t\t.as('global')\n\n\t\tconst app = new Elysia().use(PluginA()).get('/sse', async function* () {\n\t\t\tyield sse({ event: 'message', data: { meow: '1' } })\n\t\t\tyield sse({ event: 'message', data: { meow: '2' } })\n\t\t\tyield sse({ event: 'message', data: { meow: '3' } })\n\t\t})\n\n\t\tconst response = await app.handle(req('/sse'))\n\t\texpect(response.headers.get('content-type')).toBe('text/event-stream')\n\n\t\tconst result = []\n\n\t\tfor await (const chunk of streamResponse(response)) result.push(chunk)\n\t\texpect(result).toHaveLength(3)\n\t\texpect(result).toEqual([\n\t\t\t'event: message\\ndata: {\"meow\":\"1\"}\\n\\n',\n\t\t\t'event: message\\ndata: {\"meow\":\"2\"}\\n\\n',\n\t\t\t'event: message\\ndata: {\"meow\":\"3\"}\\n\\n'\n\t\t])\n\t})\n\n\t// Regression: proxying a large upstream SSE stream caused OOM (#1801).\n\t// The upstream generator must not be drained ahead of the slow consumer.\n\tit('does not buffer unboundedly when proxying a slow-consuming SSE stream', async () => {\n\t\tconst TOTAL = 50\n\t\tlet produced = 0\n\n\t\tconst upstream = new Elysia().get('/', async function* () {\n\t\t\tfor (let i = 0; i < TOTAL; i++) {\n\t\t\t\tproduced++\n\t\t\t\tyield sse(`message ${i}`)\n\t\t\t}\n\t\t})\n\n\t\t// Simulate the OOM scenario: one Elysia instance re-streams another's\n\t\t// SSE response while the consumer reads slowly.\n\t\tconst proxy = new Elysia().get('/', () =>\n\t\t\tupstream.handle(new Request('http://e.ly'))\n\t\t)\n\n\t\tconst response = await proxy.handle(req('/'))\n\t\tconst reader = response.body!.getReader()\n\n\t\t// Slow consumer: read 3 chunks with pauses between each\n\t\tawait reader.read()\n\t\tawait Bun.sleep(20)\n\t\tawait reader.read()\n\t\tawait Bun.sleep(20)\n\t\tawait reader.read()\n\n\t\t// The upstream generator must not have raced ahead and produced all\n\t\t// TOTAL chunks. A small prefetch buffer is fine, but nowhere near 50.\n\t\texpect(produced).toBeLessThan(TOTAL)\n\n\t\treader.cancel()\n\t})\n\n\t// Regression test for https://github.com/elysiajs/elysia/issues/1801\n\t// The generator must not be drained ahead of the consumer (backpressure).\n\tit('does not eagerly drain generator ahead of consumer', async () => {\n\t\tlet nextCallCount = 0\n\n\t\tasync function* lazyGenerator() {\n\t\t\tfor (let i = 0; i < 10; i++) {\n\t\t\t\tnextCallCount++\n\t\t\t\tyield String(i)\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().get('/', lazyGenerator)\n\n\t\tconst response = await app.handle(req('/'))\n\t\tconst reader = response.body!.getReader()\n\n\t\t// Read only the first 3 chunks\n\t\tawait reader.read()\n\t\tawait reader.read()\n\t\tawait reader.read()\n\n\t\t// With pull()-based backpressure the generator should not have\n\t\t// been advanced far beyond what was consumed. Allow a small buffer\n\t\t// (ReadableStream may prefetch one extra chunk via pull()) but it\n\t\t// must not have drained all 10.\n\t\texpect(nextCallCount).toBeLessThan(10)\n\n\t\treader.cancel()\n\t})\n\n\tit('stream ReadableStream binary chunks', async () => {\n\t\tconst payload = new Uint8Array(128 * 1024)\n\n\t\tfor (let i = 0; i < payload.length; i++) payload[i] = i % 251\n\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() =>\n\t\t\t\tnew ReadableStream({\n\t\t\t\t\tstart(controller) {\n\t\t\t\t\t\tcontroller.enqueue(payload.subarray(0, 32768))\n\t\t\t\t\t\tcontroller.enqueue(payload.subarray(32768, 65536))\n\t\t\t\t\t\tcontroller.enqueue(payload.subarray(65536, 98304))\n\t\t\t\t\t\tcontroller.enqueue(payload.subarray(98304))\n\t\t\t\t\t\tcontroller.close()\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t)\n\n\t\tconst response = await app.handle(req('/'))\n\t\tconst result = new Uint8Array(await response.arrayBuffer())\n\n\t\texpect(result.byteLength).toBe(payload.byteLength)\n\t\texpect(result).toEqual(payload)\n\t})\n\n\tit('stream ReadableStream binary views and blob chunks', async () => {\n\t\tconst source = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n\t\tconst expected = new Uint8Array([6, 7, 8, 9, 2, 3, 4, 5, 10, 11, 12])\n\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() =>\n\t\t\t\tnew ReadableStream({\n\t\t\t\t\tstart(controller) {\n\t\t\t\t\t\tcontroller.enqueue(source.subarray(6, 10))\n\t\t\t\t\t\tcontroller.enqueue(new DataView(source.buffer, 2, 4))\n\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\tnew Blob([new Uint8Array([10, 11, 12])])\n\t\t\t\t\t\t)\n\t\t\t\t\t\tcontroller.close()\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t)\n\n\t\tconst response = await app.handle(req('/'))\n\t\tconst result = new Uint8Array(await response.arrayBuffer())\n\n\t\texpect(result).toEqual(expected)\n\t})\n\n\tit('stream generator Uint8Array chunks as binary', async () => {\n\t\tconst app = new Elysia().get('/', async function* () {\n\t\t\tyield new Uint8Array([1, 2])\n\t\t\tawait Bun.sleep(1)\n\t\t\tyield new Uint8Array([3, 4])\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\t\tconst result = new Uint8Array(await response.arrayBuffer())\n\n\t\t// expect(result).toEqual(result.toBase64())\n\n\t\texpect(result).toEqual(new Uint8Array([1, 2, 3, 4]))\n\t})\n})\n"
  },
  {
    "path": "test/schema/schema-utils.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\n\nimport { t } from '../../src'\nimport { hasProperty, getSchemaProperties } from '../../src/schema'\n\ndescribe('getSchemaProperties', () => {\n\tit('returns properties for Object schema', () => {\n\t\tconst schema = t.Object({\n\t\t\tname: t.String(),\n\t\t\tage: t.Number()\n\t\t})\n\n\t\tconst props = getSchemaProperties(schema)\n\t\texpect(props).toBeDefined()\n\t\texpect(Object.keys(props!)).toEqual(['name', 'age'])\n\t})\n\n\tit('returns undefined for non-object schema', () => {\n\t\texpect(getSchemaProperties(t.String())).toBeUndefined()\n\t\texpect(getSchemaProperties(t.Number())).toBeUndefined()\n\t\texpect(getSchemaProperties(t.Array(t.String()))).toBeUndefined()\n\t})\n\n\tit('returns undefined for undefined/null', () => {\n\t\texpect(getSchemaProperties(undefined)).toBeUndefined()\n\t\texpect(getSchemaProperties(null as any)).toBeUndefined()\n\t})\n\n\tit('returns combined properties for Union schema', () => {\n\t\tconst schema = t.Union([\n\t\t\tt.Object({ name: t.String() }),\n\t\t\tt.Object({ age: t.Number() })\n\t\t])\n\n\t\tconst props = getSchemaProperties(schema)\n\t\texpect(props).toBeDefined()\n\t\texpect(Object.keys(props!).sort()).toEqual(['age', 'name'])\n\t})\n\n\tit('returns combined properties for Intersect schema', () => {\n\t\tconst schema = t.Intersect([\n\t\t\tt.Object({ name: t.String() }),\n\t\t\tt.Object({ age: t.Number() })\n\t\t])\n\n\t\tconst props = getSchemaProperties(schema)\n\t\texpect(props).toBeDefined()\n\t\texpect(Object.keys(props!).sort()).toEqual(['age', 'name'])\n\t})\n\n\tit('returns Object properties when property value is Union', () => {\n\t\tconst schema = t.Object({\n\t\t\tdata: t.Union([t.String(), t.Number()])\n\t\t})\n\n\t\tconst props = getSchemaProperties(schema)\n\t\texpect(props).toBeDefined()\n\t\texpect(Object.keys(props!)).toEqual(['data'])\n\t})\n\n\tit('handles nested Union/Intersect', () => {\n\t\tconst schema = t.Union([\n\t\t\tt.Intersect([\n\t\t\t\tt.Object({ a: t.String() }),\n\t\t\t\tt.Object({ b: t.Number() })\n\t\t\t]),\n\t\t\tt.Object({ c: t.Boolean() })\n\t\t])\n\n\t\tconst props = getSchemaProperties(schema)\n\t\texpect(props).toBeDefined()\n\t\texpect(Object.keys(props!).sort()).toEqual(['a', 'b', 'c'])\n\t})\n\n\tit('handles nested Intersect/Union', () => {\n\t\tconst schema = t.Intersect([\n\t\t\tt.Union([t.Object({ a: t.String() }), t.Object({ b: t.Number() })]),\n\t\t\tt.Object({ c: t.Boolean() })\n\t\t])\n\n\t\tconst props = getSchemaProperties(schema)\n\t\texpect(props).toBeDefined()\n\t\texpect(Object.keys(props!).sort()).toEqual(['a', 'b', 'c'])\n\t})\n\n\tit('returns undefined for empty Union or Intersect', () => {\n\t\texpect(getSchemaProperties({ anyOf: [] } as any)).toBeUndefined()\n\t\texpect(getSchemaProperties({ allOf: [] } as any)).toBeUndefined()\n\t})\n\n\tit('handles Union with non-object members', () => {\n\t\tconst schema = t.Union([t.Object({ name: t.String() }), t.String()])\n\n\t\tconst props = getSchemaProperties(schema)\n\t\texpect(props).toBeDefined()\n\t\texpect(Object.keys(props!)).toEqual(['name'])\n\t})\n})\n\ndescribe('hasProperty', () => {\n\tit('finds property in Object schema', () => {\n\t\tconst schema = t.Object({\n\t\t\tname: t.String({ default: 'test' })\n\t\t})\n\n\t\texpect(hasProperty('default', schema)).toBe(true)\n\t\texpect(hasProperty('minimum', schema)).toBe(false)\n\t})\n\n\tit('finds property in Union schema', () => {\n\t\tconst schema = t.Union([\n\t\t\tt.Object({ name: t.String({ default: 'test' }) }),\n\t\t\tt.Object({ name: t.String() })\n\t\t])\n\n\t\texpect(hasProperty('default', schema)).toBe(true)\n\t})\n\n\tit('finds property in Intersect schema', () => {\n\t\tconst schema = t.Intersect([\n\t\t\tt.Object({ name: t.String({ default: 'test' }) }),\n\t\t\tt.Object({ age: t.Number() })\n\t\t])\n\n\t\texpect(hasProperty('default', schema)).toBe(true)\n\t})\n\n\tit('returns false when property not in any Union member', () => {\n\t\tconst schema = t.Union([\n\t\t\tt.Object({ name: t.String() }),\n\t\t\tt.Object({ age: t.Number() })\n\t\t])\n\n\t\texpect(hasProperty('default', schema)).toBe(false)\n\t})\n\n\tit('finds property in nested Union within Object', () => {\n\t\tconst schema = t.Object({\n\t\t\tdata: t.Union([t.String({ default: 'hello' }), t.Number()])\n\t\t})\n\n\t\texpect(hasProperty('default', schema)).toBe(true)\n\t})\n\n\tit('finds property in oneOf schema', () => {\n\t\tconst schema = {\n\t\t\toneOf: [\n\t\t\t\tt.Object({ name: t.String({ default: 'test' }) }),\n\t\t\t\tt.Object({ name: t.String() })\n\t\t\t]\n\t\t}\n\n\t\texpect(hasProperty('default', schema as any)).toBe(true)\n\t})\n\n\tit('returns false for undefined schema', () => {\n\t\texpect(hasProperty('default', undefined as any)).toBe(false)\n\t})\n\n\tit('handles deeply nested structures', () => {\n\t\tconst schema = t.Union([\n\t\t\tt.Intersect([\n\t\t\t\tt.Object({\n\t\t\t\t\tconfig: t.Object({\n\t\t\t\t\t\tvalue: t.String({ default: 'nested' })\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t])\n\t\t])\n\n\t\texpect(hasProperty('default', schema)).toBe(true)\n\t})\n})\n"
  },
  {
    "path": "test/standard-schema/reference.test.ts",
    "content": "import { Elysia } from '../../src'\nimport { describe, it, expect } from 'bun:test'\nimport { z } from 'zod'\nimport { post, req } from '../utils'\n\ndescribe('Standard Schema Validate', () => {\n\tit('validate body', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tbody: z.object({\n\t\t\t\t\tid: z.number()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tbody: 'body'\n\t\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\tpost('/', {\n\t\t\t\t\tid: 1\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({ id: 1 })\n\n\t\tconst invalid = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tid: '1'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate query', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tquery: z.object({\n\t\t\t\t\tid: z.coerce.number()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', ({ query }) => query, {\n\t\t\t\tquery: 'query'\n\t\t\t})\n\n\t\tconst value = await app.handle(req('/?id=1')).then((x) => x.json())\n\n\t\texpect(value).toEqual({ id: 1 })\n\n\t\tconst invalid = await app.handle(req('/?id=a'))\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate params', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tparams: z.object({\n\t\t\t\t\tid: z.coerce.number()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/user/:id', ({ params }) => params, {\n\t\t\t\tparams: 'params'\n\t\t\t})\n\n\t\tconst value = await app.handle(req('/user/1')).then((x) => x.json())\n\n\t\texpect(value).toEqual({ id: 1 })\n\n\t\tconst invalid = await app.handle(req('/user/a'))\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate headers', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\theaders: z.object({\n\t\t\t\t\tid: z.coerce.number()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', ({ headers }) => headers, {\n\t\t\t\theaders: 'headers'\n\t\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tid: '1'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({ id: 1 })\n\n\t\tconst invalid = await app.handle(req('/', {}))\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate single response', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tresponse: z.boolean()\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/:name',\n\t\t\t\t// @ts-expect-error\n\t\t\t\t({ params: { name } }) =>\n\t\t\t\t\tname === 'lilith' ? undefined : true,\n\t\t\t\t{\n\t\t\t\t\tresponse: 'response'\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst exists = await app.handle(req('/fouco'))\n\t\tconst nonExists = await app.handle(req('/lilith'))\n\n\t\texpect(exists.status).toBe(200)\n\t\texpect(nonExists.status).toBe(422)\n\t})\n\n\tit('validate multiple response', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\t'response.404': z.literal('lilith'),\n\t\t\t\t'response.418': z.literal('fouco')\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/:name',\n\t\t\t\t({ params: { name }, status }) =>\n\t\t\t\t\tname === 'lilith'\n\t\t\t\t\t\t? status(404, 'lilith')\n\t\t\t\t\t\t: status(418, name as any),\n\t\t\t\t{\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t404: 'response.404',\n\t\t\t\t\t\t418: 'response.418'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst exists = await app.handle(req('/fouco'))\n\t\tconst nonExists = await app.handle(req('/lilith'))\n\n\t\texpect(exists.status).toBe(418)\n\t\texpect(nonExists.status).toBe(404)\n\n\t\tconst invalid = await app.handle(req('/unknown'))\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate multiple schema together', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tbody: z.object({\n\t\t\t\t\tid: z.number()\n\t\t\t\t}),\n\t\t\t\tquery: z.object({\n\t\t\t\t\tlimit: z.coerce.number()\n\t\t\t\t}),\n\t\t\t\tparams: z.object({\n\t\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t\t}),\n\t\t\t\t'response.404': z.literal('lilith'),\n\t\t\t\t'response.418': z.literal('fouco')\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/:name',\n\t\t\t\t({ params: { name }, status }) =>\n\t\t\t\t\tname === 'lilith'\n\t\t\t\t\t\t? status(404, 'lilith')\n\t\t\t\t\t\t: status(418, name as any),\n\t\t\t\t{\n\t\t\t\t\tbody: 'body',\n\t\t\t\t\tquery: 'query',\n\t\t\t\t\tparams: 'params',\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t404: 'response.404',\n\t\t\t\t\t\t418: 'response.418'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst responses = await Promise.all(\n\t\t\t[\n\t\t\t\tpost('/lilith?limit=1', {\n\t\t\t\t\tid: 1\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=10', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/unknown?limit=10', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=a', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=10', {\n\t\t\t\t\tid: '2'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco', {})\n\t\t\t].map((x) => app.handle(x).then((x) => x.status))\n\t\t)\n\n\t\texpect(responses[0]).toEqual(404)\n\t\texpect(responses[1]).toEqual(418)\n\t\texpect(responses[2]).toEqual(422)\n\t\texpect(responses[3]).toEqual(422)\n\t\texpect(responses[4]).toEqual(422)\n\t\texpect(responses[5]).toEqual(422)\n\t})\n\n\tit('merge guard', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tbody: z.object({\n\t\t\t\t\tid: z.number()\n\t\t\t\t}),\n\t\t\t\tquery: z.object({\n\t\t\t\t\tlimit: z.coerce.number()\n\t\t\t\t}),\n\t\t\t\tparams: z.object({\n\t\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t\t}),\n\t\t\t\t'response.404': z.literal('lilith'),\n\t\t\t\t'response.418': z.literal('fouco')\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tbody: 'body',\n\t\t\t\tquery: 'query',\n\t\t\t\tresponse: {\n\t\t\t\t\t404: 'response.404'\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/:name',\n\t\t\t\t({ params: { name }, status }) =>\n\t\t\t\t\tname === 'lilith'\n\t\t\t\t\t\t? status(404, 'lilith')\n\t\t\t\t\t\t: status(418, name as any),\n\t\t\t\t{\n\t\t\t\t\tparams: 'params',\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t418: 'response.418'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst responses = await Promise.all(\n\t\t\t[\n\t\t\t\tpost('/lilith?limit=1', {\n\t\t\t\t\tid: 1\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=10', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/unknown?limit=10', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=a', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=10', {\n\t\t\t\t\tid: '2'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco', {})\n\t\t\t].map((x) => app.handle(x).then((x) => x.status))\n\t\t)\n\n\t\texpect(responses[0]).toEqual(404)\n\t\texpect(responses[1]).toEqual(418)\n\t\texpect(responses[2]).toEqual(422)\n\t\texpect(responses[3]).toEqual(422)\n\t\texpect(responses[4]).toEqual(422)\n\t\texpect(responses[5]).toEqual(422)\n\t})\n\n\tit('merge plugin', async () => {\n\t\tconst plugin = new Elysia()\n\t\t\t.model({\n\t\t\t\tbody: z.object({\n\t\t\t\t\tid: z.number()\n\t\t\t\t}),\n\t\t\t\tquery: z.object({\n\t\t\t\t\tlimit: z.coerce.number()\n\t\t\t\t}),\n\t\t\t\tparams: z.object({\n\t\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t\t}),\n\t\t\t\t'response.404': z.literal('lilith'),\n\t\t\t\t'response.418': z.literal('fouco')\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tbody: 'body',\n\t\t\t\tquery: 'query',\n\t\t\t\tresponse: {\n\t\t\t\t\t404: 'response.404'\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.post(\n\t\t\t\t'/:name',\n\t\t\t\t({ params: { name }, status }) =>\n\t\t\t\t\tname === 'lilith'\n\t\t\t\t\t\t? status(404, 'lilith')\n\t\t\t\t\t\t: status(418, name as any),\n\t\t\t\t{\n\t\t\t\t\tparams: z.object({\n\t\t\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t\t\t}),\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t418: 'response.418'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst responses = await Promise.all(\n\t\t\t[\n\t\t\t\tpost('/lilith?limit=1', {\n\t\t\t\t\tid: 1\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=10', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/unknown?limit=10', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=a', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=10', {\n\t\t\t\t\tid: '2'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco', {})\n\t\t\t].map((x) => app.handle(x).then((x) => x.status))\n\t\t)\n\n\t\texpect(responses[0]).toEqual(404)\n\t\texpect(responses[1]).toEqual(418)\n\t\texpect(responses[2]).toEqual(422)\n\t\texpect(responses[3]).toEqual(422)\n\t\texpect(responses[4]).toEqual(422)\n\t\texpect(responses[5]).toEqual(422)\n\t})\n})\n"
  },
  {
    "path": "test/standard-schema/standalone.test.ts",
    "content": "import { Elysia, t } from '../../src'\nimport { describe, it, expect } from 'bun:test'\nimport { z } from 'zod'\nimport * as v from 'valibot'\nimport { type } from 'arktype'\nimport { post, req } from '../utils'\n\ndescribe('Standard Schema Standalone', () => {\n\tit('validate and normalize body', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: z.object({\n\t\t\t\t\tid: z.number()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\tpost('/', {\n\t\t\t\t\tid: 1,\n\t\t\t\t\tname: 'lilith',\n\t\t\t\t\textra: false\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({ id: 1, name: 'lilith' })\n\n\t\tconst invalid = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tid: '1',\n\t\t\t\tname: 'fouco',\n\t\t\t\textra: false\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate query', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tquery: z.object({\n\t\t\t\t\tid: z.coerce.number()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', ({ query }) => query, {\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(req('/?id=1&name=lilith&extra=true'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({ id: 1, name: 'lilith' })\n\n\t\tconst invalid = await app.handle(req('/?id=a&name=fouco'))\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate and normalize params', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tparams: z.object({\n\t\t\t\t\tid: z.coerce.number()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/:name/:id', ({ params }) => params, {\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst value = await app.handle(req('/lilith/1')).then((x) => x.json())\n\n\t\texpect(value).toEqual({ id: 1, name: 'lilith' })\n\n\t\tconst invalid = await app.handle(req('/user/a?name=fouco'))\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate and normalize headers', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\theaders: z.object({\n\t\t\t\t\tid: z.coerce.number()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', ({ headers }) => headers, {\n\t\t\t\theaders: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tid: '1',\n\t\t\t\t\t\tname: 'lilith',\n\t\t\t\t\t\textra: 'false'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({ id: 1, name: 'lilith' })\n\n\t\tconst invalid = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tid: 'a',\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate and normalize single response', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tresponse: z.object({\n\t\t\t\t\tid: z.number()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/:name',\n\t\t\t\t// @ts-expect-error\n\t\t\t\t({ params: { name } }) => ({\n\t\t\t\t\tname,\n\t\t\t\t\tid: name !== 'lilith' ? undefined : 1,\n\t\t\t\t\textra: false\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: t.Object({\n\t\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst valid = await app.handle(req('/lilith')).then((x) => x.json())\n\n\t\texpect(valid).toEqual({ id: 1, name: 'lilith' })\n\n\t\tconst invalid = await app.handle(req('/focou'))\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate and normalize multiple response', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tresponse: {\n\t\t\t\t\t404: z.object({\n\t\t\t\t\t\tid: z.number()\n\t\t\t\t\t}),\n\t\t\t\t\t418: z.object({\n\t\t\t\t\t\tid: z.number()\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/:name',\n\t\t\t\t({ params: { name }, status }) =>\n\t\t\t\t\tname === 'lilith'\n\t\t\t\t\t\t? status(404, {\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\tid: 1,\n\t\t\t\t\t\t\t\textra: false\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: status(418, {\n\t\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\tid: 2,\n\t\t\t\t\t\t\t\textra: false\n\t\t\t\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t404: t.Object({\n\t\t\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t418: t.Object({\n\t\t\t\t\t\t\tname: t.Literal('fouco')\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst lilith = await app.handle(req('/lilith')).then((x) => x.json())\n\t\tconst fouco = await app.handle(req('/fouco')).then((x) => x.json())\n\n\t\texpect(lilith).toEqual({ id: 1, name: 'lilith' })\n\t\texpect(fouco).toEqual({ id: 2, name: 'fouco' })\n\n\t\tconst invalid = await app.handle(req('/unknown'))\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate multiple schema together', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(({ error, code }) => {\n\t\t\t\tif (code !== 'VALIDATION') console.log(error)\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: z.object({\n\t\t\t\t\tname: z.string()\n\t\t\t\t}),\n\t\t\t\tquery: z.object({\n\t\t\t\t\tid: z.coerce.number()\n\t\t\t\t}),\n\t\t\t\tparams: z.object({\n\t\t\t\t\tid: z.coerce.number()\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t404: z.object({\n\t\t\t\t\t\tid: z.number()\n\t\t\t\t\t}),\n\t\t\t\t\t418: z.object({\n\t\t\t\t\t\tid: z.number()\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/:name/:id',\n\t\t\t\t({ params: { name, id }, status }) =>\n\t\t\t\t\tname === 'lilith'\n\t\t\t\t\t\t? status(404, {\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\textra: true\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: status(418, {\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\textra: true\n\t\t\t\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({\n\t\t\t\t\t\tid: t.Number()\n\t\t\t\t\t}),\n\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\tlimit: t.Number()\n\t\t\t\t\t}),\n\t\t\t\t\tparams: t.Object({\n\t\t\t\t\t\tname: t.UnionEnum(['fouco', 'lilith'])\n\t\t\t\t\t}),\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t404: z.object({ name: z.literal('lilith') }),\n\t\t\t\t\t\t418: z.object({ name: z.literal('fouco') })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst responses = await Promise.all(\n\t\t\t[\n\t\t\t\tpost('/lilith/1?limit=1&id=1', {\n\t\t\t\t\tid: 1,\n\t\t\t\t\tname: 'lilith'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/2?limit=10&id=2', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/unknown/2?limit=10&id=2', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/2?limit=a&id=2', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/2?limit=10&id=2', {\n\t\t\t\t\tid: '2',\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/2', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/a?limit=10&id=2', {})\n\t\t\t].map((x) => app.handle(x).then((x) => x.status))\n\t\t)\n\n\t\texpect(responses[0]).toEqual(404)\n\t\texpect(responses[1]).toEqual(418)\n\t\texpect(responses[2]).toEqual(422)\n\t\texpect(responses[3]).toEqual(422)\n\t\texpect(responses[4]).toEqual(422)\n\t\texpect(responses[5]).toEqual(422)\n\t\texpect(responses[6]).toEqual(422)\n\t})\n\n\tit('merge plugin', async () => {\n\t\tconst plugin = new Elysia().guard({\n\t\t\tas: 'scoped',\n\t\t\tschema: 'standalone',\n\t\t\tresponse: {\n\t\t\t\t404: z.object({\n\t\t\t\t\tid: z.number()\n\t\t\t\t}),\n\t\t\t\t418: z.object({\n\t\t\t\t\tid: z.number()\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\n\t\tconst app = new Elysia().use(plugin).get(\n\t\t\t'/:name',\n\t\t\t({ params: { name }, status }) =>\n\t\t\t\tname === 'lilith'\n\t\t\t\t\t? status(404, {\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tid: 1,\n\t\t\t\t\t\t\textra: false\n\t\t\t\t\t\t})\n\t\t\t\t\t: status(418, {\n\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tid: 2,\n\t\t\t\t\t\t\textra: false\n\t\t\t\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t404: t.Object({\n\t\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t\t}),\n\t\t\t\t\t418: t.Object({\n\t\t\t\t\t\tname: t.Literal('fouco')\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst lilith = await app.handle(req('/lilith')).then((x) => x.json())\n\t\tconst fouco = await app.handle(req('/fouco')).then((x) => x.json())\n\n\t\texpect(lilith).toEqual({ id: 1, name: 'lilith' })\n\t\texpect(fouco).toEqual({ id: 2, name: 'fouco' })\n\n\t\tconst invalid = await app.handle(req('/unknown'))\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate non-typebox schema', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: z.object({\n\t\t\t\t\tname: z.string()\n\t\t\t\t}),\n\t\t\t\tquery: z.object({\n\t\t\t\t\tid: z.coerce.number()\n\t\t\t\t}),\n\t\t\t\tparams: z.object({\n\t\t\t\t\tid: z.coerce.number()\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t404: z.object({\n\t\t\t\t\t\tid: z.number()\n\t\t\t\t\t}),\n\t\t\t\t\t418: z.object({\n\t\t\t\t\t\tid: z.number()\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/:name/:id',\n\t\t\t\t({ params: { name, id }, status }) =>\n\t\t\t\t\tname === 'lilith'\n\t\t\t\t\t\t? status(404, {\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\textra: true\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: status(418, {\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\textra: true\n\t\t\t\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tbody: v.object({\n\t\t\t\t\t\tid: v.number()\n\t\t\t\t\t}),\n\t\t\t\t\tquery: v.object({\n\t\t\t\t\t\tlimit: v.pipe(\n\t\t\t\t\t\t\tv.string(),\n\t\t\t\t\t\t\tv.transform(Number),\n\t\t\t\t\t\t\tv.number()\n\t\t\t\t\t\t)\n\t\t\t\t\t}),\n\t\t\t\t\tparams: v.object({\n\t\t\t\t\t\tname: v.union([v.literal('fouco'), v.literal('lilith')])\n\t\t\t\t\t}),\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t404: v.object({ name: v.literal('lilith') }),\n\t\t\t\t\t\t418: v.object({ name: v.literal('fouco') })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst responses = await Promise.all(\n\t\t\t[\n\t\t\t\tpost('/lilith/1?limit=1&id=1', {\n\t\t\t\t\tid: 1,\n\t\t\t\t\tname: 'lilith'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/2?limit=10&id=2', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/unknown/2?limit=10&id=2', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/2?limit=a&id=2', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/2?limit=10&id=2', {\n\t\t\t\t\tid: '2',\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/2', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/a?limit=10&id=2', {})\n\t\t\t].map((x) => app.handle(x).then((x) => x.status))\n\t\t)\n\n\t\texpect(responses[0]).toEqual(404)\n\t\texpect(responses[1]).toEqual(418)\n\t\texpect(responses[2]).toEqual(422)\n\t\texpect(responses[3]).toEqual(422)\n\t\texpect(responses[4]).toEqual(422)\n\t\texpect(responses[5]).toEqual(422)\n\t\texpect(responses[6]).toEqual(422)\n\t})\n\n\tit('validate 3 schema validators without TypeBox', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: z.object({\n\t\t\t\t\tname: z.string()\n\t\t\t\t}),\n\t\t\t\tquery: z.object({\n\t\t\t\t\tid: z.coerce.number()\n\t\t\t\t}),\n\t\t\t\tparams: z.object({\n\t\t\t\t\tid: z.coerce.number()\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t404: z.object({\n\t\t\t\t\t\tid: z.number()\n\t\t\t\t\t}),\n\t\t\t\t\t418: z.object({\n\t\t\t\t\t\tid: z.number()\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: type({\n\t\t\t\t\tworld: '\"fantasy\"'\n\t\t\t\t}),\n\t\t\t\tquery: type({\n\t\t\t\t\tworld: '\"fantasy\"'\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t404: type({\n\t\t\t\t\t\tworld: '\"fantasy\"'\n\t\t\t\t\t}),\n\t\t\t\t\t418: type({\n\t\t\t\t\t\tworld: '\"fantasy\"'\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/:name/:id',\n\t\t\t\t({ params: { name, id }, status }) =>\n\t\t\t\t\tname === 'lilith'\n\t\t\t\t\t\t? status(404, {\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\tworld: 'fantasy'\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: status(418, {\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\tworld: 'fantasy'\n\t\t\t\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tbody: v.object({\n\t\t\t\t\t\tid: v.number()\n\t\t\t\t\t}),\n\t\t\t\t\tquery: v.object({\n\t\t\t\t\t\tlimit: v.pipe(\n\t\t\t\t\t\t\tv.string(),\n\t\t\t\t\t\t\tv.transform(Number),\n\t\t\t\t\t\t\tv.number()\n\t\t\t\t\t\t)\n\t\t\t\t\t}),\n\t\t\t\t\tparams: v.object({\n\t\t\t\t\t\tname: v.union([v.literal('fouco'), v.literal('lilith')])\n\t\t\t\t\t}),\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t404: v.object({ name: v.literal('lilith') }),\n\t\t\t\t\t\t418: v.object({ name: v.literal('fouco') })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst responses = await Promise.all(\n\t\t\t[\n\t\t\t\tpost('/lilith/1?limit=1&id=1&world=fantasy', {\n\t\t\t\t\tid: 1,\n\t\t\t\t\tname: 'lilith',\n\t\t\t\t\tworld: 'fantasy'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/2?limit=10&id=2&world=fantasy', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco',\n\t\t\t\t\tworld: 'fantasy'\n\t\t\t\t}),\n\t\t\t\tpost('/unknown/2?limit=10&id=2&world=fantasy', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco',\n\t\t\t\t\tworld: 'fantasy'\n\t\t\t\t}),\n\t\t\t\tpost('/unknown/2?limit=10&id=2', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/2?limit=a&id=2', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/2?limit=10&id=2', {\n\t\t\t\t\tid: '2',\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/2', {\n\t\t\t\t\tid: 2,\n\t\t\t\t\tname: 'fouco'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco/a?limit=10&id=2', {})\n\t\t\t].map((x) => app.handle(x).then((x) => x.status))\n\t\t)\n\n\t\texpect(responses[0]).toEqual(404)\n\t\texpect(responses[1]).toEqual(418)\n\t\texpect(responses[2]).toEqual(422)\n\t\texpect(responses[3]).toEqual(422)\n\t\texpect(responses[4]).toEqual(422)\n\t\texpect(responses[5]).toEqual(422)\n\t\texpect(responses[6]).toEqual(422)\n\t\texpect(responses[7]).toEqual(422)\n\t})\n})\n"
  },
  {
    "path": "test/standard-schema/validate.test.ts",
    "content": "import { Elysia } from '../../src'\nimport { describe, it, expect } from 'bun:test'\nimport { z } from 'zod'\nimport { post, req } from '../utils'\n\ndescribe('Standard Schema Validate', () => {\n\tit('validate body', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: z.object({\n\t\t\t\tid: z.number()\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\tpost('/', {\n\t\t\t\t\tid: 1\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({ id: 1 })\n\n\t\tconst invalid = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tid: '1'\n\t\t\t})\n\t\t)\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate query', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: z.object({\n\t\t\t\tid: z.coerce.number()\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app.handle(req('/?id=1')).then((x) => x.json())\n\n\t\texpect(value).toEqual({ id: 1 })\n\n\t\tconst invalid = await app.handle(req('/?id=a'))\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate params', async () => {\n\t\tconst app = new Elysia().get('/user/:id', ({ params }) => params, {\n\t\t\tparams: z.object({\n\t\t\t\tid: z.coerce.number()\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app.handle(req('/user/1')).then((x) => x.json())\n\n\t\texpect(value).toEqual({ id: 1 })\n\n\t\tconst invalid = await app.handle(req('/user/a'))\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate headers', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: z.object({\n\t\t\t\tid: z.coerce.number()\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tid: '1'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({ id: 1 })\n\n\t\tconst invalid = await app.handle(req('/', {}))\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate single response', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/:name',\n\t\t\t// @ts-expect-error\n\t\t\t({ params: { name } }) => (name === 'lilith' ? undefined : true),\n\t\t\t{\n\t\t\t\tresponse: z.boolean()\n\t\t\t}\n\t\t)\n\n\t\tconst exists = await app.handle(req('/fouco'))\n\t\tconst nonExists = await app.handle(req('/lilith'))\n\n\t\texpect(exists.status).toBe(200)\n\t\texpect(nonExists.status).toBe(422)\n\t})\n\n\tit('validate multiple response', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/:name',\n\t\t\t({ params: { name }, status }) =>\n\t\t\t\tname === 'lilith'\n\t\t\t\t\t? status(404, 'lilith')\n\t\t\t\t\t: status(418, name as any),\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t404: z.literal('lilith'),\n\t\t\t\t\t418: z.literal('fouco')\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst exists = await app.handle(req('/fouco'))\n\t\tconst nonExists = await app.handle(req('/lilith'))\n\n\t\texpect(exists.status).toBe(418)\n\t\texpect(nonExists.status).toBe(404)\n\n\t\tconst invalid = await app.handle(req('/unknown'))\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate multiple schema together', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/:name',\n\t\t\t({ params: { name }, status }) =>\n\t\t\t\tname === 'lilith'\n\t\t\t\t\t? status(404, 'lilith')\n\t\t\t\t\t: status(418, name as any),\n\t\t\t{\n\t\t\t\tbody: z.object({\n\t\t\t\t\tid: z.number()\n\t\t\t\t}),\n\t\t\t\tquery: z.object({\n\t\t\t\t\tlimit: z.coerce.number()\n\t\t\t\t}),\n\t\t\t\tparams: z.object({\n\t\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t404: z.literal('lilith'),\n\t\t\t\t\t418: z.literal('fouco')\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst responses = await Promise.all(\n\t\t\t[\n\t\t\t\tpost('/lilith?limit=1', {\n\t\t\t\t\tid: 1\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=10', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/unknown?limit=10', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=a', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=10', {\n\t\t\t\t\tid: '2'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco', {})\n\t\t\t].map((x) => app.handle(x).then((x) => x.status))\n\t\t)\n\n\t\texpect(responses[0]).toEqual(404)\n\t\texpect(responses[1]).toEqual(418)\n\t\texpect(responses[2]).toEqual(422)\n\t\texpect(responses[3]).toEqual(422)\n\t\texpect(responses[4]).toEqual(422)\n\t\texpect(responses[5]).toEqual(422)\n\t})\n\n\tit('merge guard', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tbody: z.object({\n\t\t\t\t\tid: z.number()\n\t\t\t\t}),\n\t\t\t\tquery: z.object({\n\t\t\t\t\tlimit: z.coerce.number()\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t404: z.literal('lilith')\n\t\t\t\t}\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/:name',\n\t\t\t\t({ params: { name }, status }) =>\n\t\t\t\t\tname === 'lilith'\n\t\t\t\t\t\t? status(404, 'lilith')\n\t\t\t\t\t\t: status(418, name as any),\n\t\t\t\t{\n\t\t\t\t\tparams: z.object({\n\t\t\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t\t\t}),\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t418: z.literal('fouco')\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst responses = await Promise.all(\n\t\t\t[\n\t\t\t\tpost('/lilith?limit=1', {\n\t\t\t\t\tid: 1\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=10', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/unknown?limit=10', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=a', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=10', {\n\t\t\t\t\tid: '2'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco', {})\n\t\t\t].map((x) => app.handle(x).then((x) => x.status))\n\t\t)\n\n\t\texpect(responses[0]).toEqual(404)\n\t\texpect(responses[1]).toEqual(418)\n\t\texpect(responses[2]).toEqual(422)\n\t\texpect(responses[3]).toEqual(422)\n\t\texpect(responses[4]).toEqual(422)\n\t\texpect(responses[5]).toEqual(422)\n\t})\n\n\tit('merge plugin', async () => {\n\t\tconst plugin = new Elysia().guard({\n\t\t\tas: 'scoped',\n\t\t\tbody: z.object({\n\t\t\t\tid: z.number()\n\t\t\t}),\n\t\t\tquery: z.object({\n\t\t\t\tlimit: z.coerce.number()\n\t\t\t}),\n\t\t\tresponse: {\n\t\t\t\t404: z.literal('lilith')\n\t\t\t}\n\t\t})\n\n\t\tconst app = new Elysia()\n\t\t\t.use(plugin)\n\t\t\t.post(\n\t\t\t\t'/:name',\n\t\t\t\t({ params: { name }, status }) =>\n\t\t\t\t\tname === 'lilith'\n\t\t\t\t\t\t? status(404, 'lilith')\n\t\t\t\t\t\t: status(418, name as any),\n\t\t\t\t{\n\t\t\t\t\tparams: z.object({\n\t\t\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t\t\t}),\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t418: z.literal('fouco')\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst responses = await Promise.all(\n\t\t\t[\n\t\t\t\tpost('/lilith?limit=1', {\n\t\t\t\t\tid: 1\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=10', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/unknown?limit=10', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=a', {\n\t\t\t\t\tid: 2\n\t\t\t\t}),\n\t\t\t\tpost('/fouco?limit=10', {\n\t\t\t\t\tid: '2'\n\t\t\t\t}),\n\t\t\t\tpost('/fouco', {})\n\t\t\t].map((x) => app.handle(x).then((x) => x.status))\n\t\t)\n\n\t\texpect(responses[0]).toEqual(404)\n\t\texpect(responses[1]).toEqual(418)\n\t\texpect(responses[2]).toEqual(422)\n\t\texpect(responses[3]).toEqual(422)\n\t\texpect(responses[4]).toEqual(422)\n\t\texpect(responses[5]).toEqual(422)\n\t})\n\n\tit('handle cookie', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'test',\n\t\t\t({ cookie: { test } }) => typeof test.value,\n\t\t\t{\n\t\t\t\tcookie: z.object({ test: z.coerce.number() })\n\t\t\t}\n\t\t)\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost:3000/test', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tcookie: 'test=123'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.text())\n\n\t\texpect(value).toBe('number')\n\t})\n})\n"
  },
  {
    "path": "test/sucrose/bracket-pair-range-reverse.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\n\nimport { bracketPairRangeReverse } from '../../src/sucrose'\n\ndescribe('bracket pair range reverse', () => {\n\tit('return the correct range when given a string with a single bracket pair', () => {\n\t\tconst parameter = 'hello: { world: { a } }, elysia'\n\t\tconst result = bracketPairRangeReverse(parameter)\n\t\texpect(result).toEqual([7, 23])\n\t})\n\n\tit('return the correct range when given a string with nested bracket pairs', () => {\n\t\tconst parameter = 'hello: { world: { a } }, elysia'\n\t\tconst result = bracketPairRangeReverse(parameter)\n\t\texpect(result).toEqual([7, 23])\n\t})\n\n\tit('return [-1, 0] when given a string without any bracket pairs', () => {\n\t\tconst parameter = 'hello, elysia'\n\t\tconst result = bracketPairRangeReverse(parameter)\n\t\texpect(result).toEqual([-1, 0])\n\t})\n\n\tit('return [0, 1] when given a string with a single opening bracket at the beginning', () => {\n\t\tconst parameter = '{hello, elysia'\n\t\tconst result = bracketPairRangeReverse(parameter)\n\t\texpect(result).toEqual([-1, 0])\n\t})\n\n\tit('return [parameter.length - 1, parameter.length] when given a string with a single closing bracket at the end', () => {\n\t\tconst parameter = 'hello, elysia}'\n\t\tconst result = bracketPairRangeReverse(parameter)\n\t\texpect(result).toEqual([-1, 0])\n\t})\n\n\tit('return [-1, 0] when given an empty string', () => {\n\t\tconst parameter = ''\n\t\tconst result = bracketPairRangeReverse(parameter)\n\t\texpect(result).toEqual([-1, 0])\n\t})\n\n\tit('return the correct range when given a string with multiple bracket pairs', () => {\n\t\tconst parameter = 'hello: { world: { a } }, elysia'\n\t\tconst result = bracketPairRangeReverse(parameter)\n\t\texpect(result).toEqual([7, 23])\n\t})\n\n\tit('return the correct range when given a string with an opening bracket but no closing bracket', () => {\n\t\tconst parameter = 'hello: { world: { a }, elysia'\n\t\tconst result = bracketPairRangeReverse(parameter)\n\t\texpect(result).toEqual([16, 21])\n\t})\n\n\tit('return the correct range when given a string with brackets inside quotes', () => {\n\t\tconst parameter = 'hello: { world: { a } }, elysia'\n\t\tconst result = bracketPairRangeReverse(parameter)\n\t\texpect(result).toEqual([7, 23])\n\t})\n\n\tit('return the correct range when given a string with nested bracket pairs', () => {\n\t\tconst parameter = 'hello: { world: { a } }, elysia'\n\t\tconst result = bracketPairRangeReverse(parameter)\n\t\texpect(result).toEqual([7, 23])\n\t})\n\n\tit('return the correct range when given a string with non-bracket characters', () => {\n\t\tconst parameter = 'hello: { world: { a } }, elysia'\n\t\tconst result = bracketPairRangeReverse(parameter)\n\t\texpect(result).toEqual([7, 23])\n\t})\n})\n"
  },
  {
    "path": "test/sucrose/bracket-pair-range.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\n\nimport { bracketPairRange } from '../../src/sucrose'\n\ndescribe('bracket pair range', () => {\n\tit('return the correct range when given a string with a single bracket pair', () => {\n\t\tconst parameter = 'hello: { world: { a } }, elysia'\n\t\tconst result = bracketPairRange(parameter)\n\t\texpect(result).toEqual([7, 23])\n\t})\n\n\tit('return the correct range when given a string with nested bracket pairs', () => {\n\t\tconst parameter = 'hello: { world: { a } }, elysia'\n\t\tconst result = bracketPairRange(parameter)\n\t\texpect(result).toEqual([7, 23])\n\t})\n\n\tit('return [-1, 0] when given a string without any bracket pairs', () => {\n\t\tconst parameter = 'hello, elysia'\n\t\tconst result = bracketPairRange(parameter)\n\t\texpect(result).toEqual([-1, 0])\n\t})\n\n\tit('return [0, 1] when given a string with a single opening bracket at the beginning', () => {\n\t\tconst parameter = '{hello, elysia'\n\t\tconst result = bracketPairRange(parameter)\n\t\texpect(result).toEqual([0, 14])\n\t})\n\n\tit('return [parameter.length - 1, parameter.length] when given a string with a single closing bracket at the end', () => {\n\t\tconst parameter = 'hello, elysia}'\n\t\tconst result = bracketPairRange(parameter)\n\t\texpect(result).toEqual([-1, 0])\n\t})\n\n\tit('return [-1, 0] when given an empty string', () => {\n\t\tconst parameter = ''\n\t\tconst result = bracketPairRange(parameter)\n\t\texpect(result).toEqual([-1, 0])\n\t})\n\n\tit('return the correct range when given a string with multiple bracket pairs', () => {\n\t\tconst parameter = 'hello: { world: { a } }, elysia'\n\t\tconst result = bracketPairRange(parameter)\n\t\texpect(result).toEqual([7, 23])\n\t})\n\n\tit('return the correct range when given a string with an opening bracket but no closing bracket', () => {\n\t\tconst parameter = 'hello: { world: { a }, elysia'\n\t\tconst result = bracketPairRange(parameter)\n\t\texpect(result).toEqual([0, parameter.length])\n\t})\n\n\tit('return the correct range when given a string with brackets inside quotes', () => {\n\t\tconst parameter = 'hello: { world: { a } }, elysia'\n\t\tconst result = bracketPairRange(parameter)\n\t\texpect(result).toEqual([7, 23])\n\t})\n\n\tit('return the correct range when given a string with nested bracket pairs', () => {\n\t\tconst parameter = 'hello: { world: { a } }, elysia'\n\t\tconst result = bracketPairRange(parameter)\n\t\texpect(result).toEqual([7, 23])\n\t})\n\n\tit('return the correct range when given a string with non-bracket characters', () => {\n\t\tconst parameter = 'hello: { world: { a } }, elysia'\n\t\tconst result = bracketPairRange(parameter)\n\t\texpect(result).toEqual([7, 23])\n\t})\n})\n"
  },
  {
    "path": "test/sucrose/extract-main-parameter.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { extractMainParameter } from '../../src/sucrose'\n\ndescribe('extract main parameter', () => {\n\tit('extract main parameter when there is no spread operator and only one parameter', () => {\n\t\tconst parameter = 'param1'\n\t\tconst result = extractMainParameter(parameter)\n\t\texpect(result).toBe('param1')\n\t})\n\n\tit('extract main parameter when there is a spread operator and only one parameter', () => {\n\t\tconst parameter = '{ ...param1 }'\n\t\tconst result = extractMainParameter(parameter)\n\t\texpect(result).toBe('param1')\n\t})\n\n\tit('extract main parameter when there are multiple parameters and a spread operator', () => {\n\t\tconst parameter = '{ param1, param2, ...param3 }'\n\t\tconst result = extractMainParameter(parameter)\n\t\texpect(result).toBe('param3')\n\t})\n\n\tit('return undefined when parameter is an empty string', () => {\n\t\tconst parameter = ''\n\t\tconst result = extractMainParameter(parameter)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when parameter is undefined', () => {\n\t\tconst parameter = undefined\n\t\t// @ts-expect-error\n\t\tconst result = extractMainParameter(parameter)\n\t\texpect(result).toBeUndefined()\n\t})\n\n\tit('return undefined when parameter is null', () => {\n\t\tconst parameter = null\n\t\t// @ts-expect-error\n\t\tconst result = extractMainParameter(parameter)\n\t\texpect(result).toBeUndefined()\n\t})\n})\n"
  },
  {
    "path": "test/sucrose/find-alias.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { findAlias } from '../../src/sucrose'\n\ndescribe('find alias', () => {\n\tit('find aliases of a variable in a simple function body', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const a = body, b = body }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a', 'b'])\n\t})\n\n\tit('find aliases of a variable in a function body with multiple assignments', () => {\n\t\tconst type = 'body'\n\t\tconst body = `{ const a = body; const b = body }`\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a', 'b'])\n\t})\n\n\tit('find aliases of a variable in a function body with object destructuring as-is', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const { a, b } = body }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['{ a, b }'])\n\t})\n\n\tit('return an empty array when the variable is not found in the function body', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const a = otherVariable }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual([])\n\t})\n\n\tit('handle a function body with no content', () => {\n\t\tconst type = 'body'\n\t\tconst body = ''\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual([])\n\t})\n\n\tit('handle a function body with only one line', () => {\n\t\tconst type = 'body'\n\t\tconst body = 'const a = body'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a'])\n\t})\n\n\tit('find aliases of a variable in a nested function body', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const a = body, b = { const c = body, d = body } }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a', 'c', 'd'])\n\t})\n\n\tit('find aliases of a variable in a function body with comments', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const a = body, b = body }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a', 'b'])\n\t})\n\n\tit('find aliases of a variable in a function body with multiple lines', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const a = body,\\n  b = body }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a', 'b'])\n\t})\n\n\tit('find aliases of a variable in a nested function body', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const a = body, b = { const c = body, d = body } }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a', 'c', 'd'])\n\t})\n\n\tit('find aliases of a variable in a function body with mixed quotes', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const a = body, b = body }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a', 'b'])\n\t})\n\n\tit('handle aliases of a variable in a function body with mixed spaces and tabs', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const a = body,\\tb = body }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a', 'b'])\n\t})\n\n\tit('find aliases of a variable in a simple function body', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const a = body, b = body }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a', 'b'])\n\t})\n\n\tit('find aliases of a variable in a simple function body', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const a = body, b = body }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a', 'b'])\n\t})\n\n\tit('find aliases of a variable in a function body with a variable name that starts with an underscore', () => {\n\t\tconst type = '_body'\n\t\tconst body = '{ const _a = _body, _b = _body }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['_a', '_b'])\n\t})\n\n\tit('find aliases of a variable in a function body with a variable name that starts with a number', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const 1a = body, b = body }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['1a', 'b'])\n\t})\n\n\tit('find aliases of a variable in a function body with a variable name that contains a dot', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const a.b = body, b = body }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a.b', 'b'])\n\t})\n\n\tit('find aliases of a variable in a function body with a hyphenated variable name', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const a-b = body, b = body }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['a-b', 'b'])\n\t})\n\n\tit('find aliases of a variable in a function body with a variable name that contains a dollar sign', () => {\n\t\tconst type = 'body'\n\t\tconst body = '{ const $a = body, b = $a }'\n\n\t\tconst aliases = findAlias(type, body)\n\t\texpect(aliases).toEqual(['$a', 'b'])\n\t})\n})\n"
  },
  {
    "path": "test/sucrose/infer-body-reference.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { inferBodyReference, Sucrose } from '../../src/sucrose'\n\ndescribe('infer body reference', () => {\n\tit('infer dot notation', () => {\n\t\tconst code = 'context.body.a'\n\t\tconst aliases = ['context']\n\t\tconst inference = {\n\t\t\tquery: false,\n\t\t\theaders: false,\n\t\t\tbody: false,\n\t\t\tcookie: false,\n\t\t\tset: false,\n\t\t\tserver: false,\n\t\t\tpath: false,\n\t\t\troute: false,\n\t\t\turl: false\n\t\t} satisfies Sucrose.Inference\n\n\t\tinferBodyReference(code, aliases, inference)\n\n\t\texpect(inference.body as boolean).toBe(true)\n\t})\n\n\tit('infer property access', () => {\n\t\tconst code = 'context[\"body\"][\"a\"]'\n\t\tconst aliases = ['context']\n\t\tconst inference = {\n\t\t\tquery: false,\n\t\t\theaders: false,\n\t\t\tbody: false,\n\t\t\tcookie: false,\n\t\t\tset: false,\n\t\t\tserver: false,\n\t\t\tpath: false,\n\t\t\troute: false,\n\t\t\turl: false\n\t\t} satisfies Sucrose.Inference\n\n\t\tinferBodyReference(code, aliases, inference)\n\n\t\texpect(inference.body as boolean).toBe(true)\n\t})\n\n\tit('infer multiple query', () => {\n\t\tconst code = `{\n\t\t\tconsole.log({ a: query.quack }, {\n\t\t\t\tb: query.duck\n\t\t\t});\n\t\t\tconst b = query.bark;\n\t\t\treturn \"a\";\n\t\t}`\n\n\t\tconst aliases = ['query']\n\t\tconst inference = {\n\t\t\tbody: false,\n\t\t\tcookie: false,\n\t\t\theaders: false,\n\t\t\tquery: true,\n\t\t\tset: true,\n\t\t\tserver: false,\n\t\t\tpath: false,\n\t\t\troute: false,\n\t\t\turl: false\n\t\t} satisfies Sucrose.Inference\n\n\t\tinferBodyReference(code, aliases, inference)\n\n\t\texpect(inference).toEqual({\n\t\t\tbody: false,\n\t\t\tcookie: false,\n\t\t\theaders: false,\n\t\t\tquery: true,\n\t\t\tset: true,\n\t\t\tserver: false,\n\t\t\tpath: false,\n\t\t\troute: false,\n\t\t\turl: false\n\t\t})\n\t})\n\n\t// This is not use in Bun\n\t// it('infer single quote query', () => {\n\t// \tconst code = `{\n\t// \t\tconst b = query['quack'];\n\t// \t\treturn \"a\";\n\t// \t}`\n\n\t// \tconst aliases = ['query']\n\t// \tconst inference = {\n\t// \t\tbody: false,\n\t// \t\tcookie: false,\n\t// \t\theaders: false,\n\t// \t\tqueries: <string[]>[],\n\t// \t\tquery: true,\n\t// \t\tset: true,\n\t// \t\tunknownQueries: false\n\t// \t}\n\n\t// \tinferBodyReference(code, aliases, inference)\n\n\t// \texpect(inference).toEqual({\n\t// \t\tbody: false,\n\t// \t\tcookie: false,\n\t// \t\theaders: false,\n\t// \t\tqueries: ['quack'],\n\t// \t\tquery: true,\n\t// \t\tset: true,\n\t// \t\tunknownQueries: false\n\t// \t})\n\t// })\n\n\t// it('infer double quote query', () => {\n\t// \tconst code = `{\n\t// \t\tconst b = query[\"quack\"];\n\t// \t\treturn \"a\";\n\t// \t}`\n\n\t// \tconst aliases = ['query']\n\t// \tconst inference = {\n\t// \t\tbody: false,\n\t// \t\tcookie: false,\n\t// \t\theaders: false,\n\t// \t\tqueries: <string[]>[],\n\t// \t\tquery: true,\n\t// \t\tset: true,\n\t// \t\tunknownQueries: false\n\t// \t}\n\n\t// \tinferBodyReference(code, aliases, inference)\n\n\t// \texpect(inference).toEqual({\n\t// \t\tbody: false,\n\t// \t\tcookie: false,\n\t// \t\theaders: false,\n\t// \t\tqueries: ['quack'],\n\t// \t\tquery: true,\n\t// \t\tset: true,\n\t// \t\tunknownQueries: false\n\t// \t})\n\t// })\n\n\tit('skip dynamic quote query', () => {\n\t\tconst code = `{\n\t\t\tconst b = query[quack];\n\t\t\treturn \"a\";\n\t\t}`\n\n\t\tconst aliases = ['query']\n\t\tconst inference = {\n\t\t\tbody: false,\n\t\t\tcookie: false,\n\t\t\theaders: false,\n\t\t\tquery: true,\n\t\t\tset: true,\n\t\t\tserver: false,\n\t\t\tpath: false,\n\t\t\troute: false,\n\t\t\turl: false\n\t\t} satisfies Sucrose.Inference\n\n\t\tinferBodyReference(code, aliases, inference)\n\n\t\texpect(inference).toEqual({\n\t\t\tbody: false,\n\t\t\tcookie: false,\n\t\t\theaders: false,\n\t\t\tquery: true,\n\t\t\tset: true,\n\t\t\tserver: false,\n\t\t\tpath: false,\n\t\t\troute: false,\n\t\t\turl: false\n\t\t})\n\t})\n\n\tit('infer dot notation', () => {\n\t\tconst code = `\n\t\t\tcontext.server?.upgrade(request)\n\t\t`\n\t\tconst aliases = ['context']\n\t\tconst inference = {\n\t\t\tquery: false,\n\t\t\theaders: false,\n\t\t\tbody: false,\n\t\t\tcookie: false,\n\t\t\tset: false,\n\t\t\tserver: false,\n\t\t\tpath: false,\n\t\t\troute: false,\n\t\t\turl: false\n\t\t} satisfies Sucrose.Inference\n\n\t\tinferBodyReference(code, aliases, inference)\n\n\t\texpect(inference.server as boolean).toBe(true)\n\t})\n})\n"
  },
  {
    "path": "test/sucrose/integration.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\n\ndescribe('Integration', () => {\n\tit(\n\t\t'Allows process to finish',\n\t\tasync () => {\n\t\t\tconst res = Bun.spawn({\n\t\t\t\tcmd: [\n\t\t\t\t\t'bun',\n\t\t\t\t\t'-e',\n\t\t\t\t\t\"import { Elysia } from './src'; new Elysia().onBeforeHandle(() => { });\"\n\t\t\t\t]\n\t\t\t})\n\n\t\t\tconst status = await res.exited;\n\t\t\texpect(status).toEqual(0);\n\t\t},\n\t\t{\n\t\t\ttimeout: 500\n\t\t}\n\t)\n})\n"
  },
  {
    "path": "test/sucrose/query.test.ts",
    "content": "import { Elysia } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\n\nconst req = (path: string = '/?name=sucrose') =>\n\tnew Request(`http://localhost${path}`)\n\ndescribe('Query', () => {\n\tit('access all using property name', async () => {\n\t\tconst app = new Elysia().get('/', (ctx) => ctx.query)\n\t\tconst response = await app.handle(req())\n\n\t\texpect(await response.json()).toEqual({ name: 'sucrose' })\n\t})\n\n\tit('access all using destructuring', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query)\n\t\tconst response = await app.handle(req())\n\n\t\texpect(await response.json()).toEqual({ name: 'sucrose' })\n\t})\n\n\tit('access single param using property name', async () => {\n\t\tconst app = new Elysia().get('/', (ctx) => ctx.query.name)\n\t\tconst response = await app.handle(req())\n\n\t\texpect(await response.text()).toEqual('sucrose')\n\t})\n\n\tit('access single param using destructuring', async () => {\n\t\tconst app = new Elysia().get('/', ({ query: { name } }) => name)\n\t\tconst response = await app.handle(req())\n\n\t\texpect(await response.text()).toEqual('sucrose')\n\t})\n\n\tit('access all using destructuring assignment', async () => {\n\t\tconst app = new Elysia().get('/', (ctx) => {\n\t\t\tconst { query } = ctx\n\t\t\treturn query\n\t\t})\n\t\tconst response = await app.handle(req())\n\n\t\texpect(await response.json()).toEqual({ name: 'sucrose' })\n\t})\n\n\tit('access all using destructuring assignment within derive', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.derive((ctx) => {\n\t\t\t\tconst { query } = ctx\n\t\t\t\treturn {\n\t\t\t\t\tyay() {\n\t\t\t\t\t\treturn query\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', (ctx) => ctx.yay())\n\t\tconst response = await app.handle(req())\n\n\t\texpect(await response.json()).toEqual({ name: 'sucrose' })\n\t})\n\n\tit('access all using property name within derive', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.derive((ctx) => {\n\t\t\t\treturn {\n\t\t\t\t\tyay() {\n\t\t\t\t\t\treturn ctx.query\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/', (ctx) => ctx.yay())\n\n\t\tconst response = await app.handle(req())\n\n\t\texpect(await response.json()).toEqual({ name: 'sucrose' })\n\t})\n\n\tit('destructured encoded & (%26) query string', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/unknown', ({ query }) => query)\n\t\t\t.get('/named', ({ query: { name } }) => name)\n\n\t\tconst unknown = await app\n\t\t\t.handle(req('/unknown?name=sucrose%26albedo&alias=achemist'))\n\t\t\t.then((x) => x.json())\n\t\tconst named = await app\n\t\t\t.handle(req('/named?name=sucrose%26albedo&alias=achemist'))\n\t\t\t.then((x) => x.text())\n\n\t\texpect(unknown).toEqual({ name: 'sucrose&albedo', alias: 'achemist' })\n\t\texpect(named).toEqual('sucrose&albedo')\n\t})\n})\n"
  },
  {
    "path": "test/sucrose/remove-colon-alias.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { inferBodyReference, removeColonAlias } from '../../src/sucrose'\n\ndescribe('remove colon alias', () => {\n\tit('remove aliased name', () => {\n\t\tconst code = '{ headers: rs }'\n\n\t\texpect(removeColonAlias(code)).toBe(`{ headers }`)\n\t})\n\n\tit('remove aliased with part of keyword', () => {\n\t\tconst code = '{ headers: reqHeaders }'\n\n\t\texpect(removeColonAlias(code)).toBe(`{ headers }`)\n\t})\n\n    it('remove multiple aliased', () => {\n\t\tconst code = '{ headers: rs, query: q }'\n\n\t\texpect(removeColonAlias(code)).toBe(`{ headers, query }`)\n\t})\n\n    it('maintain same value if no aliased found', () => {\n\t\tconst code = '{ headers, query }'\n\n\t\texpect(removeColonAlias(code)).toBe(`{ headers, query }`)\n\t})\n})"
  },
  {
    "path": "test/sucrose/remove-default-parameter.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { removeDefaultParameter } from '../../src/sucrose'\n\ndescribe('removeDefaultParameter', () => {\n\t// The function removes default parameter values from a string parameter.\n\tit('should remove default parameter values from a string parameter', () => {\n\t\tconst parameter = 'a=1, b=2, c=3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function returns the modified string parameter.\n\tit('should return the modified string parameter', () => {\n\t\tconst parameter = 'a=1, b=2, c=3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function handles a string parameter with no default parameter values.\n\tit('should handle a string parameter with no default parameter values', () => {\n\t\tconst parameter = 'a, b, c'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function handles a string parameter with no equals sign.\n\tit('should handle a string parameter with no equals sign', () => {\n\t\tconst parameter = 'a, b, c'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function handles a string parameter with an equals sign but no comma or closing bracket.\n\tit('should handle a string parameter with an equals sign but no comma or closing bracket', () => {\n\t\tconst parameter = 'a=1'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a')\n\t})\n\n\t// The function handles a string parameter with an equals sign and a comma but no closing bracket.\n\tit('should handle a string parameter with an equals sign and a comma but no closing bracket', () => {\n\t\tconst parameter = 'a=1, b=2, c'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function handles a string parameter with one default parameter value.\n\tit('should remove default parameter values from a string parameter', () => {\n\t\tconst parameter = 'a=1, b=2, c=3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function handles a string parameter with multiple default parameter values.\n\tit('should remove default parameter values from a string parameter', () => {\n\t\tconst parameter = 'a=1, b=2, c=3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function handles a string parameter with default parameter values in different locations.\n\tit('should remove default parameter values from a string parameter', () => {\n\t\tconst parameter = 'a=1, b=2, c=3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function handles a string parameter with default parameter values in nested brackets.\n\tit('should remove default parameter values from a string parameter', () => {\n\t\tconst parameter = 'a=1, b=2, c=3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function handles a string parameter with an equals sign and a closing bracket but no comma.\n\tit('should remove default parameter values from a string parameter when there is an equals sign and a closing bracket but no comma', () => {\n\t\tconst parameter = 'a=1, b=2, c=3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function handles a string parameter with an equals sign, a comma, and a closing bracket in the wrong order.\n\tit('should remove default parameter values from a string parameter', () => {\n\t\tconst parameter = 'a=1, b=2, c=3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function is case-sensitive and does not remove default parameter values with different capitalization.\n\tit('should not remove default parameter values with different capitalization', () => {\n\t\tconst parameter = 'a=1, B=2, c=3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, B, c')\n\t})\n\n\t// The function does not modify the original string parameter and returns a new string.\n\tit('should remove default parameter values from a string parameter', () => {\n\t\tconst parameter = 'a=1, b=2, c=3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function can handle whitespace characters around the equals sign.\n\tit('should remove default parameter values when there are whitespace characters around the equals sign', () => {\n\t\tconst parameter = 'a = 1, b = 2, c = 3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function can handle default parameter values that contain equals signs.\n\tit('should remove default parameter values from a string parameter', () => {\n\t\tconst parameter = 'a=1, b=2, c=3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n\n\t// The function can handle default parameter values that contain commas.\n\tit('should remove default parameter values from a string parameter', () => {\n\t\tconst parameter = 'a=1, b=2, c=3'\n\t\tconst result = removeDefaultParameter(parameter)\n\t\texpect(result).toEqual('a, b, c')\n\t})\n})\n"
  },
  {
    "path": "test/sucrose/retrieve-root-parameters.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { retrieveRootparameters } from '../../src/sucrose'\n\ndescribe('retrieve root parameter', () => {\n\tit('return an empty string when given an empty string', () => {\n\t\tconst parameter = ''\n\t\tconst result = retrieveRootparameters(parameter)\n\t\texpect(result).toEqual({\n\t\t\tparameters: {},\n\t\t\thasParenthesis: false\n\t\t})\n\t})\n\n\t// Doesn't make sense as JavaScript will panic\n\t// it('return the same string when there are no brackets in the string', () => {\n\t// \tconst parameter = 'hello world'\n\t// \tconst result = retrieveRootparameters(parameter)\n\t// \texpect(result).toEqual({\n\t// \t\tparameters: ['hello world'],\n\t// \t\thasParenthesis: false\n\t// \t})\n\t// })\n\n\tit('remove brackets and their contents when they are at the root level', () => {\n\t\tconst parameter = '({ hello: { world: { a } }, elysia })'\n\t\tconst result = retrieveRootparameters(parameter)\n\t\texpect(result).toEqual({\n\t\t\tparameters: { hello: true, elysia: true },\n\t\t\thasParenthesis: true\n\t\t})\n\t})\n\n\tit('return an empty string when given only brackets', () => {\n\t\tconst parameter = '()'\n\t\tconst result = retrieveRootparameters(parameter)\n\t\texpect(result).toEqual({\n\t\t\tparameters: {},\n\t\t\thasParenthesis: false\n\t\t})\n\t})\n\n\tit('return an empty string when given only one bracket', () => {\n\t\tconst parameter = '('\n\t\tconst result = retrieveRootparameters(parameter)\n\t\texpect(result).toEqual({\n\t\t\tparameters: {},\n\t\t\thasParenthesis: false\n\t\t})\n\t})\n\n\t// Doesn't make sense as JavaScript will panic\n\t// it('return even if bracket is unbalanced', () => {\n\t// \tconst parameter = '({ hello: { world: { a } })'\n\t// \tconst result = retrieveRootparameters(parameter)\n\t// \texpect(result).toEqual({\n\t// \t\tparameters: ['hello'],\n\t// \t\thasParenthesis: true\n\t// \t})\n\t// })\n\n\tit('return the root parameters when given a string with spaces between brackets', () => {\n\t\tconst parameter = '({ hello: { world: { a } }, elysia })'\n\t\tconst result = retrieveRootparameters(parameter)\n\t\texpect(result).toEqual({\n\t\t\tparameters: { hello: true, elysia: true },\n\t\t\thasParenthesis: true\n\t\t})\n\t})\n\n\tit('return parameter on minified bracket', () => {\n\t\tconst parameter = '({ hello, path })'\n\t\tconst result = retrieveRootparameters(parameter)\n\t\texpect(result).toEqual({\n\t\t\tparameters: { hello: true, path: true },\n\t\t\thasParenthesis: true\n\t\t})\n\t})\n\n\tit('handle tab and new line', () => {\n\t\tconst parameter = '({ hello: { world: { a } }, \\nelysia, \\teden })'\n\t\tconst result = retrieveRootparameters(parameter)\n\t\texpect(result).toEqual({\n\t\t\tparameters: { hello: true, elysia: true, eden: true },\n\t\t\thasParenthesis: true\n\t\t})\n\t})\n\n\tit('handle last parameter destructuring', () => {\n\t\tconst parameter = '{ set, cookie: { auth } }'\n\t\tconst result = retrieveRootparameters(parameter)\n\t\texpect(result).toEqual({\n\t\t\thasParenthesis: true,\n\t\t\tparameters: { set: true, cookie: true }\n\t\t})\n\t})\n})\n"
  },
  {
    "path": "test/sucrose/separate-function.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\n\nimport { separateFunction } from '../../src/sucrose'\n\ndescribe('Sucrose: separateFunction', () => {\n\tit('separate arrowParam', () => {\n\t\tconst arrowParam = ({ sucrose, amber }: any) => {\n\t\t\treturn 'sucrose'\n\t\t}\n\n\t\texpect(separateFunction(arrowParam.toString())).toEqual([\n\t\t\t'{ sucrose, amber }',\n\t\t\t'{\\n      return \"sucrose\";\\n    }',\n\t\t\t{\n\t\t\t\tisArrowReturn: false\n\t\t\t}\n\t\t])\n\t})\n\n\tit('separate arrowNoParam', () => {\n\t\tconst arrowNoParam = () => 'sucrose'\n\n\t\texpect(separateFunction(arrowNoParam.toString())).toEqual([\n\t\t\t'',\n\t\t\t'\"sucrose\"',\n\t\t\t{\n\t\t\t\tisArrowReturn: true\n\t\t\t}\n\t\t])\n\t})\n\n\tit('separate arrowAsync', () => {\n\t\tconst arrowAsync = async (sucrose: any) => 'sucrose'\n\n\t\texpect(separateFunction(arrowAsync.toString())).toEqual([\n\t\t\t'sucrose',\n\t\t\t'\"sucrose\"',\n\t\t\t{\n\t\t\t\tisArrowReturn: true\n\t\t\t}\n\t\t])\n\t})\n\n\tit('separate fnParam', () => {\n\t\tfunction fnParam({ sucrose, amber }: any) {\n\t\t\treturn 'sucrose'\n\t\t}\n\n\t\texpect(separateFunction(fnParam.toString())).toEqual([\n\t\t\t'{ sucrose, amber }',\n\t\t\t'{\\n      return \"sucrose\";\\n    }',\n\t\t\t{\n\t\t\t\tisArrowReturn: false\n\t\t\t}\n\t\t])\n\t})\n\n\tit('separate fnNoParam', () => {\n\t\tfunction fnNoParam() {\n\t\t\treturn 'sucrose'\n\t\t}\n\n\t\texpect(separateFunction(fnNoParam.toString())).toEqual([\n\t\t\t'',\n\t\t\t'{\\n      return \"sucrose\";\\n    }',\n\t\t\t{\n\t\t\t\tisArrowReturn: false\n\t\t\t}\n\t\t])\n\t})\n\n\tit('separate fnAsync', () => {\n\t\tasync function fnAsync(sucrose: any) {\n\t\t\treturn 'sucrose'\n\t\t}\n\n\t\texpect(separateFunction(fnAsync.toString())).toEqual([\n\t\t\t'sucrose',\n\t\t\t'{\\n      return \"sucrose\";\\n    }',\n\t\t\t{\n\t\t\t\tisArrowReturn: false\n\t\t\t}\n\t\t])\n\t})\n\n\tit('separate minifed arrow param', () => {\n\t\tconst arrowParam = `({ sucrose, amber })=>{return \"sucrose\"}`\n\n\t\texpect(separateFunction(arrowParam.toString())).toEqual([\n\t\t\t'{ sucrose, amber }',\n\t\t\t'{return \"sucrose\"}',\n\t\t\t{\n\t\t\t\tisArrowReturn: false\n\t\t\t}\n\t\t])\n\t})\n\n\tit('separate minified arrow without whitespace in the beginning', () => {\n\t\tconst arrowParam = `({sucrose, amber })=>{return \"sucrose\"}`\n\n\t\texpect(separateFunction(arrowParam.toString())).toEqual([\n\t\t\t'{sucrose, amber }',\n\t\t\t'{return \"sucrose\"}',\n\t\t\t{\n\t\t\t\tisArrowReturn: false\n\t\t\t}\n\t\t])\n\t})\n})\n"
  },
  {
    "path": "test/sucrose/sucrose.test.ts",
    "content": "// @ts-nocheck\nimport { describe, expect, it } from 'bun:test'\nimport { Elysia } from '../../src'\n\nimport { separateFunction, sucrose } from '../../src/sucrose'\nimport { req } from '../utils'\n\ndescribe('sucrose', () => {\n\tit('common 1', () => {\n\t\texpect(\n\t\t\tsucrose({\n\t\t\t\thandler: function ({ query }) {\n\t\t\t\t\tquery.a\n\t\t\t\t},\n\t\t\t\tafterHandle: [],\n\t\t\t\tbeforeHandle: [],\n\t\t\t\terror: [\n\t\t\t\t\tfunction a({\n\t\t\t\t\t\tquery,\n\t\t\t\t\t\tquery: { a, c: d },\n\t\t\t\t\t\theaders: { hello },\n\t\t\t\t\t\t...rest\n\t\t\t\t\t}) {\n\t\t\t\t\t\tquery.b\n\t\t\t\t\t\trest.query.e\n\t\t\t\t\t},\n\t\t\t\t\t({ query: { f } }) => {}\n\t\t\t\t],\n\t\t\t\tmapResponse: [],\n\t\t\t\tafterResponse: [],\n\t\t\t\tparse: [],\n\t\t\t\trequest: [],\n\t\t\t\tstart: [],\n\t\t\t\tstop: [],\n\t\t\t\ttrace: [],\n\t\t\t\ttransform: []\n\t\t\t})\n\t\t).toEqual({\n\t\t\tquery: true,\n\t\t\theaders: true,\n\t\t\tbody: false,\n\t\t\tcookie: false,\n\t\t\tset: false,\n\t\t\tserver: false,\n\t\t\tpath: false,\n\t\t\turl: false,\n\t\t\troute: false\n\t\t})\n\t})\n\n\tit('common 2', async () => {\n\t\texpect(\n\t\t\tsucrose({\n\t\t\t\thandler: ({ set, cookie: { auth } }) => {\n\t\t\t\t\tconsole.log(auth.value)\n\t\t\t\t\treturn ''\n\t\t\t\t},\n\t\t\t\tafterHandle: [],\n\t\t\t\tbeforeHandle: [],\n\t\t\t\terror: [],\n\t\t\t\tmapResponse: [],\n\t\t\t\tafterResponse: [],\n\t\t\t\tparse: [],\n\t\t\t\trequest: [],\n\t\t\t\tstart: [],\n\t\t\t\tstop: [],\n\t\t\t\ttrace: [],\n\t\t\t\ttransform: []\n\t\t\t})\n\t\t).toEqual({\n\t\t\tquery: false,\n\t\t\theaders: false,\n\t\t\tbody: false,\n\t\t\tcookie: true,\n\t\t\tset: true,\n\t\t\tserver: false,\n\t\t\tpath: false,\n\t\t\turl: false,\n\t\t\troute: false\n\t\t})\n\t})\n\n\tit('integration 1', async () => {\n\t\tconst path = 'a'\n\n\t\tconst app = new Elysia()\n\t\t\t// ✅ easy to perform inference\n\t\t\t.get('/1', ({ query: { a } }) => a)\n\t\t\t.get('/2', ({ query }) => query.a)\n\t\t\t.get('/3', (c) => c.query.a)\n\t\t\t.get('/4', ({ query }) => query[path])\n\t\t\t.get('/5', (c) => c.query[path])\n\n\t\tnew Array(5).fill(0).map(async (_, i) => {\n\t\t\tconst result = await app\n\t\t\t\t.handle(req(`/${i + 1}?a=a&b=b`))\n\t\t\t\t.then((x) => x.text())\n\n\t\t\texpect(result).toBe('a')\n\t\t})\n\t})\n\n\tit('inherits inference from plugin', () => {\n\t\tconst plugin = new Elysia().derive(({ headers: { authorization } }) => {\n\t\t\treturn {\n\t\t\t\tget auth() {\n\t\t\t\t\treturn authorization\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tconst main = new Elysia().use(plugin)\n\n\t\t// @ts-expect-error\n\t\texpect(main.inference.headers).toBe(true)\n\t})\n\n\tit(\"don't link inference\", async () => {\n\t\tconst app = new Elysia({\n\t\t\tcookie: {\n\t\t\t\tsecrets: 'Zero Exception',\n\t\t\t\tsign: true\n\t\t\t}\n\t\t})\n\t\t\t.get('/', () => 'hello')\n\t\t\t.onBeforeHandle(({ cookie: { session }, error }) => {\n\t\t\t\tif (!session.value) return error(401, 'Unauthorized')\n\t\t\t})\n\n\t\tconst status = await app.handle(req('/')).then((x) => x.status)\n\t\texpect(status).toBe(200)\n\t})\n\n\tit('mix up chain properties as query', () => {\n\t\texpect(\n\t\t\tsucrose({\n\t\t\t\thandler: async (c) => {\n\t\t\t\t\tconst id = c.query.id\n\t\t\t\t\tconst cookie = c.cookie\n\t\t\t\t\treturn { cookie, id }\n\t\t\t\t},\n\t\t\t\tafterHandle: [],\n\t\t\t\tbeforeHandle: [],\n\t\t\t\terror: [],\n\t\t\t\tmapResponse: [],\n\t\t\t\tonResponse: [],\n\t\t\t\tparse: [],\n\t\t\t\trequest: [],\n\t\t\t\tstart: [],\n\t\t\t\tstop: [],\n\t\t\t\ttrace: [],\n\t\t\t\ttransform: []\n\t\t\t})\n\t\t).toEqual({\n\t\t\tbody: false,\n\t\t\tcookie: true,\n\t\t\theaders: false,\n\t\t\tquery: true,\n\t\t\tset: false,\n\t\t\tserver: false,\n\t\t\tpath: false,\n\t\t\turl: false,\n\t\t\troute: false\n\t\t})\n\t})\n\n\tit('infer all inferences if context is passed to function', () => {\n\t\texpect(\n\t\t\tsucrose({\n\t\t\t\thandler: function (context) {\n\t\t\t\t\tconsole.log(context)\n\t\t\t\t},\n\t\t\t\tafterHandle: [],\n\t\t\t\tbeforeHandle: [],\n\t\t\t\terror: [],\n\t\t\t\tmapResponse: [],\n\t\t\t\tonResponse: [],\n\t\t\t\tparse: [],\n\t\t\t\trequest: [],\n\t\t\t\tstart: [],\n\t\t\t\tstop: [],\n\t\t\t\ttrace: [],\n\t\t\t\ttransform: []\n\t\t\t})\n\t\t).toEqual({\n\t\t\tquery: true,\n\t\t\theaders: true,\n\t\t\tbody: true,\n\t\t\tcookie: true,\n\t\t\tset: true,\n\t\t\tserver: true,\n\t\t\tpath: true,\n\t\t\turl: true,\n\t\t\troute: true\n\t\t})\n\t})\n\n\tit('infer all inferences if context is passed to function', () => {\n\t\texpect(\n\t\t\tsucrose({\n\t\t\t\thandler: function ({ ...context }) {\n\t\t\t\t\tconsole.log(context)\n\t\t\t\t},\n\t\t\t\tafterHandle: [],\n\t\t\t\tbeforeHandle: [],\n\t\t\t\terror: [],\n\t\t\t\tmapResponse: [],\n\t\t\t\tonResponse: [],\n\t\t\t\tparse: [],\n\t\t\t\trequest: [],\n\t\t\t\tstart: [],\n\t\t\t\tstop: [],\n\t\t\t\ttrace: [],\n\t\t\t\ttransform: []\n\t\t\t})\n\t\t).toEqual({\n\t\t\tquery: true,\n\t\t\theaders: true,\n\t\t\tbody: true,\n\t\t\tcookie: true,\n\t\t\tset: true,\n\t\t\tserver: true,\n\t\t\tpath: true,\n\t\t\turl: true,\n\t\t\troute: true\n\t\t})\n\t})\n\n\tit('infer single object destructure property', () => {\n\t\texpect(\n\t\t\tsucrose({\n\t\t\t\thandler: function ({ server }) {\n\t\t\t\t\tconsole.log(server)\n\t\t\t\t},\n\t\t\t\tafterHandle: [],\n\t\t\t\tbeforeHandle: [],\n\t\t\t\terror: [],\n\t\t\t\tmapResponse: [],\n\t\t\t\tonResponse: [],\n\t\t\t\tparse: [],\n\t\t\t\trequest: [],\n\t\t\t\tstart: [],\n\t\t\t\tstop: [],\n\t\t\t\ttrace: [],\n\t\t\t\ttransform: []\n\t\t\t})\n\t\t).toEqual({\n\t\t\tquery: false,\n\t\t\theaders: false,\n\t\t\tbody: false,\n\t\t\tcookie: false,\n\t\t\tset: false,\n\t\t\tserver: true,\n\t\t\tpath: false,\n\t\t\turl: false,\n\t\t\troute: false\n\t\t})\n\t})\n\n\tit('infer server', async () => {\n\t\tconst app = new Elysia({ precompile: true })\n\t\t\t.onRequest(({ server }) => {})\n\t\t\t.get('/', () => 'Hello, World!')\n\n\t\tconst response = await app.handle(new Request('http://localhost:3000'))\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('not death lock on empty', async () => {\n\t\tconst app = new Elysia({ precompile: true })\n\t\t\t.onRequest((c) => {})\n\t\t\t.get('/', () => 'Hello, World!')\n\n\t\tconst response = await app.handle(new Request('http://localhost:3000'))\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('access route, url, path', () => {\n\t\texpect(\n\t\t\tsucrose({\n\t\t\t\thandler: function (context) {\n\t\t\t\t\tconsole.log(context.url, context.path, context.route)\n\t\t\t\t},\n\t\t\t\tafterHandle: [],\n\t\t\t\tbeforeHandle: [],\n\t\t\t\terror: [],\n\t\t\t\tmapResponse: [],\n\t\t\t\tonResponse: [],\n\t\t\t\tparse: [],\n\t\t\t\trequest: [],\n\t\t\t\tstart: [],\n\t\t\t\tstop: [],\n\t\t\t\ttrace: [],\n\t\t\t\ttransform: []\n\t\t\t})\n\t\t).toEqual({\n\t\t\tquery: false,\n\t\t\theaders: false,\n\t\t\tbody: false,\n\t\t\tcookie: false,\n\t\t\tset: false,\n\t\t\tserver: false,\n\t\t\tpath: true,\n\t\t\turl: true,\n\t\t\troute: true\n\t\t})\n\t})\n\n\tit('handle context pass to function with sub context', () => {\n\t\texpect(\n\t\t\tsucrose({\n\t\t\t\thandler: (context) => {\n\t\t\t\t\tconsole.log('path >>> ', context.path)\n\t\t\t\t\tconsole.log(context)\n\t\t\t\t}\n\t\t\t})\n\t\t).toEqual({\n\t\t\tquery: true,\n\t\t\theaders: true,\n\t\t\tbody: true,\n\t\t\tcookie: true,\n\t\t\tset: true,\n\t\t\tserver: true,\n\t\t\tpath: true,\n\t\t\turl: true,\n\t\t\troute: true\n\t\t})\n\t})\n})\n"
  },
  {
    "path": "test/timeout.ts",
    "content": "import { Elysia } from '../src'\n\nconst largePlugin = async (app: Elysia) => {\n\tawait new Promise((resolve) => setTimeout(resolve, 1000))\n\n\treturn app.get('/large', () => 'Hi')\n}\n\nexport default largePlugin\n"
  },
  {
    "path": "test/tracer/aot.test.ts",
    "content": "import { Context, Elysia } from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('Trace AoT', async () => {\n\t// it('inject request report', async () => {\n\t// \tconst app = new Elysia().trace(async () => {}).get('/', () => '')\n\n\t// \texpect(app.compile().fetch.toString()).toInclude(\n\t// \t\t`reporter.emit('event',{id,event:'request'`\n\t// \t)\n\t// })\n\n\tit('try-catch edge case', async () => {\n\t\tclass Controller {\n\t\t\tstatic async handle(ctx: Context) {\n\t\t\t\ttry {\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tconst { token } = ctx.body\n\t\t\t\t\treturn token\n\t\t\t\t} catch {\n\t\t\t\t\treturn 'nope'\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia().post('/', Controller.handle)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify({ token: 'yay' }),\n\t\t\t\theaders: { 'Content-Type': 'application/json' }\n\t\t\t})\n\t\t)\n\n\t\texpect(await response.text()).toEqual('yay')\n\t})\n\n\t// ! Fix me: uncomment when 1.0.0 is released\n\t// it('inject response report', async () => {\n\t// \tconst app = new Elysia().trace(async () => {}).get('/', () => '')\n\n\t// \texpect(app.router.history[0].composed?.toString()).toInclude(\n\t// \t\t`reporter.emit('event',{id,event:'response'`\n\t// \t)\n\t// })\n\n\tit('handle scope', async () => {\n\t\tlet called = 0\n\n\t\tconst plugin = new Elysia()\n\t\t\t.trace(({ onHandle }) => {\n\t\t\t\tonHandle(() => {\n\t\t\t\t\tcalled++\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/plugin', () => 'ok')\n\n\t\tconst app = new Elysia().use(plugin).get('/main', () => 'ok')\n\n\t\tawait Promise.all([\n\t\t\tapp.handle(req('/plugin')),\n\t\t\tapp.handle(req('/main'))\n\t\t])\n\n\t\texpect(called).toBe(1)\n\t})\n})\n"
  },
  {
    "path": "test/tracer/detail.test.ts",
    "content": "import { Elysia } from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { post, req } from '../utils'\n\ndescribe('Trace Detail', async () => {\n\tit('report parse units name', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onParse, set }) => {\n\t\t\t\tonParse(({ onEvent, onStop }) => {\n\t\t\t\t\tconst names = <string[]>[]\n\n\t\t\t\t\tonEvent(({ name }) => {\n\t\t\t\t\t\tnames.push(name)\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(() => {\n\t\t\t\t\t\tset.headers.name = names.join(', ')\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onParse(function luna() {})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tparse: [function kindred() {}]\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(post('/', {}))\n\n\t\texpect(headers.get('name')).toBe('luna, kindred')\n\t})\n\n\tit('report transform units name', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onTransform, set }) => {\n\t\t\t\tonTransform(({ onEvent, onStop }) => {\n\t\t\t\t\tconst names = <string[]>[]\n\n\t\t\t\t\tonEvent(({ name }) => {\n\t\t\t\t\t\tnames.push(name)\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(() => {\n\t\t\t\t\t\tset.headers.name = names.join(', ')\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onTransform(function luna() {})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\ttransform: [function kindred() {}]\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(headers.get('name')).toBe('luna, kindred')\n\t})\n\n\tit('report beforeHandle units name', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onBeforeHandle, set }) => {\n\t\t\t\tonBeforeHandle(({ onEvent, onStop }) => {\n\t\t\t\t\tconst names = <string[]>[]\n\n\t\t\t\t\tonEvent(({ name }) => {\n\t\t\t\t\t\tnames.push(name)\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(() => {\n\t\t\t\t\t\tset.headers.name = names.join(', ')\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onBeforeHandle(function luna() {})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tbeforeHandle: [function kindred() {}]\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(headers.get('name')).toBe('luna, kindred')\n\t})\n\n\tit('report afterHandle units name', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onAfterHandle, set }) => {\n\t\t\t\tonAfterHandle(({ onEvent, onStop }) => {\n\t\t\t\t\tconst names = <string[]>[]\n\n\t\t\t\t\tonEvent(({ name }) => {\n\t\t\t\t\t\tnames.push(name)\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(() => {\n\t\t\t\t\t\tset.headers.name = names.join(', ')\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onAfterHandle(function luna() {})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tafterHandle: [function kindred() {}]\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(headers.get('name')).toBe('luna, kindred')\n\t})\n\n\tit('report mapResponse units name', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onMapResponse, set }) => {\n\t\t\t\tonMapResponse(({ onEvent, onStop }) => {\n\t\t\t\t\tconst names = <string[]>[]\n\n\t\t\t\t\tonEvent(({ name }) => {\n\t\t\t\t\t\tnames.push(name)\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(() => {\n\t\t\t\t\t\tset.headers.name = names.join(', ')\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.mapResponse(function luna() {})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tmapResponse: [function kindred() {}]\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(headers.get('name')).toBe('luna, kindred')\n\t})\n\n\tit('report afterResponse units name', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onAfterResponse, set }) => {\n\t\t\t\tonAfterResponse(({ onEvent, onStop }) => {\n\t\t\t\t\tconst names = <string[]>[]\n\n\t\t\t\t\tonEvent(({ name }) => {\n\t\t\t\t\t\tnames.push(name)\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(() => {\n\t\t\t\t\t\texpect(names.join(', ')).toBe('luna, kindred')\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onAfterResponse(function luna() {})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tafterResponse: [function kindred() {}]\n\t\t\t})\n\n\t\tapp.handle(req('/'))\n\t})\n})\n"
  },
  {
    "path": "test/tracer/timing.test.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { Elysia } from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { post, req } from '../utils'\n\nconst delay = (delay = 7) =>\n\tnew Promise((resolve) => setTimeout(resolve, delay))\n\ndescribe('Trace Timing', async () => {\n\tit('handle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onHandle, set }) => {\n\t\t\t\tonHandle(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = elapsed.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', async () => {\n\t\t\t\tawait delay()\n\n\t\t\t\treturn 'a'\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('request', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onRequest, set }) => {\n\t\t\t\tonRequest(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = elapsed.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onRequest(async () => {\n\t\t\t\tawait delay()\n\t\t\t})\n\t\t\t.get('/', () => 'a')\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('parse', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onParse, set }) => {\n\t\t\t\tonParse(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = elapsed.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onParse(async () => {\n\t\t\t\tawait delay()\n\t\t\t})\n\t\t\t.post('/', ({ body }) => 'a')\n\n\t\tconst { headers } = await app.handle(post('/', {}))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('transform', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onTransform, set }) => {\n\t\t\t\tonTransform(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = elapsed.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onTransform(async () => {\n\t\t\t\tawait delay()\n\t\t\t})\n\t\t\t.get('/', () => 'a')\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('beforeHandle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onBeforeHandle, set }) => {\n\t\t\t\tonBeforeHandle(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = elapsed.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onBeforeHandle(async () => {\n\t\t\t\tawait delay()\n\t\t\t})\n\t\t\t.get('/', () => 'a')\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('afterHandle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onAfterHandle, set }) => {\n\t\t\t\tonAfterHandle(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = elapsed.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onAfterHandle(async () => {\n\t\t\t\tawait delay()\n\t\t\t})\n\t\t\t.get('/', () => 'a')\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('mapResponse', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onMapResponse, set }) => {\n\t\t\t\tonMapResponse(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = elapsed.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.mapResponse(async () => {\n\t\t\t\tawait delay()\n\t\t\t})\n\t\t\t.get('/', () => 'a')\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('afterResponse', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onAfterResponse, set }) => {\n\t\t\t\tonAfterResponse(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\texpect(elapsed).toBeGreaterThan(5)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onAfterResponse(async () => {\n\t\t\t\tawait delay()\n\t\t\t})\n\t\t\t.get('/', () => 'a')\n\n\t\tapp.handle(req('/'))\n\t})\n\n\tit('inline parse', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onParse, set }) => {\n\t\t\t\tonParse(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = elapsed.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post('/', ({ body }) => 'a', {\n\t\t\t\tasync parse() {\n\t\t\t\t\tawait delay()\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(post('/', {}))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('inline transform', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onTransform, set }) => {\n\t\t\t\tonTransform(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = elapsed.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tasync transform() {\n\t\t\t\t\tawait delay()\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('inline beforeHandle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onBeforeHandle, set }) => {\n\t\t\t\tonBeforeHandle(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = elapsed.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tasync beforeHandle() {\n\t\t\t\t\tawait delay()\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('inline afterHandle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onAfterHandle, set }) => {\n\t\t\t\tonAfterHandle(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = elapsed.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tasync afterHandle() {\n\t\t\t\t\tawait delay()\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('inline mapResponse', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onMapResponse, set }) => {\n\t\t\t\tonMapResponse(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = elapsed.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tasync mapResponse() {\n\t\t\t\t\tawait delay()\n\t\t\t\t}\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('inline afterResponse', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onAfterResponse, set }) => {\n\t\t\t\tonAfterResponse(({ onStop }) => {\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\texpect(elapsed).toBeGreaterThan(5)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tasync afterResponse() {\n\t\t\t\t\tawait delay()\n\t\t\t\t}\n\t\t\t})\n\n\t\tapp.handle(req('/'))\n\t})\n\n\tit('parse unit', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onParse, set }) => {\n\t\t\t\tonParse(({ onStop, onEvent }) => {\n\t\t\t\t\tlet total = 0\n\n\t\t\t\t\tonEvent(({ begin }) => {\n\t\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\t\ttotal += elapsed\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = total.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onParse(async function luna() {\n\t\t\t\tawait delay(6)\n\t\t\t})\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tparse: [\n\t\t\t\t\tasync function kindred() {\n\t\t\t\t\t\tawait delay(6)\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(post('/', {}))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('transform unit', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onTransform, set }) => {\n\t\t\t\tonTransform(({ onStop, onEvent }) => {\n\t\t\t\t\tlet total = 0\n\n\t\t\t\t\tonEvent(({ onStop }) => {\n\t\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\t\ttotal += elapsed\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = total.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onTransform(async function luna() {\n\t\t\t\tawait delay(6)\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\ttransform: [\n\t\t\t\t\tasync function kindred() {\n\t\t\t\t\t\tawait delay(6)\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('beforeHandle unit', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onBeforeHandle, set }) => {\n\t\t\t\tonBeforeHandle(({ onStop, onEvent }) => {\n\t\t\t\t\tlet total = 0\n\n\t\t\t\t\tonEvent(({ onStop }) => {\n\t\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\t\ttotal += elapsed\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = total.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onBeforeHandle(async function luna() {\n\t\t\t\tawait delay(6)\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tbeforeHandle: [\n\t\t\t\t\tasync function kindred() {\n\t\t\t\t\t\tawait delay(6)\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('beforeHandle units', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onBeforeHandle, set }) => {\n\t\t\t\tonBeforeHandle(({ onStop, onEvent }) => {\n\t\t\t\t\tlet total = 0\n\n\t\t\t\t\tonEvent(({ onStop }) => {\n\t\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\t\ttotal += elapsed\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = total.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onBeforeHandle(async function luna() {\n\t\t\t\tawait delay(6.25)\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tbeforeHandle: [\n\t\t\t\t\tasync function kindred() {\n\t\t\t\t\t\tawait delay(6.25)\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('afterHandle unit', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onAfterHandle, set }) => {\n\t\t\t\tonAfterHandle(({ onStop, onEvent }) => {\n\t\t\t\t\tlet total = 0\n\n\t\t\t\t\tonEvent(({ onStop }) => {\n\t\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\t\ttotal += elapsed\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = total.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onAfterHandle(async function luna() {\n\t\t\t\tawait delay(6)\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tafterHandle: [\n\t\t\t\t\tasync function kindred() {\n\t\t\t\t\t\tawait delay(6)\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('mapResponse unit', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onMapResponse, set }) => {\n\t\t\t\tonMapResponse(({ onStop, onEvent }) => {\n\t\t\t\t\tlet total = 0\n\n\t\t\t\t\tonEvent(({ onStop }) => {\n\t\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\t\ttotal += elapsed\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = total.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.mapResponse(async function luna() {\n\t\t\t\tawait delay(6)\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tmapResponse: [\n\t\t\t\t\tasync function kindred() {\n\t\t\t\t\t\tawait delay(6)\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t})\n\n\t\tconst { headers } = await app.handle(req('/'))\n\n\t\texpect(+(headers.get('time') ?? 0)).toBeGreaterThan(5)\n\t})\n\n\tit('afterResponse unit', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onAfterResponse, set }) => {\n\t\t\t\tonAfterResponse(({ onStop, onEvent }) => {\n\t\t\t\t\tlet total = 0\n\n\t\t\t\t\tonEvent(({ onStop }) => {\n\t\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\t\ttotal += elapsed\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\n\t\t\t\t\tonStop(({ elapsed }) => {\n\t\t\t\t\t\tset.headers.time = total.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.onAfterResponse(async function luna() {\n\t\t\t\tawait delay(6)\n\t\t\t})\n\t\t\t.get('/', () => 'a', {\n\t\t\t\tafterResponse: [\n\t\t\t\t\tasync function kindred() {\n\t\t\t\t\t\tawait delay(6)\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t})\n\n\t\tapp.handle(req('/'))\n\t})\n})\n"
  },
  {
    "path": "test/tracer/trace.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Elysia, type TraceProcess, type TraceEvent } from '../../src'\nimport { delay, req } from '../utils'\n\ndescribe('trace', () => {\n\tit('inherits plugin', async () => {\n\t\tconst timeout = setTimeout(() => {\n\t\t\tthrow new Error('Trace stuck')\n\t\t}, 1000)\n\n\t\tconst a = new Elysia().trace({ as: 'global' }, async ({ set }) => {\n\t\t\tset.headers['X-Powered-By'] = 'elysia'\n\t\t\tclearTimeout(timeout)\n\t\t})\n\n\t\tconst app = new Elysia().use(a).get('/', () => 'hi')\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.headers.get('X-Powered-By')).toBe('elysia')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('handle scoped instance', async () => {\n\t\tconst timeout = setTimeout(() => {\n\t\t\tthrow new Error('Trace stuck')\n\t\t}, 1000)\n\n\t\tconst a = new Elysia().trace({ as: 'global' }, async ({ set }) => {\n\t\t\tset.headers['X-Powered-By'] = 'elysia'\n\t\t\tclearTimeout(timeout)\n\t\t})\n\n\t\tconst b = new Elysia().get('/scoped', () => 'hi')\n\n\t\tconst app = new Elysia()\n\t\t\t.use(a)\n\t\t\t.use(b)\n\t\t\t.get('/', () => 'hi')\n\n\t\tconst response = await app.handle(req('/scoped'))\n\n\t\texpect(response.headers.get('X-Powered-By')).toBe('elysia')\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('call all trace', async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst detectEvent =\n\t\t\t(event: TraceEvent) =>\n\t\t\t({ onStop }: TraceProcess<'begin'>) => {\n\t\t\t\tonStop(() => {\n\t\t\t\t\tcalled.push(event)\n\t\t\t\t})\n\t\t\t}\n\n\t\tconst plugin = new Elysia().trace(\n\t\t\t{ as: 'scoped' },\n\t\t\t({\n\t\t\t\tonRequest,\n\t\t\t\tonParse,\n\t\t\t\tonTransform,\n\t\t\t\tonBeforeHandle,\n\t\t\t\tonHandle,\n\t\t\t\tonAfterHandle,\n\t\t\t\tonMapResponse,\n\t\t\t\tonAfterResponse\n\t\t\t}) => {\n\t\t\t\tonRequest(detectEvent('request'))\n\t\t\t\tonParse(detectEvent('parse'))\n\t\t\t\tonTransform(detectEvent('transform'))\n\t\t\t\tonBeforeHandle(detectEvent('beforeHandle'))\n\t\t\t\tonHandle(detectEvent('handle'))\n\t\t\t\tonAfterHandle(detectEvent('afterHandle'))\n\t\t\t\tonMapResponse(detectEvent('mapResponse'))\n\t\t\t\tonAfterResponse(detectEvent('afterResponse'))\n\n\t\t\t\tonAfterResponse(() => {\n\t\t\t\t\texpect(called).toEqual([\n\t\t\t\t\t\t'request',\n\t\t\t\t\t\t'parse',\n\t\t\t\t\t\t'transform',\n\t\t\t\t\t\t'beforeHandle',\n\t\t\t\t\t\t'handle',\n\t\t\t\t\t\t'afterHandle',\n\t\t\t\t\t\t'mapResponse'\n\t\t\t\t\t\t// afterResponse is being called so we can't check it yet\n\t\t\t\t\t])\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia().use(plugin).get('/', 'hi')\n\n\t\tawait app.handle(req('/'))\n\n\t\t// wait for next tick\n\t\tawait Bun.sleep(1)\n\n\t\texpect(called).toEqual([\n\t\t\t'request',\n\t\t\t'parse',\n\t\t\t'transform',\n\t\t\t'beforeHandle',\n\t\t\t'handle',\n\t\t\t'afterHandle',\n\t\t\t'mapResponse',\n\t\t\t'afterResponse'\n\t\t])\n\t})\n\n\tit(\"don't crash on composer\", async () => {\n\t\tconst called = <string[]>[]\n\n\t\tconst detectEvent =\n\t\t\t(event: TraceEvent) =>\n\t\t\t({ onStop }: TraceProcess<'begin'>) => {\n\t\t\t\tonStop(() => {\n\t\t\t\t\tcalled.push(event)\n\t\t\t\t})\n\t\t\t}\n\n\t\tconst plugin = new Elysia()\n\t\t\t.onRequest(() => {})\n\t\t\t.onTransform(() => {})\n\t\t\t.onError(() => {})\n\t\t\t.trace(\n\t\t\t\t{ as: 'scoped' },\n\t\t\t\t({\n\t\t\t\t\tonRequest,\n\t\t\t\t\tonParse,\n\t\t\t\t\tonTransform,\n\t\t\t\t\tonBeforeHandle,\n\t\t\t\t\tonHandle,\n\t\t\t\t\tonAfterHandle,\n\t\t\t\t\tonMapResponse,\n\t\t\t\t\tonAfterResponse\n\t\t\t\t}) => {\n\t\t\t\t\tonRequest(detectEvent('request'))\n\t\t\t\t\tonParse(detectEvent('parse'))\n\t\t\t\t\tonTransform(detectEvent('transform'))\n\t\t\t\t\tonBeforeHandle(detectEvent('beforeHandle'))\n\t\t\t\t\tonHandle(detectEvent('handle'))\n\t\t\t\t\tonAfterHandle(detectEvent('afterHandle'))\n\t\t\t\t\tonMapResponse(detectEvent('mapResponse'))\n\t\t\t\t\tonAfterResponse(detectEvent('afterResponse'))\n\n\t\t\t\t\tonAfterResponse(() => {\n\t\t\t\t\t\texpect(called).toEqual([\n\t\t\t\t\t\t\t'request',\n\t\t\t\t\t\t\t'parse',\n\t\t\t\t\t\t\t'transform',\n\t\t\t\t\t\t\t'beforeHandle',\n\t\t\t\t\t\t\t'handle',\n\t\t\t\t\t\t\t'afterHandle',\n\t\t\t\t\t\t\t'mapResponse'\n\t\t\t\t\t\t\t// afterResponse is being called so we can't check it yet\n\t\t\t\t\t\t])\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst app = new Elysia().use(plugin).get('/', 'hi')\n\n\t\tawait app.handle(req('/'))\n\n\t\t// wait for next tick\n\t\tawait Bun.sleep(1)\n\n\t\texpect(called).toEqual([\n\t\t\t'request',\n\t\t\t'parse',\n\t\t\t'transform',\n\t\t\t'beforeHandle',\n\t\t\t'handle',\n\t\t\t'afterHandle',\n\t\t\t'mapResponse',\n\t\t\t'afterResponse'\n\t\t])\n\t})\n\n\tit('handle local scope', async () => {\n\t\tlet called = false\n\n\t\tconst plugin = new Elysia().trace(() => {\n\t\t\tcalled = true\n\t\t})\n\n\t\tconst parent = new Elysia().use(plugin)\n\t\tconst main = new Elysia().use(parent).get('/', () => 'h')\n\n\t\tawait main.handle(req('/'))\n\t\texpect(called).toBe(false)\n\n\t\tawait parent.handle(req('/'))\n\t\texpect(called).toBe(false)\n\n\t\tawait plugin.handle(req('/'))\n\t\texpect(called).toBe(true)\n\t})\n\n\tit('handle scoped scope', async () => {\n\t\tlet called = false\n\n\t\tconst plugin = new Elysia().trace({ as: 'scoped' }, () => {\n\t\t\tcalled = true\n\t\t})\n\n\t\tconst parent = new Elysia().use(plugin)\n\t\tconst main = new Elysia().use(parent).get('/', () => 'h')\n\n\t\tawait main.handle(req('/'))\n\t\texpect(called).toBe(false)\n\n\t\tawait parent.handle(req('/'))\n\t\texpect(called).toBe(true)\n\n\t\tawait plugin.handle(req('/'))\n\t\texpect(called).toBe(true)\n\t})\n\n\tit('handle global scope', async () => {\n\t\tlet called = false\n\n\t\tconst plugin = new Elysia().trace({ as: 'global' }, () => {\n\t\t\tcalled = true\n\t\t})\n\n\t\tconst parent = new Elysia().use(plugin)\n\t\tconst main = new Elysia().use(parent).get('/', () => 'h')\n\n\t\tawait main.handle(req('/'))\n\t\texpect(called).toBe(true)\n\n\t\tawait parent.handle(req('/'))\n\t\texpect(called).toBe(true)\n\n\t\tawait plugin.handle(req('/'))\n\t\texpect(called).toBe(true)\n\t})\n\n\tit('handle as cast', async () => {\n\t\tlet called = false\n\n\t\tconst plugin = new Elysia().trace({ as: 'scoped' }, () => {\n\t\t\tcalled = true\n\t\t})\n\n\t\tconst parent = new Elysia().use(plugin).as('scoped')\n\t\tconst main = new Elysia().use(parent).get('/', () => 'h')\n\n\t\tawait main.handle(req('/'))\n\t\texpect(called).toBe(true)\n\n\t\tawait parent.handle(req('/'))\n\t\texpect(called).toBe(true)\n\n\t\tawait plugin.handle(req('/'))\n\t\texpect(called).toBe(true)\n\t})\n\n\tit('deduplicate plugin when name is provided', () => {\n\t\tconst a = new Elysia({ name: 'a' }).trace({ as: 'global' }, () => {})\n\t\tconst b = new Elysia().use(a)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(a)\n\t\t\t.use(a)\n\t\t\t.use(b)\n\t\t\t.use(b)\n\t\t\t.get('/', () => 'ok')\n\n\t\texpect(app.routes[0].hooks.trace.length).toBe(1)\n\t})\n\n\tit('report error thrown in lifecycle event', async () => {\n\t\tlet isCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onBeforeHandle }) => {\n\t\t\t\tonBeforeHandle(({ onEvent }) => {\n\t\t\t\t\tonEvent(({ onStop }) => {\n\t\t\t\t\t\tonStop(({ error }) => {\n\t\t\t\t\t\t\tif (error) isCalled = true\n\t\t\t\t\t\t\texpect(error).toBeInstanceOf(Error)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'ok', {\n\t\t\t\tbeforeHandle() {\n\t\t\t\t\tthrow new Error('A')\n\t\t\t\t}\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(isCalled).toBeTrue()\n\t})\n\n\tit('report error return in lifecycle event', async () => {\n\t\tlet isCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onBeforeHandle }) => {\n\t\t\t\tonBeforeHandle(({ onEvent }) => {\n\t\t\t\t\tonEvent(({ onStop }) => {\n\t\t\t\t\t\tonStop(({ error }) => {\n\t\t\t\t\t\t\tif (error) isCalled = true\n\t\t\t\t\t\t\texpect(error).toBeInstanceOf(Error)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'ok', {\n\t\t\t\tbeforeHandle() {\n\t\t\t\t\treturn new Error('A')\n\t\t\t\t}\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(isCalled).toBeTrue()\n\t})\n\n\tit('report error to parent group', async () => {\n\t\tlet isCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onBeforeHandle }) => {\n\t\t\t\tonBeforeHandle(({ onStop }) => {\n\t\t\t\t\tonStop(({ error }) => {\n\t\t\t\t\t\tif (error) isCalled = true\n\t\t\t\t\t\texpect(error).toBeInstanceOf(Error)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'ok', {\n\t\t\t\tbeforeHandle() {\n\t\t\t\t\treturn new Error('A')\n\t\t\t\t}\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(isCalled).toBeTrue()\n\t})\n\n\tit('report resolve parent error', async () => {\n\t\tlet isCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onBeforeHandle }) => {\n\t\t\t\tonBeforeHandle(async ({ error: err }) => {\n\t\t\t\t\tconst error = await err\n\t\t\t\t\tif (error) isCalled = true\n\t\t\t\t\texpect(error).toBeInstanceOf(Error)\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'ok', {\n\t\t\t\tbeforeHandle() {\n\t\t\t\t\treturn new Error('A')\n\t\t\t\t}\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(isCalled).toBeTrue()\n\t})\n\n\tit('report error return in lifecycle event', async () => {\n\t\tlet isCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onBeforeHandle }) => {\n\t\t\t\tonBeforeHandle(({ onStop }) => {\n\t\t\t\t\tonStop(({ error }) => {\n\t\t\t\t\t\tif (error) isCalled = true\n\t\t\t\t\t\texpect(error).toBeInstanceOf(Error)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => 'ok', {\n\t\t\t\tbeforeHandle() {\n\t\t\t\t\treturn new Error('A')\n\t\t\t\t}\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(isCalled).toBeTrue()\n\t})\n\n\tit('report error throw in handle', async () => {\n\t\tlet isCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onHandle }) => {\n\t\t\t\tonHandle(({ onStop }) => {\n\t\t\t\t\tonStop(({ error }) => {\n\t\t\t\t\t\tif (error) isCalled = true\n\t\t\t\t\t\texpect(error).toBeInstanceOf(Error)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => {\n\t\t\t\tthrow new Error('A')\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(isCalled).toBeTrue()\n\t})\n\n\tit('report error return in handle', async () => {\n\t\tlet isCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onHandle }) => {\n\t\t\t\tonHandle(({ onStop }) => {\n\t\t\t\t\tonStop(({ error }) => {\n\t\t\t\t\t\tif (error) isCalled = true\n\t\t\t\t\t\texpect(error).toBeInstanceOf(Error)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => {\n\t\t\t\treturn new Error('A')\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(isCalled).toBeTrue()\n\t})\n\n\tit('report error throw in handle', async () => {\n\t\tlet isCalled = false\n\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onHandle }) => {\n\t\t\t\tonHandle(({ onStop }) => {\n\t\t\t\t\tonStop(({ error }) => {\n\t\t\t\t\t\tif (error) isCalled = true\n\t\t\t\t\t\texpect(error).toBeInstanceOf(Error)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', () => {\n\t\t\t\tthrow new Error('A')\n\t\t\t})\n\n\t\tawait app.handle(req('/'))\n\n\t\texpect(isCalled).toBeTrue()\n\t})\n\n\tit('report route when using trace', async () => {\n\t\tlet route: string | undefined\n\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onHandle, context }) => {\n\t\t\t\tonHandle(({ onStop }) => {\n\t\t\t\t\tonStop(({ error }) => {\n\t\t\t\t\t\troute = context.route\n\t\t\t\t\t\texpect(error).toBeInstanceOf(Error)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/id/:id', () => {\n\t\t\t\tthrow new Error('A')\n\t\t\t})\n\n\t\tawait app.handle(req('/id/1'))\n\n\t\texpect(route).toBe('/id/:id')\n\t})\n\n\tit('defers stream for onHandle, and onAfterResponse', async () => {\n\t\tconst order = <string[]>[]\n\n\t\tconst app = new Elysia()\n\t\t\t.trace(({ onHandle, onAfterResponse }) => {\n\t\t\t\tonHandle(({ onStop }) => {\n\t\t\t\t\tonStop(({ error }) => {\n\t\t\t\t\t\torder.push('HANDLE')\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tonAfterResponse(() => {\n\t\t\t\t\torder.push('AFTER')\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', async function* () {\n\t\t\t\tfor (let i = 0; i < 5; i++) {\n\t\t\t\t\tyield `${i}`\n\t\t\t\t\tawait delay(1)\n\t\t\t\t}\n\t\t\t})\n\n\t\texpect(order).toEqual([])\n\n\t\tconst response = await app.handle(req('/'))\n\t\texpect(order).toEqual([])\n\n\t\tawait response.text()\n\t\texpect(order).toEqual(['HANDLE', 'AFTER'])\n\t})\n})\n"
  },
  {
    "path": "test/type-system/array-buffer.test.ts",
    "content": "import Elysia, { t } from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { Value } from '@sinclair/typebox/value'\nimport { TypeBoxError } from '@sinclair/typebox'\n\ndescribe('TypeSystem - ArrayBuffer', () => {\n\tit('Create', () => {\n\t\t// @ts-expect-error\n\t\texpect(Value.Create(t.ArrayBuffer())).toEqual([1, 2, 3])\n\n\t\texpect(\n\t\t\tValue.Create(\n\t\t\t\tt.ArrayString(t.Any(), {\n\t\t\t\t\tdefault: '[]'\n\t\t\t\t})\n\t\t\t)\n\t\t\t// @ts-expect-error\n\t\t).toBe('[]')\n\t})\n\n\tit('Check', () => {\n\t\tconst schema = t.ArrayBuffer()\n\n\t\texpect(Value.Check(schema, new ArrayBuffer())).toBe(true)\n\t\texpect(Value.Check(schema, [1, 2, 3])).toBe(false)\n\t})\n\n\tit('Encode', () => {\n\t\tconst schema = t.ArrayBuffer()\n\n\t\texpect(() => Value.Encode(schema, [1, 2, 3])).toThrow(TypeBoxError)\n\t\texpect(() => Value.Encode(schema, 'test')).toThrow(TypeBoxError)\n\t\texpect(() => Value.Encode(schema, 123)).toThrow(TypeBoxError)\n\t\texpect(() => Value.Encode(schema, true)).toThrow(TypeBoxError)\n\t\texpect(() => Value.Encode(schema, null)).toThrow(TypeBoxError)\n\t\texpect(() => Value.Encode(schema, undefined)).toThrow(TypeBoxError)\n\t})\n\n\tit('Decode', () => {\n\t\tconst schema = t.ArrayBuffer()\n\n\t\texpect(Value.Decode(schema, new ArrayBuffer())).toEqual(\n\t\t\tnew ArrayBuffer()\n\t\t)\n\t\texpect(() => Value.Decode(schema, [1, 2, 3])).toThrow(TypeBoxError)\n\t\texpect(() => Value.Decode(schema, 'test')).toThrow(TypeBoxError)\n\t\texpect(() => Value.Decode(schema, 123)).toThrow(TypeBoxError)\n\t\texpect(() => Value.Decode(schema, true)).toThrow(TypeBoxError)\n\t\texpect(() => Value.Decode(schema, null)).toThrow(TypeBoxError)\n\t\texpect(() => Value.Decode(schema, undefined)).toThrow(TypeBoxError)\n\t})\n\n\tit('Integrate', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.ArrayBuffer(),\n\t\t\tresponse: t.ArrayBuffer()\n\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: new TextEncoder().encode('可愛くてごめん'),\n\t\t\t\theaders: { 'content-type': 'application/octet-stream' }\n\t\t\t})\n\t\t)\n\n\t\texpect(await response.text()).toBe('可愛くてごめん')\n\t})\n})\n"
  },
  {
    "path": "test/type-system/array-string.test.ts",
    "content": "import Elysia, { t } from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { Value } from '@sinclair/typebox/value'\nimport { TBoolean, TString, TypeBoxError } from '@sinclair/typebox'\nimport { req } from '../utils'\n\ndescribe('TypeSystem - ArrayString', () => {\n\tit('Create', () => {\n\t\t// @ts-expect-error\n\t\texpect(Value.Create(t.ArrayString())).toBe(undefined)\n\n\t\texpect(\n\t\t\tValue.Create(\n\t\t\t\tt.ArrayString(t.Any(), {\n\t\t\t\t\tdefault: '[]'\n\t\t\t\t})\n\t\t\t)\n\t\t\t// @ts-expect-error\n\t\t).toBe('[]')\n\t})\n\n\tit('Check', () => {\n\t\tconst schema = t.ArrayString(t.Number())\n\n\t\texpect(Value.Check(schema, [1])).toBe(true)\n\t})\n\n\tit('Encode', () => {\n\t\tconst schema = t.ArrayString(t.Number())\n\n\t\texpect(Value.Encode<typeof schema, string>(schema, [1])).toBe(\n\t\t\tJSON.stringify([1])\n\t\t)\n\n\t\texpect(Value.Encode<typeof schema, string>(schema, [1])).toBe(\n\t\t\tJSON.stringify([1])\n\t\t)\n\t})\n\n\tit('Decode', () => {\n\t\tconst schema = t.ArrayString(t.Number())\n\n\t\texpect(Value.Decode<typeof schema>(schema, '[1]')).toEqual([1])\n\n\t\texpect(() => Value.Decode<typeof schema>(schema, '1')).toThrow()\n\t})\n\n\tit('Integrate', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tid: t.ArrayString(t.Number())\n\t\t\t})\n\t\t})\n\n\t\tconst res1 = await app.handle(\n\t\t\tnew Request('http://localhost', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\tbody: JSON.stringify({ id: JSON.stringify([1, 2, 3]) })\n\t\t\t})\n\t\t)\n\t\texpect(res1.status).toBe(200)\n\n\t\tconst res2 = await app.handle(\n\t\t\tnew Request('http://localhost', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\tbody: JSON.stringify({ id: [1, 2, 3] })\n\t\t\t})\n\t\t)\n\t\texpect(res2.status).toBe(200)\n\n\t\tconst res3 = await app.handle(\n\t\t\tnew Request('http://localhost', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\tbody: JSON.stringify({ id: ['a', 2, 3] })\n\t\t\t})\n\t\t)\n\t\texpect(res3.status).toBe(422)\n\t})\n})\n"
  },
  {
    "path": "test/type-system/boolean-string.test.ts",
    "content": "import Elysia, { t } from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { Value } from '@sinclair/typebox/value'\nimport { TBoolean, TypeBoxError } from '@sinclair/typebox'\nimport { req } from '../utils'\n\ndescribe('TypeSystem - BooleanString', () => {\n\tit('Create', () => {\n\t\texpect(Value.Create(t.BooleanString())).toBe(false)\n\t\texpect(Value.Create(t.BooleanString({ default: true }))).toBe(true)\n\t})\n\n\tit('Check', () => {\n\t\tconst schema = t.BooleanString()\n\n\t\texpect(Value.Check(schema, true)).toBe(true)\n\t\texpect(Value.Check(schema, 'true')).toBe(true)\n\t\texpect(Value.Check(schema, false)).toBe(true)\n\t\texpect(Value.Check(schema, 'false')).toBe(true)\n\n\t\texpect(Value.Check(schema, 'yay')).toBe(false)\n\t\texpect(Value.Check(schema, 42)).toBe(false)\n\t\texpect(Value.Check(schema, {})).toBe(false)\n\t\texpect(Value.Check(schema, undefined)).toBe(false)\n\t\texpect(Value.Check(schema, null)).toBe(false)\n\t})\n\n\tit('Encode', () => {\n\t\tconst schema = t.BooleanString()\n\n\t\texpect(Value.Encode<TBoolean, boolean>(schema, true)).toBe(true)\n\t\texpect(Value.Encode<TBoolean, string>(schema, 'true')).toBe('true')\n\n\t\texpect(Value.Encode<TBoolean, boolean>(schema, false)).toBe(false)\n\t\texpect(Value.Encode<TBoolean, string>(schema, 'false')).toBe('false')\n\n\t\tconst error = new TypeBoxError(\n\t\t\t'The encoded value does not match the expected schema'\n\t\t)\n\t\texpect(() => Value.Encode(schema, 'yay')).toThrow(error)\n\t\texpect(() => Value.Encode(schema, 42)).toThrow(error)\n\t\texpect(() => Value.Encode(schema, {})).toThrow(error)\n\t\texpect(() => Value.Encode(schema, undefined)).toThrow(error)\n\t\texpect(() => Value.Encode(schema, null)).toThrow(error)\n\t})\n\n\tit('Decode', () => {\n\t\tconst schema = t.BooleanString()\n\n\t\texpect(Value.Decode<TBoolean, boolean>(schema, true)).toBe(true)\n\t\texpect(Value.Decode<TBoolean, boolean>(schema, 'true')).toBe(true)\n\n\t\texpect(Value.Decode<TBoolean, boolean>(schema, false)).toBe(false)\n\t\texpect(Value.Decode<TBoolean, boolean>(schema, 'false')).toBe(false)\n\n\t\tconst error = new TypeBoxError(\n\t\t\t'Unable to decode value as it does not match the expected schema'\n\t\t)\n\t\texpect(() => Value.Decode(schema, 'yay')).toThrow(error)\n\t\texpect(() => Value.Decode(schema, 42)).toThrow(error)\n\t\texpect(() => Value.Decode(schema, {})).toThrow(error)\n\t\texpect(() => Value.Decode(schema, undefined)).toThrow(error)\n\t\texpect(() => Value.Decode(schema, null)).toThrow(error)\n\t})\n\n\t// it('Convert', () => {\n\t// \texpect(Value.Convert(t.BooleanString(), 'true')).toBe(true)\n\t// \texpect(Value.Convert(t.BooleanString(), 'false')).toBe(false)\n\t// })\n\n\tit('Integrate', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tvalue: t.BooleanString()\n\t\t\t})\n\t\t})\n\n\t\tconst res1 = await app.handle(req('/?value=true'))\n\t\texpect(res1.status).toBe(200)\n\n\t\tconst res2 = await app.handle(req('/?value=false'))\n\t\texpect(res2.status).toBe(200)\n\n\t\tconst res3 = await app.handle(req('/?value=aight'))\n\t\texpect(res3.status).toBe(422)\n\t})\n})\n"
  },
  {
    "path": "test/type-system/coercion-number.test.ts",
    "content": "import { Elysia, t } from '../../src'\nimport { describe, it, expect } from 'bun:test'\n\ndescribe('Coercion - Numeric -> Number', () => {\n\tit('work', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/:entityType',\n\t\t\t({ params: { entityType } }) => entityType,\n\t\t\t{\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tentityType: t.Number()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(new Request('http://localhost/999'))\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('handle property', async () => {\n\t\tconst numberApp = new Elysia()\n\t\t\t.onError(({ code }) => code)\n\t\t\t.get('/:entityType', ({ params: { entityType } }) => entityType, {\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tentityType: t.Number({\n\t\t\t\t\t\tminimum: 0,\n\t\t\t\t\t\tmaximum: 3,\n\t\t\t\t\t\tmultipleOf: 1\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst numericApp = new Elysia()\n\t\t\t.onError(({ code }) => code)\n\t\t\t.get('/:entityType', ({ params: { entityType } }) => entityType, {\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tentityType: t.Numeric({\n\t\t\t\t\t\tminimum: 0,\n\t\t\t\t\t\tmaximum: 3,\n\t\t\t\t\t\tmultipleOf: 1\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\n\t\tasync function expectValidResponse(response: Response) {\n\t\t\texpect(response.status).toBe(422)\n\t\t\tconst body = await response.text()\n\t\t\texpect(body).not.toBe('999')\n\t\t\texpect(body).toBe('VALIDATION')\n\t\t}\n\n\t\tawait expectValidResponse(\n\t\t\tawait numberApp.handle(new Request('http://localhost/999'))\n\t\t)\n\n\t\tawait expectValidResponse(\n\t\t\tawait numericApp.handle(new Request('http://localhost/999'))\n\t\t)\n\t})\n})\n"
  },
  {
    "path": "test/type-system/date.test.ts",
    "content": "import Elysia, { t } from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { Value } from '@sinclair/typebox/value'\nimport { TBoolean, TDate, TUnion, TypeBoxError } from '@sinclair/typebox'\nimport { post } from '../utils'\n\ndescribe('TypeSystem - Date', () => {\n\tit('Create', () => {\n\t\texpect(Value.Create(t.Date())).toBeInstanceOf(Date)\n\t})\n\n\tit('No default date provided', () => {\n\t\tconst schema = t.Date()\n\t\texpect(schema.default).toBeUndefined()\n\n\t\tconst unionSchema = schema as unknown as TUnion\n\t\tfor (const type of unionSchema.anyOf) {\n\t\t\texpect(type.default).toBeUndefined()\n\t\t}\n\t})\n\n\tit('Default date provided', () => {\n\t\tconst given = new Date('2025-01-01T00:00:00.000Z')\n\t\tconst schema = t.Date({ default: given })\n\t\texpect(schema.default).toEqual(given)\n\n\t\tconst unionSchema = schema as unknown as TUnion\n\t\tfor (const type of unionSchema.anyOf) {\n\t\t\texpect(new Date(type.default)).toEqual(given)\n\t\t}\n\t})\n\n\tit('Check', () => {\n\t\tconst schema = t.Date()\n\n\t\texpect(Value.Check(schema, new Date())).toEqual(true)\n\t\texpect(Value.Check(schema, '2021/1/1')).toEqual(true)\n\n\t\texpect(Value.Check(schema, 'yay')).toEqual(false)\n\t\texpect(Value.Check(schema, 42)).toEqual(true)\n\t\texpect(Value.Check(schema, {})).toEqual(false)\n\t\texpect(Value.Check(schema, undefined)).toEqual(false)\n\t\texpect(Value.Check(schema, null)).toEqual(false)\n\t})\n\n\tit('Encode', () => {\n\t\tconst schema = t.Date()\n\n\t\tconst date = new Date()\n\n\t\texpect(Value.Encode<TDate, string>(schema, date)).toBe(\n\t\t\tdate.toISOString()\n\t\t)\n\n\t\texpect(() => Value.Encode(schema, 'yay')).toThrowError()\n\t\texpect(() =>\n\t\t\tValue.Encode(schema, Value.Decode(schema, 42))\n\t\t).not.toThrowError()\n\t\texpect(() => new Date().toISOString()).not.toThrowError()\n\t\texpect(() => Value.Encode(schema, {})).toThrowError()\n\t\texpect(() => Value.Encode(schema, undefined)).toThrowError()\n\t\texpect(() => Value.Encode(schema, null)).toThrowError()\n\t})\n\n\tit('Decode', () => {\n\t\tconst schema = t.Date()\n\n\t\texpect(Value.Decode<TDate, Date>(schema, new Date())).toBeInstanceOf(\n\t\t\tDate\n\t\t)\n\t\texpect(Value.Decode<TDate, Date>(schema, '2021/1/1')).toBeInstanceOf(\n\t\t\tDate\n\t\t)\n\n\t\tconst error = new TypeBoxError(\n\t\t\t'Unable to decode value as it does not match the expected schema'\n\t\t)\n\t\texpect(() => Value.Decode(schema, 'yay')).toThrow(error)\n\t\texpect(() => Value.Decode(schema, 42)).not.toThrow(error)\n\t\texpect(() => Value.Decode(schema, {})).toThrow(error)\n\t\texpect(() => Value.Decode(schema, undefined)).toThrow(error)\n\t\texpect(() => Value.Decode(schema, null)).toThrow(error)\n\t})\n\n\tit('Integrate', async () => {\n\t\tconst app = new Elysia().post('/', ({ body: { date } }) => date, {\n\t\t\tbody: t.Object({\n\t\t\t\tdate: t.Date()\n\t\t\t})\n\t\t})\n\n\t\tconst res1 = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tdate: new Date()\n\t\t\t})\n\t\t)\n\t\texpect(res1.status).toBe(200)\n\n\t\tconst res2 = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tdate: '2021/1/1'\n\t\t\t})\n\t\t)\n\t\texpect(res2.status).toBe(200)\n\n\t\tconst res3 = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tdate: 'Skibidi dom dom yes yes'\n\t\t\t})\n\t\t)\n\t\texpect(res3.status).toBe(422)\n\t})\n})\n"
  },
  {
    "path": "test/type-system/files.test.ts",
    "content": "import { Elysia, t, ValidationError } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { post, upload } from '../utils'\n\ndescribe('Files', () => {\n\tit('validate minItems, maxItems', async () => {\n\t\tconst app = new Elysia().post('/', () => 'ok', {\n\t\t\tbody: t.Object({\n\t\t\t\tfile: t.Files({\n\t\t\t\t\tminItems: 2,\n\t\t\t\t\tmaxItems: 2\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\t// case 1 fail: less than 2 files\n\t\t{\n\t\t\tconst body = new FormData()\n\t\t\tbody.append('file', Bun.file('test/images/millenium.jpg'))\n\n\t\t\tconst response = await app.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tbody\n\t\t\t\t})\n\t\t\t)\n\n\t\t\texpect(response.status).toBe(422)\n\t\t}\n\n\t\t// case 2 pass: all valid images\n\t\t{\n\t\t\tconst body = new FormData()\n\t\t\tbody.append('file', Bun.file('test/images/millenium.jpg'))\n\t\t\tbody.append('file', Bun.file('test/images/kozeki-ui.webp'))\n\n\t\t\tconst response = await app.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tbody\n\t\t\t\t})\n\t\t\t)\n\n\t\t\texpect(response.status).toBe(200)\n\t\t}\n\n\t\t// case 3 fail: more than 2 files\n\t\t{\n\t\t\tconst body = new FormData()\n\t\t\tbody.append('file', Bun.file('test/images/millenium.jpg'))\n\t\t\tbody.append('file', Bun.file('test/images/kozeki-ui.webp'))\n\t\t\tbody.append('file', Bun.file('test/images/midori.png'))\n\n\t\t\tconst response = await app.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tbody\n\t\t\t\t})\n\t\t\t)\n\n\t\t\texpect(response.status).toBe(422)\n\t\t}\n\t})\n\n\t// Union schema tests - testing that getSchemaProperties handles Union correctly\n\tit('handle file in Union schema', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => 'ok', {\n\t\t\tbody: t.Union([\n\t\t\t\tt.Object({\n\t\t\t\t\tavatar: t.File(),\n\t\t\t\t\ttype: t.Literal('image')\n\t\t\t\t}),\n\t\t\t\tt.Object({\n\t\t\t\t\tdocument: t.File(),\n\t\t\t\t\ttype: t.Literal('doc')\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\n\t\tconst body = new FormData()\n\t\tbody.append('avatar', Bun.file('test/images/millenium.jpg'))\n\t\tbody.append('type', 'image')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('handle multiple files in Union schema', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => 'ok', {\n\t\t\tbody: t.Union([\n\t\t\t\tt.Object({\n\t\t\t\t\timages: t.Files(),\n\t\t\t\t\tcategory: t.Literal('gallery')\n\t\t\t\t}),\n\t\t\t\tt.Object({\n\t\t\t\t\tdocuments: t.Files(),\n\t\t\t\t\tcategory: t.Literal('archive')\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\n\t\tconst body = new FormData()\n\t\tbody.append('images', Bun.file('test/images/millenium.jpg'))\n\t\tbody.append('images', Bun.file('test/images/kozeki-ui.webp'))\n\t\tbody.append('category', 'gallery')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n})\n"
  },
  {
    "path": "test/type-system/form.test.ts",
    "content": "import { Elysia, file, form, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\n\nimport { Value } from '@sinclair/typebox/value'\nimport { req } from '../utils'\n\ndescribe('TypeSystem - Form', () => {\n\tit('Create', () => {\n\t\texpect(Value.Create(t.Form({}))).toEqual(form({}))\n\n\t\texpect(\n\t\t\tValue.Create(\n\t\t\t\tt.Form(\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tdefault: form({\n\t\t\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t)\n\t\t).toEqual(\n\t\t\tform({\n\t\t\t\tname: 'saltyaom'\n\t\t\t})\n\t\t)\n\t})\n\n\tit('Check', () => {\n\t\tconst schema = t.Form({\n\t\t\tname: t.String(),\n\t\t\tage: t.Number()\n\t\t})\n\n\t\texpect(\n\t\t\tValue.Check(\n\t\t\t\tschema,\n\t\t\t\tform({\n\t\t\t\t\tname: 'saltyaom',\n\t\t\t\t\tage: 20\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(true)\n\n\t\ttry {\n\t\t\tValue.Check(\n\t\t\t\tschema,\n\t\t\t\tform({\n\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t})\n\t\t\t)\n\t\t\texpect(true).toBe(false)\n\t\t} catch {\n\t\t\texpect(true).toBe(true)\n\t\t}\n\t})\n\n\tit('Integrate', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get(\n\t\t\t\t'/form/:name',\n\t\t\t\t({ params: { name } }) =>\n\t\t\t\t\tform({\n\t\t\t\t\t\tname: name as any\n\t\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: t.Form({\n\t\t\t\t\t\tname: t.Literal('saltyaom')\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\t\t\t.get(\n\t\t\t\t'/file',\n\t\t\t\t() =>\n\t\t\t\t\tform({\n\t\t\t\t\t\tteapot: file('example/teapot.webp')\n\t\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: t.Form({\n\t\t\t\t\t\tteapot: t.File()\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst res1 = await app.handle(req('/form/saltyaom'))\n\t\texpect(res1.status).toBe(200)\n\n\t\tconst res2 = await app.handle(req('/form/felis'))\n\t\texpect(res2.status).toBe(422)\n\n\t\tconst res3 = await app.handle(req('/file'))\n\t\texpect(res3.status).toBe(200)\n\t})\n})\n"
  },
  {
    "path": "test/type-system/formdata.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { z } from 'zod'\nimport { Elysia, fileType, t, type ValidationError } from '../../src'\n\nconst variantObject = t.Object({\n\tprice: t.Number({ minimum: 0 }),\n\tweight: t.Number({ minimum: 0 })\n})\n\nconst metadataObject = {\n\tcategory: t.String(),\n\ttags: t.Array(t.String()),\n\tinStock: t.Boolean()\n}\n\nconst postProductModel = t.Object({\n\tname: t.String(),\n\tvariants: t.Array(variantObject),\n\tmetadata: t.Object(metadataObject),\n\timage: t.File({ type: 'image' })\n})\ntype postProductModel = typeof postProductModel.static\n\nconst patchProductModel = t.Object({\n\tname: t.Optional(t.String()),\n\tvariants: t.Optional(t.Array(variantObject)),\n\tmetadata: t.Optional(t.Object(metadataObject)),\n\timage: t.Optional(t.File({ type: 'image' }))\n})\ntype patchProductModel = typeof patchProductModel.static\n\nconst postProductModelComplex = t.Object({\n\tname: t.String(),\n\tvariants: t.ArrayString(variantObject),\n\tmetadata: t.ObjectString(metadataObject),\n\timage: t.File({ type: 'image' })\n})\ntype postProductModelComplex = typeof postProductModelComplex.static\n\nconst patchProductModelComplex = t.Object({\n\tname: t.Optional(t.String()),\n\tvariants: t.Optional(t.ArrayString(variantObject)),\n\tmetadata: t.Optional(t.ObjectString(metadataObject)),\n\timage: t.Optional(t.File({ type: 'image' }))\n})\ntype patchProductModelComplex = typeof patchProductModelComplex.static\n\nconst app = new Elysia()\n\t.post('/product', async ({ body, status }) => status('Created', body), {\n\t\tbody: postProductModel\n\t})\n\t.patch(\n\t\t'/product/:id',\n\t\t({ body, params }) => ({\n\t\t\tid: params.id,\n\t\t\t...body\n\t\t}),\n\t\t{\n\t\t\tbody: patchProductModel\n\t\t}\n\t)\n\t.post(\n\t\t'/product-complex',\n\t\tasync ({ body, status }) => status('Created', body),\n\t\t{\n\t\t\tbody: postProductModelComplex\n\t\t}\n\t)\n\t.patch(\n\t\t'/product-complex/:id',\n\t\t({ body, params }) => ({\n\t\t\tid: params.id,\n\t\t\t...body\n\t\t}),\n\t\t{\n\t\t\tbody: patchProductModelComplex\n\t\t}\n\t)\n\ndescribe('Nested FormData with mandatory bunFile (post operation)', async () => {\n\tconst bunFilePath1 = `${import.meta.dir}/../images/aris-yuzu.jpg`\n\tconst bunFile = Bun.file(bunFilePath1) as File\n\n\tconst newProduct: postProductModel = {\n\t\tname: 'Test Product',\n\t\tvariants: [\n\t\t\t{\n\t\t\t\tprice: 10,\n\t\t\t\tweight: 100\n\t\t\t},\n\t\t\t{\n\t\t\t\tprice: 2.7,\n\t\t\t\tweight: 32\n\t\t\t}\n\t\t],\n\t\tmetadata: {\n\t\t\tcategory: 'Electronics',\n\t\t\ttags: ['new', 'featured', 'sale'],\n\t\t\tinStock: true\n\t\t},\n\t\timage: bunFile\n\t}\n\n\tit('should create a product', async () => {\n\t\tconst stringifiedVariants = JSON.stringify(newProduct.variants)\n\t\tconst stringifiedMetadata = JSON.stringify(newProduct.metadata)\n\n\t\tconst body = new FormData()\n\t\tbody.append('name', newProduct.name)\n\t\tbody.append('variants', stringifiedVariants)\n\t\tbody.append('metadata', stringifiedMetadata)\n\t\tbody.append('image', bunFile)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\t\texpect(response.status).toBe(201)\n\t\tconst data = await response.json()\n\t\texpect(data).toEqual(newProduct)\n\t})\n\n\tit('should return validation error on nested ArrayString', async () => {\n\t\tconst stringifiedVariants = JSON.stringify([\n\t\t\t{\n\t\t\t\tprice: 23,\n\t\t\t\twaighTypo: ''\n\t\t\t}\n\t\t])\n\t\tconst stringifiedMetadata = JSON.stringify(newProduct.metadata)\n\n\t\tconst body = new FormData()\n\t\tbody.append('name', newProduct.name)\n\t\tbody.append('variants', stringifiedVariants)\n\t\tbody.append('metadata', stringifiedMetadata)\n\t\tbody.append('image', bunFile)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\t\tconst data = (await response.json()) as ValidationError\n\t\texpect(response.status).toBe(422)\n\t\texpect(data.type).toBe('validation')\n\t})\n\n\tit('should return validation error on nested ObjectString', async () => {\n\t\tconst stringifiedVariants = JSON.stringify(newProduct.variants)\n\t\tconst stringifiedMetadata = JSON.stringify({\n\t\t\tcategoryTypo: 'Electronics',\n\t\t\ttags: ['new', 'featured', 'sale'],\n\t\t\tinStock: true\n\t\t})\n\n\t\tconst body = new FormData()\n\t\tbody.append('name', newProduct.name)\n\t\tbody.append('variants', stringifiedVariants)\n\t\tbody.append('metadata', stringifiedMetadata)\n\t\tbody.append('image', bunFile)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\t\tconst data = (await response.json()) as ValidationError\n\t\texpect(response.status).toBe(422)\n\t\texpect(data.type).toBe('validation')\n\t})\n})\n\ndescribe('Nested FormData with optionnal file (patch operation)', async () => {\n\tconst bunFilePath2 = `${import.meta.dir}/../images/aris-yuzu.jpg`\n\tconst bunFile = Bun.file(bunFilePath2) as File\n\n\tit('PATCH with bunFile and omitted optional t.ObjectString', async () => {\n\t\tconst body = new FormData()\n\t\tbody.append('name', 'Updated Product')\n\t\tbody.append('image', bunFile)\n\t\t// metadata and variants fields are omitted (should be OK since they're optional)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product/123', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\tconst data = (await response.json()) as patchProductModel\n\t\texpect(data).not.toBeNull()\n\t\texpect(data?.name).toBe('Updated Product')\n\t\texpect(data?.metadata).toBeUndefined()\n\t\texpect(data?.variants).toBeUndefined()\n\t})\n\n\tit('PATCH with file and valid t.ObjectString and t.ArrayString data', async () => {\n\t\tconst body = new FormData()\n\t\tbody.append('name', 'Updated Product')\n\t\tbody.append('image', bunFile)\n\t\tbody.append(\n\t\t\t'metadata',\n\t\t\tJSON.stringify({\n\t\t\t\tcategory: 'Electronics',\n\t\t\t\ttags: ['sale', 'new'],\n\t\t\t\tinStock: true\n\t\t\t})\n\t\t)\n\t\tbody.append(\n\t\t\t'variants',\n\t\t\tJSON.stringify([\n\t\t\t\t{\n\t\t\t\t\tprice: 15,\n\t\t\t\t\tweight: 200\n\t\t\t\t}\n\t\t\t])\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product/123', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\tconst data = (await response.json()) as patchProductModel\n\t\texpect(data).not.toBeNull()\n\t\texpect(data?.name).toBe('Updated Product')\n\t\texpect(data?.metadata).toEqual({\n\t\t\tcategory: 'Electronics',\n\t\t\ttags: ['sale', 'new'],\n\t\t\tinStock: true\n\t\t})\n\t\texpect(data?.variants).toEqual([\n\t\t\t{\n\t\t\t\tprice: 15,\n\t\t\t\tweight: 200\n\t\t\t}\n\t\t])\n\t})\n\n\tit('PATCH without file and omitted optional t.ObjectString and optional t.ArrayString', async () => {\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product/123', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tname: 'Updated Product'\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\tconst data = (await response.json()) as patchProductModel\n\t\texpect(data).not.toBeNull()\n\t\texpect(data?.name).toBe('Updated Product')\n\t\texpect(data?.image).toBeUndefined()\n\t\texpect(data?.metadata).toBeUndefined()\n\t\texpect(data?.variants).toBeUndefined()\n\t})\n\n\tit('PATCH should return validation error on invalid ObjectString', async () => {\n\t\tconst body = new FormData()\n\t\tbody.append('name', 'Updated Product')\n\t\tbody.append('image', bunFile)\n\t\tbody.append(\n\t\t\t'metadata',\n\t\t\tJSON.stringify({\n\t\t\t\tcategoryTypo: 'Electronics', // Wrong property name\n\t\t\t\ttags: ['sale'],\n\t\t\t\tinStock: true\n\t\t\t})\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product/123', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\t\tconst data = (await response.json()) as ValidationError\n\t\texpect(data.type).toBe('validation')\n\t})\n\n\tit('PATCH should return validation error on invalid ArrayString', async () => {\n\t\tconst body = new FormData()\n\t\tbody.append('name', 'Updated Product')\n\t\tbody.append('image', bunFile)\n\t\tbody.append(\n\t\t\t'variants',\n\t\t\tJSON.stringify([\n\t\t\t\t{\n\t\t\t\t\tpriceTypo: 15, // Wrong property name\n\t\t\t\t\tweight: 200\n\t\t\t\t}\n\t\t\t])\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product/123', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\t\tconst data = (await response.json()) as ValidationError\n\t\texpect(data.type).toBe('validation')\n\t})\n})\n\ndescribe('Nested FormData with t.ArrayString and t.ObjectString (POST operation)', async () => {\n\tconst bunFilePath3 = `${import.meta.dir}/../images/aris-yuzu.jpg`\n\tconst bunFile = Bun.file(bunFilePath3) as File\n\n\tconst newProductComplex: postProductModelComplex = {\n\t\tname: 'Test Product Complex',\n\t\tvariants: [\n\t\t\t{\n\t\t\t\tprice: 10,\n\t\t\t\tweight: 100\n\t\t\t},\n\t\t\t{\n\t\t\t\tprice: 2.7,\n\t\t\t\tweight: 32\n\t\t\t}\n\t\t],\n\t\tmetadata: {\n\t\t\tcategory: 'Electronics',\n\t\t\ttags: ['new', 'featured', 'sale'],\n\t\t\tinStock: true\n\t\t},\n\t\timage: bunFile\n\t}\n\n\tit('should create a product with t.ArrayString and t.ObjectString', async () => {\n\t\tconst stringifiedVariants = JSON.stringify(newProductComplex.variants)\n\t\tconst stringifiedMetadata = JSON.stringify(newProductComplex.metadata)\n\n\t\tconst body = new FormData()\n\t\tbody.append('name', newProductComplex.name)\n\t\tbody.append('variants', stringifiedVariants)\n\t\tbody.append('metadata', stringifiedMetadata)\n\t\tbody.append('image', bunFile)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product-complex', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\t\texpect(response.status).toBe(201)\n\t\tconst data = await response.json()\n\t\texpect(data).toEqual(newProductComplex)\n\t})\n\n\tit('should return validation error on invalid t.ArrayString nested structure', async () => {\n\t\tconst stringifiedVariants = JSON.stringify([\n\t\t\t{\n\t\t\t\tprice: 23,\n\t\t\t\tweightTypo: 100 // Wrong property name\n\t\t\t}\n\t\t])\n\t\tconst stringifiedMetadata = JSON.stringify(newProductComplex.metadata)\n\n\t\tconst body = new FormData()\n\t\tbody.append('name', newProductComplex.name)\n\t\tbody.append('variants', stringifiedVariants)\n\t\tbody.append('metadata', stringifiedMetadata)\n\t\tbody.append('image', bunFile)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product-complex', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\t\tconst data = (await response.json()) as ValidationError\n\t\texpect(response.status).toBe(422)\n\t\texpect(data.type).toBe('validation')\n\t})\n\n\tit('should return validation error on invalid t.ObjectString nested structure', async () => {\n\t\tconst stringifiedVariants = JSON.stringify(newProductComplex.variants)\n\t\tconst stringifiedMetadata = JSON.stringify({\n\t\t\tcategoryTypo: 'Electronics', // Wrong property name\n\t\t\ttags: ['new', 'featured', 'sale'],\n\t\t\tinStock: true\n\t\t})\n\n\t\tconst body = new FormData()\n\t\tbody.append('name', newProductComplex.name)\n\t\tbody.append('variants', stringifiedVariants)\n\t\tbody.append('metadata', stringifiedMetadata)\n\t\tbody.append('image', bunFile)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product-complex', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\t\tconst data = (await response.json()) as ValidationError\n\t\texpect(response.status).toBe(422)\n\t\texpect(data.type).toBe('validation')\n\t})\n\n\tit('should return validation error when variants is not a valid JSON string', async () => {\n\t\tconst stringifiedMetadata = JSON.stringify(newProductComplex.metadata)\n\n\t\tconst body = new FormData()\n\t\tbody.append('name', newProductComplex.name)\n\t\tbody.append('variants', 'not-valid-json')\n\t\tbody.append('metadata', stringifiedMetadata)\n\t\tbody.append('image', bunFile)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product-complex', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\t\tconst data = (await response.json()) as ValidationError\n\t\texpect(response.status).toBe(422)\n\t\texpect(data.type).toBe('validation')\n\t})\n\n\tit('should return validation error when metadata is not a valid JSON string', async () => {\n\t\tconst stringifiedVariants = JSON.stringify(newProductComplex.variants)\n\n\t\tconst body = new FormData()\n\t\tbody.append('name', newProductComplex.name)\n\t\tbody.append('variants', stringifiedVariants)\n\t\tbody.append('metadata', 'not-valid-json')\n\t\tbody.append('image', bunFile)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product-complex', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\t\tconst data = (await response.json()) as ValidationError\n\t\texpect(response.status).toBe(422)\n\t\texpect(data.type).toBe('validation')\n\t})\n})\n\ndescribe('Nested FormData with optional t.ArrayString and t.ObjectString (PATCH operation)', async () => {\n\tconst bunFilePath4 = `${import.meta.dir}/../images/aris-yuzu.jpg`\n\tconst bunFile = Bun.file(bunFilePath4) as File\n\n\tit('PATCH with bunFile and omitted optional t.ObjectString and t.ArrayString', async () => {\n\t\tconst body = new FormData()\n\t\tbody.append('name', 'Updated Product Complex')\n\t\tbody.append('image', bunFile)\n\t\t// metadata and variants fields are omitted (should be OK since they're optional)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product-complex/456', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\tconst data = (await response.json()) as patchProductModelComplex\n\t\texpect(data).not.toBeNull()\n\t\texpect(data?.name).toBe('Updated Product Complex')\n\t\texpect(data?.metadata).toBeUndefined()\n\t\texpect(data?.variants).toBeUndefined()\n\t})\n\n\tit('PATCH with file and valid t.ObjectString and t.ArrayString data', async () => {\n\t\tconst body = new FormData()\n\t\tbody.append('name', 'Updated Product Complex')\n\t\tbody.append('image', bunFile)\n\t\tbody.append(\n\t\t\t'metadata',\n\t\t\tJSON.stringify({\n\t\t\t\tcategory: 'Electronics',\n\t\t\t\ttags: ['sale', 'new'],\n\t\t\t\tinStock: true\n\t\t\t})\n\t\t)\n\t\tbody.append(\n\t\t\t'variants',\n\t\t\tJSON.stringify([\n\t\t\t\t{\n\t\t\t\t\tprice: 15,\n\t\t\t\t\tweight: 200\n\t\t\t\t}\n\t\t\t])\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product-complex/456', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\tconst data = (await response.json()) as patchProductModelComplex\n\t\texpect(data).not.toBeNull()\n\t\texpect(data?.name).toBe('Updated Product Complex')\n\t\texpect(data?.metadata).toEqual({\n\t\t\tcategory: 'Electronics',\n\t\t\ttags: ['sale', 'new'],\n\t\t\tinStock: true\n\t\t})\n\t\texpect(data?.variants).toEqual([\n\t\t\t{\n\t\t\t\tprice: 15,\n\t\t\t\tweight: 200\n\t\t\t}\n\t\t])\n\t})\n\n\tit('PATCH without file and omitted optional fields', async () => {\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product-complex/456', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tname: 'Updated Product Complex'\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\tconst data = (await response.json()) as patchProductModelComplex\n\t\texpect(data).not.toBeNull()\n\t\texpect(data?.name).toBe('Updated Product Complex')\n\t\texpect(data?.image).toBeUndefined()\n\t\texpect(data?.metadata).toBeUndefined()\n\t\texpect(data?.variants).toBeUndefined()\n\t})\n\n\tit('PATCH should return validation error on invalid t.ObjectString', async () => {\n\t\tconst body = new FormData()\n\t\tbody.append('name', 'Updated Product Complex')\n\t\tbody.append('image', bunFile)\n\t\tbody.append(\n\t\t\t'metadata',\n\t\t\tJSON.stringify({\n\t\t\t\tcategoryTypo: 'Electronics', // Wrong property name\n\t\t\t\ttags: ['sale'],\n\t\t\t\tinStock: true\n\t\t\t})\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product-complex/456', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\t\tconst data = (await response.json()) as ValidationError\n\t\texpect(data.type).toBe('validation')\n\t})\n\n\tit('PATCH should return validation error on invalid t.ArrayString', async () => {\n\t\tconst body = new FormData()\n\t\tbody.append('name', 'Updated Product Complex')\n\t\tbody.append('image', bunFile)\n\t\tbody.append(\n\t\t\t'variants',\n\t\t\tJSON.stringify([\n\t\t\t\t{\n\t\t\t\t\tpriceTypo: 15, // Wrong property name\n\t\t\t\t\tweight: 200\n\t\t\t\t}\n\t\t\t])\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product-complex/456', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\t\tconst data = (await response.json()) as ValidationError\n\t\texpect(data.type).toBe('validation')\n\t})\n\n\tit('PATCH should return validation error when metadata is not valid JSON', async () => {\n\t\tconst body = new FormData()\n\t\tbody.append('name', 'Updated Product Complex')\n\t\tbody.append('image', bunFile)\n\t\tbody.append('metadata', 'invalid-json')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product-complex/456', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\t\tconst data = (await response.json()) as ValidationError\n\t\texpect(data.type).toBe('validation')\n\t})\n\n\tit('PATCH should return validation error when variants is not valid JSON', async () => {\n\t\tconst body = new FormData()\n\t\tbody.append('name', 'Updated Product Complex')\n\t\tbody.append('image', bunFile)\n\t\tbody.append('variants', 'invalid-json')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/product-complex/456', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\tbody\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\t\tconst data = (await response.json()) as ValidationError\n\t\texpect(data.type).toBe('validation')\n\t})\n})\n\ndescribe('Model reference with File and nested Object', () => {\n\tconst bunFilePath5 = `${import.meta.dir}/../images/aris-yuzu.jpg`\n\tconst bunFile = Bun.file(bunFilePath5) as File\n\n\tit('should coerce nested Object to ObjectString when using model reference', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model(\n\t\t\t\t'userWithAvatar',\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tavatar: t.File(),\n\t\t\t\t\tmetadata: t.Object({\n\t\t\t\t\t\tage: t.Number()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t)\n\t\t\t.post('/user', ({ body }) => body, {\n\t\t\t\tbody: 'userWithAvatar'\n\t\t\t})\n\n\t\tconst formData = new FormData()\n\t\tformData.append('name', 'John')\n\t\tformData.append('avatar', bunFile)\n\t\tformData.append('metadata', JSON.stringify({ age: 25 }))\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/user', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\tconst result = await response.json()\n\t\texpect(result).toMatchObject({\n\t\t\tname: 'John',\n\t\t\tmetadata: { age: 25 }\n\t\t})\n\t})\n})\n\ndescribe('Zod (for standard schema) with File and nested Object', () => {\n\tconst bunFilePath6 = `test/images/aris-yuzu.jpg`\n\tconst bunFile = Bun.file(bunFilePath6) as File\n\n\tit('should handle Zod schema with File and nested object (without manual coercion)', async () => {\n\t\tconst app = new Elysia().post('/upload', ({ body }) => body, {\n\t\t\tbody: z.object({\n\t\t\t\tname: z.string(),\n\t\t\t\tfile: z.file().refine((file) => fileType(file, 'image/jpeg')),\n\t\t\t\tmetadata: z.object({\n\t\t\t\t\tage: z.coerce.number()\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tconst formData = new FormData()\n\t\tformData.append('name', 'John')\n\t\tformData.append('file', bunFile)\n\t\tformData.append('metadata', JSON.stringify({ age: '25' }))\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/upload', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tname: 'John',\n\t\t\tmetadata: { age: 25 }\n\t\t})\n\t})\n\n\tit('should handle array JSON strings in FormData', async () => {\n\t\tconst app = new Elysia().post('/upload', ({ body }) => body, {\n\t\t\tbody: z.object({\n\t\t\t\tfile: z.file().refine((file) => fileType(file, 'image/jpeg')),\n\t\t\t\ttags: z.array(z.string())\n\t\t\t})\n\t\t})\n\n\t\tconst formData = new FormData()\n\t\tformData.append('file', bunFile)\n\t\tformData.append('tags', 'tag1')\n\t\tformData.append('tags', 'tag2')\n\t\tformData.append('tags', 'tag3')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/upload', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\ttags: ['tag1', 'tag2', 'tag3']\n\t\t})\n\t})\n\n\tit('should keep invalid JSON as string', async () => {\n\t\tconst app = new Elysia().post('/upload', ({ body }) => body, {\n\t\t\tbody: z.object({\n\t\t\t\tfile: z.file().refine((file) => fileType(file, 'image/jpeg')),\n\t\t\t\tdescription: z.string()\n\t\t\t})\n\t\t})\n\n\t\tconst formData = new FormData()\n\t\tformData.append('file', bunFile)\n\t\tformData.append('description', '{invalid json}')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/upload', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tdescription: '{invalid json}'\n\t\t})\n\t})\n\n\tit('should keep plain strings that are not JSON', async () => {\n\t\tconst app = new Elysia().post('/upload', ({ body }) => body, {\n\t\t\tbody: z.object({\n\t\t\t\tfile: z.file().refine((file) => fileType(file, 'image/jpeg')),\n\t\t\t\tcomment: z.string()\n\t\t\t})\n\t\t})\n\n\t\tconst formData = new FormData()\n\t\tformData.append('file', bunFile)\n\t\tformData.append('comment', 'This is a plain comment')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/upload', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tcomment: 'This is a plain comment'\n\t\t})\n\t})\n\n\tit('should handle nested objects in JSON', async () => {\n\t\tconst app = new Elysia().post('/upload', ({ body }) => body, {\n\t\t\tbody: z.object({\n\t\t\t\tfile: z.file().refine((file) => fileType(file, 'image/jpeg')),\n\t\t\t\tprofile: z.object({\n\t\t\t\t\tuser: z.object({\n\t\t\t\t\t\tname: z.string(),\n\t\t\t\t\t\tage: z.coerce.number()\n\t\t\t\t\t}),\n\t\t\t\t\tsettings: z.object({\n\t\t\t\t\t\tnotifications: z.coerce.boolean()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tconst formData = new FormData()\n\t\tformData.append('file', bunFile)\n\t\tformData.append(\n\t\t\t'profile',\n\t\t\tJSON.stringify({\n\t\t\t\tuser: {\n\t\t\t\t\tname: 'Alice',\n\t\t\t\t\tage: 30\n\t\t\t\t},\n\t\t\t\tsettings: { notifications: true }\n\t\t\t})\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/upload', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tprofile: {\n\t\t\t\tuser: { name: 'Alice', age: 30 },\n\t\t\t\tsettings: { notifications: true }\n\t\t\t}\n\t\t})\n\t})\n\n\tit('should handle Zod schema with optional fields', async () => {\n\t\tconst app = new Elysia().post('/upload', ({ body }) => body, {\n\t\t\tbody: z.object({\n\t\t\t\tfile: z.file().refine((file) => fileType(file, 'image/jpeg')),\n\t\t\t\tname: z.string(),\n\t\t\t\tdescription: z.string().optional(),\n\t\t\t\tmetadata: z\n\t\t\t\t\t.object({\n\t\t\t\t\t\tcategory: z.string(),\n\t\t\t\t\t\ttags: z.array(z.string()).optional(),\n\t\t\t\t\t\tfeatured: z.boolean().optional()\n\t\t\t\t\t})\n\t\t\t\t\t.optional()\n\t\t\t})\n\t\t})\n\n\t\tconst formData = new FormData()\n\t\tformData.append('file', bunFile)\n\t\tformData.append('name', 'Test Product')\n\t\t// Omit optional fields\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/upload', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tname: 'Test Product'\n\t\t})\n\t\texpect(result).not.toHaveProperty('description')\n\t\texpect(result).not.toHaveProperty('metadata')\n\t})\n\n\tit('should handle Zod schema with optional fields provided', async () => {\n\t\tconst app = new Elysia().post('/upload', ({ body }) => body, {\n\t\t\tbody: z.object({\n\t\t\t\tfile: z.file().refine((file) => fileType(file, 'image/jpeg')),\n\t\t\t\tname: z.string(),\n\t\t\t\tdescription: z.string().optional(),\n\t\t\t\tmetadata: z\n\t\t\t\t\t.object({\n\t\t\t\t\t\tcategory: z.string(),\n\t\t\t\t\t\ttags: z.array(z.string()).optional(),\n\t\t\t\t\t\tfeatured: z.coerce.boolean().optional()\n\t\t\t\t\t})\n\t\t\t\t\t.optional()\n\t\t\t})\n\t\t})\n\n\t\tconst formData = new FormData()\n\t\tformData.append('file', bunFile)\n\t\tformData.append('name', 'Test Product')\n\t\tformData.append('description', 'A test description')\n\t\tformData.append(\n\t\t\t'metadata',\n\t\t\tJSON.stringify({\n\t\t\t\tcategory: 'electronics',\n\t\t\t\ttags: ['phone', 'mobile'],\n\t\t\t\tfeatured: true\n\t\t\t})\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/upload', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tname: 'Test Product',\n\t\t\tdescription: 'A test description',\n\t\t\tmetadata: {\n\t\t\t\tcategory: 'electronics',\n\t\t\t\ttags: ['phone', 'mobile'],\n\t\t\t\tfeatured: true\n\t\t\t}\n\t\t})\n\t})\n})\n"
  },
  {
    "path": "test/type-system/import.ts",
    "content": "try {\r\n\tconst { TypeSystem } = await import('../../src/type-system')\r\n\tconsole.log(TypeSystem && `✅ TypeSystem import works!`)\r\n} catch (cause) {\r\n\tthrow new Error('❌ TypeSystem import failed', { cause })\r\n}\r\nexport {}\r\n"
  },
  {
    "path": "test/type-system/object-string.test.ts",
    "content": "import Elysia, { t } from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { Value } from '@sinclair/typebox/value'\nimport { req } from '../utils'\n\ndescribe('TypeSystem - ObjectString', () => {\n\tit('Create', () => {\n\t\texpect(Value.Create(t.ObjectString({}))).toBeUndefined()\n\t\texpect(\n\t\t\tValue.Create(\n\t\t\t\tt.ObjectString({}, {\n\t\t\t\t\tdefault: '{}'\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe('{}')\n\t})\n\n\tit('Check', () => {\n\t\tconst schema = t.ObjectString({\n\t\t\tpageIndex: t.Number(),\n\t\t\tpageLimit: t.Number()\n\t\t})\n\n\t\texpect(Value.Check(schema, { pageIndex: 1, pageLimit: 1 })).toBe(true)\n\t})\n\n\tit('Encode', () => {\n\t\tconst schema = t.ObjectString({\n\t\t\tpageIndex: t.Number(),\n\t\t\tpageLimit: t.Number()\n\t\t})\n\n\t\texpect(\n\t\t\tValue.Encode<typeof schema, string>(schema, {\n\t\t\t\tpageIndex: 1,\n\t\t\t\tpageLimit: 1\n\t\t\t})\n\t\t).toBe(JSON.stringify({ pageIndex: 1, pageLimit: 1 }))\n\n\t\texpect(\n\t\t\tValue.Encode<typeof schema, string>(schema, {\n\t\t\t\tpageIndex: 1,\n\t\t\t\tpageLimit: 1\n\t\t\t})\n\t\t).toBe(JSON.stringify({ pageIndex: 1, pageLimit: 1 }))\n\t})\n\n\tit('Decode', () => {\n\t\tconst schema = t.ObjectString({\n\t\t\tpageIndex: t.Number(),\n\t\t\tpageLimit: t.Number()\n\t\t})\n\n\t\texpect(\n\t\t\tValue.Decode<typeof schema>(\n\t\t\t\tschema,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tpageIndex: 1,\n\t\t\t\t\tpageLimit: 1\n\t\t\t\t})\n\t\t\t)\n\t\t).toEqual({ pageIndex: 1, pageLimit: 1 })\n\n\t\texpect(() =>\n\t\t\tValue.Decode<typeof schema>(\n\t\t\t\tschema,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tpageLimit: 1\n\t\t\t\t})\n\t\t\t)\n\t\t).toThrow()\n\t})\n\n\tit('Integrate', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tpagination: t.ObjectString({\n\t\t\t\t\tpageIndex: t.Number(),\n\t\t\t\t\tpageLimit: t.Number()\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tconst res1 = await app.handle(\n\t\t\treq('/?pagination={\"pageIndex\":1,\"pageLimit\":1}')\n\t\t)\n\t\texpect(res1.status).toBe(200)\n\n\t\tconst res2 = await app.handle(req('/?pagination={\"pageLimit\":1}'))\n\t\texpect(res2.status).toBe(422)\n\t})\n\n\tit('Optional', async () => {\n\t\tconst schema = t.Object({\n\t\t\tname: t.String(),\n\t\t\tmetadata: t.Optional(t.ObjectString({\n\t\t\t\tpageIndex: t.Number(),\n\t\t\t\tpageLimit: t.Number()\n\t\t\t}))\n\t\t})\n\n\t\texpect(Value.Check(schema, { name: 'test' })).toBe(true)\n\t\texpect(Value.Create(schema).metadata).toBeUndefined()\n\n\t\texpect(Value.Check(schema, {\n\t\t\tname: 'test',\n\t\t\tmetadata: { pageIndex: 1, pageLimit: 10 }\n\t\t})).toBe(true)\n\t\texpect(Value.Check(schema, { name: 'test', metadata: {} })).toBe(false)\n\t})\n\n\tit('Default value', async () => {\n\t\tconst schema = t.ObjectString({\n\t\t\tpageIndex: t.Number(),\n\t\t\tpageLimit: t.Number()\n\t\t}, {\n\t\t\tdefault: { pageIndex: 0, pageLimit: 10 }\n\t\t})\n\n\t\texpect(Value.Create(schema)).toEqual({ pageIndex: 0, pageLimit: 10 })\n\n\t\texpect(Value.Check(schema, { pageIndex: 1, pageLimit: 20 })).toBe(true)\n\t\texpect(Value.Check(schema, { pageIndex: 0, pageLimit: 10 })).toBe(true)\n\t\texpect(Value.Check(schema, JSON.stringify({ pageIndex: 1, pageLimit: 20 }))).toBe(true)\n\t\texpect(Value.Check(schema, JSON.stringify({ pageIndex: 0, pageLimit: 10 }))).toBe(true)\n\n\t\texpect(Value.Check(schema, {})).toBe(false)\n\t\texpect(Value.Check(schema, { pageIndex: 1 })).toBe(false)\n\t\texpect(Value.Check(schema, undefined)).toBe(false)\n\t})\n})\n"
  },
  {
    "path": "test/type-system/string-format.test.ts",
    "content": "import Elysia, { t } from '../../src'\r\nimport { describe, expect, it } from 'bun:test'\r\nimport { Value } from '@sinclair/typebox/value'\r\nimport { TBoolean, TString, TypeBoxError } from '@sinclair/typebox'\r\nimport { req } from '../utils'\r\n\r\ndescribe('TypeSystem - ObjectString', () => {\r\n\tit('Format email', async () => {\r\n\t\tconst testString = \"foo@example.com\";\r\n\t\tconst app = new Elysia().get(\r\n\t\t\t'/',\r\n\t\t\t({ query }) => query,\r\n\t\t\t{\r\n\t\t\t\tquery: t.Object({\r\n\t\t\t\t\temail: t.String({\r\n\t\t\t\t\t\tformat: 'email'\r\n\t\t\t\t\t})\r\n\t\t\t\t})\r\n\t\t\t}\r\n\t\t)\r\n\r\n\t\tconst res1 = await app.handle(req(`/?email=${testString}`))\r\n\t\texpect(res1.status).toBe(200);\r\n\r\n\t\texpect(await (res1).json()).toEqual({ email: testString })\r\n\t})\r\n\tit('Format hostname', async () => {\r\n\t\tconst testString = \"www\";\r\n\t\tconst app = new Elysia().get(\r\n\t\t\t'/',\r\n\t\t\t({ query }) => query,\r\n\t\t\t{\r\n\t\t\t\tquery: t.Object({\r\n\t\t\t\t\thost: t.String({\r\n\t\t\t\t\t\tformat: 'hostname'\r\n\t\t\t\t\t})\r\n\t\t\t\t})\r\n\t\t\t}\r\n\t\t)\r\n\r\n\t\tconst res1 = await app.handle(req(`/?host=${testString}`))\r\n\t\texpect(res1.status).toBe(200);\r\n\r\n\t\texpect(await (res1).json()).toEqual({ host: testString })\r\n\t})\r\n\tit('Format date', async () => {\r\n\t\tconst testString = \"2024-01-01\";\r\n\t\tconst app = new Elysia().get(\r\n\t\t\t'/',\r\n\t\t\t({ query }) => query,\r\n\t\t\t{\r\n\t\t\t\tquery: t.Object({\r\n\t\t\t\t\tdate: t.String({\r\n\t\t\t\t\t\tformat: 'date'\r\n\t\t\t\t\t})\r\n\t\t\t\t})\r\n\t\t\t}\r\n\t\t)\r\n\r\n\t\tconst res1 = await app.handle(req(`/?date=${testString}`))\r\n\t\texpect(res1.status).toBe(200);\r\n\r\n\t\texpect(await (res1).json()).toEqual({ date: testString })\r\n\t})\r\n})\r\n"
  },
  {
    "path": "test/type-system/uint8array.test.ts",
    "content": "import Elysia, { t } from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { Value } from '@sinclair/typebox/value'\nimport { TypeBoxError } from '@sinclair/typebox'\n\ndescribe('TypeSystem - Uint8Array', () => {\n\t// it('Create', () => {\n\t// \t// @ts-expect-error\n\t// \texpect(Value.Create(t.Uint8Array())).toEqual([1, 2, 3])\n\n\t// \texpect(\n\t// \t\tValue.Create(\n\t// \t\t\tt.ArrayString(t.Any(), {\n\t// \t\t\t\tdefault: '[]'\n\t// \t\t\t})\n\t// \t\t)\n\t// \t\t// @ts-expect-error\n\t// \t).toBe('[]')\n\t// })\n\n\t// it('Check', () => {\n\t// \tconst schema = t.Uint8Array()\n\n\t// \texpect(Value.Check(schema, new ArrayBuffer())).toBe(true)\n\t// \texpect(Value.Check(schema, new TextEncoder().encode('hello!'))).toBe(\n\t// \t\ttrue\n\t// \t)\n\t// \texpect(Value.Check(schema, [1, 2, 3])).toBe(false)\n\n\t// \texpect(\n\t// \t\tValue.Check(\n\t// \t\t\tt.Uint8Array({\n\t// \t\t\t\tmaxByteLength: 2\n\t// \t\t\t}),\n\t// \t\t\tnew TextEncoder().encode('hello!')\n\t// \t\t)\n\t// \t).toBe(false)\n\t// })\n\n\t// it('Encode', () => {\n\t// \tconst schema = t.Uint8Array()\n\n\t// \texpect(() => Value.Encode(schema, [1, 2, 3])).toThrow(TypeBoxError)\n\t// \texpect(() => Value.Encode(schema, 'test')).toThrow(TypeBoxError)\n\t// \texpect(() => Value.Encode(schema, 123)).toThrow(TypeBoxError)\n\t// \texpect(() => Value.Encode(schema, true)).toThrow(TypeBoxError)\n\t// \texpect(() => Value.Encode(schema, null)).toThrow(TypeBoxError)\n\t// \texpect(() => Value.Encode(schema, undefined)).toThrow(TypeBoxError)\n\t// })\n\n\t// it('Decode', () => {\n\t// \tconst schema = t.Uint8Array()\n\n\t// \texpect(Value.Decode(schema, new ArrayBuffer())).toEqual(\n\t// \t\tnew Uint8Array()\n\t// \t)\n\t// \texpect(() => Value.Decode(schema, [1, 2, 3])).toThrow(TypeBoxError)\n\t// \texpect(() => Value.Decode(schema, 'test')).toThrow(TypeBoxError)\n\t// \texpect(() => Value.Decode(schema, 123)).toThrow(TypeBoxError)\n\t// \texpect(() => Value.Decode(schema, true)).toThrow(TypeBoxError)\n\t// \texpect(() => Value.Decode(schema, null)).toThrow(TypeBoxError)\n\t// \texpect(() => Value.Decode(schema, undefined)).toThrow(TypeBoxError)\n\t// })\n\n\tit('Integrate', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Uint8Array(),\n\t\t\tresponse: t.Uint8Array()\n\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: new TextEncoder().encode('可愛くてごめん'),\n\t\t\t\theaders: { 'content-type': 'application/octet-stream' }\n\t\t\t})\n\t\t)\n\n\t\texpect(await response.text()).toBe('可愛くてごめん')\n\t})\n})\n"
  },
  {
    "path": "test/type-system/union-enum.test.ts",
    "content": "import Elysia, { t } from '../../src'\nimport { describe, expect, it } from 'bun:test'\nimport { Value } from '@sinclair/typebox/value'\nimport { post } from '../utils'\n\ndescribe('TypeSystem - UnionEnum', () => {\n\tit('Create', () => {\n\t\texpect(Value.Create(t.UnionEnum(['some', 'data']))).toEqual('some')\n\t})\n\n\tit('Allows readonly', () => {\n\t\tconst readonlyArray = ['some', 'data'] as const\n\t\texpect(Value.Create(t.UnionEnum(readonlyArray))).toEqual('some')\n\t})\n\n\tit('Check', () => {\n\t\tconst schema = t.UnionEnum(['some', 'data'])\n\n\t\texpect(Value.Check(schema, 'some')).toBe(true)\n\t\texpect(Value.Check(schema, 'data')).toBe(true)\n\n\t\texpect(Value.Check(schema, { deep: 2 })).toBe(false)\n\t\texpect(Value.Check(schema, 'yay')).toBe(false)\n\t\texpect(Value.Check(schema, 42)).toBe(false)\n\t\texpect(Value.Check(schema, {})).toBe(false)\n\t\texpect(Value.Check(schema, undefined)).toBe(false)\n\t})\n\n\tit('JSON schema', () => {\n\t\texpect(t.UnionEnum(['some', 'data'])).toMatchObject({\n\t\t\ttype: 'string',\n\t\t\tenum: ['some', 'data']\n\t\t})\n\t\texpect(t.UnionEnum(['some', 1]).type).toBeUndefined()\n\t\texpect(t.UnionEnum([2, 1])).toMatchObject({\n\t\t\ttype: 'number',\n\t\t\tenum: [2, 1]\n\t\t})\n\t})\n\n\tit('Integrate', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tvalue: t.UnionEnum(['some', 1])\n\t\t\t})\n\t\t})\n\t\tconst res1 = await app.handle(post('/', { value: 1 }))\n\t\texpect(res1.status).toBe(200)\n\n\t\tconst res2 = await app.handle(post('/', { value: 'some' }))\n\t\texpect(res2.status).toBe(200)\n\n\t\tconst res3 = await app.handle(post('/', { value: 'data' }))\n\t\texpect(res3.status).toBe(422)\n\t})\n})\n"
  },
  {
    "path": "test/types/async-modules.ts",
    "content": "import { expectTypeOf } from 'expect-type'\nimport { Elysia } from '../../src'\n\n// ? async plugin should mark as partial\n{\n\tconst serviceA = async () => {\n\t\tawait Bun.sleep(1)\n\n\t\treturn new Elysia()\n\t\t\t.decorate('decoratorA', 'decoratorA')\n\t\t\t.state('storeA', 'storeA' as const)\n\t\t\t.derive(() => ({\n\t\t\t\tderiveA: 'deriveA'\n\t\t\t}))\n\t\t\t.resolve(() => ({\n\t\t\t\tresolveA: 'resolveA'\n\t\t\t}))\n\t}\n\n\tnew Elysia()\n\t\t.use(serviceA)\n\t\t.decorate((v) => {\n\t\t\texpectTypeOf(v.decoratorA).toEqualTypeOf<string | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.state((v) => {\n\t\t\texpectTypeOf(v.storeA).toEqualTypeOf<'storeA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.derive((v) => {\n\t\t\texpectTypeOf(v.deriveA).toEqualTypeOf<'deriveA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.resolve((v) => {\n\t\t\texpectTypeOf(v.resolveA).toEqualTypeOf<'resolveA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n}\n\n// ? inline async should mark plugin as partial\n{\n\tconst serviceA = new Elysia().use(async (app) => {\n\t\tawait Bun.sleep(1)\n\n\t\treturn app\n\t\t\t.decorate('decoratorA', 'decoratorA')\n\t\t\t.state('storeA', 'storeA' as const)\n\t\t\t.derive(() => ({\n\t\t\t\tderiveA: 'deriveA'\n\t\t\t}))\n\t\t\t.resolve(() => ({\n\t\t\t\tresolveA: 'resolveA'\n\t\t\t}))\n\t\t\t.as('scoped')\n\t})\n\n\tnew Elysia()\n\t\t.use(serviceA)\n\t\t.decorate((v) => {\n\t\t\texpectTypeOf(v.decoratorA).toEqualTypeOf<string | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.state((v) => {\n\t\t\texpectTypeOf(v.storeA).toEqualTypeOf<'storeA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.derive((v) => {\n\t\t\texpectTypeOf(v.deriveA).toEqualTypeOf<'deriveA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.resolve((v) => {\n\t\t\texpectTypeOf(v.resolveA).toEqualTypeOf<'resolveA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n}\n\n// ? async plugin should mark plugin as partial\n{\n\tconst serviceA = async () => {\n\t\tawait Bun.sleep(1)\n\n\t\treturn new Elysia()\n\t\t\t.decorate('decoratorA', 'decoratorA')\n\t\t\t.state('storeA', 'storeA' as const)\n\t\t\t.derive(() => ({\n\t\t\t\tderiveA: 'deriveA'\n\t\t\t}))\n\t\t\t.resolve(() => ({\n\t\t\t\tresolveA: 'resolveA'\n\t\t\t}))\n\t\t\t.as('scoped')\n\t}\n\n\tnew Elysia()\n\t\t.use(serviceA)\n\t\t.decorate((v) => {\n\t\t\texpectTypeOf(v.decoratorA).toEqualTypeOf<string | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.state((v) => {\n\t\t\texpectTypeOf(v.storeA).toEqualTypeOf<'storeA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.derive((v) => {\n\t\t\texpectTypeOf(v.deriveA).toEqualTypeOf<'deriveA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.resolve((v) => {\n\t\t\texpectTypeOf(v.resolveA).toEqualTypeOf<'resolveA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n}\n\n// ? inline async should mark plugin as partial\n{\n\tconst serviceA = new Elysia().use(async (app) => {\n\t\tawait Bun.sleep(1)\n\n\t\treturn app\n\t\t\t.decorate('decoratorA', 'decoratorA')\n\t\t\t.state('storeA', 'storeA' as const)\n\t\t\t.derive(() => ({\n\t\t\t\tderiveA: 'deriveA'\n\t\t\t}))\n\t\t\t.resolve(() => ({\n\t\t\t\tresolveA: 'resolveA'\n\t\t\t}))\n\t\t\t.as('scoped')\n\t})\n\n\tnew Elysia()\n\t\t.use(serviceA)\n\t\t.decorate((v) => {\n\t\t\texpectTypeOf(v.decoratorA).toEqualTypeOf<string | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.state((v) => {\n\t\t\texpectTypeOf(v.storeA).toEqualTypeOf<'storeA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.derive((v) => {\n\t\t\texpectTypeOf(v.deriveA).toEqualTypeOf<'deriveA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.resolve((v) => {\n\t\t\texpectTypeOf(v.resolveA).toEqualTypeOf<'resolveA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n}\n\n// ? async plugin should mark global as partial\n{\n\tconst serviceA = async () => {\n\t\tawait Bun.sleep(1)\n\n\t\treturn new Elysia()\n\t\t\t.decorate('decoratorA', 'decoratorA')\n\t\t\t.state('storeA', 'storeA' as const)\n\t\t\t.derive(() => ({\n\t\t\t\tderiveA: 'deriveA'\n\t\t\t}))\n\t\t\t.resolve(() => ({\n\t\t\t\tresolveA: 'resolveA'\n\t\t\t}))\n\t\t\t.as('global')\n\t}\n\n\tnew Elysia()\n\t\t.use(serviceA)\n\t\t.decorate((v) => {\n\t\t\texpectTypeOf(v.decoratorA).toEqualTypeOf<string | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.state((v) => {\n\t\t\texpectTypeOf(v.storeA).toEqualTypeOf<'storeA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.derive((v) => {\n\t\t\texpectTypeOf(v.deriveA).toEqualTypeOf<'deriveA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.resolve((v) => {\n\t\t\texpectTypeOf(v.resolveA).toEqualTypeOf<'resolveA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n}\n\n// ? inline async should mark global as partial\n{\n\tconst serviceA = new Elysia().use(async (app) => {\n\t\tawait Bun.sleep(1)\n\n\t\treturn app\n\t\t\t.decorate('decoratorA', 'decoratorA')\n\t\t\t.state('storeA', 'storeA' as const)\n\t\t\t.derive(() => ({\n\t\t\t\tderiveA: 'deriveA'\n\t\t\t}))\n\t\t\t.resolve(() => ({\n\t\t\t\tresolveA: 'resolveA'\n\t\t\t}))\n\t\t\t.as('global')\n\t})\n\n\tnew Elysia()\n\t\t.use(serviceA)\n\t\t.decorate((v) => {\n\t\t\texpectTypeOf(v.decoratorA).toEqualTypeOf<string | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.state((v) => {\n\t\t\texpectTypeOf(v.storeA).toEqualTypeOf<'storeA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.derive((v) => {\n\t\t\texpectTypeOf(v.deriveA).toEqualTypeOf<'deriveA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n\t\t.resolve((v) => {\n\t\t\texpectTypeOf(v.resolveA).toEqualTypeOf<'resolveA' | undefined>()\n\n\t\t\treturn v\n\t\t})\n}\n\n{\n\t// ? inherits lazy loading plugin type\n\tnew Elysia().use(import('./plugins')).get(\n\t\t'/',\n\t\t({ body, decorate, store: { state } }) => {\n\t\t\texpectTypeOf<typeof decorate>().toBeString()\n\t\t\texpectTypeOf<typeof state>().toBeString()\n\t\t\texpectTypeOf<typeof body>().toBeString()\n\t\t},\n\t\t{\n\t\t\tbody: 'string'\n\t\t}\n\t)\n}\n"
  },
  {
    "path": "test/types/documentation.ts",
    "content": "import { Elysia, t } from '../../src'\n\n// handle error property\n{\n\tnew Elysia()\n\t\t.post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tage: t.Number()\n\t\t\t}),\n\t\t\terror({ code, error }) {\n\t\t\t\tswitch (code) {\n\t\t\t\t\tcase 'VALIDATION':\n\t\t\t\t\t\tconsole.log(error.all)\n\n\t\t\t\t\t\t// Find a specific error name (path is OpenAPI Schema compliance)\n\t\t\t\t\t\tconst name = error.all.find(\n\t\t\t\t\t\t\t(x) => x.summary && 'path' in x && x.path === '/name'\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\t// If there is a validation error, then log it\n\t\t\t\t\t\tif (name) console.log(name)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n}\n"
  },
  {
    "path": "test/types/index.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport {\n\ttype Cookie,\n\tElysia,\n\tfile,\n\tform,\n\tSSEPayload,\n\tsse,\n\tstatus,\n\tt\n} from '../../src'\n\nimport { expectTypeOf } from 'expect-type'\n\nconst app = new Elysia()\n\n// ? default value of context\napp.get('/', ({ headers, query, params, body, store }) => {\n\t// ? default keyof params should be never\n\texpectTypeOf<typeof params>().toEqualTypeOf<{}>()\n\n\t// ? default headers should be Record<string, unknown>\n\texpectTypeOf<typeof headers>().toEqualTypeOf<\n\t\tRecord<string, string | undefined>\n\t>()\n\n\t// ? default query should be Record<string, string>\n\texpectTypeOf<typeof query>().toEqualTypeOf<Record<string, string>>()\n\n\t// ? default body should be unknown\n\texpectTypeOf<typeof body>().toBeUnknown()\n\n\t// ? default store should be empty\n\texpectTypeOf<typeof store>().toEqualTypeOf<{}>()\n})\n\napp.model({\n\tt: t.Object({\n\t\tusername: t.String(),\n\t\tpassword: t.String()\n\t})\n}).get(\n\t'/',\n\t({ headers, query, params, body, cookie }) => {\n\t\t// ? unwrap body type\n\t\texpectTypeOf<{\n\t\t\tusername: string\n\t\t\tpassword: string\n\t\t}>().toEqualTypeOf<typeof body>()\n\n\t\t// ? unwrap body type\n\t\texpectTypeOf<{\n\t\t\tusername: string\n\t\t\tpassword: string\n\t\t}>().toEqualTypeOf<typeof query>()\n\n\t\t// ? unwrap body type\n\t\texpectTypeOf<{\n\t\t\tusername: string\n\t\t\tpassword: string\n\t\t}>().toEqualTypeOf<typeof params>()\n\n\t\t// ? unwrap body type\n\t\texpectTypeOf<{\n\t\t\tusername: string\n\t\t\tpassword: string\n\t\t}>().toEqualTypeOf<typeof headers>()\n\n\t\t// ? unwrap cookie\n\t\texpectTypeOf<\n\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\tusername: Cookie<string>\n\t\t\t\tpassword: Cookie<string>\n\t\t\t}\n\t\t>().toEqualTypeOf<typeof cookie>()\n\n\t\treturn body\n\t},\n\t{\n\t\tbody: 't',\n\t\tparams: 't',\n\t\tquery: 't',\n\t\theaders: 't',\n\t\tresponse: 't',\n\t\tcookie: 't'\n\t}\n)\n\napp.model({\n\tt: t.Object({\n\t\tusername: t.String(),\n\t\tpassword: t.String()\n\t})\n}).get(\n\t'/',\n\t({ body }) => {\n\t\t// ? unwrap body type\n\t\texpectTypeOf<{\n\t\t\tusername: string\n\t\t\tpassword: string\n\t\t}>().toEqualTypeOf<typeof body>()\n\n\t\treturn body\n\t},\n\t{\n\t\tbody: 't',\n\t\tresponse: 't'\n\t}\n)\n\napp.get('/id/:id', ({ params }) => {\n\t// ? infer params name\n\texpectTypeOf<{\n\t\tid: string\n\t}>().toEqualTypeOf<typeof params>()\n})\n\napp.get('/id/:id/name/:name', ({ params }) => {\n\t// ? infer multiple params name\n\texpectTypeOf<{\n\t\tid: string\n\t\tname: string\n\t}>().toEqualTypeOf<typeof params>()\n})\n\n// ? support unioned response\napp.get('/', () => '1', {\n\tresponse: {\n\t\t200: t.String(),\n\t\t400: t.Number()\n\t}\n}).get('/', () => 1, {\n\tresponse: {\n\t\t200: t.String(),\n\t\t400: t.Number()\n\t}\n})\n\n// ? support pre-defined schema\napp.guard({\n\tbody: t.String()\n}).get('/', ({ body }) => {\n\texpectTypeOf<typeof body>().not.toBeUnknown()\n\texpectTypeOf<typeof body>().toBeString()\n})\n\n// ? override schema\napp.guard({\n\tbody: t.String()\n}).get(\n\t'/',\n\t({ body }) => {\n\t\texpectTypeOf<typeof body>().not.toBeUnknown()\n\t\texpectTypeOf<typeof body>().toBeNumber()\n\t},\n\t{\n\t\tbody: t.Number()\n\t}\n)\n\n// ? override schema\napp.model({\n\tstring: t.String()\n}).guard(\n\t{\n\t\tbody: t.String()\n\t},\n\t(app) =>\n\t\tapp\n\t\t\t// ? Inherits guard type\n\t\t\t.get('/', ({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().not.toBeUnknown()\n\t\t\t\texpectTypeOf<typeof body>().toBeString()\n\t\t\t})\n\t\t\t// // ? override guard type\n\t\t\t.get(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().not.toBeUnknown()\n\t\t\t\t\texpectTypeOf<typeof body>().toBeNumber()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Number()\n\t\t\t\t}\n\t\t\t)\n\t\t\t// ? Merge schema and inherits typed\n\t\t\t.get(\n\t\t\t\t'/',\n\t\t\t\t({ body, query }) => {\n\t\t\t\t\texpectTypeOf<typeof query>().not.toEqualTypeOf<\n\t\t\t\t\t\tRecord<string, unknown>\n\t\t\t\t\t>()\n\t\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\t\ta: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof body>().not.toBeUnknown()\n\t\t\t\t\texpectTypeOf<typeof body>().toBeString()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\ta: t.String()\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\t\t\t// ? Inherits schema reference\n\t\t\t.get(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().not.toBeUnknown()\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<string>()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: 'string'\n\t\t\t\t}\n\t\t\t)\n\t\t\t.get(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().not.toBeUnknown()\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<string>()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: 'string'\n\t\t\t\t}\n\t\t\t)\n\t\t\t.model({\n\t\t\t\tauthorization: t.Object({\n\t\t\t\t\tauthorization: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t\t// ? Merge inherited schema\n\t\t\t.get(\n\t\t\t\t'/',\n\t\t\t\t({ body, headers }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().not.toBeUnknown()\n\n\t\t\t\t\texpectTypeOf<typeof headers>().not.toEqualTypeOf<\n\t\t\t\t\t\tRecord<string, unknown>\n\t\t\t\t\t>()\n\t\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\t\tauthorization: string\n\t\t\t\t\t}>()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\theaders: 'authorization'\n\t\t\t\t}\n\t\t\t)\n\t\t\t.guard(\n\t\t\t\t{\n\t\t\t\t\theaders: 'authorization'\n\t\t\t\t},\n\t\t\t\t(app) =>\n\t\t\t\t\t// ? To reconcilate multiple level of schema\n\t\t\t\t\tapp.get('/', ({ body, headers }) => {\n\t\t\t\t\t\texpectTypeOf<typeof body>().not.toBeUnknown()\n\t\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<string>()\n\n\t\t\t\t\t\texpectTypeOf<typeof headers>().not.toBeUnknown()\n\t\t\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\t\t\tauthorization: string\n\t\t\t\t\t\t}>()\n\t\t\t\t\t})\n\t\t\t)\n)\n\napp.state('a', 'b')\n\t// ? Infer state\n\t.get('/', ({ store }) => {\n\t\texpectTypeOf<typeof store>().toEqualTypeOf<{\n\t\t\ta: string\n\t\t}>()\n\t})\n\t.state('b', 'c')\n\t// ? Merge state\n\t.get('/', ({ store }) => {\n\t\texpectTypeOf<typeof store>().toEqualTypeOf<{\n\t\t\ta: string\n\t\t\tb: string\n\t\t}>()\n\t})\n\t.state({\n\t\tc: 'd',\n\t\td: 'e'\n\t})\n\t// ? Use multiple state\n\t.get('/', ({ store }) => {\n\t\texpectTypeOf<typeof store>().toEqualTypeOf<{\n\t\t\ta: string\n\t\t\tb: string\n\t\t\tc: string\n\t\t\td: string\n\t\t}>()\n\t})\n\napp.decorate('a', 'b')\n\t// ? Infer state\n\t.get('/', ({ a }) => {\n\t\texpectTypeOf<typeof a>().toBeString()\n\t})\n\t.decorate('b', 'c')\n\t// ? Merge state\n\t.get('/', ({ a, b }) => {\n\t\texpectTypeOf<typeof a>().toBeString()\n\t\texpectTypeOf<typeof b>().toBeString()\n\t})\n\t.decorate({\n\t\tc: 'd',\n\t\td: 'e'\n\t})\n\t// ? Use multiple decorate\n\t.get('/', ({ a, b, c, d }) => {\n\t\texpectTypeOf<{\n\t\t\ta: typeof a\n\t\t\tb: typeof b\n\t\t\tc: typeof c\n\t\t\td: typeof d\n\t\t}>().toEqualTypeOf<{\n\t\t\ta: string\n\t\t\tb: string\n\t\t\tc: string\n\t\t\td: string\n\t\t}>()\n\t})\n\n// ? Reconcile deep using name\n{\n\tconst app = new Elysia()\n\t\t.decorate('a', {\n\t\t\thello: {\n\t\t\t\tworld: 'Tako'\n\t\t\t}\n\t\t})\n\t\t.decorate('a', {\n\t\t\thello: {\n\t\t\t\tworld: 'Ina',\n\t\t\t\tcookie: 'wah!'\n\t\t\t}\n\t\t})\n\n\texpectTypeOf<(typeof app)['decorator']['a']>().toEqualTypeOf<\n\t\t{\n\t\t\thello: {\n\t\t\t\tworld: string\n\t\t\t}\n\t\t} & {\n\t\t\thello: {\n\t\t\t\tworld: string\n\t\t\t\tcookie: string\n\t\t\t}\n\t\t}\n\t>()\n}\n\n// ? Reconcile deep using value\n{\n\tconst app = new Elysia()\n\t\t.decorate({\n\t\t\thello: {\n\t\t\t\tworld: 'Tako'\n\t\t\t}\n\t\t})\n\t\t.decorate(\n\t\t\t{ as: 'override' },\n\t\t\t{\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Ina',\n\t\t\t\t\tcookie: 'wah!'\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\texpectTypeOf<typeof app.decorator.hello>().toEqualTypeOf<{\n\t\tworld: string\n\t\tcookie: string\n\t}>()\n}\n\n// ? Reconcile deep using name\n{\n\tconst app = new Elysia()\n\t\t.state('a', {\n\t\t\thello: {\n\t\t\t\tworld: 'Tako'\n\t\t\t}\n\t\t})\n\t\t.state('a', {\n\t\t\thello: {\n\t\t\t\tworld: 'Ina',\n\t\t\t\tcookie: 'wah!'\n\t\t\t}\n\t\t})\n\n\texpectTypeOf<(typeof app)['store']['a']>().toEqualTypeOf<\n\t\t{\n\t\t\thello: {\n\t\t\t\tworld: string\n\t\t\t}\n\t\t} & {\n\t\t\thello: {\n\t\t\t\tworld: string\n\t\t\t\tcookie: string\n\t\t\t}\n\t\t}\n\t>()\n}\n\n// ? Reconcile deep using value\n{\n\tconst app = new Elysia()\n\t\t.state({\n\t\t\thello: {\n\t\t\t\tworld: 'Tako'\n\t\t\t}\n\t\t})\n\t\t.state(\n\t\t\t{ as: 'override' },\n\t\t\t{\n\t\t\t\thello: {\n\t\t\t\t\tworld: 'Ina',\n\t\t\t\t\tcookie: 'wah!'\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\texpectTypeOf<typeof app.store.hello>().toEqualTypeOf<{\n\t\tworld: string\n\t\tcookie: string\n\t}>()\n}\n\nconst b = app\n\t.model('a', t.Literal('a'))\n\t// ? Infer label model\n\t.post(\n\t\t'/',\n\t\t({ body }) => {\n\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<'a'>()\n\t\t},\n\t\t{\n\t\t\tbody: 'a',\n\t\t\ttransform() {}\n\t\t}\n\t)\n\t// ? Infer multiple model\n\t.model({\n\t\tb: t.Literal('b'),\n\t\tc: t.Literal('c')\n\t})\n\t.post(\n\t\t'/',\n\t\t({ body }) => {\n\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<'b'>()\n\t\t},\n\t\t{\n\t\t\tbody: 'b'\n\t\t}\n\t)\n\t.post(\n\t\t'/',\n\t\t({ body }) => {\n\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<'c'>()\n\t\t},\n\t\t{\n\t\t\tbody: 'c'\n\t\t}\n\t)\n\n// ? It derive void\n{\n\tapp.derive(({ headers }) => {\n\t\tif (Math.random() > 0.5)\n\t\t\treturn {\n\t\t\t\tstuff: 'a'\n\t\t\t}\n\t}).get('/', ({ stuff }) => {\n\t\texpectTypeOf<typeof stuff>().not.toBeUnknown()\n\t\texpectTypeOf<typeof stuff>().toEqualTypeOf<'a' | undefined>()\n\t})\n}\n\n// ? It resolve void\n{\n\tapp.resolve(async ({ headers }) => {\n\t\tif (Math.random() > 0.5)\n\t\t\treturn {\n\t\t\t\tstuff: 'a'\n\t\t\t}\n\t}).get('/', ({ stuff }) => {\n\t\texpectTypeOf<typeof stuff>().not.toBeUnknown()\n\t\texpectTypeOf<typeof stuff>().toEqualTypeOf<'a' | undefined>()\n\t})\n}\n\napp.derive(({ headers }) => {\n\treturn {\n\t\tauthorization: headers.authorization as string\n\t}\n})\n\t.get('/', ({ authorization }) => {\n\t\t// ? infers derive type\n\t\texpectTypeOf<typeof authorization>().toBeString()\n\t})\n\t.decorate('a', 'b')\n\t.derive(({ a }) => {\n\t\t// ? derive from current context\n\t\texpectTypeOf<typeof a>().toBeString()\n\n\t\treturn {\n\t\t\tb: a\n\t\t}\n\t})\n\t.get('/', ({ a, b }) => {\n\t\t// ? save previous derivation\n\t\texpectTypeOf<typeof a>().toBeString()\n\t\t// ? derive from context\n\t\texpectTypeOf<typeof b>().toBeString()\n\t})\n\t// ? Resolve should not include in onRequest\n\t.onRequest((context) => {\n\t\texpectTypeOf<\n\t\t\t'b' extends keyof typeof context ? true : false\n\t\t>().toEqualTypeOf<false>()\n\t})\n\t// ? Resolve should not include in onTransform\n\t.onTransform((context) => {\n\t\texpectTypeOf<\n\t\t\t'b' extends keyof typeof context ? true : false\n\t\t>().toEqualTypeOf<true>()\n\t})\n\nconst plugin = (app: Elysia) =>\n\tapp.decorate('decorate', 'a').state('state', 'a').model({\n\t\tstring: t.String()\n\t})\n\n// ? inherits plugin type\napp.use(plugin)\n\t.get(\n\t\t'/',\n\t\t({ body, decorate, store: { state } }) => {\n\t\t\texpectTypeOf<typeof decorate>().toBeString()\n\t\t\texpectTypeOf<typeof state>().toBeString()\n\t\t\texpectTypeOf<typeof body>().toBeString()\n\t\t},\n\t\t{\n\t\t\tbody: 'string'\n\t\t}\n\t)\n\t.get(\n\t\t'/',\n\t\t({ body, decorate, store: { state } }) => {\n\t\t\texpectTypeOf<typeof decorate>().toBeString()\n\t\t\texpectTypeOf<typeof state>().toBeString()\n\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<string>()\n\t\t},\n\t\t{\n\t\t\tbody: 'string'\n\t\t}\n\t)\n\nexport const asyncPlugin = async (app: Elysia) =>\n\tapp.decorate('decorate', 'a').state('state', 'a').model({\n\t\tstring: t.String()\n\t})\n\n// ? group inherits type\napp.use(plugin).group('/', (app) =>\n\tapp.get(\n\t\t'/',\n\t\t({ body, decorate, store: { state } }) => {\n\t\t\texpectTypeOf<typeof decorate>().toBeString()\n\t\t\texpectTypeOf<typeof state>().toBeString()\n\t\t\texpectTypeOf<typeof body>().toBeString()\n\t\t},\n\t\t{\n\t\t\tbody: 'string'\n\t\t}\n\t)\n)\n\n// ? guard inherits type\napp.use(plugin).guard({}, (app) =>\n\tapp.get(\n\t\t'/',\n\t\t({ body, decorate, store: { state } }) => {\n\t\t\texpectTypeOf<typeof decorate>().toBeString()\n\t\t\texpectTypeOf<typeof state>().toBeString()\n\t\t\texpectTypeOf<typeof body>().toBeString()\n\t\t},\n\t\t{\n\t\t\tbody: 'string'\n\t\t}\n\t)\n)\n\n// ? guarded group inherits type\napp.use(plugin).group(\n\t'/',\n\t{\n\t\tquery: t.Object({\n\t\t\tusername: t.String()\n\t\t})\n\t},\n\t(app) => {\n\t\tapp['~Metadata'].schema\n\n\t\treturn app.get(\n\t\t\t'/',\n\t\t\t({ query, body, decorate, store: { state } }) => {\n\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\tusername: string\n\t\t\t\t}>()\n\t\t\t\texpectTypeOf<typeof decorate>().toBeString()\n\t\t\t\texpectTypeOf<typeof state>().toBeString()\n\t\t\t\texpectTypeOf<typeof body>().toBeString()\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: 'string'\n\t\t\t}\n\t\t)\n\t}\n)\n\n// ? It inherits group type to Eden\n{\n\tconst server = app\n\t\t.group(\n\t\t\t'/v1',\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) =>\n\t\t\t\tapp.guard(\n\t\t\t\t\t{\n\t\t\t\t\t\theaders: t.Object({\n\t\t\t\t\t\t\tauthorization: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t},\n\t\t\t\t\t(app) =>\n\t\t\t\t\t\tapp.get('/a', () => 1, {\n\t\t\t\t\t\t\tbody: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t)\n\t\t)\n\t\t.get('/', () => 1)\n\n\ttype App = (typeof server)['~Routes']\n\ttype Route = App['v1']['a']['get']\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\theaders: {\n\t\t\tauthorization: string\n\t\t}\n\t\tbody: string\n\t\tquery: {\n\t\t\tname: string\n\t\t}\n\t\tparams: Record<never, string>\n\t\tresponse: {\n\t\t\t200: number\n\t\t\t422: {\n\t\t\t\ttype: 'validation'\n\t\t\t\ton: string\n\t\t\t\tsummary?: string\n\t\t\t\tmessage?: string\n\t\t\t\tfound?: unknown\n\t\t\t\tproperty?: string\n\t\t\t\texpected?: string\n\t\t\t}\n\t\t}\n\t}>()\n}\n\n// ? It doesn't exposed guard type to external route\n{\n\tconst server = app\n\t\t.guard(\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) => app\n\t\t)\n\t\t.get('/', () => 1)\n\n\ttype App = (typeof server)['~Routes']\n\ttype Route = App['get']\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\tbody: unknown\n\t\tparams: {}\n\t\tquery: unknown\n\t\theaders: unknown\n\t\tresponse: {\n\t\t\t200: number\n\t\t}\n\t}>()\n}\n\n// ? Register websocket\n{\n\tconst server = app.group(\n\t\t'/v1',\n\t\t{\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t},\n\t\t(app) =>\n\t\t\tapp.guard(\n\t\t\t\t{\n\t\t\t\t\theaders: t.Object({\n\t\t\t\t\t\tauthorization: t.String()\n\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t\t(app) =>\n\t\t\t\t\tapp.ws('/a', {\n\t\t\t\t\t\tmessage(ws, message) {\n\t\t\t\t\t\t\tmessage\n\n\t\t\t\t\t\t\tws.data.params\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbody: t.String()\n\t\t\t\t\t})\n\t\t\t)\n\t)\n\ttype App = (typeof server)['~Routes']\n\ttype Route = App['v1']['a']['subscribe']\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\tbody: string\n\t\tparams: {}\n\t\tquery: {\n\t\t\tname: string\n\t\t}\n\t\theaders: {\n\t\t\tauthorization: string\n\t\t}\n\t\tresponse: {\n\t\t\t422: {\n\t\t\t\ttype: 'validation'\n\t\t\t\ton: string\n\t\t\t\tsummary?: string\n\t\t\t\tmessage?: string\n\t\t\t\tfound?: unknown\n\t\t\t\tproperty?: string\n\t\t\t\texpected?: string\n\t\t\t}\n\t\t}\n\t}>()\n}\n\n// ? Register empty model\n{\n\tconst server = app.get('/', () => 'Hello').get('/a', () => 'hi')\n\n\ttype App = (typeof server)['~Routes']\n\ttype Route = App['get']\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\tbody: unknown\n\t\tparams: {}\n\t\tquery: unknown\n\t\theaders: unknown\n\t\tresponse: {\n\t\t\t200: string\n\t\t}\n\t}>()\n}\n\n// ? Register wildcard as params\napp.get('/*', ({ params }) => {\n\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t'*': string\n\t}>()\n\n\treturn 'hello'\n}).get('/id/:id/*', ({ params }) => {\n\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\tid: string\n\t\t'*': string\n\t}>()\n\n\treturn 'hello'\n})\n\n// ? Handle recursive path typing\napp.group(\n\t'/:a',\n\t{\n\t\tbody: t.Object({}),\n\t\tbeforeHandle({ params, params: { a } }) {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\ta: string\n\t\t\t}>()\n\n\t\t\treturn a\n\t\t}\n\t},\n\t(app) =>\n\t\tapp\n\t\t\t.get('/', ({ params, params: { a } }) => {\n\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\ta: string\n\t\t\t\t}>()\n\n\t\t\t\treturn a\n\t\t\t})\n\t\t\t.group('/:b', (app) =>\n\t\t\t\tapp.get('/', ({ params, params: { a, b } }) => {\n\t\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\t\ta: string\n\t\t\t\t\t\tb: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn b\n\t\t\t\t})\n\t\t\t)\n\t\t\t.group(\n\t\t\t\t'/:c',\n\t\t\t\t{\n\t\t\t\t\tbeforeHandle({ params, params: { a, c } }) {\n\t\t\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\t\t\ta: string\n\t\t\t\t\t\t\tc: string\n\t\t\t\t\t\t}>()\n\n\t\t\t\t\t\treturn a\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t(app) =>\n\t\t\t\t\tapp.get('/', ({ params, params: { a, c } }) => {\n\t\t\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\t\t\ta: string\n\t\t\t\t\t\t\tc: string\n\t\t\t\t\t\t}>()\n\n\t\t\t\t\t\treturn c\n\t\t\t\t\t})\n\t\t\t)\n)\n\n// ? Handle recursive schema collision causing infinite type\napp.group(\n\t'/:a',\n\t{\n\t\tbody: t.Object({\n\t\t\tusername: t.String()\n\t\t}),\n\t\tquery: t.Object({\n\t\t\tuser: t.String()\n\t\t}),\n\t\tbeforeHandle: ({ body }) => {\n\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\tusername: string\n\t\t\t}>()\n\t\t}\n\t},\n\t(app) =>\n\t\tapp.group(\n\t\t\t'/:c',\n\t\t\t{\n\t\t\t\tbeforeHandle({ body, query }) {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tusername: string\n\t\t\t\t\t\tpassword: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\t\tuser: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn body\n\t\t\t\t},\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tpassword: t.String()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) =>\n\t\t\t\tapp.get('/', ({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tusername: string\n\t\t\t\t\t\tpassword: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn body\n\t\t\t\t})\n\t\t)\n)\n\n// ? Reconcilation on state\n// {\n// \tconst a = app.state('a', 'a' as const)\n// \tconst b = a.state('a', 'b' as const)\n\n// \texpectTypeOf<(typeof a)['store']>().toEqualTypeOf<{\n// \t\ta: 'a'\n// \t}>()\n\n// \texpectTypeOf<(typeof b)['store']>().toEqualTypeOf<{\n// \t\ta: 'b'\n// \t}>()\n// }\n\n// // ? Reconcilation on decorator\n// {\n// \tconst a = app.decorate('a', 'a' as const)\n// \tconst b = a.decorate('a', 'b' as const)\n\n// \texpectTypeOf<(typeof a)['decorators']>().toEqualTypeOf<{\n// \t\ta: 'a'\n// \t}>()\n\n// \texpectTypeOf<(typeof b)['decorators']>().toEqualTypeOf<{\n// \t\ta: 'b'\n// \t}>()\n// }\n\n// // ? Reconcilation on model\n// {\n// \tconst a = app.model('a', t.String())\n// \tconst b = a.model('a', t.Number())\n\n// \texpectTypeOf<(typeof a)['definitions']['type']>().toEqualTypeOf<{\n// \t\ta: string\n// \t}>()\n\n// \texpectTypeOf<(typeof b)['definitions']['type']>().toEqualTypeOf<{\n// \t\ta: number\n// \t}>()\n// }\n\n// // ? Reconcilation on use\n// {\n// \tconst a = app\n// \t\t.state('a', 'a' as const)\n// \t\t.model('a', t.String())\n// \t\t.decorate('a', 'b' as const)\n// \t\t.use((app) =>\n// \t\t\tapp\n// \t\t\t\t.state('a', 'b' as const)\n// \t\t\t\t.model('a', t.Number())\n// \t\t\t\t.decorate('a', 'b' as const)\n// \t\t)\n\n// \texpectTypeOf<(typeof a)['store']>().toEqualTypeOf<{\n// \t\ta: 'b'\n// \t}>()\n\n// \texpectTypeOf<(typeof a)['decorators']>().toEqualTypeOf<{\n// \t\ta: 'b'\n// \t}>()\n\n// \texpectTypeOf<(typeof a)['definitions']['type']>().toEqualTypeOf<{\n// \t\ta: number\n// \t}>()\n// }\n\n// ? Inherits plugin instance path\n{\n\tconst plugin = new Elysia().get('/', () => 'hello')\n\n\tconst server = app.use(plugin)\n\n\ttype App = (typeof server)['~Routes']\n\ttype Route = App['get']\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\tbody: unknown\n\t\tparams: {}\n\t\tquery: unknown\n\t\theaders: unknown\n\t\tresponse: {\n\t\t\t200: string\n\t\t}\n\t}>()\n}\n\n// ? Inherits plugin instance prefix path\n{\n\tconst pluginPrefixApp = new Elysia({ prefix: '/app' }).get(\n\t\t'/test',\n\t\t() => 'hello'\n\t)\n\n\tconst appWithArrayOfPlugin = new Elysia({ prefix: '/api' }).use([\n\t\tpluginPrefixApp\n\t])\n\tconst appWithPlugin = new Elysia({ prefix: '/api' }).use(pluginPrefixApp)\n\n\texpectTypeOf<(typeof appWithArrayOfPlugin)['~Routes']>().toEqualTypeOf<{\n\t\tapi: {\n\t\t\tapp: {\n\t\t\t\ttest: {\n\t\t\t\t\tget: {\n\t\t\t\t\t\tbody: unknown\n\t\t\t\t\t\tparams: {}\n\t\t\t\t\t\tquery: unknown\n\t\t\t\t\t\theaders: unknown\n\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t200: string\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}>()\n\texpectTypeOf<(typeof appWithArrayOfPlugin)['~Routes']>().toEqualTypeOf<\n\t\t(typeof appWithPlugin)['~Routes']\n\t>()\n}\n\n// ? Inlining function callback don't repeat prefix\n{\n\tconst test = (app: Elysia) =>\n\t\tapp.group('/app', (group) => group.get('/test', () => 'test'))\n\n\tconst app = new Elysia().use(test)\n\n\ttype App = (typeof app)['~Routes']\n\ttype Routes = keyof App['app']['test']['get']\n\n\texpectTypeOf<Routes>().not.toBeUnknown()\n}\n\n// ? Merging identical plugin type\n{\n\tconst cookie = new Elysia({\n\t\tprefix: '/'\n\t}).derive({ as: 'global' }, () => {\n\t\treturn {\n\t\t\tcustomCookie: 'A'\n\t\t}\n\t})\n\n\tconst controller = new Elysia().use(cookie).get('/', () => 'A')\n\n\tconst app = new Elysia()\n\t\t.use(cookie)\n\t\t.use(controller)\n\t\t.get('/', ({ customCookie }) => {\n\t\t\texpectTypeOf<typeof customCookie>().toBeString()\n\t\t})\n}\n\n// ? Prefer local schema over parent schema for nesting\n{\n\tnew Elysia().group(\n\t\t'/id/:id',\n\t\t{\n\t\t\tparams: t.Object({\n\t\t\t\tid: t.Number()\n\t\t\t}),\n\t\t\tbeforeHandle({ params }) {\n\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\tid: number\n\t\t\t\t}>()\n\t\t\t}\n\t\t},\n\t\t(app) =>\n\t\t\tapp\n\t\t\t\t.get('/awd', ({ params }) => {\n\t\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t}>()\n\t\t\t\t})\n\t\t\t\t.group(\n\t\t\t\t\t'/name/:name',\n\t\t\t\t\t{\n\t\t\t\t\t\tparams: t.Object({\n\t\t\t\t\t\t\tid: t.Numeric(),\n\t\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t},\n\t\t\t\t\t(app) =>\n\t\t\t\t\t\tapp.get('/awd', ({ params }) => {\n\t\t\t\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\t\t\t\tid: number\n\t\t\t\t\t\t\t\tname: string\n\t\t\t\t\t\t\t}>()\n\t\t\t\t\t\t})\n\t\t\t\t)\n\t)\n}\n\n// ? Inherits route for scoped instance\n{\n\tconst child = new Elysia()\n\t\t.decorate('b', 'b')\n\t\t.model('b', t.String())\n\t\t.get('/child', () => 'Hello from child route')\n\tconst main = new Elysia().use(child)\n\n\ttype App = (typeof main)['~Routes']\n\n\texpectTypeOf<keyof (typeof main)['~Routes']>().toEqualTypeOf<'child'>()\n\texpectTypeOf<\n\t\tkeyof (typeof main)['~Singleton']['decorator']\n\t>().not.toEqualTypeOf<{\n\t\trequest: {\n\t\t\tb: 'b'\n\t\t}\n\t\tstore: {}\n\t}>()\n\texpectTypeOf<keyof (typeof main)['definitions']>().not.toEqualTypeOf<{\n\t\ttype: {\n\t\t\tb: string\n\t\t}\n\t\terror: {}\n\t}>()\n}\n\n// ? WebSocket infers params\n{\n\tnew Elysia()\n\t\t.ws('/:id', {\n\t\t\topen(ws) {\n\t\t\t\texpectTypeOf<typeof ws.data.params>().toEqualTypeOf<{\n\t\t\t\t\tid: string\n\t\t\t\t}>()\n\t\t\t}\n\t\t})\n\t\t.ws('/:id', {\n\t\t\tparams: t.Object({\n\t\t\t\tid: t.Number()\n\t\t\t}),\n\t\t\topen(ws) {\n\t\t\t\texpectTypeOf<typeof ws.data.params>().toEqualTypeOf<{\n\t\t\t\t\tid: number\n\t\t\t\t}>()\n\t\t\t}\n\t\t})\n}\n\nconst a = app\n\t.resolve(({ headers }) => {\n\t\treturn {\n\t\t\tauthorization: headers.authorization as string\n\t\t}\n\t})\n\t// .get('/', ({ authorization }) => {\n\t// \t// ? infers derive type\n\t// \texpectTypeOf<typeof authorization>().toBeString()\n\t// })\n\t.decorate('a', 'b')\n\t.resolve(({ a }) => {\n\t\t// ? derive from current context\n\t\texpectTypeOf<typeof a>().toBeString()\n\n\t\treturn {\n\t\t\tb: a\n\t\t}\n\t})\n\t.get('/', ({ a, b }) => {\n\t\t// ? save previous derivation\n\t\texpectTypeOf<typeof a>().toBeString()\n\t\t// ? derive from context\n\t\texpectTypeOf<typeof b>().toBeString()\n\t})\n\t// ? Resolve should not include in onTransform\n\t.onTransform((context) => {\n\t\texpectTypeOf<\n\t\t\t'b' extends keyof typeof context ? true : false\n\t\t>().toEqualTypeOf<false>()\n\t})\n\t// ? Resolve should not include in onBeforeHandle\n\t.onBeforeHandle((context) => {\n\t\texpectTypeOf<\n\t\t\t'b' extends keyof typeof context ? true : false\n\t\t>().toEqualTypeOf<true>()\n\t})\n\n{\n\tapp.macro({\n\t\ta(a: string) {}\n\t})\n\t\t.get('/', () => {}, {\n\t\t\t// ? Should contains macro\n\t\t\ta: 'a'\n\t\t})\n\t\t.get('/', () => {}, {\n\t\t\t// ? Should have error\n\t\t\t// @ts-expect-error\n\t\t\ta: 1\n\t\t})\n\t\t.macro({\n\t\t\tb(a: number) {}\n\t\t})\n\t\t.get('/', () => {}, {\n\t\t\t// ? Should merge macro\n\t\t\ta: 'a',\n\t\t\tb: 2\n\t\t})\n\t\t.guard(\n\t\t\t{\n\t\t\t\t// ? Should contains macro\n\t\t\t\ta: 'a',\n\t\t\t\tb: 2\n\t\t\t},\n\t\t\t(app) =>\n\t\t\t\tapp.get('/', () => {}, {\n\t\t\t\t\t// ? Should contains macro\n\t\t\t\t\ta: 'a',\n\t\t\t\t\tb: 2\n\t\t\t\t})\n\t\t)\n}\n\n// ? Join Eden path correctly\n{\n\tconst testController = new Elysia({\n\t\tname: 'testController',\n\t\tprefix: '/test'\n\t})\n\t\t.get('/could-be-error/right', () => ({ couldBeError: true }))\n\t\t.ws('/deep/ws', {\n\t\t\tmessage() {}\n\t\t})\n\n\tconst app = new Elysia().group('/api', (app) => app.use(testController))\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['api']['test']['could-be-error']['right']['get']\n\t>().toEqualTypeOf<{\n\t\tbody: unknown\n\t\tparams: {}\n\t\tquery: unknown\n\t\theaders: unknown\n\t\tresponse: {\n\t\t\t200: {\n\t\t\t\tcouldBeError: boolean\n\t\t\t}\n\t\t}\n\t}>()\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['api']['test']['deep']['ws']['subscribe']\n\t>().toEqualTypeOf<{\n\t\tbody: {}\n\t\tparams: {}\n\t\tquery: {}\n\t\theaders: {}\n\t\tresponse: {}\n\t}>()\n}\n\n// ? Handle error status\n{\n\tconst a = new Elysia()\n\t\t.get('/', ({ status }) => status(418, 'a'), {\n\t\t\tresponse: {\n\t\t\t\t200: t.String(),\n\t\t\t\t418: t.Literal('a')\n\t\t\t}\n\t\t})\n\t\t.get('/', ({ status }) => status(418, 'b' as any), {\n\t\t\tresponse: {\n\t\t\t\t200: t.String(),\n\t\t\t\t418: t.Literal('a')\n\t\t\t}\n\t\t})\n}\n\n// ? Get response type correctly\n{\n\tconst app = new Elysia()\n\t\t.get('', () => 'a')\n\t\t.get('/true', () => true)\n\t\t.post('', () => 'a', { response: { 201: t.String() } })\n\t\t.post('/true', () => true, { response: { 202: t.Boolean() } })\n\t\t.get('/error', ({ status }) => status(\"I'm a teapot\", 'a'))\n\t\t.post('/mirror', ({ body }) => body)\n\t\t.get('/immutable', '1')\n\t\t.get('/immutable-error', ({ status }) => status(\"I'm a teapot\", 'a'))\n\t\t.get('/async', async ({ status }) => {\n\t\t\tif (Math.random() > 0.5) return status(\"I'm a teapot\", 'Nagisa')\n\n\t\t\treturn 'Hifumi'\n\t\t})\n\t\t.get('/default-error-code', ({ status }) => {\n\t\t\tif (Math.random() > 0.5) return status(418, 'Nagisa')\n\t\t\tif (Math.random() > 0.5) return status(401)\n\n\t\t\treturn 'Hifumi'\n\t\t})\n\n\ttype app = (typeof app)['~Routes']\n\n\texpectTypeOf<app['get']['response']>().toEqualTypeOf<{\n\t\t200: string\n\t}>()\n\n\texpectTypeOf<app['post']['response']>().toEqualTypeOf<{\n\t\t200: string\n\t\t201: string\n\t\t422: {\n\t\t\ttype: 'validation'\n\t\t\ton: string\n\t\t\tsummary?: string\n\t\t\tmessage?: string\n\t\t\tfound?: unknown\n\t\t\tproperty?: string\n\t\t\texpected?: string\n\t\t}\n\t}>()\n\n\texpectTypeOf<app['true']['get']['response']>().toEqualTypeOf<{\n\t\t200: boolean\n\t}>()\n\n\texpectTypeOf<app['true']['post']['response']>().toEqualTypeOf<{\n\t\t200: boolean\n\t\t202: boolean\n\t\t422: {\n\t\t\ttype: 'validation'\n\t\t\ton: string\n\t\t\tsummary?: string\n\t\t\tmessage?: string\n\t\t\tfound?: unknown\n\t\t\tproperty?: string\n\t\t\texpected?: string\n\t\t}\n\t}>()\n\n\texpectTypeOf<app['error']['get']['response']>().toEqualTypeOf<{\n\t\t418: 'a'\n\t}>()\n\n\texpectTypeOf<app['mirror']['post']['response']>().toEqualTypeOf<{}>()\n\n\texpectTypeOf<app['immutable']['get']['response']>().toEqualTypeOf<{\n\t\t200: '1'\n\t}>()\n\n\texpectTypeOf<app['immutable-error']['get']['response']>().toEqualTypeOf<{\n\t\t418: 'a'\n\t}>()\n\n\texpectTypeOf<app['async']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'Hifumi'\n\t\t418: 'Nagisa'\n\t}>()\n\n\texpectTypeOf<app['default-error-code']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'Hifumi'\n\t\t401: 'Unauthorized'\n\t\t418: 'Nagisa'\n\t}>()\n}\n\napp.get('/', ({ set }) => {\n\t// ? Able to set literal type to set.status\n\tset.status = \"I'm a teapot\"\n\n\t// ? Able to number to set.status\n\tset.status = 418\n})\n\n// ? Ephemeral and Current type\n{\n\tconst child = new Elysia()\n\t\t.derive({ as: 'scoped' }, () => {\n\t\t\treturn {\n\t\t\t\thello: 'world'\n\t\t\t}\n\t\t})\n\t\t.get('/', ({ hello }) => {\n\t\t\texpectTypeOf<typeof hello>().toEqualTypeOf<'world'>()\n\n\t\t\treturn 'hello'\n\t\t})\n\n\tconst current = new Elysia().use(child).get('/', ({ hello }) => {\n\t\texpectTypeOf<typeof hello>().toEqualTypeOf<'world'>()\n\n\t\treturn 'hello'\n\t})\n\n\tconst parrent = new Elysia().use(current).get('/', (context) => {\n\t\texpectTypeOf<typeof context>().not.toHaveProperty('hello')\n\n\t\treturn 'hello'\n\t})\n}\n\n// ? Return file with File Schema\n{\n\tconst child = new Elysia().get(\n\t\t'/',\n\t\t() => {\n\t\t\treturn file('test/kyuukurarin.mp4')\n\t\t},\n\t\t{\n\t\t\tresponse: t.File()\n\t\t}\n\t)\n}\n\n// ? Return file with Object File Schema\n{\n\tconst child = new Elysia().get(\n\t\t'/',\n\t\t() => {\n\t\t\treturn form({\n\t\t\t\ta: file('test/kyuukurarin.mp4')\n\t\t\t})\n\t\t},\n\t\t{\n\t\t\tresponse: t.Form({\n\t\t\t\ta: t.File()\n\t\t\t})\n\t\t}\n\t)\n}\n\n// ? Accept file with Object File Schema\n{\n\tconst child = new Elysia().get(\n\t\t'/',\n\t\t({ body: { file } }) => {\n\t\t\texpectTypeOf<typeof file>().toEqualTypeOf<File>()\n\n\t\t\treturn file\n\t\t},\n\t\t{\n\t\t\tbody: t.Object({\n\t\t\t\tfile: t.File()\n\t\t\t}),\n\t\t\tresponse: t.File()\n\t\t}\n\t)\n}\n\ntype a = keyof {}\n\n// It handle optional params\n{\n\tnew Elysia()\n\t\t.get('/:id?', ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\tid?: string\n\t\t\t}>()\n\t\t})\n\t\t.get('/:id/:name?', ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\tid: string\n\t\t\t\tname?: string\n\t\t\t}>()\n\t\t})\n}\n\n// ? Elysia.as\n{\n\t// ? handle as global'\n\t{\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number()\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/plugin', () => true)\n\n\t\t// @ts-expect-error\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\t}\n\n\t// handle as global with local override\n\t{\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number()\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t.guard({\n\t\t\t\tresponse: t.Boolean()\n\t\t\t})\n\t\t\t.get('/plugin', () => true)\n\n\t\t// @ts-expect-error\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\t}\n\n\t// handle as global with scoped override'\n\t{\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number()\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tresponse: t.String()\n\t\t\t})\n\t\t\t.get('/plugin', () => 'ok')\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\t}\n\n\t// ? handle as global'\n\t{\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number()\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/plugin', () => true)\n\n\t\t// @ts-expect-error\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\t}\n\n\t// ? handle as global with local override\n\t{\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number()\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t.guard({\n\t\t\t\tresponse: t.Boolean()\n\t\t\t})\n\t\t\t.get('/plugin', () => true)\n\n\t\t// @ts-expect-error\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\t}\n\n\t// handle as global with scoped override\n\t{\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number()\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tresponse: t.String()\n\t\t\t})\n\t\t\t.get('/plugin', () => 'ok')\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\t}\n\n\t// ? handle as plugin\n\t{\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number()\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('scoped')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/plugin', () => true)\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\t}\n\n\t// ? handle as propagate twice\n\t{\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Number()\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.get('/inner', () => 'a')\n\t\t\t.as('scoped')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t// @ts-expect-error\n\t\t\t.get('/plugin', () => true)\n\t\t\t.as('scoped')\n\n\t\t// @ts-expect-error\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n\t}\n\n\t// ? Reconcile status\n\t{\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: {\n\t\t\t\t\t401: t.Number(),\n\t\t\t\t\t402: t.Number()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/inner', () => '')\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t.guard({\n\t\t\t\tresponse: {\n\t\t\t\t\t401: t.Boolean()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/plugin', ({ status }) => {\n\t\t\t\tstatus('Payment Required', 20)\n\t\t\t\treturn status(401, true)\n\t\t\t})\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'ok')\n\t}\n\n\t// ? Reconcile inline handle\n\t{\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: {\n\t\t\t\t\t401: t.Number(),\n\t\t\t\t\t402: t.Number()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/inner', '')\n\t\t\t.as('global')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t.guard({\n\t\t\t\tresponse: {\n\t\t\t\t\t401: t.Boolean()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/plugin', status(401, true))\n\n\t\tconst app = new Elysia().use(plugin).get('/', 'ok')\n\t}\n}\n\n// ? Guard as\n// handle as global\n{\n\tconst inner = new Elysia()\n\t\t.guard({\n\t\t\tas: 'global',\n\t\t\tresponse: t.Number()\n\t\t})\n\t\t// @ts-expect-error\n\t\t.get('/inner', () => 'a')\n\n\tconst plugin = new Elysia()\n\t\t.use(inner)\n\t\t// @ts-expect-error\n\t\t.get('/plugin', () => true)\n\n\t// @ts-expect-error\n\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n}\n\n// ? handle as global with local override\n{\n\tconst inner = new Elysia()\n\t\t.guard({\n\t\t\tas: 'global',\n\t\t\tresponse: t.Number()\n\t\t})\n\t\t// @ts-expect-error\n\t\t.get('/inner', () => 'a')\n\n\tconst plugin = new Elysia()\n\t\t.use(inner)\n\t\t.guard({\n\t\t\tresponse: t.Boolean()\n\t\t})\n\t\t.get('/plugin', () => true)\n\n\t// @ts-expect-error\n\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n}\n\n// handle as global with scoped override\n{\n\tconst inner = new Elysia()\n\t\t.guard({\n\t\t\tas: 'global',\n\t\t\tresponse: t.Number()\n\t\t})\n\t\t// @ts-expect-error\n\t\t.get('/inner', () => 'a')\n\n\tconst plugin = new Elysia()\n\t\t.use(inner)\n\t\t.guard({\n\t\t\tas: 'scoped',\n\t\t\tresponse: t.String()\n\t\t})\n\t\t.get('/plugin', () => 'ok')\n\n\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n}\n\n// handle as global\n{\n\tconst inner = new Elysia()\n\t\t.guard({\n\t\t\tas: 'global',\n\t\t\tresponse: t.Number()\n\t\t})\n\t\t// @ts-expect-error\n\t\t.get('/inner', () => 'a')\n\n\tconst plugin = new Elysia()\n\t\t.use(inner)\n\t\t// @ts-expect-error\n\t\t.get('/plugin', () => true)\n\n\t// @ts-expect-error\n\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n}\n\n// handle as global with local override\n{\n\tconst inner = new Elysia()\n\t\t.guard({\n\t\t\tas: 'global',\n\t\t\tresponse: t.Number()\n\t\t})\n\t\t// @ts-expect-error\n\t\t.get('/inner', () => 'a')\n\n\tconst plugin = new Elysia()\n\t\t.use(inner)\n\t\t.guard({\n\t\t\tresponse: t.Boolean()\n\t\t})\n\t\t.get('/plugin', () => true)\n\n\t// @ts-expect-error\n\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n}\n\n// ? handle as global with scoped override\n{\n\tconst inner = new Elysia()\n\t\t.guard({\n\t\t\tas: 'global',\n\t\t\tresponse: t.Number()\n\t\t})\n\t\t// @ts-expect-error\n\t\t.get('/inner', () => 'a')\n\n\tconst plugin = new Elysia()\n\t\t.use(inner)\n\t\t.guard({\n\t\t\tas: 'scoped',\n\t\t\tresponse: t.String()\n\t\t})\n\t\t.get('/plugin', () => 'ok')\n\n\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n}\n\n// handle as scoped\n{\n\tconst inner = new Elysia()\n\t\t.guard({\n\t\t\tas: 'scoped',\n\t\t\tresponse: t.Number()\n\t\t})\n\t\t// @ts-expect-error\n\t\t.get('/inner', () => 'a')\n\n\tconst plugin = new Elysia()\n\t\t.use(inner)\n\t\t// @ts-expect-error\n\t\t.get('/plugin', () => true)\n\n\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n}\n\n// handle as local\n{\n\tconst inner = new Elysia()\n\t\t.guard({\n\t\t\tas: 'local',\n\t\t\tresponse: t.Number()\n\t\t})\n\t\t// @ts-expect-error\n\t\t.get('/inner', () => 'a')\n\n\tconst plugin = new Elysia().use(inner).get('/plugin', () => true)\n\n\tconst app = new Elysia().use(plugin).get('/', () => 'not a number')\n}\n\n// ? Nested guard\n{\n\tnew Elysia()\n\t\t.state('name', 'salt')\n\t\t.get('/', ({ store: { name } }) => `Hi ${name}`, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\t\t// If query 'name' is not preset, skip the whole handler\n\t\t.guard(\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) =>\n\t\t\t\tapp\n\t\t\t\t\t// Query type is inherited from guard\n\t\t\t\t\t.get('/profile', ({ query }) => `Hi`)\n\t\t\t\t\t// Store is inherited\n\t\t\t\t\t.post(\n\t\t\t\t\t\t'/name',\n\t\t\t\t\t\t({ store, body, query }) => {\n\t\t\t\t\t\t\texpectTypeOf<typeof store>().toEqualTypeOf<{\n\t\t\t\t\t\t\t\tname: string\n\t\t\t\t\t\t\t}>()\n\n\t\t\t\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\t\t\t\tname: string\n\t\t\t\t\t\t\t}>()\n\n\t\t\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\t\t\tid: number\n\t\t\t\t\t\t\t\tusername: string\n\t\t\t\t\t\t\t\tprofile: {\n\t\t\t\t\t\t\t\t\tname: string\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}>()\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbody: t.Object({\n\t\t\t\t\t\t\t\tid: t.Number({\n\t\t\t\t\t\t\t\t\tminimum: 5\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tusername: t.String(),\n\t\t\t\t\t\t\t\tprofile: t.Object({\n\t\t\t\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t)\n\n\t// ? Reconcile status\n\t{\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tresponse: {\n\t\t\t\t\t401: t.Number(),\n\t\t\t\t\t402: t.Number()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/inner', () => '')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t.guard({\n\t\t\t\tresponse: {\n\t\t\t\t\t401: t.Boolean()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/plugin', ({ status }) => {\n\t\t\t\tstatus('Payment Required', 20)\n\t\t\t\treturn status(401, true)\n\t\t\t})\n\n\t\tconst app = new Elysia().use(plugin).get('/', () => 'ok')\n\t}\n\n\t// ? Reconcile inline handle\n\t{\n\t\tconst inner = new Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tresponse: {\n\t\t\t\t\t401: t.Number(),\n\t\t\t\t\t402: t.Number()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/inner', '')\n\n\t\tconst plugin = new Elysia()\n\t\t\t.use(inner)\n\t\t\t.guard({\n\t\t\t\tresponse: {\n\t\t\t\t\t401: t.Boolean()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/plugin', status(401, true))\n\n\t\tconst app = new Elysia().use(plugin).get('/', 'ok')\n\t}\n}\n\n// Derive guard\n{\n\tnew Elysia()\n\t\t.guard({\n\t\t\tquery: t.Object({\n\t\t\t\tid: t.Number()\n\t\t\t})\n\t\t})\n\t\t.derive(({ query }) => {\n\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\tid: number\n\t\t\t}>()\n\t\t})\n\t\t.resolve(({ query }) => {\n\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\tid: number\n\t\t\t}>()\n\t\t})\n}\n\n// ? As cast shouldn't resolve derive as any key\n{\n\tconst plugin = new Elysia()\n\t\t.derive(() => ({\n\t\t\tpluginMethod() {\n\t\t\t\tconsole.log('pluginMethod')\n\t\t\t}\n\t\t}))\n\t\t.derive(({ pluginMethod, ...rest }) => ({\n\t\t\tmyPluginMethod: pluginMethod,\n\t\t\t...rest\n\t\t}))\n\t\t.as('scoped')\n\n\texpectTypeOf<(typeof plugin)['~Ephemeral']['derive']>().toHaveProperty(\n\t\t'pluginMethod'\n\t)\n}\n\n// ? afterResponse type\n{\n\tconst app = new Elysia().get(\n\t\t'/',\n\t\t() => {\n\t\t\treturn {\n\t\t\t\tduration: 200\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tresponse: {\n\t\t\t\t200: t.Object({\n\t\t\t\t\tduration: t.Number()\n\t\t\t\t}),\n\t\t\t\t400: t.Object({\n\t\t\t\t\tstuff: t.Number()\n\t\t\t\t})\n\t\t\t},\n\t\t\tafterResponse({ response }) {\n\t\t\t\t// expectTypeOf<typeof response>().toEqualTypeOf<\n\t\t\t\t// \t| {\n\t\t\t\t// \t\t\tduration: number\n\t\t\t\t// \t  }\n\t\t\t\t// \t| {\n\t\t\t\t// \t\t\tstuff: number\n\t\t\t\t// \t  }\n\t\t\t\t// >()\n\t\t\t\t// return undefined as any\n\t\t\t}\n\t\t}\n\t)\n}\n\n// ? params in local lifecycle should follow path prefix\n{\n\tnew Elysia()\n\t\t.onParse(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<\n\t\t\t\tRecord<string, string>\n\t\t\t>()\n\t\t})\n\t\t.derive(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<\n\t\t\t\tRecord<string, string>\n\t\t\t>()\n\n\t\t\treturn {}\n\t\t})\n\t\t.resolve(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<never>()\n\n\t\t\treturn {}\n\t\t})\n\t\t.onTransform(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{}>()\n\t\t})\n\t\t.onBeforeHandle(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<\n\t\t\t\tRecord<string, string>\n\t\t\t>()\n\t\t})\n\t\t.onAfterHandle(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<\n\t\t\t\tRecord<string, string>\n\t\t\t>()\n\t\t})\n\t\t.mapResponse(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<\n\t\t\t\tRecord<string, string>\n\t\t\t>()\n\t\t})\n\t\t.onAfterResponse(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<\n\t\t\t\tRecord<string, string>\n\t\t\t>()\n\t\t})\n}\n\n// ? params in local lifecycle should follow path prefix\n{\n\tnew Elysia({ prefix: '/:id' })\n\t\t.onParse(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{ id: string }>()\n\t\t})\n\t\t.derive(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{ id: string }>()\n\n\t\t\treturn {}\n\t\t})\n\t\t.resolve(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{ id: string }>()\n\n\t\t\treturn {}\n\t\t})\n\t\t.onTransform(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{ id: string }>()\n\t\t})\n\t\t.onBeforeHandle(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{ id: string }>()\n\t\t})\n\t\t.onAfterHandle(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{ id: string }>()\n\t\t})\n\t\t.mapResponse(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{ id: string }>()\n\t\t})\n\t\t.onAfterResponse(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{ id: string }>()\n\t\t})\n}\n\n// ? params in local lifecycle should respect global scope\n{\n\tnew Elysia({ prefix: '/:id' })\n\t\t.onParse({ as: 'global' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n\t\t.derive({ as: 'global' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\n\t\t\treturn {}\n\t\t})\n\t\t.resolve({ as: 'global' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\n\t\t\treturn {}\n\t\t})\n\t\t.onTransform({ as: 'global' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n\t\t.onBeforeHandle({ as: 'global' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n\t\t.onAfterHandle({ as: 'global' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n\t\t.mapResponse({ as: 'global' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n\t\t.onAfterResponse({ as: 'global' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n}\n\n// ? params in local lifecycle should respect scoped scope\n{\n\tnew Elysia({ prefix: '/:id' })\n\t\t.onParse({ as: 'scoped' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n\t\t.derive({ as: 'scoped' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\n\t\t\treturn {}\n\t\t})\n\t\t.resolve({ as: 'scoped' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\n\t\t\treturn {}\n\t\t})\n\t\t.onTransform({ as: 'scoped' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n\t\t.onBeforeHandle({ as: 'scoped' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n\t\t.onAfterHandle({ as: 'scoped' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n\t\t.mapResponse({ as: 'scoped' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n\t\t.onAfterResponse({ as: 'scoped' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n}\n\n// ? onAfterResponse should have derivative\n{\n\tnew Elysia()\n\t\t.derive(() => {\n\t\t\treturn {\n\t\t\t\tstartTime: performance.now()\n\t\t\t}\n\t\t})\n\t\t.onAfterResponse((ctx) => {\n\t\t\texpectTypeOf<typeof ctx>().not.toBeNever()\n\t\t\texpectTypeOf<(typeof ctx)['startTime']>().toBeNumber()\n\t\t})\n}\n\n// ? Websocket Response\n{\n\tnew Elysia().ws('/', {\n\t\topen: (ws) => {\n\t\t\tws.publish('channel', 'hello')\n\t\t},\n\t\tresponse: t.String()\n\t})\n}\n\n// ? Macro resolve\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tuser: (enabled: boolean) => ({\n\t\t\t\tresolve: async ({ query: { name = 'anon' } }) => ({\n\t\t\t\t\tuser: {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tasync: false\n\t\t\t\t\t} as const\n\t\t\t\t})\n\t\t\t}),\n\t\t\tasyncUser: (enabled: boolean) => ({\n\t\t\t\tresolve: async ({ query: { name = 'anon' } }) => ({\n\t\t\t\t\tuser: {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tasync: true\n\t\t\t\t\t} as const\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t\t.get(\n\t\t\t'/',\n\t\t\t({ user }) => {\n\t\t\t\texpectTypeOf<typeof user>().toEqualTypeOf<{\n\t\t\t\t\treadonly name: string\n\t\t\t\t\treadonly async: false\n\t\t\t\t}>()\n\t\t\t},\n\t\t\t{\n\t\t\t\tuser: true\n\t\t\t}\n\t\t)\n\t\t.get(\n\t\t\t'/',\n\t\t\t({ user }) => {\n\t\t\t\texpectTypeOf<typeof user>().toEqualTypeOf<{\n\t\t\t\t\treadonly name: string\n\t\t\t\t\treadonly async: true\n\t\t\t\t}>()\n\t\t\t},\n\t\t\t{\n\t\t\t\tasyncUser: true\n\t\t\t}\n\t\t)\n}\n\n// Macro\n{\n\tconst userService = new Elysia({ name: 'user/service' })\n\t\t.state({\n\t\t\tuser: {} as Record<string, string>,\n\t\t\tsession: {} as Record<number, string>\n\t\t})\n\t\t.model({\n\t\t\tsignIn: t.Object({\n\t\t\t\tusername: t.String({ minLength: 1 }),\n\t\t\t\tpassword: t.String({ minLength: 8 })\n\t\t\t}),\n\t\t\tsession: t.Cookie(\n\t\t\t\t{\n\t\t\t\t\ttoken: t.Number()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tsecrets: 'seia'\n\t\t\t\t}\n\t\t\t),\n\t\t\toptionalSession: t.Optional(t.Ref('session'))\n\t\t})\n\t\t.macro({\n\t\t\tisSignIn(enabled: boolean) {\n\t\t\t\tif (!enabled) return {}\n\n\t\t\t\treturn {\n\t\t\t\t\tbeforeHandle({\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\tcookie: { token },\n\t\t\t\t\t\tstore: { session }\n\t\t\t\t\t}) {\n\t\t\t\t\t\tif (!token.value)\n\t\t\t\t\t\t\treturn status(401, {\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tmessage: 'Unauthorized'\n\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\texpectTypeOf<typeof session>().toEqualTypeOf<\n\t\t\t\t\t\t\tRecord<number, string>\n\t\t\t\t\t\t>()\n\n\t\t\t\t\t\tconst username =\n\t\t\t\t\t\t\tsession[token.value as unknown as number]\n\n\t\t\t\t\t\tif (!username)\n\t\t\t\t\t\t\treturn status(401, {\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tmessage: 'Unauthorized'\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n}\n\n// Use validation response instead of return type\n{\n\tconst app = new Elysia().get(\n\t\t'/',\n\t\t() => {\n\t\t\treturn {\n\t\t\t\tname: 'a',\n\t\t\t\ta: 'b'\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tresponse: {\n\t\t\t\t200: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t}),\n\t\t\t\t400: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t)\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['get']['response'][200]\n\t>().toEqualTypeOf<{\n\t\tname: string\n\t}>()\n}\n\n// Use return type when validation is not provided\n{\n\tconst app = new Elysia().get(\n\t\t'/',\n\t\t() => {\n\t\t\treturn {\n\t\t\t\tname: 'a',\n\t\t\t\ta: 'b'\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tresponse: {\n\t\t\t\t400: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t)\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['get']['response'][200]\n\t>().toEqualTypeOf<{\n\t\tname: string\n\t\ta: string\n\t}>()\n}\n\n// ? cookie sample\n{\n\tconst app = new Elysia()\n\t\t.get(\n\t\t\t'/council',\n\t\t\t({ cookie: { council } }) =>\n\t\t\t\t(council.value = [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'Rin',\n\t\t\t\t\t\taffilation: 'Administration'\n\t\t\t\t\t}\n\t\t\t\t]),\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tcouncil: t.Optional(\n\t\t\t\t\t\tt.Array(\n\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\tname: t.String(),\n\t\t\t\t\t\t\t\taffilation: t.String()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\t.get('/create', ({ cookie: { name } }) => (name.value = 'Himari'))\n\t\t.get('/multiple', ({ cookie: { name, president } }) => {\n\t\t\tname.value = 'Himari'\n\t\t\tpresident.value = 'Rio'\n\n\t\t\treturn 'ok'\n\t\t})\n\t\t.get(\n\t\t\t'/update',\n\t\t\t({ cookie: { name } }) => {\n\t\t\t\tname.value = 'seminar: Himari'\n\n\t\t\t\treturn name.value\n\t\t\t},\n\t\t\t{\n\t\t\t\tcookie: t.Cookie(\n\t\t\t\t\t{\n\t\t\t\t\t\tname: t.Optional(t.String())\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tsecrets: 'a',\n\t\t\t\t\t\tsign: ['name']\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\t\t.get('/remove', ({ cookie }) => {\n\t\t\tfor (const self of Object.values(cookie)) self.remove()\n\n\t\t\treturn 'Deleted'\n\t\t})\n\t\t.get('/remove-with-options', ({ cookie }) => {\n\t\t\tfor (const self of Object.values(cookie)) self.remove()\n\n\t\t\treturn 'Deleted'\n\t\t})\n\t\t.get('/set', ({ cookie: { session } }) => {\n\t\t\tsession.value = 'rin'\n\t\t\tsession.set({\n\t\t\t\tpath: '/'\n\t\t\t})\n\t\t})\n}\n\n// Handle macro with function\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tresolve: () => ({\n\t\t\t\t\ta: 'a'\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t\t.get(\n\t\t\t'/a',\n\t\t\t({ a }) => {\n\t\t\t\texpectTypeOf<typeof a>().toEqualTypeOf<string>()\n\t\t\t},\n\t\t\t{\n\t\t\t\ta: true\n\t\t\t\t// beforeHandle: (c) => {}\n\t\t\t}\n\t\t)\n\t\t.ws('/', {\n\t\t\ta: true,\n\t\t\tmessage({ data: { a } }) {\n\t\t\t\texpectTypeOf<typeof a>().toEqualTypeOf<string>()\n\t\t\t}\n\t\t})\n}\n\n// Type AfterHandler according to known schema\n{\n\tnew Elysia().get('/', () => 'yay', {\n\t\tafterResponse({ responseValue }) {\n\t\t\texpectTypeOf<typeof responseValue>().toEqualTypeOf<\n\t\t\t\tstring | number\n\t\t\t>()\n\t\t},\n\t\tresponse: {\n\t\t\t200: t.String(),\n\t\t\t400: t.Number()\n\t\t}\n\t})\n}\n\n// Handle Prefix\n{\n\tconst app = new Elysia().group('/users', (app) =>\n\t\tapp\n\t\t\t.post('/', async ({ body }) => {\n\t\t\t\t// Create user endpoint\n\t\t\t\treturn { success: true, userId: 1 }\n\t\t\t})\n\t\t\t.get('/:id', async ({ params }) => {\n\t\t\t\t// Get user by ID endpoint\n\t\t\t\treturn { id: params.id, name: 'John Doe' }\n\t\t\t})\n\t)\n\n\texpectTypeOf<keyof (typeof app)['~Routes']['users']>().toEqualTypeOf<\n\t\t'post' | ':id'\n\t>()\n}\n\n// onError should have status\n{\n\tnew Elysia().onError(({ status }) => {\n\t\tstatus(200)\n\t})\n}\n\n// onAfterHandle should have response\n{\n\tnew Elysia().onAfterHandle(\n\t\t{ as: 'scoped' },\n\t\t({ responseValue }) => responseValue\n\t)\n}\n\n/* Neither `a` or `b` exist at the type level, even though they do exist at runtime */\n{\n\tnew Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\ta: t.String()\n\t\t\t\t}),\n\t\t\t\tresolve: () => ({ a: 'a' as const })\n\t\t\t},\n\t\t\tb: {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tb: t.String()\n\t\t\t\t}),\n\t\t\t\tresolve: () => ({ b: 'b' as const })\n\t\t\t}\n\t\t})\n\t\t.get(\n\t\t\t'/test',\n\t\t\t({ a, b, body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\ta: string\n\t\t\t\t\tb: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof a>().toEqualTypeOf<'a'>()\n\t\t\t\texpectTypeOf<typeof b>().toEqualTypeOf<'b'>()\n\n\t\t\t\treturn { a, b }\n\t\t\t},\n\t\t\t{\n\t\t\t\ta: true,\n\t\t\t\tb: true\n\t\t\t}\n\t\t)\n}\n\n// append prefix / if not provided\n{\n\tconst plugin = new Elysia({ prefix: 'v1' }).get('thing', 'thing')\n\n\tconst app = new Elysia({ prefix: 'api' }).use(plugin)\n\n\t// This should not error\n\tapp['~Routes']?.api.v1.thing\n}\n\n// handle status in afterResponse\n{\n\tnew Elysia().get('/', () => '', {\n\t\tafterHandle: ({ status }) => status(201, { foo: 'bar' }),\n\t\tresponse: {\n\t\t\t201: t.Object({\n\t\t\t\tfoo: t.String()\n\t\t\t})\n\t\t}\n\t})\n\n\tconst route = new Elysia().get('/', () => ({ foo: 'a' }), {\n\t\t// @ts-expect-error\n\t\tafterHandle: () => ({ q: 'a' }),\n\t\tresponse: t.Object({\n\t\t\tfoo: t.String()\n\t\t})\n\t})\n}\n\n// infer SSE type correctly\n{\n\tconst app = new Elysia().get('/', function* () {\n\t\tyield sse('a')\n\n\t\tyield sse({\n\t\t\tevent: 'a',\n\t\t\tdata: 'b'\n\t\t})\n\t})\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['get']['response'][200]\n\t>().toEqualTypeOf<\n\t\tGenerator<\n\t\t\t| {\n\t\t\t\t\treadonly data: 'a'\n\t\t\t  }\n\t\t\t| {\n\t\t\t\t\treadonly event: 'a'\n\t\t\t\t\treadonly data: 'b'\n\t\t\t  },\n\t\t\tvoid,\n\t\t\tunknown\n\t\t>\n\t>()\n}\n\n// return generator SSE type correctly\n{\n\tfunction* a() {\n\t\tyield 'a'\n\t\tyield 'b'\n\t}\n\n\tconst app = new Elysia().get('/', () => sse(a()))\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['get']['response'][200]\n\t>().toEqualTypeOf<\n\t\tGenerator<\n\t\t\t| {\n\t\t\t\t\treadonly data: 'a'\n\t\t\t  }\n\t\t\t| {\n\t\t\t\t\treadonly data: 'b'\n\t\t\t  },\n\t\t\tvoid,\n\t\t\tunknown\n\t\t>\n\t>()\n}\n\n// return async generator SSE type correctly\n{\n\tasync function* a() {\n\t\tyield 'a'\n\t\tyield 'b'\n\t}\n\n\tconst app = new Elysia().get('/', () => sse(a()))\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['get']['response'][200]\n\t>().toEqualTypeOf<\n\t\tAsyncGenerator<\n\t\t\t| {\n\t\t\t\t\treadonly data: 'a'\n\t\t\t  }\n\t\t\t| {\n\t\t\t\t\treadonly data: 'b'\n\t\t\t  },\n\t\t\tvoid,\n\t\t\tunknown\n\t\t>\n\t>()\n}\n\n// return ReadableStream SSE type correctly\n{\n\tasync function* a() {\n\t\tyield 'a'\n\t\tyield 'b'\n\t}\n\n\tconst app = new Elysia().get('/', () =>\n\t\tsse(undefined as any as ReadableStream<'a'>)\n\t)\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['get']['response'][200]\n\t>().toEqualTypeOf<\n\t\tReadableStream<{\n\t\t\treadonly data: 'a'\n\t\t}>\n\t>()\n}\n\n// infer ReadableStream to Iterable\n{\n\tconst app = new Elysia()\n\t\t.get('/', () => undefined as any as ReadableStream<'a'>)\n\t\t.listen(3000)\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['get']['response'][200]\n\t>().toEqualTypeOf<ReadableStream<'a'>>()\n}\n\n// Inline Elysia file\n{\n\tnew Elysia().get('/file', file('public/takodachi.png'))\n}\n\n// derive should add property union correctly\n{\n\tconst app = new Elysia()\n\t\t.derive(({ request, status }) => {\n\t\t\tconst apiKey = request.headers.get('x-api-key')\n\t\t\tif (!apiKey) return { auth: null }\n\n\t\t\tif (Math.random() > 0.5) return status(401)\n\n\t\t\treturn { auth: { id: 1 } }\n\t\t})\n\t\t.onBeforeHandle(({ auth }) => {\n\t\t\texpectTypeOf<typeof auth>().toEqualTypeOf<{\n\t\t\t\treadonly id: 1\n\t\t\t} | null>()\n\t\t})\n}\n\n// resolve should add property union correctly\n{\n\tconst app = new Elysia()\n\t\t.resolve(({ request, status }) => {\n\t\t\tconst apiKey = request.headers.get('x-api-key')\n\t\t\tif (!apiKey) return { auth: null }\n\n\t\t\tif (Math.random() > 0.5) return status(401)\n\n\t\t\treturn { auth: { id: 1 } }\n\t\t})\n\t\t.onBeforeHandle(({ auth }) => {\n\t\t\texpectTypeOf<typeof auth>().toEqualTypeOf<{\n\t\t\t\treadonly id: 1\n\t\t\t} | null>()\n\t\t})\n}\n\n// transform shouldn't inherit schema type\n{\n\tnew Elysia()\n\t\t.guard({\n\t\t\tbody: t.Object({\n\t\t\t\ta: t.String()\n\t\t\t}),\n\t\t\tparams: t.Object({\n\t\t\t\tid: t.String()\n\t\t\t})\n\t\t})\n\t\t.onTransform(({ params, body }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{}>()\n\n\t\t\texpectTypeOf<typeof body>().toBeUnknown()\n\t\t})\n}\n\n// transform should cast params to unknown when scope is over local\n{\n\tnew Elysia({ prefix: '/:id' })\n\t\t.onTransform(({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\tid: string\n\t\t\t}>()\n\t\t})\n\t\t.onTransform({ as: 'scoped' }, ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t[name: string]: string | undefined\n\t\t\t}>()\n\t\t})\n}\n\n// Enforce return type in OptionalHandler\n{\n\tnew Elysia().get(\n\t\t'/',\n\t\t({ status }) => {\n\t\t\treturn status(401, { error: 'Unauthorized' })\n\t\t},\n\t\t{\n\t\t\tbeforeHandle: ({ status }) => {\n\t\t\t\tif (Math.random() > 0.5) {\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\treturn status(401, { a: 'Unauthorized' })\n\t\t\t\t}\n\n\t\t\t\treturn status(401, { error: 'Unauthorized' })\n\t\t\t},\n\t\t\tresponse: {\n\t\t\t\t401: t.Object({\n\t\t\t\t\terror: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t)\n}\n\n// Enforce return type of Generator\n{\n\tconst message = t.Object({\n\t\tevent: t.String(),\n\t\tdata: t.Object({\n\t\t\tmessage: t.String(),\n\t\t\ttimestamp: t.String()\n\t\t})\n\t})\n\n\tnew Elysia().get(\n\t\t'/sse',\n\t\tfunction* () {\n\t\t\tyield sse({\n\t\t\t\tevent: 'message',\n\t\t\t\tdata: {\n\t\t\t\t\tmessage: 'This is a message',\n\t\t\t\t\ttimestamp: new Date().toISOString()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t{\n\t\t\tresponse: {\n\t\t\t\t200: message\n\t\t\t}\n\t\t}\n\t)\n}\n\n// Enforce return type of AsyncGenerator\n{\n\tconst message = t.Object({\n\t\tevent: t.String(),\n\t\tdata: t.Object({\n\t\t\tmessage: t.String(),\n\t\t\ttimestamp: t.String()\n\t\t})\n\t})\n\n\tnew Elysia().get(\n\t\t'/sse',\n\t\tasync function* () {\n\t\t\tyield sse({\n\t\t\t\tevent: 'message',\n\t\t\t\tdata: {\n\t\t\t\t\tmessage: 'This is a message',\n\t\t\t\t\ttimestamp: new Date().toISOString()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t{\n\t\t\tresponse: {\n\t\t\t\t200: message\n\t\t\t}\n\t\t}\n\t)\n}\n\n// Strict status response\n{\n\tnew Elysia().post(\n\t\t'/mirror',\n\t\tasync ({ status, body }) => {\n\t\t\tif (Math.random() > 0.5)\n\t\t\t\t// @ts-expect-error - should reject extra 'body' property\n\t\t\t\treturn status(201, { body, success: false })\n\n\t\t\t// @ts-expect-error\n\t\t\tif (Math.random() > 0.5) return status(200, { success: false })\n\n\t\t\t// @ts-expect-error\n\t\t\tif (Math.random() > 0.5) return status(201, { success: true })\n\t\t\tif (Math.random() > 0.5) return status(200, { success: true })\n\n\t\t\treturn status(201, { success: false })\n\t\t},\n\t\t{\n\t\t\tbody: t.Object({\n\t\t\t\tcode: t.String()\n\t\t\t}),\n\t\t\tresponse: {\n\t\t\t\t200: t.Object({\n\t\t\t\t\tsuccess: t.Literal(true)\n\t\t\t\t}),\n\t\t\t\t201: t.Object({\n\t\t\t\t\tsuccess: t.Literal(false)\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t)\n}\n\n// Status code 200 type inference (issue #1584)\n{\n\tconst app = new Elysia().get(\n\t\t'/',\n\t\t() => ({ message: 'Hello Elysia' as const }),\n\t\t{\n\t\t\tresponse: {\n\t\t\t\t200: t.Object({\n\t\t\t\t\tmessage: t.Literal('Hello Elysia')\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t)\n\n\ttype AppResponse = (typeof app)['~Routes']['get']['response']\n\n\t// Should properly infer the 200 response type, not [x: string]: any\n\tconst _typeTest: AppResponse extends {\n\t\t200: { message: 'Hello Elysia' }\n\t}\n\t\t? true\n\t\t: false = true\n\n\t// Test with multiple status codes including 200\n\tconst app2 = new Elysia().post(\n\t\t'/test',\n\t\t({ status }) => {\n\t\t\tif (Math.random() > 0.5) {\n\t\t\t\treturn status(200, { message: 'Hello Elysia' as const })\n\t\t\t}\n\t\t\treturn status(422, { error: 'Validation error' })\n\t\t},\n\t\t{\n\t\t\tresponse: {\n\t\t\t\t200: t.Object({\n\t\t\t\t\tmessage: t.Literal('Hello Elysia')\n\t\t\t\t}),\n\t\t\t\t422: t.Object({\n\t\t\t\t\terror: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t)\n\n\ttype App2Response = (typeof app2)['~Routes']['test']['post']['response']\n\n\tconst _typeTest2: App2Response extends {\n\t\t200: { message: 'Hello Elysia' }\n\t\t422: { error: string }\n\t}\n\t\t? true\n\t\t: false = true\n}\n\n// group empty prefix\n{\n\tconst app = new Elysia()\n\t\t.group('', (app) => {\n\t\t\treturn app.get('/ok', () => 'Hello World')\n\t\t})\n\t\t.listen(3000)\n\n\ttype Routes = keyof (typeof app)['~Routes']\n\n\texpectTypeOf<Routes>().toEqualTypeOf<'ok'>()\n}\n\n// override group prefix type\n{\n\tnew Elysia().group('/:example', (app) =>\n\t\tapp.get(\n\t\t\t'/',\n\t\t\t({ params: { example } }) => {\n\t\t\t\texpectTypeOf<typeof example>().toBeNumber()\n\t\t\t},\n\t\t\t{\n\t\t\t\tparams: t.Object({\n\t\t\t\t\texample: t.Numeric()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t)\n}\n\n// ? params with model\n{\n\tnew Elysia()\n\t\t.model({\n\t\t\t'character.name': t.String(),\n\t\t\t'character.thing': t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\t\t.get('/id/:id/name/:name', ({ params }) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\tid: string\n\t\t\t\tname: string\n\t\t\t}>()\n\t\t})\n}\n\n// ? Promise<Response>\n{\n\tasync function handler() {\n\t\treturn new Response(JSON.stringify({ text: 'hello' }), {\n\t\t\tstatus: 200,\n\t\t\theaders: { 'Content-Type': 'application/json' }\n\t\t})\n\t}\n\n\tnew Elysia().get('/hello', () => handler(), {\n\t\tresponse: { 200: t.Object({ text: t.String() }) }\n\t})\n}\n"
  },
  {
    "path": "test/types/lifecycle/derive.ts",
    "content": "// /* eslint-disable @typescript-eslint/no-unused-vars */\n// import { expect } from 'bun:test'\n// import { t, Elysia, RouteSchema, Cookie, error } from '../../../src'\n// import { expectTypeOf } from 'expect-type'\n\n// // Inline Derive\n// {\n// \tnew Elysia().get(\n// \t\t'/',\n// \t\t({ name }) => {\n// \t\t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t\t},\n// \t\t{\n// \t\t\tderive: () => {\n// \t\t\t\treturn { name: 'hare' as const }\n// \t\t\t}\n// \t\t}\n// \t)\n// }\n\n// // Inline Derive Array\n// {\n// \tnew Elysia().get(\n// \t\t'/',\n// \t\t({ first, last }) => {\n// \t\t\texpectTypeOf<typeof first>().toEqualTypeOf<'hare'>()\n// \t\t\texpectTypeOf<typeof last>().toEqualTypeOf<'omagari'>()\n// \t\t},\n// \t\t{\n// \t\t\tderive: [\n// \t\t\t\t() => {\n// \t\t\t\t\treturn { first: 'hare' as const }\n// \t\t\t\t},\n// \t\t\t\t() => {\n// \t\t\t\t\treturn { last: 'omagari' as const }\n// \t\t\t\t}\n// \t\t\t]\n// \t\t}\n// \t)\n// }\n\n// // Inline Derive Array\n// {\n// \tnew Elysia().get(\n// \t\t'/',\n// \t\t({ first, last }) => {\n// \t\t\texpectTypeOf<typeof first>().toEqualTypeOf<'hare'>()\n// \t\t\texpectTypeOf<typeof last>().toEqualTypeOf<'omagari'>()\n// \t\t},\n// \t\t{\n// \t\t\tderive: [\n// \t\t\t\t() => {\n// \t\t\t\t\treturn { first: 'hare' as const }\n// \t\t\t\t},\n// \t\t\t\t() => {\n// \t\t\t\t\treturn { last: 'omagari' as const }\n// \t\t\t\t}\n// \t\t\t]\n// \t\t}\n// \t)\n// }\n\n// // ? Group Derive\n// {\n// \tnew Elysia()\n// \t\t.guard(\n// \t\t\t{\n// \t\t\t\tderive: () => ({ hi: 'hare' as const })\n// \t\t\t},\n// \t\t\t(app) =>\n// \t\t\t\tapp.get('/', ({ hi }) => {\n// \t\t\t\t\texpectTypeOf<typeof hi>().toEqualTypeOf<'hare'>()\n// \t\t\t\t})\n// \t\t)\n// \t\t.get('/nope', (context) => {\n// \t\t\texpectTypeOf<typeof context>().not.toHaveProperty('hi')\n// \t\t})\n// }\n\n// // ? Group Derive\n// {\n// \tnew Elysia()\n// \t\t.guard(\n// \t\t\t{\n// \t\t\t\tderive: [\n// \t\t\t\t\t() => ({ first: 'hare' as const }),\n// \t\t\t\t\t() => ({ last: 'omagari' as const })\n// \t\t\t\t]\n// \t\t\t},\n// \t\t\t(app) =>\n// \t\t\t\tapp.get('/', ({ first, last }) => {\n// \t\t\t\t\texpectTypeOf<typeof first>().toEqualTypeOf<'hare'>()\n// \t\t\t\t\texpectTypeOf<typeof last>().toEqualTypeOf<'omagari'>()\n// \t\t\t\t})\n// \t\t)\n// \t\t.get('/nope', (context) => {\n// \t\t\texpectTypeOf<typeof context>().not.toHaveProperty('first')\n// \t\t\texpectTypeOf<typeof context>().not.toHaveProperty('last')\n// \t\t})\n// }\n\n// // ? Guard Derive\n// {\n// \tconst plugin = new Elysia()\n// \t\t.guard({\n// \t\t\tderive: () => ({ name: 'hare' as const })\n// \t\t})\n// \t\t.get('/', ({ name }) => {\n// \t\t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t\t})\n\n// \tnew Elysia().use(plugin).get('/', (context) => {\n// \t\texpectTypeOf<typeof context>().not.toHaveProperty('name')\n// \t})\n// }\n\n// // ? Guard Derive Array\n// {\n// \tnew Elysia()\n// \t\t.guard({\n// \t\t\tderive: [\n// \t\t\t\t() => ({ first: 'hare' as const }),\n// \t\t\t\t() => ({ last: 'omagari' as const })\n// \t\t\t]\n// \t\t})\n// \t\t.get('/', ({ first, last }) => {\n// \t\t\texpectTypeOf<typeof first>().toEqualTypeOf<'hare'>()\n// \t\t\texpectTypeOf<typeof last>().toEqualTypeOf<'omagari'>()\n// \t\t})\n// }\n\n// // ? Scoped Derive\n// {\n// \tconst plugin = new Elysia()\n// \t\t.guard({\n// \t\t\tas: 'scoped',\n// \t\t\tderive: () => ({ name: 'hare' as const })\n// \t\t})\n// \t\t.get('/', ({ name }) => {\n// \t\t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t\t})\n\n// \tconst app = new Elysia().use(plugin).get('/', ({ name }) => {\n// \t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t})\n\n// \tconst root = new Elysia().use(app).get('/', (context) => {\n// \t\texpectTypeOf<typeof context>().not.toHaveProperty('name')\n// \t})\n// }\n\n// // ? Global Derive\n// {\n// \tconst plugin = new Elysia()\n// \t\t.guard({\n// \t\t\tas: 'global',\n// \t\t\tderive: () => ({ name: 'hare' as const })\n// \t\t})\n// \t\t.get('/', ({ name }) => {\n// \t\t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t\t})\n\n// \tconst app = new Elysia().use(plugin).get('/', ({ name }) => {\n// \t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t})\n\n// \tnew Elysia().use(app).get('/', ({ name }) => {\n// \t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t})\n// }\n"
  },
  {
    "path": "test/types/lifecycle/resolve.ts",
    "content": "// /* eslint-disable @typescript-eslint/no-unused-vars */\n// import { expect } from 'bun:test'\n// import { t, Elysia, RouteSchema, Cookie, error } from '../../../src'\n// import { expectTypeOf } from 'expect-type'\n\n// // Inline Resolve\n// {\n// \tnew Elysia().get(\n// \t\t'/',\n// \t\t({ name }) => {\n// \t\t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t\t},\n// \t\t{\n// \t\t\tresolve: () => {\n// \t\t\t\treturn { name: 'hare' as const }\n// \t\t\t}\n// \t\t}\n// \t)\n// }\n\n// // Inline Resolve Array\n// {\n// \tnew Elysia().get(\n// \t\t'/',\n// \t\t({ first, last }) => {\n// \t\t\texpectTypeOf<typeof first>().toEqualTypeOf<'hare'>()\n// \t\t\texpectTypeOf<typeof last>().toEqualTypeOf<'omagari'>()\n// \t\t},\n// \t\t{\n// \t\t\tresolve: [\n// \t\t\t\t() => {\n// \t\t\t\t\treturn { first: 'hare' as const }\n// \t\t\t\t},\n// \t\t\t\t() => {\n// \t\t\t\t\treturn { last: 'omagari' as const }\n// \t\t\t\t}\n// \t\t\t]\n// \t\t}\n// \t)\n// }\n\n// // Inline Resolve Array\n// {\n// \tnew Elysia().get(\n// \t\t'/',\n// \t\t({ first, last }) => {\n// \t\t\texpectTypeOf<typeof first>().toEqualTypeOf<'hare'>()\n// \t\t\texpectTypeOf<typeof last>().toEqualTypeOf<'omagari'>()\n// \t\t},\n// \t\t{\n// \t\t\tresolve: [\n// \t\t\t\t() => {\n// \t\t\t\t\treturn { first: 'hare' as const }\n// \t\t\t\t},\n// \t\t\t\t() => {\n// \t\t\t\t\treturn { last: 'omagari' as const }\n// \t\t\t\t}\n// \t\t\t]\n// \t\t}\n// \t)\n// }\n\n// // ? Group Resolve\n// {\n// \tnew Elysia()\n// \t\t.guard(\n// \t\t\t{\n// \t\t\t\tresolve: () => ({ hi: 'hare' as const })\n// \t\t\t},\n// \t\t\t(app) =>\n// \t\t\t\tapp.get('/', ({ hi }) => {\n// \t\t\t\t\texpectTypeOf<typeof hi>().toEqualTypeOf<'hare'>()\n// \t\t\t\t})\n// \t\t)\n// \t\t.get('/nope', (context) => {\n// \t\t\texpectTypeOf<typeof context>().not.toHaveProperty('hi')\n// \t\t})\n// }\n\n// // ? Group Resolve\n// {\n// \tnew Elysia()\n// \t\t.guard(\n// \t\t\t{\n// \t\t\t\tresolve: [\n// \t\t\t\t\t() => ({ first: 'hare' as const }),\n// \t\t\t\t\t() => ({ last: 'omagari' as const })\n// \t\t\t\t]\n// \t\t\t},\n// \t\t\t(app) =>\n// \t\t\t\tapp.get('/', ({ first, last }) => {\n// \t\t\t\t\texpectTypeOf<typeof first>().toEqualTypeOf<'hare'>()\n// \t\t\t\t\texpectTypeOf<typeof last>().toEqualTypeOf<'omagari'>()\n// \t\t\t\t})\n// \t\t)\n// \t\t.get('/nope', (context) => {\n// \t\t\texpectTypeOf<typeof context>().not.toHaveProperty('first')\n// \t\t\texpectTypeOf<typeof context>().not.toHaveProperty('last')\n// \t\t})\n// }\n\n// // ? Guard Resolve\n// {\n// \tconst plugin = new Elysia()\n// \t\t.guard({\n// \t\t\tresolve: () => ({ name: 'hare' as const })\n// \t\t})\n// \t\t.get('/', ({ name }) => {\n// \t\t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t\t})\n\n// \tnew Elysia().use(plugin).get('/', (context) => {\n// \t\texpectTypeOf<typeof context>().not.toHaveProperty('name')\n// \t})\n// }\n\n// // ? Guard Resolve Array\n// {\n// \tnew Elysia()\n// \t\t.guard({\n// \t\t\tresolve: [\n// \t\t\t\t() => ({ first: 'hare' as const }),\n// \t\t\t\t() => ({ last: 'omagari' as const })\n// \t\t\t]\n// \t\t})\n// \t\t.get('/', ({ first, last }) => {\n// \t\t\texpectTypeOf<typeof first>().toEqualTypeOf<'hare'>()\n// \t\t\texpectTypeOf<typeof last>().toEqualTypeOf<'omagari'>()\n// \t\t})\n// }\n\n// // ? Scoped Resolve\n// {\n// \tconst plugin = new Elysia()\n// \t\t.guard({\n// \t\t\tas: 'scoped',\n// \t\t\tresolve: () => ({ name: 'hare' as const })\n// \t\t})\n// \t\t.get('/', ({ name }) => {\n// \t\t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t\t})\n\n// \tconst app = new Elysia().use(plugin).get('/', ({ name }) => {\n// \t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t})\n\n// \tconst root = new Elysia().use(app).get('/', (context) => {\n// \t\texpectTypeOf<typeof context>().not.toHaveProperty('name')\n// \t})\n// }\n\n// // ? Global Resolve\n// {\n// \tconst plugin = new Elysia()\n// \t\t.guard({\n// \t\t\tas: 'global',\n// \t\t\tresolve: () => ({ name: 'hare' as const })\n// \t\t})\n// \t\t.get('/', ({ name }) => {\n// \t\t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t\t})\n\n// \tconst app = new Elysia().use(plugin).get('/', ({ name }) => {\n// \t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t})\n\n// \tnew Elysia().use(app).get('/', ({ name }) => {\n// \t\texpectTypeOf<typeof name>().toEqualTypeOf<'hare'>()\n// \t})\n// }\n\n// // ? Macro resolve\n// {\n// \tconst macro = new Elysia()\n// \t\t.macro({\n// \t\t\ta: () => ({\n// \t\t\t\tresolve: () => ({\n// \t\t\t\t\tmessage: 'hello' as const\n// \t\t\t\t})\n// \t\t\t})\n// \t\t})\n// \t\t.get(\n// \t\t\t'/',\n// \t\t\t({ message }) => {\n// \t\t\t\texpectTypeOf<typeof message>().toEqualTypeOf<'hello'>()\n// \t\t\t},\n// \t\t\t{\n// \t\t\t\ta: true\n// \t\t\t}\n// \t\t)\n\n// \tconst main = new Elysia().use(macro).get(\n// \t\t'/',\n// \t\t({ message }) => {\n// \t\t\texpectTypeOf<typeof message>().toEqualTypeOf<'hello'>()\n// \t\t},\n// \t\t{\n// \t\t\ta: true\n// \t\t}\n// \t)\n// }\n"
  },
  {
    "path": "test/types/lifecycle/soundness.ts",
    "content": "import { Cookie, Elysia, t } from '../../../src'\nimport { expectTypeOf } from 'expect-type'\nimport { Prettify } from '../../../src/types'\n\n// Handle resolve property correctly\n{\n\tconst app = new Elysia().resolve(({ status }) => {\n\t\tif (Math.random() > 0.05) return status(401)\n\n\t\treturn {\n\t\t\tname: 'mokou'\n\t\t}\n\t})\n\n\ttype Resolve = (typeof app)['~Volatile']['resolve']\n\texpectTypeOf<Resolve>().toEqualTypeOf<{\n\t\tname: 'mokou'\n\t}>\n}\n\n// Handle resolve property without any data\n{\n\tconst app = new Elysia().resolve(({ status }) => {\n\t\tif (Math.random() > 0.05) return status(401)\n\t})\n\n\ttype Resolve = (typeof app)['~Volatile']['resolve']\n\texpectTypeOf<Resolve>().toEqualTypeOf<{}>\n}\n\n// Type soundness of lifecycle event in local\n{\n\tconst app = new Elysia()\n\t\t.onError(({ status }) => {\n\t\t\tif (Math.random() > 0.05) return status(400)\n\t\t})\n\t\t.resolve(({ status }) => {\n\t\t\tif (Math.random() > 0.05) return status(401)\n\t\t})\n\t\t.onBeforeHandle([\n\t\t\t({ status }) => {\n\t\t\t\tif (Math.random() > 0.05) return status(402)\n\t\t\t},\n\t\t\t({ status }) => {\n\t\t\t\tif (Math.random() > 0.05) return status(403)\n\t\t\t}\n\t\t])\n\t\t.guard({\n\t\t\tbeforeHandle: [\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(405)\n\t\t\t\t},\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(406)\n\t\t\t\t}\n\t\t\t],\n\t\t\tafterHandle({ status }) {\n\t\t\t\tif (Math.random() > 0.05) return status(407)\n\t\t\t},\n\t\t\terror({ status }) {\n\t\t\t\tif (Math.random() > 0.05) return status(408)\n\t\t\t}\n\t\t})\n\t\t.get('/', ({ body, status }) =>\n\t\t\tMath.random() > 0.05 ? status(409) : ('Hello World' as const)\n\t\t)\n\n\ttype Lifecycle = Prettify<(typeof app)['~Volatile']['response']>\n\n\texpectTypeOf<Lifecycle>().toEqualTypeOf<{\n\t\t400: 'Bad Request'\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t}>()\n\n\ttype Route = Prettify<(typeof app)['~Routes']['get']['response']>\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\t200: 'Hello World'\n\t\t400: 'Bad Request'\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t\t409: 'Conflict'\n\t}>\n}\n\n// Type soundness of lifecycle event in scoped\n{\n\tconst app = new Elysia()\n\t\t.onError(({ status }) => {\n\t\t\tif (Math.random() > 0.05) return status(400)\n\t\t})\n\t\t.resolve(({ status }) => {\n\t\t\tif (Math.random() > 0.05) return status(401)\n\t\t})\n\t\t.onBeforeHandle([\n\t\t\t({ status }) => {\n\t\t\t\tif (Math.random() > 0.05) return status(402)\n\t\t\t},\n\t\t\t({ status }) => {\n\t\t\t\tif (Math.random() > 0.05) return status(403)\n\t\t\t}\n\t\t])\n\t\t.guard({\n\t\t\tbeforeHandle: [\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(405)\n\t\t\t\t},\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(406)\n\t\t\t\t}\n\t\t\t],\n\t\t\tafterHandle({ status }) {\n\t\t\t\tif (Math.random() > 0.05) return status(407)\n\t\t\t},\n\t\t\terror({ status }) {\n\t\t\t\tif (Math.random() > 0.05) return status(408)\n\t\t\t}\n\t\t})\n\t\t.as('scoped')\n\t\t.get('/', ({ body, status }) =>\n\t\t\tMath.random() > 0.05 ? status(409) : ('Hello World' as const)\n\t\t)\n\n\ttype Lifecycle = Prettify<(typeof app)['~Ephemeral']['response']>\n\n\texpectTypeOf<Lifecycle>().toEqualTypeOf<{\n\t\t400: 'Bad Request'\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t}>()\n\n\ttype Route = Prettify<(typeof app)['~Routes']['get']['response']>\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\t200: 'Hello World'\n\t\t400: 'Bad Request'\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t\t409: 'Conflict'\n\t}>\n}\n\n// Type soundness of lifecycle event in global\n{\n\tconst app = new Elysia()\n\t\t.onError(({ status }) => {\n\t\t\tif (Math.random() > 0.05) return status(400)\n\t\t})\n\t\t.resolve(({ status }) => {\n\t\t\tif (Math.random() > 0.05) return status(401)\n\t\t})\n\t\t.onBeforeHandle([\n\t\t\t({ status }) => {\n\t\t\t\tif (Math.random() > 0.05) return status(402)\n\t\t\t},\n\t\t\t({ status }) => {\n\t\t\t\tif (Math.random() > 0.05) return status(403)\n\t\t\t}\n\t\t])\n\t\t.guard({\n\t\t\tbeforeHandle: [\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(405)\n\t\t\t\t},\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(406)\n\t\t\t\t}\n\t\t\t],\n\t\t\tafterHandle({ status }) {\n\t\t\t\tif (Math.random() > 0.05) return status(407)\n\t\t\t},\n\t\t\terror({ status }) {\n\t\t\t\tif (Math.random() > 0.05) return status(408)\n\t\t\t}\n\t\t})\n\t\t.as('global')\n\t\t.get('/', ({ body, status }) =>\n\t\t\tMath.random() > 0.05 ? status(409) : ('Hello World' as const)\n\t\t)\n\n\ttype Lifecycle = Prettify<(typeof app)['~Metadata']['response']>\n\n\texpectTypeOf<Lifecycle>().toEqualTypeOf<{\n\t\t400: 'Bad Request'\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t}>()\n\n\ttype Route = Prettify<(typeof app)['~Routes']['get']['response']>\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\t200: 'Hello World'\n\t\t400: 'Bad Request'\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t\t409: 'Conflict'\n\t}>\n}\n\n// All together now\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tauth: {\n\t\t\t\tresponse: {\n\t\t\t\t\t409: t.Literal('Conflict')\n\t\t\t\t},\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random() < 0.05) return status(410)\n\t\t\t\t},\n\t\t\t\tresolve: () => ({ a: 'a' as const })\n\t\t\t}\n\t\t})\n\t\t.onError(({ status }) => {\n\t\t\tif (Math.random() < 0.05) return status(400)\n\t\t})\n\t\t.resolve(({ status }) => {\n\t\t\tif (Math.random() < 0.05) return status(401)\n\n\t\t\treturn {\n\t\t\t\tb: 'b' as const\n\t\t\t}\n\t\t})\n\t\t.onBeforeHandle([\n\t\t\t({ status }) => {\n\t\t\t\tif (Math.random() < 0.05) return status(402)\n\t\t\t},\n\t\t\t({ status }) => {\n\t\t\t\tif (Math.random() < 0.05) return status(403)\n\t\t\t}\n\t\t])\n\t\t.guard({\n\t\t\tbeforeHandle: [\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() < 0.05) return status(405)\n\t\t\t\t},\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() < 0.05) return status(406)\n\t\t\t\t}\n\t\t\t],\n\t\t\tafterHandle({ status }) {\n\t\t\t\tif (Math.random() < 0.05) return status(407)\n\t\t\t},\n\t\t\terror({ status }) {\n\t\t\t\tif (Math.random() < 0.05) return status(408)\n\t\t\t}\n\t\t})\n\t\t.post(\n\t\t\t'/',\n\t\t\t({ status, a, b }) => {\n\t\t\t\tif (Math.random() < 0.05) return status(409, 'Conflict')\n\n\t\t\t\texpectTypeOf<typeof a>().toEqualTypeOf<'a'>()\n\t\t\t\texpectTypeOf<typeof b>().toEqualTypeOf<'b'>()\n\n\t\t\t\treturn 'Type Soundness'\n\t\t\t},\n\t\t\t{\n\t\t\t\tauth: true,\n\t\t\t\tresponse: {\n\t\t\t\t\t411: t.Literal('Length Required')\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\ttype Lifecycle = (typeof app)['~Routes']['post']['response']\n\n\texpectTypeOf<Lifecycle>().toEqualTypeOf<{\n\t\t200: 'Type Soundness'\n\t\t400: 'Bad Request'\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t\t409: 'Conflict'\n\t\t410: 'Gone'\n\t\t411: 'Length Required'\n\t\t422: {\n\t\t\ttype: 'validation'\n\t\t\ton: string\n\t\t\tsummary?: string\n\t\t\tmessage?: string\n\t\t\tfound?: unknown\n\t\t\tproperty?: string\n\t\t\texpected?: string\n\t\t}\n\t}>()\n}\n\n// Macro without schema should not have 422\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tauth: {\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random() < 0.05) return status(410)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.get('/', () => 'Hello World' as const, {\n\t\t\tauth: true\n\t\t})\n\n\ttype Route = (typeof app)['~Routes']['get']['response']\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\t200: 'Hello World'\n\t\t410: 'Gone'\n\t}>()\n}\n\n// Macro with schema should have 422\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tauth: {\n\t\t\t\tresponse: {\n\t\t\t\t\t401: t.Literal('Unauthorized')\n\t\t\t\t},\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random() < 0.05) return status(410)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.get('/', () => 'Hello World' as const, {\n\t\t\tauth: true\n\t\t})\n\n\ttype Route = (typeof app)['~Routes']['get']['response']\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\t200: 'Hello World'\n\t\t401: 'Unauthorized'\n\t\t410: 'Gone'\n\t\t422: {\n\t\t\ttype: 'validation'\n\t\t\ton: string\n\t\t\tsummary?: string\n\t\t\tmessage?: string\n\t\t\tfound?: unknown\n\t\t\tproperty?: string\n\t\t\texpected?: string\n\t\t}\n\t}>()\n}\n\n// Macro should inject schema\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tauth: {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\theaders: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\tcookie: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t401: t.Literal('Unauthorized')\n\t\t\t\t},\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random() < 0.05) return status(410)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.get(\n\t\t\t'/',\n\t\t\t({ headers, body, cookie, params, query, status }) => {\n\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\tname: 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tname: 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\tname: Cookie<'lilith'>\n\t\t\t\t\t}\n\t\t\t\t>()\n\n\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\tname: 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\tname: 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\tif (Math.random() > 0.5) return status(401, 'Unauthorized')\n\n\t\t\t\tif (Math.random() > 0.5)\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\treturn status(401, 'Unauthorize')\n\n\t\t\t\treturn 'Hello World' as const\n\t\t\t},\n\t\t\t{\n\t\t\t\tauth: true\n\t\t\t}\n\t\t)\n\n\ttype Route = (typeof app)['~Routes']['get']['response']\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\t200: 'Hello World'\n\t\t401: 'Unauthorized'\n\t\t410: 'Gone'\n\t\t422: {\n\t\t\ttype: 'validation'\n\t\t\ton: string\n\t\t\tsummary?: string\n\t\t\tmessage?: string\n\t\t\tfound?: unknown\n\t\t\tproperty?: string\n\t\t\texpected?: string\n\t\t}\n\t}>()\n}\n\n// Macro should inject schema to guard\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tauth: {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\theaders: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\tcookie: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t401: t.Literal('Unauthorized')\n\t\t\t\t},\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random() < 0.05) return status(410)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.guard({\n\t\t\tauth: true\n\t\t})\n\t\t.get('/', ({ headers, body, cookie, params, query, status }) => {\n\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\tname: 'lilith'\n\t\t\t}>()\n\n\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\tname: 'lilith'\n\t\t\t}>()\n\n\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\tname: Cookie<'lilith'>\n\t\t\t\t}\n\t\t\t>()\n\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\tname: 'lilith'\n\t\t\t}>()\n\n\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\tname: 'lilith'\n\t\t\t}>()\n\n\t\t\tif (Math.random() > 0.5) return status(401, 'Unauthorized')\n\n\t\t\tif (Math.random() > 0.5)\n\t\t\t\t// @ts-expect-error\n\t\t\t\treturn status(401, 'Unauthorize')\n\n\t\t\treturn 'Hello World' as const\n\t\t})\n\n\tapp['~Volatile']['standaloneSchema']['response']['401']\n\ttype Route = (typeof app)['~Routes']['get']['response']\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\t200: 'Hello World'\n\t\t401: 'Unauthorized'\n\t\t410: 'Gone'\n\t\t422: {\n\t\t\ttype: 'validation'\n\t\t\ton: string\n\t\t\tsummary?: string\n\t\t\tmessage?: string\n\t\t\tfound?: unknown\n\t\t\tproperty?: string\n\t\t\texpected?: string\n\t\t}\n\t}>()\n}\n\n// Guard should extract possible status 1\n{\n\tconst app = new Elysia().guard({\n\t\tbeforeHandle({ status }) {\n\t\t\tif (Math.random() < 0.05) return status(410)\n\t\t}\n\t})\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t410: 'Gone'\n\t}>()\n}\n\n// Guard should extract possible status 2\n{\n\tconst app = new Elysia().guard({\n\t\tafterHandle({ status }) {\n\t\t\treturn status(411)\n\t\t}\n\t})\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t411: 'Length Required'\n\t}>()\n}\n\n// Guard should extract possible status 3\n{\n\tconst app = new Elysia().guard({\n\t\terror: [\n\t\t\t({ status }) => {\n\t\t\t\treturn status(412)\n\t\t\t},\n\t\t\t({ status }) => {\n\t\t\t\tif (Math.random() > 0.5) return status(413)\n\t\t\t}\n\t\t]\n\t})\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t412: 'Precondition Failed'\n\t\t413: 'Payload Too Large'\n\t}>()\n}\n\n// Guard should extract possible status 4\n{\n\tconst app = new Elysia().guard({\n\t\tbeforeHandle({ status }) {\n\t\t\tif (Math.random() < 0.05) return status(410)\n\t\t},\n\t\terror: [\n\t\t\t({ status }) => {\n\t\t\t\treturn status(412)\n\t\t\t},\n\t\t\t({ status }) => {\n\t\t\t\tif (Math.random() > 0.5) return status(413)\n\t\t\t}\n\t\t]\n\t})\n\n\texpectTypeOf<\n\t\tPrettify<(typeof app)['~Volatile']['response']>\n\t>().toEqualTypeOf<{\n\t\t410: 'Gone'\n\t\t412: 'Precondition Failed'\n\t\t413: 'Payload Too Large'\n\t}>()\n}\n\n// Guard should extract possible status 5\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tresolve() {\n\t\t\t\t\treturn { a: 'a' }\n\t\t\t\t},\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\treturn status(409)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.guard({\n\t\t\ta: true,\n\t\t\tbeforeHandle({ status }) {\n\t\t\t\tif (Math.random() < 0.05) return status(410)\n\t\t\t},\n\t\t\terror: [\n\t\t\t\t({ status }) => {\n\t\t\t\t\treturn status(412)\n\t\t\t\t},\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.5) return status(413)\n\t\t\t\t}\n\t\t\t]\n\t\t})\n\n\texpectTypeOf<\n\t\tPrettify<(typeof app)['~Volatile']['response']>\n\t>().toEqualTypeOf<{\n\t\t409: 'Conflict'\n\t\t410: 'Gone'\n\t\t412: 'Precondition Failed'\n\t\t413: 'Payload Too Large'\n\t}>()\n}\n\n// Macro should extract possible status 1\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random() < 0.05) return status(410)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.guard({\n\t\t\ta: true\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t410: 'Gone'\n\t}>()\n}\n\n// Macro should extract possible status 2\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tafterHandle({ status }) {\n\t\t\t\t\treturn status(411)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.guard({\n\t\t\ta: true\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t411: 'Length Required'\n\t}>()\n}\n\n// Macro should extract possible status 3\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\terror({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(412)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.guard({\n\t\t\ta: true\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t412: 'Precondition Failed'\n\t}>()\n}\n\n// Macro should extract possible status 4\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(410)\n\t\t\t\t},\n\t\t\t\tafterHandle({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(411)\n\t\t\t\t}\n\t\t\t},\n\t\t\tb: {\n\t\t\t\terror({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(412)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.guard({\n\t\t\ta: true,\n\t\t\tb: true\n\t\t})\n\n\texpectTypeOf<\n\t\tPrettify<(typeof app)['~Volatile']['response']>\n\t>().toEqualTypeOf<{\n\t\t410: 'Gone'\n\t\t411: 'Length Required'\n\t\t412: 'Precondition Failed'\n\t}>()\n}\n\n// Guard should cast to scoped\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(410)\n\t\t\t\t},\n\t\t\t\tafterHandle({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(411)\n\t\t\t\t}\n\t\t\t},\n\t\t\tb: {\n\t\t\t\terror({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(412)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.guard({\n\t\t\tas: 'scoped',\n\t\t\ta: true,\n\t\t\tb: true\n\t\t})\n\n\texpectTypeOf<\n\t\tPrettify<(typeof app)['~Ephemeral']['response']>\n\t>().toEqualTypeOf<{\n\t\t410: 'Gone'\n\t\t411: 'Length Required'\n\t\t412: 'Precondition Failed'\n\t}>()\n}\n\n// Guard should cast to global\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(410)\n\t\t\t\t},\n\t\t\t\tafterHandle({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(411)\n\t\t\t\t}\n\t\t\t},\n\t\t\tb: {\n\t\t\t\terror({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(412)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.guard({\n\t\t\tas: 'global',\n\t\t\ta: true,\n\t\t\tb: true\n\t\t})\n\n\texpectTypeOf<\n\t\tPrettify<(typeof app)['~Metadata']['response']>\n\t>().toEqualTypeOf<{\n\t\t410: 'Gone'\n\t\t411: 'Length Required'\n\t\t412: 'Precondition Failed'\n\t}>()\n}\n\n// Unwrap ElysiaCustomStatusResponse value in resolve macro automatically\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tauth: {\n\t\t\t\tresolve({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(401)\n\n\t\t\t\t\treturn { user: 'saltyaom' } as const\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.get('/', ({ user }) => user, {\n\t\t\tauth: true\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'saltyaom'\n\t\t401: 'Unauthorized'\n\t}>()\n}\n\n// Unwrap beforeHandle 200 status\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tauth: {\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(401)\n\n\t\t\t\t\tif (Math.random() > 0.5) return 'lilith'\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.get('/', () => 'fouco' as const, {\n\t\t\tauth: true\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'lilith' | 'fouco'\n\t\t401: 'Unauthorized'\n\t}>()\n}\n\n// Reconcile response\n{\n\tconst app = new Elysia()\n\t\t.onBeforeHandle(({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(404, 'lilith') : 'lilith'\n\t\t)\n\t\t.get('/', ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(404, 'fouco') : 'fouco'\n\t\t)\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'lilith' | 'fouco'\n\t\t404: 'lilith' | 'fouco'\n\t}>()\n}\n\n// onBeforeHandle\n{\n\tconst app = new Elysia()\n\t\t.onBeforeHandle(({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(404, 'lilith') : 'lilith'\n\t\t)\n\t\t.onBeforeHandle([\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : 'fouco',\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(418, 'sartre') : 'sartre'\n\t\t])\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t200: 'fouco' | 'sartre' | 'lilith'\n\t\t401: 'fouco'\n\t\t404: 'lilith'\n\t\t418: 'sartre'\n\t}>()\n}\n\n// onBeforeHandle scoped\n{\n\tconst app = new Elysia()\n\t\t.onBeforeHandle({ as: 'scoped' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(404, 'lilith') : 'lilith'\n\t\t)\n\t\t.onBeforeHandle({ as: 'scoped' }, [\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : 'fouco',\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(418, 'sartre') : 'sartre'\n\t\t])\n\n\texpectTypeOf<(typeof app)['~Ephemeral']['response']>().toEqualTypeOf<{\n\t\t200: 'fouco' | 'sartre' | 'lilith'\n\t\t401: 'fouco'\n\t\t404: 'lilith'\n\t\t418: 'sartre'\n\t}>()\n}\n\n// onBeforeHandle global\n{\n\tconst app = new Elysia()\n\t\t.onBeforeHandle({ as: 'global' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(404, 'lilith') : 'lilith'\n\t\t)\n\t\t.onBeforeHandle({ as: 'global' }, [\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : 'fouco',\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(418, 'sartre') : 'sartre'\n\t\t])\n\n\texpectTypeOf<(typeof app)['~Metadata']['response']>().toEqualTypeOf<{\n\t\t200: 'fouco' | 'sartre' | 'lilith'\n\t\t401: 'fouco'\n\t\t404: 'lilith'\n\t\t418: 'sartre'\n\t}>()\n}\n\n// onAfterHandle local\n{\n\tconst app = new Elysia()\n\t\t.onAfterHandle(({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(404, 'lilith') : 'lilith'\n\t\t)\n\t\t.onAfterHandle([\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : 'fouco',\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(418, 'sartre') : 'sartre'\n\t\t])\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t200: 'fouco' | 'sartre' | 'lilith'\n\t\t401: 'fouco'\n\t\t404: 'lilith'\n\t\t418: 'sartre'\n\t}>()\n}\n\n// onAfterHandle scoped\n{\n\tconst app = new Elysia()\n\t\t.onAfterHandle({ as: 'scoped' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(404, 'lilith') : 'lilith'\n\t\t)\n\t\t.onAfterHandle({ as: 'scoped' }, [\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : 'fouco',\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(418, 'sartre') : 'sartre'\n\t\t])\n\n\texpectTypeOf<(typeof app)['~Ephemeral']['response']>().toEqualTypeOf<{\n\t\t200: 'fouco' | 'sartre' | 'lilith'\n\t\t401: 'fouco'\n\t\t404: 'lilith'\n\t\t418: 'sartre'\n\t}>()\n}\n\n// onAfterHandle global\n{\n\tconst app = new Elysia()\n\t\t.onAfterHandle({ as: 'global' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(404, 'lilith') : 'lilith'\n\t\t)\n\t\t.onAfterHandle({ as: 'global' }, [\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : 'fouco',\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(418, 'sartre') : 'sartre'\n\t\t])\n\n\texpectTypeOf<(typeof app)['~Metadata']['response']>().toEqualTypeOf<{\n\t\t200: 'fouco' | 'sartre' | 'lilith'\n\t\t401: 'fouco'\n\t\t404: 'lilith'\n\t\t418: 'sartre'\n\t}>()\n}\n\n// onError local\n{\n\tconst app = new Elysia()\n\t\t.onError(({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(404, 'lilith') : 'lilith'\n\t\t)\n\t\t.onError([\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : 'fouco',\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(418, 'sartre') : 'sartre'\n\t\t])\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t200: 'fouco' | 'sartre' | 'lilith'\n\t\t401: 'fouco'\n\t\t404: 'lilith'\n\t\t418: 'sartre'\n\t}>()\n}\n\n// onError scoped\n{\n\tconst app = new Elysia()\n\t\t.onError({ as: 'scoped' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(404, 'lilith') : 'lilith'\n\t\t)\n\t\t.onError({ as: 'scoped' }, [\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : 'fouco',\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(418, 'sartre') : 'sartre'\n\t\t])\n\n\texpectTypeOf<(typeof app)['~Ephemeral']['response']>().toEqualTypeOf<{\n\t\t200: 'fouco' | 'sartre' | 'lilith'\n\t\t401: 'fouco'\n\t\t404: 'lilith'\n\t\t418: 'sartre'\n\t}>()\n}\n\n// onError global\n{\n\tconst app = new Elysia()\n\t\t.onError({ as: 'global' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(404, 'lilith') : 'lilith'\n\t\t)\n\t\t.onError({ as: 'global' }, [\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : 'fouco',\n\t\t\t({ status }) =>\n\t\t\t\tMath.random() > 0.5 ? status(418, 'sartre') : 'sartre'\n\t\t])\n\n\texpectTypeOf<(typeof app)['~Metadata']['response']>().toEqualTypeOf<{\n\t\t200: 'fouco' | 'sartre' | 'lilith'\n\t\t401: 'fouco'\n\t\t404: 'lilith'\n\t\t418: 'sartre'\n\t}>()\n}\n\n// resolve local\n{\n\tconst app = new Elysia()\n\t\t.resolve(({ status }) =>\n\t\t\tMath.random() > 0.5\n\t\t\t\t? status(401, 'sartre')\n\t\t\t\t: { friends: ['lilith'] }\n\t\t)\n\t\t.resolve(({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : { friends: ['lilith'] }\n\t\t)\n\t\t.get('/', ({ friends, status }) => {\n\t\t\tif (Math.random() > 0.5) return status(401, friends[0])\n\n\t\t\treturn 'NOexistenceN'\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Volatile']['resolve']>().toEqualTypeOf<{\n\t\treadonly friends: readonly ['lilith']\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t401: 'sartre' | 'fouco'\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'sartre' | 'fouco' | 'lilith'\n\t}>()\n}\n\n// resolve scoped\n{\n\tconst app = new Elysia()\n\t\t.resolve({ as: 'scoped' }, ({ status }) =>\n\t\t\tMath.random() > 0.5\n\t\t\t\t? status(401, 'sartre')\n\t\t\t\t: { friends: ['lilith'] }\n\t\t)\n\t\t.resolve({ as: 'scoped' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : { friends: ['lilith'] }\n\t\t)\n\t\t.get('/', ({ friends, status }) => {\n\t\t\tif (Math.random() > 0.5) return status(401, friends[0])\n\n\t\t\treturn 'NOexistenceN'\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Ephemeral']['resolve']>().toEqualTypeOf<{\n\t\treadonly friends: readonly ['lilith']\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Ephemeral']['response']>().toEqualTypeOf<{\n\t\t401: 'sartre' | 'fouco'\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'sartre' | 'fouco' | 'lilith'\n\t}>()\n}\n\n// resolve global\n{\n\tconst app = new Elysia()\n\t\t.resolve({ as: 'global' }, ({ status }) =>\n\t\t\tMath.random() > 0.5\n\t\t\t\t? status(401, 'sartre')\n\t\t\t\t: { friends: ['lilith'] }\n\t\t)\n\t\t.resolve({ as: 'global' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : { friends: ['lilith'] }\n\t\t)\n\t\t.get('/', ({ friends, status }) => {\n\t\t\tif (Math.random() > 0.5) return status(401, friends[0])\n\n\t\t\treturn 'NOexistenceN'\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Singleton']['resolve']>().toEqualTypeOf<{\n\t\treadonly friends: readonly ['lilith']\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Metadata']['response']>().toEqualTypeOf<{\n\t\t401: 'sartre' | 'fouco'\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'sartre' | 'fouco' | 'lilith'\n\t}>()\n}\n\n// mapResolve local\n{\n\tconst app = new Elysia()\n\t\t.mapResolve(({ status }) =>\n\t\t\tMath.random() > 0.5\n\t\t\t\t? status(401, 'sartre')\n\t\t\t\t: { friends: ['lilith'] }\n\t\t)\n\t\t.mapResolve(({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : { friends: ['lilith'] }\n\t\t)\n\t\t.get('/', ({ friends, status }) => {\n\t\t\tif (Math.random() > 0.5) return status(401, friends[0])\n\n\t\t\treturn 'NOexistenceN'\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Volatile']['resolve']>().toEqualTypeOf<{\n\t\treadonly friends: readonly ['lilith']\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t401: 'sartre' | 'fouco'\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'sartre' | 'fouco' | 'lilith'\n\t}>()\n}\n\n// mapResolve scoped\n{\n\tconst app = new Elysia()\n\t\t.mapResolve({ as: 'scoped' }, ({ status }) =>\n\t\t\tMath.random() > 0.5\n\t\t\t\t? status(401, 'sartre')\n\t\t\t\t: { friends: ['lilith'] }\n\t\t)\n\t\t.mapResolve({ as: 'scoped' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : { friends: ['lilith'] }\n\t\t)\n\t\t.get('/', ({ friends, status }) => {\n\t\t\tif (Math.random() > 0.5) return status(401, friends[0])\n\n\t\t\treturn 'NOexistenceN'\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Ephemeral']['resolve']>().toEqualTypeOf<{\n\t\treadonly friends: readonly ['lilith']\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Ephemeral']['response']>().toEqualTypeOf<{\n\t\t401: 'sartre' | 'fouco'\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'sartre' | 'fouco' | 'lilith'\n\t}>()\n}\n\n// mapResolve global\n{\n\tconst app = new Elysia()\n\t\t.mapResolve({ as: 'global' }, ({ status }) =>\n\t\t\tMath.random() > 0.5\n\t\t\t\t? status(401, 'sartre')\n\t\t\t\t: { friends: ['lilith'] }\n\t\t)\n\t\t.mapResolve({ as: 'global' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : { friends: ['lilith'] }\n\t\t)\n\t\t.get('/', ({ friends, status }) => {\n\t\t\tif (Math.random() > 0.5) return status(401, friends[0])\n\n\t\t\treturn 'NOexistenceN'\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Singleton']['resolve']>().toEqualTypeOf<{\n\t\treadonly friends: readonly ['lilith']\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Metadata']['response']>().toEqualTypeOf<{\n\t\t401: 'sartre' | 'fouco'\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'sartre' | 'fouco' | 'lilith'\n\t}>()\n}\n\n// derive local\n{\n\tconst app = new Elysia()\n\t\t.derive(({ status }) =>\n\t\t\tMath.random() > 0.5\n\t\t\t\t? status(401, 'sartre')\n\t\t\t\t: { friends: ['lilith'] }\n\t\t)\n\t\t.derive(({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : { friends: ['lilith'] }\n\t\t)\n\t\t.get('/', ({ friends, status }) => {\n\t\t\tif (Math.random() > 0.5) return status(401, friends[0])\n\n\t\t\treturn 'NOexistenceN'\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Volatile']['derive']>().toEqualTypeOf<{\n\t\treadonly friends: readonly ['lilith']\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t401: 'sartre' | 'fouco'\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'sartre' | 'fouco' | 'lilith'\n\t}>()\n}\n\n// derive scoped\n{\n\tconst app = new Elysia()\n\t\t.derive({ as: 'scoped' }, ({ status }) =>\n\t\t\tMath.random() > 0.5\n\t\t\t\t? status(401, 'sartre')\n\t\t\t\t: { friends: ['lilith'] }\n\t\t)\n\t\t.derive({ as: 'scoped' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : { friends: ['lilith'] }\n\t\t)\n\t\t.get('/', ({ friends, status }) => {\n\t\t\tif (Math.random() > 0.5) return status(401, friends[0])\n\n\t\t\treturn 'NOexistenceN'\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Ephemeral']['derive']>().toEqualTypeOf<{\n\t\treadonly friends: readonly ['lilith']\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Ephemeral']['response']>().toEqualTypeOf<{\n\t\t401: 'sartre' | 'fouco'\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'sartre' | 'fouco' | 'lilith'\n\t}>()\n}\n\n// derive global\n{\n\tconst app = new Elysia()\n\t\t.derive({ as: 'global' }, ({ status }) =>\n\t\t\tMath.random() > 0.5\n\t\t\t\t? status(401, 'sartre')\n\t\t\t\t: { friends: ['lilith'] }\n\t\t)\n\t\t.derive({ as: 'global' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : { friends: ['lilith'] }\n\t\t)\n\t\t.get('/', ({ friends, status }) => {\n\t\t\tif (Math.random() > 0.5) return status(401, friends[0])\n\n\t\t\treturn 'NOexistenceN'\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Singleton']['derive']>().toEqualTypeOf<{\n\t\treadonly friends: readonly ['lilith']\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Metadata']['response']>().toEqualTypeOf<{\n\t\t401: 'sartre' | 'fouco'\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'sartre' | 'fouco' | 'lilith'\n\t}>()\n}\n\n// mapDerive local\n{\n\tconst app = new Elysia()\n\t\t.mapDerive(({ status }) =>\n\t\t\tMath.random() > 0.5\n\t\t\t\t? status(401, 'sartre')\n\t\t\t\t: { friends: ['lilith'] }\n\t\t)\n\t\t.mapDerive(({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : { friends: ['lilith'] }\n\t\t)\n\t\t.get('/', ({ friends, status }) => {\n\t\t\tif (Math.random() > 0.5) return status(401, friends[0])\n\n\t\t\treturn 'NOexistenceN'\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Volatile']['derive']>().toEqualTypeOf<{\n\t\treadonly friends: readonly ['lilith']\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t401: 'sartre' | 'fouco'\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'sartre' | 'fouco' | 'lilith'\n\t}>()\n}\n\n// mapDerive scoped\n{\n\tconst app = new Elysia()\n\t\t.mapDerive({ as: 'scoped' }, ({ status }) =>\n\t\t\tMath.random() > 0.5\n\t\t\t\t? status(401, 'sartre')\n\t\t\t\t: { friends: ['lilith'] }\n\t\t)\n\t\t.mapDerive({ as: 'scoped' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : { friends: ['lilith'] }\n\t\t)\n\t\t.get('/', ({ friends, status }) => {\n\t\t\tif (Math.random() > 0.5) return status(401, friends[0])\n\n\t\t\treturn 'NOexistenceN'\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Ephemeral']['derive']>().toEqualTypeOf<{\n\t\treadonly friends: readonly ['lilith']\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Ephemeral']['response']>().toEqualTypeOf<{\n\t\t401: 'sartre' | 'fouco'\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'sartre' | 'fouco' | 'lilith'\n\t}>()\n}\n\n// mapDerive global\n{\n\tconst app = new Elysia()\n\t\t.mapDerive({ as: 'global' }, ({ status }) =>\n\t\t\tMath.random() > 0.5\n\t\t\t\t? status(401, 'sartre')\n\t\t\t\t: { friends: ['lilith'] }\n\t\t)\n\t\t.mapDerive({ as: 'global' }, ({ status }) =>\n\t\t\tMath.random() > 0.5 ? status(401, 'fouco') : { friends: ['lilith'] }\n\t\t)\n\t\t.get('/', ({ friends, status }) => {\n\t\t\tif (Math.random() > 0.5) return status(401, friends[0])\n\n\t\t\treturn 'NOexistenceN'\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Singleton']['derive']>().toEqualTypeOf<{\n\t\treadonly friends: readonly ['lilith']\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Metadata']['response']>().toEqualTypeOf<{\n\t\t401: 'sartre' | 'fouco'\n\t}>()\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'sartre' | 'fouco' | 'lilith'\n\t}>()\n}\n\n// Guard local\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tq: {\n\t\t\t\tbeforeHandle: [\n\t\t\t\t\t({ status }) => {\n\t\t\t\t\t\tif (Math.random() > 0.05) return status(401)\n\t\t\t\t\t},\n\t\t\t\t\t({ status }) => {\n\t\t\t\t\t\tif (Math.random() > 0.05) return status(402)\n\t\t\t\t\t}\n\t\t\t\t],\n\t\t\t\tafterHandle({ status }) {\n\t\t\t\t\tif (Math.random() > 0.05) return status(403)\n\t\t\t\t},\n\t\t\t\terror({ status }) {\n\t\t\t\t\tif (Math.random() > 0.05) return status(404, 'lilith')\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.guard({\n\t\t\tq: true,\n\t\t\tbeforeHandle: [\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(405)\n\t\t\t\t},\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(406)\n\t\t\t\t}\n\t\t\t],\n\t\t\tafterHandle({ status }) {\n\t\t\t\tif (Math.random() > 0.05) return status(407)\n\t\t\t},\n\t\t\terror({ status }) {\n\t\t\t\tif (Math.random() > 0.05) return status(408)\n\t\t\t}\n\t\t})\n\t\t.get('/', () => 'NOexistenceN' as const)\n\n\texpectTypeOf<\n\t\tPrettify<(typeof app)['~Volatile']['response']>\n\t>().toEqualTypeOf<{\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t404: 'lilith'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t}>()\n\n\texpectTypeOf<\n\t\tPrettify<(typeof app)['~Routes']['get']['response']>\n\t>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t404: 'lilith'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t}>()\n}\n\n// Guard scoped\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tq: {\n\t\t\t\tbeforeHandle: [\n\t\t\t\t\t({ status }) => {\n\t\t\t\t\t\tif (Math.random() > 0.05) return status(401)\n\t\t\t\t\t},\n\t\t\t\t\t({ status }) => {\n\t\t\t\t\t\tif (Math.random() > 0.05) return status(402)\n\t\t\t\t\t}\n\t\t\t\t],\n\t\t\t\tafterHandle({ status }) {\n\t\t\t\t\tif (Math.random() > 0.05) return status(403)\n\t\t\t\t},\n\t\t\t\terror({ status }) {\n\t\t\t\t\tif (Math.random() > 0.05) return status(404, 'lilith')\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.guard({\n\t\t\tas: 'scoped',\n\t\t\tq: true,\n\t\t\tbeforeHandle: [\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(405)\n\t\t\t\t},\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(406)\n\t\t\t\t}\n\t\t\t],\n\t\t\tafterHandle({ status }) {\n\t\t\t\tif (Math.random() > 0.05) return status(407)\n\t\t\t},\n\t\t\terror({ status }) {\n\t\t\t\tif (Math.random() > 0.05) return status(408)\n\t\t\t}\n\t\t})\n\t\t.get('/', () => 'NOexistenceN' as const)\n\n\texpectTypeOf<\n\t\tPrettify<(typeof app)['~Ephemeral']['response']>\n\t>().toEqualTypeOf<{\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t404: 'lilith'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t}>()\n\n\ttype A = keyof (typeof app)['~Routes']['get']['response']\n\n\texpectTypeOf<\n\t\tPrettify<(typeof app)['~Routes']['get']['response']>\n\t>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t404: 'lilith'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t}>()\n}\n\n// Guard global\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tq: {\n\t\t\t\tbeforeHandle: [\n\t\t\t\t\t({ status }) => {\n\t\t\t\t\t\tif (Math.random() > 0.05) return status(401)\n\t\t\t\t\t},\n\t\t\t\t\t({ status }) => {\n\t\t\t\t\t\tif (Math.random() > 0.05) return status(402)\n\t\t\t\t\t}\n\t\t\t\t],\n\t\t\t\tafterHandle({ status }) {\n\t\t\t\t\tif (Math.random() > 0.05) return status(403)\n\t\t\t\t},\n\t\t\t\terror({ status }) {\n\t\t\t\t\tif (Math.random() > 0.05) return status(404, 'lilith')\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.guard({\n\t\t\tas: 'global',\n\t\t\tq: true,\n\t\t\tbeforeHandle: [\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(405)\n\t\t\t\t},\n\t\t\t\t({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(406)\n\t\t\t\t}\n\t\t\t],\n\t\t\tafterHandle({ status }) {\n\t\t\t\tif (Math.random() > 0.05) return status(407)\n\t\t\t},\n\t\t\terror({ status }) {\n\t\t\t\tif (Math.random() > 0.05) return status(408)\n\t\t\t}\n\t\t})\n\t\t.get('/', () => 'NOexistenceN' as const)\n\n\texpectTypeOf<\n\t\tPrettify<(typeof app)['~Metadata']['response']>\n\t>().toEqualTypeOf<{\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t404: 'lilith'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t}>()\n\n\ttype A = keyof (typeof app)['~Routes']['get']['response']\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t404: 'lilith'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t}>()\n}\n\n// Multiple macro\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tq: {\n\t\t\t\tbeforeHandle: [\n\t\t\t\t\t({ status }) => {\n\t\t\t\t\t\tif (Math.random() > 0.05) return status(401)\n\t\t\t\t\t},\n\t\t\t\t\t({ status }) => {\n\t\t\t\t\t\tif (Math.random() > 0.05) return status(402)\n\t\t\t\t\t}\n\t\t\t\t],\n\t\t\t\tafterHandle({ status }) {\n\t\t\t\t\tif (Math.random() > 0.05) return status(403)\n\t\t\t\t},\n\t\t\t\terror({ status }) {\n\t\t\t\t\tif (Math.random() > 0.05) return status(404, 'lilith')\n\t\t\t\t}\n\t\t\t},\n\t\t\ta: {\n\t\t\t\tbeforeHandle: ({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.05) return status(405)\n\t\t\t\t},\n\t\t\t\tafterHandle: [\n\t\t\t\t\t({ status }) => {\n\t\t\t\t\t\tif (Math.random() > 0.05) return status(406)\n\t\t\t\t\t},\n\t\t\t\t\t({ status }) => {\n\t\t\t\t\t\tif (Math.random() > 0.05) return status(407)\n\t\t\t\t\t}\n\t\t\t\t],\n\t\t\t\terror({ status }) {\n\t\t\t\t\tif (Math.random() > 0.05) return status(408)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\t.guard({\n\t\t\tq: true,\n\t\t\ta: true\n\t\t})\n\t\t.get('/', () => 'NOexistenceN' as const)\n\n\texpectTypeOf<\n\t\tPrettify<(typeof app)['~Volatile']['response']>\n\t>().toEqualTypeOf<{\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t404: 'lilith'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t}>()\n\n\ttype A = keyof (typeof app)['~Routes']['get']['response']\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'NOexistenceN'\n\t\t401: 'Unauthorized'\n\t\t402: 'Payment Required'\n\t\t403: 'Forbidden'\n\t\t404: 'lilith'\n\t\t405: 'Method Not Allowed'\n\t\t406: 'Not Acceptable'\n\t\t407: 'Proxy Authentication Required'\n\t\t408: 'Request Timeout'\n\t}>()\n}\n\n// merge possible path\n{\n\tconst app = new Elysia()\n\t\t.onBeforeHandle(({ status }) => {\n\t\t\tif (Math.random() > 0.05) return 'fouco' as const\n\t\t\tif (Math.random() > 0.05) return 'sartre' as const\n\t\t\tif (Math.random() > 0.05) return status(404, 'lilith')\n\t\t})\n\t\t.get('/', () => 'lilith' as const)\n\n\texpectTypeOf<(typeof app)['~Volatile']['response']>().toEqualTypeOf<{\n\t\t200: 'fouco' | 'sartre'\n\t\t404: 'lilith'\n\t}>\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: 'fouco' | 'sartre' | 'lilith'\n\t\t404: 'lilith'\n\t}>()\n}\n\n// Macro Context should add to output declaration\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\tcookie: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\theaders: t.Object({\n\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t403: t.Object({\n\t\t\t\t\t\tname: t.Literal('lilith')\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.post('/', ({ body }) => 'b' as const, {\n\t\t\ta: true,\n\t\t\tbeforeHandle({ body }) {\n\t\t\t\texpectTypeOf(body).toEqualTypeOf<{\n\t\t\t\t\tname: 'lilith'\n\t\t\t\t}>()\n\t\t\t}\n\t\t})\n\n\texpectTypeOf<(typeof app)['~Routes']['post']>().toEqualTypeOf<{\n\t\tbody: {\n\t\t\tname: 'lilith'\n\t\t}\n\t\tparams: {\n\t\t\tname: 'lilith'\n\t\t}\n\t\tquery: {\n\t\t\tname: 'lilith'\n\t\t}\n\t\theaders: {\n\t\t\tname: 'lilith'\n\t\t}\n\t\tresponse: {\n\t\t\t200: 'b'\n\t\t\t403: {\n\t\t\t\tname: 'lilith'\n\t\t\t}\n\t\t\t422: {\n\t\t\t\ttype: 'validation'\n\t\t\t\ton: string\n\t\t\t\tsummary?: string\n\t\t\t\tmessage?: string\n\t\t\t\tfound?: unknown\n\t\t\t\tproperty?: string\n\t\t\t\texpected?: string\n\t\t\t}\n\t\t}\n\t}>()\n}\n\n// Macro Context schema and inline schema works together even in inline lifecycle\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\twithFriends: {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tfriends: t.Tuple([t.Literal('Sartre'), t.Literal('Fouco')])\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t\t.post(\n\t\t\t'/',\n\t\t\t({ body }) => {\n\t\t\t\texpectTypeOf(body).toEqualTypeOf<{\n\t\t\t\t\tname: 'Lilith'\n\t\t\t\t\tfriends: ['Sartre', 'Fouco']\n\t\t\t\t}>()\n\n\t\t\t\treturn body\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.Literal('Lilith')\n\t\t\t\t}),\n\t\t\t\twithFriends: true,\n\t\t\t\tresponse: {\n\t\t\t\t\t418: t.Literal('Teapot')\n\t\t\t\t},\n\t\t\t\tbeforeHandle({ body }) {\n\t\t\t\t\texpectTypeOf(body).toEqualTypeOf<{\n\t\t\t\t\t\tname: 'Lilith'\n\t\t\t\t\t\tfriends: ['Sartre', 'Fouco']\n\t\t\t\t\t}>()\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\texpectTypeOf<(typeof app)['~Routes']['post']>().toEqualTypeOf<{\n\t\tbody: {\n\t\t\tname: 'Lilith'\n\t\t\tfriends: ['Sartre', 'Fouco']\n\t\t}\n\t\tparams: {}\n\t\tquery: {}\n\t\theaders: {}\n\t\tresponse: {\n\t\t\t200: {\n\t\t\t\tname: 'Lilith'\n\t\t\t\tfriends: ['Sartre', 'Fouco']\n\t\t\t}\n\t\t\t418: 'Teapot'\n\t\t\t422: {\n\t\t\t\ttype: 'validation'\n\t\t\t\ton: string\n\t\t\t\tsummary?: string\n\t\t\t\tmessage?: string\n\t\t\t\tfound?: unknown\n\t\t\t\tproperty?: string\n\t\t\t\texpected?: string\n\t\t\t}\n\t\t}\n\t}>()\n}\n\n// resolve for lifecycle event\n{\n\tnew Elysia()\n\t\t.macro('auth', {\n\t\t\theaders: t.Object({ authorization: t.String() }),\n\t\t\tresolve: ({ status }) =>\n\t\t\t\tMath.random() > 0.5\n\t\t\t\t\t? { role: 'user' }\n\t\t\t\t\t: status(401, 'not authorized')\n\t\t})\n\t\t.post('/', ({ role }) => role, {\n\t\t\tauth: true,\n\t\t\tbeforeHandle: ({ role }) => {}\n\t\t})\n}\n\n// handle macro with arguments\n{\n\tnew Elysia()\n\t\t.macro({\n\t\t\trole: (role: 'user' | 'admin') => ({\n\t\t\t\tresolve({ status, headers: { authorization } }) {\n\t\t\t\t\tconst user = {\n\t\t\t\t\t\trole: Math.random() > 0.5 ? 'user' : 'admin'\n\t\t\t\t\t} as {\n\t\t\t\t\t\trole: 'user' | 'admin'\n\t\t\t\t\t}\n\n\t\t\t\t\tif (user.role !== role) return status(401)\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tuser\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t\t.get(\n\t\t\t'/token',\n\t\t\t({ user }) => {\n\t\t\t\texpectTypeOf(user).toEqualTypeOf<{ role: 'admin' | 'user' }>()\n\t\t\t},\n\t\t\t{\n\t\t\t\trole: 'admin'\n\t\t\t}\n\t\t)\n}\n\n// Get schema in GET\n{\n\tnew Elysia()\n\t\t.guard({\n\t\t\tschema: 'standalone',\n\t\t\tbody: t.Object({\n\t\t\t\tid: t.Number()\n\t\t\t})\n\t\t})\n\t\t.get('/user/:id', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.Literal('lilith')\n\t\t\t})\n\t\t})\n}\n\n// Merge multiple guard schema\n{\n\tconst app = new Elysia().guard(\n\t\t{\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.Literal('lilith')\n\t\t\t}),\n\t\t\tbeforeHandle({ status }) {\n\t\t\t\tif (Math.random() > 0.5) return status(401)\n\t\t\t}\n\t\t},\n\t\t(app) =>\n\t\t\tapp.guard(\n\t\t\t\t{\n\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\tlimit: t.Number()\n\t\t\t\t\t}),\n\t\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\t\tif (Math.random() > 0.5) return status(400)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t(app) =>\n\t\t\t\t\tapp.get(\n\t\t\t\t\t\t'/',\n\t\t\t\t\t\t({ query }) => {\n\t\t\t\t\t\t\texpectTypeOf(query).toEqualTypeOf<{\n\t\t\t\t\t\t\t\tplaying: boolean\n\t\t\t\t\t\t\t\tname: 'lilith'\n\t\t\t\t\t\t\t\tlimit: number\n\t\t\t\t\t\t\t}>()\n\n\t\t\t\t\t\t\treturn query\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\t\t\tplaying: t.Boolean()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t)\n\t)\n}\n\n// Merge multiple group schema\n{\n\tconst app = new Elysia().guard(\n\t\t{\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.Literal('lilith')\n\t\t\t}),\n\t\t\tbeforeHandle({ status }) {\n\t\t\t\tif (Math.random() > 0.5) return status(401)\n\t\t\t}\n\t\t},\n\t\t(app) =>\n\t\t\tapp.guard(\n\t\t\t\t{\n\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\tlimit: t.Number()\n\t\t\t\t\t}),\n\t\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\t\tif (Math.random() > 0.5) return status(400)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t(app) =>\n\t\t\t\t\tapp.get(\n\t\t\t\t\t\t'/',\n\t\t\t\t\t\t({ query }) => {\n\t\t\t\t\t\t\texpectTypeOf(query).toEqualTypeOf<{\n\t\t\t\t\t\t\t\tplaying: boolean\n\t\t\t\t\t\t\t\tname: 'lilith'\n\t\t\t\t\t\t\t\tlimit: number\n\t\t\t\t\t\t\t}>()\n\n\t\t\t\t\t\t\treturn query\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\t\t\tplaying: t.Boolean()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t)\n\t)\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: {\n\t\t\tplaying: boolean\n\t\t\tname: 'lilith'\n\t\t\tlimit: number\n\t\t}\n\t\t400: 'Bad Request'\n\t\t401: 'Unauthorized'\n\t\t422: {\n\t\t\ttype: 'validation'\n\t\t\ton: string\n\t\t\tsummary?: string\n\t\t\tmessage?: string\n\t\t\tfound?: unknown\n\t\t\tproperty?: string\n\t\t\texpected?: string\n\t\t}\n\t}>()\n}\n\n{\n\tconst app = new Elysia().guard(\n\t\t{\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.Literal('lilith')\n\t\t\t}),\n\t\t\tbeforeHandle({ status }) {\n\t\t\t\tif (Math.random() > 0.5) return status(401)\n\t\t\t}\n\t\t},\n\t\t(app) =>\n\t\t\tapp.guard(\n\t\t\t\t{\n\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\tlimit: t.Number()\n\t\t\t\t\t}),\n\t\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\t\tif (Math.random() > 0.5) return status(400)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t(app) =>\n\t\t\t\t\tapp.get(\n\t\t\t\t\t\t'/',\n\t\t\t\t\t\t({ query }) => {\n\t\t\t\t\t\t\texpectTypeOf(query).toEqualTypeOf<{\n\t\t\t\t\t\t\t\tplaying: boolean\n\t\t\t\t\t\t\t\tname: 'lilith'\n\t\t\t\t\t\t\t\tlimit: number\n\t\t\t\t\t\t\t}>()\n\n\t\t\t\t\t\t\treturn query\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tquery: t.Object({\n\t\t\t\t\t\t\t\tplaying: t.Boolean()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t)\n\t)\n\n\texpectTypeOf<(typeof app)['~Routes']['get']['response']>().toEqualTypeOf<{\n\t\t200: {\n\t\t\tplaying: boolean\n\t\t\tname: 'lilith'\n\t\t\tlimit: number\n\t\t}\n\t\t400: 'Bad Request'\n\t\t401: 'Unauthorized'\n\t\t422: {\n\t\t\ttype: 'validation'\n\t\t\ton: string\n\t\t\tsummary?: string\n\t\t\tmessage?: string\n\t\t\tfound?: unknown\n\t\t\tproperty?: string\n\t\t\texpected?: string\n\t\t}\n\t}>()\n}\n\n// Inherit macro context\n{\n\tnew Elysia()\n\t\t.macro('guestOrUser', {\n\t\t\tresolve: () => {\n\t\t\t\treturn {\n\t\t\t\t\tuser: 'Lilith' as const\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.macro('user', {\n\t\t\tguestOrUser: true,\n\t\t\tbody: t.String(),\n\t\t\tresolve: ({ user }) => {\n\t\t\t\texpectTypeOf(user).toEqualTypeOf<'Lilith'>()\n\t\t\t}\n\t\t})\n}\n\n// Handle 200 status for inline status\n{\n\tnew Elysia().get(\n\t\t'/test',\n\t\t({ status }) => {\n\t\t\tif (Math.random() > 0.1)\n\t\t\t\treturn status(200, {\n\t\t\t\t\tkey: 1,\n\t\t\t\t\tid: 1\n\t\t\t\t})\n\n\t\t\tif (Math.random() > 0.1)\n\t\t\t\treturn status(200, {\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tkey: 'a',\n\t\t\t\t\tid: 1\n\t\t\t\t})\n\n\t\t\treturn status(200, { key2: 's', id: 2 })\n\t\t},\n\t\t{\n\t\t\tresponse: {\n\t\t\t\t200: t.Union([\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tkey2: t.String(),\n\t\t\t\t\t\tid: t.Literal(2)\n\t\t\t\t\t}),\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tkey: t.Number(),\n\t\t\t\t\t\tid: t.Literal(1)\n\t\t\t\t\t})\n\t\t\t\t])\n\t\t\t}\n\t\t}\n\t)\n}\n\n// coerce union status value and return type\n{\n\tnew Elysia().get(\n\t\t'/test',\n\t\t({ status }) => {\n\t\t\treturn status(200, { key2: 's', id: 2 })\n\t\t},\n\t\t{\n\t\t\tresponse: {\n\t\t\t\t200: t.Union([\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tkey2: t.String(),\n\t\t\t\t\t\tid: t.Literal(2)\n\t\t\t\t\t}),\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tkey: t.Number(),\n\t\t\t\t\t\tid: t.Literal(1)\n\t\t\t\t\t})\n\t\t\t\t])\n\t\t\t}\n\t\t}\n\t)\n}\n\n// Macro should inherit schema type\n{\n\tnew Elysia({ name: 'my-middleware-1' })\n\t\t.guard({\n\t\t\tas: 'scoped',\n\t\t\theaders: t.Object({\n\t\t\t\trole: t.UnionEnum(['admin', 'user'])\n\t\t\t}),\n\t\t\tbody: t.Object({\n\t\t\t\tfoo: t.String()\n\t\t\t})\n\t\t})\n\t\t.macro({\n\t\t\tauth: {\n\t\t\t\tresolve: ({ headers, body }) => {\n\t\t\t\t\texpectTypeOf(headers).toEqualTypeOf<{\n\t\t\t\t\t\trole: 'admin' | 'user'\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf(body).toEqualTypeOf<{\n\t\t\t\t\t\tfoo: string\n\t\t\t\t\t}>()\n\t\t\t\t}\n\t\t\t}\n\t\t})\n}\n\n// intersect multiple resolve macro response\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tmultiple: {\n\t\t\t\tresolve({ status }) {\n\t\t\t\t\tif (Math.random() > 0.5) return status(401)\n\t\t\t\t\treturn status(403)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.get('/multiple', () => 'Ok', { multiple: true })\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['multiple']['get']['response']\n\t>().toEqualTypeOf<{\n\t\t200: string\n\t\t401: 'Unauthorized'\n\t\t403: 'Forbidden'\n\t}>()\n}\n\n// intersect multiple resolve macro response\n{\n\tconst app = new Elysia()\n\t\t.macro('multiple', {\n\t\t\tresolve({ status }) {\n\t\t\t\tif (Math.random() > 0.5) return status(401)\n\t\t\t\treturn status(403)\n\t\t\t}\n\t\t})\n\t\t.get('/multiple', () => 'Ok', { multiple: true })\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['multiple']['get']['response']\n\t>().toEqualTypeOf<{\n\t\t200: string\n\t\t401: 'Unauthorized'\n\t\t403: 'Forbidden'\n\t}>()\n}\n\n// intersect multiple resolve macro response\n{\n\tconst app = new Elysia()\n\t\t.macro('multiple', {\n\t\t\tresolve({ status }) {\n\t\t\t\tif (Math.random() > 0.5) return status(401)\n\n\t\t\t\treturn status(403)\n\t\t\t}\n\t\t})\n\t\t.get('/multiple', () => 'Ok', { multiple: true })\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['multiple']['get']['response']\n\t>().toEqualTypeOf<{\n\t\t200: string\n\t\t401: 'Unauthorized'\n\t\t403: 'Forbidden'\n\t}>()\n\n\texpectTypeOf<\n\t\t(typeof app)['~Routes']['multiple']['get']['response']\n\t>().toEqualTypeOf<{\n\t\t200: string\n\t\t401: 'Unauthorized'\n\t\t403: 'Forbidden'\n\t}>()\n}\n\n// Macro with conflict value per status\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random()) return status(400, 'a')\n\t\t\t\t\tif (Math.random()) return status(401, 'a')\n\n\t\t\t\t\treturn 'a'\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.get('/', () => 'ok', {\n\t\t\ta: true\n\t\t})\n\n\ttype Route = (typeof app)['~Routes']['get']['response']\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\t200: string\n\t\t400: 'a'\n\t\t401: 'a'\n\t}>\n}\n\n// Recursive macro with conflict value per status\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random()) return status(400, 'a')\n\t\t\t\t\tif (Math.random()) return status(401, 'a')\n\n\t\t\t\t\treturn 'before handler' as const\n\t\t\t\t}\n\t\t\t},\n\t\t\tb: {\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random()) return status(401, 'b')\n\t\t\t\t},\n\t\t\t\ta: true\n\t\t\t}\n\t\t})\n\t\t.get('/', () => 'handler' as const, {\n\t\t\tb: true\n\t\t})\n\n\ttype Routes = (typeof app)['~Routes']['get']['response']\n\n\texpectTypeOf<Routes>().toEqualTypeOf<{\n\t\t200: 'before handler' | 'handler'\n\t\t400: 'a'\n\t\t401: 'a' | 'b'\n\t}>\n}\n\n// Recursive macro with conflict value per status\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tresolve({ status }) {\n\t\t\t\t\tif (Math.random()) return status(400, 'a')\n\t\t\t\t\tif (Math.random()) return status(401, 'b')\n\t\t\t\t\tif (Math.random()) return status(401, 'c')\n\n\t\t\t\t\treturn { a: 'a' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tb: {\n\t\t\t\tresolve({ status }) {\n\t\t\t\t\tif (Math.random()) return status(400, 'x')\n\t\t\t\t\tif (Math.random()) return status(401, 'y')\n\t\t\t\t\tif (Math.random()) return status(401, 'z')\n\n\t\t\t\t\treturn { b: 'b' }\n\t\t\t\t},\n\t\t\t\ta: true\n\t\t\t}\n\t\t})\n\t\t.get('/', () => 'handler' as const, {\n\t\t\tb: true\n\t\t})\n\n\ttype Routes = (typeof app)['~Routes']['get']['response']\n\n\texpectTypeOf<Routes>().toEqualTypeOf<{\n\t\t200: 'handler'\n\t\t400: 'a' | 'x'\n\t\t401: 'b' | 'c' | 'y' | 'z'\n\t}>\n}\n\n// Separate Box from literal status-like response in macro\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\ta: {\n\t\t\t\tbeforeHandle({ status }) {\n\t\t\t\t\tif (Math.random()) return status(400, 'a')\n\t\t\t\t\tif (Math.random()) return status(401, 'a')\n\t\t\t\t\tif (Math.random()) return status(401, 'b')\n\t\t\t\t\tif (Math.random()) return status(402)\n\n\t\t\t\t\tif (Math.random())\n\t\t\t\t\t\t// Test status-like response but literal not box\n\t\t\t\t\t\treturn { status: 401, response: 'c' } as const\n\n\t\t\t\t\treturn 'a'\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.get('/', () => 'ok', {\n\t\t\ta: true\n\t\t})\n\n\ttype Route = (typeof app)['~Routes']['get']['response']\n\n\texpectTypeOf<Route>().toEqualTypeOf<{\n\t\t200: string | { readonly status: 401; readonly response: 'c' }\n\t\t400: 'a'\n\t\t401: 'a' | 'b'\n\t\t402: 'Payment Required'\n\t}>\n}\n"
  },
  {
    "path": "test/types/macro.ts",
    "content": "import { Elysia, t } from '../../src'\nimport { expectTypeOf } from 'expect-type'\n\n// guard handle resolve macro\n{\n\tconst plugin = new Elysia()\n\t\t.macro({\n\t\t\taccount: (a: boolean) => ({\n\t\t\t\tresolve: () => ({\n\t\t\t\t\taccount: 'A'\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t\t.guard({\n\t\t\taccount: true\n\t\t})\n\t\t.get('/', ({ account }) => {\n\t\t\texpectTypeOf(account).toEqualTypeOf<string>()\n\t\t})\n\n\tconst parent = new Elysia().use(plugin).get('/', (context) => {\n\t\texpectTypeOf(context).not.toHaveProperty('account')\n\t})\n\n\tconst app = new Elysia().use(parent).get('/', (context) => {\n\t\texpectTypeOf(context).not.toHaveProperty('account')\n\t})\n}\n\n// guard handle resolve macro with scoped\n{\n\tconst plugin = new Elysia()\n\t\t.macro({\n\t\t\taccount: (a: boolean) => ({\n\t\t\t\tresolve: () => ({\n\t\t\t\t\taccount: 'A'\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t\t.guard({\n\t\t\tas: 'scoped',\n\t\t\taccount: true\n\t\t})\n\t\t.get('/', ({ account }) => {\n\t\t\texpectTypeOf(account).toEqualTypeOf<string>()\n\t\t})\n\n\tconst parent = new Elysia().use(plugin).get('/', (context) => {\n\t\texpectTypeOf(context).toHaveProperty('account')\n\t\texpectTypeOf(context.account).toEqualTypeOf<string>()\n\t})\n\n\tconst app = new Elysia().use(parent).get('/', (context) => {\n\t\texpectTypeOf(context).not.toHaveProperty('account')\n\t})\n}\n\n// guard handle resolve macro with global\n{\n\tconst plugin = new Elysia()\n\t\t.macro({\n\t\t\taccount: (a: boolean) => ({\n\t\t\t\tresolve: () => ({\n\t\t\t\t\taccount: 'A'\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t\t.guard({\n\t\t\tas: 'global',\n\t\t\taccount: true\n\t\t})\n\t\t.get('/', ({ account }) => {\n\t\t\texpectTypeOf(account).toEqualTypeOf<string>()\n\t\t})\n\n\tconst parent = new Elysia().use(plugin).get('/', (context) => {\n\t\texpectTypeOf(context).toHaveProperty('account')\n\t\texpectTypeOf(context.account).toEqualTypeOf<string>()\n\t})\n\n\tconst app = new Elysia().use(parent).get('/', (context) => {\n\t\texpectTypeOf(context).toHaveProperty('account')\n\t\texpectTypeOf(context.account).toEqualTypeOf<string>()\n\t})\n}\n\n// guard handle resolve macro with local\n{\n\tconst plugin = new Elysia()\n\t\t.macro({\n\t\t\taccount: (a: boolean) => ({\n\t\t\t\tresolve: () => ({\n\t\t\t\t\taccount: 'A'\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t\t.guard({\n\t\t\tas: 'local',\n\t\t\taccount: true\n\t\t})\n\t\t.get('/', ({ account }) => {\n\t\t\texpectTypeOf(account).toEqualTypeOf<string>()\n\t\t})\n\n\tconst parent = new Elysia().use(plugin).get('/', (context) => {\n\t\texpectTypeOf(context).not.toHaveProperty('account')\n\t})\n\n\tconst app = new Elysia().use(parent).get('/', (context) => {\n\t\texpectTypeOf(context).not.toHaveProperty('account')\n\t})\n}\n\n// guard handle resolve macro with error\n{\n\tconst plugin = new Elysia()\n\t\t.macro({\n\t\t\taccount: (a: boolean) => ({\n\t\t\t\tresolve: ({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.5) return status(401)\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\taccount: 'A'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t\t.guard({\n\t\t\taccount: true\n\t\t})\n\t\t.get('/', ({ account }) => {\n\t\t\texpectTypeOf(account).toEqualTypeOf<string>()\n\t\t})\n\n\tconst parent = new Elysia().use(plugin).get('/', (context) => {\n\t\texpectTypeOf(context).not.toHaveProperty('account')\n\t})\n\n\tconst app = new Elysia().use(parent).get('/', (context) => {\n\t\texpectTypeOf(context).not.toHaveProperty('account')\n\t})\n}\n\n// guard handle resolve macro with async\n{\n\tconst plugin = new Elysia()\n\t\t.macro({\n\t\t\taccount: (a: boolean) => ({\n\t\t\t\tresolve: async ({ status }) => {\n\t\t\t\t\tif (Math.random() > 0.5) return status(401)\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\taccount: 'A'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t\t.guard({\n\t\t\tas: 'scoped',\n\t\t\taccount: true\n\t\t})\n\t\t.get('/', ({ account }) => {\n\t\t\texpectTypeOf(account).toEqualTypeOf<string>()\n\t\t})\n\n\tconst parent = new Elysia().use(plugin).get('/', (context) => {\n\t\texpectTypeOf(context).toHaveProperty('account')\n\t\texpectTypeOf(context.account).toEqualTypeOf<string>()\n\t})\n\n\tconst app = new Elysia().use(parent).get('/', (context) => {\n\t\texpectTypeOf(context).not.toHaveProperty('account')\n\t})\n}\n\n// Handle ephemeral and volatile property\n{\n\tconst app = new Elysia()\n\t\t.resolve(() => {\n\t\t\treturn {\n\t\t\t\thello: 'world'\n\t\t\t}\n\t\t})\n\t\t.macro({\n\t\t\tuser: (enabled: boolean) => ({\n\t\t\t\tresolve: ({ hello, query: { name = 'anon' } }) => {\n\t\t\t\t\texpectTypeOf(hello).toEqualTypeOf<'world' | undefined>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\tname\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t\t.get('/', ({ user }) => user, {\n\t\t\tuser: true\n\t\t})\n}\n\n// Handle shorthand function macro\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tuser: {\n\t\t\t\tresolve: ({ query: { name = 'anon' } }) => ({\n\t\t\t\t\tuser: {\n\t\t\t\t\t\tname\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t\t.get(\n\t\t\t'/',\n\t\t\t({ user }) => {\n\t\t\t\texpectTypeOf(user).toEqualTypeOf<{ name: string }>()\n\t\t\t},\n\t\t\t{\n\t\t\t\tuser: true\n\t\t\t}\n\t\t)\n\t\t.get(\n\t\t\t'/no',\n\t\t\t(context) => {\n\t\t\t\texpectTypeOf(context).not.toHaveProperty('user')\n\t\t\t},\n\t\t\t{\n\t\t\t\tuser: false\n\t\t\t}\n\t\t)\n}\n\n// resolve with custom status\n{\n\tconst app = new Elysia()\n\t\t.macro({\n\t\t\tauth: {\n\t\t\t\tresolve: [\n\t\t\t\t\t({ status }) => {\n\t\t\t\t\t\tif (Math.random() > 0.5) return status(401)\n\n\t\t\t\t\t\treturn { user: 'saltyaom' } as const\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}\n\t\t})\n\t\t.get('/', ({ user }) => user, {\n\t\t\tauth: true\n\t\t})\n}\n\n// retrieve resolve conditionally\nconst app = new Elysia()\n\t.macro({\n\t\tuser: (enabled: true) => ({\n\t\t\tresolve() {\n\t\t\t\tif (!enabled) return\n\n\t\t\t\treturn {\n\t\t\t\t\tuser: 'a'\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t})\n\t.get(\n\t\t'/',\n\t\t({ user, status }) => {\n\t\t\tif (!user) return status(401)\n\n\t\t\treturn { hello: 'hanabi' }\n\t\t},\n\t\t{\n\t\t\tuser: true\n\t\t}\n\t)\n\n// Macro name extends macro\n{\n\tnew Elysia()\n\t\t.macro('a', {\n\t\t\tbody: t.Object({ a: t.Literal('A') }),\n\t\t\tbeforeHandle({ body }) {\n\t\t\t\texpectTypeOf(body).toEqualTypeOf<{ a: 'A' }>()\n\t\t\t}\n\t\t})\n\t\t.macro('b', {\n\t\t\ta: true,\n\t\t\tbody: t.Object({ b: t.Literal('B') }),\n\t\t\tbeforeHandle({ body }) {\n\t\t\t\texpectTypeOf(body).toEqualTypeOf<{\n\t\t\t\t\ta: 'A'\n\t\t\t\t\tb: 'B'\n\t\t\t\t}>()\n\t\t\t}\n\t\t})\n}\n\n// handle function\n{\n\tnew Elysia()\n\t\t.macro('a', (a: 'a') => ({\n\t\t\tresolve: () => ({ a: 'a' as const })\n\t\t}))\n\t\t.get(\n\t\t\t'/',\n\t\t\t({ a }) => {\n\t\t\t\texpectTypeOf(a).toEqualTypeOf<'a'>()\n\n\t\t\t\treturn a\n\t\t\t},\n\t\t\t{\n\t\t\t\ta: 'a'\n\t\t\t}\n\t\t)\n\t\t.get('/', 'ok', {\n\t\t\t// @ts-expect-error\n\t\t\ta: 'b'\n\t\t})\n\t\t.listen(3000)\n}\n"
  },
  {
    "path": "test/types/plugins.ts",
    "content": "import { Elysia, t } from '../../src'\n\nconst plugin = async (app: Elysia) =>\n\tapp.decorate('decorate', 'a').state('state', 'a').model({\n\t\tstring: t.String()\n\t})\n\nexport default plugin\n"
  },
  {
    "path": "test/types/schema-standalone.ts",
    "content": "import { Cookie, Elysia, t } from '../../src'\nimport { expectTypeOf } from 'expect-type'\n\n// local\n{\n\t// Handle standalone\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.post('/', ({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tid: number\n\t\t\t\t}>()\n\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: 'a'\n\t\t\t\t}\n\t\t\t})\n\t}\n\n\t// Handle with local schema standalone\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle with multiple standalone with local schema\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ separated: t.Literal(true) })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tseparated: true\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle standalone after override guard\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tbody: t.Object({ separated: t.Literal(true) })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.Literal('saltyaom') }),\n\t\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle standalone\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.post('/', ({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tid: number\n\t\t\t\t}>()\n\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: 'a'\n\t\t\t\t}\n\t\t\t})\n\t}\n\n\t// Handle with local schema standalone\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle with multiple standalone with local schema\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ separated: t.Literal(true) })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tseparated: true\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle standalone after override guard\n\t{\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ separated: t.Literal(true) })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tseparated: true\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.Literal('saltyaom') }),\n\t\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst main = new Elysia().use(local).post(\n\t\t\t'/',\n\t\t\t({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t}>()\n\n\t\t\t\treturn {\n\t\t\t\t\tid: 1,\n\t\t\t\t\tname: body.name\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({ name: t.Literal('saltyaom') }),\n\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t}\n\t\t)\n\t}\n}\n\n// scoped\n{\n\t// Handle standalone\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.post('/', ({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tid: number\n\t\t\t\t}>()\n\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: 'a'\n\t\t\t\t}\n\t\t\t})\n\t}\n\n\t// Handle with local schema standalone\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle with multiple standalone with local schema\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ separated: t.Literal(true) })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tseparated: true\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle standalone after override guard\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tbody: t.Object({ separated: t.Literal(true) })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.Literal('saltyaom') }),\n\t\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle standalone\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.post('/', ({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tid: number\n\t\t\t\t}>()\n\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: 'a'\n\t\t\t\t}\n\t\t\t})\n\t}\n\n\t// Handle with local schema standalone\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle with multiple standalone with local schema\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ separated: t.Literal(true) })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tseparated: true\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle standalone after override guard\n\t{\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ separated: t.Literal(true) })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tseparated: true\n\t\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.Literal('saltyaom') }),\n\t\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst parent = new Elysia().use(local).post(\n\t\t\t'/',\n\t\t\t({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tid: number\n\t\t\t\t\tseparated: true\n\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t}>()\n\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tid: 1,\n\t\t\t\t\tname: body.name\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({ name: t.Literal('saltyaom') }),\n\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t}\n\t\t)\n\n\t\tconst main = new Elysia().use(parent).post(\n\t\t\t'/',\n\t\t\t({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t}>()\n\n\t\t\t\treturn {\n\t\t\t\t\tid: 1,\n\t\t\t\t\tname: body.name\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({ name: t.Literal('saltyaom') }),\n\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t}\n\t\t)\n\n\t\tconst propagated = new Elysia().use(parent.as('scoped')).post(\n\t\t\t'/',\n\t\t\t({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t\tid: number\n\t\t\t\t\tseparated: true\n\t\t\t\t}>()\n\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tid: 1,\n\t\t\t\t\tname: body.name\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({ name: t.Literal('saltyaom') }),\n\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t}\n\t\t)\n\t}\n}\n\n// global\n{\n\t// Handle standalone\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.post('/', ({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tid: number\n\t\t\t\t}>()\n\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: 'a'\n\t\t\t\t}\n\t\t\t})\n\t}\n\n\t// Handle with local schema standalone\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle with multiple standalone with local schema\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ separated: t.Literal(true) })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tseparated: true\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle standalone after override guard\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tbody: t.Object({ separated: t.Literal(true) })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.Literal('saltyaom') }),\n\t\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle standalone\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t// @ts-expect-error\n\t\t\t.post('/', ({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tid: number\n\t\t\t\t}>()\n\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: 'a'\n\t\t\t\t}\n\t\t\t})\n\t}\n\n\t// Handle with local schema standalone\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle with multiple standalone with local schema\n\t{\n\t\tnew Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tas: 'scoped',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ separated: t.Literal(true) })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tseparated: true\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\t}\n\n\t// Handle standalone after override guard\n\t{\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tas: 'global',\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ separated: t.Literal(true) })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/',\n\t\t\t\t({ body }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tid: number\n\t\t\t\t\t\tseparated: true\n\t\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t\t}>()\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t...body\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.Literal('saltyaom') }),\n\t\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst parent = new Elysia().use(local).post(\n\t\t\t'/',\n\t\t\t({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tid: number\n\t\t\t\t\tseparated: true\n\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t}>()\n\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tid: 1,\n\t\t\t\t\tname: body.name\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({ name: t.Literal('saltyaom') }),\n\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t}\n\t\t)\n\n\t\tconst main = new Elysia().use(parent).post(\n\t\t\t'/',\n\t\t\t({ body }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tname: 'saltyaom'\n\t\t\t\t\tseparated: true\n\t\t\t\t\tid: number\n\t\t\t\t}>()\n\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tid: 1,\n\t\t\t\t\tname: body.name\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({ name: t.Literal('saltyaom') }),\n\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t}\n\t\t)\n\t}\n}\n\n// handle every schema type on local\n{\n\t// ? handle local\n\t{\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ family: t.String() }),\n\t\t\t\theaders: t.Object({ family: t.String() }),\n\t\t\t\tquery: t.Object({ family: t.String() }),\n\t\t\t\tparams: t.Object({ family: t.String() }),\n\t\t\t\tresponse: t.Object({ family: t.String() }),\n\t\t\t\tcookie: t.Object({ family: t.String() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/:family',\n\t\t\t\t({ body, query, params, headers, cookie }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tfamily: string\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\t\tfamily: string\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\t\tfamily: string\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\t\tfamily: string\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\t\tfamily: Cookie<string>\n\t\t\t\t\t\t\tname: Cookie<string>\n\t\t\t\t\t\t}\n\t\t\t\t\t>()\n\n\t\t\t\t\treturn body\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst parent = new Elysia().use(local).post(\n\t\t\t'/family/:family/:name',\n\t\t\t({ body, query, params, headers, cookie }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\tname: Cookie<string>\n\t\t\t\t\t}\n\t\t\t\t>()\n\n\t\t\t\treturn body\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia().use(parent).post(\n\t\t\t'/:family/:name',\n\t\t\t({ body, query, params, headers, cookie }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\tname: Cookie<string>\n\t\t\t\t\t}\n\t\t\t\t>()\n\n\t\t\t\treturn body\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t}\n\t\t)\n\t}\n}\n\n// handle every schema type on scoped\n{\n\t// ? handle local\n\t{\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tas: 'scoped',\n\t\t\t\tbody: t.Object({ family: t.String() }),\n\t\t\t\theaders: t.Object({ family: t.String() }),\n\t\t\t\tquery: t.Object({ family: t.String() }),\n\t\t\t\tparams: t.Object({ family: t.String() }),\n\t\t\t\tresponse: t.Object({ family: t.String() }),\n\t\t\t\tcookie: t.Object({ family: t.String() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/:family',\n\t\t\t\t({ body, query, params, headers, cookie }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tfamily: string\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\t\tfamily: string\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\t\tfamily: string\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\t\tfamily: string\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\t\tfamily: Cookie<string>\n\t\t\t\t\t\t\tname: Cookie<string>\n\t\t\t\t\t\t}\n\t\t\t\t\t>()\n\n\t\t\t\t\treturn body\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst parent = new Elysia().use(local).post(\n\t\t\t'/family/:family/:name',\n\t\t\t({ body, query, params, headers, cookie }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tfamily: string\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\tfamily: string\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\tfamily: string\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\tfamily: string\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\tfamily: Cookie<string>\n\t\t\t\t\t\tname: Cookie<string>\n\t\t\t\t\t}\n\t\t\t\t>()\n\n\t\t\t\treturn body\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia().use(parent).post(\n\t\t\t'/:family/:name',\n\t\t\t({ body, query, params, headers, cookie }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\tname: Cookie<string>\n\t\t\t\t\t}\n\t\t\t\t>()\n\n\t\t\t\treturn body\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t}\n\t\t)\n\t}\n}\n\n// handle every schema type on global\n{\n\t// ? handle local\n\t{\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tas: 'global',\n\t\t\t\tbody: t.Object({ family: t.String() }),\n\t\t\t\theaders: t.Object({ family: t.String() }),\n\t\t\t\tquery: t.Object({ family: t.String() }),\n\t\t\t\tparams: t.Object({ family: t.String() }),\n\t\t\t\tresponse: t.Object({ family: t.String() }),\n\t\t\t\tcookie: t.Object({ family: t.String() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/:family',\n\t\t\t\t({ body, query, params, headers, cookie }) => {\n\t\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\t\tfamily: string\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\t\tfamily: string\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\t\tfamily: string\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\t\tfamily: string\n\t\t\t\t\t\tname: string\n\t\t\t\t\t}>()\n\n\t\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\t\tfamily: Cookie<string>\n\t\t\t\t\t\t\tname: Cookie<string>\n\t\t\t\t\t\t}\n\t\t\t\t\t>()\n\n\t\t\t\t\treturn body\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst parent = new Elysia().use(local).post(\n\t\t\t'/family/:family/:name',\n\t\t\t({ body, query, params, headers, cookie }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tfamily: string\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\tfamily: string\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\tfamily: string\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\tfamily: string\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\tfamily: Cookie<string>\n\t\t\t\t\t\tname: Cookie<string>\n\t\t\t\t\t}\n\t\t\t\t>()\n\n\t\t\t\treturn body\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia().use(parent).post(\n\t\t\t'/:family/:name',\n\t\t\t({ body, query, params, headers, cookie }) => {\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tfamily: string\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\tfamily: string\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\tfamily: string\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\tfamily: string\n\t\t\t\t\tname: string\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\tfamily: Cookie<string>\n\t\t\t\t\t\tname: Cookie<string>\n\t\t\t\t\t}\n\t\t\t\t>()\n\n\t\t\t\treturn body\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t}\n\t\t)\n\t}\n}\n"
  },
  {
    "path": "test/types/standard-schema/index.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { Cookie, Elysia, t } from '../../../src'\n\nimport z from 'zod'\n\nimport { expectTypeOf } from 'expect-type'\n\n// ? handle standard schema\n{\n\tnew Elysia().post(\n\t\t'/:name',\n\t\t({\n\t\t\tparams,\n\t\t\tparams: { name },\n\t\t\tbody,\n\t\t\tquery,\n\t\t\theaders,\n\t\t\tcookie,\n\t\t\tstatus\n\t\t}) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t}>()\n\n\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t}>()\n\n\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t}>()\n\n\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t}>()\n\n\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\tname: Cookie<'fouco' | 'lilith'>\n\t\t\t\t}\n\t\t\t>()\n\n\t\t\t// @ts-expect-error\n\t\t\tstatus(404, 'fouco')\n\n\t\t\t// @ts-expect-error\n\t\t\tstatus(418, 'lilith')\n\n\t\t\treturn name === 'lilith'\n\t\t\t\t? status(404, 'lilith')\n\t\t\t\t: status(418, name as any)\n\t\t},\n\t\t{\n\t\t\tbody: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tquery: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tparams: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\theaders: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tcookie: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tresponse: {\n\t\t\t\t404: z.literal('lilith'),\n\t\t\t\t418: z.literal('fouco')\n\t\t\t}\n\t\t}\n\t)\n}\n\n// ? handle standard schema single response\n{\n\tnew Elysia()\n\t\t.get('/lilith', () => 'lilith' as const, {\n\t\t\tresponse: z.literal('lilith')\n\t\t})\n\t\t.get('/lilith', 'lilith', {\n\t\t\tresponse: z.literal('lilith')\n\t\t})\n\t\t// @ts-expect-error\n\t\t.get('/lilith', () => 'a' as const, {\n\t\t\tresponse: z.literal('lilith')\n\t\t})\n}\n\n// ? handle standard schema from reference\n{\n\tnew Elysia()\n\t\t.model({\n\t\t\tbody: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tquery: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tparams: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\theaders: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tcookie: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\t'response.404': z.literal('lilith'),\n\t\t\t'response.418': z.literal('fouco')\n\t\t})\n\t\t.post(\n\t\t\t'/:name',\n\t\t\t({\n\t\t\t\tparams,\n\t\t\t\tparams: { name },\n\t\t\t\tbody,\n\t\t\t\tquery,\n\t\t\t\theaders,\n\t\t\t\tcookie,\n\t\t\t\tstatus\n\t\t\t}) => {\n\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\tname: Cookie<'fouco' | 'lilith'>\n\t\t\t\t\t}\n\t\t\t\t>()\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\tstatus(404, 'fouco')\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\tstatus(418, 'lilith')\n\n\t\t\t\treturn name === 'lilith'\n\t\t\t\t\t? status(404, 'lilith')\n\t\t\t\t\t: status(418, name as any)\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: 'body',\n\t\t\t\tquery: 'query',\n\t\t\t\tparams: 'params',\n\t\t\t\theaders: 'headers',\n\t\t\t\tcookie: 'cookie',\n\t\t\t\tresponse: {\n\t\t\t\t\t404: 'response.404',\n\t\t\t\t\t418: 'response.418'\n\t\t\t\t}\n\t\t\t}\n\t\t)\n}\n\n// ? handle standard schema from guard\n{\n\tnew Elysia()\n\t\t.guard({\n\t\t\tbody: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tquery: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tparams: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\theaders: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tcookie: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tresponse: {\n\t\t\t\t404: z.literal('lilith'),\n\t\t\t\t418: z.literal('fouco')\n\t\t\t}\n\t\t})\n\t\t.post(\n\t\t\t'/:name',\n\t\t\t({\n\t\t\t\tparams,\n\t\t\t\tparams: { name },\n\t\t\t\tbody,\n\t\t\t\tquery,\n\t\t\t\theaders,\n\t\t\t\tcookie,\n\t\t\t\tstatus\n\t\t\t}) => {\n\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\tname: Cookie<'fouco' | 'lilith'>\n\t\t\t\t\t}\n\t\t\t\t>()\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\tstatus(404, 'fouco')\n\n\t\t\t\t// @ts-expect-error\n\t\t\t\tstatus(418, 'lilith')\n\n\t\t\t\treturn name === 'lilith'\n\t\t\t\t\t? status(404, 'lilith')\n\t\t\t\t\t: status(418, name as any)\n\t\t\t}\n\t\t)\n}\n\n// ? merge standard schema response status from guard\n{\n\tnew Elysia()\n\t\t.guard({\n\t\t\tresponse: {\n\t\t\t\t418: z.literal('fouco')\n\t\t\t}\n\t\t})\n\t\t.get('/lilith', () => 'lilith' as const, {\n\t\t\tresponse: z.literal('lilith')\n\t\t})\n\t\t.get('/lilith', 'lilith', {\n\t\t\tresponse: z.literal('lilith')\n\t\t})\n\t\t// @ts-expect-error\n\t\t.get('/lilith', () => 'focou' as const, {\n\t\t\tresponse: z.literal('lilith')\n\t\t})\n\t\t.get('/fouco', ({ status }) => status(418, 'fouco'), {\n\t\t\tresponse: z.literal('lilith')\n\t\t})\n\t\t// @ts-expect-error\n\t\t.get('/fouco', ({ status }) => status(418, 'lilith'), {\n\t\t\tresponse: z.literal('lilith')\n\t\t})\n}\n\n// ? merge standalone standard schema\n{\n\tnew Elysia()\n\t\t.guard({\n\t\t\tschema: 'standalone',\n\t\t\tbody: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tquery: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tparams: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\theaders: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tcookie: z.object({\n\t\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t\t}),\n\t\t\tresponse: {\n\t\t\t\t404: z.object({\n\t\t\t\t\tname: z.literal('lilith')\n\t\t\t\t}),\n\t\t\t\t418: z.object({\n\t\t\t\t\tname: z.literal('fouco')\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t\t.post(\n\t\t\t'/:name',\n\t\t\t({\n\t\t\t\tparams,\n\t\t\t\tparams: { name },\n\t\t\t\tbody,\n\t\t\t\tquery,\n\t\t\t\theaders,\n\t\t\t\tcookie,\n\t\t\t\tstatus\n\t\t\t}) => {\n\t\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\t\tq: 'fouco' | 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\t\tq: 'fouco' | 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\t\tq: 'fouco' | 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\t\tq: 'fouco' | 'lilith'\n\t\t\t\t}>()\n\n\t\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\t\tname: Cookie<'fouco' | 'lilith'>\n\t\t\t\t\t\tq: Cookie<'fouco' | 'lilith'>\n\t\t\t\t\t}\n\t\t\t\t>()\n\n\t\t\t\tstatus(404, {\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tname: 'fouco',\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tq: 'fouco'\n\t\t\t\t})\n\n\t\t\t\tstatus(418, {\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tname: 'lilith',\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tq: 'lilith'\n\t\t\t\t})\n\n\t\t\t\treturn name === 'lilith'\n\t\t\t\t\t? status(404, {\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tq: 'lilith'\n\t\t\t\t\t\t})\n\t\t\t\t\t: status(418, {\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tq: 'fouco'\n\t\t\t\t\t\t})\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tq: t.UnionEnum(['lilith', 'fouco'])\n\t\t\t\t}),\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tq: t.UnionEnum(['lilith', 'fouco'])\n\t\t\t\t}),\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tq: t.UnionEnum(['lilith', 'fouco'])\n\t\t\t\t}),\n\t\t\t\theaders: t.Object({\n\t\t\t\t\tq: t.UnionEnum(['lilith', 'fouco'])\n\t\t\t\t}),\n\t\t\t\tcookie: t.Object({\n\t\t\t\t\tq: t.UnionEnum(['lilith', 'fouco'])\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t404: t.Object({\n\t\t\t\t\t\tq: t.Literal('lilith')\n\t\t\t\t\t}),\n\t\t\t\t\t418: t.Object({\n\t\t\t\t\t\tq: t.Literal('fouco')\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t)\n}\n\n// ? merge standalone standard schema from plugin\n{\n\tconst plugin = new Elysia().guard({\n\t\tas: 'scoped',\n\t\tschema: 'standalone',\n\t\tbody: z.object({\n\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t}),\n\t\tquery: z.object({\n\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t}),\n\t\tparams: z.object({\n\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t}),\n\t\theaders: z.object({\n\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t}),\n\t\tcookie: z.object({\n\t\t\tname: z.literal('fouco').or(z.literal('lilith'))\n\t\t}),\n\t\tresponse: {\n\t\t\t404: z.object({\n\t\t\t\tname: z.literal('lilith')\n\t\t\t}),\n\t\t\t418: z.object({\n\t\t\t\tname: z.literal('fouco')\n\t\t\t})\n\t\t}\n\t})\n\n\tnew Elysia().use(plugin).post(\n\t\t'/:name',\n\t\t({\n\t\t\tparams,\n\t\t\tparams: { name },\n\t\t\tbody,\n\t\t\tquery,\n\t\t\theaders,\n\t\t\tcookie,\n\t\t\tstatus\n\t\t}) => {\n\t\t\texpectTypeOf<typeof params>().toEqualTypeOf<{\n\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\tq: 'fouco' | 'lilith'\n\t\t\t}>()\n\n\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\tq: 'fouco' | 'lilith'\n\t\t\t}>()\n\n\t\t\texpectTypeOf<typeof headers>().toEqualTypeOf<{\n\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\tq: 'fouco' | 'lilith'\n\t\t\t}>()\n\n\t\t\texpectTypeOf<typeof query>().toEqualTypeOf<{\n\t\t\t\tname: 'fouco' | 'lilith'\n\t\t\t\tq: 'fouco' | 'lilith'\n\t\t\t}>()\n\n\t\t\texpectTypeOf<typeof cookie>().toEqualTypeOf<\n\t\t\t\tRecord<string, Cookie<unknown>> & {\n\t\t\t\t\tq: Cookie<'fouco' | 'lilith'>\n\t\t\t\t\tname: Cookie<'fouco' | 'lilith'>\n\t\t\t\t}\n\t\t\t>()\n\n\t\t\tstatus(404, {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tname: 'fouco',\n\t\t\t\t// @ts-expect-error\n\t\t\t\tq: 'fouco'\n\t\t\t})\n\n\t\t\tstatus(418, {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tname: 'lilith',\n\t\t\t\t// @ts-expect-error\n\t\t\t\tq: 'lilith'\n\t\t\t})\n\n\t\t\treturn name === 'lilith'\n\t\t\t\t? status(404, {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tq: 'lilith'\n\t\t\t\t\t})\n\t\t\t\t: status(418, {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tq: 'fouco'\n\t\t\t\t\t})\n\t\t},\n\t\t{\n\t\t\tbody: t.Object({\n\t\t\t\tq: t.UnionEnum(['lilith', 'fouco'])\n\t\t\t}),\n\t\t\tquery: t.Object({\n\t\t\t\tq: t.UnionEnum(['lilith', 'fouco'])\n\t\t\t}),\n\t\t\tparams: t.Object({\n\t\t\t\tq: t.UnionEnum(['lilith', 'fouco'])\n\t\t\t}),\n\t\t\theaders: t.Object({\n\t\t\t\tq: t.UnionEnum(['lilith', 'fouco'])\n\t\t\t}),\n\t\t\tcookie: t.Object({\n\t\t\t\tq: t.UnionEnum(['lilith', 'fouco'])\n\t\t\t}),\n\t\t\tresponse: {\n\t\t\t\t404: t.Object({\n\t\t\t\t\tq: t.Literal('lilith')\n\t\t\t\t}),\n\t\t\t\t418: t.Object({\n\t\t\t\t\tq: t.Literal('fouco')\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t)\n}\n"
  },
  {
    "path": "test/types/type-system.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { t, Elysia, form, file } from '../../src'\nimport { expectTypeOf } from 'expect-type'\n\n// ? ArrayString\n{\n\tnew Elysia().post(\n\t\t'/',\n\t\t({ body }) => {\n\t\t\texpectTypeOf<typeof body>().toEqualTypeOf([] as string[])\n\t\t},\n\t\t{\n\t\t\tbody: t.ArrayString(t.String())\n\t\t}\n\t)\n}\n\n// ? Form\n{\n\tnew Elysia()\n\t\t.get(\n\t\t\t'/',\n\t\t\t() =>\n\t\t\t\tform({\n\t\t\t\t\tname: 'Misono Mika',\n\t\t\t\t\tfile: file('example/kyuukurarin.mp4')\n\t\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Form({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tfile: t.File()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\t.get(\n\t\t\t'/',\n\t\t\t// @ts-expect-error\n\t\t\t() =>\n\t\t\t\tform({\n\t\t\t\t\tfile: 'a'\n\t\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Form({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tfile: t.File()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n}\n\n// Files\n{\n\tnew Elysia().get(\n\t\t'/',\n\t\t({ body }) => {\n\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<{\n\t\t\t\timages: File[]\n\t\t\t}>()\n\t\t},\n\t\t{\n\t\t\tbody: t.Object({\n\t\t\t\timages: t.Files({\n\t\t\t\t\tmaxSize: '4m',\n\t\t\t\t\ttype: 'image'\n\t\t\t\t})\n\t\t\t})\n\t\t}\n\t)\n}\n\n// use StaticDecode to unwrap type parameter\n{\n\tfunction addTwo(num: number) {\n\t\treturn num + 2\n\t}\n\n\tnew Elysia().get('', async ({ query: { foo } }) => addTwo(foo), {\n\t\tquery: t.Object({\n\t\t\tfoo: t\n\t\t\t\t.Transform(t.String())\n\t\t\t\t.Decode((x) => 12)\n\t\t\t\t.Encode((x) => x.toString())\n\t\t})\n\t})\n}\n\n// handle Elysia.Ref\n{\n\tconst Model = new Elysia().model({\n\t\thello: t.Number()\n\t})\n\n\tnew Elysia().use(Model).get(\n\t\t'',\n\t\tasync ({ body }) => {\n\t\t\texpectTypeOf<typeof body>().toEqualTypeOf<number>()\n\t\t},\n\t\t{\n\t\t\tbody: Model.Ref('hello')\n\t\t}\n\t)\n}\n\n// Transform Tuple<ElysiaFile> to Files[]\n{\n\tnew Elysia().get(\n\t\t'/test',\n\t\t() => {\n\t\t\treturn form({\n\t\t\t\tfiles: [file('test.png'), file('test.png')],\n\t\t\t\ttext: 'hello'\n\t\t\t})\n\t\t},\n\t\t{\n\t\t\tresponse: t.Form({\n\t\t\t\tfiles: t.Files(),\n\t\t\t\ttext: t.String()\n\t\t\t})\n\t\t}\n\t)\n}\n"
  },
  {
    "path": "test/types/utils.ts",
    "content": "import { t, getSchemaValidator } from '../../src'\nimport { expectTypeOf } from 'expect-type'\n\n// schema validator\n{\n\tconst schema = t.Object({\n\t\tid: t.Number(),\n\t\tname: t.String()\n\t})\n\n\tconst validator = getSchemaValidator(schema)\n\tconst result = validator.safeParse({ id: 1, name: 'test' })\n\n\tif (result.success) {\n\t\texpectTypeOf(result.data).toEqualTypeOf<{ id: number; name: string }>()\n\t}\n}\n"
  },
  {
    "path": "test/units/class-to-object.test.ts",
    "content": "// import { describe, it, expect } from 'bun:test'\n// import { classToObject } from '../../src/utils'\n\n// describe('extractPropertiesAndGetters', () => {\n// \tclass TestClass {\n// \t\tpublic normalProperty: string = 'normal'\n// \t\tprivate _computedProperty: number = 42\n\n// \t\tget computedProperty(): number {\n// \t\t\treturn this._computedProperty\n// \t\t}\n\n// \t\tpublic method(): string {\n// \t\t\treturn 'method'\n// \t\t}\n// \t}\n\n// \tit('should extract properties and getters, omitting methods', () => {\n// \t\tconst instance = new TestClass()\n// \t\tconst result = classToObject(instance)\n\n// \t\t// Check that normal property is copied\n// \t\texpect(result.normalProperty).toBe('normal')\n\n// \t\t// Check that getter is included\n// \t\texpect(result.computedProperty).toBe(42)\n\n// \t\t// Check that method is not included\n// \t\t// @ts-ignore\n// \t\texpect(result.method).toBeUndefined()\n\n// \t\t// Check that private property is not included\n// \t\texpect(result).not.toHaveProperty('_computedProperty')\n\n// \t\t// Check the structure of the result object\n// \t\texpect(Object.keys(result)).toEqual([\n// \t\t\t'normalProperty',\n// \t\t\t'computedProperty'\n// \t\t])\n// \t})\n\n// \tit('should handle objects with no getters', () => {\n// \t\tconst obj = { a: 1, b: 2 }\n// \t\tconst result = classToObject(obj)\n\n// \t\texpect(result).toEqual({ a: 1, b: 2 })\n// \t})\n\n// \tit('should handle empty objects', () => {\n// \t\tconst obj = {}\n// \t\tconst result = classToObject(obj)\n\n// \t\texpect(result).toEqual({})\n// \t})\n\n// \tit('should handle circular references', () => {\n// \t\tconst obj: any = { a: 1 }\n// \t\tobj.self = obj\n// \t\tobj.nested = { b: 2, parent: obj }\n\n// \t\tconst result = classToObject(obj)\n\n// \t\texpect(result.a).toBe(1)\n// \t\texpect(result.self).toBe(result)\n// \t\texpect(result.nested.b).toBe(2)\n// \t\texpect(result.nested.parent).toBe(result)\n// \t})\n// })\n"
  },
  {
    "path": "test/units/deduplicate-checksum.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { deduplicateChecksum, checksum } from '../../src'\n\ndescribe('Deduplicate Checksum', () => {\n\tit('work', () => {\n\t\tconst a = ['a', 'b', 'c', 'a'].map((x) => ({\n\t\t\tchecksum: checksum(x),\n\t\t\tfn: () => x\n\t\t}))\n\n\t\tdeduplicateChecksum(a)\n\n\t\texpect(a).toHaveLength(3)\n\t})\n})\n"
  },
  {
    "path": "test/units/get-schema-validator.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\n\nimport { Elysia, t, getSchemaValidator } from '../../src'\nimport { z } from 'zod'\n\ndescribe('getSchemaValidator', () => {\n\tit('handle TypeBox as sub type', () => {\n\t\tconst validator = getSchemaValidator(\n\t\t\tz.object({\n\t\t\t\tname: z.string()\n\t\t\t}),\n\t\t\t{\n\t\t\t\tvalidators: [\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tage: t.Number()\n\t\t\t\t\t})\n\t\t\t\t]\n\t\t\t}\n\t\t)\n\n\t\texpect(\n\t\t\tvalidator.Check({\n\t\t\t\tname: 'Elysia',\n\t\t\t\tage: 1\n\t\t\t})\n\t\t).toEqual({\n\t\t\tvalue: {\n\t\t\t\tname: 'Elysia',\n\t\t\t\tage: 1\n\t\t\t}\n\t\t})\n\t})\n})\n"
  },
  {
    "path": "test/units/has-ref.test.ts",
    "content": "import { t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\n\nimport { hasRef } from '../../src/schema'\n\ndescribe('has Ref', () => {\n\tit('return true if object property has ref', () => {\n\t\texpect(\n\t\t\thasRef(\n\t\t\t\tt.Object({\n\t\t\t\t\ta: t.String(),\n\t\t\t\t\tb: t.Ref('b'),\n\t\t\t\t\tc: t.Number()\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(true)\n\t})\n\n\tit('return false if object property does not have ref', () => {\n\t\texpect(\n\t\t\thasRef(\n\t\t\t\tt.Object({\n\t\t\t\t\ta: t.Number(),\n\t\t\t\t\tb: t.String(),\n\t\t\t\t\tc: t.Number()\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(false)\n\t})\n\n\tit('return true if array property contains ref', () => {\n\t\texpect(\n\t\t\thasRef(\n\t\t\t\tt.Object({\n\t\t\t\t\ta: t.String(),\n\t\t\t\t\tb: t.Ref('b'),\n\t\t\t\t\tc: t.Number()\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(true)\n\t})\n\n\tit('should return false if array does not contains ref', () => {\n\t\texpect(\n\t\t\thasRef(\n\t\t\t\tt.Array(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\ta: t.Number(),\n\t\t\t\t\t\tb: t.String(),\n\t\t\t\t\t\tc: t.Number()\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t)\n\t\t).toBe(false)\n\t})\n\n\tit('return true if nested object property has ref', () => {\n\t\texpect(\n\t\t\thasRef(\n\t\t\t\tt.Object({\n\t\t\t\t\ta: t.String(),\n\t\t\t\t\tb: t.Object({\n\t\t\t\t\t\ta: t.String(),\n\t\t\t\t\t\tb: t.Array(t.Ref('b')),\n\t\t\t\t\t\tc: t.Number()\n\t\t\t\t\t}),\n\t\t\t\t\tc: t.Number()\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(true)\n\t})\n\n\tit('return true if ref is inside array', () => {\n\t\texpect(hasRef(t.Ref('b'))).toBe(true)\n\t})\n\n\tit('return true if ref root', () => {\n\t\texpect(hasRef(t.Ref('b'))).toBe(true)\n\t})\n\n\tit('return true if nested object property is inside Union', () => {\n\t\texpect(\n\t\t\thasRef(\n\t\t\t\tt.Object({\n\t\t\t\t\ta: t.String(),\n\t\t\t\t\tb: t.Union([t.String(), t.Array(t.Ref('b'))])\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(true)\n\t})\n\n\tit('return true if nested object property is inside Intersect', () => {\n\t\texpect(\n\t\t\thasRef(\n\t\t\t\tt.Object({\n\t\t\t\t\ta: t.String(),\n\t\t\t\t\tb: t.Intersect([t.String(), t.Array(t.Ref('b'))])\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(true)\n\t})\n\n\tit('return true if Ref is inside Union', () => {\n\t\texpect(\n\t\t\thasRef(\n\t\t\t\tt.Union([\n\t\t\t\t\tt.Object({ foo: t.String() }),\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tfield: t.Ref('b')\n\t\t\t\t\t})\n\t\t\t\t])\n\t\t\t)\n\t\t).toEqual(true)\n\t})\n\n\tit('return true if Ref is inside Intersect', () => {\n\t\texpect(\n\t\t\thasRef(\n\t\t\t\tt.Intersect([\n\t\t\t\t\tt.Object({ foo: t.String() }),\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tfield: t.Ref('b')\n\t\t\t\t\t})\n\t\t\t\t])\n\t\t\t)\n\t\t).toEqual(true)\n\t})\n\n\tit('return true if Ref is inside Transform', () => {\n\t\texpect(\n\t\t\thasRef(\n\t\t\t\tt\n\t\t\t\t\t.Transform(t.Object({ id: t.Ref('b') }))\n\t\t\t\t\t.Decode((value) => value.id)\n\t\t\t\t\t.Encode((value) => ({\n\t\t\t\t\t\tid: value\n\t\t\t\t\t}))\n\t\t\t)\n\t\t).toBe(true)\n\t})\n\n\tit('return true if Ref is the root', () => {\n\t\texpect(hasRef(t.Ref('b'))).toBe(true)\n\t})\n})\n"
  },
  {
    "path": "test/units/has-transform.test.ts",
    "content": "import { t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\n\nimport { hasTransform } from '../../src/schema'\n\ndescribe('has transform', () => {\n\tit('return true if object property has Transform', () => {\n\t\texpect(\n\t\t\thasTransform(\n\t\t\t\tt.Object({\n\t\t\t\t\ta: t.String(),\n\t\t\t\t\tb: t.Numeric(),\n\t\t\t\t\tc: t.Number()\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(true)\n\t})\n\n\tit('return false if object property does not have Transform', () => {\n\t\texpect(\n\t\t\thasTransform(\n\t\t\t\tt.Object({\n\t\t\t\t\ta: t.Number(),\n\t\t\t\t\tb: t.String(),\n\t\t\t\t\tc: t.Number()\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(false)\n\t})\n\n\tit('return true if array property contains Transform', () => {\n\t\texpect(\n\t\t\thasTransform(\n\t\t\t\tt.Object({\n\t\t\t\t\ta: t.String(),\n\t\t\t\t\tb: t.Numeric(),\n\t\t\t\t\tc: t.Number()\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(true)\n\t})\n\n\tit('should return false if array does not contains Transform', () => {\n\t\texpect(\n\t\t\thasTransform(\n\t\t\t\tt.Array(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\ta: t.Number(),\n\t\t\t\t\t\tb: t.String(),\n\t\t\t\t\t\tc: t.Number()\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t)\n\t\t).toBe(false)\n\t})\n\n\tit('return true if nested object property has Transform', () => {\n\t\texpect(\n\t\t\thasTransform(\n\t\t\t\tt.Object({\n\t\t\t\t\ta: t.String(),\n\t\t\t\t\tb: t.Object({\n\t\t\t\t\t\ta: t.String(),\n\t\t\t\t\t\tb: t.Array(t.Numeric()),\n\t\t\t\t\t\tc: t.Number()\n\t\t\t\t\t}),\n\t\t\t\t\tc: t.Number()\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(true)\n\t})\n\n\tit('return true if Transform is inside array', () => {\n\t\texpect(hasTransform(t.Numeric())).toBe(true)\n\t})\n\n\tit('return true if Transform root', () => {\n\t\texpect(hasTransform(t.Numeric())).toBe(true)\n\t})\n\n\tit('return true if nested object property is inside Union', () => {\n\t\texpect(\n\t\t\thasTransform(\n\t\t\t\tt.Object({\n\t\t\t\t\ta: t.String(),\n\t\t\t\t\tb: t.Union([t.String(), t.Array(t.Numeric())])\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(true)\n\t})\n\n\tit('return true if nested object property is inside Intersect', () => {\n\t\texpect(\n\t\t\thasTransform(\n\t\t\t\tt.Object({\n\t\t\t\t\ta: t.String(),\n\t\t\t\t\tb: t.Intersect([t.String(), t.Array(t.Numeric())])\n\t\t\t\t})\n\t\t\t)\n\t\t).toBe(true)\n\t})\n\n\tit('return true if Transform is inside Intersect', () => {\n\t\texpect(\n\t\t\thasTransform(\n\t\t\t\tt.Intersect([\n\t\t\t\t\tt.Object({ foo: t.String() }),\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tfield: t\n\t\t\t\t\t\t\t.Transform(t.String())\n\t\t\t\t\t\t\t.Decode((decoded) => ({ decoded }))\n\t\t\t\t\t\t\t.Encode((v) => v.decoded)\n\t\t\t\t\t})\n\t\t\t\t])\n\t\t\t)\n\t\t).toEqual(true)\n\t})\n\n\tit('return true if Transform is inside Union', () => {\n\t\texpect(\n\t\t\thasTransform(\n\t\t\t\tt.Union([\n\t\t\t\t\tt.Object({ foo: t.String() }),\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tfield: t\n\t\t\t\t\t\t\t.Transform(t.String())\n\t\t\t\t\t\t\t.Decode((decoded) => ({ decoded }))\n\t\t\t\t\t\t\t.Encode((v) => v.decoded)\n\t\t\t\t\t})\n\t\t\t\t])\n\t\t\t)\n\t\t).toEqual(true)\n\t})\n\n\tit('return true when Transform is the root', () => {\n\t\texpect(\n\t\t\thasTransform(\n\t\t\t\tt\n\t\t\t\t\t.Transform(t.Object({ id: t.String() }))\n\t\t\t\t\t.Decode((value) => value.id)\n\t\t\t\t\t.Encode((value) => ({\n\t\t\t\t\t\tid: value\n\t\t\t\t\t}))\n\t\t\t)\n\t\t).toBe(true)\n\t})\n})\n"
  },
  {
    "path": "test/units/merge-deep.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\n\nimport { Elysia } from '../../src'\nimport { mergeDeep } from '../../src/utils'\nimport { req } from '../utils'\n\ndescribe('mergeDeep', () => {\n\tit('merge empty object', () => {\n\t\tconst result = mergeDeep({}, {})\n\t\texpect(result).toEqual({})\n\t})\n\n\tit('merge non-overlapping key', () => {\n\t\tconst result = mergeDeep({ key1: 'value1' }, { key2: 'value2' })\n\n\t\texpect(result).toEqual({ key1: 'value1', key2: 'value2' })\n\t})\n\n\tit('merge overlapping key', () => {\n\t\tconst result = mergeDeep(\n\t\t\t{\n\t\t\t\tname: 'Eula',\n\t\t\t\tcity: 'Mondstadt'\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'Amber',\n\t\t\t\taffiliation: 'Knight'\n\t\t\t}\n\t\t)\n\n\t\texpect(result).toEqual({\n\t\t\tname: 'Amber',\n\t\t\tcity: 'Mondstadt',\n\t\t\taffiliation: 'Knight'\n\t\t})\n\t})\n\n\tit('maintain overlapping class', () => {\n\t\tclass Test {\n\t\t\treadonly name = 'test'\n\n\t\t\tpublic foo() {\n\t\t\t\treturn this.name\n\t\t\t}\n\t\t}\n\n\t\tconst target = { key1: Test }\n\t\tconst source = { key2: Test }\n\n\t\tconst result = mergeDeep(target, source)\n\t\texpect(result.key1).toBe(Test)\n\t})\n\n\tit('maintain overlapping class in instance', async () => {\n\t\tclass DbConnection {\n\t\t\thealth() {\n\t\t\t\treturn 'ok'\n\t\t\t}\n\n\t\t\tgetUsers() {\n\t\t\t\treturn []\n\t\t\t}\n\t\t}\n\n\t\tconst dbPlugin = new Elysia({ name: 'db' }).decorate(\n\t\t\t'db',\n\t\t\tnew DbConnection()\n\t\t)\n\n\t\tconst userRoutes = new Elysia({ prefix: '/user' })\n\t\t\t.use(dbPlugin)\n\t\t\t.get('', ({ db }) => db.getUsers())\n\n\t\tconst app = new Elysia()\n\t\t\t.use(dbPlugin)\n\t\t\t.use(userRoutes)\n\t\t\t.get('/health', ({ db }) => db.health())\n\n\t\tconst response = await app.handle(req('/health')).then((x) => x.text())\n\n\t\texpect(response).toBe('ok')\n\t})\n\n\tit('handle freezed object', () => {\n\t\tnew Elysia()\n\t\t\t.decorate('db', Object.freeze({ hello: 'world' }))\n\t\t\t.guard({}, (app) => app)\n\t})\n\n\tit('handle circular references', () => {\n\t\tconst a: {\n\t\t\tx: number\n\t\t\ttoB?: typeof b\n\t\t} = { x: 1 }\n\t\tconst b: {\n\t\t\ty: number\n\t\t\ttoA?: typeof a\n\t\t} = { y: 2 }\n\n\t\ta.toB = b\n\t\tb.toA = a\n\n\t\tconst target = {}\n\t\tconst source = { prop: a }\n\n\t\tconst result = mergeDeep(target, source)\n\n\t\texpect(result.prop.x).toBe(1)\n\t\texpect(result.prop.toB?.y).toBe(2)\n\t})\n\n\tit('handle shared references in different branches', () => {\n\t\tconst shared = { value: 123 }\n\t\tconst target = { x: {}, y: {} }\n\t\tconst source = { x: shared, y: shared }\n\n\t\tconst result = mergeDeep(target, source)\n\n\t\texpect(result.x.value).toBe(123)\n\t\texpect(result.y.value).toBe(123)\n\t})\n\n\tit('deduplicate plugin with circular decorators', async () => {\n\t\tconst a: {\n\t\t\tx: number\n\t\t\ttoB?: typeof b\n\t\t} = { x: 1 }\n\t\tconst b: {\n\t\t\ty: number\n\t\t\ttoA?: typeof a\n\t\t} = { y: 2 }\n\t\ta.toB = b\n\t\tb.toA = a\n\n\t\tconst complex = { a }\n\n\t\tconst Plugin = new Elysia({ name: 'Plugin', seed: 'seed' })\n\t\t\t.decorate('dep', complex)\n\t\t\t.as('scoped')\n\n\t\tconst ModuleA = new Elysia({ name: 'ModuleA' })\n\t\t\t.use(Plugin)\n\t\t\t.get('/moda/a', ({ dep }) => dep.a.x)\n\t\t\t.get('/moda/b', ({ dep }) => dep.a.toB?.y)\n\n\t\tconst ModuleB = new Elysia({ name: 'ModuleB' })\n\t\t\t.use(Plugin)\n\t\t\t.get('/modb/a', ({ dep }) => dep.a.x)\n\t\t\t.get('/modb/b', ({ dep }) => dep.a.toB?.y)\n\n\t\tconst app = new Elysia().use(ModuleA).use(ModuleB)\n\n\t\tconst resA = await app.handle(req('/moda/a')).then((x) => x.text())\n\t\tconst resB = await app.handle(req('/modb/a')).then((x) => x.text())\n\t\tconst resC = await app.handle(req('/moda/b')).then((x) => x.text())\n\t\tconst resD = await app.handle(req('/modb/b')).then((x) => x.text())\n\n\t\texpect(resA).toBe('1')\n\t\texpect(resB).toBe('1')\n\t\texpect(resC).toBe('2')\n\t\texpect(resD).toBe('2')\n\t})\n})\n"
  },
  {
    "path": "test/units/merge-object-schemas.test.ts",
    "content": "import { t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\n\nimport { mergeObjectSchemas } from '../../src/schema'\n\ndescribe('mergeDeep', () => {\n\tit('merge object', () => {\n\t\tconst result = mergeObjectSchemas([\n\t\t\tt.Object({\n\t\t\t\tname: t.String()\n\t\t\t}),\n\t\t\tt.Object({\n\t\t\t\tage: t.Number()\n\t\t\t})\n\t\t])\n\n\t\texpect(result).toEqual({\n\t\t\tschema: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tage: t.Number()\n\t\t\t}),\n\t\t\tnotObjects: []\n\t\t})\n\t})\n\n\tit('handle additionalProperties true', () => {\n\t\tconst result = mergeObjectSchemas([\n\t\t\tt.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: true\n\t\t\t\t}\n\t\t\t),\n\t\t\tt.Object({\n\t\t\t\tage: t.Number()\n\t\t\t})\n\t\t])\n\n\t\texpect(result).toEqual({\n\t\t\tschema: t.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tage: t.Number()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: true\n\t\t\t\t}\n\t\t\t),\n\t\t\tnotObjects: []\n\t\t})\n\t})\n\n\tit('handle additionalProperties false', () => {\n\t\tconst result = mergeObjectSchemas([\n\t\t\tt.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t}\n\t\t\t),\n\t\t\tt.Object({\n\t\t\t\tage: t.Number()\n\t\t\t})\n\t\t])\n\n\t\texpect(result).toEqual({\n\t\t\tschema: t.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tage: t.Number()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t}\n\t\t\t),\n\t\t\tnotObjects: []\n\t\t})\n\t})\n\n\tit('prefers additionalProperties: false over true', () => {\n\t\tconst result = mergeObjectSchemas([\n\t\t\tt.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: true\n\t\t\t\t}\n\t\t\t),\n\t\t\tt.Object(\n\t\t\t\t{\n\t\t\t\t\tage: t.Number()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t}\n\t\t\t)\n\t\t])\n\n\t\texpect(result).toEqual({\n\t\t\tschema: t.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tage: t.Number()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t}\n\t\t\t),\n\t\t\tnotObjects: []\n\t\t})\n\t})\n\n\tit('handle non object', () => {\n\t\tconst result = mergeObjectSchemas([\n\t\t\tt.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t}\n\t\t\t),\n\t\t\tt.Object({\n\t\t\t\tage: t.Number()\n\t\t\t}),\n\t\t\tt.String()\n\t\t])\n\n\t\texpect(result).toEqual({\n\t\t\tschema: t.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tage: t.Number()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t}\n\t\t\t),\n\t\t\tnotObjects: [t.String()]\n\t\t})\n\t})\n\n\tit('handle single object schema', () => {\n\t\tconst result = mergeObjectSchemas([\n\t\t\tt.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t}\n\t\t\t)\n\t\t])\n\n\t\texpect(result).toEqual({\n\t\t\tschema: t.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t}\n\t\t\t),\n\t\t\tnotObjects: []\n\t\t})\n\t})\n\n\tit('handle single non object schema', () => {\n\t\tconst result = mergeObjectSchemas([t.String()])\n\n\t\texpect(result).toEqual({\n\t\t\tschema: undefined,\n\t\t\tnotObjects: [t.String()]\n\t\t})\n\t})\n\n\tit('handle multiple object schemas', () => {\n\t\tconst result = mergeObjectSchemas([\n\t\t\tt.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t}\n\t\t\t),\n\t\t\tt.Object({\n\t\t\t\tage: t.Number()\n\t\t\t}),\n\t\t\tt.Object({\n\t\t\t\temail: t.String()\n\t\t\t}),\n\t\t\tt.Object({\n\t\t\t\taddress: t.String()\n\t\t\t})\n\t\t])\n\n\t\texpect(result).toEqual({\n\t\t\tschema: t.Object(\n\t\t\t\t{\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tage: t.Number(),\n\t\t\t\t\temail: t.String(),\n\t\t\t\t\taddress: t.String()\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t}\n\t\t\t),\n\t\t\tnotObjects: []\n\t\t})\n\t})\n})\n"
  },
  {
    "path": "test/units/numeric.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { isNumericString } from '../../src/utils'\n\ndescribe('Numeric string', () => {\n\tit('valid string', async () => {\n\t\texpect(isNumericString('69')).toBe(true)\n\t\texpect(isNumericString('69.420')).toBe(true)\n\t\texpect(isNumericString('00093281')).toBe(true)\n\t\texpect(isNumericString(Number.MAX_SAFE_INTEGER.toString())).toBe(true)\n\t})\n\n\tit('invalid string', async () => {\n\t\texpect(isNumericString('pizza')).toBe(false)\n\t\texpect(isNumericString('69,420')).toBe(false)\n\t\texpect(isNumericString('0O093281')).toBe(false)\n\t\texpect(isNumericString(crypto.randomUUID())).toBe(false)\n\t\texpect(isNumericString('9007199254740995')).toBe(false)\n\t\texpect(isNumericString('123456789012345678')).toBe(false)\n\t\texpect(isNumericString('123123.999999999999')).toBe(false)\n\t})\n\n\tit('invalid on empty', async () => {\n\t\texpect(isNumericString('')).toBe(false)\n\t\texpect(isNumericString(' ')).toBe(false)\n\t\texpect(isNumericString('    ')).toBe(false)\n\t})\n\n\tit('start with number', async () => {\n\t\texpect(isNumericString('6AAAA')).toBe(false)\n\t})\n})\n"
  },
  {
    "path": "test/units/replace-schema-type.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport type { TSchema } from '@sinclair/typebox'\nimport { Elysia, t } from '../../src'\nimport {\n\treplaceSchemaTypeFromManyOptions as replaceSchemaType,\n\trevertObjAndArrStr,\n\tcoerceFormData\n} from '../../src/replace-schema'\nimport { req } from '../utils'\n\ndescribe('Replace Schema Type', () => {\n\tit('replace primitive', async () => {\n\t\texpect(\n\t\t\treplaceSchemaType(t.String(), {\n\t\t\t\tfrom: t.String(),\n\t\t\t\tto: () => t.Number()\n\t\t\t})\n\t\t).toMatchObject(t.Number())\n\t})\n\n\tit('replace object properties', async () => {\n\t\texpect(\n\t\t\treplaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tid: t.Number(),\n\t\t\t\t\tname: t.String()\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Number(),\n\t\t\t\t\tto: () => t.Numeric()\n\t\t\t\t}\n\t\t\t)\n\t\t).toMatchObject(\n\t\t\tt.Object({\n\t\t\t\tid: t.Numeric(),\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t)\n\t})\n\n\tit('replace object properties in nullable', async () => {\n\t\texpect(\n\t\t\treplaceSchemaType(\n\t\t\t\tt.Nullable(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tid: t.Number(),\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t})\n\t\t\t\t),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Number(),\n\t\t\t\t\tto: () => t.Numeric()\n\t\t\t\t}\n\t\t\t)\n\t\t).toMatchObject(\n\t\t\tt.Nullable(\n\t\t\t\tt.Object({\n\t\t\t\t\tid: t.Numeric(),\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t)\n\t\t)\n\t})\n\n\tit('replace object properties in Union', async () => {\n\t\texpect(\n\t\t\treplaceSchemaType(\n\t\t\t\tt.Union([\n\t\t\t\t\tt.String(),\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tid: t.Number(),\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t})\n\t\t\t\t]),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Number(),\n\t\t\t\t\tto: () => t.Numeric()\n\t\t\t\t}\n\t\t\t)\n\t\t).toMatchObject(\n\t\t\tt.Union([\n\t\t\t\tt.String(),\n\t\t\t\tt.Object({\n\t\t\t\t\tid: t.Numeric(),\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t])\n\t\t)\n\t})\n\n\tit('maintain descriptive properties', async () => {\n\t\texpect(\n\t\t\treplaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tid: t.Number({\n\t\t\t\t\t\tdefault: 1,\n\t\t\t\t\t\ttitle: 'hello'\n\t\t\t\t\t}),\n\t\t\t\t\tname: t.String()\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Number(),\n\t\t\t\t\tto: (options) => t.Numeric(options)\n\t\t\t\t}\n\t\t\t)\n\t\t).toMatchObject(\n\t\t\tt.Object({\n\t\t\t\tid: t.Numeric({\n\t\t\t\t\tdefault: 1,\n\t\t\t\t\ttitle: 'hello'\n\t\t\t\t}),\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t)\n\t})\n\n\tit('accept multiple replacement', async () => {\n\t\texpect(\n\t\t\treplaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tid: t.Number(),\n\t\t\t\t\tisAdmin: t.Boolean()\n\t\t\t\t}),\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\tfrom: t.Number(),\n\t\t\t\t\t\tto: () => t.Numeric()\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tfrom: t.Boolean(),\n\t\t\t\t\t\tto: () => t.BooleanString()\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t)\n\t\t).toMatchObject(\n\t\t\tt.Object({\n\t\t\t\tid: t.Numeric(),\n\t\t\t\tisAdmin: t.BooleanString()\n\t\t\t})\n\t\t)\n\t})\n\n\tit('replace excludeRoot (match ObjectString)', () => {\n\t\texpect(\n\t\t\treplaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tobj: t.Object({\n\t\t\t\t\t\tid: t.String()\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\tto: (schema) => t.ObjectString(schema.properties),\n\t\t\t\t\texcludeRoot: true,\n\t\t\t\t\tuntilObjectFound: false\n\t\t\t\t}\n\t\t\t)\n\t\t).toMatchObject(\n\t\t\tt.Object({\n\t\t\t\tobj: t.ObjectString({\n\t\t\t\t\tid: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\t})\n\n\tit('replace replace ArrayString', () => {\n\t\texpect(\n\t\t\treplaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tarr: t.Array(t.String())\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\tto: () => t.ObjectString({}),\n\t\t\t\t\texcludeRoot: true\n\t\t\t\t}\n\t\t\t)\n\t\t).toMatchObject(\n\t\t\tt.Object({\n\t\t\t\tarr: t.Array(t.String())\n\t\t\t})\n\t\t)\n\t})\n\n\tit('replace re-calculate transform', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tpagination: t.Object({\n\t\t\t\t\tpageIndex: t.Number(),\n\t\t\t\t\tpageLimit: t.Number()\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tconst status = await app\n\t\t\t.handle(req('/?pagination={\"pageIndex\":1}'))\n\t\t\t.then((x) => x.status)\n\n\t\texpect(status).toBe(422)\n\t})\n\n\tit('replace item in Array', () => {\n\t\texpect(\n\t\t\treplaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tarr: t.Array(t.Number())\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Number(),\n\t\t\t\t\tto: () => t.Numeric(),\n\t\t\t\t\texcludeRoot: true\n\t\t\t\t}\n\t\t\t)\n\t\t).toMatchObject(\n\t\t\tt.Object({\n\t\t\t\tarr: t.Array(t.Numeric())\n\t\t\t})\n\t\t)\n\t})\n\n\tdescribe('Basic Transformation', () => {\n\t\tit('should transform Object to ObjectString', () => {\n\t\t\texpect(\n\t\t\t\treplaceSchemaType(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t}),\n\t\t\t\t\t{\n\t\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s)\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\t\t})\n\n\t\tit('should transform Array to ArrayString', () => {\n\t\t\texpect(\n\t\t\t\treplaceSchemaType(t.Array(t.String()), {\n\t\t\t\t\tfrom: t.Array(t.Any()),\n\t\t\t\t\tto: (s) => t.ArrayString(s.items || t.Any(), s)\n\t\t\t\t})\n\t\t\t).toMatchObject({\n\t\t\t\telysiaMeta: 'ArrayString'\n\t\t\t})\n\t\t})\n\n\t\tit('should preserve properties after transformation', () => {\n\t\t\texpect(\n\t\t\t\treplaceSchemaType(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tname: t.String(),\n\t\t\t\t\t\tage: t.Number()\n\t\t\t\t\t}),\n\t\t\t\t\t{\n\t\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s)\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t).toMatchObject(\n\t\t\t\tt.ObjectString({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tage: t.Number()\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\t})\n\n\tdescribe('excludeRoot Option', () => {\n\t\tit('should NOT transform root when excludeRoot is true', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tmetadata: t.Object({\n\t\t\t\t\t\tcategory: t.String()\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s),\n\t\t\t\t\texcludeRoot: true\n\t\t\t\t}\n\t\t\t)\n\n\t\t\texpect(result).toMatchObject({\n\t\t\t\ttype: 'object'\n\t\t\t})\n\t\t\texpect(result.elysiaMeta).toBeUndefined()\n\t\t\texpect(result.properties.metadata).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\t\t})\n\n\t\tit('should transform root when excludeRoot is false', () => {\n\t\t\texpect(\n\t\t\t\treplaceSchemaType(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t}),\n\t\t\t\t\t{\n\t\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s),\n\t\t\t\t\t\texcludeRoot: false\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\t\t})\n\t})\n\n\tdescribe('onlyFirst Option', () => {\n\t\tit('should stop traversal after first match', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tlevel1: t.Object({\n\t\t\t\t\t\tlevel2: t.Object({\n\t\t\t\t\t\t\tlevel3: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s),\n\t\t\t\t\tonlyFirst: 'object',\n\t\t\t\t\texcludeRoot: true\n\t\t\t\t}\n\t\t\t)\n\n\t\t\texpect(result.properties.level1).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\n\t\t\tconst level1ObjBranch = result.properties.level1.anyOf.find(\n\t\t\t\t(x: TSchema) => x.type === 'object'\n\t\t\t)\n\t\t\texpect(level1ObjBranch.properties.level2).toMatchObject({\n\t\t\t\ttype: 'object'\n\t\t\t})\n\t\t\texpect(level1ObjBranch.properties.level2.elysiaMeta).toBeUndefined()\n\t\t})\n\n\t\tit('should transform all siblings at same level', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tobj1: t.Object({ a: t.String() }),\n\t\t\t\t\tobj2: t.Object({ b: t.String() }),\n\t\t\t\t\tstr: t.String()\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s),\n\t\t\t\t\tonlyFirst: 'object',\n\t\t\t\t\texcludeRoot: true\n\t\t\t\t}\n\t\t\t)\n\n\t\t\texpect(result.properties.obj1).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\t\t\texpect(result.properties.obj2).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\t\t\texpect(result.properties.str).toMatchObject({\n\t\t\t\ttype: 'string'\n\t\t\t})\n\t\t})\n\t})\n\n\tdescribe('rootOnly Option', () => {\n\t\tit('should only transform root, not children', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tnested: t.Object({\n\t\t\t\t\t\tdeep: t.String()\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s),\n\t\t\t\t\trootOnly: true\n\t\t\t\t}\n\t\t\t)\n\n\t\t\texpect(result).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\n\t\t\tconst objBranch = result.anyOf.find(\n\t\t\t\t(x: TSchema) => x.type === 'object'\n\t\t\t)\n\t\t\texpect(objBranch.properties.nested).toMatchObject({\n\t\t\t\ttype: 'object'\n\t\t\t})\n\t\t\texpect(objBranch.properties.nested.elysiaMeta).toBeUndefined()\n\t\t})\n\n\t\tit('should not transform if root does not match', () => {\n\t\t\texpect(\n\t\t\t\treplaceSchemaType(t.String(), {\n\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s),\n\t\t\t\t\trootOnly: true\n\t\t\t\t})\n\t\t\t).toMatchObject({\n\t\t\t\ttype: 'string'\n\t\t\t})\n\t\t})\n\t})\n\n\tdescribe('Double-wrapping Protection', () => {\n\t\tit('should NOT double-wrap ObjectString', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tmetadata: t.ObjectString({\n\t\t\t\t\t\tcategory: t.String()\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s),\n\t\t\t\t\texcludeRoot: true\n\t\t\t\t}\n\t\t\t)\n\n\t\t\texpect(result.properties.metadata).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\n\t\t\tconst anyOf = result.properties.metadata.anyOf\n\t\t\tconst objBranch = anyOf.find((x: TSchema) => x.type === 'object')\n\t\t\texpect(objBranch.elysiaMeta).toBeUndefined()\n\t\t\texpect(objBranch.anyOf).toBeUndefined()\n\t\t})\n\n\t\tit('should NOT double-wrap ArrayString', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\titems: t.ArrayString(t.String())\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Array(t.Any()),\n\t\t\t\t\tto: (s) => t.ArrayString(s.items || t.Any(), s),\n\t\t\t\t\texcludeRoot: true\n\t\t\t\t}\n\t\t\t)\n\n\t\t\texpect(result.properties.items).toMatchObject({\n\t\t\t\telysiaMeta: 'ArrayString'\n\t\t\t})\n\n\t\t\tconst anyOf = result.properties.items.anyOf\n\t\t\tconst arrBranch = anyOf.find((x: TSchema) => x.type === 'array')\n\t\t\texpect(arrBranch.elysiaMeta).toBeUndefined()\n\t\t})\n\t})\n\n\tdescribe('Bottom-up Traversal', () => {\n\t\tit('should transform children before parents', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tlevel1: t.Object({\n\t\t\t\t\t\tlevel2: t.Object({\n\t\t\t\t\t\t\tlevel3: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s),\n\t\t\t\t\texcludeRoot: true\n\t\t\t\t}\n\t\t\t)\n\n\t\t\texpect(result.properties.level1).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\n\t\t\tconst level1ObjBranch = result.properties.level1.anyOf.find(\n\t\t\t\t(x: TSchema) => x.type === 'object'\n\t\t\t)\n\t\t\texpect(level1ObjBranch.properties.level2).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\t\t})\n\t})\n\n\tdescribe('Array of Options', () => {\n\t\tit('should apply multiple transformations in order', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tmetadata: t.Object({\n\t\t\t\t\t\tcategory: t.String()\n\t\t\t\t\t}),\n\t\t\t\t\ttags: t.Array(t.String())\n\t\t\t\t}),\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s),\n\t\t\t\t\t\texcludeRoot: true\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tfrom: t.Array(t.Any()),\n\t\t\t\t\t\tto: (s) => t.ArrayString(s.items || t.Any(), s),\n\t\t\t\t\t\texcludeRoot: true\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t)\n\n\t\t\texpect(result.properties.metadata).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\t\t\texpect(result.properties.tags).toMatchObject({\n\t\t\t\telysiaMeta: 'ArrayString'\n\t\t\t})\n\t\t})\n\t})\n\n\tdescribe('Composition Types', () => {\n\t\tit('should traverse anyOf branches', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\t{\n\t\t\t\t\tanyOf: [\n\t\t\t\t\t\tt.Object({ a: t.String() }),\n\t\t\t\t\t\tt.Object({ b: t.Number() })\n\t\t\t\t\t]\n\t\t\t\t} as any,\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s)\n\t\t\t\t}\n\t\t\t)\n\n\t\t\texpect(result.anyOf[0]).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\t\t\texpect(result.anyOf[1]).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\t\t})\n\n\t\tit('should traverse oneOf branches', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\t{\n\t\t\t\t\toneOf: [t.Object({ type: t.String() }), t.Array(t.String())]\n\t\t\t\t} as any,\n\t\t\t\t{\n\t\t\t\t\tfrom: t.Object({}),\n\t\t\t\t\tto: (s) => t.ObjectString(s.properties || {}, s)\n\t\t\t\t}\n\t\t\t)\n\n\t\t\texpect(result.oneOf[0]).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\t\t\texpect(result.oneOf[1]).toMatchObject({\n\t\t\t\ttype: 'array'\n\t\t\t})\n\t\t})\n\t})\n\n\tdescribe('Reverse Transformation Helpers', () => {\n\t\tit('should extract plain Object from ObjectString', () => {\n\t\t\tconst objectString = t.ObjectString({\n\t\t\t\tname: t.String(),\n\t\t\t\tage: t.Number()\n\t\t\t})\n\n\t\t\tconst result = revertObjAndArrStr(objectString)\n\n\t\t\texpect(result).toMatchObject({\n\t\t\t\ttype: 'object'\n\t\t\t})\n\t\t\texpect(result.elysiaMeta).toBeUndefined()\n\t\t\texpect(result.anyOf).toBeUndefined()\n\t\t\texpect(result.properties).toMatchObject({\n\t\t\t\tname: { type: 'string' },\n\t\t\t\tage: { type: 'number' }\n\t\t\t})\n\t\t})\n\n\t\tit('should return unchanged if not ObjectString', () => {\n\t\t\tconst plainObject = t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\n\t\t\tconst result = revertObjAndArrStr(plainObject)\n\n\t\t\texpect(result).toBe(plainObject)\n\t\t})\n\n\t\tit('should extract plain Array from ArrayString', () => {\n\t\t\tconst arrayString = t.ArrayString(t.String())\n\n\t\t\tconst result = revertObjAndArrStr(arrayString)\n\n\t\t\texpect(result).toMatchObject({\n\t\t\t\ttype: 'array'\n\t\t\t})\n\t\t\texpect(result.elysiaMeta).toBeUndefined()\n\t\t\texpect(result.anyOf).toBeUndefined()\n\t\t\texpect(result.items).toMatchObject({\n\t\t\t\ttype: 'string'\n\t\t\t})\n\t\t})\n\n\t\tit('should return unchanged if not ArrayString', () => {\n\t\t\tconst plainArray = t.Array(t.String())\n\n\t\t\tconst result = revertObjAndArrStr(plainArray)\n\n\t\t\texpect(result).toBe(plainArray)\n\t\t})\n\n\t\tit('should transform ObjectString back to Object', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tmetadata: t.ObjectString({\n\t\t\t\t\t\tcategory: t.String()\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.ObjectString({}),\n\t\t\t\t\tto: (s) => revertObjAndArrStr(s),\n\t\t\t\t\texcludeRoot: true\n\t\t\t\t}\n\t\t\t)\n\n\t\t\texpect(result.properties.metadata).toMatchObject({\n\t\t\t\ttype: 'object'\n\t\t\t})\n\t\t\texpect(result.properties.metadata.elysiaMeta).toBeUndefined()\n\t\t\texpect(result.properties.metadata.anyOf).toBeUndefined()\n\t\t\texpect(result.properties.metadata.properties.category).toMatchObject(\n\t\t\t\t{\n\t\t\t\t\ttype: 'string'\n\t\t\t\t}\n\t\t\t)\n\t\t})\n\n\t\tit('should transform ArrayString back to Array', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\ttags: t.ArrayString(t.String())\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tfrom: t.ArrayString(t.Any()),\n\t\t\t\t\tto: (s) => revertObjAndArrStr(s),\n\t\t\t\t\texcludeRoot: true\n\t\t\t\t}\n\t\t\t)\n\n\t\t\texpect(result.properties.tags).toMatchObject({\n\t\t\t\ttype: 'array'\n\t\t\t})\n\t\t\texpect(result.properties.tags.elysiaMeta).toBeUndefined()\n\t\t\texpect(result.properties.tags.anyOf).toBeUndefined()\n\t\t})\n\t})\n\n\tdescribe('coerceFormData', () => {\n\t\tit('should convert first-level Object to ObjectString (excluding root)', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tuser: t.Object({\n\t\t\t\t\t\tname: t.String(),\n\t\t\t\t\t\tage: t.Number()\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\tcoerceFormData()\n\t\t\t)\n\n\t\t\t// Root should remain plain Object\n\t\t\texpect(result).toMatchObject({\n\t\t\t\ttype: 'object'\n\t\t\t})\n\t\t\texpect(result.elysiaMeta).toBeUndefined()\n\n\t\t\t// First-level nested object should be converted to ObjectString\n\t\t\texpect(result.properties.user).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\t\t})\n\n\t\tit('should NOT convert deeper nested Objects', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tlevel1: t.Object({\n\t\t\t\t\t\tlevel2: t.Object({\n\t\t\t\t\t\t\tlevel3: t.Object({\n\t\t\t\t\t\t\t\tvalue: t.String()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\tcoerceFormData()\n\t\t\t)\n\n\t\t\t// level1 should be ObjectString\n\t\t\texpect(result.properties.level1).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\n\t\t\t// level2 should remain plain Object (not converted)\n\t\t\tconst level1ObjBranch = result.properties.level1.anyOf.find(\n\t\t\t\t(x: TSchema) => x.type === 'object'\n\t\t\t)\n\t\t\texpect(level1ObjBranch.properties.level2).toMatchObject({\n\t\t\t\ttype: 'object'\n\t\t\t})\n\t\t\texpect(level1ObjBranch.properties.level2.elysiaMeta).toBeUndefined()\n\n\t\t\t// level3 should also remain plain Object\n\t\t\texpect(level1ObjBranch.properties.level2.properties.level3).toMatchObject({\n\t\t\t\ttype: 'object'\n\t\t\t})\n\t\t\texpect(level1ObjBranch.properties.level2.properties.level3.elysiaMeta).toBeUndefined()\n\t\t})\n\n\t\tit('should convert first-level Array to ArrayString', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\ttags: t.Array(t.String())\n\t\t\t\t}),\n\t\t\t\tcoerceFormData()\n\t\t\t)\n\n\t\t\t// tags should be converted to ArrayString\n\t\t\texpect(result.properties.tags).toMatchObject({\n\t\t\t\telysiaMeta: 'ArrayString'\n\t\t\t})\n\t\t})\n\n\t\tit('should NOT convert deeper nested Arrays', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tlevel1: t.Array(\n\t\t\t\t\t\tt.Array(\n\t\t\t\t\t\t\tt.Array(t.String())\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t}),\n\t\t\t\tcoerceFormData()\n\t\t\t)\n\n\t\t\t// First-level array should be ArrayString\n\t\t\texpect(result.properties.level1).toMatchObject({\n\t\t\t\telysiaMeta: 'ArrayString'\n\t\t\t})\n\n\t\t\t// Second-level array should remain plain Array\n\t\t\tconst level1ArrBranch = result.properties.level1.anyOf.find(\n\t\t\t\t(x: TSchema) => x.type === 'array'\n\t\t\t)\n\t\t\texpect(level1ArrBranch.items).toMatchObject({\n\t\t\t\ttype: 'array'\n\t\t\t})\n\t\t\texpect(level1ArrBranch.items.elysiaMeta).toBeUndefined()\n\n\t\t\t// Third-level array should also remain plain Array\n\t\t\texpect(level1ArrBranch.items.items).toMatchObject({\n\t\t\t\ttype: 'array'\n\t\t\t})\n\t\t\texpect(level1ArrBranch.items.items.elysiaMeta).toBeUndefined()\n\t\t})\n\n\t\tit('should handle Object with File and nested Object', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tavatar: t.File(),\n\t\t\t\t\tmetadata: t.Object({\n\t\t\t\t\t\ttags: t.Array(t.String()),\n\t\t\t\t\t\tsettings: t.Object({\n\t\t\t\t\t\t\ttheme: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\tcoerceFormData()\n\t\t\t)\n\n\t\t\t// Root should remain Object\n\t\t\texpect(result.type).toBe('object')\n\t\t\texpect(result.elysiaMeta).toBeUndefined()\n\n\t\t\t// File should remain as File\n\t\t\texpect(result.properties.avatar).toMatchObject({\n\t\t\t\ttype: 'string',\n\t\t\t\tformat: 'binary'\n\t\t\t})\n\n\t\t\t// First-level metadata should be ObjectString\n\t\t\texpect(result.properties.metadata).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\n\t\t\t// Nested tags array should remain plain Array (not converted)\n\t\t\tconst metadataObjBranch = result.properties.metadata.anyOf.find(\n\t\t\t\t(x: TSchema) => x.type === 'object'\n\t\t\t)\n\t\t\texpect(metadataObjBranch.properties.tags).toMatchObject({\n\t\t\t\ttype: 'array'\n\t\t\t})\n\t\t\texpect(metadataObjBranch.properties.tags.elysiaMeta).toBeUndefined()\n\n\t\t\t// Nested settings object should remain plain Object (not converted)\n\t\t\texpect(metadataObjBranch.properties.settings).toMatchObject({\n\t\t\t\ttype: 'object'\n\t\t\t})\n\t\t\texpect(metadataObjBranch.properties.settings.elysiaMeta).toBeUndefined()\n\t\t})\n\n\t\tit('should handle Object with Files (array) and nested structures', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\timages: t.Files(),\n\t\t\t\t\tdata: t.Object({\n\t\t\t\t\t\titems: t.Array(\n\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\tcoerceFormData()\n\t\t\t)\n\n\t\t\t// Files should remain as Files\n\t\t\texpect(result.properties.images).toMatchObject({\n\t\t\t\ttype: 'array',\n\t\t\t\titems: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tformat: 'binary'\n\t\t\t\t},\n\t\t\t\telysiaMeta: 'Files'\n\t\t\t})\n\n\t\t\t// First-level data should be ObjectString\n\t\t\texpect(result.properties.data).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\n\t\t\t// Nested items array should remain plain Array\n\t\t\tconst dataObjBranch = result.properties.data.anyOf.find(\n\t\t\t\t(x: TSchema) => x.type === 'object'\n\t\t\t)\n\t\t\texpect(dataObjBranch.properties.items).toMatchObject({\n\t\t\t\ttype: 'array'\n\t\t\t})\n\t\t\texpect(dataObjBranch.properties.items.elysiaMeta).toBeUndefined()\n\n\t\t\t// Array items (objects) should remain plain Objects\n\t\t\texpect(dataObjBranch.properties.items.items).toMatchObject({\n\t\t\t\ttype: 'object'\n\t\t\t})\n\t\t\texpect(dataObjBranch.properties.items.items.elysiaMeta).toBeUndefined()\n\t\t})\n\n\t\tit('should convert all first-level siblings', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tobj1: t.Object({ a: t.String() }),\n\t\t\t\t\tobj2: t.Object({ b: t.Number() }),\n\t\t\t\t\tarr1: t.Array(t.String()),\n\t\t\t\t\tarr2: t.Array(t.Number()),\n\t\t\t\t\tfile: t.File(),\n\t\t\t\t\tstr: t.String()\n\t\t\t\t}),\n\t\t\t\tcoerceFormData()\n\t\t\t)\n\n\t\t\t// All first-level objects should be ObjectString\n\t\t\texpect(result.properties.obj1).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\t\t\texpect(result.properties.obj2).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\n\t\t\t// All first-level arrays should be ArrayString\n\t\t\texpect(result.properties.arr1).toMatchObject({\n\t\t\t\telysiaMeta: 'ArrayString'\n\t\t\t})\n\t\t\texpect(result.properties.arr2).toMatchObject({\n\t\t\t\telysiaMeta: 'ArrayString'\n\t\t\t})\n\n\t\t\t// Other types should remain unchanged\n\t\t\texpect(result.properties.file).toMatchObject({\n\t\t\t\ttype: 'string',\n\t\t\t\tformat: 'binary'\n\t\t\t})\n\t\t\texpect(result.properties.str).toMatchObject({\n\t\t\t\ttype: 'string'\n\t\t\t})\n\t\t})\n\n\t\tit('should handle mixed nested structures correctly', () => {\n\t\t\tconst result = replaceSchemaType(\n\t\t\t\tt.Object({\n\t\t\t\t\tupload: t.File(),\n\t\t\t\t\tconfig: t.Object({\n\t\t\t\t\t\tnested: t.Object({\n\t\t\t\t\t\t\tdeep: t.Array(\n\t\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\t\tvalue: t.String()\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\tcoerceFormData()\n\t\t\t)\n\n\t\t\t// config should be ObjectString\n\t\t\texpect(result.properties.config).toMatchObject({\n\t\t\t\telysiaMeta: 'ObjectString'\n\t\t\t})\n\n\t\t\tconst configObjBranch = result.properties.config.anyOf.find(\n\t\t\t\t(x: TSchema) => x.type === 'object'\n\t\t\t)\n\n\t\t\t// nested should remain plain Object\n\t\t\texpect(configObjBranch.properties.nested).toMatchObject({\n\t\t\t\ttype: 'object'\n\t\t\t})\n\t\t\texpect(configObjBranch.properties.nested.elysiaMeta).toBeUndefined()\n\n\t\t\t// deep array should remain plain Array\n\t\t\texpect(configObjBranch.properties.nested.properties.deep).toMatchObject({\n\t\t\t\ttype: 'array'\n\t\t\t})\n\t\t\texpect(configObjBranch.properties.nested.properties.deep.elysiaMeta).toBeUndefined()\n\n\t\t\t// Array items should remain plain Objects\n\t\t\texpect(configObjBranch.properties.nested.properties.deep.items).toMatchObject({\n\t\t\t\ttype: 'object'\n\t\t\t})\n\t\t\texpect(configObjBranch.properties.nested.properties.deep.items.elysiaMeta).toBeUndefined()\n\t\t})\n\t})\n})\n"
  },
  {
    "path": "test/utils.d.ts",
    "content": "export declare const req: (path: string, options?: RequestInit) => import(\"undici-types\").Request;\ntype MaybeArray<T> = T | T[];\nexport declare const upload: (path: string, fields: Record<string, MaybeArray<(string & {}) | \"aris-yuzu.jpg\" | \"midori.png\" | \"millenium.jpg\">>) => {\n    request: import(\"undici-types\").Request;\n    size: number;\n};\nexport declare const post: (path: string, body?: Record<string, any>) => import(\"undici-types\").Request;\nexport declare const delay: (delay: number) => Promise<unknown>;\nexport {};\n"
  },
  {
    "path": "test/utils.ts",
    "content": "export const req = (path: string, options?: RequestInit) =>\n\tnew Request(`http://localhost${path}`, options)\n\ntype MaybeArray<T> = T | T[]\n\nexport const upload = (\n\tpath: string,\n\tfields: Record<\n\t\tstring,\n\t\tMaybeArray<\n\t\t\t| (string & {})\n\t\t\t| 'aris-yuzu.jpg'\n\t\t\t| 'midori.png'\n\t\t\t| 'millenium.jpg'\n\t\t\t| 'fake.jpg'\n\t\t\t| 'kozeki-ui.webp'\n\t\t>\n\t>\n) => {\n\tconst body = new FormData()\n\tlet size = 0\n\n\tfor (const [key, value] of Object.entries(fields)) {\n\t\tif (Array.isArray(value))\n\t\t\tvalue.forEach((value) => {\n\t\t\t\tconst file = Bun.file(`./test/images/${value}`)\n\t\t\t\tsize += file.size\n\t\t\t\tbody.append(key, file)\n\t\t\t})\n\t\telse if (value.includes('.')) {\n\t\t\tconst file = Bun.file(`./test/images/${value}`)\n\t\t\tsize += file.size\n\t\t\tbody.append(key, file)\n\t\t} else body.append(key, value)\n\t}\n\n\treturn {\n\t\trequest: new Request(`http://localhost${path}`, {\n\t\t\tmethod: 'POST',\n\t\t\tbody\n\t\t}),\n\t\tsize\n\t}\n}\n\nexport const post = (path: string, body?: string | Record<string, any>) =>\n\ttypeof body === 'string'\n\t\t? new Request(`http://localhost${path}`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'text/plain',\n\t\t\t\t\t'Content-Length': String(Buffer.byteLength(body))\n\t\t\t\t},\n\t\t\t\tbody\n\t\t\t})\n\t\t: new Request(`http://localhost${path}`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: body\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t\t\t'Content-Length': String(\n\t\t\t\t\t\t\t\tBuffer.byteLength(JSON.stringify(body))\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t: {},\n\t\t\t\tbody: body ? JSON.stringify(body) : body\n\t\t\t})\n\nexport const delay = (delay: number) =>\n\tnew Promise((resolve) => setTimeout(resolve, delay))\n"
  },
  {
    "path": "test/validator/body.test.ts",
    "content": "import { Elysia, t, ValidationError } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { post, upload } from '../utils'\n\ndescribe('Body Validator', () => {\n\tit('skip body parsing if body is empty but headers is present', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => 'ok')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('validate single', async () => {\n\t\tconst app = new Elysia().post('/', ({ body: { name } }) => name, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose'\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.text()).toBe('sucrose')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate multiple', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.String()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist',\n\t\t\t\ttrait: 'dog'\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist',\n\t\t\ttrait: 'dog'\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse without reference', async () => {\n\t\tconst app = new Elysia().post('/', () => '', {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.String()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist',\n\t\t\t\ttrait: 'dog'\n\t\t\t})\n\t\t)\n\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate optional', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.Optional(t.String())\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist'\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist'\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse single numeric', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.Optional(t.String()),\n\t\t\t\tage: t.Numeric()\n\t\t\t})\n\t\t})\n\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist',\n\t\t\t\tage: '16'\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist',\n\t\t\tage: 16\n\t\t})\n\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse multiple numeric', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.Optional(t.String()),\n\t\t\t\tage: t.Numeric(),\n\t\t\t\trank: t.Numeric()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist',\n\t\t\t\tage: '16',\n\t\t\t\trank: '4'\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist',\n\t\t\tage: 16,\n\t\t\trank: 4\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse single integer', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.Optional(t.String()),\n\t\t\t\tage: t.Integer()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist',\n\t\t\t\tage: '16'\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist',\n\t\t\tage: 16\n\t\t})\n\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse multiple integers', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.Optional(t.String()),\n\t\t\t\tage: t.Integer(),\n\t\t\t\trank: t.Integer()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist',\n\t\t\t\tage: '16',\n\t\t\t\trank: '4'\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist',\n\t\t\tage: 16,\n\t\t\trank: 4\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('rejects malformed integer from array object', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Array(\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tjob: t.String(),\n\t\t\t\t\ttrait: t.Optional(t.String()),\n\t\t\t\t\tage: t.Integer(),\n\t\t\t\t\trank: t.Integer()\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tpost('/', [\n\t\t\t\t{\n\t\t\t\t\tname: 'sucrose',\n\t\t\t\t\tjob: 'alchemist',\n\t\t\t\t\tage: 16.4,\n\t\t\t\t\trank: 4\n\t\t\t\t}\n\t\t\t])\n\t\t)\n\n\t\texpect(res.status).toBe(422)\n\t})\n\n\tit('rejects malformed integer directly in array', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Array(t.Integer())\n\t\t})\n\t\tconst res = await app.handle(post('/', [1, 2, 3, 4.2]))\n\n\t\texpect(res.status).toBe(422)\n\t})\n\tit('validate empty body', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Union([\n\t\t\t\tt.Undefined(),\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tjob: t.String(),\n\t\t\t\t\ttrait: t.Optional(t.String())\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST'\n\t\t\t})\n\t\t)\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('')\n\t})\n\n\tit('validate empty body with partial', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Union([\n\t\t\t\tt.Undefined(),\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tjob: t.String(),\n\t\t\t\t\ttrait: t.Optional(t.String()),\n\t\t\t\t\tage: t.Numeric(),\n\t\t\t\t\trank: t.Numeric()\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST'\n\t\t\t})\n\t\t)\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toEqual('')\n\t})\n\n\tit('normalize by default', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\n\t\tconst res = await app\n\t\t\t.handle(\n\t\t\t\tpost('/', {\n\t\t\t\t\tname: 'sucrose',\n\t\t\t\t\tjob: 'alchemist'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(res).toEqual({\n\t\t\tname: 'sucrose'\n\t\t})\n\t})\n\n\tit('strictly validate if not normalize', async () => {\n\t\tconst app = new Elysia({ normalize: false }).post(\n\t\t\t'/',\n\t\t\t({ body }) => body,\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist'\n\t\t\t})\n\t\t)\n\n\t\texpect(res.status).toBe(422)\n\t})\n\n\tit('validate maybe empty body', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.MaybeEmpty(\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tjob: t.String(),\n\t\t\t\t\ttrait: t.Optional(t.String())\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST'\n\t\t\t})\n\t\t)\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('')\n\t})\n\n\tit('validate record', async () => {\n\t\tconst app = new Elysia().post('/', ({ body: { name } }) => name, {\n\t\t\tbody: t.Record(t.String(), t.String())\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose'\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.text()).toBe('sucrose')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate record inside object', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/',\n\t\t\t({ body: { name, friends } }) =>\n\t\t\t\t`${name} ~ ${Object.keys(friends).join(' + ')}`,\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tfriends: t.Record(t.String(), t.String())\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose',\n\t\t\t\tfriends: {\n\t\t\t\t\tamber: 'wizard',\n\t\t\t\t\tlisa: 'librarian'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.text()).toBe('sucrose ~ amber + lisa')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate optional primitive', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body ?? 'sucrose', {\n\t\t\tbody: t.Optional(t.String())\n\t\t})\n\n\t\tconst [valid, invalid] = await Promise.all([\n\t\t\tapp.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'text/plain'\n\t\t\t\t\t},\n\t\t\t\t\tbody: 'sucrose'\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\tmethod: 'POST'\n\t\t\t\t})\n\t\t\t)\n\t\t])\n\n\t\texpect(await valid.text()).toBe('sucrose')\n\t\texpect(valid.status).toBe(200)\n\n\t\texpect(await invalid.text()).toBe('sucrose')\n\t\texpect(invalid.status).toBe(200)\n\t})\n\n\tit('validate optional object', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/',\n\t\t\t({ body }) => body?.name ?? 'sucrose',\n\t\t\t{\n\t\t\t\tbody: t.Optional(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst [valid, invalid] = await Promise.all([\n\t\t\tapp.handle(\n\t\t\t\tpost('/', {\n\t\t\t\t\tname: 'sucrose'\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\tmethod: 'POST'\n\t\t\t\t})\n\t\t\t)\n\t\t])\n\n\t\texpect(await valid.text()).toBe('sucrose')\n\t\texpect(valid.status).toBe(200)\n\n\t\texpect(await invalid.text()).toBe('sucrose')\n\t\texpect(invalid.status).toBe(200)\n\t})\n\n\tit('create default object body', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\tusername: t.String(),\n\t\t\t\tpassword: t.String(),\n\t\t\t\temail: t.Optional(t.String({ format: 'email' })),\n\t\t\t\tisSuperuser: t.Boolean({ default: false })\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\tpost('/', {\n\t\t\t\t\tusername: 'nagisa',\n\t\t\t\t\tpassword: 'hifumi_daisuki',\n\t\t\t\t\temail: 'kirifuji_nagisa@trinity.school'\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({\n\t\t\tusername: 'nagisa',\n\t\t\tpassword: 'hifumi_daisuki',\n\t\t\temail: 'kirifuji_nagisa@trinity.school',\n\t\t\tisSuperuser: false\n\t\t})\n\t})\n\n\tit('create default string body', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.String({ default: 'hifumi_daisuki' })\n\t\t})\n\n\t\tconst value = await app.handle(post('/')).then((x) => x.text())\n\n\t\texpect(value).toBe('hifumi_daisuki')\n\t})\n\n\tit('create default boolean body', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => typeof body, {\n\t\t\tbody: t.Boolean({ default: true })\n\t\t})\n\n\t\tconst value = await app.handle(post('/')).then((x) => x.text())\n\n\t\texpect(value).toBe('boolean')\n\t})\n\n\tit('create default number body', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => typeof body, {\n\t\t\tbody: t.Number({ default: 1 })\n\t\t})\n\n\t\tconst value = await app.handle(post('/')).then((x) => x.text())\n\n\t\texpect(value).toBe('number')\n\t})\n\n\tit('create default numeric body', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => typeof body, {\n\t\t\tbody: t.Numeric({ default: 1 })\n\t\t})\n\n\t\tconst value = await app.handle(post('/')).then((x) => x.text())\n\n\t\texpect(value).toBe('number')\n\t})\n\n\tit('coerce number to numeric', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => typeof body, {\n\t\t\tbody: t.Number()\n\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'text/plain'\n\t\t\t\t},\n\t\t\t\tbody: '1'\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit(\"don't coerce number object to numeric\", async () => {\n\t\tconst app = new Elysia().post('/', ({ body: { id } }) => typeof id, {\n\t\t\tbody: t.Object({\n\t\t\t\tid: t.Number()\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tid: '1'\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\t})\n\n\tit('coerce string to boolean', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => typeof body, {\n\t\t\tbody: t.Boolean()\n\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'text/plain'\n\t\t\t\t},\n\t\t\t\tbody: 'true'\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit(\"don't coerce string object to boolean\", async () => {\n\t\tconst app = new Elysia().post('/', ({ body: { id } }) => typeof id, {\n\t\t\tbody: t.Object({\n\t\t\t\tid: t.Boolean()\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tid: 'true'\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\t})\n\n\tit('handle optional at root', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Optional(\n\t\t\t\tt.Object({\n\t\t\t\t\tid: t.Numeric()\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(post('/')).then((x) => x.json()),\n\t\t\tapp\n\t\t\t\t.handle(\n\t\t\t\t\tpost('/', {\n\t\t\t\t\t\tid: 1\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t.then((x) => x.json())\n\t\t])\n\n\t\texpect(res).toEqual([{}, { id: 1 }])\n\t})\n\n\tit('parse query body with array', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body)\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('https://e.ly', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded'\n\t\t\t\t},\n\t\t\t\tbody: `tea_party=nagisa&tea_party=mika&tea_party=seia`\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\ttea_party: ['nagisa', 'mika', 'seia']\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate references', async () => {\n\t\tconst job = t.Object(\n\t\t\t{\n\t\t\t\tname: t.String()\n\t\t\t},\n\t\t\t{ $id: 'job' }\n\t\t)\n\n\t\tconst person = t.Object({\n\t\t\tname: t.String(),\n\t\t\tjob: t.Ref(job)\n\t\t})\n\n\t\tconst app = new Elysia()\n\t\t\t.model({ job, person })\n\t\t\t.post('/', ({ body: { name, job } }) => `${name} - ${job.name}`, {\n\t\t\t\tbody: person\n\t\t\t})\n\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: { name: 'alchemist' }\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.text()).toBe('sucrose - alchemist')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('handle file upload', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/single',\n\t\t\t({ body: { file } }) => file.size,\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tfile: t.File()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst { request, size } = upload('/single', {\n\t\t\tfile: 'millenium.jpg'\n\t\t})\n\n\t\tconst response = await app.handle(request).then((r) => r.text())\n\n\t\texpect(+response).toBe(size)\n\t})\n\n\tit('handle file upload using model reference', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\ta: t.Object({\n\t\t\t\t\tmessage: t.String(),\n\t\t\t\t\timage: t.Optional(t.Files())\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post('/', ({ body }) => 'ok', {\n\t\t\t\tbody: 'a'\n\t\t\t})\n\n\t\tconst { request } = upload('/', {\n\t\t\tmessage: 'Hello, world!'\n\t\t})\n\n\t\tconst status = await app.handle(request).then((r) => r.status)\n\n\t\texpect(status).toBe(200)\n\t})\n\n\tit('handle file prefix', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.post('/pass1', ({ body: { file } }) => file.size, {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tfile: t.File({\n\t\t\t\t\t\ttype: 'image/*'\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post('/pass2', ({ body: { file } }) => file.size, {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tfile: t.File({\n\t\t\t\t\t\ttype: ['application/*', 'image/*']\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post('/fail', ({ body: { file } }) => file.size, {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tfile: t.File({\n\t\t\t\t\t\ttype: 'application/*'\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\n\t\t{\n\t\t\tconst { request, size } = upload('/pass1', {\n\t\t\t\tfile: 'millenium.jpg'\n\t\t\t})\n\n\t\t\tconst response = await app.handle(request).then((r) => r.text())\n\t\t\texpect(+response).toBe(size)\n\t\t}\n\n\t\t{\n\t\t\tconst { request, size } = upload('/pass2', {\n\t\t\t\tfile: 'millenium.jpg'\n\t\t\t})\n\n\t\t\tconst response = await app.handle(request).then((r) => r.text())\n\t\t\t// expect(+response).toBe(size)\n\t\t}\n\n\t\t{\n\t\t\tconst { request } = upload('/fail', {\n\t\t\t\tfile: 'millenium.jpg'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(422)\n\t\t}\n\t})\n\n\tit('handle file type', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.post('/pass1', ({ body: { file } }) => file.size, {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tfile: t.File({\n\t\t\t\t\t\ttype: 'image/jpeg'\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post('/pass2', ({ body: { file } }) => file.size, {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tfile: t.File({\n\t\t\t\t\t\ttype: ['image/png', 'image/jpeg']\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post('/fail', ({ body: { file } }) => file.size, {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tfile: t.File({\n\t\t\t\t\t\ttype: 'image/png'\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\n\t\t{\n\t\t\tconst { request, size } = upload('/pass1', {\n\t\t\t\tfile: 'millenium.jpg'\n\t\t\t})\n\n\t\t\tconst response = await app.handle(request).then((r) => r.text())\n\t\t\texpect(+response).toBe(size)\n\t\t}\n\n\t\t{\n\t\t\tconst { request, size } = upload('/pass2', {\n\t\t\t\tfile: 'millenium.jpg'\n\t\t\t})\n\n\t\t\tconst response = await app.handle(request).then((r) => r.text())\n\t\t\texpect(+response).toBe(size)\n\t\t}\n\n\t\t{\n\t\t\tconst { request } = upload('/fail', {\n\t\t\t\tfile: 'millenium.jpg'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(422)\n\t\t}\n\t})\n\n\tit('validate actual file', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/upload',\n\t\t\t({ body: { file } }) => file.size,\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tfile: t.File({\n\t\t\t\t\t\ttype: 'image'\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\t{\n\t\t\tconst { request, size } = upload('/upload', {\n\t\t\t\tfile: 'millenium.jpg'\n\t\t\t})\n\n\t\t\tconst response = await app.handle(request).then((r) => r.text())\n\t\t\texpect(+response).toBe(size)\n\t\t}\n\n\t\t{\n\t\t\tconst { request, size } = upload('/upload', {\n\t\t\t\tfile: 'fake.jpg'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(422)\n\t\t}\n\t})\n\n\tit('validate actual file with multiple type', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/upload',\n\t\t\t({ body: { file } }) => file.size,\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tfile: t.File({\n\t\t\t\t\t\ttype: ['image/png', 'image/jpeg']\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\t{\n\t\t\tconst { request, size } = upload('/upload', {\n\t\t\t\tfile: 'millenium.jpg'\n\t\t\t})\n\n\t\t\tconst response = await app.handle(request).then((r) => r.text())\n\t\t\texpect(+response).toBe(size)\n\t\t}\n\n\t\t{\n\t\t\tconst { request, size } = upload('/upload', {\n\t\t\t\tfile: 'fake.jpg'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(422)\n\t\t}\n\n\t\t{\n\t\t\tconst { request, size } = upload('/upload', {\n\t\t\t\tfile: 'kozeki-ui.webp'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(422)\n\t\t}\n\t})\n\n\tit('validate actual file type union', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => 'ok', {\n\t\t\tbody: t.Union([\n\t\t\t\tt.Object({\n\t\t\t\t\thello: t.String(),\n\t\t\t\t\tfile: t.File({\n\t\t\t\t\t\ttype: 'image'\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\tt.Object({\n\t\t\t\t\tworld: t.String(),\n\t\t\t\t\timage: t.File({\n\t\t\t\t\t\ttype: 'image'\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\tt.Object({\n\t\t\t\t\tdonQuixote: t.String()\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\n\t\t// case 1 pass\n\t\t{\n\t\t\tconst { request, size } = upload('/', {\n\t\t\t\thello: 'ok',\n\t\t\t\tfile: 'millenium.jpg'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(200)\n\t\t}\n\n\t\t// case 1 fail\n\t\t{\n\t\t\tconst { request, size } = upload('/', {\n\t\t\t\thello: 'ok',\n\t\t\t\tfile: 'fake.jpg'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(422)\n\t\t}\n\n\t\t// case 2 pass\n\t\t{\n\t\t\tconst { request, size } = upload('/', {\n\t\t\t\tworld: 'ok',\n\t\t\t\timage: 'millenium.jpg'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(200)\n\t\t}\n\n\t\t// case 2 fail\n\t\t{\n\t\t\tconst { request, size } = upload('/', {\n\t\t\t\tworld: 'ok',\n\t\t\t\timage: 'fake.jpg'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(422)\n\t\t}\n\n\t\t// case 3 fail\n\t\t{\n\t\t\tconst { request, size } = upload('/', {\n\t\t\t\tdonQuixote: 'Limbus Company!'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(200)\n\t\t}\n\t})\n\n\tit('validate actual file type union with multiple file type', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => 'ok', {\n\t\t\tbody: t.Union([\n\t\t\t\tt.Object({\n\t\t\t\t\thello: t.String(),\n\t\t\t\t\tfile: t.File({\n\t\t\t\t\t\ttype: 'image'\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\tt.Object({\n\t\t\t\t\tworld: t.String(),\n\t\t\t\t\timage: t.File({\n\t\t\t\t\t\ttype: ['image/png', 'image/jpeg']\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\tt.Object({\n\t\t\t\t\tdonQuixote: t.String()\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\n\t\t// case 1 pass\n\t\t{\n\t\t\tconst { request, size } = upload('/', {\n\t\t\t\thello: 'ok',\n\t\t\t\tfile: 'millenium.jpg'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(200)\n\t\t}\n\n\t\t// case 1 fail\n\t\t{\n\t\t\tconst { request, size } = upload('/', {\n\t\t\t\thello: 'ok',\n\t\t\t\tfile: 'fake.jpg'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(422)\n\t\t}\n\n\t\t// case 2 pass\n\t\t{\n\t\t\tconst { request, size } = upload('/', {\n\t\t\t\tworld: 'ok',\n\t\t\t\timage: 'millenium.jpg'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(200)\n\t\t}\n\n\t\t// case 2 fail by fake image\n\t\t{\n\t\t\tconst { request, size } = upload('/', {\n\t\t\t\tworld: 'ok',\n\t\t\t\timage: 'fake.jpg'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(422)\n\t\t}\n\n\t\t// case 2 fail by incorrect image type\n\t\t{\n\t\t\tconst { request, size } = upload('/', {\n\t\t\t\tworld: 'ok',\n\t\t\t\timage: 'kozeki-ui.webp'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(422)\n\t\t}\n\n\t\t// case 3 fail\n\t\t{\n\t\t\tconst { request, size } = upload('/', {\n\t\t\t\tdonQuixote: 'Limbus Company!'\n\t\t\t})\n\n\t\t\tconst status = await app.handle(request).then((r) => r.status)\n\t\t\texpect(status).toBe(200)\n\t\t}\n\t})\n\n\tit('validate actual files', async () => {\n\t\tconst app = new Elysia().post('/', () => 'ok', {\n\t\t\tbody: t.Object({\n\t\t\t\tfile: t.Files({\n\t\t\t\t\ttype: 'image'\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\t// case 1 fail: contains fake image\n\t\t{\n\t\t\tconst body = new FormData()\n\t\t\tbody.append('file', Bun.file('test/images/fake.jpg'))\n\t\t\tbody.append('file', Bun.file('test/images/kozeki-ui.webp'))\n\n\t\t\tconst response = await app.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tbody\n\t\t\t\t})\n\t\t\t)\n\n\t\t\texpect(response.status).toBe(422)\n\t\t}\n\n\t\t// case 2 pass: all valid images\n\t\t{\n\t\t\tconst body = new FormData()\n\t\t\tbody.append('file', Bun.file('test/images/millenium.jpg'))\n\t\t\tbody.append('file', Bun.file('test/images/kozeki-ui.webp'))\n\n\t\t\tconst response = await app.handle(\n\t\t\t\tnew Request('http://localhost/', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tbody\n\t\t\t\t})\n\t\t\t)\n\n\t\t\texpect(response.status).toBe(200)\n\t\t}\n\t})\n\n\tit('handle body using Transform with Intersect ', async () => {\n\t\tconst app = new Elysia().post('/test', ({ body }) => body, {\n\t\t\tbody: t.Intersect([\n\t\t\t\tt.Object({ foo: t.String() }),\n\t\t\t\tt.Object({\n\t\t\t\t\tfield: t\n\t\t\t\t\t\t.Transform(t.String())\n\t\t\t\t\t\t.Decode((decoded) => ({ decoded }))\n\t\t\t\t\t\t.Encode((v) => v.decoded)\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost/test', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({ field: 'bar', foo: 'test' })\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({ field: { decoded: 'bar' }, foo: 'test' })\n\t})\n\n\tit('right rejects missed field with model', async () => {\n\t\tconst model = new Elysia().model(\n\t\t\t'user',\n\t\t\tt.Object({\n\t\t\t\tusername: t.String(),\n\t\t\t\tage: t.Integer()\n\t\t\t})\n\t\t)\n\n\t\tconst app = new Elysia().use(model).post('/', ({ body }) => body, {\n\t\t\tbody: 'user'\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tname: 'sucrose'\n\t\t\t})\n\t\t)\n\n\t\texpect(res.status).toBe(422)\n\t})\n\n\tit('handle coerce TransformDecodeError', async () => {\n\t\tlet err: Error | undefined\n\n\t\tconst app = new Elysia()\n\t\t\t.post('/', ({ body }) => body, {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tyear: t.Numeric({ minimum: 1900, maximum: 2160 })\n\t\t\t\t}),\n\t\t\t\terror({ code, error }) {\n\t\t\t\t\tswitch (code) {\n\t\t\t\t\t\tcase 'VALIDATION':\n\t\t\t\t\t\t\terr = error\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tawait app.handle(\n\t\t\tpost('/', {\n\t\t\t\tyear: '3000'\n\t\t\t})\n\t\t)\n\n\t\texpect(err instanceof ValidationError).toBe(true)\n\t})\n\n\tit('handle nested file upload with dot notation', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/',\n\t\t\t({ body }) => ({\n\t\t\t\tuserName: body.user.name,\n\t\t\t\tfileSize: body.user.avatar.size\n\t\t\t}),\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tuser: t.Object({\n\t\t\t\t\t\tname: t.String(),\n\t\t\t\t\t\tavatar: t.File()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst formData = new FormData()\n\t\tformData.append('user.name', 'John')\n\t\tformData.append('user.avatar', Bun.file('test/images/millenium.jpg'))\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tuserName: 'John',\n\t\t\tfileSize: expect.any(Number)\n\t\t})\n\t})\n\n\tit('handle nested files upload with dot notation', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/',\n\t\t\t({ body }) => ({\n\t\t\t\tproductName: body.product.name,\n\t\t\t\tfileSizes: body.product.images.map((f) => f.size)\n\t\t\t}),\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tproduct: t.Object({\n\t\t\t\t\t\tname: t.String(),\n\t\t\t\t\t\timages: t.Files()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst formData = new FormData()\n\t\tformData.append('product.name', 'Chair')\n\t\tformData.append('product.images', Bun.file('test/images/millenium.jpg'))\n\t\tformData.append('product.images', Bun.file('test/images/aris-yuzu.jpg'))\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tproductName: 'Chair',\n\t\t\tfileSizes: expect.arrayContaining([\n\t\t\t\texpect.any(Number),\n\t\t\t\texpect.any(Number)\n\t\t\t])\n\t\t})\n\t})\n\n\tit('handle deeply nested file upload', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/',\n\t\t\t({ body }) => ({\n\t\t\t\tbio: body.user.profile.bio,\n\t\t\t\tcountry: body.user.profile.country,\n\t\t\t\tphotoSize: body.user.profile.photo.size\n\t\t\t}),\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tuser: t.Object({\n\t\t\t\t\t\tprofile: t.Object({\n\t\t\t\t\t\t\tbio: t.String(),\n\t\t\t\t\t\t\tcountry: t.String(),\n\t\t\t\t\t\t\tphoto: t.File()\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst formData = new FormData()\n\t\tformData.append('user.profile.bio', 'Hello World')\n\t\tformData.append('user.profile.country', 'France')\n\t\tformData.append(\n\t\t\t'user.profile.photo',\n\t\t\tBun.file('test/images/millenium.jpg')\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tbio: 'Hello World',\n\t\t\tcountry: 'France',\n\t\t\tphotoSize: expect.any(Number)\n\t\t})\n\t})\n\n\tit('handle multiple nested files', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/',\n\t\t\t({ body }) => ({\n\t\t\t\tavatarSize: body.user.avatar.size,\n\t\t\t\tcoverSize: body.user.cover.size\n\t\t\t}),\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tuser: t.Object({\n\t\t\t\t\t\tavatar: t.File(),\n\t\t\t\t\t\tcover: t.File()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst formData = new FormData()\n\t\tformData.append('user.avatar', Bun.file('test/images/millenium.jpg'))\n\t\tformData.append('user.cover', Bun.file('test/images/kozeki-ui.webp'))\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tavatarSize: expect.any(Number),\n\t\t\tcoverSize: expect.any(Number)\n\t\t})\n\t})\n\n\tit('handle mixed nested and flat fields', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/',\n\t\t\t({ body }) => ({\n\t\t\t\tflatValue: body.flat,\n\t\t\t\tnestedName: body.user.name,\n\t\t\t\tnestedFileSize: body.user.avatar.size\n\t\t\t}),\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tflat: t.String(),\n\t\t\t\t\tuser: t.Object({\n\t\t\t\t\t\tname: t.String(),\n\t\t\t\t\t\tavatar: t.File()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst formData = new FormData()\n\t\tformData.append('flat', 'I am flat')\n\t\tformData.append('user.name', 'Jane')\n\t\tformData.append('user.avatar', Bun.file('test/images/millenium.jpg'))\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tflatValue: 'I am flat',\n\t\t\tnestedName: 'Jane',\n\t\t\tnestedFileSize: expect.any(Number)\n\t\t})\n\t})\n\n\tit('handle complex nested array with files', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/',\n\t\t\t({ body }) => ({\n\t\t\t\tproductName: body.name,\n\t\t\t\tcreateFilesCount: body.images.create.length,\n\t\t\t\tupdateCount: body.images.update.length,\n\t\t\t\timages: {\n\t\t\t\t\tcreate: body.images.create.map((f) => f.size),\n\t\t\t\t\tupdate: body.images.update.map((f) => ({\n\t\t\t\t\t\tid: f.id,\n\t\t\t\t\t\taltText: f.altText,\n\t\t\t\t\t\timgSize: f.img.size\n\t\t\t\t\t}))\n\t\t\t\t}\n\t\t\t}),\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\timages: t.Object({\n\t\t\t\t\t\tcreate: t.Files(),\n\t\t\t\t\t\tupdate: t.Array(\n\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\tid: t.String(),\n\t\t\t\t\t\t\t\timg: t.File(),\n\t\t\t\t\t\t\t\taltText: t.String()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst formData = new FormData()\n\t\tformData.append('name', 'Test Product')\n\t\tformData.append('images.create', Bun.file('test/images/millenium.jpg'))\n\t\tformData.append('images.create', Bun.file('test/images/kozeki-ui.webp'))\n\t\tformData.append('images.update[0].id', '123')\n\t\tformData.append(\n\t\t\t'images.update[0].img',\n\t\t\tBun.file('test/images/midori.png')\n\t\t)\n\t\tformData.append('images.update[0].altText', 'an image')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tproductName: 'Test Product',\n\t\t\tcreateFilesCount: 2,\n\t\t\tupdateCount: 1,\n\t\t\timages: {\n\t\t\t\tcreate: [expect.any(Number), expect.any(Number)],\n\t\t\t\tupdate: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: '123',\n\t\t\t\t\t\taltText: 'an image',\n\t\t\t\t\t\timgSize: expect.any(Number)\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}\n\t\t})\n\t})\n\n\tit('handle dot notation for standard schema with array and nested file', async () => {\n\t\tconst { z } = await import('zod')\n\n\t\tconst app = new Elysia().post(\n\t\t\t'/',\n\t\t\t({ body }) => ({\n\t\t\t\tupdateCount: body.images.update.length,\n\t\t\t\tupdates: body.images.update.map((item) => ({\n\t\t\t\t\tid: item.id,\n\t\t\t\t\taltText: item.altText,\n\t\t\t\t\timgSize: item.img.size\n\t\t\t\t}))\n\t\t\t}),\n\t\t\t{\n\t\t\t\tbody: z.object({\n\t\t\t\t\timages: z.object({\n\t\t\t\t\t\tupdate: z.array(\n\t\t\t\t\t\t\tz.object({\n\t\t\t\t\t\t\t\tid: z.string(),\n\t\t\t\t\t\t\t\timg: z.file(),\n\t\t\t\t\t\t\t\taltText: z.string()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst formData = new FormData()\n\t\tformData.append(\n\t\t\t'images.update[0]',\n\t\t\tJSON.stringify({ id: '123', altText: 'an image' })\n\t\t)\n\t\tformData.append(\n\t\t\t'images.update[0].img',\n\t\t\tBun.file('test/images/midori.png')\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tupdateCount: 1,\n\t\t\tupdates: [\n\t\t\t\t{\n\t\t\t\t\tid: '123',\n\t\t\t\t\taltText: 'an image',\n\t\t\t\t\timgSize: expect.any(Number)\n\t\t\t\t}\n\t\t\t]\n\t\t})\n\t})\n\n\tit('handle mix of stringify and dot notation', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/',\n\t\t\t({ body }) => ({\n\t\t\t\tproductName: body.name,\n\t\t\t\tmetadata: body.metadata,\n\t\t\t\tcreateFilesCount: body.images.create.length,\n\t\t\t\tupdateCount: body.images.update.length,\n\t\t\t\timages: {\n\t\t\t\t\tcreate: body.images.create.map((f) => f.size),\n\t\t\t\t\tupdate: body.images.update.map((f) => ({\n\t\t\t\t\t\tid: f.id,\n\t\t\t\t\t\taltText: f.altText,\n\t\t\t\t\t\timgSize: f.img.size\n\t\t\t\t\t}))\n\t\t\t\t}\n\t\t\t}),\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tmetadata: t.Object({\n\t\t\t\t\t\tdescription: t.String(),\n\t\t\t\t\t\tprice: t.Number(),\n\t\t\t\t\t\tinStock: t.Boolean(),\n\t\t\t\t\t\ttags: t.Array(t.String()),\n\t\t\t\t\t\tcategory: t.String()\n\t\t\t\t\t}),\n\t\t\t\t\timages: t.Object({\n\t\t\t\t\t\tcreate: t.Files(),\n\t\t\t\t\t\tupdate: t.Array(\n\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\tid: t.String(),\n\t\t\t\t\t\t\t\timg: t.File(),\n\t\t\t\t\t\t\t\taltText: t.String()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst formData = new FormData()\n\t\tformData.append('name', 'Test Product')\n\t\tformData.append(\n\t\t\t'metadata',\n\t\t\tJSON.stringify({\n\t\t\t\tdescription: 'A high-quality product',\n\t\t\t\tprice: 29.99,\n\t\t\t\tinStock: true,\n\t\t\t\ttags: ['electronics', 'featured', 'sale'],\n\t\t\t\tcategory: 'gadgets'\n\t\t\t})\n\t\t)\n\t\tformData.append('images.create', Bun.file('test/images/millenium.jpg'))\n\t\tformData.append('images.create', Bun.file('test/images/kozeki-ui.webp'))\n\t\tformData.append(\n\t\t\t'images.update[0]',\n\t\t\tJSON.stringify({ id: '123', altText: 'an image' })\n\t\t)\n\t\tformData.append(\n\t\t\t'images.update[0].img',\n\t\t\tBun.file('test/images/midori.png')\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tproductName: 'Test Product',\n\t\t\tcreateFilesCount: 2,\n\t\t\tupdateCount: 1,\n\t\t\tmetadata: {\n\t\t\t\tdescription: 'A high-quality product',\n\t\t\t\tprice: 29.99,\n\t\t\t\tinStock: true,\n\t\t\t\ttags: ['electronics', 'featured', 'sale'],\n\t\t\t\tcategory: 'gadgets'\n\t\t\t},\n\t\t\timages: {\n\t\t\t\tcreate: [expect.any(Number), expect.any(Number)],\n\t\t\t\tupdate: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: '123',\n\t\t\t\t\t\taltText: 'an image',\n\t\t\t\t\t\timgSize: expect.any(Number)\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}\n\t\t})\n\t})\n\n\tit('should parse sub-array correctly', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body, {\n\t\t\tbody: t.Object({\n\t\t\t\timagesOps: t.Object({\n\t\t\t\t\toptions: t.Array(\n\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\tid: t.String(),\n\t\t\t\t\t\t\tvalue: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tconst formData = new FormData()\n\t\tformData.append(\n\t\t\t'imagesOps.options',\n\t\t\tJSON.stringify([{ id: 'test-id', value: 'test-value' }])\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\tconst result = (await response.json()) as any\n\t\texpect(result.imagesOps.options).toEqual([\n\t\t\t{ id: 'test-id', value: 'test-value' }\n\t\t])\n\t})\n\n\tit('prevent prototype pollution with __proto__ in nested multipart', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body)\n\n\t\tconst formData = new FormData()\n\t\tformData.append('user.name', 'John')\n\t\tformData.append('__proto__.isAdmin', 'true')\n\t\tformData.append('user.__proto__.isAdmin', 'true')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tuser: { name: 'John' }\n\t\t})\n\n\t\t// Check that Object.prototype wasn't polluted\n\t\tconst testObj = {}\n\t\texpect('isAdmin' in testObj).toBe(false)\n\t\texpect('isAdmin' in {}).toBe(false)\n\t})\n\n\tit('prevent prototype pollution with constructor in nested multipart', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body)\n\n\t\tconst formData = new FormData()\n\t\tformData.append('user.name', 'John')\n\t\tformData.append('constructor.prototype.isAdmin', 'true')\n\t\tformData.append('user.constructor', 'bad')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\tuser: { name: 'John' }\n\t\t})\n\n\t\t// Check that Object.prototype wasn't polluted\n\t\texpect('isAdmin' in {}).toBe(false)\n\t})\n\n\tit('prevent prototype pollution in array notation', async () => {\n\t\tconst app = new Elysia().post('/', ({ body }) => body)\n\n\t\tconst formData = new FormData()\n\t\tformData.append('items[0].name', 'Item 1')\n\t\tformData.append('items[__proto__].isAdmin', 'true')\n\t\tformData.append('__proto__[0]', 'bad')\n\n\t\tconst response = await app.handle(\n\t\t\tnew Request('http://localhost/', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: formData\n\t\t\t})\n\t\t)\n\n\t\tconst result = await response.json()\n\t\texpect(response.status).toBe(200)\n\t\texpect(result).toMatchObject({\n\t\t\titems: [{ name: 'Item 1' }]\n\t\t})\n\n\t\t// Check that Object.prototype wasn't polluted\n\t\tconst testObj = {}\n\t\texpect('isAdmin' in testObj).toBe(false)\n\t})\n})\n"
  },
  {
    "path": "test/validator/cookie.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Elysia, t } from '../../src'\nimport { req } from '../utils'\n\ndescribe('Cookie Validation', () => {\n\tit('validate required cookie', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { session } }) => session.value,\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tsession: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst [valid, invalid] = await Promise.all([\n\t\t\tapp.handle(req('/', { headers: { Cookie: 'session=value' } })),\n\t\t\tapp.handle(req('/'))\n\t\t])\n\n\t\texpect(valid.status).toBe(200)\n\t\texpect(await valid.text()).toBe('value')\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate optional cookie', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { session } }) => session.value ?? 'empty',\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tsession: t.Optional(t.String())\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst [withCookie, withoutCookie] = await Promise.all([\n\t\t\tapp.handle(req('/', { headers: { Cookie: 'session=value' } })),\n\t\t\tapp.handle(req('/'))\n\t\t])\n\n\t\texpect(withCookie.status).toBe(200)\n\t\texpect(await withCookie.text()).toBe('value')\n\t\texpect(withoutCookie.status).toBe(200)\n\t\texpect(await withoutCookie.text()).toBe('empty')\n\t})\n\n\tit('validate cookie type - numeric', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { count } }) => count.value,\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tcount: t.Numeric()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst [valid, invalid] = await Promise.all([\n\t\t\tapp.handle(req('/', { headers: { Cookie: 'count=42' } })),\n\t\t\tapp.handle(req('/', { headers: { Cookie: 'count=invalid' } }))\n\t\t])\n\n\t\texpect(valid.status).toBe(200)\n\t\texpect(await valid.text()).toBe('42')\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate cookie type - boolean', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { active } }) => active.value,\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tactive: t.BooleanString()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst [validTrue, validFalse, invalid] = await Promise.all([\n\t\t\tapp.handle(req('/', { headers: { Cookie: 'active=true' } })),\n\t\t\tapp.handle(req('/', { headers: { Cookie: 'active=false' } })),\n\t\t\tapp.handle(req('/', { headers: { Cookie: 'active=maybe' } }))\n\t\t])\n\n\t\texpect(validTrue.status).toBe(200)\n\t\texpect(await validTrue.text()).toBe('true')\n\t\texpect(validFalse.status).toBe(200)\n\t\texpect(await validFalse.text()).toBe('false')\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate cookie with object schema', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { profile } }) => profile.value.name,\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tprofile: t.Object({\n\t\t\t\t\t\tname: t.String(),\n\t\t\t\t\t\tage: t.Numeric()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst valid = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tCookie:\n\t\t\t\t\t\t'profile=' +\n\t\t\t\t\t\tencodeURIComponent(\n\t\t\t\t\t\t\tJSON.stringify({ name: 'Himari', age: 16 })\n\t\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\tconst invalid = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tCookie:\n\t\t\t\t\t\t'profile=' +\n\t\t\t\t\t\tencodeURIComponent(JSON.stringify({ name: 'Himari' }))\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(valid.status).toBe(200)\n\t\texpect(await valid.text()).toBe('Himari')\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate multiple cookies', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { session, userId } }) =>\n\t\t\t\t`${session.value}:${userId.value}`,\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tsession: t.String(),\n\t\t\t\t\tuserId: t.Numeric()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst [valid, missingSession, missingUserId, invalidUserId] =\n\t\t\tawait Promise.all([\n\t\t\t\tapp.handle(\n\t\t\t\t\treq('/', {\n\t\t\t\t\t\theaders: { Cookie: 'session=abc123; userId=42' }\n\t\t\t\t\t})\n\t\t\t\t),\n\t\t\t\tapp.handle(\n\t\t\t\t\treq('/', {\n\t\t\t\t\t\theaders: { Cookie: 'userId=42' }\n\t\t\t\t\t})\n\t\t\t\t),\n\t\t\t\tapp.handle(\n\t\t\t\t\treq('/', {\n\t\t\t\t\t\theaders: { Cookie: 'session=abc123' }\n\t\t\t\t\t})\n\t\t\t\t),\n\t\t\t\tapp.handle(\n\t\t\t\t\treq('/', {\n\t\t\t\t\t\theaders: { Cookie: 'session=abc123; userId=invalid' }\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t])\n\n\t\texpect(valid.status).toBe(200)\n\t\texpect(await valid.text()).toBe('abc123:42')\n\t\texpect(missingSession.status).toBe(422)\n\t\texpect(missingUserId.status).toBe(422)\n\t\texpect(invalidUserId.status).toBe(422)\n\t})\n\n\tit('validate cookie with string constraints', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { token } }) => token.value,\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\ttoken: t.String({ minLength: 10, maxLength: 50 })\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst [valid, tooShort, tooLong] = await Promise.all([\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: { Cookie: 'token=validtoken123' }\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: { Cookie: 'token=short' }\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: { Cookie: 'token=' + 'a'.repeat(51) }\n\t\t\t\t})\n\t\t\t)\n\t\t])\n\n\t\texpect(valid.status).toBe(200)\n\t\texpect(tooShort.status).toBe(422)\n\t\texpect(tooLong.status).toBe(422)\n\t})\n\n\tit('validate cookie with numeric constraints', async () => {\n\t\tconst app = new Elysia().get('/', ({ cookie: { age } }) => age.value, {\n\t\t\tcookie: t.Cookie({\n\t\t\t\tage: t.Numeric({ minimum: 0, maximum: 120 })\n\t\t\t})\n\t\t})\n\n\t\tconst [valid, tooLow, tooHigh] = await Promise.all([\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: { Cookie: 'age=25' }\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: { Cookie: 'age=-1' }\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: { Cookie: 'age=150' }\n\t\t\t\t})\n\t\t\t)\n\t\t])\n\n\t\texpect(valid.status).toBe(200)\n\t\texpect(await valid.text()).toBe('25')\n\t\texpect(tooLow.status).toBe(422)\n\t\texpect(tooHigh.status).toBe(422)\n\t})\n\n\tit('validate cookie with pattern', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { email } }) => email.value,\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\temail: t.String({ format: 'email' })\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst [valid, invalid] = await Promise.all([\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: { Cookie: 'email=user@example.com' }\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: { Cookie: 'email=notanemail' }\n\t\t\t\t})\n\t\t\t)\n\t\t])\n\n\t\texpect(valid.status).toBe(200)\n\t\texpect(await valid.text()).toBe('user@example.com')\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate cookie with transform', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { timestamp } }) => timestamp.value,\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\ttimestamp: t\n\t\t\t\t\t\t.Transform(t.String())\n\t\t\t\t\t\t.Decode((value) => new Date(value))\n\t\t\t\t\t\t.Encode((value) => value.toISOString())\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst date = new Date('2024-01-01T00:00:00.000Z')\n\t\tconst response = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: { Cookie: `timestamp=${date.toISOString()}` }\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t})\n\n\tit('validate optional cookie with isOptional check', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie }) => {\n\t\t\t\tconst keys = Object.keys(cookie)\n\t\t\t\treturn keys.length > 0 ? 'has cookies' : 'no cookies'\n\t\t\t},\n\t\t\t{\n\t\t\t\tcookie: t.Optional(\n\t\t\t\t\tt.Cookie({\n\t\t\t\t\t\tsession: t.Optional(t.String())\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst [withCookie, withoutCookie] = await Promise.all([\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: { Cookie: 'session=value' }\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(req('/'))\n\t\t])\n\n\t\texpect(withCookie.status).toBe(200)\n\t\texpect(withoutCookie.status).toBe(200)\n\t})\n\n\tit('validate cookie with array type', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { tags } }) => tags.value.join(','),\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\ttags: t.Array(t.String())\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tCookie:\n\t\t\t\t\t\t'tags=' +\n\t\t\t\t\t\tencodeURIComponent(\n\t\t\t\t\t\t\tJSON.stringify(['tag1', 'tag2', 'tag3'])\n\t\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.text()).toBe('tag1,tag2,tag3')\n\t})\n\n\tit('validate cookie with union type', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { value } }) => String(value.value),\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tvalue: t.Union([t.String(), t.Numeric()])\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst [stringValue, numericValue, invalid] = await Promise.all([\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: { Cookie: 'value=text' }\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: { Cookie: 'value=123' }\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tCookie:\n\t\t\t\t\t\t\t'value=' +\n\t\t\t\t\t\t\tencodeURIComponent(JSON.stringify({ obj: true }))\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t])\n\n\t\texpect(stringValue.status).toBe(200)\n\t\texpect(numericValue.status).toBe(200)\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('inherits cookie validation on guard', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tcookie: t.Cookie({ session: t.String() })\n\t\t\t})\n\t\t\t.get('/', ({ cookie: { session } }) => session.value)\n\t\t\t.get(\n\t\t\t\t'/profile',\n\t\t\t\t({ cookie: { session } }) => `Profile: ${session.value}`\n\t\t\t)\n\n\t\tconst [validRoot, validProfile, invalid] = await Promise.all([\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: { Cookie: 'session=abc123' }\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(\n\t\t\t\treq('/profile', {\n\t\t\t\t\theaders: { Cookie: 'session=abc123' }\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(req('/'))\n\t\t])\n\n\t\texpect(validRoot.status).toBe(200)\n\t\texpect(await validRoot.text()).toBe('abc123')\n\t\texpect(validProfile.status).toBe(200)\n\t\texpect(await validProfile.text()).toBe('Profile: abc123')\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('merge cookie config from app', async () => {\n\t\tconst app = new Elysia({\n\t\t\tcookie: {\n\t\t\t\thttpOnly: true,\n\t\t\t\tsecure: true\n\t\t\t}\n\t\t}).get('/', ({ cookie: { session } }) => session.value ?? 'empty', {\n\t\t\tcookie: t.Cookie({\n\t\t\t\tsession: t.Optional(t.String())\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: { Cookie: 'session=test' }\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.text()).toBe('test')\n\t})\n\n\tit('validate empty cookie object when optional', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie }) =>\n\t\t\t\tObject.keys(cookie).length === 0 ? 'empty' : 'not empty',\n\t\t\t{\n\t\t\t\tcookie: t.Optional(\n\t\t\t\t\tt.Cookie({\n\t\t\t\t\t\tsession: t.Optional(t.String())\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.text()).toBe('empty')\n\t})\n\n\tit('expires setter compares timestamps not Date objects', async () => {\n\t\tconst app = new Elysia().get('/', ({ cookie: { session }, set }) => {\n\t\t\t// Test 1: Setting expires with same timestamp should not update\n\t\t\tconst date1 = new Date('2025-12-31T23:59:59.000Z')\n\t\t\tconst date2 = new Date('2025-12-31T23:59:59.000Z')\n\n\t\t\tsession.value = 'test'\n\t\t\tsession.expires = date1\n\n\t\t\t// Get reference to jar before setting with same timestamp\n\t\t\tconst jarBefore = set.cookie\n\t\t\tsession.expires = date2 // Same timestamp, should not update\n\t\t\tconst jarAfter = set.cookie\n\n\t\t\t// Verify jar wasn't recreated (same reference)\n\t\t\texpect(jarBefore).toBe(jarAfter)\n\t\t\texpect(session.expires?.getTime()).toBe(date1.getTime())\n\n\t\t\t// Test 2: Setting expires with different timestamp should update\n\t\t\tconst date3 = new Date('2026-01-01T00:00:00.000Z')\n\t\t\tsession.expires = date3\n\t\t\texpect(session.expires?.getTime()).toBe(date3.getTime())\n\n\t\t\t// Test 3: Both undefined should not update\n\t\t\tsession.expires = undefined\n\t\t\tconst jarBeforeUndefined = set.cookie\n\t\t\tsession.expires = undefined\n\t\t\tconst jarAfterUndefined = set.cookie\n\t\t\texpect(jarBeforeUndefined).toBe(jarAfterUndefined)\n\n\t\t\treturn 'ok'\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.text()).toBe('ok')\n\t})\n\n\tit('parse cookie with secrets into object when available', async () => {\n\t\tconst challengeModel = t.Object({\n\t\t\tnonce: t.String(),\n\t\t\tissued: t.Number(),\n\t\t\tbits: t.Number()\n\t\t})\n\n\t\tconst issued = Date.now()\n\n\t\tconst app = new Elysia({\n\t\t\tcookie: {\n\t\t\t\tsecrets: 'a',\n\t\t\t\tsign: ['challenge']\n\t\t\t}\n\t\t})\n\t\t\t.get(\n\t\t\t\t'/set',\n\t\t\t\t({ cookie: { challenge } }) => {\n\t\t\t\t\tchallenge.value = {\n\t\t\t\t\t\tnonce: 'hello',\n\t\t\t\t\t\tbits: 19,\n\t\t\t\t\t\tissued\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\t\tchallenge: t.Optional(challengeModel)\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\t\t\t.get(\n\t\t\t\t'/get',\n\t\t\t\t({ cookie: { challenge } }) => {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: typeof challenge,\n\t\t\t\t\t\tvalue: challenge.value\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\t\tchallenge: challengeModel\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst cookie = await app\n\t\t\t.handle(req('/set'))\n\t\t\t.then((x) => x.headers.get('set-cookie'))\n\n\t\tconst challenge = cookie!.match(/challenge=([^;]*)/)![1]\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\treq('/get', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tcookie: `challenge=${challenge}`\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\ttype: 'object',\n\t\t\tvalue: {\n\t\t\t\tnonce: 'hello',\n\t\t\t\tbits: 19,\n\t\t\t\tissued\n\t\t\t}\n\t\t})\n\t})\n\n\tit('handle graceful cookie transition from non signed to signed', async () => {\n\t\tconst challengeModel = t.Object({\n\t\t\tnonce: t.String(),\n\t\t\tissued: t.Number(),\n\t\t\tbits: t.Number()\n\t\t})\n\n\t\tconst issued = Date.now()\n\n\t\tconst app = new Elysia({\n\t\t\tcookie: {\n\t\t\t\tsecrets: ['a', null],\n\t\t\t\tsign: 'challenge'\n\t\t\t}\n\t\t}).get(\n\t\t\t'/',\n\t\t\t({ cookie: { challenge } }) => {\n\t\t\t\tchallenge.value = {\n\t\t\t\t\tnonce: 'hello',\n\t\t\t\t\tbits: 19,\n\t\t\t\t\tissued\n\t\t\t\t}\n\n\t\t\t\treturn challenge.value\n\t\t\t},\n\t\t\t{\n\t\t\t\tcookie: t.Cookie({\n\t\t\t\t\tchallenge: t.Optional(challengeModel)\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst first = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: `challenge=${JSON.stringify({\n\t\t\t\t\t\tnonce: 'hello',\n\t\t\t\t\t\tbits: 19,\n\t\t\t\t\t\tissued: 1770750432990\n\t\t\t\t\t})}`\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(first.status).toBe(200)\n\t\texpect(await first.json()).toEqual({\n\t\t\tnonce: 'hello',\n\t\t\tbits: 19,\n\t\t\tissued\n\t\t})\n\n\t\tconst cookie = first.headers.get('set-cookie')\n\t\tconst challenge = cookie!.match(/challenge=([^;]*)/)![1]\n\n\t\t// contains signature\n\t\texpect(challenge).toInclude('.')\n\n\t\tconst second = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tcookie: `challenge=${challenge}`\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(second.status).toBe(200)\n\t})\n\n\tit('handle prototype pollution', () => {\n\t\tconst app = new Elysia().get('/profile', ({ cookie }) => {\n\t\t\tconst proto = Object.getPrototypeOf(cookie)\n\t\t\tconst protoIsClean = proto === Object.prototype || proto === null\n\t\t\treturn {\n\t\t\t\thasPhantomValue: 'value' in cookie,\n\t\t\t\tprototypeIsClean: protoIsClean,\n\t\t\t\tprototype: proto,\n\t\t\t\tenumeratedKeys: (() => {\n\t\t\t\t\tconst keys: string[] = []\n\t\t\t\t\tfor (const k in cookie) keys.push(k)\n\t\t\t\t\treturn keys\n\t\t\t\t})()\n\t\t\t}\n\t\t})\n\n\t\texpect(\n\t\t\tapp\n\t\t\t\t.handle(\n\t\t\t\t\tnew Request('http://localhost/profile', {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tcookie: 'a=hi;__proto__=%7B%22injected%22%3A%22polluted%22%7D'\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t.then((x) => x.json())\n\t\t).resolves.toEqual({\n\t\t\thasPhantomValue: false,\n\t\t\tprototypeIsClean: true,\n\t\t\tprototype: null,\n\t\t\tenumeratedKeys: ['a']\n\t\t})\n\t})\n\n\tit('transform cookie value', async () => {\n\t\tlet innerValue: any = null\n\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ cookie: { thing } }) => {\n\t\t\t\tinnerValue = thing.value\n\n\t\t\t\treturn thing.value\n\t\t\t},\n\t\t\t{\n\t\t\t\tcookie: t.Object({\n\t\t\t\t\tthing: t.Number()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost:3000/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tcookie: 'thing=9'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((response) => response.json())\n\n\t\texpect(value).toBe(9)\n\t\texpect(typeof value).toBe('number')\n\n\t\texpect(innerValue).toBe(9)\n\t\texpect(typeof innerValue).toBe('number')\n\t})\n})\n"
  },
  {
    "path": "test/validator/encode.test.ts",
    "content": "import { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('Encode response', () => {\n\tit('handle default status', async () => {\n\t\tconst app = new Elysia({\n\t\t\tencodeSchema: true\n\t\t}).get(\n\t\t\t'/',\n\t\t\t() => ({\n\t\t\t\tid: 'hello world'\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tid: t\n\t\t\t\t\t\t.Transform(t.String())\n\t\t\t\t\t\t.Decode((v) => v)\n\t\t\t\t\t\t.Encode(() => 'encoded')\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tid: 'encoded'\n\t\t})\n\t})\n\n\tit('handle default named status', async () => {\n\t\tconst app = new Elysia({\n\t\t\tencodeSchema: true\n\t\t}).get(\n\t\t\t'/:id',\n\t\t\t({ status, params: { id } }) =>\n\t\t\t\tstatus(id as any, {\n\t\t\t\t\tid: 'hello world'\n\t\t\t\t}),\n\t\t\t{\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tid: t.Number()\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.Object({\n\t\t\t\t\t\tid: t\n\t\t\t\t\t\t\t.Transform(t.String())\n\t\t\t\t\t\t\t.Decode((v) => v)\n\t\t\t\t\t\t\t.Encode(() => 'encoded 200')\n\t\t\t\t\t}),\n\t\t\t\t\t418: t.Object({\n\t\t\t\t\t\tid: t\n\t\t\t\t\t\t\t.Transform(t.String())\n\t\t\t\t\t\t\t.Decode((v) => v)\n\t\t\t\t\t\t\t.Encode(() => 'encoded 418')\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/200')).then((x) => x.json()),\n\t\t\tapp.handle(req('/418')).then((x) => x.json())\n\t\t])\n\n\t\texpect(response[0]).toEqual({\n\t\t\tid: 'encoded 200'\n\t\t})\n\n\t\texpect(response[1]).toEqual({\n\t\t\tid: 'encoded 418'\n\t\t})\n\t})\n\n\tit('Encode before type check', async () => {\n\t\tconst dto = t.Object({\n\t\t\tvalue: t\n\t\t\t\t.Transform(t.String())\n\t\t\t\t.Decode((value) => parseFloat(value))\n\t\t\t\t.Encode((value) => value.toString())\n\t\t})\n\n\t\tlet bodyType = ''\n\n\t\tconst elysia = new Elysia({\n\t\t\texperimental: {\n\t\t\t\tencodeSchema: true //open the flag!\n\t\t\t}\n\t\t}).post(\n\t\t\t'/',\n\t\t\t({ body }) => {\n\t\t\t\tbodyType = typeof body.value\n\n\t\t\t\treturn body\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: dto,\n\t\t\t\tresponse: dto\n\t\t\t}\n\t\t)\n\n\t\tconst response = await elysia\n\t\t\t.handle(\n\t\t\t\tnew Request('http://localhost:3000/', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({ value: '1.1' })\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((res) => res)\n\n\t\texpect(bodyType).toBe('number')\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.json()).toEqual({ value: '1.1' })\n\t})\n})\n"
  },
  {
    "path": "test/validator/exact-mirror.test.ts",
    "content": "import { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { post, req } from '../utils'\n\ndescribe('Exact Mirror', () => {\n\tit('normalize when t.Transform is provided', async () => {\n\t\tconst app = new Elysia({\n\t\t\tnormalize: 'exactMirror'\n\t\t}).get('/', () => ({ count: 2, name: 'foo', extra: 1 }), {\n\t\t\tresponse: t.Object(\n\t\t\t\t{ name: t.String(), count: t.Optional(t.Integer()) },\n\t\t\t\t{ additionalProperties: false }\n\t\t\t)\n\t\t})\n\t})\n\n\tit('leave incorrect union field as-is', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/test',\n\t\t\t({ body }) => {\n\t\t\t\tconsole.log({ body })\n\n\t\t\t\treturn 'Hello Elysia'\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tfoo: t.Optional(\n\t\t\t\t\t\tt.Nullable(\n\t\t\t\t\t\t\tt.Number({\n\t\t\t\t\t\t\t\t// 'foo' but be either number, optional or nullable\n\t\t\t\t\t\t\t\terror: 'Must be a number'\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(\n\t\t\tpost('/test', {\n\t\t\t\tfoo: 'asd'\n\t\t\t})\n\t\t)\n\n\t\texpect(response.status).toEqual(422)\n\t})\n\n\tit('normalize array response', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => {\n\t\t\t\treturn {\n\t\t\t\t\tmessages: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmessage: 'Hello, world!',\n\t\t\t\t\t\t\tshouldBeRemoved: true\n\t\t\t\t\t\t}\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.Object({\n\t\t\t\t\t\tmessages: t.Array(\n\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\tmessage: t.String()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tmessages: [{ message: 'Hello, world!' }]\n\t\t})\n\t})\n\n\tit('normalize t.Array with t.Omit(t.Union) elements', async () => {\n\t\tconst SharedSchemaA = t.Object({ qux: t.Literal('a') })\n\t\tconst SharedSchemaB = t.Object({ qux: t.Literal('b') })\n\t\tconst SchemaA = t.Object({ foo: t.Number() })\n\t\tconst SchemaB = t.Object({ foo: t.Number(), baz: t.Boolean() })\n\n\t\tconst IntersectSchemaA = t.Intersect([SchemaA, SharedSchemaA])\n\t\tconst IntersectSchemaB = t.Intersect([SchemaB, SharedSchemaB])\n\n\t\tconst UnionSchema = t.Union([IntersectSchemaA, IntersectSchemaB])\n\t\tconst OmittedUnionSchema = t.Omit(UnionSchema, ['baz'])\n\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t// @ts-ignore\n\t\t\t() => [{ bar: 'asd', baz: true, qux: 'b', foo: 1 }],\n\t\t\t{ response: t.Array(OmittedUnionSchema) }\n\t\t)\n\n\t\tconst response = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(response).toEqual([{ qux: 'b', foo: 1 }])\n\t})\n\n\tit('normalize t.Omit(t.Union) response', async () => {\n\t\tconst SchemaA = t.Object({ foo: t.Number() })\n\t\tconst SchemaB = t.Object({ foo: t.Number(), baz: t.Boolean() })\n\n\t\tconst UnionSchema = t.Union([SchemaA, SchemaB])\n\t\tconst OmittedUnionSchema = t.Omit(UnionSchema, ['baz'])\n\n\t\tconst app = new Elysia().get('/', () => ({ baz: true, foo: 1 }), {\n\t\t\tresponse: OmittedUnionSchema\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.json()).toEqual({ foo: 1 })\n\t})\n\n\tit('normalize t.Omit(t.Union) with multiple status codes', async () => {\n\t\tconst SchemaA = t.Object({ foo: t.Number() })\n\t\tconst SchemaB = t.Object({ foo: t.Number(), baz: t.Boolean() })\n\n\t\tconst UnionSchema = t.Union([SchemaA, SchemaB])\n\t\tconst OmittedUnionSchema = t.Omit(UnionSchema, ['baz'])\n\n\t\tconst app = new Elysia().get('/', () => ({ baz: true, foo: 1 }), {\n\t\t\tresponse: {\n\t\t\t\t200: OmittedUnionSchema\n\t\t\t}\n\t\t})\n\n\t\tconst response = await app.handle(req('/'))\n\n\t\texpect(response.status).toBe(200)\n\t\texpect(await response.json()).toEqual({ foo: 1 })\n\t})\n})\n"
  },
  {
    "path": "test/validator/header.test.ts",
    "content": "import { Elysia, t, ValidationError } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('Header Validator', () => {\n\tit('validate single', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers: { name } }) => name, {\n\t\t\theaders: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tname: 'sucrose'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.text()).toBe('sucrose')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate multiple', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.String()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tname: 'sucrose',\n\t\t\t\t\tjob: 'alchemist',\n\t\t\t\t\ttrait: 'dog'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist',\n\t\t\ttrait: 'dog'\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse without reference', async () => {\n\t\tconst app = new Elysia().get('/', () => '', {\n\t\t\theaders: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.String()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tname: 'sucrose',\n\t\t\t\t\tjob: 'alchemist',\n\t\t\t\t\ttrait: 'dog'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate optional', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.Optional(t.String())\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tname: 'sucrose',\n\t\t\t\t\tjob: 'alchemist'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist'\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse single numeric', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.Optional(t.String()),\n\t\t\t\tage: t.Numeric()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tname: 'sucrose',\n\t\t\t\t\tjob: 'alchemist',\n\t\t\t\t\tage: '16'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist',\n\t\t\tage: 16\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse multiple numeric', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.Optional(t.String()),\n\t\t\t\tage: t.Numeric(),\n\t\t\t\trank: t.Numeric()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tname: 'sucrose',\n\t\t\t\t\tjob: 'alchemist',\n\t\t\t\t\tage: '16',\n\t\t\t\t\trank: '4'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist',\n\t\t\tage: 16,\n\t\t\trank: 4\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse single integer', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: t.Object({\n\t\t\t\tlimit: t.Integer()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tlimit: '16'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tlimit: 16\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse multiple integers', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: t.Object({\n\t\t\t\tlimit: t.Integer(),\n\t\t\t\toffset: t.Integer()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tlimit: '16',\n\t\t\t\t\toffset: '4'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tlimit: 16,\n\t\t\toffset: 4\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate partial', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: t.Partial(\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tjob: t.String(),\n\t\t\t\t\ttrait: t.Optional(t.String())\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.json()).toEqual({})\n\t})\n\n\tit('validate numeric with partial', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: t.Partial(\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tjob: t.String(),\n\t\t\t\t\ttrait: t.Optional(t.String()),\n\t\t\t\t\tage: t.Numeric(),\n\t\t\t\t\trank: t.Numeric()\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.json()).toEqual({})\n\t})\n\n\tit('validate optional object', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ headers }) => headers?.name ?? 'sucrose',\n\t\t\t{\n\t\t\t\theaders: t.Object(\n\t\t\t\t\t{\n\t\t\t\t\t\tname: t.Optional(t.String())\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tadditionalProperties: true\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst [valid, invalid] = await Promise.all([\n\t\t\tapp.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tname: 'sucrose'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t),\n\t\t\tapp.handle(req('/'))\n\t\t])\n\n\t\texpect(await valid.text()).toBe('sucrose')\n\t\texpect(valid.status).toBe(200)\n\n\t\texpect(await invalid.text()).toBe('sucrose')\n\t\texpect(invalid.status).toBe(200)\n\t})\n\n\tit('create default string params', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tfaction: t.String({ default: 'tea_party' })\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tname: 'nagisa'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({\n\t\t\tname: 'nagisa',\n\t\t\tfaction: 'tea_party'\n\t\t})\n\t})\n\n\tit('create default number params', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\trank: t.Number({ default: 1 })\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tname: 'nagisa'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({\n\t\t\tname: 'nagisa',\n\t\t\trank: 1\n\t\t})\n\t})\n\n\tit('coerce number object to numeric', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers: { id } }) => typeof id, {\n\t\t\theaders: t.Object({\n\t\t\t\tid: t.Number()\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tid: '1'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.text())\n\n\t\texpect(value).toBe('number')\n\t})\n\n\tit('coerce string to boolean', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ headers }) => typeof headers['is-admin'],\n\t\t\t{\n\t\t\t\theaders: t.Object({\n\t\t\t\t\t'is-admin': t.Boolean()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst value = await app\n\t\t\t.handle(\n\t\t\t\treq('/', {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'is-admin': 'true'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\t.then((x) => x.text())\n\n\t\texpect(value).toBe('boolean')\n\t})\n\n\tit('handle optional at root', async () => {\n\t\tconst app = new Elysia().get('/', ({ headers }) => headers, {\n\t\t\theaders: t.Optional(\n\t\t\t\tt.Object({\n\t\t\t\t\tid: t.Numeric()\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/')).then((x) => x.json()),\n\t\t\tapp\n\t\t\t\t.handle(\n\t\t\t\t\treq('/', {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tid: '1'\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\t.then((x) => x.json())\n\t\t])\n\n\t\texpect(res).toEqual([{}, { id: 1 }])\n\t})\n\n\tit('handle coerce TransformDecodeError', async () => {\n\t\tlet err: Error | undefined\n\n\t\tconst app = new Elysia()\n\t\t\t.get('/', ({ body }) => body, {\n\t\t\t\theaders: t.Object({\n\t\t\t\t\tyear: t.Numeric({ minimum: 1900, maximum: 2160 })\n\t\t\t\t}),\n\t\t\t\terror({ code, error }) {\n\t\t\t\t\tswitch (code) {\n\t\t\t\t\t\tcase 'VALIDATION':\n\t\t\t\t\t\t\terr = error\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tawait app.handle(\n\t\t\treq('/', {\n\t\t\t\theaders: {\n\t\t\t\t\tyear: '3000'\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(err instanceof ValidationError).toBe(true)\n\t})\n})\n"
  },
  {
    "path": "test/validator/novalidate.test.ts",
    "content": "import { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('ElysiaType.NoValidate', () => {\n\tit('should bypass validation with t.NoValidate(t.String())', async () => {\n\t\tconst app = new Elysia().get('/', () => 123 as unknown as string, {\n\t\t\tresponse: t.NoValidate(t.String())\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('123')\n\t})\n\n\tit('should bypass validation with t.NoValidate(t.Number())', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => 'not-a-number' as unknown as number,\n\t\t\t{\n\t\t\t\tresponse: t.NoValidate(t.Number())\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('not-a-number')\n\t})\n\n\tit('should bypass validation with t.NoValidate(t.Boolean())', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => 'not-a-boolean' as unknown as boolean,\n\t\t\t{\n\t\t\t\tresponse: t.NoValidate(t.Boolean())\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('not-a-boolean')\n\t})\n\n\tit('should bypass validation with t.NoValidate(t.Object())', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => 'invalid-object' as unknown as { name: string },\n\t\t\t{\n\t\t\t\tresponse: t.NoValidate(t.Object({ name: t.String() }))\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('{}')\n\t})\n\n\tit('should bypass validation with t.NoValidate(t.Array())', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => 'not-an-array' as unknown as string[],\n\t\t\t{\n\t\t\t\tresponse: t.NoValidate(t.Array(t.String()))\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('not-an-array')\n\t})\n\n\tit('should bypass validation with t.NoValidate(t.Union())', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => 'invalid' as unknown as string | number,\n\t\t\t{\n\t\t\t\tresponse: t.NoValidate(\n\t\t\t\t\tt.Union([\n\t\t\t\t\t\tt.String({ minLength: 10 }),\n\t\t\t\t\t\tt.Number({ minimum: 100 })\n\t\t\t\t\t])\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('invalid')\n\t})\n\n\tit('should bypass validation with t.NoValidate(t.Date())', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => 'Hello Elysia' as unknown as Date,\n\t\t\t{\n\t\t\t\tresponse: t.NoValidate(t.Date())\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('Hello Elysia')\n\t})\n\n\tit('should bypass validation with t.NoValidate(t.Ref())', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({ score: t.Number() })\n\t\t\t// @ts-expect-error\n\t\t\t.get('/', () => 'string instead of number!', {\n\t\t\t\tresponse: t.NoValidate(t.Ref('score'))\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('string instead of number!')\n\t})\n\n\tit('should work with actual Date when using t.NoValidate(t.Date())', async () => {\n\t\tconst testDate = new Date('2025-01-01T00:00:00Z')\n\t\tconst app = new Elysia().get('/', () => testDate, {\n\t\t\tresponse: t.NoValidate(t.Date())\n\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe(testDate.toString())\n\t})\n\n\tit('should bypass validation with t.NoValidate(t.Numeric())', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => 'not-a-number' as unknown as number,\n\t\t\t{\n\t\t\t\tresponse: t.NoValidate(t.Numeric())\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('not-a-number')\n\t})\n\n\tit('should bypass validation with t.NoValidate(t.BooleanString())', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => 'invalid-boolean' as unknown as boolean,\n\t\t\t{\n\t\t\t\tresponse: t.NoValidate(t.BooleanString())\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('invalid-boolean')\n\t})\n\n\tit('should work with NoValidate in specific status codes', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ set }) => {\n\t\t\t\tset.status = 201\n\t\t\t\treturn 'Hello' as unknown as Date\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.String(),\n\t\t\t\t\t201: t.NoValidate(t.Date())\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(201)\n\t\texpect(await res.text()).toBe('Hello')\n\t})\n\n\tit('should validate normally for non-NoValidate status codes', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ set }) => {\n\t\t\t\tset.status = 200\n\t\t\t\treturn 'Hello' as unknown as Date\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.Date(),\n\t\t\t\t\t201: t.NoValidate(t.Date())\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(422)\n\t})\n\n\tit('should work with NoValidate on nested object properties', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t// @ts-expect-error\n\t\t\t() => ({\n\t\t\t\tuser: { age: '123', name: true },\n\t\t\t\ttimestamp: '2025-01-01T00:00:00Z'\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.NoValidate(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tuser: t.Object({\n\t\t\t\t\t\t\tname: t.String(),\n\t\t\t\t\t\t\tage: t.Number()\n\t\t\t\t\t\t}),\n\t\t\t\t\t\ttimestamp: t.Date()\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.json()).toEqual({\n\t\t\tuser: { age: '123', name: true },\n\t\t\ttimestamp: '2025-01-01T00:00:00Z'\n\t\t})\n\t})\n\n\tit('should validate normally when NOT using NoValidate', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => 'Hello Elysia' as unknown as Date,\n\t\t\t{\n\t\t\t\tresponse: t.Date()\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(422)\n\t})\n\n\tit('should validate normally with strict object schemas', async () => {\n\t\tconst app = new Elysia()\n\t\t\t// @ts-expect-error\n\t\t\t.get('/', () => ({ name: 'John' }), {\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tage: t.Number()\n\t\t\t\t})\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(422)\n\t})\n\n\tit('should handle null values with NoValidate', async () => {\n\t\tconst app = new Elysia()\n\t\t\t// @ts-expect-error\n\t\t\t.get('/', () => null, {\n\t\t\t\tresponse: t.NoValidate(t.String())\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('')\n\t})\n\n\tit('should handle undefined values with NoValidate', async () => {\n\t\tconst app = new Elysia()\n\t\t\t// @ts-expect-error\n\t\t\t.get('/', () => undefined, {\n\t\t\t\tresponse: t.NoValidate(t.String())\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('')\n\t})\n\n\tit('should work with NoValidate on multiple union types', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => 'test' as unknown as string | number | boolean,\n\t\t\t{\n\t\t\t\tresponse: t.NoValidate(\n\t\t\t\t\tt.Union([t.String(), t.Number(), t.Boolean()])\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('test')\n\t})\n\n\tit('bypasses Encode when encodeSchema=true (Date)', async () => {\n\t\tconst app = new Elysia({ encodeSchema: true }).get(\n\t\t\t'/',\n\t\t\t// @ts-expect-error\n\t\t\t() => 'Hello Elysia',\n\t\t\t{ response: t.NoValidate(t.Date()) }\n\t\t)\n\t\tconst res = await app.handle(req('/'))\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('Hello Elysia')\n\t})\n\n\tit('bypasses Encode with NoValidate(t.Ref(Date)) when encodeSchema=true', async () => {\n\t\tconst app = new Elysia({ encodeSchema: true })\n\t\t\t.model({ createdAt: t.Date() })\n\t\t\t// @ts-expect-error\n\t\t\t.get('/', () => 'Hello', {\n\t\t\t\tresponse: t.NoValidate(t.Ref('createdAt'))\n\t\t\t})\n\t\tconst res = await app.handle(req('/'))\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('Hello')\n\t})\n})\n"
  },
  {
    "path": "test/validator/params.test.ts",
    "content": "import { Elysia, t, ValidationError } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('Params Validator', () => {\n\tit('parse params without validator', async () => {\n\t\tconst app = new Elysia().get('/id/:id', ({ params: { id } }) => id)\n\t\tconst res = await app.handle(req('/id/617'))\n\n\t\texpect(await res.text()).toBe('617')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate single', async () => {\n\t\tconst app = new Elysia().get('/id/:id', ({ params: { id } }) => id, {\n\t\t\tparams: t.Object({\n\t\t\t\tid: t.String()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(req('/id/617'))\n\n\t\texpect(await res.text()).toBe('617')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate multiple', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/id/:id/name/:name',\n\t\t\t({ params }) => params,\n\t\t\t{\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tid: t.String(),\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\tconst res = await app.handle(req('/id/617/name/Ga1ahad'))\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tid: '617',\n\t\t\tname: 'Ga1ahad'\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse without reference', async () => {\n\t\tconst app = new Elysia().get('/id/:id', () => '', {\n\t\t\tparams: t.Object({\n\t\t\t\tid: t.String()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(req('/id/617'))\n\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse single numeric', async () => {\n\t\tconst app = new Elysia().get('/id/:id', ({ params }) => params, {\n\t\t\tparams: t.Object({\n\t\t\t\tid: t.Numeric()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(req('/id/617'))\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tid: 617\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse multiple numeric', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/id/:id/chapter/:chapterId',\n\t\t\t({ params }) => params,\n\t\t\t{\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tid: t.Numeric(),\n\t\t\t\t\tchapterId: t.Numeric()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\tconst res = await app.handle(req('/id/617/chapter/12'))\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tid: 617,\n\t\t\tchapterId: 12\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse single integer', async () => {\n\t\tconst app = new Elysia().get('/id/:id', ({ params }) => params, {\n\t\t\tparams: t.Object({\n\t\t\t\tid: t.Integer()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(req('/id/617'))\n\t\texpect(await res.json()).toEqual({\n\t\t\tid: 617\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse malformed integer', async () => {\n\t\tconst app = new Elysia().get('/id/:id', ({ params }) => params, {\n\t\t\tparams: t.Object({\n\t\t\t\tid: t.Integer()\n\t\t\t})\n\t\t})\n\n\t\tconst res = await app.handle(req('/id/617.1234'))\n\t\texpect(await res.json()).toMatchObject({\n\t\t\ttype: 'validation',\n\t\t\ton: 'params',\n\t\t\tsummary: \"Property 'id' should be one of: 'integer', 'integer'\",\n\t\t\tproperty: '/id',\n\t\t\tmessage: 'Expected union value',\n\t\t\texpected: {\n\t\t\t\tid: 0\n\t\t\t},\n\t\t\tfound: {\n\t\t\t\tid: '617.1234'\n\t\t\t},\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\ttype: 62,\n\t\t\t\t\tschema: {\n\t\t\t\t\t\tanyOf: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tformat: 'integer',\n\t\t\t\t\t\t\t\tdefault: 0,\n\t\t\t\t\t\t\t\ttype: 'string'\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: 'integer'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t},\n\t\t\t\t\tpath: '/id',\n\t\t\t\t\tvalue: '617.1234',\n\t\t\t\t\tmessage: 'Expected union value',\n\t\t\t\t\tsummary:\n\t\t\t\t\t\t\"Property 'id' should be one of: 'integer', 'integer'\"\n\t\t\t\t}\n\t\t\t]\n\t\t})\n\t\texpect(res.status).toBe(422)\n\t})\n\n\tit('parse multiple integer', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/id/:id/chapter/:chapterId',\n\t\t\t({ params }) => params,\n\t\t\t{\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tid: t.Integer(),\n\t\t\t\t\tchapterId: t.Integer()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\tconst res = await app.handle(req('/id/617/chapter/12'))\n\t\texpect(await res.json()).toEqual({\n\t\t\tid: 617,\n\t\t\tchapterId: 12\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('create default string params', async () => {\n\t\tconst app = new Elysia().get('/:name', ({ params }) => params, {\n\t\t\tparams: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tfaction: t.String({ default: 'tea_party' })\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app.handle(req('/nagisa')).then((x) => x.json())\n\n\t\texpect(value).toEqual({\n\t\t\tname: 'nagisa',\n\t\t\tfaction: 'tea_party'\n\t\t})\n\t})\n\n\tit('create default number params', async () => {\n\t\tconst app = new Elysia().get('/:name', ({ params }) => params, {\n\t\t\tparams: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\trank: t.Number({ default: 1 })\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app.handle(req('/nagisa')).then((x) => x.json())\n\n\t\texpect(value).toEqual({\n\t\t\tname: 'nagisa',\n\t\t\trank: 1\n\t\t})\n\t})\n\n\tit('coerce number object to numeric', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/id/:id',\n\t\t\t({ params: { id } }) => typeof id,\n\t\t\t{\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tid: t.Number()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst value = await app.handle(req('/id/1')).then((x) => x.text())\n\n\t\texpect(value).toBe('number')\n\t})\n\n\tit('coerce string object to boolean', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/is-admin/:value',\n\t\t\t({ params: { value } }) => typeof value,\n\t\t\t{\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tvalue: t.Boolean()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst value = await app\n\t\t\t.handle(req('/is-admin/true'))\n\t\t\t.then((x) => x.text())\n\n\t\texpect(value).toBe('boolean')\n\t})\n\n\tdescribe('create default value on optional params', () => {\n\t\tit('parse multiple optional params', async () => {\n\t\t\tconst app = new Elysia().get(\n\t\t\t\t'/name/:last?/:first?',\n\t\t\t\t({ params: { first, last } }) => `${last}/${first}`,\n\t\t\t\t{\n\t\t\t\t\tparams: t.Object({\n\t\t\t\t\t\tfirst: t.String({\n\t\t\t\t\t\t\tdefault: 'fubuki'\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tlast: t.String({\n\t\t\t\t\t\t\tdefault: 'shirakami'\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\n\t\t\tconst res = await Promise.all([\n\t\t\t\tapp.handle(req('/name')).then((x) => x.text()),\n\t\t\t\tapp.handle(req('/name/kurokami')).then((x) => x.text()),\n\t\t\t\tapp.handle(req('/name/kurokami/sucorn')).then((x) => x.text())\n\t\t\t])\n\n\t\t\texpect(res).toEqual([\n\t\t\t\t'shirakami/fubuki',\n\t\t\t\t'kurokami/fubuki',\n\t\t\t\t'kurokami/sucorn'\n\t\t\t])\n\t\t})\n\t})\n\n\tit('handle coerce TransformDecodeError', async () => {\n\t\tlet err: Error | undefined\n\n\t\tconst app = new Elysia()\n\t\t\t.get('/id/:id', ({ body }) => body, {\n\t\t\t\tparams: t.Object({\n\t\t\t\t\tyear: t.Numeric({ minimum: 1900, maximum: 2160 })\n\t\t\t\t}),\n\t\t\t\terror({ code, error }) {\n\t\t\t\t\tswitch (code) {\n\t\t\t\t\t\tcase 'VALIDATION':\n\t\t\t\t\t\t\terr = error\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tawait app.handle(req('/id/3000'))\n\n\t\texpect(err instanceof ValidationError).toBe(true)\n\t})\n})\n"
  },
  {
    "path": "test/validator/query.test.ts",
    "content": "import { Context, Elysia, t, ValidationError } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { req } from '../utils'\n\ndescribe('Query Validator', () => {\n\tit('validate single', async () => {\n\t\tconst app = new Elysia().get('/', ({ query: { name } }) => name, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(req('/?name=sucrose'))\n\n\t\texpect(await res.text()).toBe('sucrose')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate with hyphen in key', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ query }) => query['character-name'],\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\t'character-name': t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\tconst res = await app.handle(req('/?character-name=sucrose'))\n\n\t\texpect(await res.text()).toBe('sucrose')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate with dot in key', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ query }) => query['character.name'],\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\t'character.name': t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\tconst res = await app.handle(req('/?character.name=sucrose'))\n\n\t\texpect(await res.text()).toBe('sucrose')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate multiple', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.String()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\treq('/?name=sucrose&job=alchemist&trait=dog')\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist',\n\t\t\ttrait: 'dog'\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse without reference', async () => {\n\t\tconst app = new Elysia().get('/', () => '', {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.String()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\treq('/?name=sucrose&job=alchemist&trait=dog')\n\t\t)\n\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate optional', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.Optional(t.String())\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(req('/?name=sucrose&job=alchemist'))\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist'\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse single numeric', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.Optional(t.String()),\n\t\t\t\tage: t.Numeric()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(req('/?name=sucrose&job=alchemist&age=16'))\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist',\n\t\t\tage: 16\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse multiple numeric', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tjob: t.String(),\n\t\t\t\ttrait: t.Optional(t.String()),\n\t\t\t\tage: t.Numeric(),\n\t\t\t\trank: t.Numeric()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\treq('/?name=sucrose&job=alchemist&age=16&rank=4')\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist',\n\t\t\tage: 16,\n\t\t\trank: 4\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse numeric enum', async () => {\n\t\tenum Gender {\n\t\t\tMALE = 1,\n\t\t\tFEMALE = 2,\n\t\t\tUNKNOWN = 3\n\t\t}\n\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tgender: t.NumericEnum(Gender)\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(\n\t\t\treq(`/?name=sucrose&gender=${Gender.MALE}`)\n\t\t)\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tgender: Gender.MALE\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse single integer', async () => {\n\t\tconst app = new Elysia().get('/', ({ query: { limit } }) => limit, {\n\t\t\tquery: t.Object({\n\t\t\t\tlimit: t.Integer()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(req('/?limit=16'))\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('16')\n\t})\n\n\tit('parse multiple integer', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tlimit: t.Integer(),\n\t\t\t\toffset: t.Integer()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(req('/?limit=16&offset=0'))\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.json()).toEqual({ limit: 16, offset: 0 })\n\t})\n\n\tit('validate partial', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Partial(\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tjob: t.String(),\n\t\t\t\t\ttrait: t.Optional(t.String())\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.json()).toEqual({})\n\t})\n\n\tit('parse numeric with partial', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Partial(\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tjob: t.String(),\n\t\t\t\t\ttrait: t.Optional(t.String()),\n\t\t\t\t\tage: t.Numeric(),\n\t\t\t\t\trank: t.Numeric()\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.json()).toEqual({})\n\t})\n\n\tit('parse boolean string', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tparam1: t.BooleanString()\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(req('/?param1=true'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.json()).toEqual({ param1: true })\n\t})\n\n\tit('parse optional boolean string', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tparam1: t.Optional(t.BooleanString({ default: true }))\n\t\t\t})\n\t\t})\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.json()).toEqual({ param1: true })\n\t})\n\n\tit('parse optional boolean string with second parameter', async () => {\n\t\tconst schema = t.Object({\n\t\t\tregistered: t.Optional(t.Boolean()),\n\t\t\tother: t.String()\n\t\t})\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: schema\n\t\t})\n\t\tconst res = await app.handle(req('/?other=sucrose'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.json()).toEqual({ other: 'sucrose' })\n\t})\n\n\tit('parse optional boolean string with default value', async () => {\n\t\tconst schema = t.Object({\n\t\t\tregistered: t.Optional(t.Boolean({ default: true })),\n\t\t\tother: t.String()\n\t\t})\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: schema\n\t\t})\n\t\tconst res = await app.handle(req('/?other=sucrose'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.json()).toEqual({ other: 'sucrose', registered: true })\n\t})\n\n\tit('validate optional object', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ query }) => query?.name ?? 'sucrose',\n\t\t\t{\n\t\t\t\tquery: t.Object(\n\t\t\t\t\t{\n\t\t\t\t\t\tname: t.Optional(t.String())\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tadditionalProperties: true\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\n\t\tconst [valid, invalid] = await Promise.all([\n\t\t\tapp.handle(req('/?name=sucrose')),\n\t\t\tapp.handle(req('/'))\n\t\t])\n\n\t\texpect(await valid.text()).toBe('sucrose')\n\t\texpect(valid.status).toBe(200)\n\n\t\texpect(await invalid.text()).toBe('sucrose')\n\t\texpect(invalid.status).toBe(200)\n\t})\n\n\tit('create default string query', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\tfaction: t.String({ default: 'tea_party' })\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(req('/?name=nagisa'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({\n\t\t\tname: 'nagisa',\n\t\t\tfaction: 'tea_party'\n\t\t})\n\t})\n\n\tit('create default number query', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tname: t.String(),\n\t\t\t\trank: t.Number({ default: 1 })\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app\n\t\t\t.handle(req('/?name=nagisa'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).toEqual({\n\t\t\tname: 'nagisa',\n\t\t\trank: 1\n\t\t})\n\t})\n\n\tit('handle query edge case', async () => {\n\t\tconst checker = {\n\t\t\tcheck(ctx: Context, name: string, state?: string) {\n\t\t\t\treturn typeof state !== 'undefined'\n\t\t\t}\n\t\t}\n\n\t\tconst app = new Elysia()\n\t\t\t.derive((ctx) => {\n\t\t\t\tconst { name } = ctx.params\n\n\t\t\t\treturn {\n\t\t\t\t\tcheck() {\n\t\t\t\t\t\tconst { state } = ctx.query\n\n\t\t\t\t\t\tif (!checker.check(ctx, name, state ?? ctx.query.state))\n\t\t\t\t\t\t\tthrow new Error('State mismatch')\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get('/:name', ({ check }) => {\n\t\t\t\tcheck()\n\n\t\t\t\treturn 'yay'\n\t\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(req('/a?state=123'))\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe('yay')\n\t})\n\n\tit('parse query array', async () => {\n\t\tconst params = new URLSearchParams()\n\t\tparams.append('keys', '1')\n\t\tparams.append('keys', '2')\n\n\t\tconst response = await new Elysia()\n\t\t\t.get('/', ({ query }) => query, {\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tkeys: t.Array(t.String())\n\t\t\t\t})\n\t\t\t})\n\t\t\t.handle(new Request(`http://localhost/?${params.toString()}`))\n\t\t\t.then((res) => res.json())\n\n\t\texpect(response).toEqual({ keys: ['1', '2'] })\n\t})\n\n\tit('parse query object', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\trole: t.Optional(\n\t\t\t\t\tt.Array(\n\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\treq(\n\t\t\t\t\t`/?role=${JSON.stringify([\n\t\t\t\t\t\t{ name: 'hello' },\n\t\t\t\t\t\t{ name: 'world' }\n\t\t\t\t\t])}`\n\t\t\t\t)\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\trole: [{ name: 'hello' }, { name: 'world' }]\n\t\t})\n\t})\n\n\tit('parse optional query object', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Optional(\n\t\t\t\tt.Object({\n\t\t\t\t\trole: t.Optional(\n\t\t\t\t\t\tt.Array(\n\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\treq(\n\t\t\t\t\t`/?role=${JSON.stringify([\n\t\t\t\t\t\t{ name: 'hello' },\n\t\t\t\t\t\t{ name: 'world' }\n\t\t\t\t\t])}`\n\t\t\t\t)\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\trole: [{ name: 'hello' }, { name: 'world' }]\n\t\t})\n\t})\n\n\tit('parse array with nested object', async () => {\n\t\tconst params = new URLSearchParams()\n\t\tparams.append('keys', JSON.stringify({ a: 'hello' }))\n\t\tparams.append('keys', JSON.stringify({ a: 'hi' }))\n\n\t\tconst response = await new Elysia()\n\t\t\t.get('/', ({ query }) => query, {\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tkeys: t.Array(\n\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\ta: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t})\n\t\t\t.handle(new Request(`http://localhost/?${params.toString()}`))\n\t\t\t.then((res) => res.json())\n\n\t\texpect(response).toEqual({\n\t\t\tkeys: [{ a: 'hello' }, { a: 'hi' }]\n\t\t})\n\t})\n\n\tit('parse optional array with nested object', async () => {\n\t\tconst params = new URLSearchParams()\n\t\tparams.append('keys', JSON.stringify({ a: 'hello' }))\n\t\tparams.append('keys', JSON.stringify({ a: 'hi' }))\n\n\t\tconst response = await new Elysia()\n\t\t\t.get('/', ({ query }) => query, {\n\t\t\t\tquery: t.Optional(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tkeys: t.Array(\n\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\ta: t.String()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t})\n\t\t\t.handle(new Request(`http://localhost/?${params.toString()}`))\n\t\t\t.then((res) => res.json())\n\n\t\texpect(response).toEqual({\n\t\t\tkeys: [{ a: 'hello' }, { a: 'hi' }]\n\t\t})\n\t})\n\n\tit('parse query object array without schema', async () => {\n\t\tconst params = new URLSearchParams()\n\t\tparams.append('keys', JSON.stringify({ a: 'hello' }))\n\t\tparams.append('keys', JSON.stringify({ a: 'hi' }))\n\n\t\tconst response = await new Elysia()\n\t\t\t.get('/', ({ query }) => query, {\n\t\t\t\tquery: t.Optional(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tkeys: t.Array(\n\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\ta: t.String()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t})\n\t\t\t.handle(new Request(`http://localhost/?${params.toString()}`))\n\t\t\t.then((res) => res.json())\n\n\t\texpect(response).toEqual({\n\t\t\tkeys: [{ a: 'hello' }, { a: 'hi' }]\n\t\t})\n\t})\n\n\t// People don't expect this\n\t// @see: https://x.com/saltyAom/status/1813236251321069918\n\t// it('parse query array without schema', async () => {\n\t// \tlet value: string[] | undefined\n\n\t// \tconst response = await new Elysia()\n\t// \t\t.get('/', ({ query: { keys } }) => value = keys)\n\t// \t\t.handle(new Request(`http://localhost/?id=1&id=2`))\n\t// \t\t.then((res) => res.json())\n\n\t// \texpect(value).toEqual(['1', '2'])\n\t// })\n\n\tit(\"don't parse query object without schema\", async () => {\n\t\tconst app = new Elysia().get('/', ({ query: { role } }) => role)\n\n\t\tconst response = await app\n\t\t\t.handle(req(`/?role=${JSON.stringify({ name: 'hello' })}`))\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toBe(JSON.stringify({ name: 'hello' }))\n\t})\n\n\tit('parse union primitive and object', async () => {\n\t\tconst app = new Elysia().get('/', ({ query: { ids } }) => ids, {\n\t\t\tquery: t.Object({\n\t\t\t\tids: t.Union([\n\t\t\t\t\tt.Array(\n\t\t\t\t\t\tt.Union([t.Object({ a: t.String() }), t.Numeric()])\n\t\t\t\t\t),\n\t\t\t\t\tt.Numeric()\n\t\t\t\t])\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(req(`/?ids=1&ids=${JSON.stringify({ a: 'b' })}`))\n\t\t\t.then((res) => res.json())\n\n\t\texpect(response).toEqual([1, { a: 'b' }])\n\t})\n\n\tit('coerce number object to numeric', async () => {\n\t\tconst app = new Elysia().get('/', ({ query: { id } }) => typeof id, {\n\t\t\tquery: t.Object({\n\t\t\t\tid: t.Number()\n\t\t\t})\n\t\t})\n\n\t\tconst value = await app.handle(req('/?id=1')).then((x) => x.text())\n\n\t\texpect(value).toBe('number')\n\t})\n\n\tit('coerce string object to boolean', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ query: { isAdmin } }) => typeof isAdmin,\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tisAdmin: t.Boolean()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst value = await app\n\t\t\t.handle(req('/?isAdmin=true'))\n\t\t\t.then((x) => x.text())\n\n\t\texpect(value).toBe('boolean')\n\t})\n\n\tit(\"don't parse object automatically unless explicitly specified\", async () => {\n\t\tlet value: string | undefined\n\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ query: { pagination } }) => (value = pagination as string)\n\t\t)\n\n\t\tawait app.handle(\n\t\t\treq(\n\t\t\t\t`/?pagination=${JSON.stringify({ pageIndex: 1, pageLimit: 10 })}`\n\t\t\t)\n\t\t)\n\n\t\texpect(value).toEqual(JSON.stringify({ pageIndex: 1, pageLimit: 10 }))\n\t})\n\n\tit('handle object array in single query', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tpagination: t.Array(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tpageIndex: t.Number(),\n\t\t\t\t\t\tpageLimit: t.Number()\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\treq(\n\t\t\t\t\t`/?pagination=${JSON.stringify([{ pageIndex: 1, pageLimit: 10 }])}`\n\t\t\t\t)\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tpagination: [{ pageIndex: 1, pageLimit: 10 }]\n\t\t})\n\t})\n\n\tit('handle merge object to array in multiple query', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tpagination: t.Array(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tpageIndex: t.Number(),\n\t\t\t\t\t\tpageLimit: t.Number()\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(\n\t\t\t\treq(\n\t\t\t\t\t`/?pagination=${JSON.stringify({ pageIndex: 1, pageLimit: 10 })}&pagination=${JSON.stringify({ pageIndex: 2, pageLimit: 9 })}`\n\t\t\t\t)\n\t\t\t)\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tpagination: [\n\t\t\t\t{ pageIndex: 1, pageLimit: 10 },\n\t\t\t\t{ pageIndex: 2, pageLimit: 9 }\n\t\t\t]\n\t\t})\n\t})\n\n\tit('don\\t coerce number in nested object', async () => {\n\t\tconst app = new Elysia().get('/', ({ query: { user } }) => user, {\n\t\t\tquery: t.Object({\n\t\t\t\tuser: t.Object({\n\t\t\t\t\tid: t.Number(),\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(\n\t\t\treq(\n\t\t\t\t`?user=${JSON.stringify({\n\t\t\t\t\tid: '2',\n\t\t\t\t\tname: 'test'\n\t\t\t\t})}`\n\t\t\t)\n\t\t)\n\n\t\texpect(response.status).toBe(422)\n\t})\n\n\tit('handle optional at root', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Optional(\n\t\t\t\tt.Object({\n\t\t\t\t\tid: t.Numeric()\n\t\t\t\t})\n\t\t\t)\n\t\t})\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/')).then((x) => x.json()),\n\t\t\tapp.handle(req('/?id=1')).then((x) => x.json())\n\t\t])\n\n\t\texpect(res).toEqual([{}, { id: 1 }])\n\t})\n\n\tit('parse query array in multiple location correctly', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tleading: t.String(),\n\t\t\t\tarr: t.Array(t.String()),\n\t\t\t\ttrailing: t.String()\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(req('/?leading=foo&arr=bar&arr=baz&trailing=qux&arr=xd'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tleading: 'foo',\n\t\t\tarr: ['bar', 'baz', 'xd'],\n\t\t\ttrailing: 'qux'\n\t\t})\n\t})\n\n\tit('parse + in query', async () => {\n\t\tconst api = new Elysia().get('', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tkeyword: t.String()\n\t\t\t})\n\t\t})\n\n\t\tconst url = new URL('http://localhost:3000/')\n\t\turl.searchParams.append('keyword', 'hello world')\n\t\t// console.log(url.href) //http://localhost:3000/?keyword=hello+world\n\n\t\tconst result = await api\n\t\t\t.handle(new Request(url.href))\n\t\t\t.then((response) => response.json())\n\n\t\texpect(result).toEqual({\n\t\t\tkeyword: 'hello world'\n\t\t})\n\t})\n\n\t// https://github.com/elysiajs/elysia/issues/929\n\tit('slice non-ASCII querystring offset correctly', async () => {\n\t\tconst app = new Elysia().get('/', () => 'ok', {\n\t\t\tquery: t.Object({\n\t\t\t\tkey1: t.Union([t.Array(t.String()), t.String()])\n\t\t\t})\n\t\t})\n\n\t\texpect(\n\t\t\tawait app\n\t\t\t\t.handle(req('/?key1=ab&key1=cd&z=が'))\n\t\t\t\t.then((x) => x.status)\n\t\t).toEqual(200)\n\n\t\texpect(\n\t\t\tawait app.handle(req('/?key1=ab&z=が')).then((x) => x.status)\n\t\t).toEqual(200)\n\n\t\texpect(\n\t\t\tawait app.handle(req('/?key1=ab&key1=cd&z=x')).then((x) => x.status)\n\t\t).toEqual(200)\n\n\t\texpect(\n\t\t\tawait app\n\t\t\t\t.handle(req('/?z=が&key1=ab&key1=cd'))\n\t\t\t\t.then((x) => x.status)\n\t\t).toEqual(200)\n\n\t\texpect(\n\t\t\tawait app.handle(req('/?key1=で&key1=が&z=x')).then((x) => x.status)\n\t\t).toEqual(200)\n\t})\n\n\t// https://github.com/elysiajs/elysia/issues/912\n\tit('handle JavaScript date numeric offset', () => {\n\t\tconst api = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tdate: t.Date()\n\t\t\t})\n\t\t})\n\n\t\tapi.handle(req(`/?date=${Date.now()}`)).then((x) => x.json())\n\t})\n\n\tit('handle nuqs format when specified as Array', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\ta: t.Array(t.String())\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(req('/?a=a,b')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\ta: ['a', 'b']\n\t\t})\n\t})\n\n\tit('handle nuqs format when specified as number', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\ta: t.Array(t.Numeric())\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app.handle(req('/?a=1,2')).then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\ta: [1, 2]\n\t\t})\n\t})\n\n\tit('handle nuqs format when specified as boolean', async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\ta: t.Array(t.BooleanString())\n\t\t\t})\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(req('/?a=true,false'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\ta: [true, false]\n\t\t})\n\t})\n\n\t// https://github.com/elysiajs/elysia/issues/1015\n\tit('handle ref transform', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tmyModel: t.Object({ num: t.Number() })\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/',\n\t\t\t\t({ query: { num } }) => ({\n\t\t\t\t\tnum,\n\t\t\t\t\ttype: typeof num\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tquery: 'myModel'\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(new Request('http://localhost?num=1&a=2'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({ num: 1, type: 'number' })\n\t})\n\n\t// https://github.com/elysiajs/elysia/issues/1068\n\tit('handle ref transform with ref inside reference model', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tnum2: t.Numeric(),\n\t\t\t\tmyModel: t.Object({ num: t.Numeric(), num2: t.Ref('num2') })\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/',\n\t\t\t\t({ query: { num, num2 } }) => ({\n\t\t\t\t\tnum,\n\t\t\t\t\tnumType: typeof num,\n\t\t\t\t\tnum2,\n\t\t\t\t\tnum2Type: typeof num2\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tquery: 'myModel'\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(new Request('http://localhost?num=1&num2=2'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tnum: 1,\n\t\t\tnumType: 'number',\n\t\t\tnum2: 2,\n\t\t\tnum2Type: 'number'\n\t\t})\n\t})\n\n\tit('handle \"&\" inside a query value', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'*',\n\t\t\t({ query, request }) => ({\n\t\t\t\tquery,\n\t\t\t\turl: {\n\t\t\t\t\ttest: new URL(request.url).searchParams.get('test')\n\t\t\t\t}\n\t\t\t}),\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\ttest: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst url = \"https://localhost/?test=Test1%20%26%20Test2'\"\n\n\t\tconst value = await app.handle(new Request(url)).then((x) => x.json())\n\n\t\texpect(value).toEqual({\n\t\t\tquery: {\n\t\t\t\ttest: \"Test1 & Test2'\"\n\t\t\t},\n\t\t\turl: {\n\t\t\t\ttest: new URL(url).searchParams.get('test')\n\t\t\t}\n\t\t})\n\t})\n\n\tit('handle array string correctly', async () => {\n\t\tconst app = new Elysia({ precompile: true }).get(\n\t\t\t'/',\n\t\t\t({ query }) => query,\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tstatus: t.Optional(t.Array(t.String()))\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/?')).then((x) => x.json()),\n\t\t\tapp.handle(req('/?status=a')).then((x) => x.json()),\n\t\t\tapp.handle(req('/?status=a&status=b')).then((x) => x.json())\n\t\t])\n\n\t\texpect(response).toEqual([\n\t\t\t{},\n\t\t\t{ status: ['a'] },\n\t\t\t{ status: ['a', 'b'] }\n\t\t])\n\t})\n\n\tit('handle Transform query', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/test',\n\t\t\t({ query: { id } }) => ({\n\t\t\t\tid,\n\t\t\t\ttype: typeof id\n\t\t\t}),\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tid: t\n\t\t\t\t\t\t.Transform(t.UnionEnum(['test', 'foo']))\n\t\t\t\t\t\t.Decode((id) => ({ value: id }))\n\t\t\t\t\t\t.Encode((id) => id.value)\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(req('/test?id=test'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tid: {\n\t\t\t\tvalue: 'test'\n\t\t\t},\n\t\t\ttype: 'object'\n\t\t})\n\t})\n\n\tit('handle Date query', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ query: { date } }) => date.toISOString(),\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tdate: t.Date()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst response = await app\n\t\t\t.handle(req(`/?date=2023-04-05T12:30:00+01:00`))\n\t\t\t.then((x) => x.text())\n\n\t\texpect(response).toEqual('2023-04-05T11:30:00.000Z')\n\t})\n\n\tit('handle coerce TransformDecodeError', async () => {\n\t\tlet err: Error | undefined\n\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tyear: t.Numeric({ minimum: 1900, maximum: 2160 })\n\t\t\t}),\n\t\t\terror({ code, error }) {\n\t\t\t\tswitch (code) {\n\t\t\t\t\tcase 'VALIDATION':\n\t\t\t\t\t\terr = error\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tawait app.handle(req('?year=3000'))\n\n\t\texpect(err instanceof ValidationError).toBe(true)\n\t})\n\n\tit('handle reference query array', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.model({\n\t\t\t\tids: t.Object({\n\t\t\t\t\tids: t.Array(t.Union([t.String(), t.ArrayString()]))\n\t\t\t\t})\n\t\t\t})\n\t\t\t.get('/', ({ query }) => query, {\n\t\t\t\tquery: 'ids'\n\t\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(req('?ids=1,2,3'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response).toEqual({\n\t\t\tids: ['1', '2', '3']\n\t\t})\n\t})\n\n\tit('validate url encoded query', () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\ttest: t.Optional(t.Number()),\n\t\t\t\t$test: t.Optional(t.Number())\n\t\t\t})\n\t\t})\n\n\t\tconst value = app\n\t\t\t.handle(new Request('http://localhost?test=1&%24test=2'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(value).resolves.toEqual({\n\t\t\ttest: 1,\n\t\t\t$test: 2\n\t\t})\n\t})\n\n\tit(\"don't populate object query on failed validation\", async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tfilter: t.Object({\n\t\t\t\t\tlatlng: t.Object({\n\t\t\t\t\t\twithin: t.Object({\n\t\t\t\t\t\t\tne: t.Number(),\n\t\t\t\t\t\t\tsw: t.Number()\n\t\t\t\t\t\t})\n\t\t\t\t\t}),\n\t\t\t\t\tzoom: t.Object({\n\t\t\t\t\t\tequalTo: t.Number({\n\t\t\t\t\t\t\tminimum: 0,\n\t\t\t\t\t\t\tmaximum: 20,\n\t\t\t\t\t\t\tmultipleOf: 1\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tconst filter = JSON.stringify({\n\t\t\tlatlng: {\n\t\t\t\twithin: {\n\t\t\t\t\tne: 1,\n\t\t\t\t\tsw: 1\n\t\t\t\t}\n\t\t\t},\n\t\t\tzoom: {\n\t\t\t\tequalTo: 2\n\t\t\t}\n\t\t})\n\n\t\tconst valid = await app.handle(\n\t\t\tnew Request(`http://localhost:3000/?filter=${filter}`)\n\t\t)\n\t\tconst invalid1 = await app.handle(new Request(`http://localhost:3000`))\n\t\tconst invalid2 = await app.handle(\n\t\t\tnew Request(\n\t\t\t\t`http://localhost:3000?filter=${JSON.stringify({ zoom: { equalTo: 21 } })}`\n\t\t\t)\n\t\t)\n\n\t\texpect(valid.status).toBe(200)\n\t\texpect(invalid1.status).toBe(422)\n\t\texpect(invalid2.status).toBe(422)\n\t})\n\n\tit(\"don't populate array query on failed validation\", async () => {\n\t\tconst app = new Elysia().get('/', ({ query }) => query, {\n\t\t\tquery: t.Object({\n\t\t\t\tparty: t.Array(\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t})\n\t\t})\n\n\t\tconst filter = JSON.stringify([\n\t\t\t{\n\t\t\t\tname: 'lilith'\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'fouco'\n\t\t\t}\n\t\t])\n\n\t\tconst valid = await app.handle(\n\t\t\tnew Request(`http://localhost:3000/?party=${filter}`)\n\t\t)\n\t\tconst invalid1 = await app.handle(new Request(`http://localhost:3000`))\n\t\tconst invalid2 = await app.handle(\n\t\t\tnew Request(`http://localhost:3000?filter=[]`)\n\t\t)\n\n\t\texpect(valid.status).toBe(200)\n\t\texpect(invalid1.status).toBe(422)\n\t\texpect(invalid2.status).toBe(422)\n\t})\n\n\t// Union schema tests\n\tit('handle query array in Union schema', async () => {\n\t\tconst app = new Elysia({ aot: false }).get('/', ({ query }) => query, {\n\t\t\tquery: t.Union([\n\t\t\t\tt.Object({\n\t\t\t\t\tids: t.Array(t.String())\n\t\t\t\t}),\n\t\t\t\tt.Object({\n\t\t\t\t\tid: t.String()\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(req('/?ids=1&ids=2'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response.ids).toEqual(['1', '2'])\n\t})\n\n\tit('handle numeric coercion in Union schema', async () => {\n\t\tconst app = new Elysia({ aot: false }).get('/', ({ query }) => query, {\n\t\t\tquery: t.Union([\n\t\t\t\tt.Object({\n\t\t\t\t\tpage: t.Numeric()\n\t\t\t\t}),\n\t\t\t\tt.Object({\n\t\t\t\t\tcursor: t.String()\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\n\t\tconst response = await app\n\t\t\t.handle(req('/?page=5'))\n\t\t\t.then((x) => x.json())\n\n\t\texpect(response.page).toBe(5)\n\t})\n})\n"
  },
  {
    "path": "test/validator/response-validation-nested.test.ts",
    "content": "import { describe, expect, it } from 'bun:test'\nimport { Elysia, t } from '../../src'\n\n// Issue #1659: Response validation with nested schemas crashes with 500 instead of 422\n// https://github.com/elysiajs/elysia/issues/1659\n//\n// Root cause: exact-mirror's Clean() function assumes valid data structure\n// and throws when accessing nested properties on null values.\n// Fix: Wrap Clean() calls in try-catch in dynamic-handle.ts\n\ndescribe('Response validation nested schemas', () => {\n\tit('should return 422 for invalid nested response (aot: false)', async () => {\n\t\tconst app = new Elysia({ aot: false }).post(\n\t\t\t'/test',\n\t\t\t// @ts-expect-error - intentionally returning invalid data to test validation\n\t\t\t() => ({\n\t\t\t\titems: [\n\t\t\t\t\t['t1', { file: { ver: { s: '', m: null } } }],\n\t\t\t\t\t['t2', { file: { ver: null } }] // Invalid - ver should be object\n\t\t\t\t]\n\t\t\t}),\n\t\t\t{\n\t\t\t\tbody: t.Object({}),\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\titems: t.Array(\n\t\t\t\t\t\tt.Tuple([\n\t\t\t\t\t\t\tt.String(),\n\t\t\t\t\t\t\tt.Union([\n\t\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\t\tfile: t.Object({\n\t\t\t\t\t\t\t\t\t\tver: t.Object({\n\t\t\t\t\t\t\t\t\t\t\ts: t.String(),\n\t\t\t\t\t\t\t\t\t\t\tm: t.Nullable(t.String())\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t])\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/test', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\tbody: '{}'\n\t\t\t})\n\t\t)\n\n\t\t// Should be 422 (validation error), not 500 (internal error)\n\t\texpect(res.status).toBe(422)\n\n\t\tconst json = (await res.json()) as { type: string; errors?: unknown[] }\n\t\texpect(json.type).toBe('validation')\n\t\texpect(json.errors?.length).toBeGreaterThan(0)\n\t})\n\n\tit('should return 422 for invalid nested response (aot: true)', async () => {\n\t\tconst app = new Elysia({ aot: true }).post(\n\t\t\t'/test',\n\t\t\t// @ts-expect-error - intentionally returning invalid data to test validation\n\t\t\t() => ({\n\t\t\t\titems: [\n\t\t\t\t\t['t1', { file: { ver: { s: '', m: null } } }],\n\t\t\t\t\t['t2', { file: { ver: null } }] // Invalid\n\t\t\t\t]\n\t\t\t}),\n\t\t\t{\n\t\t\t\tbody: t.Object({}),\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\titems: t.Array(\n\t\t\t\t\t\tt.Tuple([\n\t\t\t\t\t\t\tt.String(),\n\t\t\t\t\t\t\tt.Union([\n\t\t\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\t\t\tfile: t.Object({\n\t\t\t\t\t\t\t\t\t\tver: t.Object({\n\t\t\t\t\t\t\t\t\t\t\ts: t.String(),\n\t\t\t\t\t\t\t\t\t\t\tm: t.Nullable(t.String())\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t])\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(\n\t\t\tnew Request('http://localhost/test', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\tbody: '{}'\n\t\t\t})\n\t\t)\n\n\t\texpect(res.status).toBe(422)\n\n\t\tconst json = (await res.json()) as { type: string; errors?: unknown[] }\n\t\texpect(json.type).toBe('validation')\n\t\texpect(json.errors?.length).toBeGreaterThan(0)\n\t})\n\n\tit('should return 422 for tuple with null nested object (aot: false)', async () => {\n\t\tconst app = new Elysia({ aot: false }).get(\n\t\t\t'/test',\n\t\t\t// @ts-expect-error - intentionally returning invalid data to test validation\n\t\t\t() => ({\n\t\t\t\tdata: ['id', { nested: null }] // nested should be object with 'value'\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tdata: t.Tuple([\n\t\t\t\t\t\tt.String(),\n\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\tnested: t.Object({\n\t\t\t\t\t\t\t\tvalue: t.String()\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t})\n\t\t\t\t\t])\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(new Request('http://localhost/test'))\n\n\t\texpect(res.status).toBe(422)\n\n\t\tconst json = (await res.json()) as { type: string }\n\t\texpect(json.type).toBe('validation')\n\t})\n})\n"
  },
  {
    "path": "test/validator/response.test.ts",
    "content": "import { Elysia, t, sse } from '../../src'\nimport { streamResponse } from '../../src/adapter/utils'\nimport * as z from 'zod'\n\nimport { describe, expect, it } from 'bun:test'\nimport { post, req, upload } from '../utils'\n\ndescribe('Response Validator', () => {\n\tit('validate primitive', async () => {\n\t\tconst app = new Elysia().get('/', () => 'sucrose', {\n\t\t\tresponse: t.String()\n\t\t})\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('sucrose')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate number', async () => {\n\t\tconst app = new Elysia().get('/', () => 1, {\n\t\t\tresponse: t.Number()\n\t\t})\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('1')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate boolean', async () => {\n\t\tconst app = new Elysia().get('/', () => true, {\n\t\t\tresponse: t.Boolean()\n\t\t})\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('true')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate literal', async () => {\n\t\tconst app = new Elysia().get('/', () => 'A' as const, {\n\t\t\tresponse: t.Literal('A')\n\t\t})\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.text()).toBe('A')\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate single', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => ({\n\t\t\t\tname: 'sucrose'\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.json()).toEqual({ name: 'sucrose' })\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate multiple', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => ({\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist',\n\t\t\t\ttrait: 'dog'\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tjob: t.String(),\n\t\t\t\t\ttrait: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist',\n\t\t\ttrait: 'dog'\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('parse without reference', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => ({\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist',\n\t\t\t\ttrait: 'dog'\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tjob: t.String(),\n\t\t\t\t\ttrait: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate optional', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => ({\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist'\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tjob: t.String(),\n\t\t\t\t\ttrait: t.Optional(t.String())\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(await res.json()).toEqual({\n\t\t\tname: 'sucrose',\n\t\t\tjob: 'alchemist'\n\t\t})\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('allow undefined', async () => {\n\t\tconst app = new Elysia().get('/', () => {}, {\n\t\t\tbody: t.Union([\n\t\t\t\tt.Undefined(),\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String(),\n\t\t\t\t\tjob: t.String(),\n\t\t\t\t\ttrait: t.Optional(t.String())\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(await res.text()).toBe('')\n\t})\n\n\tit('normalize by default', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t() => ({\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist'\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/')).then((x) => x.json())\n\n\t\texpect(res).toEqual({\n\t\t\tname: 'sucrose'\n\t\t})\n\t})\n\n\tit('strictly validate if not normalize', async () => {\n\t\tconst app = new Elysia({ normalize: false }).get(\n\t\t\t'/',\n\t\t\t() => ({\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: 'alchemist'\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.Object({\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\texpect(res.status).toBe(422)\n\t})\n\n\tit('handle File', async () => {\n\t\tconst app = new Elysia().post('/', ({ body: { file } }) => file.size, {\n\t\t\tbody: t.Object({\n\t\t\t\tfile: t.File()\n\t\t\t})\n\t\t})\n\n\t\texpect(\n\t\t\tawait app\n\t\t\t\t.handle(\n\t\t\t\t\tupload('/', {\n\t\t\t\t\t\tfile: 'aris-yuzu.jpg'\n\t\t\t\t\t}).request\n\t\t\t\t)\n\t\t\t\t.then((x) => x.text())\n\t\t).toBe(Bun.file('./test/images/aris-yuzu.jpg').size + '')\n\t})\n\n\tit('convert File to Files automatically', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/',\n\t\t\t({ body: { files } }) => Array.isArray(files),\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tfiles: t.Files()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\texpect(\n\t\t\tawait app\n\t\t\t\t.handle(\n\t\t\t\t\tupload('/', {\n\t\t\t\t\t\tfiles: 'aris-yuzu.jpg'\n\t\t\t\t\t}).request\n\t\t\t\t)\n\t\t\t\t.then((x) => x.text())\n\t\t).toEqual('true')\n\n\t\texpect(\n\t\t\tawait app\n\t\t\t\t.handle(\n\t\t\t\t\tupload('/', {\n\t\t\t\t\t\tfiles: ['aris-yuzu.jpg', 'midori.png']\n\t\t\t\t\t}).request\n\t\t\t\t)\n\t\t\t\t.then((x) => x.text())\n\t\t).toEqual('true')\n\t})\n\n\tit('validate response per status', async () => {\n\t\tconst app = new Elysia().post(\n\t\t\t'/',\n\t\t\t({ set, body: { status, response } }) => {\n\t\t\t\tset.status = status\n\n\t\t\t\treturn response\n\t\t\t},\n\t\t\t{\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tstatus: t.Number(),\n\t\t\t\t\tresponse: t.Any()\n\t\t\t\t}),\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.String(),\n\t\t\t\t\t201: t.Number()\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tconst r200valid = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tstatus: 200,\n\t\t\t\tresponse: 'String'\n\t\t\t})\n\t\t)\n\t\tconst r200invalid = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tstatus: 200,\n\t\t\t\tresponse: 1\n\t\t\t})\n\t\t)\n\n\t\tconst r201valid = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tstatus: 201,\n\t\t\t\tresponse: 1\n\t\t\t})\n\t\t)\n\t\tconst r201invalid = await app.handle(\n\t\t\tpost('/', {\n\t\t\t\tstatus: 201,\n\t\t\t\tresponse: 'String'\n\t\t\t})\n\t\t)\n\n\t\texpect(r200valid.status).toBe(200)\n\t\texpect(r200invalid.status).toBe(422)\n\t\texpect(r201valid.status).toBe(201)\n\t\texpect(r201invalid.status).toBe(422)\n\t})\n\n\tit('validate response per status with error()', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ status }) => status(418, 'I am a teapot'),\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.String(),\n\t\t\t\t\t418: t.String()\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\t})\n\n\tit('use inline error from handler', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\t({ status }) => status(418, 'I am a teapot'),\n\t\t\t{\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.String(),\n\t\t\t\t\t418: t.String()\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\t})\n\n\tit('return null with schema', async () => {\n\t\tconst app = new Elysia().get('/', () => null, {\n\t\t\tresponse: t.Union([\n\t\t\t\tt.Null(),\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\t})\n\n\tit('return undefined with schema', async () => {\n\t\tconst app = new Elysia().get('/', () => undefined, {\n\t\t\tresponse: t.Union([\n\t\t\t\tt.Undefined(),\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\t})\n\n\tit('return void with schema', async () => {\n\t\tconst app = new Elysia().get('/', () => undefined, {\n\t\t\tresponse: t.Union([\n\t\t\t\tt.Void(),\n\t\t\t\tt.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t])\n\t\t})\n\t})\n\n\tit('return null with status based schema', async () => {\n\t\tconst app = new Elysia().get('/', () => undefined, {\n\t\t\tresponse: {\n\t\t\t\t200: t.Union([\n\t\t\t\t\tt.Void(),\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t})\n\t\t\t\t]),\n\t\t\t\t418: t.String()\n\t\t\t}\n\t\t})\n\t})\n\n\tit('return static undefined with status based schema', async () => {\n\t\tconst app = new Elysia().get('/', undefined as any, {\n\t\t\tresponse: {\n\t\t\t\t200: t.Union([\n\t\t\t\t\tt.Void(),\n\t\t\t\t\tt.Object({\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t})\n\t\t\t\t]),\n\t\t\t\t418: t.String()\n\t\t\t}\n\t\t})\n\t})\n\n\tit('return error response with validator', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/ok', () => 'ok', {\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.String(),\n\t\t\t\t\t418: t.Literal('Kirifuji Nagisa'),\n\t\t\t\t\t420: t.Literal('Snoop Dogg')\n\t\t\t\t}\n\t\t\t})\n\t\t\t.get(\n\t\t\t\t'/error',\n\t\t\t\t({ status }) => status(\"I'm a teapot\", 'Kirifuji Nagisa'),\n\t\t\t\t{\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t200: t.String(),\n\t\t\t\t\t\t418: t.Literal('Kirifuji Nagisa'),\n\t\t\t\t\t\t420: t.Literal('Snoop Dogg')\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\t\t\t.get(\n\t\t\t\t'/validate-error',\n\t\t\t\t// @ts-ignore\n\t\t\t\t({ status }) => status(\"I'm a teapot\", 'Nagisa'),\n\t\t\t\t{\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t200: t.String(),\n\t\t\t\t\t\t418: t.Literal('Kirifuji Nagisa'),\n\t\t\t\t\t\t420: t.Literal('Snoop Dogg')\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst response = await Promise.all([\n\t\t\tapp.handle(req('/ok')).then((x) => x.status),\n\t\t\tapp.handle(req('/error')).then((x) => x.status),\n\t\t\tapp.handle(req('/validate-error')).then((x) => x.status)\n\t\t])\n\n\t\texpect(response).toEqual([200, 418, 422])\n\t})\n\n\tit('validate nested references', async () => {\n\t\tconst job = t.Object(\n\t\t\t{\n\t\t\t\tname: t.String()\n\t\t\t},\n\t\t\t{ $id: 'job' }\n\t\t)\n\n\t\tconst person = t.Object({\n\t\t\tname: t.String(),\n\t\t\tjob: t.Ref(job)\n\t\t})\n\n\t\tconst app = new Elysia().model({ job, person }).get(\n\t\t\t'/',\n\t\t\t() => ({\n\t\t\t\tname: 'sucrose',\n\t\t\t\tjob: { name: 'alchemist' }\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: person\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\t\texpect(res.status).toBe(200)\n\t})\n\n\tit('validate SSE response with generator', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\tfunction* () {\n\t\t\t\tyield sse({ data: { name: 'Alice' } })\n\t\t\t\tyield sse({ data: { name: 'Bob' } })\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tdata: t.Object({\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\t\texpect(res.status).toBe(200)\n\t\texpect(res.headers.get('content-type')).toBe('text/event-stream')\n\n\t\t// Verify the stream contains the expected SSE data\n\t\tconst result = []\n\t\tfor await (const chunk of streamResponse(res)) {\n\t\t\tresult.push(chunk)\n\t\t}\n\n\t\texpect(result.join('')).toContain('data: {\"name\":\"Alice\"}')\n\t\texpect(result.join('')).toContain('data: {\"name\":\"Bob\"}')\n\t})\n\n\tit('validate async SSE response with generator', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\tasync function* () {\n\t\t\t\tyield sse({ data: { name: 'Charlie' } })\n\t\t\t\tawait Bun.sleep(1)\n\t\t\t\tyield sse({ data: { name: 'Diana' } })\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tdata: t.Object({\n\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\t\texpect(res.status).toBe(200)\n\t\texpect(res.headers.get('content-type')).toBe('text/event-stream')\n\t})\n\n\tit('validate streaming response with generator', async () => {\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\tfunction* () {\n\t\t\t\tyield { message: 'first' }\n\t\t\t\tyield { message: 'second' }\n\t\t\t},\n\t\t\t{\n\t\t\t\tresponse: t.Object({\n\t\t\t\t\tmessage: t.String()\n\t\t\t\t})\n\t\t\t}\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\t\texpect(res.status).toBe(200)\n\n\t\tconst result = []\n\t\tfor await (const chunk of streamResponse(res)) {\n\t\t\tresult.push(chunk)\n\t\t}\n\n\t\texpect(result.join('')).toContain('\"message\":\"first\"')\n\t\texpect(result.join('')).toContain('\"message\":\"second\"')\n\t})\n\n\tit('validate SSE with Zod schema (bug report scenario)', async () => {\n\t\t// This test reproduces the exact bug report:\n\t\t// https://github.com/elysiajs/elysia/issues/1490\n\t\tconst Schema = z.object({\n\t\t\tdata: z.object({\n\t\t\t\tname: z.string()\n\t\t\t})\n\t\t})\n\n\t\tconst app = new Elysia().get(\n\t\t\t'/',\n\t\t\tfunction* () {\n\t\t\t\tyield sse({ data: { name: 'Name' } })\n\t\t\t},\n\t\t\t{ response: Schema }\n\t\t)\n\n\t\tconst res = await app.handle(req('/'))\n\n\t\t// Should not throw validation error\n\t\texpect(res.status).toBe(200)\n\t\texpect(res.headers.get('content-type')).toBe('text/event-stream')\n\n\t\t// Verify the stream contains the expected SSE data\n\t\tconst result = []\n\t\tfor await (const chunk of streamResponse(res)) {\n\t\t\tresult.push(chunk)\n\t\t}\n\n\t\texpect(result.join('')).toContain('data: {\"name\":\"Name\"}')\n\t})\n\n\tit('handle distinct union', () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/health', () => ({ status: 'healthy' }) as const, {\n\t\t\t\tresponse: {\n\t\t\t\t\t200: t.Union([\n\t\t\t\t\t\tt.Object({\n\t\t\t\t\t\t\tstatus: t.Literal('a'),\n\t\t\t\t\t\t\ta: t.Object({ b: t.Integer() })\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tt.Object({ status: t.Literal('healthy') })\n\t\t\t\t\t])\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(3000)\n\n\t\tconst status = app.handle(req('/health')).then((x) => x.status)\n\n\t\texpect(status).resolves.toBe(200)\n\t})\n})\n"
  },
  {
    "path": "test/validator/standalone.test.ts",
    "content": "import { Elysia, t } from '../../src'\nimport { describe, it, expect } from 'bun:test'\nimport { post } from '../utils'\n\ndescribe('standalone validator', () => {\n\tit('handle guard without local schema', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ name: t.Literal('cantarella') })\n\t\t\t})\n\t\t\t.post('/name/:name', ({ params: { name } }) => ({\n\t\t\t\tname: name as 'cantarella'\n\t\t\t}))\n\n\t\tconst correct = await app.handle(\n\t\t\tpost('/name/cantarella', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(await correct.json()).toEqual({ name: 'cantarella' })\n\n\t\tconst incorrect = await app.handle(\n\t\t\tpost('/name/jinhsi', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect.status).toBe(422)\n\t})\n\n\tit('merge guard with local schema', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ name: t.Literal('cantarella') })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/name/:name',\n\t\t\t\t({ body, params: { name } }) => ({\n\t\t\t\t\t...body,\n\t\t\t\t\tname: name as 'cantarella'\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst correct = await app.handle(\n\t\t\tpost('/name/cantarella', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(await correct.json()).toEqual({ id: 1, name: 'cantarella' })\n\n\t\tconst incorrect = await app.handle(\n\t\t\tpost('/name/jinhsi', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect.status).toBe(422)\n\t})\n\n\tit('merge multiple guard without local schema', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() }),\n\t\t\t\tresponse: t.Object({ name: t.Literal('cantarella') })\n\t\t\t})\n\t\t\t.post('/name/:name', ({ params: { name } }) => ({\n\t\t\t\tname: name as 'cantarella'\n\t\t\t}))\n\n\t\tconst correct = await app.handle(\n\t\t\tpost('/name/cantarella', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(await correct.json()).toEqual({ name: 'cantarella' })\n\n\t\tconst incorrect = await app.handle(\n\t\t\tpost('/name/jinhsi', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect.status).toBe(422)\n\t})\n\n\tit('merge multiple guard with local schema', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tresponse: t.Object({ name: t.Literal('cantarella') })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/name/:name',\n\t\t\t\t({ body, params: { name } }) => ({\n\t\t\t\t\t...body,\n\t\t\t\t\tname: name as 'cantarella'\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst correct = await app.handle(\n\t\t\tpost('/name/cantarella', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(await correct.json()).toEqual({ id: 1, name: 'cantarella' })\n\n\t\tconst incorrect = await app.handle(\n\t\t\tpost('/name/jinhsi', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect.status).toBe(422)\n\t})\n\n\tit('use override guard when local is not provided', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tresponse: t.Object(\n\t\t\t\t\t{ name: t.Literal('cantarella') },\n\t\t\t\t\t{\n\t\t\t\t\t\tadditionalProperties: false\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() })\n\t\t\t})\n\t\t\t.post('/name/:name', ({ params: { name } }) => ({\n\t\t\t\tname: name as 'cantarella'\n\t\t\t}))\n\n\t\tconst correct = await app.handle(\n\t\t\tpost('/name/cantarella', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(await correct.json()).toEqual({ name: 'cantarella' })\n\n\t\tconst incorrect = await app.handle(\n\t\t\tpost('/name/jinhsi', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect.status).toBe(422)\n\t})\n\n\tit('override guard when local is provided', async () => {\n\t\tconst app = new Elysia({\n\t\t\tnormalize: false\n\t\t})\n\t\t\t.guard({\n\t\t\t\tresponse: t.Object({ name: t.Literal('cantarella') })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() })\n\t\t\t})\n\t\t\t.post('/name/:name', ({ body }) => body, {\n\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t})\n\n\t\tconst correct = await app.handle(\n\t\t\tpost('/name/cantarella', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(await correct.json()).toEqual({ id: 1 })\n\n\t\tconst incorrect = await app.handle(\n\t\t\tpost('/name/jinhsi', {\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect.status).toBe(422)\n\t})\n\n\tit('merge object guard with additionalProperties via mergeObjectSchemas', async () => {\n\t\tconst app = new Elysia({\n\t\t\tnormalize: false\n\t\t})\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tresponse: t.Object({ name: t.Literal('cantarella') })\n\t\t\t})\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object(\n\t\t\t\t\t{ id: t.Number() },\n\t\t\t\t\t{\n\t\t\t\t\t\tadditionalProperties: true\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/name/:name',\n\t\t\t\t({ body }) => ({\n\t\t\t\t\t...body,\n\t\t\t\t\tname: 'cantarella'\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: t.Object(\n\t\t\t\t\t\t{ id: t.Number() },\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tadditionalProperties: false\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst correct = await app.handle(\n\t\t\tpost('/name/cantarella', {\n\t\t\t\tid: 1,\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(await correct.json()).toEqual({ id: 1, name: 'cantarella' })\n\n\t\tconst incorrect = await app.handle(\n\t\t\tpost('/name/jinhsi', {\n\t\t\t\tid: 1,\n\t\t\t\tfamilia: 'fisalia',\n\t\t\t\ta: 'b'\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect.status).toBe(422)\n\t})\n\n\tit('override additionalProperties while merging guards', async () => {\n\t\tconst app = new Elysia({ normalize: false })\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object(\n\t\t\t\t\t{ id: t.Number() },\n\t\t\t\t\t{\n\t\t\t\t\t\tadditionalProperties: false\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t\tresponse: t.Object(\n\t\t\t\t\t{ name: t.Literal('cantarella') },\n\t\t\t\t\t{\n\t\t\t\t\t\tadditionalProperties: false\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/name/:name',\n\t\t\t\t({ body, params: { name } }) => ({\n\t\t\t\t\t...body,\n\t\t\t\t\tname: name as 'cantarella'\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.Literal('cantarella') }),\n\t\t\t\t\tresponse: t.Object({ id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst correct = await app.handle(\n\t\t\tpost('/name/cantarella', {\n\t\t\t\tid: 1,\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(await correct.json()).toEqual({ id: 1, name: 'cantarella' })\n\n\t\tconst incorrect = await app.handle(\n\t\t\tpost('/name/jinhsi', {\n\t\t\t\tid: 1,\n\t\t\t\tfamily: 'fisalia'\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect.status).toBe(422)\n\t})\n\n\tit('handle local scope', async () => {\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/local',\n\t\t\t\t({ body }) => ({\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\t...body\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: t.Object({ success: t.Boolean(), id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst app = new Elysia().use(local).post(\n\t\t\t'/main',\n\t\t\t() => ({\n\t\t\t\tsuccess: true\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t}\n\t\t)\n\n\t\tconst correct1 = await app.handle(\n\t\t\tpost('/main', {\n\t\t\t\tid: 1,\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct1.status).toBe(200)\n\t\texpect(await correct1.json()).toEqual({ success: true })\n\n\t\tconst correct2 = await app.handle(\n\t\t\tpost('/local', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(correct2.status).toBe(200)\n\t\texpect(await correct2.json()).toEqual({ success: true, id: 1 })\n\n\t\tconst correct3 = await app.handle(post('/main'))\n\n\t\texpect(correct3.status).toBe(200)\n\t\texpect(await correct3.json()).toEqual({ success: true })\n\n\t\tconst incorrect1 = await app.handle(\n\t\t\tpost('/local', {\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect1.status).toBe(422)\n\t})\n\n\tit('handle local scope', async () => {\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/local',\n\t\t\t\t({ body }) => ({\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\t...body\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: t.Object({ success: t.Boolean(), id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst app = new Elysia().use(local).post(\n\t\t\t'/main',\n\t\t\t() => ({\n\t\t\t\tsuccess: true\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t}\n\t\t)\n\n\t\tconst correct1 = await app.handle(\n\t\t\tpost('/main', {\n\t\t\t\tid: 1,\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct1.status).toBe(200)\n\t\texpect(await correct1.json()).toEqual({ success: true })\n\n\t\tconst correct2 = await app.handle(\n\t\t\tpost('/local', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(correct2.status).toBe(200)\n\t\texpect(await correct2.json()).toEqual({ success: true, id: 1 })\n\n\t\tconst correct3 = await app.handle(post('/main'))\n\n\t\texpect(correct3.status).toBe(200)\n\t\texpect(await correct3.json()).toEqual({ success: true })\n\n\t\tconst correct4 = await app.handle(\n\t\t\tpost('/main', {\n\t\t\t\tid: 1,\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct4.status).toBe(200)\n\t\texpect(await correct4.json()).toEqual({ success: true })\n\n\t\tconst incorrect1 = await app.handle(\n\t\t\tpost('/local', {\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect1.status).toBe(422)\n\t})\n\n\tit('handle local scope with parent schema', async () => {\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/local',\n\t\t\t\t({ body }) => ({\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\t...body\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: t.Object({ success: t.Boolean(), id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(local)\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ id: t.Number() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/main',\n\t\t\t\t() => ({\n\t\t\t\t\tsuccess: true\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst correct1 = await app.handle(\n\t\t\tpost('/main', {\n\t\t\t\tid: 1,\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct1.status).toBe(200)\n\t\texpect(await correct1.json()).toEqual({ success: true })\n\n\t\tconst correct2 = await app.handle(\n\t\t\tpost('/local', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(correct2.status).toBe(200)\n\t\texpect(await correct2.json()).toEqual({ success: true, id: 1 })\n\n\t\tconst correct3 = await app.handle(\n\t\t\tpost('/main', {\n\t\t\t\tid: 1,\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct3.status).toBe(200)\n\t\texpect(await correct3.json()).toEqual({ success: true })\n\n\t\tconst incorrect1 = await app.handle(\n\t\t\tpost('/local', {\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect1.status).toBe(422)\n\n\t\tconst incorrect2 = await app.handle(\n\t\t\tpost('/main', {\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect2.status).toBe(422)\n\t})\n\n\tit('handle scoped scope', async () => {\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tas: 'scoped',\n\t\t\t\tbody: t.Object({ id: t.Number() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/local',\n\t\t\t\t({ body }) => ({\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\t...body\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: t.Object({ success: t.Boolean(), id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst parent = new Elysia().use(local).post(\n\t\t\t'/parent',\n\t\t\t() => ({\n\t\t\t\tsuccess: true\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia().use(parent).post(\n\t\t\t'/main',\n\t\t\t() => ({\n\t\t\t\tsuccess: true\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t}\n\t\t)\n\n\t\tconst correct1 = await app.handle(\n\t\t\tpost('/parent', {\n\t\t\t\tid: 1,\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct1.status).toBe(200)\n\t\texpect(await correct1.json()).toEqual({ success: true })\n\n\t\tconst correct2 = await app.handle(\n\t\t\tpost('/local', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(correct2.status).toBe(200)\n\t\texpect(await correct2.json()).toEqual({ success: true, id: 1 })\n\n\t\tconst correct3 = await app.handle(\n\t\t\tpost('/parent', {\n\t\t\t\tid: 1,\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct3.status).toBe(200)\n\t\texpect(await correct3.json()).toEqual({ success: true })\n\n\t\tconst correct4 = await app.handle(post('/main'))\n\n\t\texpect(correct4.status).toBe(200)\n\t\texpect(await correct4.json()).toEqual({ success: true })\n\n\t\tconst incorrect1 = await app.handle(\n\t\t\tpost('/local', {\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect1.status).toBe(422)\n\n\t\tconst incorrect2 = await app.handle(\n\t\t\tpost('/parent', {\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect2.status).toBe(422)\n\t})\n\n\tit('handle global scope', async () => {\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tas: 'global',\n\t\t\t\tbody: t.Object({ id: t.Number() })\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/local',\n\t\t\t\t({ body }) => ({\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\t...body\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tresponse: t.Object({ success: t.Boolean(), id: t.Number() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst parent = new Elysia().use(local).post(\n\t\t\t'/parent',\n\t\t\t() => ({\n\t\t\t\tsuccess: true\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t}\n\t\t)\n\n\t\tconst app = new Elysia().use(parent).post(\n\t\t\t'/main',\n\t\t\t() => ({\n\t\t\t\tsuccess: true\n\t\t\t}),\n\t\t\t{\n\t\t\t\tresponse: t.Object({ success: t.Boolean() })\n\t\t\t}\n\t\t)\n\n\t\tconst correct1 = await app.handle(\n\t\t\tpost('/parent', {\n\t\t\t\tid: 1,\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct1.status).toBe(200)\n\t\texpect(await correct1.json()).toEqual({ success: true })\n\n\t\tconst correct2 = await app.handle(\n\t\t\tpost('/local', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(correct2.status).toBe(200)\n\t\texpect(await correct2.json()).toEqual({ success: true, id: 1 })\n\n\t\tconst correct3 = await app.handle(\n\t\t\tpost('/parent', {\n\t\t\t\tid: 1,\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(correct3.status).toBe(200)\n\t\texpect(await correct3.json()).toEqual({ success: true })\n\n\t\tconst incorrect1 = await app.handle(\n\t\t\tpost('/local', {\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect1.status).toBe(422)\n\n\t\tconst incorrect2 = await app.handle(\n\t\t\tpost('/parent', {\n\t\t\t\tname: 'cantarella'\n\t\t\t})\n\t\t)\n\t\texpect(incorrect2.status).toBe(422)\n\n\t\tconst incorrect3 = await app.handle(post('/main'))\n\t\texpect(incorrect3.status).toBe(422)\n\t})\n\n\tit('handle every schema type on local scope', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tbody: t.Object({ family: t.String() }),\n\t\t\t\theaders: t.Object({ family: t.String() }),\n\t\t\t\tquery: t.Object({ family: t.String() }),\n\t\t\t\tparams: t.Object({ family: t.String() }),\n\t\t\t\tresponse: t.Object({ family: t.String() }),\n\t\t\t\tcookie: t.Object({\n\t\t\t\t\tfamily: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post(\n\t\t\t\t'/:family/:name',\n\t\t\t\t({ body }) => ({\n\t\t\t\t\t...body,\n\t\t\t\t\tname: 'cantarella'\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t\t}\n\t\t\t)\n\n\t\tconst correct = await app.handle(\n\t\t\tnew Request(\n\t\t\t\t'http://localhost:3000/fisalia/cantarella?name=cantarella&family=fisalia',\n\t\t\t\t{\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t\tfamily: 'fisalia',\n\t\t\t\t\t\tname: 'cantarella',\n\t\t\t\t\t\tcookie: 'name=cantarella;family=fisalia'\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\tfamily: 'fisalia',\n\t\t\t\t\t\tname: 'cantarella'\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\t\t)\n\n\t\texpect(correct.status).toBe(200)\n\t\texpect(await correct.json()).toEqual({\n\t\t\tfamily: 'fisalia',\n\t\t\tname: 'cantarella'\n\t\t})\n\n\t\tconst incorrect = await app.handle(\n\t\t\tpost('/hsi/jinhsi', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect.status).toBe(422)\n\t})\n\n\tit('handle every schema type on scoped scope', async () => {\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tas: 'scoped',\n\t\t\t\tbody: t.Object({ family: t.String() }),\n\t\t\t\theaders: t.Object({ family: t.String() }),\n\t\t\t\tquery: t.Object({ family: t.String() }),\n\t\t\t\tparams: t.Object({ family: t.String() }),\n\t\t\t\tresponse: t.Object({ family: t.String() }),\n\t\t\t\tcookie: t.Object({\n\t\t\t\t\tfamily: t.String()\n\t\t\t\t})\n\t\t\t})\n\t\t\t.post('/:family', ({ body }) => body)\n\n\t\tconst app = new Elysia()\n\t\t\t.use(local)\n\t\t\t.post('/:family/:name', ({ body }) => body, {\n\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t})\n\n\t\tconst correct1 = await app.handle(\n\t\t\tnew Request(\n\t\t\t\t'http://localhost:3000/fisalia/cantarella?name=cantarella&family=fisalia',\n\t\t\t\t{\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t\tfamily: 'fisalia',\n\t\t\t\t\t\tname: 'cantarella',\n\t\t\t\t\t\tcookie: 'name=cantarella;family=fisalia'\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\tfamily: 'fisalia',\n\t\t\t\t\t\tname: 'cantarella'\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\t\t)\n\n\t\texpect(correct1.status).toBe(200)\n\t\texpect(await correct1.json()).toEqual({\n\t\t\tfamily: 'fisalia',\n\t\t\tname: 'cantarella'\n\t\t})\n\n\t\tconst correct2 = await app.handle(\n\t\t\tnew Request('http://localhost:3000/fisalia?family=fisalia', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\tfamily: 'fisalia',\n\t\t\t\t\tcookie: 'name=cantarella;family=fisalia'\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tfamily: 'fisalia'\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\n\t\texpect(correct2.status).toBe(200)\n\t\texpect(await correct2.json()).toEqual({\n\t\t\tfamily: 'fisalia'\n\t\t})\n\n\t\tconst incorrect1 = await app.handle(\n\t\t\tpost('/hsi/jinhsi', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect1.status).toBe(422)\n\n\t\tconst incorrect2 = await app.handle(\n\t\t\tpost('/hsi', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect2.status).toBe(422)\n\t})\n\n\tit('handle every schema type on global scope', async () => {\n\t\tconst local = new Elysia()\n\t\t\t.guard({\n\t\t\t\tschema: 'standalone',\n\t\t\t\tas: 'global',\n\t\t\t\tbody: t.Object({ family: t.String() }),\n\t\t\t\theaders: t.Object({ family: t.String() }),\n\t\t\t\tquery: t.Object({ family: t.String() }),\n\t\t\t\tparams: t.Object({ family: t.String() }),\n\t\t\t\tresponse: t.Object({ family: t.String() }),\n\t\t\t\tcookie: t.Object({ family: t.String() })\n\t\t\t})\n\t\t\t.post('/:family', ({ body }) => body)\n\n\t\tconst parent = new Elysia()\n\t\t\t.use(local)\n\t\t\t.post('/family/:family/:name', ({ body }) => body, {\n\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t})\n\n\t\tconst app = new Elysia()\n\t\t\t.use(parent)\n\t\t\t.post('/:family/:name', ({ body }) => body, {\n\t\t\t\tbody: t.Object({ name: t.String() }),\n\t\t\t\theaders: t.Object({ name: t.String() }),\n\t\t\t\tquery: t.Object({ name: t.String() }),\n\t\t\t\tparams: t.Object({ name: t.String() }),\n\t\t\t\tresponse: t.Object({ name: t.String() }),\n\t\t\t\tcookie: t.Object({ name: t.String() })\n\t\t\t})\n\n\t\tconst correct1 = await app.handle(\n\t\t\tnew Request(\n\t\t\t\t'http://localhost:3000/fisalia/cantarella?name=cantarella&family=fisalia',\n\t\t\t\t{\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t\tfamily: 'fisalia',\n\t\t\t\t\t\tname: 'cantarella',\n\t\t\t\t\t\tcookie: 'name=cantarella;family=fisalia'\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\tfamily: 'fisalia',\n\t\t\t\t\t\tname: 'cantarella'\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\t\t)\n\n\t\texpect(correct1.status).toBe(200)\n\t\texpect(await correct1.json()).toEqual({\n\t\t\tfamily: 'fisalia',\n\t\t\tname: 'cantarella'\n\t\t})\n\n\t\tconst correct2 = await app.handle(\n\t\t\tnew Request('http://localhost:3000/fisalia?family=fisalia', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\tfamily: 'fisalia',\n\t\t\t\t\tcookie: 'name=cantarella;family=fisalia'\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tfamily: 'fisalia'\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\n\t\texpect(correct2.status).toBe(200)\n\t\texpect(await correct2.json()).toEqual({\n\t\t\tfamily: 'fisalia'\n\t\t})\n\n\t\tconst correct3 = await app.handle(\n\t\t\tnew Request(\n\t\t\t\t'http://localhost:3000/family/fisalia/cantarella?name=cantarella&family=fisalia',\n\t\t\t\t{\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t\tfamily: 'fisalia',\n\t\t\t\t\t\tname: 'cantarella',\n\t\t\t\t\t\tcookie: 'name=cantarella;family=fisalia'\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\tfamily: 'fisalia',\n\t\t\t\t\t\tname: 'cantarella'\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t)\n\t\t)\n\n\t\texpect(correct3.status).toBe(200)\n\t\texpect(await correct3.json()).toEqual({\n\t\t\tfamily: 'fisalia',\n\t\t\tname: 'cantarella'\n\t\t})\n\n\t\tconst incorrect1 = await app.handle(\n\t\t\tpost('/hsi/jinhsi', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect1.status).toBe(422)\n\n\t\tconst incorrect2 = await app.handle(\n\t\t\tpost('/hsi', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect2.status).toBe(422)\n\n\t\tconst incorrect3 = await app.handle(\n\t\t\tpost('/family/hsi/jinhsi', {\n\t\t\t\tid: 1\n\t\t\t})\n\t\t)\n\n\t\texpect(incorrect3.status).toBe(422)\n\t})\n})\n"
  },
  {
    "path": "test/validator/validator.test.ts",
    "content": "import { Elysia, t } from '../../src'\n\nimport { describe, expect, it } from 'bun:test'\nimport { post, req } from '../utils'\n\ndescribe('Validator Additional Case', () => {\n\tit('validate beforeHandle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/', () => 'Mutsuki need correction 💢💢💢', {\n\t\t\t\tbeforeHandle: () => 'Mutsuki need correction 💢💢💢',\n\t\t\t\tresponse: t.String()\n\t\t\t})\n\t\t\t.get('/invalid', () => 1 as any, {\n\t\t\t\tbeforeHandle() {\n\t\t\t\t\treturn 1 as any\n\t\t\t\t},\n\t\t\t\tresponse: t.String()\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\t\tconst invalid = await app.handle(req('/invalid'))\n\n\t\texpect(await res.text()).toBe('Mutsuki need correction 💢💢💢')\n\t\texpect(res.status).toBe(200)\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate afterHandle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/', () => 'Mutsuki need correction 💢💢💢', {\n\t\t\t\tafterHandle: () => 'Mutsuki need correction 💢💢💢',\n\t\t\t\tresponse: t.String()\n\t\t\t})\n\t\t\t.get('/invalid', () => 1 as any, {\n\t\t\t\tafterHandle: () => 1 as any,\n\t\t\t\tresponse: t.String()\n\t\t\t})\n\n\t\tconst res = await app.handle(req('/'))\n\t\tconst invalid = await app.handle(req('/invalid'))\n\n\t\texpect(await res.text()).toBe('Mutsuki need correction 💢💢💢')\n\n\t\texpect(res.status).toBe(200)\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('validate beforeHandle with afterHandle', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.get('/', () => 'Mutsuki need correction 💢💢💢', {\n\t\t\t\tbeforeHandle() {},\n\t\t\t\tafterHandle() {\n\t\t\t\t\treturn 'Mutsuki need correction 💢💢💢'\n\t\t\t\t},\n\t\t\t\tresponse: t.String()\n\t\t\t})\n\t\t\t.get('/invalid', () => 1 as any, {\n\t\t\t\tafterHandle() {\n\t\t\t\t\treturn 1 as any\n\t\t\t\t},\n\t\t\t\tresponse: t.String()\n\t\t\t})\n\t\tconst res = await app.handle(req('/'))\n\t\tconst invalid = await app.handle(req('/invalid'))\n\n\t\texpect(await res.text()).toBe('Mutsuki need correction 💢💢💢')\n\t\texpect(res.status).toBe(200)\n\n\t\texpect(invalid.status).toBe(422)\n\t})\n\n\tit('handle guard hook', async () => {\n\t\tconst app = new Elysia().guard(\n\t\t\t{\n\t\t\t\tquery: t.Object({\n\t\t\t\t\tname: t.String()\n\t\t\t\t})\n\t\t\t},\n\t\t\t(app) =>\n\t\t\t\tapp.post('/user', ({ query: { name } }) => name, {\n\t\t\t\t\tbody: t.Object({\n\t\t\t\t\t\tid: t.Number(),\n\t\t\t\t\t\tusername: t.String(),\n\t\t\t\t\t\tprofile: t.Object({\n\t\t\t\t\t\t\tname: t.String()\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t)\n\n\t\tconst body = JSON.stringify({\n\t\t\tid: 6,\n\t\t\tusername: '',\n\t\t\tprofile: {\n\t\t\t\tname: 'A'\n\t\t\t}\n\t\t})\n\n\t\tconst valid = await app.handle(\n\t\t\tnew Request('http://localhost/user?name=salt', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody,\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/json',\n\t\t\t\t\t'content-length': body.length.toString()\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\texpect(await valid.text()).toBe('salt')\n\t\texpect(valid.status).toBe(200)\n\n\t\tconst invalidQuery = await app.handle(\n\t\t\tnew Request('http://localhost/user', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tid: 6,\n\t\t\t\t\tusername: '',\n\t\t\t\t\tprofile: {\n\t\t\t\t\t\tname: 'A'\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\n\t\texpect(invalidQuery.status).toBe(422)\n\n\t\tconst invalidBody = await app.handle(\n\t\t\tnew Request('http://localhost/user?name=salt', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'application/json'\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tid: 6,\n\t\t\t\t\tusername: '',\n\t\t\t\t\tprofile: {}\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\n\t\texpect(invalidBody.status).toBe(422)\n\t})\n\n\tit('inherits cookie on guard', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.guard({\n\t\t\t\tcookie: t.Cookie({ session: t.String() })\n\t\t\t})\n\t\t\t.get('/', ({ cookie: { session } }) =>\n\t\t\t\tsession.value ? session.value : 'Empty'\n\t\t\t)\n\n\t\tconst res = await Promise.all([\n\t\t\tapp.handle(req('/')),\n\t\t\tapp.handle(req('/', { headers: { Cookie: 'session=value' } }))\n\t\t])\n\n\t\texpect(res[0].status).toBe(422)\n\t\texpect(res[1].status).toBe(200)\n\t})\n\n\tit('handle record', async () => {\n\t\tconst app = new Elysia().get('/', () => 'SAFE', {\n\t\t\tquery: t.Record(t.String(), t.String())\n\t\t})\n\n\t\tconst response = await app.handle(req('/?x=1'))\n\n\t\texpect(response.status).toBe(200)\n\t})\n})\n"
  },
  {
    "path": "test/ws/aot.test.ts",
    "content": "import { describe, it } from 'bun:test'\nimport { Elysia } from '../../src'\nimport { newWebsocket, wsOpen, wsClosed } from './utils'\n\ndescribe('WebSocket with AoT disabled', () => {\n\tit('should connect and close', async () => {\n\t\tconst app = new Elysia({ aot: false })\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage() {}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\t\tawait wsClosed(ws)\n\n\t\tawait app.stop(true)\n\t})\n})\n"
  },
  {
    "path": "test/ws/connection.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { Elysia, t } from '../../src'\nimport { newWebsocket, wsOpen, wsClose, wsClosed } from './utils'\nimport { req } from '../utils'\n\ndescribe('WebSocket connection', () => {\n\tit('should connect and close', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage() {}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should close by server', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws) {\n\t\t\t\t\tws.close()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tws.send('close me!')\n\n\t\tconst { wasClean, code } = await wsClose(ws)\n\t\texpect(wasClean).toBe(false)\n\t\texpect(code).toBe(1000) // going away -> https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1\n\n\t\tapp.stop()\n\t})\n\n\tit('should terminate by server', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws) {\n\t\t\t\t\tws.terminate()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tws.send('close me!')\n\n\t\tconst { wasClean, code } = await wsClose(ws)\n\t\texpect(wasClean).toBe(false)\n\t\texpect(code).toBe(1006) // closed abnormally -> https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1\n\n\t\tapp.stop()\n\t})\n\n\tit('should separate get from ws', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage() {}\n\t\t\t})\n\t\t\t.get('/ws', () => 'hi')\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\t\tawait wsClosed(ws)\n\n\t\tconst response = await app.handle(req('/ws')).then((x) => x.text())\n\t\texpect(response).toBe('hi')\n\n\t\tapp.stop()\n\t})\n\n\tit('should separate all from ws', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.all('/ws', () => 'hi')\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage() {}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\t\tawait wsClosed(ws)\n\n\t\tconst response = await app.handle(req('/ws')).then((x) => x.text())\n\t\texpect(response).toBe('hi')\n\n\t\tapp.stop()\n\t})\n\n\tit('should separate dynamic get from ws', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws/:id', {\n\t\t\t\tmessage() {}\n\t\t\t})\n\t\t\t.get('/ws/:id', () => 'hi')\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!, '/ws/1')\n\n\t\tawait wsOpen(ws)\n\t\tawait wsClosed(ws)\n\n\t\tconst response = await app.handle(req('/ws/1')).then((x) => x.text())\n\t\texpect(response).toBe('hi')\n\n\t\tapp.stop()\n\t})\n\n\tit('should separate dynamic all from ws', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.all('/ws/:id', () => 'hi')\n\t\t\t.ws('/ws/:id', {\n\t\t\t\tmessage() {}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!, '/ws/1')\n\n\t\tawait wsOpen(ws)\n\t\tawait wsClosed(ws)\n\n\t\tconst response = await app.handle(req('/ws/1')).then((x) => x.text())\n\t\texpect(response).toBe('hi')\n\n\t\tapp.stop()\n\t})\n\n\tit('handle derive, resolve', async () => {\n\t\tlet sessionId: string | undefined\n\t\tlet user: { id: '123'; name: 'Jane Doe' } | undefined\n\n\t\tconst app = new Elysia()\n\t\t\t.derive(() => ({\n\t\t\t\tsessionId: '123'\n\t\t\t}))\n\t\t\t.resolve(() => ({\n\t\t\t\tgetUser() {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tid: '123',\n\t\t\t\t\t\tname: 'Jane Doe'\n\t\t\t\t\t} as const\n\t\t\t\t}\n\t\t\t}))\n\t\t\t.ws('/ws', {\n\t\t\t\topen(ws) {\n\t\t\t\t\tsessionId = ws.data.sessionId\n\t\t\t\t\tuser = ws.data.getUser()\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!, '/ws')\n\n\t\tawait wsOpen(ws)\n\t\tawait wsClosed(ws)\n\n\t\texpect(sessionId).toEqual('123')\n\t\texpect(user).toEqual({\n\t\t\tid: '123',\n\t\t\tname: 'Jane Doe'\n\t\t})\n\t})\n\n\tit('call ping/pong', async () => {\n\t\tlet pinged = false\n\t\tlet ponged = false\n\n\t\tconst app = new Elysia()\n\t\t\t.ws('/', {\n\t\t\t\tping() {\n\t\t\t\t\tpinged = true\n\t\t\t\t},\n\t\t\t\tpong() {\n\t\t\t\t\tponged = true\n\t\t\t\t},\n\t\t\t\tasync message(ws) {\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = new WebSocket(`ws://localhost:${app.server?.port}`)\n\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tws.addEventListener('open', () => {\n\t\t\t\tws.ping()\n\t\t\t\tws.send('df')\n\t\t\t\tws.pong()\n\n\t\t\t\tresolve()\n\t\t\t}, {\n\t\t\t\tonce: true\n\t\t\t})\n\t\t})\n\n\t\tawait Bun.sleep(3)\n\n\t\texpect(pinged).toBe(true)\n\t\texpect(ponged).toBe(true)\n\t})\n})\n"
  },
  {
    "path": "test/ws/destructuring.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\r\nimport { Elysia } from '../../src'\r\nimport { newWebsocket, wsOpen, wsClosed, wsMessage } from './utils'\r\n\r\ndescribe('WebSocket destructuring', () => {\r\n\tit('should destructure', async () => {\r\n\t\tconst app = new Elysia()\r\n\t\t\t.ws('/ws', {\r\n\t\t\t\tasync open(ws) {\r\n\t\t\t\t\tconst {\r\n\t\t\t\t\t\tsubscribe,\r\n\t\t\t\t\t\tisSubscribed,\r\n\t\t\t\t\t\tpublish,\r\n\t\t\t\t\t\tunsubscribe,\r\n\t\t\t\t\t\tcork,\r\n\t\t\t\t\t\tsend,\r\n\t\t\t\t\t\t// close,\r\n\t\t\t\t\t\t// terminate\r\n\t\t\t\t\t} = ws\r\n\r\n\t\t\t\t\tsubscribe('asdf')\r\n\t\t\t\t\tconst subscribed = isSubscribed('asdf')\r\n\t\t\t\t\tpublish('asdf', 'data')\r\n\t\t\t\t\tunsubscribe('asdf')\r\n\t\t\t\t\tcork(() => ws)\r\n\t\t\t\t\tsend('Hello!' + subscribed)\r\n\t\t\t\t\t// malloc error on macOS\r\n\t\t\t\t\t// close()\r\n\t\t\t\t\t// terminate()\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t\t.listen(0)\r\n\r\n\t\tconst ws = newWebsocket(app.server!)\r\n\r\n\t\tconst message = wsMessage(ws)\r\n\r\n\t\tawait wsOpen(ws)\r\n\r\n\t\tconst { type, data } = await message\r\n\r\n\t\texpect(type).toBe('message')\r\n\t\texpect(data).toBe('Hello!true')\r\n\r\n\t\tawait wsClosed(ws)\r\n\t\tapp.stop()\r\n\t})\r\n})\r\n"
  },
  {
    "path": "test/ws/message.test.ts",
    "content": "import { describe, it, expect } from 'bun:test'\nimport { Elysia, t } from '../../src'\nimport { newWebsocket, wsOpen, wsMessage, wsClosed } from './utils'\nimport z from 'zod'\n\ndescribe('WebSocket message', () => {\n\tit('should send & receive', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws, message) {\n\t\t\t\t\tws.send(message)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send('Hello!')\n\n\t\tconst { type, data } = await message\n\n\t\texpect(type).toBe('message')\n\t\texpect(data).toBe('Hello!')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should respond with remoteAddress', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws) {\n\t\t\t\t\tws.send(ws.remoteAddress)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send('Hello!')\n\n\t\tconst { type, data } = await message\n\n\t\texpect(type).toBe('message')\n\t\texpect(data === '::1' || data === '::ffff:127.0.0.1').toBeTruthy()\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\t// it('should subscribe & publish', async () => {\n\t// \tconst app = new Elysia()\n\t// \t\t.ws('/ws', {\n\t// \t\t\topen(ws) {\n\t// \t\t\t\tws.subscribe('asdf')\n\t// \t\t\t},\n\t// \t\t\tmessage(ws) {\n\t// \t\t\t\tws.publish('asdf', ws.isSubscribed('asdf'))\n\t// \t\t\t}\n\t// \t\t})\n\t// \t\t.listen(0)\n\n\t// \tconst wsBob = newWebsocket(app.server!)\n\t// \tconst wsAlice = newWebsocket(app.server!)\n\n\t// \tawait wsOpen(wsBob)\n\t// \tawait wsOpen(wsAlice)\n\n\t// \tconst messageBob = wsMessage(wsBob)\n\n\t// \twsAlice.send('Hello!')\n\n\t// \tconst { type, data } = await messageBob\n\n\t// \texpect(type).toBe('message')\n\t// \texpect(data).toBe('true')\n\n\t// \tawait wsClosed(wsBob)\n\t// \tawait wsClosed(wsAlice)\n\t// \tapp.stop()\n\t// })\n\n\tit('should unsubscribe', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\topen(ws) {\n\t\t\t\t\tws.subscribe('asdf')\n\t\t\t\t},\n\t\t\t\tmessage(ws, message) {\n\t\t\t\t\tif (message === 'unsubscribe') {\n\t\t\t\t\t\tws.unsubscribe('asdf')\n\t\t\t\t\t}\n\n\t\t\t\t\tws.send(ws.isSubscribed('asdf'))\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst subscribedMessage = wsMessage(ws)\n\n\t\tws.send('Hello!')\n\n\t\tconst subscribed = await subscribedMessage\n\n\t\texpect(subscribed.type).toBe('message')\n\t\texpect(subscribed.data).toBe('true')\n\n\t\tconst unsubscribedMessage = wsMessage(ws)\n\n\t\tws.send('unsubscribe')\n\n\t\tconst unsubscribed = await unsubscribedMessage\n\n\t\texpect(unsubscribed.type).toBe('message')\n\t\texpect(unsubscribed.data).toBe('false')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should validate success', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tmessage: t.String()\n\t\t\t\t}),\n\t\t\t\tmessage(ws, { message }) {\n\t\t\t\t\tws.send(message)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send(JSON.stringify({ message: 'Hello!' }))\n\n\t\tconst { type, data } = await message\n\n\t\texpect(type).toBe('message')\n\t\texpect(data).toBe('Hello!')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should validate fail', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tbody: t.Object({\n\t\t\t\t\tmessage: t.String()\n\t\t\t\t}),\n\t\t\t\tmessage(ws, { message }) {\n\t\t\t\t\tws.send(message)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send('Hello!')\n\n\t\tconst { type, data } = await message\n\n\t\texpect(type).toBe('message')\n\t\texpect(data).toInclude('Expected')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should validate standard schema success', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tbody: z.object({\n\t\t\t\t\tmessage: z.string()\n\t\t\t\t}),\n\t\t\t\tmessage(ws, { message }) {\n\t\t\t\t\tws.send(message)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send(JSON.stringify({ message: 'Hello!' }))\n\n\t\tconst { type, data } = await message\n\n\t\texpect(type).toBe('message')\n\t\texpect(data).toBe('Hello!')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should validate standard schema fail', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tbody: z.object({\n\t\t\t\t\tmessage: z.string()\n\t\t\t\t}),\n\t\t\t\tmessage(ws, { message }) {\n\t\t\t\t\tws.send(message)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send('Hello!')\n\n\t\tconst { type, data } = await message\n\n\t\texpect(type).toBe('message')\n\t\texpect(data).toInclude('validation')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should parse objects', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws, raw) {\n\t\t\t\t\tws.send(raw)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send(JSON.stringify({ message: 'Hello!' }))\n\n\t\tconst { type, data } = await message\n\t\texpect(type).toBe('message')\n\t\texpect(data).toInclude('{\"message\":\"Hello!\"}')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should parse arrays', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws, raw) {\n\t\t\t\t\tws.send(JSON.stringify(raw))\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send(JSON.stringify([{ message: 'Hello!' }]))\n\n\t\tconst { type, data } = await message\n\t\texpect(type).toBe('message')\n\t\texpect(data).toInclude('[{\"message\":\"Hello!\"}]')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should parse strings', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws, raw) {\n\t\t\t\t\tws.send(JSON.stringify(raw))\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send(JSON.stringify(\"Hello!\"))\n\n\t\tconst { type, data } = await message\n\t\texpect(type).toBe('message')\n\t\texpect(data).toInclude('\"Hello!\"')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should parse numbers', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws, raw) {\n\t\t\t\t\tws.send(JSON.stringify(raw))\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send(JSON.stringify(1234567890))\n\n\t\tconst { type, data } = await message\n\t\texpect(type).toBe('message')\n\t\texpect(data).toInclude('1234567890')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should parse true', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws, raw) {\n\t\t\t\t\tws.send(JSON.stringify(raw))\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send(JSON.stringify(true))\n\n\t\tconst { type, data } = await message\n\t\texpect(type).toBe('message')\n\t\texpect(data).toInclude('true')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should parse false', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws, raw) {\n\t\t\t\t\tws.send(JSON.stringify(raw))\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send(JSON.stringify(false))\n\n\t\tconst { type, data } = await message\n\t\texpect(type).toBe('message')\n\t\texpect(data).toInclude('false')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should parse null', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws, raw) {\n\t\t\t\t\tws.send(JSON.stringify(raw))\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send(JSON.stringify(null))\n\n\t\tconst { type, data } = await message\n\t\texpect(type).toBe('message')\n\t\texpect(data).toInclude('null')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should parse not parse /hello', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws, raw) {\n\t\t\t\t\tws.send(JSON.stringify(raw))\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send(JSON.stringify(\"/hello\"))\n\n\t\tconst { type, data } = await message\n\t\texpect(type).toBe('message')\n\t\texpect(data).toInclude('/hello')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should send from plugin', async () => {\n\t\tconst plugin = new Elysia().ws('/ws', {\n\t\t\tmessage(ws, message) {\n\t\t\t\tws.send(message)\n\t\t\t}\n\t\t})\n\n\t\tconst app = new Elysia().use(plugin).listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send('Hello!')\n\n\t\tconst { type, data } = await message\n\n\t\texpect(type).toBe('message')\n\t\texpect(data).toBe('Hello!')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should be able to receive binary data', async () => {\n\t\tconst plugin = new Elysia().ws('/ws', {\n\t\t\tmessage(ws, message) {\n\t\t\t\tws.send(message)\n\t\t\t}\n\t\t})\n\n\t\tconst app = new Elysia().use(plugin).listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send(new Uint8Array(3))\n\n\t\tconst { type, data } = await message\n\n\t\texpect(type).toBe('message')\n\t\t// @ts-ignore\n\t\texpect(data).toEqual(new Uint8Array(3))\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('should send & receive', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws, message) {\n\t\t\t\t\tws.send(message)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\t\tconst ws = newWebsocket(app.server!)\n\t\tawait wsOpen(ws)\n\t\tconst message = wsMessage(ws)\n\t\tws.send(' ')\n\t\tconst { type, data } = await message\n\t\texpect(type).toBe('message')\n\t\texpect(data).toBe(' ')\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('handle error', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.ws('/ws', {\n\t\t\t\terror() {\n\t\t\t\t\treturn 'caught'\n\t\t\t\t},\n\t\t\t\tmessage(ws, message) {\n\t\t\t\t\tthrow new Error('A')\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send('Hello!')\n\n\t\tconst { type, data } = await message\n\n\t\texpect(type).toBe('message')\n\t\texpect(data).toBe('caught')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n\tit('handle error with onError', async () => {\n\t\tconst app = new Elysia()\n\t\t\t.onError(() => {\n\t\t\t\treturn 'caught'\n\t\t\t})\n\t\t\t.ws('/ws', {\n\t\t\t\tmessage(ws, message) {\n\t\t\t\t\tthrow new Error('A')\n\t\t\t\t}\n\t\t\t})\n\t\t\t.listen(0)\n\n\t\tconst ws = newWebsocket(app.server!)\n\n\t\tawait wsOpen(ws)\n\n\t\tconst message = wsMessage(ws)\n\n\t\tws.send('Hello!')\n\n\t\tconst { type, data } = await message\n\n\t\texpect(type).toBe('message')\n\t\texpect(data).toBe('caught')\n\n\t\tawait wsClosed(ws)\n\t\tapp.stop()\n\t})\n\n    it('handle validation error with onError', async () => {\n        const app = new Elysia()\n            .onError(() => {\n                return 'caught'\n            })\n            .ws('/ws', {\n                body: t.Object({\n                    name: t.String()\n                }),\n                message(ws, message) {\n                    return ws.send(message)\n                }\n            })\n            .listen(0)\n\n        const ws = newWebsocket(app.server!)\n\n        await wsOpen(ws)\n\n        const message = wsMessage(ws)\n\n        ws.send(JSON.stringify({\n            name: 123, // expecting a string\n        }))\n\n        const { type, data } = await message\n\n        expect(type).toBe('message')\n        expect(data).toBe('caught')\n\n        await wsClosed(ws)\n        app.stop()\n    })\n})\n"
  },
  {
    "path": "test/ws/utils.ts",
    "content": "import type { Server } from 'bun'\r\n\r\nexport const newWebsocket = (server: Server<any>, path = '/ws') =>\r\n\tnew WebSocket(`ws://${server.hostname}:${server.port}${path}`, {})\r\n\r\nexport const wsOpen = (ws: WebSocket) =>\r\n\tnew Promise((resolve) => {\r\n\t\tws.onopen = resolve\r\n\t})\r\n\r\nexport const wsClose = async (ws: WebSocket) =>\r\n\tnew Promise<CloseEvent>((resolve) => {\r\n\t\tws.onclose = resolve\r\n\t})\r\n\r\nexport const wsClosed = async (ws: WebSocket) => {\r\n\tconst closed = wsClose(ws)\r\n\tws.close()\r\n\tawait closed\r\n}\r\n\r\nexport const wsMessage = (ws: WebSocket) =>\r\n\tnew Promise<MessageEvent<string | Buffer>>((resolve) => {\r\n\t\tws.onmessage = resolve\r\n\t})\r\n"
  },
  {
    "path": "tsconfig.dts.json",
    "content": "{\n  \"compilerOptions\": {\n    \"preserveSymlinks\": true,\n    /* Visit https://aka.ms/tsconfig to read more about this file */\n\n    /* Projects */\n    // \"incremental\": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */\n    // \"composite\": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */\n    // \"tsBuildInfoFile\": \"./.tsbuildinfo\",              /* Specify the path to .tsbuildinfo incremental compilation file. */\n    // \"disableSourceOfProjectReferenceRedirect\": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */\n    // \"disableSolutionSearching\": true,                 /* Opt a project out of multi-project reference checking when editing. */\n    // \"disableReferencedProjectLoad\": true,             /* Reduce the number of projects loaded automatically by TypeScript. */\n\n    /* Language and Environment */\n    \"target\": \"ES2021\",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */\n    \"lib\": [\"ESNext\"],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */\n    // \"jsx\": \"preserve\",                                /* Specify what JSX code is generated. */\n    // \"experimentalDecorators\": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */\n    // \"emitDecoratorMetadata\": true,                    /* Emit design-type metadata for decorated declarations in source files. */\n    // \"jsxFactory\": \"\",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */\n    // \"jsxFragmentFactory\": \"\",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */\n    // \"jsxImportSource\": \"\",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */\n    // \"reactNamespace\": \"\",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */\n    // \"noLib\": true,                                    /* Disable including any library files, including the default lib.d.ts. */\n    // \"useDefineForClassFields\": true,                  /* Emit ECMAScript-standard-compliant class fields. */\n    // \"moduleDetection\": \"auto\",                        /* Control what method is used to detect module-format JS files. */\n\n    /* Modules */\n    \"module\": \"ES2022\",                                /* Specify what module code is generated. */\n    \"rootDir\": \"./src\",                                  /* Specify the root folder within your source files. */\n    \"moduleResolution\": \"node\",                       /* Specify how TypeScript looks up a file from a given module specifier. */\n    // \"baseUrl\": \"./src\",                                  /* Specify the base directory to resolve non-relative module names. */\n    // \"paths\": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */\n    // \"rootDirs\": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */\n    // \"typeRoots\": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */\n    // \"types\": [\"bun-types\"],                                      /* Specify type package names to be included without being referenced in a source file. */\n    // \"allowUmdGlobalAccess\": true,                     /* Allow accessing UMD globals from modules. */\n    // \"moduleSuffixes\": [],                             /* List of file name suffixes to search when resolving a module. */\n    \"resolveJsonModule\": true,                        /* Enable importing .json files. */\n    // \"noResolve\": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */\n\n    /* JavaScript Support */\n    // \"allowJs\": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */\n    // \"checkJs\": true,                                  /* Enable error reporting in type-checked JavaScript files. */\n    // \"maxNodeModuleJsDepth\": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */\n\n    /* Emit */\n    \"declaration\": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */\n    // \"declarationMap\": true,                           /* Create sourcemaps for d.ts files. */\n    \"emitDeclarationOnly\": true,                      /* Only output d.ts files and not JavaScript files. */\n    // \"sourceMap\": true,                                /* Create source map files for emitted JavaScript files. */\n    // \"outFile\": \"./\",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */\n    \"outDir\": \"./dist\",                                   /* Specify an output folder for all emitted files. */\n    // \"removeComments\": true,                           /* Disable emitting comments. */\n    // \"noEmit\": true,                                   /* Disable emitting files from a compilation. */\n    // \"importHelpers\": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */\n    // \"importsNotUsedAsValues\": \"remove\",               /* Specify emit/checking behavior for imports that are only used for types. */\n    // \"downlevelIteration\": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */\n    // \"sourceRoot\": \"\",                                 /* Specify the root path for debuggers to find the reference source code. */\n    // \"mapRoot\": \"\",                                    /* Specify the location where debugger should locate map files instead of generated locations. */\n    // \"inlineSourceMap\": true,                          /* Include sourcemap files inside the emitted JavaScript. */\n    // \"inlineSources\": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */\n    // \"emitBOM\": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */\n    // \"newLine\": \"crlf\",                                /* Set the newline character for emitting files. */\n    // \"stripInternal\": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */\n    // \"noEmitHelpers\": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */\n    // \"noEmitOnError\": true,                            /* Disable emitting files if any type checking errors are reported. */\n    // \"preserveConstEnums\": true,                       /* Disable erasing 'const enum' declarations in generated code. */\n    // \"declarationDir\": \"./\",                           /* Specify the output directory for generated declaration files. */\n    // \"preserveValueImports\": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */\n\n    /* Interop Constraints */\n    // \"isolatedModules\": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */\n    \"allowSyntheticDefaultImports\": true,             /* Allow 'import x from y' when a module doesn't have a default export. */\n    \"esModuleInterop\": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */\n    // \"preserveSymlinks\": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */\n    \"forceConsistentCasingInFileNames\": true,            /* Ensure that casing is correct in imports. */\n\n    /* Type Checking */\n    \"strict\": true,                                      /* Enable all strict type-checking options. */\n    // \"noImplicitAny\": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */\n    // \"strictNullChecks\": true,                         /* When type checking, take into account 'null' and 'undefined'. */\n    // \"strictFunctionTypes\": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */\n    // \"strictBindCallApply\": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */\n    // \"strictPropertyInitialization\": true,             /* Check for class properties that are declared but not set in the constructor. */\n    // \"noImplicitThis\": true,                           /* Enable error reporting when 'this' is given the type 'any'. */\n    // \"useUnknownInCatchVariables\": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */\n    // \"alwaysStrict\": true,                             /* Ensure 'use strict' is always emitted. */\n    // \"noUnusedLocals\": true,                           /* Enable error reporting when local variables aren't read. */\n    // \"noUnusedParameters\": true,                       /* Raise an error when a function parameter isn't read. */\n    // \"exactOptionalPropertyTypes\": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */\n    // \"noImplicitReturns\": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */\n    // \"noFallthroughCasesInSwitch\": true,               /* Enable error reporting for fallthrough cases in switch statements. */\n    // \"noUncheckedIndexedAccess\": true,                 /* Add 'undefined' to a type when accessed using an index. */\n    // \"noImplicitOverride\": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */\n    // \"noPropertyAccessFromIndexSignature\": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */\n    // \"allowUnusedLabels\": true,                        /* Disable error reporting for unused labels. */\n    // \"allowUnreachableCode\": true,                     /* Disable error reporting for unreachable code. */\n\n    /* Completeness */\n    // \"skipDefaultLibCheck\": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */\n    \"skipLibCheck\": true,                                 /* Skip type checking all .d.ts files. */\n  },\n  \"exclude\": [\"node_modules\", \"test\", \"example\", \"dist\", \"build.ts\"]\n  // \"include\": [\"src/**/*\"]\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"resolveJsonModule\": true,\n    \"preserveSymlinks\": true,\n    /* Visit https://aka.ms/tsconfig to read more about this file */\n\n    /* Projects */\n    // \"incremental\": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */\n    // \"composite\": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */\n    // \"tsBuildInfoFile\": \"./.tsbuildinfo\",              /* Specify the path to .tsbuildinfo incremental compilation file. */\n    // \"disableSourceOfProjectReferenceRedirect\": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */\n    // \"disableSolutionSearching\": true,                 /* Opt a project out of multi-project reference checking when editing. */\n    // \"disableReferencedProjectLoad\": true,             /* Reduce the number of projects loaded automatically by TypeScript. */\n\n    /* Language and Environment */\n    \"target\": \"ES2021\",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */\n    \"lib\": [\"ESNext\"],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */\n    // \"jsx\": \"preserve\",                                /* Specify what JSX code is generated. */\n    // \"experimentalDecorators\": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */\n    // \"emitDecoratorMetadata\": true,                    /* Emit design-type metadata for decorated declarations in source files. */\n    // \"jsxFactory\": \"\",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */\n    // \"jsxFragmentFactory\": \"\",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */\n    // \"jsxImportSource\": \"\",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */\n    // \"reactNamespace\": \"\",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */\n    // \"noLib\": true,                                    /* Disable including any library files, including the default lib.d.ts. */\n    // \"useDefineForClassFields\": true,                  /* Emit ECMAScript-standard-compliant class fields. */\n    // \"moduleDetection\": \"auto\",                        /* Control what method is used to detect module-format JS files. */\n\n    /* Modules */\n    \"module\": \"ESNext\",                                /* Specify what module code is generated. */\n    // \"rootDir\": \"./src\",                                  /* Specify the root folder within your source files. */\n    \"moduleResolution\": \"bundler\",                       /* Specify how TypeScript looks up a file from a given module specifier. */\n    // \"baseUrl\": \"./src\",                                  /* Specify the base directory to resolve non-relative module names. */\n    // \"paths\": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */\n    // \"rootDirs\": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */\n    // \"typeRoots\": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */\n    // \"types\": [\"bun-types\"],                                      /* Specify type package names to be included without being referenced in a source file. */\n    // \"allowUmdGlobalAccess\": true,                     /* Allow accessing UMD globals from modules. */\n    // \"moduleSuffixes\": [],                             /* List of file name suffixes to search when resolving a module. */\n    // \"resolveJsonModule\": true,                        /* Enable importing .json files. */\n    // \"noResolve\": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */\n\n    /* JavaScript Support */\n    // \"allowJs\": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */\n    // \"checkJs\": true,                                  /* Enable error reporting in type-checked JavaScript files. */\n    // \"maxNodeModuleJsDepth\": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */\n\n    /* Emit */\n    \"declaration\": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */\n    // \"declarationMap\": true,                           /* Create sourcemaps for d.ts files. */\n    // \"emitDeclarationOnly\": true,                      /* Only output d.ts files and not JavaScript files. */\n    // \"sourceMap\": true,                                /* Create source map files for emitted JavaScript files. */\n    // \"outFile\": \"./\",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */\n    // \"outDir\": \"./dist\",                                   /* Specify an output folder for all emitted files. */\n    // \"removeComments\": true,                           /* Disable emitting comments. */\n    \"noEmit\": true,                                   /* Disable emitting files from a compilation. */\n    // \"importHelpers\": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */\n    // \"importsNotUsedAsValues\": \"remove\",               /* Specify emit/checking behavior for imports that are only used for types. */\n    // \"downlevelIteration\": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */\n    // r\"sourceRoot\": \"\",                                 /* Specify the root path for debuggers to find the reference source code. */\n    // \"mapRoot\": \"\",                                    /* Specify the location where debugger should locate map files instead of generated locations. */\n    // \"inlineSourceMap\": true,                          /* Include sourcemap files inside the emitted JavaScript. */\n    // \"inlineSources\": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */\n    // \"emitBOM\": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */\n    // \"newLine\": \"crlf\",                                /* Set the newline character for emitting files. */\n    // \"stripInternal\": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */\n    // \"noEmitHelpers\": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */\n    // \"noEmitOnError\": true,                            /* Disable emitting files if any type checking errors are reported. */\n    // \"preserveConstEnums\": true,                       /* Disable erasing 'const enum' declarations in generated code. */\n    // \"declarationDir\": \"./\",                           /* Specify the output directory for generated declaration files. */\n    // \"preserveValueImports\": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */\n\n    /* Interop Constraints */\n    // \"isolatedModules\": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */\n    \"allowSyntheticDefaultImports\": true,             /* Allow 'import x from y' when a module doesn't have a default export. */\n    \"esModuleInterop\": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */\n    // \"preserveSymlinks\": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */\n    \"forceConsistentCasingInFileNames\": true,            /* Ensure that casing is correct in imports. */\n\n    /* Type Checking */\n    \"strict\": true,                                      /* Enable all strict type-checking options. */\n    // \"noImplicitAny\": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */\n    // \"strictNullChecks\": true,                         /* When type checking, take into account 'null' and 'undefined'. */\n    // \"strictFunctionTypes\": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */\n    // \"strictBindCallApply\": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */\n    // \"strictPropertyInitialization\": true,             /* Check for class properties that are declared but not set in the constructor. */\n    // \"noImplicitThis\": true,                           /* Enable error reporting when 'this' is given the type 'any'. */\n    // \"useUnknownInCatchVariables\": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */\n    // \"alwaysStrict\": true,                             /* Ensure 'use strict' is always emitted. */\n    // \"noUnusedLocals\": true,                           /* Enable error reporting when local variables aren't read. */\n    // \"noUnusedParameters\": true,                       /* Raise an error when a function parameter isn't read. */\n    // \"exactOptionalPropertyTypes\": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */\n    // \"noImplicitReturns\": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */\n    // \"noFallthroughCasesInSwitch\": true,               /* Enable error reporting for fallthrough cases in switch statements. */\n    // \"noUncheckedIndexedAccess\": true,                 /* Add 'undefined' to a type when accessed using an index. */\n    // \"noImplicitOverride\": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */\n    // \"noPropertyAccessFromIndexSignature\": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */\n    // \"allowUnusedLabels\": true,                        /* Disable error reporting for unused labels. */\n    // \"allowUnreachableCode\": true,                     /* Disable error reporting for unreachable code. */\n\n    /* Completeness */\n    // \"skipDefaultLibCheck\": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */\n    \"skipLibCheck\": true,                                 /* Skip type checking all .d.ts files. */\n  },\n  \"exclude\": [\"node_modules\"]\n  // \"include\": [\"src/**/*\"]\n}\n"
  },
  {
    "path": "tsconfig.test.json",
    "content": "{\n  \"compilerOptions\": {\n    \"preserveSymlinks\": true,\n    /* Visit https://aka.ms/tsconfig to read more about this file */\n\n    /* Projects */\n    \"incremental\": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */\n    // \"composite\": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */\n    // \"tsBuildInfoFile\": \"./.tsbuildinfo\",              /* Specify the path to .tsbuildinfo incremental compilation file. */\n    // \"disableSourceOfProjectReferenceRedirect\": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */\n    // \"disableSolutionSearching\": true,                 /* Opt a project out of multi-project reference checking when editing. */\n    // \"disableReferencedProjectLoad\": true,             /* Reduce the number of projects loaded automatically by TypeScript. */\n\n    /* Language and Environment */\n    \"target\": \"ES2020\",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */\n    \"lib\": [\"ESNext\"],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */\n    // \"jsx\": \"preserve\",                                /* Specify what JSX code is generated. */\n    // \"experimentalDecorators\": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */\n    // \"emitDecoratorMetadata\": true,                    /* Emit design-type metadata for decorated declarations in source files. */\n    // \"jsxFactory\": \"\",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */\n    // \"jsxFragmentFactory\": \"\",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */\n    // \"jsxImportSource\": \"\",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */\n    // \"reactNamespace\": \"\",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */\n    // \"noLib\": true,                                    /* Disable including any library files, including the default lib.d.ts. */\n    // \"useDefineForClassFields\": true,                  /* Emit ECMAScript-standard-compliant class fields. */\n    // \"moduleDetection\": \"auto\",                        /* Control what method is used to detect module-format JS files. */\n\n    /* Modules */\n    \"module\": \"ES2022\",                                /* Specify what module code is generated. */\n    // \"rootDir\": \"./src\",                                  /* Specify the root folder within your source files. */\n    \"moduleResolution\": \"node\",                       /* Specify how TypeScript looks up a file from a given module specifier. */\n    // \"baseUrl\": \"./src\",                                  /* Specify the base directory to resolve non-relative module names. */\n    // \"paths\": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */\n    // \"rootDirs\": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */\n    // \"typeRoots\": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */\n    \"types\": [\"@types/bun\"],                                      /* Specify type package names to be included without being referenced in a source file. */\n    // \"allowUmdGlobalAccess\": true,                     /* Allow accessing UMD globals from modules. */\n    // \"moduleSuffixes\": [],                             /* List of file name suffixes to search when resolving a module. */\n    \"resolveJsonModule\": true,                        /* Enable importing .json files. */\n    // \"noResolve\": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */\n\n    /* JavaScript Support */\n    // \"allowJs\": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */\n    // \"checkJs\": true,                                  /* Enable error reporting in type-checked JavaScript files. */\n    // \"maxNodeModuleJsDepth\": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */\n\n    /* Emit */\n    // \"declaration\": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */\n    // \"declarationMap\": true,                           /* Create sourcemaps for d.ts files. */\n    // \"emitDeclarationOnly\": true,                      /* Only output d.ts files and not JavaScript files. */\n    // \"sourceMap\": true,                                /* Create source map files for emitted JavaScript files. */\n    // \"outFile\": \"./\",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */\n    // \"outDir\": \"./dist\",                                   /* Specify an output folder for all emitted files. */\n    // \"removeComments\": true,                           /* Disable emitting comments. */\n    \"noEmit\": true,                                   /* Disable emitting files from a compilation. */\n    // \"importHelpers\": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */\n    // \"importsNotUsedAsValues\": \"remove\",               /* Specify emit/checking behavior for imports that are only used for types. */\n    // \"downlevelIteration\": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */\n    // r\"sourceRoot\": \"\",                                 /* Specify the root path for debuggers to find the reference source code. */\n    // \"mapRoot\": \"\",                                    /* Specify the location where debugger should locate map files instead of generated locations. */\n    // \"inlineSourceMap\": true,                          /* Include sourcemap files inside the emitted JavaScript. */\n    // \"inlineSources\": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */\n    // \"emitBOM\": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */\n    // \"newLine\": \"crlf\",                                /* Set the newline character for emitting files. */\n    // \"stripInternal\": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */\n    // \"noEmitHelpers\": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */\n    // \"noEmitOnError\": true,                            /* Disable emitting files if any type checking errors are reported. */\n    // \"preserveConstEnums\": true,                       /* Disable erasing 'const enum' declarations in generated code. */\n    // \"declarationDir\": \"./\",                           /* Specify the output directory for generated declaration files. */\n    // \"preserveValueImports\": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */\n\n    /* Interop Constraints */\n    // \"isolatedModules\": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */\n    \"allowSyntheticDefaultImports\": true,             /* Allow 'import x from y' when a module doesn't have a default export. */\n    \"esModuleInterop\": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */\n    // \"preserveSymlinks\": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */\n    \"forceConsistentCasingInFileNames\": true,            /* Ensure that casing is correct in imports. */\n\n    /* Type Checking */\n    \"strict\": true,                                      /* Enable all strict type-checking options. */\n    // \"noImplicitAny\": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */\n    // \"strictNullChecks\": true,                         /* When type checking, take into account 'null' and 'undefined'. */\n    // \"strictFunctionTypes\": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */\n    // \"strictBindCallApply\": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */\n    // \"strictPropertyInitialization\": true,             /* Check for class properties that are declared but not set in the constructor. */\n    // \"noImplicitThis\": true,                           /* Enable error reporting when 'this' is given the type 'any'. */\n    // \"useUnknownInCatchVariables\": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */\n    // \"alwaysStrict\": true,                             /* Ensure 'use strict' is always emitted. */\n    // \"noUnusedLocals\": true,                           /* Enable error reporting when local variables aren't read. */\n    // \"noUnusedParameters\": true,                       /* Raise an error when a function parameter isn't read. */\n    // \"exactOptionalPropertyTypes\": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */\n    // \"noImplicitReturns\": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */\n    // \"noFallthroughCasesInSwitch\": true,               /* Enable error reporting for fallthrough cases in switch statements. */\n    // \"noUncheckedIndexedAccess\": true,                 /* Add 'undefined' to a type when accessed using an index. */\n    // \"noImplicitOverride\": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */\n    // \"noPropertyAccessFromIndexSignature\": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */\n    // \"allowUnusedLabels\": true,                        /* Disable error reporting for unused labels. */\n    // \"allowUnreachableCode\": true,                     /* Disable error reporting for unreachable code. */\n\n    /* Completeness */\n    // \"skipDefaultLibCheck\": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */\n    \"skipLibCheck\": true,                                 /* Skip type checking all .d.ts files. */\n  },\n  \"exclude\": [\"node_modules\", \"test/cloudflare/**/*\"],\n  \"include\": [\"test/types/**/*\"]\n}\n"
  }
]