better-call 0.2.14-beta.2 → 0.2.14

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/dist/client.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { R as Router, U as UnionToIntersection, E as Endpoint, H as HasRequiredKeys } from './router-Bn7zn81P.cjs';
1
+ import { R as Router, U as UnionToIntersection, E as Endpoint, H as HasRequiredKeys } from './router-tRhygVBO.cjs';
2
2
  import { BetterFetchOption, BetterFetchResponse } from '@better-fetch/fetch';
3
3
  import 'zod';
4
4
 
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { R as Router, U as UnionToIntersection, E as Endpoint, H as HasRequiredKeys } from './router-Bn7zn81P.js';
1
+ import { R as Router, U as UnionToIntersection, E as Endpoint, H as HasRequiredKeys } from './router-tRhygVBO.js';
2
2
  import { BetterFetchOption, BetterFetchResponse } from '@better-fetch/fetch';
3
3
  import 'zod';
4
4
 
package/dist/index.cjs CHANGED
@@ -50,6 +50,7 @@ __export(src_exports, {
50
50
  setResponse: () => setResponse,
51
51
  setSignedCookie: () => setSignedCookie,
52
52
  shouldSerialize: () => shouldSerialize,
53
+ signCookieValue: () => signCookieValue,
53
54
  statusCode: () => statusCode,
54
55
  toNodeHandler: () => toNodeHandler
55
56
  });
@@ -223,6 +224,12 @@ var serializeSigned = async (name, value, secret, opt = {}) => {
223
224
  value = encodeURIComponent(value);
224
225
  return _serialize(name, value, opt);
225
226
  };
227
+ var signCookieValue = async (value, secret) => {
228
+ const signature = await makeSignature(value, secret);
229
+ value = `${value}.${signature}`;
230
+ value = encodeURIComponent(value);
231
+ return value;
232
+ };
226
233
 
227
234
  // src/cookie-utils.ts
228
235
  var getCookie = (cookie, key, prefix) => {
@@ -397,7 +404,10 @@ function createEndpoint(path, options, handler) {
397
404
  ...internalCtx.body
398
405
  } : internalCtx.body
399
406
  };
400
- internalCtx.query = options.query ? options.query.parse(internalCtx.query) : internalCtx.query;
407
+ console.log(internalCtx.query);
408
+ internalCtx.query = options.query ? options.query.parse(
409
+ internalCtx
410
+ ) : internalCtx.query;
401
411
  } catch (e) {
402
412
  if (e instanceof import_zod.ZodError) {
403
413
  throw new APIError("BAD_REQUEST", {
@@ -915,6 +925,7 @@ function toNodeHandler(handler) {
915
925
  setResponse,
916
926
  setSignedCookie,
917
927
  shouldSerialize,
928
+ signCookieValue,
918
929
  statusCode,
919
930
  toNodeHandler
920
931
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/endpoint.ts","../src/error.ts","../src/helper.ts","../src/cookie.ts","../src/cookie-utils.ts","../src/router.ts","../src/utils.ts","../src/middleware.ts","../src/types.ts","../src/adapter/node.ts","../src/adapter/request.ts"],"sourcesContent":["export * from \"./endpoint\";\nexport * from \"./router\";\nexport * from \"./middleware\";\nexport * from \"./error\";\nexport * from \"./utils\";\nexport * from \"./types\";\nexport * from \"./adapter\";\nexport * from \"./cookie\";\nexport * from \"./cookie-utils\";\nexport * from \"./router\";\n","\"use server\";\nimport { ZodError } from \"zod\";\nimport { APIError } from \"./error\";\nimport { json, type HasRequiredKeys } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n\tInferUse,\n\tPrettify,\n} from \"./types\";\nimport { getCookie, getSignedCookie, setCookie, setSignedCookie } from \"./cookie-utils\";\nimport type { CookiePrefixOptions, CookieOptions } 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<\n\tE extends {\n\t\tuse?: Endpoint[];\n\t},\n>(opts?: E) {\n\treturn <Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\tpath: Path,\n\t\toptions: Opts,\n\t\thandler: (\n\t\t\tctx: Prettify<\n\t\t\t\tContext<Path, Opts> &\n\t\t\t\t\tInferUse<Opts[\"use\"]> &\n\t\t\t\t\tInferUse<E[\"use\"]> &\n\t\t\t\t\tOmit<ContextTools, \"_flag\">\n\t\t\t>,\n\t\t) => Promise<R>,\n\t) => {\n\t\treturn createEndpoint(\n\t\t\tpath,\n\t\t\t{\n\t\t\t\t...options,\n\t\t\t\tuse: [...(options?.use || []), ...(opts?.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\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\tlet responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\n\tconst handle = async <C extends HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]>(\n\t\t...ctx: C\n\t) => {\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 cookieH = header?.get(\"cookie\");\n\t\t\t\tconst cookie = getCookie(cookieH || \"\", 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\tredirect(url: string) {\n\t\t\t\tresponseHeader.set(\"Location\", url);\n\t\t\t\treturn new APIError(\"FOUND\");\n\t\t\t},\n\t\t\tjson,\n\t\t\tcontext: (ctx[0] as any)?.context || {},\n\t\t\t_flag: (ctx[0] as any)?.asResponse ? \"router\" : (ctx[0] as any)?._flag,\n\t\t\tresponseHeader,\n\t\t\tpath: path,\n\t\t\t...(ctx[0] || {}),\n\t\t};\n\t\tif (options.use?.length) {\n\t\t\tlet middlewareContexts = {};\n\t\t\tlet middlewareBody = {};\n\t\t\tfor (const middleware of options.use) {\n\t\t\t\tif (typeof middleware !== \"function\") {\n\t\t\t\t\tconsole.warn(\"Middleware is not a function\", {\n\t\t\t\t\t\tmiddleware,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst res = (await middleware(internalCtx)) as Endpoint;\n\t\t\t\tif (res) {\n\t\t\t\t\tconst body = res.options?.body\n\t\t\t\t\t\t? res.options.body.parse(internalCtx.body)\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tmiddlewareContexts = {\n\t\t\t\t\t\t...middlewareContexts,\n\t\t\t\t\t\t...res,\n\t\t\t\t\t};\n\t\t\t\t\tmiddlewareBody = {\n\t\t\t\t\t\t...middlewareBody,\n\t\t\t\t\t\t...body,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tinternalCtx = {\n\t\t\t\t...internalCtx,\n\t\t\t\tbody: {\n\t\t\t\t\t...middlewareBody,\n\t\t\t\t\t...internalCtx.body,\n\t\t\t\t},\n\t\t\t\tcontext: {\n\t\t\t\t\t...(internalCtx.context || {}),\n\t\t\t\t\t...middlewareContexts,\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} 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\ttry {\n\t\t\tlet res = (await handler(internalCtx as any)) as any;\n\t\t\tlet actualResponse: any = res;\n\n\t\t\tif (res && typeof res === \"object\" && \"_flag\" in res) {\n\t\t\t\tif (res._flag === \"json\" && internalCtx._flag === \"router\") {\n\t\t\t\t\tconst h = res.response.headers as Record<string, string>;\n\t\t\t\t\tObject.keys(h || {}).forEach((key) => {\n\t\t\t\t\t\tresponseHeader.set(key, h[key as keyof typeof h]);\n\t\t\t\t\t});\n\t\t\t\t\tresponseHeader.set(\"Content-Type\", \"application/json\");\n\t\t\t\t\tactualResponse = new Response(JSON.stringify(res.response.body), {\n\t\t\t\t\t\tstatus: res.response.status ?? 200,\n\t\t\t\t\t\tstatusText: res.response.statusText,\n\t\t\t\t\t\theaders: responseHeader,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tactualResponse = res.body;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponseHeader = new Headers();\n\n\t\t\ttype ReturnT = Awaited<ReturnType<Handler<Path, Opts, R>>>;\n\t\t\treturn actualResponse as C extends [{ asResponse: true }]\n\t\t\t\t? Response\n\t\t\t\t: R extends {\n\t\t\t\t\t\t\t_flag: \"json\";\n\t\t\t\t\t\t}\n\t\t\t\t\t? R extends { body: infer B }\n\t\t\t\t\t\t? B\n\t\t\t\t\t\t: null\n\t\t\t\t\t: ReturnT;\n\t\t} catch (e) {\n\t\t\tif (e instanceof APIError) {\n\t\t\t\tresponseHeader.set(\"Content-Type\", \"application/json\");\n\t\t\t\te.headers = responseHeader;\n\t\t\t\tresponseHeader = new Headers();\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\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 type { statusCode } from \"./utils\";\n\ntype Status = keyof typeof statusCode;\n\nexport class APIError extends Error {\n\tstatus: Status;\n\theaders: Headers;\n\tbody: Record<string, any>;\n\n\tconstructor(status: Status, body?: Record<string, any>, headers?: Headers) {\n\t\tsuper(`API Error: ${status} ${body?.message ?? \"\"}`, {\n\t\t\tcause: body,\n\t\t});\n\n\t\tthis.status = status;\n\t\tthis.body = body ?? {};\n\t\tthis.stack = \"\";\n\n\t\tthis.headers = headers ?? new Headers();\n\t\tif (!this.headers.has(\"Content-Type\")) {\n\t\t\tthis.headers.set(\"Content-Type\", \"application/json\");\n\t\t}\n\t\tthis.name = \"BetterCallAPIError\";\n\t}\n}\n","export type UnionToIntersection<Union> = (\n\tUnion extends unknown\n\t\t? (distributedUnion: Union) => void\n\t\t: never\n) extends (mergedIntersection: infer Intersection) => void\n\t? Intersection & Union\n\t: never;\n\nexport type RequiredKeysOf<BaseType extends object> = Exclude<\n\t{\n\t\t[Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]> ? Key : never;\n\t}[keyof BaseType],\n\tundefined\n>;\n\nexport type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never\n\t? false\n\t: true;\n\n/**\n * this function will return a json response and\n * infers the type of the body\n */\nexport const json = <T>(\n\tbody: T,\n\toption?: {\n\t\tstatus?: number;\n\t\tstatusText?: string;\n\t\theaders?: Record<string, string>;\n\t\t/**\n\t\t * this body will take precedence over the body in the options if both are provided.\n\t\t * This is useful if you want to return body without inferring the type.\n\t\t */\n\t\tbody?: any;\n\t},\n) => {\n\treturn {\n\t\tresponse: {\n\t\t\tbody: option?.body ?? body,\n\t\t\tstatus: option?.status ?? 200,\n\t\t\tstatusText: option?.statusText ?? \"OK\",\n\t\t\theaders: option?.headers,\n\t\t},\n\t\tbody,\n\t\t_flag: \"json\" as const,\n\t};\n};\n","//https://github.com/honojs/hono/blob/main/src/utils/cookie.ts\nimport { subtle } from \"uncrypto\";\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) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await 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 subtle.sign(algorithm.name, key, new TextEncoder().encode(value));\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 subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value));\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\topt.secure = true;\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\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\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) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\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\tconst existingCookies = header.get(\"Set-Cookie\");\n\tif (existingCookies) {\n\t\tconst cookies = existingCookies.split(\", \");\n\t\tconst updatedCookies = cookies.filter((cookie) => !cookie.startsWith(`${name}=`));\n\t\theader.delete(\"Set-Cookie\");\n\t\tupdatedCookies.forEach((cookie) => header.append(\"Set-Cookie\", cookie));\n\t}\n\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) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t}\n\t}\n\tconst obj = await parseSigned(cookie, secret, finalKey);\n\treturn obj[finalKey];\n};\n","import { createRouter as createRou3Router, addRoute, findRoute, findAllRoutes } from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./error\";\nimport type { Endpoint } 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\tonResponse?: (res: Response) => any | Promise<any>;\n\tonRequest?: (req: Request) => any | Promise<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 (endpoint.options.metadata?.SERVER_ONLY) continue;\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\tif (!path?.length) {\n\t\t\tconfig?.onError?.(new APIError(\"NOT_FOUND\"));\n\t\t\tconsole.warn(\n\t\t\t\t`[better-call]: Make sure the URL has the basePath (${config?.basePath}).`,\n\t\t\t);\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\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 routerMiddleware = findAllRoutes(middlewareRouter, \"*\", path);\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 (routerMiddleware?.length) {\n\t\t\t\tfor (const route of routerMiddleware) {\n\t\t\t\t\tconst middleware = route.data as Endpoint;\n\t\t\t\t\tconst res = await middleware({\n\t\t\t\t\t\tpath: path,\n\t\t\t\t\t\tmethod: method as \"GET\",\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tparams: route?.params as any,\n\t\t\t\t\t\trequest: request,\n\t\t\t\t\t\tbody: body,\n\t\t\t\t\t\tquery,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t...config?.extraContext,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tif (res instanceof Response) {\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tif (res?._flag === \"json\") {\n\t\t\t\t\t\treturn new Response(JSON.stringify(res), {\n\t\t\t\t\t\t\theaders: res.headers,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (res) {\n\t\t\t\t\t\tmiddlewareContext = {\n\t\t\t\t\t\t\t...res,\n\t\t\t\t\t\t\t...middlewareContext,\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\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_flag: \"router\",\n\t\t\t\tcontext: {\n\t\t\t\t\t...middlewareContext,\n\t\t\t\t\t...config?.extraContext,\n\t\t\t\t},\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: e.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: async (request: Request) => {\n\t\t\tconst onReq = await config?.onRequest?.(request);\n\t\t\tif (onReq instanceof Response) {\n\t\t\t\treturn onReq;\n\t\t\t}\n\t\t\tconst req = onReq instanceof Request ? onReq : request;\n\t\t\tconst res = await handler(req);\n\t\t\tconst onRes = await config?.onResponse?.(res);\n\t\t\tif (onRes instanceof Response) {\n\t\t\t\treturn onRes;\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\tendpoints,\n\t};\n};\n\nexport type Router = ReturnType<typeof createRouter>;\n","export async function getBody(request: Request) {\n\tconst contentType = request.headers.get(\"content-type\") || \"\";\n\n\tif (!request.body) {\n\t\treturn undefined;\n\t}\n\n\tif (contentType.includes(\"application/json\")) {\n\t\treturn await request.json();\n\t}\n\n\tif (contentType.includes(\"application/x-www-form-urlencoded\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, string> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value.toString();\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"multipart/form-data\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, any> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value;\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"text/plain\")) {\n\t\treturn await request.text();\n\t}\n\n\tif (contentType.includes(\"application/octet-stream\")) {\n\t\treturn await request.arrayBuffer();\n\t}\n\n\tif (\n\t\tcontentType.includes(\"application/pdf\") ||\n\t\tcontentType.includes(\"image/\") ||\n\t\tcontentType.includes(\"video/\")\n\t) {\n\t\tconst blob = await request.blob();\n\t\treturn blob;\n\t}\n\n\tif (contentType.includes(\"application/stream\") || request.body instanceof ReadableStream) {\n\t\treturn request.body;\n\t}\n\n\treturn await request.text();\n}\n\nexport function shouldSerialize(body: any) {\n\treturn (\n\t\ttypeof body === \"object\" &&\n\t\tbody !== null &&\n\t\t!(body instanceof Blob) &&\n\t\t!(body instanceof FormData)\n\t);\n}\n\nexport const statusCode = {\n\tOK: 200,\n\tCREATED: 201,\n\tACCEPTED: 202,\n\tNO_CONTENT: 204,\n\tMULTIPLE_CHOICES: 300,\n\tMOVED_PERMANENTLY: 301,\n\tFOUND: 302,\n\tSEE_OTHER: 303,\n\tNOT_MODIFIED: 304,\n\tTEMPORARY_REDIRECT: 307,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_ALLOWED: 405,\n\tNOT_ACCEPTABLE: 406,\n\tPROXY_AUTHENTICATION_REQUIRED: 407,\n\tREQUEST_TIMEOUT: 408,\n\tCONFLICT: 409,\n\tGONE: 410,\n\tLENGTH_REQUIRED: 411,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tURI_TOO_LONG: 414,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tEXPECTATION_FAILED: 417,\n\t\"I'M_A_TEAPOT\": 418,\n\tMISDIRECTED_REQUEST: 421,\n\tUNPROCESSABLE_ENTITY: 422,\n\tLOCKED: 423,\n\tFAILED_DEPENDENCY: 424,\n\tTOO_EARLY: 425,\n\tUPGRADE_REQUIRED: 426,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tREQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n\tUNAVAILABLE_FOR_LEGAL_REASONS: 451,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504,\n\tHTTP_VERSION_NOT_SUPPORTED: 505,\n\tVARIANT_ALSO_NEGOTIATES: 506,\n\tINSUFFICIENT_STORAGE: 507,\n\tLOOP_DETECTED: 508,\n\tNOT_EXTENDED: 510,\n\tNETWORK_AUTHENTICATION_REQUIRED: 511,\n};\n","import type {\n\tContextTools,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n\tInferBody,\n\tInferHeaders,\n\tInferRequest,\n\tInferUse,\n\tPrettify,\n} from \"./types\";\nimport { createEndpoint } from \"./endpoint\";\n\nexport type MiddlewareHandler<\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n\tExtra extends Record<string, any> = {},\n> = (\n\tctx: Prettify<\n\t\tInferBody<Opts> &\n\t\t\tInferRequest<Opts> &\n\t\t\tInferHeaders<Opts> & {\n\t\t\t\tparams?: Record<string, string>;\n\t\t\t\tquery?: Record<string, string>;\n\t\t\t} & ContextTools\n\t> &\n\t\tExtra,\n) => Promise<R>;\n\nexport function createMiddleware<Opts extends EndpointOptions, R extends EndpointResponse>(\n\toptionsOrHandler: MiddlewareHandler<Opts, R>,\n): Endpoint<Handler<string, Opts, R>, Opts>;\nexport function createMiddleware<\n\tOpts extends Omit<EndpointOptions, \"method\">,\n\tR extends EndpointResponse,\n>(\n\toptionsOrHandler: Opts,\n\thandler: MiddlewareHandler<\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t},\n\t\tR\n\t>,\n): Endpoint<\n\tHandler<\n\t\tstring,\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t},\n\t\tR\n\t>,\n\tOpts & {\n\t\tmethod: \"*\";\n\t}\n>;\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n\tif (typeof optionsOrHandler === \"function\") {\n\t\treturn createEndpoint(\n\t\t\t\"*\",\n\t\t\t{\n\t\t\t\tmethod: \"*\",\n\t\t\t},\n\t\t\toptionsOrHandler,\n\t\t);\n\t}\n\tif (!handler) {\n\t\tthrow new Error(\"Middleware handler is required\");\n\t}\n\tconst endpoint = createEndpoint(\n\t\t\"*\",\n\t\t{\n\t\t\t...optionsOrHandler,\n\t\t\tmethod: \"*\",\n\t\t},\n\t\thandler,\n\t);\n\treturn endpoint as any;\n}\n\nexport const createMiddlewareCreator = <\n\tE extends {\n\t\tuse?: Endpoint[];\n\t},\n>(\n\topts?: E,\n) => {\n\ttype H<Opts extends EndpointOptions, R extends EndpointResponse> = (\n\t\tctx: Prettify<\n\t\t\tInferBody<Opts> &\n\t\t\t\tInferUse<E[\"use\"]> &\n\t\t\t\tInferRequest<Opts> &\n\t\t\t\tInferHeaders<Opts> & {\n\t\t\t\t\tparams?: Record<string, string>;\n\t\t\t\t\tquery?: Record<string, string>;\n\t\t\t\t} & ContextTools\n\t\t>,\n\t) => Promise<R>;\n\tfunction fn<Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\toptionsOrHandler: H<Opts, R>,\n\t): Endpoint<Handler<string, Opts, R>, Opts>;\n\tfunction fn<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(\n\t\toptionsOrHandler: Opts,\n\t\thandler: H<\n\t\t\tOpts & {\n\t\t\t\tmethod: \"*\";\n\t\t\t},\n\t\t\tR\n\t\t>,\n\t): Endpoint<\n\t\tHandler<\n\t\t\tstring,\n\t\t\tOpts & {\n\t\t\t\tmethod: \"*\";\n\t\t\t},\n\t\t\tR\n\t\t>,\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t}\n\t>;\n\tfunction fn(optionsOrHandler: any, handler?: any) {\n\t\tif (typeof optionsOrHandler === \"function\") {\n\t\t\treturn createEndpoint(\n\t\t\t\t\"*\",\n\t\t\t\t{\n\t\t\t\t\tmethod: \"*\",\n\t\t\t\t},\n\t\t\t\toptionsOrHandler,\n\t\t\t);\n\t\t}\n\t\tif (!handler) {\n\t\t\tthrow new Error(\"Middleware handler is required\");\n\t\t}\n\t\tconst endpoint = createEndpoint(\n\t\t\t\"*\",\n\t\t\t{\n\t\t\t\t...optionsOrHandler,\n\t\t\t\tmethod: \"*\",\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t\treturn endpoint as any;\n\t}\n\treturn fn;\n};\n\nexport type Middleware<\n\tOpts extends EndpointOptions = EndpointOptions,\n\tR extends EndpointResponse = EndpointResponse,\n> = (\n\topts: Opts,\n\thandler: (ctx: {\n\t\tbody?: InferBody<Opts>;\n\t\tparams?: Record<string, string>;\n\t\tquery?: Record<string, string>;\n\t}) => Promise<R>,\n) => Endpoint;\n","import { z, type ZodOptional, type ZodSchema } from \"zod\";\nimport type { json, UnionToIntersection } from \"./helper\";\nimport type { CookieOptions, CookiePrefixOptions } from \"./cookie\";\nimport type { APIError } from \"./error\";\n\nexport interface EndpointOptions {\n\t/**\n\t * Request Method\n\t */\n\tmethod: Method | Method[];\n\t/**\n\t * Body Schema\n\t */\n\tbody?: ZodSchema;\n\t/**\n\t * Query Schema\n\t */\n\tquery?: ZodSchema;\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\t/**\n\t * Endpoint metadata\n\t */\n\tmetadata?:\n\t\t| Record<string, any>\n\t\t| {\n\t\t\t\t/**\n\t\t\t\t * If true this endpoint will only be available on the server\n\t\t\t\t */\n\t\t\t\tSERVER_ONLY?: boolean;\n\t\t };\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 type ContextTools = {\n\t/**\n\t * the current path\n\t */\n\tpath: string;\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, prefix?: CookiePrefixOptions) => 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\t/**\n\t * Redirect to url\n\t */\n\tredirect: (url: string) => APIError;\n\t/**\n\t * json response helper\n\t */\n\tjson: typeof json;\n\t/**\n\t * response header\n\t */\n\tresponseHeader: Headers;\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\t\t/**\n\t\t * This is used internally.\n\t\t * But you can use it to change the response form.\n\t\t *\n\t\t * - `json` will be set only when using `ctx.json` helper.\n\t\t * - `router` will be set when the handler is called from the router.\n\t\t * You can use this to change the response form to be a `Response` object.\n\t\t * - `default` will be used normally when the handler is called as a normal function.\n\t\t *\n\t\t * @internal\n\t\t */\n\t\t_flag?: \"json\" | \"router\" | \"default\";\n\t\t/**\n\t\t * Force the response to be a `Response` object.\n\t\t */\n\t\tasResponse?: boolean;\n\t};\n\nexport type InferUse<Opts extends EndpointOptions[\"use\"]> = Opts extends Endpoint[]\n\t? {\n\t\t\tcontext: UnionToIntersection<Awaited<ReturnType<Opts[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 EndpointBody =\n\t| Record<string, any>\n\t| string\n\t| boolean\n\t| number\n\t| void\n\t| undefined\n\t| null\n\t| unknown;\n\nexport type EndpointResponse =\n\t| {\n\t\t\tresponse: {\n\t\t\t\tstatus?: number;\n\t\t\t\tstatusText?: string;\n\t\t\t\theaders?: Headers;\n\t\t\t\tbody: any;\n\t\t\t};\n\t\t\tbody: EndpointBody;\n\t\t\t_flag: \"json\";\n\t }\n\t| EndpointBody;\n\nexport type Handler<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts[\"use\"]> & ContextTools>) => 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","import { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { getRequest, setResponse } from \"./request.js\";\nimport type { Router } from \"../router.js\";\n\nexport function toNodeHandler(handler: Router[\"handler\"]) {\n\treturn async (req: IncomingMessage, res: ServerResponse) => {\n\t\tconst protocol = (req.connection as any)?.encrypted ? \"https\" : \"http\";\n\t\tconst base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n\t\tconst response = await handler(getRequest({ base, request: req }));\n\t\tsetResponse(res, response);\n\t};\n}\n\nexport { getRequest, setResponse };\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport * as set_cookie_parser from \"set-cookie-parser\";\n\nfunction get_raw_body(req: IncomingMessage, body_size_limit?: number) {\n\tconst h = req.headers;\n\n\tif (!h[\"content-type\"]) return null;\n\n\tconst content_length = Number(h[\"content-length\"]);\n\n\t// check if no request body\n\tif (\n\t\t(req.httpVersionMajor === 1 && isNaN(content_length) && h[\"transfer-encoding\"] == null) ||\n\t\tcontent_length === 0\n\t) {\n\t\treturn null;\n\t}\n\n\tlet length = content_length;\n\n\tif (body_size_limit) {\n\t\tif (!length) {\n\t\t\tlength = body_size_limit;\n\t\t} else if (length > body_size_limit) {\n\t\t\tthrow Error(\n\t\t\t\t`Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tif (req.destroyed) {\n\t\tconst readable = new ReadableStream();\n\t\treadable.cancel();\n\t\treturn readable;\n\t}\n\n\tlet size = 0;\n\tlet cancelled = false;\n\n\treturn new ReadableStream({\n\t\tstart(controller) {\n\t\t\treq.on(\"error\", (error) => {\n\t\t\t\tcancelled = true;\n\t\t\t\tcontroller.error(error);\n\t\t\t});\n\n\t\t\treq.on(\"end\", () => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\tcontroller.close();\n\t\t\t});\n\n\t\t\treq.on(\"data\", (chunk) => {\n\t\t\t\tif (cancelled) return;\n\n\t\t\t\tsize += chunk.length;\n\n\t\t\t\tif (size > length) {\n\t\t\t\t\tcancelled = true;\n\n\t\t\t\t\tcontroller.error(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`request body size exceeded ${\n\t\t\t\t\t\t\t\tcontent_length ? \"'content-length'\" : \"BODY_SIZE_LIMIT\"\n\t\t\t\t\t\t\t} of ${length}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tcontroller.enqueue(chunk);\n\n\t\t\t\tif (controller.desiredSize === null || controller.desiredSize <= 0) {\n\t\t\t\t\treq.pause();\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\tpull() {\n\t\t\treq.resume();\n\t\t},\n\n\t\tcancel(reason) {\n\t\t\tcancelled = true;\n\t\t\treq.destroy(reason);\n\t\t},\n\t});\n}\n\nexport function getRequest({\n\trequest,\n\tbase,\n\tbodySizeLimit,\n}: {\n\tbase: string;\n\tbodySizeLimit?: number;\n\trequest: IncomingMessage;\n}) {\n\treturn new Request(base + request.url, {\n\t\t// @ts-expect-error\n\t\tduplex: \"half\",\n\t\tmethod: request.method,\n\t\tbody: get_raw_body(request, bodySizeLimit),\n\t\theaders: request.headers as Record<string, string>,\n\t});\n}\n\nexport async function setResponse(res: ServerResponse, response: Response) {\n\tfor (const [key, value] of response.headers as any) {\n\t\ttry {\n\t\t\tres.setHeader(\n\t\t\t\tkey,\n\t\t\t\tkey === \"set-cookie\"\n\t\t\t\t\t? set_cookie_parser.splitCookiesString(response.headers.get(key) as string)\n\t\t\t\t\t: value,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tres.getHeaderNames().forEach((name) => res.removeHeader(name));\n\t\t\tres.writeHead(500).end(String(error));\n\t\t\treturn;\n\t\t}\n\t}\n\n\tres.writeHead(response.status);\n\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\n\tif (response.body.locked) {\n\t\tres.end(\n\t\t\t\"Fatal error: Response body is locked. \" +\n\t\t\t\t\"This can happen when the response was already read (for example through 'response.json()' or 'response.text()').\",\n\t\t);\n\t\treturn;\n\t}\n\n\tconst reader = response.body.getReader();\n\n\tif (res.destroyed) {\n\t\treader.cancel();\n\t\treturn;\n\t}\n\n\tconst cancel = (error?: Error) => {\n\t\tres.off(\"close\", cancel);\n\t\tres.off(\"error\", cancel);\n\n\t\t// If the reader has already been interrupted with an error earlier,\n\t\t// then it will appear here, it is useless, but it needs to be catch.\n\t\treader.cancel(error).catch(() => {});\n\t\tif (error) res.destroy(error);\n\t};\n\n\tres.on(\"close\", cancel);\n\tres.on(\"error\", cancel);\n\n\tnext();\n\tasync function next() {\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (!res.write(value)) {\n\t\t\t\t\tres.once(\"drain\", next);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tres.end();\n\t\t} catch (error) {\n\t\t\tcancel(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,iBAAyB;;;ACGlB,IAAM,WAAN,cAAu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AAA,IAED;AACA;AAAA,EACD;AAEA,QAAM,SAAS,SAAS,KAAK,UAAU;AAEvC,MAAI,IAAI,WAAW;AAClB,WAAO,OAAO;AACd;AAAA,EACD;AAEA,QAAM,SAAS,CAAC,UAAkB;AACjC,QAAI,IAAI,SAAS,MAAM;AACvB,QAAI,IAAI,SAAS,MAAM;AAIvB,WAAO,OAAO,KAAK,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AACnC,QAAI,MAAO,KAAI,QAAQ,KAAK;AAAA,EAC7B;AAEA,MAAI,GAAG,SAAS,MAAM;AACtB,MAAI,GAAG,SAAS,MAAM;AAEtB,OAAK;AACL,iBAAe,OAAO;AACrB,QAAI;AACH,iBAAS;AACR,cAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,YAAI,KAAM;AAEV,YAAI,CAAC,IAAI,MAAM,KAAK,GAAG;AACtB,cAAI,KAAK,SAAS,IAAI;AACtB;AAAA,QACD;AAAA,MACD;AACA,UAAI,IAAI;AAAA,IACT,SAAS,OAAO;AACf,aAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;AAAA,IACjE;AAAA,EACD;AACD;;;AD1KO,SAAS,cAAc,SAA4B;AACzD,SAAO,OAAO,KAAsB,QAAwB;AAC3D,UAAM,WAAY,IAAI,YAAoB,YAAY,UAAU;AAChE,UAAM,OAAO,GAAG,QAAQ,MAAM,IAAI,QAAQ,YAAY,KAAK,IAAI,QAAQ,IAAI;AAC3E,UAAM,WAAW,MAAM,QAAQ,WAAW,EAAE,MAAM,SAAS,IAAI,CAAC,CAAC;AACjE,gBAAY,KAAK,QAAQ;AAAA,EAC1B;AACD;","names":["cookie","options","createRou3Router","handler","route","import_zod","import_node_http"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/endpoint.ts","../src/error.ts","../src/helper.ts","../src/cookie.ts","../src/cookie-utils.ts","../src/router.ts","../src/utils.ts","../src/middleware.ts","../src/types.ts","../src/adapter/node.ts","../src/adapter/request.ts"],"sourcesContent":["export * from \"./endpoint\";\nexport * from \"./router\";\nexport * from \"./middleware\";\nexport * from \"./error\";\nexport * from \"./utils\";\nexport * from \"./types\";\nexport * from \"./adapter\";\nexport * from \"./cookie\";\nexport * from \"./cookie-utils\";\nexport * from \"./router\";\n","\"use server\";\nimport { ZodError } from \"zod\";\nimport { APIError } from \"./error\";\nimport { json, type HasRequiredKeys } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n\tInferUse,\n\tPrettify,\n} from \"./types\";\nimport { getCookie, getSignedCookie, setCookie, setSignedCookie } from \"./cookie-utils\";\nimport type { CookiePrefixOptions, CookieOptions } 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<\n\tE extends {\n\t\tuse?: Endpoint[];\n\t},\n>(opts?: E) {\n\treturn <Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\tpath: Path,\n\t\toptions: Opts,\n\t\thandler: (\n\t\t\tctx: Prettify<\n\t\t\t\tContext<Path, Opts> &\n\t\t\t\t\tInferUse<Opts[\"use\"]> &\n\t\t\t\t\tInferUse<E[\"use\"]> &\n\t\t\t\t\tOmit<ContextTools, \"_flag\">\n\t\t\t>,\n\t\t) => Promise<R>,\n\t) => {\n\t\treturn createEndpoint(\n\t\t\tpath,\n\t\t\t{\n\t\t\t\t...options,\n\t\t\t\tuse: [...(options?.use || []), ...(opts?.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\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\tlet responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\n\tconst handle = async <C extends HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]>(\n\t\t...ctx: C\n\t) => {\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 cookieH = header?.get(\"cookie\");\n\t\t\t\tconst cookie = getCookie(cookieH || \"\", 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\tredirect(url: string) {\n\t\t\t\tresponseHeader.set(\"Location\", url);\n\t\t\t\treturn new APIError(\"FOUND\");\n\t\t\t},\n\t\t\tjson,\n\t\t\tcontext: (ctx[0] as any)?.context || {},\n\t\t\t_flag: (ctx[0] as any)?.asResponse ? \"router\" : (ctx[0] as any)?._flag,\n\t\t\tresponseHeader,\n\t\t\tpath: path,\n\t\t\t...(ctx[0] || {}),\n\t\t};\n\t\tif (options.use?.length) {\n\t\t\tlet middlewareContexts = {};\n\t\t\tlet middlewareBody = {};\n\t\t\tfor (const middleware of options.use) {\n\t\t\t\tif (typeof middleware !== \"function\") {\n\t\t\t\t\tconsole.warn(\"Middleware is not a function\", {\n\t\t\t\t\t\tmiddleware,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst res = (await middleware(internalCtx)) as Endpoint;\n\t\t\t\tif (res) {\n\t\t\t\t\tconst body = res.options?.body\n\t\t\t\t\t\t? res.options.body.parse(internalCtx.body)\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tmiddlewareContexts = {\n\t\t\t\t\t\t...middlewareContexts,\n\t\t\t\t\t\t...res,\n\t\t\t\t\t};\n\t\t\t\t\tmiddlewareBody = {\n\t\t\t\t\t\t...middlewareBody,\n\t\t\t\t\t\t...body,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tinternalCtx = {\n\t\t\t\t...internalCtx,\n\t\t\t\tbody: {\n\t\t\t\t\t...middlewareBody,\n\t\t\t\t\t...(internalCtx.body as Record<string, any>),\n\t\t\t\t},\n\t\t\t\tcontext: {\n\t\t\t\t\t...(internalCtx.context || {}),\n\t\t\t\t\t...middlewareContexts,\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 as Record<string, any>),\n\t\t\t\t\t\t}\n\t\t\t\t\t: internalCtx.body,\n\t\t\t};\n\t\t\tconsole.log(internalCtx.query);\n\t\t\tinternalCtx.query = options.query\n\t\t\t\t? options.query.parse(\n\t\t\t\t\t\tinternalCtx\n\t\t\t\t)\n\t\t\t\t: internalCtx.query;\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\ttry {\n\t\t\tlet res = (await handler(internalCtx as any)) as any;\n\t\t\tlet actualResponse: any = res;\n\n\t\t\tif (res && typeof res === \"object\" && \"_flag\" in res) {\n\t\t\t\tif (res._flag === \"json\" && internalCtx._flag === \"router\") {\n\t\t\t\t\tconst h = res.response.headers as Record<string, string>;\n\t\t\t\t\tObject.keys(h || {}).forEach((key) => {\n\t\t\t\t\t\tresponseHeader.set(key, h[key as keyof typeof h]);\n\t\t\t\t\t});\n\t\t\t\t\tresponseHeader.set(\"Content-Type\", \"application/json\");\n\t\t\t\t\tactualResponse = new Response(JSON.stringify(res.response.body), {\n\t\t\t\t\t\tstatus: res.response.status ?? 200,\n\t\t\t\t\t\tstatusText: res.response.statusText,\n\t\t\t\t\t\theaders: responseHeader,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tactualResponse = res.body;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponseHeader = new Headers();\n\n\t\t\ttype ReturnT = Awaited<ReturnType<Handler<Path, Opts, R>>>;\n\t\t\treturn actualResponse as C extends [{ asResponse: true }]\n\t\t\t\t? Response\n\t\t\t\t: R extends {\n\t\t\t\t\t\t\t_flag: \"json\";\n\t\t\t\t\t\t}\n\t\t\t\t\t? R extends { body: infer B }\n\t\t\t\t\t\t? B\n\t\t\t\t\t\t: null\n\t\t\t\t\t: ReturnT;\n\t\t} catch (e) {\n\t\t\tif (e instanceof APIError) {\n\t\t\t\tresponseHeader.set(\"Content-Type\", \"application/json\");\n\t\t\t\te.headers = responseHeader;\n\t\t\t\tresponseHeader = new Headers();\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\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 type { statusCode } from \"./utils\";\n\ntype Status = keyof typeof statusCode;\n\nexport class APIError extends Error {\n\tstatus: Status;\n\theaders: Headers;\n\tbody: Record<string, any>;\n\n\tconstructor(status: Status, body?: Record<string, any>, headers?: Headers) {\n\t\tsuper(`API Error: ${status} ${body?.message ?? \"\"}`, {\n\t\t\tcause: body,\n\t\t});\n\n\t\tthis.status = status;\n\t\tthis.body = body ?? {};\n\t\tthis.stack = \"\";\n\n\t\tthis.headers = headers ?? new Headers();\n\t\tif (!this.headers.has(\"Content-Type\")) {\n\t\t\tthis.headers.set(\"Content-Type\", \"application/json\");\n\t\t}\n\t\tthis.name = \"BetterCallAPIError\";\n\t}\n}\n","export type UnionToIntersection<Union> = (\n\tUnion extends unknown\n\t\t? (distributedUnion: Union) => void\n\t\t: never\n) extends (mergedIntersection: infer Intersection) => void\n\t? Intersection & Union\n\t: never;\n\nexport type RequiredKeysOf<BaseType extends object> = Exclude<\n\t{\n\t\t[Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]> ? Key : never;\n\t}[keyof BaseType],\n\tundefined\n>;\n\nexport type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never\n\t? false\n\t: true;\n\n/**\n * this function will return a json response and\n * infers the type of the body\n */\nexport const json = <T>(\n\tbody: T,\n\toption?: {\n\t\tstatus?: number;\n\t\tstatusText?: string;\n\t\theaders?: Record<string, string>;\n\t\t/**\n\t\t * this body will take precedence over the body in the options if both are provided.\n\t\t * This is useful if you want to return body without inferring the type.\n\t\t */\n\t\tbody?: any;\n\t},\n) => {\n\treturn {\n\t\tresponse: {\n\t\t\tbody: option?.body ?? body,\n\t\t\tstatus: option?.status ?? 200,\n\t\t\tstatusText: option?.statusText ?? \"OK\",\n\t\t\theaders: option?.headers,\n\t\t},\n\t\tbody,\n\t\t_flag: \"json\" as const,\n\t};\n};\n","//https://github.com/honojs/hono/blob/main/src/utils/cookie.ts\nimport { subtle } from \"uncrypto\";\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) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await 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 subtle.sign(algorithm.name, key, new TextEncoder().encode(value));\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 subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value));\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\topt.secure = true;\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\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\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\nexport const signCookieValue = async (value: string, secret: string | BufferSource) => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn value;\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) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\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\tconst existingCookies = header.get(\"Set-Cookie\");\n\tif (existingCookies) {\n\t\tconst cookies = existingCookies.split(\", \");\n\t\tconst updatedCookies = cookies.filter((cookie) => !cookie.startsWith(`${name}=`));\n\t\theader.delete(\"Set-Cookie\");\n\t\tupdatedCookies.forEach((cookie) => header.append(\"Set-Cookie\", cookie));\n\t}\n\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) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t}\n\t}\n\tconst obj = await parseSigned(cookie, secret, finalKey);\n\treturn obj[finalKey];\n};\n","import { createRouter as createRou3Router, addRoute, findRoute, findAllRoutes } from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./error\";\nimport type { Endpoint } 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\tonResponse?: (res: Response) => any | Promise<any>;\n\tonRequest?: (req: Request) => any | Promise<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 (endpoint.options.metadata?.SERVER_ONLY) continue;\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\tif (!path?.length) {\n\t\t\tconfig?.onError?.(new APIError(\"NOT_FOUND\"));\n\t\t\tconsole.warn(\n\t\t\t\t`[better-call]: Make sure the URL has the basePath (${config?.basePath}).`,\n\t\t\t);\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\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 routerMiddleware = findAllRoutes(middlewareRouter, \"*\", path);\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 (routerMiddleware?.length) {\n\t\t\t\tfor (const route of routerMiddleware) {\n\t\t\t\t\tconst middleware = route.data as Endpoint;\n\t\t\t\t\tconst res = await middleware({\n\t\t\t\t\t\tpath: path,\n\t\t\t\t\t\tmethod: method as \"GET\",\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tparams: route?.params as any,\n\t\t\t\t\t\trequest: request,\n\t\t\t\t\t\tbody: body,\n\t\t\t\t\t\tquery,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t...config?.extraContext,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tif (res instanceof Response) {\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tif (res?._flag === \"json\") {\n\t\t\t\t\t\treturn new Response(JSON.stringify(res), {\n\t\t\t\t\t\t\theaders: res.headers,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (res) {\n\t\t\t\t\t\tmiddlewareContext = {\n\t\t\t\t\t\t\t...res,\n\t\t\t\t\t\t\t...middlewareContext,\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\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_flag: \"router\",\n\t\t\t\tcontext: {\n\t\t\t\t\t...middlewareContext,\n\t\t\t\t\t...config?.extraContext,\n\t\t\t\t},\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: e.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: async (request: Request) => {\n\t\t\tconst onReq = await config?.onRequest?.(request);\n\t\t\tif (onReq instanceof Response) {\n\t\t\t\treturn onReq;\n\t\t\t}\n\t\t\tconst req = onReq instanceof Request ? onReq : request;\n\t\t\tconst res = await handler(req);\n\t\t\tconst onRes = await config?.onResponse?.(res);\n\t\t\tif (onRes instanceof Response) {\n\t\t\t\treturn onRes;\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\tendpoints,\n\t};\n};\n\nexport type Router = ReturnType<typeof createRouter>;\n","export async function getBody(request: Request) {\n\tconst contentType = request.headers.get(\"content-type\") || \"\";\n\n\tif (!request.body) {\n\t\treturn undefined;\n\t}\n\n\tif (contentType.includes(\"application/json\")) {\n\t\treturn await request.json();\n\t}\n\n\tif (contentType.includes(\"application/x-www-form-urlencoded\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, string> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value.toString();\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"multipart/form-data\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, any> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value;\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"text/plain\")) {\n\t\treturn await request.text();\n\t}\n\n\tif (contentType.includes(\"application/octet-stream\")) {\n\t\treturn await request.arrayBuffer();\n\t}\n\n\tif (\n\t\tcontentType.includes(\"application/pdf\") ||\n\t\tcontentType.includes(\"image/\") ||\n\t\tcontentType.includes(\"video/\")\n\t) {\n\t\tconst blob = await request.blob();\n\t\treturn blob;\n\t}\n\n\tif (contentType.includes(\"application/stream\") || request.body instanceof ReadableStream) {\n\t\treturn request.body;\n\t}\n\n\treturn await request.text();\n}\n\nexport function shouldSerialize(body: any) {\n\treturn (\n\t\ttypeof body === \"object\" &&\n\t\tbody !== null &&\n\t\t!(body instanceof Blob) &&\n\t\t!(body instanceof FormData)\n\t);\n}\n\nexport const statusCode = {\n\tOK: 200,\n\tCREATED: 201,\n\tACCEPTED: 202,\n\tNO_CONTENT: 204,\n\tMULTIPLE_CHOICES: 300,\n\tMOVED_PERMANENTLY: 301,\n\tFOUND: 302,\n\tSEE_OTHER: 303,\n\tNOT_MODIFIED: 304,\n\tTEMPORARY_REDIRECT: 307,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_ALLOWED: 405,\n\tNOT_ACCEPTABLE: 406,\n\tPROXY_AUTHENTICATION_REQUIRED: 407,\n\tREQUEST_TIMEOUT: 408,\n\tCONFLICT: 409,\n\tGONE: 410,\n\tLENGTH_REQUIRED: 411,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tURI_TOO_LONG: 414,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tEXPECTATION_FAILED: 417,\n\t\"I'M_A_TEAPOT\": 418,\n\tMISDIRECTED_REQUEST: 421,\n\tUNPROCESSABLE_ENTITY: 422,\n\tLOCKED: 423,\n\tFAILED_DEPENDENCY: 424,\n\tTOO_EARLY: 425,\n\tUPGRADE_REQUIRED: 426,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tREQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n\tUNAVAILABLE_FOR_LEGAL_REASONS: 451,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504,\n\tHTTP_VERSION_NOT_SUPPORTED: 505,\n\tVARIANT_ALSO_NEGOTIATES: 506,\n\tINSUFFICIENT_STORAGE: 507,\n\tLOOP_DETECTED: 508,\n\tNOT_EXTENDED: 510,\n\tNETWORK_AUTHENTICATION_REQUIRED: 511,\n};\n","import type {\n\tContextTools,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n\tInferBody,\n\tInferHeaders,\n\tInferRequest,\n\tInferUse,\n\tPrettify,\n} from \"./types\";\nimport { createEndpoint } from \"./endpoint\";\n\nexport type MiddlewareHandler<\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n\tExtra extends Record<string, any> = {},\n> = (\n\tctx: Prettify<\n\t\tInferBody<Opts> &\n\t\t\tInferRequest<Opts> &\n\t\t\tInferHeaders<Opts> & {\n\t\t\t\tparams?: Record<string, string>;\n\t\t\t\tquery?: Record<string, string>;\n\t\t\t} & ContextTools\n\t> &\n\t\tExtra,\n) => Promise<R>;\n\nexport function createMiddleware<Opts extends EndpointOptions, R extends EndpointResponse>(\n\toptionsOrHandler: MiddlewareHandler<Opts, R>,\n): Endpoint<Handler<string, Opts, R>, Opts>;\nexport function createMiddleware<\n\tOpts extends Omit<EndpointOptions, \"method\">,\n\tR extends EndpointResponse,\n>(\n\toptionsOrHandler: Opts,\n\thandler: MiddlewareHandler<\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t},\n\t\tR\n\t>,\n): Endpoint<\n\tHandler<\n\t\tstring,\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t},\n\t\tR\n\t>,\n\tOpts & {\n\t\tmethod: \"*\";\n\t}\n>;\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n\tif (typeof optionsOrHandler === \"function\") {\n\t\treturn createEndpoint(\n\t\t\t\"*\",\n\t\t\t{\n\t\t\t\tmethod: \"*\",\n\t\t\t},\n\t\t\toptionsOrHandler,\n\t\t);\n\t}\n\tif (!handler) {\n\t\tthrow new Error(\"Middleware handler is required\");\n\t}\n\tconst endpoint = createEndpoint(\n\t\t\"*\",\n\t\t{\n\t\t\t...optionsOrHandler,\n\t\t\tmethod: \"*\",\n\t\t},\n\t\thandler,\n\t);\n\treturn endpoint as any;\n}\n\nexport const createMiddlewareCreator = <\n\tE extends {\n\t\tuse?: Endpoint[];\n\t},\n>(\n\topts?: E,\n) => {\n\ttype H<Opts extends EndpointOptions, R extends EndpointResponse> = (\n\t\tctx: Prettify<\n\t\t\tInferBody<Opts> &\n\t\t\t\tInferUse<E[\"use\"]> &\n\t\t\t\tInferRequest<Opts> &\n\t\t\t\tInferHeaders<Opts> & {\n\t\t\t\t\tparams?: Record<string, string>;\n\t\t\t\t\tquery?: Record<string, string>;\n\t\t\t\t} & ContextTools\n\t\t>,\n\t) => Promise<R>;\n\tfunction fn<Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\toptionsOrHandler: H<Opts, R>,\n\t): Endpoint<Handler<string, Opts, R>, Opts>;\n\tfunction fn<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(\n\t\toptionsOrHandler: Opts,\n\t\thandler: H<\n\t\t\tOpts & {\n\t\t\t\tmethod: \"*\";\n\t\t\t},\n\t\t\tR\n\t\t>,\n\t): Endpoint<\n\t\tHandler<\n\t\t\tstring,\n\t\t\tOpts & {\n\t\t\t\tmethod: \"*\";\n\t\t\t},\n\t\t\tR\n\t\t>,\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t}\n\t>;\n\tfunction fn(optionsOrHandler: any, handler?: any) {\n\t\tif (typeof optionsOrHandler === \"function\") {\n\t\t\treturn createEndpoint(\n\t\t\t\t\"*\",\n\t\t\t\t{\n\t\t\t\t\tmethod: \"*\",\n\t\t\t\t},\n\t\t\t\toptionsOrHandler,\n\t\t\t);\n\t\t}\n\t\tif (!handler) {\n\t\t\tthrow new Error(\"Middleware handler is required\");\n\t\t}\n\t\tconst endpoint = createEndpoint(\n\t\t\t\"*\",\n\t\t\t{\n\t\t\t\t...optionsOrHandler,\n\t\t\t\tmethod: \"*\",\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t\treturn endpoint as any;\n\t}\n\treturn fn;\n};\n\nexport type Middleware<\n\tOpts extends EndpointOptions = EndpointOptions,\n\tR extends EndpointResponse = EndpointResponse,\n> = (\n\topts: Opts,\n\thandler: (ctx: {\n\t\tbody?: InferBody<Opts>;\n\t\tparams?: Record<string, string>;\n\t\tquery?: Record<string, string>;\n\t}) => Promise<R>,\n) => Endpoint;\n","import { z, type ZodOptional, type ZodSchema } from \"zod\";\nimport type { json, UnionToIntersection } from \"./helper\";\nimport type { CookieOptions, CookiePrefixOptions } from \"./cookie\";\nimport type { APIError } from \"./error\";\n\nexport interface EndpointOptions {\n\t/**\n\t * Request Method\n\t */\n\tmethod: Method | Method[];\n\t/**\n\t * Body Schema\n\t */\n\tbody?: ZodSchema;\n\t/**\n\t * Query Schema\n\t */\n\tquery?: ZodSchema;\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\t/**\n\t * Endpoint metadata\n\t */\n\tmetadata?:\n\t\t| Record<string, any>\n\t\t| {\n\t\t\t\t/**\n\t\t\t\t * If true this endpoint will only be available on the server\n\t\t\t\t */\n\t\t\t\tSERVER_ONLY?: boolean;\n\t\t\t\t/**\n\t\t\t\t * A helper to infer the body and query schema.\n\t\t\t\t */\n\t\t\t\t$Infer?: {\n\t\t\t\t\tbody?: Record<string, any>;\n\t\t\t\t\tquery?: Record<string, any>;\n\t\t\t\t};\n\t\t };\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 type ContextTools = {\n\t/**\n\t * the current path\n\t */\n\tpath: string;\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, prefix?: CookiePrefixOptions) => 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\t/**\n\t * Redirect to url\n\t */\n\tredirect: (url: string) => APIError;\n\t/**\n\t * json response helper\n\t */\n\tjson: typeof json;\n\t/**\n\t * response header\n\t */\n\tresponseHeader: Headers;\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\t\t/**\n\t\t * This is used internally.\n\t\t * But you can use it to change the response form.\n\t\t *\n\t\t * - `json` will be set only when using `ctx.json` helper.\n\t\t * - `router` will be set when the handler is called from the router.\n\t\t * You can use this to change the response form to be a `Response` object.\n\t\t * - `default` will be used normally when the handler is called as a normal function.\n\t\t *\n\t\t * @internal\n\t\t */\n\t\t_flag?: \"json\" | \"router\" | \"default\";\n\t\t/**\n\t\t * Force the response to be a `Response` object.\n\t\t */\n\t\tasResponse?: boolean;\n\t};\n\nexport type InferUse<Opts extends EndpointOptions[\"use\"]> = Opts extends Endpoint[]\n\t? {\n\t\t\tcontext: UnionToIntersection<Awaited<ReturnType<Opts[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 EndpointBody =\n\t| Record<string, any>\n\t| string\n\t| boolean\n\t| number\n\t| void\n\t| undefined\n\t| null\n\t| unknown;\n\nexport type EndpointResponse =\n\t| {\n\t\t\tresponse: {\n\t\t\t\tstatus?: number;\n\t\t\t\tstatusText?: string;\n\t\t\t\theaders?: Headers;\n\t\t\t\tbody: any;\n\t\t\t};\n\t\t\tbody: EndpointBody;\n\t\t\t_flag: \"json\";\n\t }\n\t| EndpointBody;\n\nexport type Handler<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts[\"use\"]> & ContextTools>) => 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> = Opts[\"metadata\"] extends {\n\t$Infer: {\n\t\tbody: infer B;\n\t};\n}\n\t? {\n\t\t\tbody: B;\n\t\t}\n\t: Body extends ZodSchema\n\t\t? Body extends ZodOptional<any>\n\t\t\t? {\n\t\t\t\t\tbody?: Prettify<z.infer<Body>>;\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tbody: Prettify<z.infer<Body>>;\n\t\t\t\t}\n\t\t: {\n\t\t\t\tbody?: undefined;\n\t\t\t};\n","import { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { getRequest, setResponse } from \"./request.js\";\nimport type { Router } from \"../router.js\";\n\nexport function toNodeHandler(handler: Router[\"handler\"]) {\n\treturn async (req: IncomingMessage, res: ServerResponse) => {\n\t\tconst protocol = (req.connection as any)?.encrypted ? \"https\" : \"http\";\n\t\tconst base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n\t\tconst response = await handler(getRequest({ base, request: req }));\n\t\tsetResponse(res, response);\n\t};\n}\n\nexport { getRequest, setResponse };\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport * as set_cookie_parser from \"set-cookie-parser\";\n\nfunction get_raw_body(req: IncomingMessage, body_size_limit?: number) {\n\tconst h = req.headers;\n\n\tif (!h[\"content-type\"]) return null;\n\n\tconst content_length = Number(h[\"content-length\"]);\n\n\t// check if no request body\n\tif (\n\t\t(req.httpVersionMajor === 1 && isNaN(content_length) && h[\"transfer-encoding\"] == null) ||\n\t\tcontent_length === 0\n\t) {\n\t\treturn null;\n\t}\n\n\tlet length = content_length;\n\n\tif (body_size_limit) {\n\t\tif (!length) {\n\t\t\tlength = body_size_limit;\n\t\t} else if (length > body_size_limit) {\n\t\t\tthrow Error(\n\t\t\t\t`Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tif (req.destroyed) {\n\t\tconst readable = new ReadableStream();\n\t\treadable.cancel();\n\t\treturn readable;\n\t}\n\n\tlet size = 0;\n\tlet cancelled = false;\n\n\treturn new ReadableStream({\n\t\tstart(controller) {\n\t\t\treq.on(\"error\", (error) => {\n\t\t\t\tcancelled = true;\n\t\t\t\tcontroller.error(error);\n\t\t\t});\n\n\t\t\treq.on(\"end\", () => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\tcontroller.close();\n\t\t\t});\n\n\t\t\treq.on(\"data\", (chunk) => {\n\t\t\t\tif (cancelled) return;\n\n\t\t\t\tsize += chunk.length;\n\n\t\t\t\tif (size > length) {\n\t\t\t\t\tcancelled = true;\n\n\t\t\t\t\tcontroller.error(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`request body size exceeded ${\n\t\t\t\t\t\t\t\tcontent_length ? \"'content-length'\" : \"BODY_SIZE_LIMIT\"\n\t\t\t\t\t\t\t} of ${length}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tcontroller.enqueue(chunk);\n\n\t\t\t\tif (controller.desiredSize === null || controller.desiredSize <= 0) {\n\t\t\t\t\treq.pause();\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\tpull() {\n\t\t\treq.resume();\n\t\t},\n\n\t\tcancel(reason) {\n\t\t\tcancelled = true;\n\t\t\treq.destroy(reason);\n\t\t},\n\t});\n}\n\nexport function getRequest({\n\trequest,\n\tbase,\n\tbodySizeLimit,\n}: {\n\tbase: string;\n\tbodySizeLimit?: number;\n\trequest: IncomingMessage;\n}) {\n\treturn new Request(base + request.url, {\n\t\t// @ts-expect-error\n\t\tduplex: \"half\",\n\t\tmethod: request.method,\n\t\tbody: get_raw_body(request, bodySizeLimit),\n\t\theaders: request.headers as Record<string, string>,\n\t});\n}\n\nexport async function setResponse(res: ServerResponse, response: Response) {\n\tfor (const [key, value] of response.headers as any) {\n\t\ttry {\n\t\t\tres.setHeader(\n\t\t\t\tkey,\n\t\t\t\tkey === \"set-cookie\"\n\t\t\t\t\t? set_cookie_parser.splitCookiesString(response.headers.get(key) as string)\n\t\t\t\t\t: value,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tres.getHeaderNames().forEach((name) => res.removeHeader(name));\n\t\t\tres.writeHead(500).end(String(error));\n\t\t\treturn;\n\t\t}\n\t}\n\n\tres.writeHead(response.status);\n\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\n\tif (response.body.locked) {\n\t\tres.end(\n\t\t\t\"Fatal error: Response body is locked. \" +\n\t\t\t\t\"This can happen when the response was already read (for example through 'response.json()' or 'response.text()').\",\n\t\t);\n\t\treturn;\n\t}\n\n\tconst reader = response.body.getReader();\n\n\tif (res.destroyed) {\n\t\treader.cancel();\n\t\treturn;\n\t}\n\n\tconst cancel = (error?: Error) => {\n\t\tres.off(\"close\", cancel);\n\t\tres.off(\"error\", cancel);\n\n\t\t// If the reader has already been interrupted with an error earlier,\n\t\t// then it will appear here, it is useless, but it needs to be catch.\n\t\treader.cancel(error).catch(() => {});\n\t\tif (error) res.destroy(error);\n\t};\n\n\tres.on(\"close\", cancel);\n\tres.on(\"error\", cancel);\n\n\tnext();\n\tasync function next() {\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (!res.write(value)) {\n\t\t\t\t\tres.once(\"drain\", next);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tres.end();\n\t\t} catch (error) {\n\t\t\tcancel(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,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,CAAC,CAAC;AACjE,gBAAY,KAAK,QAAQ;AAAA,EAC1B;AACD;","names":["cookie","options","createRou3Router","handler","route","import_zod","import_node_http"]}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as Endpoint, a as EndpointOptions, b as EndpointResponse, P as Prettify, C as Context, I as InferUse, c as ContextTools, H as HasRequiredKeys, M as Method, d as Handler, e as InferBody, f as InferRequest, g as InferHeaders, h as InferUseOptions, R as Router, i as CookiePrefixOptions, j as CookieOptions } from './router-Bn7zn81P.cjs';
2
- export { A as APIError, u as Cookie, v as CookieConstraint, t as EndpointBody, p as InferMethod, r as InferParam, n as InferParamPath, o as InferParamWildCard, q as InferQuery, S as SignedCookie, k as createRouter, l as getBody, w as parse, x as parseSigned, y as serialize, z as serializeSigned, s as shouldSerialize, m as statusCode } from './router-Bn7zn81P.cjs';
1
+ import { E as Endpoint, a as EndpointOptions, b as EndpointResponse, P as Prettify, C as Context, I as InferUse, c as ContextTools, H as HasRequiredKeys, M as Method, d as Handler, e as InferBody, f as InferRequest, g as InferHeaders, h as InferUseOptions, R as Router, i as CookiePrefixOptions, j as CookieOptions } from './router-tRhygVBO.cjs';
2
+ export { A as APIError, u as Cookie, v as CookieConstraint, t as EndpointBody, p as InferMethod, r as InferParam, n as InferParamPath, o as InferParamWildCard, q as InferQuery, S as SignedCookie, k as createRouter, l as getBody, w as parse, x as parseSigned, y as serialize, z as serializeSigned, s as shouldSerialize, B as signCookieValue, m as statusCode } from './router-tRhygVBO.cjs';
3
3
  import { IncomingMessage, ServerResponse } from 'node:http';
4
4
  import 'zod';
5
5
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as Endpoint, a as EndpointOptions, b as EndpointResponse, P as Prettify, C as Context, I as InferUse, c as ContextTools, H as HasRequiredKeys, M as Method, d as Handler, e as InferBody, f as InferRequest, g as InferHeaders, h as InferUseOptions, R as Router, i as CookiePrefixOptions, j as CookieOptions } from './router-Bn7zn81P.js';
2
- export { A as APIError, u as Cookie, v as CookieConstraint, t as EndpointBody, p as InferMethod, r as InferParam, n as InferParamPath, o as InferParamWildCard, q as InferQuery, S as SignedCookie, k as createRouter, l as getBody, w as parse, x as parseSigned, y as serialize, z as serializeSigned, s as shouldSerialize, m as statusCode } from './router-Bn7zn81P.js';
1
+ import { E as Endpoint, a as EndpointOptions, b as EndpointResponse, P as Prettify, C as Context, I as InferUse, c as ContextTools, H as HasRequiredKeys, M as Method, d as Handler, e as InferBody, f as InferRequest, g as InferHeaders, h as InferUseOptions, R as Router, i as CookiePrefixOptions, j as CookieOptions } from './router-tRhygVBO.js';
2
+ export { A as APIError, u as Cookie, v as CookieConstraint, t as EndpointBody, p as InferMethod, r as InferParam, n as InferParamPath, o as InferParamWildCard, q as InferQuery, S as SignedCookie, k as createRouter, l as getBody, w as parse, x as parseSigned, y as serialize, z as serializeSigned, s as shouldSerialize, B as signCookieValue, m as statusCode } from './router-tRhygVBO.js';
3
3
  import { IncomingMessage, ServerResponse } from 'node:http';
4
4
  import 'zod';
5
5
 
package/dist/index.js CHANGED
@@ -170,6 +170,12 @@ var serializeSigned = async (name, value, secret, opt = {}) => {
170
170
  value = encodeURIComponent(value);
171
171
  return _serialize(name, value, opt);
172
172
  };
173
+ var signCookieValue = async (value, secret) => {
174
+ const signature = await makeSignature(value, secret);
175
+ value = `${value}.${signature}`;
176
+ value = encodeURIComponent(value);
177
+ return value;
178
+ };
173
179
 
174
180
  // src/cookie-utils.ts
175
181
  var getCookie = (cookie, key, prefix) => {
@@ -344,7 +350,10 @@ function createEndpoint(path, options, handler) {
344
350
  ...internalCtx.body
345
351
  } : internalCtx.body
346
352
  };
347
- internalCtx.query = options.query ? options.query.parse(internalCtx.query) : internalCtx.query;
353
+ console.log(internalCtx.query);
354
+ internalCtx.query = options.query ? options.query.parse(
355
+ internalCtx
356
+ ) : internalCtx.query;
348
357
  } catch (e) {
349
358
  if (e instanceof ZodError) {
350
359
  throw new APIError("BAD_REQUEST", {
@@ -857,6 +866,7 @@ export {
857
866
  setResponse,
858
867
  setSignedCookie,
859
868
  shouldSerialize,
869
+ signCookieValue,
860
870
  statusCode,
861
871
  toNodeHandler
862
872
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/endpoint.ts","../src/error.ts","../src/helper.ts","../src/cookie.ts","../src/cookie-utils.ts","../src/router.ts","../src/utils.ts","../src/middleware.ts","../src/types.ts","../src/adapter/request.ts","../src/adapter/node.ts"],"sourcesContent":["\"use server\";\nimport { ZodError } from \"zod\";\nimport { APIError } from \"./error\";\nimport { json, type HasRequiredKeys } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n\tInferUse,\n\tPrettify,\n} from \"./types\";\nimport { getCookie, getSignedCookie, setCookie, setSignedCookie } from \"./cookie-utils\";\nimport type { CookiePrefixOptions, CookieOptions } 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<\n\tE extends {\n\t\tuse?: Endpoint[];\n\t},\n>(opts?: E) {\n\treturn <Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\tpath: Path,\n\t\toptions: Opts,\n\t\thandler: (\n\t\t\tctx: Prettify<\n\t\t\t\tContext<Path, Opts> &\n\t\t\t\t\tInferUse<Opts[\"use\"]> &\n\t\t\t\t\tInferUse<E[\"use\"]> &\n\t\t\t\t\tOmit<ContextTools, \"_flag\">\n\t\t\t>,\n\t\t) => Promise<R>,\n\t) => {\n\t\treturn createEndpoint(\n\t\t\tpath,\n\t\t\t{\n\t\t\t\t...options,\n\t\t\t\tuse: [...(options?.use || []), ...(opts?.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\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\tlet responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\n\tconst handle = async <C extends HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]>(\n\t\t...ctx: C\n\t) => {\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 cookieH = header?.get(\"cookie\");\n\t\t\t\tconst cookie = getCookie(cookieH || \"\", 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\tredirect(url: string) {\n\t\t\t\tresponseHeader.set(\"Location\", url);\n\t\t\t\treturn new APIError(\"FOUND\");\n\t\t\t},\n\t\t\tjson,\n\t\t\tcontext: (ctx[0] as any)?.context || {},\n\t\t\t_flag: (ctx[0] as any)?.asResponse ? \"router\" : (ctx[0] as any)?._flag,\n\t\t\tresponseHeader,\n\t\t\tpath: path,\n\t\t\t...(ctx[0] || {}),\n\t\t};\n\t\tif (options.use?.length) {\n\t\t\tlet middlewareContexts = {};\n\t\t\tlet middlewareBody = {};\n\t\t\tfor (const middleware of options.use) {\n\t\t\t\tif (typeof middleware !== \"function\") {\n\t\t\t\t\tconsole.warn(\"Middleware is not a function\", {\n\t\t\t\t\t\tmiddleware,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst res = (await middleware(internalCtx)) as Endpoint;\n\t\t\t\tif (res) {\n\t\t\t\t\tconst body = res.options?.body\n\t\t\t\t\t\t? res.options.body.parse(internalCtx.body)\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tmiddlewareContexts = {\n\t\t\t\t\t\t...middlewareContexts,\n\t\t\t\t\t\t...res,\n\t\t\t\t\t};\n\t\t\t\t\tmiddlewareBody = {\n\t\t\t\t\t\t...middlewareBody,\n\t\t\t\t\t\t...body,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tinternalCtx = {\n\t\t\t\t...internalCtx,\n\t\t\t\tbody: {\n\t\t\t\t\t...middlewareBody,\n\t\t\t\t\t...internalCtx.body,\n\t\t\t\t},\n\t\t\t\tcontext: {\n\t\t\t\t\t...(internalCtx.context || {}),\n\t\t\t\t\t...middlewareContexts,\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} 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\ttry {\n\t\t\tlet res = (await handler(internalCtx as any)) as any;\n\t\t\tlet actualResponse: any = res;\n\n\t\t\tif (res && typeof res === \"object\" && \"_flag\" in res) {\n\t\t\t\tif (res._flag === \"json\" && internalCtx._flag === \"router\") {\n\t\t\t\t\tconst h = res.response.headers as Record<string, string>;\n\t\t\t\t\tObject.keys(h || {}).forEach((key) => {\n\t\t\t\t\t\tresponseHeader.set(key, h[key as keyof typeof h]);\n\t\t\t\t\t});\n\t\t\t\t\tresponseHeader.set(\"Content-Type\", \"application/json\");\n\t\t\t\t\tactualResponse = new Response(JSON.stringify(res.response.body), {\n\t\t\t\t\t\tstatus: res.response.status ?? 200,\n\t\t\t\t\t\tstatusText: res.response.statusText,\n\t\t\t\t\t\theaders: responseHeader,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tactualResponse = res.body;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponseHeader = new Headers();\n\n\t\t\ttype ReturnT = Awaited<ReturnType<Handler<Path, Opts, R>>>;\n\t\t\treturn actualResponse as C extends [{ asResponse: true }]\n\t\t\t\t? Response\n\t\t\t\t: R extends {\n\t\t\t\t\t\t\t_flag: \"json\";\n\t\t\t\t\t\t}\n\t\t\t\t\t? R extends { body: infer B }\n\t\t\t\t\t\t? B\n\t\t\t\t\t\t: null\n\t\t\t\t\t: ReturnT;\n\t\t} catch (e) {\n\t\t\tif (e instanceof APIError) {\n\t\t\t\tresponseHeader.set(\"Content-Type\", \"application/json\");\n\t\t\t\te.headers = responseHeader;\n\t\t\t\tresponseHeader = new Headers();\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\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 type { statusCode } from \"./utils\";\n\ntype Status = keyof typeof statusCode;\n\nexport class APIError extends Error {\n\tstatus: Status;\n\theaders: Headers;\n\tbody: Record<string, any>;\n\n\tconstructor(status: Status, body?: Record<string, any>, headers?: Headers) {\n\t\tsuper(`API Error: ${status} ${body?.message ?? \"\"}`, {\n\t\t\tcause: body,\n\t\t});\n\n\t\tthis.status = status;\n\t\tthis.body = body ?? {};\n\t\tthis.stack = \"\";\n\n\t\tthis.headers = headers ?? new Headers();\n\t\tif (!this.headers.has(\"Content-Type\")) {\n\t\t\tthis.headers.set(\"Content-Type\", \"application/json\");\n\t\t}\n\t\tthis.name = \"BetterCallAPIError\";\n\t}\n}\n","export type UnionToIntersection<Union> = (\n\tUnion extends unknown\n\t\t? (distributedUnion: Union) => void\n\t\t: never\n) extends (mergedIntersection: infer Intersection) => void\n\t? Intersection & Union\n\t: never;\n\nexport type RequiredKeysOf<BaseType extends object> = Exclude<\n\t{\n\t\t[Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]> ? Key : never;\n\t}[keyof BaseType],\n\tundefined\n>;\n\nexport type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never\n\t? false\n\t: true;\n\n/**\n * this function will return a json response and\n * infers the type of the body\n */\nexport const json = <T>(\n\tbody: T,\n\toption?: {\n\t\tstatus?: number;\n\t\tstatusText?: string;\n\t\theaders?: Record<string, string>;\n\t\t/**\n\t\t * this body will take precedence over the body in the options if both are provided.\n\t\t * This is useful if you want to return body without inferring the type.\n\t\t */\n\t\tbody?: any;\n\t},\n) => {\n\treturn {\n\t\tresponse: {\n\t\t\tbody: option?.body ?? body,\n\t\t\tstatus: option?.status ?? 200,\n\t\t\tstatusText: option?.statusText ?? \"OK\",\n\t\t\theaders: option?.headers,\n\t\t},\n\t\tbody,\n\t\t_flag: \"json\" as const,\n\t};\n};\n","//https://github.com/honojs/hono/blob/main/src/utils/cookie.ts\nimport { subtle } from \"uncrypto\";\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) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await 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 subtle.sign(algorithm.name, key, new TextEncoder().encode(value));\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 subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value));\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\topt.secure = true;\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\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\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) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\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\tconst existingCookies = header.get(\"Set-Cookie\");\n\tif (existingCookies) {\n\t\tconst cookies = existingCookies.split(\", \");\n\t\tconst updatedCookies = cookies.filter((cookie) => !cookie.startsWith(`${name}=`));\n\t\theader.delete(\"Set-Cookie\");\n\t\tupdatedCookies.forEach((cookie) => header.append(\"Set-Cookie\", cookie));\n\t}\n\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) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t}\n\t}\n\tconst obj = await parseSigned(cookie, secret, finalKey);\n\treturn obj[finalKey];\n};\n","import { createRouter as createRou3Router, addRoute, findRoute, findAllRoutes } from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./error\";\nimport type { Endpoint } 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\tonResponse?: (res: Response) => any | Promise<any>;\n\tonRequest?: (req: Request) => any | Promise<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 (endpoint.options.metadata?.SERVER_ONLY) continue;\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\tif (!path?.length) {\n\t\t\tconfig?.onError?.(new APIError(\"NOT_FOUND\"));\n\t\t\tconsole.warn(\n\t\t\t\t`[better-call]: Make sure the URL has the basePath (${config?.basePath}).`,\n\t\t\t);\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\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 routerMiddleware = findAllRoutes(middlewareRouter, \"*\", path);\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 (routerMiddleware?.length) {\n\t\t\t\tfor (const route of routerMiddleware) {\n\t\t\t\t\tconst middleware = route.data as Endpoint;\n\t\t\t\t\tconst res = await middleware({\n\t\t\t\t\t\tpath: path,\n\t\t\t\t\t\tmethod: method as \"GET\",\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tparams: route?.params as any,\n\t\t\t\t\t\trequest: request,\n\t\t\t\t\t\tbody: body,\n\t\t\t\t\t\tquery,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t...config?.extraContext,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tif (res instanceof Response) {\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tif (res?._flag === \"json\") {\n\t\t\t\t\t\treturn new Response(JSON.stringify(res), {\n\t\t\t\t\t\t\theaders: res.headers,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (res) {\n\t\t\t\t\t\tmiddlewareContext = {\n\t\t\t\t\t\t\t...res,\n\t\t\t\t\t\t\t...middlewareContext,\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\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_flag: \"router\",\n\t\t\t\tcontext: {\n\t\t\t\t\t...middlewareContext,\n\t\t\t\t\t...config?.extraContext,\n\t\t\t\t},\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: e.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: async (request: Request) => {\n\t\t\tconst onReq = await config?.onRequest?.(request);\n\t\t\tif (onReq instanceof Response) {\n\t\t\t\treturn onReq;\n\t\t\t}\n\t\t\tconst req = onReq instanceof Request ? onReq : request;\n\t\t\tconst res = await handler(req);\n\t\t\tconst onRes = await config?.onResponse?.(res);\n\t\t\tif (onRes instanceof Response) {\n\t\t\t\treturn onRes;\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\tendpoints,\n\t};\n};\n\nexport type Router = ReturnType<typeof createRouter>;\n","export async function getBody(request: Request) {\n\tconst contentType = request.headers.get(\"content-type\") || \"\";\n\n\tif (!request.body) {\n\t\treturn undefined;\n\t}\n\n\tif (contentType.includes(\"application/json\")) {\n\t\treturn await request.json();\n\t}\n\n\tif (contentType.includes(\"application/x-www-form-urlencoded\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, string> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value.toString();\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"multipart/form-data\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, any> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value;\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"text/plain\")) {\n\t\treturn await request.text();\n\t}\n\n\tif (contentType.includes(\"application/octet-stream\")) {\n\t\treturn await request.arrayBuffer();\n\t}\n\n\tif (\n\t\tcontentType.includes(\"application/pdf\") ||\n\t\tcontentType.includes(\"image/\") ||\n\t\tcontentType.includes(\"video/\")\n\t) {\n\t\tconst blob = await request.blob();\n\t\treturn blob;\n\t}\n\n\tif (contentType.includes(\"application/stream\") || request.body instanceof ReadableStream) {\n\t\treturn request.body;\n\t}\n\n\treturn await request.text();\n}\n\nexport function shouldSerialize(body: any) {\n\treturn (\n\t\ttypeof body === \"object\" &&\n\t\tbody !== null &&\n\t\t!(body instanceof Blob) &&\n\t\t!(body instanceof FormData)\n\t);\n}\n\nexport const statusCode = {\n\tOK: 200,\n\tCREATED: 201,\n\tACCEPTED: 202,\n\tNO_CONTENT: 204,\n\tMULTIPLE_CHOICES: 300,\n\tMOVED_PERMANENTLY: 301,\n\tFOUND: 302,\n\tSEE_OTHER: 303,\n\tNOT_MODIFIED: 304,\n\tTEMPORARY_REDIRECT: 307,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_ALLOWED: 405,\n\tNOT_ACCEPTABLE: 406,\n\tPROXY_AUTHENTICATION_REQUIRED: 407,\n\tREQUEST_TIMEOUT: 408,\n\tCONFLICT: 409,\n\tGONE: 410,\n\tLENGTH_REQUIRED: 411,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tURI_TOO_LONG: 414,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tEXPECTATION_FAILED: 417,\n\t\"I'M_A_TEAPOT\": 418,\n\tMISDIRECTED_REQUEST: 421,\n\tUNPROCESSABLE_ENTITY: 422,\n\tLOCKED: 423,\n\tFAILED_DEPENDENCY: 424,\n\tTOO_EARLY: 425,\n\tUPGRADE_REQUIRED: 426,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tREQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n\tUNAVAILABLE_FOR_LEGAL_REASONS: 451,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504,\n\tHTTP_VERSION_NOT_SUPPORTED: 505,\n\tVARIANT_ALSO_NEGOTIATES: 506,\n\tINSUFFICIENT_STORAGE: 507,\n\tLOOP_DETECTED: 508,\n\tNOT_EXTENDED: 510,\n\tNETWORK_AUTHENTICATION_REQUIRED: 511,\n};\n","import type {\n\tContextTools,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n\tInferBody,\n\tInferHeaders,\n\tInferRequest,\n\tInferUse,\n\tPrettify,\n} from \"./types\";\nimport { createEndpoint } from \"./endpoint\";\n\nexport type MiddlewareHandler<\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n\tExtra extends Record<string, any> = {},\n> = (\n\tctx: Prettify<\n\t\tInferBody<Opts> &\n\t\t\tInferRequest<Opts> &\n\t\t\tInferHeaders<Opts> & {\n\t\t\t\tparams?: Record<string, string>;\n\t\t\t\tquery?: Record<string, string>;\n\t\t\t} & ContextTools\n\t> &\n\t\tExtra,\n) => Promise<R>;\n\nexport function createMiddleware<Opts extends EndpointOptions, R extends EndpointResponse>(\n\toptionsOrHandler: MiddlewareHandler<Opts, R>,\n): Endpoint<Handler<string, Opts, R>, Opts>;\nexport function createMiddleware<\n\tOpts extends Omit<EndpointOptions, \"method\">,\n\tR extends EndpointResponse,\n>(\n\toptionsOrHandler: Opts,\n\thandler: MiddlewareHandler<\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t},\n\t\tR\n\t>,\n): Endpoint<\n\tHandler<\n\t\tstring,\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t},\n\t\tR\n\t>,\n\tOpts & {\n\t\tmethod: \"*\";\n\t}\n>;\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n\tif (typeof optionsOrHandler === \"function\") {\n\t\treturn createEndpoint(\n\t\t\t\"*\",\n\t\t\t{\n\t\t\t\tmethod: \"*\",\n\t\t\t},\n\t\t\toptionsOrHandler,\n\t\t);\n\t}\n\tif (!handler) {\n\t\tthrow new Error(\"Middleware handler is required\");\n\t}\n\tconst endpoint = createEndpoint(\n\t\t\"*\",\n\t\t{\n\t\t\t...optionsOrHandler,\n\t\t\tmethod: \"*\",\n\t\t},\n\t\thandler,\n\t);\n\treturn endpoint as any;\n}\n\nexport const createMiddlewareCreator = <\n\tE extends {\n\t\tuse?: Endpoint[];\n\t},\n>(\n\topts?: E,\n) => {\n\ttype H<Opts extends EndpointOptions, R extends EndpointResponse> = (\n\t\tctx: Prettify<\n\t\t\tInferBody<Opts> &\n\t\t\t\tInferUse<E[\"use\"]> &\n\t\t\t\tInferRequest<Opts> &\n\t\t\t\tInferHeaders<Opts> & {\n\t\t\t\t\tparams?: Record<string, string>;\n\t\t\t\t\tquery?: Record<string, string>;\n\t\t\t\t} & ContextTools\n\t\t>,\n\t) => Promise<R>;\n\tfunction fn<Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\toptionsOrHandler: H<Opts, R>,\n\t): Endpoint<Handler<string, Opts, R>, Opts>;\n\tfunction fn<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(\n\t\toptionsOrHandler: Opts,\n\t\thandler: H<\n\t\t\tOpts & {\n\t\t\t\tmethod: \"*\";\n\t\t\t},\n\t\t\tR\n\t\t>,\n\t): Endpoint<\n\t\tHandler<\n\t\t\tstring,\n\t\t\tOpts & {\n\t\t\t\tmethod: \"*\";\n\t\t\t},\n\t\t\tR\n\t\t>,\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t}\n\t>;\n\tfunction fn(optionsOrHandler: any, handler?: any) {\n\t\tif (typeof optionsOrHandler === \"function\") {\n\t\t\treturn createEndpoint(\n\t\t\t\t\"*\",\n\t\t\t\t{\n\t\t\t\t\tmethod: \"*\",\n\t\t\t\t},\n\t\t\t\toptionsOrHandler,\n\t\t\t);\n\t\t}\n\t\tif (!handler) {\n\t\t\tthrow new Error(\"Middleware handler is required\");\n\t\t}\n\t\tconst endpoint = createEndpoint(\n\t\t\t\"*\",\n\t\t\t{\n\t\t\t\t...optionsOrHandler,\n\t\t\t\tmethod: \"*\",\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t\treturn endpoint as any;\n\t}\n\treturn fn;\n};\n\nexport type Middleware<\n\tOpts extends EndpointOptions = EndpointOptions,\n\tR extends EndpointResponse = EndpointResponse,\n> = (\n\topts: Opts,\n\thandler: (ctx: {\n\t\tbody?: InferBody<Opts>;\n\t\tparams?: Record<string, string>;\n\t\tquery?: Record<string, string>;\n\t}) => Promise<R>,\n) => Endpoint;\n","import { z, type ZodOptional, type ZodSchema } from \"zod\";\nimport type { json, UnionToIntersection } from \"./helper\";\nimport type { CookieOptions, CookiePrefixOptions } from \"./cookie\";\nimport type { APIError } from \"./error\";\n\nexport interface EndpointOptions {\n\t/**\n\t * Request Method\n\t */\n\tmethod: Method | Method[];\n\t/**\n\t * Body Schema\n\t */\n\tbody?: ZodSchema;\n\t/**\n\t * Query Schema\n\t */\n\tquery?: ZodSchema;\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\t/**\n\t * Endpoint metadata\n\t */\n\tmetadata?:\n\t\t| Record<string, any>\n\t\t| {\n\t\t\t\t/**\n\t\t\t\t * If true this endpoint will only be available on the server\n\t\t\t\t */\n\t\t\t\tSERVER_ONLY?: boolean;\n\t\t };\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 type ContextTools = {\n\t/**\n\t * the current path\n\t */\n\tpath: string;\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, prefix?: CookiePrefixOptions) => 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\t/**\n\t * Redirect to url\n\t */\n\tredirect: (url: string) => APIError;\n\t/**\n\t * json response helper\n\t */\n\tjson: typeof json;\n\t/**\n\t * response header\n\t */\n\tresponseHeader: Headers;\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\t\t/**\n\t\t * This is used internally.\n\t\t * But you can use it to change the response form.\n\t\t *\n\t\t * - `json` will be set only when using `ctx.json` helper.\n\t\t * - `router` will be set when the handler is called from the router.\n\t\t * You can use this to change the response form to be a `Response` object.\n\t\t * - `default` will be used normally when the handler is called as a normal function.\n\t\t *\n\t\t * @internal\n\t\t */\n\t\t_flag?: \"json\" | \"router\" | \"default\";\n\t\t/**\n\t\t * Force the response to be a `Response` object.\n\t\t */\n\t\tasResponse?: boolean;\n\t};\n\nexport type InferUse<Opts extends EndpointOptions[\"use\"]> = Opts extends Endpoint[]\n\t? {\n\t\t\tcontext: UnionToIntersection<Awaited<ReturnType<Opts[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 EndpointBody =\n\t| Record<string, any>\n\t| string\n\t| boolean\n\t| number\n\t| void\n\t| undefined\n\t| null\n\t| unknown;\n\nexport type EndpointResponse =\n\t| {\n\t\t\tresponse: {\n\t\t\t\tstatus?: number;\n\t\t\t\tstatusText?: string;\n\t\t\t\theaders?: Headers;\n\t\t\t\tbody: any;\n\t\t\t};\n\t\t\tbody: EndpointBody;\n\t\t\t_flag: \"json\";\n\t }\n\t| EndpointBody;\n\nexport type Handler<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts[\"use\"]> & ContextTools>) => 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","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport * as set_cookie_parser from \"set-cookie-parser\";\n\nfunction get_raw_body(req: IncomingMessage, body_size_limit?: number) {\n\tconst h = req.headers;\n\n\tif (!h[\"content-type\"]) return null;\n\n\tconst content_length = Number(h[\"content-length\"]);\n\n\t// check if no request body\n\tif (\n\t\t(req.httpVersionMajor === 1 && isNaN(content_length) && h[\"transfer-encoding\"] == null) ||\n\t\tcontent_length === 0\n\t) {\n\t\treturn null;\n\t}\n\n\tlet length = content_length;\n\n\tif (body_size_limit) {\n\t\tif (!length) {\n\t\t\tlength = body_size_limit;\n\t\t} else if (length > body_size_limit) {\n\t\t\tthrow Error(\n\t\t\t\t`Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tif (req.destroyed) {\n\t\tconst readable = new ReadableStream();\n\t\treadable.cancel();\n\t\treturn readable;\n\t}\n\n\tlet size = 0;\n\tlet cancelled = false;\n\n\treturn new ReadableStream({\n\t\tstart(controller) {\n\t\t\treq.on(\"error\", (error) => {\n\t\t\t\tcancelled = true;\n\t\t\t\tcontroller.error(error);\n\t\t\t});\n\n\t\t\treq.on(\"end\", () => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\tcontroller.close();\n\t\t\t});\n\n\t\t\treq.on(\"data\", (chunk) => {\n\t\t\t\tif (cancelled) return;\n\n\t\t\t\tsize += chunk.length;\n\n\t\t\t\tif (size > length) {\n\t\t\t\t\tcancelled = true;\n\n\t\t\t\t\tcontroller.error(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`request body size exceeded ${\n\t\t\t\t\t\t\t\tcontent_length ? \"'content-length'\" : \"BODY_SIZE_LIMIT\"\n\t\t\t\t\t\t\t} of ${length}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tcontroller.enqueue(chunk);\n\n\t\t\t\tif (controller.desiredSize === null || controller.desiredSize <= 0) {\n\t\t\t\t\treq.pause();\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\tpull() {\n\t\t\treq.resume();\n\t\t},\n\n\t\tcancel(reason) {\n\t\t\tcancelled = true;\n\t\t\treq.destroy(reason);\n\t\t},\n\t});\n}\n\nexport function getRequest({\n\trequest,\n\tbase,\n\tbodySizeLimit,\n}: {\n\tbase: string;\n\tbodySizeLimit?: number;\n\trequest: IncomingMessage;\n}) {\n\treturn new Request(base + request.url, {\n\t\t// @ts-expect-error\n\t\tduplex: \"half\",\n\t\tmethod: request.method,\n\t\tbody: get_raw_body(request, bodySizeLimit),\n\t\theaders: request.headers as Record<string, string>,\n\t});\n}\n\nexport async function setResponse(res: ServerResponse, response: Response) {\n\tfor (const [key, value] of response.headers as any) {\n\t\ttry {\n\t\t\tres.setHeader(\n\t\t\t\tkey,\n\t\t\t\tkey === \"set-cookie\"\n\t\t\t\t\t? set_cookie_parser.splitCookiesString(response.headers.get(key) as string)\n\t\t\t\t\t: value,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tres.getHeaderNames().forEach((name) => res.removeHeader(name));\n\t\t\tres.writeHead(500).end(String(error));\n\t\t\treturn;\n\t\t}\n\t}\n\n\tres.writeHead(response.status);\n\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\n\tif (response.body.locked) {\n\t\tres.end(\n\t\t\t\"Fatal error: Response body is locked. \" +\n\t\t\t\t\"This can happen when the response was already read (for example through 'response.json()' or 'response.text()').\",\n\t\t);\n\t\treturn;\n\t}\n\n\tconst reader = response.body.getReader();\n\n\tif (res.destroyed) {\n\t\treader.cancel();\n\t\treturn;\n\t}\n\n\tconst cancel = (error?: Error) => {\n\t\tres.off(\"close\", cancel);\n\t\tres.off(\"error\", cancel);\n\n\t\t// If the reader has already been interrupted with an error earlier,\n\t\t// then it will appear here, it is useless, but it needs to be catch.\n\t\treader.cancel(error).catch(() => {});\n\t\tif (error) res.destroy(error);\n\t};\n\n\tres.on(\"close\", cancel);\n\tres.on(\"error\", cancel);\n\n\tnext();\n\tasync function next() {\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (!res.write(value)) {\n\t\t\t\t\tres.once(\"drain\", next);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tres.end();\n\t\t} catch (error) {\n\t\t\tcancel(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { getRequest, setResponse } from \"./request.js\";\nimport type { Router } from \"../router.js\";\n\nexport function toNodeHandler(handler: Router[\"handler\"]) {\n\treturn async (req: IncomingMessage, res: ServerResponse) => {\n\t\tconst protocol = (req.connection as any)?.encrypted ? \"https\" : \"http\";\n\t\tconst base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n\t\tconst response = await handler(getRequest({ base, request: req }));\n\t\tsetResponse(res, response);\n\t};\n}\n\nexport { getRequest, setResponse };\n"],"mappings":";;;;;AACA,SAAS,gBAAgB;;;ACGlB,IAAM,WAAN,cAAuB,MAAM;AAAA,EAKnC,YAAY,QAAgB,MAA4B,SAAmB;AAC1E,UAAM,cAAc,MAAM,IAAI,MAAM,WAAW,EAAE,IAAI;AAAA,MACpD,OAAO;AAAA,IACR,CAAC;AAPF;AACA;AACA;AAOC,SAAK,SAAS;AACd,SAAK,OAAO,QAAQ,CAAC;AACrB,SAAK,QAAQ;AAEb,SAAK,UAAU,WAAW,IAAI,QAAQ;AACtC,QAAI,CAAC,KAAK,QAAQ,IAAI,cAAc,GAAG;AACtC,WAAK,QAAQ,IAAI,gBAAgB,kBAAkB;AAAA,IACpD;AACA,SAAK,OAAO;AAAA,EACb;AACD;;;ACDO,IAAM,OAAO,CACnB,MACA,WAUI;AACJ,SAAO;AAAA,IACN,UAAU;AAAA,MACT,MAAM,QAAQ,QAAQ;AAAA,MAC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AAC,IAAI,MAAM,KAAK,GAAG;AACtB,cAAI,KAAK,SAAS,IAAI;AACtB;AAAA,QACD;AAAA,MACD;AACA,UAAI,IAAI;AAAA,IACT,SAAS,OAAO;AACf,aAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;AAAA,IACjE;AAAA,EACD;AACD;;;AC1KO,SAAS,cAAc,SAA4B;AACzD,SAAO,OAAO,KAAsB,QAAwB;AAC3D,UAAM,WAAY,IAAI,YAAoB,YAAY,UAAU;AAChE,UAAM,OAAO,GAAG,QAAQ,MAAM,IAAI,QAAQ,YAAY,KAAK,IAAI,QAAQ,IAAI;AAC3E,UAAM,WAAW,MAAM,QAAQ,WAAW,EAAE,MAAM,SAAS,IAAI,CAAC,CAAC;AACjE,gBAAY,KAAK,QAAQ;AAAA,EAC1B;AACD;","names":["cookie","options","handler","route"]}
1
+ {"version":3,"sources":["../src/endpoint.ts","../src/error.ts","../src/helper.ts","../src/cookie.ts","../src/cookie-utils.ts","../src/router.ts","../src/utils.ts","../src/middleware.ts","../src/types.ts","../src/adapter/request.ts","../src/adapter/node.ts"],"sourcesContent":["\"use server\";\nimport { ZodError } from \"zod\";\nimport { APIError } from \"./error\";\nimport { json, type HasRequiredKeys } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n\tInferUse,\n\tPrettify,\n} from \"./types\";\nimport { getCookie, getSignedCookie, setCookie, setSignedCookie } from \"./cookie-utils\";\nimport type { CookiePrefixOptions, CookieOptions } 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<\n\tE extends {\n\t\tuse?: Endpoint[];\n\t},\n>(opts?: E) {\n\treturn <Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\tpath: Path,\n\t\toptions: Opts,\n\t\thandler: (\n\t\t\tctx: Prettify<\n\t\t\t\tContext<Path, Opts> &\n\t\t\t\t\tInferUse<Opts[\"use\"]> &\n\t\t\t\t\tInferUse<E[\"use\"]> &\n\t\t\t\t\tOmit<ContextTools, \"_flag\">\n\t\t\t>,\n\t\t) => Promise<R>,\n\t) => {\n\t\treturn createEndpoint(\n\t\t\tpath,\n\t\t\t{\n\t\t\t\t...options,\n\t\t\t\tuse: [...(options?.use || []), ...(opts?.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\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\tlet responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\n\tconst handle = async <C extends HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]>(\n\t\t...ctx: C\n\t) => {\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 cookieH = header?.get(\"cookie\");\n\t\t\t\tconst cookie = getCookie(cookieH || \"\", 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\tredirect(url: string) {\n\t\t\t\tresponseHeader.set(\"Location\", url);\n\t\t\t\treturn new APIError(\"FOUND\");\n\t\t\t},\n\t\t\tjson,\n\t\t\tcontext: (ctx[0] as any)?.context || {},\n\t\t\t_flag: (ctx[0] as any)?.asResponse ? \"router\" : (ctx[0] as any)?._flag,\n\t\t\tresponseHeader,\n\t\t\tpath: path,\n\t\t\t...(ctx[0] || {}),\n\t\t};\n\t\tif (options.use?.length) {\n\t\t\tlet middlewareContexts = {};\n\t\t\tlet middlewareBody = {};\n\t\t\tfor (const middleware of options.use) {\n\t\t\t\tif (typeof middleware !== \"function\") {\n\t\t\t\t\tconsole.warn(\"Middleware is not a function\", {\n\t\t\t\t\t\tmiddleware,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst res = (await middleware(internalCtx)) as Endpoint;\n\t\t\t\tif (res) {\n\t\t\t\t\tconst body = res.options?.body\n\t\t\t\t\t\t? res.options.body.parse(internalCtx.body)\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tmiddlewareContexts = {\n\t\t\t\t\t\t...middlewareContexts,\n\t\t\t\t\t\t...res,\n\t\t\t\t\t};\n\t\t\t\t\tmiddlewareBody = {\n\t\t\t\t\t\t...middlewareBody,\n\t\t\t\t\t\t...body,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tinternalCtx = {\n\t\t\t\t...internalCtx,\n\t\t\t\tbody: {\n\t\t\t\t\t...middlewareBody,\n\t\t\t\t\t...(internalCtx.body as Record<string, any>),\n\t\t\t\t},\n\t\t\t\tcontext: {\n\t\t\t\t\t...(internalCtx.context || {}),\n\t\t\t\t\t...middlewareContexts,\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 as Record<string, any>),\n\t\t\t\t\t\t}\n\t\t\t\t\t: internalCtx.body,\n\t\t\t};\n\t\t\tconsole.log(internalCtx.query);\n\t\t\tinternalCtx.query = options.query\n\t\t\t\t? options.query.parse(\n\t\t\t\t\t\tinternalCtx\n\t\t\t\t)\n\t\t\t\t: internalCtx.query;\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\ttry {\n\t\t\tlet res = (await handler(internalCtx as any)) as any;\n\t\t\tlet actualResponse: any = res;\n\n\t\t\tif (res && typeof res === \"object\" && \"_flag\" in res) {\n\t\t\t\tif (res._flag === \"json\" && internalCtx._flag === \"router\") {\n\t\t\t\t\tconst h = res.response.headers as Record<string, string>;\n\t\t\t\t\tObject.keys(h || {}).forEach((key) => {\n\t\t\t\t\t\tresponseHeader.set(key, h[key as keyof typeof h]);\n\t\t\t\t\t});\n\t\t\t\t\tresponseHeader.set(\"Content-Type\", \"application/json\");\n\t\t\t\t\tactualResponse = new Response(JSON.stringify(res.response.body), {\n\t\t\t\t\t\tstatus: res.response.status ?? 200,\n\t\t\t\t\t\tstatusText: res.response.statusText,\n\t\t\t\t\t\theaders: responseHeader,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tactualResponse = res.body;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponseHeader = new Headers();\n\n\t\t\ttype ReturnT = Awaited<ReturnType<Handler<Path, Opts, R>>>;\n\t\t\treturn actualResponse as C extends [{ asResponse: true }]\n\t\t\t\t? Response\n\t\t\t\t: R extends {\n\t\t\t\t\t\t\t_flag: \"json\";\n\t\t\t\t\t\t}\n\t\t\t\t\t? R extends { body: infer B }\n\t\t\t\t\t\t? B\n\t\t\t\t\t\t: null\n\t\t\t\t\t: ReturnT;\n\t\t} catch (e) {\n\t\t\tif (e instanceof APIError) {\n\t\t\t\tresponseHeader.set(\"Content-Type\", \"application/json\");\n\t\t\t\te.headers = responseHeader;\n\t\t\t\tresponseHeader = new Headers();\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\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 type { statusCode } from \"./utils\";\n\ntype Status = keyof typeof statusCode;\n\nexport class APIError extends Error {\n\tstatus: Status;\n\theaders: Headers;\n\tbody: Record<string, any>;\n\n\tconstructor(status: Status, body?: Record<string, any>, headers?: Headers) {\n\t\tsuper(`API Error: ${status} ${body?.message ?? \"\"}`, {\n\t\t\tcause: body,\n\t\t});\n\n\t\tthis.status = status;\n\t\tthis.body = body ?? {};\n\t\tthis.stack = \"\";\n\n\t\tthis.headers = headers ?? new Headers();\n\t\tif (!this.headers.has(\"Content-Type\")) {\n\t\t\tthis.headers.set(\"Content-Type\", \"application/json\");\n\t\t}\n\t\tthis.name = \"BetterCallAPIError\";\n\t}\n}\n","export type UnionToIntersection<Union> = (\n\tUnion extends unknown\n\t\t? (distributedUnion: Union) => void\n\t\t: never\n) extends (mergedIntersection: infer Intersection) => void\n\t? Intersection & Union\n\t: never;\n\nexport type RequiredKeysOf<BaseType extends object> = Exclude<\n\t{\n\t\t[Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]> ? Key : never;\n\t}[keyof BaseType],\n\tundefined\n>;\n\nexport type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never\n\t? false\n\t: true;\n\n/**\n * this function will return a json response and\n * infers the type of the body\n */\nexport const json = <T>(\n\tbody: T,\n\toption?: {\n\t\tstatus?: number;\n\t\tstatusText?: string;\n\t\theaders?: Record<string, string>;\n\t\t/**\n\t\t * this body will take precedence over the body in the options if both are provided.\n\t\t * This is useful if you want to return body without inferring the type.\n\t\t */\n\t\tbody?: any;\n\t},\n) => {\n\treturn {\n\t\tresponse: {\n\t\t\tbody: option?.body ?? body,\n\t\t\tstatus: option?.status ?? 200,\n\t\t\tstatusText: option?.statusText ?? \"OK\",\n\t\t\theaders: option?.headers,\n\t\t},\n\t\tbody,\n\t\t_flag: \"json\" as const,\n\t};\n};\n","//https://github.com/honojs/hono/blob/main/src/utils/cookie.ts\nimport { subtle } from \"uncrypto\";\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) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await 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 subtle.sign(algorithm.name, key, new TextEncoder().encode(value));\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 subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value));\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\topt.secure = true;\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\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\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\nexport const signCookieValue = async (value: string, secret: string | BufferSource) => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn value;\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) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\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\tconst existingCookies = header.get(\"Set-Cookie\");\n\tif (existingCookies) {\n\t\tconst cookies = existingCookies.split(\", \");\n\t\tconst updatedCookies = cookies.filter((cookie) => !cookie.startsWith(`${name}=`));\n\t\theader.delete(\"Set-Cookie\");\n\t\tupdatedCookies.forEach((cookie) => header.append(\"Set-Cookie\", cookie));\n\t}\n\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) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t}\n\t}\n\tconst obj = await parseSigned(cookie, secret, finalKey);\n\treturn obj[finalKey];\n};\n","import { createRouter as createRou3Router, addRoute, findRoute, findAllRoutes } from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./error\";\nimport type { Endpoint } 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\tonResponse?: (res: Response) => any | Promise<any>;\n\tonRequest?: (req: Request) => any | Promise<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 (endpoint.options.metadata?.SERVER_ONLY) continue;\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\tif (!path?.length) {\n\t\t\tconfig?.onError?.(new APIError(\"NOT_FOUND\"));\n\t\t\tconsole.warn(\n\t\t\t\t`[better-call]: Make sure the URL has the basePath (${config?.basePath}).`,\n\t\t\t);\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\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 routerMiddleware = findAllRoutes(middlewareRouter, \"*\", path);\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 (routerMiddleware?.length) {\n\t\t\t\tfor (const route of routerMiddleware) {\n\t\t\t\t\tconst middleware = route.data as Endpoint;\n\t\t\t\t\tconst res = await middleware({\n\t\t\t\t\t\tpath: path,\n\t\t\t\t\t\tmethod: method as \"GET\",\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tparams: route?.params as any,\n\t\t\t\t\t\trequest: request,\n\t\t\t\t\t\tbody: body,\n\t\t\t\t\t\tquery,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t...config?.extraContext,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tif (res instanceof Response) {\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tif (res?._flag === \"json\") {\n\t\t\t\t\t\treturn new Response(JSON.stringify(res), {\n\t\t\t\t\t\t\theaders: res.headers,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (res) {\n\t\t\t\t\t\tmiddlewareContext = {\n\t\t\t\t\t\t\t...res,\n\t\t\t\t\t\t\t...middlewareContext,\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\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_flag: \"router\",\n\t\t\t\tcontext: {\n\t\t\t\t\t...middlewareContext,\n\t\t\t\t\t...config?.extraContext,\n\t\t\t\t},\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: e.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: async (request: Request) => {\n\t\t\tconst onReq = await config?.onRequest?.(request);\n\t\t\tif (onReq instanceof Response) {\n\t\t\t\treturn onReq;\n\t\t\t}\n\t\t\tconst req = onReq instanceof Request ? onReq : request;\n\t\t\tconst res = await handler(req);\n\t\t\tconst onRes = await config?.onResponse?.(res);\n\t\t\tif (onRes instanceof Response) {\n\t\t\t\treturn onRes;\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\tendpoints,\n\t};\n};\n\nexport type Router = ReturnType<typeof createRouter>;\n","export async function getBody(request: Request) {\n\tconst contentType = request.headers.get(\"content-type\") || \"\";\n\n\tif (!request.body) {\n\t\treturn undefined;\n\t}\n\n\tif (contentType.includes(\"application/json\")) {\n\t\treturn await request.json();\n\t}\n\n\tif (contentType.includes(\"application/x-www-form-urlencoded\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, string> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value.toString();\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"multipart/form-data\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, any> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value;\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"text/plain\")) {\n\t\treturn await request.text();\n\t}\n\n\tif (contentType.includes(\"application/octet-stream\")) {\n\t\treturn await request.arrayBuffer();\n\t}\n\n\tif (\n\t\tcontentType.includes(\"application/pdf\") ||\n\t\tcontentType.includes(\"image/\") ||\n\t\tcontentType.includes(\"video/\")\n\t) {\n\t\tconst blob = await request.blob();\n\t\treturn blob;\n\t}\n\n\tif (contentType.includes(\"application/stream\") || request.body instanceof ReadableStream) {\n\t\treturn request.body;\n\t}\n\n\treturn await request.text();\n}\n\nexport function shouldSerialize(body: any) {\n\treturn (\n\t\ttypeof body === \"object\" &&\n\t\tbody !== null &&\n\t\t!(body instanceof Blob) &&\n\t\t!(body instanceof FormData)\n\t);\n}\n\nexport const statusCode = {\n\tOK: 200,\n\tCREATED: 201,\n\tACCEPTED: 202,\n\tNO_CONTENT: 204,\n\tMULTIPLE_CHOICES: 300,\n\tMOVED_PERMANENTLY: 301,\n\tFOUND: 302,\n\tSEE_OTHER: 303,\n\tNOT_MODIFIED: 304,\n\tTEMPORARY_REDIRECT: 307,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_ALLOWED: 405,\n\tNOT_ACCEPTABLE: 406,\n\tPROXY_AUTHENTICATION_REQUIRED: 407,\n\tREQUEST_TIMEOUT: 408,\n\tCONFLICT: 409,\n\tGONE: 410,\n\tLENGTH_REQUIRED: 411,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tURI_TOO_LONG: 414,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tEXPECTATION_FAILED: 417,\n\t\"I'M_A_TEAPOT\": 418,\n\tMISDIRECTED_REQUEST: 421,\n\tUNPROCESSABLE_ENTITY: 422,\n\tLOCKED: 423,\n\tFAILED_DEPENDENCY: 424,\n\tTOO_EARLY: 425,\n\tUPGRADE_REQUIRED: 426,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tREQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n\tUNAVAILABLE_FOR_LEGAL_REASONS: 451,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504,\n\tHTTP_VERSION_NOT_SUPPORTED: 505,\n\tVARIANT_ALSO_NEGOTIATES: 506,\n\tINSUFFICIENT_STORAGE: 507,\n\tLOOP_DETECTED: 508,\n\tNOT_EXTENDED: 510,\n\tNETWORK_AUTHENTICATION_REQUIRED: 511,\n};\n","import type {\n\tContextTools,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n\tInferBody,\n\tInferHeaders,\n\tInferRequest,\n\tInferUse,\n\tPrettify,\n} from \"./types\";\nimport { createEndpoint } from \"./endpoint\";\n\nexport type MiddlewareHandler<\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n\tExtra extends Record<string, any> = {},\n> = (\n\tctx: Prettify<\n\t\tInferBody<Opts> &\n\t\t\tInferRequest<Opts> &\n\t\t\tInferHeaders<Opts> & {\n\t\t\t\tparams?: Record<string, string>;\n\t\t\t\tquery?: Record<string, string>;\n\t\t\t} & ContextTools\n\t> &\n\t\tExtra,\n) => Promise<R>;\n\nexport function createMiddleware<Opts extends EndpointOptions, R extends EndpointResponse>(\n\toptionsOrHandler: MiddlewareHandler<Opts, R>,\n): Endpoint<Handler<string, Opts, R>, Opts>;\nexport function createMiddleware<\n\tOpts extends Omit<EndpointOptions, \"method\">,\n\tR extends EndpointResponse,\n>(\n\toptionsOrHandler: Opts,\n\thandler: MiddlewareHandler<\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t},\n\t\tR\n\t>,\n): Endpoint<\n\tHandler<\n\t\tstring,\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t},\n\t\tR\n\t>,\n\tOpts & {\n\t\tmethod: \"*\";\n\t}\n>;\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n\tif (typeof optionsOrHandler === \"function\") {\n\t\treturn createEndpoint(\n\t\t\t\"*\",\n\t\t\t{\n\t\t\t\tmethod: \"*\",\n\t\t\t},\n\t\t\toptionsOrHandler,\n\t\t);\n\t}\n\tif (!handler) {\n\t\tthrow new Error(\"Middleware handler is required\");\n\t}\n\tconst endpoint = createEndpoint(\n\t\t\"*\",\n\t\t{\n\t\t\t...optionsOrHandler,\n\t\t\tmethod: \"*\",\n\t\t},\n\t\thandler,\n\t);\n\treturn endpoint as any;\n}\n\nexport const createMiddlewareCreator = <\n\tE extends {\n\t\tuse?: Endpoint[];\n\t},\n>(\n\topts?: E,\n) => {\n\ttype H<Opts extends EndpointOptions, R extends EndpointResponse> = (\n\t\tctx: Prettify<\n\t\t\tInferBody<Opts> &\n\t\t\t\tInferUse<E[\"use\"]> &\n\t\t\t\tInferRequest<Opts> &\n\t\t\t\tInferHeaders<Opts> & {\n\t\t\t\t\tparams?: Record<string, string>;\n\t\t\t\t\tquery?: Record<string, string>;\n\t\t\t\t} & ContextTools\n\t\t>,\n\t) => Promise<R>;\n\tfunction fn<Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\toptionsOrHandler: H<Opts, R>,\n\t): Endpoint<Handler<string, Opts, R>, Opts>;\n\tfunction fn<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(\n\t\toptionsOrHandler: Opts,\n\t\thandler: H<\n\t\t\tOpts & {\n\t\t\t\tmethod: \"*\";\n\t\t\t},\n\t\t\tR\n\t\t>,\n\t): Endpoint<\n\t\tHandler<\n\t\t\tstring,\n\t\t\tOpts & {\n\t\t\t\tmethod: \"*\";\n\t\t\t},\n\t\t\tR\n\t\t>,\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t}\n\t>;\n\tfunction fn(optionsOrHandler: any, handler?: any) {\n\t\tif (typeof optionsOrHandler === \"function\") {\n\t\t\treturn createEndpoint(\n\t\t\t\t\"*\",\n\t\t\t\t{\n\t\t\t\t\tmethod: \"*\",\n\t\t\t\t},\n\t\t\t\toptionsOrHandler,\n\t\t\t);\n\t\t}\n\t\tif (!handler) {\n\t\t\tthrow new Error(\"Middleware handler is required\");\n\t\t}\n\t\tconst endpoint = createEndpoint(\n\t\t\t\"*\",\n\t\t\t{\n\t\t\t\t...optionsOrHandler,\n\t\t\t\tmethod: \"*\",\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t\treturn endpoint as any;\n\t}\n\treturn fn;\n};\n\nexport type Middleware<\n\tOpts extends EndpointOptions = EndpointOptions,\n\tR extends EndpointResponse = EndpointResponse,\n> = (\n\topts: Opts,\n\thandler: (ctx: {\n\t\tbody?: InferBody<Opts>;\n\t\tparams?: Record<string, string>;\n\t\tquery?: Record<string, string>;\n\t}) => Promise<R>,\n) => Endpoint;\n","import { z, type ZodOptional, type ZodSchema } from \"zod\";\nimport type { json, UnionToIntersection } from \"./helper\";\nimport type { CookieOptions, CookiePrefixOptions } from \"./cookie\";\nimport type { APIError } from \"./error\";\n\nexport interface EndpointOptions {\n\t/**\n\t * Request Method\n\t */\n\tmethod: Method | Method[];\n\t/**\n\t * Body Schema\n\t */\n\tbody?: ZodSchema;\n\t/**\n\t * Query Schema\n\t */\n\tquery?: ZodSchema;\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\t/**\n\t * Endpoint metadata\n\t */\n\tmetadata?:\n\t\t| Record<string, any>\n\t\t| {\n\t\t\t\t/**\n\t\t\t\t * If true this endpoint will only be available on the server\n\t\t\t\t */\n\t\t\t\tSERVER_ONLY?: boolean;\n\t\t\t\t/**\n\t\t\t\t * A helper to infer the body and query schema.\n\t\t\t\t */\n\t\t\t\t$Infer?: {\n\t\t\t\t\tbody?: Record<string, any>;\n\t\t\t\t\tquery?: Record<string, any>;\n\t\t\t\t};\n\t\t };\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 type ContextTools = {\n\t/**\n\t * the current path\n\t */\n\tpath: string;\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, prefix?: CookiePrefixOptions) => 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\t/**\n\t * Redirect to url\n\t */\n\tredirect: (url: string) => APIError;\n\t/**\n\t * json response helper\n\t */\n\tjson: typeof json;\n\t/**\n\t * response header\n\t */\n\tresponseHeader: Headers;\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\t\t/**\n\t\t * This is used internally.\n\t\t * But you can use it to change the response form.\n\t\t *\n\t\t * - `json` will be set only when using `ctx.json` helper.\n\t\t * - `router` will be set when the handler is called from the router.\n\t\t * You can use this to change the response form to be a `Response` object.\n\t\t * - `default` will be used normally when the handler is called as a normal function.\n\t\t *\n\t\t * @internal\n\t\t */\n\t\t_flag?: \"json\" | \"router\" | \"default\";\n\t\t/**\n\t\t * Force the response to be a `Response` object.\n\t\t */\n\t\tasResponse?: boolean;\n\t};\n\nexport type InferUse<Opts extends EndpointOptions[\"use\"]> = Opts extends Endpoint[]\n\t? {\n\t\t\tcontext: UnionToIntersection<Awaited<ReturnType<Opts[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 EndpointBody =\n\t| Record<string, any>\n\t| string\n\t| boolean\n\t| number\n\t| void\n\t| undefined\n\t| null\n\t| unknown;\n\nexport type EndpointResponse =\n\t| {\n\t\t\tresponse: {\n\t\t\t\tstatus?: number;\n\t\t\t\tstatusText?: string;\n\t\t\t\theaders?: Headers;\n\t\t\t\tbody: any;\n\t\t\t};\n\t\t\tbody: EndpointBody;\n\t\t\t_flag: \"json\";\n\t }\n\t| EndpointBody;\n\nexport type Handler<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts[\"use\"]> & ContextTools>) => 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> = Opts[\"metadata\"] extends {\n\t$Infer: {\n\t\tbody: infer B;\n\t};\n}\n\t? {\n\t\t\tbody: B;\n\t\t}\n\t: Body extends ZodSchema\n\t\t? Body extends ZodOptional<any>\n\t\t\t? {\n\t\t\t\t\tbody?: Prettify<z.infer<Body>>;\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tbody: Prettify<z.infer<Body>>;\n\t\t\t\t}\n\t\t: {\n\t\t\t\tbody?: undefined;\n\t\t\t};\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport * as set_cookie_parser from \"set-cookie-parser\";\n\nfunction get_raw_body(req: IncomingMessage, body_size_limit?: number) {\n\tconst h = req.headers;\n\n\tif (!h[\"content-type\"]) return null;\n\n\tconst content_length = Number(h[\"content-length\"]);\n\n\t// check if no request body\n\tif (\n\t\t(req.httpVersionMajor === 1 && isNaN(content_length) && h[\"transfer-encoding\"] == null) ||\n\t\tcontent_length === 0\n\t) {\n\t\treturn null;\n\t}\n\n\tlet length = content_length;\n\n\tif (body_size_limit) {\n\t\tif (!length) {\n\t\t\tlength = body_size_limit;\n\t\t} else if (length > body_size_limit) {\n\t\t\tthrow Error(\n\t\t\t\t`Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tif (req.destroyed) {\n\t\tconst readable = new ReadableStream();\n\t\treadable.cancel();\n\t\treturn readable;\n\t}\n\n\tlet size = 0;\n\tlet cancelled = false;\n\n\treturn new ReadableStream({\n\t\tstart(controller) {\n\t\t\treq.on(\"error\", (error) => {\n\t\t\t\tcancelled = true;\n\t\t\t\tcontroller.error(error);\n\t\t\t});\n\n\t\t\treq.on(\"end\", () => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\tcontroller.close();\n\t\t\t});\n\n\t\t\treq.on(\"data\", (chunk) => {\n\t\t\t\tif (cancelled) return;\n\n\t\t\t\tsize += chunk.length;\n\n\t\t\t\tif (size > length) {\n\t\t\t\t\tcancelled = true;\n\n\t\t\t\t\tcontroller.error(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`request body size exceeded ${\n\t\t\t\t\t\t\t\tcontent_length ? \"'content-length'\" : \"BODY_SIZE_LIMIT\"\n\t\t\t\t\t\t\t} of ${length}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tcontroller.enqueue(chunk);\n\n\t\t\t\tif (controller.desiredSize === null || controller.desiredSize <= 0) {\n\t\t\t\t\treq.pause();\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\tpull() {\n\t\t\treq.resume();\n\t\t},\n\n\t\tcancel(reason) {\n\t\t\tcancelled = true;\n\t\t\treq.destroy(reason);\n\t\t},\n\t});\n}\n\nexport function getRequest({\n\trequest,\n\tbase,\n\tbodySizeLimit,\n}: {\n\tbase: string;\n\tbodySizeLimit?: number;\n\trequest: IncomingMessage;\n}) {\n\treturn new Request(base + request.url, {\n\t\t// @ts-expect-error\n\t\tduplex: \"half\",\n\t\tmethod: request.method,\n\t\tbody: get_raw_body(request, bodySizeLimit),\n\t\theaders: request.headers as Record<string, string>,\n\t});\n}\n\nexport async function setResponse(res: ServerResponse, response: Response) {\n\tfor (const [key, value] of response.headers as any) {\n\t\ttry {\n\t\t\tres.setHeader(\n\t\t\t\tkey,\n\t\t\t\tkey === \"set-cookie\"\n\t\t\t\t\t? set_cookie_parser.splitCookiesString(response.headers.get(key) as string)\n\t\t\t\t\t: value,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tres.getHeaderNames().forEach((name) => res.removeHeader(name));\n\t\t\tres.writeHead(500).end(String(error));\n\t\t\treturn;\n\t\t}\n\t}\n\n\tres.writeHead(response.status);\n\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\n\tif (response.body.locked) {\n\t\tres.end(\n\t\t\t\"Fatal error: Response body is locked. \" +\n\t\t\t\t\"This can happen when the response was already read (for example through 'response.json()' or 'response.text()').\",\n\t\t);\n\t\treturn;\n\t}\n\n\tconst reader = response.body.getReader();\n\n\tif (res.destroyed) {\n\t\treader.cancel();\n\t\treturn;\n\t}\n\n\tconst cancel = (error?: Error) => {\n\t\tres.off(\"close\", cancel);\n\t\tres.off(\"error\", cancel);\n\n\t\t// If the reader has already been interrupted with an error earlier,\n\t\t// then it will appear here, it is useless, but it needs to be catch.\n\t\treader.cancel(error).catch(() => {});\n\t\tif (error) res.destroy(error);\n\t};\n\n\tres.on(\"close\", cancel);\n\tres.on(\"error\", cancel);\n\n\tnext();\n\tasync function next() {\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (!res.write(value)) {\n\t\t\t\t\tres.once(\"drain\", next);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tres.end();\n\t\t} catch (error) {\n\t\t\tcancel(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { getRequest, setResponse } from \"./request.js\";\nimport type { Router } from \"../router.js\";\n\nexport function toNodeHandler(handler: Router[\"handler\"]) {\n\treturn async (req: IncomingMessage, res: ServerResponse) => {\n\t\tconst protocol = (req.connection as any)?.encrypted ? \"https\" : \"http\";\n\t\tconst base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n\t\tconst response = await handler(getRequest({ base, request: req }));\n\t\tsetResponse(res, response);\n\t};\n}\n\nexport { getRequest, setResponse };\n"],"mappings":";;;;;AACA,SAAS,gBAAgB;;;ACGlB,IAAM,WAAN,cAAuB,MAAM;AAAA,EAKnC,YAAY,QAAgB,MAA4B,SAAmB;AAC1E,UAAM,cAAc,MAAM,IAAI,MAAM,WAAW,EAAE,IAAI;AAAA,MACpD,OAAO;AAAA,IACR,CAAC;AAPF;AACA;AACA;AAOC,SAAK,SAAS;AACd,SAAK,OAAO,QAAQ,CAAC;AACrB,SAAK,QAAQ;AAEb,SAAK,UAAU,WAAW,IAAI,QAAQ;AACtC,QAAI,CAAC,KAAK,QAAQ,IAAI,cAAc,GAAG;AACtC,WAAK,QAAQ,IAAI,gBAAgB,kBAAkB;AAAA,IACpD;AACA,SAAK,OAAO;AAAA,EACb;AACD;;;ACDO,IAAM,OAAO,CACnB,MACA,WAUI;AACJ,SAAO;AAAA,IACN,UAAU;AAAA,MACT,MAAM,QAAQ,QAAQ;AAAA,MACtB,QAAQ,QAAQ,UAAU;AAAA,MAC1B,YAAY,QAAQ,cAAc;AAAA,MAClC,SAAS,QAAQ;AAAA,IAClB;AAAA,IACA;AAAA,IACA,OAAO;AAAA,EACR;AACD;;;AC7CA,SAAS,cAAc;AA+BvB,IAAM,YAAY,EAAE,MAAM,QAAQ,MAAM,UAAU;AAElD,IAAM,eAAe,OAAO,WAAkC;AAC7D,QAAM,YAAY,OAAO,WAAW,WAAW,IAAI,YAAY,EAAE,OAAO,MAAM,IAAI;AAClF,SAAO,MAAM,OAAO,UAAU,OAAO,WAAW,WAAW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AI,MAAM,OAAO,KAAK,CAAC,CAAC;AAAA,IACjE;AAAA,EACD;AACD;;;AC1KO,SAAS,cAAc,SAA4B;AACzD,SAAO,OAAO,KAAsB,QAAwB;AAC3D,UAAM,WAAY,IAAI,YAAoB,YAAY,UAAU;AAChE,UAAM,OAAO,GAAG,QAAQ,MAAM,IAAI,QAAQ,YAAY,KAAK,IAAI,QAAQ,IAAI;AAC3E,UAAM,WAAW,MAAM,QAAQ,WAAW,EAAE,MAAM,SAAS,IAAI,CAAC,CAAC;AACjE,gBAAY,KAAK,QAAQ;AAAA,EAC1B;AACD;","names":["cookie","options","handler","route"]}
@@ -64,6 +64,7 @@ declare const parse: (cookie: string, name?: string) => Cookie;
64
64
  declare const parseSigned: (cookie: string, secret: string | BufferSource, name?: string) => Promise<SignedCookie>;
65
65
  declare const serialize: <Name extends string>(name: Name, value: string, opt?: CookieConstraint<Name>) => string;
66
66
  declare const serializeSigned: (name: string, value: string, secret: string | BufferSource, opt?: CookieOptions) => Promise<string>;
67
+ declare const signCookieValue: (value: string, secret: string | BufferSource) => Promise<string>;
67
68
 
68
69
  declare function getBody(request: Request): Promise<any>;
69
70
  declare function shouldSerialize(body: any): boolean;
@@ -161,6 +162,13 @@ interface EndpointOptions {
161
162
  * If true this endpoint will only be available on the server
162
163
  */
163
164
  SERVER_ONLY?: boolean;
165
+ /**
166
+ * A helper to infer the body and query schema.
167
+ */
168
+ $Infer?: {
169
+ body?: Record<string, any>;
170
+ query?: Record<string, any>;
171
+ };
164
172
  };
165
173
  }
166
174
  type Endpoint<Handler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>, Option extends EndpointOptions = EndpointOptions> = {
@@ -301,7 +309,13 @@ type EndpointResponse = {
301
309
  } | EndpointBody;
302
310
  type Handler<Path extends string, Opts extends EndpointOptions, R extends EndpointResponse> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts["use"]> & ContextTools>) => Promise<R>;
303
311
  type Method = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "*";
304
- type InferBody<Opts extends EndpointOptions, Body extends ZodSchema | undefined = Opts["body"] & (undefined extends InferUseOptions<Opts>["body"] ? {} : InferUseOptions<Opts>["body"])> = Body extends ZodSchema ? Body extends ZodOptional<any> ? {
312
+ type InferBody<Opts extends EndpointOptions, Body extends ZodSchema | undefined = Opts["body"] & (undefined extends InferUseOptions<Opts>["body"] ? {} : InferUseOptions<Opts>["body"])> = Opts["metadata"] extends {
313
+ $Infer: {
314
+ body: infer B;
315
+ };
316
+ } ? {
317
+ body: B;
318
+ } : Body extends ZodSchema ? Body extends ZodOptional<any> ? {
305
319
  body?: Prettify<z.infer<Body>>;
306
320
  } : {
307
321
  body: Prettify<z.infer<Body>>;
@@ -339,4 +353,4 @@ declare const createRouter: <E extends Record<string, Endpoint>, Config extends
339
353
  };
340
354
  type Router = ReturnType<typeof createRouter>;
341
355
 
342
- export { APIError as A, type Context as C, type Endpoint as E, type HasRequiredKeys as H, type InferUse as I, type Method as M, type Prettify as P, type Router as R, type SignedCookie as S, type UnionToIntersection as U, type EndpointOptions as a, type EndpointResponse as b, type ContextTools as c, type Handler as d, type InferBody as e, type InferRequest as f, type InferHeaders as g, type InferUseOptions as h, type CookiePrefixOptions as i, type CookieOptions as j, createRouter as k, getBody as l, statusCode as m, type InferParamPath as n, type InferParamWildCard as o, type InferMethod as p, type InferQuery as q, type InferParam as r, shouldSerialize as s, type EndpointBody as t, type Cookie as u, type CookieConstraint as v, parse as w, parseSigned as x, serialize as y, serializeSigned as z };
356
+ export { APIError as A, signCookieValue as B, type Context as C, type Endpoint as E, type HasRequiredKeys as H, type InferUse as I, type Method as M, type Prettify as P, type Router as R, type SignedCookie as S, type UnionToIntersection as U, type EndpointOptions as a, type EndpointResponse as b, type ContextTools as c, type Handler as d, type InferBody as e, type InferRequest as f, type InferHeaders as g, type InferUseOptions as h, type CookiePrefixOptions as i, type CookieOptions as j, createRouter as k, getBody as l, statusCode as m, type InferParamPath as n, type InferParamWildCard as o, type InferMethod as p, type InferQuery as q, type InferParam as r, shouldSerialize as s, type EndpointBody as t, type Cookie as u, type CookieConstraint as v, parse as w, parseSigned as x, serialize as y, serializeSigned as z };
@@ -64,6 +64,7 @@ declare const parse: (cookie: string, name?: string) => Cookie;
64
64
  declare const parseSigned: (cookie: string, secret: string | BufferSource, name?: string) => Promise<SignedCookie>;
65
65
  declare const serialize: <Name extends string>(name: Name, value: string, opt?: CookieConstraint<Name>) => string;
66
66
  declare const serializeSigned: (name: string, value: string, secret: string | BufferSource, opt?: CookieOptions) => Promise<string>;
67
+ declare const signCookieValue: (value: string, secret: string | BufferSource) => Promise<string>;
67
68
 
68
69
  declare function getBody(request: Request): Promise<any>;
69
70
  declare function shouldSerialize(body: any): boolean;
@@ -161,6 +162,13 @@ interface EndpointOptions {
161
162
  * If true this endpoint will only be available on the server
162
163
  */
163
164
  SERVER_ONLY?: boolean;
165
+ /**
166
+ * A helper to infer the body and query schema.
167
+ */
168
+ $Infer?: {
169
+ body?: Record<string, any>;
170
+ query?: Record<string, any>;
171
+ };
164
172
  };
165
173
  }
166
174
  type Endpoint<Handler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>, Option extends EndpointOptions = EndpointOptions> = {
@@ -301,7 +309,13 @@ type EndpointResponse = {
301
309
  } | EndpointBody;
302
310
  type Handler<Path extends string, Opts extends EndpointOptions, R extends EndpointResponse> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts["use"]> & ContextTools>) => Promise<R>;
303
311
  type Method = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "*";
304
- type InferBody<Opts extends EndpointOptions, Body extends ZodSchema | undefined = Opts["body"] & (undefined extends InferUseOptions<Opts>["body"] ? {} : InferUseOptions<Opts>["body"])> = Body extends ZodSchema ? Body extends ZodOptional<any> ? {
312
+ type InferBody<Opts extends EndpointOptions, Body extends ZodSchema | undefined = Opts["body"] & (undefined extends InferUseOptions<Opts>["body"] ? {} : InferUseOptions<Opts>["body"])> = Opts["metadata"] extends {
313
+ $Infer: {
314
+ body: infer B;
315
+ };
316
+ } ? {
317
+ body: B;
318
+ } : Body extends ZodSchema ? Body extends ZodOptional<any> ? {
305
319
  body?: Prettify<z.infer<Body>>;
306
320
  } : {
307
321
  body: Prettify<z.infer<Body>>;
@@ -339,4 +353,4 @@ declare const createRouter: <E extends Record<string, Endpoint>, Config extends
339
353
  };
340
354
  type Router = ReturnType<typeof createRouter>;
341
355
 
342
- export { APIError as A, type Context as C, type Endpoint as E, type HasRequiredKeys as H, type InferUse as I, type Method as M, type Prettify as P, type Router as R, type SignedCookie as S, type UnionToIntersection as U, type EndpointOptions as a, type EndpointResponse as b, type ContextTools as c, type Handler as d, type InferBody as e, type InferRequest as f, type InferHeaders as g, type InferUseOptions as h, type CookiePrefixOptions as i, type CookieOptions as j, createRouter as k, getBody as l, statusCode as m, type InferParamPath as n, type InferParamWildCard as o, type InferMethod as p, type InferQuery as q, type InferParam as r, shouldSerialize as s, type EndpointBody as t, type Cookie as u, type CookieConstraint as v, parse as w, parseSigned as x, serialize as y, serializeSigned as z };
356
+ export { APIError as A, signCookieValue as B, type Context as C, type Endpoint as E, type HasRequiredKeys as H, type InferUse as I, type Method as M, type Prettify as P, type Router as R, type SignedCookie as S, type UnionToIntersection as U, type EndpointOptions as a, type EndpointResponse as b, type ContextTools as c, type Handler as d, type InferBody as e, type InferRequest as f, type InferHeaders as g, type InferUseOptions as h, type CookiePrefixOptions as i, type CookieOptions as j, createRouter as k, getBody as l, statusCode as m, type InferParamPath as n, type InferParamWildCard as o, type InferMethod as p, type InferQuery as q, type InferParam as r, shouldSerialize as s, type EndpointBody as t, type Cookie as u, type CookieConstraint as v, parse as w, parseSigned as x, serialize as y, serializeSigned as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "better-call",
3
- "version": "0.2.14-beta.2",
3
+ "version": "0.2.14",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -35,22 +35,22 @@
35
35
  "exports": {
36
36
  ".": {
37
37
  "import": {
38
- "default": "./dist/index.js",
39
- "types": "./dist/index.d.ts"
38
+ "types": "./dist/index.d.ts",
39
+ "default": "./dist/index.js"
40
40
  },
41
41
  "require": {
42
- "default": "./dist/index.cjs",
43
- "types": "./dist/index.d.cts"
42
+ "types": "./dist/index.d.cts",
43
+ "default": "./dist/index.cjs"
44
44
  }
45
45
  },
46
46
  "./client": {
47
47
  "import": {
48
- "default": "./dist/client.js",
49
- "types": "./dist/client.d.ts"
48
+ "types": "./dist/client.d.ts",
49
+ "default": "./dist/client.js"
50
50
  },
51
51
  "require": {
52
- "default": "./dist/client.cjs",
53
- "types": "./dist/client.d.cts"
52
+ "types": "./dist/client.d.cts",
53
+ "default": "./dist/client.cjs"
54
54
  }
55
55
  }
56
56
  },