PageSourceSearch

https://rxresu.me/assets/client-C3V6Axks.js

js rxresu.me collected 2026-09-25 20:27:49 UTC 107,662 bytes, 3 lines download raw bytes

1import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{t}from"./react-DiVRNtpo.js";import{A as n,S as r,f as i}from"./schemas-jb9PpQOi.js";function a(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}var o=a({INVALID_METADATA_TYPE:`metadata must be an object or undefined`,REFILL_AMOUNT_AND_INTERVAL_REQUIRED:`refillAmount is required when refillInterval is provided`,REFILL_INTERVAL_AND_AMOUNT_REQUIRED:`refillInterval is required when refillAmount is provided`,USER_BANNED:`User is banned`,UNAUTHORIZED_SESSION:`Unauthorized or invalid session`,KEY_NOT_FOUND:`API Key not found`,KEY_DISABLED:`API Key is disabled`,KEY_EXPIRED:`API Key has expired`,USAGE_EXCEEDED:`API Key has reached its usage limit`,KEY_NOT_RECOVERABLE:`API Key is not recoverable`,EXPIRES_IN_IS_TOO_SMALL:`The expiresIn is smaller than the predefined minimum value.`,EXPIRES_IN_IS_TOO_LARGE:`The expiresIn is larger than the predefined maximum value.`,INVALID_REMAINING:`The remaining count is either too large or too small.`,INVALID_PREFIX_LENGTH:`The prefix length is either too large or too small.`,INVALID_NAME_LENGTH:`The name length is either too large or too small.`,METADATA_DISABLED:`Metadata is disabled.`,RATE_LIMIT_EXCEEDED:`Rate limit exceeded.`,NO_VALUES_TO_UPDATE:`No values to update.`,KEY_DISABLED_EXPIRATION:`Custom key expiration values are disabled.`,INVALID_API_KEY:`Invalid API key.`,INVALID_USER_ID_FROM_API_KEY:`The user id from the API key is invalid.`,INVALID_REFERENCE_ID_FROM_API_KEY:`The reference id from the API key is invalid.`,INVALID_API_KEY_GETTER_RETURN_TYPE:`API Key getter returned an invalid key type. Expected string.`,SERVER_ONLY_PROPERTY:`The property you're trying to set can only be set from the server auth instance only.`,FAILED_TO_UPDATE_API_KEY:`Failed to update API key`,NAME_REQUIRED:`API Key name is required.`,ORGANIZATION_ID_REQUIRED:`Organization ID is required for organization-owned API keys.`,USER_NOT_MEMBER_OF_ORGANIZATION:`You are not a member of the organization that owns this API key.`,INSUFFICIENT_API_KEY_PERMISSIONS:`You do not have permission to perform this action on organization API keys.`,NO_DEFAULT_API_KEY_CONFIGURATION_FOUND:`No default api-key configuration found.`,ORGANIZATION_PLUGIN_REQUIRED:`Organization plugin is required for organization-owned API keys. Please install and configure the organization plugin.`}),s=`1.7.5`,c=()=>({id:`api-key`,version:s,$InferServerPlugin:{},pathMethods:{"/api-key/create":`POST`,"/api-key/delete":`POST`,"/api-key/delete-all-expired-api-keys":`POST`},$ERROR_CODES:o}),l=Object.create(null),u=e=>({}),d=new Proxy(l,{get(e,t){return u()[t]??l[t]},has(e,t){return t in u()||t in l},set(e,t,n){let r=u(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;let n=u(!0);return delete n[t],!0},ownKeys(){let e=u(!0);return Object.keys(e)}});d.NODE_ENV;function f(e,t){return typeof process<`u`?{}[e]??t:typeof Deno<`u`?Deno.env.get(e)??t:typeof Bun<`u`?Bun.env[e]??t:t}Object.freeze({get BETTER_AUTH_SECRET(){return f(`BETTER_AUTH_SECRET`)},get AUTH_SECRET(){return f(`AUTH_SECRET`)},get BETTER_AUTH_TELEMETRY(){return f(`BETTER_AUTH_TELEMETRY`)},get BETTER_AUTH_TELEMETRY_ID(){return f(`BETTER_AUTH_TELEMETRY_ID`)},get NODE_ENV(){return f(`NODE_ENV`,`development`)},get PACKAGE_VERSION(){return f(`PACKAGE_VERSION`,`0.0.0`)},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return f(`BETTER_AUTH_TELEMETRY_ENDPOINT`,``)}});var p=1,m=4,h=8,g=24,_={eterm:m,cons25:m,console:m,cygwin:m,dtterm:m,gnome:m,hurd:m,jfbterm:m,konsole:m,kterm:m,mlterm:m,mosh:g,putty:m,st:m,"rxvt-unicode-24bit":g,terminator:g,"xterm-kitty":g},v=new Map(Object.entries({APPVEYOR:h,BUILDKITE:h,CIRCLECI:g,DRONE:h,GITEA_ACTIONS:g,GITHUB_ACTIONS:g,GITLAB_CI:h,TRAVIS:h})),y=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function b(){if(f(`FORCE_COLOR`)!==void 0)switch(f(`FORCE_COLOR`)){case``:case`1`:case`true`:return m;case`2`:return h;case`3`:return g;default:return p}if(f(`NODE_DISABLE_COLORS`)!==void 0&&f(`NODE_DISABLE_COLORS`)!==``||f(`NO_COLOR`)!==void 0&&f(`NO_COLOR`)!==``||f(`TERM`)===`dumb`)return p;if(f(`TMUX`))return g;if(`TF_BUILD`in d&&`AGENT_NAME`in d)return m;if(`CI`in d){for(let{0:e,1:t}of v)if(e in d)return t;return f(`CI_NAME`)===`codeship`?h:p}if(`TEAMCITY_VERSION`in d)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(f(`TEAMCITY_VERSION`))===null?p:m;switch(f(`TERM_PROGRAM`)){case`iTerm.app`:return!f(`TERM_PROGRAM_VERSION`)||/^[0-2]\./.exec(f(`TERM_PROGRAM_VERSION`))!==null?h:g;case`HyperTerm`:case`MacTerm`:return g;case`Apple_Terminal`:return h}if(f(`COLORTERM`)===`truecolor`||f(`COLORTERM`)===`24bit`)return g;if(f(`TERM`)){if(/truecolor/.exec(f(`TERM`))!==null)return g;if(/^xterm-256/.exec(f(`TERM`))!==null)return h;let e=f(`TERM`).toLowerCase();if(_[e])return _[e];if(y.some(t=>t.exec(e)!==null))return m}return f(`COLORTERM`)?m:p}var x=Symbol.for(`better-auth:global`),S=null,ee={},C=`1.7.5`;function te(){return globalThis[x]||(globalThis[x]={version:C,epoch:1,context:ee},S=globalThis[x]),S=globalThis[x],S.version!==C&&(S.version=C,S.epoch++),globalThis[x]}function ne(){return te().context.endpointContextAsyncStorage?.getStore()}var w={reset:`\x1B[0m`,bright:`\x1B[1m`,dim:`\x1B[2m`,undim:`\x1B[22m`,underscore:`\x1B[4m`,blink:`\x1B[5m`,reverse:`\x1B[7m`,hidden:`\x1B[8m`,fg:{black:`\x1B[30m`,red:`\x1B[31m`,green:`\x1B[32m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,magenta:`\x1B[35m`,cyan:`\x1B[36m`,white:`\x1B[37m`},bg:{black:`\x1B[40m`,red:`\x1B[41m`,green:`\x1B[42m`,yellow:`\x1B[43m`,blue:`\x1B[44m`,magenta:`\x1B[45m`,cyan:`\x1B[46m`,white:`\x1B[47m`}},re=[`debug`,`info`,`success`,`warn`,`error`];function ie(e,t){return re.indexOf(t)>=re.indexOf(e)}var ae={info:w.fg.blue,success:w.fg.green,warn:w.fg.yellow,error:w.fg.red,debug:w.fg.magenta},oe=(e,t,n)=>{let r=new Date().toISOString();return n?`${w.dim}${r}${w.reset} ${ae[e]}${e.toUpperCase()}${w.reset} ${w.bright}[Better Auth]:${w.reset} ${t}`:`${r} ${e.toUpperCase()} [Better Auth]: ${t}`},se=(e=>{let t=e?.disabled!==!0,n=e?.level??`warn`,r=e?.disableColors===void 0?b()!==1:!e.disableColors,i=(i,a,o=[])=>{if(!t||!ie(n,i))return;let s=oe(i,a,r);if(!e||typeof e.log!=`function`){i===`error`?console.error(s,...o):i===`warn`?console.warn(s,...o):console.log(s,...o);return}e.log(i===`success`?`info`:i,a,...o)};return{...Object.fromEntries(re.map(e=>[e,(...[t,...n])=>i(e,t,n)])),get level(){return n}}})(),T=()=>{let e=ne()?.context.logger;return e&&e!==ce?e:se},ce={debug:(...e)=>T().debug(...e),info:(...e)=>T().info(...e),success:(...e)=>T().success(...e),warn:(...e)=>T().warn(...e),error:(...e)=>T().error(...e),get level(){return T().level}}
1,le=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},ue=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let t=await i.init?.call(i,e.toString(),n);n=t.options||n,e=t.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},de=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}},fe=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)}};function pe(e){if(typeof e==`number`)return new de({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new de(e);case`exponential`:return new fe(e);default:throw Error(`Invalid retry strategy`)}}var me=[`get`,`post`,`put`,`patch`,`delete`];function he(e){if(!e.startsWith(`@`))return{method:void 0,path:e};let t=e.indexOf(`/`),n=e.slice(1,t===-1?void 0:t);return me.includes(n)?{method:n,path:t===-1?e:e.slice(t+1)}:{method:void 0,path:e}}var ge=e=>e===`.`||e===`..`,_e=e=>e.split(`:`).map(e=>encodeURIComponent(e)).join(`:`);function ve(e,t){let n=t.get(e);if(n===void 0)return _e(e);if(ge(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function ye(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``,{path:o}=he(e);o!==e&&(e=`/${o}`),a.endsWith(`/`)||(a+=`/`);let[s,c]=e.replace(a,``).split(`?`),l=new URLSearchParams(c);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)l.append(e,n);continue}else n=JSON.stringify(t);l.set(e,n)}let u=new Map;if(r){if(Array.isArray(r)){let e=s.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];u.set(n,String(e))}}else for(let[e,t]of Object.entries(r))u.set(`:${e}`,String(t))}s=s.split(`/`).map(e=>ve(e,u)).join(`/`),s=s.replace(/^\/+/,``);let d=l.toString();return d=d.length>0?`?${d}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${s}${d}`,a):`${a}${s}${d}`}var be=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},xe=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Se(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return xe.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function Ce(e){try{return JSON.parse(e),!0}catch{return!1}}function we(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function Te(e){try{return JSON.parse(e)}catch{return e}}function Ee(e){return typeof e==`function`}function De(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&Ee(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&Ee(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function Oe(...e){let t={};for(let n of e)if(n){if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}}return t}async function ke(e){let t=new Headers(Oe(e?.headers,await be(e)));if(!t.has(`content-type`)){let n=Ae(e?.body);n&&t.set(`content-type`,n)}return t}function Ae(e){return we(e)?`application/json`:null}function je(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function Me(e,t){let{body:n}=e;return n?!we(n)||typeof n==`string`?n:je(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function Ne(e,t){if(t?.method)return t.method.toUpperCase();let{method:n}=he(e);return n?n.toUpperCase():t?.body?`POST`:`GET`}function Pe(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}
1var Fe=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function Ie(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new Fe(n.issues);return n.value}function Le(e){"@babel/helpers - typeof";return Le=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},Le(e)}function Re(e,t){if(Le(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Le(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ze(e){var t=Re(e,`string`);return Le(t)==`symbol`?t:t+``}function Be(e,t,n){return(t=ze(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ve(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function E(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Ve(Object(n),!0).forEach(function(t){Be(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Ve(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var He=async(e,t)=>{var n;let{hooks:r,url:i,options:a}=await ue(e,t),o=De(a),s=new AbortController,c=a.signal??s.signal,l=ye(i,a),u=await ke(a),d=Me(a,u),f=Ne(i,a),p=E(E({},a),{},{url:l,headers:u,body:d,method:f,signal:c});for(let e of r.onRequest)if(e){let t=await e(p);typeof t==`object`&&t&&Object.assign(p,t)}(`pipeTo`in p&&typeof p.pipeTo==`function`||typeof(t==null||(n=t.body)==null?void 0:n.pipe)==`function`)&&(`duplex`in p||(p.duplex=`half`));let{clearTimeout:m}=Pe(a,s),h=await o(p.url,p);m();let g={response:h,request:p};for(let e of r.onResponse)if(e){var _;let n=await e(E(E({},g),{},{response:t!=null&&(_=t.hookOptions)!=null&&_.cloneResponse?h.clone():h}));n instanceof Response?h=n:typeof n==`object`&&n&&(h=n.response)}if(h.ok){if(p.method===`HEAD`)return{data:``,error:null};let e=Se(h),n={data:null,response:h,request:p};if(e===`json`||e===`text`){let e=await h.text();n.data=await(p.jsonParser??Te)(e)}else n.data=await h[e]();p?.output&&p.output&&!p.disableValidation&&(n.data=await Ie(p.output,n.data));for(let e of r.onSuccess)if(e){var v;await e(E(E({},n),{},{response:t!=null&&(v=t.hookOptions)!=null&&v.cloneResponse?h.clone():h}))}return t?.throw?n.data:{data:n.data,error:null}}let y=t?.jsonParser??Te,b=await h.text(),x=Ce(b),S=x?await y(b):null,ee={response:h,responseText:b,request:p,error:E(E({},S),{},{status:h.status,statusText:h.statusText})};for(let e of r.onError)if(e){var C;await e(E(E({},ee),{},{response:t!=null&&(C=t.hookOptions)!=null&&C.cloneResponse?h.clone():h}))}if(t?.retry){let n=pe(t.retry),i=t.retryAttempt??0;if(await n.shouldAttemptRetry(i,h)){for(let e of r.onRetry)e&&await e(g);let a=n.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await He(e,E(E({},t),{},{retryAttempt:i+1}))}}if(t?.throw)throw new le(h.status,h.statusText,x?S:b);return{data:null,error:E(E({},S),{},{status:h.status,statusText:h.statusText})}},Ue=e=>({id:`apply-schema`,name:`Apply Schema`,version:`1.0.0`,async init(t,n){var r;let i=E(E({},n),e.query!==void 0&&{query:E(E({},e.query),n?.query)}),a=((r=e.plugins)==null||(r=r.find(e=>e.schema?.config?t.startsWith(e.schema.config.baseURL||``)||t.startsWith(e.schema.config.prefix||``):!1))==null?void 0:r.schema)||e.schema;if(a){let r=t;a.config?.prefix&&r.startsWith(a.config.prefix)&&(r=r.replace(a.config.prefix,``),a.config.baseURL&&(t=t.replace(a.config.prefix,a.config.baseURL))),a.config?.baseURL&&r.startsWith(a.config.baseURL)&&(r=r.replace(a.config.baseURL,``)),r.startsWith(`/`)&&r.charAt(1)===`@`&&(r=r.substring(1));let o=a.schema[r];if(o){let{method:a,path:s}=he(r);
1a&&(t=t.slice(0,t.length-r.length)+s);let c=n?.headers;if(o.headers&&!n?.disableValidation){let e={};if(n?.headers){if(n.headers instanceof Headers)n.headers.forEach((t,n)=>{e[n.toLowerCase()]=t});else if(typeof n.headers==`object`)for(let[t,r]of Object.entries(n.headers))r!=null&&(e[t.toLowerCase()]=r)}let t=await Ie(o.headers,e),r={};for(let[e,n]of Object.entries(t))r[e.toLowerCase()]=n;c=r}let l=o.method??a;if(i=E(E(E(E({},i),l!==void 0&&{method:l}),o.output!==void 0&&{output:o.output}),c!==void 0&&{headers:c}),!n?.disableValidation){if(o.query&&(i.query=await Ie(o.query,n?.query),i.query!==null&&typeof i.query==`object`)){let t=E({},e.query);for(let e of Object.keys(t))n?.query&&Object.prototype.hasOwnProperty.call(n.query,e)&&(t[e]=n.query[e]);i.query=E(E({},t),i.query)}i=E(E({},i),{},{body:o.input?await Ie(o.input,n?.body):n?.body,params:o.params?await Ie(o.params,n?.params):n?.params})}return{url:t,options:i}}}return E({url:t},(n!==void 0||e.query!==void 0)&&{options:i})}}),We=e=>{async function t(t,n){let r=E(E(E({},e),n),{},{headers:Oe(e?.headers,n?.headers),plugins:[...e?.plugins||[],Ue(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await He(t,r)}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 He(t,r)}return t};function Ge(e,t){return e.userId||t?.resolveUserId?.({userId:e.userId,user:e.user,session:e.session})||e.user?.id||e.session?.user?.id||void 0}var Ke=e=>({id:`dash`,getActions:(t,n,r)=>({dash:{getAuditLogs:async(n={})=>{let r=Ge(n,e);return t(`/events/audit-logs`,{method:`GET`,query:{limit:n.limit,offset:n.offset,organizationId:n.organizationId,identifier:n.identifier,eventType:n.eventType,userId:r}})},getAllAuditLogs:async(e={})=>t(`/events/all-audit-logs`,{method:`GET`,query:{limit:e.limit,offset:e.offset,organizationId:e.organizationId,userId:e.userId,eventType:e.eventType,identifier:e.identifier}})}}),pathMethods:{"/events/audit-logs":`GET`,"/events/all-audit-logs":`GET`}}),qe=`ba_param`;function Je(e){let t=e.getAll(qe);if(t.length)return new Set(t)}function Ye(e){let t=new URLSearchParams(e);if(!t.has(`sig`))return;let n=Je(t);if(!n)return;let r=new URLSearchParams;for(let[e,i]of t.entries())(e===`sig`||e===qe||n.has(e))&&r.append(e,i);return r.toString()}var Xe=`1.7.5`,Ze=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;function Qe(e){if(typeof e==`string`&&Ze.test(e)){let t=new Date(e);if(!isNaN(t.getTime()))return t}return e}function $e(e){if(e==null)return e;if(typeof e==`string`)return Qe(e);if(e instanceof Date)return e;if(Array.isArray(e))return e.map($e);if(typeof e==`object`){let t={};for(let n of Object.keys(e))t[n]=$e(e[n]);return t}return e}function et(e){try{return typeof e==`string`?JSON.parse(e,(e,t)=>Qe(t)):e==null?null:$e(e)}catch(e){return ce.error(`Error parsing JSON`,{error:e}),null}}var tt=`1.7.5`,nt=e=>({id:`additional-fields-client`,version:tt,$InferServerPlugin:{}}),rt=a({FAILED_TO_CREATE_USER:`Failed to create user`,USER_ALREADY_EXISTS:`User already exists.`,USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:`User already exists. Use another email.`,YOU_CANNOT_BAN_YOURSELF:`You cannot ban yourself`,YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE:`You are not allowed to change users role`,YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS:`You are not allowed to create users`,YOU_ARE_NOT_ALLOWED_TO_LIST_USERS:`You are not allowed to list users`,YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS:`You are not allowed to list users sessions`,YOU_ARE_NOT_ALLOWED_TO_BAN_USERS:`You are not allowed to ban users`,YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS:`You are not allowed to impersonate users`,YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS:`You are not allowed to revoke users sessions`,YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS:`You are not allowed to delete users`,YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD:`You are not allowed to set users password`,BANNED_USER:`You have been banned from this application`,YOU_ARE_NOT_ALLOWED_TO_GET_USER:`You are not allowed to get user`,NO_DATA_TO_UPDATE:`No data to update`,YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS:`You are not allowed to update users`,YOU_CANNOT_REMOVE_YOURSELF:`You cannot remove yourself`,YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE:`You are not allowed to set a non-existent role value`,YOU_CANNOT_IMPERSONATE_ADMINS:`You cannot impersonate admins`,INVALID_ROLE_TYPE:`Invalid role type`,YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL:`You are not allowed to update users email`,PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER:`Password cannot be updated through update-user. Use the set-user-password endpoint instead`});function it(){let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,`writable`)?e.writable:e.set!==void 0}function at(e){let t=e.split(`
2    at `);return t.length<=1?e:(t.splice(1,1),t.join(`
3    at `))}
3function ot(e,t){class n extends e{#e;constructor(...e){if(it()){let t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);let t=Error().stack;t&&(this.#e=at(t.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(n.prototype,"constructor",{get(){return t},enumerable:!1,configurable:!0}),n}var st={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},ct=class extends Error{status;body;headers;statusCode;constructor(e=`INTERNAL_SERVER_ERROR`,t=void 0,n={},r=typeof e==`number`?e:st[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=n,this.statusCode=r,this.name=`APIError`,this.status=e,this.headers=n,this.statusCode=r,this.body=t}},lt=class extends ct{message;issues;constructor(e,t){super(400,{message:e,code:`VALIDATION_ERROR`}),this.message=e,this.issues=t,this.issues=t}},ut=class extends Error{constructor(e){super(e),this.name=`BetterCallError`}},dt=Symbol.for(`better-call:api-error-headers`),D=ot(ct,Error),O=class extends Error{constructor(e,t){super(e,t),this.name=`BetterAuthError`,this.message=e,this.stack=``}},ft=class e extends D{constructor(...e){super(...e)}static fromStatus(t,n){return new e(t,n)}static from(t,n){return new e(t,{message:n.message,code:n.code})}};function pt(e){return{success:!1,error:`You are not allowed to access resource: ${e}`}}function mt(e){return{success:!1,error:`unauthorized to access resource "${e}"`}}function ht(e){return e===`OR`?`OR`:`AND`}function gt(e){return Array.isArray(e)}function _t(e){if(gt(e))return{actions:e,connector:`AND`};if(!e||typeof e!=`object`)throw new O(`Invalid access control request`);let{actions:t,connector:n}=e;return gt(t)?{actions:t,connector:ht(n)}:{actions:[],connector:ht(n)}}function vt(e,t){return typeof t==`string`&&e.includes(t)}function yt(e,{actions:t,connector:n}){return t.length===0?!1:n===`OR`?t.some(t=>vt(e,t)):t.every(t=>vt(e,t))}function bt(e){return{authorize(t,n=`AND`){let r=!1;for(let[i,a]of Object.entries(t)){let t=e[i];if(!t){if(n===`AND`)return pt(i);continue}let o=yt(t,_t(a));if(o&&(r=!0),o&&n===`OR`)return{success:!0};if(!o&&n===`AND`)return mt(i)}return r?{success:!0}:{success:!1,error:`Not authorized`}},statements:e}}function xt(e){return{newRole(e){return bt(e)},statements:e}}var St=xt({user:[`create`,`list`,`set-role`,`ban`,`impersonate`,`impersonate-admins`,`delete`,`set-password`,`set-email`,`get`,`update`],session:[`list`,`revoke`,`delete`]}),Ct=St.newRole({user:[`create`,`list`,`set-role`,`ban`,`impersonate`,`delete`,`set-password`,`set-email`,`get`,`update`],session:[`list`,`revoke`,`delete`]}),wt=St.newRole({user:[],session:[]}),Tt={admin:Ct,user:wt},Et=e=>{if(e.userId&&e.options?.adminUserIds?.includes(e.userId))return!0;if(!e.permissions)return!1;let t=(e.role||e.options?.defaultRole||`user`).split(`,`),n=e.options?.roles||Tt;for(let r of t)if(n[r]?.authorize(e.permissions)?.success)return!0;return!1},Dt=e=>{let t={admin:Ct,user:wt,...e?.roles};return{id:`admin-client`,version:tt,$InferServerPlugin:{},getActions:()=>({admin:{checkRolePermission:n=>Et({role:n.role,options:{ac:e?.ac,roles:t},permissions:n.permissions})}}),pathMethods:{"/admin/list-users":`GET`,"/admin/impersonate-user":`POST`,"/admin/stop-impersonating":`POST`},atomListeners:[{matcher:e=>e===`/admin/impersonate-user`||e===`/admin/stop-impersonating`,signal:`$sessionSignal`}],$ERROR_CODES:rt}},Ot=47;function kt(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===Ot;)t--;return t===e.length?e:e.slice(0,t)}function At(e){try{return(kt(new URL(e).pathname)||`/`)!==`/`}catch{throw new O(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function jt(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new O(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof O?t:new O(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function k(e,t=`/api/auth`){if(jt(e),At(e))return e;let n=kt(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function Mt(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function Nt(e,t,n,r,i){if(e)return k(e,t);if(r!==!1){let e=d.BETTER_AUTH_URL||d.NEXT_PUBLIC_BETTER_AUTH_URL||d.PUBLIC_BETTER_AUTH_URL||d.NUXT_PUBLIC_BETTER_AUTH_URL||d.NUXT_PUBLIC_AUTH_URL||(d.BASE_URL===`/`?void 0:d.BASE_URL);if(e)return k(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&Mt(o,`proto`)&&Mt(a,`host`))try{return k(`${o}://${a}`,t)}catch{}if(n){let e=Pt(n.url);if(!e)throw new O(`Could not get origin from request. Please provide a valid base URL.`);return k(e,t)}if(typeof window<`u`&&window.location)return k(window.location.origin,t)}function Pt(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}var Ft=[`javascript:`,`data:`,`vbscript:`];function It(e){let t;try{t=new URL(e)}catch{return!0}return!Ft.includes(t.protocol)}var A=[],j=0,Lt=null,Rt=4,zt=globalThis.nanostoresGlobal||={epoch:0},Bt=()=>{let e,t;for(;j<A.length;){t=j,j+=Rt;try{A[t](A[t+1].value,A[t+2],A[t+3])}catch(t){e=t}}if(A.length=j=0,e)throw e},Vt=e=>{let t=[],n={eq:Object.is,get(){return n.lc||n.listen(()=>{})(),n.value},init:e,lc:0,listen(e){return n.lc=t.push(e),()=>{for(let t=j;t<A.length;)A[t]===e?A.splice(t,Rt):t+=Rt;let r=t.indexOf(e);~r&&(t.splice(r,1),--n.lc||n.off())}},notify(e,r){zt.epoch++;let i=!A.length&&!0;for(let i of t)Lt?.has(i)||(Lt?.add(i),A.push(i,n,e,r));i&&Bt()},off(){},set(e){let t=n.value;n.eq(t,e)||(n.value=e,n.notify(t))},subscribe(e){let t=n.listen(e);return e(n.value),t},value:e};return n},Ht=2,Ut=5,Wt=6,Gt=10,Kt=(e,t,n,r)=>(e.events=e.events||{},e.events[n+Gt]||(e.events[n+Gt]=r(t=>{e.events[n].reduceRight((e,t)=>(t(e),e),{shared:{},...t})})),e.events[n]=e.events[n]||[],e.events[n].push(t),()=>{let r=e.events[n],i=r.indexOf(t);~i&&(r.splice(i,1),r.length||(e.events[n+Gt](),delete e.events[n+Gt]))}),qt=(e,t)=>Kt(e,t,Ht,t=>{let n=e.set,r=e.setKey;return e.setKey&&=(n,i)=>{let a;if(t({abort:()=>{a=!0},changed:n,newValue:{...e.value,[n]:i}}),!a)return r(n,i)},e.set=e=>{let r;if(t({abort:()=>{r=!0},newValue:e}),!r)return n(e)},()=>{e.set=n,e.setKey=r}}),Jt=1e3,Yt=(e,t)=>Kt(e,n=>{let r=t(n);r&&e.events[Wt].push(r)},Ut,t=>{let n=e.listen;e.listen=(...r)=>(!e.lc&&!e.active&&(e.active=!0,t()),n(...r));let r=e.off;return e.events[Wt]=[],e.off=()=>{r(),setTimeout(()=>
3{if(e.active&&!e.lc){e.active=!1;for(let t of e.events[Wt])t();e.events[Wt]=[]}},Jt)},()=>{e.listen=n,e.off=r}});function Xt(e,t){let n=Qt(t),r=e;for(let e of n){if(r==null)return;r=r[e]}return r}var Zt=/(.*)\[(\d+)\]/;function Qt(e){return e.split(`.`).flatMap(e=>$t(e))}function $t(e){if(Zt.test(e)){let[,t,n]=e.match(Zt);return[...$t(t),n]}return[e]}function en(e,t,n){let r=new Set(t);return e.listen((e,i,a)=>{(a===void 0?t.some(t=>i===void 0||e[t]!==i[t]||Xt(e,t)!==Xt(i,t)):r.has(a)||r.has(a.split(/\.|\[/)[0]))&&n(e,i,a)})}function tn(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function M(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!M(e[n],t[n]))return!1;return!0}if(tn(e)&&tn(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!(r in t)||!M(e[r],t[r]))return!1;return!0}return!1}function nn(e,t){return qt(e,({newValue:n,abort:r})=>{t(e.value,n)&&r()})}var rn=()=>typeof window>`u`;function an(e,t){return M(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}var on=(e,t,n,r)=>{let i=Vt({data:null,error:null,isPending:!0,isRefetching:!1,refetch:e=>a(e)});Yt(i,()=>nn(i,an));let a=async e=>new Promise(a=>{let o=typeof r==`function`?r({data:i.get().data,error:i.get().error,isPending:i.get().isPending}):r;n(t,{...o,query:{...o?.query,...e?.query},async onSuccess(e){let t=i.get(),n=t.data!=null&&e.data!=null&&M(t.data,e.data)?t.data:e.data;i.set({data:n,error:null,isPending:!1,isRefetching:!1,refetch:i.value.refetch}),await o?.onSuccess?.(e)},async onError(e){let{request:t}=e,n=typeof t.retry==`number`?t.retry:t.retry?.attempts,r=t.retryAttempt||0;if(n&&r<n)return;let a=e.error.status===401;i.set({error:e.error,data:a?null:i.get().data,isPending:!1,isRefetching:!1,refetch:i.value.refetch}),await o?.onError?.(e)},async onRequest(e){let t=i.get();i.set({isPending:t.data===null,data:t.data,error:null,isRefetching:!0,refetch:i.value.refetch}),await o?.onRequest?.(e)}}).catch(e=>{i.set({error:e,data:i.get().data,isPending:!1,isRefetching:!1,refetch:i.value.refetch})}).finally(()=>{a(void 0)})});e=Array.isArray(e)?e:[e];let o=!1,s=!1,c=!1,l=()=>{if(o){c=!0;return}o=!0,a().finally(()=>{o=!1;let e=c&&s;c=!1,e&&l()})};return Yt(i,()=>{if(rn())return;s=!0;let t=!1,n,r=e.map(e=>e.listen(()=>{t?a():(t=!0,clearTimeout(n),l())}));return n=setTimeout(()=>{t=!0,l()},0),()=>{s=!1;for(let e of r)e();clearTimeout(n)}}),i},sn=a({OTP_NOT_ENABLED:`OTP not enabled`,OTP_NOT_CONFIGURED:`OTP is not available`,OTP_HAS_EXPIRED:`OTP has expired`,TOTP_NOT_ENABLED:`TOTP not enabled`,TOTP_ALREADY_ENABLED:`TOTP is already enabled`,TOTP_NOT_CONFIGURED:`TOTP is not available`,TWO_FACTOR_NOT_ENABLED:`Two factor isn't enabled`,BACKUP_CODES_NOT_ENABLED:`Backup codes aren't enabled`,INVALID_BACKUP_CODE:`Invalid backup code`,INVALID_CODE:`Invalid code`,TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:`Too many attempts. Please request a new code.`,ACCOUNT_TEMPORARILY_LOCKED:`Too many failed verification attempts. Your account is temporarily locked. Please try again later.`,INVALID_TWO_FACTOR_COOKIE:`Invalid two factor cookie`}),cn=e=>({id:`two-factor`,version:tt,$InferServerPlugin:{},atomListeners:[{matcher:e=>e.startsWith(`/two-factor/`),signal:`$sessionSignal`}],pathMethods:{"/two-factor/disable":`POST`,"/two-factor/enable":`POST`,"/two-factor/send-otp":`POST`,"/two-factor/generate-backup-codes":`POST`,"/two-factor/get-totp-uri":`POST`,"/two-factor/verify-totp":`POST`,"/two-factor/verify-otp":`POST`,"/two-factor/verify-backup-code":`POST`},fetchPlugins:[{id:`two-factor`,name:`two-factor`,hooks:{async onSuccess(t){if(t.data?.twoFactorRedirect){if(e?.onTwoFactorRedirect){await e.onTwoFactorRedirect({twoFactorMethods:t.data.twoFactorMethods});return}e?.twoFactorPage&&typeof window<`u`&&It(e.twoFactorPage)&&(window.location.href=e.twoFactorPage)}}}}],$ERROR_CODES:sn}),ln=a({INVALID_USERNAME_OR_PASSWORD:`Invalid username or password`,EMAIL_NOT_VERIFIED:`Email not verified`,UNEXPECTED_ERROR:`Unexpected error`,USERNAME_IS_ALREADY_TAKEN:`Username is already taken. Please try another.`,USERNAME_TOO_SHORT:`Username is too short`,USERNAME_TOO_LONG:`Username is too long`,INVALID_USERNAME:`Username is invali
3d`,INVALID_DISPLAY_USERNAME:`Display username is invalid`,USERNAME_IS_IMMUTABLE:`Username cannot be updated`}),un=e=>({id:`username`,version:tt,$InferServerPlugin:{},atomListeners:[{matcher:e=>e===`/sign-in/username`,signal:`$sessionSignal`}],$ERROR_CODES:ln}),dn=()=>({id:`oauth-provider-client`,version:Xe,fetchPlugins:[{id:`oauth-provider-signin`,name:`oauth-provider-signin`,description:`Adds the current page query to oauth requests`,hooks:{async onRequest(e){let t=e.headers,n=typeof e.body==`string`?t.get(`content-type`)===`application/x-www-form-urlencoded`?Object.fromEntries(new URLSearchParams(e.body)):et(e.body??`{}`):e.body;n?.oauth_query||typeof window<`u`&&window?.location?.search&&e.method!==`GET`&&e.method!==`DELETE`&&(e.body=JSON.stringify({...n,oauth_query:Ye(window.location.search)}))}}}],$InferServerPlugin:{}}),fn=new TextEncoder,pn=new TextDecoder,mn=new TextDecoder(`utf-8`,{fatal:!0});function hn(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var gn=/[^\x00-\x7f]/;function N(e){if(typeof e==`string`&&e.length>=128){if(gn.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return fn.encode(e)}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function _n(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?`base64url`:`base64`,omitPadding:t});let n=32768,r=[];for(let t=0;t<e.length;t+=n)r.push(String.fromCharCode.apply(null,e.subarray(t,t+n)));let i=btoa(r.join(``));return t?i.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`):i}function vn(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?`base64url`:`base64`});if(t){if(e.includes(`+`)||e.includes(`/`))throw TypeError(`Invalid base64url`);e=e.replace(/-/g,`+`).replace(/_/g,`/`)}let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}async function yn(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}var P=class 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)}},F=class extends P{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},bn=class extends P{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},xn=class extends P{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},I=class extends P{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},L=class extends P{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},R=class extends P{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},Sn=class extends P{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},Cn=class extends P{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},wn=class extends P{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)}},Tn=class extends P{[Symbol.asyncIterator]=async function*(){};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)}},En=class extends P{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},Dn=class extends P{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}},On=`The input to be decoded is not correctly encoded.`;function kn(e){try{return vn(typeof e==`string`?e:pn.decode(e),!0)}catch(e){throw TypeError(On,{cause:e})}}function z(e){return _n(typeof e==`string`?fn.encode(e):e,!0)}function B(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function An(e){return B(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(B)}function jn(...e){let t=new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}function Mn(e,t,n){try{return kn(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function Nn(e,t,n){try{return N(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function Pn(e,t,n){let r;try{r=JSON.parse(mn.decode(kn(e)))}catch{throw new t(n)}if(!B(r))throw new t(n);return r}var Fn={__proto__:null,b64:!0};function In(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}
3" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function Ln(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new I(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function Rn(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new L(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}var zn=e=>e[Symbol.toStringTag],Bn=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function Vn(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(B(t)){if(o=tr(t),typeof o.kty!=`string`)throw Yn(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(Bn(e,o,n),o.kty===`oct`)return kn(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Kn(t))throw Yn(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${zn(t)} instances must be of type "${e}" for the ${r} algorithm`);if(Wn(t))return t;if(s=t,s.type===`secret`)return s.export()}Hn||=new WeakMap;let c=t,l=Hn.get(c);if(l?.[r])return l[r];if(l||Hn.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Un[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await rr(e,o)}var Hn,Un={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},Wn=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Gn=e=>e?.[Symbol.toStringTag]===`KeyObject`,Kn=e=>Wn(e)||Gn(e);function qn(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Jn=(e,...t)=>qn(`Key must be `,e,...t);function Yn(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(qn(`Key for the ${e} algorithm must be `,t,...r))}var Xn=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Zn(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Qn(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function $n(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw Xn(t.name);if(t.hash&&r.hash?.name!==t.hash)throw Xn(t.hash,`algorithm.hash`);
3if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw Xn(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw Xn(t.length,`algorithm.length`);Zn(e,n)}function er(e){return{__proto__:null,...e}}function tr(e){let t=er(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}function nr(e){if(e!==void 0&&typeof e!=`boolean`)throw TypeError(`"extractable" option must be a boolean`);return e}async function rr(e,t,n){if(!e.kty.includes(t.kty))throw new I(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function ir(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),$n(e,t,n),e}function ar(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}var or=[[`encrypt`,`wrapKey`],[`decrypt`,`unwrapKey`]],sr=[[],[`deriveBits`]],cr=[[],[]];function lr(e){return{kty:[`RSA`],mode:`key-encryption`,subtle:{name:`RSA-OAEP`,hash:`SHA-${e}`},usages:or,ops:[`wrapKey`,`unwrapKey`]}}function ur(e){return{kty:[`EC`,`OKP`],mode:e,subtle:{name:`ECDH`},resolve:({kty:e,crv:t,asymmetricKeyType:n})=>{if(t===`X25519`||n===`x25519`)return{name:`X25519`};if(e===`OKP`)throw new I(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);return{name:`ECDH`,namedCurve:t}},usages:sr,ops:[void 0,`deriveBits`]}}function V(e,t=!1){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:t?`AES-GCM`:`AES-KW`,length:e},usages:cr,ops:t?[`encrypt`,`decrypt`]:[`wrapKey`,`unwrapKey`]}}function dr(){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:`PBKDF2`},usages:cr,ops:[`deriveBits`,`deriveBits`]}}var fr=ar({dir:{kty:[`oct`],mode:`direct-encryption`,secret:!0,subtle:{name:`AES-GCM`},usages:cr,ops:[`encrypt`,`decrypt`]},"RSA-OAEP":lr(1),"RSA-OAEP-256":lr(256),"RSA-OAEP-384":lr(384),"RSA-OAEP-512":lr(512),"ECDH-ES":ur(`direct-key-agreement`),"ECDH-ES+A128KW":ur(`key-agreement-with-key-wrapping`),"ECDH-ES+A192KW":ur(`key-agreement-with-key-wrapping`),"ECDH-ES+A256KW":ur(`key-agreement-with-key-wrapping`),A128KW:V(128),A192KW:V(192),A256KW:V(256),A128GCMKW:V(128,!0),A192GCMKW:V(192,!0),A256GCMKW:V(256,!0),"PBES2-HS256+A128KW":dr(),"PBES2-HS384+A192KW":dr(),"PBES2-HS512+A256KW":dr()}),pr=[`encrypt`,`decrypt`];function H(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-CBC`:`AES-GCM`,length:e},usages:cr,ops:pr,cekBits:e,ivBits:t?128:96,cbc:t}}ar({A128GCM:H(128),A192GCM:H(192),A256GCM:H(256),"A128CBC-HS256":H(256,!0),"A192CBC-HS384":H(384,!0),"A256CBC-HS512":H(512,!0)});var U=[[`verify`],[`sign`]];function mr(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:U}}function W(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:U,minRsaBits:2048}}function hr(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:U}}function gr(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:U}}function _r(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:U}}var vr=ar({HS256:mr(256),HS384:mr(384),HS512:mr(512),RS256:W(256),RS384:W(384),RS512:W(512),PS256:W(256,32),PS384:W(384,48),PS512:W(512,64),ES256:hr(`P-256`,256),ES384:hr(`P-384`,384),ES512:hr(`P-521`,512),EdDSA:gr(),Ed25519:gr(),"ML-DSA-44":_r(44),"ML-DSA-65":_r(65),"ML-DSA-87":_r(87)});function yr(e){let t=typeof e==`string`?vr[e]:void 0;if(!t)throw new I(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function br(e){return[e&&In(`algorithms`,e.algorithms),e?.crit]}function xr(e){return e===void 0?{}
3:Pn(e,L,`JWS Protected Header is invalid`)}function Sr(e){try{return N(e)}catch{throw new L(`JWS Compact Serialization payload must use only ASCII characters`)}}async function Cr(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??xr(a);if(!jn(c,o))throw new L(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=Rn(c,Ln(L,Fn,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new L(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new xn(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new L(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new L(`JWS Payload must be a string or an Uint8Array instance`);let f=u||typeof s!=`string`?s:r(s),p=!1;typeof n==`function`&&(n=await n(c,e),p=!0);let m=yr(d),h=hn(a===void 0?new Uint8Array:N(a),N(`.`),typeof f==`string`?t[2]??=Nn(f,`payload`,L):f),g=Mn(e.signature,`signature`,L),_=await Vn(m,n,`verify`),v=await ir(_,m.subtle,`verify`);m.minRsaBits&&Qn(m.alg,v);let y=!1;try{y=await crypto.subtle.verify(m.signing,v,g,h)}catch{}if(!y)throw new Dn;let b={payload:typeof f==`string`?Mn(f,`payload`,L):f};return a!==void 0&&(b.protectedHeader=c),o!==void 0&&(b.unprotectedHeader=o),p?[{...b,key:_},u]:[b,u]}async function wr(e,t,n){if(e instanceof Uint8Array&&(e=pn.decode(e)),typeof e!=`string`)throw new L(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new L(`Invalid Compact JWS`);return Cr({payload:i,protected:r,signature:a},t,n,Sr)}var Tr=e=>Math.floor(e.getTime()/1e3),Er={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Dr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,G=`check_failed`;function Or(){throw TypeError(`Invalid time period format`)}function kr(e){typeof e!=`string`&&Or();let t=Dr.exec(e);(!t||t[4]&&t[1])&&Or();let n=parseFloat(t[2]),r=Math.round(n*Er[t[3][0].toLowerCase()]);return Number.isFinite(r)||Or(),t[1]===`-`||t[4]===`ago`?-r:r}function K(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Ar(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function jr(e){if(typeof e!=`string`&&(!Array.isArray(e)||Array.from(e).some(e=>typeof e!=`string`)))throw TypeError(`"aud" claim must be a string or an array of strings`)}function Mr(e,t){return typeof e==`number`?K(t,e):e instanceof Date?K(t,Tr(e)):Tr(new Date)+kr(e)}var Nr=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},Pr=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function Fr(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new F(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function Ir(e,t){throw new F(`unexpected "${t}" claim value`,e,t,G)}function Lr(e,t,n={}){let r;try{r=JSON.parse(mn.decode(t))}catch{}if(!B(r))throw new R(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||Nr(e.typ)!==Nr(i)))throw new F(`unexpected "typ" JWT header value`,r,`typ`,G);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!Object.hasOwn(r,e))throw new F(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&Ir(r,`iss`),s!==void 0&&r.sub!==s&&Ir(r,`sub`),c!==void 0&&!Pr(r.aud,typeof c==`string`?[c]:c)&&Ir(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=kr(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}K(`clockTolerance option`,f);let{currentDate:p}=n,m=K(`currentDate option`,Tr(p===void 0?new Date:p)),h=Fr(r,`iat`,l!==void 0),g=Fr(r,`nbf`);if(g!==void 0&&g>m+f)throw new F(`"nbf" claim timestamp check failed`,r,`nbf`,G);let _=Fr(r,`exp`);if(_!==void 0&&_<=m-f)throw new bn(`"exp" claim timestamp check failed`,r,`exp`,G);if(l!==void 0){let e=m-h,t=K(`maxTokenAge option`,typeof l==`number`?l:kr(l));if(e-f>t)throw new bn(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,G);if(e<-f)throw new F(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,G)}return r}var Rr;function q(e){return Rr.get(e)}function zr(e){let t=q(e);for(let e of[`iat`,`nbf`,`exp`]){let n=t[e];
3if(typeof n==`number`&&!Number.isFinite(n))throw TypeError(`"${e}" claim must be a finite number`)}return fn.encode(JSON.stringify(t))}var Br=class{constructor(e={}){if(!B(e))throw TypeError(`JWT Claims Set MUST be an object`);(Rr||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Ar(`iss`,e),q(this).iss=e,this}setSubject(e){return Ar(`sub`,e),q(this).sub=e,this}setAudience(e){return jr(e),q(this).aud=e,this}setJti(e){return Ar(`jti`,e),q(this).jti=e,this}setNotBefore(e){return q(this).nbf=Mr(e,`setNotBefore`),this}setExpirationTime(e){return q(this).exp=Mr(e,`setExpirationTime`),this}setIssuedAt(e){let t=q(this);return t.iat=e===void 0?Tr(new Date):typeof e==`string`?K(`setIssuedAt`,Tr(new Date)+kr(e)):Mr(e,`setIssuedAt`),this}};async function Vr(e,t,n){let[r,i]=await wr(e,br(n),t);if(!i)throw new R(`JWTs MUST NOT use unencoded payload`);let a=Lr(r.protectedHeader,r.payload,n);return{...r,payload:a}}function Hr(e=`JWK "alg" (Algorithm) Parameter`){throw new I(`Invalid or unsupported ${e} value`)}function Ur(e,t){return(typeof e==`string`?vr[e]??fr[e]:void 0)??Hr(t)}async function Wr(e){if(Gn(e)){if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`})}if(e instanceof Uint8Array)return{kty:`oct`,k:z(e)};if(!Wn(e))throw TypeError(Jn(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let t=await crypto.subtle.exportKey(`jwk`,e);delete t.ext,delete t.key_ops,delete t.use,t.kty!==`AKP`&&delete t.alg;for(let e of Object.keys(t))t[e]===void 0&&delete t[e];return t}var J=(e,t)=>{if(typeof e!=`string`||!e)throw new Sn(`${t} missing or invalid`)};async function Gr(e,t){let n;if(B(e)){if(n=er(e),typeof n.kty!=`string`)throw TypeError(Jn(e,`CryptoKey`,`KeyObject`,`JSON Web Key`))}else if(Kn(e))n=er(await Wr(e));else throw TypeError(Jn(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:J(n.alg,`"alg" (Algorithm) Parameter`),J(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:J(n.crv,`"crv" (Curve) Parameter`),J(n.x,`"x" (X Coordinate) Parameter`),J(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:J(n.crv,`"crv" (Subtype of Key Pair) Parameter`),J(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:J(n.e,`"e" (Exponent) Parameter`),J(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:if(typeof n.k!=`string`)throw new Sn(`"k" (Key Value) Parameter missing or invalid`);r={k:n.k,kty:n.kty};break;default:throw new I(`"kty" (Key Type) Parameter missing or unsupported`)}let i=N(JSON.stringify(r));return z(await yn(t,i))}function Kr(e,t,n,r){let{kty:i,key_ops:a,ext:o,kid:s,alg:c,use:l,crv:u}=e;return(o===void 0||typeof o==`boolean`)&&(a===void 0||Array.isArray(a)&&a.every((e,t)=>typeof e==`string`&&a.indexOf(e)===t)&&a.includes(`verify`))&&t.kty.includes(i)&&(r===void 0||typeof r==`string`&&r===s)&&(c===void 0?i!==`AKP`:n===c)&&(l===void 0||l===`sig`)&&(!t.crv||u===t.crv)}async function qr(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=rr(n,t,!0).then(e=>{if(e.type!==`public`)throw new Cn(`JSON Web Key Set members must be public keys`);return r[i]=e,e}).catch(t=>{throw r[i]===e&&delete r[i],t});r[i]=e}return r[i]}function Jr(e){let t;try{t=structuredClone(e)}catch{}if(!An(t))throw new Cn(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=er(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),r=new WeakMap;return Object.defineProperty(async(e,i)=>{let{alg:a,kid:o}={...e,...i?.header},s=typeof a==`string`?vr[a]:void 0;if(!s||s.secret)throw new I(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>Kr(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new wn;if(u!==1){let e=new Tn;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await qr(r,e,s)}catch{}},e}return qr(r,l,s)},"jwks",{value:()=>structuredClone(t)})}var Yr=Br,Xr=class extends Yr{encode(){return`${z(JSON.stringify({alg:`none`}))}.${z(zr(this))}.`}static decode(e,t){if(typeof e!=`string`)throw new R(`Unsecured JWT must be a string`);let{0:n,1:r,2:i,length:a}=e.split(`.`);if(a!==3||i!==``)throw new R(`Invalid Unsecured JWT`);let o,s;
3try{o=Pn(n,L,`JWS Protected Header is invalid`);let e=Ln(L,Fn,void 0,o,o);s=Rn(o,e)}catch(e){throw e instanceof L?new R(`Invalid Unsecured JWT`,{cause:e}):e}if(o.alg!==`none`)throw new R(`Invalid Unsecured JWT`);if(!s)throw new R(`JWTs MUST NOT use unencoded payload`);return{payload:Lr(o,Mn(r,`payload`,R),t),header:o}}};async function Zr(e,t,n){if(!B(e))throw TypeError(`JWK must be an object`);let r=tr(e),i=nr(n?.extractable),{alg:a}=r;if(t??=a,r.kty!==`oct`&&!t)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);switch(r.kty){case`oct`:if(typeof r.k!=`string`)throw TypeError(`missing "k" (Key Value) Parameter value`);return kn(r.k);case`AKP`:if(typeof a!=`string`||!a)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==a)throw TypeError(`JWK alg and alg option value mismatch`);return rr(Ur(t),r,i);case`RSA`:case`EC`:case`OKP`:return rr(Ur(t),r,i);default:throw new I(`Unsupported "kty" (Key Type) Parameter value`)}}function Qr(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e){if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`)}let n=`Invalid Token or Protected Header formatting`;if(typeof t!=`string`||!t)throw TypeError(n);return Pn(t,TypeError,n)}function $r(){let e=typeof globalThis<`u`&&globalThis.crypto;if(e&&typeof e.subtle==`object`&&e.subtle!=null)return e.subtle;throw Error(`crypto.subtle must be defined`)}var ei={name:`HMAC`,hash:`SHA-256`},ti=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await $r().importKey(`raw`,t,ei,!1,[`sign`,`verify`])},ni=async(e,t,n)=>{try{let r=atob(e),i=new Uint8Array(r.length);for(let e=0,t=r.length;e<t;e++)i[e]=r.charCodeAt(e);return await $r().verify(ei,n,i,new TextEncoder().encode(t))}catch{return!1}},ri=async(e,t)=>{let n=await ti(t),r=await $r().sign(ei.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},ii=async(e,t)=>{let n=await ri(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e};function ai(e){return e instanceof D||e?.name===`APIError`}function oi(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function si(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function ci(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}var li=(e,t)=>{let n=e;if(t){if(t===`secure`)n=`__Secure-`+e;else if(t===`host`)n=`__Host-`+e;else return}return n};function ui(e){if(typeof e!=`string`)throw TypeError(`argument str must be a string`);let t=new Map,n=0;for(;n<e.length;){let r=e.indexOf(`=`,n);if(r===-1)break;let i=e.indexOf(`;`,n);if(i===-1)i=e.length;else if(i<r){n=e.lastIndexOf(`;`,r-1)+1;continue}let a=e.slice(n,r).trim();if(!t.has(a)){let n=e.slice(r+1,i).trim();n.codePointAt(0)===34&&(n=n.slice(1,-1)),t.set(a,oi(n))}n=i+1}return t}var di=(e,t,n={})=>{let r;if(r=n?.prefix===`secure`?`${`__Secure-${e}`}=${t}`:n?.prefix===`host`?`${`__Host-${e}`}=${t}`:`${e}=${t}`,e.startsWith(`__Secure-`)&&!n.secure&&(n.secure=!0),e.startsWith(`__Host-`)&&(n.secure||=!0,n.path!==`/`&&(n.path=`/`),n.domain&&=void 0),n&&typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&n.prefix!==`host`&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}return n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned&&(n.secure||=!0,r+=`; Partitioned`),r},fi=(e,t,n)=>(t=encodeURIComponent(t),di(e,t,n)),pi=async(e,t,n,r)=>(t=await ii(t,n),di(e,t,r));async function mi(e,t={}){let n={body:t.body,query:t.query};if(e.body){let r=await e.body[`~standard`].validate(t.body);if(r.issues)return{data:null,error:hi(r.issues,`body`)};n.body=r.value}if(e.query){let r=await e.query[`~standard`].validate(t.query);if(r.issues)return{data:null,error:hi(r.issues,`query`)};n.query=r.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:`Headers is required`,issues:[]}}:e.requireRequest&&!t.request?{data:null,error:{message:`Request is required`,issues:[]}}:{data:n,error:null}}function hi(e,t){return{message:e.map(e=>`[${e.path?.length?`${t}.`+e.path.map(e=>typeof e==`object`?e.key:e).join(`.`):t}] ${e.message}`).join(`; `),issues:e}}var gi=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:o}=await mi(t,e);if(o)throw new lt(o.message,o.issues);let s=`headers`in e?e.headers instanceof Headers?e.headers:new Headers(e.headers):`request`in e&&ci(e.request)?e.request.headers:null,c=s?.get(`cookie`),l=c?ui(c):void 0,u={...e,body:a.body,query:a.query,path:e.path||n||`virtual:`,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??(Array.isArray(t.method)?t.method[0]:t.method===`*`?`GET`:t.method),setHeader:(e,t)=>{r.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let n=li(e,t);return n&&l?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=li(e,n);if(!r)return null;let i=l?.get(r);if(!i)return null;let a=i.lastIndexOf(`.`);if(a<1)return null;let o=i.substring(0,a),s=i.substring(a+1);return s.length!==44||!s.endsWith(`=`)?null:await ni(s,o,await ti(t))?o:!1},setCookie:(e,t,n)=>
3{let i=fi(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await pi(e,t,n,i);return r.append(`set-cookie`,a),a},redirect:e=>(r.set(`location`,e),new D(`FOUND`,void 0,r)),error:(e,t,n)=>new D(e,t,n),setStatus:e=>{i=e},json:(t,n)=>e.asResponse?{body:n?.body||t,routerResponse:n,_flag:`json`}:t,responseHeaders:r,get responseStatus(){return i}};for(let e of t.use||[]){let t=await e({...u,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(u.context,t.response),t.headers&&t.headers.forEach((e,t)=>{u.responseHeaders.set(t,e)})}return u};function _i(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function vi(e){let t=new WeakMap,n=new WeakMap,r=0,i=(e,n)=>{let r=n;for(;r;){if(r===e)return!0;r=t.get(r)}return!1};return JSON.stringify(e,function(e,a){if(typeof a==`bigint`)return a.toString();if(typeof a==`object`&&a){if(i(a,this))return`[Circular ref-${n.get(a)}]`;t.set(a,this),n.has(a)||n.set(a,r++)}return a})}function yi(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}var bi=new Set(`host.user-agent.referer.from.expect.authorization.proxy-authorization.cookie.origin.accept-charset.accept-encoding.accept-language.if-match.if-none-match.if-modified-since.if-unmodified-since.if-range.range.max-forwards.connection.keep-alive.transfer-encoding.te.upgrade.trailer.proxy-connection.content-length`.split(`.`));function xi(e){for(let t of bi)e.delete(t)}function Si(e,t){if(t)for(let[n,r]of new Headers(t).entries())n.toLowerCase()===`set-cookie`?e.append(n,r):e.set(n,r)}function Ci(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);xi(n),Si(e.headers,n)}return e}if(yi(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if(Si(i,r?.headers),Si(i,e.headers),t?.headers){let e=new Headers(t.headers);xi(e),Si(i,e)}return i.set(`Content-Type`,`application/json`),new Response(JSON.stringify(n),{...r,headers:i,status:e.status??t?.status??r?.status,statusText:t?.statusText??r?.statusText})}if(ai(e))return Ci(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let n=e,r=new Headers(t?.headers);return xi(r),e?typeof e==`string`?(n=e,r.set(`Content-Type`,`text/plain`)):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?(n=e,r.set(`Content-Type`,`application/octet-stream`)):e instanceof Blob?(n=e,r.set(`Content-Type`,e.type||`application/octet-stream`)):e instanceof FormData?n=e:e instanceof URLSearchParams?(n=e,r.set(`Content-Type`,`application/x-www-form-urlencoded`)):e instanceof ReadableStream?(n=e,r.set(`Content-Type`,`application/octet-stream`)):_i(e)&&(n=vi(e),r.set(`Content-Type`,`application/json`)):(e===null&&(n=JSON.stringify(null)),r.set(`content-type`,`application/json`)),new Response(n,{...t,headers:r})}function wi(e,t,n){let r=typeof e==`string`?e:void 0,i=typeof t==`object`?t:e,a=typeof t==`function`?t:n;if((i.method===`GET`||i.method===`HEAD`)&&i.body)throw new ut(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new ut(`Path cannot contain consecutive slashes`);let o=async(...e)=>{let t=e[0]||{},{data:n,error:o}=await si(gi(t,{options:i,path:r}));if(o)throw o instanceof lt?(i.onValidationError&&await i.onValidationError({message:o.message,issues:o.issues}),new D(400,{message:o.message,code:`VALIDATION_ERROR`})):o;let s=await a(n).catch(async e=>{if(ai(e)){let n=i.onAPIError;if(n&&await n(e),t.asResponse)return e}throw e}),c=n.responseHeaders,l=n.responseStatus;return t.asResponse?Ci(s,{headers:c,status:l}):t.returnHeaders?t.returnStatus?{headers:c,response:s,status:l}:{headers:c,response:s}:t.returnStatus?{response:s,status:l}:s};return o.options=i,o.path=r,o}function Ti(e,t){return[...e??[],...t??[]]}wi.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return wi(n,{...r,use:Ti(r.use,e?.use)},i)}let[n,r]=t;return wi({...n,use:Ti(n.use,e?.use)},r)}return t};function Ei(e,t){let n=async n=>{let r=n,i=typeof e==`function`?e:t,a=await gi(r,{options:typeof e==`function`?{}:e,path:`/`});if(!i)throw Error(`handler must be defined`);try{let e=await i(a),t=a.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw ai(e)&&Object.defineProperty(e,dt,{enumerable:!1,
3configurable:!0,get(){return a.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}Ei.create=e=>{function t(t,n){if(typeof t==`function`)return Ei({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return Ei({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};var Di=new Set([301,302,303,307,308]);function Oi(e){return e.type===`opaqueredirect`||Di.has(e.status)}function ki(e){return new O(`The OAuth endpoint "${e}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}var Ai={redirect:`manual`};async function ji(e,t){let n=!1,r=t?.onError,i=await He(e,{...t,...Ai,async onError(e){Oi(e.response)&&(n=!0),await r?.(e)}}).catch(t=>{throw n?ki(e):t});if(n)throw ki(e);return i}var Mi=`dpop+jwt`,Ni=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],Pi=300,Fi=512,Ii=new Set([`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`k`]);function Li(){let e=new Map;return{reserve({key:t,expiresAt:n,now:r}){let i=r.getTime();for(let[t,n]of e)n<=i&&e.delete(t);return!e.has(t)&&(e.set(t,n.getTime()),!0)}}}function Y(e,t){return Object.assign(Error(t),{code:e})}function Ri(e){return e instanceof Error&&`code`in e&&e.code===`invalid_dpop_proof`}function zi(e){if(!e)return;let t=e.trim();if(!t)return;let n=/^([A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*)\s+(.+)$/.exec(t);if(!n)return{scheme:`Unknown`,token:t};let r=n[1]??``,i=n[2]?.trim()??``;return r.toLowerCase()===`bearer`?{scheme:`Bearer`,token:i}:r.toLowerCase()===`dpop`?{scheme:`DPoP`,token:i}:{scheme:`Unknown`,token:t}}function Bi(e){let t=new URL(e);if(t.hash)throw Error(`DPoP proof htu must not contain a fragment`);return`${t.origin}${t.pathname}`}async function Vi(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return z(new Uint8Array(t))}async function Hi(e){return Gr(e,`sha256`)}function Ui(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.jkt;return typeof t==`string`&&t.length>0?t:void 0}function Wi(e){return Ui(e.cnf)}function Gi(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ki(e,t){let n=e[t];
3return typeof n==`number`&&Number.isFinite(n)?n:void 0}function qi(e,t){if(!e||e===`none`||e.startsWith(`HS`))throw Y(`invalid_dpop_proof`,`DPoP proof must use an asymmetric JWS algorithm`);if(!t.includes(e))throw Y(`invalid_dpop_proof`,`DPoP proof uses an unsupported JWS algorithm`)}function Ji(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Y(`invalid_dpop_proof`,`DPoP proof header must include a public jwk`);if(e.kty===`oct`)throw Y(`invalid_dpop_proof`,`DPoP proof jwk must be asymmetric`);for(let t of Ii)if(t in e)throw Y(`invalid_dpop_proof`,`DPoP proof jwk must not contain private key material`)}async function Yi(e){let t=`${e.jkt}\n${e.htm}\n${e.htu}\n${e.jti}`,n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return z(new Uint8Array(n))}async function Xi(e,t){if(e&&!await e.reserve(t))throw Y(`invalid_dpop_proof`,`DPoP proof jti has already been used`)}async function Zi({proofJwt:e,method:t,url:n,accessToken:r,expectedJkt:i,requireAth:a=!1,nowSeconds:o=Math.floor(Date.now()/1e3),proofMaxAgeSeconds:s=Pi,signingAlgorithms:c=Ni,replayStore:l}){if(!e||e.split(`.`).length!==3)throw Y(`invalid_dpop_proof`,`DPoP proof must be a compact JWT`);let u;try{u=Qr(e)}catch(e){throw Y(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof header is invalid`)}if(u.typ!==`dpop+jwt`)throw Y(`invalid_dpop_proof`,`DPoP proof typ must be "dpop+jwt"`);qi(u.alg,c),Ji(u.jwk);let d;try{d=(await Vr(e,await Zr(u.jwk,u.alg),{typ:Mi})).payload}catch(e){throw Y(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof signature is invalid`)}let f=Gi(d,`htm`),p=Gi(d,`htu`),m=Gi(d,`jti`),h=Ki(d,`iat`);if(!f||!p||!m||h===void 0)throw Y(`invalid_dpop_proof`,`DPoP proof must include htm, htu, jti, and iat claims`);if(m.length>Fi)throw Y(`invalid_dpop_proof`,`DPoP proof jti is too large`);if(f.toUpperCase()!==t.toUpperCase())throw Y(`invalid_dpop_proof`,`DPoP proof htm does not match the request method`);let g,_;try{g=Bi(n),_=Bi(p)}catch(e){throw Y(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof htu is invalid`)}if(_!==g)throw Y(`invalid_dpop_proof`,`DPoP proof htu does not match the request URL`);if(h>o+5||o-h>s)throw Y(`invalid_dpop_proof`,`DPoP proof iat is outside the accepted window`);let v=Gi(d,`ath`);if(a&&!v)throw Y(`invalid_dpop_proof`,`DPoP proof must include an ath claim`);if(r!==void 0&&v!==await Vi(r))throw Y(`invalid_dpop_proof`,`DPoP proof ath does not match the access token`);let y=await Hi(u.jwk);if(i!==void 0&&y!==i)throw Y(`invalid_dpop_proof`,`DPoP proof key does not match the bound token`);let b=await Yi({jkt:y,htm:f.toUpperCase(),htu:g,jti:m}),x=new Date((h+s)*1e3);return await Xi(l,{key:b,expiresAt:x,now:new Date(o*1e3)}),{jwk:u.jwk,jkt:y,jti:m,htm:f,htu:g,iat:h,ath:v,replayKey:b,expiresAt:x}}function Qi(e,t){return Object.assign(Error(t),{code:e})}function $i(e){return e instanceof Error&&`code`in e&&(e.code===`invalid_token`||e.code===`invalid_dpop_proof`)}async function ea({payload:e,authorization:t,proofJwt:n,method:r,url:i,replayStore:a,proofMaxAgeSeconds:o,signingAlgorithms:s}){let c=Wi(e);if(!c){if(t.scheme===`DPoP`)throw Qi(`invalid_token`,`DPoP authorization requires a DPoP-bound access token`);return}if(t.scheme!==`DPoP`)throw Qi(`invalid_token`,`DPoP-bound access token requires the DPoP authorization scheme`);if(!n)throw Qi(`invalid_dpop_proof`,`DPoP proof header is required`);try{await Zi({proofJwt:n,method:r,url:i,accessToken:t.token,expectedJkt:c,requireAth:!0,proofMaxAgeSeconds:o,signingAlgorithms:s,replayStore:a})}catch(e){throw Ri(e)?Qi(`invalid_dpop_proof`,e.message):e}}var ta=new Set([En.code,Cn.code,Tn.code]);function na(e){return ta.has(e.code)}var ra=new Map,ia=new WeakMap,aa=3e5,oa=3e4;function sa(e,t){if(e&&!(Date.now()-e.fetchedAt>=aa)&&(!t||e.jwks.keys.some(e=>e.kid===t)))return e.jwks}function ca(e,t){return t.fromCache&&!t.kid&&(e instanceof wn||e instanceof Dn)?!t.noKidRefetchedAt||Date.now()-t.noKidRefetchedAt>=oa:!1}async function la(e){let t=typeof e==`string`?await ji(e,{headers:{Accept:`application/json`}}).then(async e=>{if(e.error)throw Error(`Jwks failed: ${e.error.message??e.error.statusText}`);return e.data}):await e();
3if(!t)throw Error(`No jwks found`);return t}function ua(e){return{authorizationHeader:e.headers.get(`authorization`),dpopProofJwt:e.headers.get(`dpop`),method:e.method,url:e.url}}var da=Li();async function fa(e,t){try{let n=await pa(e,t),r;try{r=await Vr(e,Jr(n.jwks),t.verifyOptions)}catch(i){if(ca(i,n))r=await Vr(e,Jr((await pa(e,{...t,forceRefresh:!0})).jwks),t.verifyOptions);else throw i}return r.payload.azp&&(r.payload.client_id=r.payload.azp),r.payload}catch(e){throw e instanceof Error?e:Error(e)}}async function pa(e,t){let n;try{n=Qr(e)}catch(e){throw e instanceof Error?e:Error(e)}let r=n.kid;if(typeof t.jwksFetch!=`string`){let e=t.jwksCacheKey;if(!e){let e=await t.jwksFetch();if(!e)throw Error(`No jwks found`);return{jwks:e,fromCache:!1,kid:r}}let n=ia.get(e),i=t.forceRefresh?void 0:sa(n,r);if(i)return{jwks:i,fromCache:!0,kid:r,noKidRefetchedAt:n?.noKidRefetchedAt};let a=await t.jwksFetch();if(!a)throw Error(`No jwks found`);let o=Date.now();return ia.set(e,{jwks:a,fetchedAt:o,...t.forceRefresh&&!r?{noKidRefetchedAt:o}:{}}),{jwks:a,fromCache:!1,kid:r}}let i=t.jwksFetch,a=ra.get(i),o=t.forceRefresh?void 0:sa(a,r);if(!o){let e=await la(t.jwksFetch),n=Date.now();return ra.set(i,{jwks:e,fetchedAt:n,...t.forceRefresh&&!r?{noKidRefetchedAt:n}:{}}),{jwks:e,fromCache:!1,kid:r}}return{jwks:o,fromCache:!0,kid:r,noKidRefetchedAt:a?.noKidRefetchedAt}}async function ma(e,t){let n;if(t.jwksUrl&&!t?.remoteVerify?.force)try{n=await fa(e,{jwksFetch:t.jwksUrl,verifyOptions:t.verifyOptions})}catch(e){if(e instanceof Error){if(e.name!==`TypeError`&&e.name!==`JWSInvalid`)throw e instanceof bn?new D(`UNAUTHORIZED`,{message:`token expired`}):e instanceof P?na(e)?e:new D(`UNAUTHORIZED`,{message:`invalid access token`}):e}else throw Error(e)}if(t?.remoteVerify){let{data:r,error:i}=await ji(t.remoteVerify.introspectUrl,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:t.remoteVerify.clientId,client_secret:t.remoteVerify.clientSecret,token:e,token_type_hint:`access_token`}).toString()});if(i&&ce.error(`Introspection failed: ${i.message??i.statusText}`),!r)throw new D(`INTERNAL_SERVER_ERROR`,{message:`introspection failed`});if(!r.active)throw new D(`UNAUTHORIZED`,{message:`token inactive`});try{let e=new Xr(r).encode(),{audience:i,...a}=t.verifyOptions,o=!r.aud&&t.remoteVerify.allowMissingAudience===!0;n=Xr.decode(e,o?a:t.verifyOptions).payload}catch(e){throw Error(e)}}if(!n)throw new D(`UNAUTHORIZED`,{message:`no token payload`});let r=xa(n.scope);if(t.requiredScopes){let e=t.isScopeSatisfied??((e,t)=>t.has(e)),n=t.requiredScopes.filter(t=>!e(t,r));if(n.length>0)throw Sa(n)}return n}var ha=/^[\x21\x23-\x5b\x5d-\x7e]+$/,ga=/^[\x20-\x21\x23-\x5b\x5d-\x7e]+$/,_a=new WeakSet;function va(e){return ha.test(e)}function ya(e,t){for(let n of e)if(!va(n))throw TypeError(`invalid ${t}: ${JSON.stringify(n)}`)}function ba(e){e.requiredScopes&&ya(e.requiredScopes,`required scope`)}function xa(e){if(e===void 0)return new Set;if(typeof e!=`string`||e.length===0||e.split(` `).some(e=>!va(e)))throw new D(`UNAUTHORIZED`,{message:`access token scope claim is invalid`,error:`invalid_token`,error_description:`access token scope claim is invalid`});return new Set(e.split(` `))}function Sa(e,t=`access token is missing required scope: ${e.join(` `)}`){if(e.length===0)throw TypeError(`requiredScopes must contain at least one scope`);if(ya(e,`required scope`),typeof t!=`string`||!ga.test(t))throw TypeError(`invalid error_description`);let n=new D(`FORBIDDEN`,{message:t,error:`insufficient_scope`,error_description:t,scope:[...new Set(e)].join(` `)});return _a.add(n),n}function Ca(e){if(!(e instanceof D)||!_a.has(e)||e.status!==`FORBIDDEN`)return!1;let t=e.body;if(t?.error!==`insufficient_scope`||typeof t.scope!=`string`)return!1;let n=t.scope.split(` `);return n.length>0&&n.every(va)}function wa(e,t){throw new D(`UNAUTHORIZED`,t?{message:e,error:t,error_description:e}:{message:e})}async function Ta(e,t){ba(t);let n=await ma(e,t);return Wi(n)&&wa(`DPoP-bound access token requires verifyAccessTokenRequest`,`invalid_token`),n}async function Ea(e,t){ba(t);let n=zi(e.authorizationHeader);n?.token||wa(`missing authorization header`),n.scheme===`Unknown`&&wa(`authorization scheme must be Bearer or DPoP`,`invalid_token`);let r=await ma(n.token,t);try{await ea({payload:r,authorization:n,proofJwt:e.dpopProofJwt,method:e.method,url:e.url,replayStore:t.dpop?.replayStore??da,proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms})}catch(e){throw $i(e)&&wa(e.message,e.code),e}return r}var Da=e=>e.getPlugin(`oauth-provider`),Oa=e=>{let t=e.getPlugin(`jwt`);
3if(!t)throw new O(`jwt_config`);return t};function ka(e){return e instanceof D||e instanceof ft||e?.name===`APIError`}function Aa(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function ja(e,t,n=`.`,r){if(!Aa(t))return ja(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:Aa(a)&&Aa(i[t])?ja(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function Ma(e){return(...t)=>t.reduce((t,n)=>ja(t,n,``,e),{})}var Na=Ma(),Pa=new Set([`invalid_dpop_proof`]),Fa=/^[\x21\x23-\x5b\x5d-\x7e]+$/,Ia=/^[\x20-\x21\x23-\x5b\x5d-\x7e]+$/;function X(e){if(/[\x00-\x1f\x7f]/.test(e))throw TypeError(`invalid WWW-Authenticate parameter`);return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function La(e){if(e){for(let t of e)if(!Fa.test(t))throw TypeError(`invalid challenge scope: ${JSON.stringify(t)}`);return[...new Set(e)].join(` `)}}function Ra(e){if(typeof e!=`string`||!Ia.test(e))throw TypeError(`invalid error_description`);return e}function za(e){let t=e.body;return{errorCode:typeof t?.error==`string`?t.error:void 0,description:typeof t?.error_description==`string`?t.error_description:typeof t?.message==`string`?t.message:e.message}}function Ba(e){let{errorCode:t,description:n}=za(e);return!!t&&(Pa.has(t)||t===`invalid_token`&&n.includes(`DPoP`))}function Va(e,t){let{errorCode:n,description:r}=za(e),i=t?.dpopSigningAlgorithms??Ni;return[`DPoP error="${X(n??`invalid_dpop_proof`)}"`,`error_description="${Ra(r)}"`,`algs="${X(i.join(` `))}"`].join(`, `)}function Ha(e){let t=e.body;return{scope:t?.scope,description:t?.error_description===void 0?e.message:t.error_description}}function Ua(e,t){let n=URL.canParse?.(e)?new URL(e):null;if(n&&n.origin!==`null`){let e=n.pathname.endsWith(`/`)?n.pathname.slice(0,-1):n.pathname;return`${n.origin}/.well-known/oauth-protected-resource${e}${n.search}`}let r=t?.resourceMetadataMappings?.[e];if(!r)throw new D(`INTERNAL_SERVER_ERROR`,{message:`missing resource_metadata mapping for ${e}`});return r}function Wa(e,t,n){return(Array.isArray(e)?e:[e]).map(e=>`Bearer ${n(Ua(e,t)).filter(e=>!!e).join(`, `)}`).join(`, `)}function Ga(e,t,n){let r=La(n?.challengeScopes);if(ka(e)&&e.status===`UNAUTHORIZED`)return Ba(e)?new D(`UNAUTHORIZED`,{message:e.message}
3,{"WWW-Authenticate":Va(e,n)}):new D(`UNAUTHORIZED`,{message:e.message},{"WWW-Authenticate":Wa(t,n,e=>[`resource_metadata="${X(e)}"`,r&&`scope="${X(r)}"`])});if(Ca(e)){let i=Ha(e),a=Ra(i.description),o=i.scope||r;return new D(`FORBIDDEN`,{message:a},{"WWW-Authenticate":Wa(t,n,e=>[`error="insufficient_scope"`,o&&`scope="${X(o)}"`,`resource_metadata="${X(e)}"`,`error_description="${a}"`])})}}var Ka=e=>{let t,n=async()=>(t||=e?Da(await e.$context):void 0,t),r,i=async()=>(r||=e&&!(await n())?.options?.disableJwtPlugin?Oa(await e.$context):void 0,r?.options),a=typeof e?.options.baseURL==`string`?e.options.baseURL:void 0,o=async()=>(await i())?.jwt?.issuer??a,s=e?.options.basePath,c=async e=>{let t=await i(),n=e?.verifyOptions?.audience??a,r=e?.verifyOptions?.issuer??t?.jwt?.issuer??a;if(!n)throw Error(`please define opts.verifyOptions.audience`);if(!r)throw Error(`please define opts.verifyOptions.issuer`);let o=e?.jwksUrl??t?.jwks?.remoteUrl??(a?`${a+(s??``)}${t?.jwks?.jwksPath??`/jwks`}`:void 0),c=e?.remoteVerify?.introspectUrl??(a?`${a}${s??``}/oauth2/introspect`:void 0);return{...e,jwksUrl:o,verifyOptions:{...e?.verifyOptions,audience:n,issuer:r},remoteVerify:e?.remoteVerify&&c?{...e.remoteVerify,introspectUrl:c}:void 0}},l=e=>typeof e.headers?.get==`function`?ua(e):e;return{id:`oauth-provider-resource-client`,version:Xe,getActions(){return{verifyBearerToken:(async(e,t)=>{let n=await c(t);try{if(!e?.length)throw new D(`UNAUTHORIZED`,{message:`missing authorization header`});return await Ta(e,n)}catch(e){throw Ga(e,n.verifyOptions.audience,{resourceMetadataMappings:t?.resourceMetadataMappings,dpopSigningAlgorithms:Ni})||e}}),verifyAccessTokenRequest:(async(e,t)=>{let n=await c(t);try{return await Ea(l(e),n)}catch(e){throw Ga(e,n.verifyOptions.audience,{resourceMetadataMappings:t?.resourceMetadataMappings,dpopSigningAlgorithms:t?.dpop?.signingAlgorithms??Ni})||e}}),getProtectedResourceMetadata:(async(e,t)=>{let r=e?.resource??a,i=(await n())?.options;if(!r)throw Error(`missing required resource`);if(i?.scopes&&t?.externalScopes&&(e?.authorization_servers?.length??0)<=1)throw new O(`external scopes should not be provided with one authorization server`);if(e?.scopes_supported){let n=new Set([...i?.scopes??[],...t?.externalScopes??[]]);for(let t of e.scopes_supported){if(t===`openid`)throw new O(`Only the Auth Server should utilize the openid scope`);if(!n.has(t))throw new O(`Unsupported scope ${t}. If external, please add to "externalScopes"`)}}let s=await o();return{resource:r,authorization_servers:s?[s]:void 0,dpop_signing_alg_values_supported:[...i?.dpop?.signingAlgorithms??Ni],...e}})}}}},Z=a({CHALLENGE_NOT_FOUND:`Challenge not found`,YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY:`You are not allowed to register this passkey`,FAILED_TO_VERIFY_REGISTRATION:`Failed to verify registration`,PASSKEY_NOT_FOUND:`Passkey not found`,AUTHENTICATION_FAILED:`Authentication failed`,UNABLE_TO_CREATE_SESSION:`Unable to create session`,USER_NOT_FOUND:`User not found`,FAILED_TO_UPDATE_PASSKEY:`Failed to update passkey`,PREVIOUSLY_REGISTERED:`Previously registered`,REGISTRATION_CANCELLED:`Registration cancelled`,AUTH_CANCELLED:`Auth cancelled`,UNKNOWN_ERROR:`Unknown error`,SESSION_REQUIRED:`Passkey registration requires an authenticated session`,RESOLVE_USER_REQUIRED:`Passkey registration requires either an authenticated session or a resolveUser callback when requireSession is false`,RESOLVED_USER_INVALID:`Resolved user is invalid`}),qa=`1.7.5`;function Q(e){let t=new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function Ja(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=(4-t.length%4)%4,r=t.padEnd(t.length+n,`=`),i=atob(r),a=new ArrayBuffer(i.length),o=new Uint8Array(a);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return a}function Ya(){return Xa.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential==`function`)}var Xa={stubThis:e=>e};function Za(e){let{id:t}=e;return{...e,id:Ja(t),transports:e.transports}}function Qa(e){return e===`localhost`||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}
3var $=class extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??n.name,this.code=t}};function $a({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new $({message:`Registration ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`ConstraintError`){if(n.authenticatorSelection?.requireResidentKey===!0)return new $({message:`Discoverable credentials were required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT`,cause:e});if(t.mediation===`conditional`&&n.authenticatorSelection?.userVerification===`required`)return new $({message:`User verification was required during automatic registration but it could not be performed`,code:`ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE`,cause:e});if(n.authenticatorSelection?.userVerification===`required`)return new $({message:`User verification was required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT`,cause:e})}else if(e.name===`InvalidStateError`)return new $({message:`The authenticator was previously registered`,code:`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`,cause:e});else if(e.name===`NotAllowedError`)return new $({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`NotSupportedError`)return n.pubKeyCredParams.filter(e=>e.type===`public-key`).length===0?new $({message:`No entry in pubKeyCredParams was of type "public-key"`,code:`ERROR_MALFORMED_PUBKEYCREDPARAMS`,cause:e}):new $({message:`No available authenticator supported any of the specified pubKeyCredParams algorithms`,code:`ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!Qa(t))return new $({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rp.id!==t)return new $({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`TypeError`){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new $({message:`User ID was not between 1 and 64 characters`,code:`ERROR_INVALID_USER_ID_LENGTH`,cause:e})}else if(e.name===`UnknownError`)return new $({message:`The authenticator was unable to process the specified options, or could not create a new credential`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}var eo=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}}},to=[`cross-platform`,`platform`];function no(e){if(e&&!(to.indexOf(e)<0))return e}async function ro(e){!e.optionsJSON&&e.challenge&&(console.warn(`startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useAutoRegister:n=!1}=e;if(!Ya())throw Error(`WebAuthn is not supported in this browser`);let r={...t,challenge:Ja(t.challenge),user:{...t.user,id:Ja(t.user.id)},excludeCredentials:t.excludeCredentials?.map(Za)},i={};n&&(i.mediation=`conditional`),i.publicKey=r,i.signal=eo.createNewAbortSignal();let a;try{a=await navigator.credentials.create(i)}catch(e){throw $a({error:e,options:i})}if(!a)throw Error(`Registration was not completed`);let{id:o,rawId:s,response:c,type:l}=a,u;typeof c.getTransports==`function`&&(u=c.getTransports());let d;if(typeof c.getPublicKeyAlgorithm==`function`)try{d=c.getPublicKeyAlgorithm()}catch(e){io(`getPublicKeyAlgorithm()`,e)}let f;if(typeof c.getPublicKey==`function`)try{let e=c.getPublicKey();e!==null&&(f=Q(e))}catch(e){io(`getPublicKey()`,e)}let p;
3if(typeof c.getAuthenticatorData==`function`)try{p=Q(c.getAuthenticatorData())}catch(e){io(`getAuthenticatorData()`,e)}return{id:o,rawId:Q(s),response:{attestationObject:Q(c.attestationObject),clientDataJSON:Q(c.clientDataJSON),transports:u,publicKeyAlgorithm:d,publicKey:f,authenticatorData:p},type:l,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:no(a.authenticatorAttachment)}}function io(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}function ao(){if(!Ya())return oo.stubThis(new Promise(e=>e(!1)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?oo.stubThis(new Promise(e=>e(!1))):oo.stubThis(e.isConditionalMediationAvailable())}var oo={stubThis:e=>e};function so({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new $({message:`Authentication ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`NotAllowedError`)return new $({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!Qa(t))return new $({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rpId!==t)return new $({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`UnknownError`)return new $({message:`The authenticator was unable to process the specified options, or could not create a new assertion signature`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}async function co(e){!e.optionsJSON&&e.challenge&&(console.warn(`startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useBrowserAutofill:n=!1,verifyBrowserAutofillInput:r=!0}=e;if(!Ya())throw Error(`WebAuthn is not supported in this browser`);let i;t.allowCredentials?.length!==0&&(i=t.allowCredentials?.map(Za));let a={...t,challenge:Ja(t.challenge),allowCredentials:i},o={};if(n){if(!await ao())throw Error(`Browser does not support WebAuthn autofill`);if(document.querySelectorAll(`input[autocomplete$='webauthn']`).length<1&&r)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation=`conditional`,a.allowCredentials=[]}o.publicKey=a,o.signal=eo.createNewAbortSignal();let s;try{s=await navigator.credentials.get(o)}catch(e){throw so({error:e,options:o})}if(!s)throw Error(`Authentication was not completed`);let{id:c,rawId:l,response:u,type:d}=s,f;return u.userHandle&&(f=Q(u.userHandle)),{id:c,rawId:Q(l),response:{authenticatorData:Q(u.authenticatorData),clientDataJSON:Q(u.clientDataJSON),signature:Q(u.signature),userHandle:f},type:d,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:no(s.authenticatorAttachment)}}var lo=Symbol.for(`better-auth:broadcast-channel`),uo=()=>Math.floor(Date.now()/1e3),fo=class{listeners=new Set;name;constructor(e=`better-auth.message`){this.name=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}post(e){if(typeof window<`u`)try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:uo()}))}catch{}}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=e=>{if(e.key!==this.name)return;let t=JSON.parse(e.newValue??`{}`);t?.event===`session`&&t?.data&&this.listeners.forEach(e=>e(t))};return window.addEventListener(`storage`,e),()=>{window.removeEventListener(`storage`,e)}}};function po(e=`better-auth.message`){return globalThis[lo]||(globalThis[lo]=new fo(e)),globalThis[lo]}var mo=Symbol.for(`better-auth:focus-manager`),ho=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}
3setFocused(e){this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||typeof document>`u`||window.addEventListener===void 0)return()=>{};let e=()=>{document.visibilityState===`visible`&&this.setFocused(!0)};return document.addEventListener(`visibilitychange`,e,!1),()=>{document.removeEventListener(`visibilitychange`,e,!1)}}};function go(){return globalThis[mo]||(globalThis[mo]=new ho),globalThis[mo]}var _o=Symbol.for(`better-auth:online-manager`),vo=class{listeners=new Set;isOnline=typeof navigator<`u`?navigator.onLine:!0;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=()=>this.setOnline(!0),t=()=>this.setOnline(!1);return window.addEventListener(`online`,e,!1),window.addEventListener(`offline`,t,!1),()=>{window.removeEventListener(`online`,e,!1),window.removeEventListener(`offline`,t,!1)}}};function yo(){return globalThis[_o]||(globalThis[_o]=new vo),globalThis[_o]}var bo={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*:/},xo=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,So={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},Co=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function wo(e){return e instanceof Date&&!isNaN(e.getTime())}function To(e){let t=Co.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l,u,d]=t,f=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(a,10),parseInt(o,10),parseInt(s,10),c?parseInt(c.padEnd(3,`0`),10):0));if(l){let e=(parseInt(u,10)*60+parseInt(d,10))*(l===`+`?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return wo(f)?f:null}function Eo(e,t={}){let{strict:n=!1,warnings:r=!1,reviver:i,parseDates:a=!0}=t;if(typeof e!=`string`)return e;let o=e.trim(),s=o.toLowerCase();if(s.length<=9&&s in So)return So[s];if(!xo.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(bo).some(([e,t])=>{let n=t.test(o);return n&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),n})&&n)throw Error(`[better-json] Potential prototype pollution attempt detected`);try{return JSON.parse(o,(e,t)=>{if(e===`__proto__`||e===`constructor`&&t&&typeof t==`object`&&`prototype`in t){r&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(a&&typeof t==`string`){let e=To(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function Do(e,t={strict:!0}){return Eo(e,t)}var Oo=()=>Math.floor(Date.now()/1e3),ko=5;function Ao(e){let{fetchSession:t,shouldPollSession:n=()=>!0,sessionSignal:r,options:i={}}=e,a=i.sessionOptions?.refetchInterval??0,o=i.sessionOptions?.refetchOnWindowFocus??!0,s=i.sessionOptions?.refetchWhenOffline??!1,c={isInitialized:!1,lastSessionRequest:0},l=()=>s||yo().isOnline,u=e=>{if(l()){if(e?.event===`storage`){t();return}if(e?.event===`poll`){c.lastSessionRequest=Oo(),t();return}if(e?.event===`visibilitychange`){if(Oo()-c.lastSessionRequest<ko)return;c.lastSessionRequest=Oo(),t();return}t()}},d=e=>{po().post({event:`session`,data:{trigger:e},clientId:Math.random().toString(36).substring(7)})},f=()=>{a&&a>0&&(c.pollInterval=setInterval(()=>{n()&&u({event:`poll`})},a*1e3))},p=()=>{c.unsubscribeBroadcast=po().subscribe(()=>{u({event:`storage`})})},m=()=>{o&&(c.unsubscribeFocus=go().subscribe(()=>{u({event:`visibilitychange`})}))},h=()=>{c.unsubscribeOnline=yo().subscribe(e=>{e&&u({event:`visibilitychange`})})},g=()=>{c.unsubscribeSignal=r.listen(()=>{t()})};return{init:()=>{c.isInitialized||(c.isInitialized=!0,f(),p(),m(),h(),g(),c.cleanupBroadcastSetup=po().setup(),c.cleanupFocusSetup=go().setup(),c.cleanupOnlineSetup=yo().setup())},cleanup:()=>{c.isInitialized&&(c.pollInterval&&=(clearInterval(c.pollInterval),void 0),c.unsubscribeBroadcast&&=(c.unsubscribeBroadcast(),void 0),c.unsubscribeFocus&&=(c.unsubscribeFocus(),void 0),c.unsubscribeOnline&&=(c.unsubscribeOnline(),void 0),c.unsubscribeSignal&&=(c.unsubscribeSignal(),void 0),c.cleanupBroadcastSetup&&=(c.cleanupBroadcastSetup(),void 0),c.cleanupFocusSetup&&=(c.cleanupFocusSetup(),void 0),c.cleanupOnlineSetup&&=(c.cleanupOnlineSetup(),void 0),c.isInitialized=!1,c.lastSessionRequest=0)},triggerRefetch:u,broadcastSessionUpdate:d}}var jo={id:`redirect`,name:`Redirect`,hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&It(e.data.url)&&typeof window<`u`&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}},Mo=()=>typeof window>`u`,No=Jt;function Po(e,t){if(typeof window>`u`)return;let n=e.get();n.data===null&&t!==null&&e.set({...n,data:t,error:null,isPending:!1})}function Fo(e){return typeof e==`object`&&e&&`data`in e&&`error`in e?e:{data:e,error:null}}function Io(e){return!e||e.session===null&&e.user===null?null:e}function Lo(e,t){return M(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}function Ro(e,t){let n=Vt(!1),r,i=0,a=0;n.listen(()=>{a++,i=0});let o=e=>u(e),s=Vt({data:null,error:null,isPending:!0,isRefetching:!1,refetch:o});nn(s,Lo);let c=async(t,n)=>{let r=s.value;if(s.set({...r,isPending:r.data===null,isRefetching:!0,error:null,refetch:o}),t.aborted)return`aborted`;try{let r=await e(`/get-session`,{method:`GET`,query:n?.query,signal:t});if(t.aborted)return`aborted`;let{data:i,error:a}=Fo(r),c=`fresh`;if(i?.needsRefresh)try{let n=await e(`/get-session`,{method:`POST`,signal:t});if(t.aborted)return`aborted`;({data:i,error:a}=Fo(n))}catch{if(t.aborted)return`aborted`;c=`stale`}if(a){let e=s.value,t=a?.status===401;return s.set({data:t?null:e.data,error:a,isPending:!1,isRefetching:!1,refetch:o}),`failed`}let l=Io(i),u=s.value,d=u.data!=null&&l!=null&&M(u.data,l)?u.data:l;return s.set({data:d,error:null,isPending:!1,isRefetching:!1,refetch:o}),c}catch(e){if(t.aborted)return`aborted`;let n=s.value;return s.set({data:n.data,error:e,isPending:!1,isRefetching:!1,refetch:o}),`failed`}},l=()=>{let e=s.value.data?.session?.expiresAt,t=e instanceof Date?e.getTime():1/0;return Math.min(Date.now()+No,t)},u=e=>{i=0,r?.cancel();let t=new AbortController,n={cancel:()=>t.abort(),promise:Promise.resolve().then(()=>t.signal.aborted?`aborted`:c(t.signal,e)),revision:a};r=n;let o=e=>{r===n&&(r=void 0,e===`fresh`&&n.revision===a&&(i=l()))};return n.promise.then(o,()=>o(`failed`)),n.promise.then(()=>void 0)},d=()=>r?.revision===a?r.promise.then(()=>void 0):Date.now()<i?Promise.resolve():u(),f=()=>{};return Yt(s,()=>{let e;Mo()||(e=setTimeout(()=>{d()},0));let r=Ao({fetchSession:u,shouldPollSession:()=>s.value.data!=null,sessionSignal:n,options:t});return r.init(),f=r.broadcastSessionUpdate,()=>{e&&clearTimeout(e),r.cleanup()}}),{session:s,$sessionSignal:n,broadcastSessionUpdate:e=>f(e)}}var zo=e=>{if(typeof process>`u`)return;let t=e??`/api/auth`;if({}.NEXT_PUBLIC_AUTH_URL)return{}.NEXT_PUBLIC_AUTH_URL;if(typeof window>`u`){if({}.NEXTAUTH_URL)try{return{}.NEXTAUTH_URL}catch{}if({}.VERCEL_URL)try{let e={}.VERCEL_URL.startsWith(`http`)?``:`https://`;return`${new URL(`${e}${{}.VERCEL_URL}`).origin}${t}`}catch{}}},Bo=(e,t)=>{let n=`credentials`in Request.prototype,r=Nt(e?.baseURL,e?.basePath,void 0,t)??zo(e?.basePath)??`/api/auth`,i=e?.plugins?.flatMap(e=>e.fetchPlugins).filter(e=>e!==void 0)||[],a={id:`lifecycle-hooks`,name:`lifecycle-hooks`,hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:o,onError:s,onRequest:c,onResponse:l,...u}=e?.fetchOptions||{},d=We({baseURL:r,...n?{credentials:`include`}:{},method:`GET`,jsonParser(e){return e?Do(e,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[a,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[jo],...i]}),{$sessionSignal:f,session:p,broadcastSessionUpdate:m}=Ro(d,e),h=!1,g=e=>{h||e===null||(h=!0,Po(p,e))},_=e?.plugins||[],v={},y={$sessionSignal:f,session:p}
3,b={"/sign-out":`POST`,"/revoke-sessions":`POST`,"/revoke-other-sessions":`POST`,"/delete-user":`POST`},x=[{signal:`$sessionSignal`,matcher(e){return e===`/sign-out`||e===`/update-user`||e===`/update-session`||e===`/sign-up/email`||e===`/sign-in/email`||e===`/delete-user`||e===`/verify-email`||e===`/revoke-sessions`||e===`/revoke-session`||e===`/revoke-other-sessions`||e===`/change-email`||e===`/change-password`},callback(e){e===`/sign-out`?m(`signout`):(e===`/update-user`||e===`/update-session`)&&m(`updateUser`)}}];for(let e of _)e.getAtoms&&Object.assign(y,e.getAtoms?.(d)),e.pathMethods&&Object.assign(b,e.pathMethods),e.atomListeners&&x.push(...e.atomListeners);let S={notify:e=>{y[e].set(!y[e].get())},listen:(e,t)=>{y[e].subscribe(t)},atoms:y};for(let t of _)t.getActions&&(v=Na(t.getActions?.(d,S,e)??{},v));return{get baseURL(){return r},pluginsActions:v,pluginsAtoms:y,pluginPathMethods:b,atomListeners:x,hydrateSession:g,$sessionSignal:f,$fetch:d,$store:S}};function Vo(e){return typeof e==`object`&&!!e&&`get`in e&&typeof e.get==`function`&&`lc`in e&&typeof e.lc==`number`}function Ho(e){return e.charAt(0).toUpperCase()+e.slice(1)}var Uo=/[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu,Wo=/['\u2019]/g;function Go(e){return e.replace(Wo,``).match(Uo)??[]}function Ko(e){return Go(e).map(e=>e.toLowerCase()).join(`-`)}function qo(e,t,n){let r=t[e],{fetchOptions:i,query:a,...o}=n||{};return r||(i?.method?i.method:o&&Object.keys(o).length>0?`POST`:`GET`)}function Jo(e,t,n,r,i){function a(o=[]){return new Proxy(function(){},{get(t,n){if(typeof n!=`string`||n===`then`||n===`catch`||n===`finally`)return;let r=[...o,n],i=e;for(let e of r)if(i&&typeof i==`object`&&e in i)i=i[e];else{i=void 0;break}return typeof i==`function`||Vo(i)?i:a(r)},apply:async(e,a,s)=>{let c=`/`+o.map(Ko).join(`/`),l=s[0]||{},u=s[1]||{},{query:d,fetchOptions:f,...p}=l,m={...u,...f},h=qo(c,n,l);return await t(c,{...m,body:h===`GET`?void 0:{...p,...m?.body||{}},query:d||m?.query,method:h,async onSuccess(e){if(await m?.onSuccess?.(e),!i||m.disableSignal)return;let t=i.filter(e=>e.matcher(c));if(!t.length)return;let n=new Set;for(let e of t){let t=r[e.signal];if(!t)return;if(n.has(e.signal))continue;n.add(e.signal);let i=t.get();setTimeout(()=>{t.set(!i)},10),e.callback?.(c)}}})}})}return a()}var Yo=(e,{$listPasskeys:t,$store:n})=>({signIn:{passkey:async(r,i)=>{let a=await e(`/passkey/generate-authenticate-options`,{method:`GET`,throw:!1});if(!a.data)return a;let o=a.data.extensions||r?.extensions?{...a.data.extensions||{},...r?.extensions||{}}:void 0,s;try{s=await co({optionsJSON:{...a.data,extensions:o},useBrowserAutofill:r?.autoFill})}catch(e){return{data:null,error:{code:e instanceof $?e.code:`AUTH_CANCELLED`,message:Z.AUTH_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}}try{let{clientExtensionResults:a,...o}=s,c=await e(`/passkey/verify-authentication`,{body:{response:o},...r?.fetchOptions,...i,method:`POST`,throw:!1});return t.set(Math.random()),n.notify(`$sessionSignal`),r?.returnWebAuthnResponse?{...c,webauthn:{response:s,clientExtensionResults:a}}:c}catch(e){return console.error(`[Better Auth] Error verifying passkey`,e),{data:null,error:{code:`AUTH_CANCELLED`,message:Z.AUTH_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}}}},passkey:{addPasskey:async(r,i)=>{let a=await e(`/passkey/generate-register-options`,{method:`GET`,query:{...r?.authenticatorAttachment&&{authenticatorAttachment:r.authenticatorAttachment},...r?.name&&{name:r.name},...r?.context&&{context:r.context}},throw:!1});if(!a.data)return a;try{let o=a.data.extensions||r?.extensions?{...a.data.extensions||{},...r?.extensions||{}}:void 0,s=await ro({optionsJSON:{...a.data,extensions:o},useAutoRegister:r?.useAutoRegister}),{clientExtensionResults:c,...l}=s,u=await e(`/passkey/verify-registration`,{...r?.fetchOptions,...i,body:{response:l,name:r?.name,...r?.createSession&&{createSession:!0}},method:`POST`,throw:!1});return u.data?(t.set(Math.random()),u.data.session&&n.notify(`$sessionSignal`),r?.returnWebAuthnResponse?{...u,webauthn:{response:s,clientExtensionResults:c}}:u):u}catch(e){return e instanceof $?e.code===`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`?{data:null,error:{code:e.code,message:Z.PREVIOUSLY_REGISTERED.message,status:400,statusText:`BAD_REQUEST`}}:e.code===`ERROR_CEREMONY_ABORTED`?{data:null,error:{code:e.code,message:Z.REGISTRATION_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}:{data:null,error:{code:e.code,message:e.message,status:400,statusText:`BAD_REQUEST`}}:{data:null,error:{code:`UNKNOWN_ERROR`,message:e instanceof Error?e.message:Z.UNKNOWN_ERROR.message,status:500,statusText:`INTERNAL_SERVER_ERROR`}}}}},$Infer:{}}),Xo=()=>
3{let e=Vt();return{id:`passkey`,version:qa,$InferServerPlugin:{},getActions:(t,n)=>Yo(t,{$listPasskeys:e,$store:n}),getAtoms(t){return{listPasskeys:on(e,`/passkey/list-user-passkeys`,t,{method:`GET`}),$listPasskeys:e}},pathMethods:{"/passkey/register":`POST`,"/passkey/authenticate":`POST`},atomListeners:[{matcher(e){return e===`/passkey/verify-registration`||e===`/passkey/delete-passkey`||e===`/passkey/update-passkey`||e===`/sign-out`},signal:`$listPasskeys`},{matcher:e=>e===`/passkey/verify-authentication`,signal:`$sessionSignal`}],$ERROR_CODES:Z}},Zo=e(t(),1);function Qo(e,t={}){let n=(0,Zo.useRef)(e.get()),{keys:r,deps:i=[e,r]}=t,a=(0,Zo.useCallback)(t=>{let i=e=>{n.current!==e&&(n.current=e,t())};return i(e.value),r?.length?en(e,r,i):e.listen(i)},i),o=()=>n.current;return(0,Zo.useSyncExternalStore)(a,o,o)}function $o(e){return`use${Ho(e)}`}function es(e){let{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,hydrateSession:i,$fetch:a,$store:o,atomListeners:s}=Bo(e),c={};for(let[e,t]of Object.entries(r))c[$o(e)]=()=>Qo(t);return Jo({...n,...c,hydrateSession:i,$fetch:a,$store:o},a,t,r,s)}var ts=/[\\\u0000-\u0020\u007f]/;function ns(e){if(typeof e==`string`&&e.startsWith(`/`)&&!e.startsWith(`//`)&&!ts.test(e))try{let t=decodeURIComponent(e.split(/[?#]/,1)[0]??``);return t.startsWith(`//`)||ts.test(t)||new URL(e,`https://callback.invalid`).origin!==`https://callback.invalid`?void 0:e}catch{return}}var rs=r({callbackURL:n().transform(ns).optional(),reauthenticate:i().optional().catch(void 0)});function is(e){let t=ns(e);return{href:t??`/dashboard`,reloadDocument:t!==void 0,replace:!0}}function as(e){let t=ns(e);if(!t)return{};let n=new URL(t,`https://callback.invalid`);return n.pathname!==`/api/auth/oauth`||!n.searchParams.has(`sig`)?{}:{oauth_query:n.search.slice(1)}}function os(e){return typeof e==`object`&&!!e&&`redirect`in e&&e.redirect===!0&&`url`in e&&typeof e.url==`string`}function ss(e){let t=as(e);return{fetchOptions:{onRequest(e){if(!t.oauth_query)return;let n=typeof e.body==`string`?JSON.parse(e.body):e.body;n&&typeof n==`object`&&(e.body=JSON.stringify({...n,...t}))}}}}var cs=es({plugins:[Ke(),Dt(),c(),Xo(),un(),cn({onTwoFactorRedirect(){if(typeof window<`u`){let{callbackURL:e,reauthenticate:t}=rs.parse({reauthenticate:new URLSearchParams(window.location.search).get(`reauthenticate`)===`true`,callbackURL:new URLSearchParams(window.location.search).get(`callbackURL`)}),n=e?`?${new URLSearchParams({callbackURL:e,...t?{reauthenticate:`true`}:{}})}`:``;window.location.href=`/auth/verify-2fa${n}`}}}),dn(),Ka(),nt()]});export{as as a,ss as i,rs as n,os as o,is as r,cs as t};

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.