better-call 0.0.5-beta.13 → 0.0.5-beta.15

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/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var x=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var D=(t,e,n)=>e in t?x(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var N=(t,e)=>{for(var n in e)x(t,n,{get:e[n],enumerable:!0})},H=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let d of S(e))!b.call(t,d)&&d!==n&&x(t,d,{get:()=>e[d],enumerable:!(s=w(e,d))||s.enumerable});return t};var M=t=>H(x({},"__esModule",{value:!0}),t);var l=(t,e,n)=>D(t,typeof e!="symbol"?e+"":e,n);var B={};N(B,{APIError:()=>y,createEndpoint:()=>m,createEndpointCreator:()=>L,createMiddleware:()=>U,createMiddlewareCreator:()=>q,createRouter:()=>$,getBody:()=>h,shouldSerialize:()=>c,statusCode:()=>P});module.exports=M(B);var g=require("zod");var Q=require("zod");function U(t,e){if(typeof t=="function")return m("*",{method:"*"},t);if(!e)throw new Error("Middleware handler is required");return m("*",{...t,method:"*"},e)}var q=()=>{function t(e,n){if(typeof e=="function")return m("*",{method:"*"},e);if(!n)throw new Error("Middleware handler is required");return m("*",{...e,method:"*"},n)}return t};var y=class extends Error{constructor(n,s){super(`API Error: ${n} ${s?.message??""}`,{cause:s});l(this,"status");l(this,"body");this.status=n,this.body=s??{},this.stack="",this.name="BetterCallAPIError"}};function L(){return(t,e,n)=>m(t,e,n)}function m(t,e,n){let s=new Headers,d=async(...o)=>{let r={setHeader(a,i){s.set(a,i)},setCookie(a,i,E){let f=E||{};s.append("Set-Cookie",`${a}=${i}; Max-Age=${f.maxAge||0}; Domain=${f.domain||""}; Path=${f.path||"/"}; Secure=${f.secure||!1}; HttpOnly=${f.httpOnly||!1}; SameSite=${f.sameSite||"none"}; Expires=${f.expires||""};`)},getCookie(a){return o[0]?.headers?.get("cookie")?.split(";").find(E=>E.startsWith(`${a}=`))?.split("=")[1]},...o[0]||{},context:{}};if(e.use?.length)for(let a of e.use){let i=await a(r),E=i.options?.body?i.options.body.parse(r.body):void 0;i&&(r={...r,body:E?{...E,...r.body}:r.body,context:{...r.context||{},...i}})}try{let a=e.body?e.body.parse(r.body):r.body;r={...r,body:a?{...a,...r.body}:r.body},r.query=e.query?e.query.parse(r.query):r.query,r.params=e.params?e.params.parse(r.params):r.params}catch(a){throw a instanceof g.ZodError?new y("BAD_REQUEST",{message:a.message,details:a.errors}):a}if(e.requireHeaders&&!r.headers)throw new y("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!r.request)throw new y("BAD_REQUEST",{message:"Request is required"});return await n(r)};return d.path=t,d.options=e,d.method=e.method,d.headers=s,d}var u=require("rou3");async function h(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 n=await t.formData(),s={};return n.forEach((d,o)=>{s[o]=d.toString()}),s}if(e.includes("multipart/form-data")){let n=await t.formData(),s={};return n.forEach((d,o)=>{s[o]=d}),s}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 c(t){return typeof t=="object"&&t!==null&&!(t instanceof Blob)&&!(t instanceof FormData)}var P={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 $=(t,e)=>{let n=(0,u.createRouter)();for(let o of t)if(Array.isArray(o.options?.method))for(let r of o.options.method)(0,u.addRoute)(n,r,o.path,o);else(0,u.addRoute)(n,o.options.method,o.path,o);let s=(0,u.createRouter)();for(let o of e?.routerMiddleware||[])(0,u.addRoute)(s,"*",o.path,o.middleware);return{handler:async o=>{let r=new URL(o.url),R=r.pathname;e?.basePath&&(R=R.split(e.basePath)[1]);let a=o.method,i=(0,u.findRoute)(n,a,R),E=i?.data,f=await h(o),T=o.headers,I=Object.fromEntries(r.searchParams),C=(0,u.findRoute)(s,"*",R)?.data;if(!E)return new Response(null,{status:404,statusText:"Not Found"});try{let p={};if(C){let _=await C({path:R,method:a,headers:T,params:i?.params,request:o,body:f,query:I,...e?.extraContext});_&&(p={..._,...p})}let O=await E({path:R,method:a,headers:T,params:i?.params,request:o,body:f,query:I,...p,...e?.extraContext});if(O instanceof Response)return O;let A=c(O)?JSON.stringify(O):O;return new Response(A,{headers:E.headers})}catch(p){if(e?.onError){let O=await e.onError(p);if(O instanceof Response)return O}if(p instanceof y)return new Response(p.body?JSON.stringify(p.body):null,{status:P[p.status],statusText:p.status,headers:{"Content-Type":"application/json"}});if(e?.throwError)throw p;return new Response(null,{status:500,statusText:"Internal Server Error"})}}}};var ne=require("zod");0&&(module.exports={APIError,createEndpoint,createEndpointCreator,createMiddleware,createMiddlewareCreator,createRouter,getBody,shouldSerialize,statusCode});
1
+ "use strict";var h=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var Q=Object.prototype.hasOwnProperty;var W=(r,e,t)=>e in r?h(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var K=(r,e)=>{for(var t in e)h(r,t,{get:e[t],enumerable:!0})},v=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $(e))!Q.call(r,s)&&s!==t&&h(r,s,{get:()=>e[s],enumerable:!(n=L(e,s))||n.enumerable});return r};var F=r=>v(h({},"__esModule",{value:!0}),r);var R=(r,e,t)=>W(r,typeof e!="symbol"?e+"":e,t);var ee={};K(ee,{APIError:()=>E,createEndpoint:()=>x,createEndpointCreator:()=>X,createMiddleware:()=>G,createMiddlewareCreator:()=>z,createRouter:()=>J,getBody:()=>T,shouldSerialize:()=>S,statusCode:()=>_});module.exports=F(ee);var q=require("zod");var re=require("zod");function G(r,e){if(typeof r=="function")return x("*",{method:"*"},r);if(!e)throw new Error("Middleware handler is required");return x("*",{...r,method:"*"},e)}var z=()=>{function r(e,t){if(typeof e=="function")return x("*",{method:"*"},e);if(!t)throw new Error("Middleware handler is required");return x("*",{...e,method:"*"},t)}return r};var E=class extends Error{constructor(t,n){super(`API Error: ${t} ${n?.message??""}`,{cause:n});R(this,"status");R(this,"body");this.status=t,this.body=n??{},this.stack="",this.name="BetterCallAPIError"}};var C={name:"HMAC",hash:"SHA-256"},b=async r=>{let e=typeof r=="string"?new TextEncoder().encode(r):r;return await crypto.subtle.importKey("raw",e,C,!1,["sign","verify"])},Z=async(r,e)=>{let t=await b(e),n=await crypto.subtle.sign(C.name,t,new TextEncoder().encode(r));return btoa(String.fromCharCode(...new Uint8Array(n)))},Y=async(r,e,t)=>{try{let n=atob(r),s=new Uint8Array(n.length);for(let o=0,i=n.length;o<i;o++)s[o]=n.charCodeAt(o);return await crypto.subtle.verify(C,t,s,new TextEncoder().encode(e))}catch{return!1}},V=/^[\w!#$%&'*.^`|~+-]+$/,j=/^[ !#-:<-[\]-~]*$/,P=(r,e)=>r.trim().split(";").reduce((n,s)=>{s=s.trim();let o=s.indexOf("=");if(o===-1)return n;let i=s.substring(0,o).trim();if(e&&e!==i||!V.test(i))return n;let p=s.substring(o+1).trim();return p.startsWith('"')&&p.endsWith('"')&&(p=p.slice(1,-1)),j.test(p)&&(n[i]=decodeURIComponent(p)),n},{}),A=async(r,e,t)=>{let n={},s=await b(e);for(let[o,i]of Object.entries(P(r,t))){let p=i.lastIndexOf(".");if(p<1)continue;let a=i.substring(0,p),d=i.substring(p+1);if(d.length!==44||!d.endsWith("="))continue;let u=await Y(d,a,s);n[o]=u?a:!1}return n},H=(r,e,t={})=>{let n=`${r}=${e}`;if(r.startsWith("__Secure-")&&!t.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(r.startsWith("__Host-")){if(!t.secure)throw new Error("__Host- Cookie must have Secure attributes");if(t.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(t.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(t&&typeof t.maxAge=="number"&&t.maxAge>=0){if(t.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(t.maxAge)}`}if(t.domain&&t.prefix!=="host"&&(n+=`; Domain=${t.domain}`),t.path&&(n+=`; Path=${t.path}`),t.expires){if(t.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${t.expires.toUTCString()}`}if(t.httpOnly&&(n+="; HttpOnly"),t.secure&&(n+="; Secure"),t.sameSite&&(n+=`; SameSite=${t.sameSite.charAt(0).toUpperCase()+t.sameSite.slice(1)}`),t.partitioned){if(!t.secure)throw new Error("Partitioned Cookie must have Secure attributes");n+="; Partitioned"}return n},O=(r,e,t)=>(e=encodeURIComponent(e),H(r,e,t)),l=async(r,e,t,n={})=>{let s=await Z(e,t);return e=`${e}.${s}`,e=encodeURIComponent(e),H(r,e,n)};var N=(r,e,t)=>{if(!r)return;let n=e;if(t==="secure")n="__Secure-"+e;else if(t==="host")n="__Host-"+e;else return;return P(r,n)[n]},D=(r,e,t,n)=>{let s;n?.prefix==="secure"?s=O("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?s=O("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):s=O(e,t,{path:"/",...n}),r.append("Set-Cookie",s)},U=async(r,e,t,n,s)=>{let o;s?.prefix==="secure"?o=await l("__Secure-"+e,t,n,{path:"/",...s,secure:!0}):s?.prefix==="host"?o=await l("__Host-"+e,t,n,{...s,path:"/",secure:!0,domain:void 0}):o=await l(e,t,n,{path:"/",...s}),r.append("Set-Cookie",o)},M=async(r,e,t,n)=>{let s=r.get("Cookie");if(!s)return;let o=t;return n==="secure"?o="__Secure-"+t:n==="host"&&(o="__Host-"+t),(await A(s,e,o))[o]};function X(){return(r,e,t)=>x(r,e,t)}function x(r,e,t){let n=new Headers,s=async(...o)=>{let i={setHeader(a,d){n.set(a,d)},setCookie(a,d,u){D(n,a,d,u)},getCookie(a,d){let u=o[0]?.headers;return N(u?.get("Cookie")||"",a,d)},getSignedCookie(a,d,u){let m=o[0]?.headers;if(!m)throw new TypeError("Headers are required");return M(m,d,a,u)},async setSignedCookie(a,d,u,m){await U(n,a,d,u,m)},...o[0]||{},context:{}};if(e.use?.length)for(let a of e.use){let d=await a(i),u=d.options?.body?d.options.body.parse(i.body):void 0;d&&(i={...i,body:u?{...u,...i.body}:i.body,context:{...i.context||{},...d}})}try{let a=e.body?e.body.parse(i.body):i.body;i={...i,body:a?{...a,...i.body}:i.body},i.query=e.query?e.query.parse(i.query):i.query,i.params=e.params?e.params.parse(i.params):i.params}catch(a){throw a instanceof q.ZodError?new E("BAD_REQUEST",{message:a.message,details:a.errors}):a}if(e.requireHeaders&&!i.headers)throw new E("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!i.request)throw new E("BAD_REQUEST",{message:"Request is required"});return await t(i)};return s.path=r,s.options=e,s.method=e.method,s.headers=n,s}var c=require("rou3");async function T(r){let e=r.headers.get("content-type")||"";if(r.body){if(e.includes("application/json"))return await r.json();if(e.includes("application/x-www-form-urlencoded")){let t=await r.formData(),n={};return t.forEach((s,o)=>{n[o]=s.toString()}),n}if(e.includes("multipart/form-data")){let t=await r.formData(),n={};return t.forEach((s,o)=>{n[o]=s}),n}return e.includes("text/plain")?await r.text():e.includes("application/octet-stream")?await r.arrayBuffer():e.includes("application/pdf")||e.includes("image/")||e.includes("video/")?await r.blob():e.includes("application/stream")||r.body instanceof ReadableStream?r.body:await r.text()}}function S(r){return typeof r=="object"&&r!==null&&!(r instanceof Blob)&&!(r instanceof FormData)}var _={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};var J=(r,e)=>{let t=(0,c.createRouter)();for(let o of r)if(Array.isArray(o.options?.method))for(let i of o.options.method)(0,c.addRoute)(t,i,o.path,o);else(0,c.addRoute)(t,o.options.method,o.path,o);let n=(0,c.createRouter)();for(let o of e?.routerMiddleware||[])(0,c.addRoute)(n,"*",o.path,o.middleware);return{handler:async o=>{let i=new URL(o.url),p=i.pathname;e?.basePath&&(p=p.split(e.basePath)[1]);let a=o.method,d=(0,c.findRoute)(t,a,p),u=d?.data,m=await T(o),g=o.headers,w=Object.fromEntries(i.searchParams),I=(0,c.findRoute)(n,"*",p)?.data;if(!u)return new Response(null,{status:404,statusText:"Not Found"});try{let f={};if(I){let k=await I({path:p,method:a,headers:g,params:d?.params,request:o,body:m,query:w,...e?.extraContext});k&&(f={...k,...f})}let y=await u({path:p,method:a,headers:g,params:d?.params,request:o,body:m,query:w,...f,...e?.extraContext});if(y instanceof Response)return y;let B=S(y)?JSON.stringify(y):y;return new Response(B,{headers:u.headers})}catch(f){if(e?.onError){let y=await e.onError(f);if(y instanceof Response)return y}if(f instanceof E)return new Response(f.body?JSON.stringify(f.body):null,{status:_[f.status],statusText:f.status,headers:u.headers});if(e?.throwError)throw f;return new Response(null,{status:500,statusText:"Internal Server Error"})}}}};var Re=require("zod");0&&(module.exports={APIError,createEndpoint,createEndpointCreator,createMiddleware,createMiddlewareCreator,createRouter,getBody,shouldSerialize,statusCode});
2
2
  //# sourceMappingURL=index.cjs.map
@@ -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","../src/types.ts"],"sourcesContent":["export * from \"./endpoint\"\nexport * from \"./router\"\nexport * from \"./middleware\"\nexport * from \"./better-call-error\"\nexport * from \"./utils\"\nexport * from \"./types\"","import { z, ZodError, type ZodOptional, type ZodSchema } from \"zod\"\nimport { createMiddleware, type Middleware } from \"./middleware\"\nimport { APIError } from \"./better-call-error\";\nimport type { HasRequiredKeys, UnionToIntersection } from \"./helper\";\nimport type { Context, ContextTools, CookieOptions, 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, options?: CookieOptions) {\n const cookieOptions = options || {}\n responseHeader.append(\"Set-Cookie\", `${key}=${value}; Max-Age=${cookieOptions.maxAge || 0}; Domain=${cookieOptions.domain || \"\"}; Path=${cookieOptions.path || \"/\"}; Secure=${cookieOptions.secure || false}; HttpOnly=${cookieOptions.httpOnly || false}; SameSite=${cookieOptions.sameSite || \"none\"}; Expires=${cookieOptions.expires || \"\"};`)\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 extraContext?: Record<string, any>\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 ...config?.extraContext\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 ...config?.extraContext\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","import { z, type ZodOptional, type ZodSchema } from \"zod\"\nimport type { Middleware } from \"./middleware\"\nimport type { UnionToIntersection } from \"./helper\";\n\n\nexport interface EndpointOptions {\n method: Method | Method[]\n body?: ZodSchema\n query?: ZodSchema\n params?: ZodSchema<any>\n /**\n * If true headers will be required to be passed in the context\n */\n requireHeaders?: boolean\n /**\n * If true request object will be required\n */\n requireRequest?: boolean\n /**\n * List of endpoints that will be called before this endpoint\n */\n use?: Endpoint[]\n}\n\nexport type Endpoint<Handler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>, Option extends EndpointOptions = EndpointOptions> = {\n path: string\n options: Option\n headers?: Headers\n} & (Handler)\n\nexport type InferParamPath<Path> =\n Path extends `${infer _Start}:${infer Param}/${infer Rest}`\n ? { [K in Param | keyof InferParamPath<Rest>]: string }\n : Path extends `${infer _Start}:${infer Param}`\n ? { [K in Param]: string }\n : Path extends `${infer _Start}/${infer Rest}`\n ? InferParamPath<Rest>\n : undefined;\n\nexport type InferParamWildCard<Path> = Path extends `${infer _Start}/*:${infer Param}/${infer Rest}` | `${infer _Start}/**:${infer Param}/${infer Rest}`\n ? { [K in Param | keyof InferParamPath<Rest>]: string }\n : Path extends `${infer _Start}/*`\n ? { [K in \"_\"]: string }\n : Path extends `${infer _Start}/${infer Rest}`\n ? InferParamPath<Rest>\n : undefined;\n\n\nexport type Prettify<T> = {\n [key in keyof T]: T[key];\n} & {};\n\n\nexport interface CookieOptions {\n /**\n * Max age in seconds\n */\n maxAge?: number\n /**\n * Domain\n */\n domain?: string\n /**\n * Path\n */\n path?: string\n /**\n * Secure\n */\n secure?: boolean\n /**\n * HttpOnly\n */\n httpOnly?: boolean\n\n /**\n * SameSite\n */\n sameSite?: 'strict' | 'lax' | 'none'\n /** \n * Expires\n */\n expires?: Date\n}\n\nexport type ContextTools = {\n /**\n * Set header\n * \n * If it's called outside of a request it will just be ignored.\n */\n setHeader: (key: string, value: string) => void\n /**\n * cookie setter.\n * \n * If it's called outside of a request it will just be ignored.\n */\n setCookie: (key: string, value: string, options?: CookieOptions) => void\n /**\n * Get cookie value\n * \n * If it's called outside of a request it will just be ignored.\n */\n getCookie: (key: string) => string | undefined\n}\n\nexport type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> & InferParam<Path> & InferMethod<Opts['method']> & InferHeaders<Opts> & InferRequest<Opts> & InferQuery<Opts[\"query\"]>\n\nexport type InferUse<Opts extends EndpointOptions> = Opts[\"use\"] extends Endpoint[] ? {\n context: UnionToIntersection<Awaited<ReturnType<Opts[\"use\"][number]>>>\n} : {}\n\nexport type InferUseOptions<Opts extends EndpointOptions> = Opts[\"use\"] extends Array<infer U> ? UnionToIntersection<U extends Endpoint ? U['options'] : {\n body?: {},\n requireRequest?: boolean\n requireHeaders?: boolean\n}> : {\n body?: {},\n requireRequest?: boolean\n requireHeaders?: boolean\n}\n\nexport type InferMethod<M extends Method | Method[]> = M extends Array<Method> ? {\n method: M[number]\n} : {\n method?: M\n}\n\nexport type InferHeaders<Opt extends EndpointOptions, HeaderReq = Opt[\"requireHeaders\"]> = HeaderReq extends true ? {\n headers: Headers\n} : InferUseOptions<Opt>['requireHeaders'] extends true ? {\n headers: Headers\n} : {\n headers?: Headers\n}\n\n\nexport type InferRequest<Opt extends EndpointOptions, RequestReq = Opt[\"requireRequest\"]> = RequestReq extends true ? {\n request: Request\n} : InferUseOptions<Opt>['requireRequest'] extends true ? {\n request: Request\n} : {\n request?: Request\n}\n\n\nexport type InferQuery<Query> = Query extends ZodSchema ? Query extends ZodOptional<any> ? {\n query?: z.infer<Query>\n} : {\n query: z.infer<Query>\n} : {\n query?: undefined\n}\n\nexport type InferParam<Path extends string, ParamPath extends InferParamPath<Path> = InferParamPath<Path>, WildCard extends InferParamWildCard<Path> = InferParamWildCard<Path>> = ParamPath extends undefined ? WildCard extends undefined ? {\n params?: Record<string, string>\n} : {\n params: WildCard\n} : {\n params: Prettify<ParamPath & (WildCard extends undefined ? {} : WildCard)>\n}\n\n\nexport type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined\n\nexport type Handler<Path extends string, Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts> & ContextTools> & Extra) => Promise<R>\n\nexport type Method = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"*\"\n\n\nexport type InferBody<Opts extends EndpointOptions, Body extends ZodSchema | undefined = (Opts[\"body\"] &\n (undefined extends InferUseOptions<Opts>['body'] ? {} : InferUseOptions<Opts>['body']))> = Body extends ZodSchema ? Body extends ZodOptional<any> ? {\n body?: Prettify<z.infer<Body>>\n } : {\n body: Prettify<z.infer<Body>>\n } : {\n body?: undefined\n }"],"mappings":"ijBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,cAAAE,EAAA,mBAAAC,EAAA,0BAAAC,EAAA,qBAAAC,EAAA,4BAAAC,EAAA,iBAAAC,EAAA,YAAAC,EAAA,oBAAAC,EAAA,eAAAC,IAAA,eAAAC,EAAAX,GCAA,IAAAY,EAA8D,eCA9D,IAAAC,EAAkB,eAiBX,SAASC,EAAiBC,EAAuBC,EAAe,CACnE,GAAI,OAAOD,GAAqB,WAC5B,OAAOE,EAAe,IAAK,CACvB,OAAQ,GACZ,EAAGF,CAAgB,EAEvB,GAAI,CAACC,EACD,MAAM,IAAI,MAAM,gCAAgC,EAMpD,OAJiBC,EAAe,IAAK,CACjC,GAAGF,EACH,OAAQ,GACZ,EAAGC,CAAO,CAEd,CAEO,IAAME,E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uBAChB,CAAC,CACL,CACJ,CAGA,CACJ,EExIA,IAAAI,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","createEndpointCreator","path","options","handler","createEndpoint","responseHeader","handle","ctx","internalCtx","key","value","cookieOptions","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","import_zod"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/endpoint.ts","../src/middleware.ts","../src/better-call-error.ts","../src/cookie.ts","../src/cookie-utils.ts","../src/router.ts","../src/utils.ts","../src/types.ts"],"sourcesContent":["export * from \"./endpoint\"\nexport * from \"./router\"\nexport * from \"./middleware\"\nexport * from \"./better-call-error\"\nexport * from \"./utils\"\nexport * from \"./types\"","import { z, ZodError, type ZodOptional, type ZodSchema } from \"zod\";\nimport { createMiddleware, type Middleware } from \"./middleware\";\nimport { APIError } from \"./better-call-error\";\nimport type { HasRequiredKeys, UnionToIntersection } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tCookieOptions,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n} from \"./types\";\nimport { getCookie, getSignedCookie, setCookie, setSignedCookie } from \"./cookie-utils\";\nimport type { CookiePrefixOptions } from \"./cookie\";\n\nexport interface EndpointConfig {\n\t/**\n\t * Throw when the response isn't in 200 range\n\t */\n\tthrowOnError?: boolean;\n}\n\nexport function createEndpointCreator<T extends Record<string, any>>() {\n\treturn <Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\tpath: Path,\n\t\toptions: Opts,\n\t\thandler: Handler<Path, Opts, R, T>,\n\t) => {\n\t\t//@ts-expect-error\n\t\treturn createEndpoint(path, options, handler);\n\t};\n}\n\nexport function createEndpoint<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n>(path: Path, options: Opts, handler: Handler<Path, Opts, R>) {\n\tconst responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\tconst handle = async (...ctx: HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]) => {\n\t\tlet internalCtx = {\n\t\t\tsetHeader(key: string, value: string) {\n\t\t\t\tresponseHeader.set(key, value);\n\t\t\t},\n\t\t\tsetCookie(key: string, value: string, options?: CookieOptions) {\n\t\t\t\tsetCookie(responseHeader, key, value, options);\n\t\t\t},\n\t\t\tgetCookie(key: string, prefix?: CookiePrefixOptions) {\n\t\t\t\tconst header = ctx[0]?.headers;\n\t\t\t\tconst cookie = getCookie(header?.get(\"Cookie\") || \"\", key, prefix);\n\t\t\t\treturn cookie;\n\t\t\t},\n\t\t\tgetSignedCookie(key: string, secret: string, prefix?: CookiePrefixOptions) {\n\t\t\t\tconst header = ctx[0]?.headers;\n\t\t\t\tif (!header) {\n\t\t\t\t\tthrow new TypeError(\"Headers are required\");\n\t\t\t\t}\n\t\t\t\tconst cookie = getSignedCookie(header, secret, key, prefix);\n\t\t\t\treturn cookie;\n\t\t\t},\n\t\t\tasync setSignedCookie(\n\t\t\t\tkey: string,\n\t\t\t\tvalue: string,\n\t\t\t\tsecret: string | BufferSource,\n\t\t\t\toptions?: CookieOptions,\n\t\t\t) {\n\t\t\t\tawait setSignedCookie(responseHeader, key, value, secret, options);\n\t\t\t},\n\t\t\t...(ctx[0] || {}),\n\t\t\tcontext: {},\n\t\t};\n\t\tif (options.use?.length) {\n\t\t\tfor (const middleware of options.use) {\n\t\t\t\tconst res = (await middleware(internalCtx)) as Endpoint;\n\t\t\t\tconst body = res.options?.body\n\t\t\t\t\t? res.options.body.parse(internalCtx.body)\n\t\t\t\t\t: undefined;\n\t\t\t\tif (res) {\n\t\t\t\t\tinternalCtx = {\n\t\t\t\t\t\t...internalCtx,\n\t\t\t\t\t\tbody: body\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t...body,\n\t\t\t\t\t\t\t\t\t...internalCtx.body,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: internalCtx.body,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t...(internalCtx.context || {}),\n\t\t\t\t\t\t\t...res,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst body = options.body ? options.body.parse(internalCtx.body) : internalCtx.body;\n\t\t\tinternalCtx = {\n\t\t\t\t...internalCtx,\n\t\t\t\tbody: body\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...body,\n\t\t\t\t\t\t\t...internalCtx.body,\n\t\t\t\t\t\t}\n\t\t\t\t\t: internalCtx.body,\n\t\t\t};\n\t\t\tinternalCtx.query = options.query\n\t\t\t\t? options.query.parse(internalCtx.query)\n\t\t\t\t: internalCtx.query;\n\t\t\tinternalCtx.params = options.params\n\t\t\t\t? options.params.parse(internalCtx.params)\n\t\t\t\t: internalCtx.params;\n\t\t} catch (e) {\n\t\t\tif (e instanceof ZodError) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: e.message,\n\t\t\t\t\tdetails: e.errors,\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t\tif (options.requireHeaders && !internalCtx.headers) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Headers are required\",\n\t\t\t});\n\t\t}\n\t\tif (options.requireRequest && !internalCtx.request) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Request is required\",\n\t\t\t});\n\t\t}\n\t\t//@ts-expect-error\n\t\tconst res = await handler(internalCtx);\n\t\treturn res as ReturnType<Handler<Path, Opts, R>>;\n\t};\n\thandle.path = path;\n\thandle.options = options;\n\thandle.method = options.method;\n\thandle.headers = responseHeader;\n\treturn handle;\n}\n","import { z } from \"zod\"\nimport type { ContextTools, Endpoint, EndpointOptions, EndpointResponse, Handler, InferBody, InferHeaders, InferRequest, Prettify } from \"./types\"\nimport { createEndpoint } from \"./endpoint\"\n\nexport type MiddlewareHandler<Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<InferBody<Opts> & InferRequest<Opts> & InferHeaders<Opts> & {\n params?: Record<string, string>,\n query?: Record<string, string>,\n} & ContextTools> & Extra) => Promise<R>\n\nexport function createMiddleware<Opts extends EndpointOptions, R extends EndpointResponse>(optionsOrHandler: MiddlewareHandler<Opts, R>): Endpoint<Handler<string, Opts, R>, Opts>\nexport function createMiddleware<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(optionsOrHandler: Opts, handler: MiddlewareHandler<Opts & {\n method: \"*\"\n}, R>): Endpoint<Handler<string, Opts & {\n method: \"*\"\n}, R>, Opts & {\n method: \"*\"\n}>\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n if (typeof optionsOrHandler === \"function\") {\n return createEndpoint(\"*\", {\n method: \"*\"\n }, optionsOrHandler)\n }\n if (!handler) {\n throw new Error(\"Middleware handler is required\")\n }\n const endpoint = createEndpoint(\"*\", {\n ...optionsOrHandler,\n method: \"*\"\n }, handler)\n return endpoint as any\n}\n\nexport const createMiddlewareCreator = <ExtraContext extends Record<string, any> = {}>() => {\n function fn<Opts extends EndpointOptions, R extends EndpointResponse>(optionsOrHandler: MiddlewareHandler<Opts, R, ExtraContext>): Endpoint<Handler<string, Opts, R>, Opts>\n function fn<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(optionsOrHandler: Opts, handler: MiddlewareHandler<Opts & {\n method: \"*\"\n }, R, ExtraContext>): Endpoint<Handler<string, Opts & {\n method: \"*\"\n }, R>, Opts & {\n method: \"*\"\n }>\n function fn(optionsOrHandler: any, handler?: any) {\n if (typeof optionsOrHandler === \"function\") {\n return createEndpoint(\"*\", {\n method: \"*\"\n }, optionsOrHandler)\n }\n if (!handler) {\n throw new Error(\"Middleware handler is required\")\n }\n const endpoint = createEndpoint(\"*\", {\n ...optionsOrHandler,\n method: \"*\"\n }, handler)\n return endpoint as any\n }\n return fn\n}\n\nexport type Middleware<Opts extends EndpointOptions = EndpointOptions, R extends EndpointResponse = EndpointResponse> = (opts: Opts, handler: (ctx: {\n body?: InferBody<Opts>,\n params?: Record<string, string>,\n query?: Record<string, string>\n}) => Promise<R>) => Endpoint","import type { statusCode } from \"./utils\"\n\ntype Status = keyof typeof statusCode\n\nexport class APIError extends Error {\n status: Status\n body: Record<string, any>\n constructor(\n status: Status,\n body?: Record<string, any>,\n ) {\n super(\n `API Error: ${status} ${body?.message ?? \"\"}`,\n {\n cause: body,\n }\n )\n this.status = status\n this.body = body ?? {}\n this.stack = \"\";\n this.name = \"BetterCallAPIError\"\n }\n}","//https://github.com/honojs/hono/blob/main/src/utils/cookie.ts\n\nexport type Cookie = Record<string, string>;\nexport type SignedCookie = Record<string, string | false>;\n\ntype PartitionCookieConstraint =\n\t| { partition: true; secure: true }\n\t| { partition?: boolean; secure?: boolean }; // reset to default\ntype SecureCookieConstraint = { secure: true };\ntype HostCookieConstraint = { secure: true; path: \"/\"; domain?: undefined };\n\nexport type CookieOptions = {\n\tdomain?: string;\n\texpires?: Date;\n\thttpOnly?: boolean;\n\tmaxAge?: number;\n\tpath?: string;\n\tsecure?: boolean;\n\tsigningSecret?: string;\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\tpartitioned?: boolean;\n\tprefix?: CookiePrefixOptions;\n} & PartitionCookieConstraint;\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieConstraint<Name> = Name extends `__Secure-${string}`\n\t? CookieOptions & SecureCookieConstraint\n\t: Name extends `__Host-${string}`\n\t\t? CookieOptions & HostCookieConstraint\n\t\t: CookieOptions;\n\nconst algorithm = { name: \"HMAC\", hash: \"SHA-256\" };\n\nconst getCryptoKey = async (secret: string | BufferSource): Promise<CryptoKey> => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await crypto.subtle.importKey(\"raw\", secretBuf, algorithm, false, [\"sign\", \"verify\"]);\n};\n\nconst makeSignature = async (value: string, secret: string | BufferSource): Promise<string> => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await crypto.subtle.sign(\n\t\talgorithm.name,\n\t\tkey,\n\t\tnew TextEncoder().encode(value),\n\t);\n\t// the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n\nconst verifySignature = async (\n\tbase64Signature: string,\n\tvalue: string,\n\tsecret: CryptoKey,\n): Promise<boolean> => {\n\ttry {\n\t\tconst signatureBinStr = atob(base64Signature);\n\t\tconst signature = new Uint8Array(signatureBinStr.length);\n\t\tfor (let i = 0, len = signatureBinStr.length; i < len; i++) {\n\t\t\tsignature[i] = signatureBinStr.charCodeAt(i);\n\t\t}\n\t\treturn await crypto.subtle.verify(\n\t\t\talgorithm,\n\t\t\tsecret,\n\t\t\tsignature,\n\t\t\tnew TextEncoder().encode(value),\n\t\t);\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\n\n// all alphanumeric chars and all of _!#$%&'*.^`|~+-\n// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)\nconst validCookieNameRegEx = /^[\\w!#$%&'*.^`|~+-]+$/;\n\n// all ASCII chars 32-126 except 34, 59, and 92 (i.e. space to tilde but not double quote, semicolon, or backslash)\n// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)\n//\n// note: the spec also prohibits comma and space, but we allow both since they are very common in the real world\n// (see: https://github.com/golang/go/issues/7243)\nconst validCookieValueRegEx = /^[ !#-:<-[\\]-~]*$/;\n\nexport const parse = (cookie: string, name?: string): Cookie => {\n\tconst pairs = cookie.trim().split(\";\");\n\treturn pairs.reduce((parsedCookie, pairStr) => {\n\t\tpairStr = pairStr.trim();\n\t\tconst valueStartPos = pairStr.indexOf(\"=\");\n\t\tif (valueStartPos === -1) {\n\t\t\treturn parsedCookie;\n\t\t}\n\n\t\tconst cookieName = pairStr.substring(0, valueStartPos).trim();\n\t\tif ((name && name !== cookieName) || !validCookieNameRegEx.test(cookieName)) {\n\t\t\treturn parsedCookie;\n\t\t}\n\n\t\tlet cookieValue = pairStr.substring(valueStartPos + 1).trim();\n\t\tif (cookieValue.startsWith('\"') && cookieValue.endsWith('\"')) {\n\t\t\tcookieValue = cookieValue.slice(1, -1);\n\t\t}\n\t\tif (validCookieValueRegEx.test(cookieValue)) {\n\t\t\tparsedCookie[cookieName] = decodeURIComponent(cookieValue);\n\t\t}\n\n\t\treturn parsedCookie;\n\t}, {} as Cookie);\n};\n\nexport const parseSigned = async (\n\tcookie: string,\n\tsecret: string | BufferSource,\n\tname?: string,\n): Promise<SignedCookie> => {\n\tconst parsedCookie: SignedCookie = {};\n\tconst secretKey = await getCryptoKey(secret);\n\n\tfor (const [key, value] of Object.entries(parse(cookie, name))) {\n\t\tconst signatureStartPos = value.lastIndexOf(\".\");\n\t\tif (signatureStartPos < 1) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst signedValue = value.substring(0, signatureStartPos);\n\t\tconst signature = value.substring(signatureStartPos + 1);\n\t\tif (signature.length !== 44 || !signature.endsWith(\"=\")) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst isVerified = await verifySignature(signature, signedValue, secretKey);\n\t\tparsedCookie[key] = isVerified ? signedValue : false;\n\t}\n\n\treturn parsedCookie;\n};\n\nconst _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {\n\tlet cookie = `${name}=${value}`;\n\n\tif (name.startsWith(\"__Secure-\") && !opt.secure) {\n\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.1\n\t\tthrow new Error(\"__Secure- Cookie must have Secure attributes\");\n\t}\n\n\tif (name.startsWith(\"__Host-\")) {\n\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.2\n\t\tif (!opt.secure) {\n\t\t\tthrow new Error(\"__Host- Cookie must have Secure attributes\");\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\tthrow new Error('__Host- Cookie must have Path attributes with \"/\"');\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\tthrow new Error(\"__Host- Cookie must not have Domain attributes\");\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.2\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.1\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\t// FIXME: replace link to RFC\n\t\t// https://www.ietf.org/archive/id/draft-cutler-httpbis-partitioned-cookies-01.html#section-2.3\n\t\tif (!opt.secure) {\n\t\t\tthrow new Error(\"Partitioned Cookie must have Secure attributes\");\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serialize = <Name extends string>(\n\tname: Name,\n\tvalue: string,\n\topt?: CookieConstraint<Name>,\n): string => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(name, value, opt);\n};\n\nexport const serializeSigned = async (\n\tname: string,\n\tvalue: string,\n\tsecret: string | BufferSource,\n\topt: CookieOptions = {},\n): Promise<string> => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(name, value, opt);\n};\n","//https://github.com/honojs/hono/blob/main/src/helper/cookie/index.ts\n\nimport {\n\tparse,\n\tparseSigned,\n\tserialize,\n\tserializeSigned,\n\ttype CookieOptions,\n\ttype CookiePrefixOptions,\n} from \"./cookie\";\n\nexport const getCookie = (cookie?: string, key?: string, prefix?: CookiePrefixOptions) => {\n\tif (!cookie) {\n\t\treturn undefined;\n\t}\n\tlet finalKey = key;\n\tif (prefix === \"secure\") {\n\t\tfinalKey = \"__Secure-\" + key;\n\t} else if (prefix === \"host\") {\n\t\tfinalKey = \"__Host-\" + key;\n\t} else {\n\t\treturn undefined;\n\t}\n\tconst obj = parse(cookie, finalKey);\n\treturn obj[finalKey];\n};\n\nexport const setCookie = (\n\theader: Headers,\n\tname: string,\n\tvalue: string,\n\topt?: CookieOptions,\n): void => {\n\t// Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.\n\t// Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)\n\t// and must not have a Domain attribute.\n\t// Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'\n\tlet cookie;\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = serialize(\"__Secure-\" + name, value, { path: \"/\", ...opt, secure: true });\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = serialize(\"__Host-\" + name, value, {\n\t\t\t...opt,\n\t\t\tpath: \"/\",\n\t\t\tsecure: true,\n\t\t\tdomain: undefined,\n\t\t});\n\t} else {\n\t\tcookie = serialize(name, value, { path: \"/\", ...opt });\n\t}\n\theader.append(\"Set-Cookie\", cookie);\n};\n\nexport const setSignedCookie = async (\n\theader: Headers,\n\tname: string,\n\tvalue: string,\n\tsecret: string | BufferSource,\n\topt?: CookieOptions,\n): Promise<void> => {\n\tlet cookie;\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = await serializeSigned(\"__Secure-\" + name, value, secret, {\n\t\t\tpath: \"/\",\n\t\t\t...opt,\n\t\t\tsecure: true,\n\t\t});\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = await serializeSigned(\"__Host-\" + name, value, secret, {\n\t\t\t...opt,\n\t\t\tpath: \"/\",\n\t\t\tsecure: true,\n\t\t\tdomain: undefined,\n\t\t});\n\t} else {\n\t\tcookie = await serializeSigned(name, value, secret, { path: \"/\", ...opt });\n\t}\n\theader.append(\"Set-Cookie\", cookie);\n};\n\nexport const getSignedCookie = async (\n\theader: Headers,\n\tsecret: string,\n\tkey: string,\n\tprefix?: CookiePrefixOptions,\n) => {\n\tconst cookie = header.get(\"Cookie\");\n\tif (!cookie) {\n\t\treturn undefined;\n\t}\n\tlet finalKey = key;\n\tif (prefix === \"secure\") {\n\t\tfinalKey = \"__Secure-\" + key;\n\t} else if (prefix === \"host\") {\n\t\tfinalKey = \"__Host-\" + key;\n\t}\n\tconst obj = await parseSigned(cookie, secret, finalKey);\n\treturn obj[finalKey];\n};\n","import {\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 extraContext?: Record<string, any>\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 ...config?.extraContext\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 ...config?.extraContext\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: handler.headers,\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","import { z, type ZodOptional, type ZodSchema } from \"zod\";\nimport type { Middleware } from \"./middleware\";\nimport type { UnionToIntersection } from \"./helper\";\nimport type { CookiePrefixOptions } from \"./cookie\";\n\nexport interface EndpointOptions {\n\tmethod: Method | Method[];\n\tbody?: ZodSchema;\n\tquery?: ZodSchema;\n\tparams?: ZodSchema<any>;\n\t/**\n\t * If true headers will be required to be passed in the context\n\t */\n\trequireHeaders?: boolean;\n\t/**\n\t * If true request object will be required\n\t */\n\trequireRequest?: boolean;\n\t/**\n\t * List of endpoints that will be called before this endpoint\n\t */\n\tuse?: Endpoint[];\n}\n\nexport type Endpoint<\n\tHandler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>,\n\tOption extends EndpointOptions = EndpointOptions,\n> = {\n\tpath: string;\n\toptions: Option;\n\theaders?: Headers;\n} & Handler;\n\nexport type InferParamPath<Path> = Path extends `${infer _Start}:${infer Param}/${infer Rest}`\n\t? { [K in Param | keyof InferParamPath<Rest>]: string }\n\t: Path extends `${infer _Start}:${infer Param}`\n\t\t? { [K in Param]: string }\n\t\t: Path extends `${infer _Start}/${infer Rest}`\n\t\t\t? InferParamPath<Rest>\n\t\t\t: undefined;\n\nexport type InferParamWildCard<Path> = Path extends\n\t| `${infer _Start}/*:${infer Param}/${infer Rest}`\n\t| `${infer _Start}/**:${infer Param}/${infer Rest}`\n\t? { [K in Param | keyof InferParamPath<Rest>]: string }\n\t: Path extends `${infer _Start}/*`\n\t\t? { [K in \"_\"]: string }\n\t\t: Path extends `${infer _Start}/${infer Rest}`\n\t\t\t? InferParamPath<Rest>\n\t\t\t: undefined;\n\nexport type Prettify<T> = {\n\t[key in keyof T]: T[key];\n} & {};\n\nexport interface CookieOptions {\n\t/**\n\t * Max age in seconds\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Domain\n\t */\n\tdomain?: string;\n\t/**\n\t * Path\n\t */\n\tpath?: string;\n\t/**\n\t * Secure\n\t */\n\tsecure?: boolean;\n\t/**\n\t * HttpOnly\n\t */\n\thttpOnly?: boolean;\n\n\t/**\n\t * SameSite\n\t */\n\tsameSite?: \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Expires\n\t */\n\texpires?: Date;\n}\n\nexport type ContextTools = {\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * cookie setter.\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetCookie: (key: string, value: string, options?: CookieOptions) => void;\n\t/**\n\t * Get cookie value\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tgetCookie: (key: string, value: string, options?: CookieOptions) => string | undefined;\n\t/**\n\t * Set signed cookie\n\t */\n\tsetSignedCookie: (\n\t\tkey: string,\n\t\tvalue: string,\n\t\tsecret: string | BufferSource,\n\t\toptions?: CookieOptions,\n\t) => Promise<void>;\n\t/**\n\t * Get signed cookie value\n\t */\n\n\tgetSignedCookie: (\n\t\tkey: string,\n\t\tsecret: string,\n\t\tprefix?: CookiePrefixOptions,\n\t) => Promise<string | undefined>;\n};\n\nexport type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> &\n\tInferParam<Path> &\n\tInferMethod<Opts[\"method\"]> &\n\tInferHeaders<Opts> &\n\tInferRequest<Opts> &\n\tInferQuery<Opts[\"query\"]>;\n\nexport type InferUse<Opts extends EndpointOptions> = Opts[\"use\"] extends Endpoint[]\n\t? {\n\t\t\tcontext: UnionToIntersection<Awaited<ReturnType<Opts[\"use\"][number]>>>;\n\t\t}\n\t: {};\n\nexport type InferUseOptions<Opts extends EndpointOptions> = Opts[\"use\"] extends Array<infer U>\n\t? UnionToIntersection<\n\t\t\tU extends Endpoint\n\t\t\t\t? U[\"options\"]\n\t\t\t\t: {\n\t\t\t\t\t\tbody?: {};\n\t\t\t\t\t\trequireRequest?: boolean;\n\t\t\t\t\t\trequireHeaders?: boolean;\n\t\t\t\t\t}\n\t\t>\n\t: {\n\t\t\tbody?: {};\n\t\t\trequireRequest?: boolean;\n\t\t\trequireHeaders?: boolean;\n\t\t};\n\nexport type InferMethod<M extends Method | Method[]> = M extends Array<Method>\n\t? {\n\t\t\tmethod: M[number];\n\t\t}\n\t: {\n\t\t\tmethod?: M;\n\t\t};\n\nexport type InferHeaders<\n\tOpt extends EndpointOptions,\n\tHeaderReq = Opt[\"requireHeaders\"],\n> = HeaderReq extends true\n\t? {\n\t\t\theaders: Headers;\n\t\t}\n\t: InferUseOptions<Opt>[\"requireHeaders\"] extends true\n\t\t? {\n\t\t\t\theaders: Headers;\n\t\t\t}\n\t\t: {\n\t\t\t\theaders?: Headers;\n\t\t\t};\n\nexport type InferRequest<\n\tOpt extends EndpointOptions,\n\tRequestReq = Opt[\"requireRequest\"],\n> = RequestReq extends true\n\t? {\n\t\t\trequest: Request;\n\t\t}\n\t: InferUseOptions<Opt>[\"requireRequest\"] extends true\n\t\t? {\n\t\t\t\trequest: Request;\n\t\t\t}\n\t\t: {\n\t\t\t\trequest?: Request;\n\t\t\t};\n\nexport type InferQuery<Query> = Query extends ZodSchema\n\t? Query extends ZodOptional<any>\n\t\t? {\n\t\t\t\tquery?: z.infer<Query>;\n\t\t\t}\n\t\t: {\n\t\t\t\tquery: z.infer<Query>;\n\t\t\t}\n\t: {\n\t\t\tquery?: undefined;\n\t\t};\n\nexport type InferParam<\n\tPath extends string,\n\tParamPath extends InferParamPath<Path> = InferParamPath<Path>,\n\tWildCard extends InferParamWildCard<Path> = InferParamWildCard<Path>,\n> = ParamPath extends undefined\n\t? WildCard extends undefined\n\t\t? {\n\t\t\t\tparams?: Record<string, string>;\n\t\t\t}\n\t\t: {\n\t\t\t\tparams: WildCard;\n\t\t\t}\n\t: {\n\t\t\tparams: Prettify<ParamPath & (WildCard extends undefined ? {} : WildCard)>;\n\t\t};\n\nexport type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined;\n\nexport type Handler<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n\tExtra extends Record<string, any> = {},\n> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts> & ContextTools> & Extra) => Promise<R>;\n\nexport type Method = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"*\";\n\nexport type InferBody<\n\tOpts extends EndpointOptions,\n\tBody extends ZodSchema | undefined = Opts[\"body\"] &\n\t\t(undefined extends InferUseOptions<Opts>[\"body\"] ? {} : InferUseOptions<Opts>[\"body\"]),\n> = Body extends ZodSchema\n\t? Body extends ZodOptional<any>\n\t\t? {\n\t\t\t\tbody?: Prettify<z.infer<Body>>;\n\t\t\t}\n\t\t: {\n\t\t\t\tbody: Prettify<z.infer<Body>>;\n\t\t\t}\n\t: {\n\t\t\tbody?: undefined;\n\t\t};\n"],"mappings":"ijBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,cAAAE,EAAA,mBAAAC,EAAA,0BAAAC,EAAA,qBAAAC,EAAA,4BAAAC,EAAA,iBAAAC,EAAA,YAAAC,EAAA,oBAAAC,EAAA,eAAAC,IAAA,eAAAC,EAAAX,ICAA,IAAAY,EAA8D,eCA9D,IAAAC,GAAkB,eAiBX,SAASC,EAAiBC,EAAuBC,EAAe,CACnE,GAAI,OAAOD,GAAqB,WAC5B,OAAOE,EAAe,IAAK,CACvB,OAAQ,GACZ,EAAGF,CAAgB,EAEvB,GAAI,CAACC,EACD,MAAM,IAAI,MAAM,gCAAgC,EAMpD,OAJiBC,EAAe,IAAK,CACjC,GAAGF,EACH,OAAQ,GACZ,EAAGC,CAAO,CAEd,CAEO,IAAME,EAA0B,IAAqD,CASxF,SAASC,EAAGJ,EAAuBC,EAAe,CAC9C,GAAI,OAAOD,GAAqB,WAC5B,OAAOE,EAAe,IAAK,CACvB,OAAQ,GACZ,EAAGF,CAAgB,EAEvB,GAAI,CAACC,EACD,MAAM,IAAI,MAAM,gCAAgC,EAMpD,OAJiBC,EAAe,IAAK,CACjC,GAAGF,EACH,OAAQ,GACZ,EAAGC,CAAO,CAEd,CACA,OAAOG,CACX,ECtDO,IAAMC,EAAN,cAAuB,KAAM,CAGhC,YACIC,EACAC,EACF,CACE,MACI,cAAcD,CAAM,IAAIC,GAAM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,IACAD,EAAoB,CAChB,GAAGC,EACH,GAAGD,CACP,EAER,CACA,IAAME,EAAa,MAAMR,EAAQ,CAC7B,KAAMD,EACN,OAAQL,EACR,QAAAS,EACA,OAAQP,GAAO,OACf,QAASC,EACT,KAAMI,EACN,MAAAG,EACA,GAAGE,EACH,GAAGhB,GAAQ,YACf,CAAC,EACD,GAAIkB,aAAsB,SACtB,OAAOA,EAEX,IAAMC,EAAUC,EAAgBF,CAAU,EAAI,KAAK,UAAUA,CAAU,EAAIA,EAC3E,OAAO,IAAI,SAASC,EAAgB,CAChC,QAAST,EAAQ,OACrB,CAAC,CACL,OAASW,EAAG,CACR,GAAIrB,GAAQ,QAAS,CACjB,IAAMsB,EAAa,MAAMtB,EAAO,QAAQqB,CAAC,EACzC,GAAIC,aAAsB,SACtB,OAAOA,CAEf,CACA,GAAID,aAAaE,EACb,OAAO,IAAI,SAASF,EAAE,KAAO,KAAK,UAAUA,EAAE,IAAI,EAAI,KAAM,CACxD,OAAQG,EAAWH,EAAE,MAAM,EAC3B,WAAYA,EAAE,OACd,QAASX,EAAQ,OACrB,CAAC,EAEL,GAAIV,GAAQ,WACR,MAAMqB,EAEV,OAAO,IAAI,SAAS,KAAM,CACtB,OAAQ,IACR,WAAY,uBAChB,CAAC,CACL,CACJ,CAGA,CACJ,EEtIA,IAAAI,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","i","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","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
@@ -6,6 +6,8 @@ type RequiredKeysOf<BaseType extends object> = Exclude<{
6
6
  }[keyof BaseType], undefined>;
7
7
  type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never ? false : true;
8
8
 
9
+ type CookiePrefixOptions = "host" | "secure";
10
+
9
11
  interface EndpointOptions {
10
12
  method: Method | Method[];
11
13
  body?: ZodSchema;
@@ -28,7 +30,7 @@ type Endpoint<Handler extends (ctx: any) => Promise<any> = (ctx: any) => Promise
28
30
  path: string;
29
31
  options: Option;
30
32
  headers?: Headers;
31
- } & (Handler);
33
+ } & Handler;
32
34
  type InferParamPath<Path> = Path extends `${infer _Start}:${infer Param}/${infer Rest}` ? {
33
35
  [K in Param | keyof InferParamPath<Rest>]: string;
34
36
  } : Path extends `${infer _Start}:${infer Param}` ? {
@@ -66,7 +68,7 @@ interface CookieOptions {
66
68
  /**
67
69
  * SameSite
68
70
  */
69
- sameSite?: 'strict' | 'lax' | 'none';
71
+ sameSite?: "strict" | "lax" | "none";
70
72
  /**
71
73
  * Expires
72
74
  */
@@ -90,13 +92,21 @@ type ContextTools = {
90
92
  *
91
93
  * If it's called outside of a request it will just be ignored.
92
94
  */
93
- getCookie: (key: string) => string | undefined;
95
+ getCookie: (key: string, value: string, options?: CookieOptions) => string | undefined;
96
+ /**
97
+ * Set signed cookie
98
+ */
99
+ setSignedCookie: (key: string, value: string, secret: string | BufferSource, options?: CookieOptions) => Promise<void>;
100
+ /**
101
+ * Get signed cookie value
102
+ */
103
+ getSignedCookie: (key: string, secret: string, prefix?: CookiePrefixOptions) => Promise<string | undefined>;
94
104
  };
95
- type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> & InferParam<Path> & InferMethod<Opts['method']> & InferHeaders<Opts> & InferRequest<Opts> & InferQuery<Opts["query"]>;
105
+ type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> & InferParam<Path> & InferMethod<Opts["method"]> & InferHeaders<Opts> & InferRequest<Opts> & InferQuery<Opts["query"]>;
96
106
  type InferUse<Opts extends EndpointOptions> = Opts["use"] extends Endpoint[] ? {
97
107
  context: UnionToIntersection<Awaited<ReturnType<Opts["use"][number]>>>;
98
108
  } : {};
99
- type InferUseOptions<Opts extends EndpointOptions> = Opts["use"] extends Array<infer U> ? UnionToIntersection<U extends Endpoint ? U['options'] : {
109
+ type InferUseOptions<Opts extends EndpointOptions> = Opts["use"] extends Array<infer U> ? UnionToIntersection<U extends Endpoint ? U["options"] : {
100
110
  body?: {};
101
111
  requireRequest?: boolean;
102
112
  requireHeaders?: boolean;
@@ -112,14 +122,14 @@ type InferMethod<M extends Method | Method[]> = M extends Array<Method> ? {
112
122
  };
113
123
  type InferHeaders<Opt extends EndpointOptions, HeaderReq = Opt["requireHeaders"]> = HeaderReq extends true ? {
114
124
  headers: Headers;
115
- } : InferUseOptions<Opt>['requireHeaders'] extends true ? {
125
+ } : InferUseOptions<Opt>["requireHeaders"] extends true ? {
116
126
  headers: Headers;
117
127
  } : {
118
128
  headers?: Headers;
119
129
  };
120
130
  type InferRequest<Opt extends EndpointOptions, RequestReq = Opt["requireRequest"]> = RequestReq extends true ? {
121
131
  request: Request;
122
- } : InferUseOptions<Opt>['requireRequest'] extends true ? {
132
+ } : InferUseOptions<Opt>["requireRequest"] extends true ? {
123
133
  request: Request;
124
134
  } : {
125
135
  request?: Request;
@@ -141,7 +151,7 @@ type InferParam<Path extends string, ParamPath extends InferParamPath<Path> = In
141
151
  type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined;
142
152
  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>;
143
153
  type Method = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "*";
144
- 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> ? {
154
+ 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> ? {
145
155
  body?: Prettify<z.infer<Body>>;
146
156
  } : {
147
157
  body: Prettify<z.infer<Body>>;
package/dist/index.d.ts CHANGED
@@ -6,6 +6,8 @@ type RequiredKeysOf<BaseType extends object> = Exclude<{
6
6
  }[keyof BaseType], undefined>;
7
7
  type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never ? false : true;
8
8
 
9
+ type CookiePrefixOptions = "host" | "secure";
10
+
9
11
  interface EndpointOptions {
10
12
  method: Method | Method[];
11
13
  body?: ZodSchema;
@@ -28,7 +30,7 @@ type Endpoint<Handler extends (ctx: any) => Promise<any> = (ctx: any) => Promise
28
30
  path: string;
29
31
  options: Option;
30
32
  headers?: Headers;
31
- } & (Handler);
33
+ } & Handler;
32
34
  type InferParamPath<Path> = Path extends `${infer _Start}:${infer Param}/${infer Rest}` ? {
33
35
  [K in Param | keyof InferParamPath<Rest>]: string;
34
36
  } : Path extends `${infer _Start}:${infer Param}` ? {
@@ -66,7 +68,7 @@ interface CookieOptions {
66
68
  /**
67
69
  * SameSite
68
70
  */
69
- sameSite?: 'strict' | 'lax' | 'none';
71
+ sameSite?: "strict" | "lax" | "none";
70
72
  /**
71
73
  * Expires
72
74
  */
@@ -90,13 +92,21 @@ type ContextTools = {
90
92
  *
91
93
  * If it's called outside of a request it will just be ignored.
92
94
  */
93
- getCookie: (key: string) => string | undefined;
95
+ getCookie: (key: string, value: string, options?: CookieOptions) => string | undefined;
96
+ /**
97
+ * Set signed cookie
98
+ */
99
+ setSignedCookie: (key: string, value: string, secret: string | BufferSource, options?: CookieOptions) => Promise<void>;
100
+ /**
101
+ * Get signed cookie value
102
+ */
103
+ getSignedCookie: (key: string, secret: string, prefix?: CookiePrefixOptions) => Promise<string | undefined>;
94
104
  };
95
- type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> & InferParam<Path> & InferMethod<Opts['method']> & InferHeaders<Opts> & InferRequest<Opts> & InferQuery<Opts["query"]>;
105
+ type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> & InferParam<Path> & InferMethod<Opts["method"]> & InferHeaders<Opts> & InferRequest<Opts> & InferQuery<Opts["query"]>;
96
106
  type InferUse<Opts extends EndpointOptions> = Opts["use"] extends Endpoint[] ? {
97
107
  context: UnionToIntersection<Awaited<ReturnType<Opts["use"][number]>>>;
98
108
  } : {};
99
- type InferUseOptions<Opts extends EndpointOptions> = Opts["use"] extends Array<infer U> ? UnionToIntersection<U extends Endpoint ? U['options'] : {
109
+ type InferUseOptions<Opts extends EndpointOptions> = Opts["use"] extends Array<infer U> ? UnionToIntersection<U extends Endpoint ? U["options"] : {
100
110
  body?: {};
101
111
  requireRequest?: boolean;
102
112
  requireHeaders?: boolean;
@@ -112,14 +122,14 @@ type InferMethod<M extends Method | Method[]> = M extends Array<Method> ? {
112
122
  };
113
123
  type InferHeaders<Opt extends EndpointOptions, HeaderReq = Opt["requireHeaders"]> = HeaderReq extends true ? {
114
124
  headers: Headers;
115
- } : InferUseOptions<Opt>['requireHeaders'] extends true ? {
125
+ } : InferUseOptions<Opt>["requireHeaders"] extends true ? {
116
126
  headers: Headers;
117
127
  } : {
118
128
  headers?: Headers;
119
129
  };
120
130
  type InferRequest<Opt extends EndpointOptions, RequestReq = Opt["requireRequest"]> = RequestReq extends true ? {
121
131
  request: Request;
122
- } : InferUseOptions<Opt>['requireRequest'] extends true ? {
132
+ } : InferUseOptions<Opt>["requireRequest"] extends true ? {
123
133
  request: Request;
124
134
  } : {
125
135
  request?: Request;
@@ -141,7 +151,7 @@ type InferParam<Path extends string, ParamPath extends InferParamPath<Path> = In
141
151
  type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined;
142
152
  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>;
143
153
  type Method = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "*";
144
- 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> ? {
154
+ 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> ? {
145
155
  body?: Prettify<z.infer<Body>>;
146
156
  } : {
147
157
  body: Prettify<z.infer<Body>>;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var w=Object.defineProperty;var S=(t,e,r)=>e in t?w(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var m=(t,e,r)=>S(t,typeof e!="symbol"?e+"":e,r);import{ZodError as b}from"zod";import"zod";function U(t,e){if(typeof t=="function")return R("*",{method:"*"},t);if(!e)throw new Error("Middleware handler is required");return R("*",{...t,method:"*"},e)}var q=()=>{function t(e,r){if(typeof e=="function")return R("*",{method:"*"},e);if(!r)throw new Error("Middleware handler is required");return R("*",{...e,method:"*"},r)}return t};var y=class extends Error{constructor(r,a){super(`API Error: ${r} ${a?.message??""}`,{cause:a});m(this,"status");m(this,"body");this.status=r,this.body=a??{},this.stack="",this.name="BetterCallAPIError"}};function W(){return(t,e,r)=>R(t,e,r)}function R(t,e,r){let a=new Headers,p=async(...o)=>{let n={setHeader(s,d){a.set(s,d)},setCookie(s,d,E){let f=E||{};a.append("Set-Cookie",`${s}=${d}; Max-Age=${f.maxAge||0}; Domain=${f.domain||""}; Path=${f.path||"/"}; Secure=${f.secure||!1}; HttpOnly=${f.httpOnly||!1}; SameSite=${f.sameSite||"none"}; Expires=${f.expires||""};`)},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 b?new y("BAD_REQUEST",{message:s.message,details:s.errors}):s}if(e.requireHeaders&&!n.headers)throw new y("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!n.request)throw new y("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 _,addRoute as x,findRoute as g}from"rou3";async function T(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 I(t){return typeof t=="object"&&t!==null&&!(t instanceof Blob)&&!(t instanceof FormData)}var C={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 j=(t,e)=>{let r=_();for(let o of t)if(Array.isArray(o.options?.method))for(let n of o.options.method)x(r,n,o.path,o);else x(r,o.options.method,o.path,o);let a=_();for(let o of e?.routerMiddleware||[])x(a,"*",o.path,o.middleware);return{handler:async o=>{let n=new URL(o.url),O=n.pathname;e?.basePath&&(O=O.split(e.basePath)[1]);let s=o.method,d=g(r,s,O),E=d?.data,f=await T(o),l=o.headers,h=Object.fromEntries(n.searchParams),c=g(a,"*",O)?.data;if(!E)return new Response(null,{status:404,statusText:"Not Found"});try{let i={};if(c){let P=await c({path:O,method:s,headers:l,params:d?.params,request:o,body:f,query:h,...e?.extraContext});P&&(i={...P,...i})}let u=await E({path:O,method:s,headers:l,params:d?.params,request:o,body:f,query:h,...i,...e?.extraContext});if(u instanceof Response)return u;let A=I(u)?JSON.stringify(u):u;return new Response(A,{headers:E.headers})}catch(i){if(e?.onError){let u=await e.onError(i);if(u instanceof Response)return u}if(i instanceof y)return new Response(i.body?JSON.stringify(i.body):null,{status:C[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"})}}}};import"zod";export{y as APIError,R as createEndpoint,W as createEndpointCreator,U as createMiddleware,q as createMiddlewareCreator,j as createRouter,T as getBody,I as shouldSerialize,C as statusCode};
1
+ var L=Object.defineProperty;var $=(r,e,t)=>e in r?L(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var l=(r,e,t)=>$(r,typeof e!="symbol"?e+"":e,t);import{ZodError as F}from"zod";import"zod";function V(r,e){if(typeof r=="function")return y("*",{method:"*"},r);if(!e)throw new Error("Middleware handler is required");return y("*",{...r,method:"*"},e)}var j=()=>{function r(e,t){if(typeof e=="function")return y("*",{method:"*"},e);if(!t)throw new Error("Middleware handler is required");return y("*",{...e,method:"*"},t)}return r};var m=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"},_=async r=>{let e=typeof r=="string"?new TextEncoder().encode(r):r;return await crypto.subtle.importKey("raw",e,g,!1,["sign","verify"])},Q=async(r,e)=>{let t=await _(e),n=await crypto.subtle.sign(g.name,t,new TextEncoder().encode(r));return btoa(String.fromCharCode(...new Uint8Array(n)))},W=async(r,e,t)=>{try{let n=atob(r),s=new Uint8Array(n.length);for(let o=0,i=n.length;o<i;o++)s[o]=n.charCodeAt(o);return await crypto.subtle.verify(g,t,s,new TextEncoder().encode(e))}catch{return!1}},K=/^[\w!#$%&'*.^`|~+-]+$/,v=/^[ !#-:<-[\]-~]*$/,R=(r,e)=>r.trim().split(";").reduce((n,s)=>{s=s.trim();let o=s.indexOf("=");if(o===-1)return n;let i=s.substring(0,o).trim();if(e&&e!==i||!K.test(i))return n;let p=s.substring(o+1).trim();return p.startsWith('"')&&p.endsWith('"')&&(p=p.slice(1,-1)),v.test(p)&&(n[i]=decodeURIComponent(p)),n},{}),w=async(r,e,t)=>{let n={},s=await _(e);for(let[o,i]of Object.entries(R(r,t))){let p=i.lastIndexOf(".");if(p<1)continue;let a=i.substring(0,p),d=i.substring(p+1);if(d.length!==44||!d.endsWith("="))continue;let u=await W(d,a,s);n[o]=u?a:!1}return n},I=(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},x=(r,e,t)=>(e=encodeURIComponent(e),I(r,e,t)),h=async(r,e,t,n={})=>{let s=await Q(e,t);return e=`${e}.${s}`,e=encodeURIComponent(e),I(r,e,n)};var k=(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]},b=(r,e,t,n)=>{let s;n?.prefix==="secure"?s=x("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?s=x("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):s=x(e,t,{path:"/",...n}),r.append("Set-Cookie",s)},A=async(r,e,t,n,s)=>{let o;s?.prefix==="secure"?o=await h("__Secure-"+e,t,n,{path:"/",...s,secure:!0}):s?.prefix==="host"?o=await h("__Host-"+e,t,n,{...s,path:"/",secure:!0,domain:void 0}):o=await h(e,t,n,{path:"/",...s}),r.append("Set-Cookie",o)},H=async(r,e,t,n)=>{let s=r.get("Cookie");if(!s)return;let o=t;return n==="secure"?o="__Secure-"+t:n==="host"&&(o="__Host-"+t),(await w(s,e,o))[o]};function ue(){return(r,e,t)=>y(r,e,t)}function y(r,e,t){let n=new Headers,s=async(...o)=>{let i={setHeader(a,d){n.set(a,d)},setCookie(a,d,u){b(n,a,d,u)},getCookie(a,d){let u=o[0]?.headers;return k(u?.get("Cookie")||"",a,d)},getSignedCookie(a,d,u){let c=o[0]?.headers;if(!c)throw new TypeError("Headers are required");return H(c,d,a,u)},async setSignedCookie(a,d,u,c){await A(n,a,d,u,c)},...o[0]||{},context:{}};if(e.use?.length)for(let a of e.use){let d=await a(i),u=d.options?.body?d.options.body.parse(i.body):void 0;d&&(i={...i,body:u?{...u,...i.body}:i.body,context:{...i.context||{},...d}})}try{let a=e.body?e.body.parse(i.body):i.body;i={...i,body:a?{...a,...i.body}:i.body},i.query=e.query?e.query.parse(i.query):i.query,i.params=e.params?e.params.parse(i.params):i.params}catch(a){throw a instanceof F?new m("BAD_REQUEST",{message:a.message,details:a.errors}):a}if(e.requireHeaders&&!i.headers)throw new m("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!i.request)throw new m("BAD_REQUEST",{message:"Request is required"});return await t(i)};return s.path=r,s.options=e,s.method=e.method,s.headers=n,s}import{createRouter as M,addRoute as C,findRoute as q}from"rou3";async function N(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,o)=>{n[o]=s.toString()}),n}if(e.includes("multipart/form-data")){let t=await r.formData(),n={};return t.forEach((s,o)=>{n[o]=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 D(r){return typeof r=="object"&&r!==null&&!(r instanceof Blob)&&!(r instanceof FormData)}var U={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 xe=(r,e)=>{let t=M();for(let o of r)if(Array.isArray(o.options?.method))for(let i of o.options.method)C(t,i,o.path,o);else C(t,o.options.method,o.path,o);let n=M();for(let o of e?.routerMiddleware||[])C(n,"*",o.path,o.middleware);return{handler:async o=>{let i=new URL(o.url),p=i.pathname;e?.basePath&&(p=p.split(e.basePath)[1]);let a=o.method,d=q(t,a,p),u=d?.data,c=await N(o),O=o.headers,P=Object.fromEntries(i.searchParams),T=q(n,"*",p)?.data;if(!u)return new Response(null,{status:404,statusText:"Not Found"});try{let f={};if(T){let S=await T({path:p,method:a,headers:O,params:d?.params,request:o,body:c,query:P,...e?.extraContext});S&&(f={...S,...f})}let E=await u({path:p,method:a,headers:O,params:d?.params,request:o,body:c,query:P,...f,...e?.extraContext});if(E instanceof Response)return E;let B=D(E)?JSON.stringify(E):E;return new Response(B,{headers:u.headers})}catch(f){if(e?.onError){let E=await e.onError(f);if(E instanceof Response)return E}if(f instanceof m)return new Response(f.body?JSON.stringify(f.body):null,{status:U[f.status],statusText:f.status,headers:u.headers});if(e?.throwError)throw f;return new Response(null,{status:500,statusText:"Internal Server Error"})}}}};import"zod";export{m as APIError,y as createEndpoint,ue as createEndpointCreator,V as createMiddleware,j as createMiddlewareCreator,xe as createRouter,N as getBody,D as shouldSerialize,U as statusCode};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/endpoint.ts","../src/middleware.ts","../src/better-call-error.ts","../src/router.ts","../src/utils.ts","../src/types.ts"],"sourcesContent":["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, CookieOptions, 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, options?: CookieOptions) {\n const cookieOptions = options || {}\n responseHeader.append(\"Set-Cookie\", `${key}=${value}; Max-Age=${cookieOptions.maxAge || 0}; Domain=${cookieOptions.domain || \"\"}; Path=${cookieOptions.path || \"/\"}; Secure=${cookieOptions.secure || false}; HttpOnly=${cookieOptions.httpOnly || false}; SameSite=${cookieOptions.sameSite || \"none\"}; Expires=${cookieOptions.expires || \"\"};`)\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 extraContext?: Record<string, any>\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 ...config?.extraContext\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 ...config?.extraContext\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","import { z, type ZodOptional, type ZodSchema } from \"zod\"\nimport type { Middleware } from \"./middleware\"\nimport type { UnionToIntersection } from \"./helper\";\n\n\nexport interface EndpointOptions {\n method: Method | Method[]\n body?: ZodSchema\n query?: ZodSchema\n params?: ZodSchema<any>\n /**\n * If true headers will be required to be passed in the context\n */\n requireHeaders?: boolean\n /**\n * If true request object will be required\n */\n requireRequest?: boolean\n /**\n * List of endpoints that will be called before this endpoint\n */\n use?: Endpoint[]\n}\n\nexport type Endpoint<Handler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>, Option extends EndpointOptions = EndpointOptions> = {\n path: string\n options: Option\n headers?: Headers\n} & (Handler)\n\nexport type InferParamPath<Path> =\n Path extends `${infer _Start}:${infer Param}/${infer Rest}`\n ? { [K in Param | keyof InferParamPath<Rest>]: string }\n : Path extends `${infer _Start}:${infer Param}`\n ? { [K in Param]: string }\n : Path extends `${infer _Start}/${infer Rest}`\n ? InferParamPath<Rest>\n : undefined;\n\nexport type InferParamWildCard<Path> = Path extends `${infer _Start}/*:${infer Param}/${infer Rest}` | `${infer _Start}/**:${infer Param}/${infer Rest}`\n ? { [K in Param | keyof InferParamPath<Rest>]: string }\n : Path extends `${infer _Start}/*`\n ? { [K in \"_\"]: string }\n : Path extends `${infer _Start}/${infer Rest}`\n ? InferParamPath<Rest>\n : undefined;\n\n\nexport type Prettify<T> = {\n [key in keyof T]: T[key];\n} & {};\n\n\nexport interface CookieOptions {\n /**\n * Max age in seconds\n */\n maxAge?: number\n /**\n * Domain\n */\n domain?: string\n /**\n * Path\n */\n path?: string\n /**\n * Secure\n */\n secure?: boolean\n /**\n * HttpOnly\n */\n httpOnly?: boolean\n\n /**\n * SameSite\n */\n sameSite?: 'strict' | 'lax' | 'none'\n /** \n * Expires\n */\n expires?: Date\n}\n\nexport type ContextTools = {\n /**\n * Set header\n * \n * If it's called outside of a request it will just be ignored.\n */\n setHeader: (key: string, value: string) => void\n /**\n * cookie setter.\n * \n * If it's called outside of a request it will just be ignored.\n */\n setCookie: (key: string, value: string, options?: CookieOptions) => void\n /**\n * Get cookie value\n * \n * If it's called outside of a request it will just be ignored.\n */\n getCookie: (key: string) => string | undefined\n}\n\nexport type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> & InferParam<Path> & InferMethod<Opts['method']> & InferHeaders<Opts> & InferRequest<Opts> & InferQuery<Opts[\"query\"]>\n\nexport type InferUse<Opts extends EndpointOptions> = Opts[\"use\"] extends Endpoint[] ? {\n context: UnionToIntersection<Awaited<ReturnType<Opts[\"use\"][number]>>>\n} : {}\n\nexport type InferUseOptions<Opts extends EndpointOptions> = Opts[\"use\"] extends Array<infer U> ? UnionToIntersection<U extends Endpoint ? U['options'] : {\n body?: {},\n requireRequest?: boolean\n requireHeaders?: boolean\n}> : {\n body?: {},\n requireRequest?: boolean\n requireHeaders?: boolean\n}\n\nexport type InferMethod<M extends Method | Method[]> = M extends Array<Method> ? {\n method: M[number]\n} : {\n method?: M\n}\n\nexport type InferHeaders<Opt extends EndpointOptions, HeaderReq = Opt[\"requireHeaders\"]> = HeaderReq extends true ? {\n headers: Headers\n} : InferUseOptions<Opt>['requireHeaders'] extends true ? {\n headers: Headers\n} : {\n headers?: Headers\n}\n\n\nexport type InferRequest<Opt extends EndpointOptions, RequestReq = Opt[\"requireRequest\"]> = RequestReq extends true ? {\n request: Request\n} : InferUseOptions<Opt>['requireRequest'] extends true ? {\n request: Request\n} : {\n request?: Request\n}\n\n\nexport type InferQuery<Query> = Query extends ZodSchema ? Query extends ZodOptional<any> ? {\n query?: z.infer<Query>\n} : {\n query: z.infer<Query>\n} : {\n query?: undefined\n}\n\nexport type InferParam<Path extends string, ParamPath extends InferParamPath<Path> = InferParamPath<Path>, WildCard extends InferParamWildCard<Path> = InferParamWildCard<Path>> = ParamPath extends undefined ? WildCard extends undefined ? {\n params?: Record<string, string>\n} : {\n params: WildCard\n} : {\n params: Prettify<ParamPath & (WildCard extends undefined ? {} : WildCard)>\n}\n\n\nexport type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined\n\nexport type Handler<Path extends string, Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts> & ContextTools> & Extra) => Promise<R>\n\nexport type Method = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"*\"\n\n\nexport type InferBody<Opts extends EndpointOptions, Body extends ZodSchema | undefined = (Opts[\"body\"] &\n (undefined extends InferUseOptions<Opts>['body'] ? {} : InferUseOptions<Opts>['body']))> = Body extends ZodSchema ? Body extends ZodOptional<any> ? {\n body?: Prettify<z.infer<Body>>\n } : {\n body: Prettify<z.infer<Body>>\n } : {\n body?: undefined\n }"],"mappings":"oKAAA,OAAY,YAAAA,MAAkD,MCA9D,MAAkB,MAiBX,SAASC,EAAiBC,EAAuBC,EAAe,CACnE,GAAI,OAAOD,GAAqB,WAC5B,OAAOE,EAAe,IAAK,CACvB,OAAQ,GACZ,EAAGF,CAAgB,EAEvB,GAAI,CAACC,EACD,MAAM,IAAI,MAAM,gCAAgC,EAMpD,OAJiBC,EAAe,IAAK,CACjC,GAAGF,EACH,OAAQ,GACZ,EAAGC,CAAO,CAEd,CAEO,IAAME,EAA0B,IAAqD,CASxF,SAASC,EAAGJ,EAAuBC,EAAe,CAC9C,GAAI,OAAOD,GAAqB,WAC5B,OAAOE,EAAe,IAAK,CACvB,OAAQ,GACZ,EAAGF,CAAgB,EAEvB,GAAI,CAACC,EACD,MAAM,IAAI,MAAM,gCAAgC,EAMpD,OAJiBC,EAAe,IAAK,CACjC,GAAGF,EACH,OAAQ,GACZ,EAAGC,CAAO,CAEd,CACA,OAAOG,CACX,ECtDO,IAAMC,EAAN,cAAuB,KAAM,CAGhC,YACIC,EACAC,EACF,CACE,MACI,cAAcD,CAAM,IAAIC,GAAM,SAAW,EAAE,GAC3C,CACI,MAAOA,CACX,CACJ,EAXJC,EAAA,eACAA,EAAA,aAWI,KAAK,OAASF,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ACf,CAAC,EACGmB,IACAD,EAAoB,CAChB,GAAGC,EACH,GAAGD,CACP,EAER,CACA,IAAME,EAAa,MAAMR,EAAQ,CAC7B,KAAMF,EACN,OAAQN,EACR,QAAAW,EACA,OAAQR,GAAO,OACf,QAASC,EACT,KAAMK,EACN,MAAAG,EACA,GAAGE,EACH,GAAGlB,GAAQ,YACf,CAAC,EACD,GAAIoB,aAAsB,SACtB,OAAOA,EAEX,IAAMC,EAAUC,EAAgBF,CAAU,EAAI,KAAK,UAAUA,CAAU,EAAIA,EAC3E,OAAO,IAAI,SAASC,EAAgB,CAChC,QAAST,EAAQ,OACrB,CAAC,CACL,OAASW,EAAG,CACR,GAAIvB,GAAQ,QAAS,CACjB,IAAMwB,EAAa,MAAMxB,EAAO,QAAQuB,CAAC,EACzC,GAAIC,aAAsB,SACtB,OAAOA,CAEf,CACA,GAAID,aAAaE,EACb,OAAO,IAAI,SAASF,EAAE,KAAO,KAAK,UAAUA,EAAE,IAAI,EAAI,KAAM,CACxD,OAAQG,EAAWH,EAAE,MAAM,EAC3B,WAAYA,EAAE,OACd,QAAS,CACL,eAAgB,kBACpB,CACJ,CAAC,EAEL,GAAIvB,GAAQ,WACR,MAAMuB,EAEV,OAAO,IAAI,SAAS,KAAM,CACtB,OAAQ,IACR,WAAY,uBAChB,CAAC,CACL,CACJ,CAGA,CACJ,EExIA,MAAoD","names":["ZodError","createMiddleware","optionsOrHandler","handler","createEndpoint","createMiddlewareCreator","fn","APIError","status","body","__publicField","createEndpointCreator","path","options","handler","createEndpoint","responseHeader","handle","ctx","internalCtx","key","value","cookieOptions","cookie","middleware","res","body","e","ZodError","APIError","createRou3Router","addRoute","findRoute","getBody","request","contentType","formData","result","value","key","shouldSerialize","body","statusCode","createRouter","endpoints","config","router","createRou3Router","endpoint","method","addRoute","middlewareRouter","route","request","url","path","findRoute","handler","body","getBody","headers","query","middleware","middlewareContext","res","handlerRes","resBody","shouldSerialize","e","onErrorRes","APIError","statusCode"]}
1
+ {"version":3,"sources":["../src/endpoint.ts","../src/middleware.ts","../src/better-call-error.ts","../src/cookie.ts","../src/cookie-utils.ts","../src/router.ts","../src/utils.ts","../src/types.ts"],"sourcesContent":["import { z, ZodError, type ZodOptional, type ZodSchema } from \"zod\";\nimport { createMiddleware, type Middleware } from \"./middleware\";\nimport { APIError } from \"./better-call-error\";\nimport type { HasRequiredKeys, UnionToIntersection } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tCookieOptions,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n} from \"./types\";\nimport { getCookie, getSignedCookie, setCookie, setSignedCookie } from \"./cookie-utils\";\nimport type { CookiePrefixOptions } from \"./cookie\";\n\nexport interface EndpointConfig {\n\t/**\n\t * Throw when the response isn't in 200 range\n\t */\n\tthrowOnError?: boolean;\n}\n\nexport function createEndpointCreator<T extends Record<string, any>>() {\n\treturn <Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\tpath: Path,\n\t\toptions: Opts,\n\t\thandler: Handler<Path, Opts, R, T>,\n\t) => {\n\t\t//@ts-expect-error\n\t\treturn createEndpoint(path, options, handler);\n\t};\n}\n\nexport function createEndpoint<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n>(path: Path, options: Opts, handler: Handler<Path, Opts, R>) {\n\tconst responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\tconst handle = async (...ctx: HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]) => {\n\t\tlet internalCtx = {\n\t\t\tsetHeader(key: string, value: string) {\n\t\t\t\tresponseHeader.set(key, value);\n\t\t\t},\n\t\t\tsetCookie(key: string, value: string, options?: CookieOptions) {\n\t\t\t\tsetCookie(responseHeader, key, value, options);\n\t\t\t},\n\t\t\tgetCookie(key: string, prefix?: CookiePrefixOptions) {\n\t\t\t\tconst header = ctx[0]?.headers;\n\t\t\t\tconst cookie = getCookie(header?.get(\"Cookie\") || \"\", key, prefix);\n\t\t\t\treturn cookie;\n\t\t\t},\n\t\t\tgetSignedCookie(key: string, secret: string, prefix?: CookiePrefixOptions) {\n\t\t\t\tconst header = ctx[0]?.headers;\n\t\t\t\tif (!header) {\n\t\t\t\t\tthrow new TypeError(\"Headers are required\");\n\t\t\t\t}\n\t\t\t\tconst cookie = getSignedCookie(header, secret, key, prefix);\n\t\t\t\treturn cookie;\n\t\t\t},\n\t\t\tasync setSignedCookie(\n\t\t\t\tkey: string,\n\t\t\t\tvalue: string,\n\t\t\t\tsecret: string | BufferSource,\n\t\t\t\toptions?: CookieOptions,\n\t\t\t) {\n\t\t\t\tawait setSignedCookie(responseHeader, key, value, secret, options);\n\t\t\t},\n\t\t\t...(ctx[0] || {}),\n\t\t\tcontext: {},\n\t\t};\n\t\tif (options.use?.length) {\n\t\t\tfor (const middleware of options.use) {\n\t\t\t\tconst res = (await middleware(internalCtx)) as Endpoint;\n\t\t\t\tconst body = res.options?.body\n\t\t\t\t\t? res.options.body.parse(internalCtx.body)\n\t\t\t\t\t: undefined;\n\t\t\t\tif (res) {\n\t\t\t\t\tinternalCtx = {\n\t\t\t\t\t\t...internalCtx,\n\t\t\t\t\t\tbody: body\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t...body,\n\t\t\t\t\t\t\t\t\t...internalCtx.body,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: internalCtx.body,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t...(internalCtx.context || {}),\n\t\t\t\t\t\t\t...res,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst body = options.body ? options.body.parse(internalCtx.body) : internalCtx.body;\n\t\t\tinternalCtx = {\n\t\t\t\t...internalCtx,\n\t\t\t\tbody: body\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...body,\n\t\t\t\t\t\t\t...internalCtx.body,\n\t\t\t\t\t\t}\n\t\t\t\t\t: internalCtx.body,\n\t\t\t};\n\t\t\tinternalCtx.query = options.query\n\t\t\t\t? options.query.parse(internalCtx.query)\n\t\t\t\t: internalCtx.query;\n\t\t\tinternalCtx.params = options.params\n\t\t\t\t? options.params.parse(internalCtx.params)\n\t\t\t\t: internalCtx.params;\n\t\t} catch (e) {\n\t\t\tif (e instanceof ZodError) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: e.message,\n\t\t\t\t\tdetails: e.errors,\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t\tif (options.requireHeaders && !internalCtx.headers) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Headers are required\",\n\t\t\t});\n\t\t}\n\t\tif (options.requireRequest && !internalCtx.request) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Request is required\",\n\t\t\t});\n\t\t}\n\t\t//@ts-expect-error\n\t\tconst res = await handler(internalCtx);\n\t\treturn res as ReturnType<Handler<Path, Opts, R>>;\n\t};\n\thandle.path = path;\n\thandle.options = options;\n\thandle.method = options.method;\n\thandle.headers = responseHeader;\n\treturn handle;\n}\n","import { z } from \"zod\"\nimport type { ContextTools, Endpoint, EndpointOptions, EndpointResponse, Handler, InferBody, InferHeaders, InferRequest, Prettify } from \"./types\"\nimport { createEndpoint } from \"./endpoint\"\n\nexport type MiddlewareHandler<Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<InferBody<Opts> & InferRequest<Opts> & InferHeaders<Opts> & {\n params?: Record<string, string>,\n query?: Record<string, string>,\n} & ContextTools> & Extra) => Promise<R>\n\nexport function createMiddleware<Opts extends EndpointOptions, R extends EndpointResponse>(optionsOrHandler: MiddlewareHandler<Opts, R>): Endpoint<Handler<string, Opts, R>, Opts>\nexport function createMiddleware<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(optionsOrHandler: Opts, handler: MiddlewareHandler<Opts & {\n method: \"*\"\n}, R>): Endpoint<Handler<string, Opts & {\n method: \"*\"\n}, R>, Opts & {\n method: \"*\"\n}>\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n if (typeof optionsOrHandler === \"function\") {\n return createEndpoint(\"*\", {\n method: \"*\"\n }, optionsOrHandler)\n }\n if (!handler) {\n throw new Error(\"Middleware handler is required\")\n }\n const endpoint = createEndpoint(\"*\", {\n ...optionsOrHandler,\n method: \"*\"\n }, handler)\n return endpoint as any\n}\n\nexport const createMiddlewareCreator = <ExtraContext extends Record<string, any> = {}>() => {\n function fn<Opts extends EndpointOptions, R extends EndpointResponse>(optionsOrHandler: MiddlewareHandler<Opts, R, ExtraContext>): Endpoint<Handler<string, Opts, R>, Opts>\n function fn<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(optionsOrHandler: Opts, handler: MiddlewareHandler<Opts & {\n method: \"*\"\n }, R, ExtraContext>): Endpoint<Handler<string, Opts & {\n method: \"*\"\n }, R>, Opts & {\n method: \"*\"\n }>\n function fn(optionsOrHandler: any, handler?: any) {\n if (typeof optionsOrHandler === \"function\") {\n return createEndpoint(\"*\", {\n method: \"*\"\n }, optionsOrHandler)\n }\n if (!handler) {\n throw new Error(\"Middleware handler is required\")\n }\n const endpoint = createEndpoint(\"*\", {\n ...optionsOrHandler,\n method: \"*\"\n }, handler)\n return endpoint as any\n }\n return fn\n}\n\nexport type Middleware<Opts extends EndpointOptions = EndpointOptions, R extends EndpointResponse = EndpointResponse> = (opts: Opts, handler: (ctx: {\n body?: InferBody<Opts>,\n params?: Record<string, string>,\n query?: Record<string, string>\n}) => Promise<R>) => Endpoint","import type { statusCode } from \"./utils\"\n\ntype Status = keyof typeof statusCode\n\nexport class APIError extends Error {\n status: Status\n body: Record<string, any>\n constructor(\n status: Status,\n body?: Record<string, any>,\n ) {\n super(\n `API Error: ${status} ${body?.message ?? \"\"}`,\n {\n cause: body,\n }\n )\n this.status = status\n this.body = body ?? {}\n this.stack = \"\";\n this.name = \"BetterCallAPIError\"\n }\n}","//https://github.com/honojs/hono/blob/main/src/utils/cookie.ts\n\nexport type Cookie = Record<string, string>;\nexport type SignedCookie = Record<string, string | false>;\n\ntype PartitionCookieConstraint =\n\t| { partition: true; secure: true }\n\t| { partition?: boolean; secure?: boolean }; // reset to default\ntype SecureCookieConstraint = { secure: true };\ntype HostCookieConstraint = { secure: true; path: \"/\"; domain?: undefined };\n\nexport type CookieOptions = {\n\tdomain?: string;\n\texpires?: Date;\n\thttpOnly?: boolean;\n\tmaxAge?: number;\n\tpath?: string;\n\tsecure?: boolean;\n\tsigningSecret?: string;\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\tpartitioned?: boolean;\n\tprefix?: CookiePrefixOptions;\n} & PartitionCookieConstraint;\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieConstraint<Name> = Name extends `__Secure-${string}`\n\t? CookieOptions & SecureCookieConstraint\n\t: Name extends `__Host-${string}`\n\t\t? CookieOptions & HostCookieConstraint\n\t\t: CookieOptions;\n\nconst algorithm = { name: \"HMAC\", hash: \"SHA-256\" };\n\nconst getCryptoKey = async (secret: string | BufferSource): Promise<CryptoKey> => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await crypto.subtle.importKey(\"raw\", secretBuf, algorithm, false, [\"sign\", \"verify\"]);\n};\n\nconst makeSignature = async (value: string, secret: string | BufferSource): Promise<string> => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await crypto.subtle.sign(\n\t\talgorithm.name,\n\t\tkey,\n\t\tnew TextEncoder().encode(value),\n\t);\n\t// the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n\nconst verifySignature = async (\n\tbase64Signature: string,\n\tvalue: string,\n\tsecret: CryptoKey,\n): Promise<boolean> => {\n\ttry {\n\t\tconst signatureBinStr = atob(base64Signature);\n\t\tconst signature = new Uint8Array(signatureBinStr.length);\n\t\tfor (let i = 0, len = signatureBinStr.length; i < len; i++) {\n\t\t\tsignature[i] = signatureBinStr.charCodeAt(i);\n\t\t}\n\t\treturn await crypto.subtle.verify(\n\t\t\talgorithm,\n\t\t\tsecret,\n\t\t\tsignature,\n\t\t\tnew TextEncoder().encode(value),\n\t\t);\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\n\n// all alphanumeric chars and all of _!#$%&'*.^`|~+-\n// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)\nconst validCookieNameRegEx = /^[\\w!#$%&'*.^`|~+-]+$/;\n\n// all ASCII chars 32-126 except 34, 59, and 92 (i.e. space to tilde but not double quote, semicolon, or backslash)\n// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)\n//\n// note: the spec also prohibits comma and space, but we allow both since they are very common in the real world\n// (see: https://github.com/golang/go/issues/7243)\nconst validCookieValueRegEx = /^[ !#-:<-[\\]-~]*$/;\n\nexport const parse = (cookie: string, name?: string): Cookie => {\n\tconst pairs = cookie.trim().split(\";\");\n\treturn pairs.reduce((parsedCookie, pairStr) => {\n\t\tpairStr = pairStr.trim();\n\t\tconst valueStartPos = pairStr.indexOf(\"=\");\n\t\tif (valueStartPos === -1) {\n\t\t\treturn parsedCookie;\n\t\t}\n\n\t\tconst cookieName = pairStr.substring(0, valueStartPos).trim();\n\t\tif ((name && name !== cookieName) || !validCookieNameRegEx.test(cookieName)) {\n\t\t\treturn parsedCookie;\n\t\t}\n\n\t\tlet cookieValue = pairStr.substring(valueStartPos + 1).trim();\n\t\tif (cookieValue.startsWith('\"') && cookieValue.endsWith('\"')) {\n\t\t\tcookieValue = cookieValue.slice(1, -1);\n\t\t}\n\t\tif (validCookieValueRegEx.test(cookieValue)) {\n\t\t\tparsedCookie[cookieName] = decodeURIComponent(cookieValue);\n\t\t}\n\n\t\treturn parsedCookie;\n\t}, {} as Cookie);\n};\n\nexport const parseSigned = async (\n\tcookie: string,\n\tsecret: string | BufferSource,\n\tname?: string,\n): Promise<SignedCookie> => {\n\tconst parsedCookie: SignedCookie = {};\n\tconst secretKey = await getCryptoKey(secret);\n\n\tfor (const [key, value] of Object.entries(parse(cookie, name))) {\n\t\tconst signatureStartPos = value.lastIndexOf(\".\");\n\t\tif (signatureStartPos < 1) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst signedValue = value.substring(0, signatureStartPos);\n\t\tconst signature = value.substring(signatureStartPos + 1);\n\t\tif (signature.length !== 44 || !signature.endsWith(\"=\")) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst isVerified = await verifySignature(signature, signedValue, secretKey);\n\t\tparsedCookie[key] = isVerified ? signedValue : false;\n\t}\n\n\treturn parsedCookie;\n};\n\nconst _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {\n\tlet cookie = `${name}=${value}`;\n\n\tif (name.startsWith(\"__Secure-\") && !opt.secure) {\n\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.1\n\t\tthrow new Error(\"__Secure- Cookie must have Secure attributes\");\n\t}\n\n\tif (name.startsWith(\"__Host-\")) {\n\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.2\n\t\tif (!opt.secure) {\n\t\t\tthrow new Error(\"__Host- Cookie must have Secure attributes\");\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\tthrow new Error('__Host- Cookie must have Path attributes with \"/\"');\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\tthrow new Error(\"__Host- Cookie must not have Domain attributes\");\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.2\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.1\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\t// FIXME: replace link to RFC\n\t\t// https://www.ietf.org/archive/id/draft-cutler-httpbis-partitioned-cookies-01.html#section-2.3\n\t\tif (!opt.secure) {\n\t\t\tthrow new Error(\"Partitioned Cookie must have Secure attributes\");\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serialize = <Name extends string>(\n\tname: Name,\n\tvalue: string,\n\topt?: CookieConstraint<Name>,\n): string => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(name, value, opt);\n};\n\nexport const serializeSigned = async (\n\tname: string,\n\tvalue: string,\n\tsecret: string | BufferSource,\n\topt: CookieOptions = {},\n): Promise<string> => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(name, value, opt);\n};\n","//https://github.com/honojs/hono/blob/main/src/helper/cookie/index.ts\n\nimport {\n\tparse,\n\tparseSigned,\n\tserialize,\n\tserializeSigned,\n\ttype CookieOptions,\n\ttype CookiePrefixOptions,\n} from \"./cookie\";\n\nexport const getCookie = (cookie?: string, key?: string, prefix?: CookiePrefixOptions) => {\n\tif (!cookie) {\n\t\treturn undefined;\n\t}\n\tlet finalKey = key;\n\tif (prefix === \"secure\") {\n\t\tfinalKey = \"__Secure-\" + key;\n\t} else if (prefix === \"host\") {\n\t\tfinalKey = \"__Host-\" + key;\n\t} else {\n\t\treturn undefined;\n\t}\n\tconst obj = parse(cookie, finalKey);\n\treturn obj[finalKey];\n};\n\nexport const setCookie = (\n\theader: Headers,\n\tname: string,\n\tvalue: string,\n\topt?: CookieOptions,\n): void => {\n\t// Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.\n\t// Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)\n\t// and must not have a Domain attribute.\n\t// Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'\n\tlet cookie;\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = serialize(\"__Secure-\" + name, value, { path: \"/\", ...opt, secure: true });\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = serialize(\"__Host-\" + name, value, {\n\t\t\t...opt,\n\t\t\tpath: \"/\",\n\t\t\tsecure: true,\n\t\t\tdomain: undefined,\n\t\t});\n\t} else {\n\t\tcookie = serialize(name, value, { path: \"/\", ...opt });\n\t}\n\theader.append(\"Set-Cookie\", cookie);\n};\n\nexport const setSignedCookie = async (\n\theader: Headers,\n\tname: string,\n\tvalue: string,\n\tsecret: string | BufferSource,\n\topt?: CookieOptions,\n): Promise<void> => {\n\tlet cookie;\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = await serializeSigned(\"__Secure-\" + name, value, secret, {\n\t\t\tpath: \"/\",\n\t\t\t...opt,\n\t\t\tsecure: true,\n\t\t});\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = await serializeSigned(\"__Host-\" + name, value, secret, {\n\t\t\t...opt,\n\t\t\tpath: \"/\",\n\t\t\tsecure: true,\n\t\t\tdomain: undefined,\n\t\t});\n\t} else {\n\t\tcookie = await serializeSigned(name, value, secret, { path: \"/\", ...opt });\n\t}\n\theader.append(\"Set-Cookie\", cookie);\n};\n\nexport const getSignedCookie = async (\n\theader: Headers,\n\tsecret: string,\n\tkey: string,\n\tprefix?: CookiePrefixOptions,\n) => {\n\tconst cookie = header.get(\"Cookie\");\n\tif (!cookie) {\n\t\treturn undefined;\n\t}\n\tlet finalKey = key;\n\tif (prefix === \"secure\") {\n\t\tfinalKey = \"__Secure-\" + key;\n\t} else if (prefix === \"host\") {\n\t\tfinalKey = \"__Host-\" + key;\n\t}\n\tconst obj = await parseSigned(cookie, secret, finalKey);\n\treturn obj[finalKey];\n};\n","import {\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 extraContext?: Record<string, any>\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 ...config?.extraContext\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 ...config?.extraContext\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: handler.headers,\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","import { z, type ZodOptional, type ZodSchema } from \"zod\";\nimport type { Middleware } from \"./middleware\";\nimport type { UnionToIntersection } from \"./helper\";\nimport type { CookiePrefixOptions } from \"./cookie\";\n\nexport interface EndpointOptions {\n\tmethod: Method | Method[];\n\tbody?: ZodSchema;\n\tquery?: ZodSchema;\n\tparams?: ZodSchema<any>;\n\t/**\n\t * If true headers will be required to be passed in the context\n\t */\n\trequireHeaders?: boolean;\n\t/**\n\t * If true request object will be required\n\t */\n\trequireRequest?: boolean;\n\t/**\n\t * List of endpoints that will be called before this endpoint\n\t */\n\tuse?: Endpoint[];\n}\n\nexport type Endpoint<\n\tHandler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>,\n\tOption extends EndpointOptions = EndpointOptions,\n> = {\n\tpath: string;\n\toptions: Option;\n\theaders?: Headers;\n} & Handler;\n\nexport type InferParamPath<Path> = Path extends `${infer _Start}:${infer Param}/${infer Rest}`\n\t? { [K in Param | keyof InferParamPath<Rest>]: string }\n\t: Path extends `${infer _Start}:${infer Param}`\n\t\t? { [K in Param]: string }\n\t\t: Path extends `${infer _Start}/${infer Rest}`\n\t\t\t? InferParamPath<Rest>\n\t\t\t: undefined;\n\nexport type InferParamWildCard<Path> = Path extends\n\t| `${infer _Start}/*:${infer Param}/${infer Rest}`\n\t| `${infer _Start}/**:${infer Param}/${infer Rest}`\n\t? { [K in Param | keyof InferParamPath<Rest>]: string }\n\t: Path extends `${infer _Start}/*`\n\t\t? { [K in \"_\"]: string }\n\t\t: Path extends `${infer _Start}/${infer Rest}`\n\t\t\t? InferParamPath<Rest>\n\t\t\t: undefined;\n\nexport type Prettify<T> = {\n\t[key in keyof T]: T[key];\n} & {};\n\nexport interface CookieOptions {\n\t/**\n\t * Max age in seconds\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Domain\n\t */\n\tdomain?: string;\n\t/**\n\t * Path\n\t */\n\tpath?: string;\n\t/**\n\t * Secure\n\t */\n\tsecure?: boolean;\n\t/**\n\t * HttpOnly\n\t */\n\thttpOnly?: boolean;\n\n\t/**\n\t * SameSite\n\t */\n\tsameSite?: \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Expires\n\t */\n\texpires?: Date;\n}\n\nexport type ContextTools = {\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * cookie setter.\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetCookie: (key: string, value: string, options?: CookieOptions) => void;\n\t/**\n\t * Get cookie value\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tgetCookie: (key: string, value: string, options?: CookieOptions) => string | undefined;\n\t/**\n\t * Set signed cookie\n\t */\n\tsetSignedCookie: (\n\t\tkey: string,\n\t\tvalue: string,\n\t\tsecret: string | BufferSource,\n\t\toptions?: CookieOptions,\n\t) => Promise<void>;\n\t/**\n\t * Get signed cookie value\n\t */\n\n\tgetSignedCookie: (\n\t\tkey: string,\n\t\tsecret: string,\n\t\tprefix?: CookiePrefixOptions,\n\t) => Promise<string | undefined>;\n};\n\nexport type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> &\n\tInferParam<Path> &\n\tInferMethod<Opts[\"method\"]> &\n\tInferHeaders<Opts> &\n\tInferRequest<Opts> &\n\tInferQuery<Opts[\"query\"]>;\n\nexport type InferUse<Opts extends EndpointOptions> = Opts[\"use\"] extends Endpoint[]\n\t? {\n\t\t\tcontext: UnionToIntersection<Awaited<ReturnType<Opts[\"use\"][number]>>>;\n\t\t}\n\t: {};\n\nexport type InferUseOptions<Opts extends EndpointOptions> = Opts[\"use\"] extends Array<infer U>\n\t? UnionToIntersection<\n\t\t\tU extends Endpoint\n\t\t\t\t? U[\"options\"]\n\t\t\t\t: {\n\t\t\t\t\t\tbody?: {};\n\t\t\t\t\t\trequireRequest?: boolean;\n\t\t\t\t\t\trequireHeaders?: boolean;\n\t\t\t\t\t}\n\t\t>\n\t: {\n\t\t\tbody?: {};\n\t\t\trequireRequest?: boolean;\n\t\t\trequireHeaders?: boolean;\n\t\t};\n\nexport type InferMethod<M extends Method | Method[]> = M extends Array<Method>\n\t? {\n\t\t\tmethod: M[number];\n\t\t}\n\t: {\n\t\t\tmethod?: M;\n\t\t};\n\nexport type InferHeaders<\n\tOpt extends EndpointOptions,\n\tHeaderReq = Opt[\"requireHeaders\"],\n> = HeaderReq extends true\n\t? {\n\t\t\theaders: Headers;\n\t\t}\n\t: InferUseOptions<Opt>[\"requireHeaders\"] extends true\n\t\t? {\n\t\t\t\theaders: Headers;\n\t\t\t}\n\t\t: {\n\t\t\t\theaders?: Headers;\n\t\t\t};\n\nexport type InferRequest<\n\tOpt extends EndpointOptions,\n\tRequestReq = Opt[\"requireRequest\"],\n> = RequestReq extends true\n\t? {\n\t\t\trequest: Request;\n\t\t}\n\t: InferUseOptions<Opt>[\"requireRequest\"] extends true\n\t\t? {\n\t\t\t\trequest: Request;\n\t\t\t}\n\t\t: {\n\t\t\t\trequest?: Request;\n\t\t\t};\n\nexport type InferQuery<Query> = Query extends ZodSchema\n\t? Query extends ZodOptional<any>\n\t\t? {\n\t\t\t\tquery?: z.infer<Query>;\n\t\t\t}\n\t\t: {\n\t\t\t\tquery: z.infer<Query>;\n\t\t\t}\n\t: {\n\t\t\tquery?: undefined;\n\t\t};\n\nexport type InferParam<\n\tPath extends string,\n\tParamPath extends InferParamPath<Path> = InferParamPath<Path>,\n\tWildCard extends InferParamWildCard<Path> = InferParamWildCard<Path>,\n> = ParamPath extends undefined\n\t? WildCard extends undefined\n\t\t? {\n\t\t\t\tparams?: Record<string, string>;\n\t\t\t}\n\t\t: {\n\t\t\t\tparams: WildCard;\n\t\t\t}\n\t: {\n\t\t\tparams: Prettify<ParamPath & (WildCard extends undefined ? {} : WildCard)>;\n\t\t};\n\nexport type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined;\n\nexport type Handler<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n\tExtra extends Record<string, any> = {},\n> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts> & ContextTools> & Extra) => Promise<R>;\n\nexport type Method = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"*\";\n\nexport type InferBody<\n\tOpts extends EndpointOptions,\n\tBody extends ZodSchema | undefined = Opts[\"body\"] &\n\t\t(undefined extends InferUseOptions<Opts>[\"body\"] ? {} : InferUseOptions<Opts>[\"body\"]),\n> = Body extends ZodSchema\n\t? Body extends ZodOptional<any>\n\t\t? {\n\t\t\t\tbody?: Prettify<z.infer<Body>>;\n\t\t\t}\n\t\t: {\n\t\t\t\tbody: Prettify<z.infer<Body>>;\n\t\t\t}\n\t: {\n\t\t\tbody?: undefined;\n\t\t};\n"],"mappings":"oKAAA,OAAY,YAAAA,MAAkD,MCA9D,MAAkB,MAiBX,SAASC,EAAiBC,EAAuBC,EAAe,CACnE,GAAI,OAAOD,GAAqB,WAC5B,OAAOE,EAAe,IAAK,CACvB,OAAQ,GACZ,EAAGF,CAAgB,EAEvB,GAAI,CAACC,EACD,MAAM,IAAI,MAAM,gCAAgC,EAMpD,OAJiBC,EAAe,IAAK,CACj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,WAAY,uBAChB,CAAC,CACL,CACJ,CAGA,CACJ,EEtIA,MAAoD","names":["ZodError","createMiddleware","optionsOrHandler","handler","createEndpoint","createMiddlewareCreator","fn","APIError","status","body","__publicField","algorithm","getCryptoKey","secret","secretBuf","makeSignature","value","key","signature","verifySignature","base64Signature","signatureBinStr","i","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","ZodError","APIError","createRou3Router","addRoute","findRoute","getBody","request","contentType","formData","result","value","key","shouldSerialize","body","statusCode","createRouter","endpoints","config","router","createRou3Router","endpoint","method","addRoute","middlewareRouter","route","request","url","path","findRoute","handler","body","getBody","headers","query","middleware","middlewareContext","res","handlerRes","resBody","shouldSerialize","e","onErrorRes","APIError","statusCode"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "better-call",
3
- "version": "0.0.5-beta.13",
3
+ "version": "0.0.5-beta.15",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -24,6 +24,7 @@
24
24
  "typescript": "^5.0.0"
25
25
  },
26
26
  "dependencies": {
27
+ "@biomejs/biome": "^1.8.3",
27
28
  "rou3": "^0.5.1"
28
29
  },
29
30
  "exports": {