better-call 0.0.5-beta.2 → 0.0.5-beta.20
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 +75 -32
- package/dist/client.cjs +2 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +36 -0
- package/dist/client.d.ts +36 -0
- package/dist/client.js +2 -0
- package/dist/client.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +88 -171
- package/dist/index.d.ts +88 -171
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/router-CAklHiJN.d.cts +190 -0
- package/dist/router-CAklHiJN.d.ts +190 -0
- package/package.json +9 -2
package/README.md
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
# better-call
|
|
2
2
|
|
|
3
|
-
Better call is a tiny web framework for creating endpoints that can be invoked as a normal function or mounted to a router
|
|
3
|
+
Better call is a tiny web framework for creating endpoints that can be invoked as a normal function or mounted to a router to be served by any web standard compatible server (like Bun, node, nextjs, sveltekit...) and also can be invoked from a client using the typed rpc client.
|
|
4
4
|
|
|
5
5
|
Built for typescript and it comes with a very high performance router based on [rou3](https://github.com/unjs/rou3).
|
|
6
6
|
|
|
7
|
-
|
|
8
7
|
> ⚠️ This project early in development and not ready for production use. But feel free to try it out and give feedback.
|
|
9
8
|
|
|
10
9
|
## Install
|
|
@@ -15,7 +14,12 @@ pnpm i better-call
|
|
|
15
14
|
|
|
16
15
|
## Usage
|
|
17
16
|
|
|
18
|
-
The building blocks for better-call are endpoints. You can create an endpoint by calling `createEndpoint` and passing it a path,
|
|
17
|
+
The building blocks for better-call are endpoints. You can create an endpoint by calling `createEndpoint` and passing it a path, [options](#endpointoptions) and a handler that will be invoked when the endpoint is called.
|
|
18
|
+
|
|
19
|
+
Then
|
|
20
|
+
1. you can mount the endpoint to a router and serve it with any web standard compatible server
|
|
21
|
+
2. call it as a normal function on the server.
|
|
22
|
+
3. use typed RPC client to call it on the client.
|
|
19
23
|
|
|
20
24
|
```ts
|
|
21
25
|
import { createEndpoint, createRouter } from "better-call"
|
|
@@ -40,6 +44,16 @@ const item = await createItem({
|
|
|
40
44
|
id: "123"
|
|
41
45
|
}
|
|
42
46
|
})
|
|
47
|
+
|
|
48
|
+
// You cam also infer it on a client
|
|
49
|
+
import { createClient } from "better-call/client";
|
|
50
|
+
|
|
51
|
+
const client = createClient<typeof router>();
|
|
52
|
+
const items = await client("/item", {
|
|
53
|
+
body: {
|
|
54
|
+
id: "123"
|
|
55
|
+
}
|
|
56
|
+
});
|
|
43
57
|
```
|
|
44
58
|
|
|
45
59
|
OR you can mount the endpoint to a router and serve it with any web standard compatible server.
|
|
@@ -58,36 +72,45 @@ Bun.serve({
|
|
|
58
72
|
|
|
59
73
|
### Middleware
|
|
60
74
|
|
|
61
|
-
|
|
75
|
+
Endpoints can use middleware by passing the `use` option to the endpoint. To create a middleware, you can call `createMiddleware` and pass it a function or an options object and a handler function.
|
|
62
76
|
|
|
63
|
-
If you return a context object from the middleware, it will be
|
|
77
|
+
If you return a context object from the middleware, it will be available in the endpoint context.
|
|
64
78
|
|
|
65
79
|
```ts
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const createProtectedEndpoint = createMiddleware(async (ctx) => {
|
|
69
|
-
if(ctx.headers.get("Authorization") !== "Bearer 123") {
|
|
70
|
-
throw new Error("Unauthorized")
|
|
71
|
-
}
|
|
80
|
+
const middleware = createMiddleware(async (ctx) => {
|
|
72
81
|
return {
|
|
73
|
-
|
|
74
|
-
session: {
|
|
75
|
-
id: "123",
|
|
76
|
-
}
|
|
77
|
-
}
|
|
82
|
+
name: "hello"
|
|
78
83
|
}
|
|
79
84
|
})
|
|
85
|
+
const endpoint = createEndpoint("/", {
|
|
86
|
+
method: "GET",
|
|
87
|
+
use: [middleware],
|
|
88
|
+
}, async (ctx) => {
|
|
89
|
+
//this will be the context object returned by the middleware with the name property
|
|
90
|
+
ctx.context
|
|
91
|
+
})
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
You can also pass an options object to the middleware and a handler function.
|
|
80
95
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
96
|
+
```ts
|
|
97
|
+
const middleware = createMiddleware({
|
|
98
|
+
body: z.object({
|
|
99
|
+
name: z.string()
|
|
100
|
+
})
|
|
101
|
+
}, async (ctx) => {
|
|
87
102
|
return {
|
|
88
|
-
|
|
103
|
+
name: "hello"
|
|
89
104
|
}
|
|
90
105
|
})
|
|
106
|
+
|
|
107
|
+
const endpoint = createEndpoint("/", {
|
|
108
|
+
method: "GET",
|
|
109
|
+
use: [middleware],
|
|
110
|
+
}, async (ctx) => {
|
|
111
|
+
//the body will also contain the middleware body
|
|
112
|
+
ctx.body
|
|
113
|
+
})
|
|
91
114
|
```
|
|
92
115
|
|
|
93
116
|
### Router
|
|
@@ -102,8 +125,34 @@ const router = createRouter([
|
|
|
102
125
|
createItem
|
|
103
126
|
])
|
|
104
127
|
```
|
|
128
|
+
|
|
105
129
|
Behind the scenes, the router uses [rou3](https://github.com/unjs/rou3) to match the endpoints and invoke the correct endpoint. You can look at the [rou3 documentation](https://github.com/unjs/rou3) for more information.
|
|
106
130
|
|
|
131
|
+
#### Router Options
|
|
132
|
+
|
|
133
|
+
**routerMiddleware**: A router middleware is similar to an endpoint middleware but it's applied to any path that matches the route. You have to pass endpoints to the router middleware as an array.
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
const routeMiddleware = createEndpoint("/api/**", {
|
|
137
|
+
method: "GET",
|
|
138
|
+
}, async (ctx) => {
|
|
139
|
+
return {
|
|
140
|
+
name: "hello"
|
|
141
|
+
}
|
|
142
|
+
})
|
|
143
|
+
const router = createRouter([
|
|
144
|
+
createItem
|
|
145
|
+
], {
|
|
146
|
+
routerMiddleware: [routeMiddleware]
|
|
147
|
+
})
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
**basePath**: The base path for the router. All paths will be relative to this path.
|
|
151
|
+
|
|
152
|
+
**onError**: The router will call this function if an error occurs in the middleware or the endpoint.
|
|
153
|
+
|
|
154
|
+
**throwError**: If true, the router will throw an error if an error occurs in the middleware or the endpoint.
|
|
155
|
+
|
|
107
156
|
|
|
108
157
|
### Returning non 200 responses
|
|
109
158
|
|
|
@@ -168,15 +217,7 @@ const createItem = createEndpoint("/item", {
|
|
|
168
217
|
})
|
|
169
218
|
```
|
|
170
219
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
### `createEndpoint`
|
|
174
|
-
|
|
175
|
-
```ts
|
|
176
|
-
createEndpoint(path: string, options: EndpointOptions, fn: EndpointFunction): Endpoint
|
|
177
|
-
```
|
|
178
|
-
|
|
179
|
-
Creates an endpoint. The `path` is the path that will be used to match the endpoint. The `options` are the options that will be used to validate the request. The `fn` is the function that will be invoked when the endpoint is called.
|
|
220
|
+
### Endpoint Parameters
|
|
180
221
|
|
|
181
222
|
### `path`
|
|
182
223
|
|
|
@@ -205,6 +246,7 @@ type EndpointOptions = {
|
|
|
205
246
|
params?: ZodSchema
|
|
206
247
|
requireHeaders?: boolean
|
|
207
248
|
requireRequest?: boolean
|
|
249
|
+
use?: Endpoint[]
|
|
208
250
|
}
|
|
209
251
|
```
|
|
210
252
|
|
|
@@ -220,6 +262,7 @@ type EndpointOptions = {
|
|
|
220
262
|
|
|
221
263
|
- **requireRequest**: if true, the endpoint will throw an error if the request doesn't have a request object. And even when you call the endpoint as a function, it will require a request to be passed in the context.
|
|
222
264
|
|
|
265
|
+
- **use**: the use option accepts an array of endpoints and will be called before the endpoint is called.
|
|
223
266
|
|
|
224
267
|
### `EndpointFunction`
|
|
225
268
|
|
package/dist/client.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var s=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var a=(t,e)=>{for(var r in e)s(t,r,{get:e[r],enumerable:!0})},x=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of p(e))!y.call(t,n)&&n!==r&&s(t,n,{get:()=>e[n],enumerable:!(o=d(e,n))||o.enumerable});return t};var u=t=>x(s({},"__esModule",{value:!0}),t);var c={};a(c,{createClient:()=>T});module.exports=u(c);var i=require("@better-fetch/fetch"),T=t=>{let e=(0,i.createFetch)(t);return async(r,...o)=>{let n=o[0];return await e(r,{...o[0],body:n.body,params:n.params})}};0&&(module.exports={createClient});
|
|
2
|
+
//# sourceMappingURL=client.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type { Endpoint, Prettify } from \"./types\";\nimport type { HasRequiredKeys, UnionToIntersection } from \"type-fest\";\nimport { type BetterFetchOption, type BetterFetchResponse, createFetch } from \"@better-fetch/fetch\";\nimport type { Router } from \"./router\";\n\ntype InferContext<T> = T extends (ctx: infer Ctx) => any\n\t? Ctx extends object\n\t\t? Ctx\n\t\t: never\n\t: never;\n\nexport interface ClientOptions extends BetterFetchOption {\n\tbaseURL: string;\n}\n\ntype WithRequired<T, K> = T & {\n\t[P in K extends string ? K : never]-?: T[P extends keyof T ? P : never];\n};\n\nexport type RequiredOptionKeys<\n\tC extends {\n\t\tbody?: any;\n\t\tquery?: any;\n\t\tparams?: any;\n\t},\n> = (undefined extends C[\"body\"]\n\t? {}\n\t: {\n\t\t\tbody: true;\n\t\t}) &\n\t(undefined extends C[\"query\"]\n\t\t? {}\n\t\t: {\n\t\t\t\tquery: true;\n\t\t\t}) &\n\t(undefined extends C[\"params\"]\n\t\t? {}\n\t\t: {\n\t\t\t\tparams: true;\n\t\t\t});\n\nexport const createClient = <R extends Router | Router[\"endpoints\"]>(options: ClientOptions) => {\n\tconst fetch = createFetch(options);\n\ttype API = R extends Router ? R[\"endpoints\"] : R;\n\ttype Options = API extends {\n\t\t[key: string]: infer T;\n\t}\n\t\t? T extends Endpoint\n\t\t\t? {\n\t\t\t\t\t[key in T[\"options\"][\"method\"] extends \"GET\"\n\t\t\t\t\t\t? T[\"path\"]\n\t\t\t\t\t\t: `@${T[\"options\"][\"method\"] extends string ? Lowercase<T[\"options\"][\"method\"]> : never}${T[\"path\"]}`]: T;\n\t\t\t\t}\n\t\t\t: {}\n\t\t: {};\n\n\ttype O = Prettify<UnionToIntersection<Options>>;\n\treturn async <OPT extends O, K extends keyof OPT, C extends InferContext<OPT[K]>>(\n\t\tpath: K,\n\t\t...options: HasRequiredKeys<C> extends true\n\t\t\t? [\n\t\t\t\t\tWithRequired<\n\t\t\t\t\t\tBetterFetchOption<C[\"body\"], C[\"query\"], C[\"params\"]>,\n\t\t\t\t\t\tkeyof RequiredOptionKeys<C>\n\t\t\t\t\t>,\n\t\t\t\t]\n\t\t\t: [BetterFetchOption<C[\"body\"], C[\"query\"], C[\"params\"]>?]\n\t): Promise<\n\t\tBetterFetchResponse<Awaited<ReturnType<OPT[K] extends Endpoint ? OPT[K] : never>>>\n\t> => {\n\t\tconst opts = options[0] as {\n\t\t\tparams?: Record<string, any>;\n\t\t\tbody?: Record<string, any>;\n\t\t};\n\t\treturn (await fetch(path as string, {\n\t\t\t...options[0],\n\t\t\tbody: opts.body,\n\t\t\tparams: opts.params,\n\t\t})) as any;\n\t};\n};\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,IAAA,eAAAC,EAAAH,GAEA,IAAAI,EAA8E,+BAuCjEF,EAAwDG,GAA2B,CAC/F,IAAMC,KAAQ,eAAYD,CAAO,EAejC,MAAO,OACNE,KACGF,IAUC,CACJ,IAAMG,EAAOH,EAAQ,CAAC,EAItB,OAAQ,MAAMC,EAAMC,EAAgB,CACnC,GAAGF,EAAQ,CAAC,EACZ,KAAMG,EAAK,KACX,OAAQA,EAAK,MACd,CAAC,CACF,CACD","names":["client_exports","__export","createClient","__toCommonJS","import_fetch","options","fetch","path","opts"]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { R as Router, f as Endpoint } from './router-CAklHiJN.cjs';
|
|
2
|
+
import { UnionToIntersection, HasRequiredKeys } from 'type-fest';
|
|
3
|
+
import { BetterFetchOption, BetterFetchResponse } from '@better-fetch/fetch';
|
|
4
|
+
import 'zod';
|
|
5
|
+
|
|
6
|
+
type InferContext<T> = T extends (ctx: infer Ctx) => any ? Ctx extends object ? Ctx : never : never;
|
|
7
|
+
interface ClientOptions extends BetterFetchOption {
|
|
8
|
+
baseURL: string;
|
|
9
|
+
}
|
|
10
|
+
type WithRequired<T, K> = T & {
|
|
11
|
+
[P in K extends string ? K : never]-?: T[P extends keyof T ? P : never];
|
|
12
|
+
};
|
|
13
|
+
type RequiredOptionKeys<C extends {
|
|
14
|
+
body?: any;
|
|
15
|
+
query?: any;
|
|
16
|
+
params?: any;
|
|
17
|
+
}> = (undefined extends C["body"] ? {} : {
|
|
18
|
+
body: true;
|
|
19
|
+
}) & (undefined extends C["query"] ? {} : {
|
|
20
|
+
query: true;
|
|
21
|
+
}) & (undefined extends C["params"] ? {} : {
|
|
22
|
+
params: true;
|
|
23
|
+
});
|
|
24
|
+
declare const createClient: <R extends Router | Router["endpoints"]>(options: ClientOptions) => <OPT extends UnionToIntersection<(R extends {
|
|
25
|
+
handler: (request: Request) => Promise<Response>;
|
|
26
|
+
endpoints: Record<string, Endpoint>;
|
|
27
|
+
} ? R["endpoints"] : R) extends {
|
|
28
|
+
[key: string]: infer T_1;
|
|
29
|
+
} ? T_1 extends Endpoint ? { [key_1 in T_1["options"]["method"] extends "GET" ? T_1["path"] : `@${T_1["options"]["method"] extends string ? Lowercase<T_1["options"]["method"]> : never}${T_1["path"]}`]: T_1; } : {} : {}> extends infer T ? { [key in keyof T]: UnionToIntersection<(R extends {
|
|
30
|
+
handler: (request: Request) => Promise<Response>;
|
|
31
|
+
endpoints: Record<string, Endpoint>;
|
|
32
|
+
} ? R["endpoints"] : R) extends {
|
|
33
|
+
[key: string]: infer T_1;
|
|
34
|
+
} ? T_1 extends Endpoint ? { [key_1 in T_1["options"]["method"] extends "GET" ? T_1["path"] : `@${T_1["options"]["method"] extends string ? Lowercase<T_1["options"]["method"]> : never}${T_1["path"]}`]: T_1; } : {} : {}>[key]; } : never, K extends keyof OPT, C extends InferContext<OPT[K]>>(path: K, ...options: HasRequiredKeys<C> extends true ? [WithRequired<BetterFetchOption<C["body"], C["query"], C["params"]>, keyof RequiredOptionKeys<C>>] : [BetterFetchOption<C["body"], C["query"], C["params"]>?]) => Promise<BetterFetchResponse<Awaited<ReturnType<OPT[K] extends Endpoint ? OPT[K] : never>>>>;
|
|
35
|
+
|
|
36
|
+
export { type ClientOptions, type RequiredOptionKeys, createClient };
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { R as Router, f as Endpoint } from './router-CAklHiJN.js';
|
|
2
|
+
import { UnionToIntersection, HasRequiredKeys } from 'type-fest';
|
|
3
|
+
import { BetterFetchOption, BetterFetchResponse } from '@better-fetch/fetch';
|
|
4
|
+
import 'zod';
|
|
5
|
+
|
|
6
|
+
type InferContext<T> = T extends (ctx: infer Ctx) => any ? Ctx extends object ? Ctx : never : never;
|
|
7
|
+
interface ClientOptions extends BetterFetchOption {
|
|
8
|
+
baseURL: string;
|
|
9
|
+
}
|
|
10
|
+
type WithRequired<T, K> = T & {
|
|
11
|
+
[P in K extends string ? K : never]-?: T[P extends keyof T ? P : never];
|
|
12
|
+
};
|
|
13
|
+
type RequiredOptionKeys<C extends {
|
|
14
|
+
body?: any;
|
|
15
|
+
query?: any;
|
|
16
|
+
params?: any;
|
|
17
|
+
}> = (undefined extends C["body"] ? {} : {
|
|
18
|
+
body: true;
|
|
19
|
+
}) & (undefined extends C["query"] ? {} : {
|
|
20
|
+
query: true;
|
|
21
|
+
}) & (undefined extends C["params"] ? {} : {
|
|
22
|
+
params: true;
|
|
23
|
+
});
|
|
24
|
+
declare const createClient: <R extends Router | Router["endpoints"]>(options: ClientOptions) => <OPT extends UnionToIntersection<(R extends {
|
|
25
|
+
handler: (request: Request) => Promise<Response>;
|
|
26
|
+
endpoints: Record<string, Endpoint>;
|
|
27
|
+
} ? R["endpoints"] : R) extends {
|
|
28
|
+
[key: string]: infer T_1;
|
|
29
|
+
} ? T_1 extends Endpoint ? { [key_1 in T_1["options"]["method"] extends "GET" ? T_1["path"] : `@${T_1["options"]["method"] extends string ? Lowercase<T_1["options"]["method"]> : never}${T_1["path"]}`]: T_1; } : {} : {}> extends infer T ? { [key in keyof T]: UnionToIntersection<(R extends {
|
|
30
|
+
handler: (request: Request) => Promise<Response>;
|
|
31
|
+
endpoints: Record<string, Endpoint>;
|
|
32
|
+
} ? R["endpoints"] : R) extends {
|
|
33
|
+
[key: string]: infer T_1;
|
|
34
|
+
} ? T_1 extends Endpoint ? { [key_1 in T_1["options"]["method"] extends "GET" ? T_1["path"] : `@${T_1["options"]["method"] extends string ? Lowercase<T_1["options"]["method"]> : never}${T_1["path"]}`]: T_1; } : {} : {}>[key]; } : never, K extends keyof OPT, C extends InferContext<OPT[K]>>(path: K, ...options: HasRequiredKeys<C> extends true ? [WithRequired<BetterFetchOption<C["body"], C["query"], C["params"]>, keyof RequiredOptionKeys<C>>] : [BetterFetchOption<C["body"], C["query"], C["params"]>?]) => Promise<BetterFetchResponse<Awaited<ReturnType<OPT[K] extends Endpoint ? OPT[K] : never>>>>;
|
|
35
|
+
|
|
36
|
+
export { type ClientOptions, type RequiredOptionKeys, createClient };
|
package/dist/client.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type { Endpoint, Prettify } from \"./types\";\nimport type { HasRequiredKeys, UnionToIntersection } from \"type-fest\";\nimport { type BetterFetchOption, type BetterFetchResponse, createFetch } from \"@better-fetch/fetch\";\nimport type { Router } from \"./router\";\n\ntype InferContext<T> = T extends (ctx: infer Ctx) => any\n\t? Ctx extends object\n\t\t? Ctx\n\t\t: never\n\t: never;\n\nexport interface ClientOptions extends BetterFetchOption {\n\tbaseURL: string;\n}\n\ntype WithRequired<T, K> = T & {\n\t[P in K extends string ? K : never]-?: T[P extends keyof T ? P : never];\n};\n\nexport type RequiredOptionKeys<\n\tC extends {\n\t\tbody?: any;\n\t\tquery?: any;\n\t\tparams?: any;\n\t},\n> = (undefined extends C[\"body\"]\n\t? {}\n\t: {\n\t\t\tbody: true;\n\t\t}) &\n\t(undefined extends C[\"query\"]\n\t\t? {}\n\t\t: {\n\t\t\t\tquery: true;\n\t\t\t}) &\n\t(undefined extends C[\"params\"]\n\t\t? {}\n\t\t: {\n\t\t\t\tparams: true;\n\t\t\t});\n\nexport const createClient = <R extends Router | Router[\"endpoints\"]>(options: ClientOptions) => {\n\tconst fetch = createFetch(options);\n\ttype API = R extends Router ? R[\"endpoints\"] : R;\n\ttype Options = API extends {\n\t\t[key: string]: infer T;\n\t}\n\t\t? T extends Endpoint\n\t\t\t? {\n\t\t\t\t\t[key in T[\"options\"][\"method\"] extends \"GET\"\n\t\t\t\t\t\t? T[\"path\"]\n\t\t\t\t\t\t: `@${T[\"options\"][\"method\"] extends string ? Lowercase<T[\"options\"][\"method\"]> : never}${T[\"path\"]}`]: T;\n\t\t\t\t}\n\t\t\t: {}\n\t\t: {};\n\n\ttype O = Prettify<UnionToIntersection<Options>>;\n\treturn async <OPT extends O, K extends keyof OPT, C extends InferContext<OPT[K]>>(\n\t\tpath: K,\n\t\t...options: HasRequiredKeys<C> extends true\n\t\t\t? [\n\t\t\t\t\tWithRequired<\n\t\t\t\t\t\tBetterFetchOption<C[\"body\"], C[\"query\"], C[\"params\"]>,\n\t\t\t\t\t\tkeyof RequiredOptionKeys<C>\n\t\t\t\t\t>,\n\t\t\t\t]\n\t\t\t: [BetterFetchOption<C[\"body\"], C[\"query\"], C[\"params\"]>?]\n\t): Promise<\n\t\tBetterFetchResponse<Awaited<ReturnType<OPT[K] extends Endpoint ? OPT[K] : never>>>\n\t> => {\n\t\tconst opts = options[0] as {\n\t\t\tparams?: Record<string, any>;\n\t\t\tbody?: Record<string, any>;\n\t\t};\n\t\treturn (await fetch(path as string, {\n\t\t\t...options[0],\n\t\t\tbody: opts.body,\n\t\t\tparams: opts.params,\n\t\t})) as any;\n\t};\n};\n"],"mappings":"AAEA,OAA2D,eAAAA,MAAmB,sBAuCvE,IAAMC,EAAwDC,GAA2B,CAC/F,IAAMC,EAAQH,EAAYE,CAAO,EAejC,MAAO,OACNE,KACGF,IAUC,CACJ,IAAMG,EAAOH,EAAQ,CAAC,EAItB,OAAQ,MAAMC,EAAMC,EAAgB,CACnC,GAAGF,EAAQ,CAAC,EACZ,KAAMG,EAAK,KACX,OAAQA,EAAK,MACd,CAAC,CACF,CACD","names":["createFetch","createClient","options","fetch","path","opts"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var h=Object.defineProperty;var
|
|
1
|
+
"use strict";var h=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var W=Object.prototype.hasOwnProperty;var v=(r,e,t)=>e in r?h(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var K=(r,e)=>{for(var t in e)h(r,t,{get:e[t],enumerable:!0})},F=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Q(e))!W.call(r,s)&&s!==t&&h(r,s,{get:()=>e[s],enumerable:!(n=$(e,s))||n.enumerable});return r};var G=r=>F(h({},"__esModule",{value:!0}),r);var R=(r,e,t)=>v(r,typeof e!="symbol"?e+"":e,t);var te={};K(te,{APIError:()=>y,createEndpoint:()=>x,createEndpointCreator:()=>J,createMiddleware:()=>z,createMiddlewareCreator:()=>Z,createRouter:()=>ee,getBody:()=>T,shouldSerialize:()=>S,statusCode:()=>_});module.exports=G(te);var B=require("zod");var ne=require("zod");function z(r,e){if(typeof r=="function")return x("*",{method:"*"},r);if(!e)throw new Error("Middleware handler is required");return x("*",{...r,method:"*"},e)}var Z=()=>{function r(e,t){if(typeof e=="function")return x("*",{method:"*"},e);if(!t)throw new Error("Middleware handler is required");return x("*",{...e,method:"*"},t)}return r};var y=class extends Error{constructor(t,n){super(`API Error: ${t} ${n?.message??""}`,{cause:n});R(this,"status");R(this,"body");this.status=t,this.body=n??{},this.stack="",this.name="BetterCallAPIError"}};var C={name:"HMAC",hash:"SHA-256"},A=async r=>{let e=typeof r=="string"?new TextEncoder().encode(r):r;return await crypto.subtle.importKey("raw",e,C,!1,["sign","verify"])},Y=async(r,e)=>{let t=await A(e),n=await crypto.subtle.sign(C.name,t,new TextEncoder().encode(r));return btoa(String.fromCharCode(...new Uint8Array(n)))},V=async(r,e,t)=>{try{let n=atob(r),s=new Uint8Array(n.length);for(let i=0,o=n.length;i<o;i++)s[i]=n.charCodeAt(i);return await crypto.subtle.verify(C,t,s,new TextEncoder().encode(e))}catch{return!1}},j=/^[\w!#$%&'*.^`|~+-]+$/,X=/^[ !#-:<-[\]-~]*$/,P=(r,e)=>r.trim().split(";").reduce((n,s)=>{s=s.trim();let i=s.indexOf("=");if(i===-1)return n;let o=s.substring(0,i).trim();if(e&&e!==o||!j.test(o))return n;let p=s.substring(i+1).trim();return p.startsWith('"')&&p.endsWith('"')&&(p=p.slice(1,-1)),X.test(p)&&(n[o]=decodeURIComponent(p)),n},{}),H=async(r,e,t)=>{let n={},s=await A(e);for(let[i,o]of Object.entries(P(r,t))){let p=o.lastIndexOf(".");if(p<1)continue;let a=o.substring(0,p),d=o.substring(p+1);if(d.length!==44||!d.endsWith("="))continue;let u=await V(d,a,s);n[i]=u?a:!1}return n},N=(r,e,t={})=>{let n=`${r}=${e}`;if(r.startsWith("__Secure-")&&!t.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(r.startsWith("__Host-")){if(!t.secure)throw new Error("__Host- Cookie must have Secure attributes");if(t.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(t.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(t&&typeof t.maxAge=="number"&&t.maxAge>=0){if(t.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(t.maxAge)}`}if(t.domain&&t.prefix!=="host"&&(n+=`; Domain=${t.domain}`),t.path&&(n+=`; Path=${t.path}`),t.expires){if(t.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${t.expires.toUTCString()}`}if(t.httpOnly&&(n+="; HttpOnly"),t.secure&&(n+="; Secure"),t.sameSite&&(n+=`; SameSite=${t.sameSite.charAt(0).toUpperCase()+t.sameSite.slice(1)}`),t.partitioned){if(!t.secure)throw new Error("Partitioned Cookie must have Secure attributes");n+="; Partitioned"}return n},O=(r,e,t)=>(e=encodeURIComponent(e),N(r,e,t)),l=async(r,e,t,n={})=>{let s=await Y(e,t);return e=`${e}.${s}`,e=encodeURIComponent(e),N(r,e,n)};var D=(r,e,t)=>{if(!r)return;let n=e;if(t==="secure")n="__Secure-"+e;else if(t==="host")n="__Host-"+e;else return;return P(r,n)[n]},U=(r,e,t,n)=>{let s;n?.prefix==="secure"?s=O("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?s=O("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):s=O(e,t,{path:"/",...n}),r.append("Set-Cookie",s)},M=async(r,e,t,n,s)=>{let i;s?.prefix==="secure"?i=await l("__Secure-"+e,t,n,{path:"/",...s,secure:!0}):s?.prefix==="host"?i=await l("__Host-"+e,t,n,{...s,path:"/",secure:!0,domain:void 0}):i=await l(e,t,n,{path:"/",...s}),r.append("Set-Cookie",i)},q=async(r,e,t,n)=>{let s=r.get("Cookie");if(!s)return;let i=t;return n==="secure"?i="__Secure-"+t:n==="host"&&(i="__Host-"+t),(await H(s,e,i))[i]};function J(){return(r,e,t)=>x(r,e,t)}function x(r,e,t){let n=new Headers,s=async(...i)=>{let o={setHeader(a,d){n.set(a,d)},setCookie(a,d,u){U(n,a,d,u)},getCookie(a,d){let u=i[0]?.headers;return D(u?.get("Cookie")||"",a,d)},getSignedCookie(a,d,u){let c=i[0]?.headers;if(!c)throw new TypeError("Headers are required");return q(c,d,a,u)},async setSignedCookie(a,d,u,c){await M(n,a,d,u,c)},...i[0]||{},context:{}};if(e.use?.length)for(let a of e.use){let d=await a(o),u=d.options?.body?d.options.body.parse(o.body):void 0;d&&(o={...o,body:u?{...u,...o.body}:o.body,context:{...o.context||{},...d}})}try{let a=e.body?e.body.parse(o.body):o.body;o={...o,body:a?{...a,...o.body}:o.body},o.query=e.query?e.query.parse(o.query):o.query,o.params=e.params?e.params.parse(o.params):o.params}catch(a){throw a instanceof B.ZodError?new y("BAD_REQUEST",{message:a.message,details:a.errors}):a}if(e.requireHeaders&&!o.headers)throw new y("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!o.request)throw new y("BAD_REQUEST",{message:"Request is required"});return await t(o)};return s.path=r,s.options=e,s.method=e.method,s.headers=n,s}var E=require("rou3");async function T(r){let e=r.headers.get("content-type")||"";if(r.body){if(e.includes("application/json"))return await r.json();if(e.includes("application/x-www-form-urlencoded")){let t=await r.formData(),n={};return t.forEach((s,i)=>{n[i]=s.toString()}),n}if(e.includes("multipart/form-data")){let t=await r.formData(),n={};return t.forEach((s,i)=>{n[i]=s}),n}return e.includes("text/plain")?await r.text():e.includes("application/octet-stream")?await r.arrayBuffer():e.includes("application/pdf")||e.includes("image/")||e.includes("video/")?await r.blob():e.includes("application/stream")||r.body instanceof ReadableStream?r.body:await r.text()}}function S(r){return typeof r=="object"&&r!==null&&!(r instanceof Blob)&&!(r instanceof FormData)}var _={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};var ee=(r,e)=>{let t=Object.values(r),n=(0,E.createRouter)();for(let o of t)if(Array.isArray(o.options?.method))for(let p of o.options.method)(0,E.addRoute)(n,p,o.path,o);else(0,E.addRoute)(n,o.options.method,o.path,o);let s=(0,E.createRouter)();for(let o of e?.routerMiddleware||[])(0,E.addRoute)(s,"*",o.path,o.middleware);return{handler:async o=>{let p=new URL(o.url),a=p.pathname;e?.basePath&&(a=a.split(e.basePath)[1]);let d=o.method,u=(0,E.findRoute)(n,d,a),c=u?.data,g=await T(o),w=o.headers,I=Object.fromEntries(p.searchParams),k=(0,E.findRoute)(s,"*",a)?.data;if(!c)return new Response(null,{status:404,statusText:"Not Found"});try{let f={};if(k){let b=await k({path:a,method:d,headers:w,params:u?.params,request:o,body:g,query:I,...e?.extraContext});b&&(f={...b,...f})}let m=await c({path:a,method:d,headers:w,params:u?.params,request:o,body:g,query:I,...f,...e?.extraContext});if(m instanceof Response)return m;let L=S(m)?JSON.stringify(m):m;return new Response(L,{headers:c.headers})}catch(f){if(e?.onError){let m=await e.onError(f);if(m instanceof Response)return m}if(f instanceof y)return new Response(f.body?JSON.stringify(f.body):null,{status:_[f.status],statusText:f.status,headers:c.headers});if(e?.throwError)throw f;return new Response(null,{status:500,statusText:"Internal Server Error"})}},endpoints:r}};var Ce=require("zod");0&&(module.exports={APIError,createEndpoint,createEndpointCreator,createMiddleware,createMiddlewareCreator,createRouter,getBody,shouldSerialize,statusCode});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/endpoint.ts","../src/better-call-error.ts","../src/router.ts","../src/utils.ts","../src/middleware.ts"],"sourcesContent":["export * from \"./endpoint\"\nexport * from \"./router\"\nexport * from \"./middleware\"\nexport * from \"./better-call-error\"\nexport * from \"./utils\"","import { z, ZodError, type ZodOptional, type ZodSchema } from \"zod\"\nimport type { Middleware } from \"./middleware\"\nimport { APIError } from \"./better-call-error\";\n\n\nexport type RequiredKeysOf<BaseType extends object> = Exclude<{\n [Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]>\n ? Key\n : never\n}[keyof BaseType], undefined>;\n\nexport type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never ? false : true;\n\ntype Method = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"*\"\n\nexport interface EndpointOptions {\n method: Method | Method[]\n body?: ZodSchema\n query?: ZodSchema\n params?: ZodSchema<any>\n /**\n * If true headers will be required to be passed in the context\n */\n requireHeaders?: boolean\n /**\n * If true request object will be required\n */\n requireRequest?: boolean\n}\n\ntype InferParamPath<Path> =\n Path extends `${infer _Start}:${infer Param}/${infer Rest}`\n ? { [K in Param | keyof InferParamPath<Rest>]: string }\n : Path extends `${infer _Start}:${infer Param}`\n ? { [K in Param]: string }\n : Path extends `${infer _Start}/${infer Rest}`\n ? InferParamPath<Rest>\n : undefined;\n\ntype InferParamWildCard<Path> = Path extends `${infer _Start}/*:${infer Param}/${infer Rest}` | `${infer _Start}/**:${infer Param}/${infer Rest}`\n ? { [K in Param | keyof InferParamPath<Rest>]: string }\n : Path extends `${infer _Start}/*`\n ? { [K in \"_\"]: string }\n : Path extends `${infer _Start}/${infer Rest}`\n ? InferParamPath<Rest>\n : undefined;\n\n\nexport type Prettify<T> = {\n [key in keyof T]: T[key];\n} & {};\n\ntype ContextTools = {\n setHeader: (key: string, value: string) => void\n setCookie: (key: string, value: string) => void\n getCookie: (key: string) => string | undefined\n}\n\nexport type Context<Path extends string, Opts extends EndpointOptions, Extra extends Record<string, any> = {}> = InferBody<Opts[\"body\"]> & InferParam<Path> & InferMethod<Opts['method']> & InferHeaders<Opts[\"requireHeaders\"]> & InferRequest<Opts[\"requireRequest\"]> & InferQuery<Opts[\"query\"]> & Extra\n\ntype InferMethod<M extends Method | Method[]> = M extends Array<Method> ? {\n method: M[number]\n} : {\n method?: M\n}\n\ntype InferHeaders<HeaderReq> = HeaderReq extends true ? {\n headers: Headers\n} : {\n headers?: Headers\n}\n\ntype InferRequest<RequestReq> = RequestReq extends true ? {\n request: Request\n} : {\n request?: Request\n}\n\n\ntype InferBody<Body> = Body extends ZodSchema ? Body extends ZodOptional<any> ? {\n body?: z.infer<Body>\n} : {\n body: z.infer<Body>\n} : {\n body?: undefined\n}\n\ntype InferQuery<Query> = Query extends ZodSchema ? Query extends ZodOptional<any> ? {\n query?: z.infer<Query>\n} : {\n query: z.infer<Query>\n} : {\n query?: undefined\n}\n\ntype InferParam<Path extends string, ParamPath extends InferParamPath<Path> = InferParamPath<Path>, WildCard extends InferParamWildCard<Path> = InferParamWildCard<Path>> = ParamPath extends undefined ? WildCard extends undefined ? {\n params?: undefined\n} : {\n params: WildCard\n} : {\n params: ParamPath & (WildCard extends undefined ? {} : WildCard)\n}\n\n\nexport type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined\n\nexport type Handler<Path extends string, Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = Record<string, any>> = (ctx: Context<Path, Opts, Extra>) => Promise<R>\n\nexport interface EndpointConfig {\n /**\n * Throw when the response isn't in 200 range\n */\n throwOnError?: boolean\n}\n\nexport function createEndpoint<Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(path: Path, options: Opts, handler: Handler<Path, Opts, R, ContextTools>) {\n const responseHeader = new Headers()\n type Ctx = Context<Path, Opts>\n const handle = async (...ctx: HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]) => {\n const internalCtx = ({\n setHeader(key, value) {\n responseHeader.set(key, value)\n },\n setCookie(key, value) {\n responseHeader.append(\"Set-Cookie\", `${key}=${value}`)\n },\n getCookie(key) {\n const header = ctx[0]?.headers\n return header?.get(\"cookie\")?.split(\";\").find(cookie => cookie.startsWith(`${key}=`))?.split(\"=\")[1]\n },\n ...(ctx[0] || {})\n }) as (Ctx & ContextTools)\n try {\n internalCtx.body = options.body ? options.body.parse(internalCtx.body) : undefined\n internalCtx.query = options.query ? options.query.parse(internalCtx.query) : undefined\n internalCtx.params = options.params ? options.params.parse(internalCtx.params) : undefined\n } catch (e) {\n if (e instanceof ZodError) {\n throw new APIError(\"Bad Request\", {\n message: e.message,\n details: e.errors\n })\n }\n throw e\n }\n if (options.requireHeaders && !internalCtx.headers) {\n throw new APIError(\"Bad Request\", {\n message: \"Headers are required\"\n })\n }\n if (options.requireRequest && !internalCtx.request) {\n throw new APIError(\"Bad Request\", {\n message: \"Request is required\"\n })\n }\n const res = await handler(internalCtx)\n return res as ReturnType<Handler<Path, Opts, R>>\n }\n handle.path = path\n handle.options = options\n handle.method = options.method\n handle.headers = responseHeader\n //for type inference\n handle.middleware = undefined as (Middleware<any> | undefined)\n\n return handle\n}\n\nexport type Endpoint = {\n path: string\n options: EndpointOptions\n middleware?: Middleware<any>\n headers?: Headers\n} & ((ctx: any) => Promise<any>)","import type { statusCode } from \"./utils\"\n\ntype Status = keyof typeof statusCode\n\nexport class APIError extends Error {\n status: Status\n body: Record<string, any>\n constructor(\n status: Status,\n body?: Record<string, any>,\n ) {\n super(\n `API Error: ${status} ${body?.message ?? \"\"}`,\n {\n cause: body,\n }\n )\n this.status = status\n this.body = body ?? {}\n this.stack = \"\";\n this.name = \"BetterCallAPIError\"\n }\n}","import type { Endpoint } from \"./endpoint\";\nimport {\n createRouter as createRou3Router,\n addRoute,\n findRoute,\n} from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./better-call-error\";\n\ninterface RouterConfig {\n /**\n * Throw error if error occurred other than APIError\n */\n throwError?: boolean\n /**\n * Handle error\n */\n onError?: (e: unknown) => void | Promise<void> | Response | Promise<Response>\n /**\n * Base path for the router\n */\n basePath?: string\n}\n\nexport const createRouter = <E extends Endpoint, Config extends RouterConfig>(endpoints: E[], config?: Config) => {\n const router = createRou3Router()\n for (const endpoint of endpoints) {\n if (Array.isArray(endpoint.options?.method)) {\n for (const method of endpoint.options.method) {\n addRoute(router, method, endpoint.path, endpoint)\n }\n } else {\n addRoute(router, endpoint.options.method, endpoint.path, endpoint)\n }\n }\n\n const handler = async (request: Request) => {\n const url = new URL(request.url);\n let path = url.pathname\n if (config?.basePath) {\n path = path.split(config.basePath)[1]\n }\n const method = request.method;\n const route = findRoute(router, method, path)\n const handler = route?.data as Endpoint\n const body = await getBody(request)\n const headers = request.headers\n\n //handler 404\n if (!handler) {\n return new Response(null, {\n status: 404,\n statusText: \"Not Found\"\n })\n }\n try {\n let middleware: Record<string, any> = {}\n if (handler.middleware) {\n middleware = await handler.middleware({\n path: path,\n method: method,\n headers,\n params: url.searchParams,\n request: request.clone(),\n body: body,\n }) || {}\n }\n const handlerRes = await handler({\n path: path,\n method: method as \"GET\",\n headers,\n params: route?.params as any,\n request: request,\n body: body,\n ...middleware?.context,\n })\n if (handlerRes instanceof Response) {\n return handlerRes\n }\n const resBody = shouldSerialize(handlerRes) ? JSON.stringify(handlerRes) : handlerRes\n return new Response(resBody as any, {\n headers: handler.headers\n })\n } catch (e) {\n if (config?.onError) {\n const onErrorRes = await config.onError(e)\n if (onErrorRes instanceof Response) {\n return onErrorRes\n }\n }\n if (e instanceof APIError) {\n return new Response(e.body ? JSON.stringify(e.body) : null, {\n status: statusCode[e.status],\n statusText: e.status,\n headers: {\n \"Content-Type\": \"application/json\",\n }\n })\n }\n if (config?.throwError) {\n throw e\n }\n return new Response(null, {\n status: 500,\n statusText: \"Internal Server Error\"\n })\n }\n }\n return { handler }\n}","export async function getBody(request: Request) {\n const contentType = request.headers.get('content-type') || '';\n\n if (!request.body) {\n return undefined\n }\n\n if (contentType.includes('application/json')) {\n return await request.json();\n }\n\n if (contentType.includes('application/x-www-form-urlencoded')) {\n const formData = await request.formData();\n const result: Record<string, string> = {};\n formData.forEach((value, key) => {\n result[key] = value.toString();\n });\n return result;\n }\n\n if (contentType.includes('multipart/form-data')) {\n const formData = await request.formData();\n const result: Record<string, any> = {};\n formData.forEach((value, key) => {\n result[key] = value;\n });\n return result;\n }\n\n if (contentType.includes('text/plain')) {\n return await request.text();\n }\n\n if (contentType.includes('application/octet-stream')) {\n return await request.arrayBuffer();\n }\n\n if (contentType.includes('application/pdf') || contentType.includes('image/') || contentType.includes('video/')) {\n const blob = await request.blob();\n return blob;\n }\n\n if (contentType.includes('application/stream') || request.body instanceof ReadableStream) {\n return request.body;\n }\n\n return await request.text();\n}\n\n\nexport function shouldSerialize(body: any) {\n return typeof body === \"object\" && body !== null && !(body instanceof Blob) && !(body instanceof FormData)\n}\n\nexport const statusCode = {\n \"OK\": 200,\n \"Created\": 201,\n \"Accepted\": 202,\n \"No Content\": 204,\n \"Multiple Choices\": 300,\n \"Moved Permanently\": 301,\n \"Found\": 302,\n \"See Other\": 303,\n \"Not Modified\": 304,\n \"Temporary Redirect\": 307,\n \"Bad Request\": 400,\n \"Unauthorized\": 401,\n \"Payment Required\": 402,\n \"Forbidden\": 403,\n \"Not Found\": 404,\n \"Method Not Allowed\": 405,\n \"Not Acceptable\": 406,\n \"Proxy Authentication Required\": 407,\n \"Request Timeout\": 408,\n \"Conflict\": 409,\n \"Gone\": 410,\n \"Length Required\": 411,\n \"Precondition Failed\": 412,\n \"Payload Too Large\": 413,\n \"URI Too Long\": 414,\n \"Unsupported Media Type\": 415,\n \"Range Not Satisfiable\": 416,\n \"Expectation Failed\": 417,\n \"I'm a teapot\": 418,\n \"Misdirected Request\": 421,\n \"Unprocessable Entity\": 422,\n \"Locked\": 423,\n \"Failed Dependency\": 424,\n \"Too Early\": 425,\n \"Upgrade Required\": 426,\n \"Precondition Required\": 428,\n \"Too Many Requests\": 429,\n \"Request Header Fields Too Large\": 431,\n \"Unavailable For Legal Reasons\": 451,\n \"Internal Server Error\": 500,\n \"Not Implemented\": 501,\n \"Bad Gateway\": 502,\n \"Service Unavailable\": 503,\n \"Gateway Timeout\": 504,\n \"HTTP Version Not Supported\": 505,\n \"Variant Also Negotiates\": 506,\n \"Insufficient Storage\": 507,\n \"Loop Detected\": 508,\n \"Not Extended\": 510,\n \"Network Authentication Required\": 511,\n}","import type { HasRequiredKeys } from \"type-fest\"\nimport { type Context, type EndpointOptions, type EndpointResponse, type Handler } from \"./endpoint\"\n\n\nexport type Middleware<E extends Record<string, string>> = (ctx: Context<string, EndpointOptions, E>) => Promise<{\n context: E\n} | void>\n\nexport const createMiddleware = <E extends Record<string, any>, M extends Middleware<E>>(middleware: M) => {\n type MiddlewareContext = Awaited<ReturnType<M>> extends {\n context: infer C\n } ? C extends Record<string, any> ? C : {} : {}\n return <Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(path: Path, options: Opts, handler: Handler<Path, Opts, R, MiddlewareContext>) => {\n type Ctx = Context<Path, Opts, MiddlewareContext>\n const handle = async (...ctx: HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]) => {\n const res = await handler((ctx[0] || {}) as Ctx)\n return res as ReturnType<Handler<Path, Opts, R>>\n }\n handle.path = path\n handle.options = options\n handle.middleware = middleware\n return handle\n }\n}"],"mappings":"ijBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,cAAAE,EAAA,mBAAAC,EAAA,qBAAAC,EAAA,iBAAAC,EAAA,YAAAC,EAAA,oBAAAC,EAAA,eAAAC,IAAA,eAAAC,EAAAT,GCAA,IAAAU,EAA8D,eCIvD,IAAMC,EAAN,cAAuB,KAAM,CAGhC,YACIC,EACAC,EACF,CACE,MACI,cAAcD,CAAM,IAAIC,GAAM,SAAW,EAAE,GAC3C,CACI,MAAOA,CACX,CACJ,EAXJC,EAAA,eACAA,EAAA,aAWI,KAAK,OAASF,EACd,KAAK,KAAOC,GAAQ,CAAC,EACrB,KAAK,MAAQ,GACb,KAAK,KAAO,oBAChB,CACJ,ED6FO,SAASE,EAA8FC,EAAYC,EAAeC,EAA+C,CACpL,IAAMC,EAAiB,IAAI,QAErBC,EAAS,SAAUC,IAA4D,CACjF,IAAMC,EAAe,CACjB,UAAUC,EAAKC,EAAO,CAClBL,EAAe,IAAII,EAAKC,CAAK,CACjC,EACA,UAAUD,EAAKC,EAAO,CAClBL,EAAe,OAAO,aAAc,GAAGI,CAAG,IAAIC,CAAK,EAAE,CACzD,EACA,UAAUD,EAAK,CAEX,OADeF,EAAI,CAAC,GAAG,SACR,IAAI,QAAQ,GAAG,MAAM,GAAG,EAAE,KAAKI,GAAUA,EAAO,WAAW,GAAGF,CAAG,GAAG,CAAC,GAAG,MAAM,GAAG,EAAE,CAAC,CACvG,EACA,GAAIF,EAAI,CAAC,GAAK,CAAC,CACnB,EACA,GAAI,CACAC,EAAY,KAAOL,EAAQ,KAAOA,EAAQ,KAAK,MAAMK,EAAY,IAAI,EAAI,OACzEA,EAAY,MAAQL,EAAQ,MAAQA,EAAQ,MAAM,MAAMK,EAAY,KAAK,EAAI,OAC7EA,EAAY,OAASL,EAAQ,OAASA,EA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EAAE,MAAM,EAC3B,WAAYA,EAAE,OACd,QAAS,CACL,eAAgB,kBACpB,CACJ,CAAC,EAEL,GAAIjB,GAAQ,WACR,MAAMiB,EAEV,OAAO,IAAI,SAAS,KAAM,CACtB,OAAQ,IACR,WAAY,uBAChB,CAAC,CACL,CACJ,CACiB,CACrB,EErGO,IAAMI,EAA4EC,GAI9E,CAAgFC,EAAYC,EAAeC,IAAuD,CAErK,IAAMC,EAAS,SAAUC,IACT,MAAMF,EAASE,EAAI,CAAC,GAAK,CAAC,CAAS,EAGnD,OAAAD,EAAO,KAAOH,EACdG,EAAO,QAAUF,EACjBE,EAAO,WAAaJ,EACbI,CACX","names":["src_exports","__export","APIError","createEndpoint","createMiddleware","createRouter","getBody","shouldSerialize","statusCode","__toCommonJS","import_zod","APIError","status","body","__publicField","createEndpoint","path","options","handler","responseHeader","handle","ctx","internalCtx","key","value","cookie","e","APIError","import_rou3","getBody","request","contentType","formData","result","value","key","shouldSerialize","body","statusCode","createRouter","endpoints","config","router","createRou3Router","endpoint","method","request","url","path","route","handler","body","getBody","headers","middleware","handlerRes","resBody","shouldSerialize","e","onErrorRes","APIError","statusCode","createMiddleware","middleware","path","options","handler","handle","ctx"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/endpoint.ts","../src/middleware.ts","../src/better-call-error.ts","../src/cookie.ts","../src/cookie-utils.ts","../src/router.ts","../src/utils.ts","../src/types.ts"],"sourcesContent":["export * from \"./endpoint\"\nexport * from \"./router\"\nexport * from \"./middleware\"\nexport * from \"./better-call-error\"\nexport * from \"./utils\"\nexport * from \"./types\"","import { z, ZodError, type ZodOptional, type ZodSchema } from \"zod\";\nimport { createMiddleware, type Middleware } from \"./middleware\";\nimport { APIError } from \"./better-call-error\";\nimport type { HasRequiredKeys, UnionToIntersection } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tCookieOptions,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n} from \"./types\";\nimport { getCookie, getSignedCookie, setCookie, setSignedCookie } from \"./cookie-utils\";\nimport type { CookiePrefixOptions } from \"./cookie\";\n\nexport interface EndpointConfig {\n\t/**\n\t * Throw when the response isn't in 200 range\n\t */\n\tthrowOnError?: boolean;\n}\n\nexport function createEndpointCreator<T extends Record<string, any>>() {\n\treturn <Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\tpath: Path,\n\t\toptions: Opts,\n\t\thandler: Handler<Path, Opts, R, T>,\n\t) => {\n\t\t//@ts-expect-error\n\t\treturn createEndpoint(path, options, handler);\n\t};\n}\n\nexport function createEndpoint<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n>(path: Path, options: Opts, handler: Handler<Path, Opts, R>) {\n\tconst responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\tconst handle = async (...ctx: HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]) => {\n\t\tlet internalCtx = {\n\t\t\tsetHeader(key: string, value: string) {\n\t\t\t\tresponseHeader.set(key, value);\n\t\t\t},\n\t\t\tsetCookie(key: string, value: string, options?: CookieOptions) {\n\t\t\t\tsetCookie(responseHeader, key, value, options);\n\t\t\t},\n\t\t\tgetCookie(key: string, prefix?: CookiePrefixOptions) {\n\t\t\t\tconst header = ctx[0]?.headers;\n\t\t\t\tconst cookie = getCookie(header?.get(\"Cookie\") || \"\", key, prefix);\n\t\t\t\treturn cookie;\n\t\t\t},\n\t\t\tgetSignedCookie(key: string, secret: string, prefix?: CookiePrefixOptions) {\n\t\t\t\tconst header = ctx[0]?.headers;\n\t\t\t\tif (!header) {\n\t\t\t\t\tthrow new TypeError(\"Headers are required\");\n\t\t\t\t}\n\t\t\t\tconst cookie = getSignedCookie(header, secret, key, prefix);\n\t\t\t\treturn cookie;\n\t\t\t},\n\t\t\tasync setSignedCookie(\n\t\t\t\tkey: string,\n\t\t\t\tvalue: string,\n\t\t\t\tsecret: string | BufferSource,\n\t\t\t\toptions?: CookieOptions,\n\t\t\t) {\n\t\t\t\tawait setSignedCookie(responseHeader, key, value, secret, options);\n\t\t\t},\n\t\t\t...(ctx[0] || {}),\n\t\t\tcontext: {},\n\t\t};\n\t\tif (options.use?.length) {\n\t\t\tfor (const middleware of options.use) {\n\t\t\t\tconst res = (await middleware(internalCtx)) as Endpoint;\n\t\t\t\tconst body = res.options?.body\n\t\t\t\t\t? res.options.body.parse(internalCtx.body)\n\t\t\t\t\t: undefined;\n\t\t\t\tif (res) {\n\t\t\t\t\tinternalCtx = {\n\t\t\t\t\t\t...internalCtx,\n\t\t\t\t\t\tbody: body\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t...body,\n\t\t\t\t\t\t\t\t\t...internalCtx.body,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: internalCtx.body,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t...(internalCtx.context || {}),\n\t\t\t\t\t\t\t...res,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst body = options.body ? options.body.parse(internalCtx.body) : internalCtx.body;\n\t\t\tinternalCtx = {\n\t\t\t\t...internalCtx,\n\t\t\t\tbody: body\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...body,\n\t\t\t\t\t\t\t...internalCtx.body,\n\t\t\t\t\t\t}\n\t\t\t\t\t: internalCtx.body,\n\t\t\t};\n\t\t\tinternalCtx.query = options.query\n\t\t\t\t? options.query.parse(internalCtx.query)\n\t\t\t\t: internalCtx.query;\n\t\t\tinternalCtx.params = options.params\n\t\t\t\t? options.params.parse(internalCtx.params)\n\t\t\t\t: internalCtx.params;\n\t\t} catch (e) {\n\t\t\tif (e instanceof ZodError) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: e.message,\n\t\t\t\t\tdetails: e.errors,\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t\tif (options.requireHeaders && !internalCtx.headers) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Headers are required\",\n\t\t\t});\n\t\t}\n\t\tif (options.requireRequest && !internalCtx.request) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Request is required\",\n\t\t\t});\n\t\t}\n\t\t//@ts-expect-error\n\t\tconst res = await handler(internalCtx);\n\t\treturn res as ReturnType<Handler<Path, Opts, R>>;\n\t};\n\thandle.path = path;\n\thandle.options = options;\n\thandle.method = options.method;\n\thandle.headers = responseHeader;\n\treturn handle;\n}\n","import { z } from \"zod\"\nimport type { ContextTools, Endpoint, EndpointOptions, EndpointResponse, Handler, InferBody, InferHeaders, InferRequest, Prettify } from \"./types\"\nimport { createEndpoint } from \"./endpoint\"\n\nexport type MiddlewareHandler<Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<InferBody<Opts> & InferRequest<Opts> & InferHeaders<Opts> & {\n params?: Record<string, string>,\n query?: Record<string, string>,\n} & ContextTools> & Extra) => Promise<R>\n\nexport function createMiddleware<Opts extends EndpointOptions, R extends EndpointResponse>(optionsOrHandler: MiddlewareHandler<Opts, R>): Endpoint<Handler<string, Opts, R>, Opts>\nexport function createMiddleware<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(optionsOrHandler: Opts, handler: MiddlewareHandler<Opts & {\n method: \"*\"\n}, R>): Endpoint<Handler<string, Opts & {\n method: \"*\"\n}, R>, Opts & {\n method: \"*\"\n}>\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n if (typeof optionsOrHandler === \"function\") {\n return createEndpoint(\"*\", {\n method: \"*\"\n }, optionsOrHandler)\n }\n if (!handler) {\n throw new Error(\"Middleware handler is required\")\n }\n const endpoint = createEndpoint(\"*\", {\n ...optionsOrHandler,\n method: \"*\"\n }, handler)\n return endpoint as any\n}\n\nexport const createMiddlewareCreator = <ExtraContext extends Record<string, any> = {}>() => {\n function fn<Opts extends EndpointOptions, R extends EndpointResponse>(optionsOrHandler: MiddlewareHandler<Opts, R, ExtraContext>): Endpoint<Handler<string, Opts, R>, Opts>\n function fn<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(optionsOrHandler: Opts, handler: MiddlewareHandler<Opts & {\n method: \"*\"\n }, R, ExtraContext>): Endpoint<Handler<string, Opts & {\n method: \"*\"\n }, R>, Opts & {\n method: \"*\"\n }>\n function fn(optionsOrHandler: any, handler?: any) {\n if (typeof optionsOrHandler === \"function\") {\n return createEndpoint(\"*\", {\n method: \"*\"\n }, optionsOrHandler)\n }\n if (!handler) {\n throw new Error(\"Middleware handler is required\")\n }\n const endpoint = createEndpoint(\"*\", {\n ...optionsOrHandler,\n method: \"*\"\n }, handler)\n return endpoint as any\n }\n return fn\n}\n\nexport type Middleware<Opts extends EndpointOptions = EndpointOptions, R extends EndpointResponse = EndpointResponse> = (opts: Opts, handler: (ctx: {\n body?: InferBody<Opts>,\n params?: Record<string, string>,\n query?: Record<string, string>\n}) => Promise<R>) => Endpoint","import type { statusCode } from \"./utils\"\n\ntype Status = keyof typeof statusCode\n\nexport class APIError extends Error {\n status: Status\n body: Record<string, any>\n constructor(\n status: Status,\n body?: Record<string, any>,\n ) {\n super(\n `API Error: ${status} ${body?.message ?? \"\"}`,\n {\n cause: body,\n }\n )\n this.status = status\n this.body = body ?? {}\n this.stack = \"\";\n this.name = \"BetterCallAPIError\"\n }\n}","//https://github.com/honojs/hono/blob/main/src/utils/cookie.ts\n\nexport type Cookie = Record<string, string>;\nexport type SignedCookie = Record<string, string | false>;\n\ntype PartitionCookieConstraint =\n\t| { partition: true; secure: true }\n\t| { partition?: boolean; secure?: boolean }; // reset to default\ntype SecureCookieConstraint = { secure: true };\ntype HostCookieConstraint = { secure: true; path: \"/\"; domain?: undefined };\n\nexport type CookieOptions = {\n\tdomain?: string;\n\texpires?: Date;\n\thttpOnly?: boolean;\n\tmaxAge?: number;\n\tpath?: string;\n\tsecure?: boolean;\n\tsigningSecret?: string;\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\tpartitioned?: boolean;\n\tprefix?: CookiePrefixOptions;\n} & PartitionCookieConstraint;\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieConstraint<Name> = Name extends `__Secure-${string}`\n\t? CookieOptions & SecureCookieConstraint\n\t: Name extends `__Host-${string}`\n\t\t? CookieOptions & HostCookieConstraint\n\t\t: CookieOptions;\n\nconst algorithm = { name: \"HMAC\", hash: \"SHA-256\" };\n\nconst getCryptoKey = async (secret: string | BufferSource): Promise<CryptoKey> => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await crypto.subtle.importKey(\"raw\", secretBuf, algorithm, false, [\"sign\", \"verify\"]);\n};\n\nconst makeSignature = async (value: string, secret: string | BufferSource): Promise<string> => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await crypto.subtle.sign(\n\t\talgorithm.name,\n\t\tkey,\n\t\tnew TextEncoder().encode(value),\n\t);\n\t// the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n\nconst verifySignature = async (\n\tbase64Signature: string,\n\tvalue: string,\n\tsecret: CryptoKey,\n): Promise<boolean> => {\n\ttry {\n\t\tconst signatureBinStr = atob(base64Signature);\n\t\tconst signature = new Uint8Array(signatureBinStr.length);\n\t\tfor (let i = 0, len = signatureBinStr.length; i < len; i++) {\n\t\t\tsignature[i] = signatureBinStr.charCodeAt(i);\n\t\t}\n\t\treturn await crypto.subtle.verify(\n\t\t\talgorithm,\n\t\t\tsecret,\n\t\t\tsignature,\n\t\t\tnew TextEncoder().encode(value),\n\t\t);\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\n\n// all alphanumeric chars and all of _!#$%&'*.^`|~+-\n// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)\nconst validCookieNameRegEx = /^[\\w!#$%&'*.^`|~+-]+$/;\n\n// all ASCII chars 32-126 except 34, 59, and 92 (i.e. space to tilde but not double quote, semicolon, or backslash)\n// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)\n//\n// note: the spec also prohibits comma and space, but we allow both since they are very common in the real world\n// (see: https://github.com/golang/go/issues/7243)\nconst validCookieValueRegEx = /^[ !#-:<-[\\]-~]*$/;\n\nexport const parse = (cookie: string, name?: string): Cookie => {\n\tconst pairs = cookie.trim().split(\";\");\n\treturn pairs.reduce((parsedCookie, pairStr) => {\n\t\tpairStr = pairStr.trim();\n\t\tconst valueStartPos = pairStr.indexOf(\"=\");\n\t\tif (valueStartPos === -1) {\n\t\t\treturn parsedCookie;\n\t\t}\n\n\t\tconst cookieName = pairStr.substring(0, valueStartPos).trim();\n\t\tif ((name && name !== cookieName) || !validCookieNameRegEx.test(cookieName)) {\n\t\t\treturn parsedCookie;\n\t\t}\n\n\t\tlet cookieValue = pairStr.substring(valueStartPos + 1).trim();\n\t\tif (cookieValue.startsWith('\"') && cookieValue.endsWith('\"')) {\n\t\t\tcookieValue = cookieValue.slice(1, -1);\n\t\t}\n\t\tif (validCookieValueRegEx.test(cookieValue)) {\n\t\t\tparsedCookie[cookieName] = decodeURIComponent(cookieValue);\n\t\t}\n\n\t\treturn parsedCookie;\n\t}, {} as Cookie);\n};\n\nexport const parseSigned = async (\n\tcookie: string,\n\tsecret: string | BufferSource,\n\tname?: string,\n): Promise<SignedCookie> => {\n\tconst parsedCookie: SignedCookie = {};\n\tconst secretKey = await getCryptoKey(secret);\n\n\tfor (const [key, value] of Object.entries(parse(cookie, name))) {\n\t\tconst signatureStartPos = value.lastIndexOf(\".\");\n\t\tif (signatureStartPos < 1) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst signedValue = value.substring(0, signatureStartPos);\n\t\tconst signature = value.substring(signatureStartPos + 1);\n\t\tif (signature.length !== 44 || !signature.endsWith(\"=\")) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst isVerified = await verifySignature(signature, signedValue, secretKey);\n\t\tparsedCookie[key] = isVerified ? signedValue : false;\n\t}\n\n\treturn parsedCookie;\n};\n\nconst _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {\n\tlet cookie = `${name}=${value}`;\n\n\tif (name.startsWith(\"__Secure-\") && !opt.secure) {\n\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.1\n\t\tthrow new Error(\"__Secure- Cookie must have Secure attributes\");\n\t}\n\n\tif (name.startsWith(\"__Host-\")) {\n\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.2\n\t\tif (!opt.secure) {\n\t\t\tthrow new Error(\"__Host- Cookie must have Secure attributes\");\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\tthrow new Error('__Host- Cookie must have Path attributes with \"/\"');\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\tthrow new Error(\"__Host- Cookie must not have Domain attributes\");\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.2\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.1\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\t// FIXME: replace link to RFC\n\t\t// https://www.ietf.org/archive/id/draft-cutler-httpbis-partitioned-cookies-01.html#section-2.3\n\t\tif (!opt.secure) {\n\t\t\tthrow new Error(\"Partitioned Cookie must have Secure attributes\");\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serialize = <Name extends string>(\n\tname: Name,\n\tvalue: string,\n\topt?: CookieConstraint<Name>,\n): string => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(name, value, opt);\n};\n\nexport const serializeSigned = async (\n\tname: string,\n\tvalue: string,\n\tsecret: string | BufferSource,\n\topt: CookieOptions = {},\n): Promise<string> => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(name, value, opt);\n};\n","//https://github.com/honojs/hono/blob/main/src/helper/cookie/index.ts\n\nimport {\n\tparse,\n\tparseSigned,\n\tserialize,\n\tserializeSigned,\n\ttype CookieOptions,\n\ttype CookiePrefixOptions,\n} from \"./cookie\";\n\nexport const getCookie = (cookie?: string, key?: string, prefix?: CookiePrefixOptions) => {\n\tif (!cookie) {\n\t\treturn undefined;\n\t}\n\tlet finalKey = key;\n\tif (prefix === \"secure\") {\n\t\tfinalKey = \"__Secure-\" + key;\n\t} else if (prefix === \"host\") {\n\t\tfinalKey = \"__Host-\" + key;\n\t} else {\n\t\treturn undefined;\n\t}\n\tconst obj = parse(cookie, finalKey);\n\treturn obj[finalKey];\n};\n\nexport const setCookie = (\n\theader: Headers,\n\tname: string,\n\tvalue: string,\n\topt?: CookieOptions,\n): void => {\n\t// Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.\n\t// Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)\n\t// and must not have a Domain attribute.\n\t// Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'\n\tlet cookie;\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = serialize(\"__Secure-\" + name, value, { path: \"/\", ...opt, secure: true });\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = serialize(\"__Host-\" + name, value, {\n\t\t\t...opt,\n\t\t\tpath: \"/\",\n\t\t\tsecure: true,\n\t\t\tdomain: undefined,\n\t\t});\n\t} else {\n\t\tcookie = serialize(name, value, { path: \"/\", ...opt });\n\t}\n\theader.append(\"Set-Cookie\", cookie);\n};\n\nexport const setSignedCookie = async (\n\theader: Headers,\n\tname: string,\n\tvalue: string,\n\tsecret: string | BufferSource,\n\topt?: CookieOptions,\n): Promise<void> => {\n\tlet cookie;\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = await serializeSigned(\"__Secure-\" + name, value, secret, {\n\t\t\tpath: \"/\",\n\t\t\t...opt,\n\t\t\tsecure: true,\n\t\t});\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = await serializeSigned(\"__Host-\" + name, value, secret, {\n\t\t\t...opt,\n\t\t\tpath: \"/\",\n\t\t\tsecure: true,\n\t\t\tdomain: undefined,\n\t\t});\n\t} else {\n\t\tcookie = await serializeSigned(name, value, secret, { path: \"/\", ...opt });\n\t}\n\theader.append(\"Set-Cookie\", cookie);\n};\n\nexport const getSignedCookie = async (\n\theader: Headers,\n\tsecret: string,\n\tkey: string,\n\tprefix?: CookiePrefixOptions,\n) => {\n\tconst cookie = header.get(\"Cookie\");\n\tif (!cookie) {\n\t\treturn undefined;\n\t}\n\tlet finalKey = key;\n\tif (prefix === \"secure\") {\n\t\tfinalKey = \"__Secure-\" + key;\n\t} else if (prefix === \"host\") {\n\t\tfinalKey = \"__Host-\" + key;\n\t}\n\tconst obj = await parseSigned(cookie, secret, finalKey);\n\treturn obj[finalKey];\n};\n","import { createRouter as createRou3Router, addRoute, findRoute } from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./better-call-error\";\nimport type { Middleware, MiddlewareHandler } from \"./middleware\";\nimport type { Endpoint, Method } from \"./types\";\n\ninterface RouterConfig {\n\t/**\n\t * Throw error if error occurred other than APIError\n\t */\n\tthrowError?: boolean;\n\t/**\n\t * Handle error\n\t */\n\tonError?: (e: unknown) => void | Promise<void> | Response | Promise<Response>;\n\t/**\n\t * Base path for the router\n\t */\n\tbasePath?: string;\n\t/**\n\t * Middlewares for the router\n\t */\n\trouterMiddleware?: {\n\t\tpath: string;\n\t\tmiddleware: Endpoint;\n\t}[];\n\textraContext?: Record<string, any>;\n}\n\nexport const createRouter = <E extends Record<string, Endpoint>, Config extends RouterConfig>(\n\tendpoints: E,\n\tconfig?: Config,\n) => {\n\tconst _endpoints = Object.values(endpoints);\n\tconst router = createRou3Router();\n\tfor (const endpoint of _endpoints) {\n\t\tif (Array.isArray(endpoint.options?.method)) {\n\t\t\tfor (const method of endpoint.options.method) {\n\t\t\t\taddRoute(router, method, endpoint.path, endpoint);\n\t\t\t}\n\t\t} else {\n\t\t\taddRoute(router, endpoint.options.method, endpoint.path, endpoint);\n\t\t}\n\t}\n\n\tconst middlewareRouter = createRou3Router();\n\tfor (const route of config?.routerMiddleware || []) {\n\t\taddRoute(middlewareRouter, \"*\", route.path, route.middleware);\n\t}\n\n\tconst handler = async (request: Request) => {\n\t\tconst url = new URL(request.url);\n\t\tlet path = url.pathname;\n\t\tif (config?.basePath) {\n\t\t\tpath = path.split(config.basePath)[1];\n\t\t}\n\t\tconst method = request.method;\n\t\tconst route = findRoute(router, method, path);\n\t\tconst handler = route?.data as Endpoint;\n\t\tconst body = await getBody(request);\n\t\tconst headers = request.headers;\n\t\tconst query = Object.fromEntries(url.searchParams);\n\t\tconst middleware = findRoute(middlewareRouter, \"*\", path)?.data as Endpoint | undefined;\n\t\t//handler 404\n\t\tif (!handler) {\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 404,\n\t\t\t\tstatusText: \"Not Found\",\n\t\t\t});\n\t\t}\n\t\ttry {\n\t\t\tlet middlewareContext: Record<string, any> = {};\n\t\t\tif (middleware) {\n\t\t\t\tconst res = await middleware({\n\t\t\t\t\tpath: path,\n\t\t\t\t\tmethod: method as \"GET\",\n\t\t\t\t\theaders,\n\t\t\t\t\tparams: route?.params as any,\n\t\t\t\t\trequest: request,\n\t\t\t\t\tbody: body,\n\t\t\t\t\tquery,\n\t\t\t\t\t...config?.extraContext,\n\t\t\t\t});\n\t\t\t\tif (res) {\n\t\t\t\t\tmiddlewareContext = {\n\t\t\t\t\t\t...res,\n\t\t\t\t\t\t...middlewareContext,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst handlerRes = await handler({\n\t\t\t\tpath: path,\n\t\t\t\tmethod: method as \"GET\",\n\t\t\t\theaders,\n\t\t\t\tparams: route?.params as any,\n\t\t\t\trequest: request,\n\t\t\t\tbody: body,\n\t\t\t\tquery,\n\t\t\t\t...middlewareContext,\n\t\t\t\t...config?.extraContext,\n\t\t\t});\n\t\t\tif (handlerRes instanceof Response) {\n\t\t\t\treturn handlerRes;\n\t\t\t}\n\t\t\tconst resBody = shouldSerialize(handlerRes) ? JSON.stringify(handlerRes) : handlerRes;\n\t\t\treturn new Response(resBody as any, {\n\t\t\t\theaders: handler.headers,\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (config?.onError) {\n\t\t\t\tconst onErrorRes = await config.onError(e);\n\t\t\t\tif (onErrorRes instanceof Response) {\n\t\t\t\t\treturn onErrorRes;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (e instanceof APIError) {\n\t\t\t\treturn new Response(e.body ? JSON.stringify(e.body) : null, {\n\t\t\t\t\tstatus: statusCode[e.status],\n\t\t\t\t\tstatusText: e.status,\n\t\t\t\t\theaders: handler.headers,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (config?.throwError) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 500,\n\t\t\t\tstatusText: \"Internal Server Error\",\n\t\t\t});\n\t\t}\n\t};\n\treturn {\n\t\thandler,\n\t\tendpoints,\n\t};\n};\n\nexport type Router = ReturnType<typeof createRouter>;\n","export async function getBody(request: Request) {\n const contentType = request.headers.get('content-type') || '';\n\n if (!request.body) {\n return undefined\n }\n\n if (contentType.includes('application/json')) {\n return await request.json();\n }\n\n if (contentType.includes('application/x-www-form-urlencoded')) {\n const formData = await request.formData();\n const result: Record<string, string> = {};\n formData.forEach((value, key) => {\n result[key] = value.toString();\n });\n return result;\n }\n\n if (contentType.includes('multipart/form-data')) {\n const formData = await request.formData();\n const result: Record<string, any> = {};\n formData.forEach((value, key) => {\n result[key] = value;\n });\n return result;\n }\n\n if (contentType.includes('text/plain')) {\n return await request.text();\n }\n\n if (contentType.includes('application/octet-stream')) {\n return await request.arrayBuffer();\n }\n\n if (contentType.includes('application/pdf') || contentType.includes('image/') || contentType.includes('video/')) {\n const blob = await request.blob();\n return blob;\n }\n\n if (contentType.includes('application/stream') || request.body instanceof ReadableStream) {\n return request.body;\n }\n\n return await request.text();\n}\n\n\nexport function shouldSerialize(body: any) {\n return typeof body === \"object\" && body !== null && !(body instanceof Blob) && !(body instanceof FormData)\n}\n\nexport const statusCode = {\n \"OK\": 200,\n \"CREATED\": 201,\n \"ACCEPTED\": 202,\n \"NO_CONTENT\": 204,\n \"MULTIPLE_CHOICES\": 300,\n \"MOVED_PERMANENTLY\": 301,\n \"FOUND\": 302,\n \"SEE_OTHER\": 303,\n \"NOT_MODIFIED\": 304,\n \"TEMPORARY_REDIRECT\": 307,\n \"BAD_REQUEST\": 400,\n \"UNAUTHORIZED\": 401,\n \"PAYMENT_REQUIRED\": 402,\n \"FORBIDDEN\": 403,\n \"NOT_FOUND\": 404,\n \"METHOD_NOT_ALLOWED\": 405,\n \"NOT_ACCEPTABLE\": 406,\n \"PROXY_AUTHENTICATION_REQUIRED\": 407,\n \"REQUEST_TIMEOUT\": 408,\n \"CONFLICT\": 409,\n \"GONE\": 410,\n \"LENGTH_REQUIRED\": 411,\n \"PRECONDITION_FAILED\": 412,\n \"PAYLOAD_TOO_LARGE\": 413,\n \"URI_TOO_LONG\": 414,\n \"UNSUPPORTED_MEDIA_TYPE\": 415,\n \"RANGE_NOT_SATISFIABLE\": 416,\n \"EXPECTATION_FAILED\": 417,\n \"I'M_A_TEAPOT\": 418,\n \"MISDIRECTED_REQUEST\": 421,\n \"UNPROCESSABLE_ENTITY\": 422,\n \"LOCKED\": 423,\n \"FAILED_DEPENDENCY\": 424,\n \"TOO_EARLY\": 425,\n \"UPGRADE_REQUIRED\": 426,\n \"PRECONDITION_REQUIRED\": 428,\n \"TOO_MANY_REQUESTS\": 429,\n \"REQUEST_HEADER_FIELDS_TOO_LARGE\": 431,\n \"UNAVAILABLE_FOR_LEGAL_REASONS\": 451,\n \"INTERNAL_SERVER_ERROR\": 500,\n \"NOT_IMPLEMENTED\": 501,\n \"BAD_GATEWAY\": 502,\n \"SERVICE_UNAVAILABLE\": 503,\n \"GATEWAY_TIMEOUT\": 504,\n \"HTTP_VERSION_NOT_SUPPORTED\": 505,\n \"VARIANT_ALSO_NEGOTIATES\": 506,\n \"INSUFFICIENT_STORAGE\": 507,\n \"LOOP_DETECTED\": 508,\n \"NOT_EXTENDED\": 510,\n \"NETWORK_AUTHENTICATION_REQUIRED\": 511,\n}\n","import { z, type ZodOptional, type ZodSchema } from \"zod\";\nimport type { Middleware } from \"./middleware\";\nimport type { UnionToIntersection } from \"./helper\";\nimport type { CookiePrefixOptions } from \"./cookie\";\n\nexport interface EndpointOptions {\n\tmethod: Method | Method[];\n\tbody?: ZodSchema;\n\tquery?: ZodSchema;\n\tparams?: ZodSchema<any>;\n\t/**\n\t * If true headers will be required to be passed in the context\n\t */\n\trequireHeaders?: boolean;\n\t/**\n\t * If true request object will be required\n\t */\n\trequireRequest?: boolean;\n\t/**\n\t * List of endpoints that will be called before this endpoint\n\t */\n\tuse?: Endpoint[];\n}\n\nexport type Endpoint<\n\tHandler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>,\n\tOption extends EndpointOptions = EndpointOptions,\n> = {\n\tpath: string;\n\toptions: Option;\n\theaders?: Headers;\n} & Handler;\n\nexport type InferParamPath<Path> = Path extends `${infer _Start}:${infer Param}/${infer Rest}`\n\t? { [K in Param | keyof InferParamPath<Rest>]: string }\n\t: Path extends `${infer _Start}:${infer Param}`\n\t\t? { [K in Param]: string }\n\t\t: Path extends `${infer _Start}/${infer Rest}`\n\t\t\t? InferParamPath<Rest>\n\t\t\t: undefined;\n\nexport type InferParamWildCard<Path> = Path extends\n\t| `${infer _Start}/*:${infer Param}/${infer Rest}`\n\t| `${infer _Start}/**:${infer Param}/${infer Rest}`\n\t? { [K in Param | keyof InferParamPath<Rest>]: string }\n\t: Path extends `${infer _Start}/*`\n\t\t? { [K in \"_\"]: string }\n\t\t: Path extends `${infer _Start}/${infer Rest}`\n\t\t\t? InferParamPath<Rest>\n\t\t\t: undefined;\n\nexport type Prettify<T> = {\n\t[key in keyof T]: T[key];\n} & {};\n\nexport interface CookieOptions {\n\t/**\n\t * Max age in seconds\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Domain\n\t */\n\tdomain?: string;\n\t/**\n\t * Path\n\t */\n\tpath?: string;\n\t/**\n\t * Secure\n\t */\n\tsecure?: boolean;\n\t/**\n\t * HttpOnly\n\t */\n\thttpOnly?: boolean;\n\n\t/**\n\t * SameSite\n\t */\n\tsameSite?: \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Expires\n\t */\n\texpires?: Date;\n}\n\nexport type ContextTools = {\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * cookie setter.\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetCookie: (key: string, value: string, options?: CookieOptions) => void;\n\t/**\n\t * Get cookie value\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tgetCookie: (key: string, value: string, options?: CookieOptions) => string | undefined;\n\t/**\n\t * Set signed cookie\n\t */\n\tsetSignedCookie: (\n\t\tkey: string,\n\t\tvalue: string,\n\t\tsecret: string | BufferSource,\n\t\toptions?: CookieOptions,\n\t) => Promise<void>;\n\t/**\n\t * Get signed cookie value\n\t */\n\n\tgetSignedCookie: (\n\t\tkey: string,\n\t\tsecret: string,\n\t\tprefix?: CookiePrefixOptions,\n\t) => Promise<string | undefined>;\n};\n\nexport type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> &\n\tInferParam<Path> &\n\tInferMethod<Opts[\"method\"]> &\n\tInferHeaders<Opts> &\n\tInferRequest<Opts> &\n\tInferQuery<Opts[\"query\"]>;\n\nexport type InferUse<Opts extends EndpointOptions> = Opts[\"use\"] extends Endpoint[]\n\t? {\n\t\t\tcontext: UnionToIntersection<Awaited<ReturnType<Opts[\"use\"][number]>>>;\n\t\t}\n\t: {};\n\nexport type InferUseOptions<Opts extends EndpointOptions> = Opts[\"use\"] extends Array<infer U>\n\t? UnionToIntersection<\n\t\t\tU extends Endpoint\n\t\t\t\t? U[\"options\"]\n\t\t\t\t: {\n\t\t\t\t\t\tbody?: {};\n\t\t\t\t\t\trequireRequest?: boolean;\n\t\t\t\t\t\trequireHeaders?: boolean;\n\t\t\t\t\t}\n\t\t>\n\t: {\n\t\t\tbody?: {};\n\t\t\trequireRequest?: boolean;\n\t\t\trequireHeaders?: boolean;\n\t\t};\n\nexport type InferMethod<M extends Method | Method[]> = M extends Array<Method>\n\t? {\n\t\t\tmethod: M[number];\n\t\t}\n\t: {\n\t\t\tmethod?: M;\n\t\t};\n\nexport type InferHeaders<\n\tOpt extends EndpointOptions,\n\tHeaderReq = Opt[\"requireHeaders\"],\n> = HeaderReq extends true\n\t? {\n\t\t\theaders: Headers;\n\t\t}\n\t: InferUseOptions<Opt>[\"requireHeaders\"] extends true\n\t\t? {\n\t\t\t\theaders: Headers;\n\t\t\t}\n\t\t: {\n\t\t\t\theaders?: Headers;\n\t\t\t};\n\nexport type InferRequest<\n\tOpt extends EndpointOptions,\n\tRequestReq = Opt[\"requireRequest\"],\n> = RequestReq extends true\n\t? {\n\t\t\trequest: Request;\n\t\t}\n\t: InferUseOptions<Opt>[\"requireRequest\"] extends true\n\t\t? {\n\t\t\t\trequest: Request;\n\t\t\t}\n\t\t: {\n\t\t\t\trequest?: Request;\n\t\t\t};\n\nexport type InferQuery<Query> = Query extends ZodSchema\n\t? Query extends ZodOptional<any>\n\t\t? {\n\t\t\t\tquery?: z.infer<Query>;\n\t\t\t}\n\t\t: {\n\t\t\t\tquery: z.infer<Query>;\n\t\t\t}\n\t: {\n\t\t\tquery?: undefined;\n\t\t};\n\nexport type InferParam<\n\tPath extends string,\n\tParamPath extends InferParamPath<Path> = InferParamPath<Path>,\n\tWildCard extends InferParamWildCard<Path> = InferParamWildCard<Path>,\n> = ParamPath extends undefined\n\t? WildCard extends undefined\n\t\t? {\n\t\t\t\tparams?: Record<string, string>;\n\t\t\t}\n\t\t: {\n\t\t\t\tparams: WildCard;\n\t\t\t}\n\t: {\n\t\t\tparams: Prettify<ParamPath & (WildCard extends undefined ? {} : WildCard)>;\n\t\t};\n\nexport type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined;\n\nexport type Handler<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n\tExtra extends Record<string, any> = {},\n> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts> & ContextTools> & Extra) => Promise<R>;\n\nexport type Method = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"*\";\n\nexport type InferBody<\n\tOpts extends EndpointOptions,\n\tBody extends ZodSchema | undefined = Opts[\"body\"] &\n\t\t(undefined extends InferUseOptions<Opts>[\"body\"] ? {} : InferUseOptions<Opts>[\"body\"]),\n> = Body extends ZodSchema\n\t? Body extends ZodOptional<any>\n\t\t? {\n\t\t\t\tbody?: Prettify<z.infer<Body>>;\n\t\t\t}\n\t\t: {\n\t\t\t\tbody: Prettify<z.infer<Body>>;\n\t\t\t}\n\t: {\n\t\t\tbody?: undefined;\n\t\t};\n"],"mappings":"ijBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,cAAAE,EAAA,mBAAAC,EAAA,0BAAAC,EAAA,qBAAAC,EAAA,4BAAAC,EAAA,iBAAAC,GAAA,YAAAC,EAAA,oBAAAC,EAAA,eAAAC,IAAA,eAAAC,EAAAX,ICAA,IAAAY,EAA8D,eCA9D,IAAAC,GAAkB,eAiBX,SAASC,EAAiBC,EAAuBC,EAAe,CACnE,GAAI,OAAOD,GAAqB,WAC5B,OAAOE,EAAe,IAAK,CACvB,OAAQ,GACZ,EAAGF,CAAgB,EAEvB,GAAI,CAACC,EACD,MAAM,IAAI,MAAM,gCAAgC,EAMpD,OAJiBC,EAAe,IAAK,CACjC,GAAGF,EACH,OAAQ,GACZ,EAAGC,CAAO,CAEd,CAEO,IAAME,EAA0B,IAAqD,CASxF,SAASC,EAAGJ,EAAuBC,EAAe,CAC9C,GAAI,OAAOD,GAAqB,WAC5B,OAAOE,EAAe,IAAK,CACvB,OAAQ,GACZ,EAAGF,CAAgB,EAEvB,GAAI,CAACC,EACD,MAAM,IAAI,MAAM,gCAAgC,EAMpD,OAJiBC,EAAe,IAAK,CACjC,GAAGF,EACH,OAAQ,GACZ,EAAGC,CAAO,CAEd,CACA,OAAOG,CACX,ECtDO,IAAMC,EAAN,cAAuB,KAAM,CAGhC,YACIC,EACAC,EACF,CACE,MACI,cAAcD,CAAM,IAAIC,GAAM,SA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AAC,EACGkB,IACHD,EAAoB,CACnB,GAAGC,EACH,GAAGD,CACJ,EAEF,CACA,IAAME,EAAa,MAAMR,EAAQ,CAChC,KAAMD,EACN,OAAQL,EACR,QAAAS,EACA,OAAQP,GAAO,OACf,QAASC,EACT,KAAMI,EACN,MAAAG,EACA,GAAGE,EACH,GAAGjB,GAAQ,YACZ,CAAC,EACD,GAAImB,aAAsB,SACzB,OAAOA,EAER,IAAMC,EAAUC,EAAgBF,CAAU,EAAI,KAAK,UAAUA,CAAU,EAAIA,EAC3E,OAAO,IAAI,SAASC,EAAgB,CACnC,QAAST,EAAQ,OAClB,CAAC,CACF,OAASW,EAAG,CACX,GAAItB,GAAQ,QAAS,CACpB,IAAMuB,EAAa,MAAMvB,EAAO,QAAQsB,CAAC,EACzC,GAAIC,aAAsB,SACzB,OAAOA,CAET,CACA,GAAID,aAAaE,EAChB,OAAO,IAAI,SAASF,EAAE,KAAO,KAAK,UAAUA,EAAE,IAAI,EAAI,KAAM,CAC3D,OAAQG,EAAWH,EAAE,MAAM,EAC3B,WAAYA,EAAE,OACd,QAASX,EAAQ,OAClB,CAAC,EAEF,GAAIX,GAAQ,WACX,MAAMsB,EAEP,OAAO,IAAI,SAAS,KAAM,CACzB,OAAQ,IACR,WAAY,uBACb,CAAC,CACF,CACD,EAGC,UAAAvB,CACD,CACD,EEvIA,IAAA2B,GAAoD","names":["src_exports","__export","APIError","createEndpoint","createEndpointCreator","createMiddleware","createMiddlewareCreator","createRouter","getBody","shouldSerialize","statusCode","__toCommonJS","import_zod","import_zod","createMiddleware","optionsOrHandler","handler","createEndpoint","createMiddlewareCreator","fn","APIError","status","body","__publicField","algorithm","getCryptoKey","secret","secretBuf","makeSignature","value","key","signature","verifySignature","base64Signature","signatureBinStr","len","validCookieNameRegEx","validCookieValueRegEx","parse","cookie","name","parsedCookie","pairStr","valueStartPos","cookieName","cookieValue","parseSigned","secretKey","signatureStartPos","signedValue","isVerified","_serialize","opt","serialize","serializeSigned","getCookie","cookie","key","prefix","finalKey","parse","setCookie","header","name","value","opt","serialize","setSignedCookie","secret","serializeSigned","getSignedCookie","parseSigned","createEndpointCreator","path","options","handler","createEndpoint","responseHeader","handle","ctx","internalCtx","key","value","setCookie","prefix","header","getCookie","secret","getSignedCookie","setSignedCookie","middleware","res","body","e","APIError","import_rou3","getBody","request","contentType","formData","result","value","key","shouldSerialize","body","statusCode","createRouter","endpoints","config","_endpoints","router","createRou3Router","endpoint","method","middlewareRouter","route","request","url","path","handler","body","getBody","headers","query","middleware","middlewareContext","res","handlerRes","resBody","shouldSerialize","e","onErrorRes","APIError","statusCode","import_zod"]}
|