barejs 0.2.8 → 0.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -12
- package/dist/edge.js +23 -23
- package/dist/index.js +127 -127
- package/dist/node.js +127 -127
- package/dist/types/core/bare.d.ts +15 -3
- package/dist/types/core/router.d.ts +1 -0
- package/dist/types/edge.d.ts +11 -0
- package/dist/types/index.d.ts +1 -1
- package/llms.txt +4 -4
- package/package.json +2 -2
- package/src/core/bare.ts +55 -20
- package/src/core/context.ts +1 -1
- package/src/core/router.ts +5 -1
- package/src/edge.ts +26 -1
- package/src/index.ts +1 -1
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
<div align="center">
|
|
2
2
|
<br />
|
|
3
3
|
<h1>Bare<span style="color: #F7DF1E;">JS</span></h1>
|
|
4
|
-
<p><strong>The batteries-included
|
|
5
|
-
<p><i>JIT-compiled O(1) radix router, LIFO context pooling & optional <code>uWebSockets.js</code> · Unified validation (Standard Schema v1: Valibot, ArkType, Zod 4 · TypeBox · JSON Schema) with response secret-stripping · End-to-end <code>bareTreaty</code> RPC, typed WebSockets, SSE, generator streaming, OpenAPI 3.1 & JSON-RPC 2.0 · Built-in <code>bareAuth</code> (JWT/JWKS), <code>basicAuth</code>, <code>Hash</code> (Argon2id/scrypt), <code>cors</code>, <code>csrf</code>, <code>rateLimit</code>, <code>idempotency</code>, <code>circuitBreaker</code>, <code>compress</code> (zstd/br/gzip), <code>file()</code>/<code>staticFile</code>, <code>app.macro()</code>, <code>app.cron()</code> & W3C <code>tracing()</code> ·
|
|
4
|
+
<p><strong>The batteries-included TypeScript web framework for Bun, Node.js, Deno, Edge & AWS Lambda.</strong></p>
|
|
5
|
+
<p><i>JIT-compiled O(1) radix router, LIFO context pooling & optional <code>uWebSockets.js</code> · Unified validation (Standard Schema v1: Valibot, ArkType, Zod 4 · TypeBox · JSON Schema) with response secret-stripping · End-to-end <code>bareTreaty</code> RPC, typed WebSockets, SSE, generator streaming, OpenAPI 3.1 & JSON-RPC 2.0 · Built-in <code>bareAuth</code> (JWT/JWKS), <code>basicAuth</code>, <code>Hash</code> (Argon2id/scrypt), <code>cors</code>, <code>csrf</code>, <code>rateLimit</code>, <code>idempotency</code>, <code>circuitBreaker</code>, <code>compress</code> (zstd/br/gzip), <code>file()</code>/<code>staticFile</code>, <code>app.macro()</code>, <code>app.cron()</code> & W3C <code>tracing()</code> · Modular subpaths: <code>barejs/edge</code> (53 KB), <code>barejs/html</code>, <code>barejs/etag</code>, <code>barejs/cache</code>, <code>barejs/jsx</code>, <code>barejs/ssg</code>, <code>barejs/aws-lambda</code>, <code>barejs/cloudflare-pages</code> & <code>barejs/netlify</code>.</i></p>
|
|
6
6
|
|
|
7
7
|
<p>
|
|
8
8
|
<a href="https://www.npmjs.com/package/barejs"><img src="https://img.shields.io/npm/v/barejs?style=for-the-badge&logo=npm&color=CB3837" alt="NPM Version"></a>
|
|
@@ -44,6 +44,9 @@ app.listen(3000);
|
|
|
44
44
|
```bash
|
|
45
45
|
# Official multi-runtime starter CLI (Bun, Node.js, Node.js + uWebSockets.js, Deno)
|
|
46
46
|
bun create barejs my-app # or --bun | --node | --node-uws | --deno
|
|
47
|
+
|
|
48
|
+
# Optional: Install the official BareJS AI Agent Skill (Claude Code, Cursor, Codex, OpenCode)
|
|
49
|
+
bunx skills add xarhang/bareJS
|
|
47
50
|
```
|
|
48
51
|
|
|
49
52
|
<details>
|
|
@@ -60,6 +63,7 @@ deno add npm:barejs # Deno (>= 2.0)
|
|
|
60
63
|
- **Deno:** `Deno.serve({ port: 3000 }, (req, info) => app.fetch(req, info.remoteAddr.hostname));`
|
|
61
64
|
- **Edge Workers:** `import { BareJS } from 'barejs/edge'; export default app;` *(Cloudflare Workers, Vercel Edge, Deno Deploy — zero `node:*` imports)*
|
|
62
65
|
- **AWS Lambda:** `import { awsLambda } from 'barejs/aws-lambda'; export const handler = awsLambda(app);` *(API Gateway v1/v2 & ALB)*
|
|
66
|
+
- **Meta Frameworks:** `const app = new BareJS({ prefix: '/api' }); export const GET = app.fetch;` *(Next.js App Router, Astro, SvelteKit, Nuxt/Nitro, Remix, SolidStart, TanStack Start — [recipes](./docs/integrations.md))*
|
|
63
67
|
|
|
64
68
|
</details>
|
|
65
69
|
|
|
@@ -91,14 +95,14 @@ Everything below ships in `barejs` with full TypeScript types — no extra packa
|
|
|
91
95
|
|
|
92
96
|
| Area | Built-In APIs & Exports |
|
|
93
97
|
| :--- | :--- |
|
|
94
|
-
| **Routing & Core** | `BareJS`, `BareRouter`, optional params (`:type?`), regex params (`:id{[0-9]+}`), `*` wildcards, `app.group()`, `app.route()`, `app.use(plugin)`, `app.derive()`, `app.macro()`, `app.onRequest()`, `app.onResponse()`, `app.onError()`, `app.setNotFound()`, `app.request()`, `app.listenCluster()`, native `tls`, `uWebSockets.js` (`engine: 'uws'`), lazy LIFO `Context` pool |
|
|
98
|
+
| **Routing & Core** | `BareJS`, `BareRouter`, `new BareJS({ prefix })` / `app.basePath()`, optional params (`:type?`), regex params (`:id{[0-9]+}`), `*` wildcards, `app.group()`, `app.route()`, `app.use(plugin)`, `app.derive()`, `app.macro()`, `app.onRequest()`, `app.onResponse()`, `app.onError()`, `app.setNotFound()`, `app.request()`, `app.listenCluster()`, native `tls`, `uWebSockets.js` (`engine: 'uws'`), lazy LIFO `Context` pool |
|
|
95
99
|
| **Validation & Schemas** | `RouteSchemas` (`body`, `query`, `params`, `headers`, `cookies`, `response` single or per-status `{ 200, 404 }`, `maxBodySize`, `stripUnknown`) — **Standard Schema v1** (Valibot, ArkType, Zod 4, Effect), **TypeBox** (`Type`/`t`), **Zod** (`Z`/`z`), **Native** (`native()`), auto-coercion, recursive response secret-field stripping |
|
|
96
100
|
| **Typed RPC & Docs** | `bareTreaty(app \| url)` (chained Proxy RPC + typed `.subscribe()` WebSockets), `bareClient(app \| url)` (with non-throwing `client.safe.*`), `app.docs()` (**OpenAPI 3.1** + Scalar UI), `app.rpc()` (**JSON-RPC 2.0**) |
|
|
97
101
|
| **Auth & Security** | `bareAuth()` (HS256/RS256/ES256/JWKS + `createToken`, `revokeToken`, `isTokenRevoked`), `basicAuth()`, `hasRole()`, `Hash` (Argon2id/bcrypt/scrypt), HMAC-signed `HttpOnly` cookies (`ctx.setCookie` / `ctx.getSignedCookie`), `cors()`, `csrf()`, `securityHeaders()`, `rateLimit()`, `trustProxy` CIDR allowlist, CRLF injection guards |
|
|
98
102
|
| **Resilience & State** | `idempotency()` (`409` in-flight + `X-Idempotent-Replayed`), `createSingleflight()`, `circuitBreaker()`, `timeout()`, `redisStore()` (`Bun.redis` / `ioredis`), `app.cron()`, `app.onDrain()` |
|
|
99
103
|
| **Real-Time, Files & HTML** | `app.ws('/ws/:room')` (fail-closed schemas + pub/sub), `ctx.sse()`, **Generator Streaming** (`function*` / `async function*`), `file()` 1-liner (root jail + download), `staticFile()` (ETag/`304`/Range `206`/SPA), `ctx.upload()` / `ctx.uploadStream()`, `compress()` (`zstd`/`br`/`gzip`), `html`/`raw` (`barejs/html`), `etag()` (`barejs/etag`) |
|
|
100
104
|
| **Observability** | Zero-dep W3C `tracing()` (`traceparent` + `Server-Timing`), `serverTiming()`, `logger()`, `app.useLog({ format: 'json' })`, `healthcheck()` |
|
|
101
|
-
| **External Interop** | Standard `Request`/`Response` works directly with **Better-Auth**, **GraphQL Yoga**, **Auth0**, **Clerk**, **Sentry**, **OpenTelemetry** ([recipes](./docs/integrations.md)) |
|
|
105
|
+
| **External Interop** | Standard `Request`/`Response` works directly with **Next.js**, **Astro**, **SvelteKit**, **Nuxt**, **Remix**, **SolidStart**, **TanStack Start**, **Better-Auth**, **GraphQL Yoga**, **Auth0**, **Clerk**, **Sentry**, **OpenTelemetry** ([recipes](./docs/integrations.md)) |
|
|
102
106
|
|
|
103
107
|
---
|
|
104
108
|
|
|
@@ -111,8 +115,10 @@ Everything below ships in `barejs` with full TypeScript types — no extra packa
|
|
|
111
115
|
import { BareJS, bareTreaty, bareAuth } from 'barejs';
|
|
112
116
|
|
|
113
117
|
const authPlugin = new BareJS()
|
|
114
|
-
.macro(
|
|
115
|
-
|
|
118
|
+
.macro({
|
|
119
|
+
auth: {
|
|
120
|
+
beforeHandle: (ctx, role: string) => (ctx.user?.role === role ? undefined : ctx.status(403).json({ error: 'Forbidden' }))
|
|
121
|
+
}
|
|
116
122
|
});
|
|
117
123
|
|
|
118
124
|
const app = new BareJS()
|
|
@@ -138,7 +144,7 @@ const app = new BareJS()
|
|
|
138
144
|
.use(securityHeaders(), cors({ origin: 'https://app.example.com' }), etag())
|
|
139
145
|
.get('/catalog', () => ({ items: ['a', 'b'] })) // Automatic W/"..." ETag & 304 Not Modified
|
|
140
146
|
.post('/charge', idempotency({ ttlMs: 86_400_000 }), () => ({ paid: true }))
|
|
141
|
-
.get('/metrics', basicAuth({
|
|
147
|
+
.get('/metrics', basicAuth({ user: 'ops', pass: process.env.OPS_PASSWORD! }), () => 'ok');
|
|
142
148
|
```
|
|
143
149
|
|
|
144
150
|
</details>
|
|
@@ -208,10 +214,10 @@ Measured in-process on **Bun** with [`mitata`](https://github.com/evanwash/mitat
|
|
|
208
214
|
|
|
209
215
|
| Scenario | **BareJS** | **ElysiaJS** | **Hono** |
|
|
210
216
|
| :--- | :---: | :---: | :---: |
|
|
211
|
-
| **1. 100 Routes + Dynamic Params** | **`
|
|
212
|
-
| **2. 10 Middlewares + Deep Path** | **`
|
|
213
|
-
| **3. POST JSON + Schema Validation** | **`2.
|
|
214
|
-
| **4. Async Handler + Query Parsing** |
|
|
217
|
+
| **1. 100 Routes + Dynamic Params** | **`803 ns`**<br><sub>`p99: 4.36 µs`</sub> | `1.23 µs`<br><sub>`p99: 5.38 µs`</sub> | `2.88 µs`<br><sub>`p99: 11.42 µs`</sub> |
|
|
218
|
+
| **2. 10 Middlewares + Deep Path** | **`741 ns`**<br><sub>`p99: 4.14 µs`</sub> | `1.24 µs`<br><sub>`p99: 6.04 µs`</sub> | `3.20 µs`<br><sub>`p99: 10.69 µs`</sub> |
|
|
219
|
+
| **3. POST JSON + Schema Validation** | **`2.36 µs`**<br><sub>`p99: 9.36 µs`</sub> | `3.11 µs`<br><sub>`p99: 12.47 µs`</sub> | `3.21 µs`<br><sub>`p99: 13.48 µs`</sub> |
|
|
220
|
+
| **4. Async Handler + Query Parsing** | **`1.27 µs`**<br><sub>`p99: 5.15 µs`</sub> | `1.55 µs`<br><sub>`p99: 6.71 µs`</sub> | `2.17 µs`<br><sub>`p99: 9.51 µs`</sub> |
|
|
215
221
|
|
|
216
222
|
> Last Updated: 2026-12-01 (github action — `linux`, INTEL(R) XEON(R) PLATINUM 8573C, Bun `1.4.5`, Elysia `1.4.21`, Hono `4.11.4`)
|
|
217
223
|
|
|
@@ -225,5 +231,5 @@ See **[BENCHMARKS.md](./BENCHMARKS.md)** for all 7 scenarios & reproduction step
|
|
|
225
231
|
|
|
226
232
|
- **[Documentation Site](https://xarhang.github.io/bareJS/)** — Interactive docs with `Ctrl+K` instant search, sticky TOC, and live benchmark dashboard.
|
|
227
233
|
- **[Comprehensive Guide](./docs/guide.md)** · **[API Reference](./docs/reference.md)** · **[Integrations](./docs/integrations.md)** · **[Examples](./examples/)** · **[Benchmarks](./BENCHMARKS.md)** · **[Security](./SECURITY.md)** · **[`llms.txt`](./llms.txt)** / **[`llms-full.txt`](https://xarhang.github.io/bareJS/llms-full.txt)** (AI docs)
|
|
228
|
-
- **Status:** Active `0.2.x` (**
|
|
234
|
+
- **Status:** Active `0.2.x` (**511 tests across 38 files**), verified in [CI](./.github/workflows/ci.yml) across **Bun**, **Node.js 20 & 22**, and **Deno 2**.
|
|
229
235
|
- **License:** [MIT](./LICENSE) — Maintained by [xarhang](https://github.com/xarhang).
|
package/dist/edge.js
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
import*as r from"@sinclair/typebox/compiler";import{z as
|
|
1
|
+
import*as r from"@sinclair/typebox/compiler";import{z as ER}from"zod";var c=ER,A=(R,f=400)=>Response.json(R,{status:f,headers:{"Content-Type":"application/json"}});var gR=(R)=>{let f=a(R),_=async(Z,$)=>{try{let Q=Z instanceof Object&&"req"in Z,G=Q?await Z.jsonBody():await Z.json(),Y=f(G);if(!Y.ok)return A({status:"error",code:Y.error?.code||"TYPE_MISMATCH",message:Y.error?.message||"Validation failed",...Y.error?.path?{field:Y.error.path}:{}});if(Q)Z.body=Y.data;return $?$():void 0}catch(Q){if(Q?.status===413)return A({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return A({status:"error",message:"Invalid JSON payload"})}};return _.__schema=R,_};var t=(R)=>Boolean(R&&typeof R==="object"&&"~standard"in R&&R["~standard"]&&typeof R["~standard"].validate==="function"),p=(R)=>{if(!R||typeof R!=="object")return{ok:!1,error:{message:"Invalid validator result"}};if(Array.isArray(R.issues))return{ok:!1,error:R.issues.map((f)=>({message:f?.message||"Validation failed",...f?.path?{path:f.path.map((_)=>typeof _==="object"&&_!==null&&("key"in _)?_.key:_)}:{}}))};if("value"in R)return{ok:!0,data:R.value};return{ok:!1,error:{message:"Invalid validator result"}}},zR=(R)=>{let f=async(_,Z)=>{try{let $=_ instanceof Object&&"req"in _,Q=$?await _.jsonBody():await _.json(),G=await R["~standard"].validate(Q),Y=p(G);if(!Y.ok)return A({status:"error",code:"VALIDATION_FAILED",errors:Y.error});if($)_.body=Y.data;return Z?Z():void 0}catch($){if($?.status===413)return A({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return A({status:"error",message:"Invalid JSON payload"})}};return f.__schema=R,f};var s=(R,f)=>{if(f===void 0)return!0;if(Array.isArray(f))return f.some((_)=>s(R,_));if(f==="array")return Array.isArray(R);if(f==="integer")return typeof R==="number"&&Number.isInteger(R);if(f==="number")return typeof R==="number"&&Number.isFinite(R);if(f==="object")return R!==null&&typeof R==="object"&&!Array.isArray(R);if(f==="null")return R===null;return typeof R===f},i=(R,f)=>{if(R===f)return!0;if(typeof R!=="object"||typeof f!=="object"||R===null||f===null)return!1;if(Array.isArray(R)!==Array.isArray(f))return!1;if(Array.isArray(R)){if(R.length!==f.length)return!1;for(let Z=0;Z<R.length;Z++)if(!i(R[Z],f[Z]))return!1;return!0}let _=Object.keys(R);if(_.length!==Object.keys(f).length)return!1;for(let Z=0;Z<_.length;Z++){let $=_[Z];if(!Object.hasOwn(f,$)||!i(R[$],f[$]))return!1}return!0},V=(R,f,_,Z)=>{if(!f||typeof f!=="object")return{ok:!0};if(Object.hasOwn(f,"const")&&!i(R,f.const))return{ok:!1,error:{message:`Value at '${_||"root"}' must equal ${JSON.stringify(f.const)}`,path:_}};if(Array.isArray(f.enum)&&!f.enum.some(($)=>i($,R)))return{ok:!1,error:{message:`Value at '${_||"root"}' must be one of enum values`,path:_}};if(f.not&&typeof f.not==="object"&&V(R,f.not,_,!1).ok)return{ok:!1,error:{message:`Value at '${_||"root"}' must not match the 'not' schema`,path:_}};if(Array.isArray(f.allOf))for(let $=0;$<f.allOf.length;$++){let Q=V(R,f.allOf[$],_,!1);if(!Q.ok)return Q}if(Array.isArray(f.anyOf)){let $=!1;for(let Q=0;Q<f.anyOf.length;Q++)if(V(R,f.anyOf[Q],_,!1).ok){$=!0;break}if(!$)return{ok:!1,error:{message:`Value at '${_||"root"}' failed anyOf constraint`,path:_}}}if(Array.isArray(f.oneOf)){let $=0;for(let Q=0;Q<f.oneOf.length;Q++)if(V(R,f.oneOf[Q],_,!1).ok)$++;if($!==1)return{ok:!1,error:{message:`Value at '${_||"root"}' must match exactly one schema in oneOf`,path:_}}}if(!s(R,f.type))return{ok:!1,error:{message:_?`Field '${_}' must be of type ${f.type}`:`Expected type ${f.type}`,path:_}};if(typeof R==="number"){if(typeof f.minimum==="number"&&R<f.minimum)return{ok:!1,error:{message:`Field '${_}' must be >= ${f.minimum}`,path:_}};if(typeof f.maximum==="number"&&R>f.maximum)return{ok:!1,error:{message:`Field '${_}' must be <= ${f.maximum}`,path:_}};if(typeof f.multipleOf==="number"&&f.multipleOf>0){let $=R/f.multipleOf;if(Math.abs($-Math.round($))>0.000000001*Math.max(1,Math.abs($)))return{ok:!1,error:{message:`Field '${_}' must be a multiple of ${f.multipleOf}`,path:_}}}if(typeof f.exclusiveMinimum==="number"&&R<=f.exclusiveMinimum)return{ok:!1,error:{message:`Field '${_}' must be > ${f.exclusiveMinimum}`,path:_}};if(typeof f.exclusiveMaximum==="number"&&R>=f.exclusiveMaximum)return{ok:!1,error:{message:`Field '${_}' must be < ${f.exclusiveMaximum}`,path:_}}}if(typeof R==="string"){if(typeof f.minLength==="number"&&R.length<f.minLength)return{ok:!1,error:{message:`Field '${_}' length must be >= ${f.minLength}`,path:_}};if(typeof f.maxLength==="number"&&R.length>f.maxLength)return{ok:!1,error:{message:`Field '${_}' length must be <= ${f.maxLength}`,path:_}};if(typeof f.pattern==="string")try{if(!new RegExp(f.pattern).test(R))return{ok:!1,error:{message:`Field '${_}' does not match pattern`,path:_}}}catch{}}if(Array.isArray(R)){if(typeof f.minItems==="number"&&R.length<f.minItems)return{ok:!1,error:{message:`Field '${_}' must have at least ${f.minItems} items`,path:_}};if(typeof f.maxItems==="number"&&R.length>f.maxItems)return{ok:!1,error:{message:`Field '${_}' must have at most ${f.maxItems} items`,path:_}};if(f.uniqueItems===!0){for(let $=1;$<R.length;$++)for(let Q=0;Q<$;Q++)if(i(R[$],R[Q]))return{ok:!1,error:{message:`Field '${_}' must have unique items`,path:_}}}if(Array.isArray(f.items)){let $=Math.min(R.length,f.items.length);for(let Q=0;Q<$;Q++){let G=V(R[Q],f.items[Q],_?`${_}[${Q}]`:`[${Q}]`,!1);if(!G.ok)return G}}else if(f.items&&typeof f.items==="object")for(let $=0;$<R.length;$++){let Q=V(R[$],f.items,_?`${_}[${$}]`:`[${$}]`,!1);if(!Q.ok)return Q}}if(R!==null&&typeof R==="object"&&!Array.isArray(R)){let $=f.properties&&typeof f.properties==="object"?f.properties:null,Q=Array.isArray(f.required)?f.required:null,G=Q?new Set(Q):null;if(typeof f.minProperties==="number"||typeof f.maxProperties==="number"){let T=Object.keys(R).length;if(typeof f.minProperties==="number"&&T<f.minProperties)return{ok:!1,error:{message:`Object at '${_||"root"}' must have at least ${f.minProperties} properties`,path:_}};if(typeof f.maxProperties==="number"&&T>f.maxProperties)return{ok:!1,error:{message:`Object at '${_||"root"}' must have at most ${f.maxProperties} properties`,path:_}}}if(Q)for(let T=0;T<Q.length;T++){let B=Q[T];if(!Object.hasOwn(R,B)||R[B]===void 0){let I=$?.[B]?.type;return{ok:!1,error:{message:I?`Field '${B}' must be of type ${I}`:`Missing required field '${B}'`,path:_?`${_}.${B}`:B}}}}if($){let T=Object.keys($);for(let B=0;B<T.length;B++){let I=T[B];if(!(Object.hasOwn(R,I)&&R[I]!==void 0)){if(Z&&!G)return{ok:!1,error:{message:`Field '${I}' must be of type ${$[I]?.type}`,path:_?`${_}.${I}`:I}};continue}let X=_?`${_}.${I}`:I,D=V(R[I],$[I],X,!1);if(!D.ok)return D}}let Y=new Set;if(f.patternProperties&&typeof f.patternProperties==="object"){let T=Object.keys(R);for(let[B,I]of Object.entries(f.patternProperties)){let u;try{u=new RegExp(B)}catch{continue}for(let X=0;X<T.length;X++){let D=T[X];if(!u.test(D))continue;Y.add(D);let M=V(R[D],I,_?`${_}.${D}`:D,!1);if(!M.ok)return M}}}if(f.dependentRequired&&typeof f.dependentRequired==="object")for(let[T,B]of Object.entries(f.dependentRequired)){if(!Object.hasOwn(R,T)||!Array.isArray(B))continue;for(let I of B)if(!Object.hasOwn(R,I))return{ok:!1,error:{message:`Field '${I}' is required when '${T}' is present`,path:_?`${_}.${I}`:I}}}if(f.additionalProperties===!1){let T=Object.keys(R);for(let B=0;B<T.length;B++){let I=T[B];if((!$||!Object.hasOwn($,I))&&!Y.has(I))return{ok:!1,error:{code:"ADDITIONAL_PROPERTIES",message:`Unknown field '${I}' is not allowed`,path:_?`${_}.${I}`:I}}}}else if(f.additionalProperties&&typeof f.additionalProperties==="object"){let T=Object.keys(R);for(let B=0;B<T.length;B++){let I=T[B];if((!$||!Object.hasOwn($,I))&&!Y.has(I)){let u=V(R[I],f.additionalProperties,_?`${_}.${I}`:I,!1);if(!u.ok)return u}}}}return{ok:!0}},a=(R)=>{let f=Boolean(R?.anyOf||R?.oneOf||R?.allOf),_=!f&&!Array.isArray(R?.required)&&Boolean(R?.properties),Z=!R?.type||R.type==="object";return($)=>{if(!R||typeof R!=="object")return!$||typeof $!=="object"||Array.isArray($)?{ok:!1,error:{message:"Invalid JSON object payload"}}:{ok:!0,data:$};if(Z&&(!$||typeof $!=="object"||Array.isArray($))&&!f)return{ok:!1,error:{message:"Invalid JSON object payload"}};let Q=V($,R,"",_);return Q.ok?{ok:!0,data:$}:Q}},y=(R)=>{if(R&&"_def"in R)return(f)=>{let _=R.safeParse(f);return _.success?{ok:!0,data:_.data}:{ok:!1,error:_.error.flatten()}};if(t(R)){let f=R["~standard"].validate;return(_)=>{let Z=f(_);if(Z&&typeof Z.then==="function")return Z.then(($)=>p($),()=>({ok:!1,error:{message:"Validation failed"}}));return p(Z)}}try{let f=r.TypeCompiler.Compile(R);return(_)=>{if(f.Check(_))return{ok:!0,data:_};let Z=f.Errors(_).First();return{ok:!1,error:{message:Z?.message||"Invalid input",path:Z?.path}}}}catch{return a(R)}},e=(R,f,_,Z,$)=>{if(!R)return null;let Q=`ar_${Z}_${$}`,G=`j_${Z}_${$}`,Y=`ai_${Z}_${$}`;if(R.type==="array"&&R.items){let I=e(R.items,Y,`${Q}[${G}] = `,Z+1,$+1);if(I===null)return null;return`if (Array.isArray(${f})) {
|
|
2
2
|
const ${Q} = new Array(${f}.length);
|
|
3
|
-
for (let ${
|
|
4
|
-
const ${
|
|
5
|
-
${
|
|
3
|
+
for (let ${G} = 0; ${G} < ${f}.length; ${G}++) {
|
|
4
|
+
const ${Y} = ${f}[${G}];
|
|
5
|
+
${I}
|
|
6
6
|
}
|
|
7
7
|
${_}${Q};
|
|
8
8
|
} else {
|
|
9
9
|
${_}${f};
|
|
10
|
-
}`}let T=`ao_${Z}_${$}`,
|
|
10
|
+
}`}let T=`ao_${Z}_${$}`,B=v(R,Y,T,Z+1);if(B===null)return null;return`if (Array.isArray(${f})) {
|
|
11
11
|
const ${Q} = new Array(${f}.length);
|
|
12
|
-
for (let ${
|
|
13
|
-
const ${
|
|
14
|
-
if (${
|
|
12
|
+
for (let ${G} = 0; ${G} < ${f}.length; ${G}++) {
|
|
13
|
+
const ${Y} = ${f}[${G}];
|
|
14
|
+
if (${Y} && typeof ${Y} === 'object' && !Array.isArray(${Y})) {
|
|
15
15
|
const ${T} = {};
|
|
16
|
-
${
|
|
16
|
+
${B} ${Q}[${G}] = ${T};
|
|
17
17
|
} else {
|
|
18
|
-
${Q}[${
|
|
18
|
+
${Q}[${G}] = ${Y};
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
21
|
${_}${Q};
|
|
22
22
|
} else {
|
|
23
23
|
${_}${f};
|
|
24
|
-
}`},v=(R,f,_,Z=0)=>{let $=R?.properties;if(!$||typeof $!=="object")return null;let Q="",
|
|
25
|
-
`,T?.type==="array"&&T?.items){let
|
|
26
|
-
${
|
|
24
|
+
}`},v=(R,f,_,Z=0)=>{let $=R?.properties;if(!$||typeof $!=="object")return null;let Q="",G=0;for(let[Y,T]of Object.entries($)){if(Y==="__proto__"||Y==="constructor"||Y==="prototype")continue;let B=JSON.stringify(Y),I=`v_${Z}_${G++}`,u=`d_${Z}_${G}`;if(Q+=`const ${I} = Object.hasOwn(${f}, ${B}) ? ${f}[${B}] : undefined;
|
|
25
|
+
`,T?.type==="array"&&T?.items){let D=e(T.items,I,`${_}[${B}] = `,Z,G);if(D!==null){Q+=`if (${I} !== undefined) {
|
|
26
|
+
${D}
|
|
27
27
|
}
|
|
28
|
-
`;continue}}let
|
|
29
|
-
`,Q+=` if (${
|
|
30
|
-
`,Q+=` const ${
|
|
31
|
-
${
|
|
28
|
+
`;continue}}let X=v(T,I,u,Z+1);if(X!==null)Q+=`if (${I} !== undefined) {
|
|
29
|
+
`,Q+=` if (${I} && typeof ${I} === 'object' && !Array.isArray(${I})) {
|
|
30
|
+
`,Q+=` const ${u} = {};
|
|
31
|
+
${X} ${_}[${B}] = ${u};
|
|
32
32
|
`,Q+=` } else {
|
|
33
|
-
${_}[${
|
|
33
|
+
${_}[${B}] = ${I};
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
|
-
`;else Q+=`if (${
|
|
37
|
-
`}return Q},m=(R)=>{if(!R||typeof R!=="object")return!1;if(Array.isArray(R.anyOf)||Array.isArray(R.oneOf)||Array.isArray(R.allOf))return!0;if(R.additionalProperties&&typeof R.additionalProperties==="object")return!0;if(R.patternProperties&&typeof R.patternProperties==="object")return!0;if(Array.isArray(R.items))return!0;if(R.type==="array"&&R.items)return m(R.items);if(R.properties&&typeof R.properties==="object"){for(let f of Object.values(R.properties))if(m(f))return!0}return!1},RR=(R,f)=>{let _=!1;if(R?.properties&&typeof R.properties==="object")Object.assign(f,R.properties),_=!0;if(Array.isArray(R?.allOf)){for(let Z of R.allOf)if(RR(Z,f))_=!0}return _},P=(R,f)=>{if(!f||typeof f!=="object"||R===null||typeof R!=="object")return R;if(Array.isArray(R)){if(Array.isArray(f.items))return R.map((
|
|
36
|
+
`;else Q+=`if (${I} !== undefined) ${_}[${B}] = ${I};
|
|
37
|
+
`}return Q},m=(R)=>{if(!R||typeof R!=="object")return!1;if(Array.isArray(R.anyOf)||Array.isArray(R.oneOf)||Array.isArray(R.allOf))return!0;if(R.additionalProperties&&typeof R.additionalProperties==="object")return!0;if(R.patternProperties&&typeof R.patternProperties==="object")return!0;if(Array.isArray(R.items))return!0;if(R.type==="array"&&R.items)return m(R.items);if(R.properties&&typeof R.properties==="object"){for(let f of Object.values(R.properties))if(m(f))return!0}return!1},RR=(R,f)=>{let _=!1;if(R?.properties&&typeof R.properties==="object")Object.assign(f,R.properties),_=!0;if(Array.isArray(R?.allOf)){for(let Z of R.allOf)if(RR(Z,f))_=!0}return _},P=(R,f)=>{if(!f||typeof f!=="object"||R===null||typeof R!=="object")return R;if(Array.isArray(R)){if(Array.isArray(f.items))return R.map((G,Y)=>f.items[Y]?P(G,f.items[Y]):G);if(f.items&&typeof f.items==="object")return R.map((G)=>P(G,f.items));return R}let _=f.anyOf||f.oneOf;if(Array.isArray(_)&&_.length>0){let G=null;for(let Y of _)if(Y&&typeof Y==="object"&&y(Y)(R).ok){G=Y;break}if(G){if(f.properties&&typeof f.properties==="object"){let Y={...f.properties,...G.properties||{}},T={};for(let[B,I]of Object.entries(Y)){if(B==="__proto__"||B==="constructor"||B==="prototype")continue;if(Object.hasOwn(R,B)&&R[B]!==void 0)T[B]=P(R[B],I)}return T}return P(R,G)}if(!f.properties)return R}if(Array.isArray(f.allOf)){let G={};if(RR(f,G)){let Y={};for(let[T,B]of Object.entries(G)){if(T==="__proto__"||T==="constructor"||T==="prototype")continue;if(Object.hasOwn(R,T)&&R[T]!==void 0)Y[T]=P(R[T],B)}return Y}}let Z=Boolean(f.properties&&typeof f.properties==="object"),$=Boolean(f.patternProperties&&typeof f.patternProperties==="object"),Q=Boolean(f.additionalProperties&&typeof f.additionalProperties==="object");if(Z||$||Q){let G={},Y=Z?f.properties:null;if(Y)for(let[T,B]of Object.entries(Y)){if(T==="__proto__"||T==="constructor"||T==="prototype")continue;if(Object.hasOwn(R,T)&&R[T]!==void 0)G[T]=P(R[T],B)}if($||Q){let T=$?Object.entries(f.patternProperties).map(([B,I])=>({re:new RegExp(B),sub:I})):[];for(let B of Object.keys(R)){if(B==="__proto__"||B==="constructor"||B==="prototype")continue;if(R[B]===void 0||Y&&Object.hasOwn(Y,B))continue;let I=!1;for(let u=0;u<T.length;u++)if(T[u].re.test(B)){G[B]=P(R[B],T[u].sub),I=!0;break}if(!I&&Q)G[B]=P(R[B],f.additionalProperties)}}return G}return R},d=(R)=>{if(!R||"_def"in R||t(R))return null;if(m(R))return(_)=>P(_,R);if(R.type==="array"&&R.items){if(R.items.type==="array")return(Z)=>P(Z,R);let _=v(R.items,"item","outItem");if(_===null)return(Z)=>P(Z,R);return new Function(`return function(arr) {
|
|
38
38
|
if (!Array.isArray(arr)) return arr;
|
|
39
39
|
const len = arr.length;
|
|
40
40
|
const out = new Array(len);
|
|
@@ -54,7 +54,7 @@ ${Y} ${_}[${I}] = ${B};
|
|
|
54
54
|
const out = {};
|
|
55
55
|
${f}
|
|
56
56
|
return out;
|
|
57
|
-
}`)()},LR=/^[1-5]\d\d$/,h=(R)=>{if(!R||typeof R!=="object"||Array.isArray(R))return!1;if("~standard"in R||"_def"in R||typeof R.parse==="function"||"type"in R||"properties"in R||"anyOf"in R||"oneOf"in R||"allOf"in R||"$ref"in R||Symbol.for("TypeBox.Kind")in R)return!1;let f=Object.keys(R);if(f.length===0)return!1;for(let _=0;_<f.length;_++)if(!LR.test(f[_]))return!1;return!0},fR=(R)=>{if(h(R)){let $=new Map;for(let[Q,X]of Object.entries(R)){let G=Number(Q);if(Number.isInteger(G)&&G>=100&&G<=599)$.set(G,fR(X))}return(Q,X)=>{let G=X??(Q instanceof Response?Q.status:200),T=$.get(G);return T?T(Q,G):Q}}let f=y(R),_=d(R),Z=($)=>{if(!$.ok)return A({status:"error",code:"RESPONSE_VALIDATION_FAILED",error:$.error},500);return $.data};return($)=>{if($ instanceof Response)return $;let Q=_?_($):$,X=f(Q);if(X&&typeof X.then==="function")return X.then(Z);return Z(X)}},FR=(R)=>{let f=R;while(f?._def){let _=f._def.typeName;if(_==="ZodOptional"||_==="ZodDefault"||_==="ZodNullable")f=f._def.innerType;else if(_==="ZodEffects")f=f._def.schema;else break}return f?.type||f?._def?.typeName},UR=/^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/,l=(R,f)=>{let _=f;while(_?._def?.typeName==="ZodEffects")_=_._def.schema;let Z=_?.properties||(_?._def?.shape?typeof _._def.shape==="function"?_._def.shape():_._def.shape:null);if(!Z)return R;let $={...R};for(let[Q,X]of Object.entries(Z)){if(!Object.hasOwn($,Q))continue;let G=$[Q];if(typeof G!=="string")continue;let T=FR(X);if(T==="number"||T==="integer"||T==="ZodNumber"){if(/^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/.test(G)){let I=Number(G);if(Number.isFinite(I))$[Q]=I}}else if(T==="boolean"||T==="ZodBoolean"){if(G==="true")$[Q]=!0;else if(G==="false")$[Q]=!1}}return $},_R=(R)=>{let f=R.body?y(R.body):null,_=R.query?y(R.query):null,Z=R.params?y(R.params):null,$=R.headers?y(R.headers):null,Q=R.cookies?y(R.cookies):null,X=R.stripUnknown&&R.body?d(R.body):null,G=R.stripUnknown&&R.query?d(R.query):null,T=R.stripUnknown&&R.params?d(R.params):null,I=R.stripUnknown&&R.cookies?d(R.cookies):null,M=R.response?fR(R.response):null,B=R.maxBodySize??1048576,Y=[],E=new Set;{let U=R.query;while(U?._def?.schema)U=U._def.schema;let H=U?.properties||(U?._def?.shape?typeof U._def.shape==="function"?U._def.shape():U._def.shape:null),L=(K)=>{let C=K;while(C?._def){let S=C._def.typeName;if(S==="ZodOptional"||S==="ZodDefault"||S==="ZodNullable")C=C._def.innerType;else if(S==="ZodEffects")C=C._def.schema;else break}return C};if(H)for(let[K,C]of Object.entries(H)){let S=L(C);if(!(S?.type==="array"||S?._def?.typeName==="ZodArray"))continue;Y.push(K);let J=L(S.items??S._def?.type),q=J?.type??J?._def?.typeName;if(q==="number"||q==="integer"||q==="ZodNumber")E.add(K)}}let u=Boolean(Z||_||$||Q),g=(U)=>{let H=()=>{if(!Q)return;let C=l(U.cookies,R.cookies),S=Q(C);if(S&&typeof S.then==="function")return S.then((J)=>{if(!J.ok)return A({status:"error",code:"COOKIES_INVALID",error:J.error});U._cookies=I?I(J.data):J.data;return});let j=S;if(!j.ok)return A({status:"error",code:"COOKIES_INVALID",error:j.error});U._cookies=I?I(j.data):j.data;return},L=()=>{if(!$)return H();let C={};U.req.headers.forEach((J,q)=>{let O=q.toLowerCase();if(O!=="__proto__"&&O!=="constructor"&&O!=="prototype")C[O]=J});let S=$(C);if(S&&typeof S.then==="function")return S.then((J)=>J.ok?H():A({status:"error",code:"HEADERS_INVALID",error:J.error}));let j=S;if(!j.ok)return A({status:"error",code:"HEADERS_INVALID",error:j.error});return H()},K=()=>{if(!_)return L();let C=l(U.query,R.query);for(let J of Y){let q=U.queryAll(J);if(q.length>0)C[J]=q.map((O)=>E.has(J)&&UR.test(O)?Number(O):O)}let S=_(C);if(S&&typeof S.then==="function")return S.then((J)=>{if(!J.ok)return A({status:"error",code:"QUERY_INVALID",error:J.error});return U._query=G?G(J.data):J.data,L()});let j=S;if(!j.ok)return A({status:"error",code:"QUERY_INVALID",error:j.error});return U._query=G?G(j.data):j.data,L()};if(Z){let C=l(U.params,R.params),S=Z(C);if(S&&typeof S.then==="function")return S.then((J)=>{if(!J.ok)return A({status:"error",code:"PARAMS_INVALID",error:J.error});return U.params=T?T(J.data):J.data,K()});let j=S;if(!j.ok)return A({status:"error",code:"PARAMS_INVALID",error:j.error});U.params=T?T(j.data):j.data}return K()};if(!f){let U=(H,L)=>{if(u){let K=g(H);if(K&&typeof K.then==="function")return K.then((C)=>C?C:L?L():void 0);if(K)return K}return L?L():void 0};if(U.__routeSchemas=R,M)U.__responseFilter=M;return U}let D=Boolean(R.body&&"_def"in R.body),z=(U,H,L)=>{if(!H.ok)return A({status:"error",code:"VALIDATION_FAILED",error:H.error});return U.body=X?X(H.data):H.data,L?L():void 0},W=(U,H,L)=>{let K;try{K=f(H)}catch{if(D)return R.body.safeParseAsync(H).then((C)=>{if(!C.success)return A({status:"error",code:"VALIDATION_FAILED",error:C.error.flatten()});return U.body=X?X(C.data):C.data,L?L():void 0});K={ok:!1,error:{message:"Validation failed"}}}if(K&&typeof K.then==="function")return K.then((C)=>z(U,C,L));return z(U,K,L)},F=(U,H)=>{let L;try{L=U.jsonBodySyncOrAsync(B)}catch(K){if(K?.status===413)return A({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return A({status:"error",message:"Malformed JSON payload"})}if(L&&typeof L.then==="function")return L.then((K)=>W(U,K,H),(K)=>{if(K?.status===413)return A({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return A({status:"error",message:"Malformed JSON payload"})});return W(U,L,H)},N=(U,H)=>{if(u){let L=g(U);if(L&&typeof L.then==="function")return L.then((K)=>K?K:F(U,H));if(L)return L}return F(U,H)};if(N.__schema=R.body,N.__routeSchemas=R,M)N.__responseFilter=M;return N};class n{prefix;groupMiddleware;routes=[];constructor(R="",f=[]){this.prefix=R;this.groupMiddleware=f}static expandOptionalPaths(R){if(!R.includes("?"))return[R];let f=R.split("/").filter(Boolean);if(!f.some(($)=>$.startsWith(":")&&$.endsWith("?")))return[R];let Z=[""];for(let $=0;$<f.length;$++){let Q=f[$];if(Q.startsWith(":")&&Q.endsWith("?")){let X=Q.slice(0,-1),G=[];for(let T=0;T<Z.length;T++)G.push(Z[T]),G.push(Z[T]+"/"+X);Z=G}else for(let X=0;X<Z.length;X++)Z[X]=Z[X]+"/"+Q}return Array.from(new Set(Z))}_add(R,f,_){let Z=(this.prefix+"/"+f).replace(/\/+/g,"/");if(Z.endsWith("/"))Z=Z.slice(0,-1);let $=[];for(let G=0;G<_.length;G++){let T=_[G];if(typeof T==="function")$.push(T);else if(T&&typeof T==="object")$.push(_R(T))}let Q=n.expandOptionalPaths(Z||""),X=R.toUpperCase();for(let G=0;G<Q.length;G++)this.routes.push({method:X,path:Q[G],handlers:[...this.groupMiddleware,...$]});return this._onRouteMutate?.(),this}get=(R,...f)=>this._add("GET",R,f);post=(R,...f)=>this._add("POST",R,f);put=(R,...f)=>this._add("PUT",R,f);patch=(R,...f)=>this._add("PATCH",R,f);delete=(R,...f)=>this._add("DELETE",R,f);options=(R,...f)=>this._add("OPTIONS",R,f);head=(R,...f)=>this._add("HEAD",R,f);all=(R,...f)=>{for(let _ of["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"])this._add(_,R,f);return this};group=(R,...f)=>{let _=f.pop(),Z=f,$=(this.prefix+"/"+R).replace(/\/+/g,"/"),Q=new n($,[...this.groupMiddleware,...Z]);return _(Q),this.routes.push(...Q.routes),this._onRouteMutate?.(),this};_mountRouter(R,f){let _=(this.prefix+"/"+R).replace(/\/+/g,"/").replace(/\/$/,"");for(let Z of f.routes){let $=(_+"/"+Z.path).replace(/\/+/g,"/");if($.endsWith("/"))$=$.slice(0,-1);this.routes.push({method:Z.method,path:$||"",handlers:[...this.groupMiddleware,...Z.handlers]})}this._onRouteMutate?.()}route(R,f){return this._mountRouter(R,f),this}use(R,...f){if(typeof R==="string"){let Z=[],$=[];for(let Q=0;Q<f.length;Q++){let X=f[Q];if(X instanceof n||X&&X.routes)$.push(X);else if(typeof X==="function")Z.push(X)}if($.length===0)throw new TypeError(`BareRouter.use("${R}", ...) requires a BareRouter instance`);for(let Q=0;Q<$.length;Q++){let X=this.routes.length;if(this._mountRouter(R,$[Q]),Z.length>0)for(let G=X;G<this.routes.length;G++)this.routes[G].handlers=[...this.groupMiddleware,...Z,...this.routes[G].handlers.slice(this.groupMiddleware.length)]}return this._onRouteMutate?.(),this}let _=[R,...f];for(let Z=0;Z<_.length;Z++){let $=_[Z];if($ instanceof n||$&&$.routes)this._mountRouter("",$);else if($&&typeof $.install==="function")$.install(this);else if(typeof $==="function")this.groupMiddleware.push($)}return this._onRouteMutate?.(),this}}import{Type as gf,Type as zf}from"@sinclair/typebox";var $R=(R,f,_)=>{let Z=f;if(_?.params){let G=_.params;Z=Z.replace(/:([a-zA-Z0-9_]+)(?=\/|\?|$)/g,(T,I)=>Object.hasOwn(G,I)&&G[I]!==void 0?encodeURIComponent(String(G[I])):T)}let $=R.endsWith("/")?R.slice(0,-1):R,Q=Z.startsWith("/")?Z:`/${Z}`,X=`${$}${Q}`;if(_?.query){let G=new URLSearchParams;for(let[I,M]of Object.entries(_.query))if(M!==void 0)G.set(I,String(M));let T=G.toString();if(T)X+=(X.includes("?")?"&":"?")+T}return X},ZR=(R)=>{if(typeof R==="string"){let f=R.trim();if(f.startsWith("{")&&f.endsWith("}")||f.startsWith("[")&&f.endsWith("]"))try{return JSON.parse(f)}catch{return R}}return R},TR=(R)=>{if(typeof R==="string"||R instanceof ArrayBuffer||ArrayBuffer.isView(R))return R;return JSON.stringify(R)},KR=(R,f,_)=>{let Z=new Set,$=new Set,Q=new Set,X=1,G=new URL(f),T=R?.wsRoutes,I=null,M={};if(T&&T.size>0){let Y=T.get(G.pathname);if(Y)I=Y;else{let E=G.pathname.split("/").filter(Boolean);for(let[u,g]of T.entries()){let D=u.split("/").filter(Boolean);if(D.length!==E.length)continue;let z={},W=!0;for(let F=0;F<D.length;F++)if(D[F].startsWith(":"))z[D[F].slice(1)]=decodeURIComponent(E[F]);else if(D[F]!==E[F]){W=!1;break}if(W){I=g,M=z;break}}}}let B={data:I?{...I,params:M}:{params:M},send(Y){if(X!==1)return;let E=ZR(Y);for(let u of Z)u(E)},close(Y=1000,E=""){if(X===3)return;X=3;for(let u of Q)u(Y,E)}};return queueMicrotask(async()=>{if(X!==1)return;if(I?.__validateUpgrade)try{let Y=await I.__validateUpgrade(f,_);if(!Y?.ok){B.close(1008,Y?.code||"WS_UPGRADE_INVALID");return}if(Y.query!==void 0)B.data.query=Y.query;if(Y.headers!==void 0)B.data.headers=Y.headers}catch{B.close(1008,"WS_UPGRADE_INVALID");return}if(X!==1)return;I?.open?.(B);for(let Y of $)Y()}),{get readyState(){return X},send(Y){if(X!==1)throw new Error("WebSocket is closed");I?.message?.(B,TR(Y))},onMessage(Y){return Z.add(Y),()=>Z.delete(Y)},onOpen(Y){return $.add(Y),()=>$.delete(Y)},onClose(Y){return Q.add(Y),()=>Q.delete(Y)},close(Y=1000,E=""){if(X===3)return;X=3,I?.close?.(B,Y,E);for(let u of Q)u(Y,E)}}},SR=(R)=>{let f=R.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:"),_=new WebSocket(f),Z=new Set,$=new Set,Q=new Set;return _.onmessage=(X)=>{let G=ZR(X.data);for(let T of Z)T(G)},_.onopen=()=>{for(let X of $)X()},_.onclose=(X)=>{for(let G of Q)G(X.code,X.reason)},{get readyState(){return _.readyState},send(X){_.send(TR(X))},onMessage(X){return Z.add(X),()=>Z.delete(X)},onOpen(X){return $.add(X),()=>$.delete(X)},onClose(X){return Q.add(X),()=>Q.delete(X)},close(X,G){_.close(X,G)}}},HR=new Set(["get","post","put","patch","delete"]),QR=(R,f={})=>{let _=typeof R==="object"&&R!==null&&typeof R.fetch==="function",Z=_?"http://localhost":R,$=f.fetch??(_?(B,Y)=>R.fetch(new Request(String(B),Y)):fetch),Q=f.headers??{},X=async(B,Y,E)=>{let u=$R(Z,Y,E),g=new Headers;for(let[F,N]of Object.entries(Q))g.set(F,N);if(E?.headers)for(let[F,N]of Object.entries(E.headers))g.set(F,N);let D={method:B,headers:g};if(E?.body!==void 0&&B!=="GET"&&B!=="HEAD"){let F=E.body;if(typeof F==="string"||F instanceof FormData||F instanceof URLSearchParams||F instanceof Blob||F instanceof ArrayBuffer||ArrayBuffer.isView(F)||typeof ReadableStream!=="undefined"&&F instanceof ReadableStream){if(F instanceof FormData)g.delete("content-type");D.body=F}else{if(!g.has("content-type"))g.set("Content-Type","application/json");D.body=JSON.stringify(F)}}let z=await $(u,D),W=null;if(z.status!==204&&z.status!==205&&z.status!==304){let F=(z.headers.get("content-type")||"").toLowerCase();if(F.includes("application/json")||F.includes("+json")){let N=await z.text();if(N)try{W=JSON.parse(N)}catch{W=N}else W=null}else W=await z.text()}if(!z.ok)return{ok:!1,data:null,error:W,status:z.status,headers:z.headers};return{ok:!0,data:W,error:null,status:z.status,headers:z.headers}},G=async(B,Y,E)=>{let u=await X(B,Y,E);if(!u.ok){let g=new Error(`HTTP ${u.status}`);throw g.status=u.status,g.data=u.error,g}return u.data},T=(B,Y)=>{let E=$R(Z,B,Y),u={...Q,...Y?.headers||{}};return _?KR(R,E,u):SR(E)},I=(B)=>{return new Proxy((E)=>{if(typeof E==="string"||typeof E==="number")return I([...B,encodeURIComponent(String(E))]);let u=[...B];for(let g of Object.values(E))u.push(encodeURIComponent(String(g)));return I(u)},{get(E,u){if(typeof u==="symbol")return;if(u==="then"||u==="catch"||u==="finally")return;if(HR.has(u)){let g=u.toUpperCase(),D="/"+B.join("/");return(z)=>X(g,D,z)}if(u==="subscribe"){let g="/"+B.join("/");return(D)=>T(g,D)}return I([...B,u])}})};return{get:(B,Y)=>G("GET",B,Y),post:(B,Y)=>G("POST",B,Y),put:(B,Y)=>G("PUT",B,Y),patch:(B,Y)=>G("PATCH",B,Y),delete:(B,Y)=>G("DELETE",B,Y),safe:{get:(B,Y)=>X("GET",B,Y),post:(B,Y)=>X("POST",B,Y),put:(B,Y)=>X("PUT",B,Y),patch:(B,Y)=>X("PATCH",B,Y),delete:(B,Y)=>X("DELETE",B,Y)},treaty:I([]),ws:T}},CR=(R,f={})=>QR(R,f).treaty;var k=(R)=>{let f=R.get("Vary");if(!f)R.set("Vary","Origin");else if(!f.toLowerCase().split(",").some((_)=>_.trim()==="origin"))R.set("Vary",`${f}, Origin`)},WR=(R={})=>{let f=R.origin??"*",_=R.methods||"GET,POST,PUT,PATCH,DELETE,OPTIONS",Z=Array.isArray(R.allowedHeaders)?R.allowedHeaders.join(", "):R.allowedHeaders||"Content-Type, Authorization",$=Array.isArray(R.exposedHeaders)?R.exposedHeaders.join(", "):R.exposedHeaders,Q=R.credentials===!0,X=(M)=>{let B=M._headers?.vary;if(!B)M.setHeader("Vary","Origin");else if(!B.toLowerCase().split(",").map((Y)=>Y.trim()).includes("origin"))M.setHeader("Vary",`${B}, Origin`)};if(typeof f==="string"){if(f===""){let u=(g,D)=>{if(g.req.method==="OPTIONS")return new Response(null,{status:204,headers:{Vary:"Origin"}});g.setHeader("Vary","Origin");let z=D?.();if(z&&typeof z.then==="function")return z.then((W)=>{if(W instanceof Response)k(W.headers);else X(g);return W});if(z instanceof Response)k(z.headers);else X(g);return z};return u.__isCors=!0,u}let M=Q&&f!=="*",B={"Access-Control-Allow-Origin":f,"Access-Control-Allow-Methods":_,"Access-Control-Allow-Headers":Z};if(f!=="*")B.Vary="Origin";if(M)B["Access-Control-Allow-Credentials"]="true";let Y={status:204,headers:B},E=(u,g)=>{if(u.req.method==="OPTIONS")return new Response(null,Y);if(u.setHeader("Access-Control-Allow-Origin",f),u.setHeader("Access-Control-Allow-Methods",_),f!=="*")u.setHeader("Vary","Origin");if(M)u.setHeader("Access-Control-Allow-Credentials","true");if($)u.setHeader("Access-Control-Expose-Headers",$);let D=g?.();if(D&&typeof D.then==="function")return D.then((z)=>{if(z instanceof Response){if(z.headers.set("Access-Control-Allow-Origin",f),z.headers.set("Access-Control-Allow-Methods",_),f!=="*")k(z.headers);if(M)z.headers.set("Access-Control-Allow-Credentials","true");if($)z.headers.set("Access-Control-Expose-Headers",$)}else if(f!=="*")X(u);return z});if(D instanceof Response){if(D.headers.set("Access-Control-Allow-Origin",f),D.headers.set("Access-Control-Allow-Methods",_),f!=="*")k(D.headers);if(M)D.headers.set("Access-Control-Allow-Credentials","true");if($)D.headers.set("Access-Control-Expose-Headers",$)}else if(f!=="*")X(u);return D};return E.__isCors=!0,E}let G=Array.isArray(f)?new Set(f):null,T=(M)=>{if(!M)return null;if(G)return G.has(M)?M:null;return f(M)?M:null},I=(M,B)=>{let Y=T(M.req.headers.get("origin"));if(M.req.method==="OPTIONS"){let u={"Access-Control-Allow-Methods":_,"Access-Control-Allow-Headers":Z,Vary:"Origin"};if(Y)u["Access-Control-Allow-Origin"]=Y;if(Q&&Y)u["Access-Control-Allow-Credentials"]="true";return new Response(null,{status:204,headers:u})}if(M.setHeader("Vary","Origin"),M.setHeader("Access-Control-Allow-Methods",_),Y){if(M.setHeader("Access-Control-Allow-Origin",Y),Q)M.setHeader("Access-Control-Allow-Credentials","true")}if($)M.setHeader("Access-Control-Expose-Headers",$);let E=B?.();if(E&&typeof E.then==="function")return E.then((u)=>{if(u instanceof Response){if(k(u.headers),u.headers.set("Access-Control-Allow-Methods",_),Y){if(u.headers.set("Access-Control-Allow-Origin",Y),Q)u.headers.set("Access-Control-Allow-Credentials","true")}if($)u.headers.set("Access-Control-Expose-Headers",$)}else X(M);return u});if(E instanceof Response){if(k(E.headers),E.headers.set("Access-Control-Allow-Methods",_),Y){if(E.headers.set("Access-Control-Allow-Origin",Y),Q)E.headers.set("Access-Control-Allow-Credentials","true")}if($)E.headers.set("Access-Control-Expose-Headers",$)}else X(M);return E};return I.__isCors=!0,I};var JR=(R={})=>{let f=[];if(R.noSniff!==!1)f.push(["X-Content-Type-Options","nosniff"]);if(R.frameOptions!==!1)f.push(["X-Frame-Options",R.frameOptions??"DENY"]);if(R.referrerPolicy!==!1)f.push(["Referrer-Policy",R.referrerPolicy??"strict-origin-when-cross-origin"]);if(R.hsts!==!1)f.push(["Strict-Transport-Security",R.hsts??"max-age=31536000; includeSubDomains"]);if(R.contentSecurityPolicy)f.push(["Content-Security-Policy",R.contentSecurityPolicy]);f.push(["X-XSS-Protection","0"]);let _=f.length,Z=Object.freeze((()=>{let $={};for(let Q=0;Q<_;Q++){let X=f[Q];$[X[0].toLowerCase()]=X[1]}return $})());return($,Q)=>{if(!$._headers)$._headers=Z;else $._headers={...$._headers,...Z};let X=Q?.();if(X&&typeof X.then==="function")return X.then((G)=>{if(G instanceof Response)for(let T=0;T<_;T++){let I=f[T];if(!G.headers.has(I[0]))G.headers.set(I[0],I[1])}return G});if(X instanceof Response)for(let G=0;G<_;G++){let T=f[G];if(!X.headers.has(T[0]))X.headers.set(T[0],T[1])}return X}};var jR=(R={})=>{let f=R.windowMs??60000,_=R.max??100,Z=R.message??"Too many requests, please try again later.",$=Math.max(1,R.maxEntries??1e4),Q=R.keyGenerator??((I)=>I.ip),X=R.store,G=(I,M,B,Y,E)=>{let u=Math.max(0,_-M),g=String(Math.ceil(B/1000));if(I.setHeader("X-RateLimit-Limit",String(_)),I.setHeader("X-RateLimit-Remaining",String(u)),I.setHeader("X-RateLimit-Reset",g),M>_){let D=Math.max(1,Math.ceil((B-Y)/1000));return Response.json({status:"error",code:"RATE_LIMITED",message:Z},{status:429,headers:{"Retry-After":String(D),"X-RateLimit-Limit":String(_),"X-RateLimit-Remaining":"0","X-RateLimit-Reset":g}})}return E?.()};if(X)return async(I,M)=>{let B=Date.now(),Y=Q(I),{count:E,resetAt:u}=await X.increment(Y,f);return G(I,E,u,B,M)};let T=new Map;return(I,M)=>{let B=Date.now(),Y=Q(I),E=T.get(Y);if(!E||B>=E.resetAt){if(T.size>=$)for(let[g,D]of T){if(B>=D.resetAt)T.delete(g);if(T.size<$)break}let u=Y;if(T.size>=$&&!T.has(Y)){u="\x00__overflow__";let g=T.get(u);if(g&&B<g.resetAt)return g.count++,G(I,g.count,g.resetAt,B,M)}E={count:1,resetAt:B+f},T.delete(u),T.set(u,E)}else E.count++,T.delete(Y),T.set(Y,E);return G(I,E.count,E.resetAt,B,M)}};var AR=(R=1e4,f={})=>{let _=f.status??408,Z=f.message??"Request Timeout",$=Number.isFinite(R)?Math.min(Math.max(R,0),2147483647):2147483647,Q=async(X,G)=>{let T;try{let I=Promise.resolve(G()),M=new Promise((B)=>{T=setTimeout(()=>{X._detached=!0,I.catch(()=>{}),B(Response.json({status:"error",code:"REQUEST_TIMEOUT",message:Z},{status:_}))},$)});return await Promise.race([I,M])}finally{if(T!==void 0)clearTimeout(T)}};return Q.__timeout={ms:$,status:_,message:Z},Q};var NR=(R={})=>{let f=R.failureThreshold??5,_=R.resetTimeoutMs??30000,Z=R.isFailure??((u,g)=>Boolean(g)||u instanceof Response&&(u.status>=500||u.status===408)),$="CLOSED",Q=0,X=0,G=!1,T=0,I=0,M=0,B=(u)=>{if($!==u){let g=$;$=u,T++;try{R.onStateChange?.(g,u)}catch{}}},Y=async(u)=>{if($==="OPEN"){let F=Date.now()-X;if(F<_){let N=Math.max(1,Math.ceil((_-F)/1000));return Response.json({status:"error",code:"CIRCUIT_OPEN",message:"Service temporarily unavailable"},{status:503,headers:{"Retry-After":String(N)}})}B("HALF_OPEN")}let g=!1;if($==="HALF_OPEN"){if(G)return Response.json({status:"error",code:"CIRCUIT_OPEN",message:"Service temporarily unavailable"},{status:503,headers:{"Retry-After":"1"}});G=!0,g=!0}let D=T,z,W=g?++I:0;if(g)M=W,z=setTimeout(()=>{if(M===W&&D===T)G=!1,M=0,X=Date.now(),B("OPEN")},Math.min(Math.max(_,1),2147483647));try{let F=await u();if(D!==T)return F;if(Z(F)){if(Q++,g||Q>=f)X=Date.now(),B("OPEN")}else if(Q=0,g)B("CLOSED");return F}catch(F){if(D===T&&Z(void 0,F)){if(Q++,g||Q>=f)X=Date.now(),B("OPEN")}throw F}finally{if(z!==void 0)clearTimeout(z);if(g&&M===W)G=!1,M=0}},E=(u,g)=>Y(()=>g?g():void 0);return E.__circuitBreaker=Y,E};var PR=(R,f={})=>{let _=f.prefix??"barejs:",Z=typeof R.send==="function",$=(B)=>Z?R.send("GET",[B]):R.get(B),Q=(B)=>Z?R.send("DEL",[B]):R.del(B),X=(B)=>Z?R.send("INCR",[B]):R.incr(B),G=async(B,Y,E)=>{if(Z){await R.send("SET",[B,Y,"PX",String(E)]);return}try{await R.set(B,Y,"PX",E)}catch{if(await R.set(B,Y),typeof R.pexpire==="function")await R.pexpire(B,E);else if(typeof R.expire==="function")await R.expire(B,Math.max(1,Math.ceil(E/1000)))}},T=async(B,Y)=>{if(Z)await R.send("PEXPIRE",[B,String(Y)]);else if(typeof R.pexpire==="function")await R.pexpire(B,Y);else if(typeof R.expire==="function")await R.expire(B,Math.max(1,Math.ceil(Y/1000)))},I=new Map,M='if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';return{async increment(B,Y){let E=`${_}rl:${B}`,u=Number(await X(E));if(u===1)await T(E,Y);let g=Y,D=null;if(Z)D=Number(await R.send("PTTL",[E]));else if(typeof R.pttl==="function")D=Number(await R.pttl(E));else if(typeof R.ttl==="function"){let z=Number(await R.ttl(E));D=z<0?z:z*1000}if(D===-1)await T(E,Y);else if(D!==null&&Number.isFinite(D)&&D>0)g=D;return{count:u,resetAt:Date.now()+g}},async get(B){let Y=await $(`${_}idem:${B}`);if(!Y)return;try{let E=JSON.parse(typeof Y==="string"?Y:String(Y));if(typeof E.rawBodyBase64==="string"){let u=Buffer.from(E.rawBodyBase64,"base64");return{status:E.status,rawBody:u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),contentType:E.contentType,headers:E.headers,expiresAt:E.expiresAt}}return E}catch{return}},async set(B,Y,E){let u={status:Y.status,expiresAt:Y.expiresAt};if(Y.rawBody!==void 0){if(u.rawBodyBase64=Buffer.from(Y.rawBody).toString("base64"),u.contentType=Y.contentType,Y.headers)u.headers=Y.headers}else u.body=Y.body;await G(`${_}idem:${B}`,JSON.stringify(u),E)},async acquireToken(B,Y=30000){let E=`${_}idem:lock:${B}`,u=crypto.randomUUID();if(Z){let D=await R.send("SET",[E,u,"PX",String(Y),"NX"]);return D==="OK"||D===!0?u:null}let g=await R.set(E,u,"PX",Y,"NX");return g==="OK"||g===!0||g===1?u:null},async acquire(B,Y=30000){let E=await this.acquireToken(B,Y);if(!E)return!1;let u=I.get(B);if(!u)u=[],I.set(B,u);return u.push(E),!0},async release(B,Y){let E=`${_}idem:lock:${B}`,u=Y;if(u===void 0){let D=I.get(B);if(u=D?.pop(),D&&D.length===0)I.delete(B)}if(!u)return;if(Z)try{await R.send("EVAL",['if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',"1",E,u]);return}catch{}else if(typeof R.eval==="function")try{await R.eval('if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',1,E,u);return}catch{}if(await $(E)===u)await Q(E)},async revoke(B,Y){await G(`${_}rev:${B}`,"1",Y)},async isRevoked(B){let Y=await $(`${_}rev:${B}`);return Y!==null&&Y!==void 0}}};var VR=(R={})=>{let f=R.path??"/health",_=R.readyPath,Z=R.checks,$=Date.now(),Q=async()=>{let X={},G=!0;if(Z){let I=Object.entries(Z);await Promise.all(I.map(async([M,B])=>{try{let Y=await B();if(X[M]=Y?"ok":"fail",!Y)G=!1}catch{X[M]="fail",G=!1}}))}let T={status:G?"ok":"degraded",uptimeMs:Date.now()-$,timestamp:new Date().toISOString()};if(R.version)T.version=R.version;if(Z)T.checks=X;return Response.json(T,{status:G?200:503})};return{install(X){if(X.get(f,Q),_&&_!==f)X.get(_,Q)}}};var qR=(R)=>{let f=R.indexOf("/",8);if(f===-1)return"/";let _=R.indexOf("?",f);return _===-1?R.slice(f):R.slice(f,_)},OR=(R={})=>{let f=R.format??"pretty",_=R.requestId??!0,Z=R.skip,$=R.onLog;return(Q,X)=>{let G=qR(Q.req.url);if(Z?.(Q,G))return X?.();let T=_?Q.requestId:void 0;if(T)Q.setHeader("x-request-id",T);let I={timestamp:new Date().toISOString(),method:Q.req.method,path:G,...T?{requestId:T}:{},ip:Q.ip};if($)$(I);else if(f==="json")console.log(JSON.stringify(I));else{let M=T?` [${T.slice(0,8)}]`:"";console.log(`[${I.timestamp}] ${I.method} ${I.path}${M}`)}return X?.()}};var w=(R)=>{if(!R||!R._def)return{type:"object"};let f=R._def,_=f.typeName;if(_==="ZodObject"){let Z=typeof f.shape==="function"?f.shape():f.shape,$={},Q=[];for(let[X,G]of Object.entries(Z||{})){let T=G;if($[X]=w(T),T?._def?.typeName!=="ZodOptional"&&T?._def?.typeName!=="ZodDefault")Q.push(X)}return{type:"object",properties:$,...Q.length?{required:Q}:{}}}if(_==="ZodString"){let Z={type:"string"};for(let $ of f.checks||[])if($.kind==="min")Z.minLength=$.value;else if($.kind==="max")Z.maxLength=$.value;else if($.kind==="email")Z.format="email";else if($.kind==="uuid")Z.format="uuid";return Z}if(_==="ZodNumber"){let Z={type:"number"};for(let $ of f.checks||[])if($.kind==="int")Z.type="integer";else if($.kind==="min")Z[$.inclusive===!1?"exclusiveMinimum":"minimum"]=$.value;else if($.kind==="max")Z[$.inclusive===!1?"exclusiveMaximum":"maximum"]=$.value;return Z}if(_==="ZodNullable")return{anyOf:[w(f.innerType),{type:"null"}]};if(_==="ZodBoolean")return{type:"boolean"};if(_==="ZodArray")return{type:"array",items:w(f.type)};if(_==="ZodOptional"||_==="ZodDefault")return w(f.innerType);if(_==="ZodEffects")return w(f.schema);if(_==="ZodLiteral")return{const:f.value};if(_==="ZodDate")return{type:"string",format:"date-time"};if(_==="ZodRecord")return{type:"object",additionalProperties:w(f.valueType)};if(_==="ZodUnion"&&Array.isArray(f.options))return{anyOf:f.options.map(w)};if(_==="ZodEnum")return{type:"string",enum:f.values};return{type:"object"}},b=(R)=>{if(!R)return{type:"object"};if("_def"in R)return w(R);return JSON.parse(JSON.stringify(R))},wR=(R,f={})=>{let _={},Z=new Set(["/docs","/docs/json",...f.excludePaths||[]]),$=!1,Q=!1;for(let T of R){if(Z.has(T.path))continue;let I=("/"+T.path).replace(/\/+/g,"/").replace(/:([a-zA-Z0-9_]+)/g,"{$1}").replace(/\/\*$/,"/{wildcard}");if(!_[I])_[I]={};let M=T.method.toLowerCase(),B=[],Y=void 0,E=void 0,u=void 0,g=null,D=[];for(let H of T.handlers){if(!H)continue;if(H.__isBareAuth)$=!0,D.push({bearerAuth:[]});if(H.__isBasicAuth)Q=!0,D.push({basicAuth:[]});let L=H.__routeSchemas;if(L){if(L.detail)u=L.detail;if(L.params)g=b(L.params);if(L.query){let K=b(L.query),C=new Set(K.required||[]);for(let[S,j]of Object.entries(K.properties||{}))B.push({name:S,in:"query",required:C.has(S),schema:j})}if(L.headers){let K=b(L.headers),C=new Set(K.required||[]);for(let[S,j]of Object.entries(K.properties||{}))B.push({name:S,in:"header",required:C.has(S),schema:j})}if(L.cookies){let K=b(L.cookies),C=new Set(K.required||[]);for(let[S,j]of Object.entries(K.properties||{}))B.push({name:S,in:"cookie",required:C.has(S),schema:j})}if(L.response)E=L.response}if(H.__schema&&!Y)Y={required:!0,content:{"application/json":{schema:b(H.__schema)}}}}let z=[],W=T.path.matchAll(/:([a-zA-Z0-9_]+)/g);for(let H of W){let L=H[1],K=g?.properties?.[L]||{type:"string"};z.push({name:L,in:"path",required:!0,schema:K})}if(/\/\*$/.test(T.path))z.push({name:"wildcard",in:"path",required:!0,schema:{type:"string"}});let F=[...z,...B],N={"200":"Success","201":"Created","202":"Accepted","204":"No Content","400":"Bad Request","401":"Unauthorized","403":"Forbidden","404":"Not Found","409":"Conflict","413":"Payload Too Large","415":"Unsupported Media Type","422":"Unprocessable Entity","429":"Too Many Requests","500":"Internal Server Error","503":"Service Unavailable"},U={};if(E&&h(E))for(let[H,L]of Object.entries(E))U[H]={description:N[H]||`Response ${H}`,content:{"application/json":{schema:b(L)}}};else U["200"]={description:"Success",...E?{content:{"application/json":{schema:b(E)}}}:{}};_[I][M]={summary:u?.summary||`${T.method} ${I}`,...u?.description?{description:u.description}:{},...u?.tags?{tags:u.tags}:{},...D.length?{security:D}:{},...F.length?{parameters:F}:{},...Y?{requestBody:Y}:{},responses:U}}let X={};if($)X.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"};if(Q)X.basicAuth={type:"http",scheme:"basic"};let G={...X,...f.securitySchemes||{}};return{openapi:"3.1.0",info:{title:f.title||"BareJS API",version:f.version||"1.0.0",...f.description?{description:f.description}:{}},...f.servers?.length?{servers:f.servers}:{},...f.tags?.length?{tags:f.tags}:{},...Object.keys(G).length>0?{components:{securitySchemes:G}}:{},...f.security?.length?{security:f.security}:{},paths:_}},yR=(R)=>R.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">"),bR=(R,f="BareJS API Docs")=>{let _=f.replace(/[<>&"]/g,""),Z=yR(R);return`<!doctype html>
|
|
57
|
+
}`)()},FR=/^[1-5]\d\d$/,h=(R)=>{if(!R||typeof R!=="object"||Array.isArray(R))return!1;if("~standard"in R||"_def"in R||typeof R.parse==="function"||"type"in R||"properties"in R||"anyOf"in R||"oneOf"in R||"allOf"in R||"$ref"in R||Symbol.for("TypeBox.Kind")in R)return!1;let f=Object.keys(R);if(f.length===0)return!1;for(let _=0;_<f.length;_++)if(!FR.test(f[_]))return!1;return!0},fR=(R)=>{if(h(R)){let $=new Map;for(let[Q,G]of Object.entries(R)){let Y=Number(Q);if(Number.isInteger(Y)&&Y>=100&&Y<=599)$.set(Y,fR(G))}return(Q,G)=>{let Y=G??(Q instanceof Response?Q.status:200),T=$.get(Y);return T?T(Q,Y):Q}}let f=y(R),_=d(R),Z=($)=>{if(!$.ok)return A({status:"error",code:"RESPONSE_VALIDATION_FAILED",error:$.error},500);return $.data};return($)=>{if($ instanceof Response)return $;let Q=_?_($):$,G=f(Q);if(G&&typeof G.then==="function")return G.then(Z);return Z(G)}},LR=(R)=>{let f=R;while(f?._def){let _=f._def.typeName;if(_==="ZodOptional"||_==="ZodDefault"||_==="ZodNullable")f=f._def.innerType;else if(_==="ZodEffects")f=f._def.schema;else break}return f?.type||f?._def?.typeName},UR=/^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/,l=(R,f)=>{let _=f;while(_?._def?.typeName==="ZodEffects")_=_._def.schema;let Z=_?.properties||(_?._def?.shape?typeof _._def.shape==="function"?_._def.shape():_._def.shape:null);if(!Z)return R;let $={...R};for(let[Q,G]of Object.entries(Z)){if(!Object.hasOwn($,Q))continue;let Y=$[Q];if(typeof Y!=="string")continue;let T=LR(G);if(T==="number"||T==="integer"||T==="ZodNumber"){if(/^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/.test(Y)){let B=Number(Y);if(Number.isFinite(B))$[Q]=B}}else if(T==="boolean"||T==="ZodBoolean"){if(Y==="true")$[Q]=!0;else if(Y==="false")$[Q]=!1}}return $},_R=(R)=>{let f=R.body?y(R.body):null,_=R.query?y(R.query):null,Z=R.params?y(R.params):null,$=R.headers?y(R.headers):null,Q=R.cookies?y(R.cookies):null,G=R.stripUnknown&&R.body?d(R.body):null,Y=R.stripUnknown&&R.query?d(R.query):null,T=R.stripUnknown&&R.params?d(R.params):null,B=R.stripUnknown&&R.cookies?d(R.cookies):null,I=R.response?fR(R.response):null,u=R.maxBodySize??1048576,X=[],D=new Set;{let U=R.query;while(U?._def?.schema)U=U._def.schema;let C=U?.properties||(U?._def?.shape?typeof U._def.shape==="function"?U._def.shape():U._def.shape:null),F=(K)=>{let H=K;while(H?._def){let W=H._def.typeName;if(W==="ZodOptional"||W==="ZodDefault"||W==="ZodNullable")H=H._def.innerType;else if(W==="ZodEffects")H=H._def.schema;else break}return H};if(C)for(let[K,H]of Object.entries(C)){let W=F(H);if(!(W?.type==="array"||W?._def?.typeName==="ZodArray"))continue;X.push(K);let J=F(W.items??W._def?.type),q=J?.type??J?._def?.typeName;if(q==="number"||q==="integer"||q==="ZodNumber")D.add(K)}}let M=Boolean(Z||_||$||Q),g=(U)=>{let C=()=>{if(!Q)return;let H=l(U.cookies,R.cookies),W=Q(H);if(W&&typeof W.then==="function")return W.then((J)=>{if(!J.ok)return A({status:"error",code:"COOKIES_INVALID",error:J.error});U._cookies=B?B(J.data):J.data;return});let j=W;if(!j.ok)return A({status:"error",code:"COOKIES_INVALID",error:j.error});U._cookies=B?B(j.data):j.data;return},F=()=>{if(!$)return C();let H={};U.req.headers.forEach((J,q)=>{let O=q.toLowerCase();if(O!=="__proto__"&&O!=="constructor"&&O!=="prototype")H[O]=J});let W=$(H);if(W&&typeof W.then==="function")return W.then((J)=>J.ok?C():A({status:"error",code:"HEADERS_INVALID",error:J.error}));let j=W;if(!j.ok)return A({status:"error",code:"HEADERS_INVALID",error:j.error});return C()},K=()=>{if(!_)return F();let H=l(U.query,R.query);for(let J of X){let q=U.queryAll(J);if(q.length>0)H[J]=q.map((O)=>D.has(J)&&UR.test(O)?Number(O):O)}let W=_(H);if(W&&typeof W.then==="function")return W.then((J)=>{if(!J.ok)return A({status:"error",code:"QUERY_INVALID",error:J.error});return U._query=Y?Y(J.data):J.data,F()});let j=W;if(!j.ok)return A({status:"error",code:"QUERY_INVALID",error:j.error});return U._query=Y?Y(j.data):j.data,F()};if(Z){let H=l(U.params,R.params),W=Z(H);if(W&&typeof W.then==="function")return W.then((J)=>{if(!J.ok)return A({status:"error",code:"PARAMS_INVALID",error:J.error});return U.params=T?T(J.data):J.data,K()});let j=W;if(!j.ok)return A({status:"error",code:"PARAMS_INVALID",error:j.error});U.params=T?T(j.data):j.data}return K()};if(!f){let U=(C,F)=>{if(M){let K=g(C);if(K&&typeof K.then==="function")return K.then((H)=>H?H:F?F():void 0);if(K)return K}return F?F():void 0};if(U.__routeSchemas=R,I)U.__responseFilter=I;return U}let E=Boolean(R.body&&"_def"in R.body),z=(U,C,F)=>{if(!C.ok)return A({status:"error",code:"VALIDATION_FAILED",error:C.error});return U.body=G?G(C.data):C.data,F?F():void 0},S=(U,C,F)=>{let K;try{K=f(C)}catch{if(E)return R.body.safeParseAsync(C).then((H)=>{if(!H.success)return A({status:"error",code:"VALIDATION_FAILED",error:H.error.flatten()});return U.body=G?G(H.data):H.data,F?F():void 0});K={ok:!1,error:{message:"Validation failed"}}}if(K&&typeof K.then==="function")return K.then((H)=>z(U,H,F));return z(U,K,F)},L=(U,C)=>{let F;try{F=U.jsonBodySyncOrAsync(u)}catch(K){if(K?.status===413)return A({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return A({status:"error",message:"Malformed JSON payload"})}if(F&&typeof F.then==="function")return F.then((K)=>S(U,K,C),(K)=>{if(K?.status===413)return A({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return A({status:"error",message:"Malformed JSON payload"})});return S(U,F,C)},N=(U,C)=>{if(M){let F=g(U);if(F&&typeof F.then==="function")return F.then((K)=>K?K:L(U,C));if(F)return F}return L(U,C)};if(N.__schema=R.body,N.__routeSchemas=R,I)N.__responseFilter=I;return N};class n{prefix;groupMiddleware;routes=[];constructor(R="",f=[]){this.prefix=R;this.groupMiddleware=f}static expandOptionalPaths(R){if(!R.includes("?"))return[R];let f=R.split("/").filter(Boolean);if(!f.some(($)=>$.startsWith(":")&&$.endsWith("?")))return[R];let Z=[""];for(let $=0;$<f.length;$++){let Q=f[$];if(Q.startsWith(":")&&Q.endsWith("?")){let G=Q.slice(0,-1),Y=[];for(let T=0;T<Z.length;T++)Y.push(Z[T]),Y.push(Z[T]+"/"+G);Z=Y}else for(let G=0;G<Z.length;G++)Z[G]=Z[G]+"/"+Q}return Array.from(new Set(Z))}_add(R,f,_){let Z=(this.prefix+"/"+f).replace(/\/+/g,"/");if(Z.endsWith("/"))Z=Z.slice(0,-1);let $=[];for(let Y=0;Y<_.length;Y++){let T=_[Y];if(typeof T==="function")$.push(T);else if(T&&typeof T==="object")$.push(_R(T))}let Q=n.expandOptionalPaths(Z||""),G=R.toUpperCase();for(let Y=0;Y<Q.length;Y++)this.routes.push({method:G,path:Q[Y],handlers:[...this.groupMiddleware,...$]});return this._onRouteMutate?.(),this}get=(R,...f)=>this._add("GET",R,f);post=(R,...f)=>this._add("POST",R,f);put=(R,...f)=>this._add("PUT",R,f);patch=(R,...f)=>this._add("PATCH",R,f);delete=(R,...f)=>this._add("DELETE",R,f);options=(R,...f)=>this._add("OPTIONS",R,f);head=(R,...f)=>this._add("HEAD",R,f);all=(R,...f)=>{for(let _ of["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"])this._add(_,R,f);return this};_createGroupRouter(R,f){return new n(R,f)}group=(R,...f)=>{let _=f.pop(),Z=f,$=(this.prefix+"/"+R).replace(/\/+/g,"/"),Q=this._createGroupRouter($,[...this.groupMiddleware,...Z]);return _(Q),this.routes.push(...Q.routes),this._onRouteMutate?.(),this};_mountRouter(R,f){let _=(this.prefix+"/"+R).replace(/\/+/g,"/").replace(/\/$/,"");for(let Z of f.routes){let $=(_+"/"+Z.path).replace(/\/+/g,"/");if($.endsWith("/"))$=$.slice(0,-1);this.routes.push({method:Z.method,path:$||"",handlers:[...this.groupMiddleware,...Z.handlers]})}this._onRouteMutate?.()}route(R,f){return this._mountRouter(R,f),this}use(R,...f){if(typeof R==="string"){let Z=[],$=[];for(let Q=0;Q<f.length;Q++){let G=f[Q];if(G instanceof n||G&&G.routes)$.push(G);else if(typeof G==="function")Z.push(G)}if($.length===0)throw new TypeError(`BareRouter.use("${R}", ...) requires a BareRouter instance`);for(let Q=0;Q<$.length;Q++){let G=this.routes.length;if(this._mountRouter(R,$[Q]),Z.length>0)for(let Y=G;Y<this.routes.length;Y++)this.routes[Y].handlers=[...this.groupMiddleware,...Z,...this.routes[Y].handlers.slice(this.groupMiddleware.length)]}return this._onRouteMutate?.(),this}let _=[R,...f];for(let Z=0;Z<_.length;Z++){let $=_[Z];if($ instanceof n||$&&$.routes)this._mountRouter("",$);else if($&&typeof $.install==="function")$.install(this);else if(typeof $==="function")this.groupMiddleware.push($)}return this._onRouteMutate?.(),this}}import{Type as gf,Type as zf}from"@sinclair/typebox";var $R=(R,f,_)=>{let Z=f;if(_?.params){let Y=_.params;Z=Z.replace(/:([a-zA-Z0-9_]+)(?=\/|\?|$)/g,(T,B)=>Object.hasOwn(Y,B)&&Y[B]!==void 0?encodeURIComponent(String(Y[B])):T)}let $=R.endsWith("/")?R.slice(0,-1):R,Q=Z.startsWith("/")?Z:`/${Z}`,G=`${$}${Q}`;if(_?.query){let Y=new URLSearchParams;for(let[B,I]of Object.entries(_.query))if(I!==void 0)Y.set(B,String(I));let T=Y.toString();if(T)G+=(G.includes("?")?"&":"?")+T}return G},ZR=(R)=>{if(typeof R==="string"){let f=R.trim();if(f.startsWith("{")&&f.endsWith("}")||f.startsWith("[")&&f.endsWith("]"))try{return JSON.parse(f)}catch{return R}}return R},TR=(R)=>{if(typeof R==="string"||R instanceof ArrayBuffer||ArrayBuffer.isView(R))return R;return JSON.stringify(R)},KR=(R,f,_)=>{let Z=new Set,$=new Set,Q=new Set,G=1,Y=new URL(f),T=R?.wsRoutes,B=null,I={};if(T&&T.size>0){let X=T.get(Y.pathname);if(X)B=X;else{let D=Y.pathname.split("/").filter(Boolean);for(let[M,g]of T.entries()){let E=M.split("/").filter(Boolean);if(E.length!==D.length)continue;let z={},S=!0;for(let L=0;L<E.length;L++)if(E[L].startsWith(":"))z[E[L].slice(1)]=decodeURIComponent(D[L]);else if(E[L]!==D[L]){S=!1;break}if(S){B=g,I=z;break}}}}let u={data:B?{...B,params:I}:{params:I},send(X){if(G!==1)return;let D=ZR(X);for(let M of Z)M(D)},close(X=1000,D=""){if(G===3)return;G=3;for(let M of Q)M(X,D)}};return queueMicrotask(async()=>{if(G!==1)return;if(B?.__validateUpgrade)try{let X=await B.__validateUpgrade(f,_);if(!X?.ok){u.close(1008,X?.code||"WS_UPGRADE_INVALID");return}if(X.query!==void 0)u.data.query=X.query;if(X.headers!==void 0)u.data.headers=X.headers}catch{u.close(1008,"WS_UPGRADE_INVALID");return}if(G!==1)return;B?.open?.(u);for(let X of $)X()}),{get readyState(){return G},send(X){if(G!==1)throw new Error("WebSocket is closed");B?.message?.(u,TR(X))},onMessage(X){return Z.add(X),()=>Z.delete(X)},onOpen(X){return $.add(X),()=>$.delete(X)},onClose(X){return Q.add(X),()=>Q.delete(X)},close(X=1000,D=""){if(G===3)return;G=3,B?.close?.(u,X,D);for(let M of Q)M(X,D)}}},WR=(R)=>{let f=R.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:"),_=new WebSocket(f),Z=new Set,$=new Set,Q=new Set;return _.onmessage=(G)=>{let Y=ZR(G.data);for(let T of Z)T(Y)},_.onopen=()=>{for(let G of $)G()},_.onclose=(G)=>{for(let Y of Q)Y(G.code,G.reason)},{get readyState(){return _.readyState},send(G){_.send(TR(G))},onMessage(G){return Z.add(G),()=>Z.delete(G)},onOpen(G){return $.add(G),()=>$.delete(G)},onClose(G){return Q.add(G),()=>Q.delete(G)},close(G,Y){_.close(G,Y)}}},CR=new Set(["get","post","put","patch","delete"]),QR=(R,f={})=>{let _=typeof R==="object"&&R!==null&&typeof R.fetch==="function",Z=_?"http://localhost":R,$=f.fetch??(_?(u,X)=>R.fetch(new Request(String(u),X)):fetch),Q=f.headers??{},G=async(u,X,D)=>{let M=$R(Z,X,D),g=new Headers;for(let[L,N]of Object.entries(Q))g.set(L,N);if(D?.headers)for(let[L,N]of Object.entries(D.headers))g.set(L,N);let E={method:u,headers:g};if(D?.body!==void 0&&u!=="GET"&&u!=="HEAD"){let L=D.body;if(typeof L==="string"||L instanceof FormData||L instanceof URLSearchParams||L instanceof Blob||L instanceof ArrayBuffer||ArrayBuffer.isView(L)||typeof ReadableStream!=="undefined"&&L instanceof ReadableStream){if(L instanceof FormData)g.delete("content-type");E.body=L}else{if(!g.has("content-type"))g.set("Content-Type","application/json");E.body=JSON.stringify(L)}}let z=await $(M,E),S=null;if(z.status!==204&&z.status!==205&&z.status!==304){let L=(z.headers.get("content-type")||"").toLowerCase();if(L.includes("application/json")||L.includes("+json")){let N=await z.text();if(N)try{S=JSON.parse(N)}catch{S=N}else S=null}else S=await z.text()}if(!z.ok)return{ok:!1,data:null,error:S,status:z.status,headers:z.headers};return{ok:!0,data:S,error:null,status:z.status,headers:z.headers}},Y=async(u,X,D)=>{let M=await G(u,X,D);if(!M.ok){let g=new Error(`HTTP ${M.status}`);throw g.status=M.status,g.data=M.error,g}return M.data},T=(u,X)=>{let D=$R(Z,u,X),M={...Q,...X?.headers||{}};return _?KR(R,D,M):WR(D)},B=(u)=>{return new Proxy((D)=>{if(typeof D==="string"||typeof D==="number")return B([...u,encodeURIComponent(String(D))]);let M=[...u];for(let g of Object.values(D))M.push(encodeURIComponent(String(g)));return B(M)},{get(D,M){if(typeof M==="symbol")return;if(M==="then"||M==="catch"||M==="finally")return;if(CR.has(M)){let g=M.toUpperCase(),E="/"+u.join("/");return(z)=>G(g,E,z)}if(M==="subscribe"){let g="/"+u.join("/");return(E)=>T(g,E)}return B([...u,M])}})};return{get:(u,X)=>Y("GET",u,X),post:(u,X)=>Y("POST",u,X),put:(u,X)=>Y("PUT",u,X),patch:(u,X)=>Y("PATCH",u,X),delete:(u,X)=>Y("DELETE",u,X),safe:{get:(u,X)=>G("GET",u,X),post:(u,X)=>G("POST",u,X),put:(u,X)=>G("PUT",u,X),patch:(u,X)=>G("PATCH",u,X),delete:(u,X)=>G("DELETE",u,X)},treaty:B([]),ws:T}},HR=(R,f={})=>QR(R,f).treaty;var k=(R)=>{let f=R.get("Vary");if(!f)R.set("Vary","Origin");else if(!f.toLowerCase().split(",").some((_)=>_.trim()==="origin"))R.set("Vary",`${f}, Origin`)},SR=(R={})=>{let f=R.origin??"*",_=R.methods||"GET,POST,PUT,PATCH,DELETE,OPTIONS",Z=Array.isArray(R.allowedHeaders)?R.allowedHeaders.join(", "):R.allowedHeaders||"Content-Type, Authorization",$=Array.isArray(R.exposedHeaders)?R.exposedHeaders.join(", "):R.exposedHeaders,Q=R.credentials===!0,G=(I)=>{let u=I._headers?.vary;if(!u)I.setHeader("Vary","Origin");else if(!u.toLowerCase().split(",").map((X)=>X.trim()).includes("origin"))I.setHeader("Vary",`${u}, Origin`)};if(typeof f==="string"){if(f===""){let M=(g,E)=>{if(g.req.method==="OPTIONS")return new Response(null,{status:204,headers:{Vary:"Origin"}});g.setHeader("Vary","Origin");let z=E?.();if(z&&typeof z.then==="function")return z.then((S)=>{if(S instanceof Response)k(S.headers);else G(g);return S});if(z instanceof Response)k(z.headers);else G(g);return z};return M.__isCors=!0,M}let I=Q&&f!=="*",u={"Access-Control-Allow-Origin":f,"Access-Control-Allow-Methods":_,"Access-Control-Allow-Headers":Z};if(f!=="*")u.Vary="Origin";if(I)u["Access-Control-Allow-Credentials"]="true";let X={status:204,headers:u},D=(M,g)=>{if(M.req.method==="OPTIONS")return new Response(null,X);if(M.setHeader("Access-Control-Allow-Origin",f),M.setHeader("Access-Control-Allow-Methods",_),f!=="*")M.setHeader("Vary","Origin");if(I)M.setHeader("Access-Control-Allow-Credentials","true");if($)M.setHeader("Access-Control-Expose-Headers",$);let E=g?.();if(E&&typeof E.then==="function")return E.then((z)=>{if(z instanceof Response){if(z.headers.set("Access-Control-Allow-Origin",f),z.headers.set("Access-Control-Allow-Methods",_),f!=="*")k(z.headers);if(I)z.headers.set("Access-Control-Allow-Credentials","true");if($)z.headers.set("Access-Control-Expose-Headers",$)}else if(f!=="*")G(M);return z});if(E instanceof Response){if(E.headers.set("Access-Control-Allow-Origin",f),E.headers.set("Access-Control-Allow-Methods",_),f!=="*")k(E.headers);if(I)E.headers.set("Access-Control-Allow-Credentials","true");if($)E.headers.set("Access-Control-Expose-Headers",$)}else if(f!=="*")G(M);return E};return D.__isCors=!0,D}let Y=Array.isArray(f)?new Set(f):null,T=(I)=>{if(!I)return null;if(Y)return Y.has(I)?I:null;return f(I)?I:null},B=(I,u)=>{let X=T(I.req.headers.get("origin"));if(I.req.method==="OPTIONS"){let M={"Access-Control-Allow-Methods":_,"Access-Control-Allow-Headers":Z,Vary:"Origin"};if(X)M["Access-Control-Allow-Origin"]=X;if(Q&&X)M["Access-Control-Allow-Credentials"]="true";return new Response(null,{status:204,headers:M})}if(I.setHeader("Vary","Origin"),I.setHeader("Access-Control-Allow-Methods",_),X){if(I.setHeader("Access-Control-Allow-Origin",X),Q)I.setHeader("Access-Control-Allow-Credentials","true")}if($)I.setHeader("Access-Control-Expose-Headers",$);let D=u?.();if(D&&typeof D.then==="function")return D.then((M)=>{if(M instanceof Response){if(k(M.headers),M.headers.set("Access-Control-Allow-Methods",_),X){if(M.headers.set("Access-Control-Allow-Origin",X),Q)M.headers.set("Access-Control-Allow-Credentials","true")}if($)M.headers.set("Access-Control-Expose-Headers",$)}else G(I);return M});if(D instanceof Response){if(k(D.headers),D.headers.set("Access-Control-Allow-Methods",_),X){if(D.headers.set("Access-Control-Allow-Origin",X),Q)D.headers.set("Access-Control-Allow-Credentials","true")}if($)D.headers.set("Access-Control-Expose-Headers",$)}else G(I);return D};return B.__isCors=!0,B};var JR=(R={})=>{let f=[];if(R.noSniff!==!1)f.push(["X-Content-Type-Options","nosniff"]);if(R.frameOptions!==!1)f.push(["X-Frame-Options",R.frameOptions??"DENY"]);if(R.referrerPolicy!==!1)f.push(["Referrer-Policy",R.referrerPolicy??"strict-origin-when-cross-origin"]);if(R.hsts!==!1)f.push(["Strict-Transport-Security",R.hsts??"max-age=31536000; includeSubDomains"]);if(R.contentSecurityPolicy)f.push(["Content-Security-Policy",R.contentSecurityPolicy]);f.push(["X-XSS-Protection","0"]);let _=f.length,Z=Object.freeze((()=>{let $={};for(let Q=0;Q<_;Q++){let G=f[Q];$[G[0].toLowerCase()]=G[1]}return $})());return($,Q)=>{if(!$._headers)$._headers=Z;else $._headers={...$._headers,...Z};let G=Q?.();if(G&&typeof G.then==="function")return G.then((Y)=>{if(Y instanceof Response)for(let T=0;T<_;T++){let B=f[T];if(!Y.headers.has(B[0]))Y.headers.set(B[0],B[1])}return Y});if(G instanceof Response)for(let Y=0;Y<_;Y++){let T=f[Y];if(!G.headers.has(T[0]))G.headers.set(T[0],T[1])}return G}};var jR=(R={})=>{let f=R.windowMs??60000,_=R.max??100,Z=R.message??"Too many requests, please try again later.",$=Math.max(1,R.maxEntries??1e4),Q=R.keyGenerator??((B)=>B.ip),G=R.store,Y=(B,I,u,X,D)=>{let M=Math.max(0,_-I),g=String(Math.ceil(u/1000));if(B.setHeader("X-RateLimit-Limit",String(_)),B.setHeader("X-RateLimit-Remaining",String(M)),B.setHeader("X-RateLimit-Reset",g),I>_){let E=Math.max(1,Math.ceil((u-X)/1000));return Response.json({status:"error",code:"RATE_LIMITED",message:Z},{status:429,headers:{"Retry-After":String(E),"X-RateLimit-Limit":String(_),"X-RateLimit-Remaining":"0","X-RateLimit-Reset":g}})}return D?.()};if(G)return async(B,I)=>{let u=Date.now(),X=Q(B),{count:D,resetAt:M}=await G.increment(X,f);return Y(B,D,M,u,I)};let T=new Map;return(B,I)=>{let u=Date.now(),X=Q(B),D=T.get(X);if(!D||u>=D.resetAt){if(T.size>=$)for(let[g,E]of T){if(u>=E.resetAt)T.delete(g);if(T.size<$)break}let M=X;if(T.size>=$&&!T.has(X)){M="\x00__overflow__";let g=T.get(M);if(g&&u<g.resetAt)return g.count++,Y(B,g.count,g.resetAt,u,I)}D={count:1,resetAt:u+f},T.delete(M),T.set(M,D)}else D.count++,T.delete(X),T.set(X,D);return Y(B,D.count,D.resetAt,u,I)}};var AR=(R=1e4,f={})=>{let _=f.status??408,Z=f.message??"Request Timeout",$=Number.isFinite(R)?Math.min(Math.max(R,0),2147483647):2147483647,Q=async(G,Y)=>{let T;try{let B=Promise.resolve(Y()),I=new Promise((u)=>{T=setTimeout(()=>{G._detached=!0,B.catch(()=>{}),u(Response.json({status:"error",code:"REQUEST_TIMEOUT",message:Z},{status:_}))},$)});return await Promise.race([B,I])}finally{if(T!==void 0)clearTimeout(T)}};return Q.__timeout={ms:$,status:_,message:Z},Q};var NR=(R={})=>{let f=R.failureThreshold??5,_=R.resetTimeoutMs??30000,Z=R.isFailure??((M,g)=>Boolean(g)||M instanceof Response&&(M.status>=500||M.status===408)),$="CLOSED",Q=0,G=0,Y=!1,T=0,B=0,I=0,u=(M)=>{if($!==M){let g=$;$=M,T++;try{R.onStateChange?.(g,M)}catch{}}},X=async(M)=>{if($==="OPEN"){let L=Date.now()-G;if(L<_){let N=Math.max(1,Math.ceil((_-L)/1000));return Response.json({status:"error",code:"CIRCUIT_OPEN",message:"Service temporarily unavailable"},{status:503,headers:{"Retry-After":String(N)}})}u("HALF_OPEN")}let g=!1;if($==="HALF_OPEN"){if(Y)return Response.json({status:"error",code:"CIRCUIT_OPEN",message:"Service temporarily unavailable"},{status:503,headers:{"Retry-After":"1"}});Y=!0,g=!0}let E=T,z,S=g?++B:0;if(g)I=S,z=setTimeout(()=>{if(I===S&&E===T)Y=!1,I=0,G=Date.now(),u("OPEN")},Math.min(Math.max(_,1),2147483647));try{let L=await M();if(E!==T)return L;if(Z(L)){if(Q++,g||Q>=f)G=Date.now(),u("OPEN")}else if(Q=0,g)u("CLOSED");return L}catch(L){if(E===T&&Z(void 0,L)){if(Q++,g||Q>=f)G=Date.now(),u("OPEN")}throw L}finally{if(z!==void 0)clearTimeout(z);if(g&&I===S)Y=!1,I=0}},D=(M,g)=>X(()=>g?g():void 0);return D.__circuitBreaker=X,D};var PR=(R,f={})=>{let _=f.prefix??"barejs:",Z=typeof R.send==="function",$=(u)=>Z?R.send("GET",[u]):R.get(u),Q=(u)=>Z?R.send("DEL",[u]):R.del(u),G=(u)=>Z?R.send("INCR",[u]):R.incr(u),Y=async(u,X,D)=>{if(Z){await R.send("SET",[u,X,"PX",String(D)]);return}try{await R.set(u,X,"PX",D)}catch{if(await R.set(u,X),typeof R.pexpire==="function")await R.pexpire(u,D);else if(typeof R.expire==="function")await R.expire(u,Math.max(1,Math.ceil(D/1000)))}},T=async(u,X)=>{if(Z)await R.send("PEXPIRE",[u,String(X)]);else if(typeof R.pexpire==="function")await R.pexpire(u,X);else if(typeof R.expire==="function")await R.expire(u,Math.max(1,Math.ceil(X/1000)))},B=new Map,I='if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';return{async increment(u,X){let D=`${_}rl:${u}`,M=Number(await G(D));if(M===1)await T(D,X);let g=X,E=null;if(Z)E=Number(await R.send("PTTL",[D]));else if(typeof R.pttl==="function")E=Number(await R.pttl(D));else if(typeof R.ttl==="function"){let z=Number(await R.ttl(D));E=z<0?z:z*1000}if(E===-1)await T(D,X);else if(E!==null&&Number.isFinite(E)&&E>0)g=E;return{count:M,resetAt:Date.now()+g}},async get(u){let X=await $(`${_}idem:${u}`);if(!X)return;try{let D=JSON.parse(typeof X==="string"?X:String(X));if(typeof D.rawBodyBase64==="string"){let M=Buffer.from(D.rawBodyBase64,"base64");return{status:D.status,rawBody:M.buffer.slice(M.byteOffset,M.byteOffset+M.byteLength),contentType:D.contentType,headers:D.headers,expiresAt:D.expiresAt}}return D}catch{return}},async set(u,X,D){let M={status:X.status,expiresAt:X.expiresAt};if(X.rawBody!==void 0){if(M.rawBodyBase64=Buffer.from(X.rawBody).toString("base64"),M.contentType=X.contentType,X.headers)M.headers=X.headers}else M.body=X.body;await Y(`${_}idem:${u}`,JSON.stringify(M),D)},async acquireToken(u,X=30000){let D=`${_}idem:lock:${u}`,M=crypto.randomUUID();if(Z){let E=await R.send("SET",[D,M,"PX",String(X),"NX"]);return E==="OK"||E===!0?M:null}let g=await R.set(D,M,"PX",X,"NX");return g==="OK"||g===!0||g===1?M:null},async acquire(u,X=30000){let D=await this.acquireToken(u,X);if(!D)return!1;let M=B.get(u);if(!M)M=[],B.set(u,M);return M.push(D),!0},async release(u,X){let D=`${_}idem:lock:${u}`,M=X;if(M===void 0){let E=B.get(u);if(M=E?.pop(),E&&E.length===0)B.delete(u)}if(!M)return;if(Z)try{await R.send("EVAL",['if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',"1",D,M]);return}catch{}else if(typeof R.eval==="function")try{await R.eval('if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',1,D,M);return}catch{}if(await $(D)===M)await Q(D)},async revoke(u,X){await Y(`${_}rev:${u}`,"1",X)},async isRevoked(u){let X=await $(`${_}rev:${u}`);return X!==null&&X!==void 0}}};var VR=(R={})=>{let f=R.path??"/health",_=R.readyPath,Z=R.checks,$=Date.now(),Q=async()=>{let G={},Y=!0;if(Z){let B=Object.entries(Z);await Promise.all(B.map(async([I,u])=>{try{let X=await u();if(G[I]=X?"ok":"fail",!X)Y=!1}catch{G[I]="fail",Y=!1}}))}let T={status:Y?"ok":"degraded",uptimeMs:Date.now()-$,timestamp:new Date().toISOString()};if(R.version)T.version=R.version;if(Z)T.checks=G;return Response.json(T,{status:Y?200:503})};return{install(G){if(G.get(f,Q),_&&_!==f)G.get(_,Q)}}};var qR=(R)=>{let f=R.indexOf("/",8);if(f===-1)return"/";let _=R.indexOf("?",f);return _===-1?R.slice(f):R.slice(f,_)},OR=(R={})=>{let f=R.format??"pretty",_=R.requestId??!0,Z=R.skip,$=R.onLog;return(Q,G)=>{let Y=qR(Q.req.url);if(Z?.(Q,Y))return G?.();let T=_?Q.requestId:void 0;if(T)Q.setHeader("x-request-id",T);let B={timestamp:new Date().toISOString(),method:Q.req.method,path:Y,...T?{requestId:T}:{},ip:Q.ip};if($)$(B);else if(f==="json")console.log(JSON.stringify(B));else{let I=T?` [${T.slice(0,8)}]`:"";console.log(`[${B.timestamp}] ${B.method} ${B.path}${I}`)}return G?.()}};var w=(R)=>{if(!R||!R._def)return{type:"object"};let f=R._def,_=f.typeName;if(_==="ZodObject"){let Z=typeof f.shape==="function"?f.shape():f.shape,$={},Q=[];for(let[G,Y]of Object.entries(Z||{})){let T=Y;if($[G]=w(T),T?._def?.typeName!=="ZodOptional"&&T?._def?.typeName!=="ZodDefault")Q.push(G)}return{type:"object",properties:$,...Q.length?{required:Q}:{}}}if(_==="ZodString"){let Z={type:"string"};for(let $ of f.checks||[])if($.kind==="min")Z.minLength=$.value;else if($.kind==="max")Z.maxLength=$.value;else if($.kind==="email")Z.format="email";else if($.kind==="uuid")Z.format="uuid";return Z}if(_==="ZodNumber"){let Z={type:"number"};for(let $ of f.checks||[])if($.kind==="int")Z.type="integer";else if($.kind==="min")Z[$.inclusive===!1?"exclusiveMinimum":"minimum"]=$.value;else if($.kind==="max")Z[$.inclusive===!1?"exclusiveMaximum":"maximum"]=$.value;return Z}if(_==="ZodNullable")return{anyOf:[w(f.innerType),{type:"null"}]};if(_==="ZodBoolean")return{type:"boolean"};if(_==="ZodArray")return{type:"array",items:w(f.type)};if(_==="ZodOptional"||_==="ZodDefault")return w(f.innerType);if(_==="ZodEffects")return w(f.schema);if(_==="ZodLiteral")return{const:f.value};if(_==="ZodDate")return{type:"string",format:"date-time"};if(_==="ZodRecord")return{type:"object",additionalProperties:w(f.valueType)};if(_==="ZodUnion"&&Array.isArray(f.options))return{anyOf:f.options.map(w)};if(_==="ZodEnum")return{type:"string",enum:f.values};return{type:"object"}},b=(R)=>{if(!R)return{type:"object"};if("_def"in R)return w(R);return JSON.parse(JSON.stringify(R))},wR=(R,f={})=>{let _={},Z=new Set(["/docs","/docs/json",...f.excludePaths||[]]),$=!1,Q=!1;for(let T of R){if(Z.has(T.path))continue;let B=("/"+T.path).replace(/\/+/g,"/").replace(/:([a-zA-Z0-9_]+)/g,"{$1}").replace(/\/\*$/,"/{wildcard}");if(!_[B])_[B]={};let I=T.method.toLowerCase(),u=[],X=void 0,D=void 0,M=void 0,g=null,E=[];for(let C of T.handlers){if(!C)continue;if(C.__isBareAuth)$=!0,E.push({bearerAuth:[]});if(C.__isBasicAuth)Q=!0,E.push({basicAuth:[]});let F=C.__routeSchemas;if(F){if(F.detail)M=F.detail;if(F.params)g=b(F.params);if(F.query){let K=b(F.query),H=new Set(K.required||[]);for(let[W,j]of Object.entries(K.properties||{}))u.push({name:W,in:"query",required:H.has(W),schema:j})}if(F.headers){let K=b(F.headers),H=new Set(K.required||[]);for(let[W,j]of Object.entries(K.properties||{}))u.push({name:W,in:"header",required:H.has(W),schema:j})}if(F.cookies){let K=b(F.cookies),H=new Set(K.required||[]);for(let[W,j]of Object.entries(K.properties||{}))u.push({name:W,in:"cookie",required:H.has(W),schema:j})}if(F.response)D=F.response}if(C.__schema&&!X)X={required:!0,content:{"application/json":{schema:b(C.__schema)}}}}let z=[],S=T.path.matchAll(/:([a-zA-Z0-9_]+)/g);for(let C of S){let F=C[1],K=g?.properties?.[F]||{type:"string"};z.push({name:F,in:"path",required:!0,schema:K})}if(/\/\*$/.test(T.path))z.push({name:"wildcard",in:"path",required:!0,schema:{type:"string"}});let L=[...z,...u],N={"200":"Success","201":"Created","202":"Accepted","204":"No Content","400":"Bad Request","401":"Unauthorized","403":"Forbidden","404":"Not Found","409":"Conflict","413":"Payload Too Large","415":"Unsupported Media Type","422":"Unprocessable Entity","429":"Too Many Requests","500":"Internal Server Error","503":"Service Unavailable"},U={};if(D&&h(D))for(let[C,F]of Object.entries(D))U[C]={description:N[C]||`Response ${C}`,content:{"application/json":{schema:b(F)}}};else U["200"]={description:"Success",...D?{content:{"application/json":{schema:b(D)}}}:{}};_[B][I]={summary:M?.summary||`${T.method} ${B}`,...M?.description?{description:M.description}:{},...M?.tags?{tags:M.tags}:{},...E.length?{security:E}:{},...L.length?{parameters:L}:{},...X?{requestBody:X}:{},responses:U}}let G={};if($)G.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"};if(Q)G.basicAuth={type:"http",scheme:"basic"};let Y={...G,...f.securitySchemes||{}};return{openapi:"3.1.0",info:{title:f.title||"BareJS API",version:f.version||"1.0.0",...f.description?{description:f.description}:{}},...f.servers?.length?{servers:f.servers}:{},...f.tags?.length?{tags:f.tags}:{},...Object.keys(Y).length>0?{components:{securitySchemes:Y}}:{},...f.security?.length?{security:f.security}:{},paths:_}},yR=(R)=>R.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">"),bR=(R,f="BareJS API Docs")=>{let _=f.replace(/[<>&"]/g,""),Z=yR(R);return`<!doctype html>
|
|
58
58
|
<html>
|
|
59
59
|
<head>
|
|
60
60
|
<title>${_}</title>
|
|
@@ -65,6 +65,6 @@ ${Y} ${_}[${I}] = ${B};
|
|
|
65
65
|
<script id="api-reference" data-url="${Z}"></script>
|
|
66
66
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
67
67
|
</body>
|
|
68
|
-
</html>`};var nR=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,kR=Array.from({length:256},(R,f)=>f.toString(16).padStart(2,"0")),
|
|
68
|
+
</html>`};var nR=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,kR=Array.from({length:256},(R,f)=>f.toString(16).padStart(2,"0")),GR=(R)=>{let f=new Uint8Array(R);crypto.getRandomValues(f);let _="";for(let Z=0;Z<R;Z++)_+=kR[f[Z]];return _},XR=(R={})=>{let f=R.serverTiming===!1?null:(R.serverTiming||"app").replace(/[^a-zA-Z0-9_.-]/g,""),_=R.exposeTraceparent??!0,Z=R.onSpan;return async($,Q)=>{let G=performance.now(),Y=$.req.headers.get("traceparent")?.trim().toLowerCase(),T=Y?nR.exec(Y):null,B=T&&T[2]!=="00000000000000000000000000000000"?T[2]:GR(16),I=T&&T[3]!=="0000000000000000"?T[3]:void 0,u=T?T[4]:"01",X=GR(8),D=`00-${B}-${X}-${u}`;if($.set("traceId",B),$.set("spanId",X),I)$.set("parentSpanId",I);if($.set("traceparent",D),_)$.setHeader("traceparent",D);let M=await Q(),g=performance.now()-G;if(f){let E=`${f};dur=${g.toFixed(2)}`;if(M instanceof Response)try{M.headers.append("Server-Timing",E)}catch{}else $.setHeader("Server-Timing",E)}if(Z){let E=$.req.url,z=E.indexOf("/",8),S=z===-1?-1:E.indexOf("?",z),L=z===-1?"/":S===-1?E.slice(z):E.slice(z,S),N=M instanceof Response?M.status:$._status||200;Z({traceId:B,spanId:X,parentSpanId:I,traceparent:D,method:$.req.method,path:L,status:N,durationMs:g})}return M}},dR=(R="app")=>XR({serverTiming:R,exposeTraceparent:!1});var YR=Symbol("BareRawHtml"),iR={"&":"&","<":"<",">":">",'"':""","'":"'"},xR=/[&<>"']/g,uR=(R)=>R.replace(xR,(f)=>iR[f]),BR=(R)=>({[YR]:!0,value:R,toString(){return R},toResponse(f=200,_){return new Response(R,{status:f,headers:{"content-type":"text/html; charset=utf-8",..._||{}}})}}),vR=(R)=>BR(String(R)),IR=(R)=>{if(R===null||R===void 0||R===!1)return"";if(typeof R==="object"&&R[YR]===!0)return R.value;if(Array.isArray(R)){let f="";for(let _=0;_<R.length;_++)f+=IR(R[_]);return f}return uR(String(R))},oR=(R,...f)=>{let _=R[0]??"";for(let Z=0;Z<f.length;Z++)_+=IR(f[Z])+(R[Z+1]??"");return BR(_)};var lR=["cache-control","content-location","date","etag","expires","vary"],pR=(R)=>{let f=2166136261,_=16777619;for(let Z=0;Z<R.length;Z++){let $=R[Z];f^=$,f=Math.imul(f,16777619),_^=$^Z&255,_=Math.imul(_,16777619)}return`${R.length.toString(16)}-${(f>>>0).toString(16).padStart(8,"0")}${(_>>>0).toString(16).padStart(8,"0")}`},mR=async(R)=>{let f=await crypto.subtle.digest("SHA-256",R),_=new Uint8Array(f),Z="";for(let $=0;$<16;$++)Z+=_[$].toString(16).padStart(2,"0");return Z},MR=(R)=>R.startsWith("W/")?R.slice(2):R,hR=(R,f)=>{let _=R.trim();if(_==="*")return!0;let Z=MR(f),$=_.split(",");for(let Q=0;Q<$.length;Q++)if(MR($[Q].trim())===Z)return!0;return!1},rR=(R={})=>{let f=R.weak??!0,_=R.retainedHeaders??lR,Z=async(Q,G)=>{let Y=Q.req.method;if(Y!=="GET"&&Y!=="HEAD")return G;let T;if(G instanceof Response)T=G;else if(typeof G==="string")T=new Response(G,{status:Q._status||200,headers:Q._headers||{"content-type":"text/plain; charset=utf-8"}});else if(G!==void 0&&G!==null)T=Response.json(G,{status:Q._status||200,headers:Q._headers});else return G;if(T.status!==200)return T;if(T.headers.has("etag"))return T;if((T.headers.get("content-type")||"").toLowerCase().includes("text/event-stream"))return T;let I=new Uint8Array(await T.arrayBuffer());if(I.byteLength===0)return new Response(I,{status:T.status,headers:T.headers});let u=f?pR(I):await mR(I),X=f?`W/"${u}"`:`"${u}"`,D=Q.req.headers.get("if-none-match");if(D&&hR(D,X)){let g=new Headers;for(let E=0;E<_.length;E++){let z=_[E],S=T.headers.get(z);if(S!==null)g.set(z,S)}return g.set("etag",X),new Response(null,{status:304,headers:g})}let M=new Headers(T.headers);return M.set("etag",X),new Response(Y==="HEAD"?null:I,{status:T.status,headers:M})},$=async(Q,G)=>{let Y=await(G?G():void 0);return Z(Q,Y)};return $.__postResponse=Z,$};var o=new Set(["__proto__","constructor","prototype"]);class DR{req;params;env;executionCtx;store=new Map;body=void 0;user=void 0;_status=200;_headers=void 0;_setCookies=void 0;_query=null;_cookies=null;_jsonCache=void 0;_jsonParsed=!1;_requestId=null;constructor(R,f={},_={},Z){this.req=R,this.params=f,this.env=_,this.executionCtx=Z}get requestId(){if(!this._requestId)this._requestId=this.req.headers.get("x-request-id")||crypto.randomUUID();return this._requestId}get ip(){return this.req.headers.get("cf-connecting-ip")||this.req.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||this.req.headers.get("x-real-ip")||"127.0.0.1"}get query(){if(this._query)return this._query;let R=Object.create(null),f=this.req.url.indexOf("?");if(f!==-1){let _=new URLSearchParams(this.req.url.slice(f+1));for(let[Z,$]of _)if(!o.has(Z))R[Z]=$}return this._query=R,R}get cookies(){if(this._cookies)return this._cookies;let R=Object.create(null),f=this.req.headers.get("cookie");if(f)for(let _ of f.split(";")){let Z=_.indexOf("=");if(Z===-1)continue;let $=_.slice(0,Z).trim();if(!$||o.has($))continue;try{R[$]=decodeURIComponent(_.slice(Z+1).trim())}catch{R[$]=_.slice(Z+1).trim()}}return this._cookies=R,R}get(R){return this.store.get(R)}set(R,f){return this.store.set(R,f),this}status(R){return this._status=R,this}setHeader(R,f){if(!this._headers)this._headers=Object.create(null);else if(Object.getPrototypeOf(this._headers)===Object.prototype)this._headers={...this._headers};let _=R.indexOf("\r")!==-1||R.indexOf(`
|
|
69
69
|
`)!==-1?R.replace(/[\r\n]+/g,""):R,Z=f.indexOf("\r")!==-1||f.indexOf(`
|
|
70
|
-
`)!==-1?f.replace(/[\r\n]+/g,""):f;return this._headers[_.toLowerCase()]=Z,this}appendHeader(R,f){if(R.toLowerCase()==="set-cookie"){if(!this._setCookies)this._setCookies=[];return this._setCookies.push(f),this}return this.setHeader(R,f)}setCookie(R,f,_={}){let $=[`${R.replace(/[\r\n;= ]+/g,"")}=${encodeURIComponent(f)}`];if($.push(`Path=${(_.path??"/").replace(/[\r\n;]+/g,"")}`),_.maxAge!==void 0)$.push(`Max-Age=${Math.floor(_.maxAge)}`);if(_.domain)$.push(`Domain=${_.domain.replace(/[\r\n;]+/g,"")}`);if(_.httpOnly!==!1)$.push("HttpOnly");if(_.secure)$.push("Secure");return $.push(`SameSite=${_.sameSite??"Lax"}`),this.appendHeader("Set-Cookie",$.join("; "))}deleteCookie(R,f="/"){return this.setCookie(R,"",{maxAge:0,path:f})}async jsonBody(R=1048576){if(this._jsonParsed)return this._jsonCache;let f=await this.req.text();if(new TextEncoder().encode(f).byteLength>R){let _=new Error("Payload Too Large");throw _.status=413,_}try{this._jsonCache=f?JSON.parse(f):null}catch{let _=new Error("Malformed JSON payload");throw _.status=400,_}return this._jsonParsed=!0,this._jsonCache}async textBody(){return this.req.text()}buildHeaders(R){let f=new Headers;if(this._headers)for(let _ in this._headers)f.set(_,this._headers[_]);if(this._setCookies)for(let _=0;_<this._setCookies.length;_++)f.append("set-cookie",this._setCookies[_]);if(!f.has("content-type"))f.set("content-type",R);return f}json(R,f){return new Response(JSON.stringify(R),{status:f??this._status,headers:this.buildHeaders("application/json; charset=utf-8")})}text(R,f){return new Response(R,{status:f??this._status,headers:this.buildHeaders("text/plain; charset=utf-8")})}html(R,f){return new Response(R,{status:f??this._status,headers:this.buildHeaders("text/html; charset=utf-8")})}send(R,f){return this.json({status:this._status,msg:R,...f})}redirect(R,f=302){let _=new Headers;if(this._headers)for(let Z in this._headers)_.set(Z,this._headers[Z]);return _.set("location",R.replace(/[\r\n]+/g,"")),new Response(null,{status:f,headers:_})}}class x{children=Object.create(null);paramNode=null;wildcardNode=null;entry=null;paramNames=[];insert(R,f){let _=this,Z=R.split("/").filter(Boolean),$=[];for(let Q of Z)if(Q==="*"){if(!_.wildcardNode)_.wildcardNode=new x;_=_.wildcardNode;break}else if(Q.startsWith(":")){if(!_.paramNode)_.paramNode=new x;$.push(Q.slice(1)),_=_.paramNode}else{if(!_.children[Q])_.children[Q]=new x;_=_.children[Q]}_.entry=f,_.paramNames=$}search(R){let f=R.split("/").filter(Boolean),_=(Z,$,Q)=>{if($===f.length){if(!Z.entry)return null;let T=Object.create(null);for(let
|
|
70
|
+
`)!==-1?f.replace(/[\r\n]+/g,""):f;return this._headers[_.toLowerCase()]=Z,this}appendHeader(R,f){if(R.toLowerCase()==="set-cookie"){if(!this._setCookies)this._setCookies=[];return this._setCookies.push(f),this}return this.setHeader(R,f)}setCookie(R,f,_={}){let $=[`${R.replace(/[\r\n;= ]+/g,"")}=${encodeURIComponent(f)}`];if($.push(`Path=${(_.path??"/").replace(/[\r\n;]+/g,"")}`),_.maxAge!==void 0)$.push(`Max-Age=${Math.floor(_.maxAge)}`);if(_.domain)$.push(`Domain=${_.domain.replace(/[\r\n;]+/g,"")}`);if(_.httpOnly!==!1)$.push("HttpOnly");if(_.secure)$.push("Secure");return $.push(`SameSite=${_.sameSite??"Lax"}`),this.appendHeader("Set-Cookie",$.join("; "))}deleteCookie(R,f="/"){return this.setCookie(R,"",{maxAge:0,path:f})}async jsonBody(R=1048576){if(this._jsonParsed)return this._jsonCache;let f=await this.req.text();if(new TextEncoder().encode(f).byteLength>R){let _=new Error("Payload Too Large");throw _.status=413,_}try{this._jsonCache=f?JSON.parse(f):null}catch{let _=new Error("Malformed JSON payload");throw _.status=400,_}return this._jsonParsed=!0,this._jsonCache}async textBody(){return this.req.text()}buildHeaders(R){let f=new Headers;if(this._headers)for(let _ in this._headers)f.set(_,this._headers[_]);if(this._setCookies)for(let _=0;_<this._setCookies.length;_++)f.append("set-cookie",this._setCookies[_]);if(!f.has("content-type"))f.set("content-type",R);return f}json(R,f){return new Response(JSON.stringify(R),{status:f??this._status,headers:this.buildHeaders("application/json; charset=utf-8")})}text(R,f){return new Response(R,{status:f??this._status,headers:this.buildHeaders("text/plain; charset=utf-8")})}html(R,f){return new Response(R,{status:f??this._status,headers:this.buildHeaders("text/html; charset=utf-8")})}send(R,f){return this.json({status:this._status,msg:R,...f})}redirect(R,f=302){let _=new Headers;if(this._headers)for(let Z in this._headers)_.set(Z,this._headers[Z]);return _.set("location",R.replace(/[\r\n]+/g,"")),new Response(null,{status:f,headers:_})}}class x{children=Object.create(null);paramNode=null;wildcardNode=null;entry=null;paramNames=[];insert(R,f){let _=this,Z=R.split("/").filter(Boolean),$=[];for(let Q of Z)if(Q==="*"){if(!_.wildcardNode)_.wildcardNode=new x;_=_.wildcardNode;break}else if(Q.startsWith(":")){if(!_.paramNode)_.paramNode=new x;$.push(Q.slice(1)),_=_.paramNode}else{if(!_.children[Q])_.children[Q]=new x;_=_.children[Q]}_.entry=f,_.paramNames=$}search(R){let f=R.split("/").filter(Boolean),_=(Z,$,Q)=>{if($===f.length){if(!Z.entry)return null;let T=Object.create(null);for(let B=0;B<Z.paramNames.length;B++){let I=Z.paramNames[B];if(!o.has(I))T[I]=Q[B]}return{entry:Z.entry,params:T}}let G=f[$],Y=Z.children[G];if(Y){let T=_(Y,$+1,Q);if(T)return T}if(Z.paramNode){Q.push(G);let T=_(Z.paramNode,$+1,Q);if(T)return T;Q.pop()}if(Z.wildcardNode&&Z.wildcardNode.entry){let T=Object.create(null);for(let B=0;B<Z.wildcardNode.paramNames.length;B++){let I=Z.wildcardNode.paramNames[B];if(!o.has(I))T[I]=Q[B]}return T["*"]=f.slice($).join("/"),{entry:Z.wildcardNode.entry,params:T}}return null};return _(this,0,[])}}class cR{prefix="";staticRoutes=new Map;dynamicTrees=new Map;middlewares=[];requestHooks=[];responseHooks=[];errorHandler=null;constructor(R){if(R?.prefix)this.prefix=("/"+R.prefix).replace(/\/+/g,"/").replace(/\/$/,"")}basePath(R){let f=("/"+R).replace(/\/+/g,"/").replace(/\/$/,"");if(f)this.prefix=(this.prefix+f).replace(/\/+/g,"/").replace(/\/$/,"");return this}use(R){return this.middlewares.push(R),this}onRequest(R){return this.requestHooks.push(R),this}onResponse(R){return this.responseHooks.push(R),this}onError(R){return this.errorHandler=R,this}add(R,f,..._){if(_.length===0)return this;let Z=_[_.length-1],$=_.slice(0,-1),Q=(this.prefix+"/"+f).replace(/\/+/g,"/"),G=Q.length>1&&Q.endsWith("/")?Q.slice(0,-1):Q||"/",Y={middlewares:$,handler:Z};if(!G.includes(":")&&!G.includes("*"))this.staticRoutes.set(`${R}:${G}`,Y);else{let T=this.dynamicTrees.get(R);if(!T)T=new x,this.dynamicTrees.set(R,T);T.insert(G,Y)}return this}get(R,...f){return this.add("GET",R,...f)}post(R,...f){return this.add("POST",R,...f)}put(R,...f){return this.add("PUT",R,...f)}patch(R,...f){return this.add("PATCH",R,...f)}delete(R,...f){return this.add("DELETE",R,...f)}options(R,...f){return this.add("OPTIONS",R,...f)}head(R,...f){return this.add("HEAD",R,...f)}all(R,...f){for(let _ of["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"])this.add(_,R,...f);return this}normalizeResponse(R,f){if(f instanceof Response)return f;if(typeof f==="string")return R.text(f);if(f===null||f===void 0)return new Response(null,{status:204});return R.json(f)}fetch=async(R,f,_)=>{let Z=R.url,$=Z.indexOf("/",8),Q=$===-1?-1:Z.indexOf("?",$),G=$===-1?"/":Q===-1?Z.slice($):Z.slice($,Q),Y=R.method,T=this.staticRoutes.get(`${Y}:${G}`),B={};if(!T){let u=this.dynamicTrees.get(Y);if(u){let X=u.search(G);if(X)T=X.entry,B=X.params}}let I=new DR(R,B,f??{},_);try{for(let E=0;E<this.requestHooks.length;E++)await this.requestHooks[E](I);let u=T?[...this.middlewares,...T.middlewares,T.handler]:[...this.middlewares,()=>new Response(JSON.stringify({status:404,message:"Not Found"}),{status:404,headers:{"content-type":"application/json; charset=utf-8"}})],X=-1,D=async(E)=>{if(E<=X)throw new Error("next() called multiple times");X=E;let z=u[E];if(!z)return;return z(I,()=>D(E+1))},M=await D(0),g=this.normalizeResponse(I,M);for(let E=0;E<this.responseHooks.length;E++)await this.responseHooks[E](I,g);return g}catch(u){if(this.errorHandler)return this.errorHandler(u,I);let X=u?.status>=400&&u?.status<600?u.status:500;return new Response(JSON.stringify({status:X,message:X<500?u?.message||"Bad Request":"Internal Server Error"}),{status:X,headers:{"content-type":"application/json; charset=utf-8"}})}};request(R,f,_){let Z=R.startsWith("http://")||R.startsWith("https://")?R:`http://localhost${R.startsWith("/")?R:`/${R}`}`;return this.fetch(new Request(Z,f),_)}}function Nf(){let R=new Map;return{do(f,_){let Z=R.get(f);if(Z)return Z;let $=Promise.resolve().then(_).finally(()=>{R.delete(f)});return R.set(f,$),$},size(){return R.size}}}export{c as z,XR as tracing,AR as timeout,zf as t,zR as standard,dR as serverTiming,JR as securityHeaders,bR as renderDocsHTML,PR as redisStore,vR as raw,jR as rateLimit,gR as native,OR as logger,oR as html,VR as healthcheck,wR as generateOpenAPISpec,rR as etag,uR as escapeHtml,Nf as createSingleflight,SR as cors,NR as circuitBreaker,HR as bareTreaty,QR as bareClient,c as Z,gf as Type,DR as EdgeContext,n as BareRouter,cR as BareJS,cR as BareEdge};
|