better-call 0.0.5-beta.8 → 0.1.0

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/endpoint.ts","../src/middleware.ts","../src/better-call-error.ts","../src/router.ts","../src/utils.ts"],"sourcesContent":["export * from \"./endpoint\"\nexport * from \"./router\"\nexport * from \"./middleware\"\nexport * from \"./better-call-error\"\nexport * from \"./utils\"","import { z, ZodError, type ZodOptional, type ZodSchema } from \"zod\"\nimport { createMiddleware, type Middleware } from \"./middleware\"\nimport { APIError } from \"./better-call-error\";\nimport type { HasRequiredKeys, UnionToIntersection } from \"./helper\";\nimport type { Context, ContextTools, Endpoint, EndpointOptions, EndpointResponse, Handler } from \"./types\";\n\n\nexport interface EndpointConfig {\n /**\n * Throw when the response isn't in 200 range\n */\n throwOnError?: boolean\n}\n\nexport function createEndpointCreator<T extends Record<string, any>>() {\n return <Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(path: Path, options: Opts, handler: Handler<Path, Opts, R, T>) => {\n //@ts-expect-error\n return createEndpoint(path, options, handler)\n }\n\n}\n\nexport function createEndpoint<Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(path: Path, options: Opts, handler: Handler<Path, Opts, R>) {\n const responseHeader = new Headers()\n type Ctx = Context<Path, Opts>\n const handle = async (...ctx: HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]) => {\n let internalCtx = ({\n setHeader(key: string, value: string) {\n responseHeader.set(key, value)\n },\n setCookie(key: string, value: string) {\n responseHeader.append(\"Set-Cookie\", `${key}=${value}`)\n },\n getCookie(key: string) {\n const header = ctx[0]?.headers\n return header?.get(\"cookie\")?.split(\";\").find(cookie => cookie.startsWith(`${key}=`))?.split(\"=\")[1]\n },\n ...(ctx[0] || {}),\n context: {}\n })\n if (options.use?.length) {\n for (const middleware of options.use) {\n const res = await middleware(internalCtx) as Endpoint\n const body = res.options?.body ? res.options.body.parse(internalCtx.body) : undefined\n if (res) {\n internalCtx = {\n ...internalCtx,\n body: body ? {\n ...body,\n ...internalCtx.body\n } : internalCtx.body,\n context: {\n ...internalCtx.context || {},\n ...res\n }\n }\n }\n }\n }\n try {\n const body = options.body ? options.body.parse(internalCtx.body) : internalCtx.body\n internalCtx = {\n ...internalCtx,\n body: body ? {\n ...body,\n ...internalCtx.body\n } : internalCtx.body,\n }\n internalCtx.query = options.query ? options.query.parse(internalCtx.query) : internalCtx.query\n internalCtx.params = options.params ? options.params.parse(internalCtx.params) : internalCtx.params\n } catch (e) {\n if (e instanceof ZodError) {\n throw new APIError(\"BAD_REQUEST\", {\n message: e.message,\n details: e.errors\n })\n }\n throw e\n }\n if (options.requireHeaders && !internalCtx.headers) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Headers are required\"\n })\n }\n if (options.requireRequest && !internalCtx.request) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Request is required\"\n })\n }\n //@ts-expect-error\n const res = await handler(internalCtx)\n return res as ReturnType<Handler<Path, Opts, R>>\n }\n handle.path = path\n handle.options = options\n handle.method = options.method\n handle.headers = responseHeader\n return handle\n}","import { z } from \"zod\"\nimport type { ContextTools, Endpoint, EndpointOptions, EndpointResponse, Handler, InferBody, InferHeaders, InferRequest, Prettify } from \"./types\"\nimport { createEndpoint } from \"./endpoint\"\n\nexport type MiddlewareHandler<Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<InferBody<Opts> & InferRequest<Opts> & InferHeaders<Opts> & {\n params?: Record<string, string>,\n query?: Record<string, string>,\n} & ContextTools> & Extra) => Promise<R>\n\nexport function createMiddleware<Opts extends EndpointOptions, R extends EndpointResponse>(optionsOrHandler: MiddlewareHandler<Opts, R>): Endpoint<Handler<string, Opts, R>, Opts>\nexport function createMiddleware<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(optionsOrHandler: Opts, handler: MiddlewareHandler<Opts & {\n method: \"*\"\n}, R>): Endpoint<Handler<string, Opts & {\n method: \"*\"\n}, R>, Opts & {\n method: \"*\"\n}>\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n if (typeof optionsOrHandler === \"function\") {\n return createEndpoint(\"*\", {\n method: \"*\"\n }, optionsOrHandler)\n }\n if (!handler) {\n throw new Error(\"Middleware handler is required\")\n }\n const endpoint = createEndpoint(\"*\", {\n ...optionsOrHandler,\n method: \"*\"\n }, handler)\n return endpoint as any\n}\n\nexport const createMiddlewareCreator = <ExtraContext extends Record<string, any> = {}>() => {\n function fn<Opts extends EndpointOptions, R extends EndpointResponse>(optionsOrHandler: MiddlewareHandler<Opts, R, ExtraContext>): Endpoint<Handler<string, Opts, R>, Opts>\n function fn<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(optionsOrHandler: Opts, handler: MiddlewareHandler<Opts & {\n method: \"*\"\n }, R, ExtraContext>): Endpoint<Handler<string, Opts & {\n method: \"*\"\n }, R>, Opts & {\n method: \"*\"\n }>\n function fn(optionsOrHandler: any, handler?: any) {\n if (typeof optionsOrHandler === \"function\") {\n return createEndpoint(\"*\", {\n method: \"*\"\n }, optionsOrHandler)\n }\n if (!handler) {\n throw new Error(\"Middleware handler is required\")\n }\n const endpoint = createEndpoint(\"*\", {\n ...optionsOrHandler,\n method: \"*\"\n }, handler)\n return endpoint as any\n }\n return fn\n}\n\nexport type Middleware<Opts extends EndpointOptions = EndpointOptions, R extends EndpointResponse = EndpointResponse> = (opts: Opts, handler: (ctx: {\n body?: InferBody<Opts>,\n params?: Record<string, string>,\n query?: Record<string, string>\n}) => Promise<R>) => Endpoint","import type { statusCode } from \"./utils\"\n\ntype Status = keyof typeof statusCode\n\nexport class APIError extends Error {\n status: Status\n body: Record<string, any>\n constructor(\n status: Status,\n body?: Record<string, any>,\n ) {\n super(\n `API Error: ${status} ${body?.message ?? \"\"}`,\n {\n cause: body,\n }\n )\n this.status = status\n this.body = body ?? {}\n this.stack = \"\";\n this.name = \"BetterCallAPIError\"\n }\n}","import {\n createRouter as createRou3Router,\n addRoute,\n findRoute,\n} from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./better-call-error\";\nimport type { Middleware, MiddlewareHandler } from \"./middleware\";\nimport type { Endpoint, Method } from \"./types\";\n\ninterface RouterConfig {\n /**\n * Throw error if error occurred other than APIError\n */\n throwError?: boolean\n /**\n * Handle error\n */\n onError?: (e: unknown) => void | Promise<void> | Response | Promise<Response>\n /**\n * Base path for the router\n */\n basePath?: string\n /**\n * Middlewares for the router\n */\n routerMiddleware?: {\n path: string,\n middleware: Endpoint\n }[]\n}\n\nexport const createRouter = <E extends Endpoint, Config extends RouterConfig>(endpoints: E[], config?: Config) => {\n const router = createRou3Router()\n for (const endpoint of endpoints) {\n if (Array.isArray(endpoint.options?.method)) {\n for (const method of endpoint.options.method) {\n addRoute(router, method, endpoint.path, endpoint)\n }\n } else {\n addRoute(router, endpoint.options.method, endpoint.path, endpoint)\n }\n }\n\n const middlewareRouter = createRou3Router()\n for (const route of (config?.routerMiddleware || [])) {\n addRoute(middlewareRouter, \"*\", route.path, route.middleware)\n }\n\n const handler = async (request: Request) => {\n const url = new URL(request.url);\n let path = url.pathname\n if (config?.basePath) {\n path = path.split(config.basePath)[1]\n }\n const method = request.method;\n const route = findRoute(router, method, path)\n const handler = route?.data as Endpoint\n const body = await getBody(request)\n const headers = request.headers\n const query = Object.fromEntries(url.searchParams)\n const middleware = findRoute(middlewareRouter, \"*\", path)?.data as Endpoint | undefined\n //handler 404\n if (!handler) {\n return new Response(null, {\n status: 404,\n statusText: \"Not Found\"\n })\n }\n try {\n let middlewareContext: Record<string, any> = {}\n if (middleware) {\n const res = await middleware({\n path: path,\n method: method as \"GET\",\n headers,\n params: route?.params as any,\n request: request,\n body: body,\n query\n })\n if (res) {\n middlewareContext = {\n ...res,\n ...middlewareContext\n }\n }\n }\n const handlerRes = await handler({\n path: path,\n method: method as \"GET\",\n headers,\n params: route?.params as any,\n request: request,\n body: body,\n query,\n ...middlewareContext,\n })\n if (handlerRes instanceof Response) {\n return handlerRes\n }\n const resBody = shouldSerialize(handlerRes) ? JSON.stringify(handlerRes) : handlerRes\n return new Response(resBody as any, {\n headers: handler.headers\n })\n } catch (e) {\n if (config?.onError) {\n const onErrorRes = await config.onError(e)\n if (onErrorRes instanceof Response) {\n return onErrorRes\n }\n }\n if (e instanceof APIError) {\n return new Response(e.body ? JSON.stringify(e.body) : null, {\n status: statusCode[e.status],\n statusText: e.status,\n headers: {\n \"Content-Type\": \"application/json\",\n }\n })\n }\n if (config?.throwError) {\n throw e\n }\n return new Response(null, {\n status: 500,\n statusText: \"Internal Server Error\"\n })\n }\n }\n return {\n handler\n }\n}","export async function getBody(request: Request) {\n const contentType = request.headers.get('content-type') || '';\n\n if (!request.body) {\n return undefined\n }\n\n if (contentType.includes('application/json')) {\n return await request.json();\n }\n\n if (contentType.includes('application/x-www-form-urlencoded')) {\n const formData = await request.formData();\n const result: Record<string, string> = {};\n formData.forEach((value, key) => {\n result[key] = value.toString();\n });\n return result;\n }\n\n if (contentType.includes('multipart/form-data')) {\n const formData = await request.formData();\n const result: Record<string, any> = {};\n formData.forEach((value, key) => {\n result[key] = value;\n });\n return result;\n }\n\n if (contentType.includes('text/plain')) {\n return await request.text();\n }\n\n if (contentType.includes('application/octet-stream')) {\n return await request.arrayBuffer();\n }\n\n if (contentType.includes('application/pdf') || contentType.includes('image/') || contentType.includes('video/')) {\n const blob = await request.blob();\n return blob;\n }\n\n if (contentType.includes('application/stream') || request.body instanceof ReadableStream) {\n return request.body;\n }\n\n return await request.text();\n}\n\n\nexport function shouldSerialize(body: any) {\n return typeof body === \"object\" && body !== null && !(body instanceof Blob) && !(body instanceof FormData)\n}\n\nexport const statusCode = {\n \"OK\": 200,\n \"CREATED\": 201,\n \"ACCEPTED\": 202,\n \"NO_CONTENT\": 204,\n \"MULTIPLE_CHOICES\": 300,\n \"MOVED_PERMANENTLY\": 301,\n \"FOUND\": 302,\n \"SEE_OTHER\": 303,\n \"NOT_MODIFIED\": 304,\n \"TEMPORARY_REDIRECT\": 307,\n \"BAD_REQUEST\": 400,\n \"UNAUTHORIZED\": 401,\n \"PAYMENT_REQUIRED\": 402,\n \"FORBIDDEN\": 403,\n \"NOT_FOUND\": 404,\n \"METHOD_NOT_ALLOWED\": 405,\n \"NOT_ACCEPTABLE\": 406,\n \"PROXY_AUTHENTICATION_REQUIRED\": 407,\n \"REQUEST_TIMEOUT\": 408,\n \"CONFLICT\": 409,\n \"GONE\": 410,\n \"LENGTH_REQUIRED\": 411,\n \"PRECONDITION_FAILED\": 412,\n \"PAYLOAD_TOO_LARGE\": 413,\n \"URI_TOO_LONG\": 414,\n \"UNSUPPORTED_MEDIA_TYPE\": 415,\n \"RANGE_NOT_SATISFIABLE\": 416,\n \"EXPECTATION_FAILED\": 417,\n \"I'M_A_TEAPOT\": 418,\n \"MISDIRECTED_REQUEST\": 421,\n \"UNPROCESSABLE_ENTITY\": 422,\n \"LOCKED\": 423,\n \"FAILED_DEPENDENCY\": 424,\n \"TOO_EARLY\": 425,\n \"UPGRADE_REQUIRED\": 426,\n \"PRECONDITION_REQUIRED\": 428,\n \"TOO_MANY_REQUESTS\": 429,\n \"REQUEST_HEADER_FIELDS_TOO_LARGE\": 431,\n \"UNAVAILABLE_FOR_LEGAL_REASONS\": 451,\n \"INTERNAL_SERVER_ERROR\": 500,\n \"NOT_IMPLEMENTED\": 501,\n \"BAD_GATEWAY\": 502,\n \"SERVICE_UNAVAILABLE\": 503,\n \"GATEWAY_TIMEOUT\": 504,\n \"HTTP_VERSION_NOT_SUPPORTED\": 505,\n \"VARIANT_ALSO_NEGOTIATES\": 506,\n \"INSUFFICIENT_STORAGE\": 507,\n \"LOOP_DETECTED\": 508,\n \"NOT_EXTENDED\": 510,\n \"NETWORK_AUTHENTICATION_REQUIRED\": 511,\n}\n"],"mappings":"ijBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,cAAAE,EA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,OAAQG,EAAWH,EAAE,MAAM,EAC3B,WAAYA,EAAE,OACd,QAAS,CACL,eAAgB,kBACpB,CACJ,CAAC,EAEL,GAAIrB,GAAQ,WACR,MAAMqB,EAEV,OAAO,IAAI,SAAS,KAAM,CACtB,OAAQ,IACR,WAAY,uBAChB,CAAC,CACL,CACJ,CAGA,CACJ","names":["src_exports","__export","APIError","createEndpoint","createEndpointCreator","createMiddleware","createMiddlewareCreator","createRouter","getBody","shouldSerialize","statusCode","__toCommonJS","import_zod","import_zod","createMiddleware","optionsOrHandler","handler","createEndpoint","createMiddlewareCreator","fn","APIError","status","body","__publicField","createEndpointCreator","path","options","handler","createEndpoint","responseHeader","handle","ctx","internalCtx","key","value","cookie","middleware","res","body","e","APIError","import_rou3","getBody","request","contentType","formData","result","value","key","shouldSerialize","body","statusCode","createRouter","endpoints","config","router","createRou3Router","endpoint","method","middlewareRouter","route","request","url","path","handler","body","getBody","headers","query","middleware","middlewareContext","res","handlerRes","resBody","shouldSerialize","e","onErrorRes","APIError","statusCode"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/endpoint.ts","../src/middleware.ts","../src/error.ts","../src/cookie.ts","../src/cookie-utils.ts","../src/router.ts","../src/utils.ts","../src/types.ts"],"sourcesContent":["export * from \"./endpoint\";\nexport * from \"./router\";\nexport * from \"./middleware\";\nexport * from \"./error\";\nexport * from \"./utils\";\nexport * from \"./types\";\n","import { z, ZodError, type ZodOptional, type ZodSchema } from \"zod\";\nimport { createMiddleware, type Middleware } from \"./middleware\";\nimport { APIError } from \"./error\";\nimport type { HasRequiredKeys, UnionToIntersection } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tCookieOptions,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n} from \"./types\";\nimport { getCookie, getSignedCookie, setCookie, setSignedCookie } from \"./cookie-utils\";\nimport type { CookiePrefixOptions } from \"./cookie\";\n\nexport interface EndpointConfig {\n\t/**\n\t * Throw when the response isn't in 200 range\n\t */\n\tthrowOnError?: boolean;\n}\n\nexport function createEndpointCreator<T extends Record<string, any>>() {\n\treturn <Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\tpath: Path,\n\t\toptions: Opts,\n\t\thandler: Handler<Path, Opts, R, T>,\n\t) => {\n\t\t//@ts-expect-error\n\t\treturn createEndpoint(path, options, handler);\n\t};\n}\n\nexport function createEndpoint<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n>(path: Path, options: Opts, handler: Handler<Path, Opts, R>) {\n\tconst responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\tconst handle = async (...ctx: HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]) => {\n\t\tlet internalCtx = {\n\t\t\tsetHeader(key: string, value: string) {\n\t\t\t\tresponseHeader.set(key, value);\n\t\t\t},\n\t\t\tsetCookie(key: string, value: string, options?: CookieOptions) {\n\t\t\t\tsetCookie(responseHeader, key, value, options);\n\t\t\t},\n\t\t\tgetCookie(key: string, prefix?: CookiePrefixOptions) {\n\t\t\t\tconst header = ctx[0]?.headers;\n\t\t\t\tconst cookie = getCookie(header?.get(\"Cookie\") || \"\", key, prefix);\n\t\t\t\treturn cookie;\n\t\t\t},\n\t\t\tgetSignedCookie(key: string, secret: string, prefix?: CookiePrefixOptions) {\n\t\t\t\tconst header = ctx[0]?.headers;\n\t\t\t\tif (!header) {\n\t\t\t\t\tthrow new TypeError(\"Headers are required\");\n\t\t\t\t}\n\t\t\t\tconst cookie = getSignedCookie(header, secret, key, prefix);\n\t\t\t\treturn cookie;\n\t\t\t},\n\t\t\tasync setSignedCookie(\n\t\t\t\tkey: string,\n\t\t\t\tvalue: string,\n\t\t\t\tsecret: string | BufferSource,\n\t\t\t\toptions?: CookieOptions,\n\t\t\t) {\n\t\t\t\tawait setSignedCookie(responseHeader, key, value, secret, options);\n\t\t\t},\n\t\t\t...(ctx[0] || {}),\n\t\t\tcontext: {},\n\t\t};\n\t\tif (options.use?.length) {\n\t\t\tfor (const middleware of options.use) {\n\t\t\t\tconst res = (await middleware(internalCtx)) as Endpoint;\n\t\t\t\tconst body = res.options?.body\n\t\t\t\t\t? res.options.body.parse(internalCtx.body)\n\t\t\t\t\t: undefined;\n\t\t\t\tif (res) {\n\t\t\t\t\tinternalCtx = {\n\t\t\t\t\t\t...internalCtx,\n\t\t\t\t\t\tbody: body\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t...body,\n\t\t\t\t\t\t\t\t\t...internalCtx.body,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: internalCtx.body,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t...(internalCtx.context || {}),\n\t\t\t\t\t\t\t...res,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst body = options.body ? options.body.parse(internalCtx.body) : internalCtx.body;\n\t\t\tinternalCtx = {\n\t\t\t\t...internalCtx,\n\t\t\t\tbody: body\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...body,\n\t\t\t\t\t\t\t...internalCtx.body,\n\t\t\t\t\t\t}\n\t\t\t\t\t: internalCtx.body,\n\t\t\t};\n\t\t\tinternalCtx.query = options.query\n\t\t\t\t? options.query.parse(internalCtx.query)\n\t\t\t\t: internalCtx.query;\n\t\t} catch (e) {\n\t\t\tif (e instanceof ZodError) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: e.message,\n\t\t\t\t\tdetails: e.errors,\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t\tif (options.requireHeaders && !internalCtx.headers) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Headers are required\",\n\t\t\t});\n\t\t}\n\t\tif (options.requireRequest && !internalCtx.request) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Request is required\",\n\t\t\t});\n\t\t}\n\t\t//@ts-expect-error\n\t\tconst res = await handler(internalCtx);\n\t\treturn res as ReturnType<Handler<Path, Opts, R>>;\n\t};\n\thandle.path = path;\n\thandle.options = options;\n\thandle.method = options.method;\n\thandle.headers = responseHeader;\n\treturn handle;\n}\n","import { z } from \"zod\";\nimport type {\n\tContextTools,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n\tInferBody,\n\tInferHeaders,\n\tInferRequest,\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 = <ExtraContext extends Record<string, any> = {}>() => {\n\tfunction fn<Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\toptionsOrHandler: MiddlewareHandler<Opts, R, ExtraContext>,\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: MiddlewareHandler<\n\t\t\tOpts & {\n\t\t\t\tmethod: \"*\";\n\t\t\t},\n\t\t\tR,\n\t\t\tExtraContext\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 type { statusCode } from \"./utils\";\n\ntype Status = keyof typeof statusCode;\n\nexport class APIError extends Error {\n\tstatus: Status;\n\tbody: Record<string, any>;\n\tconstructor(status: Status, body?: Record<string, any>) {\n\t\tsuper(`API Error: ${status} ${body?.message ?? \"\"}`, {\n\t\t\tcause: body,\n\t\t});\n\t\tthis.status = status;\n\t\tthis.body = body ?? {};\n\t\tthis.stack = \"\";\n\t\tthis.name = \"BetterCallAPIError\";\n\t}\n}\n","//https://github.com/honojs/hono/blob/main/src/utils/cookie.ts\n\nexport type Cookie = Record<string, string>;\nexport type SignedCookie = Record<string, string | false>;\n\ntype PartitionCookieConstraint =\n\t| { partition: true; secure: true }\n\t| { partition?: boolean; secure?: boolean }; // reset to default\ntype SecureCookieConstraint = { secure: true };\ntype HostCookieConstraint = { secure: true; path: \"/\"; domain?: undefined };\n\nexport type CookieOptions = {\n\tdomain?: string;\n\texpires?: Date;\n\thttpOnly?: boolean;\n\tmaxAge?: number;\n\tpath?: string;\n\tsecure?: boolean;\n\tsigningSecret?: string;\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\tpartitioned?: boolean;\n\tprefix?: CookiePrefixOptions;\n} & PartitionCookieConstraint;\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieConstraint<Name> = Name extends `__Secure-${string}`\n\t? CookieOptions & SecureCookieConstraint\n\t: Name extends `__Host-${string}`\n\t\t? CookieOptions & HostCookieConstraint\n\t\t: CookieOptions;\n\nconst algorithm = { name: \"HMAC\", hash: \"SHA-256\" };\n\nconst getCryptoKey = async (secret: string | BufferSource): Promise<CryptoKey> => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await crypto.subtle.importKey(\"raw\", secretBuf, algorithm, false, [\"sign\", \"verify\"]);\n};\n\nconst makeSignature = async (value: string, secret: string | BufferSource): Promise<string> => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await crypto.subtle.sign(\n\t\talgorithm.name,\n\t\tkey,\n\t\tnew TextEncoder().encode(value),\n\t);\n\t// the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n\nconst verifySignature = async (\n\tbase64Signature: string,\n\tvalue: string,\n\tsecret: CryptoKey,\n): Promise<boolean> => {\n\ttry {\n\t\tconst signatureBinStr = atob(base64Signature);\n\t\tconst signature = new Uint8Array(signatureBinStr.length);\n\t\tfor (let i = 0, len = signatureBinStr.length; i < len; i++) {\n\t\t\tsignature[i] = signatureBinStr.charCodeAt(i);\n\t\t}\n\t\treturn await crypto.subtle.verify(\n\t\t\talgorithm,\n\t\t\tsecret,\n\t\t\tsignature,\n\t\t\tnew TextEncoder().encode(value),\n\t\t);\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\n\n// all alphanumeric chars and all of _!#$%&'*.^`|~+-\n// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)\nconst validCookieNameRegEx = /^[\\w!#$%&'*.^`|~+-]+$/;\n\n// all ASCII chars 32-126 except 34, 59, and 92 (i.e. space to tilde but not double quote, semicolon, or backslash)\n// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)\n//\n// note: the spec also prohibits comma and space, but we allow both since they are very common in the real world\n// (see: https://github.com/golang/go/issues/7243)\nconst validCookieValueRegEx = /^[ !#-:<-[\\]-~]*$/;\n\nexport const parse = (cookie: string, name?: string): Cookie => {\n\tconst pairs = cookie.trim().split(\";\");\n\treturn pairs.reduce((parsedCookie, pairStr) => {\n\t\tpairStr = pairStr.trim();\n\t\tconst valueStartPos = pairStr.indexOf(\"=\");\n\t\tif (valueStartPos === -1) {\n\t\t\treturn parsedCookie;\n\t\t}\n\n\t\tconst cookieName = pairStr.substring(0, valueStartPos).trim();\n\t\tif ((name && name !== cookieName) || !validCookieNameRegEx.test(cookieName)) {\n\t\t\treturn parsedCookie;\n\t\t}\n\n\t\tlet cookieValue = pairStr.substring(valueStartPos + 1).trim();\n\t\tif (cookieValue.startsWith('\"') && cookieValue.endsWith('\"')) {\n\t\t\tcookieValue = cookieValue.slice(1, -1);\n\t\t}\n\t\tif (validCookieValueRegEx.test(cookieValue)) {\n\t\t\tparsedCookie[cookieName] = decodeURIComponent(cookieValue);\n\t\t}\n\n\t\treturn parsedCookie;\n\t}, {} as Cookie);\n};\n\nexport const parseSigned = async (\n\tcookie: string,\n\tsecret: string | BufferSource,\n\tname?: string,\n): Promise<SignedCookie> => {\n\tconst parsedCookie: SignedCookie = {};\n\tconst secretKey = await getCryptoKey(secret);\n\n\tfor (const [key, value] of Object.entries(parse(cookie, name))) {\n\t\tconst signatureStartPos = value.lastIndexOf(\".\");\n\t\tif (signatureStartPos < 1) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst signedValue = value.substring(0, signatureStartPos);\n\t\tconst signature = value.substring(signatureStartPos + 1);\n\t\tif (signature.length !== 44 || !signature.endsWith(\"=\")) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst isVerified = await verifySignature(signature, signedValue, secretKey);\n\t\tparsedCookie[key] = isVerified ? signedValue : false;\n\t}\n\n\treturn parsedCookie;\n};\n\nconst _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {\n\tlet cookie = `${name}=${value}`;\n\n\tif (name.startsWith(\"__Secure-\") && !opt.secure) {\n\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.1\n\t\tthrow new Error(\"__Secure- Cookie must have Secure attributes\");\n\t}\n\n\tif (name.startsWith(\"__Host-\")) {\n\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.2\n\t\tif (!opt.secure) {\n\t\t\tthrow new Error(\"__Host- Cookie must have Secure attributes\");\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\tthrow new Error('__Host- Cookie must have Path attributes with \"/\"');\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\tthrow new Error(\"__Host- Cookie must not have Domain attributes\");\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.2\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.1\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\t// FIXME: replace link to RFC\n\t\t// https://www.ietf.org/archive/id/draft-cutler-httpbis-partitioned-cookies-01.html#section-2.3\n\t\tif (!opt.secure) {\n\t\t\tthrow new Error(\"Partitioned Cookie must have Secure attributes\");\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serialize = <Name extends string>(\n\tname: Name,\n\tvalue: string,\n\topt?: CookieConstraint<Name>,\n): string => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(name, value, opt);\n};\n\nexport const serializeSigned = async (\n\tname: string,\n\tvalue: string,\n\tsecret: string | BufferSource,\n\topt: CookieOptions = {},\n): Promise<string> => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(name, value, opt);\n};\n","//https://github.com/honojs/hono/blob/main/src/helper/cookie/index.ts\n\nimport {\n\tparse,\n\tparseSigned,\n\tserialize,\n\tserializeSigned,\n\ttype CookieOptions,\n\ttype CookiePrefixOptions,\n} from \"./cookie\";\n\nexport const getCookie = (cookie?: string, key?: string, prefix?: CookiePrefixOptions) => {\n\tif (!cookie) {\n\t\treturn undefined;\n\t}\n\tlet finalKey = key;\n\tif (prefix === \"secure\") {\n\t\tfinalKey = \"__Secure-\" + key;\n\t} else if (prefix === \"host\") {\n\t\tfinalKey = \"__Host-\" + key;\n\t} else {\n\t\treturn undefined;\n\t}\n\tconst obj = parse(cookie, finalKey);\n\treturn obj[finalKey];\n};\n\nexport const setCookie = (\n\theader: Headers,\n\tname: string,\n\tvalue: string,\n\topt?: CookieOptions,\n): void => {\n\t// Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.\n\t// Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)\n\t// and must not have a Domain attribute.\n\t// Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'\n\tlet cookie;\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = serialize(\"__Secure-\" + name, value, { path: \"/\", ...opt, secure: true });\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = serialize(\"__Host-\" + name, value, {\n\t\t\t...opt,\n\t\t\tpath: \"/\",\n\t\t\tsecure: true,\n\t\t\tdomain: undefined,\n\t\t});\n\t} else {\n\t\tcookie = serialize(name, value, { path: \"/\", ...opt });\n\t}\n\theader.append(\"Set-Cookie\", cookie);\n};\n\nexport const setSignedCookie = async (\n\theader: Headers,\n\tname: string,\n\tvalue: string,\n\tsecret: string | BufferSource,\n\topt?: CookieOptions,\n): Promise<void> => {\n\tlet cookie;\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = await serializeSigned(\"__Secure-\" + name, value, secret, {\n\t\t\tpath: \"/\",\n\t\t\t...opt,\n\t\t\tsecure: true,\n\t\t});\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = await serializeSigned(\"__Host-\" + name, value, secret, {\n\t\t\t...opt,\n\t\t\tpath: \"/\",\n\t\t\tsecure: true,\n\t\t\tdomain: undefined,\n\t\t});\n\t} else {\n\t\tcookie = await serializeSigned(name, value, secret, { path: \"/\", ...opt });\n\t}\n\theader.append(\"Set-Cookie\", cookie);\n};\n\nexport const getSignedCookie = async (\n\theader: Headers,\n\tsecret: string,\n\tkey: string,\n\tprefix?: CookiePrefixOptions,\n) => {\n\tconst cookie = header.get(\"Cookie\");\n\tif (!cookie) {\n\t\treturn undefined;\n\t}\n\tlet finalKey = key;\n\tif (prefix === \"secure\") {\n\t\tfinalKey = \"__Secure-\" + key;\n\t} else if (prefix === \"host\") {\n\t\tfinalKey = \"__Host-\" + key;\n\t}\n\tconst obj = await parseSigned(cookie, secret, finalKey);\n\treturn obj[finalKey];\n};\n","import { createRouter as createRou3Router, addRoute, findRoute } from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./error\";\nimport type { Middleware, MiddlewareHandler } from \"./middleware\";\nimport type { Endpoint, Method } from \"./types\";\n\ninterface RouterConfig {\n\t/**\n\t * Throw error if error occurred other than APIError\n\t */\n\tthrowError?: boolean;\n\t/**\n\t * Handle error\n\t */\n\tonError?: (e: unknown) => void | Promise<void> | Response | Promise<Response>;\n\t/**\n\t * Base path for the router\n\t */\n\tbasePath?: string;\n\t/**\n\t * Middlewares for the router\n\t */\n\trouterMiddleware?: {\n\t\tpath: string;\n\t\tmiddleware: Endpoint;\n\t}[];\n\textraContext?: Record<string, any>;\n}\n\nexport const createRouter = <E extends Record<string, Endpoint>, Config extends RouterConfig>(\n\tendpoints: E,\n\tconfig?: Config,\n) => {\n\tconst _endpoints = Object.values(endpoints);\n\tconst router = createRou3Router();\n\tfor (const endpoint of _endpoints) {\n\t\tif (Array.isArray(endpoint.options?.method)) {\n\t\t\tfor (const method of endpoint.options.method) {\n\t\t\t\taddRoute(router, method, endpoint.path, endpoint);\n\t\t\t}\n\t\t} else {\n\t\t\taddRoute(router, endpoint.options.method, endpoint.path, endpoint);\n\t\t}\n\t}\n\n\tconst middlewareRouter = createRou3Router();\n\tfor (const route of config?.routerMiddleware || []) {\n\t\taddRoute(middlewareRouter, \"*\", route.path, route.middleware);\n\t}\n\n\tconst handler = async (request: Request) => {\n\t\tconst url = new URL(request.url);\n\t\tlet path = url.pathname;\n\t\tif (config?.basePath) {\n\t\t\tpath = path.split(config.basePath)[1];\n\t\t}\n\t\tconst method = request.method;\n\t\tconst route = findRoute(router, method, path);\n\t\tconst handler = route?.data as Endpoint;\n\t\tconst body = await getBody(request);\n\t\tconst headers = request.headers;\n\t\tconst query = Object.fromEntries(url.searchParams);\n\t\tconst middleware = findRoute(middlewareRouter, \"*\", path)?.data as Endpoint | undefined;\n\t\t//handler 404\n\t\tif (!handler) {\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 404,\n\t\t\t\tstatusText: \"Not Found\",\n\t\t\t});\n\t\t}\n\t\ttry {\n\t\t\tlet middlewareContext: Record<string, any> = {};\n\t\t\tif (middleware) {\n\t\t\t\tconst res = await middleware({\n\t\t\t\t\tpath: path,\n\t\t\t\t\tmethod: method as \"GET\",\n\t\t\t\t\theaders,\n\t\t\t\t\tparams: route?.params as any,\n\t\t\t\t\trequest: request,\n\t\t\t\t\tbody: body,\n\t\t\t\t\tquery,\n\t\t\t\t\t...config?.extraContext,\n\t\t\t\t});\n\t\t\t\tif (res) {\n\t\t\t\t\tmiddlewareContext = {\n\t\t\t\t\t\t...res,\n\t\t\t\t\t\t...middlewareContext,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst handlerRes = await handler({\n\t\t\t\tpath: path,\n\t\t\t\tmethod: method as \"GET\",\n\t\t\t\theaders,\n\t\t\t\tparams: route?.params as any,\n\t\t\t\trequest: request,\n\t\t\t\tbody: body,\n\t\t\t\tquery,\n\t\t\t\t...middlewareContext,\n\t\t\t\t...config?.extraContext,\n\t\t\t});\n\t\t\tif (handlerRes instanceof Response) {\n\t\t\t\treturn handlerRes;\n\t\t\t}\n\t\t\tconst resBody = shouldSerialize(handlerRes) ? JSON.stringify(handlerRes) : handlerRes;\n\t\t\treturn new Response(resBody as any, {\n\t\t\t\theaders: handler.headers,\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (config?.onError) {\n\t\t\t\tconst onErrorRes = await config.onError(e);\n\t\t\t\tif (onErrorRes instanceof Response) {\n\t\t\t\t\treturn onErrorRes;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (e instanceof APIError) {\n\t\t\t\treturn new Response(e.body ? JSON.stringify(e.body) : null, {\n\t\t\t\t\tstatus: statusCode[e.status],\n\t\t\t\t\tstatusText: e.status,\n\t\t\t\t\theaders: handler.headers,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (config?.throwError) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 500,\n\t\t\t\tstatusText: \"Internal Server Error\",\n\t\t\t});\n\t\t}\n\t};\n\treturn {\n\t\thandler,\n\t\tendpoints,\n\t};\n};\n\nexport type Router = ReturnType<typeof createRouter>;\n","export async function getBody(request: Request) {\n\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 { z, type ZodOptional, type ZodSchema } from \"zod\";\nimport type { UnionToIntersection } from \"./helper\";\nimport type { CookiePrefixOptions } from \"./cookie\";\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}\n\nexport type Endpoint<\n\tHandler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>,\n\tOption extends EndpointOptions = EndpointOptions,\n> = {\n\tpath: string;\n\toptions: Option;\n\theaders?: Headers;\n} & Handler;\n\nexport type InferParamPath<Path> = Path extends `${infer _Start}:${infer Param}/${infer Rest}`\n\t? { [K in Param | keyof InferParamPath<Rest>]: string }\n\t: Path extends `${infer _Start}:${infer Param}`\n\t\t? { [K in Param]: string }\n\t\t: Path extends `${infer _Start}/${infer Rest}`\n\t\t\t? InferParamPath<Rest>\n\t\t\t: undefined;\n\nexport type InferParamWildCard<Path> = Path extends\n\t| `${infer _Start}/*:${infer Param}/${infer Rest}`\n\t| `${infer _Start}/**:${infer Param}/${infer Rest}`\n\t? { [K in Param | keyof InferParamPath<Rest>]: string }\n\t: Path extends `${infer _Start}/*`\n\t\t? { [K in \"_\"]: string }\n\t\t: Path extends `${infer _Start}/${infer Rest}`\n\t\t\t? InferParamPath<Rest>\n\t\t\t: undefined;\n\nexport type Prettify<T> = {\n\t[key in keyof T]: T[key];\n} & {};\n\nexport interface CookieOptions {\n\t/**\n\t * Max age in seconds\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Domain\n\t */\n\tdomain?: string;\n\t/**\n\t * Path\n\t */\n\tpath?: string;\n\t/**\n\t * Secure\n\t */\n\tsecure?: boolean;\n\t/**\n\t * HttpOnly\n\t */\n\thttpOnly?: boolean;\n\n\t/**\n\t * SameSite\n\t */\n\tsameSite?: \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Expires\n\t */\n\texpires?: Date;\n}\n\nexport type ContextTools = {\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * cookie setter.\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetCookie: (key: string, value: string, options?: CookieOptions) => void;\n\t/**\n\t * Get cookie value\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tgetCookie: (key: string, value: string, options?: CookieOptions) => string | undefined;\n\t/**\n\t * Set signed cookie\n\t */\n\tsetSignedCookie: (\n\t\tkey: string,\n\t\tvalue: string,\n\t\tsecret: string | BufferSource,\n\t\toptions?: CookieOptions,\n\t) => Promise<void>;\n\t/**\n\t * Get signed cookie value\n\t */\n\n\tgetSignedCookie: (\n\t\tkey: string,\n\t\tsecret: string,\n\t\tprefix?: CookiePrefixOptions,\n\t) => Promise<string | undefined>;\n};\n\nexport type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> &\n\tInferParam<Path> &\n\tInferMethod<Opts[\"method\"]> &\n\tInferHeaders<Opts> &\n\tInferRequest<Opts> &\n\tInferQuery<Opts[\"query\"]>;\n\nexport type InferUse<Opts extends EndpointOptions> = Opts[\"use\"] extends Endpoint[]\n\t? {\n\t\t\tcontext: UnionToIntersection<Awaited<ReturnType<Opts[\"use\"][number]>>>;\n\t\t}\n\t: {};\n\nexport type InferUseOptions<Opts extends EndpointOptions> = Opts[\"use\"] extends Array<infer U>\n\t? UnionToIntersection<\n\t\t\tU extends Endpoint\n\t\t\t\t? U[\"options\"]\n\t\t\t\t: {\n\t\t\t\t\t\tbody?: {};\n\t\t\t\t\t\trequireRequest?: boolean;\n\t\t\t\t\t\trequireHeaders?: boolean;\n\t\t\t\t\t}\n\t\t>\n\t: {\n\t\t\tbody?: {};\n\t\t\trequireRequest?: boolean;\n\t\t\trequireHeaders?: boolean;\n\t\t};\n\nexport type InferMethod<M extends Method | Method[]> = M extends Array<Method>\n\t? {\n\t\t\tmethod: M[number];\n\t\t}\n\t: {\n\t\t\tmethod?: M;\n\t\t};\n\nexport type InferHeaders<\n\tOpt extends EndpointOptions,\n\tHeaderReq = Opt[\"requireHeaders\"],\n> = HeaderReq extends true\n\t? {\n\t\t\theaders: Headers;\n\t\t}\n\t: InferUseOptions<Opt>[\"requireHeaders\"] extends true\n\t\t? {\n\t\t\t\theaders: Headers;\n\t\t\t}\n\t\t: {\n\t\t\t\theaders?: Headers;\n\t\t\t};\n\nexport type InferRequest<\n\tOpt extends EndpointOptions,\n\tRequestReq = Opt[\"requireRequest\"],\n> = RequestReq extends true\n\t? {\n\t\t\trequest: Request;\n\t\t}\n\t: InferUseOptions<Opt>[\"requireRequest\"] extends true\n\t\t? {\n\t\t\t\trequest: Request;\n\t\t\t}\n\t\t: {\n\t\t\t\trequest?: Request;\n\t\t\t};\n\nexport type InferQuery<Query> = Query extends ZodSchema\n\t? Query extends ZodOptional<any>\n\t\t? {\n\t\t\t\tquery?: z.infer<Query>;\n\t\t\t}\n\t\t: {\n\t\t\t\tquery: z.infer<Query>;\n\t\t\t}\n\t: {\n\t\t\tquery?: undefined;\n\t\t};\n\nexport type InferParam<\n\tPath extends string,\n\tParamPath extends InferParamPath<Path> = InferParamPath<Path>,\n\tWildCard extends InferParamWildCard<Path> = InferParamWildCard<Path>,\n> = ParamPath extends undefined\n\t? WildCard extends undefined\n\t\t? {\n\t\t\t\tparams?: Record<string, string>;\n\t\t\t}\n\t\t: {\n\t\t\t\tparams: WildCard;\n\t\t\t}\n\t: {\n\t\t\tparams: Prettify<ParamPath & (WildCard extends undefined ? {} : WildCard)>;\n\t\t};\n\nexport type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined;\n\nexport type Handler<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n\tExtra extends Record<string, any> = {},\n> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts> & ContextTools> & Extra) => Promise<R>;\n\nexport type Method = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"*\";\n\nexport type InferBody<\n\tOpts extends EndpointOptions,\n\tBody extends ZodSchema | undefined = Opts[\"body\"] &\n\t\t(undefined extends InferUseOptions<Opts>[\"body\"] ? {} : InferUseOptions<Opts>[\"body\"]),\n> = Body extends ZodSchema\n\t? Body extends ZodOptional<any>\n\t\t? {\n\t\t\t\tbody?: Prettify<z.infer<Body>>;\n\t\t\t}\n\t\t: {\n\t\t\t\tbody: Prettify<z.infer<Body>>;\n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ACpB,IAAMuB,EAAa,MAAMvB,EAAO,QAAQsB,CAAC,EACzC,GAAIC,aAAsB,SACzB,OAAOA,CAET,CACA,GAAID,aAAaE,EAChB,OAAO,IAAI,SAASF,EAAE,KAAO,KAAK,UAAUA,EAAE,IAAI,EAAI,KAAM,CAC3D,OAAQG,EAAWH,EAAE,MAAM,EAC3B,WAAYA,EAAE,OACd,QAASX,EAAQ,OAClB,CAAC,EAEF,GAAIX,GAAQ,WACX,MAAMsB,EAEP,OAAO,IAAI,SAAS,KAAM,CACzB,OAAQ,IACR,WAAY,uBACb,CAAC,CACF,CACD,EAGC,UAAAvB,CACD,CACD,EEvIA,IAAA2B,GAAoD","names":["src_exports","__export","APIError","createEndpoint","createEndpointCreator","createMiddleware","createMiddlewareCreator","createRouter","getBody","shouldSerialize","statusCode","__toCommonJS","import_zod","import_zod","createMiddleware","optionsOrHandler","handler","createEndpoint","createMiddlewareCreator","fn","APIError","status","body","__publicField","algorithm","getCryptoKey","secret","secretBuf","makeSignature","value","key","signature","verifySignature","base64Signature","signatureBinStr","len","validCookieNameRegEx","validCookieValueRegEx","parse","cookie","name","parsedCookie","pairStr","valueStartPos","cookieName","cookieValue","parseSigned","secretKey","signatureStartPos","signedValue","isVerified","_serialize","opt","serialize","serializeSigned","getCookie","cookie","key","prefix","finalKey","parse","setCookie","header","name","value","opt","serialize","setSignedCookie","secret","serializeSigned","getSignedCookie","parseSigned","createEndpointCreator","path","options","handler","createEndpoint","responseHeader","handle","ctx","internalCtx","key","value","setCookie","prefix","header","getCookie","secret","getSignedCookie","setSignedCookie","middleware","res","body","e","APIError","import_rou3","getBody","request","contentType","formData","result","value","key","shouldSerialize","body","statusCode","createRouter","endpoints","config","_endpoints","router","createRou3Router","endpoint","method","middlewareRouter","route","request","url","path","handler","body","getBody","headers","query","middleware","middlewareContext","res","handlerRes","resBody","shouldSerialize","e","onErrorRes","APIError","statusCode","import_zod"]}
package/dist/index.d.cts CHANGED
@@ -1,123 +1,6 @@
1
- import { ZodSchema, ZodOptional, z } from 'zod';
2
-
3
- type UnionToIntersection<Union> = (Union extends unknown ? (distributedUnion: Union) => void : never) extends ((mergedIntersection: infer Intersection) => void) ? Intersection & Union : never;
4
- type RequiredKeysOf<BaseType extends object> = Exclude<{
5
- [Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]> ? Key : never;
6
- }[keyof BaseType], undefined>;
7
- type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never ? false : true;
8
-
9
- interface EndpointOptions {
10
- method: Method | Method[];
11
- body?: ZodSchema;
12
- query?: ZodSchema;
13
- params?: ZodSchema<any>;
14
- /**
15
- * If true headers will be required to be passed in the context
16
- */
17
- requireHeaders?: boolean;
18
- /**
19
- * If true request object will be required
20
- */
21
- requireRequest?: boolean;
22
- /**
23
- * List of endpoints that will be called before this endpoint
24
- */
25
- use?: Endpoint[];
26
- }
27
- type Endpoint<Handler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>, Option extends EndpointOptions = EndpointOptions> = {
28
- path: string;
29
- options: Option;
30
- headers?: Headers;
31
- } & (Handler);
32
- type InferParamPath<Path> = Path extends `${infer _Start}:${infer Param}/${infer Rest}` ? {
33
- [K in Param | keyof InferParamPath<Rest>]: string;
34
- } : Path extends `${infer _Start}:${infer Param}` ? {
35
- [K in Param]: string;
36
- } : Path extends `${infer _Start}/${infer Rest}` ? InferParamPath<Rest> : undefined;
37
- type InferParamWildCard<Path> = Path extends `${infer _Start}/*:${infer Param}/${infer Rest}` | `${infer _Start}/**:${infer Param}/${infer Rest}` ? {
38
- [K in Param | keyof InferParamPath<Rest>]: string;
39
- } : Path extends `${infer _Start}/*` ? {
40
- [K in "_"]: string;
41
- } : Path extends `${infer _Start}/${infer Rest}` ? InferParamPath<Rest> : undefined;
42
- type Prettify<T> = {
43
- [key in keyof T]: T[key];
44
- } & {};
45
- type ContextTools = {
46
- /**
47
- * Set header
48
- *
49
- * If it's called outside of a request it will just be ignored.
50
- */
51
- setHeader: (key: string, value: string) => void;
52
- /**
53
- * cookie setter.
54
- *
55
- * If it's called outside of a request it will just be ignored.
56
- */
57
- setCookie: (key: string, value: string) => void;
58
- /**
59
- * Get cookie value
60
- *
61
- * If it's called outside of a request it will just be ignored.
62
- */
63
- getCookie: (key: string) => string | undefined;
64
- };
65
- type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> & InferParam<Path> & InferMethod<Opts['method']> & InferHeaders<Opts> & InferRequest<Opts> & InferQuery<Opts["query"]>;
66
- type InferUse<Opts extends EndpointOptions> = Opts["use"] extends Endpoint[] ? {
67
- context: UnionToIntersection<Awaited<ReturnType<Opts["use"][number]>>>;
68
- } : {};
69
- type InferUseOptions<Opts extends EndpointOptions> = Opts["use"] extends Array<infer U> ? UnionToIntersection<U extends Endpoint ? U['options'] : {
70
- body?: {};
71
- requireRequest?: boolean;
72
- requireHeaders?: boolean;
73
- }> : {
74
- body?: {};
75
- requireRequest?: boolean;
76
- requireHeaders?: boolean;
77
- };
78
- type InferMethod<M extends Method | Method[]> = M extends Array<Method> ? {
79
- method: M[number];
80
- } : {
81
- method?: M;
82
- };
83
- type InferHeaders<Opt extends EndpointOptions, HeaderReq = Opt["requireHeaders"]> = HeaderReq extends true ? {
84
- headers: Headers;
85
- } : InferUseOptions<Opt>['requireHeaders'] extends true ? {
86
- headers: Headers;
87
- } : {
88
- headers?: Headers;
89
- };
90
- type InferRequest<Opt extends EndpointOptions, RequestReq = Opt["requireRequest"]> = RequestReq extends true ? {
91
- request: Request;
92
- } : InferUseOptions<Opt>['requireRequest'] extends true ? {
93
- request: Request;
94
- } : {
95
- request?: Request;
96
- };
97
- type InferQuery<Query> = Query extends ZodSchema ? Query extends ZodOptional<any> ? {
98
- query?: z.infer<Query>;
99
- } : {
100
- query: z.infer<Query>;
101
- } : {
102
- query?: undefined;
103
- };
104
- type InferParam<Path extends string, ParamPath extends InferParamPath<Path> = InferParamPath<Path>, WildCard extends InferParamWildCard<Path> = InferParamWildCard<Path>> = ParamPath extends undefined ? WildCard extends undefined ? {
105
- params?: Record<string, string>;
106
- } : {
107
- params: WildCard;
108
- } : {
109
- params: Prettify<ParamPath & (WildCard extends undefined ? {} : WildCard)>;
110
- };
111
- type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined;
112
- type Handler<Path extends string, Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts> & ContextTools> & Extra) => Promise<R>;
113
- type Method = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "*";
114
- 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> ? {
115
- body?: Prettify<z.infer<Body>>;
116
- } : {
117
- body: Prettify<z.infer<Body>>;
118
- } : {
119
- body?: undefined;
120
- };
1
+ import { E as EndpointOptions, a as EndpointResponse, H as Handler, b as HasRequiredKeys, C as Context, M as Method, P as Prettify, I as InferBody, c as InferRequest, d as InferHeaders, e as ContextTools, f as Endpoint } from './router-fNn8BCPr.cjs';
2
+ export { j as CookieOptions, m as InferMethod, o as InferParam, h as InferParamPath, i as InferParamWildCard, n as InferQuery, k as InferUse, l as InferUseOptions, R as Router, g as createRouter } from './router-fNn8BCPr.cjs';
3
+ import 'zod';
121
4
 
122
5
  interface EndpointConfig {
123
6
  /**
@@ -140,31 +23,6 @@ declare function createEndpoint<Path extends string, Opts extends EndpointOption
140
23
  headers: Headers;
141
24
  };
142
25
 
143
- interface RouterConfig {
144
- /**
145
- * Throw error if error occurred other than APIError
146
- */
147
- throwError?: boolean;
148
- /**
149
- * Handle error
150
- */
151
- onError?: (e: unknown) => void | Promise<void> | Response | Promise<Response>;
152
- /**
153
- * Base path for the router
154
- */
155
- basePath?: string;
156
- /**
157
- * Middlewares for the router
158
- */
159
- routerMiddleware?: {
160
- path: string;
161
- middleware: Endpoint;
162
- }[];
163
- }
164
- declare const createRouter: <E extends Endpoint, Config extends RouterConfig>(endpoints: E[], config?: Config) => {
165
- handler: (request: Request) => Promise<Response>;
166
- };
167
-
168
26
  type MiddlewareHandler<Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<InferBody<Opts> & InferRequest<Opts> & InferHeaders<Opts> & {
169
27
  params?: Record<string, string>;
170
28
  query?: Record<string, string>;
@@ -255,4 +113,4 @@ declare class APIError extends Error {
255
113
  constructor(status: Status, body?: Record<string, any>);
256
114
  }
257
115
 
258
- export { APIError, type EndpointConfig, type Middleware, type MiddlewareHandler, createEndpoint, createEndpointCreator, createMiddleware, createMiddlewareCreator, createRouter, getBody, shouldSerialize, statusCode };
116
+ export { APIError, Context, ContextTools, Endpoint, type EndpointConfig, EndpointOptions, EndpointResponse, Handler, InferBody, InferHeaders, InferRequest, Method, type Middleware, type MiddlewareHandler, Prettify, createEndpoint, createEndpointCreator, createMiddleware, createMiddlewareCreator, getBody, shouldSerialize, statusCode };
package/dist/index.d.ts CHANGED
@@ -1,123 +1,6 @@
1
- import { ZodSchema, ZodOptional, z } from 'zod';
2
-
3
- type UnionToIntersection<Union> = (Union extends unknown ? (distributedUnion: Union) => void : never) extends ((mergedIntersection: infer Intersection) => void) ? Intersection & Union : never;
4
- type RequiredKeysOf<BaseType extends object> = Exclude<{
5
- [Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]> ? Key : never;
6
- }[keyof BaseType], undefined>;
7
- type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never ? false : true;
8
-
9
- interface EndpointOptions {
10
- method: Method | Method[];
11
- body?: ZodSchema;
12
- query?: ZodSchema;
13
- params?: ZodSchema<any>;
14
- /**
15
- * If true headers will be required to be passed in the context
16
- */
17
- requireHeaders?: boolean;
18
- /**
19
- * If true request object will be required
20
- */
21
- requireRequest?: boolean;
22
- /**
23
- * List of endpoints that will be called before this endpoint
24
- */
25
- use?: Endpoint[];
26
- }
27
- type Endpoint<Handler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>, Option extends EndpointOptions = EndpointOptions> = {
28
- path: string;
29
- options: Option;
30
- headers?: Headers;
31
- } & (Handler);
32
- type InferParamPath<Path> = Path extends `${infer _Start}:${infer Param}/${infer Rest}` ? {
33
- [K in Param | keyof InferParamPath<Rest>]: string;
34
- } : Path extends `${infer _Start}:${infer Param}` ? {
35
- [K in Param]: string;
36
- } : Path extends `${infer _Start}/${infer Rest}` ? InferParamPath<Rest> : undefined;
37
- type InferParamWildCard<Path> = Path extends `${infer _Start}/*:${infer Param}/${infer Rest}` | `${infer _Start}/**:${infer Param}/${infer Rest}` ? {
38
- [K in Param | keyof InferParamPath<Rest>]: string;
39
- } : Path extends `${infer _Start}/*` ? {
40
- [K in "_"]: string;
41
- } : Path extends `${infer _Start}/${infer Rest}` ? InferParamPath<Rest> : undefined;
42
- type Prettify<T> = {
43
- [key in keyof T]: T[key];
44
- } & {};
45
- type ContextTools = {
46
- /**
47
- * Set header
48
- *
49
- * If it's called outside of a request it will just be ignored.
50
- */
51
- setHeader: (key: string, value: string) => void;
52
- /**
53
- * cookie setter.
54
- *
55
- * If it's called outside of a request it will just be ignored.
56
- */
57
- setCookie: (key: string, value: string) => void;
58
- /**
59
- * Get cookie value
60
- *
61
- * If it's called outside of a request it will just be ignored.
62
- */
63
- getCookie: (key: string) => string | undefined;
64
- };
65
- type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> & InferParam<Path> & InferMethod<Opts['method']> & InferHeaders<Opts> & InferRequest<Opts> & InferQuery<Opts["query"]>;
66
- type InferUse<Opts extends EndpointOptions> = Opts["use"] extends Endpoint[] ? {
67
- context: UnionToIntersection<Awaited<ReturnType<Opts["use"][number]>>>;
68
- } : {};
69
- type InferUseOptions<Opts extends EndpointOptions> = Opts["use"] extends Array<infer U> ? UnionToIntersection<U extends Endpoint ? U['options'] : {
70
- body?: {};
71
- requireRequest?: boolean;
72
- requireHeaders?: boolean;
73
- }> : {
74
- body?: {};
75
- requireRequest?: boolean;
76
- requireHeaders?: boolean;
77
- };
78
- type InferMethod<M extends Method | Method[]> = M extends Array<Method> ? {
79
- method: M[number];
80
- } : {
81
- method?: M;
82
- };
83
- type InferHeaders<Opt extends EndpointOptions, HeaderReq = Opt["requireHeaders"]> = HeaderReq extends true ? {
84
- headers: Headers;
85
- } : InferUseOptions<Opt>['requireHeaders'] extends true ? {
86
- headers: Headers;
87
- } : {
88
- headers?: Headers;
89
- };
90
- type InferRequest<Opt extends EndpointOptions, RequestReq = Opt["requireRequest"]> = RequestReq extends true ? {
91
- request: Request;
92
- } : InferUseOptions<Opt>['requireRequest'] extends true ? {
93
- request: Request;
94
- } : {
95
- request?: Request;
96
- };
97
- type InferQuery<Query> = Query extends ZodSchema ? Query extends ZodOptional<any> ? {
98
- query?: z.infer<Query>;
99
- } : {
100
- query: z.infer<Query>;
101
- } : {
102
- query?: undefined;
103
- };
104
- type InferParam<Path extends string, ParamPath extends InferParamPath<Path> = InferParamPath<Path>, WildCard extends InferParamWildCard<Path> = InferParamWildCard<Path>> = ParamPath extends undefined ? WildCard extends undefined ? {
105
- params?: Record<string, string>;
106
- } : {
107
- params: WildCard;
108
- } : {
109
- params: Prettify<ParamPath & (WildCard extends undefined ? {} : WildCard)>;
110
- };
111
- type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined;
112
- type Handler<Path extends string, Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts> & ContextTools> & Extra) => Promise<R>;
113
- type Method = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "*";
114
- 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> ? {
115
- body?: Prettify<z.infer<Body>>;
116
- } : {
117
- body: Prettify<z.infer<Body>>;
118
- } : {
119
- body?: undefined;
120
- };
1
+ import { E as EndpointOptions, a as EndpointResponse, H as Handler, b as HasRequiredKeys, C as Context, M as Method, P as Prettify, I as InferBody, c as InferRequest, d as InferHeaders, e as ContextTools, f as Endpoint } from './router-fNn8BCPr.js';
2
+ export { j as CookieOptions, m as InferMethod, o as InferParam, h as InferParamPath, i as InferParamWildCard, n as InferQuery, k as InferUse, l as InferUseOptions, R as Router, g as createRouter } from './router-fNn8BCPr.js';
3
+ import 'zod';
121
4
 
122
5
  interface EndpointConfig {
123
6
  /**
@@ -140,31 +23,6 @@ declare function createEndpoint<Path extends string, Opts extends EndpointOption
140
23
  headers: Headers;
141
24
  };
142
25
 
143
- interface RouterConfig {
144
- /**
145
- * Throw error if error occurred other than APIError
146
- */
147
- throwError?: boolean;
148
- /**
149
- * Handle error
150
- */
151
- onError?: (e: unknown) => void | Promise<void> | Response | Promise<Response>;
152
- /**
153
- * Base path for the router
154
- */
155
- basePath?: string;
156
- /**
157
- * Middlewares for the router
158
- */
159
- routerMiddleware?: {
160
- path: string;
161
- middleware: Endpoint;
162
- }[];
163
- }
164
- declare const createRouter: <E extends Endpoint, Config extends RouterConfig>(endpoints: E[], config?: Config) => {
165
- handler: (request: Request) => Promise<Response>;
166
- };
167
-
168
26
  type MiddlewareHandler<Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<InferBody<Opts> & InferRequest<Opts> & InferHeaders<Opts> & {
169
27
  params?: Record<string, string>;
170
28
  query?: Record<string, string>;
@@ -255,4 +113,4 @@ declare class APIError extends Error {
255
113
  constructor(status: Status, body?: Record<string, any>);
256
114
  }
257
115
 
258
- export { APIError, type EndpointConfig, type Middleware, type MiddlewareHandler, createEndpoint, createEndpointCreator, createMiddleware, createMiddlewareCreator, createRouter, getBody, shouldSerialize, statusCode };
116
+ export { APIError, Context, ContextTools, Endpoint, type EndpointConfig, EndpointOptions, EndpointResponse, Handler, InferBody, InferHeaders, InferRequest, Method, type Middleware, type MiddlewareHandler, Prettify, createEndpoint, createEndpointCreator, createMiddleware, createMiddlewareCreator, getBody, shouldSerialize, statusCode };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var D=Object.defineProperty;var g=(t,e,r)=>e in t?D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var f=(t,e,r)=>g(t,typeof e!="symbol"?e+"":e,r);import{ZodError as P}from"zod";import"zod";function H(t,e){if(typeof t=="function")return O("*",{method:"*"},t);if(!e)throw new Error("Middleware handler is required");return O("*",{...t,method:"*"},e)}var L=()=>{function t(e,r){if(typeof e=="function")return O("*",{method:"*"},e);if(!r)throw new Error("Middleware handler is required");return O("*",{...e,method:"*"},r)}return t};var c=class extends Error{constructor(r,a){super(`API Error: ${r} ${a?.message??""}`,{cause:a});f(this,"status");f(this,"body");this.status=r,this.body=a??{},this.stack="",this.name="BetterCallAPIError"}};function j(){return(t,e,r)=>O(t,e,r)}function O(t,e,r){let a=new Headers,p=async(...o)=>{let n={setHeader(s,d){a.set(s,d)},setCookie(s,d){a.append("Set-Cookie",`${s}=${d}`)},getCookie(s){return o[0]?.headers?.get("cookie")?.split(";").find(E=>E.startsWith(`${s}=`))?.split("=")[1]},...o[0]||{},context:{}};if(e.use?.length)for(let s of e.use){let d=await s(n),E=d.options?.body?d.options.body.parse(n.body):void 0;d&&(n={...n,body:E?{...E,...n.body}:n.body,context:{...n.context||{},...d}})}try{let s=e.body?e.body.parse(n.body):n.body;n={...n,body:s?{...s,...n.body}:n.body},n.query=e.query?e.query.parse(n.query):n.query,n.params=e.params?e.params.parse(n.params):n.params}catch(s){throw s instanceof P?new c("BAD_REQUEST",{message:s.message,details:s.errors}):s}if(e.requireHeaders&&!n.headers)throw new c("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!n.request)throw new c("BAD_REQUEST",{message:"Request is required"});return await r(n)};return p.path=t,p.options=e,p.method=e.method,p.headers=a,p}import{createRouter as I,addRoute as l,findRoute as N}from"rou3";async function w(t){let e=t.headers.get("content-type")||"";if(t.body){if(e.includes("application/json"))return await t.json();if(e.includes("application/x-www-form-urlencoded")){let r=await t.formData(),a={};return r.forEach((p,o)=>{a[o]=p.toString()}),a}if(e.includes("multipart/form-data")){let r=await t.formData(),a={};return r.forEach((p,o)=>{a[o]=p}),a}return e.includes("text/plain")?await t.text():e.includes("application/octet-stream")?await t.arrayBuffer():e.includes("application/pdf")||e.includes("image/")||e.includes("video/")?await t.blob():e.includes("application/stream")||t.body instanceof ReadableStream?t.body:await t.text()}}function _(t){return typeof t=="object"&&t!==null&&!(t instanceof Blob)&&!(t instanceof FormData)}var A={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};var Z=(t,e)=>{let r=I();for(let o of t)if(Array.isArray(o.options?.method))for(let n of o.options.method)l(r,n,o.path,o);else l(r,o.options.method,o.path,o);let a=I();for(let o of e?.routerMiddleware||[])l(a,"*",o.path,o.middleware);return{handler:async o=>{let n=new URL(o.url),u=n.pathname;e?.basePath&&(u=u.split(e.basePath)[1]);let s=o.method,d=N(r,s,u),E=d?.data,m=await w(o),y=o.headers,T=Object.fromEntries(n.searchParams),h=N(a,"*",u)?.data;if(!E)return new Response(null,{status:404,statusText:"Not Found"});try{let i={};if(h){let x=await h({path:u,method:s,headers:y,params:d?.params,request:o,body:m,query:T});x&&(i={...x,...i})}let R=await E({path:u,method:s,headers:y,params:d?.params,request:o,body:m,query:T,...i});if(R instanceof Response)return R;let C=_(R)?JSON.stringify(R):R;return new Response(C,{headers:E.headers})}catch(i){if(e?.onError){let R=await e.onError(i);if(R instanceof Response)return R}if(i instanceof c)return new Response(i.body?JSON.stringify(i.body):null,{status:A[i.status],statusText:i.status,headers:{"Content-Type":"application/json"}});if(e?.throwError)throw i;return new Response(null,{status:500,statusText:"Internal Server Error"})}}}};export{c as APIError,O as createEndpoint,j as createEndpointCreator,H as createMiddleware,L as createMiddlewareCreator,Z as createRouter,w as getBody,_ as shouldSerialize,A as statusCode};
1
+ var $=Object.defineProperty;var Q=(r,e,t)=>e in r?$(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var l=(r,e,t)=>Q(r,typeof e!="symbol"?e+"":e,t);import{ZodError as G}from"zod";import"zod";function j(r,e){if(typeof r=="function")return x("*",{method:"*"},r);if(!e)throw new Error("Middleware handler is required");return x("*",{...r,method:"*"},e)}var X=()=>{function r(e,t){if(typeof e=="function")return x("*",{method:"*"},e);if(!t)throw new Error("Middleware handler is required");return x("*",{...e,method:"*"},t)}return r};var y=class extends Error{constructor(t,n){super(`API Error: ${t} ${n?.message??""}`,{cause:n});l(this,"status");l(this,"body");this.status=t,this.body=n??{},this.stack="",this.name="BetterCallAPIError"}};var g={name:"HMAC",hash:"SHA-256"},w=async r=>{let e=typeof r=="string"?new TextEncoder().encode(r):r;return await crypto.subtle.importKey("raw",e,g,!1,["sign","verify"])},W=async(r,e)=>{let t=await w(e),n=await crypto.subtle.sign(g.name,t,new TextEncoder().encode(r));return btoa(String.fromCharCode(...new Uint8Array(n)))},v=async(r,e,t)=>{try{let n=atob(r),s=new Uint8Array(n.length);for(let i=0,o=n.length;i<o;i++)s[i]=n.charCodeAt(i);return await crypto.subtle.verify(g,t,s,new TextEncoder().encode(e))}catch{return!1}},K=/^[\w!#$%&'*.^`|~+-]+$/,F=/^[ !#-:<-[\]-~]*$/,R=(r,e)=>r.trim().split(";").reduce((n,s)=>{s=s.trim();let i=s.indexOf("=");if(i===-1)return n;let o=s.substring(0,i).trim();if(e&&e!==o||!K.test(o))return n;let p=s.substring(i+1).trim();return p.startsWith('"')&&p.endsWith('"')&&(p=p.slice(1,-1)),F.test(p)&&(n[o]=decodeURIComponent(p)),n},{}),I=async(r,e,t)=>{let n={},s=await w(e);for(let[i,o]of Object.entries(R(r,t))){let p=o.lastIndexOf(".");if(p<1)continue;let a=o.substring(0,p),d=o.substring(p+1);if(d.length!==44||!d.endsWith("="))continue;let u=await v(d,a,s);n[i]=u?a:!1}return n},k=(r,e,t={})=>{let n=`${r}=${e}`;if(r.startsWith("__Secure-")&&!t.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(r.startsWith("__Host-")){if(!t.secure)throw new Error("__Host- Cookie must have Secure attributes");if(t.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(t.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(t&&typeof t.maxAge=="number"&&t.maxAge>=0){if(t.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(t.maxAge)}`}if(t.domain&&t.prefix!=="host"&&(n+=`; Domain=${t.domain}`),t.path&&(n+=`; Path=${t.path}`),t.expires){if(t.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${t.expires.toUTCString()}`}if(t.httpOnly&&(n+="; HttpOnly"),t.secure&&(n+="; Secure"),t.sameSite&&(n+=`; SameSite=${t.sameSite.charAt(0).toUpperCase()+t.sameSite.slice(1)}`),t.partitioned){if(!t.secure)throw new Error("Partitioned Cookie must have Secure attributes");n+="; Partitioned"}return n},m=(r,e,t)=>(e=encodeURIComponent(e),k(r,e,t)),h=async(r,e,t,n={})=>{let s=await W(e,t);return e=`${e}.${s}`,e=encodeURIComponent(e),k(r,e,n)};var b=(r,e,t)=>{if(!r)return;let n=e;if(t==="secure")n="__Secure-"+e;else if(t==="host")n="__Host-"+e;else return;return R(r,n)[n]},A=(r,e,t,n)=>{let s;n?.prefix==="secure"?s=m("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?s=m("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):s=m(e,t,{path:"/",...n}),r.append("Set-Cookie",s)},H=async(r,e,t,n,s)=>{let i;s?.prefix==="secure"?i=await h("__Secure-"+e,t,n,{path:"/",...s,secure:!0}):s?.prefix==="host"?i=await h("__Host-"+e,t,n,{...s,path:"/",secure:!0,domain:void 0}):i=await h(e,t,n,{path:"/",...s}),r.append("Set-Cookie",i)},N=async(r,e,t,n)=>{let s=r.get("Cookie");if(!s)return;let i=t;return n==="secure"?i="__Secure-"+t:n==="host"&&(i="__Host-"+t),(await I(s,e,i))[i]};function fe(){return(r,e,t)=>x(r,e,t)}function x(r,e,t){let n=new Headers,s=async(...i)=>{let o={setHeader(a,d){n.set(a,d)},setCookie(a,d,u){A(n,a,d,u)},getCookie(a,d){let u=i[0]?.headers;return b(u?.get("Cookie")||"",a,d)},getSignedCookie(a,d,u){let c=i[0]?.headers;if(!c)throw new TypeError("Headers are required");return N(c,d,a,u)},async setSignedCookie(a,d,u,c){await H(n,a,d,u,c)},...i[0]||{},context:{}};if(e.use?.length)for(let a of e.use){let d=await a(o),u=d.options?.body?d.options.body.parse(o.body):void 0;d&&(o={...o,body:u?{...u,...o.body}:o.body,context:{...o.context||{},...d}})}try{let a=e.body?e.body.parse(o.body):o.body;o={...o,body:a?{...a,...o.body}:o.body},o.query=e.query?e.query.parse(o.query):o.query}catch(a){throw a instanceof G?new y("BAD_REQUEST",{message:a.message,details:a.errors}):a}if(e.requireHeaders&&!o.headers)throw new y("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!o.request)throw new y("BAD_REQUEST",{message:"Request is required"});return await t(o)};return s.path=r,s.options=e,s.method=e.method,s.headers=n,s}import{createRouter as q,addRoute as C,findRoute as B}from"rou3";async function D(r){let e=r.headers.get("content-type")||"";if(r.body){if(e.includes("application/json"))return await r.json();if(e.includes("application/x-www-form-urlencoded")){let t=await r.formData(),n={};return t.forEach((s,i)=>{n[i]=s.toString()}),n}if(e.includes("multipart/form-data")){let t=await r.formData(),n={};return t.forEach((s,i)=>{n[i]=s}),n}return e.includes("text/plain")?await r.text():e.includes("application/octet-stream")?await r.arrayBuffer():e.includes("application/pdf")||e.includes("image/")||e.includes("video/")?await r.blob():e.includes("application/stream")||r.body instanceof ReadableStream?r.body:await r.text()}}function U(r){return typeof r=="object"&&r!==null&&!(r instanceof Blob)&&!(r instanceof FormData)}var M={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};var he=(r,e)=>{let t=Object.values(r),n=q();for(let o of t)if(Array.isArray(o.options?.method))for(let p of o.options.method)C(n,p,o.path,o);else C(n,o.options.method,o.path,o);let s=q();for(let o of e?.routerMiddleware||[])C(s,"*",o.path,o.middleware);return{handler:async o=>{let p=new URL(o.url),a=p.pathname;e?.basePath&&(a=a.split(e.basePath)[1]);let d=o.method,u=B(n,d,a),c=u?.data,O=await D(o),P=o.headers,T=Object.fromEntries(p.searchParams),S=B(s,"*",a)?.data;if(!c)return new Response(null,{status:404,statusText:"Not Found"});try{let f={};if(S){let _=await S({path:a,method:d,headers:P,params:u?.params,request:o,body:O,query:T,...e?.extraContext});_&&(f={..._,...f})}let E=await c({path:a,method:d,headers:P,params:u?.params,request:o,body:O,query:T,...f,...e?.extraContext});if(E instanceof Response)return E;let L=U(E)?JSON.stringify(E):E;return new Response(L,{headers:c.headers})}catch(f){if(e?.onError){let E=await e.onError(f);if(E instanceof Response)return E}if(f instanceof y)return new Response(f.body?JSON.stringify(f.body):null,{status:M[f.status],statusText:f.status,headers:c.headers});if(e?.throwError)throw f;return new Response(null,{status:500,statusText:"Internal Server Error"})}},endpoints:r}};import"zod";export{y as APIError,x as createEndpoint,fe as createEndpointCreator,j as createMiddleware,X as createMiddlewareCreator,he as createRouter,D as getBody,U as shouldSerialize,M as statusCode};
2
2
  //# sourceMappingURL=index.js.map