@juspay/neurolink 12.47.6 → 12.47.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
## [12.47.
|
|
1
|
+
## [12.47.7](https://github.com/juspay/neurolink/compare/v12.47.6...v12.47.7) (2026-10-05)
|
|
2
2
|
|
|
3
3
|
### Bug Fixes
|
|
4
4
|
|
|
5
|
-
- **(core):**
|
|
5
|
+
- **(core):** state the Node versions that need --experimental-sqlite correctly ([092858f](https://github.com/juspay/neurolink/commit/092858f386c5350ddd8ece24b8548db0daa40d5c))
|
|
6
6
|
|
|
7
7
|
## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
|
|
8
8
|
|
|
@@ -2239,7 +2239,7 @@ Content:
|
|
|
2239
2239
|
${e.text}
|
|
2240
2240
|
|
|
2241
2241
|
Return the extracted data as JSON.`,i=await this.callLLM(o,t);try{const s=i.match(/\{[\s\S]*\}/);return JSON.parse(s?s[0]:i)}catch{return h.warn("[MetadataExtractor] Failed to parse custom extraction as JSON"),{raw:i}}}parseQAPairs(e,t){const r=[],n=e.split(`
|
|
2242
|
-
`).filter(s=>s.trim());let o=null,i=null;for(const s of n){const a=s.trim();/^\d+[.):]\s*/.test(a)||/^Q[.:]?\s*/i.test(a)?(o&&r.push({question:o,...t&&i?{answer:i}:{}}),o=a.replace(/^\d+[.):]\s*/,"").replace(/^Q[.:]?\s*/i,""),i=null):/^A[.:]?\s*/i.test(a)&&o?i=a.replace(/^A[.:]?\s*/i,""):o&&!i?o+=" "+a:i&&(i+=" "+a)}return o&&r.push({question:o,...t&&i?{answer:i}:{}}),r}async callLLM(e,t){return(await(await Cr.createProvider(t.provider||this.provider,t.modelName||this.modelName)).generate({prompt:e,maxTokens:t.maxTokens||500,temperature:t.temperature||.3}))?.content||""}}}}),zmr,Vce,_l,cc=E({"src/lib/auth/providers/BaseAuthProvider.ts"(){"use strict";$t(),Hn(),z(),Gs(),zmr=xt,Vce=class{sessions=new Map;userSessions=new Map;async get(e){return this.sessions.get(e)??null}async save(e){this.sessions.set(e.id,e);const t=this.userSessions.get(e.user.id)??new Set;t.add(e.id),this.userSessions.set(e.user.id,t)}async delete(e){const t=this.sessions.get(e);if(t){this.sessions.delete(e);const r=this.userSessions.get(t.user.id);r&&(r.delete(e),r.size===0&&this.userSessions.delete(t.user.id))}}async deleteAllForUser(e){const t=this.userSessions.get(e);if(t){for(const r of t)this.sessions.delete(r);this.userSessions.delete(e)}}async getForUser(e){const t=this.userSessions.get(e);if(!t)return[];const r=Date.now(),n=[],o=[];for(const i of t){const s=this.sessions.get(i);if(s){if(s.expiresAt&&s.expiresAt.getTime()<r){o.push(i);continue}if(!s.isValid){o.push(i);continue}n.push(s)}}for(const i of o)this.sessions.delete(i),t.delete(i);return t.size===0&&this.userSessions.delete(e),n}async exists(e){return this.sessions.has(e)}async touch(e){const t=this.sessions.get(e);t&&(t.lastActivityAt=new Date,this.sessions.set(e,t))}async clear(){this.sessions.clear(),this.userSessions.clear()}get size(){return this.sessions.size}},_l=class{config;sessionStorage;sessionConfig;rbacConfig;emitter=new un;constructor(e){const t={fromHeader:{name:"Authorization",scheme:"Bearer"}};this.config={required:!0,...e,tokenExtraction:{...t,...e.tokenExtraction}},this.sessionConfig={storage:"memory",duration:3600,autoRefresh:!0,refreshThreshold:300,allowMultipleSessions:!0,maxSessionsPerUser:10,prefix:"neurolink:session:",...e.session},this.rbacConfig={enabled:!0,defaultRoles:[],roleHierarchy:{},rolePermissions:{},superAdminRoles:["super_admin","root"],...e.rbac},this.sessionStorage=e.session?.customStorage??new Vce,h.debug("[BaseAuthProvider] Initialized")}async extractToken(e){const t=this.config.tokenExtraction;if(t?.fromHeader){const r=t.fromHeader.name.toLowerCase();let n;for(const[o,i]of Object.entries(e.headers))if(o.toLowerCase()===r&&typeof i=="string"){n=i;break}if(typeof n=="string")if(t.fromHeader.scheme){const o=`${t.fromHeader.scheme} `;if(n.startsWith(o))return n.slice(o.length)}else return n}if(t?.fromCookie&&e.cookies){const r=e.cookies[t.fromCookie.name];if(r)return r}if(t?.fromQuery&&e.path)try{const n=new URL(e.path,"http://localhost").searchParams.get(t.fromQuery.name);if(n)return n}catch{}return t?.custom?await Promise.resolve(t.custom(e)):null}async createSession(e,t){const r=new Date,n=this.sessionConfig.duration??3600;if(!this.sessionConfig.allowMultipleSessions)await this.revokeAllSessions(e.id);else if(this.sessionConfig.maxSessionsPerUser){const i=await this.sessionStorage.getForUser(e.id);if(i.length>=this.sessionConfig.maxSessionsPerUser){const s=i.sort((a,l)=>a.createdAt.getTime()-l.createdAt.getTime())[0];s&&await this.sessionStorage.delete(s.id)}}const o={id:Qe(),user:e,accessToken:Qe(),isValid:!0,expiresAt:new Date(r.getTime()+n*1e3),createdAt:r,lastActivityAt:r,ipAddress:t?.ip??t?.ipAddress,userAgent:t?.userAgent};return await this.sessionStorage.save(o),h.debug(`[BaseAuthProvider] Created session ${o.id} for user ${e.id}`),o}async validateSession(e){const t=await this.sessionStorage.get(e);if(!t)return{valid:!1,error:"Session not found",errorCode:"AUTH-010"};if(t.expiresAt&&t.expiresAt.getTime()<Date.now())return await this.sessionStorage.delete(e),{valid:!1,error:"Session expired",errorCode:"AUTH-011"};if(!t.isValid)return{valid:!1,error:"Session revoked",errorCode:"AUTH-012"};let r=!1;if(this.sessionConfig.autoRefresh&&this.sessionConfig.refreshThreshold&&t.expiresAt&&t.expiresAt.getTime()-Date.now()<this.sessionConfig.refreshThreshold*1e3){const n=await this.refreshSession(e);return r=!0,{valid:!0,session:n??void 0,refreshed:r}}return await this.sessionStorage.touch(e),{valid:!0,session:t,refreshed:r}}async refreshSession(e){const t=await this.sessionStorage.get(e);if(!t)throw xt.create("SESSION_NOT_FOUND",`Session not found: ${e}`,{details:{sessionId:e}});if(!t.isValid)throw xt.create("SESSION_REVOKED",`Cannot refresh revoked session: ${e}`,{details:{sessionId:e}});if(t.expiresAt&&t.expiresAt.getTime()<Date.now())throw await this.sessionStorage.delete(e),xt.create("SESSION_EXPIRED",`Cannot refresh expired session: ${e}`,{details:{sessionId:e}});const r=this.sessionConfig.duration??3600;return t.expiresAt=new Date(Date.now()+r*1e3),t.lastActivityAt=new Date,await this.sessionStorage.save(t),h.debug(`[BaseAuthProvider] Refreshed session ${e}`),t}async revokeSession(e){const t=await this.sessionStorage.get(e);t&&(t.isValid=!1,await this.sessionStorage.save(t),h.debug(`[BaseAuthProvider] Revoked session ${e}`))}async revokeAllSessions(e){await this.sessionStorage.deleteAllForUser(e),h.debug(`[BaseAuthProvider] Revoked all sessions for user ${e}`)}async authorize(e,t){if(!this.rbacConfig.enabled)return{authorized:!0,user:e};if(this.isSuperAdmin(e))return{authorized:!0,user:e};const r={authorized:!0,user:e,requiredRoles:t.roles,requiredPermissions:t.permissions,missingRoles:[],missingPermissions:[]};if(t.roles&&t.roles.length>0){const n=this.getEffectiveRoles(e),o=t.roles.filter(i=>!n.has(i));t.requireAllRoles?o.length>0&&(r.authorized=!1,r.missingRoles=o,r.reason=`Missing required roles: ${o.join(", ")}`):t.roles.some(s=>n.has(s))||(r.authorized=!1,r.missingRoles=t.roles,r.reason=`Missing any of required roles: ${t.roles.join(", ")}`)}if(t.permissions&&t.permissions.length>0){const n=this.getEffectivePermissions(e),o=t.permissions.filter(i=>!this.hasPermission(n,i));o.length>0&&(r.authorized=!1,r.missingPermissions=o,r.reason=r.reason?`${r.reason}; Missing permissions: ${o.join(", ")}`:`Missing required permissions: ${o.join(", ")}`)}return r}isSuperAdmin(e){const t=this.rbacConfig.superAdminRoles??[];return e.roles.some(r=>t.includes(r))}getEffectiveRoles(e){const t=new Set(e.roles),r=this.rbacConfig.roleHierarchy??{};let n=!0;for(;n;){n=!1;for(const o of t){const i=r[o]??[];for(const s of i)t.has(s)||(t.add(s),n=!0)}}return t}getEffectivePermissions(e){const t=new Set(e.permissions),r=this.rbacConfig.rolePermissions??{},n=this.getEffectiveRoles(e);for(const o of n){const i=r[o]??[];for(const s of i)t.add(s)}return t}hasPermission(e,t){if(e.has(t)||e.has("*"))return!0;const r=t.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(e.has(o))return!0}return!1}parseJWT(e){try{const t=e.split(".");if(t.length!==3)return null;const r=t[1],n=Buffer.from(r,"base64url").toString("utf-8");return JSON.parse(n)}catch{return null}}isTokenExpired(e,t=0){if(!e.exp)return!1;const r=Math.floor(Date.now()/1e3);return e.exp+t<r}isTokenNotYetValid(e,t=0){if(!e.nbf)return!1;const r=Math.floor(Date.now()/1e3);return e.nbf-t>r}extractUserFromClaims(e,t){const r=t?.rolesClaimKey??"roles",n=t?.permissionsClaimKey??"permissions",o=t?.idClaimKey??"sub",i=Array.isArray(e[r])?e[r]:this.rbacConfig.defaultRoles??[],s=Array.isArray(e[n])?e[n]:[];return{id:e[o]??"",email:e.email,name:e.name,picture:e.picture,roles:i,permissions:s,emailVerified:e.email_verified,providerData:e}}async getUser(e){return h.debug(`[BaseAuthProvider] getUser not implemented for ${this.type}`),null}async updateUserRoles(e,t){throw xt.create("PROVIDER_ERROR",`updateUserRoles not supported by ${this.type} provider`)}async updateUserPermissions(e,t){throw xt.create("PROVIDER_ERROR",`updateUserPermissions not supported by ${this.type} provider`)}async dispose(){await this.sessionStorage.clear(),h.debug(`[BaseAuthProvider] Disposed ${this.type} provider`)}async authorizeUser(e,t){return this.authorize(e,{permissions:[t]})}async authorizeRoles(e,t){return this.authorize(e,{roles:t})}async authorizePermissions(e,t){return this.authorize(e,{permissions:t})}async getSession(e){return this.sessionStorage.get(e)}async destroySession(e){await this.revokeSession(e)}async getUserSessions(e){return this.sessionStorage.getForUser(e)}async destroyAllUserSessions(e){await this.revokeAllSessions(e)}async authenticateRequest(e){const t=await this.extractToken(e);if(!t)return this.config.required&&this.emitter.emit("auth:unauthorized",e,"No token provided"),null;const r=await this.authenticateToken(t,e);if(!r.valid||!r.user)return this.emitter.emit("auth:unauthorized",e,r.error??"Invalid token"),null;const i=(await this.getUserSessions(r.user.id)).find(s=>s.isValid&&(!s.expiresAt||s.expiresAt.getTime()>Date.now()))??await this.createSession(r.user,e);return{...e,user:r.user,session:i,request:e,authenticatedAt:new Date,provider:this.type}}async healthCheck(){return{healthy:!0,providerConnected:!0,sessionStorageHealthy:!0}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}emit(e,...t){this.emitter.emit(e,...t)}}}});function Gmr(...e){const t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function rb(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){const n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}var YC,nb,adn,ZC=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js"(){YC=new TextEncoder,nb=new TextDecoder,adn=2**32}});function ldn(e){if(Uint8Array.prototype.toBase64)return e.toBase64();const t=32768,r=[];for(let n=0;n<e.length;n+=t)r.push(String.fromCharCode.apply(null,e.subarray(n,n+t)));return btoa(r.join(""))}function qmr(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var Vmr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js"(){}});function BF(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:nb.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=nb.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return qmr(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function jce(e){let t=e;return typeof t=="string"&&(t=YC.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):ldn(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var QC=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js"(){ZC(),Vmr()}});function cdn(e){return parseInt(e.name.slice(4),10)}function Hce(e,t){if(cdn(e.hash)!==t)throw Ap(`SHA-${t}`,"algorithm.hash")}function udn(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ddn(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function pdn(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!T0(e.algorithm,"HMAC"))throw Ap("HMAC");Hce(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!T0(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Ap("RSASSA-PKCS1-v1_5");Hce(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!T0(e.algorithm,"RSA-PSS"))throw Ap("RSA-PSS");Hce(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!T0(e.algorithm,"Ed25519"))throw Ap("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!T0(e.algorithm,t))throw Ap(t);break}case"ES256":case"ES384":case"ES512":{if(!T0(e.algorithm,"ECDSA"))throw Ap("ECDSA");const n=udn(t);if(e.algorithm.namedCurve!==n)throw Ap(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ddn(e,r)}var Ap,T0,mdn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js"(){Ap=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),T0=(e,t)=>e.name===t}});function jmr(e,t,...r){if(r=r.filter(Boolean),r.length>2){const n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Hmr,Wce,Wmr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js"(){Hmr=(e,...t)=>jmr("Key must be ",e,...t),Wce=(e,t,...r)=>jmr(`Key for the ${e} algorithm must be `,t,...r)}}),Ha,lu,Kce,Kmr,El,Ho,zF,Jce,Xce,Jmr,Xmr,Ymr,Sl=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js"(){Ha=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)}},lu=class extends Ha{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}},Kce=class extends Ha{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}},Kmr=class extends Ha{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},El=class extends Ha{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Ho=class extends Ha{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},zF=class extends Ha{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},Jce=class extends Ha{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Xce=class extends Ha{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)}},Jmr=class extends Ha{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}},Xmr=class extends Ha{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}},Ymr=class extends Ha{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}}}),Yce,Zce,Qce,Zmr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js"(){Yce=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Zce=e=>e?.[Symbol.toStringTag]==="KeyObject",Qce=e=>Yce(e)||Zce(e)}});function Qmr(e,t){if(e)throw new TypeError(`${t} can only be called once`)}function ehr(e,t,r){try{return BF(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}var thr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js"(){QC()}});function Cp(e){if(!nhr(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function rhr(...e){const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){const o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(const i of o){if(r.has(i))return!1;r.add(i)}}return!0}var nhr,GF,ohr,ihr,shr,Ip=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js"(){nhr=e=>typeof e=="object"&&e!==null,GF=e=>Cp(e)&&typeof e.kty=="string",ohr=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),ihr=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,shr=e=>e.kty==="oct"&&typeof e.k=="string"}});function ahr(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function lhr(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new El(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function chr(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Hmr(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return pdn(t,e,r),t}async function hdn(e,t,r){const n=await chr(e,t,"sign");ahr(e,n);const o=await crypto.subtle.sign(lhr(e,n.algorithm),n,r);return new Uint8Array(o)}async function fdn(e,t,r,n){const o=await chr(e,t,"verify");ahr(e,o);const i=lhr(e,o.algorithm);try{return await crypto.subtle.verify(i,o,r,n)}catch{return!1}}var uhr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js"(){Sl(),mdn(),Wmr()}});function gdn(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new El(e1)}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new El(e1)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new El(e1)}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new El(e1)}break}default:throw new El('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function qF(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=gdn(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}var e1,dhr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js"(){Sl(),e1='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'}});async function phr(e,t){if(e instanceof Uint8Array||Yce(e))return e;if(Zce(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return mhr(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return eue(e,r,t)}if(GF(e))return e.k?BF(e.k):eue(e,e,t,!0);throw new Error("unreachable")}var b0,ob,eue,mhr,hhr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js"(){Ip(),QC(),dhr(),Zmr(),b0="given KeyObject instance cannot be used for this algorithm",eue=async(e,t,r,n=!1)=>{ob||=new WeakMap;let o=ob.get(e);if(o?.[r])return o[r];const i=await qF({...t,alg:r});return n&&Object.freeze(e),o?o[r]=i:ob.set(e,{[r]:i}),i},mhr=(e,t)=>{ob||=new WeakMap;let r=ob.get(e);if(r?.[t])return r[t];const n=e.type==="public",o=!!n;let i;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(b0)}i=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(b0);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(b0);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let s;switch(t){case"RSA-OAEP":s="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":s="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":s="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":s="SHA-512";break;default:throw new TypeError(b0)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:s},o,n?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:s},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){const a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(b0);const l={ES256:"P-256",ES384:"P-384",ES512:"P-521"};l[t]&&a===l[t]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:a},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:a},o,n?[]:["deriveBits"]))}if(!i)throw new TypeError(b0);return r?r[t]=i:ob.set(e,{[t]:i}),i}}});function ydn(e){r1(e,48,"Invalid SPKI structure"),t1(e),r1(e,48,"Expected algorithm identifier");const t=t1(e);return{algIdStart:e.pos,algIdLength:t}}var VF,fhr,t1,r1,tue,ghr,yhr,vhr,whr,Thr,vdn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/asn1.js"(){Vmr(),Sl(),VF=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},fhr=e=>({data:e,pos:0}),t1=e=>{const t=e.data[e.pos++];if(t&128){const r=t&127;let n=0;for(let o=0;o<r;o++)n=n<<8|e.data[e.pos++];return n}return t},r1=(e,t,r)=>{if(e.data[e.pos++]!==t)throw new Error(r)},tue=(e,t)=>{const r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},ghr=e=>{r1(e,6,"Expected algorithm OID");const t=t1(e);return tue(e,t)},yhr=e=>{const t=ghr(e);if(VF(t,[43,101,110]))return"X25519";if(!VF(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");r1(e,6,"Expected curve OID");const r=t1(e),n=tue(e,r);for(const{name:o,oid:i}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(VF(n,i))return o;throw new Error("Unsupported named curve")},vhr=async(e,t,r,n)=>{let o,i;const s=e==="spki",a=()=>s?["verify"]:["sign"],l=()=>s?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},i=a();break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},i=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},i=l();break;case"ES256":case"ES384":case"ES512":{o={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},i=a();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{const c=n.getNamedCurve(t);o=c==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:c}}catch{throw new El("Invalid or unsupported key format")}i=s?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":o={name:"Ed25519"},i=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":o={name:r},i=a();break;default:throw new El('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,o,n?.extractable??!!s,i)},whr=(e,t)=>qmr(e.replace(t,"")),Thr=(e,t,r)=>{const n=whr(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);let o=r;return t?.startsWith?.("ECDH-ES")&&(o||={},o.getNamedCurve=i=>{const s=fhr(i);return ydn(s),yhr(s)}),vhr("spki",n,t,o)}}});async function wdn(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Thr(e,t,r)}async function rue(e,t,r){if(!Cp(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return BF(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new El('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return qF({...e,alg:t,ext:n});case"AKP":{if(typeof e.alg!="string"||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==void 0&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return qF({...e,ext:n})}case"EC":case"OKP":return qF({...e,alg:t,ext:n});default:throw new El('Unsupported "kty" (Key Type) Parameter value')}}var bhr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js"(){QC(),vdn(),dhr(),Sl(),Ip()}});function _hr(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(const s of n.crit){if(!i.has(s))throw new El(`Extension Header Parameter "${s}" is not recognized`);if(o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}var Ehr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js"(){Sl()}});function Tdn(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}var bdn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js"(){}});function Shr(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":khr(e,t,r);break;default:xhr(e,t,r)}}var _0,jF,khr,xhr,Ahr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js"(){Wmr(),Zmr(),Ip(),_0=e=>e?.[Symbol.toStringTag],jF=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},khr=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(GF(t)){if(shr(t)&&jF(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Qce(t))throw new TypeError(Wce(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${_0(t)} instances for symmetric algorithms must be of type "secret"`)}},xhr=(e,t,r)=>{if(GF(t))switch(r){case"decrypt":case"sign":if(ohr(t)&&jF(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(ihr(t)&&jF(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Qce(t))throw new TypeError(Wce(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${_0(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${_0(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${_0(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${_0(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${_0(t)} instances for asymmetric algorithm encryption must be of type "public"`)}}}});async function _dn(e,t,r){if(!Cp(e))throw new Ho("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new Ho('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new Ho("JWS Protected Header incorrect type");if(e.payload===void 0)throw new Ho("JWS Payload missing");if(typeof e.signature!="string")throw new Ho("JWS Signature missing or incorrect type");if(e.header!==void 0&&!Cp(e.header))throw new Ho("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const y=BF(e.protected);n=JSON.parse(nb.decode(y))}catch{throw new Ho("JWS Protected Header is invalid")}if(!rhr(n,e.header))throw new Ho("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header},i=_hr(Ho,new Map([["b64",!0]]),r?.crit,n,o);let s=!0;if(i.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new Ho('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if(typeof a!="string"||!a)throw new Ho('JWS "alg" (Algorithm) Header Parameter missing or invalid');const l=r&&Tdn("algorithms",r.algorithms);if(l&&!l.has(a))throw new Kmr('"alg" (Algorithm) Header Parameter value not allowed');if(s){if(typeof e.payload!="string")throw new Ho("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new Ho("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof t=="function"&&(t=await t(n,e),c=!0),Shr(a,t,"verify");const u=Gmr(e.protected!==void 0?rb(e.protected):new Uint8Array,rb("."),typeof e.payload=="string"?s?rb(e.payload):YC.encode(e.payload):e.payload),d=ehr(e.signature,"signature",Ho),p=await phr(t,a);if(!await fdn(a,p,d,u))throw new Ymr;let f;s?f=ehr(e.payload,"payload",Ho):typeof e.payload=="string"?f=YC.encode(e.payload):f=e.payload;const g={payload:f};return e.protected!==void 0&&(g.protectedHeader=n),e.header!==void 0&&(g.unprotectedHeader=e.header),c?{...g,key:p}:g}var Edn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js"(){QC(),uhr(),Sl(),ZC(),thr(),Ip(),Ip(),Ahr(),Ehr(),bdn(),hhr()}});async function Sdn(e,t,r){if(e instanceof Uint8Array&&(e=nb.decode(e)),typeof e!="string")throw new Ho("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:i,length:s}=e.split(".");if(s!==3)throw new Ho("Invalid Compact JWS");const a=await _dn({payload:o,protected:n,signature:i},t,r),l={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...l,key:a.key}:l}var kdn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js"(){Edn(),Sl(),ZC()}});function n1(e){const t=Rhr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]),n=t[3].toLowerCase();let o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*nue);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*oue);break;case"day":case"days":case"d":o=Math.round(r*HF);break;case"week":case"weeks":case"w":o=Math.round(r*Chr);break;default:o=Math.round(r*Ihr);break}return t[1]==="-"||t[4]==="ago"?-o:o}function E0(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function xdn(e,t,r={}){let n;try{n=JSON.parse(nb.decode(t))}catch{}if(!Cp(n))throw new zF("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&(typeof e.typ!="string"||iue(e.typ)!==iue(o)))throw new lu('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:s,subject:a,audience:l,maxTokenAge:c}=r,u=[...i];c!==void 0&&u.push("iat"),l!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),s!==void 0&&u.push("iss");for(const f of new Set(u.reverse()))if(!(f in n))throw new lu(`missing required "${f}" claim`,n,f,"missing");if(s&&!(Array.isArray(s)?s:[s]).includes(n.iss))throw new lu('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new lu('unexpected "sub" claim value',n,"sub","check_failed");if(l&&!Phr(n.aud,typeof l=="string"?[l]:l))throw new lu('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=n1(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:p}=r,m=Rp(p||new Date);if((n.iat!==void 0||c)&&typeof n.iat!="number")throw new lu('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new lu('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>m+d)throw new lu('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new lu('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=m-d)throw new Kce('"exp" claim timestamp check failed',n,"exp","check_failed")}if(c){const f=m-n.iat,g=typeof c=="number"?c:n1(c);if(f-d>g)throw new Kce('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(f<0-d)throw new lu('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var Rp,nue,oue,HF,Chr,Ihr,Rhr,iue,Phr,Mhr,Ohr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js"(){Sl(),ZC(),Ip(),Rp=e=>Math.floor(e.getTime()/1e3),nue=60,oue=nue*60,HF=oue*24,Chr=HF*7,Ihr=HF*365.25,Rhr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,iue=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,Phr=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,Mhr=class{#e;constructor(e){if(!Cp(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return YC.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e=="number"?this.#e.nbf=E0("setNotBefore",e):e instanceof Date?this.#e.nbf=E0("setNotBefore",Rp(e)):this.#e.nbf=Rp(new Date)+n1(e)}set exp(e){typeof e=="number"?this.#e.exp=E0("setExpirationTime",e):e instanceof Date?this.#e.exp=E0("setExpirationTime",Rp(e)):this.#e.exp=Rp(new Date)+n1(e)}set iat(e){e===void 0?this.#e.iat=Rp(new Date):e instanceof Date?this.#e.iat=E0("setIssuedAt",Rp(e)):typeof e=="string"?this.#e.iat=E0("setIssuedAt",Rp(new Date)+n1(e)):this.#e.iat=E0("setIssuedAt",e)}}}});async function cu(e,t,r){const n=await Sdn(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new zF("JWTs MUST NOT use unencoded payload");const i={payload:xdn(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...i,key:n.key}:i}var Adn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js"(){kdn(),Ohr(),Sl()}}),Dhr,Cdn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js"(){QC(),uhr(),Ip(),Sl(),ZC(),Ahr(),Ehr(),hhr(),thr(),Dhr=class{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return Qmr(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return Qmr(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,t){if(!this.#t&&!this.#r)throw new Ho("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!rhr(this.#t,this.#r))throw new Ho("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this.#t,...this.#r},n=_hr(Ho,new Map([["b64",!0]]),t?.crit,this.#t,r);let o=!0;if(n.has("b64")&&(o=this.#t.b64,typeof o!="boolean"))throw new Ho('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=r;if(typeof i!="string"||!i)throw new Ho('JWS "alg" (Algorithm) Header Parameter missing or invalid');Shr(i,e,"sign");let s,a;o?(s=jce(this.#e),a=rb(s)):(a=this.#e,s="");let l,c;this.#t?(l=jce(JSON.stringify(this.#t)),c=rb(l)):(l="",c=new Uint8Array);const u=Gmr(c,rb("."),a),d=await phr(e,i),p=await hdn(i,d,u),m={signature:jce(p),payload:s};return this.#r&&(m.header=this.#r),this.#t&&(m.protected=l),m}}}}),Nhr,Idn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js"(){Cdn(),Nhr=class{#e;constructor(e){this.#e=new Dhr(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,t){const r=await this.#e.sign(e,t);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}}}),Lhr,Rdn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js"(){Idn(),Sl(),Ohr(),Lhr=class{#e;#t;constructor(e={}){this.#t=new Mhr(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,t){const r=new Nhr(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new zF("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}}});function Pdn(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new El('Unsupported "alg" value for a JSON Web Key Set')}}function Mdn(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(Odn)}function Odn(e){return Cp(e)}async function Fhr(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){const o=await rue({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new Jce("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function $hr(e){const t=new Uhr(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var Uhr,Ddn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js"(){bhr(),Sl(),Ip(),Uhr=class{#e;#t=new WeakMap;constructor(e){if(!Mdn(e))throw new Jce("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},o=Pdn(r),i=this.#e.keys.filter(l=>{let c=o===l.kty;if(c&&typeof n=="string"&&(c=n===l.kid),c&&(typeof l.alg=="string"||o==="AKP")&&(c=r===l.alg),c&&typeof l.use=="string"&&(c=l.use==="sig"),c&&Array.isArray(l.key_ops)&&(c=l.key_ops.includes("verify")),c)switch(r){case"ES256":c=l.crv==="P-256";break;case"ES384":c=l.crv==="P-384";break;case"ES512":c=l.crv==="P-521";break;case"Ed25519":case"EdDSA":c=l.crv==="Ed25519";break}return c}),{0:s,length:a}=i;if(a===0)throw new Xce;if(a!==1){const l=new Jmr,c=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(const u of i)try{yield await Fhr(c,u,r)}catch{}},l}return Fhr(this.#t,s,r)}}}});function Ndn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function Ldn(e,t,r,n=fetch){const o=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(i=>{throw i.name==="TimeoutError"?new Xmr:i});if(o.status!==200)throw new Ha("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new Ha("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function Fdn(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!Cp(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,Cp))}function o1(e,t){const r=new zhr(e,t),n=async(o,i)=>r.getKey(o,i);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>r.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>r.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var sue,Bhr,WF,zhr,$dn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js"(){Sl(),Ddn(),Ip(),(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(sue="jose/v6.2.2"),Bhr=Symbol(),WF=Symbol(),zhr=class{#e;#t;#r;#n;#o;#i;#s;#c;#a;#l;constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration=="number"?t?.timeoutDuration:5e3,this.#r=typeof t?.cooldownDuration=="number"?t?.cooldownDuration:3e4,this.#n=typeof t?.cacheMaxAge=="number"?t?.cacheMaxAge:6e5,this.#s=new Headers(t?.headers),sue&&!this.#s.has("User-Agent")&&this.#s.set("User-Agent",sue),this.#s.has("accept")||(this.#s.set("accept","application/json"),this.#s.append("accept","application/jwk-set+json")),this.#c=t?.[Bhr],t?.[WF]!==void 0&&(this.#l=t?.[WF],Fdn(t?.[WF],this.#n)&&(this.#o=this.#l.uat,this.#a=$hr(this.#l.jwks)))}pendingFetch(){return!!this.#i}coolingDown(){return typeof this.#o=="number"?Date.now()<this.#o+this.#r:!1}fresh(){return typeof this.#o=="number"?Date.now()<this.#o+this.#n:!1}jwks(){return this.#a?.jwks()}async getKey(e,t){(!this.#a||!this.fresh())&&await this.reload();try{return await this.#a(e,t)}catch(r){if(r instanceof Xce&&this.coolingDown()===!1)return await this.reload(),this.#a(e,t);throw r}}async reload(){this.#i&&Ndn()&&(this.#i=void 0),this.#i||=Ldn(this.#e.href,this.#s,AbortSignal.timeout(this.#t),this.#c).then(e=>{this.#a=$hr(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#o=Date.now(),this.#i=void 0}).catch(e=>{throw this.#i=void 0,e}),await this.#i}}}}),sd=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js"(){Adn(),Rdn(),$dn(),bhr()}}),Ghr={};Z(Ghr,{Auth0Provider:()=>qhr});var qhr,Udn=E({"src/lib/auth/providers/auth0.ts"(){"use strict";cc(),Gs(),z(),Jn(),sd(),qhr=class extends _l{type="auth0";domain;clientId;audience;rolesNamespace;permissionsNamespace;jwks=null;constructor(e){if(super(e),!e.domain)throw xt.create("CONFIGURATION_ERROR","Auth0 domain is required",{details:{missingFields:["domain"]}});if(!e.clientId)throw xt.create("CONFIGURATION_ERROR","Auth0 clientId is required",{details:{missingFields:["clientId"]}});this.domain=e.domain,this.clientId=e.clientId,this.audience=e.audience,this.rolesNamespace=e.options?.rolesNamespace,this.permissionsNamespace=e.options?.permissionsNamespace}async initialize(){try{const e=new URL(`https://${this.domain}/.well-known/jwks.json`);this.jwks=o1(e),h.debug(`Auth0 provider initialized for domain: ${this.domain}`)}catch(e){throw xt.create("PROVIDER_INIT_FAILED","Failed to initialize Auth0 JWKS",{cause:e instanceof Error?e:new Error(String(e))})}}async authenticateToken(e,t){this.jwks||await this.initialize();try{if(!this.jwks)return{valid:!1,error:"Auth0 JWKS not initialized"};const{payload:r}=await cu(e,this.jwks,{issuer:`https://${this.domain}/`,audience:this.audience}),n=r;if(this.audience){const c=n.aud;if(!(Array.isArray(c)?c:[c]).includes(this.audience))return{valid:!1,error:`Token audience does not match expected audience: ${this.audience}`}}if(this.clientId){const c=n.aud,u=r.azp,d=Array.isArray(c)?c:[c];if(u){if(u!==this.clientId)return{valid:!1,error:`Token azp claim "${u}" does not match clientId "${this.clientId}"`}}else if(!d.includes(this.clientId))return{valid:!1,error:`Token audience does not include clientId "${this.clientId}"`}}const o=this.rolesNamespace??"roles",i=this.permissionsNamespace??"permissions",s=r[o]||n.roles||[],a=r[i]||n.permissions||[],l={id:n.sub,email:n.email,name:n.name,picture:n.picture,emailVerified:n.email_verified,roles:s,permissions:a,metadata:{iss:n.iss,aud:n.aud}};return{valid:!0,payload:r,user:l,expiresAt:new Date(n.exp*1e3),tokenType:"jwt"}}catch(r){const n=r instanceof Error?r.message:String(r);return h.warn("Auth0 token validation failed:",n),{valid:!1,error:n}}}async getUser(e){const t=process.env.AUTH0_MANAGEMENT_TOKEN;if(!t)return h.warn("AUTH0_MANAGEMENT_TOKEN not set, cannot fetch user profile"),null;try{const n=await Ot()(`https://${this.domain}/api/v2/users/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok){if(n.status===404)return null;throw xt.create("PROVIDER_ERROR",`Auth0 API returned ${n.status}`,{details:{statusCode:n.status}})}const o=await n.json();return{id:o.user_id,email:o.email,name:o.name,picture:o.picture,emailVerified:o.email_verified,roles:o.app_metadata?.roles||[],permissions:o.app_metadata?.permissions||[],createdAt:o.created_at?new Date(o.created_at):void 0,lastLoginAt:o.last_login?new Date(o.last_login):void 0,metadata:o.user_metadata}}catch(r){throw h.error("Failed to fetch Auth0 user:",r),r}}async getUserByEmail(e){const t=process.env.AUTH0_MANAGEMENT_TOKEN;if(!t)return h.warn("AUTH0_MANAGEMENT_TOKEN not set, cannot fetch user by email"),null;try{const n=await Ot()(`https://${this.domain}/api/v2/users-by-email?email=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok)throw xt.create("PROVIDER_ERROR",`Auth0 API returned ${n.status}`,{details:{statusCode:n.status}});const o=await n.json();if(o.length===0)return null;const i=o[0];return{id:i.user_id,email:i.email,name:i.name,picture:i.picture,emailVerified:i.email_verified,roles:i.app_metadata?.roles||[],permissions:i.app_metadata?.permissions||[],createdAt:i.created_at?new Date(i.created_at):void 0,lastLoginAt:i.last_login?new Date(i.last_login):void 0,metadata:i.user_metadata}}catch(r){throw h.error("Failed to fetch Auth0 user by email:",r),r}}async healthCheck(){try{const t=await Ot()(`https://${this.domain}/.well-known/openid-configuration`);return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0,error:t.ok?void 0:`HTTP ${t.status}`}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Vhr={};Z(Vhr,{ClerkProvider:()=>jhr});var jhr,Bdn=E({"src/lib/auth/providers/clerk.ts"(){"use strict";cc(),Gs(),z(),Jn(),sd(),jhr=class extends _l{type="clerk";secretKey;jwtKey;publishableKey;jwks=null;localKey=null;constructor(e){if(super(e),!e.secretKey)throw xt.create("CONFIGURATION_ERROR","Clerk secretKey is required",{details:{missingFields:["secretKey"]}});this.secretKey=e.secretKey,this.jwtKey=e.jwtKey,this.publishableKey=e.publishableKey}async initialize(){const e=new URL("https://api.clerk.com/v1/jwks");this.jwks=o1(e),h.debug("Clerk provider initialized")}async authenticateToken(e,t){return e.includes(".")&&e.split(".").length===3?this.validateJWT(e):this.validateSessionToken(e)}async validateJWT(e){try{let t;if(this.jwtKey)this.localKey||(this.localKey=new TextEncoder().encode(this.jwtKey)),{payload:t}=await cu(e,this.localKey);else{if(this.jwks||await this.initialize(),!this.jwks)return{valid:!1,error:"Clerk JWKS not initialized"};({payload:t}=await cu(e,this.jwks))}if(this.publishableKey&&t.azp&&t.azp!==this.publishableKey)return{valid:!1,error:`Invalid authorized party: ${t.azp}. Expected: ${this.publishableKey}`};const r={id:t.sub,email:t.email,name:t.name,picture:t.picture,emailVerified:t.email_verified,roles:t["https://clerk.dev/roles"]||[],permissions:t["https://clerk.dev/permissions"]||[],organizationId:t.org_id,metadata:{azp:t.azp,sid:t.sid}};return{valid:!0,payload:t,user:r,expiresAt:t.exp?new Date(t.exp*1e3):void 0,tokenType:"jwt"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async validateSessionToken(e){try{const r=await Ot()("https://api.clerk.com/v1/sessions/verify",{method:"POST",headers:{Authorization:`Bearer ${this.secretKey}`,"Content-Type":"application/json"},body:JSON.stringify({token:e})});if(!r.ok)return{valid:!1,error:(await r.json()).errors?.[0]?.message||"Session validation failed"};const n=await r.json(),o=n.user,i=o?.email_addresses,s={id:n.user_id,email:i?.[0]?.email_address,name:o?.first_name?`${o.first_name} ${o.last_name||""}`.trim():void 0,picture:o?.image_url,roles:o?.public_metadata?.roles||[],permissions:o?.public_metadata?.permissions||[],organizationId:n.active_organization_id};return{valid:!0,payload:n,user:s,expiresAt:n.expire_at?new Date(n.expire_at):void 0,tokenType:"session"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async getUser(e){try{const r=await Ot()(`https://api.clerk.com/v1/users/${e}`,{headers:{Authorization:`Bearer ${this.secretKey}`}});if(!r.ok){if(r.status===404)return null;throw xt.create("PROVIDER_ERROR",`Clerk API returned ${r.status}`,{details:{statusCode:r.status}})}const n=await r.json(),o=n.email_addresses;return{id:n.id,email:o?.[0]?.email_address,name:n.first_name?`${n.first_name} ${n.last_name||""}`.trim():void 0,picture:n.image_url,emailVerified:o?.[0]?.verification?.status==="verified",roles:n.public_metadata?.roles||[],permissions:n.public_metadata?.permissions||[],createdAt:n.created_at?new Date(n.created_at):void 0,lastLoginAt:n.last_sign_in_at?new Date(n.last_sign_in_at):void 0,metadata:n.private_metadata}}catch(t){if(h.error("Failed to fetch Clerk user:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async getUserByEmail(e){try{const r=await Ot()(`https://api.clerk.com/v1/users?email_address=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${this.secretKey}`}});if(!r.ok)throw xt.create("PROVIDER_ERROR",`Clerk API returned ${r.status}`,{details:{statusCode:r.status}});const n=await r.json();if(n.length===0)return null;const o=n[0],i=o.email_addresses;return{id:o.id,email:i?.[0]?.email_address,name:o.first_name?`${o.first_name} ${o.last_name||""}`.trim():void 0,picture:o.image_url,emailVerified:i?.[0]?.verification?.status==="verified",roles:o.public_metadata?.roles||[],permissions:o.public_metadata?.permissions||[],createdAt:o.created_at?new Date(o.created_at):void 0,lastLoginAt:o.last_sign_in_at?new Date(o.last_sign_in_at):void 0,metadata:o.private_metadata}}catch(t){if(h.error("Failed to fetch Clerk user by email:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async healthCheck(){try{const t=await Ot()("https://api.clerk.com/v1/organizations?limit=1",{headers:{Authorization:`Bearer ${this.secretKey}`}});return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Hhr={};Z(Hhr,{FirebaseAuthProvider:()=>Whr});var Whr,zdn=E({"src/lib/auth/providers/firebase.ts"(){"use strict";cc(),Gs(),z(),Jn(),sd(),Whr=class extends _l{type="firebase";projectId;apiKey;serviceAccount;jwks=null;constructor(e){if(super(e),!e.projectId)throw xt.create("CONFIGURATION_ERROR","Firebase projectId is required",{details:{missingFields:["projectId"]}});this.projectId=e.projectId,this.apiKey=e.apiKey,this.serviceAccount=e.serviceAccount}async initialize(){const e=new URL("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com");this.jwks=o1(e),h.debug(`Firebase provider initialized for project: ${this.projectId}`)}async authenticateToken(e,t){this.jwks||await this.initialize();try{const r=this.jwks;if(!r)throw xt.create("PROVIDER_INIT_FAILED","Firebase JWKS was not initialized",{details:{provider:"firebase"}});const{payload:n}=await cu(e,r,{issuer:`https://securetoken.google.com/${this.projectId}`,audience:this.projectId}),o=this.payloadToUser(n);return{valid:!0,payload:n,user:o,expiresAt:n.exp?new Date(n.exp*1e3):void 0,tokenType:"jwt"}}catch(r){return this.apiKey?this.validateViaApi(e):{valid:!1,error:r instanceof Error?r.message:String(r)}}}async validateViaApi(e){try{const r=await Ot()(`https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=${this.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({idToken:e}),signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:(await r.json()).error?.message||`Firebase API returned ${r.status}`};const o=(await r.json()).users||[];if(o.length===0)return{valid:!1,error:"User not found"};const i=o[0],s=this.firebaseUserToAuthUser(i);return{valid:!0,payload:i,user:s,tokenType:"jwt"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}payloadToUser(e){const t=e;return{id:e.sub,email:e.email,name:e.name,picture:e.picture,emailVerified:e.email_verified,roles:t.roles||[],permissions:t.permissions||[],metadata:{firebase:{sign_in_provider:e.firebase?.sign_in_provider||"unknown",identities:e.firebase?.identities}}}}firebaseUserToAuthUser(e){let t={};if(e.customAttributes)try{t=JSON.parse(e.customAttributes)}catch{h.warn("Failed to parse Firebase customAttributes, treating as empty")}return{id:e.localId,email:e.email,name:e.displayName,picture:e.photoUrl,emailVerified:e.emailVerified,roles:t.roles||[],permissions:t.permissions||[],createdAt:e.createdAt?new Date(parseInt(e.createdAt)):void 0,lastLoginAt:e.lastLoginAt?new Date(parseInt(e.lastLoginAt)):void 0,metadata:{providerUserInfo:e.providerUserInfo}}}async getUser(e){return this.apiKey?(h.warn("Direct user lookup by ID requires Firebase Admin SDK which is not supported in browser/edge environments"),null):(h.warn("Firebase API key required for user lookup"),null)}async healthCheck(){try{const t=await Ot()("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",{signal:AbortSignal.timeout(5e3)});return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Khr={};Z(Khr,{SupabaseAuthProvider:()=>Jhr});var Jhr,Gdn=E({"src/lib/auth/providers/supabase.ts"(){"use strict";cc(),Gs(),z(),Jn(),sd(),Jhr=class extends _l{type="supabase";supabaseUrl;anonKey;serviceRoleKey;jwtSecret;constructor(e){if(super(e),!e.url)throw xt.create("CONFIGURATION_ERROR","Supabase URL is required",{details:{missingFields:["url"]}});if(!e.anonKey)throw xt.create("CONFIGURATION_ERROR","Supabase anon key is required",{details:{missingFields:["anonKey"]}});this.supabaseUrl=e.url.replace(/\/$/,""),this.anonKey=e.anonKey,this.serviceRoleKey=e.serviceRoleKey,this.jwtSecret=e.jwtSecret}async authenticateToken(e,t){try{if(this.jwtSecret){const s=new TextEncoder().encode(this.jwtSecret),{payload:a}=await cu(e,s);if(!a.sub)return{valid:!1,error:"Token missing sub claim: cannot authenticate without a user identity"};const l=a.role;if(l&&l!=="authenticated")return{valid:!1,error:`Invalid token role: ${l}. Only "authenticated" role is accepted`};const c=this.payloadToUser(a);return{valid:!0,payload:a,user:c,expiresAt:a.exp?new Date(a.exp*1e3):void 0,tokenType:"jwt"}}const n=await Ot()(`${this.supabaseUrl}/auth/v1/user`,{headers:{Authorization:`Bearer ${e}`,apikey:this.anonKey}});if(!n.ok)return{valid:!1,error:`Token validation failed: HTTP ${n.status}`};const o=await n.json(),i=this.supabaseUserToAuthUser(o);return{valid:!0,payload:o,user:i,tokenType:"jwt"}}catch(r){return{valid:!1,error:r instanceof Error?r.message:String(r)}}}payloadToUser(e){const t=e.app_metadata,r=e.user_metadata,n=e.role;return{id:e.sub,email:e.email,name:r?.full_name||r?.name,picture:r?.avatar_url,emailVerified:e.email_confirmed||!1,roles:n?[n]:t?.roles||[],permissions:t?.permissions||[],metadata:r}}supabaseUserToAuthUser(e){const t=e.app_metadata,r=e.user_metadata;return{id:e.id,email:e.email,name:r?.full_name||r?.name,picture:r?.avatar_url,emailVerified:!!e.email_confirmed_at,roles:t?.roles||[],permissions:t?.permissions||[],createdAt:e.created_at?new Date(e.created_at):void 0,lastLoginAt:e.last_sign_in_at?new Date(e.last_sign_in_at):void 0,metadata:r}}async getUser(e){if(!this.serviceRoleKey)return h.warn("Service role key required for user lookup"),null;try{const r=await Ot()(`${this.supabaseUrl}/auth/v1/admin/users/${e}`,{headers:{Authorization:`Bearer ${this.serviceRoleKey}`,apikey:this.anonKey}});if(!r.ok){if(r.status===404)return null;throw xt.create("PROVIDER_ERROR",`Supabase API returned ${r.status}`,{details:{statusCode:r.status}})}const n=await r.json();return this.supabaseUserToAuthUser(n)}catch(t){if(h.error("Failed to fetch Supabase user:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async getUserByEmail(e){if(!this.serviceRoleKey)return h.warn("Service role key required for user lookup by email"),null;try{const r=await Ot()(`${this.supabaseUrl}/auth/v1/admin/users?email=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${this.serviceRoleKey}`,apikey:this.anonKey}});if(!r.ok)throw xt.create("PROVIDER_ERROR",`Supabase API returned ${r.status}`,{details:{statusCode:r.status}});const o=(await r.json()).users||[];return o.length===0?null:this.supabaseUserToAuthUser(o[0])}catch(t){if(h.error("Failed to fetch Supabase user by email:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async healthCheck(){try{const t=await Ot()(`${this.supabaseUrl}/auth/v1/health`,{headers:{apikey:this.anonKey}});return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Xhr={};Z(Xhr,{CognitoProvider:()=>Yhr});var aue,Yhr,qdn=E({"src/lib/auth/providers/CognitoProvider.ts"(){"use strict";sd(),z(),Gs(),cc(),aue=new Map,Yhr=class extends _l{type="cognito";cognitoConfig;jwksUri;jwksCacheDuration;expectedIssuer;constructor(e){if(super(e),e.type!=="cognito")throw xt.create("CONFIGURATION_ERROR",`Invalid provider type: ${e.type}. Expected: cognito`);if(this.cognitoConfig=e,!this.cognitoConfig.userPoolId)throw xt.create("CONFIGURATION_ERROR","Cognito userPoolId is required");if(!this.cognitoConfig.clientId)throw xt.create("CONFIGURATION_ERROR","Cognito clientId is required");if(!this.cognitoConfig.region)throw xt.create("CONFIGURATION_ERROR","Cognito region is required");this.expectedIssuer=`https://cognito-idp.${this.cognitoConfig.region}.amazonaws.com/${this.cognitoConfig.userPoolId}`,this.jwksUri=`${this.expectedIssuer}/.well-known/jwks.json`,this.jwksCacheDuration=e.tokenValidation?.jwksCacheDuration??6e5,h.debug(`[CognitoProvider] Initialized for user pool: ${this.cognitoConfig.userPoolId}`)}async authenticateToken(e){try{const t=this.parseJWT(e);if(!t)return{valid:!1,error:"Failed to decode token",errorCode:"AUTH-006"};if(t.iss!==this.expectedIssuer)return{valid:!1,error:`Invalid issuer: ${t.iss}. Expected: ${this.expectedIssuer}`,errorCode:"AUTH-001"};const r=t.token_use;if(r!=="id"&&r!=="access")return{valid:!1,error:`Invalid token_use: ${r}. Expected: id or access`,errorCode:"AUTH-001"};if(r==="id"){if(t.aud!==this.cognitoConfig.clientId)return{valid:!1,error:`Invalid audience: ${t.aud}. Expected: ${this.cognitoConfig.clientId}`,errorCode:"AUTH-001"}}else if(t.client_id!==this.cognitoConfig.clientId)return{valid:!1,error:`Invalid client_id: ${t.client_id}. Expected: ${this.cognitoConfig.clientId}`,errorCode:"AUTH-001"};const n=this.config.tokenValidation?.clockTolerance??30;if(this.isTokenExpired(t,n))return{valid:!1,error:"Token has expired",errorCode:"AUTH-002",expiresAt:t.exp?new Date(t.exp*1e3):void 0};if(this.config.tokenValidation?.validateSignature!==!1&&!await this.verifySignature(e))return{valid:!1,error:"Invalid token signature",errorCode:"AUTH-004"};const o=this.extractCognitoUser(t,r),i={};for(const[s,a]of Object.entries(t))a!==void 0&&(i[s]=a);return{valid:!0,user:o,claims:i,expiresAt:t.exp?new Date(t.exp*1e3):void 0,issuer:t.iss,audience:t.aud}}catch(t){return h.error("[CognitoProvider] Token validation error:",t),{valid:!1,error:t instanceof Error?t.message:"Token validation failed",errorCode:"AUTH-014"}}}async verifySignature(e){try{const t=e.split(".");if(t.length!==3)return!1;const r=JSON.parse(Buffer.from(t[0],"base64url").toString("utf-8")),n=r.kid;if(!n)return h.warn("[CognitoProvider] Token missing kid in header"),!1;const i=(await this.getJWKS()).keys.find(l=>l.kid===n);if(!i)return h.warn(`[CognitoProvider] Key not found for kid: ${n}`),!1;const s=await rue(i,r.alg),a=this.config.tokenValidation?.clockTolerance??30;return await cu(e,s,{clockTolerance:a}),!0}catch(t){return h.error("[CognitoProvider] Signature verification error:",t),!1}}async getJWKS(){const e=aue.get(this.jwksUri);if(e&&e.expiresAt>Date.now())return e.jwks;try{const t=await fetch(this.jwksUri,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`JWKS fetch failed: ${t.status}`);const r=await t.json();return aue.set(this.jwksUri,{jwks:r,expiresAt:Date.now()+this.jwksCacheDuration}),r}catch(t){throw xt.create("JWKS_FETCH_FAILED",`Failed to fetch JWKS from ${this.jwksUri}: ${t instanceof Error?t.message:String(t)}`,{cause:t instanceof Error?t:void 0})}}extractCognitoUser(e,t){const r=e.sub??"",n=e.email??e["custom:email"],o=e.name??e["cognito:username"]??e.preferred_username,i=e.picture??e["custom:picture"];let s=[];const a=e["cognito:groups"];a&&Array.isArray(a)&&(s=a),s.length===0&&this.rbacConfig.defaultRoles&&(s=this.rbacConfig.defaultRoles);const l=[];if(this.cognitoConfig.customAttributes)for(const d of this.cognitoConfig.customAttributes){const p=e[`custom:${d}`];p&&(p.includes(",")?l.push(...p.split(",").map(m=>m.trim())):l.push(p))}const c={provider:"cognito"};e["cognito:username"]!==void 0&&(c.username=e["cognito:username"]),c.token_use=t,e.auth_time!==void 0&&(c.auth_time=e.auth_time);const u=e.client_id??e.aud;return u!==void 0&&(c.client_id=u),a!==void 0&&(c.cognito_groups=a),{id:r,email:n,name:o,picture:i,roles:s,permissions:l,emailVerified:e.email_verified,providerData:c}}async getUser(e){return h.debug("[CognitoProvider] getUser() is not implemented. Requires AWS SDK (@aws-sdk/client-cognito-identity-provider)."),null}}}}),Zhr={};Z(Zhr,{KeycloakProvider:()=>Qhr});var lue,Qhr,Vdn=E({"src/lib/auth/providers/KeycloakProvider.ts"(){"use strict";sd(),z(),Gs(),cc(),lue=new Map,Qhr=class extends _l{type="keycloak";keycloakConfig;jwksUri;jwksCacheDuration;expectedIssuer;constructor(e){if(super(e),e.type!=="keycloak")throw xt.create("CONFIGURATION_ERROR",`Invalid provider type: ${e.type}. Expected: keycloak`);if(this.keycloakConfig=e,!this.keycloakConfig.serverUrl)throw xt.create("CONFIGURATION_ERROR","Keycloak serverUrl is required");if(!this.keycloakConfig.realm)throw xt.create("CONFIGURATION_ERROR","Keycloak realm is required");if(!this.keycloakConfig.clientId)throw xt.create("CONFIGURATION_ERROR","Keycloak clientId is required");const t=this.keycloakConfig.serverUrl.replace(/\/$/,"");this.expectedIssuer=`${t}/realms/${this.keycloakConfig.realm}`,this.jwksUri=`${this.expectedIssuer}/protocol/openid-connect/certs`,this.jwksCacheDuration=e.tokenValidation?.jwksCacheDuration??6e5,h.debug(`[KeycloakProvider] Initialized for realm: ${this.keycloakConfig.realm}`)}async authenticateToken(e){try{const t=this.parseJWT(e);if(!t)return{valid:!1,error:"Failed to decode token",errorCode:"AUTH-006"};if(t.iss!==this.expectedIssuer)return{valid:!1,error:`Invalid issuer: ${t.iss}. Expected: ${this.expectedIssuer}`,errorCode:"AUTH-001"};if(!(Array.isArray(t.aud)?t.aud:[t.aud]).includes(this.keycloakConfig.clientId))return{valid:!1,error:`Invalid audience: token aud does not contain clientId "${this.keycloakConfig.clientId}"`,errorCode:"AUTH-001"};const n=t.azp;if(n&&n!==this.keycloakConfig.clientId)return{valid:!1,error:`Invalid authorized party: ${n}. Expected: ${this.keycloakConfig.clientId}`,errorCode:"AUTH-001"};const o=this.config.tokenValidation?.clockTolerance??0;if(this.isTokenExpired(t,o))return{valid:!1,error:"Token has expired",errorCode:"AUTH-002",expiresAt:t.exp?new Date(t.exp*1e3):void 0};if(this.isTokenNotYetValid(t,o))return{valid:!1,error:"Token is not yet valid",errorCode:"AUTH-001"};if(this.keycloakConfig.verifyToken!==!1&&this.config.tokenValidation?.validateSignature!==!1&&!await this.verifySignature(e))return{valid:!1,error:"Invalid token signature",errorCode:"AUTH-004"};const i=this.extractKeycloakUser(t),s={};for(const[a,l]of Object.entries(t))l!==void 0&&(s[a]=l);return{valid:!0,user:i,claims:s,expiresAt:t.exp?new Date(t.exp*1e3):void 0,issuer:t.iss,audience:t.aud}}catch(t){return h.error("[KeycloakProvider] Token validation error:",t),{valid:!1,error:t instanceof Error?t.message:"Token validation failed",errorCode:"AUTH-014"}}}async verifySignature(e){try{const t=e.split(".");if(t.length!==3)return!1;const r=JSON.parse(Buffer.from(t[0],"base64url").toString("utf-8")),n=r.kid;if(!n)return h.warn("[KeycloakProvider] Token missing kid in header"),!1;const i=(await this.getJWKS()).keys.find(l=>l.kid===n);if(!i)return h.warn(`[KeycloakProvider] Key not found for kid: ${n}`),!1;const s=await rue(i,r.alg),a=this.config.tokenValidation?.clockTolerance??30;return await cu(e,s,{clockTolerance:a}),!0}catch(t){return h.error("[KeycloakProvider] Signature verification error:",t),!1}}async getJWKS(){const e=lue.get(this.jwksUri);if(e&&e.expiresAt>Date.now())return e.jwks;try{const t=await fetch(this.jwksUri,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`JWKS fetch failed: ${t.status}`);const r=await t.json();return lue.set(this.jwksUri,{jwks:r,expiresAt:Date.now()+this.jwksCacheDuration}),r}catch(t){throw xt.create("JWKS_FETCH_FAILED",`Failed to fetch JWKS from ${this.jwksUri}: ${t instanceof Error?t.message:String(t)}`,{cause:t instanceof Error?t:void 0})}}extractKeycloakUser(e){const t=e.sub??"",r=e.email,n=e.name??e.preferred_username,o=e.picture;let i=[];const s=e.realm_access;s?.roles&&(i=[...s.roles]);const a=e.resource_access;if(a){const d=a[this.keycloakConfig.clientId]?.roles;d&&(i=[...i,...d.map(p=>`${this.keycloakConfig.clientId}:${p}`)]);for(const[p,m]of Object.entries(a))p!==this.keycloakConfig.clientId&&m.roles&&(i=[...i,...m.roles.map(f=>`${p}:${f}`)])}i.length===0&&this.rbacConfig.defaultRoles&&(i=this.rbacConfig.defaultRoles);let l=[];const c=e.scope;c&&(l=c.split(" ").filter(d=>d.length>0));const u={provider:"keycloak"};return e.preferred_username!==void 0&&(u.preferred_username=e.preferred_username),e.given_name!==void 0&&(u.given_name=e.given_name),e.family_name!==void 0&&(u.family_name=e.family_name),s!==void 0&&(u.realm_access=s),a!==void 0&&(u.resource_access=a),e.azp!==void 0&&(u.azp=e.azp),e.session_state!==void 0&&(u.session_state=e.session_state),e.acr!==void 0&&(u.acr=e.acr),e.typ!==void 0&&(u.typ=e.typ),{id:t,email:r,name:n,picture:o,roles:i,permissions:l,emailVerified:e.email_verified,providerData:u}}async getUser(e){if(!this.keycloakConfig.clientSecret)return h.debug("[KeycloakProvider] clientSecret required for admin API"),null;try{const t=await fetch(`${this.expectedIssuer}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:this.keycloakConfig.clientId,client_secret:this.keycloakConfig.clientSecret}),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Failed to get admin token: ${t.status}`);const r=await t.json(),n=this.keycloakConfig.serverUrl.replace(/\/$/,""),o=await fetch(`${n}/admin/realms/${this.keycloakConfig.realm}/users/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${r.access_token}`},signal:AbortSignal.timeout(5e3)});if(!o.ok){if(o.status===404)return null;throw new Error(`Failed to get user: ${o.status}`)}const i=await o.json(),s=await fetch(`${n}/admin/realms/${this.keycloakConfig.realm}/users/${encodeURIComponent(e)}/role-mappings/realm`,{headers:{Authorization:`Bearer ${r.access_token}`},signal:AbortSignal.timeout(5e3)});let a=this.rbacConfig.defaultRoles??[];s.ok&&(a=(await s.json()).map(u=>u.name));const l={};for(const[c,u]of Object.entries(i))u!==void 0&&(l[c]=u);return{id:i.id,email:i.email,name:`${i.firstName??""} ${i.lastName??""}`.trim()||i.username,picture:void 0,roles:a,permissions:[],emailVerified:i.emailVerified,providerData:l,createdAt:i.createdTimestamp?new Date(i.createdTimestamp):void 0}}catch(t){return h.error(`[KeycloakProvider] Failed to get user ${e}:`,t),null}}}}}),efr={};Z(efr,{BetterAuthProvider:()=>tfr});var tfr,jdn=E({"src/lib/auth/providers/betterAuth.ts"(){"use strict";Jn(),Gs(),sd(),cc(),tfr=class extends _l{type="better-auth";secret;baseUrl;secretKey;constructor(e){if(super(e),!e.secret)throw xt.create("CONFIGURATION_ERROR","Better Auth secret is required",{details:{provider:"better-auth",missingFields:["secret"]}});if(!e.baseUrl)throw xt.create("CONFIGURATION_ERROR","Better Auth baseUrl is required",{details:{provider:"better-auth",missingFields:["baseUrl"]}});this.secret=e.secret,this.baseUrl=e.baseUrl.replace(/\/$/,""),this.secretKey=new TextEncoder().encode(this.secret)}async authenticateToken(e,t){if(e.includes(".")&&e.split(".").length===3){const r=await this.validateJWT(e);if(r.valid)return r}return this.validateSessionViaAPI(e)}async validateJWT(e){try{const{payload:t}=await cu(e,this.secretKey);if(!t.sub)return{valid:!1,error:"Token missing required 'sub' claim"};const r={id:t.sub,email:t.email,name:t.name,picture:t.picture,emailVerified:t.email_verified,roles:t.roles||[],permissions:t.permissions||[],metadata:t.metadata};return{valid:!0,payload:t,user:r,expiresAt:t.exp?new Date(t.exp*1e3):void 0,tokenType:"jwt"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async validateSessionViaAPI(e){try{const r=await Ot()(`${this.baseUrl}/api/auth/session`,{headers:{Cookie:`better-auth.session_token=${e}`},signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:`Session validation failed: HTTP ${r.status}`};const n=await r.json();if(!n.user)return{valid:!1,error:"Invalid session"};const o={id:n.user.id,email:n.user.email,name:n.user.name,picture:n.user.image,emailVerified:n.user.emailVerified,roles:n.user.roles||[],permissions:n.user.permissions||[],createdAt:n.user.createdAt?new Date(n.user.createdAt):void 0,metadata:n.user};return{valid:!0,payload:n,user:o,expiresAt:n.session?.expiresAt?new Date(n.session.expiresAt):void 0,tokenType:"session"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async healthCheck(){try{const r=(await Ot()(`${this.baseUrl}/api/auth/session`,{signal:AbortSignal.timeout(5e3)})).status<500;return{healthy:r,providerConnected:r,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),rfr={};Z(rfr,{WorkOSProvider:()=>nfr});var nfr,Hdn=E({"src/lib/auth/providers/workos.ts"(){"use strict";z(),Jn(),Gs(),sd(),cc(),nfr=class extends _l{type="workos";apiKey;clientId;organizationId;jwks=null;constructor(e){if(super(e),!e.apiKey)throw xt.create("CONFIGURATION_ERROR","WorkOS API key is required",{details:{provider:"workos",missingFields:["apiKey"]}});if(!e.clientId)throw xt.create("CONFIGURATION_ERROR","WorkOS client ID is required",{details:{provider:"workos",missingFields:["clientId"]}});this.apiKey=e.apiKey,this.clientId=e.clientId,this.organizationId=e.organizationId}async initialize(){const e=new URL("https://api.workos.com/sso/jwks");this.jwks=o1(e),h.debug("WorkOS provider initialized")}async authenticateToken(e,t){this.jwks||await this.initialize();try{const r=this.jwks;if(!r)throw xt.create("PROVIDER_INIT_FAILED","WorkOS JWKS was not initialized",{details:{provider:"workos"}});const{payload:n}=await cu(e,r,{audience:this.clientId});if(this.organizationId&&n.org_id!==this.organizationId)return{valid:!1,error:`Organization mismatch: expected ${this.organizationId}, got ${n.org_id}`};const o={id:n.sub,email:n.email,name:n.first_name&&n.last_name?`${n.first_name} ${n.last_name}`.trim():void 0,emailVerified:!0,roles:n.roles||[],permissions:n.permissions||[],organizationId:n.org_id,metadata:{connection_id:n.connection_id,connection_type:n.connection_type,idp_id:n.idp_id}};return{valid:!0,payload:n,user:o,expiresAt:n.exp?new Date(n.exp*1e3):void 0,tokenType:"jwt"}}catch{return this.validateSessionViaAPI(e)}}async validateSessionViaAPI(e){try{const r=await Ot()("https://api.workos.com/user_management/authenticate",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({session_token:e,client_id:this.clientId}),signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:`Session validation failed: HTTP ${r.status}`};const n=await r.json();if(!n.user)return{valid:!1,error:"User not found in session"};if(this.organizationId&&n.organization_id!==this.organizationId)return{valid:!1,error:`Organization mismatch: expected ${this.organizationId}, got ${n.organization_id}`};const o={id:n.user.id,email:n.user.email,name:n.user.first_name&&n.user.last_name?`${n.user.first_name} ${n.user.last_name}`.trim():void 0,picture:n.user.profile_picture_url,emailVerified:n.user.email_verified,roles:[],permissions:[],organizationId:n.organization_id,createdAt:n.user.created_at?new Date(n.user.created_at):void 0,metadata:n.user};return{valid:!0,payload:n,user:o,tokenType:"session"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async getUser(e){try{const r=await Ot()(`https://api.workos.com/user_management/users/${e}`,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!r.ok){if(r.status===404)return null;throw xt.create("PROVIDER_ERROR",`WorkOS API returned ${r.status}`,{details:{provider:"workos",statusCode:r.status}})}const n=await r.json();return{id:n.id,email:n.email,name:n.first_name&&n.last_name?`${n.first_name} ${n.last_name}`.trim():void 0,picture:n.profile_picture_url,emailVerified:n.email_verified,roles:[],permissions:[],createdAt:n.created_at?new Date(n.created_at):void 0,metadata:n}}catch(t){throw h.error("Failed to fetch WorkOS user:",t instanceof Error?t.message:String(t)),t}}async getUserByEmail(e){try{const r=await Ot()(`https://api.workos.com/user_management/users?email=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!r.ok)throw xt.create("PROVIDER_ERROR",`WorkOS API returned ${r.status}`,{details:{provider:"workos",statusCode:r.status}});const o=(await r.json()).data||[];if(o.length===0)return null;const i=o[0];return{id:i.id,email:i.email,name:i.first_name&&i.last_name?`${i.first_name} ${i.last_name}`.trim():void 0,picture:i.profile_picture_url,emailVerified:i.email_verified,roles:[],permissions:[],createdAt:i.created_at?new Date(i.created_at):void 0,metadata:i}}catch(t){if(h.error("Failed to fetch WorkOS user by email:",t instanceof Error?t.message:String(t)),t instanceof Error&&t.name==="AuthError")throw t;return null}}async healthCheck(){try{const t=await Ot()("https://api.workos.com/sso/jwks");return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),ofr={};Z(ofr,{OAuth2Provider:()=>ifr});var ifr,Wdn=E({"src/lib/auth/providers/oauth2.ts"(){"use strict";sd(),Jn(),z(),Gs(),cc(),ifr=class extends _l{type="oauth2";authorizationUrl;tokenUrl;userInfoUrl;jwksUrl;clientId;clientSecret;scopes;redirectUrl;usePKCE;jwks=null;constructor(e){if(super(e),!e.authorizationUrl)throw xt.create("CONFIGURATION_ERROR","OAuth2 authorizationUrl is required");if(!e.tokenUrl)throw xt.create("CONFIGURATION_ERROR","OAuth2 tokenUrl is required");if(!e.clientId)throw xt.create("CONFIGURATION_ERROR","OAuth2 clientId is required");this.authorizationUrl=e.authorizationUrl,this.tokenUrl=e.tokenUrl,this.userInfoUrl=e.userInfoUrl,this.jwksUrl=e.jwksUrl,this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.scopes=e.scopes??["openid","profile","email"],this.redirectUrl=e.redirectUrl,this.usePKCE=e.usePKCE??!1}async initialize(){if(this.jwksUrl)try{const e=new URL(this.jwksUrl);this.jwks=o1(e),h.debug(`OAuth2 provider initialized with JWKS: ${this.jwksUrl}`)}catch(e){throw xt.create("PROVIDER_INIT_FAILED","Failed to initialize OAuth2 JWKS",{cause:e instanceof Error?e:new Error(String(e))})}}async authenticateToken(e,t){if(this.jwksUrl){if(this.jwks||await this.initialize(),!this.jwks)return{valid:!1,error:"JWKS not available after initialization"};try{const{payload:r}=await cu(e,this.jwks);if(r.iss){const o=new URL(this.authorizationUrl).origin;if(!r.iss.startsWith(o))return{valid:!1,error:`Invalid issuer: ${r.iss}. Expected origin: ${o}`}}if(r.aud){const o=Array.isArray(r.aud)?r.aud:[r.aud];if(!o.includes(this.clientId))return{valid:!1,error:`Invalid audience: ${o.join(", ")}. Expected: ${this.clientId}`}}if(!r.sub)return{valid:!1,error:"JWT is missing required 'sub' claim: cannot identify user"};const n={id:r.sub,email:r.email,name:r.name,picture:r.picture,roles:r.roles??[],permissions:r.permissions??[],metadata:r};return{valid:!0,payload:r,user:n,expiresAt:r.exp?new Date(r.exp*1e3):void 0,tokenType:"jwt"}}catch{h.debug("JWKS validation failed, trying userinfo endpoint")}}return this.userInfoUrl?this.validateViaUserInfo(e):{valid:!1,error:"No validation method available (provide jwksUrl or userInfoUrl)"}}async validateViaUserInfo(e){try{const t=Ot();if(!this.userInfoUrl)return{valid:!1,error:"UserInfo URL not configured"};const r=await t(this.userInfoUrl,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:`UserInfo endpoint returned ${r.status}`};const n=await r.json(),o=n.sub??n.id;if(!o)return{valid:!1,error:"UserInfo response is missing 'sub' and 'id': cannot identify user"};const i={id:o,email:n.email,name:n.name,picture:n.picture,emailVerified:n.email_verified,roles:n.roles??[],permissions:n.permissions??[],metadata:n};return{valid:!0,payload:n,user:i,tokenType:"oauth"}}catch(t){const r=t instanceof Error?t.message:String(t);return h.warn("OAuth2 userinfo validation failed:",r),{valid:!1,error:r}}}getAuthorizationUrl(e,t){const r=new URLSearchParams({response_type:"code",client_id:this.clientId,scope:this.scopes.join(" "),state:e});return this.redirectUrl&&r.set("redirect_uri",this.redirectUrl),this.usePKCE&&t&&(r.set("code_challenge",t),r.set("code_challenge_method","S256")),`${this.authorizationUrl}?${r.toString()}`}async exchangeCode(e,t){const r=Ot(),n=new URLSearchParams({grant_type:"authorization_code",client_id:this.clientId,code:e});this.clientSecret&&n.set("client_secret",this.clientSecret),this.redirectUrl&&n.set("redirect_uri",this.redirectUrl),this.usePKCE&&t&&n.set("code_verifier",t);const o=await r(this.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),signal:AbortSignal.timeout(5e3)});if(!o.ok)throw xt.create("PROVIDER_ERROR",`Token exchange failed: ${o.status}`);const i=await o.json();return{accessToken:i.access_token,refreshToken:i.refresh_token,idToken:i.id_token}}async healthCheck(){try{const e=Ot(),t=this.jwksUrl??this.authorizationUrl,r=await e(t,{method:"HEAD"});return{healthy:r.ok||r.status===405,providerConnected:!0,sessionStorageHealthy:!0,error:r.ok||r.status===405?void 0:`HTTP ${r.status}`}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),sfr={};Z(sfr,{JWTProvider:()=>afr});var afr,Kdn=E({"src/lib/auth/providers/jwt.ts"(){"use strict";sd(),z(),Gs(),cc(),afr=class extends _l{type="jwt";secret;publicKey;algorithms;issuer;audience;keyObject=null;constructor(e){if(super(e),!e.secret&&!e.publicKey)throw xt.create("CONFIGURATION_ERROR","JWT requires either secret (for HMAC) or publicKey (for RSA/ECDSA)",{details:{provider:"jwt",missingFields:["secret","publicKey"]}});this.secret=e.secret,this.publicKey=e.publicKey,this.algorithms=e.algorithms??(e.secret?["HS256"]:["RS256"]),this.issuer=e.issuer,this.audience=e.audience}async initialize(){try{this.secret?(this.keyObject=new TextEncoder().encode(this.secret),h.debug("JWT provider initialized with symmetric secret")):this.publicKey&&(this.keyObject=await wdn(this.publicKey,this.algorithms[0]),h.debug("JWT provider initialized with asymmetric public key"))}catch(e){throw xt.create("PROVIDER_INIT_FAILED",`Failed to initialize JWT key: ${e instanceof Error?e.message:String(e)}`,{details:{provider:"jwt"},cause:e instanceof Error?e:void 0})}}async authenticateToken(e,t){this.keyObject||await this.initialize();try{const r=this.keyObject;if(!r)throw xt.create("PROVIDER_INIT_FAILED","JWT verification key was not initialized",{details:{provider:"jwt"}});const n={};this.algorithms.length>0&&(n.algorithms=this.algorithms),this.issuer&&(n.issuer=this.issuer),this.audience&&(n.audience=this.audience);const{payload:o}=await cu(e,r,n);if(!o.sub)return{valid:!1,error:"JWT is missing required 'sub' claim: cannot identify user"};const i={id:o.sub,email:o.email,name:o.name,picture:o.picture,emailVerified:o.email_verified,roles:o.roles??[],permissions:o.permissions??o.scope?.split(" ")??[],metadata:{iss:o.iss,aud:o.aud,jti:o.jti}};return{valid:!0,payload:o,user:i,expiresAt:o.exp?new Date(o.exp*1e3):void 0,tokenType:"jwt"}}catch(r){const n=r instanceof Error?r.message:String(r);h.warn("JWT validation failed:",n);let o=n;return n.includes("JWTExpired")?o="Token has expired":n.includes("signature")?o="Invalid token signature":n.includes("audience")?o="Invalid token audience":n.includes("issuer")&&(o="Invalid token issuer"),{valid:!1,error:o}}}async signToken(e,t){if(!this.secret)throw xt.create("CONFIGURATION_ERROR","Token signing requires a secret (symmetric key)",{details:{provider:"jwt"}});this.keyObject||await this.initialize();const r=new Lhr(e).setProtectedHeader({alg:this.algorithms[0]}).setIssuedAt();return this.issuer&&r.setIssuer(this.issuer),this.audience&&r.setAudience(this.audience),t?.expiresIn&&r.setExpirationTime(t.expiresIn),r.sign(this.keyObject)}async healthCheck(){try{return this.keyObject||await this.initialize(),{healthy:this.keyObject!==null,providerConnected:!0,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),lfr={};Z(lfr,{CustomAuthProvider:()=>cfr});var cfr,Jdn=E({"src/lib/auth/providers/custom.ts"(){"use strict";z(),Gs(),cc(),cfr=class extends _l{type="custom";validateTokenFn;getUserFn;createSessionFn;constructor(e){if(super(e),!e.validateToken)throw xt.create("CONFIGURATION_ERROR","Custom validateToken function is required",{details:{provider:"custom",missingFields:["validateToken"]}});this.validateTokenFn=e.validateToken,this.getUserFn=e.getUser,this.createSessionFn=e.createSession}async authenticateToken(e,t){try{return await this.validateTokenFn(e,t)}catch(r){return{valid:!1,error:r instanceof Error?r.message:String(r)}}}async createSession(e,t){if(this.createSessionFn){const r=await this.createSessionFn(e,t);return await this.sessionStorage.save(r),this.emit("auth:login",r.user),r}return super.createSession(e,t)}async getUser(e){if(this.getUserFn)try{return await this.getUserFn(e)}catch(t){return h.error("Custom getUser failed:",t),null}return h.warn("Custom getUser function not provided"),null}async healthCheck(){return{healthy:!0,providerConnected:!0,sessionStorageHealthy:!0}}}}}),Xdn,Ydn,Zdn,Qdn,KF,ufr,cue,epn,ib,tpn,rpn,npn,i1=E({"node-stub:readline"(){Xdn=globalThis.crypto,Ydn=globalThis.ReadableStream||class{},Zdn=globalThis.URL,Qdn=globalThis.URLSearchParams,KF=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},KF.custom=Symbol.for("nodejs.util.inspect.custom"),KF.colors={},KF.styles={},ufr=globalThis.TextDecoder,cue=globalThis.TextEncoder,epn=globalThis.performance||{now:()=>Date.now()},ib=()=>({}),tpn=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new cue().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new cue().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new ufr().decode(this)}},rpn=globalThis.clearTimeout,npn=globalThis.clearInterval}});function Pp(e,t=dfr){const r=e??t,n=Number.isNaN(r)?0:r;if(n===1/0)return;const o=Math.max(0,n)*pfr;if(Number.isFinite(o))return Date.now()-o}var dfr,pfr,Mp=E({"src/lib/localUsage/scanWindow.ts"(){"use strict";dfr=30,pfr=864e5}}),mfr={};Z(mfr,{createClaudeCodeReader:()=>spn});function hfr(){return Rt(Fs(),".claude","projects")}function opn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"modeled",unpricedRequests:0,unpricedModels:[]}}async function ffr(e,t){let r;try{r=await cl(e,{withFileTypes:!0})}catch{return}for(const n of r){const o=Rt(e,n.name);n.isDirectory()?await ffr(o,t):n.isFile()&&n.name.endsWith(".jsonl")&&t.push(o)}}function JF(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function ipn(e,t,r){const n=new Map,o=ib({input:Qh(e,{encoding:"utf8"}),crlfDelay:1/0});try{for await(const i of o){if(!i||i.charCodeAt(0)!==123)continue;let s;try{s=JSON.parse(i)}catch{continue}const a=s;if(a.type!=="assistant"||!a.message?.usage)continue;const l=a.message.usage,c=a.message.id;if(typeof c!="string"||c.length===0)continue;const u={model:a.message.model??"unknown",input:JF(l.input_tokens),output:JF(l.output_tokens),read:JF(l.cache_read_input_tokens),create:JF(l.cache_creation_input_tokens)},d=n.get(c);(!d||u.output>d.output)&&n.set(c,u)}}finally{o.close()}for(const i of n.values())t.requests+=1,t.inputTokens+=i.input,t.outputTokens+=i.output,t.cacheReadTokens+=i.read,t.cacheCreationTokens+=i.create,Ud(uue,i.model)?t.costUsd+=Ls(uue,i.model,{input:i.input,output:i.output,total:i.input+i.output,cacheReadTokens:i.read,cacheCreationTokens:i.create}):(t.unpricedRequests+=1,r.add(i.model))}async function spn(){return{descriptor:{id:XF,displayName:"Claude Code",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"modeled",requiresSqlite:!1},detect:async()=>{try{return(await vo(hfr())).isDirectory()}catch{return!1}},scan:async e=>{const t=opn(),r=[],n=new Set,o=[];await ffr(hfr(),o);const i=Pp(e?.sinceDays);let s=0;for(const a of o)try{if(i!==void 0&&(await vo(a)).mtimeMs<i)continue;await ipn(a,t,n),s+=1}catch(l){r.push({cliId:XF,filePath:a,message:l instanceof Error?l.message:String(l)})}return t.unpricedModels=[...n].sort(),t.costUsd=Math.round(t.costUsd*1e6)/1e6,{cliId:XF,totals:t,filesScanned:s,errors:r}}}}var XF,uue,apn=E({"src/lib/localUsage/claudeCodeReader.ts"(){"use strict";Tn(),i1(),ui(),$s(),kr(),sl(),Mp(),XF="claude-code",uue="anthropic"}}),gfr={};Z(gfr,{createCodexReader:()=>upn});function yfr(){return Rt(Fs(),".codex","sessions")}function lpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}async function vfr(e,t){let r;try{r=await cl(e,{withFileTypes:!0})}catch{return}for(const n of r){const o=Rt(e,n.name);n.isDirectory()?await vfr(o,t):n.isFile()&&n.name.endsWith(".jsonl")&&t.push(o)}}function YF(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function cpn(e){const t=ib({input:Qh(e,{encoding:"utf8"}),crlfDelay:1/0});let r,n=-1,o,i=-1,s=0;try{for await(const a of t){const l=a.includes('"token_count"'),c=a.includes('"turn_context"');if(!l&&!c)continue;let u;try{u=JSON.parse(a)}catch{continue}const d=u;if(d.type==="turn_context"&&d.payload?.model){r=d.payload.model;continue}if(d.payload?.type!=="token_count")continue;const p=d.payload.info?.total_token_usage;if(!p)continue;const m=YF(p.total_tokens);m>i&&(s+=1),i=m,m>n&&(n=m,o={input:YF(p.input_tokens),output:YF(p.output_tokens),cached:YF(p.cached_input_tokens)})}}finally{t.close()}return o?{model:r,billableEvents:s,...o}:null}async function upn(){return{descriptor:{id:ZF,displayName:"Codex",verified:!0,dedupStrategy:"session-dag",costConfidence:"unavailable",requiresSqlite:!1},detect:async()=>{try{return(await vo(yfr())).isDirectory()}catch{return!1}},scan:async e=>{const t=lpn(),r=[],n=new Set,o=[];await vfr(yfr(),o);const i=Pp(e?.sinceDays);let s=0;for(const a of o)try{if(i!==void 0&&(await vo(a)).mtimeMs<i)continue;const l=await cpn(a);if(s+=1,!l)continue;t.requests+=l.billableEvents,t.inputTokens+=Math.max(0,l.input-l.cached),t.cacheReadTokens+=l.cached,t.outputTokens+=l.output,l.model&&n.add(l.model)}catch(l){r.push({cliId:ZF,filePath:a,message:l instanceof Error?l.message:String(l)})}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:ZF,totals:t,filesScanned:s,errors:r}}}}var ZF,dpn=E({"src/lib/localUsage/codexReader.ts"(){"use strict";Tn(),i1(),ui(),$s(),kr(),Mp(),ZF="codex"}}),s1={};Z(s1,{Agent:()=>Cfr,AsyncLocalStorage:()=>Gfr,Buffer:()=>B0r,Channel:()=>I0r,DatabaseSync:()=>U0r,Duplex:()=>Vfr,EventEmitter:()=>zfr,Http2ServerRequest:()=>j0r,Http2ServerResponse:()=>H0r,Interface:()=>$0r,MIMEType:()=>Z0r,PassThrough:()=>jfr,PerformanceObserver:()=>x0r,Readable:()=>pue,ReadableStream:()=>Hfr,Resolver:()=>S0r,STATUS_CODES:()=>Wgr,TextDecoder:()=>fue,TextEncoder:()=>l1,Transform:()=>qfr,URL:()=>d0r,URLSearchParams:()=>p0r,Worker:()=>O0r,Writable:()=>mue,access:()=>kgr,appendFile:()=>ngr,appendFileSync:()=>kfr,arch:()=>qgr,arrayBuffer:()=>W0r,availableParallelism:()=>egr,basename:()=>Dfr,builtinModules:()=>a0r,callbackify:()=>w0r,channel:()=>C0r,chmod:()=>Qfr,chmodSync:()=>Zfr,clearInterval:()=>Y0r,clearTimeout:()=>J0r,closeSync:()=>agr,connect:()=>Kgr,constants:()=>z0r,copyFileSync:()=>igr,cpSync:()=>xfr,cpus:()=>Ugr,createConnection:()=>Jgr,createGunzip:()=>r0r,createGzip:()=>n0r,createHash:()=>due,createHmac:()=>bfr,createInterface:()=>F0r,createReadStream:()=>vgr,createRequire:()=>s0r,createServer:()=>Afr,createWriteStream:()=>ygr,debug:()=>y0r,debuglog:()=>hue,default:()=>wfr,deflateSync:()=>Ygr,deprecate:()=>v0r,deserialize:()=>M0r,dirname:()=>Ofr,exec:()=>Pgr,execFile:()=>Ogr,execFileSync:()=>Dgr,execSync:()=>Mgr,existsSync:()=>Jfr,extname:()=>Nfr,fileURLToPath:()=>m0r,finished:()=>Kfr,format:()=>u0r,freemem:()=>Bgr,fstatSync:()=>lgr,get:()=>Hgr,gunzip:()=>t0r,gunzipSync:()=>Zgr,gzip:()=>e0r,gzipSync:()=>Qgr,hasSubscribers:()=>R0r,homedir:()=>Lgr,hostname:()=>$gr,inflateSync:()=>Xgr,inherits:()=>f0r,inspect:()=>a1,isAbsolute:()=>Ffr,isBuiltin:()=>l0r,isDeepStrictEqual:()=>T0r,isIP:()=>V0r,isIPv4:()=>q0r,isIPv6:()=>G0r,isMainThread:()=>D0r,join:()=>Pfr,loadavg:()=>tgr,lookup:()=>E0r,lstatSync:()=>dgr,mkdir:()=>bgr,mkdirSync:()=>cgr,monitorEventLoopDelay:()=>A0r,normalize:()=>Bfr,ok:()=>o0r,open:()=>Cgr,openSync:()=>sgr,parentPort:()=>N0r,parse:()=>c0r,pathToFileURL:()=>h0r,performance:()=>k0r,pipeline:()=>Wfr,platform:()=>Ngr,posix:()=>Ufr,promises:()=>Tfr,promisify:()=>g0r,randomBytes:()=>_fr,randomUUID:()=>Efr,readFile:()=>wgr,readFileSync:()=>Xfr,readdir:()=>Egr,readdirSync:()=>pgr,realpath:()=>Igr,realpathSync:()=>ogr,relative:()=>Lfr,release:()=>Vgr,rename:()=>xgr,renameSync:()=>hgr,request:()=>jgr,resolve:()=>Mfr,rm:()=>Agr,rmSync:()=>ggr,rmdirSync:()=>fgr,sep:()=>$fr,serialize:()=>P0r,setImmediate:()=>rgr,setInterval:()=>X0r,setTimeout:()=>K0r,spawn:()=>Rgr,stat:()=>_gr,statSync:()=>ugr,strict:()=>i0r,tmpdir:()=>Fgr,toUSVString:()=>b0r,totalmem:()=>zgr,type:()=>Ggr,types:()=>_0r,unlink:()=>Sgr,unlinkSync:()=>mgr,validateHeaderName:()=>Ifr,validateHeaderValue:()=>Rfr,webcrypto:()=>Sfr,workerData:()=>L0r,writeFile:()=>Tgr,writeFileSync:()=>Yfr});var Oo,qn,wfr,Tfr,due,bfr,_fr,Efr,Sfr,kfr,xfr,Afr,Cfr,Ifr,Rfr,Pfr,Mfr,Ofr,Dfr,Nfr,Lfr,Ffr,$fr,Ufr,Bfr,zfr,Gfr,pue,mue,qfr,Vfr,jfr,Hfr,Wfr,Kfr,Jfr,Xfr,Yfr,Zfr,Qfr,egr,tgr,rgr,ngr,ogr,igr,sgr,agr,lgr,cgr,ugr,dgr,pgr,mgr,hgr,fgr,ggr,ygr,vgr,wgr,Tgr,bgr,_gr,Egr,Sgr,kgr,xgr,Agr,Cgr,Igr,Rgr,Pgr,Mgr,Ogr,Dgr,Ngr,Lgr,Fgr,$gr,Ugr,Bgr,zgr,Ggr,qgr,Vgr,jgr,Hgr,Wgr,Kgr,Jgr,Xgr,Ygr,Zgr,Qgr,e0r,t0r,r0r,n0r,o0r,i0r,s0r,a0r,l0r,c0r,u0r,d0r,p0r,m0r,h0r,f0r,g0r,hue,y0r,a1,v0r,w0r,T0r,b0r,_0r,fue,l1,E0r,S0r,k0r,x0r,A0r,C0r,I0r,R0r,P0r,M0r,O0r,D0r,N0r,L0r,F0r,$0r,U0r,B0r,z0r,G0r,q0r,V0r,j0r,H0r,W0r,gue,K0r,J0r,X0r,Y0r,Z0r,QF=E({"node-stub:node:sqlite"(){Oo=()=>{},qn=async()=>{},wfr={},Tfr={readFile:qn,writeFile:qn,mkdir:qn,stat:qn,readdir:qn,unlink:qn,access:qn,rm:qn,rename:qn},due=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new l1().encode(r):r),this},digest(r){let n=0;for(const i of t)for(let s=0;s<i.length;s++)n=(n<<5)-n+i[s]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},bfr=(e,t)=>due(e),_fr=e=>new Uint8Array(e||32),Efr=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),Sfr=globalThis.crypto,kfr=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},xfr=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},Afr=()=>({listen:Oo,close:Oo,on:Oo}),Cfr=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},Ifr=Oo,Rfr=Oo,Pfr=(...e)=>e.join("/"),Mfr=(...e)=>e.join("/"),Ofr=e=>e||"",Dfr=e=>e?.split?.("/")?.pop?.()||"",Nfr=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},Lfr=(e,t)=>t||"",Ffr=()=>!1,$fr="/",Ufr={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},Bfr=e=>e,zfr=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(i=>i===r||i.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},Gfr=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},pue=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},mue=class{write(){return!0}end(){}on(){return this}destroy(){}},qfr=class{push(){}on(){return this}},Vfr=class{on(){return this}},jfr=class{pipe(){return this}on(){return this}},Hfr=globalThis.ReadableStream||class{},Wfr=Oo,Kfr=Oo,Jfr=()=>!1,Xfr=()=>"",Yfr=Oo,Zfr=Oo,Qfr=qn,egr=()=>1,tgr=()=>[0,0,0],rgr=qn,ngr=qn,ogr=e=>e,igr=Oo,sgr=()=>0,agr=Oo,lgr=()=>({}),cgr=Oo,ugr=()=>({}),dgr=()=>({isSymbolicLink:()=>!1}),pgr=()=>[],mgr=Oo,hgr=Oo,fgr=Oo,ggr=Oo,ygr=()=>new mue,vgr=()=>new pue,wgr=qn,Tgr=qn,bgr=qn,_gr=qn,Egr=qn,Sgr=qn,kgr=qn,xgr=qn,Agr=qn,Cgr=async()=>({stat:qn,readFile:qn,close:qn,read:qn,write:qn}),Igr=async e=>e,Rgr=()=>({on:Oo,stdout:{on:Oo},stderr:{on:Oo},kill:Oo}),Pgr=(e,t)=>t?.(null,"",""),Mgr=()=>"",Ogr=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},Dgr=()=>"",Ngr="browser",Lgr=()=>"/",Fgr=()=>"/tmp",$gr=()=>"browser",Ugr=()=>[{}],Bgr=()=>0,zgr=()=>0,Ggr=()=>"Browser",qgr=()=>"wasm",Vgr=()=>"0",jgr=()=>({}),Hgr=()=>({}),Wgr={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},Kgr=()=>({}),Jgr=()=>({}),Xgr=()=>new Uint8Array,Ygr=()=>new Uint8Array,Zgr=()=>new Uint8Array,Qgr=()=>new Uint8Array,e0r=(e,t)=>t?.(null,e),t0r=(e,t)=>t?.(null,e),r0r=()=>({}),n0r=()=>({}),o0r=Oo,i0r={},s0r=()=>()=>({}),a0r=[],l0r=()=>!1,c0r=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),u0r=()=>"",d0r=globalThis.URL,p0r=globalThis.URLSearchParams,m0r=e=>typeof e=="string"?e.replace("file://",""):e,h0r=e=>new globalThis.URL("file://"+e),f0r=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},g0r=e=>(...t)=>new Promise((r,n)=>e(...t,(o,i)=>o?n(o):r(i))),hue=e=>{const t=(...r)=>{};return t.enabled=!1,t},y0r=hue,a1=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},a1.custom=Symbol.for("nodejs.util.inspect.custom"),a1.colors={},a1.styles={},v0r=e=>e,w0r=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},T0r=(e,t)=>JSON.stringify(e)===JSON.stringify(t),b0r=e=>String(e),_0r={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},fue=globalThis.TextDecoder,l1=globalThis.TextEncoder,E0r=(e,t)=>t?.(null,"127.0.0.1",4),S0r=class{},k0r=globalThis.performance||{now:()=>Date.now()},x0r=class{observe(){}disconnect(){}},A0r=()=>({enable:Oo,disable:Oo,percentile:()=>0}),C0r=()=>({}),I0r=class{},R0r=()=>!1,P0r=()=>new Uint8Array,M0r=Oo,O0r=class{},D0r=!0,N0r=null,L0r=null,F0r=()=>({}),$0r=class{},U0r=class{},B0r=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new l1().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new l1().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new fue().decode(this)}},z0r={F_OK:0,R_OK:4,W_OK:2,X_OK:1},G0r=()=>!1,q0r=()=>!1,V0r=()=>0,j0r=class{},H0r=class{},W0r=async()=>new ArrayBuffer(0),gue=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),K0r=(...e)=>gue(globalThis.setTimeout(...e)),J0r=globalThis.clearTimeout,X0r=(...e)=>gue(globalThis.setInterval(...e)),Y0r=globalThis.clearInterval,Z0r=class{constructor(e){this.type=e}toString(){return this.type}}}}),Q0r={};Z(Q0r,{createOpenCodeReader:()=>mpn});function eyr(){return Rt(Fs(),".local","share","opencode","opencode.db")}function ppn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function e$(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function mpn(){return{descriptor:{id:mh,displayName:"OpenCode",verified:!0,dedupStrategy:"rowid-high-water-mark",costConfidence:"unavailable",requiresSqlite:!0},detect:async()=>{try{return(await vo(eyr())).isFile()}catch{return!1}},scan:async e=>{const t=ppn(),r=[],n=new Set,o=eyr();let i;try{const l=await Promise.resolve().then(()=>(QF(),s1));typeof l=="object"&&l!==null&&"DatabaseSync"in l&&typeof l.DatabaseSync=="function"&&(i=l.DatabaseSync)}catch(l){return r.push({cliId:mh,filePath:o,message:`node:sqlite unavailable on this runtime: ${l instanceof Error?l.message:String(l)} (needs Node >=22.13.0; on 22.5-22.12 pass --experimental-sqlite)`}),{cliId:mh,totals:t,filesScanned:0,errors:r}}if(!i)return r.push({cliId:mh,filePath:o,message:"node:sqlite did not expose a callable DatabaseSync \u2014 the experimental API has likely changed shape"}),{cliId:mh,totals:t,filesScanned:0,errors:r};const s=Pp(e?.sinceDays)??0;let a;try{a=new i(o,{readOnly:!0});const l=a.prepare("SELECT data FROM message WHERE time_created >= ?").all(s);for(const c of l){if(typeof c.data!="string")continue;let u;try{u=JSON.parse(c.data)}catch{continue}const d=u,p=d.tokens;if(!p||d.role!=="assistant")continue;const m=e$(p.input),f=e$(p.output),g=e$(p.cache?.read),y=e$(p.cache?.write);m===0&&f===0&&g===0&&y===0||(t.requests+=1,t.inputTokens+=m,t.outputTokens+=f,t.cacheReadTokens+=g,t.cacheCreationTokens+=y,d.modelID&&n.add(d.modelID))}}catch(l){r.push({cliId:mh,filePath:o,message:l instanceof Error?l.message:String(l)})}finally{try{a?.close()}catch{}}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:mh,totals:t,filesScanned:t.requests>0||r.length===0?1:0,errors:r}}}}var mh,hpn=E({"src/lib/localUsage/openCodeReader.ts"(){"use strict";ui(),$s(),kr(),Mp(),mh="opencode"}}),tyr={};Z(tyr,{createQwenCodeReader:()=>vpn});function ryr(){return Rt(Fs(),".qwen","projects")}function fpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function t$(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function nyr(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}async function gpn(e,t){let r;try{r=await cl(e,{withFileTypes:!0})}catch(o){return nyr(o)||t.push({cliId:sb,filePath:e,message:o instanceof Error?o.message:String(o)}),[]}const n=[];for(const o of r){if(!o.isDirectory())continue;const i=Rt(e,o.name,"chats");try{(await vo(i)).isDirectory()&&n.push(i)}catch{}}return n}async function oyr(e,t,r){let n;try{n=await cl(e,{withFileTypes:!0})}catch(o){nyr(o)||r.push({cliId:sb,filePath:e,message:o instanceof Error?o.message:String(o)});return}for(const o of n){const i=Rt(e,o.name);o.isDirectory()?await oyr(i,t,r):o.isFile()&&o.name.endsWith(".jsonl")&&t.push(i)}}async function ypn(e,t,r){const n=new Map,o=ib({input:Qh(e,{encoding:"utf8"}),crlfDelay:1/0});try{for await(const i of o){if(!i||i.charCodeAt(0)!==123)continue;let s;try{s=JSON.parse(i)}catch{continue}const a=s;if(a.type!=="assistant"||!a.usageMetadata)continue;const l=a.uuid;if(typeof l!="string"||l.length===0)continue;const c=a.usageMetadata,u=t$(c.promptTokenCount),d=t$(c.cachedContentTokenCount),p={model:a.model??"unknown",input:Math.max(0,u-d),output:t$(c.candidatesTokenCount)+t$(c.thoughtsTokenCount),cached:d},m=n.get(l),f=p.input+p.output+p.cached,g=m?m.input+m.output+m.cached:-1;(!m||f>g)&&n.set(l,p)}}finally{o.close()}for(const i of n.values())t.requests+=1,t.inputTokens+=i.input,t.outputTokens+=i.output,t.cacheReadTokens+=i.cached,t.unpricedRequests+=1,r.add(i.model)}async function vpn(){return{descriptor:{id:sb,displayName:"Qwen Code",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"unavailable",requiresSqlite:!1},detect:async()=>{try{return(await vo(ryr())).isDirectory()}catch{return!1}},scan:async e=>{const t=fpn(),r=[],n=new Set,o=await gpn(ryr(),r),i=[];for(const l of o)await oyr(l,i,r);const s=Pp(e?.sinceDays);let a=0;for(const l of i)try{if(s!==void 0&&(await vo(l)).mtimeMs<s)continue;await ypn(l,t,n),a+=1}catch(c){r.push({cliId:sb,filePath:l,message:c instanceof Error?c.message:String(c)})}return t.unpricedModels=[...n].sort(),{cliId:sb,totals:t,filesScanned:a,errors:r}}}}var sb,wpn=E({"src/lib/localUsage/qwenCodeReader.ts"(){"use strict";Tn(),i1(),ui(),$s(),kr(),Mp(),sb="qwen-code"}}),iyr={};Z(iyr,{createGeminiCliReader:()=>Spn});function syr(){return Rt(Fs(),".gemini","tmp")}function Tpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function c1(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function ayr(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}async function bpn(e,t){let r;try{r=await cl(e,{withFileTypes:!0})}catch(o){return ayr(o)||t.push({cliId:ab,filePath:e,message:o instanceof Error?o.message:String(o)}),[]}const n=[];for(const o of r){if(!o.isDirectory())continue;const i=Rt(e,o.name,"chats");try{(await vo(i)).isDirectory()&&n.push(i)}catch{}}return n}async function lyr(e,t,r){let n;try{n=await cl(e,{withFileTypes:!0})}catch(o){ayr(o)||r.push({cliId:ab,filePath:e,message:o instanceof Error?o.message:String(o)});return}for(const o of n){const i=Rt(e,o.name);o.isDirectory()?await lyr(i,t,r):o.isFile()&&o.name.endsWith(".jsonl")&&t.push(i)}}function _pn(e){if(typeof e!="object"||e===null)return[];const t=e;if(t.$set!==void 0){if(typeof t.$set!="object"||t.$set===null)return[];const r=t.$set.messages;return Array.isArray(r)?r.filter(n=>typeof n=="object"&&n!==null):[]}return typeof t.id=="string"&&typeof t.type=="string"?[e]:[]}async function Epn(e,t,r){const n=new Map,o=ib({input:Qh(e,{encoding:"utf8"}),crlfDelay:1/0});try{let i=0;for await(const s of o){if(i+=1,i===1||!s||s.charCodeAt(0)!==123)continue;let a;try{a=JSON.parse(s)}catch{continue}for(const l of _pn(a)){if(l.type!=="gemini"||!l.tokens)continue;const c=l.id;if(typeof c!="string"||c.length===0)continue;const u=l.tokens,d=c1(u.input),p=c1(u.cached),m={model:l.model??"unknown",input:Math.max(0,d-p),output:c1(u.output)+c1(u.thoughts)+c1(u.tool),cached:p},f=n.get(c),g=m.input+m.output+m.cached,y=f?f.input+f.output+f.cached:-1;(!f||g>y)&&n.set(c,m)}}}finally{o.close()}for(const i of n.values())t.requests+=1,t.inputTokens+=i.input,t.outputTokens+=i.output,t.cacheReadTokens+=i.cached,t.unpricedRequests+=1,r.add(i.model)}async function Spn(){return{descriptor:{id:ab,displayName:"Gemini CLI",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"unavailable",requiresSqlite:!1},detect:async()=>{try{return(await vo(syr())).isDirectory()}catch{return!1}},scan:async e=>{const t=Tpn(),r=[],n=new Set,o=await bpn(syr(),r),i=[];for(const l of o)await lyr(l,i,r);const s=Pp(e?.sinceDays);let a=0;for(const l of i)try{if(s!==void 0&&(await vo(l)).mtimeMs<s)continue;await Epn(l,t,n),a+=1}catch(c){r.push({cliId:ab,filePath:l,message:c instanceof Error?c.message:String(c)})}return t.unpricedModels=[...n].sort(),{cliId:ab,totals:t,filesScanned:a,errors:r}}}}var ab,kpn=E({"src/lib/localUsage/geminiCliReader.ts"(){"use strict";Tn(),i1(),ui(),$s(),kr(),Mp(),ab="gemini-cli"}}),cyr={};Z(cyr,{createCopilotCliReader:()=>Cpn});function uyr(){return Rt(Fs(),".copilot","session-store.db")}function xpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function u1(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Apn(e){const t=Pp(e)??0;return new Date(t).toISOString()}async function Cpn(){return{descriptor:{id:hh,displayName:"Copilot CLI",verified:!0,dedupStrategy:"rowid-high-water-mark",costConfidence:"unavailable",requiresSqlite:!0},detect:async()=>{try{return(await vo(uyr())).isFile()}catch{return!1}},scan:async e=>{const t=xpn(),r=[],n=new Set,o=uyr();let i;try{const l=await Promise.resolve().then(()=>(QF(),s1));typeof l=="object"&&l!==null&&"DatabaseSync"in l&&typeof l.DatabaseSync=="function"&&(i=l.DatabaseSync)}catch(l){return r.push({cliId:hh,filePath:o,message:`node:sqlite unavailable on this runtime: ${l instanceof Error?l.message:String(l)} (needs Node >=22.13.0; on 22.5-22.12 pass --experimental-sqlite)`}),{cliId:hh,totals:t,filesScanned:0,errors:r}}if(!i)return r.push({cliId:hh,filePath:o,message:"node:sqlite did not expose a callable DatabaseSync \u2014 the experimental API has likely changed shape"}),{cliId:hh,totals:t,filesScanned:0,errors:r};const s=Apn(e?.sinceDays);let a;try{a=new i(o,{readOnly:!0});const l=a.prepare("SELECT model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens, created_at FROM assistant_usage_events WHERE created_at >= ?").all(s);for(const c of l){const u=u1(c.input_tokens),d=u1(c.output_tokens),p=u1(c.cache_read_tokens),m=u1(c.cache_write_tokens),f=u1(c.reasoning_tokens);u===0&&d===0&&p===0&&m===0&&f===0||(t.requests+=1,t.inputTokens+=Math.max(0,u-p-m),t.outputTokens+=d+f,t.cacheReadTokens+=p,t.cacheCreationTokens+=m,n.add(c.model??"unknown"))}}catch(l){r.push({cliId:hh,filePath:o,message:l instanceof Error?l.message:String(l)})}finally{try{a?.close()}catch{}}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:hh,totals:t,filesScanned:t.requests>0||r.length===0?1:0,errors:r}}}}var hh,Ipn=E({"src/lib/localUsage/copilotCliReader.ts"(){"use strict";ui(),$s(),kr(),Mp(),hh="copilot"}}),dyr={};Z(dyr,{createCursorReader:()=>Dpn,extractCursorContextTokens:()=>hyr});function r$(){return Rt(Fs(),".cursor","chats")}function Rpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function pyr(e){const t=[];let r=0;const n=()=>{let o=0,i=0;for(;r<e.length;){const s=e[r];if(r+=1,s===void 0||i>53||(o+=(s&127)*Math.pow(2,i),!Number.isSafeInteger(o)))return null;if(i+=7,(s&128)===0)return o}return null};for(;r<e.length;){const o=n();if(o===null)return null;const i=Math.floor(o/8),s=o%8;if(s===0){const a=n();if(a===null)return null;t.push({field:i,kind:"varint",value:a})}else if(s===2){const a=n();if(a===null||r+a>e.length)return null;t.push({field:i,kind:"bytes",value:e.subarray(r,r+a)}),r+=a}else if(s===5)r+=4;else if(s===1)r+=8;else return null;if(r>e.length)return null}return t}function Ppn(e){const t=pyr(e);if(t===null||t.length===0)return null;let r,n=!1,o=0;for(const i of t)if(i.field===1&&i.kind==="bytes")try{r=yue.decode(i.value)}catch{return null}else if(i.field===2&&i.kind==="bytes")try{yue.decode(i.value),n=!0}catch{return null}else if(i.field===3&&i.kind==="varint")o=i.value;else if(!(i.field===4&&i.kind==="varint"))return null;return r===void 0||!n?null:{name:r,tokens:o}}function myr(e,t){if(t>12)return null;const r=pyr(e);if(r===null)return null;const n=[];for(const o of r)if(o.kind==="bytes"){const i=Ppn(o.value);i!==null&&n.push(i)}if(n.length>=2){const o=n.reduce((i,s)=>i+s.tokens,0);if(o>0){for(const i of r)if(i.kind==="varint"&&i.value===o)return o}}for(const o of r){if(o.kind!=="bytes")continue;const i=myr(o.value,t+1);if(i!==null)return i}return null}function hyr(e){return myr(e,0)}function Mpn(e){if(/^(?:[0-9a-fA-F]{2})+$/.test(e))try{const t=JSON.parse(Buffer.from(e,"hex").toString("utf8"));if(typeof t=="object"&&t!==null&&"latestRootBlobId"in t&&typeof t.latestRootBlobId=="string")return t.latestRootBlobId}catch{}}async function Opn(){const e=r$(),t=[];let r;try{r=await cl(e)}catch{return t}for(const n of r){let o;try{o=await cl(Rt(e,n))}catch{continue}for(const i of o){const s=Rt(e,n,i,"store.db");try{(await vo(s)).isFile()&&t.push(s)}catch{}}}return t}async function Dpn(){return{descriptor:{id:uu,displayName:"Cursor",verified:!0,dedupStrategy:"last-write-wins",costConfidence:"unavailable",requiresSqlite:!0,requestUnit:"session-snapshot"},detect:async()=>{try{return(await vo(r$())).isDirectory()}catch{return!1}},scan:async e=>{const t=Rpn(),r=[];let n;try{const s=await Promise.resolve().then(()=>(QF(),s1));typeof s=="object"&&s!==null&&"DatabaseSync"in s&&typeof s.DatabaseSync=="function"&&(n=s.DatabaseSync)}catch(s){return r.push({cliId:uu,filePath:r$(),message:`node:sqlite unavailable on this runtime: ${s instanceof Error?s.message:String(s)} (needs Node >=22.13.0; on 22.5-22.12 pass --experimental-sqlite)`}),{cliId:uu,totals:t,filesScanned:0,errors:r}}if(!n)return r.push({cliId:uu,filePath:r$(),message:"node:sqlite did not expose a callable DatabaseSync \u2014 the experimental API has likely changed shape"}),{cliId:uu,totals:t,filesScanned:0,errors:r};const o=Pp(e?.sinceDays);let i=0;for(const s of await Opn()){if(o!==void 0)try{if((await vo(s)).mtimeMs<o)continue}catch{continue}let a;try{a=new n(s,{readOnly:!0}),i+=1;const l=a.prepare("SELECT value FROM meta").all(),c=l.find(f=>typeof f.value=="string")?.value;if(c===void 0){if(l.length===0)continue;r.push({cliId:uu,filePath:s,message:"meta row holds no text value \u2014 Cursor's on-disk format has likely changed"});continue}const u=Mpn(c);if(u===void 0){r.push({cliId:uu,filePath:s,message:"meta row is not hex-encoded JSON carrying a latestRootBlobId \u2014 Cursor's on-disk format has likely changed"});continue}const p=a.prepare("SELECT data FROM blobs WHERE id = ?").all(u)[0]?.data;if(!(p instanceof Uint8Array)||p.length===0)continue;const m=hyr(p);if(m===null){r.push({cliId:uu,filePath:s,message:"root blob carried no context breakdown whose parts sum to a stated total \u2014 Cursor's on-disk format has likely changed"});continue}t.requests+=1,t.inputTokens+=m}catch(l){r.push({cliId:uu,filePath:s,message:l instanceof Error?l.message:String(l)})}finally{try{a?.close()}catch{}}}return{cliId:uu,totals:t,filesScanned:i,errors:r}}}}var uu,yue,Npn=E({"src/lib/localUsage/cursorReader.ts"(){"use strict";ui(),$s(),kr(),Mp(),uu="cursor",yue=new TextDecoder("utf-8",{fatal:!0})}}),fyr={};Z(fyr,{createGrokReader:()=>Vpn});function Lpn(){const e=process.env.GROK_HOME;return e!==void 0&&e.trim().length>0?e:Rt(Fs(),".grok")}function gyr(){return Rt(Lpn(),"sessions")}function Fpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function lb(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:0}function yyr(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}async function $pn(e,t){let r;try{r=await cl(e,{withFileTypes:!0})}catch(o){return yyr(o)||t.push({cliId:S0,filePath:e,message:o instanceof Error?o.message:String(o)}),[]}const n=[];for(const o of r){if(!o.isDirectory())continue;const i=Rt(e,o.name);let s;try{s=await cl(i,{withFileTypes:!0})}catch(a){yyr(a)||t.push({cliId:S0,filePath:i,message:a instanceof Error?a.message:String(a)});continue}for(const a of s){if(!a.isDirectory())continue;const l=Rt(i,a.name,"updates.jsonl");try{(await vo(l)).isFile()&&n.push(l)}catch{}}}return n}function Upn(e){const t=typeof e.modelUsage=="object"&&e.modelUsage!==null?Object.keys(e.modelUsage).filter(r=>r.length>0):[];return{input:lb(e.inputTokens),output:lb(e.outputTokens),cacheRead:lb(e.cachedReadTokens),cacheCreation:lb(e.cacheCreationTokens),calls:lb(e.modelCalls),turns:lb(e.numTurns),models:t}}function Bpn(e,t){return t.turns>e.turns&&t.input>=e.input&&t.output>=e.output&&t.cacheRead>=e.cacheRead&&t.cacheCreation>=e.cacheCreation&&t.calls>=e.calls}function zpn(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e,r=vyr.map(n=>t[n]).filter(n=>typeof n=="number");return r.length>0&&r.every(Number.isFinite)}function Gpn(e){if(typeof e!="object"||e===null)return null;const t=e;if(t.method!=="_x.ai/session/update"||typeof t.params!="object"||t.params===null)return null;const r=t.params.update;if(typeof r!="object"||r===null)return null;const n=r;return n.sessionUpdate!=="turn_completed"||n.usage===void 0||n.usage===null?null:{promptId:typeof n.prompt_id=="string"?n.prompt_id:void 0,usage:n.usage}}async function qpn(e,t,r,n){const o=new Map;let i=0;const s=ib({input:Qh(e,{encoding:"utf8"}),crlfDelay:1/0});try{let l=0;for await(const c of s){if(l+=1,!c||c.charCodeAt(0)!==123)continue;let u;try{u=JSON.parse(c)}catch{continue}const d=Gpn(u);if(d!==null){if(!zpn(d.usage)){i+=1,d.promptId!==void 0&&o.delete(d.promptId);continue}o.set(d.promptId??`line:${l}`,Upn(d.usage))}}}finally{s.close()}i>0&&n.push({cliId:S0,filePath:e,message:`${i} completed turn(s) carried a usage record with no recognisable token or call counter \u2014 Grok Build's stream format has likely changed`});let a;for(const l of o.values()){const c=a!==void 0&&Bpn(a,l)?{input:l.input-a.input,output:l.output-a.output,cacheRead:l.cacheRead-a.cacheRead,cacheCreation:l.cacheCreation-a.cacheCreation,calls:l.calls-a.calls}:l;a=l;const u=c.calls>0?c.calls:1;t.requests+=u,t.inputTokens+=c.input,t.outputTokens+=c.output,t.cacheReadTokens+=c.cacheRead,t.cacheCreationTokens+=c.cacheCreation,t.unpricedRequests+=u;for(const d of l.models.length>0?l.models:["unknown"])r.add(d)}}async function Vpn(){return{descriptor:{id:S0,displayName:"Grok Build",verified:!0,dedupStrategy:"last-write-wins",costConfidence:"unavailable",requiresSqlite:!1},detect:async()=>{try{return(await vo(gyr())).isDirectory()}catch{return!1}},scan:async e=>{const t=Fpn(),r=[],n=new Set,o=Pp(e?.sinceDays);let i=0;for(const s of await $pn(gyr(),r))try{if(o!==void 0&&(await vo(s)).mtimeMs<o)continue;await qpn(s,t,n,r),i+=1}catch(a){r.push({cliId:S0,filePath:s,message:a instanceof Error?a.message:String(a)})}return t.unpricedModels=[...n].sort(),{cliId:S0,totals:t,filesScanned:i,errors:r}}}}var S0,vyr,jpn=E({"src/lib/localUsage/grokReader.ts"(){"use strict";Tn(),i1(),ui(),$s(),kr(),Mp(),S0="grok",vyr=["inputTokens","outputTokens","modelCalls"]}}),wyr={};Z(wyr,{createHermesReader:()=>Jpn});function vue(){const e=process.env.HERMES_HOME;return e!==void 0&&e.trim().length>0?e:Rt(Fs(),".hermes")}function Hpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"modeled",unpricedRequests:0,unpricedModels:[]}}function k0(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0}function Tyr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}async function byr(){const e=vue(),t=[],r=Rt(e,"state.db");try{(await vo(r)).isFile()&&t.push(r)}catch{}let n;try{n=(await cl(Rt(e,"profiles"),{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return t}for(const o of n){const i=Rt(e,"profiles",o,"state.db");try{(await vo(i)).isFile()&&t.push(i)}catch{}}return t}function _yr(e,t){const r=e.prepare(`PRAGMA table_info(${t})`).all();return new Set(r.map(n=>n.name).filter(n=>typeof n=="string"))}function Eyr(e,t,r,n=t){return e.has(t)?`${n===t?t:`${t} AS ${n}`}`:`${r} AS ${n}`}function Wpn(e){const t=typeof e.cost_status=="string"?e.cost_status.toLowerCase():"",r=Tyr(e.actual_cost_usd),n=Tyr(e.estimated_cost_usd);return t==="actual"||t==="billed"?r:t==="estimated"||n!==null&&n>0?n:null}function Syr(e){const[t]=e;return e.length===1&&t!==void 0?t:`COALESCE(${e.join(", ")})`}function kyr(e,t,r){const n=k0(e.api_call_count),o=k0(e.input_tokens),i=k0(e.output_tokens);if(n===0&&o+i===0)return;t.requests+=n>0?n:1,t.inputTokens+=o,t.outputTokens+=i,t.cacheReadTokens+=k0(e.cache_read_tokens),t.cacheCreationTokens+=k0(e.cache_write_tokens);const s=Wpn(e);s===null?(t.unpricedRequests+=n>0?n:1,r.add(typeof e.model=="string"&&e.model?e.model:"unknown")):t.costUsd+=s}function Kpn(e,t,r,n,o,i){const s=_yr(e,"sessions");if(s.size===0){i.push({cliId:du,filePath:t,message:"no sessions table \u2014 not a Hermes state store, or one this reader does not understand"});return}const a=Ayr.filter(g=>!s.has(g));if(a.length>0){i.push({cliId:du,filePath:t,message:`sessions table lacks required column(s) ${a.join(", ")} \u2014 Hermes' schema has changed`});return}const l=_yr(e,"session_model_usage"),c=xyr.filter(g=>!l.has(g));if(l.size>0&&c.length>0){i.push({cliId:du,filePath:t,message:`session_model_usage table lacks required column(s) ${c.join(", ")} \u2014 Hermes' schema has changed`});return}const u=l.size>0,d=[s.has("last_activity_at")?"s.last_activity_at":null,s.has("ended_at")?"s.ended_at":null,"s.started_at"].filter(g=>g!==null);if(u){const g=[l.has("last_seen")?"u.last_seen":null,l.has("first_seen")?"u.first_seen":null,...d].filter(T=>T!==null),y=`SELECT u.session_id, u.model, u.api_call_count, u.input_tokens, u.output_tokens, ${wue.map(T=>l.has(T)?`u.${T}`:`0 AS ${T}`).join(", ")}, ${Tue.map(T=>l.has(T)?`u.${T}`:`NULL AS ${T}`).join(", ")}, ${Syr(g)} AS at FROM session_model_usage u LEFT JOIN sessions s ON s.id = u.session_id`,v=e.prepare(y).all();for(const T of v)r!==void 0&&k0(T.at)<r||kyr(T,n,o)}const p=u?" WHERE NOT EXISTS (SELECT 1 FROM session_model_usage u WHERE u.session_id = s.id)":"",m=`SELECT s.id AS session_id, ${Eyr(s,"model","NULL")}, ${Eyr(s,"api_call_count","0")}, s.input_tokens, s.output_tokens, ${wue.map(g=>s.has(g)?`s.${g}`:`0 AS ${g}`).join(", ")}, ${Tue.map(g=>s.has(g)?`s.${g}`:`NULL AS ${g}`).join(", ")}, ${Syr(d)} AS at FROM sessions s${p}`,f=e.prepare(m).all();for(const g of f)r!==void 0&&k0(g.at)<r||kyr(g,n,o)}async function Jpn(){return{descriptor:{id:du,displayName:"Hermes Agent",verified:!0,dedupStrategy:"last-write-wins",costConfidence:"modeled",requiresSqlite:!0},detect:async()=>(await byr()).length>0,scan:async e=>{const t=Hpn(),r=[],n=new Set;let o;try{const l=await Promise.resolve().then(()=>(QF(),s1));typeof l=="object"&&l!==null&&"DatabaseSync"in l&&typeof l.DatabaseSync=="function"&&(o=l.DatabaseSync)}catch(l){return r.push({cliId:du,filePath:vue(),message:`node:sqlite unavailable on this runtime: ${l instanceof Error?l.message:String(l)} (needs Node >=22.13.0; on 22.5-22.12 pass --experimental-sqlite)`}),{cliId:du,totals:t,filesScanned:0,errors:r}}if(!o)return r.push({cliId:du,filePath:vue(),message:"node:sqlite did not expose a callable DatabaseSync \u2014 the experimental API has likely changed shape"}),{cliId:du,totals:t,filesScanned:0,errors:r};const i=Pp(e?.sinceDays),s=i===void 0?void 0:i/1e3;let a=0;for(const l of await byr()){let c;try{c=new o(l,{readOnly:!0}),a+=1,Kpn(c,l,s,t,n,r)}catch(u){r.push({cliId:du,filePath:l,message:u instanceof Error?u.message:String(u)})}finally{try{c?.close()}catch{}}}return t.unpricedModels=[...n].sort(),{cliId:du,totals:t,filesScanned:a,errors:r}}}}var du,xyr,Ayr,wue,Tue,Xpn=E({"src/lib/localUsage/hermesReader.ts"(){"use strict";ui(),$s(),kr(),Mp(),du="hermes",xyr=["session_id","model","api_call_count","input_tokens","output_tokens"],Ayr=["id","started_at","input_tokens","output_tokens"],wue=["cache_read_tokens","cache_write_tokens","reasoning_tokens"],Tue=["estimated_cost_usd","actual_cost_usd","cost_status"]}});Ga(),Os(),Fl(),Tn(),kr(),$t(),z(),pt();var{readFile:bue,writeFile:Cyr,readdir:Ypn,mkdir:Zpn,unlink:Qpn,access:emn}=ns,tmn=class{configPath=".neurolink.config";backupDir=".neurolink.backups";config=null;configCache=new Map;async loadConfig(){return this.config||(this.config=await this.readConfigFile()),this.config}async updateConfig(e,t={}){const{createBackup:r=!0,validate:n=!0,merge:o=!0,reason:i="update",silent:s=!1}=t;r&&(await this.createBackup(i),s||h.info("\u{1F4BE} Backup created before config update"));const a=await this.loadConfig();if(this.config=o?{...a,...e,lastUpdated:Date.now()}:{...e,lastUpdated:Date.now()},n){const l=await this.validateConfig(this.config);if(!l.valid)throw new Error(`Config validation failed: ${l.errors.join(", ")}`)}try{await this.persistConfig(this.config),s||h.info("\u2705 Configuration updated successfully")}catch(l){throw r&&(await this.restoreLatestBackup(),s||h.info("\u{1F504} Auto-restored from backup due to error")),new Error(`Config update failed, restored from backup: ${l.message}`,{cause:l})}}async createBackup(e="manual"){await this.ensureBackupDirectory();const r=`neurolink-config-${new Date().toISOString().replace(/[:.]/g,"-")}.js`,n=Rt(this.backupDir,r),o=await this.loadConfig(),i=this.generateConfigHash(o),s={reason:e,timestamp:Date.now(),version:o.configVersion||"unknown",originalPath:this.configPath,hash:i,size:JSON.stringify(o).length,createdBy:"NeuroLinkConfigManager"},a=`// NeuroLink Config Backup - ${e}
|
|
2242
|
+
`).filter(s=>s.trim());let o=null,i=null;for(const s of n){const a=s.trim();/^\d+[.):]\s*/.test(a)||/^Q[.:]?\s*/i.test(a)?(o&&r.push({question:o,...t&&i?{answer:i}:{}}),o=a.replace(/^\d+[.):]\s*/,"").replace(/^Q[.:]?\s*/i,""),i=null):/^A[.:]?\s*/i.test(a)&&o?i=a.replace(/^A[.:]?\s*/i,""):o&&!i?o+=" "+a:i&&(i+=" "+a)}return o&&r.push({question:o,...t&&i?{answer:i}:{}}),r}async callLLM(e,t){return(await(await Cr.createProvider(t.provider||this.provider,t.modelName||this.modelName)).generate({prompt:e,maxTokens:t.maxTokens||500,temperature:t.temperature||.3}))?.content||""}}}}),zmr,Vce,_l,cc=E({"src/lib/auth/providers/BaseAuthProvider.ts"(){"use strict";$t(),Hn(),z(),Gs(),zmr=xt,Vce=class{sessions=new Map;userSessions=new Map;async get(e){return this.sessions.get(e)??null}async save(e){this.sessions.set(e.id,e);const t=this.userSessions.get(e.user.id)??new Set;t.add(e.id),this.userSessions.set(e.user.id,t)}async delete(e){const t=this.sessions.get(e);if(t){this.sessions.delete(e);const r=this.userSessions.get(t.user.id);r&&(r.delete(e),r.size===0&&this.userSessions.delete(t.user.id))}}async deleteAllForUser(e){const t=this.userSessions.get(e);if(t){for(const r of t)this.sessions.delete(r);this.userSessions.delete(e)}}async getForUser(e){const t=this.userSessions.get(e);if(!t)return[];const r=Date.now(),n=[],o=[];for(const i of t){const s=this.sessions.get(i);if(s){if(s.expiresAt&&s.expiresAt.getTime()<r){o.push(i);continue}if(!s.isValid){o.push(i);continue}n.push(s)}}for(const i of o)this.sessions.delete(i),t.delete(i);return t.size===0&&this.userSessions.delete(e),n}async exists(e){return this.sessions.has(e)}async touch(e){const t=this.sessions.get(e);t&&(t.lastActivityAt=new Date,this.sessions.set(e,t))}async clear(){this.sessions.clear(),this.userSessions.clear()}get size(){return this.sessions.size}},_l=class{config;sessionStorage;sessionConfig;rbacConfig;emitter=new un;constructor(e){const t={fromHeader:{name:"Authorization",scheme:"Bearer"}};this.config={required:!0,...e,tokenExtraction:{...t,...e.tokenExtraction}},this.sessionConfig={storage:"memory",duration:3600,autoRefresh:!0,refreshThreshold:300,allowMultipleSessions:!0,maxSessionsPerUser:10,prefix:"neurolink:session:",...e.session},this.rbacConfig={enabled:!0,defaultRoles:[],roleHierarchy:{},rolePermissions:{},superAdminRoles:["super_admin","root"],...e.rbac},this.sessionStorage=e.session?.customStorage??new Vce,h.debug("[BaseAuthProvider] Initialized")}async extractToken(e){const t=this.config.tokenExtraction;if(t?.fromHeader){const r=t.fromHeader.name.toLowerCase();let n;for(const[o,i]of Object.entries(e.headers))if(o.toLowerCase()===r&&typeof i=="string"){n=i;break}if(typeof n=="string")if(t.fromHeader.scheme){const o=`${t.fromHeader.scheme} `;if(n.startsWith(o))return n.slice(o.length)}else return n}if(t?.fromCookie&&e.cookies){const r=e.cookies[t.fromCookie.name];if(r)return r}if(t?.fromQuery&&e.path)try{const n=new URL(e.path,"http://localhost").searchParams.get(t.fromQuery.name);if(n)return n}catch{}return t?.custom?await Promise.resolve(t.custom(e)):null}async createSession(e,t){const r=new Date,n=this.sessionConfig.duration??3600;if(!this.sessionConfig.allowMultipleSessions)await this.revokeAllSessions(e.id);else if(this.sessionConfig.maxSessionsPerUser){const i=await this.sessionStorage.getForUser(e.id);if(i.length>=this.sessionConfig.maxSessionsPerUser){const s=i.sort((a,l)=>a.createdAt.getTime()-l.createdAt.getTime())[0];s&&await this.sessionStorage.delete(s.id)}}const o={id:Qe(),user:e,accessToken:Qe(),isValid:!0,expiresAt:new Date(r.getTime()+n*1e3),createdAt:r,lastActivityAt:r,ipAddress:t?.ip??t?.ipAddress,userAgent:t?.userAgent};return await this.sessionStorage.save(o),h.debug(`[BaseAuthProvider] Created session ${o.id} for user ${e.id}`),o}async validateSession(e){const t=await this.sessionStorage.get(e);if(!t)return{valid:!1,error:"Session not found",errorCode:"AUTH-010"};if(t.expiresAt&&t.expiresAt.getTime()<Date.now())return await this.sessionStorage.delete(e),{valid:!1,error:"Session expired",errorCode:"AUTH-011"};if(!t.isValid)return{valid:!1,error:"Session revoked",errorCode:"AUTH-012"};let r=!1;if(this.sessionConfig.autoRefresh&&this.sessionConfig.refreshThreshold&&t.expiresAt&&t.expiresAt.getTime()-Date.now()<this.sessionConfig.refreshThreshold*1e3){const n=await this.refreshSession(e);return r=!0,{valid:!0,session:n??void 0,refreshed:r}}return await this.sessionStorage.touch(e),{valid:!0,session:t,refreshed:r}}async refreshSession(e){const t=await this.sessionStorage.get(e);if(!t)throw xt.create("SESSION_NOT_FOUND",`Session not found: ${e}`,{details:{sessionId:e}});if(!t.isValid)throw xt.create("SESSION_REVOKED",`Cannot refresh revoked session: ${e}`,{details:{sessionId:e}});if(t.expiresAt&&t.expiresAt.getTime()<Date.now())throw await this.sessionStorage.delete(e),xt.create("SESSION_EXPIRED",`Cannot refresh expired session: ${e}`,{details:{sessionId:e}});const r=this.sessionConfig.duration??3600;return t.expiresAt=new Date(Date.now()+r*1e3),t.lastActivityAt=new Date,await this.sessionStorage.save(t),h.debug(`[BaseAuthProvider] Refreshed session ${e}`),t}async revokeSession(e){const t=await this.sessionStorage.get(e);t&&(t.isValid=!1,await this.sessionStorage.save(t),h.debug(`[BaseAuthProvider] Revoked session ${e}`))}async revokeAllSessions(e){await this.sessionStorage.deleteAllForUser(e),h.debug(`[BaseAuthProvider] Revoked all sessions for user ${e}`)}async authorize(e,t){if(!this.rbacConfig.enabled)return{authorized:!0,user:e};if(this.isSuperAdmin(e))return{authorized:!0,user:e};const r={authorized:!0,user:e,requiredRoles:t.roles,requiredPermissions:t.permissions,missingRoles:[],missingPermissions:[]};if(t.roles&&t.roles.length>0){const n=this.getEffectiveRoles(e),o=t.roles.filter(i=>!n.has(i));t.requireAllRoles?o.length>0&&(r.authorized=!1,r.missingRoles=o,r.reason=`Missing required roles: ${o.join(", ")}`):t.roles.some(s=>n.has(s))||(r.authorized=!1,r.missingRoles=t.roles,r.reason=`Missing any of required roles: ${t.roles.join(", ")}`)}if(t.permissions&&t.permissions.length>0){const n=this.getEffectivePermissions(e),o=t.permissions.filter(i=>!this.hasPermission(n,i));o.length>0&&(r.authorized=!1,r.missingPermissions=o,r.reason=r.reason?`${r.reason}; Missing permissions: ${o.join(", ")}`:`Missing required permissions: ${o.join(", ")}`)}return r}isSuperAdmin(e){const t=this.rbacConfig.superAdminRoles??[];return e.roles.some(r=>t.includes(r))}getEffectiveRoles(e){const t=new Set(e.roles),r=this.rbacConfig.roleHierarchy??{};let n=!0;for(;n;){n=!1;for(const o of t){const i=r[o]??[];for(const s of i)t.has(s)||(t.add(s),n=!0)}}return t}getEffectivePermissions(e){const t=new Set(e.permissions),r=this.rbacConfig.rolePermissions??{},n=this.getEffectiveRoles(e);for(const o of n){const i=r[o]??[];for(const s of i)t.add(s)}return t}hasPermission(e,t){if(e.has(t)||e.has("*"))return!0;const r=t.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(e.has(o))return!0}return!1}parseJWT(e){try{const t=e.split(".");if(t.length!==3)return null;const r=t[1],n=Buffer.from(r,"base64url").toString("utf-8");return JSON.parse(n)}catch{return null}}isTokenExpired(e,t=0){if(!e.exp)return!1;const r=Math.floor(Date.now()/1e3);return e.exp+t<r}isTokenNotYetValid(e,t=0){if(!e.nbf)return!1;const r=Math.floor(Date.now()/1e3);return e.nbf-t>r}extractUserFromClaims(e,t){const r=t?.rolesClaimKey??"roles",n=t?.permissionsClaimKey??"permissions",o=t?.idClaimKey??"sub",i=Array.isArray(e[r])?e[r]:this.rbacConfig.defaultRoles??[],s=Array.isArray(e[n])?e[n]:[];return{id:e[o]??"",email:e.email,name:e.name,picture:e.picture,roles:i,permissions:s,emailVerified:e.email_verified,providerData:e}}async getUser(e){return h.debug(`[BaseAuthProvider] getUser not implemented for ${this.type}`),null}async updateUserRoles(e,t){throw xt.create("PROVIDER_ERROR",`updateUserRoles not supported by ${this.type} provider`)}async updateUserPermissions(e,t){throw xt.create("PROVIDER_ERROR",`updateUserPermissions not supported by ${this.type} provider`)}async dispose(){await this.sessionStorage.clear(),h.debug(`[BaseAuthProvider] Disposed ${this.type} provider`)}async authorizeUser(e,t){return this.authorize(e,{permissions:[t]})}async authorizeRoles(e,t){return this.authorize(e,{roles:t})}async authorizePermissions(e,t){return this.authorize(e,{permissions:t})}async getSession(e){return this.sessionStorage.get(e)}async destroySession(e){await this.revokeSession(e)}async getUserSessions(e){return this.sessionStorage.getForUser(e)}async destroyAllUserSessions(e){await this.revokeAllSessions(e)}async authenticateRequest(e){const t=await this.extractToken(e);if(!t)return this.config.required&&this.emitter.emit("auth:unauthorized",e,"No token provided"),null;const r=await this.authenticateToken(t,e);if(!r.valid||!r.user)return this.emitter.emit("auth:unauthorized",e,r.error??"Invalid token"),null;const i=(await this.getUserSessions(r.user.id)).find(s=>s.isValid&&(!s.expiresAt||s.expiresAt.getTime()>Date.now()))??await this.createSession(r.user,e);return{...e,user:r.user,session:i,request:e,authenticatedAt:new Date,provider:this.type}}async healthCheck(){return{healthy:!0,providerConnected:!0,sessionStorageHealthy:!0}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}emit(e,...t){this.emitter.emit(e,...t)}}}});function Gmr(...e){const t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function rb(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){const n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}var YC,nb,adn,ZC=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js"(){YC=new TextEncoder,nb=new TextDecoder,adn=2**32}});function ldn(e){if(Uint8Array.prototype.toBase64)return e.toBase64();const t=32768,r=[];for(let n=0;n<e.length;n+=t)r.push(String.fromCharCode.apply(null,e.subarray(n,n+t)));return btoa(r.join(""))}function qmr(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var Vmr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js"(){}});function BF(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:nb.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=nb.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return qmr(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function jce(e){let t=e;return typeof t=="string"&&(t=YC.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):ldn(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var QC=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js"(){ZC(),Vmr()}});function cdn(e){return parseInt(e.name.slice(4),10)}function Hce(e,t){if(cdn(e.hash)!==t)throw Ap(`SHA-${t}`,"algorithm.hash")}function udn(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ddn(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function pdn(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!T0(e.algorithm,"HMAC"))throw Ap("HMAC");Hce(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!T0(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Ap("RSASSA-PKCS1-v1_5");Hce(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!T0(e.algorithm,"RSA-PSS"))throw Ap("RSA-PSS");Hce(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!T0(e.algorithm,"Ed25519"))throw Ap("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!T0(e.algorithm,t))throw Ap(t);break}case"ES256":case"ES384":case"ES512":{if(!T0(e.algorithm,"ECDSA"))throw Ap("ECDSA");const n=udn(t);if(e.algorithm.namedCurve!==n)throw Ap(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ddn(e,r)}var Ap,T0,mdn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js"(){Ap=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),T0=(e,t)=>e.name===t}});function jmr(e,t,...r){if(r=r.filter(Boolean),r.length>2){const n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Hmr,Wce,Wmr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js"(){Hmr=(e,...t)=>jmr("Key must be ",e,...t),Wce=(e,t,...r)=>jmr(`Key for the ${e} algorithm must be `,t,...r)}}),Ha,lu,Kce,Kmr,El,Ho,zF,Jce,Xce,Jmr,Xmr,Ymr,Sl=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js"(){Ha=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)}},lu=class extends Ha{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}},Kce=class extends Ha{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}},Kmr=class extends Ha{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},El=class extends Ha{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Ho=class extends Ha{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},zF=class extends Ha{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},Jce=class extends Ha{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Xce=class extends Ha{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)}},Jmr=class extends Ha{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}},Xmr=class extends Ha{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}},Ymr=class extends Ha{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}}}),Yce,Zce,Qce,Zmr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js"(){Yce=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Zce=e=>e?.[Symbol.toStringTag]==="KeyObject",Qce=e=>Yce(e)||Zce(e)}});function Qmr(e,t){if(e)throw new TypeError(`${t} can only be called once`)}function ehr(e,t,r){try{return BF(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}var thr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js"(){QC()}});function Cp(e){if(!nhr(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function rhr(...e){const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){const o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(const i of o){if(r.has(i))return!1;r.add(i)}}return!0}var nhr,GF,ohr,ihr,shr,Ip=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js"(){nhr=e=>typeof e=="object"&&e!==null,GF=e=>Cp(e)&&typeof e.kty=="string",ohr=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),ihr=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,shr=e=>e.kty==="oct"&&typeof e.k=="string"}});function ahr(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function lhr(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new El(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function chr(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Hmr(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return pdn(t,e,r),t}async function hdn(e,t,r){const n=await chr(e,t,"sign");ahr(e,n);const o=await crypto.subtle.sign(lhr(e,n.algorithm),n,r);return new Uint8Array(o)}async function fdn(e,t,r,n){const o=await chr(e,t,"verify");ahr(e,o);const i=lhr(e,o.algorithm);try{return await crypto.subtle.verify(i,o,r,n)}catch{return!1}}var uhr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js"(){Sl(),mdn(),Wmr()}});function gdn(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new El(e1)}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new El(e1)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new El(e1)}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new El(e1)}break}default:throw new El('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function qF(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=gdn(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}var e1,dhr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js"(){Sl(),e1='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'}});async function phr(e,t){if(e instanceof Uint8Array||Yce(e))return e;if(Zce(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return mhr(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return eue(e,r,t)}if(GF(e))return e.k?BF(e.k):eue(e,e,t,!0);throw new Error("unreachable")}var b0,ob,eue,mhr,hhr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js"(){Ip(),QC(),dhr(),Zmr(),b0="given KeyObject instance cannot be used for this algorithm",eue=async(e,t,r,n=!1)=>{ob||=new WeakMap;let o=ob.get(e);if(o?.[r])return o[r];const i=await qF({...t,alg:r});return n&&Object.freeze(e),o?o[r]=i:ob.set(e,{[r]:i}),i},mhr=(e,t)=>{ob||=new WeakMap;let r=ob.get(e);if(r?.[t])return r[t];const n=e.type==="public",o=!!n;let i;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(b0)}i=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(b0);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(b0);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let s;switch(t){case"RSA-OAEP":s="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":s="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":s="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":s="SHA-512";break;default:throw new TypeError(b0)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:s},o,n?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:s},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){const a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(b0);const l={ES256:"P-256",ES384:"P-384",ES512:"P-521"};l[t]&&a===l[t]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:a},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:a},o,n?[]:["deriveBits"]))}if(!i)throw new TypeError(b0);return r?r[t]=i:ob.set(e,{[t]:i}),i}}});function ydn(e){r1(e,48,"Invalid SPKI structure"),t1(e),r1(e,48,"Expected algorithm identifier");const t=t1(e);return{algIdStart:e.pos,algIdLength:t}}var VF,fhr,t1,r1,tue,ghr,yhr,vhr,whr,Thr,vdn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/asn1.js"(){Vmr(),Sl(),VF=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},fhr=e=>({data:e,pos:0}),t1=e=>{const t=e.data[e.pos++];if(t&128){const r=t&127;let n=0;for(let o=0;o<r;o++)n=n<<8|e.data[e.pos++];return n}return t},r1=(e,t,r)=>{if(e.data[e.pos++]!==t)throw new Error(r)},tue=(e,t)=>{const r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},ghr=e=>{r1(e,6,"Expected algorithm OID");const t=t1(e);return tue(e,t)},yhr=e=>{const t=ghr(e);if(VF(t,[43,101,110]))return"X25519";if(!VF(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");r1(e,6,"Expected curve OID");const r=t1(e),n=tue(e,r);for(const{name:o,oid:i}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(VF(n,i))return o;throw new Error("Unsupported named curve")},vhr=async(e,t,r,n)=>{let o,i;const s=e==="spki",a=()=>s?["verify"]:["sign"],l=()=>s?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},i=a();break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},i=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},i=l();break;case"ES256":case"ES384":case"ES512":{o={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},i=a();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{const c=n.getNamedCurve(t);o=c==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:c}}catch{throw new El("Invalid or unsupported key format")}i=s?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":o={name:"Ed25519"},i=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":o={name:r},i=a();break;default:throw new El('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,o,n?.extractable??!!s,i)},whr=(e,t)=>qmr(e.replace(t,"")),Thr=(e,t,r)=>{const n=whr(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);let o=r;return t?.startsWith?.("ECDH-ES")&&(o||={},o.getNamedCurve=i=>{const s=fhr(i);return ydn(s),yhr(s)}),vhr("spki",n,t,o)}}});async function wdn(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Thr(e,t,r)}async function rue(e,t,r){if(!Cp(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return BF(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new El('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return qF({...e,alg:t,ext:n});case"AKP":{if(typeof e.alg!="string"||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==void 0&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return qF({...e,ext:n})}case"EC":case"OKP":return qF({...e,alg:t,ext:n});default:throw new El('Unsupported "kty" (Key Type) Parameter value')}}var bhr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js"(){QC(),vdn(),dhr(),Sl(),Ip()}});function _hr(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(const s of n.crit){if(!i.has(s))throw new El(`Extension Header Parameter "${s}" is not recognized`);if(o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}var Ehr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js"(){Sl()}});function Tdn(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}var bdn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js"(){}});function Shr(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":khr(e,t,r);break;default:xhr(e,t,r)}}var _0,jF,khr,xhr,Ahr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js"(){Wmr(),Zmr(),Ip(),_0=e=>e?.[Symbol.toStringTag],jF=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},khr=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(GF(t)){if(shr(t)&&jF(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Qce(t))throw new TypeError(Wce(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${_0(t)} instances for symmetric algorithms must be of type "secret"`)}},xhr=(e,t,r)=>{if(GF(t))switch(r){case"decrypt":case"sign":if(ohr(t)&&jF(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(ihr(t)&&jF(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Qce(t))throw new TypeError(Wce(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${_0(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${_0(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${_0(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${_0(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${_0(t)} instances for asymmetric algorithm encryption must be of type "public"`)}}}});async function _dn(e,t,r){if(!Cp(e))throw new Ho("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new Ho('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new Ho("JWS Protected Header incorrect type");if(e.payload===void 0)throw new Ho("JWS Payload missing");if(typeof e.signature!="string")throw new Ho("JWS Signature missing or incorrect type");if(e.header!==void 0&&!Cp(e.header))throw new Ho("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const y=BF(e.protected);n=JSON.parse(nb.decode(y))}catch{throw new Ho("JWS Protected Header is invalid")}if(!rhr(n,e.header))throw new Ho("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header},i=_hr(Ho,new Map([["b64",!0]]),r?.crit,n,o);let s=!0;if(i.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new Ho('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if(typeof a!="string"||!a)throw new Ho('JWS "alg" (Algorithm) Header Parameter missing or invalid');const l=r&&Tdn("algorithms",r.algorithms);if(l&&!l.has(a))throw new Kmr('"alg" (Algorithm) Header Parameter value not allowed');if(s){if(typeof e.payload!="string")throw new Ho("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new Ho("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof t=="function"&&(t=await t(n,e),c=!0),Shr(a,t,"verify");const u=Gmr(e.protected!==void 0?rb(e.protected):new Uint8Array,rb("."),typeof e.payload=="string"?s?rb(e.payload):YC.encode(e.payload):e.payload),d=ehr(e.signature,"signature",Ho),p=await phr(t,a);if(!await fdn(a,p,d,u))throw new Ymr;let f;s?f=ehr(e.payload,"payload",Ho):typeof e.payload=="string"?f=YC.encode(e.payload):f=e.payload;const g={payload:f};return e.protected!==void 0&&(g.protectedHeader=n),e.header!==void 0&&(g.unprotectedHeader=e.header),c?{...g,key:p}:g}var Edn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js"(){QC(),uhr(),Sl(),ZC(),thr(),Ip(),Ip(),Ahr(),Ehr(),bdn(),hhr()}});async function Sdn(e,t,r){if(e instanceof Uint8Array&&(e=nb.decode(e)),typeof e!="string")throw new Ho("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:i,length:s}=e.split(".");if(s!==3)throw new Ho("Invalid Compact JWS");const a=await _dn({payload:o,protected:n,signature:i},t,r),l={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...l,key:a.key}:l}var kdn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js"(){Edn(),Sl(),ZC()}});function n1(e){const t=Rhr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]),n=t[3].toLowerCase();let o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*nue);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*oue);break;case"day":case"days":case"d":o=Math.round(r*HF);break;case"week":case"weeks":case"w":o=Math.round(r*Chr);break;default:o=Math.round(r*Ihr);break}return t[1]==="-"||t[4]==="ago"?-o:o}function E0(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function xdn(e,t,r={}){let n;try{n=JSON.parse(nb.decode(t))}catch{}if(!Cp(n))throw new zF("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&(typeof e.typ!="string"||iue(e.typ)!==iue(o)))throw new lu('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:s,subject:a,audience:l,maxTokenAge:c}=r,u=[...i];c!==void 0&&u.push("iat"),l!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),s!==void 0&&u.push("iss");for(const f of new Set(u.reverse()))if(!(f in n))throw new lu(`missing required "${f}" claim`,n,f,"missing");if(s&&!(Array.isArray(s)?s:[s]).includes(n.iss))throw new lu('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new lu('unexpected "sub" claim value',n,"sub","check_failed");if(l&&!Phr(n.aud,typeof l=="string"?[l]:l))throw new lu('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=n1(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:p}=r,m=Rp(p||new Date);if((n.iat!==void 0||c)&&typeof n.iat!="number")throw new lu('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new lu('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>m+d)throw new lu('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new lu('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=m-d)throw new Kce('"exp" claim timestamp check failed',n,"exp","check_failed")}if(c){const f=m-n.iat,g=typeof c=="number"?c:n1(c);if(f-d>g)throw new Kce('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(f<0-d)throw new lu('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var Rp,nue,oue,HF,Chr,Ihr,Rhr,iue,Phr,Mhr,Ohr=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js"(){Sl(),ZC(),Ip(),Rp=e=>Math.floor(e.getTime()/1e3),nue=60,oue=nue*60,HF=oue*24,Chr=HF*7,Ihr=HF*365.25,Rhr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,iue=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,Phr=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,Mhr=class{#e;constructor(e){if(!Cp(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return YC.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e=="number"?this.#e.nbf=E0("setNotBefore",e):e instanceof Date?this.#e.nbf=E0("setNotBefore",Rp(e)):this.#e.nbf=Rp(new Date)+n1(e)}set exp(e){typeof e=="number"?this.#e.exp=E0("setExpirationTime",e):e instanceof Date?this.#e.exp=E0("setExpirationTime",Rp(e)):this.#e.exp=Rp(new Date)+n1(e)}set iat(e){e===void 0?this.#e.iat=Rp(new Date):e instanceof Date?this.#e.iat=E0("setIssuedAt",Rp(e)):typeof e=="string"?this.#e.iat=E0("setIssuedAt",Rp(new Date)+n1(e)):this.#e.iat=E0("setIssuedAt",e)}}}});async function cu(e,t,r){const n=await Sdn(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new zF("JWTs MUST NOT use unencoded payload");const i={payload:xdn(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...i,key:n.key}:i}var Adn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js"(){kdn(),Ohr(),Sl()}}),Dhr,Cdn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js"(){QC(),uhr(),Ip(),Sl(),ZC(),Ahr(),Ehr(),hhr(),thr(),Dhr=class{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return Qmr(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return Qmr(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,t){if(!this.#t&&!this.#r)throw new Ho("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!rhr(this.#t,this.#r))throw new Ho("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this.#t,...this.#r},n=_hr(Ho,new Map([["b64",!0]]),t?.crit,this.#t,r);let o=!0;if(n.has("b64")&&(o=this.#t.b64,typeof o!="boolean"))throw new Ho('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=r;if(typeof i!="string"||!i)throw new Ho('JWS "alg" (Algorithm) Header Parameter missing or invalid');Shr(i,e,"sign");let s,a;o?(s=jce(this.#e),a=rb(s)):(a=this.#e,s="");let l,c;this.#t?(l=jce(JSON.stringify(this.#t)),c=rb(l)):(l="",c=new Uint8Array);const u=Gmr(c,rb("."),a),d=await phr(e,i),p=await hdn(i,d,u),m={signature:jce(p),payload:s};return this.#r&&(m.header=this.#r),this.#t&&(m.protected=l),m}}}}),Nhr,Idn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js"(){Cdn(),Nhr=class{#e;constructor(e){this.#e=new Dhr(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,t){const r=await this.#e.sign(e,t);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}}}),Lhr,Rdn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js"(){Idn(),Sl(),Ohr(),Lhr=class{#e;#t;constructor(e={}){this.#t=new Mhr(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,t){const r=new Nhr(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new zF("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}}});function Pdn(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new El('Unsupported "alg" value for a JSON Web Key Set')}}function Mdn(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(Odn)}function Odn(e){return Cp(e)}async function Fhr(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){const o=await rue({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new Jce("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function $hr(e){const t=new Uhr(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var Uhr,Ddn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js"(){bhr(),Sl(),Ip(),Uhr=class{#e;#t=new WeakMap;constructor(e){if(!Mdn(e))throw new Jce("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},o=Pdn(r),i=this.#e.keys.filter(l=>{let c=o===l.kty;if(c&&typeof n=="string"&&(c=n===l.kid),c&&(typeof l.alg=="string"||o==="AKP")&&(c=r===l.alg),c&&typeof l.use=="string"&&(c=l.use==="sig"),c&&Array.isArray(l.key_ops)&&(c=l.key_ops.includes("verify")),c)switch(r){case"ES256":c=l.crv==="P-256";break;case"ES384":c=l.crv==="P-384";break;case"ES512":c=l.crv==="P-521";break;case"Ed25519":case"EdDSA":c=l.crv==="Ed25519";break}return c}),{0:s,length:a}=i;if(a===0)throw new Xce;if(a!==1){const l=new Jmr,c=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(const u of i)try{yield await Fhr(c,u,r)}catch{}},l}return Fhr(this.#t,s,r)}}}});function Ndn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function Ldn(e,t,r,n=fetch){const o=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(i=>{throw i.name==="TimeoutError"?new Xmr:i});if(o.status!==200)throw new Ha("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new Ha("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function Fdn(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!Cp(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,Cp))}function o1(e,t){const r=new zhr(e,t),n=async(o,i)=>r.getKey(o,i);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>r.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>r.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var sue,Bhr,WF,zhr,$dn=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js"(){Sl(),Ddn(),Ip(),(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(sue="jose/v6.2.2"),Bhr=Symbol(),WF=Symbol(),zhr=class{#e;#t;#r;#n;#o;#i;#s;#c;#a;#l;constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration=="number"?t?.timeoutDuration:5e3,this.#r=typeof t?.cooldownDuration=="number"?t?.cooldownDuration:3e4,this.#n=typeof t?.cacheMaxAge=="number"?t?.cacheMaxAge:6e5,this.#s=new Headers(t?.headers),sue&&!this.#s.has("User-Agent")&&this.#s.set("User-Agent",sue),this.#s.has("accept")||(this.#s.set("accept","application/json"),this.#s.append("accept","application/jwk-set+json")),this.#c=t?.[Bhr],t?.[WF]!==void 0&&(this.#l=t?.[WF],Fdn(t?.[WF],this.#n)&&(this.#o=this.#l.uat,this.#a=$hr(this.#l.jwks)))}pendingFetch(){return!!this.#i}coolingDown(){return typeof this.#o=="number"?Date.now()<this.#o+this.#r:!1}fresh(){return typeof this.#o=="number"?Date.now()<this.#o+this.#n:!1}jwks(){return this.#a?.jwks()}async getKey(e,t){(!this.#a||!this.fresh())&&await this.reload();try{return await this.#a(e,t)}catch(r){if(r instanceof Xce&&this.coolingDown()===!1)return await this.reload(),this.#a(e,t);throw r}}async reload(){this.#i&&Ndn()&&(this.#i=void 0),this.#i||=Ldn(this.#e.href,this.#s,AbortSignal.timeout(this.#t),this.#c).then(e=>{this.#a=$hr(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#o=Date.now(),this.#i=void 0}).catch(e=>{throw this.#i=void 0,e}),await this.#i}}}}),sd=E({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js"(){Adn(),Rdn(),$dn(),bhr()}}),Ghr={};Z(Ghr,{Auth0Provider:()=>qhr});var qhr,Udn=E({"src/lib/auth/providers/auth0.ts"(){"use strict";cc(),Gs(),z(),Jn(),sd(),qhr=class extends _l{type="auth0";domain;clientId;audience;rolesNamespace;permissionsNamespace;jwks=null;constructor(e){if(super(e),!e.domain)throw xt.create("CONFIGURATION_ERROR","Auth0 domain is required",{details:{missingFields:["domain"]}});if(!e.clientId)throw xt.create("CONFIGURATION_ERROR","Auth0 clientId is required",{details:{missingFields:["clientId"]}});this.domain=e.domain,this.clientId=e.clientId,this.audience=e.audience,this.rolesNamespace=e.options?.rolesNamespace,this.permissionsNamespace=e.options?.permissionsNamespace}async initialize(){try{const e=new URL(`https://${this.domain}/.well-known/jwks.json`);this.jwks=o1(e),h.debug(`Auth0 provider initialized for domain: ${this.domain}`)}catch(e){throw xt.create("PROVIDER_INIT_FAILED","Failed to initialize Auth0 JWKS",{cause:e instanceof Error?e:new Error(String(e))})}}async authenticateToken(e,t){this.jwks||await this.initialize();try{if(!this.jwks)return{valid:!1,error:"Auth0 JWKS not initialized"};const{payload:r}=await cu(e,this.jwks,{issuer:`https://${this.domain}/`,audience:this.audience}),n=r;if(this.audience){const c=n.aud;if(!(Array.isArray(c)?c:[c]).includes(this.audience))return{valid:!1,error:`Token audience does not match expected audience: ${this.audience}`}}if(this.clientId){const c=n.aud,u=r.azp,d=Array.isArray(c)?c:[c];if(u){if(u!==this.clientId)return{valid:!1,error:`Token azp claim "${u}" does not match clientId "${this.clientId}"`}}else if(!d.includes(this.clientId))return{valid:!1,error:`Token audience does not include clientId "${this.clientId}"`}}const o=this.rolesNamespace??"roles",i=this.permissionsNamespace??"permissions",s=r[o]||n.roles||[],a=r[i]||n.permissions||[],l={id:n.sub,email:n.email,name:n.name,picture:n.picture,emailVerified:n.email_verified,roles:s,permissions:a,metadata:{iss:n.iss,aud:n.aud}};return{valid:!0,payload:r,user:l,expiresAt:new Date(n.exp*1e3),tokenType:"jwt"}}catch(r){const n=r instanceof Error?r.message:String(r);return h.warn("Auth0 token validation failed:",n),{valid:!1,error:n}}}async getUser(e){const t=process.env.AUTH0_MANAGEMENT_TOKEN;if(!t)return h.warn("AUTH0_MANAGEMENT_TOKEN not set, cannot fetch user profile"),null;try{const n=await Ot()(`https://${this.domain}/api/v2/users/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok){if(n.status===404)return null;throw xt.create("PROVIDER_ERROR",`Auth0 API returned ${n.status}`,{details:{statusCode:n.status}})}const o=await n.json();return{id:o.user_id,email:o.email,name:o.name,picture:o.picture,emailVerified:o.email_verified,roles:o.app_metadata?.roles||[],permissions:o.app_metadata?.permissions||[],createdAt:o.created_at?new Date(o.created_at):void 0,lastLoginAt:o.last_login?new Date(o.last_login):void 0,metadata:o.user_metadata}}catch(r){throw h.error("Failed to fetch Auth0 user:",r),r}}async getUserByEmail(e){const t=process.env.AUTH0_MANAGEMENT_TOKEN;if(!t)return h.warn("AUTH0_MANAGEMENT_TOKEN not set, cannot fetch user by email"),null;try{const n=await Ot()(`https://${this.domain}/api/v2/users-by-email?email=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok)throw xt.create("PROVIDER_ERROR",`Auth0 API returned ${n.status}`,{details:{statusCode:n.status}});const o=await n.json();if(o.length===0)return null;const i=o[0];return{id:i.user_id,email:i.email,name:i.name,picture:i.picture,emailVerified:i.email_verified,roles:i.app_metadata?.roles||[],permissions:i.app_metadata?.permissions||[],createdAt:i.created_at?new Date(i.created_at):void 0,lastLoginAt:i.last_login?new Date(i.last_login):void 0,metadata:i.user_metadata}}catch(r){throw h.error("Failed to fetch Auth0 user by email:",r),r}}async healthCheck(){try{const t=await Ot()(`https://${this.domain}/.well-known/openid-configuration`);return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0,error:t.ok?void 0:`HTTP ${t.status}`}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Vhr={};Z(Vhr,{ClerkProvider:()=>jhr});var jhr,Bdn=E({"src/lib/auth/providers/clerk.ts"(){"use strict";cc(),Gs(),z(),Jn(),sd(),jhr=class extends _l{type="clerk";secretKey;jwtKey;publishableKey;jwks=null;localKey=null;constructor(e){if(super(e),!e.secretKey)throw xt.create("CONFIGURATION_ERROR","Clerk secretKey is required",{details:{missingFields:["secretKey"]}});this.secretKey=e.secretKey,this.jwtKey=e.jwtKey,this.publishableKey=e.publishableKey}async initialize(){const e=new URL("https://api.clerk.com/v1/jwks");this.jwks=o1(e),h.debug("Clerk provider initialized")}async authenticateToken(e,t){return e.includes(".")&&e.split(".").length===3?this.validateJWT(e):this.validateSessionToken(e)}async validateJWT(e){try{let t;if(this.jwtKey)this.localKey||(this.localKey=new TextEncoder().encode(this.jwtKey)),{payload:t}=await cu(e,this.localKey);else{if(this.jwks||await this.initialize(),!this.jwks)return{valid:!1,error:"Clerk JWKS not initialized"};({payload:t}=await cu(e,this.jwks))}if(this.publishableKey&&t.azp&&t.azp!==this.publishableKey)return{valid:!1,error:`Invalid authorized party: ${t.azp}. Expected: ${this.publishableKey}`};const r={id:t.sub,email:t.email,name:t.name,picture:t.picture,emailVerified:t.email_verified,roles:t["https://clerk.dev/roles"]||[],permissions:t["https://clerk.dev/permissions"]||[],organizationId:t.org_id,metadata:{azp:t.azp,sid:t.sid}};return{valid:!0,payload:t,user:r,expiresAt:t.exp?new Date(t.exp*1e3):void 0,tokenType:"jwt"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async validateSessionToken(e){try{const r=await Ot()("https://api.clerk.com/v1/sessions/verify",{method:"POST",headers:{Authorization:`Bearer ${this.secretKey}`,"Content-Type":"application/json"},body:JSON.stringify({token:e})});if(!r.ok)return{valid:!1,error:(await r.json()).errors?.[0]?.message||"Session validation failed"};const n=await r.json(),o=n.user,i=o?.email_addresses,s={id:n.user_id,email:i?.[0]?.email_address,name:o?.first_name?`${o.first_name} ${o.last_name||""}`.trim():void 0,picture:o?.image_url,roles:o?.public_metadata?.roles||[],permissions:o?.public_metadata?.permissions||[],organizationId:n.active_organization_id};return{valid:!0,payload:n,user:s,expiresAt:n.expire_at?new Date(n.expire_at):void 0,tokenType:"session"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async getUser(e){try{const r=await Ot()(`https://api.clerk.com/v1/users/${e}`,{headers:{Authorization:`Bearer ${this.secretKey}`}});if(!r.ok){if(r.status===404)return null;throw xt.create("PROVIDER_ERROR",`Clerk API returned ${r.status}`,{details:{statusCode:r.status}})}const n=await r.json(),o=n.email_addresses;return{id:n.id,email:o?.[0]?.email_address,name:n.first_name?`${n.first_name} ${n.last_name||""}`.trim():void 0,picture:n.image_url,emailVerified:o?.[0]?.verification?.status==="verified",roles:n.public_metadata?.roles||[],permissions:n.public_metadata?.permissions||[],createdAt:n.created_at?new Date(n.created_at):void 0,lastLoginAt:n.last_sign_in_at?new Date(n.last_sign_in_at):void 0,metadata:n.private_metadata}}catch(t){if(h.error("Failed to fetch Clerk user:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async getUserByEmail(e){try{const r=await Ot()(`https://api.clerk.com/v1/users?email_address=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${this.secretKey}`}});if(!r.ok)throw xt.create("PROVIDER_ERROR",`Clerk API returned ${r.status}`,{details:{statusCode:r.status}});const n=await r.json();if(n.length===0)return null;const o=n[0],i=o.email_addresses;return{id:o.id,email:i?.[0]?.email_address,name:o.first_name?`${o.first_name} ${o.last_name||""}`.trim():void 0,picture:o.image_url,emailVerified:i?.[0]?.verification?.status==="verified",roles:o.public_metadata?.roles||[],permissions:o.public_metadata?.permissions||[],createdAt:o.created_at?new Date(o.created_at):void 0,lastLoginAt:o.last_sign_in_at?new Date(o.last_sign_in_at):void 0,metadata:o.private_metadata}}catch(t){if(h.error("Failed to fetch Clerk user by email:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async healthCheck(){try{const t=await Ot()("https://api.clerk.com/v1/organizations?limit=1",{headers:{Authorization:`Bearer ${this.secretKey}`}});return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Hhr={};Z(Hhr,{FirebaseAuthProvider:()=>Whr});var Whr,zdn=E({"src/lib/auth/providers/firebase.ts"(){"use strict";cc(),Gs(),z(),Jn(),sd(),Whr=class extends _l{type="firebase";projectId;apiKey;serviceAccount;jwks=null;constructor(e){if(super(e),!e.projectId)throw xt.create("CONFIGURATION_ERROR","Firebase projectId is required",{details:{missingFields:["projectId"]}});this.projectId=e.projectId,this.apiKey=e.apiKey,this.serviceAccount=e.serviceAccount}async initialize(){const e=new URL("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com");this.jwks=o1(e),h.debug(`Firebase provider initialized for project: ${this.projectId}`)}async authenticateToken(e,t){this.jwks||await this.initialize();try{const r=this.jwks;if(!r)throw xt.create("PROVIDER_INIT_FAILED","Firebase JWKS was not initialized",{details:{provider:"firebase"}});const{payload:n}=await cu(e,r,{issuer:`https://securetoken.google.com/${this.projectId}`,audience:this.projectId}),o=this.payloadToUser(n);return{valid:!0,payload:n,user:o,expiresAt:n.exp?new Date(n.exp*1e3):void 0,tokenType:"jwt"}}catch(r){return this.apiKey?this.validateViaApi(e):{valid:!1,error:r instanceof Error?r.message:String(r)}}}async validateViaApi(e){try{const r=await Ot()(`https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=${this.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({idToken:e}),signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:(await r.json()).error?.message||`Firebase API returned ${r.status}`};const o=(await r.json()).users||[];if(o.length===0)return{valid:!1,error:"User not found"};const i=o[0],s=this.firebaseUserToAuthUser(i);return{valid:!0,payload:i,user:s,tokenType:"jwt"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}payloadToUser(e){const t=e;return{id:e.sub,email:e.email,name:e.name,picture:e.picture,emailVerified:e.email_verified,roles:t.roles||[],permissions:t.permissions||[],metadata:{firebase:{sign_in_provider:e.firebase?.sign_in_provider||"unknown",identities:e.firebase?.identities}}}}firebaseUserToAuthUser(e){let t={};if(e.customAttributes)try{t=JSON.parse(e.customAttributes)}catch{h.warn("Failed to parse Firebase customAttributes, treating as empty")}return{id:e.localId,email:e.email,name:e.displayName,picture:e.photoUrl,emailVerified:e.emailVerified,roles:t.roles||[],permissions:t.permissions||[],createdAt:e.createdAt?new Date(parseInt(e.createdAt)):void 0,lastLoginAt:e.lastLoginAt?new Date(parseInt(e.lastLoginAt)):void 0,metadata:{providerUserInfo:e.providerUserInfo}}}async getUser(e){return this.apiKey?(h.warn("Direct user lookup by ID requires Firebase Admin SDK which is not supported in browser/edge environments"),null):(h.warn("Firebase API key required for user lookup"),null)}async healthCheck(){try{const t=await Ot()("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",{signal:AbortSignal.timeout(5e3)});return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Khr={};Z(Khr,{SupabaseAuthProvider:()=>Jhr});var Jhr,Gdn=E({"src/lib/auth/providers/supabase.ts"(){"use strict";cc(),Gs(),z(),Jn(),sd(),Jhr=class extends _l{type="supabase";supabaseUrl;anonKey;serviceRoleKey;jwtSecret;constructor(e){if(super(e),!e.url)throw xt.create("CONFIGURATION_ERROR","Supabase URL is required",{details:{missingFields:["url"]}});if(!e.anonKey)throw xt.create("CONFIGURATION_ERROR","Supabase anon key is required",{details:{missingFields:["anonKey"]}});this.supabaseUrl=e.url.replace(/\/$/,""),this.anonKey=e.anonKey,this.serviceRoleKey=e.serviceRoleKey,this.jwtSecret=e.jwtSecret}async authenticateToken(e,t){try{if(this.jwtSecret){const s=new TextEncoder().encode(this.jwtSecret),{payload:a}=await cu(e,s);if(!a.sub)return{valid:!1,error:"Token missing sub claim: cannot authenticate without a user identity"};const l=a.role;if(l&&l!=="authenticated")return{valid:!1,error:`Invalid token role: ${l}. Only "authenticated" role is accepted`};const c=this.payloadToUser(a);return{valid:!0,payload:a,user:c,expiresAt:a.exp?new Date(a.exp*1e3):void 0,tokenType:"jwt"}}const n=await Ot()(`${this.supabaseUrl}/auth/v1/user`,{headers:{Authorization:`Bearer ${e}`,apikey:this.anonKey}});if(!n.ok)return{valid:!1,error:`Token validation failed: HTTP ${n.status}`};const o=await n.json(),i=this.supabaseUserToAuthUser(o);return{valid:!0,payload:o,user:i,tokenType:"jwt"}}catch(r){return{valid:!1,error:r instanceof Error?r.message:String(r)}}}payloadToUser(e){const t=e.app_metadata,r=e.user_metadata,n=e.role;return{id:e.sub,email:e.email,name:r?.full_name||r?.name,picture:r?.avatar_url,emailVerified:e.email_confirmed||!1,roles:n?[n]:t?.roles||[],permissions:t?.permissions||[],metadata:r}}supabaseUserToAuthUser(e){const t=e.app_metadata,r=e.user_metadata;return{id:e.id,email:e.email,name:r?.full_name||r?.name,picture:r?.avatar_url,emailVerified:!!e.email_confirmed_at,roles:t?.roles||[],permissions:t?.permissions||[],createdAt:e.created_at?new Date(e.created_at):void 0,lastLoginAt:e.last_sign_in_at?new Date(e.last_sign_in_at):void 0,metadata:r}}async getUser(e){if(!this.serviceRoleKey)return h.warn("Service role key required for user lookup"),null;try{const r=await Ot()(`${this.supabaseUrl}/auth/v1/admin/users/${e}`,{headers:{Authorization:`Bearer ${this.serviceRoleKey}`,apikey:this.anonKey}});if(!r.ok){if(r.status===404)return null;throw xt.create("PROVIDER_ERROR",`Supabase API returned ${r.status}`,{details:{statusCode:r.status}})}const n=await r.json();return this.supabaseUserToAuthUser(n)}catch(t){if(h.error("Failed to fetch Supabase user:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async getUserByEmail(e){if(!this.serviceRoleKey)return h.warn("Service role key required for user lookup by email"),null;try{const r=await Ot()(`${this.supabaseUrl}/auth/v1/admin/users?email=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${this.serviceRoleKey}`,apikey:this.anonKey}});if(!r.ok)throw xt.create("PROVIDER_ERROR",`Supabase API returned ${r.status}`,{details:{statusCode:r.status}});const o=(await r.json()).users||[];return o.length===0?null:this.supabaseUserToAuthUser(o[0])}catch(t){if(h.error("Failed to fetch Supabase user by email:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async healthCheck(){try{const t=await Ot()(`${this.supabaseUrl}/auth/v1/health`,{headers:{apikey:this.anonKey}});return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Xhr={};Z(Xhr,{CognitoProvider:()=>Yhr});var aue,Yhr,qdn=E({"src/lib/auth/providers/CognitoProvider.ts"(){"use strict";sd(),z(),Gs(),cc(),aue=new Map,Yhr=class extends _l{type="cognito";cognitoConfig;jwksUri;jwksCacheDuration;expectedIssuer;constructor(e){if(super(e),e.type!=="cognito")throw xt.create("CONFIGURATION_ERROR",`Invalid provider type: ${e.type}. Expected: cognito`);if(this.cognitoConfig=e,!this.cognitoConfig.userPoolId)throw xt.create("CONFIGURATION_ERROR","Cognito userPoolId is required");if(!this.cognitoConfig.clientId)throw xt.create("CONFIGURATION_ERROR","Cognito clientId is required");if(!this.cognitoConfig.region)throw xt.create("CONFIGURATION_ERROR","Cognito region is required");this.expectedIssuer=`https://cognito-idp.${this.cognitoConfig.region}.amazonaws.com/${this.cognitoConfig.userPoolId}`,this.jwksUri=`${this.expectedIssuer}/.well-known/jwks.json`,this.jwksCacheDuration=e.tokenValidation?.jwksCacheDuration??6e5,h.debug(`[CognitoProvider] Initialized for user pool: ${this.cognitoConfig.userPoolId}`)}async authenticateToken(e){try{const t=this.parseJWT(e);if(!t)return{valid:!1,error:"Failed to decode token",errorCode:"AUTH-006"};if(t.iss!==this.expectedIssuer)return{valid:!1,error:`Invalid issuer: ${t.iss}. Expected: ${this.expectedIssuer}`,errorCode:"AUTH-001"};const r=t.token_use;if(r!=="id"&&r!=="access")return{valid:!1,error:`Invalid token_use: ${r}. Expected: id or access`,errorCode:"AUTH-001"};if(r==="id"){if(t.aud!==this.cognitoConfig.clientId)return{valid:!1,error:`Invalid audience: ${t.aud}. Expected: ${this.cognitoConfig.clientId}`,errorCode:"AUTH-001"}}else if(t.client_id!==this.cognitoConfig.clientId)return{valid:!1,error:`Invalid client_id: ${t.client_id}. Expected: ${this.cognitoConfig.clientId}`,errorCode:"AUTH-001"};const n=this.config.tokenValidation?.clockTolerance??30;if(this.isTokenExpired(t,n))return{valid:!1,error:"Token has expired",errorCode:"AUTH-002",expiresAt:t.exp?new Date(t.exp*1e3):void 0};if(this.config.tokenValidation?.validateSignature!==!1&&!await this.verifySignature(e))return{valid:!1,error:"Invalid token signature",errorCode:"AUTH-004"};const o=this.extractCognitoUser(t,r),i={};for(const[s,a]of Object.entries(t))a!==void 0&&(i[s]=a);return{valid:!0,user:o,claims:i,expiresAt:t.exp?new Date(t.exp*1e3):void 0,issuer:t.iss,audience:t.aud}}catch(t){return h.error("[CognitoProvider] Token validation error:",t),{valid:!1,error:t instanceof Error?t.message:"Token validation failed",errorCode:"AUTH-014"}}}async verifySignature(e){try{const t=e.split(".");if(t.length!==3)return!1;const r=JSON.parse(Buffer.from(t[0],"base64url").toString("utf-8")),n=r.kid;if(!n)return h.warn("[CognitoProvider] Token missing kid in header"),!1;const i=(await this.getJWKS()).keys.find(l=>l.kid===n);if(!i)return h.warn(`[CognitoProvider] Key not found for kid: ${n}`),!1;const s=await rue(i,r.alg),a=this.config.tokenValidation?.clockTolerance??30;return await cu(e,s,{clockTolerance:a}),!0}catch(t){return h.error("[CognitoProvider] Signature verification error:",t),!1}}async getJWKS(){const e=aue.get(this.jwksUri);if(e&&e.expiresAt>Date.now())return e.jwks;try{const t=await fetch(this.jwksUri,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`JWKS fetch failed: ${t.status}`);const r=await t.json();return aue.set(this.jwksUri,{jwks:r,expiresAt:Date.now()+this.jwksCacheDuration}),r}catch(t){throw xt.create("JWKS_FETCH_FAILED",`Failed to fetch JWKS from ${this.jwksUri}: ${t instanceof Error?t.message:String(t)}`,{cause:t instanceof Error?t:void 0})}}extractCognitoUser(e,t){const r=e.sub??"",n=e.email??e["custom:email"],o=e.name??e["cognito:username"]??e.preferred_username,i=e.picture??e["custom:picture"];let s=[];const a=e["cognito:groups"];a&&Array.isArray(a)&&(s=a),s.length===0&&this.rbacConfig.defaultRoles&&(s=this.rbacConfig.defaultRoles);const l=[];if(this.cognitoConfig.customAttributes)for(const d of this.cognitoConfig.customAttributes){const p=e[`custom:${d}`];p&&(p.includes(",")?l.push(...p.split(",").map(m=>m.trim())):l.push(p))}const c={provider:"cognito"};e["cognito:username"]!==void 0&&(c.username=e["cognito:username"]),c.token_use=t,e.auth_time!==void 0&&(c.auth_time=e.auth_time);const u=e.client_id??e.aud;return u!==void 0&&(c.client_id=u),a!==void 0&&(c.cognito_groups=a),{id:r,email:n,name:o,picture:i,roles:s,permissions:l,emailVerified:e.email_verified,providerData:c}}async getUser(e){return h.debug("[CognitoProvider] getUser() is not implemented. Requires AWS SDK (@aws-sdk/client-cognito-identity-provider)."),null}}}}),Zhr={};Z(Zhr,{KeycloakProvider:()=>Qhr});var lue,Qhr,Vdn=E({"src/lib/auth/providers/KeycloakProvider.ts"(){"use strict";sd(),z(),Gs(),cc(),lue=new Map,Qhr=class extends _l{type="keycloak";keycloakConfig;jwksUri;jwksCacheDuration;expectedIssuer;constructor(e){if(super(e),e.type!=="keycloak")throw xt.create("CONFIGURATION_ERROR",`Invalid provider type: ${e.type}. Expected: keycloak`);if(this.keycloakConfig=e,!this.keycloakConfig.serverUrl)throw xt.create("CONFIGURATION_ERROR","Keycloak serverUrl is required");if(!this.keycloakConfig.realm)throw xt.create("CONFIGURATION_ERROR","Keycloak realm is required");if(!this.keycloakConfig.clientId)throw xt.create("CONFIGURATION_ERROR","Keycloak clientId is required");const t=this.keycloakConfig.serverUrl.replace(/\/$/,"");this.expectedIssuer=`${t}/realms/${this.keycloakConfig.realm}`,this.jwksUri=`${this.expectedIssuer}/protocol/openid-connect/certs`,this.jwksCacheDuration=e.tokenValidation?.jwksCacheDuration??6e5,h.debug(`[KeycloakProvider] Initialized for realm: ${this.keycloakConfig.realm}`)}async authenticateToken(e){try{const t=this.parseJWT(e);if(!t)return{valid:!1,error:"Failed to decode token",errorCode:"AUTH-006"};if(t.iss!==this.expectedIssuer)return{valid:!1,error:`Invalid issuer: ${t.iss}. Expected: ${this.expectedIssuer}`,errorCode:"AUTH-001"};if(!(Array.isArray(t.aud)?t.aud:[t.aud]).includes(this.keycloakConfig.clientId))return{valid:!1,error:`Invalid audience: token aud does not contain clientId "${this.keycloakConfig.clientId}"`,errorCode:"AUTH-001"};const n=t.azp;if(n&&n!==this.keycloakConfig.clientId)return{valid:!1,error:`Invalid authorized party: ${n}. Expected: ${this.keycloakConfig.clientId}`,errorCode:"AUTH-001"};const o=this.config.tokenValidation?.clockTolerance??0;if(this.isTokenExpired(t,o))return{valid:!1,error:"Token has expired",errorCode:"AUTH-002",expiresAt:t.exp?new Date(t.exp*1e3):void 0};if(this.isTokenNotYetValid(t,o))return{valid:!1,error:"Token is not yet valid",errorCode:"AUTH-001"};if(this.keycloakConfig.verifyToken!==!1&&this.config.tokenValidation?.validateSignature!==!1&&!await this.verifySignature(e))return{valid:!1,error:"Invalid token signature",errorCode:"AUTH-004"};const i=this.extractKeycloakUser(t),s={};for(const[a,l]of Object.entries(t))l!==void 0&&(s[a]=l);return{valid:!0,user:i,claims:s,expiresAt:t.exp?new Date(t.exp*1e3):void 0,issuer:t.iss,audience:t.aud}}catch(t){return h.error("[KeycloakProvider] Token validation error:",t),{valid:!1,error:t instanceof Error?t.message:"Token validation failed",errorCode:"AUTH-014"}}}async verifySignature(e){try{const t=e.split(".");if(t.length!==3)return!1;const r=JSON.parse(Buffer.from(t[0],"base64url").toString("utf-8")),n=r.kid;if(!n)return h.warn("[KeycloakProvider] Token missing kid in header"),!1;const i=(await this.getJWKS()).keys.find(l=>l.kid===n);if(!i)return h.warn(`[KeycloakProvider] Key not found for kid: ${n}`),!1;const s=await rue(i,r.alg),a=this.config.tokenValidation?.clockTolerance??30;return await cu(e,s,{clockTolerance:a}),!0}catch(t){return h.error("[KeycloakProvider] Signature verification error:",t),!1}}async getJWKS(){const e=lue.get(this.jwksUri);if(e&&e.expiresAt>Date.now())return e.jwks;try{const t=await fetch(this.jwksUri,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`JWKS fetch failed: ${t.status}`);const r=await t.json();return lue.set(this.jwksUri,{jwks:r,expiresAt:Date.now()+this.jwksCacheDuration}),r}catch(t){throw xt.create("JWKS_FETCH_FAILED",`Failed to fetch JWKS from ${this.jwksUri}: ${t instanceof Error?t.message:String(t)}`,{cause:t instanceof Error?t:void 0})}}extractKeycloakUser(e){const t=e.sub??"",r=e.email,n=e.name??e.preferred_username,o=e.picture;let i=[];const s=e.realm_access;s?.roles&&(i=[...s.roles]);const a=e.resource_access;if(a){const d=a[this.keycloakConfig.clientId]?.roles;d&&(i=[...i,...d.map(p=>`${this.keycloakConfig.clientId}:${p}`)]);for(const[p,m]of Object.entries(a))p!==this.keycloakConfig.clientId&&m.roles&&(i=[...i,...m.roles.map(f=>`${p}:${f}`)])}i.length===0&&this.rbacConfig.defaultRoles&&(i=this.rbacConfig.defaultRoles);let l=[];const c=e.scope;c&&(l=c.split(" ").filter(d=>d.length>0));const u={provider:"keycloak"};return e.preferred_username!==void 0&&(u.preferred_username=e.preferred_username),e.given_name!==void 0&&(u.given_name=e.given_name),e.family_name!==void 0&&(u.family_name=e.family_name),s!==void 0&&(u.realm_access=s),a!==void 0&&(u.resource_access=a),e.azp!==void 0&&(u.azp=e.azp),e.session_state!==void 0&&(u.session_state=e.session_state),e.acr!==void 0&&(u.acr=e.acr),e.typ!==void 0&&(u.typ=e.typ),{id:t,email:r,name:n,picture:o,roles:i,permissions:l,emailVerified:e.email_verified,providerData:u}}async getUser(e){if(!this.keycloakConfig.clientSecret)return h.debug("[KeycloakProvider] clientSecret required for admin API"),null;try{const t=await fetch(`${this.expectedIssuer}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:this.keycloakConfig.clientId,client_secret:this.keycloakConfig.clientSecret}),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Failed to get admin token: ${t.status}`);const r=await t.json(),n=this.keycloakConfig.serverUrl.replace(/\/$/,""),o=await fetch(`${n}/admin/realms/${this.keycloakConfig.realm}/users/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${r.access_token}`},signal:AbortSignal.timeout(5e3)});if(!o.ok){if(o.status===404)return null;throw new Error(`Failed to get user: ${o.status}`)}const i=await o.json(),s=await fetch(`${n}/admin/realms/${this.keycloakConfig.realm}/users/${encodeURIComponent(e)}/role-mappings/realm`,{headers:{Authorization:`Bearer ${r.access_token}`},signal:AbortSignal.timeout(5e3)});let a=this.rbacConfig.defaultRoles??[];s.ok&&(a=(await s.json()).map(u=>u.name));const l={};for(const[c,u]of Object.entries(i))u!==void 0&&(l[c]=u);return{id:i.id,email:i.email,name:`${i.firstName??""} ${i.lastName??""}`.trim()||i.username,picture:void 0,roles:a,permissions:[],emailVerified:i.emailVerified,providerData:l,createdAt:i.createdTimestamp?new Date(i.createdTimestamp):void 0}}catch(t){return h.error(`[KeycloakProvider] Failed to get user ${e}:`,t),null}}}}}),efr={};Z(efr,{BetterAuthProvider:()=>tfr});var tfr,jdn=E({"src/lib/auth/providers/betterAuth.ts"(){"use strict";Jn(),Gs(),sd(),cc(),tfr=class extends _l{type="better-auth";secret;baseUrl;secretKey;constructor(e){if(super(e),!e.secret)throw xt.create("CONFIGURATION_ERROR","Better Auth secret is required",{details:{provider:"better-auth",missingFields:["secret"]}});if(!e.baseUrl)throw xt.create("CONFIGURATION_ERROR","Better Auth baseUrl is required",{details:{provider:"better-auth",missingFields:["baseUrl"]}});this.secret=e.secret,this.baseUrl=e.baseUrl.replace(/\/$/,""),this.secretKey=new TextEncoder().encode(this.secret)}async authenticateToken(e,t){if(e.includes(".")&&e.split(".").length===3){const r=await this.validateJWT(e);if(r.valid)return r}return this.validateSessionViaAPI(e)}async validateJWT(e){try{const{payload:t}=await cu(e,this.secretKey);if(!t.sub)return{valid:!1,error:"Token missing required 'sub' claim"};const r={id:t.sub,email:t.email,name:t.name,picture:t.picture,emailVerified:t.email_verified,roles:t.roles||[],permissions:t.permissions||[],metadata:t.metadata};return{valid:!0,payload:t,user:r,expiresAt:t.exp?new Date(t.exp*1e3):void 0,tokenType:"jwt"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async validateSessionViaAPI(e){try{const r=await Ot()(`${this.baseUrl}/api/auth/session`,{headers:{Cookie:`better-auth.session_token=${e}`},signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:`Session validation failed: HTTP ${r.status}`};const n=await r.json();if(!n.user)return{valid:!1,error:"Invalid session"};const o={id:n.user.id,email:n.user.email,name:n.user.name,picture:n.user.image,emailVerified:n.user.emailVerified,roles:n.user.roles||[],permissions:n.user.permissions||[],createdAt:n.user.createdAt?new Date(n.user.createdAt):void 0,metadata:n.user};return{valid:!0,payload:n,user:o,expiresAt:n.session?.expiresAt?new Date(n.session.expiresAt):void 0,tokenType:"session"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async healthCheck(){try{const r=(await Ot()(`${this.baseUrl}/api/auth/session`,{signal:AbortSignal.timeout(5e3)})).status<500;return{healthy:r,providerConnected:r,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),rfr={};Z(rfr,{WorkOSProvider:()=>nfr});var nfr,Hdn=E({"src/lib/auth/providers/workos.ts"(){"use strict";z(),Jn(),Gs(),sd(),cc(),nfr=class extends _l{type="workos";apiKey;clientId;organizationId;jwks=null;constructor(e){if(super(e),!e.apiKey)throw xt.create("CONFIGURATION_ERROR","WorkOS API key is required",{details:{provider:"workos",missingFields:["apiKey"]}});if(!e.clientId)throw xt.create("CONFIGURATION_ERROR","WorkOS client ID is required",{details:{provider:"workos",missingFields:["clientId"]}});this.apiKey=e.apiKey,this.clientId=e.clientId,this.organizationId=e.organizationId}async initialize(){const e=new URL("https://api.workos.com/sso/jwks");this.jwks=o1(e),h.debug("WorkOS provider initialized")}async authenticateToken(e,t){this.jwks||await this.initialize();try{const r=this.jwks;if(!r)throw xt.create("PROVIDER_INIT_FAILED","WorkOS JWKS was not initialized",{details:{provider:"workos"}});const{payload:n}=await cu(e,r,{audience:this.clientId});if(this.organizationId&&n.org_id!==this.organizationId)return{valid:!1,error:`Organization mismatch: expected ${this.organizationId}, got ${n.org_id}`};const o={id:n.sub,email:n.email,name:n.first_name&&n.last_name?`${n.first_name} ${n.last_name}`.trim():void 0,emailVerified:!0,roles:n.roles||[],permissions:n.permissions||[],organizationId:n.org_id,metadata:{connection_id:n.connection_id,connection_type:n.connection_type,idp_id:n.idp_id}};return{valid:!0,payload:n,user:o,expiresAt:n.exp?new Date(n.exp*1e3):void 0,tokenType:"jwt"}}catch{return this.validateSessionViaAPI(e)}}async validateSessionViaAPI(e){try{const r=await Ot()("https://api.workos.com/user_management/authenticate",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({session_token:e,client_id:this.clientId}),signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:`Session validation failed: HTTP ${r.status}`};const n=await r.json();if(!n.user)return{valid:!1,error:"User not found in session"};if(this.organizationId&&n.organization_id!==this.organizationId)return{valid:!1,error:`Organization mismatch: expected ${this.organizationId}, got ${n.organization_id}`};const o={id:n.user.id,email:n.user.email,name:n.user.first_name&&n.user.last_name?`${n.user.first_name} ${n.user.last_name}`.trim():void 0,picture:n.user.profile_picture_url,emailVerified:n.user.email_verified,roles:[],permissions:[],organizationId:n.organization_id,createdAt:n.user.created_at?new Date(n.user.created_at):void 0,metadata:n.user};return{valid:!0,payload:n,user:o,tokenType:"session"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async getUser(e){try{const r=await Ot()(`https://api.workos.com/user_management/users/${e}`,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!r.ok){if(r.status===404)return null;throw xt.create("PROVIDER_ERROR",`WorkOS API returned ${r.status}`,{details:{provider:"workos",statusCode:r.status}})}const n=await r.json();return{id:n.id,email:n.email,name:n.first_name&&n.last_name?`${n.first_name} ${n.last_name}`.trim():void 0,picture:n.profile_picture_url,emailVerified:n.email_verified,roles:[],permissions:[],createdAt:n.created_at?new Date(n.created_at):void 0,metadata:n}}catch(t){throw h.error("Failed to fetch WorkOS user:",t instanceof Error?t.message:String(t)),t}}async getUserByEmail(e){try{const r=await Ot()(`https://api.workos.com/user_management/users?email=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!r.ok)throw xt.create("PROVIDER_ERROR",`WorkOS API returned ${r.status}`,{details:{provider:"workos",statusCode:r.status}});const o=(await r.json()).data||[];if(o.length===0)return null;const i=o[0];return{id:i.id,email:i.email,name:i.first_name&&i.last_name?`${i.first_name} ${i.last_name}`.trim():void 0,picture:i.profile_picture_url,emailVerified:i.email_verified,roles:[],permissions:[],createdAt:i.created_at?new Date(i.created_at):void 0,metadata:i}}catch(t){if(h.error("Failed to fetch WorkOS user by email:",t instanceof Error?t.message:String(t)),t instanceof Error&&t.name==="AuthError")throw t;return null}}async healthCheck(){try{const t=await Ot()("https://api.workos.com/sso/jwks");return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),ofr={};Z(ofr,{OAuth2Provider:()=>ifr});var ifr,Wdn=E({"src/lib/auth/providers/oauth2.ts"(){"use strict";sd(),Jn(),z(),Gs(),cc(),ifr=class extends _l{type="oauth2";authorizationUrl;tokenUrl;userInfoUrl;jwksUrl;clientId;clientSecret;scopes;redirectUrl;usePKCE;jwks=null;constructor(e){if(super(e),!e.authorizationUrl)throw xt.create("CONFIGURATION_ERROR","OAuth2 authorizationUrl is required");if(!e.tokenUrl)throw xt.create("CONFIGURATION_ERROR","OAuth2 tokenUrl is required");if(!e.clientId)throw xt.create("CONFIGURATION_ERROR","OAuth2 clientId is required");this.authorizationUrl=e.authorizationUrl,this.tokenUrl=e.tokenUrl,this.userInfoUrl=e.userInfoUrl,this.jwksUrl=e.jwksUrl,this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.scopes=e.scopes??["openid","profile","email"],this.redirectUrl=e.redirectUrl,this.usePKCE=e.usePKCE??!1}async initialize(){if(this.jwksUrl)try{const e=new URL(this.jwksUrl);this.jwks=o1(e),h.debug(`OAuth2 provider initialized with JWKS: ${this.jwksUrl}`)}catch(e){throw xt.create("PROVIDER_INIT_FAILED","Failed to initialize OAuth2 JWKS",{cause:e instanceof Error?e:new Error(String(e))})}}async authenticateToken(e,t){if(this.jwksUrl){if(this.jwks||await this.initialize(),!this.jwks)return{valid:!1,error:"JWKS not available after initialization"};try{const{payload:r}=await cu(e,this.jwks);if(r.iss){const o=new URL(this.authorizationUrl).origin;if(!r.iss.startsWith(o))return{valid:!1,error:`Invalid issuer: ${r.iss}. Expected origin: ${o}`}}if(r.aud){const o=Array.isArray(r.aud)?r.aud:[r.aud];if(!o.includes(this.clientId))return{valid:!1,error:`Invalid audience: ${o.join(", ")}. Expected: ${this.clientId}`}}if(!r.sub)return{valid:!1,error:"JWT is missing required 'sub' claim: cannot identify user"};const n={id:r.sub,email:r.email,name:r.name,picture:r.picture,roles:r.roles??[],permissions:r.permissions??[],metadata:r};return{valid:!0,payload:r,user:n,expiresAt:r.exp?new Date(r.exp*1e3):void 0,tokenType:"jwt"}}catch{h.debug("JWKS validation failed, trying userinfo endpoint")}}return this.userInfoUrl?this.validateViaUserInfo(e):{valid:!1,error:"No validation method available (provide jwksUrl or userInfoUrl)"}}async validateViaUserInfo(e){try{const t=Ot();if(!this.userInfoUrl)return{valid:!1,error:"UserInfo URL not configured"};const r=await t(this.userInfoUrl,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:`UserInfo endpoint returned ${r.status}`};const n=await r.json(),o=n.sub??n.id;if(!o)return{valid:!1,error:"UserInfo response is missing 'sub' and 'id': cannot identify user"};const i={id:o,email:n.email,name:n.name,picture:n.picture,emailVerified:n.email_verified,roles:n.roles??[],permissions:n.permissions??[],metadata:n};return{valid:!0,payload:n,user:i,tokenType:"oauth"}}catch(t){const r=t instanceof Error?t.message:String(t);return h.warn("OAuth2 userinfo validation failed:",r),{valid:!1,error:r}}}getAuthorizationUrl(e,t){const r=new URLSearchParams({response_type:"code",client_id:this.clientId,scope:this.scopes.join(" "),state:e});return this.redirectUrl&&r.set("redirect_uri",this.redirectUrl),this.usePKCE&&t&&(r.set("code_challenge",t),r.set("code_challenge_method","S256")),`${this.authorizationUrl}?${r.toString()}`}async exchangeCode(e,t){const r=Ot(),n=new URLSearchParams({grant_type:"authorization_code",client_id:this.clientId,code:e});this.clientSecret&&n.set("client_secret",this.clientSecret),this.redirectUrl&&n.set("redirect_uri",this.redirectUrl),this.usePKCE&&t&&n.set("code_verifier",t);const o=await r(this.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),signal:AbortSignal.timeout(5e3)});if(!o.ok)throw xt.create("PROVIDER_ERROR",`Token exchange failed: ${o.status}`);const i=await o.json();return{accessToken:i.access_token,refreshToken:i.refresh_token,idToken:i.id_token}}async healthCheck(){try{const e=Ot(),t=this.jwksUrl??this.authorizationUrl,r=await e(t,{method:"HEAD"});return{healthy:r.ok||r.status===405,providerConnected:!0,sessionStorageHealthy:!0,error:r.ok||r.status===405?void 0:`HTTP ${r.status}`}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),sfr={};Z(sfr,{JWTProvider:()=>afr});var afr,Kdn=E({"src/lib/auth/providers/jwt.ts"(){"use strict";sd(),z(),Gs(),cc(),afr=class extends _l{type="jwt";secret;publicKey;algorithms;issuer;audience;keyObject=null;constructor(e){if(super(e),!e.secret&&!e.publicKey)throw xt.create("CONFIGURATION_ERROR","JWT requires either secret (for HMAC) or publicKey (for RSA/ECDSA)",{details:{provider:"jwt",missingFields:["secret","publicKey"]}});this.secret=e.secret,this.publicKey=e.publicKey,this.algorithms=e.algorithms??(e.secret?["HS256"]:["RS256"]),this.issuer=e.issuer,this.audience=e.audience}async initialize(){try{this.secret?(this.keyObject=new TextEncoder().encode(this.secret),h.debug("JWT provider initialized with symmetric secret")):this.publicKey&&(this.keyObject=await wdn(this.publicKey,this.algorithms[0]),h.debug("JWT provider initialized with asymmetric public key"))}catch(e){throw xt.create("PROVIDER_INIT_FAILED",`Failed to initialize JWT key: ${e instanceof Error?e.message:String(e)}`,{details:{provider:"jwt"},cause:e instanceof Error?e:void 0})}}async authenticateToken(e,t){this.keyObject||await this.initialize();try{const r=this.keyObject;if(!r)throw xt.create("PROVIDER_INIT_FAILED","JWT verification key was not initialized",{details:{provider:"jwt"}});const n={};this.algorithms.length>0&&(n.algorithms=this.algorithms),this.issuer&&(n.issuer=this.issuer),this.audience&&(n.audience=this.audience);const{payload:o}=await cu(e,r,n);if(!o.sub)return{valid:!1,error:"JWT is missing required 'sub' claim: cannot identify user"};const i={id:o.sub,email:o.email,name:o.name,picture:o.picture,emailVerified:o.email_verified,roles:o.roles??[],permissions:o.permissions??o.scope?.split(" ")??[],metadata:{iss:o.iss,aud:o.aud,jti:o.jti}};return{valid:!0,payload:o,user:i,expiresAt:o.exp?new Date(o.exp*1e3):void 0,tokenType:"jwt"}}catch(r){const n=r instanceof Error?r.message:String(r);h.warn("JWT validation failed:",n);let o=n;return n.includes("JWTExpired")?o="Token has expired":n.includes("signature")?o="Invalid token signature":n.includes("audience")?o="Invalid token audience":n.includes("issuer")&&(o="Invalid token issuer"),{valid:!1,error:o}}}async signToken(e,t){if(!this.secret)throw xt.create("CONFIGURATION_ERROR","Token signing requires a secret (symmetric key)",{details:{provider:"jwt"}});this.keyObject||await this.initialize();const r=new Lhr(e).setProtectedHeader({alg:this.algorithms[0]}).setIssuedAt();return this.issuer&&r.setIssuer(this.issuer),this.audience&&r.setAudience(this.audience),t?.expiresIn&&r.setExpirationTime(t.expiresIn),r.sign(this.keyObject)}async healthCheck(){try{return this.keyObject||await this.initialize(),{healthy:this.keyObject!==null,providerConnected:!0,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),lfr={};Z(lfr,{CustomAuthProvider:()=>cfr});var cfr,Jdn=E({"src/lib/auth/providers/custom.ts"(){"use strict";z(),Gs(),cc(),cfr=class extends _l{type="custom";validateTokenFn;getUserFn;createSessionFn;constructor(e){if(super(e),!e.validateToken)throw xt.create("CONFIGURATION_ERROR","Custom validateToken function is required",{details:{provider:"custom",missingFields:["validateToken"]}});this.validateTokenFn=e.validateToken,this.getUserFn=e.getUser,this.createSessionFn=e.createSession}async authenticateToken(e,t){try{return await this.validateTokenFn(e,t)}catch(r){return{valid:!1,error:r instanceof Error?r.message:String(r)}}}async createSession(e,t){if(this.createSessionFn){const r=await this.createSessionFn(e,t);return await this.sessionStorage.save(r),this.emit("auth:login",r.user),r}return super.createSession(e,t)}async getUser(e){if(this.getUserFn)try{return await this.getUserFn(e)}catch(t){return h.error("Custom getUser failed:",t),null}return h.warn("Custom getUser function not provided"),null}async healthCheck(){return{healthy:!0,providerConnected:!0,sessionStorageHealthy:!0}}}}}),Xdn,Ydn,Zdn,Qdn,KF,ufr,cue,epn,ib,tpn,rpn,npn,i1=E({"node-stub:readline"(){Xdn=globalThis.crypto,Ydn=globalThis.ReadableStream||class{},Zdn=globalThis.URL,Qdn=globalThis.URLSearchParams,KF=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},KF.custom=Symbol.for("nodejs.util.inspect.custom"),KF.colors={},KF.styles={},ufr=globalThis.TextDecoder,cue=globalThis.TextEncoder,epn=globalThis.performance||{now:()=>Date.now()},ib=()=>({}),tpn=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new cue().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new cue().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new ufr().decode(this)}},rpn=globalThis.clearTimeout,npn=globalThis.clearInterval}});function Pp(e,t=dfr){const r=e??t,n=Number.isNaN(r)?0:r;if(n===1/0)return;const o=Math.max(0,n)*pfr;if(Number.isFinite(o))return Date.now()-o}var dfr,pfr,Mp=E({"src/lib/localUsage/scanWindow.ts"(){"use strict";dfr=30,pfr=864e5}}),mfr={};Z(mfr,{createClaudeCodeReader:()=>spn});function hfr(){return Rt(Fs(),".claude","projects")}function opn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"modeled",unpricedRequests:0,unpricedModels:[]}}async function ffr(e,t){let r;try{r=await cl(e,{withFileTypes:!0})}catch{return}for(const n of r){const o=Rt(e,n.name);n.isDirectory()?await ffr(o,t):n.isFile()&&n.name.endsWith(".jsonl")&&t.push(o)}}function JF(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function ipn(e,t,r){const n=new Map,o=ib({input:Qh(e,{encoding:"utf8"}),crlfDelay:1/0});try{for await(const i of o){if(!i||i.charCodeAt(0)!==123)continue;let s;try{s=JSON.parse(i)}catch{continue}const a=s;if(a.type!=="assistant"||!a.message?.usage)continue;const l=a.message.usage,c=a.message.id;if(typeof c!="string"||c.length===0)continue;const u={model:a.message.model??"unknown",input:JF(l.input_tokens),output:JF(l.output_tokens),read:JF(l.cache_read_input_tokens),create:JF(l.cache_creation_input_tokens)},d=n.get(c);(!d||u.output>d.output)&&n.set(c,u)}}finally{o.close()}for(const i of n.values())t.requests+=1,t.inputTokens+=i.input,t.outputTokens+=i.output,t.cacheReadTokens+=i.read,t.cacheCreationTokens+=i.create,Ud(uue,i.model)?t.costUsd+=Ls(uue,i.model,{input:i.input,output:i.output,total:i.input+i.output,cacheReadTokens:i.read,cacheCreationTokens:i.create}):(t.unpricedRequests+=1,r.add(i.model))}async function spn(){return{descriptor:{id:XF,displayName:"Claude Code",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"modeled",requiresSqlite:!1},detect:async()=>{try{return(await vo(hfr())).isDirectory()}catch{return!1}},scan:async e=>{const t=opn(),r=[],n=new Set,o=[];await ffr(hfr(),o);const i=Pp(e?.sinceDays);let s=0;for(const a of o)try{if(i!==void 0&&(await vo(a)).mtimeMs<i)continue;await ipn(a,t,n),s+=1}catch(l){r.push({cliId:XF,filePath:a,message:l instanceof Error?l.message:String(l)})}return t.unpricedModels=[...n].sort(),t.costUsd=Math.round(t.costUsd*1e6)/1e6,{cliId:XF,totals:t,filesScanned:s,errors:r}}}}var XF,uue,apn=E({"src/lib/localUsage/claudeCodeReader.ts"(){"use strict";Tn(),i1(),ui(),$s(),kr(),sl(),Mp(),XF="claude-code",uue="anthropic"}}),gfr={};Z(gfr,{createCodexReader:()=>upn});function yfr(){return Rt(Fs(),".codex","sessions")}function lpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}async function vfr(e,t){let r;try{r=await cl(e,{withFileTypes:!0})}catch{return}for(const n of r){const o=Rt(e,n.name);n.isDirectory()?await vfr(o,t):n.isFile()&&n.name.endsWith(".jsonl")&&t.push(o)}}function YF(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function cpn(e){const t=ib({input:Qh(e,{encoding:"utf8"}),crlfDelay:1/0});let r,n=-1,o,i=-1,s=0;try{for await(const a of t){const l=a.includes('"token_count"'),c=a.includes('"turn_context"');if(!l&&!c)continue;let u;try{u=JSON.parse(a)}catch{continue}const d=u;if(d.type==="turn_context"&&d.payload?.model){r=d.payload.model;continue}if(d.payload?.type!=="token_count")continue;const p=d.payload.info?.total_token_usage;if(!p)continue;const m=YF(p.total_tokens);m>i&&(s+=1),i=m,m>n&&(n=m,o={input:YF(p.input_tokens),output:YF(p.output_tokens),cached:YF(p.cached_input_tokens)})}}finally{t.close()}return o?{model:r,billableEvents:s,...o}:null}async function upn(){return{descriptor:{id:ZF,displayName:"Codex",verified:!0,dedupStrategy:"session-dag",costConfidence:"unavailable",requiresSqlite:!1},detect:async()=>{try{return(await vo(yfr())).isDirectory()}catch{return!1}},scan:async e=>{const t=lpn(),r=[],n=new Set,o=[];await vfr(yfr(),o);const i=Pp(e?.sinceDays);let s=0;for(const a of o)try{if(i!==void 0&&(await vo(a)).mtimeMs<i)continue;const l=await cpn(a);if(s+=1,!l)continue;t.requests+=l.billableEvents,t.inputTokens+=Math.max(0,l.input-l.cached),t.cacheReadTokens+=l.cached,t.outputTokens+=l.output,l.model&&n.add(l.model)}catch(l){r.push({cliId:ZF,filePath:a,message:l instanceof Error?l.message:String(l)})}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:ZF,totals:t,filesScanned:s,errors:r}}}}var ZF,dpn=E({"src/lib/localUsage/codexReader.ts"(){"use strict";Tn(),i1(),ui(),$s(),kr(),Mp(),ZF="codex"}}),s1={};Z(s1,{Agent:()=>Cfr,AsyncLocalStorage:()=>Gfr,Buffer:()=>B0r,Channel:()=>I0r,DatabaseSync:()=>U0r,Duplex:()=>Vfr,EventEmitter:()=>zfr,Http2ServerRequest:()=>j0r,Http2ServerResponse:()=>H0r,Interface:()=>$0r,MIMEType:()=>Z0r,PassThrough:()=>jfr,PerformanceObserver:()=>x0r,Readable:()=>pue,ReadableStream:()=>Hfr,Resolver:()=>S0r,STATUS_CODES:()=>Wgr,TextDecoder:()=>fue,TextEncoder:()=>l1,Transform:()=>qfr,URL:()=>d0r,URLSearchParams:()=>p0r,Worker:()=>O0r,Writable:()=>mue,access:()=>kgr,appendFile:()=>ngr,appendFileSync:()=>kfr,arch:()=>qgr,arrayBuffer:()=>W0r,availableParallelism:()=>egr,basename:()=>Dfr,builtinModules:()=>a0r,callbackify:()=>w0r,channel:()=>C0r,chmod:()=>Qfr,chmodSync:()=>Zfr,clearInterval:()=>Y0r,clearTimeout:()=>J0r,closeSync:()=>agr,connect:()=>Kgr,constants:()=>z0r,copyFileSync:()=>igr,cpSync:()=>xfr,cpus:()=>Ugr,createConnection:()=>Jgr,createGunzip:()=>r0r,createGzip:()=>n0r,createHash:()=>due,createHmac:()=>bfr,createInterface:()=>F0r,createReadStream:()=>vgr,createRequire:()=>s0r,createServer:()=>Afr,createWriteStream:()=>ygr,debug:()=>y0r,debuglog:()=>hue,default:()=>wfr,deflateSync:()=>Ygr,deprecate:()=>v0r,deserialize:()=>M0r,dirname:()=>Ofr,exec:()=>Pgr,execFile:()=>Ogr,execFileSync:()=>Dgr,execSync:()=>Mgr,existsSync:()=>Jfr,extname:()=>Nfr,fileURLToPath:()=>m0r,finished:()=>Kfr,format:()=>u0r,freemem:()=>Bgr,fstatSync:()=>lgr,get:()=>Hgr,gunzip:()=>t0r,gunzipSync:()=>Zgr,gzip:()=>e0r,gzipSync:()=>Qgr,hasSubscribers:()=>R0r,homedir:()=>Lgr,hostname:()=>$gr,inflateSync:()=>Xgr,inherits:()=>f0r,inspect:()=>a1,isAbsolute:()=>Ffr,isBuiltin:()=>l0r,isDeepStrictEqual:()=>T0r,isIP:()=>V0r,isIPv4:()=>q0r,isIPv6:()=>G0r,isMainThread:()=>D0r,join:()=>Pfr,loadavg:()=>tgr,lookup:()=>E0r,lstatSync:()=>dgr,mkdir:()=>bgr,mkdirSync:()=>cgr,monitorEventLoopDelay:()=>A0r,normalize:()=>Bfr,ok:()=>o0r,open:()=>Cgr,openSync:()=>sgr,parentPort:()=>N0r,parse:()=>c0r,pathToFileURL:()=>h0r,performance:()=>k0r,pipeline:()=>Wfr,platform:()=>Ngr,posix:()=>Ufr,promises:()=>Tfr,promisify:()=>g0r,randomBytes:()=>_fr,randomUUID:()=>Efr,readFile:()=>wgr,readFileSync:()=>Xfr,readdir:()=>Egr,readdirSync:()=>pgr,realpath:()=>Igr,realpathSync:()=>ogr,relative:()=>Lfr,release:()=>Vgr,rename:()=>xgr,renameSync:()=>hgr,request:()=>jgr,resolve:()=>Mfr,rm:()=>Agr,rmSync:()=>ggr,rmdirSync:()=>fgr,sep:()=>$fr,serialize:()=>P0r,setImmediate:()=>rgr,setInterval:()=>X0r,setTimeout:()=>K0r,spawn:()=>Rgr,stat:()=>_gr,statSync:()=>ugr,strict:()=>i0r,tmpdir:()=>Fgr,toUSVString:()=>b0r,totalmem:()=>zgr,type:()=>Ggr,types:()=>_0r,unlink:()=>Sgr,unlinkSync:()=>mgr,validateHeaderName:()=>Ifr,validateHeaderValue:()=>Rfr,webcrypto:()=>Sfr,workerData:()=>L0r,writeFile:()=>Tgr,writeFileSync:()=>Yfr});var Oo,qn,wfr,Tfr,due,bfr,_fr,Efr,Sfr,kfr,xfr,Afr,Cfr,Ifr,Rfr,Pfr,Mfr,Ofr,Dfr,Nfr,Lfr,Ffr,$fr,Ufr,Bfr,zfr,Gfr,pue,mue,qfr,Vfr,jfr,Hfr,Wfr,Kfr,Jfr,Xfr,Yfr,Zfr,Qfr,egr,tgr,rgr,ngr,ogr,igr,sgr,agr,lgr,cgr,ugr,dgr,pgr,mgr,hgr,fgr,ggr,ygr,vgr,wgr,Tgr,bgr,_gr,Egr,Sgr,kgr,xgr,Agr,Cgr,Igr,Rgr,Pgr,Mgr,Ogr,Dgr,Ngr,Lgr,Fgr,$gr,Ugr,Bgr,zgr,Ggr,qgr,Vgr,jgr,Hgr,Wgr,Kgr,Jgr,Xgr,Ygr,Zgr,Qgr,e0r,t0r,r0r,n0r,o0r,i0r,s0r,a0r,l0r,c0r,u0r,d0r,p0r,m0r,h0r,f0r,g0r,hue,y0r,a1,v0r,w0r,T0r,b0r,_0r,fue,l1,E0r,S0r,k0r,x0r,A0r,C0r,I0r,R0r,P0r,M0r,O0r,D0r,N0r,L0r,F0r,$0r,U0r,B0r,z0r,G0r,q0r,V0r,j0r,H0r,W0r,gue,K0r,J0r,X0r,Y0r,Z0r,QF=E({"node-stub:node:sqlite"(){Oo=()=>{},qn=async()=>{},wfr={},Tfr={readFile:qn,writeFile:qn,mkdir:qn,stat:qn,readdir:qn,unlink:qn,access:qn,rm:qn,rename:qn},due=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new l1().encode(r):r),this},digest(r){let n=0;for(const i of t)for(let s=0;s<i.length;s++)n=(n<<5)-n+i[s]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},bfr=(e,t)=>due(e),_fr=e=>new Uint8Array(e||32),Efr=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),Sfr=globalThis.crypto,kfr=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},xfr=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},Afr=()=>({listen:Oo,close:Oo,on:Oo}),Cfr=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},Ifr=Oo,Rfr=Oo,Pfr=(...e)=>e.join("/"),Mfr=(...e)=>e.join("/"),Ofr=e=>e||"",Dfr=e=>e?.split?.("/")?.pop?.()||"",Nfr=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},Lfr=(e,t)=>t||"",Ffr=()=>!1,$fr="/",Ufr={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},Bfr=e=>e,zfr=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(i=>i===r||i.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},Gfr=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},pue=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},mue=class{write(){return!0}end(){}on(){return this}destroy(){}},qfr=class{push(){}on(){return this}},Vfr=class{on(){return this}},jfr=class{pipe(){return this}on(){return this}},Hfr=globalThis.ReadableStream||class{},Wfr=Oo,Kfr=Oo,Jfr=()=>!1,Xfr=()=>"",Yfr=Oo,Zfr=Oo,Qfr=qn,egr=()=>1,tgr=()=>[0,0,0],rgr=qn,ngr=qn,ogr=e=>e,igr=Oo,sgr=()=>0,agr=Oo,lgr=()=>({}),cgr=Oo,ugr=()=>({}),dgr=()=>({isSymbolicLink:()=>!1}),pgr=()=>[],mgr=Oo,hgr=Oo,fgr=Oo,ggr=Oo,ygr=()=>new mue,vgr=()=>new pue,wgr=qn,Tgr=qn,bgr=qn,_gr=qn,Egr=qn,Sgr=qn,kgr=qn,xgr=qn,Agr=qn,Cgr=async()=>({stat:qn,readFile:qn,close:qn,read:qn,write:qn}),Igr=async e=>e,Rgr=()=>({on:Oo,stdout:{on:Oo},stderr:{on:Oo},kill:Oo}),Pgr=(e,t)=>t?.(null,"",""),Mgr=()=>"",Ogr=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},Dgr=()=>"",Ngr="browser",Lgr=()=>"/",Fgr=()=>"/tmp",$gr=()=>"browser",Ugr=()=>[{}],Bgr=()=>0,zgr=()=>0,Ggr=()=>"Browser",qgr=()=>"wasm",Vgr=()=>"0",jgr=()=>({}),Hgr=()=>({}),Wgr={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},Kgr=()=>({}),Jgr=()=>({}),Xgr=()=>new Uint8Array,Ygr=()=>new Uint8Array,Zgr=()=>new Uint8Array,Qgr=()=>new Uint8Array,e0r=(e,t)=>t?.(null,e),t0r=(e,t)=>t?.(null,e),r0r=()=>({}),n0r=()=>({}),o0r=Oo,i0r={},s0r=()=>()=>({}),a0r=[],l0r=()=>!1,c0r=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),u0r=()=>"",d0r=globalThis.URL,p0r=globalThis.URLSearchParams,m0r=e=>typeof e=="string"?e.replace("file://",""):e,h0r=e=>new globalThis.URL("file://"+e),f0r=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},g0r=e=>(...t)=>new Promise((r,n)=>e(...t,(o,i)=>o?n(o):r(i))),hue=e=>{const t=(...r)=>{};return t.enabled=!1,t},y0r=hue,a1=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},a1.custom=Symbol.for("nodejs.util.inspect.custom"),a1.colors={},a1.styles={},v0r=e=>e,w0r=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},T0r=(e,t)=>JSON.stringify(e)===JSON.stringify(t),b0r=e=>String(e),_0r={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},fue=globalThis.TextDecoder,l1=globalThis.TextEncoder,E0r=(e,t)=>t?.(null,"127.0.0.1",4),S0r=class{},k0r=globalThis.performance||{now:()=>Date.now()},x0r=class{observe(){}disconnect(){}},A0r=()=>({enable:Oo,disable:Oo,percentile:()=>0}),C0r=()=>({}),I0r=class{},R0r=()=>!1,P0r=()=>new Uint8Array,M0r=Oo,O0r=class{},D0r=!0,N0r=null,L0r=null,F0r=()=>({}),$0r=class{},U0r=class{},B0r=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new l1().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new l1().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new fue().decode(this)}},z0r={F_OK:0,R_OK:4,W_OK:2,X_OK:1},G0r=()=>!1,q0r=()=>!1,V0r=()=>0,j0r=class{},H0r=class{},W0r=async()=>new ArrayBuffer(0),gue=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),K0r=(...e)=>gue(globalThis.setTimeout(...e)),J0r=globalThis.clearTimeout,X0r=(...e)=>gue(globalThis.setInterval(...e)),Y0r=globalThis.clearInterval,Z0r=class{constructor(e){this.type=e}toString(){return this.type}}}}),Q0r={};Z(Q0r,{createOpenCodeReader:()=>mpn});function eyr(){return Rt(Fs(),".local","share","opencode","opencode.db")}function ppn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function e$(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function mpn(){return{descriptor:{id:mh,displayName:"OpenCode",verified:!0,dedupStrategy:"rowid-high-water-mark",costConfidence:"unavailable",requiresSqlite:!0},detect:async()=>{try{return(await vo(eyr())).isFile()}catch{return!1}},scan:async e=>{const t=ppn(),r=[],n=new Set,o=eyr();let i;try{const l=await Promise.resolve().then(()=>(QF(),s1));typeof l=="object"&&l!==null&&"DatabaseSync"in l&&typeof l.DatabaseSync=="function"&&(i=l.DatabaseSync)}catch(l){return r.push({cliId:mh,filePath:o,message:`node:sqlite unavailable on this runtime: ${l instanceof Error?l.message:String(l)} (unflagged since Node 22.13.0 and 23.4.0; on 22.5.0 to 22.12.x and 23.0 to 23.3 pass --experimental-sqlite)`}),{cliId:mh,totals:t,filesScanned:0,errors:r}}if(!i)return r.push({cliId:mh,filePath:o,message:"node:sqlite did not expose a callable DatabaseSync \u2014 the experimental API has likely changed shape"}),{cliId:mh,totals:t,filesScanned:0,errors:r};const s=Pp(e?.sinceDays)??0;let a;try{a=new i(o,{readOnly:!0});const l=a.prepare("SELECT data FROM message WHERE time_created >= ?").all(s);for(const c of l){if(typeof c.data!="string")continue;let u;try{u=JSON.parse(c.data)}catch{continue}const d=u,p=d.tokens;if(!p||d.role!=="assistant")continue;const m=e$(p.input),f=e$(p.output),g=e$(p.cache?.read),y=e$(p.cache?.write);m===0&&f===0&&g===0&&y===0||(t.requests+=1,t.inputTokens+=m,t.outputTokens+=f,t.cacheReadTokens+=g,t.cacheCreationTokens+=y,d.modelID&&n.add(d.modelID))}}catch(l){r.push({cliId:mh,filePath:o,message:l instanceof Error?l.message:String(l)})}finally{try{a?.close()}catch{}}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:mh,totals:t,filesScanned:t.requests>0||r.length===0?1:0,errors:r}}}}var mh,hpn=E({"src/lib/localUsage/openCodeReader.ts"(){"use strict";ui(),$s(),kr(),Mp(),mh="opencode"}}),tyr={};Z(tyr,{createQwenCodeReader:()=>vpn});function ryr(){return Rt(Fs(),".qwen","projects")}function fpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function t$(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function nyr(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}async function gpn(e,t){let r;try{r=await cl(e,{withFileTypes:!0})}catch(o){return nyr(o)||t.push({cliId:sb,filePath:e,message:o instanceof Error?o.message:String(o)}),[]}const n=[];for(const o of r){if(!o.isDirectory())continue;const i=Rt(e,o.name,"chats");try{(await vo(i)).isDirectory()&&n.push(i)}catch{}}return n}async function oyr(e,t,r){let n;try{n=await cl(e,{withFileTypes:!0})}catch(o){nyr(o)||r.push({cliId:sb,filePath:e,message:o instanceof Error?o.message:String(o)});return}for(const o of n){const i=Rt(e,o.name);o.isDirectory()?await oyr(i,t,r):o.isFile()&&o.name.endsWith(".jsonl")&&t.push(i)}}async function ypn(e,t,r){const n=new Map,o=ib({input:Qh(e,{encoding:"utf8"}),crlfDelay:1/0});try{for await(const i of o){if(!i||i.charCodeAt(0)!==123)continue;let s;try{s=JSON.parse(i)}catch{continue}const a=s;if(a.type!=="assistant"||!a.usageMetadata)continue;const l=a.uuid;if(typeof l!="string"||l.length===0)continue;const c=a.usageMetadata,u=t$(c.promptTokenCount),d=t$(c.cachedContentTokenCount),p={model:a.model??"unknown",input:Math.max(0,u-d),output:t$(c.candidatesTokenCount)+t$(c.thoughtsTokenCount),cached:d},m=n.get(l),f=p.input+p.output+p.cached,g=m?m.input+m.output+m.cached:-1;(!m||f>g)&&n.set(l,p)}}finally{o.close()}for(const i of n.values())t.requests+=1,t.inputTokens+=i.input,t.outputTokens+=i.output,t.cacheReadTokens+=i.cached,t.unpricedRequests+=1,r.add(i.model)}async function vpn(){return{descriptor:{id:sb,displayName:"Qwen Code",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"unavailable",requiresSqlite:!1},detect:async()=>{try{return(await vo(ryr())).isDirectory()}catch{return!1}},scan:async e=>{const t=fpn(),r=[],n=new Set,o=await gpn(ryr(),r),i=[];for(const l of o)await oyr(l,i,r);const s=Pp(e?.sinceDays);let a=0;for(const l of i)try{if(s!==void 0&&(await vo(l)).mtimeMs<s)continue;await ypn(l,t,n),a+=1}catch(c){r.push({cliId:sb,filePath:l,message:c instanceof Error?c.message:String(c)})}return t.unpricedModels=[...n].sort(),{cliId:sb,totals:t,filesScanned:a,errors:r}}}}var sb,wpn=E({"src/lib/localUsage/qwenCodeReader.ts"(){"use strict";Tn(),i1(),ui(),$s(),kr(),Mp(),sb="qwen-code"}}),iyr={};Z(iyr,{createGeminiCliReader:()=>Spn});function syr(){return Rt(Fs(),".gemini","tmp")}function Tpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function c1(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function ayr(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}async function bpn(e,t){let r;try{r=await cl(e,{withFileTypes:!0})}catch(o){return ayr(o)||t.push({cliId:ab,filePath:e,message:o instanceof Error?o.message:String(o)}),[]}const n=[];for(const o of r){if(!o.isDirectory())continue;const i=Rt(e,o.name,"chats");try{(await vo(i)).isDirectory()&&n.push(i)}catch{}}return n}async function lyr(e,t,r){let n;try{n=await cl(e,{withFileTypes:!0})}catch(o){ayr(o)||r.push({cliId:ab,filePath:e,message:o instanceof Error?o.message:String(o)});return}for(const o of n){const i=Rt(e,o.name);o.isDirectory()?await lyr(i,t,r):o.isFile()&&o.name.endsWith(".jsonl")&&t.push(i)}}function _pn(e){if(typeof e!="object"||e===null)return[];const t=e;if(t.$set!==void 0){if(typeof t.$set!="object"||t.$set===null)return[];const r=t.$set.messages;return Array.isArray(r)?r.filter(n=>typeof n=="object"&&n!==null):[]}return typeof t.id=="string"&&typeof t.type=="string"?[e]:[]}async function Epn(e,t,r){const n=new Map,o=ib({input:Qh(e,{encoding:"utf8"}),crlfDelay:1/0});try{let i=0;for await(const s of o){if(i+=1,i===1||!s||s.charCodeAt(0)!==123)continue;let a;try{a=JSON.parse(s)}catch{continue}for(const l of _pn(a)){if(l.type!=="gemini"||!l.tokens)continue;const c=l.id;if(typeof c!="string"||c.length===0)continue;const u=l.tokens,d=c1(u.input),p=c1(u.cached),m={model:l.model??"unknown",input:Math.max(0,d-p),output:c1(u.output)+c1(u.thoughts)+c1(u.tool),cached:p},f=n.get(c),g=m.input+m.output+m.cached,y=f?f.input+f.output+f.cached:-1;(!f||g>y)&&n.set(c,m)}}}finally{o.close()}for(const i of n.values())t.requests+=1,t.inputTokens+=i.input,t.outputTokens+=i.output,t.cacheReadTokens+=i.cached,t.unpricedRequests+=1,r.add(i.model)}async function Spn(){return{descriptor:{id:ab,displayName:"Gemini CLI",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"unavailable",requiresSqlite:!1},detect:async()=>{try{return(await vo(syr())).isDirectory()}catch{return!1}},scan:async e=>{const t=Tpn(),r=[],n=new Set,o=await bpn(syr(),r),i=[];for(const l of o)await lyr(l,i,r);const s=Pp(e?.sinceDays);let a=0;for(const l of i)try{if(s!==void 0&&(await vo(l)).mtimeMs<s)continue;await Epn(l,t,n),a+=1}catch(c){r.push({cliId:ab,filePath:l,message:c instanceof Error?c.message:String(c)})}return t.unpricedModels=[...n].sort(),{cliId:ab,totals:t,filesScanned:a,errors:r}}}}var ab,kpn=E({"src/lib/localUsage/geminiCliReader.ts"(){"use strict";Tn(),i1(),ui(),$s(),kr(),Mp(),ab="gemini-cli"}}),cyr={};Z(cyr,{createCopilotCliReader:()=>Cpn});function uyr(){return Rt(Fs(),".copilot","session-store.db")}function xpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function u1(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Apn(e){const t=Pp(e)??0;return new Date(t).toISOString()}async function Cpn(){return{descriptor:{id:hh,displayName:"Copilot CLI",verified:!0,dedupStrategy:"rowid-high-water-mark",costConfidence:"unavailable",requiresSqlite:!0},detect:async()=>{try{return(await vo(uyr())).isFile()}catch{return!1}},scan:async e=>{const t=xpn(),r=[],n=new Set,o=uyr();let i;try{const l=await Promise.resolve().then(()=>(QF(),s1));typeof l=="object"&&l!==null&&"DatabaseSync"in l&&typeof l.DatabaseSync=="function"&&(i=l.DatabaseSync)}catch(l){return r.push({cliId:hh,filePath:o,message:`node:sqlite unavailable on this runtime: ${l instanceof Error?l.message:String(l)} (unflagged since Node 22.13.0 and 23.4.0; on 22.5.0 to 22.12.x and 23.0 to 23.3 pass --experimental-sqlite)`}),{cliId:hh,totals:t,filesScanned:0,errors:r}}if(!i)return r.push({cliId:hh,filePath:o,message:"node:sqlite did not expose a callable DatabaseSync \u2014 the experimental API has likely changed shape"}),{cliId:hh,totals:t,filesScanned:0,errors:r};const s=Apn(e?.sinceDays);let a;try{a=new i(o,{readOnly:!0});const l=a.prepare("SELECT model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens, created_at FROM assistant_usage_events WHERE created_at >= ?").all(s);for(const c of l){const u=u1(c.input_tokens),d=u1(c.output_tokens),p=u1(c.cache_read_tokens),m=u1(c.cache_write_tokens),f=u1(c.reasoning_tokens);u===0&&d===0&&p===0&&m===0&&f===0||(t.requests+=1,t.inputTokens+=Math.max(0,u-p-m),t.outputTokens+=d+f,t.cacheReadTokens+=p,t.cacheCreationTokens+=m,n.add(c.model??"unknown"))}}catch(l){r.push({cliId:hh,filePath:o,message:l instanceof Error?l.message:String(l)})}finally{try{a?.close()}catch{}}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:hh,totals:t,filesScanned:t.requests>0||r.length===0?1:0,errors:r}}}}var hh,Ipn=E({"src/lib/localUsage/copilotCliReader.ts"(){"use strict";ui(),$s(),kr(),Mp(),hh="copilot"}}),dyr={};Z(dyr,{createCursorReader:()=>Dpn,extractCursorContextTokens:()=>hyr});function r$(){return Rt(Fs(),".cursor","chats")}function Rpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function pyr(e){const t=[];let r=0;const n=()=>{let o=0,i=0;for(;r<e.length;){const s=e[r];if(r+=1,s===void 0||i>53||(o+=(s&127)*Math.pow(2,i),!Number.isSafeInteger(o)))return null;if(i+=7,(s&128)===0)return o}return null};for(;r<e.length;){const o=n();if(o===null)return null;const i=Math.floor(o/8),s=o%8;if(s===0){const a=n();if(a===null)return null;t.push({field:i,kind:"varint",value:a})}else if(s===2){const a=n();if(a===null||r+a>e.length)return null;t.push({field:i,kind:"bytes",value:e.subarray(r,r+a)}),r+=a}else if(s===5)r+=4;else if(s===1)r+=8;else return null;if(r>e.length)return null}return t}function Ppn(e){const t=pyr(e);if(t===null||t.length===0)return null;let r,n=!1,o=0;for(const i of t)if(i.field===1&&i.kind==="bytes")try{r=yue.decode(i.value)}catch{return null}else if(i.field===2&&i.kind==="bytes")try{yue.decode(i.value),n=!0}catch{return null}else if(i.field===3&&i.kind==="varint")o=i.value;else if(!(i.field===4&&i.kind==="varint"))return null;return r===void 0||!n?null:{name:r,tokens:o}}function myr(e,t){if(t>12)return null;const r=pyr(e);if(r===null)return null;const n=[];for(const o of r)if(o.kind==="bytes"){const i=Ppn(o.value);i!==null&&n.push(i)}if(n.length>=2){const o=n.reduce((i,s)=>i+s.tokens,0);if(o>0){for(const i of r)if(i.kind==="varint"&&i.value===o)return o}}for(const o of r){if(o.kind!=="bytes")continue;const i=myr(o.value,t+1);if(i!==null)return i}return null}function hyr(e){return myr(e,0)}function Mpn(e){if(/^(?:[0-9a-fA-F]{2})+$/.test(e))try{const t=JSON.parse(Buffer.from(e,"hex").toString("utf8"));if(typeof t=="object"&&t!==null&&"latestRootBlobId"in t&&typeof t.latestRootBlobId=="string")return t.latestRootBlobId}catch{}}async function Opn(){const e=r$(),t=[];let r;try{r=await cl(e)}catch{return t}for(const n of r){let o;try{o=await cl(Rt(e,n))}catch{continue}for(const i of o){const s=Rt(e,n,i,"store.db");try{(await vo(s)).isFile()&&t.push(s)}catch{}}}return t}async function Dpn(){return{descriptor:{id:uu,displayName:"Cursor",verified:!0,dedupStrategy:"last-write-wins",costConfidence:"unavailable",requiresSqlite:!0,requestUnit:"session-snapshot"},detect:async()=>{try{return(await vo(r$())).isDirectory()}catch{return!1}},scan:async e=>{const t=Rpn(),r=[];let n;try{const s=await Promise.resolve().then(()=>(QF(),s1));typeof s=="object"&&s!==null&&"DatabaseSync"in s&&typeof s.DatabaseSync=="function"&&(n=s.DatabaseSync)}catch(s){return r.push({cliId:uu,filePath:r$(),message:`node:sqlite unavailable on this runtime: ${s instanceof Error?s.message:String(s)} (unflagged since Node 22.13.0 and 23.4.0; on 22.5.0 to 22.12.x and 23.0 to 23.3 pass --experimental-sqlite)`}),{cliId:uu,totals:t,filesScanned:0,errors:r}}if(!n)return r.push({cliId:uu,filePath:r$(),message:"node:sqlite did not expose a callable DatabaseSync \u2014 the experimental API has likely changed shape"}),{cliId:uu,totals:t,filesScanned:0,errors:r};const o=Pp(e?.sinceDays);let i=0;for(const s of await Opn()){if(o!==void 0)try{if((await vo(s)).mtimeMs<o)continue}catch{continue}let a;try{a=new n(s,{readOnly:!0}),i+=1;const l=a.prepare("SELECT value FROM meta").all(),c=l.find(f=>typeof f.value=="string")?.value;if(c===void 0){if(l.length===0)continue;r.push({cliId:uu,filePath:s,message:"meta row holds no text value \u2014 Cursor's on-disk format has likely changed"});continue}const u=Mpn(c);if(u===void 0){r.push({cliId:uu,filePath:s,message:"meta row is not hex-encoded JSON carrying a latestRootBlobId \u2014 Cursor's on-disk format has likely changed"});continue}const p=a.prepare("SELECT data FROM blobs WHERE id = ?").all(u)[0]?.data;if(!(p instanceof Uint8Array)||p.length===0)continue;const m=hyr(p);if(m===null){r.push({cliId:uu,filePath:s,message:"root blob carried no context breakdown whose parts sum to a stated total \u2014 Cursor's on-disk format has likely changed"});continue}t.requests+=1,t.inputTokens+=m}catch(l){r.push({cliId:uu,filePath:s,message:l instanceof Error?l.message:String(l)})}finally{try{a?.close()}catch{}}}return{cliId:uu,totals:t,filesScanned:i,errors:r}}}}var uu,yue,Npn=E({"src/lib/localUsage/cursorReader.ts"(){"use strict";ui(),$s(),kr(),Mp(),uu="cursor",yue=new TextDecoder("utf-8",{fatal:!0})}}),fyr={};Z(fyr,{createGrokReader:()=>Vpn});function Lpn(){const e=process.env.GROK_HOME;return e!==void 0&&e.trim().length>0?e:Rt(Fs(),".grok")}function gyr(){return Rt(Lpn(),"sessions")}function Fpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function lb(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:0}function yyr(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}async function $pn(e,t){let r;try{r=await cl(e,{withFileTypes:!0})}catch(o){return yyr(o)||t.push({cliId:S0,filePath:e,message:o instanceof Error?o.message:String(o)}),[]}const n=[];for(const o of r){if(!o.isDirectory())continue;const i=Rt(e,o.name);let s;try{s=await cl(i,{withFileTypes:!0})}catch(a){yyr(a)||t.push({cliId:S0,filePath:i,message:a instanceof Error?a.message:String(a)});continue}for(const a of s){if(!a.isDirectory())continue;const l=Rt(i,a.name,"updates.jsonl");try{(await vo(l)).isFile()&&n.push(l)}catch{}}}return n}function Upn(e){const t=typeof e.modelUsage=="object"&&e.modelUsage!==null?Object.keys(e.modelUsage).filter(r=>r.length>0):[];return{input:lb(e.inputTokens),output:lb(e.outputTokens),cacheRead:lb(e.cachedReadTokens),cacheCreation:lb(e.cacheCreationTokens),calls:lb(e.modelCalls),turns:lb(e.numTurns),models:t}}function Bpn(e,t){return t.turns>e.turns&&t.input>=e.input&&t.output>=e.output&&t.cacheRead>=e.cacheRead&&t.cacheCreation>=e.cacheCreation&&t.calls>=e.calls}function zpn(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e,r=vyr.map(n=>t[n]).filter(n=>typeof n=="number");return r.length>0&&r.every(Number.isFinite)}function Gpn(e){if(typeof e!="object"||e===null)return null;const t=e;if(t.method!=="_x.ai/session/update"||typeof t.params!="object"||t.params===null)return null;const r=t.params.update;if(typeof r!="object"||r===null)return null;const n=r;return n.sessionUpdate!=="turn_completed"||n.usage===void 0||n.usage===null?null:{promptId:typeof n.prompt_id=="string"?n.prompt_id:void 0,usage:n.usage}}async function qpn(e,t,r,n){const o=new Map;let i=0;const s=ib({input:Qh(e,{encoding:"utf8"}),crlfDelay:1/0});try{let l=0;for await(const c of s){if(l+=1,!c||c.charCodeAt(0)!==123)continue;let u;try{u=JSON.parse(c)}catch{continue}const d=Gpn(u);if(d!==null){if(!zpn(d.usage)){i+=1,d.promptId!==void 0&&o.delete(d.promptId);continue}o.set(d.promptId??`line:${l}`,Upn(d.usage))}}}finally{s.close()}i>0&&n.push({cliId:S0,filePath:e,message:`${i} completed turn(s) carried a usage record with no recognisable token or call counter \u2014 Grok Build's stream format has likely changed`});let a;for(const l of o.values()){const c=a!==void 0&&Bpn(a,l)?{input:l.input-a.input,output:l.output-a.output,cacheRead:l.cacheRead-a.cacheRead,cacheCreation:l.cacheCreation-a.cacheCreation,calls:l.calls-a.calls}:l;a=l;const u=c.calls>0?c.calls:1;t.requests+=u,t.inputTokens+=c.input,t.outputTokens+=c.output,t.cacheReadTokens+=c.cacheRead,t.cacheCreationTokens+=c.cacheCreation,t.unpricedRequests+=u;for(const d of l.models.length>0?l.models:["unknown"])r.add(d)}}async function Vpn(){return{descriptor:{id:S0,displayName:"Grok Build",verified:!0,dedupStrategy:"last-write-wins",costConfidence:"unavailable",requiresSqlite:!1},detect:async()=>{try{return(await vo(gyr())).isDirectory()}catch{return!1}},scan:async e=>{const t=Fpn(),r=[],n=new Set,o=Pp(e?.sinceDays);let i=0;for(const s of await $pn(gyr(),r))try{if(o!==void 0&&(await vo(s)).mtimeMs<o)continue;await qpn(s,t,n,r),i+=1}catch(a){r.push({cliId:S0,filePath:s,message:a instanceof Error?a.message:String(a)})}return t.unpricedModels=[...n].sort(),{cliId:S0,totals:t,filesScanned:i,errors:r}}}}var S0,vyr,jpn=E({"src/lib/localUsage/grokReader.ts"(){"use strict";Tn(),i1(),ui(),$s(),kr(),Mp(),S0="grok",vyr=["inputTokens","outputTokens","modelCalls"]}}),wyr={};Z(wyr,{createHermesReader:()=>Jpn});function vue(){const e=process.env.HERMES_HOME;return e!==void 0&&e.trim().length>0?e:Rt(Fs(),".hermes")}function Hpn(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"modeled",unpricedRequests:0,unpricedModels:[]}}function k0(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0}function Tyr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}async function byr(){const e=vue(),t=[],r=Rt(e,"state.db");try{(await vo(r)).isFile()&&t.push(r)}catch{}let n;try{n=(await cl(Rt(e,"profiles"),{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return t}for(const o of n){const i=Rt(e,"profiles",o,"state.db");try{(await vo(i)).isFile()&&t.push(i)}catch{}}return t}function _yr(e,t){const r=e.prepare(`PRAGMA table_info(${t})`).all();return new Set(r.map(n=>n.name).filter(n=>typeof n=="string"))}function Eyr(e,t,r,n=t){return e.has(t)?`${n===t?t:`${t} AS ${n}`}`:`${r} AS ${n}`}function Wpn(e){const t=typeof e.cost_status=="string"?e.cost_status.toLowerCase():"",r=Tyr(e.actual_cost_usd),n=Tyr(e.estimated_cost_usd);return t==="actual"||t==="billed"?r:t==="estimated"||n!==null&&n>0?n:null}function Syr(e){const[t]=e;return e.length===1&&t!==void 0?t:`COALESCE(${e.join(", ")})`}function kyr(e,t,r){const n=k0(e.api_call_count),o=k0(e.input_tokens),i=k0(e.output_tokens);if(n===0&&o+i===0)return;t.requests+=n>0?n:1,t.inputTokens+=o,t.outputTokens+=i,t.cacheReadTokens+=k0(e.cache_read_tokens),t.cacheCreationTokens+=k0(e.cache_write_tokens);const s=Wpn(e);s===null?(t.unpricedRequests+=n>0?n:1,r.add(typeof e.model=="string"&&e.model?e.model:"unknown")):t.costUsd+=s}function Kpn(e,t,r,n,o,i){const s=_yr(e,"sessions");if(s.size===0){i.push({cliId:du,filePath:t,message:"no sessions table \u2014 not a Hermes state store, or one this reader does not understand"});return}const a=Ayr.filter(g=>!s.has(g));if(a.length>0){i.push({cliId:du,filePath:t,message:`sessions table lacks required column(s) ${a.join(", ")} \u2014 Hermes' schema has changed`});return}const l=_yr(e,"session_model_usage"),c=xyr.filter(g=>!l.has(g));if(l.size>0&&c.length>0){i.push({cliId:du,filePath:t,message:`session_model_usage table lacks required column(s) ${c.join(", ")} \u2014 Hermes' schema has changed`});return}const u=l.size>0,d=[s.has("last_activity_at")?"s.last_activity_at":null,s.has("ended_at")?"s.ended_at":null,"s.started_at"].filter(g=>g!==null);if(u){const g=[l.has("last_seen")?"u.last_seen":null,l.has("first_seen")?"u.first_seen":null,...d].filter(T=>T!==null),y=`SELECT u.session_id, u.model, u.api_call_count, u.input_tokens, u.output_tokens, ${wue.map(T=>l.has(T)?`u.${T}`:`0 AS ${T}`).join(", ")}, ${Tue.map(T=>l.has(T)?`u.${T}`:`NULL AS ${T}`).join(", ")}, ${Syr(g)} AS at FROM session_model_usage u LEFT JOIN sessions s ON s.id = u.session_id`,v=e.prepare(y).all();for(const T of v)r!==void 0&&k0(T.at)<r||kyr(T,n,o)}const p=u?" WHERE NOT EXISTS (SELECT 1 FROM session_model_usage u WHERE u.session_id = s.id)":"",m=`SELECT s.id AS session_id, ${Eyr(s,"model","NULL")}, ${Eyr(s,"api_call_count","0")}, s.input_tokens, s.output_tokens, ${wue.map(g=>s.has(g)?`s.${g}`:`0 AS ${g}`).join(", ")}, ${Tue.map(g=>s.has(g)?`s.${g}`:`NULL AS ${g}`).join(", ")}, ${Syr(d)} AS at FROM sessions s${p}`,f=e.prepare(m).all();for(const g of f)r!==void 0&&k0(g.at)<r||kyr(g,n,o)}async function Jpn(){return{descriptor:{id:du,displayName:"Hermes Agent",verified:!0,dedupStrategy:"last-write-wins",costConfidence:"modeled",requiresSqlite:!0},detect:async()=>(await byr()).length>0,scan:async e=>{const t=Hpn(),r=[],n=new Set;let o;try{const l=await Promise.resolve().then(()=>(QF(),s1));typeof l=="object"&&l!==null&&"DatabaseSync"in l&&typeof l.DatabaseSync=="function"&&(o=l.DatabaseSync)}catch(l){return r.push({cliId:du,filePath:vue(),message:`node:sqlite unavailable on this runtime: ${l instanceof Error?l.message:String(l)} (unflagged since Node 22.13.0 and 23.4.0; on 22.5.0 to 22.12.x and 23.0 to 23.3 pass --experimental-sqlite)`}),{cliId:du,totals:t,filesScanned:0,errors:r}}if(!o)return r.push({cliId:du,filePath:vue(),message:"node:sqlite did not expose a callable DatabaseSync \u2014 the experimental API has likely changed shape"}),{cliId:du,totals:t,filesScanned:0,errors:r};const i=Pp(e?.sinceDays),s=i===void 0?void 0:i/1e3;let a=0;for(const l of await byr()){let c;try{c=new o(l,{readOnly:!0}),a+=1,Kpn(c,l,s,t,n,r)}catch(u){r.push({cliId:du,filePath:l,message:u instanceof Error?u.message:String(u)})}finally{try{c?.close()}catch{}}}return t.unpricedModels=[...n].sort(),{cliId:du,totals:t,filesScanned:a,errors:r}}}}var du,xyr,Ayr,wue,Tue,Xpn=E({"src/lib/localUsage/hermesReader.ts"(){"use strict";ui(),$s(),kr(),Mp(),du="hermes",xyr=["session_id","model","api_call_count","input_tokens","output_tokens"],Ayr=["id","started_at","input_tokens","output_tokens"],wue=["cache_read_tokens","cache_write_tokens","reasoning_tokens"],Tue=["estimated_cost_usd","actual_cost_usd","cost_status"]}});Ga(),Os(),Fl(),Tn(),kr(),$t(),z(),pt();var{readFile:bue,writeFile:Cyr,readdir:Ypn,mkdir:Zpn,unlink:Qpn,access:emn}=ns,tmn=class{configPath=".neurolink.config";backupDir=".neurolink.backups";config=null;configCache=new Map;async loadConfig(){return this.config||(this.config=await this.readConfigFile()),this.config}async updateConfig(e,t={}){const{createBackup:r=!0,validate:n=!0,merge:o=!0,reason:i="update",silent:s=!1}=t;r&&(await this.createBackup(i),s||h.info("\u{1F4BE} Backup created before config update"));const a=await this.loadConfig();if(this.config=o?{...a,...e,lastUpdated:Date.now()}:{...e,lastUpdated:Date.now()},n){const l=await this.validateConfig(this.config);if(!l.valid)throw new Error(`Config validation failed: ${l.errors.join(", ")}`)}try{await this.persistConfig(this.config),s||h.info("\u2705 Configuration updated successfully")}catch(l){throw r&&(await this.restoreLatestBackup(),s||h.info("\u{1F504} Auto-restored from backup due to error")),new Error(`Config update failed, restored from backup: ${l.message}`,{cause:l})}}async createBackup(e="manual"){await this.ensureBackupDirectory();const r=`neurolink-config-${new Date().toISOString().replace(/[:.]/g,"-")}.js`,n=Rt(this.backupDir,r),o=await this.loadConfig(),i=this.generateConfigHash(o),s={reason:e,timestamp:Date.now(),version:o.configVersion||"unknown",originalPath:this.configPath,hash:i,size:JSON.stringify(o).length,createdBy:"NeuroLinkConfigManager"},a=`// NeuroLink Config Backup - ${e}
|
|
2243
2243
|
// Created: ${new Date().toISOString()}
|
|
2244
2244
|
// Reason: ${e}
|
|
2245
2245
|
// Hash: ${i}
|
|
@@ -125,7 +125,7 @@ export async function createCopilotCliReader() {
|
|
|
125
125
|
errors.push({
|
|
126
126
|
cliId: CLI_ID,
|
|
127
127
|
filePath: dbPath,
|
|
128
|
-
message: `node:sqlite unavailable on this runtime: ${error instanceof Error ? error.message : String(error)} (
|
|
128
|
+
message: `node:sqlite unavailable on this runtime: ${error instanceof Error ? error.message : String(error)} (unflagged since Node 22.13.0 and 23.4.0; on 22.5.0 to 22.12.x and 23.0 to 23.3 pass --experimental-sqlite)`,
|
|
129
129
|
});
|
|
130
130
|
return { cliId: CLI_ID, totals, filesScanned: 0, errors };
|
|
131
131
|
}
|
|
@@ -375,7 +375,7 @@ export async function createCursorReader() {
|
|
|
375
375
|
errors.push({
|
|
376
376
|
cliId: CLI_ID,
|
|
377
377
|
filePath: chatsRoot(),
|
|
378
|
-
message: `node:sqlite unavailable on this runtime: ${error instanceof Error ? error.message : String(error)} (
|
|
378
|
+
message: `node:sqlite unavailable on this runtime: ${error instanceof Error ? error.message : String(error)} (unflagged since Node 22.13.0 and 23.4.0; on 22.5.0 to 22.12.x and 23.0 to 23.3 pass --experimental-sqlite)`,
|
|
379
379
|
});
|
|
380
380
|
return { cliId: CLI_ID, totals, filesScanned: 0, errors };
|
|
381
381
|
}
|
|
@@ -318,7 +318,7 @@ export async function createHermesReader() {
|
|
|
318
318
|
errors.push({
|
|
319
319
|
cliId: CLI_ID,
|
|
320
320
|
filePath: hermesHome(),
|
|
321
|
-
message: `node:sqlite unavailable on this runtime: ${error instanceof Error ? error.message : String(error)} (
|
|
321
|
+
message: `node:sqlite unavailable on this runtime: ${error instanceof Error ? error.message : String(error)} (unflagged since Node 22.13.0 and 23.4.0; on 22.5.0 to 22.12.x and 23.0 to 23.3 pass --experimental-sqlite)`,
|
|
322
322
|
});
|
|
323
323
|
return { cliId: CLI_ID, totals, filesScanned: 0, errors };
|
|
324
324
|
}
|
|
@@ -81,8 +81,8 @@ export async function createOpenCodeReader() {
|
|
|
81
81
|
const models = new Set();
|
|
82
82
|
const dbPath = databasePath();
|
|
83
83
|
// `node:sqlite` arrived in Node 22.5.0 behind `--experimental-sqlite`, was
|
|
84
|
-
// unflagged in 22.13.0 and is still marked experimental, so it
|
|
85
|
-
// absent or change shape. Imported lazily and behind a try/catch: a
|
|
84
|
+
// unflagged in 22.13.0 and 23.4.0 and is still marked experimental, so it
|
|
85
|
+
// can be absent or change shape. Imported lazily and behind a try/catch: a
|
|
86
86
|
// runtime without it must degrade to a reported failure for this one
|
|
87
87
|
// reader, not take down a scan of all the others.
|
|
88
88
|
let DatabaseSync;
|
|
@@ -103,7 +103,7 @@ export async function createOpenCodeReader() {
|
|
|
103
103
|
errors.push({
|
|
104
104
|
cliId: CLI_ID,
|
|
105
105
|
filePath: dbPath,
|
|
106
|
-
message: `node:sqlite unavailable on this runtime: ${error instanceof Error ? error.message : String(error)} (
|
|
106
|
+
message: `node:sqlite unavailable on this runtime: ${error instanceof Error ? error.message : String(error)} (unflagged since Node 22.13.0 and 23.4.0; on 22.5.0 to 22.12.x and 23.0 to 23.3 pass --experimental-sqlite)`,
|
|
107
107
|
});
|
|
108
108
|
return { cliId: CLI_ID, totals, filesScanned: 0, errors };
|
|
109
109
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "12.47.
|
|
3
|
+
"version": "12.47.7",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002/call) for routing, tool selection and context budgeting. MCP-native (4 transports), voice TTS/STT/realtime, RAG, agents, memory, compaction, 9 observability exporters. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · TypeSafe Jev and more.",
|
|
6
6
|
"author": {
|