1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,400969,e=>{"use strict";let t,r,o,n,i,s;var a,c,d=e.i(791768),l=e.i(90985);let u=[],p=0,f=0,h=e=>{let t=[],r={get:()=>(r.lc||r.listen(()=>{})(),r.value),lc:0,listen:e=>(r.lc=t.push(e),()=>{for(let t=p+4;t<u.length;)u[t]===e?u.splice(t,4):t+=4;let o=t.indexOf(e);~o&&(t.splice(o,1),--r.lc||r.off())}),notify(e,o){f++;let n=!u.length;for(let n of t)u.push(n,r.value,e,o);if(n){for(p=0;p<u.length;p+=4)u[p](u[p+1],u[p+2],u[p+3]);u.length=0}},off(){},set(e){let t=r.value;t!==e&&(r.value=e,r.notify(t))},subscribe(e){let t=r.listen(e);return e(r.value),t},value:e};return r};var m=Object.defineProperty,y=Object.defineProperties,g=Object.getOwnPropertyDescriptors,w=Object.getOwnPropertySymbols,b=Object.prototype.hasOwnProperty,v=Object.prototype.propertyIsEnumerable,E=(e,t,r)=>t in e?m(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t)=>{for(var r in t||(t={}))b.call(t,r)&&E(e,r,t[r]);if(w)for(var r of w(t))v.call(t,r)&&E(e,r,t[r]);return e},x=(e,t)=>y(e,g(t)),T=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r}},k=async(e,t)=>{var r,o,n,i,s,a;let c=t||{},d={onRequest:[null==t?void 0:t.onRequest],onResponse:[null==t?void 0:t.onResponse],onSuccess:[null==t?void 0:t.onSuccess],onError:[null==t?void 0:t.onError],onRetry:[null==t?void 0:t.onRetry]};if(!t||!(null==t?void 0:t.plugins))return{url:e,options:c,hooks:d};for(let l of(null==t?void 0:t.plugins)||[]){if(l.init){let o=await (null==(r=l.init)?void 0:r.call(l,e.toString(),t));c=o.options||c,e=o.url}d.onRequest.push(null==(o=l.hooks)?void 0:o.onRequest),d.onResponse.push(null==(n=l.hooks)?void 0:n.onResponse),d.onSuccess.push(null==(i=l.hooks)?void 0:i.onSuccess),d.onError.push(null==(s=l.hooks)?void 0:s.onError),d.onRetry.push(null==(a=l.hooks)?void 0:a.onRetry)}return{url:e,options:c,hooks:d}},S=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},R=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}},_=async e=>{let t={},r=async e=>"function"==typeof e?await e():e;if(null==e?void 0:e.auth){if("Bearer"===e.auth.type){let o=await r(e.auth.token);if(!o)return t;t.authorization=`Bearer ${o}`}else if("Basic"===e.auth.type){let o=r(e.auth.username),n=r(e.auth.password);if(!o||!n)return t;t.authorization=`Basic ${btoa(`${o}:${n}`)}`}else if("Custom"===e.auth.type){let o=r(e.auth.value);if(!o)return t;t.authorization=`${r(e.auth.prefix)} ${o}`}}return t},U=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function I(e){if(void 0===e)return!1;let t=typeof e;return"string"===t||"number"===t||"boolean"===t||null===t||"object"===t&&(!!Array.isArray(e)||!e.buffer&&(e.constructor&&"Object"===e.constructor.name||"function"==typeof e.toJSON))}function O(e){try{return JSON.parse(e)}catch(t){return e}}function P(e){return"function"==typeof e}async function D(e){let t=new Headers(null==e?void 0:e.headers);for(let[r,o]of Object.entries(await _(e)||{}))t.set(r,o);if(!t.has("content-type")){let r=I(null==e?void 0:e.body)?"application/json":null;r&&t.set("content-type",r)}return t}var Z=class e extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function j(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new Z(r.issues);return r.value}var L=["get","post","put","patch","delete"],C=async(e,t)=>{var r,o,n,i,s,a,c,d;let l,{hooks:u,url:p,options:f}=await k(e,t),h=function(e){if(null==e?void 0:e.customFetchImpl)return e.customFetchImpl;if("undefined"!=typeof globalThis&&P(globalThis.fetch))return globalThis.fetch;if("undefined"!=typeof window&&P(window.fetch))return window.fetch;throw Error("No fetch implementation found")}(f),m=new AbortController,y=null!=(r=f.signal)?r:m.signal,g=function(e,t){let{baseURL:r,params:o,query:n}=t||{query:{},params:{},baseURL:""},i=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r||"";if(e.startsWith("@")){let t=e.toString().split("@")[1].split("/")[0];L.includes(t)&&(e=e.replace(`@${t}/`,"/"))}i.endsWith("/")||(i+="/");let[s,a]=e.replace(i,"").split("?"),c=new URLSearchParams(a);for(let[e,t]of Object.entries(n||{}))null!=t&&c.set(e,String(t));if(o)if(Array.isArray(o))for(let[e,t]of s.split("/").filter(e=>e.startsWith(":")).entries()){let r=o[e];s=s.replace(t,r)}else for(let[e,t]of Object.entries(o))s=s.replace(`:${e}`,String(t));(s=s.split("/").map(encodeURIComponent).join("/")).startsWith("/")&&(s=s.slice(1));let d=c.toString();return(d=d.length>0?`?${d}`.replace(/\+/g,"%20"):"",i.startsWith("http"))?new URL(`${s}${d}`,i):`${i}${s}${d}`}(p,f),w=function(e){if(!(null==e?void 0:e.body))return null;let t=new Headers(null==e?void 0:e.headers);if(I(e.body)&&!t.has("content-type")){for(let[t,r]of Object.entries(null==e?void 0:e.body))r instanceof Date&&(e.body[t]=r.toISOString());return JSON.stringify(e.body)}return e.body}(f),b=await D(f),v=function(e,t){var r;if(null==t?void 0:t.method)return t.method.toUpperCase();if(e.startsWith("@")){let o=null==(r=e.split("@")[1])?void 0:r.split("/")[0];return L.includes(o)?o.toUpperCase():(null==t?void 0:t.body)?"POST":"GET"}return(null==t?void 0:t.body)?"POST":"GET"}(p,f),E=x(A({},f),{url:g,headers:b,body:w,method:v,signal:y});for(let e of u.onRequest)if(e){let t=await e(E);t instanceof Object&&(E=t)}("pipeTo"in E&&"function"==typeof E.pipeTo||"function"==typeof(null==(o=null==t?void 0:t.body)?void 0:o.pipe))&&!("duplex"in E)&&(E.duplex="half");let{clearTimeout:_}=(!(null==f?void 0:f.signal)&&(null==f?void 0:f.timeout)&&(l=setTimeout(()=>null==m?void 0:m.abort(),null==f?void 0:f.timeout)),{abortTimeout:l,clearTimeout:()=>{l&&clearTimeout(l)}}),Z=await h(E.url,E);_();let N={response:Z,request:E};for(let e of u.onResponse)if(e){let r=await e(x(A({},N),{response:(null==(n=null==t?void 0:t.hookOptions)?void 0:n.cloneResponse)?Z.clone():Z}));r instanceof Response?Z=r:r instanceof Object&&(Z=r.response)}if(Z.ok){if("HEAD"===E.method)return{data:"",error:null};let e=function(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let o=t.split(";").shift()||"";return U.test(o)?"json":r.has(o)||o.startsWith("text/")?"text":"blob"}(Z),r={data:"",response:Z,request:E};if("json"===e||"text"===e){let e=await Z.text(),t=null!=(i=E.jsonParser)?i:O;r.data=await t(e)}else r.data=await Z[e]();for(let e of((null==E?void 0:E.output)&&E.output&&!E.disableValidation&&(r.data=await j(E.output,r.data)),u.onSuccess))e&&await e(x(A({},r),{response:(null==(s=null==t?void 0:t.hookOptions)?void 0:s.cloneResponse)?Z.clone():Z}));return(null==t?void 0:t.throw)?r.data:{data:r.data,error:null}}let $=null!=(a=null==t?void 0:t.jsonParser)?a:O,z=await Z.text(),H=function(e){try{return JSON.parse(e),!0}catch(e){return!1}}(z),V=H?await $(z):null,q={response:Z,responseText:z,request:E,error:x(A({},V),{status:Z.status,statusText:Z.statusText})};for(let e of u.onError)e&&await e(x(A({},q),{response:(null==(c=null==t?void 0:t.hookOptions)?void 0:c.cloneResponse)?Z.clone():Z}));if(null==t?void 0:t.retry){let r=function(e){if("number"==typeof e)return new S({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new S(e);case"exponential":return new R(e);default:throw Error("Invalid retry strategy")}}(t.retry),o=null!=(d=t.retryAttempt)?d:0;if(await r.shouldAttemptRetry(o,Z)){for(let e of u.onRetry)e&&await e(N);let n=r.getDelay(o);return await new Promise(e=>setTimeout(e,n)),await C(e,x(A({},t),{retryAttempt:o+1}))}}if(null==t?void 0:t.throw)throw new T(Z.status,Z.statusText,H?V:z);return{data:null,error:x(A({},V),{status:Z.status,statusText:Z.statusText})}};let N=Object.create(null),$=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?N:globalThis),z=new Proxy(N,{get:(e,t)=>$()[t]??N[t],has:(e,t)=>
1t in $()||t in N,set:(e,t,r)=>($(!0)[t]=r,!0),deleteProperty(e,t){if(!t)return!1;let r=$(!0);return delete r[t],!0},ownKeys:()=>Object.keys($(!0))}),H=void 0!==l.default&&l.default.env&&"production"||"",V="dev"===H||"development"===H,q=(e,t)=>{var r,o;return r=r=>{let o=t(r);o&&e.events[6].push(o)},o=t=>{let r=e.listen;e.listen=(...o)=>(e.lc||e.active||(e.active=!0,t()),r(...o));let o=e.off;return e.events[6]=[],e.off=()=>{o(),setTimeout(()=>{if(e.active&&!e.lc){for(let t of(e.active=!1,e.events[6]))t();e.events[6]=[]}},1e3)},()=>{e.listen=r,e.off=o}},e.events=e.events||{},e.events[15]||(e.events[15]=o(t=>{e.events[5].reduceRight((e,t)=>(t(e),e),{shared:{},...t})})),e.events[5]=e.events[5]||[],e.events[5].push(r),()=>{let t=e.events[5],o=t.indexOf(r);t.splice(o,1),t.length||(delete e.events[5],e.events[15](),delete e.events[15])}},B="undefined"==typeof window;class K extends Error{constructor(e,t){super(e),this.name="BetterAuthError",this.message=e,this.cause=t,this.stack=""}}function M(e){return{newRole:e=>{var t;return{authorize(e,r="AND"){let o=!1;for(let[n,i]of Object.entries(e)){let e=t[n];if(!e)return{success:!1,error:`You are not allowed to access resource: ${n}`};if(Array.isArray(i))o=i.every(t=>e.includes(t));else if("object"==typeof i)o="OR"===i.connector?i.actions.some(t=>e.includes(t)):i.actions.every(t=>e.includes(t));else throw new K("Invalid access control request");if(o&&"OR"===r)return{success:o};if(!o&&"AND"===r)return{success:!1,error:`unauthorized to access resource "${n}"`}}return o?{success:o}:{success:!1,error:"Not authorized"}},statements:t=e}},statements:e}}let W=M({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]});W.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"],team:["create","update","delete"],ac:["create","read","update","delete"]}),W.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]}),W.newRole({organization:[],member:[],invitation:[],team:[],ac:["read"]});var F=e.i(598439);let J=globalThis.crypto,G=J.subtle,Q=e=>J.getRandomValues(e);var Y=Object.defineProperty,X={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},ee=function(e,t){class r extends e{#e;constructor(...e){if(function(){let e=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");return void 0===e?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,"writable")?e.writable:void 0!==e.set}()){const t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);const t=Error().stack;t&&(this.#e=function(e){let t=e.split("\n at ");return t.length<=1?e:(t.splice(1,1),t.join("\n at "))}(t.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(r.prototype,"constructor",{get:()=>t,enumerable:!1,configurable:!0}),r}(class extends Error{constructor(e="INTERNAL_SERVER_ERROR",t,r={},o="number"==typeof e?e:X[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=r,this.statusCode=o,this.name="APIError",this.status=e,this.headers=r,this.statusCode=o,this.body=t?{code:t?.message?.toUpperCase().replace(/ /g,"_").replace(/[^A-Z0-9_]/g,""),...t}:void 0}},Error);function et(e){return e instanceof ee||e?.name==="APIError"}async function er(e,t={}){let r={body:t.body,query:t.query};if(e.body){let o=await e.body["~standard"].validate(t.body);if(o.issues)return{data:null,error:eo(o.issues,"body")};r.body=o.value}if(e.query){let o=await e.query["~standard"].validate(t.query);if(o.issues)return{data:null,error:eo(o.issues,"query")};r.query=o.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:"Headers is required"}}:e.requireRequest&&!t.request?{data:null,error:{message:"Request is required"}}:{data:r,error:null}}function eo(e,t){let r=[];for(let t of e){let e=t.message;r.push(e)}return{message:`Invalid ${t} parameters`}}var en={name:"HMAC",hash:"SHA-256"},ei=async e=>{let t="string"==typeof e?new TextEncoder().encode(e):e;return await G.importKey("raw",t,en,!1,["sign","verify"])},es=async(e,t,r)=>{try{let o=atob(e),n=new Uint8Array(o.length);for(let e=0,t=o.length;e<t;
1e++)n[e]=o.charCodeAt(e);return await G.verify(en,r,n,new TextEncoder().encode(t))}catch(e){return!1}},ea=async(e,t)=>{let r=await ei(t);return btoa(String.fromCharCode(...new Uint8Array(await G.sign(en.name,r,new TextEncoder().encode(e)))))},ec=async(e,t)=>{let r=await ea(e,t);return encodeURIComponent(e=`${e}.${r}`)},ed=(e,t)=>{let r=e;if(t)if("secure"===t)r="__Secure-"+e;else{if("host"!==t)return;r="__Host-"+e}return r},el=(e,t,r={})=>{let o;if(o=r?.prefix==="secure"?`__Secure-${e}=${t}`:r?.prefix==="host"?`__Host-${e}=${t}`:`${e}=${t}`,e.startsWith("__Secure-")&&!r.secure&&(r.secure=!0),e.startsWith("__Host-")&&(r.secure||(r.secure=!0),"/"!==r.path&&(r.path="/"),r.domain&&(r.domain=void 0)),r&&"number"==typeof r.maxAge&&r.maxAge>=0){if(r.maxAge>3456e4)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");o+=`; Max-Age=${Math.floor(r.maxAge)}`}if(r.domain&&"host"!==r.prefix&&(o+=`; Domain=${r.domain}`),r.path&&(o+=`; Path=${r.path}`),r.expires){if(r.expires.getTime()-Date.now()>3456e7)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");o+=`; Expires=${r.expires.toUTCString()}`}return r.httpOnly&&(o+="; HttpOnly"),r.secure&&(o+="; Secure"),r.sameSite&&(o+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`),r.partitioned&&(r.secure||(r.secure=!0),o+="; Partitioned"),o},eu=async(e,t,r,o)=>el(e,t=await ec(t,r),o),ep=async(e,{options:t,path:r})=>{let o=new Headers,{data:n,error:i}=await er(t,e);if(i)throw new ee(400,{message:i.message,code:"VALIDATION_ERROR"});let s="headers"in e?e.headers instanceof Headers?e.headers:new Headers(e.headers):"request"in e&&e.request instanceof Request?e.request.headers:null,a=s?.get("cookie"),c=a?function(e){if("string"!=typeof e)throw TypeError("argument str must be a string");let t=new Map,r=0;for(;r<e.length;){let o=e.indexOf("=",r);
1if(-1===o)break;let n=e.indexOf(";",r);if(-1===n)n=e.length;else if(n<o){r=e.lastIndexOf(";",o-1)+1;continue}let i=e.slice(r,o).trim();if(!t.has(i)){let r=e.slice(o+1,n).trim();34===r.codePointAt(0)&&(r=r.slice(1,-1)),t.set(i,function(e){try{return e.includes("%")?decodeURIComponent(e):e}catch{return e}}(r))}r=n+1}return t}(a):void 0,d={...e,body:n.body,query:n.query,path:e.path||r,context:"context"in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:"params"in e?e.params:void 0,method:e.method,setHeader:(e,t)=>{o.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let r=ed(e,t);return r&&c?.get(r)||null},getSignedCookie:async(e,t,r)=>{let o=ed(e,r);if(!o)return null;let n=c?.get(o);if(!n)return null;let i=n.lastIndexOf(".");if(i<1)return null;let s=n.substring(0,i),a=n.substring(i+1);if(44!==a.length||!a.endsWith("="))return null;let d=await ei(t);return!!await es(a,s,d)&&s},setCookie:(e,t,r)=>{var n;let i=el(e,n=encodeURIComponent(n=t),r);return o.append("set-cookie",i),i},setSignedCookie:async(e,t,r,n)=>{let i=await eu(e,t,r,n);return o.append("set-cookie",i),i},redirect:e=>(o.set("location",e),new ee("FOUND",void 0,o)),error:(e,t,r)=>new ee(e,t,r),json:(t,r)=>e.asResponse?{body:r?.body||t,routerResponse:r,_flag:"json"}:t,responseHeaders:o};for(let e of t.use||[]){let t=await e({...d,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(d.context,t.response),t.headers&&t.headers.forEach((e,t)=>{d.responseHeaders.set(t,e)})}return d};function ef(e,t){let r=async r=>{let o="function"==typeof e?e:t,n=await ep(r,{options:"function"==typeof e?{}:e,path:"/"});if(!o)throw Error("handler must be defined");let i=await o(n),s=n.responseHeaders;return r.returnHeaders?{headers:s,response:i}:i};return r.options="function"==typeof e?{}:e,r}ef.create=e=>function(t,r){if("function"==typeof t)return ef({use:e?.use},t);if(!r)throw Error("Middleware handler is required");return ef({...t,method:"*",use:[...e?.use||[],...t.use||[]]},r)};var eh=(e,t,r)=>{let o=async(...o)=>{let n=o[0]||{},i=await ep(n,{options:t,path:e}),s=await r(i).catch(async e=>{if(et(e)){let r=t.onAPIError;if(r&&await r(e),n.asResponse)return e}throw e}),a=i.responseHeaders;return n.asResponse?function e(t,r){if(t instanceof Response)return r?.headers instanceof Headers&&r.headers.forEach((e,r)=>{t.headers.set(r,e)}),t;if(t&&"object"==typeof t&&"_flag"in t&&"json"===t._flag){let e=t.body,o=t.routerResponse;if(o instanceof Response)return o;let n=new Headers({...o?.headers,...t.headers,...r?.headers,"Content-Type":"application/json"});return new Response(JSON.stringify(e),{...o,headers:n,status:t.status??r?.status??o?.status,statusText:r?.statusText??o?.statusText})}if(et(t))return e(t.body,{status:r?.status??t.statusCode,statusText:t.status.toString(),headers:r?.headers||t.headers});let o=t,n=new Headers(r?.headers);if(t){if("string"==typeof t)o=t,n.set("Content-Type","text/plain");else if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))o=t,n.set("Content-Type","application/octet-stream");else if(t instanceof Blob)o=t,n.set("Content-Type",t.type||"application/octet-stream");else if(t instanceof FormData)o=t;else if(t instanceof URLSearchParams)o=t,n.set("Content-Type","application/x-www-form-urlencoded");else if(t instanceof ReadableStream)o=t,n.set("Content-Type","application/octet-stream");else if(function(e){if(void 0===e)return!1;let t=typeof e;return"string"===t||"number"===t||"boolean"===t||null===t||"object"===t&&(!!Array.isArray(e)||!e.buffer&&(e.constructor&&"Object"===e.constructor.name||"function"==typeof e.toJSON))}(t)){let e,r;e=0,r=new WeakMap,o=JSON.stringify(t,(t,o)=>{if("bigint"==typeof o)return o.toString();if("object"==typeof o&&null!==o){if(r.has(o))return`[Circular ref-${r.get(o)}]`;r.set(o,e++)}return o},void 0),n.set("Content-Type","application/json")}}else null===t&&(o=JSON.stringify(null)),n.set("content-type","application/json");return new Response(o,{...r,headers:n})}(s,{headers:a}):n.returnHeaders?{headers:a,response:s}:s};return o.options=t,o.path=e,o};function em(e,t,r){function o(r,o){var n;for(let i in Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(n=r._zod).traits??(n.traits=new Set),r._zod.traits.add(e),t(r,o),s.prototype)i in r||Object.defineProperty(r,i,{value:s.prototype[i].bind(r)});r._zod.constr=s,r._zod.def=o}
1let n=r?.Parent??Object;class i extends n{}function s(e){var t;let n=r?.Parent?new i:this;for(let r of(o(n,e),(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred))r();return n}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}eh.create=e=>(t,r,o)=>eh(t,{...r,use:[...r?.use||[],...e?.use||[]]},o),Object.freeze({status:"aborted"}),Symbol("zod_brand");var ey=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},eg={};function ew(e){return e&&Object.assign(eg,e),eg}var eb={},ev={BIGINT_FORMAT_RANGES:()=>e1,Class:()=>ts,NUMBER_FORMAT_RANGES:()=>e0,aborted:()=>e9,allowsEval:()=>eV,assert:()=>eS,assertEqual:()=>eA,assertIs:()=>eT,assertNever:()=>ek,assertNotEqual:()=>ex,assignProp:()=>ej,cached:()=>eI,captureStackTrace:()=>ez,cleanEnum:()=>ti,cleanRegex:()=>eP,clone:()=>eJ,createTransparentProxy:()=>eQ,defineLazy:()=>eZ,esc:()=>e$,escapeRegex:()=>eF,extend:()=>e5,finalizeIssue:()=>tt,floatSafeRemainder:()=>eD,getElementAtPath:()=>eL,getEnumValues:()=>eR,getLengthableOrigin:()=>to,getParsedType:()=>eK,getSizableOrigin:()=>tr,isObject:()=>eH,isPlainObject:()=>eq,issue:()=>tn,joinValues:()=>e_,jsonStringifyReplacer:()=>eU,merge:()=>e4,normalizeParams:()=>eG,nullish:()=>eO,numKeys:()=>eB,omit:()=>e6,optionalKeys:()=>eX,partial:()=>e8,pick:()=>e2,prefixIssues:()=>e7,primitiveTypes:()=>eW,promiseAllObject:()=>eC,propertyKeyTypes:()=>eM,randomString:()=>eN,required:()=>e3,stringifyPrimitive:()=>eY,unwrapMessage:()=>te};for(var eE in ev)Y(eb,eE,{get:ev[eE],enumerable:!0});function eA(e){return e}function ex(e){return e}function eT(e){}function ek(e){throw Error()}function eS(e){}function eR(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function e_(e,t="|"){return e.map(e=>eY(e)).join(t)}function eU(e,t){return"bigint"==typeof t?t.toString():t}function eI(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function eO(e){return null==e}function eP(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function eD(e,t){let r=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,n=r>o?r:o;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}function eZ(e,t,r){Object.defineProperty(e,t,{get(){{let o=r();return e[t]=o,o}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function ej(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function eL(e,t){return t?t.reduce((e,t)=>e?.[t],e):e}function eC(e){let t=Object.keys(e);return Promise.all(t.map(t=>e[t])).then(e=>{let r={};for(let o=0;o<t.length;o++)r[t[o]]=e[o];return r})}function eN(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function e$(e){return JSON.stringify(e)}var ez=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function eH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var eV=eI(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function eq(e){if(!1===eH(e))return!1;let t=e.constructor;if(void 0===t)return!0;let r=t.prototype;return!1!==eH(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function eB(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var eK=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return"promise";if("undefined"!=typeof Map&&e instanceof Map)return"map";if("undefined"!=typeof Set&&e instanceof Set)return"set";if("undefined"!=typeof Date&&e instanceof Date)return"date";if("undefined"!=typeof File&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},eM=new Set(["string","number","symbol"]),eW=new Set(["string","number","bigint","boolean","symbol","undefined"]);function eF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eJ(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function eG(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function eQ(e){let t;return new Proxy({},{get:(r,o,n)=>(t??(t=e()),Reflect.get(t,o,n)),set:(r,o,n,i)=>(t??(t=e()),Reflect.set(t,o,n,i)),has:(r,o)=>(t??(t=e()),Reflect.has(t,o)),deleteProperty:(r,o)=>(t??(t=e()),Reflect.deleteProperty(t,o)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,o)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)),defineProperty:(r,o,n)=>(t??(t=e()),Reflect.defineProperty(t,o,n))})}function eY(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function eX(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}var e0={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},e1={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function e2(e,t){let r={},o=e._zod.def;for(let e in t){if(!(e in o.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(r[e]=o.shape[e])}return eJ(e,{...e._zod.def,shape:r,checks:[]})}function e6(e,t){let r={...e._zod.def.shape},o=e._zod.def;for(let e in t){if(!(e in o.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return eJ(e,{...e._zod.def,shape:r,checks:[]})}function e5(e,t){if(!eq(t))throw Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let r={...e._zod.def.shape,...t};return ej(this,"shape",r),r},checks:[]};return eJ(e,r)}function e4(e,t){return eJ(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return ej(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function e8(e,t,r){let o=t._zod.def.shape,n={...o};if(r)for(let t in r){if(!(t in o))throw Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=e?new e({type:"optional",innerType:o[t]}):o[t])}else for(let t in o)n[t]=e?new e({type:"optional",innerType:o[t]}):o[t];return eJ(t,{...t._zod.def,shape:n,checks:[]})}function e3(e,t,r){let o=t._zod.def.shape,n={...o};if(r)for(let t in r){if(!(t in n))throw Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=new e({type:"nonoptional",innerType:o[t]}))}else for(let t in o)n[t]=new e({type:"nonoptional",innerType:o[t]});return eJ(t,{...t._zod.def,shape:n,checks:[]})}function e9(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function e7(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function te(e){return"string"==typeof e?e:e?.message}function tt(e,t,r){let o={...e,path:e.path??[]};return e.message||(o.message=te(e.inst?._zod.def?.error?.(e))??te(t?.error?.(e))??te(r.customError?.(e))??te(r.localeError?.(e))??"Invalid input"),delete o.inst,delete o.continue,t?.reportInput||delete o.input,o}function tr(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function to(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function tn(...e){let[t,r,o]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:o}:{...t}}function ti(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var ts=class{constructor(...e){}},ta=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get:()=>JSON.stringify(t,eU,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},tc=em("$ZodError",ta),td=em("$ZodError",ta,{Parent:Error}),tl=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new ey;return i.issues.length?{success:!1,error:new(e??tc)(i.issues.map(e=>
1tt(e,n,ew())))}:{success:!0,data:i.value}},tu=tl(td),tp=e=>async(t,r,o)=>{let n=o?Object.assign(o,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>tt(e,n,ew())))}:{success:!0,data:i.value}},tf=tp(td),th=em("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),tm=em("$ZodCheckMaxLength",(e,t)=>{var r;th.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!eO(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let o=r.value;if(o.length<=t.maximum)return;let n=to(o);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),ty=em("$ZodCheckMinLength",(e,t)=>{var r;th.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!eO(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let o=r.value;if(o.length>=t.minimum)return;let n=to(o);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),tg=em("$ZodCheckLengthEquals",(e,t)=>{var r;th.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!eO(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let o=r.value,n=o.length;if(n===t.length)return;let i=to(o),s=n>t.length;r.issues.push({origin:i,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),tw=em("$ZodCheckOverwrite",(e,t)=>{th.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),tb=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}},tv={major:4,minor:0,patch:0},tE=em("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=tv;let o=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&o.unshift(e),o))for(let r of t._zod.onattach)r(e);if(0===o.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let o,n=e9(e);for(let i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(n)continue;let t=e.issues.length,s=i._zod.check(e);if(s instanceof Promise&&r?.async===!1)throw new ey;if(o||s instanceof Promise)o=(o??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(n||(n=e9(e,t)))});else{if(e.issues.length===t)continue;n||(n=e9(e,t))}}return o?o.then(()=>e):e};e._zod.run=(r,n)=>{let i=e._zod.parse(r,n);if(i instanceof Promise){if(!1===n.async)throw new ey;return i.then(e=>t(e,o,n))}return t(i,o,n)}}e["~standard"]={validate:t=>{try{let r=tu(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return tf(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),tA=em("$ZodUnknown",(e,t)=>{tE.init(e,t),e._zod.parse=e=>e}),tx=em("$ZodNever",(e,t)=>{tE.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function tT(e,t,r){e.issues.length&&t.issues.push(...e7(r,e.issues)),t.value[r]=e.value}var tk=em("$ZodArray",(e,t)=>{tE.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let e=0;e<n.length;e++){let s=n[e],a=t.element._zod.run({value:s,issues:[]},o);a instanceof Promise?i.push(a.then(t=>tT(t,r,e))):tT(a,r,e)}return i.length?Promise.all(i).then(()=>r):r}});function tS(e,t,r){e.issues.length&&t.issues.push(...e7(r,e.issues)),t.value[r]=e.value}function tR(e,t,r,o){e.issues.length?void 0===o[r]?r in o?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...e7(r,e.issues)):void 0===e.value?r in o&&(t.value[r]=void 0):t.value[r]=e.value}function t_(e,t,r,o){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>tt(e,o,ew())))}),t}(e,t)=>{let r,o;tE.init(e,t);let n=eI(()=>{let e=Object.keys(t.shape);for(let r of e)if(!(t.shape[r]instanceof tE))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=eX(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});eZ(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let o=e[t]._zod;if(o.values)for(let e of(r[t]??(r[t]=new Set),o.values))r[t].add(e)}return r});let i=!eg.jitless,s=i&&eV.value,a=t.catchall;e._zod.parse=(c,d)=>{o??(o=n.value);let l=c.value;if(!eH(l))return c.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),c;let u=[];
1if(i&&s&&d?.async===!1&&!0!==d.jitless)r||(r=(e=>{let t=new tb(["shape","payload","ctx"]),r=n.value,o=e=>{let t=e$(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let i=Object.create(null),s=0;for(let e of r.keys)i[e]=`key_${s++}`;for(let e of(t.write("const newResult = {}"),r.keys))if(r.optionalKeys.has(e)){let r=i[e];t.write(`const ${r} = ${o(e)};`);let n=e$(e);t.write(` 2 if (${r}.issues.length) { 3 if (input[${n}] === undefined) { 4 if (${n} in input) { 5 newResult[${n}] = undefined; 6 } 7 } else { 8 payload.issues = payload.issues.concat( 9 ${r}.issues.map((iss) => ({ 10 ...iss, 11 path: iss.path ? [${n}, ...iss.path] : [${n}], 12 })) 13 ); 14 } 15 } else if (${r}.value === undefined) { 16 if (${n} in input) newResult[${n}] = undefined; 17 } else { 18 newResult[${n}] = ${r}.value; 19 } 20 `)}else{let r=i[e];t.write(`const ${r} = ${o(e)};`),t.write(` 21 if (${r}.issues.length) payload.issues = payload.issues.concat(${r}.issues.map(iss => ({ 22 ...iss, 23 path: iss.path ? [${e$(e)}, ...iss.path] : [${e$(e)}] 24 })));`),t.write(`newResult[${e$(e)}] = ${r}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");let a=t.compile();return(t,r)=>a(e,t,r)})(t.shape)),c=r(c,d);else{c.value={};let e=o.shape;for(let t of o.keys){let r=e[t],o=r._zod.run({value:l[t],issues:[]},d),n="optional"===r._zod.optin&&"optional"===r._zod.optout;o instanceof Promise?u.push(o.then(e=>n?tR(e,c,t,l):tS(e,c,t))):n?tR(o,c,t,l):tS(o,c,t)}}if(!a)return u.length?Promise.all(u).then(()=>c):c;let p=[],f=o.keySet,h=a._zod,m=h.def.type;
24for(let e of Object.keys(l)){if(f.has(e))continue;if("never"===m){p.push(e);continue}let t=h.run({value:l[e],issues:[]},d);t instanceof Promise?u.push(t.then(t=>tS(t,c,e))):tS(t,c,e)}return(p.length&&c.issues.push({code:"unrecognized_keys",keys:p,input:l,inst:e}),u.length)?Promise.all(u).then(()=>c):c}};var tU=em("$ZodUnion",(e,t)=>{tE.init(e,t),eZ(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),eZ(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),eZ(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),eZ(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>eP(e.source)).join("|")})$`)}}),e._zod.parse=(r,o)=>{let n=!1,i=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},o);if(t instanceof Promise)i.push(t),n=!0;else{if(0===t.issues.length)return t;i.push(t)}}return n?Promise.all(i).then(t=>t_(t,r,e,o)):t_(i,r,e,o)}}),tI=em("$ZodIntersection",(e,t)=>{tE.init(e,t),e._zod.parse=(e,r)=>{let o=e.value,n=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);return n instanceof Promise||i instanceof Promise?Promise.all([n,i]).then(([t,r])=>tO(e,t,r)):tO(e,n,i)}});function tO(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),e9(e))return e;let o=function e(t,r){if(t===r||t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(eq(t)&&eq(r)){let o=Object.keys(r),n=Object.keys(t).filter(e=>-1!==o.indexOf(e)),i={...t,...r};for(let o of n){let n=e(t[o],r[o]);if(!n.valid)return{valid:!1,mergeErrorPath:[o,...n.mergeErrorPath]};i[o]=n.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};let o=[];for(let n=0;n<t.length;n++){let i=e(t[n],r[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};o.push(i.data)}return{valid:!0,data:o}}return{valid:!1,mergeErrorPath:[]}}(t.value,r.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var tP=em("$ZodEnum",(e,t)=>{tE.init(e,t);let r=eR(t.entries);e._zod.values=new Set(r),e._zod.pattern=RegExp(`^(${r.filter(e=>eM.has(typeof e)).map(e=>"string"==typeof e?eF(e):e.toString()).join("|")})$`),e._zod.parse=(t,o)=>{let n=t.value;return e._zod.values.has(n)||t.issues.push({code:"invalid_value",values:r,input:n,inst:e}),t}}),tD=em("$ZodTransform",(e,t)=>{tE.init(e,t),e._zod.parse=(e,r)=>{let o=t.transform(e.value,e);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(t=>(e.value=t,e));if(o instanceof Promise)throw new ey;return e.value=o,e}}),tZ=em("$ZodOptional",(e,t)=>{tE.init(e,t),e._zod.optin="optional",e._zod.optout="optional",eZ(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),eZ(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${eP(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,r):void 0===e.value?e:t.innerType._zod.run(e,r)}),tj=em("$ZodNullable",(e,t)=>{tE.init(e,t),eZ(e._zod,"optin",()=>t.innerType._zod.optin),eZ(e._zod,"optout",()=>t.innerType._zod.optout),eZ(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${eP(e.source)}|null)$`):void 0}),eZ(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),tL=em("$ZodDefault",(e,t)=>{tE.init(e,t),e._zod.optin="optional",eZ(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;let o=t.innerType._zod.run(e,r);return o instanceof Promise?o.then(e=>tC(e,t)):tC(o,t)}});function tC(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var tN=em("$ZodPrefault",(e,t)=>{tE.init(e,t),e._zod.optin="optional",eZ(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),t$=em("$ZodNonOptional",(e,t)=>{tE.init(e,t),eZ(e._zod,"values",()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(t=>tz(t,e)):tz(n,e)}});function tz(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var tH=em("$ZodCatch",(e,t)=>{tE.init(e,t),e._zod.optin="optional",eZ(e._zod,"optout",()=>t.innerType._zod.optout),eZ(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{let o=t.innerType._zod.run(e,r);return o instanceof Promise?o.then(o=>(e.value=o.value,o.issues.length&&(e.value=t.catchValue({...e,error:{issues:o.issues.map(e=>tt(e,r,ew()))},input:e.value}),e.issues=[]),e)):(e.value=o.value,o.issues.length&&(e.value=t.catchValue({...e,error:{issues:o.issues.map(e=>tt(e,r,ew()))},input:e.value}),e.issues=[]),e)}}),tV=em("$ZodPipe",(e,t)=>{tE.init(e,t),eZ(e._zod,"values",()=>t.in._zod.values),eZ(e._zod,"optin",()=>t.in._zod.optin),eZ(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,r)=>{let o=t.in._zod.run(e,r);return o instanceof Promise?o.then(e=>tq(e,t,r)):tq(o,t,r)}});function tq(e,t,r){return e9(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var tB=em("$ZodReadonly",(e,t)=>{tE.init(e,t),eZ(e._zod,"propValues",()=>t.innerType._zod.propValues),eZ(e._zod,"values",()=>t.innerType._zod.values),eZ(e._zod,"optin",()=>t.innerType._zod.optin),eZ(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{let o=t.innerType._zod.run(e,r);return o instanceof Promise?o.then(tK):tK(o)}});function tK(e){return e.value=Object.freeze(e.value),e}var tM=em("$ZodCustom",(e,t)=>{th.init(e,t),tE.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then(t=>tW(t,r,o,e));tW(n,r,o,e)}});function tW(e,t,r,o){if(!e){let e={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(e.params=o._zod.def.params),t.issues.push(tn(e))}}Symbol("ZodOutput"),Symbol("ZodInput");var tF=new class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function tJ(e,t){return new ty({check:"min_length",...eG(t),minimum:e})}var tG=(e,t)=>{tc.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>{let r,o,n;return r=t||function(e){return e.message},o={_errors:[]},(n=e=>{for(let t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>n({issues:e}));else if("invalid_key"===t.code)n({issues:t.issues});else if("invalid_element"===t.code)n({issues:t.issues});
24else if(0===t.path.length)o._errors.push(r(t));else{let e=o,n=0;for(;n<t.path.length;){let o=t.path[n];n===t.path.length-1?(e[o]=e[o]||{_errors:[]},e[o]._errors.push(r(t))):e[o]=e[o]||{_errors:[]},e=e[o],n++}}})(e),o}},flatten:{value:t=>(function(e,t=e=>e.message){let r={},o=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}})(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get:()=>0===e.issues.length}})};em("ZodError",tG);var tQ=em("ZodError",tG,{Parent:Error}),tY=(e,t,r,o)=>{let n=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:t,issues:[]},n);if(i instanceof Promise)throw new ey;if(i.issues.length){let e=new(o?.Err??tQ)(i.issues.map(e=>tt(e,n,ew())));throw ez(e,o?.callee),e}return i.value},tX=async(e,t,r,o)=>{let n=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:t,issues:[]},n);if(i instanceof Promise&&(i=await i),i.issues.length){let e=new(o?.Err??tQ)(i.issues.map(e=>tt(e,n,ew())));throw ez(e,o?.callee),e}return i.value},t0=tl(tQ),t1=tp(tQ),t2=em("ZodType",(e,t)=>(tE.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>eJ(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>tY(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>t0(e,t,r),e.parseAsync=async(t,r)=>tX(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>t1(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(function(e,t={}){return new rl({type:"custom",check:"custom",fn:e,...eG(t)})}(t,r)),e.superRefine=t=>{var r,o;let n,i;return e.check((r=t,i=(o=e=>(e.addIssue=t=>{"string"==typeof t?e.issues.push(eb.issue(t,e.value,i._zod.def)):(t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=e.value),t.inst??(t.inst=i),t.continue??(t.continue=!i._zod.def.abort),e.issues.push(eb.issue(t)))},r(e.value,e)),(n=new th({check:"custom"}))._zod.check=o,n)))},e.overwrite=t=>e.check(new tw({check:"overwrite",tx:t})),e.optional=()=>re(e),e.nullable=()=>rr(e),e.nullish=()=>re(rr(e)),e.nonoptional=t=>{var r,o;return r=e,o=t,new ri({type:"nonoptional",innerType:r,...eb.normalizeParams(o)})},e.array=()=>(function(e,t){return new t5({type:"array",element:e,...eG(void 0)})})(e),e.or=t=>new t4({type:"union",options:[e,t],...eb.normalizeParams(void 0)}),e.and=t=>{var r;return r=e,new t8({type:"intersection",left:r,right:t})},e.transform=t=>rc(e,new t9({type:"transform",transform:t})),e.default=t=>{var r,o;return r=e,o=t,new ro({type:"default",innerType:r,get defaultValue(){return"function"==typeof o?o():o}})},e.prefault=t=>{var r,o;return r=e,o=t,new rn({type:"prefault",innerType:r,get defaultValue(){return"function"==typeof o?o():o}})},e.catch=t=>{var r;return new rs({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r})},e.pipe=t=>rc(e,t),e.readonly=()=>new rd({type:"readonly",innerType:e}),e.describe=t=>{let r=e.clone();return tF.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>tF.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return tF.get(e);let r=e.clone();return tF.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),t6=em("ZodUnknown",(e,t)=>{tA.init(e,t),t2.init(e,t)});(e,t)=>{tx.init(e,t),t2.init(e,t)};var t5=em("ZodArray",(e,t)=>{tk.init(e,t),t2.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(tJ(t,r)),e.nonempty=t=>e.check(tJ(1,t)),e.max=(t,r)=>e.check(new tm({check:"max_length",...eG(r),maximum:t})),e.length=(t,r)=>e.check(new tg({check:"length_equals",...eG(r),length:t})),e.unwrap=()=>e.element}),t4=em("ZodUnion",(e,t)=>{tU.init(e,t),t2.init(e,t),e.options=t.options}),t8=em("ZodIntersection",(e,t)=>{tI.init(e,t),t2.init(e,t)}),t3=em("ZodEnum",(e,t)=>{tP.init(e,t),t2.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(e,o)=>{let n={};for(let o of e)if(r.has(o))n[o]=t.entries[o];else throw Error(`Key ${o} not found in enum`);return new t3({...t,checks:[],...eb.normalizeParams(o),entries:n})},e.exclude=(e,o)=>{let n={...t.entries};for(let t of e)if(r.has(t))delete n[t];else throw Error(`Key ${t} not found in enum`);return new t3({...t,checks:[],...eb.normalizeParams(o),entries:n})}}),t9=em("ZodTransform",(e,t)=>{tD.init(e,t),t2.init(e,t),e._zod.parse=(r,o)=>{r.addIssue=o=>{"string"==typeof o?r.issues.push(eb.issue(o,r.value,t)):(o.fatal&&(
24o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!0),r.issues.push(eb.issue(o)))};let n=t.transform(r.value,r);return n instanceof Promise?n.then(e=>(r.value=e,r)):(r.value=n,r)}}),t7=em("ZodOptional",(e,t)=>{tZ.init(e,t),t2.init(e,t),e.unwrap=()=>e._zod.def.innerType});function re(e){return new t7({type:"optional",innerType:e})}var rt=em("ZodNullable",(e,t)=>{tj.init(e,t),t2.init(e,t),e.unwrap=()=>e._zod.def.innerType});function rr(e){return new rt({type:"nullable",innerType:e})}var ro=em("ZodDefault",(e,t)=>{tL.init(e,t),t2.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),rn=em("ZodPrefault",(e,t)=>{tN.init(e,t),t2.init(e,t),e.unwrap=()=>e._zod.def.innerType}),ri=em("ZodNonOptional",(e,t)=>{t$.init(e,t),t2.init(e,t),e.unwrap=()=>e._zod.def.innerType}),rs=em("ZodCatch",(e,t)=>{tH.init(e,t),t2.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),ra=em("ZodPipe",(e,t)=>{tV.init(e,t),t2.init(e,t),e.in=t.in,e.out=t.out});function rc(e,t){return new ra({type:"pipe",in:e,out:t})}var rd=em("ZodReadonly",(e,t)=>{tB.init(e,t),t2.init(e,t)}),rl=em("ZodCustom",(e,t)=>{tM.init(e,t),t2.init(e,t)}),ru=e.i(448969);e.s(["default",0,ru],331243),e.s(["default",0,ru],453267),e.i(453267),e.i(331243),e.s(["$brand",()=>ru.$brand,"$input",()=>ru.$input,"$output",()=>ru.$output,"NEVER",()=>ru.NEVER,"TimePrecision",()=>ru.TimePrecision,"ZodAny",()=>ru.ZodAny,"ZodArray",()=>ru.ZodArray,"ZodBase64",()=>ru.ZodBase64,"ZodBase64URL",()=>ru.ZodBase64URL,"ZodBigInt",()=>ru.ZodBigInt,"ZodBigIntFormat",()=>ru.ZodBigIntFormat,"ZodBoolean",()=>ru.ZodBoolean,"ZodCIDRv4",()=>ru.ZodCIDRv4,"ZodCIDRv6",()=>ru.ZodCIDRv6,"ZodCUID",()=>ru.ZodCUID,"ZodCUID2",()=>ru.ZodCUID2,"ZodCatch",()=>ru.ZodCatch,"ZodCodec",()=>ru.ZodCodec,"ZodCustom",()=>ru.ZodCustom,"ZodCustomStringFormat",()=>ru.ZodCustomStringFormat,"ZodDate",()=>ru.ZodDate,"ZodDefault",()=>ru.ZodDefault,"ZodDiscriminatedUnion",()=>ru.ZodDiscriminatedUnion,"ZodE164",()=>ru.ZodE164,"ZodEmail",()=>ru.ZodEmail,"ZodEmoji",()=>ru.ZodEmoji,"ZodEnum",()=>ru.ZodEnum,"ZodError",()=>ru.ZodError,"ZodFile",()=>ru.ZodFile,"ZodFirstPartyTypeKind",()=>ru.ZodFirstPartyTypeKind,"ZodFunction",()=>
24ru.ZodFunction,"ZodGUID",()=>ru.ZodGUID,"ZodIPv4",()=>ru.ZodIPv4,"ZodIPv6",()=>ru.ZodIPv6,"ZodISODate",()=>ru.ZodISODate,"ZodISODateTime",()=>ru.ZodISODateTime,"ZodISODuration",()=>ru.ZodISODuration,"ZodISOTime",()=>ru.ZodISOTime,"ZodIntersection",()=>ru.ZodIntersection,"ZodIssueCode",()=>ru.ZodIssueCode,"ZodJWT",()=>ru.ZodJWT,"ZodKSUID",()=>ru.ZodKSUID,"ZodLazy",()=>ru.ZodLazy,"ZodLiteral",()=>ru.ZodLiteral,"ZodMap",()=>ru.ZodMap,"ZodNaN",()=>ru.ZodNaN,"ZodNanoID",()=>ru.ZodNanoID,"ZodNever",()=>ru.ZodNever,"ZodNonOptional",()=>ru.ZodNonOptional,"ZodNull",()=>ru.ZodNull,"ZodNullable",()=>ru.ZodNullable,"ZodNumber",()=>ru.ZodNumber,"ZodNumberFormat",()=>ru.ZodNumberFormat,"ZodObject",()=>ru.ZodObject,"ZodOptional",()=>ru.ZodOptional,"ZodPipe",()=>ru.ZodPipe,"ZodPrefault",()=>ru.ZodPrefault,"ZodPromise",()=>ru.ZodPromise,"ZodReadonly",()=>ru.ZodReadonly,"ZodRealError",()=>ru.ZodRealError,"ZodRecord",()=>ru.ZodRecord,"ZodSet",()=>ru.ZodSet,"ZodString",()=>ru.ZodString,"ZodStringFormat",()=>ru.ZodStringFormat,"ZodSuccess",()=>ru.ZodSuccess,"ZodSymbol",()=>ru.ZodSymbol,"ZodTemplateLiteral",()=>ru.ZodTemplateLiteral,"ZodTransform",()=>ru.ZodTransform,"ZodTuple",()=>ru.ZodTuple,"ZodType",()=>ru.ZodType,"ZodULID",()=>ru.ZodULID,"ZodURL",()=>ru.ZodURL,"ZodUUID",()=>ru.ZodUUID,"ZodUndefined",()=>ru.ZodUndefined,"ZodUnion",()=>ru.ZodUnion,"ZodUnknown",()=>ru.ZodUnknown,"ZodVoid",()=>ru.ZodVoid,"ZodXID",()=>ru.ZodXID,"_ZodString",()=>ru._ZodString,"_default",()=>ru._default,"_function",()=>ru._function,"any",()=>ru.any,"array",()=>ru.array,"base64",()=>ru.base64,"base64url",()=>ru.base64url,"bigint",()=>ru.bigint,"boolean",()=>ru.boolean,"catch",()=>ru.catch,"check",()=>ru.check,"cidrv4",()=>ru.cidrv4,"cidrv6",()=>ru.cidrv6,"clone",()=>ru.clone,"codec",()=>ru.codec,"coerce",()=>ru.coerce,"config",()=>ru.config,"core",()=>ru.core,"cuid",()=>ru.cuid,"cuid2",()=>ru.cuid2,"custom",()=>ru.custom,"date",()=>ru.date,"decode",()=>ru.decode,"decodeAsync",()=>ru.decodeAsync,"default",0,ru,"discriminatedUnion",()=>ru.discriminatedUnion,"e164",()=>ru.e164,"email",()=>ru.email,"emoji",()=>ru.emoji,"encode",()=>ru.encode,"encodeAsync",()=>ru.encodeAsync,"endsWith",()=>ru.endsWith,"enum",()=>ru.enum,"file",()=>ru.file,"flattenError",()=>ru.flattenError,"float32",()=>ru.float32,"float64",()=>ru.float64,"formatError",()=>ru.formatError,"function",()=>ru.function,"getErrorMap",()=>ru.getErrorMap,"globalRegistry",()=>ru.globalRegistry,"gt",()=>ru.gt,"gte",()=>ru.gte,"guid",()=>ru.guid,"hash",()=>ru.hash,"hex",()=>ru.hex,"hostname",()=>ru.hostname,"httpUrl",()=>ru.httpUrl,"includes",()=>ru.includes,"instanceof",()=>ru.instanceof,"int",()=>ru.int,"int32",()=>ru.int32,"int64",()=>ru.int64,"intersection",()=>ru.intersection,"ipv4",()=>ru.ipv4,"ipv6",()=>ru.ipv6,"iso",()=>ru.iso,"json",()=>ru.json,"jwt",()=>ru.jwt,"keyof",()=>ru.keyof,"ksuid",()=>ru.ksuid,"lazy",()=>ru.lazy,"length",()=>ru.length,"literal",()=>ru.literal,"locales",()=>ru.locales,"looseObject",()=>ru.looseObject,"lowercase",()=>ru.lowercase,"lt",()=>ru.lt,"lte",()=>ru.lte,"map",()=>ru.map,"maxLength",()=>ru.maxLength,"maxSize",()=>ru.maxSize,"mime",()=>ru.mime,"minLength",()=>ru.minLength,"minSize",()=>ru.minSize,"multipleOf",()=>ru.multipleOf,"nan",()=>ru.nan,"nanoid",()=>ru.nanoid,"nativeEnum",()=>ru.nativeEnum,"negative",()=>ru.negative,"never",()=>ru.never,"nonnegative",()=>ru.nonnegative,"nonoptional",()=>ru.nonoptional,"nonpositive",()=>ru.nonpositive,"normalize",()=>ru.normalize,"null",()=>ru.null,"nullable",()=>ru.nullable,"nullish",()=>ru.nullish,"number",()=>ru.number,"object",()=>ru.object,"optional",()=>ru.optional,"overwrite",()=>ru.overwrite,"parse",()=>ru.parse,"parseAsync",()=>ru.parseAsync,"partialRecord",()=>ru.partialRecord,"pipe",()=>ru.pipe,"positive",()=>ru.positive,"prefault",()=>ru.prefault,"preprocess",()=>ru.preprocess,"prettifyError",()=>ru.prettifyError,"promise",()=>ru.promise,"property",()=>ru.property,"readonly",()=>ru.readonly,"record",()=>ru.record,"refine",()=>ru.refine,"regex",()=>ru.regex,"regexes",()=>ru.regexes,"registry",()=>ru.registry,"safeDecode",()=>ru.safeDecode,"safeDecodeAsync",()=>ru.safeDecodeAsync,"safeEncode",()=>ru.safeEncode,"safeEncodeAsync",()=>ru.safeEncodeAsync,"safeParse",()=>ru.safeParse,"safeParseAsync",()=>ru.safeParseAsync,"set",()=>ru.set,"setErrorMap",()=>ru.setErrorMap,"size",()=>ru.size,"startsWith",()=>ru.startsWith,"strictObject",()=>ru.strictObject,"string",()=>
24ru.string,"stringFormat",()=>ru.stringFormat,"stringbool",()=>ru.stringbool,"success",()=>ru.success,"superRefine",()=>ru.superRefine,"symbol",()=>ru.symbol,"templateLiteral",()=>ru.templateLiteral,"toJSONSchema",()=>ru.toJSONSchema,"toLowerCase",()=>ru.toLowerCase,"toUpperCase",()=>ru.toUpperCase,"transform",()=>ru.transform,"treeifyError",()=>ru.treeifyError,"trim",()=>ru.trim,"tuple",()=>ru.tuple,"uint32",()=>ru.uint32,"uint64",()=>ru.uint64,"ulid",()=>ru.ulid,"undefined",()=>ru.undefined,"union",()=>ru.union,"unknown",()=>ru.unknown,"uppercase",()=>ru.uppercase,"url",()=>ru.url,"util",()=>ru.util,"uuid",()=>ru.uuid,"uuidv4",()=>ru.uuidv4,"uuidv6",()=>ru.uuidv6,"uuidv7",()=>ru.uuidv7,"void",()=>ru.void,"xid",()=>ru.xid,"z",0,ru],260465),e.i(260465),e.s(["$brand",()=>ru.$brand,"$input",()=>ru.$input,"$output",()=>ru.$output,"NEVER",()=>ru.NEVER,"TimePrecision",()=>ru.TimePrecision,"ZodAny",()=>ru.ZodAny,"ZodArray",()=>ru.ZodArray,"ZodBase64",()=>ru.ZodBase64,"ZodBase64URL",()=>ru.ZodBase64URL,"ZodBigInt",()=>ru.ZodBigInt,"ZodBigIntFormat",()=>ru.ZodBigIntFormat,"ZodBoolean",()=>ru.ZodBoolean,"ZodCIDRv4",()=>ru.ZodCIDRv4,"ZodCIDRv6",()=>ru.ZodCIDRv6,"ZodCUID",()=>ru.ZodCUID,"ZodCUID2",()=>ru.ZodCUID2,"ZodCatch",()=>ru.ZodCatch,"ZodCodec",()=>ru.ZodCodec,"ZodCustom",()=>ru.ZodCustom,"ZodCustomStringFormat",()=>ru.ZodCustomStringFormat,"ZodDate",()=>ru.ZodDate,"ZodDefault",()=>ru.ZodDefault,"ZodDiscriminatedUnion",()=>ru.ZodDiscriminatedUnion,"ZodE164",()=>ru.ZodE164,"ZodEmail",()=>ru.ZodEmail,"ZodEmoji",()=>ru.ZodEmoji,"ZodEnum",()=>ru.ZodEnum,"ZodError",()=>ru.ZodError,"ZodFile",()=>ru.ZodFile,"ZodFirstPartyTypeKind",()=>ru.ZodFirstPartyTypeKind,"ZodFunction",()=>
24ru.ZodFunction,"ZodGUID",()=>ru.ZodGUID,"ZodIPv4",()=>ru.ZodIPv4,"ZodIPv6",()=>ru.ZodIPv6,"ZodISODate",()=>ru.ZodISODate,"ZodISODateTime",()=>ru.ZodISODateTime,"ZodISODuration",()=>ru.ZodISODuration,"ZodISOTime",()=>ru.ZodISOTime,"ZodIntersection",()=>ru.ZodIntersection,"ZodIssueCode",()=>ru.ZodIssueCode,"ZodJWT",()=>ru.ZodJWT,"ZodKSUID",()=>ru.ZodKSUID,"ZodLazy",()=>ru.ZodLazy,"ZodLiteral",()=>ru.ZodLiteral,"ZodMap",()=>ru.ZodMap,"ZodNaN",()=>ru.ZodNaN,"ZodNanoID",()=>ru.ZodNanoID,"ZodNever",()=>ru.ZodNever,"ZodNonOptional",()=>ru.ZodNonOptional,"ZodNull",()=>ru.ZodNull,"ZodNullable",()=>ru.ZodNullable,"ZodNumber",()=>ru.ZodNumber,"ZodNumberFormat",()=>ru.ZodNumberFormat,"ZodObject",()=>ru.ZodObject,"ZodOptional",()=>ru.ZodOptional,"ZodPipe",()=>ru.ZodPipe,"ZodPrefault",()=>ru.ZodPrefault,"ZodPromise",()=>ru.ZodPromise,"ZodReadonly",()=>ru.ZodReadonly,"ZodRealError",()=>ru.ZodRealError,"ZodRecord",()=>ru.ZodRecord,"ZodSet",()=>ru.ZodSet,"ZodString",()=>ru.ZodString,"ZodStringFormat",()=>ru.ZodStringFormat,"ZodSuccess",()=>ru.ZodSuccess,"ZodSymbol",()=>ru.ZodSymbol,"ZodTemplateLiteral",()=>ru.ZodTemplateLiteral,"ZodTransform",()=>ru.ZodTransform,"ZodTuple",()=>ru.ZodTuple,"ZodType",()=>ru.ZodType,"ZodULID",()=>ru.ZodULID,"ZodURL",()=>ru.ZodURL,"ZodUUID",()=>ru.ZodUUID,"ZodUndefined",()=>ru.ZodUndefined,"ZodUnion",()=>ru.ZodUnion,"ZodUnknown",()=>ru.ZodUnknown,"ZodVoid",()=>ru.ZodVoid,"ZodXID",()=>ru.ZodXID,"_ZodString",()=>ru._ZodString,"_default",()=>ru._default,"_function",()=>ru._function,"any",()=>ru.any,"array",()=>ru.array,"base64",()=>ru.base64,"base64url",()=>ru.base64url,"bigint",()=>ru.bigint,"boolean",()=>ru.boolean,"catch",()=>ru.catch,"check",()=>ru.check,"cidrv4",()=>ru.cidrv4,"cidrv6",()=>ru.cidrv6,"clone",()=>ru.clone,"codec",()=>ru.codec,"coerce",()=>ru.coerce,"config",()=>ru.config,"core",()=>ru.core,"cuid",()=>ru.cuid,"cuid2",()=>ru.cuid2,"custom",()=>ru.custom,"date",()=>ru.date,"decode",()=>ru.decode,"decodeAsync",()=>ru.decodeAsync,"default",0,ru,"discriminatedUnion",()=>ru.discriminatedUnion,"e164",()=>ru.e164,"email",()=>ru.email,"emoji",()=>ru.emoji,"encode",()=>ru.encode,"encodeAsync",()=>ru.encodeAsync,"endsWith",()=>ru.endsWith,"enum",()=>ru.enum,"file",()=>ru.file,"flattenError",()=>ru.flattenError,"float32",()=>ru.float32,"float64",()=>ru.float64,"formatError",()=>ru.formatError,"function",()=>ru.function,"getErrorMap",()=>ru.getErrorMap,"globalRegistry",()=>ru.globalRegistry,"gt",()=>ru.gt,"gte",()=>ru.gte,"guid",()=>ru.guid,"hash",()=>ru.hash,"hex",()=>ru.hex,"hostname",()=>ru.hostname,"httpUrl",()=>ru.httpUrl,"includes",()=>ru.includes,"instanceof",()=>ru.instanceof,"int",()=>ru.int,"int32",()=>ru.int32,"int64",()=>ru.int64,"intersection",()=>ru.intersection,"ipv4",()=>ru.ipv4,"ipv6",()=>ru.ipv6,"iso",()=>ru.iso,"json",()=>ru.json,"jwt",()=>ru.jwt,"keyof",()=>ru.keyof,"ksuid",()=>ru.ksuid,"lazy",()=>ru.lazy,"length",()=>ru.length,"literal",()=>ru.literal,"locales",()=>ru.locales,"looseObject",()=>ru.looseObject,"lowercase",()=>ru.lowercase,"lt",()=>ru.lt,"lte",()=>ru.lte,"map",()=>ru.map,"maxLength",()=>ru.maxLength,"maxSize",()=>ru.maxSize,"mime",()=>ru.mime,"minLength",()=>ru.minLength,"minSize",()=>ru.minSize,"multipleOf",()=>ru.multipleOf,"nan",()=>ru.nan,"nanoid",()=>ru.nanoid,"nativeEnum",()=>ru.nativeEnum,"negative",()=>ru.negative,"never",()=>ru.never,"nonnegative",()=>ru.nonnegative,"nonoptional",()=>ru.nonoptional,"nonpositive",()=>ru.nonpositive,"normalize",()=>ru.normalize,"null",()=>ru.null,"nullable",()=>ru.nullable,"nullish",()=>ru.nullish,"number",()=>ru.number,"object",()=>ru.object,"optional",()=>ru.optional,"overwrite",()=>ru.overwrite,"parse",()=>ru.parse,"parseAsync",()=>ru.parseAsync,"partialRecord",()=>ru.partialRecord,"pipe",()=>ru.pipe,"positive",()=>ru.positive,"prefault",()=>ru.prefault,"preprocess",()=>ru.preprocess,"prettifyError",()=>ru.prettifyError,"promise",()=>ru.promise,"property",()=>ru.property,"readonly",()=>ru.readonly,"record",()=>ru.record,"refine",()=>ru.refine,"regex",()=>ru.regex,"regexes",()=>ru.regexes,"registry",()=>ru.registry,"safeDecode",()=>ru.safeDecode,"safeDecodeAsync",()=>ru.safeDecodeAsync,"safeEncode",()=>ru.safeEncode,"safeEncodeAsync",()=>ru.safeEncodeAsync,"safeParse",()=>ru.safeParse,"safeParseAsync",()=>ru.safeParseAsync,"set",()=>ru.set,"setErrorMap",()=>ru.setErrorMap,"size",()=>ru.size,"startsWith",()=>ru.startsWith,"strictObject",()=>ru.strictObject,"string",()=>
24ru.string,"stringFormat",()=>ru.stringFormat,"stringbool",()=>ru.stringbool,"success",()=>ru.success,"superRefine",()=>ru.superRefine,"symbol",()=>ru.symbol,"templateLiteral",()=>ru.templateLiteral,"toJSONSchema",()=>ru.toJSONSchema,"toLowerCase",()=>ru.toLowerCase,"toUpperCase",()=>ru.toUpperCase,"transform",()=>ru.transform,"treeifyError",()=>ru.treeifyError,"trim",()=>ru.trim,"tuple",()=>ru.tuple,"uint32",()=>ru.uint32,"uint64",()=>ru.uint64,"ulid",()=>ru.ulid,"undefined",()=>ru.undefined,"union",()=>ru.union,"unknown",()=>ru.unknown,"uppercase",()=>ru.uppercase,"url",()=>ru.url,"util",()=>ru.util,"uuid",()=>ru.uuid,"uuidv4",()=>ru.uuidv4,"uuidv6",()=>ru.uuidv6,"uuidv7",()=>ru.uuidv7,"void",()=>ru.void,"xid",()=>ru.xid,"z",()=>ru],926919),e.i(926919);var rp=e.i(580588),rp=rp;let rf=(e,t="ms")=>new Date(Date.now()+("sec"===t?1e3*e:e));function rh(e){return e?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function rm(e,t,r){let o="",n=0,i=0;for(let r of e)for(n=n<<8|r,i+=8;i>=6;)i-=6,o+=t[n>>i&63];if(i>0&&(o+=t[n<<6-i&63]),r){let e=(4-o.length%4)%4;o+="=".repeat(e)}return o}function ry(e,t){let r=new Map;for(let e=0;e<t.length;e++)r.set(t[e],e);let o=[],n=0,i=0;for(let t of e){if("="===t)break;let e=r.get(t);if(void 0===e)throw Error(`Invalid Base64 character: ${t}`);n=n<<6|e,(i+=6)>=8&&(i-=8,o.push(n>>i&255))}return Uint8Array.from(o)}let rg={encode(e,t={}){let r=rh(!1);return rm("string"==typeof e?new TextEncoder().encode(e):new Uint8Array(e),r,t.padding??!0)},decode(e){"string"!=typeof e&&(e=new TextDecoder().decode(e));let t=rh(e.includes("-")||e.includes("_"));return ry(e,t)}},rw={encode(e,t={}){let r=rh(!0);return rm("string"==typeof e?new TextEncoder().encode(e):new Uint8Array(e),r,t.padding??!0)},decode(e){let t=rh(e.includes("-")||e.includes("_"));return ry(e,t)}},rb=(e="SHA-256",t="none")=>{let r={importKey:async(t,r)=>G.importKey("raw","string"==typeof t?new TextEncoder().encode(t):t,{name:"HMAC",hash:{name:e}},!1,[r]),sign:async(e,o)=>{"string"==typeof e&&(e=await r.importKey(e,"sign"));let n=await G.sign("HMAC",e,"string"==typeof o?new TextEncoder().encode(o):o);return"hex"===t?(e=>{if("string"==typeof e&&(e=new TextEncoder().encode(e)),0===e.byteLength)return"";let t=new Uint8Array(e),r="";for(let e of t)r+=e.toString(16).padStart(2,"0");return r})(n):"base64"===t||"base64url"===t||"base64urlnopad"===t?rw.encode(n,{padding:"base64urlnopad"!==t}):n},verify:async(e,o,n)=>("string"==typeof e&&(e=await r.importKey(e,"verify")),"hex"===t&&(n=(e=>{if(!e)return"";if("string"==typeof e){if(e.length%2!=0||!RegExp("^[0123456789abcdef]+$").test(e))throw Error("Invalid hexadecimal string");let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.slice(r,r+2),16);return new TextDecoder().decode(t)}return new TextDecoder().decode(e)})(n)),("base64"===t||"base64url"===t||"base64urlnopad"===t)&&(n=await rg.decode(n)),G.verify("HMAC",e,"string"==typeof n?new TextEncoder().encode(n):n,"string"==typeof o?new TextEncoder().encode(o):o))};return r},rv=["info","success","warn","error","debug"],rE="\x1b[0m",rA="\x1b[31m",rx="\x1b[32m",rT="\x1b[33m",rk="\x1b[34m",rS="\x1b[35m",rR={info:rk,success:rx,warn:rT,error:rA,debug:rS},r_=(o=a?.disabled!==!0,n=a?.level??"error",{...Object.fromEntries(rv.map(e=>[e,(...[t,...r])=>((e,t,r=[])=>{let i;if(!o||!(rv.indexOf(e)<=rv.indexOf(n)))return;let s=(i=new Date().toISOString(),`\x1b[2m${i}${rE} ${rR[e]}${e.toUpperCase()}${rE} \x1b[1m[Better Auth]:${rE} ${t}`);a&&"function"==typeof a.log?a.log("success"===e?"info":e,t,...r):"error"===e?console.error(s,...r):"warn"===e?console.warn(s,...r):console.log(s,...r)})(e,t,r)])),get level(){return n}});function rU(e){try{if("string"!=typeof e)return e;return JSON.parse(e,function(e,t){if("string"==typeof t&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(t)){let e=new Date(t);if(!isNaN(e.getTime()))return e}return t})}catch(e){return r_.error("Error parsing JSON",{error:e}),null}}function rI(e,t="/api/auth"){return!function(e){try{let t=new URL(e);return"/"!==t.pathname}catch(t){throw new K(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}(e)?(t=t.startsWith("/")?t:`/${t}`,`${e.replace(/\/+$/,"")}${t}`):e}function rO(e){try{return new URL(e).origin}catch(e){return null}}function rP(e){try{return new URL(e).protocol}catch(e){return null}}function rD(e){try{return new URL(e).host}catch(t){return e}}let rZ=new Map,rj={decode:(e,t="utf-8")=>(rZ.has(t)||rZ.set(t,new TextDecoder(t)),rZ.get(t).decode(e)),encode:new TextEncoder().encode};async function rL(e,t){if(e.context.options.session?.cookieCache?.enabled){let r={session:Object.entries(t.session).reduce((t,[r,o])=>{let n=e.context.options.session?.additionalFields?.[r];return n&&!1===n.returned||(t[r]=o),t},{}),user:t.user},o=rf(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),n=rw.encode(JSON.stringify({session:r,expiresAt:o,signature:await rb("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify({...r,expiresAt:o}))}),{padding:!1});if(n.length>4093)throw new K("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,n,e.context.authCookies.sessionData.options)}}async function rC(e,t,r,o){let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);r=void 0!==r?r:!!n;let i=e.context.authCookies.sessionToken.options,s=r?void 0:e.context.sessionConfig.expires
24In;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:s,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),await rL(e,t),e.context.setNewSession(t),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function rN(e,t){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),t||e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var rp=rp;let r$=ef(async()=>({})),rz=ef.create({use:[r$,ef(async()=>({}))]}),rH=eh.create({use:[r$]}),rV="Failed to get session",rq="Invalid password",rB="Invalid email or password",rK="Provider not found",rM="Invalid token",rW="id_token not supported",rF="Failed to get user info",rJ="User email not found",rG="Email not verified",rQ="Password too short",rY="Password too long",rX="Credential account not found",r0=F.optional(F.object({disableCookieCache:rp.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:rp.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),r1=async(e,t)=>{if(e.context.session)return e.context.session;let r=await rH("/get-session",{method:"GET",query:r0,requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}},required:["session","user"]}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return null;let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?rU(rj.decode(rw.decode(r))):null;if(o&&!await rb("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify({...o.session,expiresAt:o.expiresAt}),o.signature)){let t=e.context.authCookies.sessionData.name;return e.setCookie(t,"",{maxAge:0}),e.json(null)}let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let t=o.session;if(!(o.expiresAt<Date.now()||t.session.expiresAt<new Date))return e.context.session=t,e.json(t);{let t=e.context.authCookies.sessionData.name;e.setCookie(t,"",{maxAge:0})}}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return rN(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-1e3*s+1e3*a<=Date.now()&&(!e.query?.disableRefresh||!e.context.options.session?.disableSessionRefresh)){let t=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:rf(e.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!t)return rN(e),e.json(null,{status:401});let r=(t.expiresAt.valueOf()-Date.now())/1e3;return await rC(e,{session:t,user:i.user},!1,{maxAge:r}),e.json({session:t,user:i.user})}return await rL(e,i),e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new ee("INTERNAL_SERVER_ERROR",{message:rV})}})({...e,asResponse:!1,headers:e.headers,returnHeaders:!1,query:{...t,...e.query}}).catch(e=>null);return e.context.session=r,r},r2=rz(async e=>{let t=await r1(e);if(!t?.session)throw new ee("UNAUTHORIZED");return{session:t}});rz(async e=>{let t=await r1(e);if(!t?.session&&(e.request||e.headers))throw new ee("UNAUTHORIZED");return{session:t}});let r6=rz(async e=>{let t=await r1(e);if(!t?.session)throw new ee("UNAUTHORIZED");if(0===e.context.sessionConfig.freshAge)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.updatedAt?.valueOf()||t.session.createdAt.valueOf();
24if(!(Date.now()-o<1e3*r))throw new ee("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});function r5(e,t){return{digest:async r=>{let o=new TextEncoder,n="string"==typeof r?o.encode(r):r,i=await G.digest(e,n);return"hex"===t?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join(""):"base64"===t||"base64url"===t||"base64urlnopad"===t?t.includes("url")?rw.encode(i,{padding:"base64urlnopad"!==t}):rg.encode(i):i}}}function r4(e){if("boolean"!=typeof e)throw Error(`boolean expected, not ${e}`)}function r8(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function r3(e,t,r=""){let o=e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name,n=e?.length,i=void 0!==t;if(!o||i&&n!==t)throw Error((r&&`"${r}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(o?`length=${n}`:`type=${typeof e}`));return e}function r9(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function r7(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function oe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}rH("/revoke-session",{method:"POST",body:F.object({token:F.string().meta({description:"The token to revoke"})}),use:[r2],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",description:"The token to revoke"}},required:["token"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the session was revoked successfully"}},required:["status"]}}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new ee("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new ee("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(t){throw e.context.logger.error(t&&"object"==typeof t&&"name"in t?t.name:"",t),new ee("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),rH("/revoke-sessions",{method:"POST",use:[r2],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all sessions were revoked successfully"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&"object"==typeof t&&"name"in t?t.name:"",t),new ee("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),rH("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[r2],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all other sessions were revoked successfully"}},required:["status"]}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new ee("UNAUTHORIZED");let r=(await e.context.internalAdapter.listSessions(t.user.id)).filter(e=>e.expiresAt>new Date).filter(t=>t.token!==e.context.session.session.token);return await Promise.all(r.map(t=>e.context.internalAdapter.deleteSession(t.token))),e.json({status:!0})});let ot=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0],or="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,oo=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function on(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function oi(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&t.byteOffset%4!=0)throw Error("invalid output, must be aligned");return t}function os(e){return Uint8Array.from(e)}function oa(e=32){let t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}function oc(e,t=oa){let{nonceLength:r}=e;r8(r);let o=(e,t)=>{let r=function(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];r3(o),t+=o.length}let r=new Uint8Array(t);for(let t=0,o=0;t<e.length;t++){let n=e[t];r.set(n,o),o+=n.length}return r}(e,t);return t.fill(0),r};return(n,...i)=>({encrypt(s){r3(s);
24let a=t(r),c=e(n,a,...i).encrypt(s);return c instanceof Promise?c.then(e=>o(a,e)):o(a,c)},decrypt(t){r3(t);let o=t.subarray(0,r),s=t.subarray(r);return e(n,o,...i).decrypt(s)}})}let od=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),ol=od("expand 16-byte k"),ou=od("expand 32-byte k"),op=r7(ol),of=r7(ou);function oh(e,t){return e<<t|e>>>32-t}function om(e){return e.byteOffset%4==0}let oy=0x100000000-1,og=Uint32Array.of();function ow(e,t){let{allowShortKeys:r,extendNonceFn:o,counterLength:n,counterRight:i,rounds:s}=function(e,t){if(null==t||"object"!=typeof t)throw Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw Error("core must be a function");return r8(n),r8(s),r4(i),r4(r),(t,a,c,d,l=0)=>{let u,p;r3(t,void 0,"key"),r3(a,void 0,"nonce"),r3(c,void 0,"data");let f=c.length;if(void 0===d&&(d=new Uint8Array(f)),r3(d,void 0,"output"),r8(l),l<0||l>=oy)throw Error("arx: counter overflow");if(d.length<f)throw Error(`arx: output (${d.length}) is shorter than data (${f})`);let h=[],m=t.length;if(32===m)h.push(u=os(t)),p=of;else if(16===m&&r)(u=new Uint8Array(32)).set(t),u.set(t,16),p=op,h.push(u);else throw r3(t,32,"arx key"),Error("invalid key size");om(a)||h.push(a=os(a));let y=r7(u);if(o){if(24!==a.length)throw Error("arx: extended nonce must be 24 bytes");o(p,y,r7(a.subarray(0,16)),y),a=a.subarray(16)}let g=16-n;if(g!==a.length)throw Error(`arx: nonce must be ${g} or 16 bytes`);if(12!==g){let e=new Uint8Array(12);e.set(a,i?0:12-a.length),a=e,h.push(a)}return!function(e,t,r,o,n,i,s,a){let c=n.length,d=new Uint8Array(64),l=r7(d),u=om(n)&&om(i),p=u?r7(n):og,f=u?r7(i):og;for(let h=0;h<c;s++){if(e(t,r,o,l,s,a),s>=oy)throw Error("arx: counter overflow");let m=Math.min(64,c-h);if(u&&64===m){let e=h/4;if(h%4!=0)throw Error("arx: invalid block position");for(let t=0,r;t<16;t++)f[r=e+t]=p[r]^l[t];h+=64;continue}for(let e=0,t;e<m;e++)i[t=h+e]=n[t]^d[e];h+=m}}(e,p,y,r7(a),c,d,l,s),oe(...h),d}}function ob(e,t){return 255&e[t++]|(255&e[t++])<<8}class ov{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(e){const t=ob(e=os(r3(e,32,"key")),0),r=ob(e,2),o=ob(e,4),n=ob(e,6),i=ob(e,8),s=ob(e,10),a=ob(e,12),c=ob(e,14);this.r[0]=8191&t,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|n<<9)&8191,this.r[4]=(n>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|s<<2)&8191,this.r[7]=(s>>>11|a<<5)&8065,this.r[8]=(a>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=ob(e,16+2*t)}process(e,t,r=!1){let{h:o,r:n}=this,i=n[0],s=n[1],a=n[2],c=n[3],d=n[4],l=n[5],u=n[6],p=n[7],f=n[8],h=n[9],m=ob(e,t+0),y=ob(e,t+2),g=ob(e,t+4),w=ob(e,t+6),b=ob(e,t+8),v=ob(e,t+10),E=ob(e,t+12),A=ob(e,t+14),x=o[0]+(8191&m),T=o[1]+((m>>>13|y<<3)&8191),k=o[2]+((y>>>10|g<<6)&8191),S=o[3]+((g>>>7|w<<9)&8191),R=o[4]+((w>>>4|b<<12)&8191),_=o[5]+(b>>>1&8191),U=o[6]+((b>>>14|v<<2)&8191),I=o[7]+((v>>>11|E<<5)&8191),O=o[8]+((E>>>8|A<<8)&8191),P=o[9]+(A>>>5|2048*!r),D=0,Z=0+x*i+5*h*T+5*f*k+5*p*S+5*u*R;D=Z>>>13,Z&=8191,Z+=5*l*_+5*d*U+5*c*I+5*a*O+5*s*P,D+=Z>>>13,Z&=8191;let j=D+x*s+T*i+5*h*k+5*f*S+5*p*R;D=j>>>13,j&=8191,j+=5*u*_+5*l*U+5*d*I+5*c*O+5*a*P,D+=j>>>13,j&=8191;let L=D+x*a+T*s+k*i+5*h*S+5*f*R;D=L>>>13,L&=8191,L+=5*p*_+5*u*U+5*l*I+5*d*O+5*c*P,D+=L>>>13,L&=8191;let C=D+x*c+T*a+k*s+S*i+5*h*R;D=C>>>13,C&=8191,C+=5*f*_+5*p*U+5*u*I+5*l*O+5*d*P,D+=C>>>13,C&=8191;let N=D+x*d+T*c+k*a+S*s+R*i;D=N>>>13,N&=8191,N+=5*h*_+5*f*U+5*p*I+5*u*O+5*l*P,D+=N>>>13,N&=8191;let $=D+x*l+T*d+k*c+S*a+R*s;D=$>>>13,$&=8191,$+=_*i+5*h*U+5*f*I+5*p*O+5*u*P,D+=$>>>13,$&=8191;let z=D+x*u+T*l+k*d+S*c+R*a;D=z>>>13,z&=8191,z+=_*s+U*i+5*h*I+5*f*O+5*p*P,D+=z>>>13,z&=8191;let H=D+x*p+T*u+k*l+S*d+R*c;D=H>>>13,H&=8191,H+=_*a+U*s+I*i+5*h*O+5*f*P,D+=H>>>13,H&=8191;let V=D+x*f+T*p+k*u+S*l+R*d;D=V>>>13,V&=8191,V+=_*c+U*a+I*s+O*i+5*h*P,D+=V>>>13,V&=8191;let q=D+x*h+T*f+k*p+S*u+R*l;D=q>>>13,q&=8191,q+=_*d+U*c+I*a+O*s+P*i,D+=q>>>13,q&=8191,Z=8191&(D=(D=(D<<2)+D|0)+Z|0),D>>>=13,j+=D,o[0]=Z,o[1]=j,o[2]=L,o[3]=C,o[4]=N,o[5]=$,o[6]=z,o[7]=H,o[8]=V,o[9]=q}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=o,o=e[t]>>>13,e[t]&=8191;e[0]+=5*o,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+o,o=r[t]>>>13,r[t]&=8191;r[9]-=8192;let n=(1^o)-1;for(let e=0;e<10;e++)r[e]&=n;n=~n;for(let t=0;t<10;t++)e[t]=e[t]&n|r[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=65535&i;for(let r=1;r<8;r++)i=(e[r]+t[r]|0)+(i>>>16)|0,e[r]=65535&i;oe(r)}update(e){r9(this),r3(e);let{buffer:t,blockLen:r}=this,o=(e=os(e)).length;for(let n=0;n<o;){let i=Math.min(r-this.pos,o-n);if(i===r){for(;r<=o-n;n+=r)this.process(e,n);continue}t.set(e.subarray(n,n+i),this.pos),this.pos+=i,n+=i,this.pos===r&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){oe(this.h,this.r,this.buffer,this.pad)}digestInto(e){r9(this);r3(e,void 0,"output");let t=this.outputLen;if(e.length<t)throw Error("digestInto() expects output buffer of length at least "+t);this.finished=!0;let{buffer:r,h:o}=this,{pos:n}=this;if(n){for(r[n++]=1;n<16;n++)r[n]=0;this.process(r,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=o[t]>>>0,e[i++]=o[t]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}let oE=(c=e=>new ov(e),(i=(e,t)=>c(t).update(e).digest()).outputLen=(s=c(new Uint8Array(32))).outputLen,i.blockLen=s.blockLen,i.create=e=>c(e),i);function oA(e,t,r,o,n,i=20){let s=e[0],a=e[1],c=e[2],d=e[3],l=t[0],u=t[1],p=t[2],f=t[3],h=t[4],m=t[5],y=t[6],g=t[7],w=r[0],b=r[1],v=r[2],E=s,A=a,x=c,T=d,k=l,S=u,R=p,_=f,U=h,I=m,O=y,P=g,D=n,Z=w,j=b,L=v;for(let e=0;e<i;e+=2)U=U+(D=oh(D^(E=E+k|0),16))|0,E=E+(k=oh(k^U,12))|0,U=U+(D=oh(D^E,8))|0,k=oh(k^U,7),I=I+(Z=oh(Z^(A=A+S|0),16))|0,A=A+(S=oh(S^I,12))|0,I=I+(Z=oh(Z^A,8))|0,S=oh(S^I,7),O=O+(j=oh(j^(x=x+R|0),16))|0,x=x+(R=oh(R^O,12))|0,O=O+(j=oh(j^x,8))|0,R=oh(R^O,7),P=P+(L=oh(L^(T=T+_|0),16))|0,T=T+(_=oh(_^P,12))|0,P=P+(L=oh(L^T,8))|0,_=oh(_^P,7),O=O+(L=oh(L^(E=E+S|0),16))|0,E=E+(S=oh(S^O,12))|0,O=O+(L=oh(L^E,8))|0,S=oh(S^O,7),P=P+(D=oh(D^(A=A+R|0),16))|0,A=A+(R=oh(R^P,12))|0,P=P+(D=oh(D^A,8))|0,R=oh(R^P,7),U=U+(Z=oh(Z^(x=x+_|0),16))|0,x=x+(_=oh(_^U,12))|0,U=U+(Z=oh(Z^x,8))|0,_=oh(_^U,7),I=I+(j=oh(j^(T=T+k|0),16))|0,T=T+(k=oh(k^I,12))|0,I=I+(j=oh(j^T,8))|0,k=oh(k^I,7);let C=0;
24o[C++]=s+E|0,o[C++]=a+A|0,o[C++]=c+x|0,o[C++]=d+T|0,o[C++]=l+k|0,o[C++]=u+S|0,o[C++]=p+R|0,o[C++]=f+_|0,o[C++]=h+U|0,o[C++]=m+I|0,o[C++]=y+O|0,o[C++]=g+P|0,o[C++]=n+D|0,o[C++]=w+Z|0,o[C++]=b+j|0,o[C++]=v+L|0}let ox=ow(oA,{counterRight:!1,counterLength:4,allowShortKeys:!1}),oT=ow(oA,{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,r,o){let n=e[0],i=e[1],s=e[2],a=e[3],c=t[0],d=t[1],l=t[2],u=t[3],p=t[4],f=t[5],h=t[6],m=t[7],y=r[0],g=r[1],w=r[2],b=r[3];for(let e=0;e<20;e+=2)p=p+(y=oh(y^(n=n+c|0),16))|0,n=n+(c=oh(c^p,12))|0,p=p+(y=oh(y^n,8))|0,c=oh(c^p,7),f=f+(g=oh(g^(i=i+d|0),16))|0,i=i+(d=oh(d^f,12))|0,f=f+(g=oh(g^i,8))|0,d=oh(d^f,7),h=h+(w=oh(w^(s=s+l|0),16))|0,s=s+(l=oh(l^h,12))|0,h=h+(w=oh(w^s,8))|0,l=oh(l^h,7),m=m+(b=oh(b^(a=a+u|0),16))|0,a=a+(u=oh(u^m,12))|0,m=m+(b=oh(b^a,8))|0,u=oh(u^m,7),h=h+(b=oh(b^(n=n+d|0),16))|0,n=n+(d=oh(d^h,12))|0,h=h+(b=oh(b^n,8))|0,d=oh(d^h,7),m=m+(y=oh(y^(i=i+l|0),16))|0,i=i+(l=oh(l^m,12))|0,m=m+(y=oh(y^i,8))|0,l=oh(l^m,7),p=p+(g=oh(g^(s=s+u|0),16))|0,s=s+(u=oh(u^p,12))|0,p=p+(g=oh(g^s,8))|0,u=oh(u^p,7),f=f+(w=oh(w^(a=a+c|0),16))|0,a=a+(c=oh(c^f,12))|0,f=f+(w=oh(w^a,8))|0,c=oh(c^f,7);let v=0;o[v++]=n,o[v++]=i,o[v++]=s,o[v++]=a,o[v++]=y,o[v++]=g,o[v++]=w,o[v++]=b},allowShortKeys:!1}),ok=new Uint8Array(16),oS=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(ok.subarray(r))},oR=new Uint8Array(32);function o_(e,t,r,o,n){var i,s;let a,c;void 0!==n&&r3(n,void 0,"AAD");let d=e(t,r,oR),l=(i=o.length,s=n?n.length:0,r4(!0),(c=new DataView((a=new Uint8Array(16)).buffer,a.byteOffset,a.byteLength)).setBigUint64(0,BigInt(s),!0),c.setBigUint64(8,BigInt(i),!0),a),u=oE.create(d);n&&oS(u,n),oS(u,o),u.update(l);let p=u.digest();return oe(d,l),p}let oU=e=>(t,r,o)=>({encrypt(n,i){let s=n.length;(i=oi(s+16,i,!1)).set(n);let a=i.subarray(0,-16);e(t,r,a,a,1);let c=o_(e,t,r,a,o);return i.set(c,s),oe(c),i},decrypt(n,i){i=oi(n.length-16,i,!1);let s=n.subarray(0,-16),a=n.subarray(-16),c=o_(e,t,r,s,o);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return 0===r}(a,c))throw Error("invalid tag");return i.set(n.subarray(0,-16)),e(t,r,i,i,1),oe(c),i}});oU(ox);let oI=((e,t)=>{function r(o,...n){if(r3(o,void 0,"key"),!ot)throw Error("Non little-endian hardware is not yet supported");void 0!==e.nonceLength&&r3(n[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");let i=e.tagLength;i&&void 0!==n[1]&&r3(n[1],void 0,"AAD");let s=t(o,...n),a=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");r3(t,void 0,"output")}},c=!1;return{encrypt(e,t){if(c)throw Error("cannot encrypt() twice with same key + nonce");return c=!0,r3(e),a(s.encrypt.length,t),s.encrypt(e,t)},decrypt(e,t){if(r3(e),i&&e.length<i)throw Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,t),s.decrypt(e,t)}}}return Object.assign(r,e),r})({blockSize:64,nonceLength:24,tagLength:16},oU(oT)),oO=new TextEncoder,oP=new TextDecoder;function oD(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let o of e)t.set(o,r),r+=o.length;return t}function oZ(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:oP.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=oP.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{var r=t;if(Uint8Array.fromBase64)return Uint8Array.fromBase64(r);let e=atob(r),o=new Uint8Array(e.length);for(let t=0;t<e.length;t++)o[t]=e.charCodeAt(t);return o}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}function oj(e){let t=e;return("string"==typeof t&&(t=oO.encode(t)),Uint8Array.prototype.toBase64)?t.toBase64({alphabet:"base64url",omitPadding:!0}):(function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=[];for(let r=0;r<e.length;r+=32768)t.push(String.fromCharCode.apply(null,e.subarray(r,r+32768)));return btoa(t.join(""))})(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class oL extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class oC extends oL{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",o="unspecified"){super(e,{cause:{claim:r,reason:o,payload:t}}
24),this.claim=r,this.reason=o,this.payload=t}}class oN extends oL{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",o="unspecified"){super(e,{cause:{claim:r,reason:o,payload:t}}),this.claim=r,this.reason=o,this.payload=t}}class o$ extends oL{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class oz extends oL{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class oH extends oL{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class oV extends oL{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class oq extends oL{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class oB extends oL{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t)}}class oK extends oL{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}class oM extends oL{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}let oW=(e,t)=>{let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};
24case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new oz(`alg ${e} is not supported either by JOSE or your javascript runtime`)}},oF=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function oJ(e,t="algorithm.name"){return TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function oG(e,t){return e.name===t}function oQ(e){return parseInt(e.name.slice(4),10)}function oY(e,t,...r){if((r=r.filter(Boolean)).length>2){let t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function oX(e,t,...r){return oY(`Key for the ${e} algorithm must be `,t,...r)}let o0=async(e,t,r)=>{if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(((e,...t)=>oY("Key must be ",e,...t))(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return!function(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!oG(e.algorithm,"HMAC"))throw oJ("HMAC");let r=parseInt(t.slice(2),10);if(oQ(e.algorithm.hash)!==r)throw oJ(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!oG(e.algorithm,"RSASSA-PKCS1-v1_5"))throw oJ("RSASSA-PKCS1-v1_5");let r=parseInt(t.slice(2),10);if(oQ(e.algorithm.hash)!==r)throw oJ(`SHA-${r}`,"algorithm.hash");break}
24case"PS256":case"PS384":case"PS512":{if(!oG(e.algorithm,"RSA-PSS"))throw oJ("RSA-PSS");let r=parseInt(t.slice(2),10);if(oQ(e.algorithm.hash)!==r)throw oJ(`SHA-${r}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":if(!oG(e.algorithm,"Ed25519"))throw oJ("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":if(!oG(e.algorithm,t))throw oJ(t);break;case"ES256":case"ES384":case"ES512":{if(!oG(e.algorithm,"ECDSA"))throw oJ("ECDSA");let r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw oJ(r,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}if(r&&!e.usages.includes(r))throw TypeError(`CryptoKey does not support this operation, its usages must include ${r}.`)}(t,e,r),t},o1=async(e,t,r)=>{let o=await o0(e,t,"sign");return oF(e,o),new Uint8Array(await crypto.subtle.sign(oW(e,o.algorithm),o,r))},o2=(...e)=>{let t,r=e.filter(Boolean);if(0===r.length||1===r.length)return!0;for(let e of r){let r=Object.keys(e);if(!t||0===t.size){t=new Set(r);continue}for(let e of r){if(t.has(e))return!1;t.add(e)}}return!0};function o6(e){return e?.[Symbol.toStringTag]==="CryptoKey"}function o5(e){return e?.[Symbol.toStringTag]==="KeyObject"}let o4=e=>o6(e)||o5(e),o8=e=>{if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t};function o3(e){return o8(e)&&"string"==typeof e.kty}let o9=e=>e?.[Symbol.toStringTag],o7=(e,t,r)=>{if(void 0!==t.use){let e;switch(r){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let o;switch(!0){case"sign"===r||"verify"===r:case"dir"===e:case e.includes("CBC-HS"):o=r;break;case e.startsWith("PBES2"):o="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):o=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===r?"wrapKey":"unwrapKey":r;break;case"encrypt"===r&&e.startsWith("RSA"):o="wrapKey";break;case"decrypt"===r:o=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(o&&t.key_ops?.includes?.(o)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}return!0},ne=(e,t,r)=>{e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(e)||/^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(e)?((e,t,r)=>{if(!(t instanceof Uint8Array)){if(o3(t)){if("oct"===t.kty&&"string"==typeof t.k&&o7(e,t,r))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!o4(t))throw TypeError(oX(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw TypeError(`${o9(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,r):((e,t,r)=>{if(o3(t))switch(r){case"decrypt":case"sign":if("oct"!==t.kty&&("AKP"===t.kty&&"string"==typeof t.priv||"string"==typeof t.d)&&o7(e,t,r))return;throw TypeError("JSON Web Key for this operation be a private JWK");case"encrypt":case"verify":if("oct"!==t.kty&&void 0===t.d&&void 0===t.priv&&o7(e,t,r))return;throw TypeError("JSON Web Key for this operation be a public JWK")}if(!o4(t))throw TypeError(oX(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw TypeError(`${o9(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(r){case"sign":throw TypeError(`${o9(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${o9(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(r){case"verify":throw TypeError(`${o9(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${o9(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,r)},nt=(e,t,r,o,n)=>{let i;if(void 0!==n.crit&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||void 0===o.crit)return new Set;if(!Array.isArray(o.crit)||0===o.crit.length||o.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let s of(i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t,o.crit)){if(!i.has(s))throw new oz(`Extension Header Parameter "${s}" is not recognized`);if(void 0===n[s])throw new e(`Extension Header Parameter "${s}" is missing`);if(i.get(s)&&void 0===o[s])throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(o.crit)},nr=async e=>{if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new oz('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new oz('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new oz('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;
24case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new oz('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new oz('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),o={...e};return"AKP"!==o.kty&&delete o.alg,delete o.use,crypto.subtle.importKey("jwk",o,t,e.ext??(!e.d&&!e.priv),e.key_ops??r)},no=async(e,r,o,n=!1)=>{let i=(t||=new WeakMap).get(e);if(i?.[o])return i[o];let s=await nr({...r,alg:o});return n&&Object.freeze(e),i?i[o]=s:t.set(e,{[o]:s}),s},nn=async(e,r)=>{if(e instanceof Uint8Array||o6(e))return e;if(o5(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,r)=>{let o,n=(t||=new WeakMap).get(e);if(n?.[r])return n[r];let i="public"===e.type,s=!!i;if("x25519"===e.asymmetricKeyType){switch(r){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError("given KeyObject instance cannot be used for this algorithm")}o=e.toCryptoKey(e.asymmetricKeyType,s,i?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==r&&"Ed25519"!==r)throw TypeError("given KeyObject instance cannot be used for this algorithm");o=e.toCryptoKey(e.asymmetricKeyType,s,[i?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(r!==e.asymmetricKeyType.toUpperCase())throw TypeError("given KeyObject instance cannot be used for this algorithm");o=e.toCryptoKey(e.asymmetricKeyType,s,[i?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let t;switch(r){case"RSA-OAEP":t="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":t="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":t="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":t="SHA-512";break;default:throw TypeError("given KeyObject instance cannot be used for this algorithm")}if(r.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:t},s,i?["encrypt"]:["decrypt"]);o=e.toCryptoKey({name:r.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:t},s,[i?"verify":"sign"])}if("ec"===e.asymmetricKeyType){let t=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!t)throw TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===r&&"P-256"===t&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:t},s,[i?"verify":"sign"])),"ES384"===r&&"P-384"===t&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:t},s,[i?"verify":"sign"])),"ES512"===r&&"P-521"===t&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:t},s,[i?"verify":"sign"])),r.startsWith("ECDH-ES")&&(o=e.toCryptoKey({name:"ECDH",namedCurve:t},s,i?[]:["deriveBits"]))}if(!o)throw TypeError("given KeyObject instance cannot be used for this algorithm");return n?n[r]=o:t.set(e,{[r]:o}),o})(e,r)}catch(e){if(e instanceof TypeError)throw e}let o=e.export({format:"jwk"});return no(e,o,r)}if(o3(e))return e.k?oZ(e.k):no(e,e,r,!0);throw Error("unreachable")};class ni{#t;#r;#o;constructor(e){if(!(e instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this.#t=e}setProtectedHeader(e){if(this.#r)throw TypeError("setProtectedHeader can only be called once");return this.#r=e,this}setUnprotectedHeader(e){if(this.#o)throw TypeError("setUnprotectedHeader can only be called once");return this.#o=e,this}async sign(e,t){let r;if(!this.#r&&!this.#o)throw new oH("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!o2(this.#r,this.#o))throw new oH("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this.#r,...this.#o},n=nt(oH,new Map([["b64",!0]]),t?.crit,this.#r,o),i=!0;if(n.has("b64")&&"boolean"!=typeof(i=this.#r.b64))throw new oH('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if("string"!=typeof s||!s)throw new oH('JWS "alg" (Algorithm) Header Parameter missing or invalid');ne(s,e,"sign");let a=this.#t;i&&(a=oO.encode(oj(a)));let c=oD(r=this.#r?oO.encode(oj(JSON.stringify(this.#r))):oO.encode(""),oO.encode("."),a),d=await nn(e,s),l={signature:oj(await o1(s,d,c)),payload:""};return i&&(l.payload=oP.decode(a)),this.#o&&(l.header=this.#o),this.#r&&(l.protected=oP.decode(r)),l}}class ns{#n;constructor(e){this.#n=new ni(e)}setProtectedHeader(e){return this.#n.setProtectedHeader(e),this}async sign(e,t){let r=await this.#n.sign(e,t);if(void 0===r.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}let na=e=>Math.floor(e.getTime()/1e3),nc=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,nd=e=>{let t,r=nc.exec(e);if(!r||r[4]&&r[1])throw TypeError("Invalid time period format");let o=parseFloat(r[2]);switch(r[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":t=Math.round(o);break;case"minute":case"minutes":case"min":case"mins":case"m":t=Math.round(60*o);break;case"hour":case"hours":case"hr":case"hrs":case"h":t=Math.round(3600*o);break;case"day":case"days":case"d":t=Math.round(86400*o);break;case"week":case"weeks":case"w":t=Math.round(604800*o);break;default:t=Math.round(0x1e187e0*o)}return"-"===r[1]||"ago"===r[4]?-t:t};function nl(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}let nu=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`;class np{#t;constructor(e){if(!o8(e))throw TypeError("JWT Claims Set MUST be an object");this.#t=structuredClone(e)}data(){return oO.encode(JSON.stringify(this.#t))}get iss(){return this.#t.iss}set iss(e){this.#t.iss=e}get sub(){return this.#t.sub}set sub(e){this.#t.sub=e}get aud(){return this.#t.aud}set aud(e){this.#t.aud=e}set jti(e){this.#t.jti=e}set nbf(e){"number"==typeof e?this.#t.nbf=nl("setNotBefore",e):e instanceof Date?this.#t.nbf=nl("setNotBefore",na(e)):this.#t.nbf=na(new Date)+nd(e)}set exp(e){"number"==typeof e?this.#t.exp=nl("setExpirationTime",e):e instanceof Date?this.#t.exp=nl("setExpirationTime",na(e)):this.#t.exp=na(new Date)+nd(e)}
24set iat(e){void 0===e?this.#t.iat=na(new Date):e instanceof Date?this.#t.iat=nl("setIssuedAt",na(e)):"string"==typeof e?this.#t.iat=nl("setIssuedAt",na(new Date)+nd(e)):this.#t.iat=nl("setIssuedAt",e)}}class nf{#r;#i;constructor(e={}){this.#i=new np(e)}setIssuer(e){return this.#i.iss=e,this}setSubject(e){return this.#i.sub=e,this}setAudience(e){return this.#i.aud=e,this}setJti(e){return this.#i.jti=e,this}setNotBefore(e){return this.#i.nbf=e,this}setExpirationTime(e){return this.#i.exp=e,this}setIssuedAt(e){return this.#i.iat=e,this}setProtectedHeader(e){return this.#r=e,this}async sign(e,t){let r=new ns(this.#i.data());if(r.setProtectedHeader(this.#r),Array.isArray(this.#r?.crit)&&this.#r.crit.includes("b64")&&!1===this.#r.b64)throw new oV("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}let nh=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),nm=Uint32Array.from([0xc1059ed8,0x367cd507,0x3070dd17,0xf70e5939,0xffc00b31,0x68581511,0x64f98fa7,0xbefa4fa4]),ny=Uint32Array.from([0xcbbb9d5d,0xc1059ed8,0x629a292a,0x367cd507,0x9159015a,0x3070dd17,0x152fecd8,0xf70e5939,0x67332667,0xffc00b31,0x8eb44a87,0x68581511,0xdb0c2e0d,0x64f98fa7,0x47b5481d,0xbefa4fa4]),ng=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),nw=BigInt(0x100000000-1),nb=BigInt(32),nv=function(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:r,l:s}=function(e,t=!1){return t?{h:Number(e&nw),l:Number(e>>nb&nw)}:{h:0|Number(e>>nb&nw),l:0|Number(e&nw)}}(e[i],t);[o[i],n[i]]=[r,s]}return[o,n]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e3585
245771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),nE=nv[0],nA=nv[1],nx=new Uint32Array(80),nT=new Uint32Array(80);function nk(e){switch(e){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw Error(`Unsupported alphabet: ${e}`)}}function nS(...e){let t=e.map(nk).join("");if(0===t.length)throw Error("No valid characters provided for random string generation.");let r=t.length;return(e,...o)=>{let n;if(e<=0)throw Error("Length must be a positive integer.");let i=t,s=r;o.length>0&&(s=(i=o.map(nk).join("")).length);let a=Math.floor(256/s)*s,c=new Uint8Array(2*e),d=c.length,l="",u=d;for(;l.length<e;)u>=d&&(Q(c),u=0),(n=c[u++])<a&&(l+=i[n%s]);return l}}let nR=nS("a-z","0-9","A-Z","-_");async function n_(e,t,r=3600){return await new nf(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}let nU=async({key:e,data:t})=>{let r=await r5("SHA-256").digest(e),o=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}(t);var n=oc(oI)(new Uint8Array(r)).encrypt(o);if(r3(n),or)return n.toHex();let i="";for(let e=0;e<n.length;e++)i+=oo[n[e]];return i},nI=async({key:e,data:t})=>{let r=await r5("SHA-256").digest(e),o=function(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);if(or)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let t=0,n=0;t<r;t++,n+=2){let r=on(e.charCodeAt(n)),i=on(e.charCodeAt(n+1));if(void 0===r||void 0===i)throw Error('hex string expected, got non-hex character "'+(e[n]+e[n+1])+'" at index '+n);o[t]=16*r+i}return o}(t),n=oc(oI)(new Uint8Array(r));return new TextDecoder().decode(n.decrypt(o))},nO=async(e,t,r,o)=>{let n=await o0(e,t,"verify");oF(e,n);let i=oW(e,n.algorithm);try{return await crypto.subtle.verify(i,n,r,o)}catch{return!1}};async function nP(e,t,r){let o,n;if(!o8(e))throw new oH("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new oH('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new oH("JWS Protected Header incorrect type");if(void 0===e.payload)throw new oH("JWS Payload missing");if("string"!=typeof e.signature)throw new oH("JWS Signature missing or incorrect type");
24if(void 0!==e.header&&!o8(e.header))throw new oH("JWS Unprotected Header incorrect type");let i={};if(e.protected)try{let t=oZ(e.protected);i=JSON.parse(oP.decode(t))}catch{throw new oH("JWS Protected Header is invalid")}if(!o2(i,e.header))throw new oH("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...i,...e.header},a=nt(oH,new Map([["b64",!0]]),r?.crit,i,s),c=!0;if(a.has("b64")&&"boolean"!=typeof(c=i.b64))throw new oH('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:d}=s;if("string"!=typeof d||!d)throw new oH('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=r&&((e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)})("algorithms",r.algorithms);if(l&&!l.has(d))throw new o$('"alg" (Algorithm) Header Parameter value not allowed');if(c){if("string"!=typeof e.payload)throw new oH("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new oH("JWS Payload must be a string or an Uint8Array instance");let u=!1;"function"==typeof t&&(t=await t(i,e),u=!0),ne(d,t,"verify");let p=oD(oO.encode(e.protected??""),oO.encode("."),"string"==typeof e.payload?oO.encode(e.payload):e.payload);try{o=oZ(e.signature)}catch{throw new oH("Failed to base64url decode the signature")}let f=await nn(t,d);if(!await nO(d,f,o,p))throw new oM;if(c)try{n=oZ(e.payload)}catch{throw new oH("Failed to base64url decode the payload")}else n="string"==typeof e.payload?oO.encode(e.payload):e.payload;let h={payload:n};return(void 0!==e.protected&&(h.protectedHeader=i),void 0!==e.header&&(h.unprotectedHeader=e.header),u)?{...h,key:f}:h}async function nD(e,t,r){if(e instanceof Uint8Array&&(e=oP.decode(e)),"string"!=typeof e)throw new oH("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=e.split(".");if(3!==s)throw new oH("Invalid Compact JWS");let a=await nP({payload:n,protected:o,signature:i},t,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}async function nZ(e,t,r){let o=await nD(e,t,r);if(o.protectedHeader.crit?.includes("b64")&&!1===o.protectedHeader.b64)throw new oV("JWTs MUST NOT use unencoded payload");let n={payload:function(e,t,r={}){var o,n;let i,s;try{i=JSON.parse(oP.decode(t))}catch{}if(!o8(i))throw new oV("JWT Claims Set must be a top-level JSON object");let{typ:a}=r;if(a&&("string"!=typeof e.typ||nu(e.typ)!==nu(a)))throw new oC('unexpected "typ" JWT header value',i,"typ","check_failed");let{requiredClaims:c=[],issuer:d,subject:l,audience:u,maxTokenAge:p}=r,f=[...c];for(let e of(void 0!==p&&f.push("iat"),void 0!==u&&f.push("aud"),void 0!==l&&f.push("sub"),void 0!==d&&f.push("iss"),new Set(f.reverse())))if(!(e in i))throw new oC(`missing required "${e}" claim`,i,e,"missing");if(d&&!(Array.isArray(d)?d:[d]).includes(i.iss))throw new oC('unexpected "iss" claim value',i,"iss","check_failed");if(l&&i.sub!==l)throw new oC('unexpected "sub" claim value',i,"sub","check_failed");if(u&&(o=i.aud,n="string"==typeof u?[u]:u,"string"==typeof o?!n.includes(o):!(Array.isArray(o)&&n.some(Set.prototype.has.bind(new Set(o))))))throw new oC('unexpected "aud" claim value',i,"aud","check_failed");switch(typeof r.clockTolerance){case"string":s=nd(r.clockTolerance);break;case"number":s=r.clockTolerance;break;case"undefined":s=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:h}=r,m=na(h||new Date);if((void 0!==i.iat||p)&&"number"!=typeof i.iat)throw new oC('"iat" claim must be a number',i,"iat","invalid");if(void 0!==i.nbf){if("number"!=typeof i.nbf)throw new oC('"nbf" claim must be a number',i,"nbf","invalid");if(i.nbf>m+s)throw new oC('"nbf" claim timestamp check failed',i,"nbf","check_failed")}if(void 0!==i.exp){if("number"!=typeof i.exp)throw new oC('"exp" claim must be a number',i,"exp","invalid");if(i.exp<=m-s)throw new oN('"exp" claim timestamp check failed',i,"exp","check_failed")}if(p){let e=m-i.iat;if(e-s>("number"==typeof p?p:nd(p)))throw new oN('"iat" claim timestamp check failed (too far in the past)',i,"iat","check_failed");if(e<0-s)throw new oC('"iat" claim timestamp check failed (it should be in the past)',i,"iat","check_failed")}return i}(o.protectedHeader,o.payload,r),protectedHeader:o.protectedHeader};return"function"==typeof t?{...n,key:o.key}:n}
24async function nj(e,t,r){let o;if(!o8(e))throw TypeError("JWK must be an object");switch(t??=e.alg,o??=r?.extractable??e.ext,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw TypeError('missing "k" (Key Value) Parameter value');return oZ(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new oz('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return nr({...e,alg:t,ext:o});case"AKP":if("string"!=typeof e.alg||!e.alg)throw TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw TypeError("JWK alg and alg option value mismatch");return nr({...e,ext:o});case"EC":case"OKP":return nr({...e,alg:t,ext:o});default:throw new oz('Unsupported "kty" (Key Type) Parameter value')}}function nL(e){return o8(e)}class nC{#s;#a=new WeakMap;constructor(e){if(!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(nL)}(e))throw new oq("JSON Web Key Set malformed");this.#s=structuredClone(e)}jwks(){return this.#s}async getKey(e,t){let{alg:r,kid:o}={...e,...t?.header},n=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new oz('Unsupported "alg" value for a JSON Web Key Set')}}(r),i=this.#s.keys.filter(e=>{let t=n===e.kty;if(t&&"string"==typeof o&&(t=o===e.kid),t&&("string"==typeof e.alg||"AKP"===n)&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;
24case"Ed25519":case"EdDSA":t="Ed25519"===e.crv}return t}),{0:s,length:a}=i;if(0===a)throw new oB;if(1!==a){let e=new oK,t=this.#a;throw e[Symbol.asyncIterator]=async function*(){for(let e of i)try{yield await nN(t,e,r)}catch{}},e}return nN(this.#a,s,r)}}async function nN(e,t,r){let o=e.get(t)||e.set(t,{}).get(t);if(void 0===o[r]){let e=await nj({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new oq("JSON Web Key Set members must be public keys");o[r]=e}return o[r]}"undefined"!=typeof navigator&&navigator.userAgent?.startsWith?.("Mozilla/5.0 ")||(r="jose/v6.1.0");Symbol();Symbol();let n$=e=>nS("a-z","A-Z","0-9")(e||32);var rp=rp;let nz=F.object({id:F.string(),createdAt:F.date().default(()=>new Date),updatedAt:F.date().default(()=>new Date)});function nH(e){if(null===e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.iterator in e)&&(!(Symbol.toStringTag in e)||"[object Module]"===Object.prototype.toString.call(e))}function nV(e){return(...t)=>t.reduce((t,r)=>(function e(t,r,o=".",n){if(!nH(r))return e(t,{},o,n);let i=Object.assign({},r);for(let r in t){if("__proto__"===r||"constructor"===r)continue;let s=t[r];null!=s&&(n&&n(i,r,s,o)||(Array.isArray(s)&&Array.isArray(i[r])?i[r]=[...s,...i[r]]:nH(s)&&nH(i[r])?i[r]=e(s,i[r],(o?`${o}.`:"")+r.toString(),n):i[r]=s))}return i})(t,r,"",e),{})}function nq(e){return"-"===e||"^"===e||"$"===e||"+"===e||"."===e||"("===e||")"===e||"|"===e||"["===e||"]"===e||"{"===e||"}"===e||"*"===e||"?"===e||"\\"===e?`\\${e}`:e}function nB(e,t){if("string"!=typeof t)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function nK(e,t){if("string"!=typeof e&&!Array.isArray(e))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if(("string"==typeof t||"boolean"==typeof t)&&(t={separator:t}),2==arguments.length&&!(void 0===t||"object"==typeof t&&null!==t&&!Array.isArray(t)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if("\\"===(t=t||{}).separator)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=function e(t,r=!0){if(Array.isArray(t)){let o=t.map(t=>`^${e(t,r)}$`);return`(?:${o.join("|")})`}let o="",n="",i=".";!0===r?(o="/",n="[/\\\\]",i="[^/\\\\]"):r&&((n=function(e){let t="";for(let r=0;r<e.length;r++)t+=nq(e[r]);return t}(o=r)).length>1?(n=`(?:${n})`,i=`((?!${n}).)`):i=`[^${n}]`);let s=r?`${n}+?`:"",a=r?`${n}*?`:"",c=r?t.split(o):[t],d="";for(let e=0;e<c.length;e++){let t=c[e],o=c[e+1],n="";if(t||!(e>0)){if(r&&(n=e===c.length-1?a:"**"!==o?s:""),r&&"**"===t){n&&(d+=0===e?"":n,d+=`(?:${i}*?${n})*?`);continue}for(let e=0;e<t.length;e++){let r=t[e];"\\"===r?e<t.length-1&&(d+=nq(t[e+1]),e++):"?"===r?d+=i:"*"===r?d+=`${i}*?`:d+=nq(r)}d+=n}}return d}(e,t.separator),o=RegExp(`^${r}$`,t.flags),n=nB.bind(null,o);return n.options=t,n.pattern=e,n.regexp=o,n}nz.extend({providerId:F.string(),accountId:F.string(),userId:rp.string(),accessToken:F.string().nullish(),refreshToken:F.str
24ing().nullish(),idToken:F.string().nullish(),accessTokenExpiresAt:F.date().nullish(),refreshTokenExpiresAt:F.date().nullish(),scope:F.string().nullish(),password:F.string().nullish()}),nz.extend({email:F.string().transform(e=>e.toLowerCase()),emailVerified:F.boolean().default(!1),name:F.string(),image:F.string().nullish()}),nz.extend({userId:rp.string(),expiresAt:F.date(),token:F.string(),ipAddress:F.string().nullish(),userAgent:F.string().nullish()}),nz.extend({value:F.string(),expiresAt:F.date(),identifier:F.string()}),nV(),nV((e,t,r)=>{if(void 0!==e[t]&&"function"==typeof r)return e[t]=r(e[t]),!0}),nV((e,t,r)=>{if(Array.isArray(e[t])&&"function"==typeof r)return e[t]=r(e[t]),!0}),rz(async e=>{if(e.request?.method!=="POST"||!e.request)return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,a=t?.errorCallbackURL,c=t?.newUserCallbackURL,d=Array.isArray(o.options.trustedOrigins)?o.trustedOrigins:[...o.trustedOrigins,...await o.options.trustedOrigins?.(e.request)||[]],l=e.headers?.has("cookie"),u=(t,r)=>{if(t&&!d.some(e=>((e,t)=>{if(e.startsWith("/"))return!1;if(t.includes("*"))return t.includes("://")?nK(t)(rO(e)||e):nK(t)(rD(e));let r=rP(e);return"http:"!==r&&"https:"!==r&&r?e.startsWith(t):t===rO(e)})(t,e)||t?.startsWith("/")&&"origin"!==r&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(t)))throw e.context.logger.error(`Invalid ${r}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config 25`,`Current list of trustedOrigins: ${d}`),new ee("FORBIDDEN",{message:`Invalid ${r}`})};l&&!e.context.options.advanced?.disableCSRFCheck&&u(n,"origin"),i&&u(i,"callbackURL"),s&&u(s,"redirectURL"),a&&u(a,"errorCallbackURL"),c&&u(c,"newUserCallbackURL")});let nM=e=>rz(async t=>{if(!t.request)return;let{context:r}=t,o=e(t),n=Array.isArray(r.options.trustedOrigins)?r.trustedOrigins:[...r.trustedOrigins,...await r.options.trustedOrigins?.(t.request)||[]],i=(e,r)=>{if(e&&!n.some(t=>((e,t)=>{if(e.startsWith("/"))return!1;if(t.includes("*"))return t.includes("://")?nK(t)(rO(e)||e):nK(t)(rD(e));let r=rP(e);return"http:"!==r&&"https:"!==r&&r?e.startsWith(t):t===rO(e)})(e,t)||e?.startsWith("/")&&"origin"!==r&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(e)))throw t.context.logger.error(`Invalid ${r}: ${e}`),t.context.logger.info(`If it's a valid URL, please add ${e} to trustedOrigins in your auth config 26`,`Current list of trustedOrigins: ${n}`),new ee("FORBIDDEN",{message:`Invalid ${r}`})};for(let e of Array.isArray(o)?o:[o])i(e,"callbackURL")});async function nW(e,t,r,o=3600){return await n_({email:t.toLowerCase(),updateTo:r},e,o)}async function nF(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new ee("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await nW(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}rH("/send-verification-email",{method:"POST",body:F.object({email:F.email().meta({description:"The email to send the verification email to"}),callbackURL:F.string().meta({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to",example:"[email protected]"},callbackURL:{type:"string",description:"The URL to use for email verification callback",example:"https://example.com/callback",nullable:!0}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the email was sent successfully",example:!0}}}}}},400:{description:"Bad Request",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Error message",example:"Verification email isn't enabled"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new ee("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await r1(e);
26if(!r){let r=await e.context.internalAdapter.findUserByEmail(t);return r&&await nF(e,r.user),e.json({status:!0})}if(r?.user.emailVerified)throw new ee("BAD_REQUEST",{message:"You can only send a verification email to an unverified email"});if(r?.user.email!==t)throw new ee("BAD_REQUEST",{message:"You can only send a verification email to your own email"});return await nF(e,r.user),e.json({status:!0})}),rH("/verify-email",{method:"GET",query:F.object({token:F.string().meta({description:"The token to verify the email"}),callbackURL:F.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[nM(e=>e.query.callbackURL)],metadata:{openapi:{description:"Verify the email of the user",parameters:[{name:"token",in:"query",description:"The token to verify the email",required:!0,schema:{type:"string"}},{name:"callbackURL",in:"query",description:"The URL to redirect to after email verification",required:!1,schema:{type:"string"}}],responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{id:{type:"string",description:"User ID"},email:{type:"string",description:"User email"},name:{type:"string",description:"User name"},image:{type:"string",description:"User image URL"},emailVerified:{type:"boolean",description:"Indicates if the user email is verified"},createdAt:{type:"string",description:"User creation date"},updatedAt:{type:"string",description:"User update date"}},required:["id","email","name","image","emailVerified","createdAt","updatedAt"]},status:{type:"boolean",description:"Indicates if the email was verified successfully"}},required:["user","status"]}}}}}}}},async e=>{let t;function r(t){if(e.query.callbackURL){if(e.query.callbackURL.includes("?"))throw e.redirect(`${e.query.callbackURL}&error=${t}`);throw e.redirect(`${e.query.callbackURL}?error=${t}`)}throw new ee("UNAUTHORIZED",{message:t})}let{token:o}=e.query;try{t=await nZ(o,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(e){if(e instanceof oN)return r("token_expired");return r("invalid_token")}let n=F.object({email:F.string().email(),updateTo:F.string().optional()}).parse(t.payload),i=await e.context.internalAdapter.findUserByEmail(n.email);if(!i)return r("user_not_found");if(n.updateTo){let t=await r1(e);if(!t||t.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return r("unauthorized")}let o=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1},e),i=await nW(e.context.secret,n.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:o,url:`${e.context.baseURL}/verify-email?token=${i}&callbackURL=${e.query.callbackURL||"/"}`,token:i},e.request),await rC(e,{session:t.session,user:{...t.user,email:n.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:{id:o.id,email:o.email,name:o.name,image:o.image,emailVerified:o.emailVerified,createdAt:o.createdAt,updatedAt:o.updatedAt}})}e.context.options.emailVerification?.onEmailVerification&&await e.context.options.emailVerification.onEmailVerification(i.user,e.request);let s=await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0},e);if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(s,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await r1(e);if(t&&t.user.email===n.email)await rC(e,{session:t.session,user:{...t.user,emailVerified:!0}});else{let t=await e.context.internalAdapter.createSession(i.user.id,e);if(!t)throw new ee("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await rC(e,{session:t,user:{...i.user,emailVerified:!0}})}}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});let nJ={isAction:!1};async function nG(e,t){let r=e.body?.callbackURL||e.context.options.baseURL;if(!r)throw new ee("BAD_REQUEST",{message:"callbackURL is required"});let o=nR(128),n=nR(32),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp}),s=new Date;s.setMinutes(s.getMinutes()+10);
26let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s},e);if(!a)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ee("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function nQ(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r){e.context.logger.error("State Mismatch. Verification not found",{state:t});let r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;throw e.redirect(`${r}?error=please_restart_the_process`)}let o=F.object({callbackURL:F.string(),codeVerifier:F.string(),errorURL:F.string().optional(),newUserURL:F.string().optional(),expiresAt:F.number(),link:F.object({email:F.string(),userId:rp.string()}).optional(),requestSignUp:F.boolean().optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now()){await e.context.internalAdapter.deleteVerificationValue(r.id);let t=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;throw e.redirect(`${t}?error=please_restart_the_process`)}return await e.context.internalAdapter.deleteVerificationValue(r.id),o}function nY(e,t){return t.options.account?.encryptOAuthTokens&&e?nU({key:t.secret,data:e}):e}async function nX(e,{userInfo:t,account:r,callbackURL:o,disableSignUp:n,overrideUserInfo:i}){let s=await e.context.internalAdapter.findOAuthUser(t.email.toLowerCase(),r.accountId,r.providerId).catch(t=>{r_.error("Better auth was unable to query your database.\nError: ",t);let r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;throw e.redirect(`${r}?error=internal_server_error`)}),a=s?.user,c=!a;if(s){let o=s.accounts.find(e=>e.providerId===r.providerId&&e.accountId===r.accountId);if(o){if(e.context.options.account?.updateAccountOnSignIn!==!1){let t=Object.fromEntries(Object.entries({idToken:r.idToken,accessToken:await nY(r.accessToken,e.context),refreshToken:await nY(r.refreshToken,e.context),accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope}).filter(([e,t])=>void 0!==t));Object.keys(t).length>0&&await e.context.internalAdapter.updateAccount(o.id,t,e)}}else{let o=e.context.options.account?.accountLinking?.trustedProviders;if(!o?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return V&&r_.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:s.user.id,accessToken:await nY(r.accessToken,e.context),refreshToken:await nY(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope},e)}catch(e){return r_.error("Unable to link account",e),{error:"unable to link account",data:null}}}if(i){let{id:r,...o}=t;await e.context.internalAdapter.updateUser(s.user.id,{...o,email:t.email.toLowerCase(),emailVerified:t.email.toLowerCase()===s.user.email&&s.user.emailVerified||t.emailVerified})}}else{if(n)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:n,...i}=t;if(a=await e.context.internalAdapter.createOAuthUser({...i,email:t.email.toLowerCase()},{accessToken:await nY(r.accessToken,e.context),refreshToken:await nY(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()},e).then(e=>e?.user),!t.emailVerified&&a&&e.context.options.emailVerification?.sendOnSignUp){let t=await nW(e.context.secret,a.email,void 0,e.context.options.emailVerification?.expiresIn),r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:r,token:t},e.request)}}catch(e){if(r_.error(e),e instanceof ee)return{error:e.message,data:null,isRegister:!1};return{error:"unable to create user",data:null,isRegister:!1}}}if(!a)return{error:"unable to create user",data:null,isRegister:!1};
26let d=await e.context.internalAdapter.createSession(a.id,e);return d?{data:{session:d,user:a},error:null,isRegister:c}:{error:"unable to create session",data:null,isRegister:!1}}let n0=F.enum(["apple","atlassian","cognito","discord","facebook","figma","github","microsoft","google","huggingface","slack","spotify","twitch","twitter","dropbox","kick","linear","linkedin","gitlab","tiktok","reddit","roblox","salesforce","vk","zoom","notion","kakao","naver","line","paypal"]).or(F.string());rH("/sign-in/social",{method:"POST",body:F.object({callbackURL:F.string().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:F.string().optional(),errorCallbackURL:F.string().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:n0,disableRedirect:F.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:F.optional(F.object({token:F.string().meta({description:"ID token from the provider"}),nonce:F.string().meta({description:"Nonce used to generate the token"}).optional(),accessToken:F.string().meta({description:"Access token from the provider"}
26).optional(),refreshToken:F.string().meta({description:"Refresh token from the provider"}).optional(),expiresAt:F.number().meta({description:"Expiry date of the token"}).optional()})),scopes:F.array(F.string()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:F.boolean().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:F.string().meta({description:"The login hint to use for the authorization code request"}).optional()}),metadata:{openapi:{description:"Sign in with a social provider",operationId:"socialSignIn",responses:{200:{description:"Success - Returns either session details or redirect URL",content:{"application/json":{schema:{type:"object",description:"Session response when idToken is provided",properties:{redirect:{type:"boolean",enum:[!1]},token:{type:"string",description:"Session token",url:{type:"null",nullable:!0},user:{type:"object",properties:{id:{type:"string"},email:{type:"string"},name:{type:"string",nullable:!0},image:{type:"string",nullable:!0},emailVerified:{type:"boolean"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},required:["id","email","emailVerified","createdAt","updatedAt"]}}},required:["redirect","token","user"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(t=>t.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new ee("NOT_FOUND",{message:rK});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new ee("NOT_FOUND",{message:rW});let{token:r,nonce:o}=e.body.idToken;if(!await t.verifyIdToken(r,o))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new ee("UNAUTHORIZED",{message:rM});let n=await t.getUserInfo({idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!n||!n?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new ee("UNAUTHORIZED",{message:rF});if(!n.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new ee("UNAUTHORIZED",{message:rJ});let i=await nX(e,{userInfo:{...n.user,email:n.user.email,id:String(n.user.id),name:n.user.name||"",image:n.user.image,emailVerified:n.user.emailVerified||!1},account:{providerId:t.id,accountId:String(n.user.id),accessToken:e.body.idToken.accessToken},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.disableSignUp});if(i.error)throw new ee("UNAUTHORIZED",{message:i.error});return await rC(e,i.data),e.json({redirect:!1,token:i.data.session.token,url:void 0,user:{id:i.data.user.id,email:i.data.user.email,name:i.data.user.name,image:i.data.user.image,emailVerified:i.data.user.emailVerified,createdAt:i.data.user.createdAt,updatedAt:i.data.user.updatedAt}})}let{codeVerifier:r,state:o}=await nG(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`,scopes:e.body.scopes,loginHint:e.body.loginHint});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),rH("/sign-in/email",{method:"POST",body:F.object({email:F.string().meta({description:"Email of the user"}),password:F.string().meta({description:"Password of the user"}),callbackURL:F.string().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:F.boolean().meta({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success - Returns either session details or redirect URL",content:{"application/json":{schema:{type:"object",description:"Session response when idToken is provided",properties:{redirect:{type:"boolean",enum:[!1]},token:{type:"string",description:"Session token"},url:{type:"null",nullable:!0},user:{type:"object",properties:{id:{type:"string"},email:{type:"string"},name:{type:"string",nullable:!0},image:{type:"string",nullable:!0},emailVerified:{type:"boolean"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},required:["id","email","emailVerified","createdAt","updatedAt"]}},required:["redirect","token","user"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new ee("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!F.string().email().safeParse(t).success)throw new ee("BAD_REQUEST",{message:"Invalid email"});
26let o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new ee("UNAUTHORIZED",{message:rB});let n=o.accounts.find(e=>"credential"===e.providerId);if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new ee("UNAUTHORIZED",{message:rB});let i=n?.password;if(!i)throw e.context.logger.error("Password not found",{email:t}),new ee("UNAUTHORIZED",{message:rB});if(!await e.context.password.verify({hash:i,password:r}))throw e.context.logger.error("Invalid password"),new ee("UNAUTHORIZED",{message:rB});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!o.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new ee("FORBIDDEN",{message:rG});if(e.context.options?.emailVerification?.sendOnSignIn){let t=await nW(e.context.secret,o.user.email,void 0,e.context.options.emailVerification?.expiresIn),r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:o.user,url:r,token:t},e.request)}throw new ee("FORBIDDEN",{message:rG})}let s=await e.context.internalAdapter.createSession(o.user.id,e,!1===e.body.rememberMe);if(!s)throw e.context.logger.error("Failed to create session"),new ee("UNAUTHORIZED",{message:"Failed to create session"});return await rC(e,{session:s,user:o.user},!1===e.body.rememberMe),e.json({redirect:!!e.body.callbackURL,token:s.token,url:e.body.callbackURL,user:{id:o.user.id,email:o.user.email,name:o.user.name,image:o.user.image,emailVerified:o.user.emailVerified,createdAt:o.user.createdAt,updatedAt:o.user.updatedAt}})});let n1=F.object({code:F.string().optional(),error:F.string().optional(),device_id:F.string().optional(),error_description:F.string().optional(),state:F.string().optional(),user:F.string().optional()});function n2(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([e,t])=>o.searchParams.set(e,t)),o.href}rH("/callback/:id",{method:["GET","POST"],body:n1.optional(),query:n1.optional(),metadata:nJ},async e=>{let t,r,o,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;try{if("GET"===e.method)t=n1.parse(e.query);else if("POST"===e.method)t=n1.parse(e.body);else throw Error("Unsupported method")}catch(t){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",t),e.redirect(`${n}?error=invalid_callback_request`)}let{code:i,error:s,state:a,error_description:c,device_id:d}=t;if(s)throw e.redirect(`${n}?error=${s}&error_description=${c}`);if(!a)throw e.context.logger.error("State not found",s),e.redirect(`${n}?error=state_not_found`);let{codeVerifier:l,callbackURL:u,link:p,errorURL:f,newUserURL:h,requestSignUp:m}=await nQ(e);function y(t){let r=f||n;throw r=r.includes("?")?`${r}&error=${t}`:`${r}?error=${t}`,e.redirect(r)}if(!i)throw e.context.logger.error("Code not found"),y("no_code");let g=e.context.socialProviders.find(t=>t.id===e.params.id);if(!g)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),y("oauth_provider_not_found");try{r=await g.validateAuthorizationCode({code:i,codeVerifier:l,deviceId:d,redirectURI:`${e.context.baseURL}/callback/${g.id}`})}catch(t){throw e.context.logger.error("",t),y("invalid_code")}let w=await g.getUserInfo({...r,user:e.body?.user?rU(e.body.user):void 0}).then(e=>e?.user);if(!w)return e.context.logger.error("Unable to get user info"),y("unable_to_get_user_info");if(!u)throw e.context.logger.error("No callback URL found"),y("no_callback_url");if(p){let t,o=e.context.options.account?.accountLinking?.trustedProviders;if(!o?.includes(g.id)&&!w.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error("Unable to link account - untrusted provider"),y("unable_to_link_account");if(w.email!==p.email&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return y("email_doesn't_match");let n=await e.context.internalAdapter.findAccount(String(w.id));if(n){if(n.userId.toString()!==p.userId.toString())return y("account_already_linked_to_different_user");let t=Object.fromEntries(Object.entries({accessToken:await nY(r.accessToken,e.context),refreshToken:await nY(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scopes?.join(",")}).filter(([e,t])=>void 0!==t));
26await e.context.internalAdapter.updateAccount(n.id,t)}else if(!await e.context.internalAdapter.createAccount({userId:p.userId,providerId:g.id,accountId:String(w.id),...r,accessToken:await nY(r.accessToken,e.context),refreshToken:await nY(r.refreshToken,e.context),scope:r.scopes?.join(",")},e))return y("unable_to_link_account");try{t=u.toString()}catch{t=u}throw e.redirect(t)}if(!w.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),y("email_not_found");let b=await nX(e,{userInfo:{...w,id:String(w.id),email:w.email,name:w.name||w.email},account:{providerId:g.id,accountId:String(w.id),...r,scope:r.scopes?.join(",")},callbackURL:u,disableSignUp:g.disableImplicitSignUp&&!m||g.options?.disableSignUp,overrideUserInfo:g.options?.overrideUserInfoOnSignIn});if(b.error)return e.context.logger.error(b.error.split(" ").join("_")),y(b.error.split(" ").join("_"));let{session:v,user:E}=b.data;await rC(e,{session:v,user:E});try{o=(b.isRegister&&h||u).toString()}catch{o=b.isRegister&&h||u}throw e.redirect(o)}),rH("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw rN(e),new ee("BAD_REQUEST",{message:rV});return await e.context.internalAdapter.deleteSession(t),rN(e),e.json({success:!0})}),rH("/request-password-reset",{method:"POST",body:F.object({email:F.email().meta({description:"The email address of the user to send a password reset email to"}),redirectTo:F.string().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"},message:{type:"string"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),new ee("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let n=rf(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),i=n$(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${i}`,expiresAt:n},e);let s=r?encodeURIComponent(r):"",a=`${e.context.baseURL}/reset-password/${i}?callbackURL=${s}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:i},e.request),e.json({status:!0})}),rH("/forget-password",{method:"POST",body:F.object({email:F.string().email().meta({description:"The email address of the user to send a password reset email to"}),redirectTo:F.string().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"},message:{type:"string"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),new ee("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}
26=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let n=rf(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),i=n$(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${i}`,expiresAt:n},e);let s=r?encodeURIComponent(r):"",a=`${e.context.baseURL}/reset-password/${i}?callbackURL=${s}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:i},e.request),e.json({status:!0})}),rH("/reset-password/:token",{method:"GET",query:F.object({callbackURL:F.string().meta({description:"The URL to redirect the user to reset their password"})}),use:[nM(e=>e.query.callbackURL)],metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{var t,r;let o,{token:n}=e.params,{callbackURL:i}=e.query;if(!n||!i)throw e.redirect(n2(e.context,i,{error:"INVALID_TOKEN"}));let s=await e.context.internalAdapter.findVerificationValue(`reset-password:${n}`);if(!s||s.expiresAt<new Date)throw e.redirect(n2(e.context,i,{error:"INVALID_TOKEN"}));throw e.redirect((t=e.context,r={token:n},o=new URL(i,t.baseURL),r&&Object.entries(r).forEach(([e,t])=>o.searchParams.set(e,t)),o.href))}),rH("/reset-password",{method:"POST",query:F.object({token:F.string().optional()}).optional(),body:F.object({newPassword:F.string().meta({description:"The new password to set"}
26),token:F.string().meta({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token;if(!t)throw new ee("BAD_REQUEST",{message:rM});let{newPassword:r}=e.body,o=e.context.password?.config.minPasswordLength,n=e.context.password?.config.maxPasswordLength;if(r.length<o)throw new ee("BAD_REQUEST",{message:rQ});if(r.length>n)throw new ee("BAD_REQUEST",{message:rY});let i=`reset-password:${t}`,s=await e.context.internalAdapter.findVerificationValue(i);if(!s||s.expiresAt<new Date)throw new ee("BAD_REQUEST",{message:rM});let a=s.value,c=await e.context.password.hash(r);if((await e.context.internalAdapter.findAccounts(a)).find(e=>"credential"===e.providerId)?await e.context.internalAdapter.updatePassword(a,c,e):await e.context.internalAdapter.createAccount({userId:a,providerId:"credential",password:c,accountId:a},e),await e.context.internalAdapter.deleteVerificationValue(s.id),e.context.options.emailAndPassword?.onPasswordReset){let t=await e.context.internalAdapter.findUserById(a);t&&await e.context.options.emailAndPassword.onPasswordReset({user:t},e.request)}return e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteSessions(a),e.json({status:!0})}),rH("/change-password",{method:"POST",body:F.object({newPassword:F.string().meta({description:"The new password to set"}),currentPassword:F.string().meta({description:"The current password is required"}),revokeOtherSessions:F.boolean().meta({description:"Must be a boolean value"}).optional()}),use:[r2],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Password successfully changed",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"New session token if other sessions were revoked"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new ee("BAD_REQUEST",{message:rQ});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new ee("BAD_REQUEST",{message:rY});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(e=>"credential"===e.providerId&&e.password);if(!a||!a.password)throw new ee("BAD_REQUEST",{message:rX});let c=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new ee("BAD_REQUEST",{message:rq});await e.context.internalAdapter.updateAccount(a.id,{password:c});let d=null;if(o){await e.context.internalAdapter.deleteSessions(n.user.id);let t=await e.context.internalAdapter.createSession(n.user.id,e);if(!t)throw new ee("INTERNAL_SERVER_ERROR",{message:rV});await rC(e,{session:t,user:n.user}),d=t.token}return e.json({token:d,user:{id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt}})}),rH("/set-password",{method:"POST",body:F.object({newPassword:F.string().meta({description:"The new password to set is required"})}),metadata:{SERVER_ONLY:!0},use:[r2]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new ee("BAD_REQUEST",{message:rQ});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new ee("BAD_REQUEST",{message:rY});
26let i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(e=>"credential"===e.providerId&&e.password),s=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:s},e),e.json({status:!0});throw new ee("BAD_REQUEST",{message:"user already has a password"})}),rH("/delete-user",{method:"POST",use:[r2],body:F.object({callbackURL:F.string().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:F.string().meta({description:"The password of the user is required to delete the user"}).optional(),token:F.string().meta({description:"The token to delete the user is required"}).optional()}),metadata:{openapi:{description:"Delete the user",responses:{200:{description:"User deletion processed successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the operation was successful"},message:{type:"string",enum:["User deleted","Verification email sent"],description:"Status message of the deletion process"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new ee("NOT_FOUND");let t=e.context.session;if(e.body.password){let r=(await e.context.internalAdapter.findAccounts(t.user.id)).find(e=>"credential"===e.providerId&&e.password);if(!r||!r.password)throw new ee("BAD_REQUEST",{message:rX});if(!await e.context.password.verify({hash:r.password,password:e.body.password}))throw new ee("BAD_REQUEST",{message:rq})}if(e.body.token)return await n6({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=nR(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${r}`,expiresAt:new Date(Date.now()+1e3*(e.context.options.user.deleteUser?.deleteTokenExpiresIn||86400))},e);let o=`${e.context.baseURL}/delete-user/callback?token=${r}&callbackURL=${e.body.callbackURL||"/"}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:o,token:r},e.request),e.json({success:!0,message:"Verification email sent"})}if(!e.body.password&&0!==e.context.sessionConfig.freshAge){let r=new Date(t.session.createdAt).getTime(),o=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>1e3*o)throw new ee("BAD_REQUEST",{message:"Session expired. Re-authenticate to perform this action."})}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),rN(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})});let n6=rH("/delete-user/callback",{method:"GET",query:F.object({token:F.string().meta({description:"The token to verify the deletion request"}),callbackURL:F.string().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[nM(e=>e.query.callbackURL)],metadata:{openapi:{description:"Callback to complete user deletion with verification token",responses:{200:{description:"User successfully deleted",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the deletion was successful"},message:{type:"string",enum:["User deleted"],description:"Confirmation message"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new ee("NOT_FOUND");let t=await r1(e);if(!t)throw new ee("NOT_FOUND",{message:rF});let r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date||r.value!==t.user.id)throw new ee("NOT_FOUND",{message:rM});let o=e.context.options.user.deleteUser?.beforeDelete;
26o&&await o(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationValue(r.id),rN(e);let n=e.context.options.user.deleteUser?.afterDelete;if(n&&await n(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})});rH("/change-email",{method:"POST",body:F.object({newEmail:F.email().meta({description:"The new email address to set must be a valid email address"}),callbackURL:F.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[r2],metadata:{openapi:{responses:{200:{description:"Email change request processed successfully",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the request was successful"},message:{type:"string",enum:["Email updated","Verification email sent"],description:"Status message of the email change process",nullable:!0}},required:["status"]}}}},422:{description:"Unprocessable Entity. Email already exists",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new ee("BAD_REQUEST",{message:"Change email is disabled"});let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new ee("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(t))throw e.context.logger.error("Email already exists"),new ee("BAD_REQUEST",{message:"Couldn't update your email"});if(!0!==e.context.session.user.emailVerified){if(await e.context.internalAdapter.findUserByEmail(t))throw new ee("UNPROCESSABLE_ENTITY",{message:"User already exists. Use another email."});if(await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:t},e),await rC(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),e.context.options.emailVerification?.sendVerificationEmail){let r=await nW(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:{...e.context.session.user,email:t},url:o,token:r},e.request)}return e.json({status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new ee("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await nW(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:t,url:o,token:r},e.request),e.json({status:!0})}),rH("/error",{method:"GET",metadata:{...nJ,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string",description:"The HTML content of the error page"}}}}}}}},async e=>new Response(((e="Unknown")=>`<!DOCTYPE html> 27<html lang="en"> 28<head> 29 <meta charset="UTF-8"> 30 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 31 <title>Authentication Error</title> 32 <style> 33 :root { 34 --bg-color: #f8f9fa; 35 --text-color: #212529; 36 --accent-color: #000000; 37 --error-color: #dc3545; 38 --border-color: #e9ecef; 39 } 40 body { 41 font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; 42 background-color: var(--bg-color); 43 color: var(--text-color); 44 display: flex; 45 justify-content: center; 46 align-items: center; 47 height: 100vh; 48 margin: 0; 49 line-height: 1.5; 50 } 51 .error-container { 52 background-color: #ffffff; 53 border-radius: 12px; 54 box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05); 55 padding: 2.5rem; 56 text-align: center; 57 max-width: 90%; 58 width: 400px; 59 } 60 h1 { 61 color: var(--error-color); 62 font-size: 1.75rem; 63 margin-bottom: 1rem; 64 font-weight: 600; 65 } 66 p { 67 margin-bottom: 1.5rem; 68 color: #495057; 69 } 70 .btn { 71 background-color: var(--accent-color); 72 color: #ffffff; 73 text-decoration: none; 74 padding: 0.75rem 1.5rem; 75 border-radius: 6px; 76 transition: all 0.3s ease; 77 display: inline-block; 78 font-weight: 500; 79 border: 2px solid var(--accent-color); 80 } 81 .btn:hover { 82 background-color: #131721; 83 } 84 .error-code { 85 font-size: 0.875rem; 86 color: #6c757d; 87 margin-top: 1.5rem; 88 padding-top: 1.5rem; 89 border-top: 1px solid var(--border-color); 90 } 91 .icon { 92 font-size: 3rem; 93 margin-bottom: 1rem; 94 } 95 </style> 96</head> 97<body> 98 <div class="error-container"> 99 <div class="icon">\u26A0\uFE0F</div> 100 <h1>Better Auth Error</h1> 101 <p>We encountered an issue while processing your request. Please try again or c
101ontact the application owner if the problem persists.</p> 102 <a href="/" id="returnLink" class="btn">Return to Application</a> 103 <div class="error-code">Error Code: <span id="errorCode">${e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</span></div> 104 </div> 105</body> 106</html>`)(new URL(e.request?.url||"").searchParams.get("error")||"Unknown"),{headers:{"Content-Type":"text/html"}})),rH("/ok",{method:"GET",metadata:{...nJ,openapi:{description:"Check if the API is working",responses:{200:{description:"API is working",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean",description:"Indicates if the API is working"}},required:["ok"]}}}}}}}},async e=>e.json({ok:!0})),rH("/list-accounts",{method:"GET",use:[r2],metadata:{openapi:{description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},accountId:{type:"string"},scopes:{type:"array",items:{type:"string"}}},required:["id","providerId","createdAt","updatedAt","accountId","scopes"]}}}}}}}}},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(e=>({id:e.id,providerId:e.providerId,createdAt:e.createdAt,updatedAt:e.updatedAt,accountId:e.accountId,scopes:e.scope?.split(",")||[]})))}),rH("/link-social",{method:"POST",requireHeaders:!0,body:F.object({callbackURL:F.string().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:n0,idToken:F.object({token:F.string(),nonce:F.string().optional(),accessToken:F.string().optional(),refreshToken:F.str
106ing().optional(),scopes:F.array(F.string()).optional()}).optional(),requestSignUp:F.boolean().optional(),scopes:F.array(F.string()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:F.string().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:F.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional()}),use:[r2],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string",description:"The authorization URL to redirect the user to"},redirect:{type:"boolean",description:"Indicates if the user should be redirected to the authorization URL"},status:{type:"boolean"}},required:["redirect"]}}}}}}}},async e=>{let t=e.context.session,r=e.context.socialProviders.find(t=>t.id===e.body.provider);if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new ee("NOT_FOUND",{message:rK});if(e.body.idToken){if(!r.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new ee("NOT_FOUND",{message:rW});let{token:o,nonce:n}=e.body.idToken;if(!await r.verifyIdToken(o,n))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new ee("UNAUTHORIZED",{message:rM});let i=await r.getUserInfo({idToken:o,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!i||!i?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new ee("UNAUTHORIZED",{message:rF});let s=String(i.user.id);if(!i.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new ee("UNAUTHORIZED",{message:rJ});if((await e.context.internalAdapter.findAccounts(t.user.id)).find(e=>e.providerId===r.id&&e.accountId===s))return e.json({url:"",status:!0,redirect:!1});let a=e.context.options.account?.accountLinking?.trustedProviders;if(!a?.includes(r.id)&&!i.user.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)throw new ee("UNAUTHORIZED",{message:"Account not linked - linking not allowed"});if(i.user.email!==t.user.email&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw new ee("UNAUTHORIZED",{message:"Account not linked - different emails not allowed"});try{await e.context.internalAdapter.createAccount({userId:t.user.id,providerId:r.id,accountId:s,accessToken:e.body.idToken.accessToken,idToken:o,refreshToken:e.body.idToken.refreshToken,scope:e.body.idToken.scopes?.join(",")},e)}catch(e){throw new ee("EXPECTATION_FAILED",{message:"Account not linked - unable to create account"})}if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{await e.context.internalAdapter.updateUser(t.user.id,{name:i.user?.name,image:i.user?.image})}catch(e){console.warn("Could not update user - "+e.toString())}return e.json({url:"",status:!0,redirect:!1})}let o=await nG(e,{userId:t.user.id,email:t.user.email}),n=await r.createAuthorizationURL({state:o.state,codeVerifier:o.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${r.id}`,scopes:e.body.scopes});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),rH("/unlink-account",{method:"POST",body:F.object({providerId:F.string(),accountId:F.string().optional()}),use:[r6],metadata:{openapi:{description:"Unlink an account",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let{providerId:t,accountId:r}=e.body,o=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(1===o.length&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw new ee("BAD_REQUEST",{message:"You can't unlink your last account"});let n=o.find(e=>r?e.accountId===r&&e.providerId===t:e.providerId===t);if(!n)throw new ee("BAD_REQUEST",{message:"Account not found"});
106return await e.context.internalAdapter.deleteAccount(n.id),e.json({status:!0})});let n5=rH("/get-access-token",{method:"POST",body:F.object({providerId:F.string().meta({description:"The provider ID for the OAuth provider"}),accountId:F.string().meta({description:"The account ID associated with the refresh token"}).optional(),userId:F.string().meta({description:"The user ID associated with the account"}).optional()}),metadata:{openapi:{description:"Get a valid access token, doing a refresh if needed",responses:{200:{description:"A Valid access token",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},refreshToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"},refreshTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let{providerId:t,accountId:r,userId:o}=e.body,n=e.request,i=await r1(e);if(n&&!i)throw e.error("UNAUTHORIZED");let s=i?.user?.id||o;if(!s)throw new ee("BAD_REQUEST",{message:"Either userId or session is required"});if(!e.context.socialProviders.find(e=>e.id===t))throw new ee("BAD_REQUEST",{message:`Provider ${t} is not supported.`});let a=(await e.context.internalAdapter.findAccounts(s)).find(e=>r?e.id===r&&e.providerId===t:e.providerId===t);if(!a)throw new ee("BAD_REQUEST",{message:"Account not found"});let c=e.context.socialProviders.find(e=>e.id===t);if(!c)throw new ee("BAD_REQUEST",{message:`Provider ${t} not found.`});try{var d,l;let t=null,r=a.accessTokenExpiresAt&&new Date(a.accessTokenExpiresAt).getTime()-Date.now()<5e3;a.refreshToken&&r&&c.refreshAccessToken&&(t=await c.refreshAccessToken(a.refreshToken),await e.context.internalAdapter.updateAccount(a.id,{accessToken:await nY(t.accessToken,e.context),accessTokenExpiresAt:t.accessTokenExpiresAt,refreshToken:await nY(t.refreshToken,e.context),refreshTokenExpiresAt:t.refreshTokenExpiresAt}));let o={accessToken:await (d=t?.accessToken??a.accessToken??"",l=e.context,!d?d:l.options.account?.encryptOAuthTokens?nI({key:l.secret,data:d}):d),accessTokenExpiresAt:t?.accessTokenExpiresAt??a.accessTokenExpiresAt??void 0,scopes:a.scope?.split(",")??[],idToken:t?.idToken??a.idToken??void 0};return e.json(o)}catch(e){throw new ee("BAD_REQUEST",{message:"Failed to get a valid access token",cause:e})}});rH("/refresh-token",{method:"POST",body:F.object({providerId:F.string().meta({description:"The provider ID for the OAuth provider"}),accountId:F.string().meta({description:"The account ID associated with the refresh token"}).optional(),userId:F.string().meta({description:"The user ID associated with the account"}).optional()}),metadata:{openapi:{description:"Refresh the access token using a refresh token",responses:{200:{description:"Access token refreshed successfully",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},refreshToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"},refreshTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let{providerId:t,accountId:r,userId:o}=e.body,n=e.request,i=await r1(e);if(n&&!i)throw e.error("UNAUTHORIZED");let s=i?.user?.id||o;if(!s)throw new ee("BAD_REQUEST",{message:"Either userId or session is required"});let a=(await e.context.internalAdapter.findAccounts(s)).find(e=>r?e.id===r&&e.providerId===t:e.providerId===t);if(!a)throw new ee("BAD_REQUEST",{message:"Account not found"});let c=e.context.socialProviders.find(e=>e.id===t);if(!c)throw new ee("BAD_REQUEST",{message:`Provider ${t} not found.`});if(!c.refreshAccessToken)throw new ee("BAD_REQUEST",{message:`Provider ${t} does not support token refreshing.`});try{let t=await c.refreshAccessToken(a.refreshToken);return await e.context.internalAdapter.updateAccount(a.id,{accessToken:await nY(t.accessToken,e.context),refreshToken:await nY(t.refreshToken,e.context),accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt}),e.json(t)}catch(e){throw new ee("BAD_REQUEST",{message:"Failed to refresh access token",cause:e})}}),rH("/account-info",{method:"POST",use:[r2],metadata:{openapi:{description:"Get the account info provided by the provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},email:{type:"string"},image:{type:"string"},emailVerified:{type:"boolean"}},required:["id","emailVerified"]},data:{type:"object",properties:{},additionalProperties:!0}},required:["user","data"],additionalProperties:!1}}}}}}},body:F.object({accountId:F.string().meta({description:"The provider given account id for which to get the account info"})})},async e=>
106{let t=await e.context.internalAdapter.findAccount(e.body.accountId);if(!t||t.userId!==e.context.session.user.id)throw new ee("BAD_REQUEST",{message:"Account not found"});let r=e.context.socialProviders.find(e=>e.id===t.providerId);if(!r)throw new ee("INTERNAL_SERVER_ERROR",{message:`Provider account provider is ${t.providerId} but it is not configured`});let o=await n5({...e,body:{accountId:t.id,providerId:t.providerId},returnHeaders:!1});if(!o.accessToken)throw new ee("BAD_REQUEST",{message:"Access token not found"});let n=await r.getUserInfo({...o,accessToken:o.accessToken});return e.json(n)}),nV((e,t,r)=>{if(Array.isArray(e[t])&&Array.isArray(r))return e[t]=r,!0}),new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let e=Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};let n4=M({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]});n4.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]}),n4.newRole({user:[],session:[]});let n8=!1,n3={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},n9=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,n7={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},ie=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/,it={id:"redirect",name:"Redirect",hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&"undefined"!=typeof window&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}};var ir=e.i(884702);function io(e){var t,r;let{pluginPathMethods:o,pluginsActions:n,pluginsAtoms:i,$fetch:s,$store:a,atomListeners:c}=(e=>{var t;let r,o="credentials"in Request.prototype,n=function(e,t,r){let o,n;if(e)return rI(e,t);let i=z.BETTER_AUTH_URL||z.NEXT_PUBLIC_BETTER_AUTH_URL||z.PUBLIC_BETTER_AUTH_URL||z.NUXT_PUBLIC_BETTER_AUTH_URL||z.NUXT_PUBLIC_AUTH_URL||("/"!==z.BASE_URL?z.BASE_URL:void 0);if(i)return rI(i,t);return o&&n?rI(`${n}://${o}`,t):"undefined"!=typeof window&&window.location?rI(window.location.origin,t):void 0}(e?.baseURL,e?.basePath),i=e?.plugins?.flatMap(e=>e.fetchPlugins).filter(e=>void 0!==e)||[],s={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:a,onError:c,onRequest:d,onResponse:l,...u}=e?.fetchOptions||{},p=(t={baseURL:n,...o?{credentials:"include"}:{},method:"GET",jsonParser:e=>e?function(e,t={strict:!0}){return function(e,t={}){let{strict:r=!1,warnings:o=!1,reviver:n,parseDates:i=!0}=t;if("string"!=typeof e)return e;let s=e.trim();if('"'===s[0]&&s.endsWith('"')&&!s.slice(1,-1).includes('"'))return s.slice(1,-1);let a=s.toLowerCase();if(a.length<=9&&a in n7)return n7[a];if(!n9.test(s)){if(r)throw SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(n3).some(([e,t])=>{let r=t.test(s);return r&&o&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),r})&&r)throw Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(s,(e,t)=>{if("__proto__"===e||"constructor"===e&&t&&"object"==typeof t&&"prototype"in t){o&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(i&&"string"==typeof t){let e=function(e){let t=ie.exec(e);if(!t)return null;let[,r,o,n,i,s,a,c,d,l,u]=t,p=new Date(Date.UTC(parseInt(r,10),parseInt(o,10)-1,parseInt(n,10),parseInt(i,10),parseInt(s,10),parseInt(a,10),c?parseInt(c.padEnd(3,"0"),10):0));if(d){let e=(60*parseInt(l,10)+parseInt(u,10))*("+"===d?-1:1);p.setUTCMinutes(p.getUTCMinutes()+e)}
106return p instanceof Date&&!isNaN(p.getTime())?p:null}(t);if(e)return e}return n?n(e,t):t})}catch(t){if(r)throw t;return e}}(e,t)}(e,{strict:!1}):null,customFetchImpl:fetch,...u,plugins:[s,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[it],...i]},async function(e,r){let o,n=x(A(A({},t),r),{plugins:[...(null==t?void 0:t.plugins)||[],(o=t||{},{id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(e,t){var r,n,i,s;let a=(null==(n=null==(r=o.plugins)?void 0:r.find(t=>{var r;return null!=(r=t.schema)&&!!r.config&&(e.startsWith(t.schema.config.baseURL||"")||e.startsWith(t.schema.config.prefix||""))}))?void 0:n.schema)||o.schema;if(a){let r=e;(null==(i=a.config)?void 0:i.prefix)&&r.startsWith(a.config.prefix)&&(r=r.replace(a.config.prefix,""),a.config.baseURL&&(e=e.replace(a.config.prefix,a.config.baseURL))),(null==(s=a.config)?void 0:s.baseURL)&&r.startsWith(a.config.baseURL)&&(r=r.replace(a.config.baseURL,""));let o=a.schema[r];if(o){let r=x(A({},t),{method:o.method,output:o.output});return(null==t?void 0:t.disableValidation)||(r=x(A({},r),{body:o.input?await j(o.input,null==t?void 0:t.body):null==t?void 0:t.body,params:o.params?await j(o.params,null==t?void 0:t.params):null==t?void 0:t.params,query:o.query?await j(o.query,null==t?void 0:t.query):null==t?void 0:t.query})),{url:e,options:r}}}return{url:e,options:t}}})]});if(null==t?void 0:t.catchAllError)try{return await C(e,n)}catch(e){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:e}}}return await C(e,n)}),{$sessionSignal:f,session:m}={session:((e,t,r,o)=>{let n=h({data:null,error:null,isPending:!0,isRefetching:!1,refetch:e=>i(e)}),i=e=>{let i="function"==typeof o?o({data:n.get().data,error:n.get().error,isPending:n.get().isPending}):o;r(t,{...i,query:{...i?.query,...e?.query},async onSuccess(e){n.set({data:e.data,error:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch}),await i?.onSuccess?.(e)},async onError(e){let{request:t}=e,r="number"==typeof t.retry?t.retry:t.retry?.attempts,o=t.retryAttempt||0;r&&o<r||(n.set({error:e.error,data:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch}),await i?.onError?.(e))},async onRequest(e){let t=n.get();n.set({isPending:null===t.data,data:t.data,error:null,isRefetching:!0,refetch:n.value.refetch}),await i?.onRequest?.(e)}}).catch(e=>{n.set({error:e,data:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch})})};e=Array.isArray(e)?e:[e];let s=!1;for(let t of e)t.subscribe(()=>{B||(s?i():q(n,()=>(setTimeout(()=>{i()},0),s=!0,()=>{n.off(),t.off()})))});return n})(r=h(!1),"/get-session",p,{method:"GET"}),$sessionSignal:r},y=e?.plugins||[],g={},w={$sessionSignal:f,session:m},b={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},v=[{signal:"$sessionSignal",matcher:e=>"/sign-out"===e||"/update-user"===e||e.startsWith("/sign-in")||e.startsWith("/sign-up")||"/delete-user"===e||"/verify-email"===e}];for(let e of y)e.getAtoms&&Object.assign(w,e.getAtoms?.(p)),e.pathMethods&&Object.assign(b,e.pathMethods),e.atomListeners&&v.push(...e.atomListeners);let E={notify:e=>{w[e].set(!w[e].get())},listen:(e,t)=>{w[e].subscribe(t)},atoms:w};for(let t of y)t.getActions&&Object.assign(g,t.getActions?.(p,E,e));return{pluginsActions:g,pluginsAtoms:w,pluginPathMethods:b,atomListeners:v,$fetch:p,$store:E}})(e),d={};for(let[e,t]of Object.entries(i)){d[`use${(r=e).charAt(0).toUpperCase()+r.slice(1)}`]=()=>(function(e,t={}){let r=(0,ir.useRef)(e.get()),{keys:o,deps:n=[e,o]}=t,i=(0,ir.useCallback)(t=>{let n=e=>{r.current!==e&&(r.current=e,t())};if(n(e.value),o?.length){let t;return t=new Set(o).add(void 0),e.listen((e,r,o)=>{t.has(o)&&n(e,r,o)})}return e.listen(n)},n),s=()=>r.current;return(0,ir.useSyncExternalStore)(i,s,s)})(t)}return t={...n,...d,$fetch:s,$store:a},function e(r=[]){return new Proxy(function(){},{get(o,n){var i;if("then"===n||"catch"===n||"finally"===n)return;let s=[...r,n],a=t;for(let e of s)if(a&&"object"==typeof a&&e in a)a=a[e];else{a=void 0;break}return"function"==typeof a?a:"object"==typeof(i=a)&&null!==i&&"get"in i&&"function"==typeof i.get&&"lc"in i&&"number"==typeof i.lc?a:e(s)},apply:async(e,t,n)=>{let a="/"+r.map(e=>e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)).join("/"),d=n[0]||{},l=n[1]||{},{query:u,fetchOptions:p,...f}=d,h={...l,...p},m=function(e,t,r){let o=t[e],{fetchOptions:n,query:i,...s}=r||{};return o||(n?.method?n.method:s&&Object.keys(s).length>0?"POST":"GET")}(a,o,d);return await s(a,{...h,body:"GET"===m?void 0:{...f,...h?.body||{}},query:u||h?.query,method:m,async onSuccess(e){await h?.onSuccess?.(e);let t=c?.find(e=>e.matcher(a));if(!t)return;let r=i[t.signal];if(!r)return;let o=r.get();setTimeout(()=>{r.set(!o)},10)}})}})}()}function ii({minIntervalMs:e}){let t=new Map,r=0;return async(o,n)=>{let i,s;if(!e||!function(e,t){if("GET"!==((t?.method??(e instanceof Request?e.method:"GET"))?.toUpperCase?.()??"GET"))return!1;let r="string"==typeof e?e:e instanceof URL?e.toString():e.url;return new URL(r,window.location.origin).pathname.endsWith("/get-session")}(o,n))return fetch(o,n);
106let a=(i="string"==typeof o?o:o instanceof URL?o.toString():o.url,s=new URL(i,window.location.origin),`GET ${s.origin}${s.pathname}`),c=t.get(a);if(c)return c;let d=Date.now(),l=Math.max(0,r+e-d),u=(async()=>(l>0&&await new Promise(e=>setTimeout(e,l)),r=Date.now(),fetch(o,n)))().finally(()=>{t.delete(a)});return t.set(a,u),u}}let is=Number(d.env.NEXT_PUBLIC_AUTH_GET_SESSION_MIN_INTERVAL_MS)||2e3,ia=io({baseURL:d.env.NEXT_PUBLIC_APP_URL,fetchOptions:{retry:0,timeout:1e4,customFetchImpl:ii({minIntervalMs:is}),onError(e){d.env.NODE_ENV}}}),{useSession:ic,signIn:id,signUp:il,signOut:iu}=ia;function ip(){let e,t;return io({baseURL:d.env.NEXT_PUBLIC_APP_URL,plugins:(t=[],d.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID&&"true"===d.env.NEXT_PUBLIC_GOOGLE_ONE_TAP_ENABLED&&t.push((e={clientId:d.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,autoSelect:!1,cancelOnTapOutside:!1,context:"signin",additionalOptions:{use_fedcm_for_prompt:!0},promptOptions:{baseDelay:1e3,maxAttempts:1}},{id:"one-tap",getActions:(t,r)=>({oneTap:async(r,o)=>{if(n8)return void console.warn("A Google One Tap request is already in progress. Please wait.");n8=!0;try{if("undefined"==typeof window||!window.document)return void console.warn("Google One Tap is only available in browser environments");let{autoSelect:n,cancelOnTapOutside:i,context:s}=r??{},a=s??e.context??"signin";await new Promise(e=>{if(window.googleScriptInitialized)return void e();let t=document.createElement("script");t.src="https://accounts.google.com/gsi/client",t.async=!0,t.defer=!0,t.onload=()=>{window.googleScriptInitialized=!0,e()},document.head.appendChild(t)}),await new Promise((s,c)=>{let d=!1,l=e.promptOptions?.baseDelay??1e3,u=e.promptOptions?.maxAttempts??5;window.google?.accounts.id.initialize({client_id:e.clientId,callback:async e=>{d=!0;try{await t("/one-tap/callback",{method:"POST",body:{idToken:e.credential},...r?.fetchOptions,...o}),(!r?.fetchOptions&&!o||r?.callbackURL)&&(window.location.href=r?.callbackURL??"/"),s()}catch(e){console.error("Error during One Tap callback:",e),c(e)}}
106,auto_select:n,cancel_on_tap_outside:i,context:a,...e.additionalOptions});let p=e=>{d||window.google?.accounts.id.prompt(t=>{if(!d){if(t.isDismissedMoment&&t.isDismissedMoment())if(e<u){let t=Math.pow(2,e)*l;setTimeout(()=>p(e+1),t)}else r?.onPromptNotification?.(t);else if(t.isSkippedMoment&&t.isSkippedMoment())if(e<u){let t=Math.pow(2,e)*l;setTimeout(()=>p(e+1),t)}else r?.onPromptNotification?.(t)}})};p(0)})}catch(e){throw console.error("Error during Google One Tap flow:",e),e}finally{n8=!1}}}),getAtoms:e=>({})})),t),fetchOptions:{retry:0,timeout:1e4,customFetchImpl:ii({minIntervalMs:is}),onError(e){d.env.NODE_ENV}}})}e.s(["authClient",0,ia,"getAuthClient",()=>ip,"signIn",0,id,"signOut",0,iu,"signUp",0,il,"useSession",0,ic],400969)}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.