@juspay/neurolink 11.22.1 → 11.22.2

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
- ## [11.22.1](https://github.com/juspay/neurolink/compare/v11.22.0...v11.22.1) (2026-08-23)
1
+ ## [11.22.2](https://github.com/juspay/neurolink/compare/v11.22.1...v11.22.2) (2026-08-24)
2
2
 
3
3
  ### Bug Fixes
4
4
 
5
- - **(cli):** bound the synchronous ollama and scanner subprocesses ([51109e3](https://github.com/juspay/neurolink/commit/51109e3eeb3a6665eb840cc7a3aa561bb115d4b7))
5
+ - **(localUsage):** treat a non-positive scan window as empty, not unbounded ([e79d1d5](https://github.com/juspay/neurolink/commit/e79d1d54565f6e0b84c8dd6ab55a892560c81b4e)), closes [#1482](https://github.com/juspay/neurolink/issues/1482)
6
6
 
7
7
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
8
8
 
@@ -2213,7 +2213,7 @@ Content:
2213
2213
  ${e.text}
2214
2214
 
2215
2215
  Return the extracted data as JSON.`,s=await this.callLLM(o,t);try{const i=s.match(/\{[\s\S]*\}/);return JSON.parse(i?i[0]:s)}catch{return f.warn("[MetadataExtractor] Failed to parse custom extraction as JSON"),{raw:s}}}parseQAPairs(e,t){const r=[],n=e.split(`
2216
- `).filter(i=>i.trim());let o=null,s=null;for(const i of n){const a=i.trim();/^\d+[.):]\s*/.test(a)||/^Q[.:]?\s*/i.test(a)?(o&&r.push({question:o,...t&&s?{answer:s}:{}}),o=a.replace(/^\d+[.):]\s*/,"").replace(/^Q[.:]?\s*/i,""),s=null):/^A[.:]?\s*/i.test(a)&&o?s=a.replace(/^A[.:]?\s*/i,""):o&&!s?o+=" "+a:s&&(s+=" "+a)}return o&&r.push({question:o,...t&&s?{answer:s}:{}}),r}async callLLM(e,t){return(await(await Fr.createProvider(t.provider||this.provider,t.modelName||this.modelName)).generate({prompt:e,maxTokens:t.maxTokens||500,temperature:t.temperature||.3}))?.content||""}}}}),$Wt,Hne,Il,_c=C({"src/lib/auth/providers/BaseAuthProvider.ts"(){"use strict";$t(),Pn(),V(),Yi(),$Wt=xt,Hne=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 s of t){const i=this.sessions.get(s);if(i){if(i.expiresAt&&i.expiresAt.getTime()<r){o.push(s);continue}if(!i.isValid){o.push(s);continue}n.push(i)}}for(const s of o)this.sessions.delete(s),t.delete(s);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}},Il=class{config;sessionStorage;sessionConfig;rbacConfig;emitter=new Rn;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 Hne,f.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,s]of Object.entries(e.headers))if(o.toLowerCase()===r&&typeof s=="string"){n=s;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 s=await this.sessionStorage.getForUser(e.id);if(s.length>=this.sessionConfig.maxSessionsPerUser){const i=s.sort((a,l)=>a.createdAt.getTime()-l.createdAt.getTime())[0];i&&await this.sessionStorage.delete(i.id)}}const o={id:st(),user:e,accessToken:st(),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),f.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),f.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),f.debug(`[BaseAuthProvider] Revoked session ${e}`))}async revokeAllSessions(e){await this.sessionStorage.deleteAllForUser(e),f.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(s=>!n.has(s));t.requireAllRoles?o.length>0&&(r.authorized=!1,r.missingRoles=o,r.reason=`Missing required roles: ${o.join(", ")}`):t.roles.some(i=>n.has(i))||(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(s=>!this.hasPermission(n,s));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 s=r[o]??[];for(const i of s)t.has(i)||(t.add(i),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 s=r[o]??[];for(const i of s)t.add(i)}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",s=Array.isArray(e[r])?e[r]:this.rbacConfig.defaultRoles??[],i=Array.isArray(e[n])?e[n]:[];return{id:e[o]??"",email:e.email,name:e.name,picture:e.picture,roles:s,permissions:i,emailVerified:e.email_verified,providerData:e}}async getUser(e){return f.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(),f.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 s=(await this.getUserSessions(r.user.id)).find(i=>i.isValid&&(!i.expiresAt||i.expiresAt.getTime()>Date.now()))??await this.createSession(r.user,e);return{...e,user:r.user,session:s,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 FWt(...e){const t=e.reduce((o,{length:s})=>o+s,0),r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function k_(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 Ox,I_,UHr,Nx=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js"(){Ox=new TextEncoder,I_=new TextDecoder,UHr=2**32}});function BHr(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 UWt(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 BWt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js"(){}});function vL(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:I_.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=I_.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return UWt(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Vne(e){let t=e;return typeof t=="string"&&(t=Ox.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):BHr(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Lx=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js"(){Nx(),BWt()}});function zHr(e){return parseInt(e.name.slice(4),10)}function Wne(e,t){if(zHr(e.hash)!==t)throw lp(`SHA-${t}`,"algorithm.hash")}function jHr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function qHr(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function GHr(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Bg(e.algorithm,"HMAC"))throw lp("HMAC");Wne(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!Bg(e.algorithm,"RSASSA-PKCS1-v1_5"))throw lp("RSASSA-PKCS1-v1_5");Wne(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!Bg(e.algorithm,"RSA-PSS"))throw lp("RSA-PSS");Wne(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!Bg(e.algorithm,"Ed25519"))throw lp("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!Bg(e.algorithm,t))throw lp(t);break}case"ES256":case"ES384":case"ES512":{if(!Bg(e.algorithm,"ECDSA"))throw lp("ECDSA");const n=jHr(t);if(e.algorithm.namedCurve!==n)throw lp(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}qHr(e,r)}var lp,Bg,HHr=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js"(){lp=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),Bg=(e,t)=>e.name===t}});function zWt(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 jWt,Kne,qWt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js"(){jWt=(e,...t)=>zWt("Key must be ",e,...t),Kne=(e,t,...r)=>zWt(`Key for the ${e} algorithm must be `,t,...r)}}),Za,au,Jne,GWt,Rl,Mo,_L,Yne,Zne,HWt,VWt,WWt,Pl=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js"(){Za=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)}},au=class extends Za{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}},Jne=class extends Za{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}},GWt=class extends Za{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Rl=class extends Za{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Mo=class extends Za{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},_L=class extends Za{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},Yne=class extends Za{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Zne=class extends Za{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)}},HWt=class extends Za{[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)}},VWt=class extends Za{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}},WWt=class extends Za{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}}}),Xne,Qne,eoe,KWt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js"(){Xne=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Qne=e=>e?.[Symbol.toStringTag]==="KeyObject",eoe=e=>Xne(e)||Qne(e)}});function JWt(e,t){if(e)throw new TypeError(`${t} can only be called once`)}function YWt(e,t,r){try{return vL(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}var ZWt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js"(){Lx()}});function cp(e){if(!QWt(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 XWt(...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 s of o){if(r.has(s))return!1;r.add(s)}}return!0}var QWt,wL,eKt,tKt,rKt,up=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js"(){QWt=e=>typeof e=="object"&&e!==null,wL=e=>cp(e)&&typeof e.kty=="string",eKt=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),tKt=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,rKt=e=>e.kty==="oct"&&typeof e.k=="string"}});function nKt(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 oKt(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 Rl(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function sKt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(jWt(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return GHr(t,e,r),t}async function VHr(e,t,r){const n=await sKt(e,t,"sign");nKt(e,n);const o=await crypto.subtle.sign(oKt(e,n.algorithm),n,r);return new Uint8Array(o)}async function WHr(e,t,r,n){const o=await sKt(e,t,"verify");nKt(e,o);const s=oKt(e,o.algorithm);try{return await crypto.subtle.verify(s,o,r,n)}catch{return!1}}var iKt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js"(){Pl(),HHr(),qWt()}});function KHr(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 Rl($x)}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 Rl($x)}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 Rl($x)}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 Rl($x)}break}default:throw new Rl('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function TL(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=KHr(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 $x,aKt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js"(){Pl(),$x='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'}});async function lKt(e,t){if(e instanceof Uint8Array||Xne(e))return e;if(Qne(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return cKt(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return toe(e,r,t)}if(wL(e))return e.k?vL(e.k):toe(e,e,t,!0);throw new Error("unreachable")}var zg,R_,toe,cKt,uKt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js"(){up(),Lx(),aKt(),KWt(),zg="given KeyObject instance cannot be used for this algorithm",toe=async(e,t,r,n=!1)=>{R_||=new WeakMap;let o=R_.get(e);if(o?.[r])return o[r];const s=await TL({...t,alg:r});return n&&Object.freeze(e),o?o[r]=s:R_.set(e,{[r]:s}),s},cKt=(e,t)=>{R_||=new WeakMap;let r=R_.get(e);if(r?.[t])return r[t];const n=e.type==="public",o=!!n;let s;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(zg)}s=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(zg);s=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(zg);s=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let i;switch(t){case"RSA-OAEP":i="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":i="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":i="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":i="SHA-512";break;default:throw new TypeError(zg)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:i},o,n?["encrypt"]:["decrypt"]);s=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},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(zg);const l={ES256:"P-256",ES384:"P-384",ES512:"P-521"};l[t]&&a===l[t]&&(s=e.toCryptoKey({name:"ECDSA",namedCurve:a},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(s=e.toCryptoKey({name:"ECDH",namedCurve:a},o,n?[]:["deriveBits"]))}if(!s)throw new TypeError(zg);return r?r[t]=s:R_.set(e,{[t]:s}),s}}});function JHr(e){Ux(e,48,"Invalid SPKI structure"),Fx(e),Ux(e,48,"Expected algorithm identifier");const t=Fx(e);return{algIdStart:e.pos,algIdLength:t}}var bL,dKt,Fx,Ux,roe,pKt,mKt,hKt,fKt,gKt,YHr=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/asn1.js"(){BWt(),Pl(),bL=(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},dKt=e=>({data:e,pos:0}),Fx=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},Ux=(e,t,r)=>{if(e.data[e.pos++]!==t)throw new Error(r)},roe=(e,t)=>{const r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},pKt=e=>{Ux(e,6,"Expected algorithm OID");const t=Fx(e);return roe(e,t)},mKt=e=>{const t=pKt(e);if(bL(t,[43,101,110]))return"X25519";if(!bL(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");Ux(e,6,"Expected curve OID");const r=Fx(e),n=roe(e,r);for(const{name:o,oid:s}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(bL(n,s))return o;throw new Error("Unsupported named curve")},hKt=async(e,t,r,n)=>{let o,s;const i=e==="spki",a=()=>i?["verify"]:["sign"],l=()=>i?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},s=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}`},s=l();break;case"ES256":case"ES384":case"ES512":{o={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},s=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 Rl("Invalid or unsupported key format")}s=i?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":o={name:"Ed25519"},s=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":o={name:r},s=a();break;default:throw new Rl('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,o,n?.extractable??!!i,s)},fKt=(e,t)=>UWt(e.replace(t,"")),gKt=(e,t,r)=>{const n=fKt(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);let o=r;return t?.startsWith?.("ECDH-ES")&&(o||={},o.getNamedCurve=s=>{const i=dKt(s);return JHr(i),mKt(i)}),hKt("spki",n,t,o)}}});async function ZHr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return gKt(e,t,r)}async function noe(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 vL(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new Rl('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return TL({...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 TL({...e,ext:n})}case"EC":case"OKP":return TL({...e,alg:t,ext:n});default:throw new Rl('Unsupported "kty" (Key Type) Parameter value')}}var yKt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js"(){Lx(),YHr(),aKt(),Pl(),up()}});function vKt(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(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(const i of n.crit){if(!s.has(i))throw new Rl(`Extension Header Parameter "${i}" is not recognized`);if(o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var _Kt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js"(){Pl()}});function XHr(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 QHr=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js"(){}});function wKt(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":TKt(e,t,r);break;default:bKt(e,t,r)}}var jg,EL,TKt,bKt,EKt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js"(){qWt(),KWt(),up(),jg=e=>e?.[Symbol.toStringTag],EL=(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},TKt=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(wL(t)){if(rKt(t)&&EL(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(!eoe(t))throw new TypeError(Kne(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${jg(t)} instances for symmetric algorithms must be of type "secret"`)}},bKt=(e,t,r)=>{if(wL(t))switch(r){case"decrypt":case"sign":if(eKt(t)&&EL(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(tKt(t)&&EL(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!eoe(t))throw new TypeError(Kne(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${jg(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${jg(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${jg(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${jg(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${jg(t)} instances for asymmetric algorithm encryption must be of type "public"`)}}}});async function e7r(e,t,r){if(!cp(e))throw new Mo("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new Mo('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new Mo("JWS Protected Header incorrect type");if(e.payload===void 0)throw new Mo("JWS Payload missing");if(typeof e.signature!="string")throw new Mo("JWS Signature missing or incorrect type");if(e.header!==void 0&&!cp(e.header))throw new Mo("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const v=vL(e.protected);n=JSON.parse(I_.decode(v))}catch{throw new Mo("JWS Protected Header is invalid")}if(!XWt(n,e.header))throw new Mo("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header},s=vKt(Mo,new Map([["b64",!0]]),r?.crit,n,o);let i=!0;if(s.has("b64")&&(i=n.b64,typeof i!="boolean"))throw new Mo('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if(typeof a!="string"||!a)throw new Mo('JWS "alg" (Algorithm) Header Parameter missing or invalid');const l=r&&XHr("algorithms",r.algorithms);if(l&&!l.has(a))throw new GWt('"alg" (Algorithm) Header Parameter value not allowed');if(i){if(typeof e.payload!="string")throw new Mo("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new Mo("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof t=="function"&&(t=await t(n,e),c=!0),wKt(a,t,"verify");const u=FWt(e.protected!==void 0?k_(e.protected):new Uint8Array,k_("."),typeof e.payload=="string"?i?k_(e.payload):Ox.encode(e.payload):e.payload),d=YWt(e.signature,"signature",Mo),m=await lKt(t,a);if(!await WHr(a,m,d,u))throw new WWt;let g;i?g=YWt(e.payload,"payload",Mo):typeof e.payload=="string"?g=Ox.encode(e.payload):g=e.payload;const y={payload:g};return e.protected!==void 0&&(y.protectedHeader=n),e.header!==void 0&&(y.unprotectedHeader=e.header),c?{...y,key:m}:y}var t7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js"(){Lx(),iKt(),Pl(),Nx(),ZWt(),up(),up(),EKt(),_Kt(),QHr(),uKt()}});async function r7r(e,t,r){if(e instanceof Uint8Array&&(e=I_.decode(e)),typeof e!="string")throw new Mo("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:s,length:i}=e.split(".");if(i!==3)throw new Mo("Invalid Compact JWS");const a=await e7r({payload:o,protected:n,signature:s},t,r),l={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...l,key:a.key}:l}var n7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js"(){t7r(),Pl(),Nx()}});function Bx(e){const t=xKt.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*ooe);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*soe);break;case"day":case"days":case"d":o=Math.round(r*SL);break;case"week":case"weeks":case"w":o=Math.round(r*SKt);break;default:o=Math.round(r*CKt);break}return t[1]==="-"||t[4]==="ago"?-o:o}function qg(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function o7r(e,t,r={}){let n;try{n=JSON.parse(I_.decode(t))}catch{}if(!cp(n))throw new _L("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&(typeof e.typ!="string"||ioe(e.typ)!==ioe(o)))throw new au('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:s=[],issuer:i,subject:a,audience:l,maxTokenAge:c}=r,u=[...s];c!==void 0&&u.push("iat"),l!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),i!==void 0&&u.push("iss");for(const g of new Set(u.reverse()))if(!(g in n))throw new au(`missing required "${g}" claim`,n,g,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new au('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new au('unexpected "sub" claim value',n,"sub","check_failed");if(l&&!AKt(n.aud,typeof l=="string"?[l]:l))throw new au('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=Bx(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,h=dp(m||new Date);if((n.iat!==void 0||c)&&typeof n.iat!="number")throw new au('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new au('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>h+d)throw new au('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new au('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=h-d)throw new Jne('"exp" claim timestamp check failed',n,"exp","check_failed")}if(c){const g=h-n.iat,y=typeof c=="number"?c:Bx(c);if(g-d>y)throw new Jne('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(g<0-d)throw new au('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var dp,ooe,soe,SL,SKt,CKt,xKt,ioe,AKt,kKt,IKt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js"(){Pl(),Nx(),up(),dp=e=>Math.floor(e.getTime()/1e3),ooe=60,soe=ooe*60,SL=soe*24,SKt=SL*7,CKt=SL*365.25,xKt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ioe=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,AKt=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,kKt=class{#e;constructor(e){if(!cp(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return Ox.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=qg("setNotBefore",e):e instanceof Date?this.#e.nbf=qg("setNotBefore",dp(e)):this.#e.nbf=dp(new Date)+Bx(e)}set exp(e){typeof e=="number"?this.#e.exp=qg("setExpirationTime",e):e instanceof Date?this.#e.exp=qg("setExpirationTime",dp(e)):this.#e.exp=dp(new Date)+Bx(e)}set iat(e){e===void 0?this.#e.iat=dp(new Date):e instanceof Date?this.#e.iat=qg("setIssuedAt",dp(e)):typeof e=="string"?this.#e.iat=qg("setIssuedAt",dp(new Date)+Bx(e)):this.#e.iat=qg("setIssuedAt",e)}}}});async function lu(e,t,r){const n=await r7r(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new _L("JWTs MUST NOT use unencoded payload");const s={payload:o7r(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...s,key:n.key}:s}var s7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js"(){n7r(),IKt(),Pl()}}),RKt,i7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js"(){Lx(),iKt(),up(),Pl(),Nx(),EKt(),_Kt(),uKt(),ZWt(),RKt=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 JWt(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return JWt(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,t){if(!this.#t&&!this.#r)throw new Mo("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!XWt(this.#t,this.#r))throw new Mo("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this.#t,...this.#r},n=vKt(Mo,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 Mo('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if(typeof s!="string"||!s)throw new Mo('JWS "alg" (Algorithm) Header Parameter missing or invalid');wKt(s,e,"sign");let i,a;o?(i=Vne(this.#e),a=k_(i)):(a=this.#e,i="");let l,c;this.#t?(l=Vne(JSON.stringify(this.#t)),c=k_(l)):(l="",c=new Uint8Array);const u=FWt(c,k_("."),a),d=await lKt(e,s),m=await VHr(s,d,u),h={signature:Vne(m),payload:i};return this.#r&&(h.header=this.#r),this.#t&&(h.protected=l),h}}}}),PKt,a7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js"(){i7r(),PKt=class{#e;constructor(e){this.#e=new RKt(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}`}}}}),MKt,l7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js"(){a7r(),Pl(),IKt(),MKt=class{#e;#t;constructor(e={}){this.#t=new kKt(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 PKt(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new _L("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}}});function c7r(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 Rl('Unsupported "alg" value for a JSON Web Key Set')}}function u7r(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(d7r)}function d7r(e){return cp(e)}async function DKt(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){const o=await noe({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new Yne("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function OKt(e){const t=new NKt(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 NKt,p7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js"(){yKt(),Pl(),up(),NKt=class{#e;#t=new WeakMap;constructor(e){if(!u7r(e))throw new Yne("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=c7r(r),s=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:i,length:a}=s;if(a===0)throw new Zne;if(a!==1){const l=new HWt,c=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(const u of s)try{yield await DKt(c,u,r)}catch{}},l}return DKt(this.#t,i,r)}}}});function m7r(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function h7r(e,t,r,n=fetch){const o=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(s=>{throw s.name==="TimeoutError"?new VWt:s});if(o.status!==200)throw new Za("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new Za("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function f7r(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 zx(e,t){const r=new $Kt(e,t),n=async(o,s)=>r.getKey(o,s);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 aoe,LKt,CL,$Kt,g7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js"(){Pl(),p7r(),up(),(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(aoe="jose/v6.2.2"),LKt=Symbol(),CL=Symbol(),$Kt=class{#e;#t;#r;#n;#o;#s;#i;#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.#i=new Headers(t?.headers),aoe&&!this.#i.has("User-Agent")&&this.#i.set("User-Agent",aoe),this.#i.has("accept")||(this.#i.set("accept","application/json"),this.#i.append("accept","application/jwk-set+json")),this.#c=t?.[LKt],t?.[CL]!==void 0&&(this.#l=t?.[CL],f7r(t?.[CL],this.#n)&&(this.#o=this.#l.uat,this.#a=OKt(this.#l.jwks)))}pendingFetch(){return!!this.#s}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 Zne&&this.coolingDown()===!1)return await this.reload(),this.#a(e,t);throw r}}async reload(){this.#s&&m7r()&&(this.#s=void 0),this.#s||=h7r(this.#e.href,this.#i,AbortSignal.timeout(this.#t),this.#c).then(e=>{this.#a=OKt(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#o=Date.now(),this.#s=void 0}).catch(e=>{throw this.#s=void 0,e}),await this.#s}}}}),ed=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js"(){s7r(),l7r(),g7r(),yKt()}}),FKt={};le(FKt,{Auth0Provider:()=>UKt});var UKt,y7r=C({"src/lib/auth/providers/auth0.ts"(){"use strict";_c(),Yi(),V(),Xn(),ed(),UKt=class extends Il{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=zx(e),f.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 lu(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",s=this.permissionsNamespace??"permissions",i=r[o]||n.roles||[],a=r[s]||n.permissions||[],l={id:n.sub,email:n.email,name:n.name,picture:n.picture,emailVerified:n.email_verified,roles:i,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 f.warn("Auth0 token validation failed:",n),{valid:!1,error:n}}}async getUser(e){const t=process.env.AUTH0_MANAGEMENT_TOKEN;if(!t)return f.warn("AUTH0_MANAGEMENT_TOKEN not set, cannot fetch user profile"),null;try{const n=await Ut()(`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 f.error("Failed to fetch Auth0 user:",r),r}}async getUserByEmail(e){const t=process.env.AUTH0_MANAGEMENT_TOKEN;if(!t)return f.warn("AUTH0_MANAGEMENT_TOKEN not set, cannot fetch user by email"),null;try{const n=await Ut()(`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 s=o[0];return{id:s.user_id,email:s.email,name:s.name,picture:s.picture,emailVerified:s.email_verified,roles:s.app_metadata?.roles||[],permissions:s.app_metadata?.permissions||[],createdAt:s.created_at?new Date(s.created_at):void 0,lastLoginAt:s.last_login?new Date(s.last_login):void 0,metadata:s.user_metadata}}catch(r){throw f.error("Failed to fetch Auth0 user by email:",r),r}}async healthCheck(){try{const t=await Ut()(`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)}}}}}}),BKt={};le(BKt,{ClerkProvider:()=>zKt});var zKt,v7r=C({"src/lib/auth/providers/clerk.ts"(){"use strict";_c(),Yi(),V(),Xn(),ed(),zKt=class extends Il{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=zx(e),f.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 lu(e,this.localKey);else{if(this.jwks||await this.initialize(),!this.jwks)return{valid:!1,error:"Clerk JWKS not initialized"};({payload:t}=await lu(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 Ut()("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,s=o?.email_addresses,i={id:n.user_id,email:s?.[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:i,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 Ut()(`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(f.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 Ut()(`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],s=o.email_addresses;return{id:o.id,email:s?.[0]?.email_address,name:o.first_name?`${o.first_name} ${o.last_name||""}`.trim():void 0,picture:o.image_url,emailVerified:s?.[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(f.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 Ut()("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)}}}}}}),jKt={};le(jKt,{FirebaseAuthProvider:()=>qKt});var qKt,_7r=C({"src/lib/auth/providers/firebase.ts"(){"use strict";_c(),Yi(),V(),Xn(),ed(),qKt=class extends Il{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=zx(e),f.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 lu(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 Ut()(`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 s=o[0],i=this.firebaseUserToAuthUser(s);return{valid:!0,payload:s,user:i,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{f.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?(f.warn("Direct user lookup by ID requires Firebase Admin SDK which is not supported in browser/edge environments"),null):(f.warn("Firebase API key required for user lookup"),null)}async healthCheck(){try{const t=await Ut()("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)}}}}}}),GKt={};le(GKt,{SupabaseAuthProvider:()=>HKt});var HKt,w7r=C({"src/lib/auth/providers/supabase.ts"(){"use strict";_c(),Yi(),V(),Xn(),ed(),HKt=class extends Il{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 i=new TextEncoder().encode(this.jwtSecret),{payload:a}=await lu(e,i);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 Ut()(`${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(),s=this.supabaseUserToAuthUser(o);return{valid:!0,payload:o,user:s,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 f.warn("Service role key required for user lookup"),null;try{const r=await Ut()(`${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(f.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 f.warn("Service role key required for user lookup by email"),null;try{const r=await Ut()(`${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(f.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 Ut()(`${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)}}}}}}),VKt={};le(VKt,{CognitoProvider:()=>WKt});var loe,WKt,T7r=C({"src/lib/auth/providers/CognitoProvider.ts"(){"use strict";ed(),V(),Yi(),_c(),loe=new Map,WKt=class extends Il{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,f.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),s={};for(const[i,a]of Object.entries(t))a!==void 0&&(s[i]=a);return{valid:!0,user:o,claims:s,expiresAt:t.exp?new Date(t.exp*1e3):void 0,issuer:t.iss,audience:t.aud}}catch(t){return f.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 f.warn("[CognitoProvider] Token missing kid in header"),!1;const s=(await this.getJWKS()).keys.find(l=>l.kid===n);if(!s)return f.warn(`[CognitoProvider] Key not found for kid: ${n}`),!1;const i=await noe(s,r.alg),a=this.config.tokenValidation?.clockTolerance??30;return await lu(e,i,{clockTolerance:a}),!0}catch(t){return f.error("[CognitoProvider] Signature verification error:",t),!1}}async getJWKS(){const e=loe.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 loe.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,s=e.picture??e["custom:picture"];let i=[];const a=e["cognito:groups"];a&&Array.isArray(a)&&(i=a),i.length===0&&this.rbacConfig.defaultRoles&&(i=this.rbacConfig.defaultRoles);const l=[];if(this.cognitoConfig.customAttributes)for(const d of this.cognitoConfig.customAttributes){const m=e[`custom:${d}`];m&&(m.includes(",")?l.push(...m.split(",").map(h=>h.trim())):l.push(m))}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:s,roles:i,permissions:l,emailVerified:e.email_verified,providerData:c}}async getUser(e){return f.debug("[CognitoProvider] getUser() is not implemented. Requires AWS SDK (@aws-sdk/client-cognito-identity-provider)."),null}}}}),KKt={};le(KKt,{KeycloakProvider:()=>JKt});var coe,JKt,b7r=C({"src/lib/auth/providers/KeycloakProvider.ts"(){"use strict";ed(),V(),Yi(),_c(),coe=new Map,JKt=class extends Il{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,f.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 s=this.extractKeycloakUser(t),i={};for(const[a,l]of Object.entries(t))l!==void 0&&(i[a]=l);return{valid:!0,user:s,claims:i,expiresAt:t.exp?new Date(t.exp*1e3):void 0,issuer:t.iss,audience:t.aud}}catch(t){return f.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 f.warn("[KeycloakProvider] Token missing kid in header"),!1;const s=(await this.getJWKS()).keys.find(l=>l.kid===n);if(!s)return f.warn(`[KeycloakProvider] Key not found for kid: ${n}`),!1;const i=await noe(s,r.alg),a=this.config.tokenValidation?.clockTolerance??30;return await lu(e,i,{clockTolerance:a}),!0}catch(t){return f.error("[KeycloakProvider] Signature verification error:",t),!1}}async getJWKS(){const e=coe.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 coe.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 s=[];const i=e.realm_access;i?.roles&&(s=[...i.roles]);const a=e.resource_access;if(a){const d=a[this.keycloakConfig.clientId]?.roles;d&&(s=[...s,...d.map(m=>`${this.keycloakConfig.clientId}:${m}`)]);for(const[m,h]of Object.entries(a))m!==this.keycloakConfig.clientId&&h.roles&&(s=[...s,...h.roles.map(g=>`${m}:${g}`)])}s.length===0&&this.rbacConfig.defaultRoles&&(s=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),i!==void 0&&(u.realm_access=i),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:s,permissions:l,emailVerified:e.email_verified,providerData:u}}async getUser(e){if(!this.keycloakConfig.clientSecret)return f.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 s=await o.json(),i=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??[];i.ok&&(a=(await i.json()).map(u=>u.name));const l={};for(const[c,u]of Object.entries(s))u!==void 0&&(l[c]=u);return{id:s.id,email:s.email,name:`${s.firstName??""} ${s.lastName??""}`.trim()||s.username,picture:void 0,roles:a,permissions:[],emailVerified:s.emailVerified,providerData:l,createdAt:s.createdTimestamp?new Date(s.createdTimestamp):void 0}}catch(t){return f.error(`[KeycloakProvider] Failed to get user ${e}:`,t),null}}}}}),YKt={};le(YKt,{BetterAuthProvider:()=>ZKt});var ZKt,E7r=C({"src/lib/auth/providers/betterAuth.ts"(){"use strict";Xn(),Yi(),ed(),_c(),ZKt=class extends Il{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 lu(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 Ut()(`${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 Ut()(`${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)}}}}}}),XKt={};le(XKt,{WorkOSProvider:()=>QKt});var QKt,S7r=C({"src/lib/auth/providers/workos.ts"(){"use strict";V(),Xn(),Yi(),ed(),_c(),QKt=class extends Il{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=zx(e),f.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 lu(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 Ut()("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 Ut()(`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 f.error("Failed to fetch WorkOS user:",t instanceof Error?t.message:String(t)),t}}async getUserByEmail(e){try{const r=await Ut()(`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 s=o[0];return{id:s.id,email:s.email,name:s.first_name&&s.last_name?`${s.first_name} ${s.last_name}`.trim():void 0,picture:s.profile_picture_url,emailVerified:s.email_verified,roles:[],permissions:[],createdAt:s.created_at?new Date(s.created_at):void 0,metadata:s}}catch(t){if(f.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 Ut()("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)}}}}}}),eJt={};le(eJt,{OAuth2Provider:()=>tJt});var tJt,C7r=C({"src/lib/auth/providers/oauth2.ts"(){"use strict";ed(),Xn(),V(),Yi(),_c(),tJt=class extends Il{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=zx(e),f.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 lu(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{f.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=Ut();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 s={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:s,tokenType:"oauth"}}catch(t){const r=t instanceof Error?t.message:String(t);return f.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=Ut(),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 s=await o.json();return{accessToken:s.access_token,refreshToken:s.refresh_token,idToken:s.id_token}}async healthCheck(){try{const e=Ut(),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)}}}}}}),rJt={};le(rJt,{JWTProvider:()=>nJt});var nJt,x7r=C({"src/lib/auth/providers/jwt.ts"(){"use strict";ed(),V(),Yi(),_c(),nJt=class extends Il{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),f.debug("JWT provider initialized with symmetric secret")):this.publicKey&&(this.keyObject=await ZHr(this.publicKey,this.algorithms[0]),f.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 lu(e,r,n);if(!o.sub)return{valid:!1,error:"JWT is missing required 'sub' claim: cannot identify user"};const s={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:s,expiresAt:o.exp?new Date(o.exp*1e3):void 0,tokenType:"jwt"}}catch(r){const n=r instanceof Error?r.message:String(r);f.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 MKt(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)}}}}}}),oJt={};le(oJt,{CustomAuthProvider:()=>sJt});var sJt,A7r=C({"src/lib/auth/providers/custom.ts"(){"use strict";V(),Yi(),_c(),sJt=class extends Il{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 f.error("Custom getUser failed:",t),null}return f.warn("Custom getUser function not provided"),null}async healthCheck(){return{healthy:!0,providerConnected:!0,sessionStorageHealthy:!0}}}}}),k7r,I7r,R7r,P7r,xL,iJt,uoe,M7r,doe,D7r,O7r,N7r,aJt=C({"node-stub:readline"(){k7r=globalThis.crypto,I7r=globalThis.ReadableStream||class{},R7r=globalThis.URL,P7r=globalThis.URLSearchParams,xL=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},xL.custom=Symbol.for("nodejs.util.inspect.custom"),xL.colors={},xL.styles={},iJt=globalThis.TextDecoder,uoe=globalThis.TextEncoder,M7r=globalThis.performance||{now:()=>Date.now()},doe=()=>({}),D7r=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),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new uoe().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((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new uoe().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 iJt().decode(this)}},O7r=globalThis.clearTimeout,N7r=globalThis.clearInterval}}),lJt={};le(lJt,{createClaudeCodeReader:()=>F7r});function cJt(){return Sr(Tu(),".claude","projects")}function L7r(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"modeled",unpricedRequests:0,unpricedModels:[]}}async function uJt(e,t){let r;try{r=await aP(e,{withFileTypes:!0})}catch{return}for(const n of r){const o=Sr(e,n.name);n.isDirectory()?await uJt(o,t):n.isFile()&&n.name.endsWith(".jsonl")&&t.push(o)}}function AL(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function $7r(e,t,r){const n=new Map,o=doe({input:sR(e,{encoding:"utf8"}),crlfDelay:1/0});try{for await(const s of o){if(!s||s.charCodeAt(0)!==123)continue;let i;try{i=JSON.parse(s)}catch{continue}const a=i;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:AL(l.input_tokens),output:AL(l.output_tokens),read:AL(l.cache_read_input_tokens),create:AL(l.cache_creation_input_tokens)},d=n.get(c);(!d||u.output>d.output)&&n.set(c,u)}}finally{o.close()}for(const s of n.values())t.requests+=1,t.inputTokens+=s.input,t.outputTokens+=s.output,t.cacheReadTokens+=s.read,t.cacheCreationTokens+=s.create,Db(poe,s.model)?t.costUsd+=Fa(poe,s.model,{input:s.input,output:s.output,total:s.input+s.output,cacheReadTokens:s.read,cacheCreationTokens:s.create}):(t.unpricedRequests+=1,r.add(s.model))}async function F7r(){return{descriptor:{id:kL,displayName:"Claude Code",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"modeled",requiresSqlite:!1},detect:async()=>{try{return(await Ou(cJt())).isDirectory()}catch{return!1}},scan:async e=>{const t=L7r(),r=[],n=new Set,o=[];await uJt(cJt(),o);const s=e?.sinceDays??dJt,i=Number.isFinite(s)&&s>0?Date.now()-s*864e5:void 0;let a=0;for(const l of o)try{if(i!==void 0&&(await Ou(l)).mtimeMs<i)continue;await $7r(l,t,n),a+=1}catch(c){r.push({cliId:kL,filePath:l,message:c instanceof Error?c.message:String(c)})}return t.unpricedModels=[...n].sort(),t.costUsd=Math.round(t.costUsd*1e6)/1e6,{cliId:kL,totals:t,filesScanned:a,errors:r}}}}var kL,dJt,poe,U7r=C({"src/lib/localUsage/claudeCodeReader.ts"(){"use strict";pn(),aJt(),ma(),Wl(),Nr(),Zl(),kL="claude-code",dJt=30,poe="anthropic"}}),pJt={};le(pJt,{createCodexReader:()=>j7r});function mJt(){return Sr(Tu(),".codex","sessions")}function B7r(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}async function hJt(e,t){let r;try{r=await aP(e,{withFileTypes:!0})}catch{return}for(const n of r){const o=Sr(e,n.name);n.isDirectory()?await hJt(o,t):n.isFile()&&n.name.endsWith(".jsonl")&&t.push(o)}}function IL(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function z7r(e){const t=doe({input:sR(e,{encoding:"utf8"}),crlfDelay:1/0});let r,n=-1,o,s=-1,i=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 m=d.payload.info?.total_token_usage;if(!m)continue;const h=IL(m.total_tokens);h>s&&(i+=1),s=h,h>n&&(n=h,o={input:IL(m.input_tokens),output:IL(m.output_tokens),cached:IL(m.cached_input_tokens)})}}finally{t.close()}return o?{model:r,billableEvents:i,...o}:null}async function j7r(){return{descriptor:{id:RL,displayName:"Codex",verified:!0,dedupStrategy:"session-dag",costConfidence:"unavailable",requiresSqlite:!1},detect:async()=>{try{return(await Ou(mJt())).isDirectory()}catch{return!1}},scan:async e=>{const t=B7r(),r=[],n=new Set,o=[];await hJt(mJt(),o);const s=e?.sinceDays??fJt,i=Number.isFinite(s)&&s>0?Date.now()-s*864e5:void 0;let a=0;for(const l of o)try{if(i!==void 0&&(await Ou(l)).mtimeMs<i)continue;const c=await z7r(l);if(a+=1,!c)continue;t.requests+=c.billableEvents,t.inputTokens+=Math.max(0,c.input-c.cached),t.cacheReadTokens+=c.cached,t.outputTokens+=c.output,c.model&&n.add(c.model)}catch(c){r.push({cliId:RL,filePath:l,message:c instanceof Error?c.message:String(c)})}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:RL,totals:t,filesScanned:a,errors:r}}}}var RL,fJt,q7r=C({"src/lib/localUsage/codexReader.ts"(){"use strict";pn(),aJt(),ma(),Wl(),Nr(),RL="codex",fJt=30}}),gJt={};le(gJt,{AsyncLocalStorage:()=>$Jt,Buffer:()=>IZt,Channel:()=>vZt,DatabaseSync:()=>kZt,Duplex:()=>UJt,EventEmitter:()=>LJt,Http2ServerRequest:()=>OZt,Http2ServerResponse:()=>NZt,Interface:()=>AZt,MIMEType:()=>zZt,PassThrough:()=>BJt,PerformanceObserver:()=>fZt,Readable:()=>hoe,ReadableStream:()=>zJt,Resolver:()=>mZt,TextDecoder:()=>yoe,TextEncoder:()=>qx,Transform:()=>FJt,URL:()=>eZt,URLSearchParams:()=>tZt,Worker:()=>bZt,Writable:()=>foe,access:()=>fYt,appendFile:()=>KJt,appendFileSync:()=>EJt,arch:()=>DYt,arrayBuffer:()=>LZt,basename:()=>IJt,builtinModules:()=>YYt,callbackify:()=>lZt,channel:()=>yZt,chmodSync:()=>WJt,clearInterval:()=>BZt,clearTimeout:()=>FZt,closeSync:()=>XJt,connect:()=>$Yt,constants:()=>RZt,copyFileSync:()=>YJt,cpSync:()=>SJt,cpus:()=>IYt,createConnection:()=>FYt,createGunzip:()=>HYt,createGzip:()=>VYt,createHash:()=>moe,createHmac:()=>_Jt,createInterface:()=>xZt,createReadStream:()=>lYt,createRequire:()=>JYt,createServer:()=>CJt,createWriteStream:()=>aYt,debug:()=>iZt,debuglog:()=>goe,default:()=>yJt,deflateSync:()=>BYt,deprecate:()=>aZt,deserialize:()=>TZt,dirname:()=>kJt,exec:()=>TYt,execFile:()=>EYt,execFileSync:()=>SYt,execSync:()=>bYt,existsSync:()=>GJt,extname:()=>RJt,fileURLToPath:()=>rZt,finished:()=>qJt,format:()=>QYt,freemem:()=>RYt,fstatSync:()=>QJt,get:()=>LYt,gunzip:()=>GYt,gunzipSync:()=>zYt,gzip:()=>qYt,gzipSync:()=>jYt,hasSubscribers:()=>_Zt,homedir:()=>xYt,hostname:()=>kYt,inflateSync:()=>UYt,inherits:()=>oZt,inspect:()=>jx,isAbsolute:()=>MJt,isBuiltin:()=>ZYt,isDeepStrictEqual:()=>cZt,isIP:()=>DZt,isIPv4:()=>MZt,isIPv6:()=>PZt,isMainThread:()=>EZt,join:()=>xJt,lookup:()=>pZt,mkdir:()=>dYt,mkdirSync:()=>eYt,monitorEventLoopDelay:()=>gZt,normalize:()=>NJt,ok:()=>WYt,open:()=>vYt,openSync:()=>ZJt,parentPort:()=>SZt,parse:()=>XYt,pathToFileURL:()=>nZt,performance:()=>hZt,pipeline:()=>jJt,platform:()=>CYt,posix:()=>OJt,promises:()=>vJt,promisify:()=>sZt,randomBytes:()=>wJt,randomUUID:()=>TJt,readFile:()=>cYt,readFileSync:()=>HJt,readdir:()=>mYt,readdirSync:()=>rYt,realpath:()=>_Yt,realpathSync:()=>JJt,relative:()=>PJt,release:()=>OYt,rename:()=>gYt,renameSync:()=>oYt,request:()=>NYt,resolve:()=>AJt,rm:()=>yYt,rmSync:()=>iYt,rmdirSync:()=>sYt,sep:()=>DJt,serialize:()=>wZt,setInterval:()=>UZt,setTimeout:()=>$Zt,spawn:()=>wYt,stat:()=>pYt,statSync:()=>tYt,strict:()=>KYt,tmpdir:()=>AYt,toUSVString:()=>uZt,totalmem:()=>PYt,type:()=>MYt,types:()=>dZt,unlink:()=>hYt,unlinkSync:()=>nYt,webcrypto:()=>bJt,workerData:()=>CZt,writeFile:()=>uYt,writeFileSync:()=>VJt});var Do,Wn,yJt,vJt,moe,_Jt,wJt,TJt,bJt,EJt,SJt,CJt,xJt,AJt,kJt,IJt,RJt,PJt,MJt,DJt,OJt,NJt,LJt,$Jt,hoe,foe,FJt,UJt,BJt,zJt,jJt,qJt,GJt,HJt,VJt,WJt,KJt,JJt,YJt,ZJt,XJt,QJt,eYt,tYt,rYt,nYt,oYt,sYt,iYt,aYt,lYt,cYt,uYt,dYt,pYt,mYt,hYt,fYt,gYt,yYt,vYt,_Yt,wYt,TYt,bYt,EYt,SYt,CYt,xYt,AYt,kYt,IYt,RYt,PYt,MYt,DYt,OYt,NYt,LYt,$Yt,FYt,UYt,BYt,zYt,jYt,qYt,GYt,HYt,VYt,WYt,KYt,JYt,YYt,ZYt,XYt,QYt,eZt,tZt,rZt,nZt,oZt,sZt,goe,iZt,jx,aZt,lZt,cZt,uZt,dZt,yoe,qx,pZt,mZt,hZt,fZt,gZt,yZt,vZt,_Zt,wZt,TZt,bZt,EZt,SZt,CZt,xZt,AZt,kZt,IZt,RZt,PZt,MZt,DZt,OZt,NZt,LZt,voe,$Zt,FZt,UZt,BZt,zZt,G7r=C({"node-stub:node:sqlite"(){Do=()=>{},Wn=async()=>{},yJt={},vJt={readFile:Wn,writeFile:Wn,mkdir:Wn,stat:Wn,readdir:Wn,unlink:Wn,access:Wn,rm:Wn,rename:Wn},moe=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new qx().encode(r):r),this},digest(r){let n=0;for(const s of t)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},_Jt=(e,t)=>moe(e),wJt=e=>new Uint8Array(e||32),TJt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),bJt=globalThis.crypto,EJt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},SJt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},CJt=()=>({listen:Do,close:Do,on:Do}),xJt=(...e)=>e.join("/"),AJt=(...e)=>e.join("/"),kJt=e=>e||"",IJt=e=>e?.split?.("/")?.pop?.()||"",RJt=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},PJt=(e,t)=>t||"",MJt=()=>!1,DJt="/",OJt={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},NJt=e=>e,LJt=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},$Jt=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},hoe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},foe=class{write(){return!0}end(){}on(){return this}destroy(){}},FJt=class{push(){}on(){return this}},UJt=class{on(){return this}},BJt=class{pipe(){return this}on(){return this}},zJt=globalThis.ReadableStream||class{},jJt=Do,qJt=Do,GJt=()=>!1,HJt=()=>"",VJt=Do,WJt=Do,KJt=Wn,JJt=e=>e,YJt=Do,ZJt=()=>0,XJt=Do,QJt=()=>({}),eYt=Do,tYt=()=>({}),rYt=()=>[],nYt=Do,oYt=Do,sYt=Do,iYt=Do,aYt=()=>new foe,lYt=()=>new hoe,cYt=Wn,uYt=Wn,dYt=Wn,pYt=Wn,mYt=Wn,hYt=Wn,fYt=Wn,gYt=Wn,yYt=Wn,vYt=async()=>({stat:Wn,readFile:Wn,close:Wn,read:Wn,write:Wn}),_Yt=async e=>e,wYt=()=>({on:Do,stdout:{on:Do},stderr:{on:Do},kill:Do}),TYt=(e,t)=>t?.(null,"",""),bYt=()=>"",EYt=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},SYt=()=>"",CYt="browser",xYt=()=>"/",AYt=()=>"/tmp",kYt=()=>"browser",IYt=()=>[{}],RYt=()=>0,PYt=()=>0,MYt=()=>"Browser",DYt=()=>"wasm",OYt=()=>"0",NYt=()=>({}),LYt=()=>({}),$Yt=()=>({}),FYt=()=>({}),UYt=()=>new Uint8Array,BYt=()=>new Uint8Array,zYt=()=>new Uint8Array,jYt=()=>new Uint8Array,qYt=(e,t)=>t?.(null,e),GYt=(e,t)=>t?.(null,e),HYt=()=>({}),VYt=()=>({}),WYt=Do,KYt={},JYt=()=>()=>({}),YYt=[],ZYt=()=>!1,XYt=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),QYt=()=>"",eZt=globalThis.URL,tZt=globalThis.URLSearchParams,rZt=e=>typeof e=="string"?e.replace("file://",""):e,nZt=e=>new globalThis.URL("file://"+e),oZt=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},sZt=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),goe=e=>{const t=(...r)=>{};return t.enabled=!1,t},iZt=goe,jx=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},jx.custom=Symbol.for("nodejs.util.inspect.custom"),jx.colors={},jx.styles={},aZt=e=>e,lZt=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},cZt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),uZt=e=>String(e),dZt={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},yoe=globalThis.TextDecoder,qx=globalThis.TextEncoder,pZt=(e,t)=>t?.(null,"127.0.0.1",4),mZt=class{},hZt=globalThis.performance||{now:()=>Date.now()},fZt=class{observe(){}disconnect(){}},gZt=()=>({enable:Do,disable:Do,percentile:()=>0}),yZt=()=>({}),vZt=class{},_Zt=()=>!1,wZt=()=>new Uint8Array,TZt=Do,bZt=class{},EZt=!0,SZt=null,CZt=null,xZt=()=>({}),AZt=class{},kZt=class{},IZt=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),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new qx().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((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new qx().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 yoe().decode(this)}},RZt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},PZt=()=>!1,MZt=()=>!1,DZt=()=>0,OZt=class{},NZt=class{},LZt=async()=>new ArrayBuffer(0),voe=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),$Zt=(...e)=>voe(globalThis.setTimeout(...e)),FZt=globalThis.clearTimeout,UZt=(...e)=>voe(globalThis.setInterval(...e)),BZt=globalThis.clearInterval,zZt=class{constructor(e){this.type=e}toString(){return this.type}}}}),jZt={};le(jZt,{createOpenCodeReader:()=>V7r});function qZt(){return Sr(Tu(),".local","share","opencode","opencode.db")}function H7r(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function PL(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function V7r(){return{descriptor:{id:Km,displayName:"OpenCode",verified:!0,dedupStrategy:"rowid-high-water-mark",costConfidence:"unavailable",requiresSqlite:!0},detect:async()=>{try{return(await Ou(qZt())).isFile()}catch{return!1}},scan:async e=>{const t=H7r(),r=[],n=new Set,o=qZt();let s;try{const c=await Promise.resolve().then(()=>(G7r(),gJt));typeof c=="object"&&c!==null&&"DatabaseSync"in c&&typeof c.DatabaseSync=="function"&&(s=c.DatabaseSync)}catch(c){return r.push({cliId:Km,filePath:o,message:`node:sqlite unavailable on this runtime: ${c instanceof Error?c.message:String(c)}`}),{cliId:Km,totals:t,filesScanned:0,errors:r}}if(!s)return r.push({cliId:Km,filePath:o,message:"node:sqlite did not expose a callable DatabaseSync \u2014 the experimental API has likely changed shape"}),{cliId:Km,totals:t,filesScanned:0,errors:r};const i=e?.sinceDays??GZt,a=Number.isFinite(i)&&i>0?Date.now()-i*864e5:0;let l;try{l=new s(o,{readOnly:!0});const c=l.prepare(`SELECT data FROM message WHERE time_created >= ${a}`).all();for(const u of c){if(typeof u.data!="string")continue;let d;try{d=JSON.parse(u.data)}catch{continue}const m=d,h=m.tokens;if(!h||m.role!=="assistant")continue;const g=PL(h.input),y=PL(h.output),v=PL(h.cache?.read),w=PL(h.cache?.write);g===0&&y===0&&v===0&&w===0||(t.requests+=1,t.inputTokens+=g,t.outputTokens+=y,t.cacheReadTokens+=v,t.cacheCreationTokens+=w,m.modelID&&n.add(m.modelID))}}catch(c){r.push({cliId:Km,filePath:o,message:c instanceof Error?c.message:String(c)})}finally{try{l?.close()}catch{}}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:Km,totals:t,filesScanned:t.requests>0||r.length===0?1:0,errors:r}}}}var Km,GZt,W7r=C({"src/lib/localUsage/openCodeReader.ts"(){"use strict";ma(),Wl(),Nr(),Km="opencode",GZt=30}});vc(),ra(),AA(),pn(),Nr(),$t(),V(),Ct();var{readFile:_oe,writeFile:HZt,readdir:K7r,mkdir:J7r,unlink:Y7r,access:Z7r}=vi,X7r=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:s="update",silent:i=!1}=t;r&&(await this.createBackup(s),i||f.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),i||f.info("\u2705 Configuration updated successfully")}catch(l){throw r&&(await this.restoreLatestBackup(),i||f.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=Sr(this.backupDir,r),o=await this.loadConfig(),s=this.generateConfigHash(o),i={reason:e,timestamp:Date.now(),version:o.configVersion||"unknown",originalPath:this.configPath,hash:s,size:JSON.stringify(o).length,createdBy:"NeuroLinkConfigManager"},a=`// NeuroLink Config Backup - ${e}
2216
+ `).filter(i=>i.trim());let o=null,s=null;for(const i of n){const a=i.trim();/^\d+[.):]\s*/.test(a)||/^Q[.:]?\s*/i.test(a)?(o&&r.push({question:o,...t&&s?{answer:s}:{}}),o=a.replace(/^\d+[.):]\s*/,"").replace(/^Q[.:]?\s*/i,""),s=null):/^A[.:]?\s*/i.test(a)&&o?s=a.replace(/^A[.:]?\s*/i,""):o&&!s?o+=" "+a:s&&(s+=" "+a)}return o&&r.push({question:o,...t&&s?{answer:s}:{}}),r}async callLLM(e,t){return(await(await Fr.createProvider(t.provider||this.provider,t.modelName||this.modelName)).generate({prompt:e,maxTokens:t.maxTokens||500,temperature:t.temperature||.3}))?.content||""}}}}),$Wt,Hne,Il,_c=C({"src/lib/auth/providers/BaseAuthProvider.ts"(){"use strict";$t(),Pn(),V(),Yi(),$Wt=xt,Hne=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 s of t){const i=this.sessions.get(s);if(i){if(i.expiresAt&&i.expiresAt.getTime()<r){o.push(s);continue}if(!i.isValid){o.push(s);continue}n.push(i)}}for(const s of o)this.sessions.delete(s),t.delete(s);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}},Il=class{config;sessionStorage;sessionConfig;rbacConfig;emitter=new Rn;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 Hne,f.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,s]of Object.entries(e.headers))if(o.toLowerCase()===r&&typeof s=="string"){n=s;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 s=await this.sessionStorage.getForUser(e.id);if(s.length>=this.sessionConfig.maxSessionsPerUser){const i=s.sort((a,l)=>a.createdAt.getTime()-l.createdAt.getTime())[0];i&&await this.sessionStorage.delete(i.id)}}const o={id:st(),user:e,accessToken:st(),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),f.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),f.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),f.debug(`[BaseAuthProvider] Revoked session ${e}`))}async revokeAllSessions(e){await this.sessionStorage.deleteAllForUser(e),f.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(s=>!n.has(s));t.requireAllRoles?o.length>0&&(r.authorized=!1,r.missingRoles=o,r.reason=`Missing required roles: ${o.join(", ")}`):t.roles.some(i=>n.has(i))||(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(s=>!this.hasPermission(n,s));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 s=r[o]??[];for(const i of s)t.has(i)||(t.add(i),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 s=r[o]??[];for(const i of s)t.add(i)}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",s=Array.isArray(e[r])?e[r]:this.rbacConfig.defaultRoles??[],i=Array.isArray(e[n])?e[n]:[];return{id:e[o]??"",email:e.email,name:e.name,picture:e.picture,roles:s,permissions:i,emailVerified:e.email_verified,providerData:e}}async getUser(e){return f.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(),f.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 s=(await this.getUserSessions(r.user.id)).find(i=>i.isValid&&(!i.expiresAt||i.expiresAt.getTime()>Date.now()))??await this.createSession(r.user,e);return{...e,user:r.user,session:s,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 FWt(...e){const t=e.reduce((o,{length:s})=>o+s,0),r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function k_(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 Ox,I_,UHr,Nx=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js"(){Ox=new TextEncoder,I_=new TextDecoder,UHr=2**32}});function BHr(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 UWt(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 BWt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js"(){}});function vL(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:I_.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=I_.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return UWt(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Vne(e){let t=e;return typeof t=="string"&&(t=Ox.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):BHr(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Lx=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js"(){Nx(),BWt()}});function zHr(e){return parseInt(e.name.slice(4),10)}function Wne(e,t){if(zHr(e.hash)!==t)throw lp(`SHA-${t}`,"algorithm.hash")}function jHr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function qHr(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function GHr(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Bg(e.algorithm,"HMAC"))throw lp("HMAC");Wne(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!Bg(e.algorithm,"RSASSA-PKCS1-v1_5"))throw lp("RSASSA-PKCS1-v1_5");Wne(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!Bg(e.algorithm,"RSA-PSS"))throw lp("RSA-PSS");Wne(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!Bg(e.algorithm,"Ed25519"))throw lp("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!Bg(e.algorithm,t))throw lp(t);break}case"ES256":case"ES384":case"ES512":{if(!Bg(e.algorithm,"ECDSA"))throw lp("ECDSA");const n=jHr(t);if(e.algorithm.namedCurve!==n)throw lp(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}qHr(e,r)}var lp,Bg,HHr=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js"(){lp=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),Bg=(e,t)=>e.name===t}});function zWt(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 jWt,Kne,qWt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js"(){jWt=(e,...t)=>zWt("Key must be ",e,...t),Kne=(e,t,...r)=>zWt(`Key for the ${e} algorithm must be `,t,...r)}}),Za,au,Jne,GWt,Rl,Mo,_L,Yne,Zne,HWt,VWt,WWt,Pl=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js"(){Za=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)}},au=class extends Za{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}},Jne=class extends Za{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}},GWt=class extends Za{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Rl=class extends Za{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Mo=class extends Za{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},_L=class extends Za{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},Yne=class extends Za{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Zne=class extends Za{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)}},HWt=class extends Za{[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)}},VWt=class extends Za{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}},WWt=class extends Za{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}}}),Xne,Qne,eoe,KWt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js"(){Xne=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Qne=e=>e?.[Symbol.toStringTag]==="KeyObject",eoe=e=>Xne(e)||Qne(e)}});function JWt(e,t){if(e)throw new TypeError(`${t} can only be called once`)}function YWt(e,t,r){try{return vL(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}var ZWt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js"(){Lx()}});function cp(e){if(!QWt(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 XWt(...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 s of o){if(r.has(s))return!1;r.add(s)}}return!0}var QWt,wL,eKt,tKt,rKt,up=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js"(){QWt=e=>typeof e=="object"&&e!==null,wL=e=>cp(e)&&typeof e.kty=="string",eKt=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),tKt=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,rKt=e=>e.kty==="oct"&&typeof e.k=="string"}});function nKt(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 oKt(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 Rl(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function sKt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(jWt(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return GHr(t,e,r),t}async function VHr(e,t,r){const n=await sKt(e,t,"sign");nKt(e,n);const o=await crypto.subtle.sign(oKt(e,n.algorithm),n,r);return new Uint8Array(o)}async function WHr(e,t,r,n){const o=await sKt(e,t,"verify");nKt(e,o);const s=oKt(e,o.algorithm);try{return await crypto.subtle.verify(s,o,r,n)}catch{return!1}}var iKt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js"(){Pl(),HHr(),qWt()}});function KHr(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 Rl($x)}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 Rl($x)}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 Rl($x)}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 Rl($x)}break}default:throw new Rl('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function TL(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=KHr(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 $x,aKt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js"(){Pl(),$x='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'}});async function lKt(e,t){if(e instanceof Uint8Array||Xne(e))return e;if(Qne(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return cKt(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return toe(e,r,t)}if(wL(e))return e.k?vL(e.k):toe(e,e,t,!0);throw new Error("unreachable")}var zg,R_,toe,cKt,uKt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js"(){up(),Lx(),aKt(),KWt(),zg="given KeyObject instance cannot be used for this algorithm",toe=async(e,t,r,n=!1)=>{R_||=new WeakMap;let o=R_.get(e);if(o?.[r])return o[r];const s=await TL({...t,alg:r});return n&&Object.freeze(e),o?o[r]=s:R_.set(e,{[r]:s}),s},cKt=(e,t)=>{R_||=new WeakMap;let r=R_.get(e);if(r?.[t])return r[t];const n=e.type==="public",o=!!n;let s;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(zg)}s=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(zg);s=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(zg);s=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let i;switch(t){case"RSA-OAEP":i="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":i="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":i="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":i="SHA-512";break;default:throw new TypeError(zg)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:i},o,n?["encrypt"]:["decrypt"]);s=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},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(zg);const l={ES256:"P-256",ES384:"P-384",ES512:"P-521"};l[t]&&a===l[t]&&(s=e.toCryptoKey({name:"ECDSA",namedCurve:a},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(s=e.toCryptoKey({name:"ECDH",namedCurve:a},o,n?[]:["deriveBits"]))}if(!s)throw new TypeError(zg);return r?r[t]=s:R_.set(e,{[t]:s}),s}}});function JHr(e){Ux(e,48,"Invalid SPKI structure"),Fx(e),Ux(e,48,"Expected algorithm identifier");const t=Fx(e);return{algIdStart:e.pos,algIdLength:t}}var bL,dKt,Fx,Ux,roe,pKt,mKt,hKt,fKt,gKt,YHr=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/asn1.js"(){BWt(),Pl(),bL=(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},dKt=e=>({data:e,pos:0}),Fx=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},Ux=(e,t,r)=>{if(e.data[e.pos++]!==t)throw new Error(r)},roe=(e,t)=>{const r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},pKt=e=>{Ux(e,6,"Expected algorithm OID");const t=Fx(e);return roe(e,t)},mKt=e=>{const t=pKt(e);if(bL(t,[43,101,110]))return"X25519";if(!bL(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");Ux(e,6,"Expected curve OID");const r=Fx(e),n=roe(e,r);for(const{name:o,oid:s}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(bL(n,s))return o;throw new Error("Unsupported named curve")},hKt=async(e,t,r,n)=>{let o,s;const i=e==="spki",a=()=>i?["verify"]:["sign"],l=()=>i?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},s=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}`},s=l();break;case"ES256":case"ES384":case"ES512":{o={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},s=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 Rl("Invalid or unsupported key format")}s=i?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":o={name:"Ed25519"},s=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":o={name:r},s=a();break;default:throw new Rl('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,o,n?.extractable??!!i,s)},fKt=(e,t)=>UWt(e.replace(t,"")),gKt=(e,t,r)=>{const n=fKt(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);let o=r;return t?.startsWith?.("ECDH-ES")&&(o||={},o.getNamedCurve=s=>{const i=dKt(s);return JHr(i),mKt(i)}),hKt("spki",n,t,o)}}});async function ZHr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return gKt(e,t,r)}async function noe(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 vL(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new Rl('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return TL({...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 TL({...e,ext:n})}case"EC":case"OKP":return TL({...e,alg:t,ext:n});default:throw new Rl('Unsupported "kty" (Key Type) Parameter value')}}var yKt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js"(){Lx(),YHr(),aKt(),Pl(),up()}});function vKt(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(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(const i of n.crit){if(!s.has(i))throw new Rl(`Extension Header Parameter "${i}" is not recognized`);if(o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var _Kt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js"(){Pl()}});function XHr(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 QHr=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js"(){}});function wKt(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":TKt(e,t,r);break;default:bKt(e,t,r)}}var jg,EL,TKt,bKt,EKt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js"(){qWt(),KWt(),up(),jg=e=>e?.[Symbol.toStringTag],EL=(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},TKt=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(wL(t)){if(rKt(t)&&EL(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(!eoe(t))throw new TypeError(Kne(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${jg(t)} instances for symmetric algorithms must be of type "secret"`)}},bKt=(e,t,r)=>{if(wL(t))switch(r){case"decrypt":case"sign":if(eKt(t)&&EL(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(tKt(t)&&EL(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!eoe(t))throw new TypeError(Kne(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${jg(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${jg(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${jg(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${jg(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${jg(t)} instances for asymmetric algorithm encryption must be of type "public"`)}}}});async function e7r(e,t,r){if(!cp(e))throw new Mo("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new Mo('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new Mo("JWS Protected Header incorrect type");if(e.payload===void 0)throw new Mo("JWS Payload missing");if(typeof e.signature!="string")throw new Mo("JWS Signature missing or incorrect type");if(e.header!==void 0&&!cp(e.header))throw new Mo("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const v=vL(e.protected);n=JSON.parse(I_.decode(v))}catch{throw new Mo("JWS Protected Header is invalid")}if(!XWt(n,e.header))throw new Mo("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header},s=vKt(Mo,new Map([["b64",!0]]),r?.crit,n,o);let i=!0;if(s.has("b64")&&(i=n.b64,typeof i!="boolean"))throw new Mo('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if(typeof a!="string"||!a)throw new Mo('JWS "alg" (Algorithm) Header Parameter missing or invalid');const l=r&&XHr("algorithms",r.algorithms);if(l&&!l.has(a))throw new GWt('"alg" (Algorithm) Header Parameter value not allowed');if(i){if(typeof e.payload!="string")throw new Mo("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new Mo("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof t=="function"&&(t=await t(n,e),c=!0),wKt(a,t,"verify");const u=FWt(e.protected!==void 0?k_(e.protected):new Uint8Array,k_("."),typeof e.payload=="string"?i?k_(e.payload):Ox.encode(e.payload):e.payload),d=YWt(e.signature,"signature",Mo),m=await lKt(t,a);if(!await WHr(a,m,d,u))throw new WWt;let g;i?g=YWt(e.payload,"payload",Mo):typeof e.payload=="string"?g=Ox.encode(e.payload):g=e.payload;const y={payload:g};return e.protected!==void 0&&(y.protectedHeader=n),e.header!==void 0&&(y.unprotectedHeader=e.header),c?{...y,key:m}:y}var t7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js"(){Lx(),iKt(),Pl(),Nx(),ZWt(),up(),up(),EKt(),_Kt(),QHr(),uKt()}});async function r7r(e,t,r){if(e instanceof Uint8Array&&(e=I_.decode(e)),typeof e!="string")throw new Mo("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:s,length:i}=e.split(".");if(i!==3)throw new Mo("Invalid Compact JWS");const a=await e7r({payload:o,protected:n,signature:s},t,r),l={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...l,key:a.key}:l}var n7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js"(){t7r(),Pl(),Nx()}});function Bx(e){const t=xKt.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*ooe);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*soe);break;case"day":case"days":case"d":o=Math.round(r*SL);break;case"week":case"weeks":case"w":o=Math.round(r*SKt);break;default:o=Math.round(r*CKt);break}return t[1]==="-"||t[4]==="ago"?-o:o}function qg(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function o7r(e,t,r={}){let n;try{n=JSON.parse(I_.decode(t))}catch{}if(!cp(n))throw new _L("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&(typeof e.typ!="string"||ioe(e.typ)!==ioe(o)))throw new au('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:s=[],issuer:i,subject:a,audience:l,maxTokenAge:c}=r,u=[...s];c!==void 0&&u.push("iat"),l!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),i!==void 0&&u.push("iss");for(const g of new Set(u.reverse()))if(!(g in n))throw new au(`missing required "${g}" claim`,n,g,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new au('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new au('unexpected "sub" claim value',n,"sub","check_failed");if(l&&!AKt(n.aud,typeof l=="string"?[l]:l))throw new au('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=Bx(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,h=dp(m||new Date);if((n.iat!==void 0||c)&&typeof n.iat!="number")throw new au('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new au('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>h+d)throw new au('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new au('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=h-d)throw new Jne('"exp" claim timestamp check failed',n,"exp","check_failed")}if(c){const g=h-n.iat,y=typeof c=="number"?c:Bx(c);if(g-d>y)throw new Jne('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(g<0-d)throw new au('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var dp,ooe,soe,SL,SKt,CKt,xKt,ioe,AKt,kKt,IKt=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js"(){Pl(),Nx(),up(),dp=e=>Math.floor(e.getTime()/1e3),ooe=60,soe=ooe*60,SL=soe*24,SKt=SL*7,CKt=SL*365.25,xKt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ioe=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,AKt=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,kKt=class{#e;constructor(e){if(!cp(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return Ox.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=qg("setNotBefore",e):e instanceof Date?this.#e.nbf=qg("setNotBefore",dp(e)):this.#e.nbf=dp(new Date)+Bx(e)}set exp(e){typeof e=="number"?this.#e.exp=qg("setExpirationTime",e):e instanceof Date?this.#e.exp=qg("setExpirationTime",dp(e)):this.#e.exp=dp(new Date)+Bx(e)}set iat(e){e===void 0?this.#e.iat=dp(new Date):e instanceof Date?this.#e.iat=qg("setIssuedAt",dp(e)):typeof e=="string"?this.#e.iat=qg("setIssuedAt",dp(new Date)+Bx(e)):this.#e.iat=qg("setIssuedAt",e)}}}});async function lu(e,t,r){const n=await r7r(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new _L("JWTs MUST NOT use unencoded payload");const s={payload:o7r(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...s,key:n.key}:s}var s7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js"(){n7r(),IKt(),Pl()}}),RKt,i7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js"(){Lx(),iKt(),up(),Pl(),Nx(),EKt(),_Kt(),uKt(),ZWt(),RKt=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 JWt(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return JWt(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,t){if(!this.#t&&!this.#r)throw new Mo("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!XWt(this.#t,this.#r))throw new Mo("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this.#t,...this.#r},n=vKt(Mo,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 Mo('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if(typeof s!="string"||!s)throw new Mo('JWS "alg" (Algorithm) Header Parameter missing or invalid');wKt(s,e,"sign");let i,a;o?(i=Vne(this.#e),a=k_(i)):(a=this.#e,i="");let l,c;this.#t?(l=Vne(JSON.stringify(this.#t)),c=k_(l)):(l="",c=new Uint8Array);const u=FWt(c,k_("."),a),d=await lKt(e,s),m=await VHr(s,d,u),h={signature:Vne(m),payload:i};return this.#r&&(h.header=this.#r),this.#t&&(h.protected=l),h}}}}),PKt,a7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js"(){i7r(),PKt=class{#e;constructor(e){this.#e=new RKt(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}`}}}}),MKt,l7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js"(){a7r(),Pl(),IKt(),MKt=class{#e;#t;constructor(e={}){this.#t=new kKt(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 PKt(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new _L("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}}});function c7r(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 Rl('Unsupported "alg" value for a JSON Web Key Set')}}function u7r(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(d7r)}function d7r(e){return cp(e)}async function DKt(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){const o=await noe({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new Yne("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function OKt(e){const t=new NKt(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 NKt,p7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js"(){yKt(),Pl(),up(),NKt=class{#e;#t=new WeakMap;constructor(e){if(!u7r(e))throw new Yne("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=c7r(r),s=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:i,length:a}=s;if(a===0)throw new Zne;if(a!==1){const l=new HWt,c=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(const u of s)try{yield await DKt(c,u,r)}catch{}},l}return DKt(this.#t,i,r)}}}});function m7r(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function h7r(e,t,r,n=fetch){const o=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(s=>{throw s.name==="TimeoutError"?new VWt:s});if(o.status!==200)throw new Za("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new Za("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function f7r(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 zx(e,t){const r=new $Kt(e,t),n=async(o,s)=>r.getKey(o,s);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 aoe,LKt,CL,$Kt,g7r=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js"(){Pl(),p7r(),up(),(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(aoe="jose/v6.2.2"),LKt=Symbol(),CL=Symbol(),$Kt=class{#e;#t;#r;#n;#o;#s;#i;#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.#i=new Headers(t?.headers),aoe&&!this.#i.has("User-Agent")&&this.#i.set("User-Agent",aoe),this.#i.has("accept")||(this.#i.set("accept","application/json"),this.#i.append("accept","application/jwk-set+json")),this.#c=t?.[LKt],t?.[CL]!==void 0&&(this.#l=t?.[CL],f7r(t?.[CL],this.#n)&&(this.#o=this.#l.uat,this.#a=OKt(this.#l.jwks)))}pendingFetch(){return!!this.#s}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 Zne&&this.coolingDown()===!1)return await this.reload(),this.#a(e,t);throw r}}async reload(){this.#s&&m7r()&&(this.#s=void 0),this.#s||=h7r(this.#e.href,this.#i,AbortSignal.timeout(this.#t),this.#c).then(e=>{this.#a=OKt(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#o=Date.now(),this.#s=void 0}).catch(e=>{throw this.#s=void 0,e}),await this.#s}}}}),ed=C({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js"(){s7r(),l7r(),g7r(),yKt()}}),FKt={};le(FKt,{Auth0Provider:()=>UKt});var UKt,y7r=C({"src/lib/auth/providers/auth0.ts"(){"use strict";_c(),Yi(),V(),Xn(),ed(),UKt=class extends Il{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=zx(e),f.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 lu(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",s=this.permissionsNamespace??"permissions",i=r[o]||n.roles||[],a=r[s]||n.permissions||[],l={id:n.sub,email:n.email,name:n.name,picture:n.picture,emailVerified:n.email_verified,roles:i,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 f.warn("Auth0 token validation failed:",n),{valid:!1,error:n}}}async getUser(e){const t=process.env.AUTH0_MANAGEMENT_TOKEN;if(!t)return f.warn("AUTH0_MANAGEMENT_TOKEN not set, cannot fetch user profile"),null;try{const n=await Ut()(`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 f.error("Failed to fetch Auth0 user:",r),r}}async getUserByEmail(e){const t=process.env.AUTH0_MANAGEMENT_TOKEN;if(!t)return f.warn("AUTH0_MANAGEMENT_TOKEN not set, cannot fetch user by email"),null;try{const n=await Ut()(`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 s=o[0];return{id:s.user_id,email:s.email,name:s.name,picture:s.picture,emailVerified:s.email_verified,roles:s.app_metadata?.roles||[],permissions:s.app_metadata?.permissions||[],createdAt:s.created_at?new Date(s.created_at):void 0,lastLoginAt:s.last_login?new Date(s.last_login):void 0,metadata:s.user_metadata}}catch(r){throw f.error("Failed to fetch Auth0 user by email:",r),r}}async healthCheck(){try{const t=await Ut()(`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)}}}}}}),BKt={};le(BKt,{ClerkProvider:()=>zKt});var zKt,v7r=C({"src/lib/auth/providers/clerk.ts"(){"use strict";_c(),Yi(),V(),Xn(),ed(),zKt=class extends Il{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=zx(e),f.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 lu(e,this.localKey);else{if(this.jwks||await this.initialize(),!this.jwks)return{valid:!1,error:"Clerk JWKS not initialized"};({payload:t}=await lu(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 Ut()("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,s=o?.email_addresses,i={id:n.user_id,email:s?.[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:i,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 Ut()(`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(f.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 Ut()(`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],s=o.email_addresses;return{id:o.id,email:s?.[0]?.email_address,name:o.first_name?`${o.first_name} ${o.last_name||""}`.trim():void 0,picture:o.image_url,emailVerified:s?.[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(f.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 Ut()("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)}}}}}}),jKt={};le(jKt,{FirebaseAuthProvider:()=>qKt});var qKt,_7r=C({"src/lib/auth/providers/firebase.ts"(){"use strict";_c(),Yi(),V(),Xn(),ed(),qKt=class extends Il{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=zx(e),f.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 lu(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 Ut()(`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 s=o[0],i=this.firebaseUserToAuthUser(s);return{valid:!0,payload:s,user:i,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{f.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?(f.warn("Direct user lookup by ID requires Firebase Admin SDK which is not supported in browser/edge environments"),null):(f.warn("Firebase API key required for user lookup"),null)}async healthCheck(){try{const t=await Ut()("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)}}}}}}),GKt={};le(GKt,{SupabaseAuthProvider:()=>HKt});var HKt,w7r=C({"src/lib/auth/providers/supabase.ts"(){"use strict";_c(),Yi(),V(),Xn(),ed(),HKt=class extends Il{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 i=new TextEncoder().encode(this.jwtSecret),{payload:a}=await lu(e,i);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 Ut()(`${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(),s=this.supabaseUserToAuthUser(o);return{valid:!0,payload:o,user:s,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 f.warn("Service role key required for user lookup"),null;try{const r=await Ut()(`${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(f.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 f.warn("Service role key required for user lookup by email"),null;try{const r=await Ut()(`${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(f.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 Ut()(`${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)}}}}}}),VKt={};le(VKt,{CognitoProvider:()=>WKt});var loe,WKt,T7r=C({"src/lib/auth/providers/CognitoProvider.ts"(){"use strict";ed(),V(),Yi(),_c(),loe=new Map,WKt=class extends Il{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,f.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),s={};for(const[i,a]of Object.entries(t))a!==void 0&&(s[i]=a);return{valid:!0,user:o,claims:s,expiresAt:t.exp?new Date(t.exp*1e3):void 0,issuer:t.iss,audience:t.aud}}catch(t){return f.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 f.warn("[CognitoProvider] Token missing kid in header"),!1;const s=(await this.getJWKS()).keys.find(l=>l.kid===n);if(!s)return f.warn(`[CognitoProvider] Key not found for kid: ${n}`),!1;const i=await noe(s,r.alg),a=this.config.tokenValidation?.clockTolerance??30;return await lu(e,i,{clockTolerance:a}),!0}catch(t){return f.error("[CognitoProvider] Signature verification error:",t),!1}}async getJWKS(){const e=loe.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 loe.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,s=e.picture??e["custom:picture"];let i=[];const a=e["cognito:groups"];a&&Array.isArray(a)&&(i=a),i.length===0&&this.rbacConfig.defaultRoles&&(i=this.rbacConfig.defaultRoles);const l=[];if(this.cognitoConfig.customAttributes)for(const d of this.cognitoConfig.customAttributes){const m=e[`custom:${d}`];m&&(m.includes(",")?l.push(...m.split(",").map(h=>h.trim())):l.push(m))}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:s,roles:i,permissions:l,emailVerified:e.email_verified,providerData:c}}async getUser(e){return f.debug("[CognitoProvider] getUser() is not implemented. Requires AWS SDK (@aws-sdk/client-cognito-identity-provider)."),null}}}}),KKt={};le(KKt,{KeycloakProvider:()=>JKt});var coe,JKt,b7r=C({"src/lib/auth/providers/KeycloakProvider.ts"(){"use strict";ed(),V(),Yi(),_c(),coe=new Map,JKt=class extends Il{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,f.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 s=this.extractKeycloakUser(t),i={};for(const[a,l]of Object.entries(t))l!==void 0&&(i[a]=l);return{valid:!0,user:s,claims:i,expiresAt:t.exp?new Date(t.exp*1e3):void 0,issuer:t.iss,audience:t.aud}}catch(t){return f.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 f.warn("[KeycloakProvider] Token missing kid in header"),!1;const s=(await this.getJWKS()).keys.find(l=>l.kid===n);if(!s)return f.warn(`[KeycloakProvider] Key not found for kid: ${n}`),!1;const i=await noe(s,r.alg),a=this.config.tokenValidation?.clockTolerance??30;return await lu(e,i,{clockTolerance:a}),!0}catch(t){return f.error("[KeycloakProvider] Signature verification error:",t),!1}}async getJWKS(){const e=coe.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 coe.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 s=[];const i=e.realm_access;i?.roles&&(s=[...i.roles]);const a=e.resource_access;if(a){const d=a[this.keycloakConfig.clientId]?.roles;d&&(s=[...s,...d.map(m=>`${this.keycloakConfig.clientId}:${m}`)]);for(const[m,h]of Object.entries(a))m!==this.keycloakConfig.clientId&&h.roles&&(s=[...s,...h.roles.map(g=>`${m}:${g}`)])}s.length===0&&this.rbacConfig.defaultRoles&&(s=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),i!==void 0&&(u.realm_access=i),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:s,permissions:l,emailVerified:e.email_verified,providerData:u}}async getUser(e){if(!this.keycloakConfig.clientSecret)return f.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 s=await o.json(),i=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??[];i.ok&&(a=(await i.json()).map(u=>u.name));const l={};for(const[c,u]of Object.entries(s))u!==void 0&&(l[c]=u);return{id:s.id,email:s.email,name:`${s.firstName??""} ${s.lastName??""}`.trim()||s.username,picture:void 0,roles:a,permissions:[],emailVerified:s.emailVerified,providerData:l,createdAt:s.createdTimestamp?new Date(s.createdTimestamp):void 0}}catch(t){return f.error(`[KeycloakProvider] Failed to get user ${e}:`,t),null}}}}}),YKt={};le(YKt,{BetterAuthProvider:()=>ZKt});var ZKt,E7r=C({"src/lib/auth/providers/betterAuth.ts"(){"use strict";Xn(),Yi(),ed(),_c(),ZKt=class extends Il{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 lu(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 Ut()(`${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 Ut()(`${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)}}}}}}),XKt={};le(XKt,{WorkOSProvider:()=>QKt});var QKt,S7r=C({"src/lib/auth/providers/workos.ts"(){"use strict";V(),Xn(),Yi(),ed(),_c(),QKt=class extends Il{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=zx(e),f.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 lu(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 Ut()("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 Ut()(`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 f.error("Failed to fetch WorkOS user:",t instanceof Error?t.message:String(t)),t}}async getUserByEmail(e){try{const r=await Ut()(`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 s=o[0];return{id:s.id,email:s.email,name:s.first_name&&s.last_name?`${s.first_name} ${s.last_name}`.trim():void 0,picture:s.profile_picture_url,emailVerified:s.email_verified,roles:[],permissions:[],createdAt:s.created_at?new Date(s.created_at):void 0,metadata:s}}catch(t){if(f.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 Ut()("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)}}}}}}),eJt={};le(eJt,{OAuth2Provider:()=>tJt});var tJt,C7r=C({"src/lib/auth/providers/oauth2.ts"(){"use strict";ed(),Xn(),V(),Yi(),_c(),tJt=class extends Il{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=zx(e),f.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 lu(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{f.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=Ut();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 s={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:s,tokenType:"oauth"}}catch(t){const r=t instanceof Error?t.message:String(t);return f.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=Ut(),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 s=await o.json();return{accessToken:s.access_token,refreshToken:s.refresh_token,idToken:s.id_token}}async healthCheck(){try{const e=Ut(),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)}}}}}}),rJt={};le(rJt,{JWTProvider:()=>nJt});var nJt,x7r=C({"src/lib/auth/providers/jwt.ts"(){"use strict";ed(),V(),Yi(),_c(),nJt=class extends Il{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),f.debug("JWT provider initialized with symmetric secret")):this.publicKey&&(this.keyObject=await ZHr(this.publicKey,this.algorithms[0]),f.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 lu(e,r,n);if(!o.sub)return{valid:!1,error:"JWT is missing required 'sub' claim: cannot identify user"};const s={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:s,expiresAt:o.exp?new Date(o.exp*1e3):void 0,tokenType:"jwt"}}catch(r){const n=r instanceof Error?r.message:String(r);f.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 MKt(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)}}}}}}),oJt={};le(oJt,{CustomAuthProvider:()=>sJt});var sJt,A7r=C({"src/lib/auth/providers/custom.ts"(){"use strict";V(),Yi(),_c(),sJt=class extends Il{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 f.error("Custom getUser failed:",t),null}return f.warn("Custom getUser function not provided"),null}async healthCheck(){return{healthy:!0,providerConnected:!0,sessionStorageHealthy:!0}}}}}),k7r,I7r,R7r,P7r,xL,iJt,uoe,M7r,doe,D7r,O7r,N7r,aJt=C({"node-stub:readline"(){k7r=globalThis.crypto,I7r=globalThis.ReadableStream||class{},R7r=globalThis.URL,P7r=globalThis.URLSearchParams,xL=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},xL.custom=Symbol.for("nodejs.util.inspect.custom"),xL.colors={},xL.styles={},iJt=globalThis.TextDecoder,uoe=globalThis.TextEncoder,M7r=globalThis.performance||{now:()=>Date.now()},doe=()=>({}),D7r=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),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new uoe().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((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new uoe().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 iJt().decode(this)}},O7r=globalThis.clearTimeout,N7r=globalThis.clearInterval}}),lJt={};le(lJt,{createClaudeCodeReader:()=>F7r});function cJt(){return Sr(Tu(),".claude","projects")}function L7r(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"modeled",unpricedRequests:0,unpricedModels:[]}}async function uJt(e,t){let r;try{r=await aP(e,{withFileTypes:!0})}catch{return}for(const n of r){const o=Sr(e,n.name);n.isDirectory()?await uJt(o,t):n.isFile()&&n.name.endsWith(".jsonl")&&t.push(o)}}function AL(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function $7r(e,t,r){const n=new Map,o=doe({input:sR(e,{encoding:"utf8"}),crlfDelay:1/0});try{for await(const s of o){if(!s||s.charCodeAt(0)!==123)continue;let i;try{i=JSON.parse(s)}catch{continue}const a=i;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:AL(l.input_tokens),output:AL(l.output_tokens),read:AL(l.cache_read_input_tokens),create:AL(l.cache_creation_input_tokens)},d=n.get(c);(!d||u.output>d.output)&&n.set(c,u)}}finally{o.close()}for(const s of n.values())t.requests+=1,t.inputTokens+=s.input,t.outputTokens+=s.output,t.cacheReadTokens+=s.read,t.cacheCreationTokens+=s.create,Db(poe,s.model)?t.costUsd+=Fa(poe,s.model,{input:s.input,output:s.output,total:s.input+s.output,cacheReadTokens:s.read,cacheCreationTokens:s.create}):(t.unpricedRequests+=1,r.add(s.model))}async function F7r(){return{descriptor:{id:kL,displayName:"Claude Code",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"modeled",requiresSqlite:!1},detect:async()=>{try{return(await Ou(cJt())).isDirectory()}catch{return!1}},scan:async e=>{const t=L7r(),r=[],n=new Set,o=[];await uJt(cJt(),o);const s=e?.sinceDays??dJt,i=Number.isNaN(s)?0:s,a=i===1/0?void 0:Date.now()-Math.max(0,i)*864e5;let l=0;for(const c of o)try{if(a!==void 0&&(await Ou(c)).mtimeMs<a)continue;await $7r(c,t,n),l+=1}catch(u){r.push({cliId:kL,filePath:c,message:u instanceof Error?u.message:String(u)})}return t.unpricedModels=[...n].sort(),t.costUsd=Math.round(t.costUsd*1e6)/1e6,{cliId:kL,totals:t,filesScanned:l,errors:r}}}}var kL,dJt,poe,U7r=C({"src/lib/localUsage/claudeCodeReader.ts"(){"use strict";pn(),aJt(),ma(),Wl(),Nr(),Zl(),kL="claude-code",dJt=30,poe="anthropic"}}),pJt={};le(pJt,{createCodexReader:()=>j7r});function mJt(){return Sr(Tu(),".codex","sessions")}function B7r(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}async function hJt(e,t){let r;try{r=await aP(e,{withFileTypes:!0})}catch{return}for(const n of r){const o=Sr(e,n.name);n.isDirectory()?await hJt(o,t):n.isFile()&&n.name.endsWith(".jsonl")&&t.push(o)}}function IL(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function z7r(e){const t=doe({input:sR(e,{encoding:"utf8"}),crlfDelay:1/0});let r,n=-1,o,s=-1,i=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 m=d.payload.info?.total_token_usage;if(!m)continue;const h=IL(m.total_tokens);h>s&&(i+=1),s=h,h>n&&(n=h,o={input:IL(m.input_tokens),output:IL(m.output_tokens),cached:IL(m.cached_input_tokens)})}}finally{t.close()}return o?{model:r,billableEvents:i,...o}:null}async function j7r(){return{descriptor:{id:RL,displayName:"Codex",verified:!0,dedupStrategy:"session-dag",costConfidence:"unavailable",requiresSqlite:!1},detect:async()=>{try{return(await Ou(mJt())).isDirectory()}catch{return!1}},scan:async e=>{const t=B7r(),r=[],n=new Set,o=[];await hJt(mJt(),o);const s=e?.sinceDays??fJt,i=Number.isNaN(s)?0:s,a=i===1/0?void 0:Date.now()-Math.max(0,i)*864e5;let l=0;for(const c of o)try{if(a!==void 0&&(await Ou(c)).mtimeMs<a)continue;const u=await z7r(c);if(l+=1,!u)continue;t.requests+=u.billableEvents,t.inputTokens+=Math.max(0,u.input-u.cached),t.cacheReadTokens+=u.cached,t.outputTokens+=u.output,u.model&&n.add(u.model)}catch(u){r.push({cliId:RL,filePath:c,message:u instanceof Error?u.message:String(u)})}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:RL,totals:t,filesScanned:l,errors:r}}}}var RL,fJt,q7r=C({"src/lib/localUsage/codexReader.ts"(){"use strict";pn(),aJt(),ma(),Wl(),Nr(),RL="codex",fJt=30}}),gJt={};le(gJt,{AsyncLocalStorage:()=>$Jt,Buffer:()=>IZt,Channel:()=>vZt,DatabaseSync:()=>kZt,Duplex:()=>UJt,EventEmitter:()=>LJt,Http2ServerRequest:()=>OZt,Http2ServerResponse:()=>NZt,Interface:()=>AZt,MIMEType:()=>zZt,PassThrough:()=>BJt,PerformanceObserver:()=>fZt,Readable:()=>hoe,ReadableStream:()=>zJt,Resolver:()=>mZt,TextDecoder:()=>yoe,TextEncoder:()=>qx,Transform:()=>FJt,URL:()=>eZt,URLSearchParams:()=>tZt,Worker:()=>bZt,Writable:()=>foe,access:()=>fYt,appendFile:()=>KJt,appendFileSync:()=>EJt,arch:()=>DYt,arrayBuffer:()=>LZt,basename:()=>IJt,builtinModules:()=>YYt,callbackify:()=>lZt,channel:()=>yZt,chmodSync:()=>WJt,clearInterval:()=>BZt,clearTimeout:()=>FZt,closeSync:()=>XJt,connect:()=>$Yt,constants:()=>RZt,copyFileSync:()=>YJt,cpSync:()=>SJt,cpus:()=>IYt,createConnection:()=>FYt,createGunzip:()=>HYt,createGzip:()=>VYt,createHash:()=>moe,createHmac:()=>_Jt,createInterface:()=>xZt,createReadStream:()=>lYt,createRequire:()=>JYt,createServer:()=>CJt,createWriteStream:()=>aYt,debug:()=>iZt,debuglog:()=>goe,default:()=>yJt,deflateSync:()=>BYt,deprecate:()=>aZt,deserialize:()=>TZt,dirname:()=>kJt,exec:()=>TYt,execFile:()=>EYt,execFileSync:()=>SYt,execSync:()=>bYt,existsSync:()=>GJt,extname:()=>RJt,fileURLToPath:()=>rZt,finished:()=>qJt,format:()=>QYt,freemem:()=>RYt,fstatSync:()=>QJt,get:()=>LYt,gunzip:()=>GYt,gunzipSync:()=>zYt,gzip:()=>qYt,gzipSync:()=>jYt,hasSubscribers:()=>_Zt,homedir:()=>xYt,hostname:()=>kYt,inflateSync:()=>UYt,inherits:()=>oZt,inspect:()=>jx,isAbsolute:()=>MJt,isBuiltin:()=>ZYt,isDeepStrictEqual:()=>cZt,isIP:()=>DZt,isIPv4:()=>MZt,isIPv6:()=>PZt,isMainThread:()=>EZt,join:()=>xJt,lookup:()=>pZt,mkdir:()=>dYt,mkdirSync:()=>eYt,monitorEventLoopDelay:()=>gZt,normalize:()=>NJt,ok:()=>WYt,open:()=>vYt,openSync:()=>ZJt,parentPort:()=>SZt,parse:()=>XYt,pathToFileURL:()=>nZt,performance:()=>hZt,pipeline:()=>jJt,platform:()=>CYt,posix:()=>OJt,promises:()=>vJt,promisify:()=>sZt,randomBytes:()=>wJt,randomUUID:()=>TJt,readFile:()=>cYt,readFileSync:()=>HJt,readdir:()=>mYt,readdirSync:()=>rYt,realpath:()=>_Yt,realpathSync:()=>JJt,relative:()=>PJt,release:()=>OYt,rename:()=>gYt,renameSync:()=>oYt,request:()=>NYt,resolve:()=>AJt,rm:()=>yYt,rmSync:()=>iYt,rmdirSync:()=>sYt,sep:()=>DJt,serialize:()=>wZt,setInterval:()=>UZt,setTimeout:()=>$Zt,spawn:()=>wYt,stat:()=>pYt,statSync:()=>tYt,strict:()=>KYt,tmpdir:()=>AYt,toUSVString:()=>uZt,totalmem:()=>PYt,type:()=>MYt,types:()=>dZt,unlink:()=>hYt,unlinkSync:()=>nYt,webcrypto:()=>bJt,workerData:()=>CZt,writeFile:()=>uYt,writeFileSync:()=>VJt});var Do,Wn,yJt,vJt,moe,_Jt,wJt,TJt,bJt,EJt,SJt,CJt,xJt,AJt,kJt,IJt,RJt,PJt,MJt,DJt,OJt,NJt,LJt,$Jt,hoe,foe,FJt,UJt,BJt,zJt,jJt,qJt,GJt,HJt,VJt,WJt,KJt,JJt,YJt,ZJt,XJt,QJt,eYt,tYt,rYt,nYt,oYt,sYt,iYt,aYt,lYt,cYt,uYt,dYt,pYt,mYt,hYt,fYt,gYt,yYt,vYt,_Yt,wYt,TYt,bYt,EYt,SYt,CYt,xYt,AYt,kYt,IYt,RYt,PYt,MYt,DYt,OYt,NYt,LYt,$Yt,FYt,UYt,BYt,zYt,jYt,qYt,GYt,HYt,VYt,WYt,KYt,JYt,YYt,ZYt,XYt,QYt,eZt,tZt,rZt,nZt,oZt,sZt,goe,iZt,jx,aZt,lZt,cZt,uZt,dZt,yoe,qx,pZt,mZt,hZt,fZt,gZt,yZt,vZt,_Zt,wZt,TZt,bZt,EZt,SZt,CZt,xZt,AZt,kZt,IZt,RZt,PZt,MZt,DZt,OZt,NZt,LZt,voe,$Zt,FZt,UZt,BZt,zZt,G7r=C({"node-stub:node:sqlite"(){Do=()=>{},Wn=async()=>{},yJt={},vJt={readFile:Wn,writeFile:Wn,mkdir:Wn,stat:Wn,readdir:Wn,unlink:Wn,access:Wn,rm:Wn,rename:Wn},moe=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new qx().encode(r):r),this},digest(r){let n=0;for(const s of t)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},_Jt=(e,t)=>moe(e),wJt=e=>new Uint8Array(e||32),TJt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),bJt=globalThis.crypto,EJt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},SJt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},CJt=()=>({listen:Do,close:Do,on:Do}),xJt=(...e)=>e.join("/"),AJt=(...e)=>e.join("/"),kJt=e=>e||"",IJt=e=>e?.split?.("/")?.pop?.()||"",RJt=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},PJt=(e,t)=>t||"",MJt=()=>!1,DJt="/",OJt={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},NJt=e=>e,LJt=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},$Jt=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},hoe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},foe=class{write(){return!0}end(){}on(){return this}destroy(){}},FJt=class{push(){}on(){return this}},UJt=class{on(){return this}},BJt=class{pipe(){return this}on(){return this}},zJt=globalThis.ReadableStream||class{},jJt=Do,qJt=Do,GJt=()=>!1,HJt=()=>"",VJt=Do,WJt=Do,KJt=Wn,JJt=e=>e,YJt=Do,ZJt=()=>0,XJt=Do,QJt=()=>({}),eYt=Do,tYt=()=>({}),rYt=()=>[],nYt=Do,oYt=Do,sYt=Do,iYt=Do,aYt=()=>new foe,lYt=()=>new hoe,cYt=Wn,uYt=Wn,dYt=Wn,pYt=Wn,mYt=Wn,hYt=Wn,fYt=Wn,gYt=Wn,yYt=Wn,vYt=async()=>({stat:Wn,readFile:Wn,close:Wn,read:Wn,write:Wn}),_Yt=async e=>e,wYt=()=>({on:Do,stdout:{on:Do},stderr:{on:Do},kill:Do}),TYt=(e,t)=>t?.(null,"",""),bYt=()=>"",EYt=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},SYt=()=>"",CYt="browser",xYt=()=>"/",AYt=()=>"/tmp",kYt=()=>"browser",IYt=()=>[{}],RYt=()=>0,PYt=()=>0,MYt=()=>"Browser",DYt=()=>"wasm",OYt=()=>"0",NYt=()=>({}),LYt=()=>({}),$Yt=()=>({}),FYt=()=>({}),UYt=()=>new Uint8Array,BYt=()=>new Uint8Array,zYt=()=>new Uint8Array,jYt=()=>new Uint8Array,qYt=(e,t)=>t?.(null,e),GYt=(e,t)=>t?.(null,e),HYt=()=>({}),VYt=()=>({}),WYt=Do,KYt={},JYt=()=>()=>({}),YYt=[],ZYt=()=>!1,XYt=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),QYt=()=>"",eZt=globalThis.URL,tZt=globalThis.URLSearchParams,rZt=e=>typeof e=="string"?e.replace("file://",""):e,nZt=e=>new globalThis.URL("file://"+e),oZt=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},sZt=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),goe=e=>{const t=(...r)=>{};return t.enabled=!1,t},iZt=goe,jx=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},jx.custom=Symbol.for("nodejs.util.inspect.custom"),jx.colors={},jx.styles={},aZt=e=>e,lZt=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},cZt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),uZt=e=>String(e),dZt={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},yoe=globalThis.TextDecoder,qx=globalThis.TextEncoder,pZt=(e,t)=>t?.(null,"127.0.0.1",4),mZt=class{},hZt=globalThis.performance||{now:()=>Date.now()},fZt=class{observe(){}disconnect(){}},gZt=()=>({enable:Do,disable:Do,percentile:()=>0}),yZt=()=>({}),vZt=class{},_Zt=()=>!1,wZt=()=>new Uint8Array,TZt=Do,bZt=class{},EZt=!0,SZt=null,CZt=null,xZt=()=>({}),AZt=class{},kZt=class{},IZt=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),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new qx().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((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new qx().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 yoe().decode(this)}},RZt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},PZt=()=>!1,MZt=()=>!1,DZt=()=>0,OZt=class{},NZt=class{},LZt=async()=>new ArrayBuffer(0),voe=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),$Zt=(...e)=>voe(globalThis.setTimeout(...e)),FZt=globalThis.clearTimeout,UZt=(...e)=>voe(globalThis.setInterval(...e)),BZt=globalThis.clearInterval,zZt=class{constructor(e){this.type=e}toString(){return this.type}}}}),jZt={};le(jZt,{createOpenCodeReader:()=>V7r});function qZt(){return Sr(Tu(),".local","share","opencode","opencode.db")}function H7r(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function PL(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function V7r(){return{descriptor:{id:Km,displayName:"OpenCode",verified:!0,dedupStrategy:"rowid-high-water-mark",costConfidence:"unavailable",requiresSqlite:!0},detect:async()=>{try{return(await Ou(qZt())).isFile()}catch{return!1}},scan:async e=>{const t=H7r(),r=[],n=new Set,o=qZt();let s;try{const u=await Promise.resolve().then(()=>(G7r(),gJt));typeof u=="object"&&u!==null&&"DatabaseSync"in u&&typeof u.DatabaseSync=="function"&&(s=u.DatabaseSync)}catch(u){return r.push({cliId:Km,filePath:o,message:`node:sqlite unavailable on this runtime: ${u instanceof Error?u.message:String(u)}`}),{cliId:Km,totals:t,filesScanned:0,errors:r}}if(!s)return r.push({cliId:Km,filePath:o,message:"node:sqlite did not expose a callable DatabaseSync \u2014 the experimental API has likely changed shape"}),{cliId:Km,totals:t,filesScanned:0,errors:r};const i=e?.sinceDays??GZt,a=Number.isNaN(i)?0:i,l=a===1/0?0:Date.now()-Math.max(0,a)*864e5;let c;try{c=new s(o,{readOnly:!0});const u=c.prepare("SELECT data FROM message WHERE time_created >= ?").all(l);for(const d of u){if(typeof d.data!="string")continue;let m;try{m=JSON.parse(d.data)}catch{continue}const h=m,g=h.tokens;if(!g||h.role!=="assistant")continue;const y=PL(g.input),v=PL(g.output),w=PL(g.cache?.read),b=PL(g.cache?.write);y===0&&v===0&&w===0&&b===0||(t.requests+=1,t.inputTokens+=y,t.outputTokens+=v,t.cacheReadTokens+=w,t.cacheCreationTokens+=b,h.modelID&&n.add(h.modelID))}}catch(u){r.push({cliId:Km,filePath:o,message:u instanceof Error?u.message:String(u)})}finally{try{c?.close()}catch{}}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:Km,totals:t,filesScanned:t.requests>0||r.length===0?1:0,errors:r}}}}var Km,GZt,W7r=C({"src/lib/localUsage/openCodeReader.ts"(){"use strict";ma(),Wl(),Nr(),Km="opencode",GZt=30}});vc(),ra(),AA(),pn(),Nr(),$t(),V(),Ct();var{readFile:_oe,writeFile:HZt,readdir:K7r,mkdir:J7r,unlink:Y7r,access:Z7r}=vi,X7r=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:s="update",silent:i=!1}=t;r&&(await this.createBackup(s),i||f.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),i||f.info("\u2705 Configuration updated successfully")}catch(l){throw r&&(await this.restoreLatestBackup(),i||f.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=Sr(this.backupDir,r),o=await this.loadConfig(),s=this.generateConfigHash(o),i={reason:e,timestamp:Date.now(),version:o.configVersion||"unknown",originalPath:this.configPath,hash:s,size:JSON.stringify(o).length,createdBy:"NeuroLinkConfigManager"},a=`// NeuroLink Config Backup - ${e}
2217
2217
  // Created: ${new Date().toISOString()}
2218
2218
  // Reason: ${e}
2219
2219
  // Hash: ${s}
@@ -179,10 +179,22 @@ export async function createClaudeCodeReader() {
179
179
  const unpriced = new Set();
180
180
  const files = [];
181
181
  await collectTranscripts(projectsRoot(), files);
182
- const sinceDays = options?.sinceDays ?? DEFAULT_SINCE_DAYS;
183
- const cutoff = Number.isFinite(sinceDays) && sinceDays > 0
184
- ? Date.now() - sinceDays * 86_400_000
185
- : undefined;
182
+ // Only Infinity means "no time filter". A non-positive sinceDays used to
183
+ // leave the cutoff undefined and read EVERYTHING — measured at 17,534
184
+ // files and 35.9s for `sinceDays: 0`, which is the widest possible scan
185
+ // in answer to the narrowest possible request. Zero now means a
186
+ // zero-length window, which is what it reads as.
187
+ // NaN is not a window, and it is the case the previous fix missed:
188
+ // Math.max(0, NaN) is NaN, every comparison against NaN is false, so the
189
+ // filter passes EVERY file. Measured: sinceDays NaN read 17,537 files in
190
+ // 32.8s — the same unbounded sweep this guard exists to prevent, reached
191
+ // by a different door. The old guard caught it with Number.isFinite and
192
+ // the replacement dropped that check.
193
+ const requestedDays = options?.sinceDays ?? DEFAULT_SINCE_DAYS;
194
+ const sinceDays = Number.isNaN(requestedDays) ? 0 : requestedDays;
195
+ const cutoff = sinceDays === Infinity
196
+ ? undefined
197
+ : Date.now() - Math.max(0, sinceDays) * 86_400_000;
186
198
  let filesScanned = 0;
187
199
  for (const file of files) {
188
200
  try {
@@ -167,10 +167,22 @@ export async function createCodexReader() {
167
167
  const models = new Set();
168
168
  const files = [];
169
169
  await collectRollouts(sessionsRoot(), files);
170
- const sinceDays = options?.sinceDays ?? DEFAULT_SINCE_DAYS;
171
- const cutoff = Number.isFinite(sinceDays) && sinceDays > 0
172
- ? Date.now() - sinceDays * 86_400_000
173
- : undefined;
170
+ // Only Infinity means "no time filter". A non-positive sinceDays used to
171
+ // leave the cutoff undefined and read EVERYTHING — measured at 17,534
172
+ // files and 35.9s for `sinceDays: 0`, which is the widest possible scan
173
+ // in answer to the narrowest possible request. Zero now means a
174
+ // zero-length window, which is what it reads as.
175
+ // NaN is not a window, and it is the case the previous fix missed:
176
+ // Math.max(0, NaN) is NaN, every comparison against NaN is false, so the
177
+ // filter passes EVERY file. Measured: sinceDays NaN read 17,537 files in
178
+ // 32.8s — the same unbounded sweep this guard exists to prevent, reached
179
+ // by a different door. The old guard caught it with Number.isFinite and
180
+ // the replacement dropped that check.
181
+ const requestedDays = options?.sinceDays ?? DEFAULT_SINCE_DAYS;
182
+ const sinceDays = Number.isNaN(requestedDays) ? 0 : requestedDays;
183
+ const cutoff = sinceDays === Infinity
184
+ ? undefined
185
+ : Date.now() - Math.max(0, sinceDays) * 86_400_000;
174
186
  let filesScanned = 0;
175
187
  for (const file of files) {
176
188
  try {
@@ -114,10 +114,28 @@ export async function createOpenCodeReader() {
114
114
  });
115
115
  return { cliId: CLI_ID, totals, filesScanned: 0, errors };
116
116
  }
117
- const sinceDays = options?.sinceDays ?? DEFAULT_SINCE_DAYS;
118
- const cutoffMs = Number.isFinite(sinceDays) && sinceDays > 0
119
- ? Date.now() - sinceDays * 86_400_000
120
- : 0;
117
+ // Only Infinity means "no time filter". A non-positive sinceDays used to
118
+ // leave the cutoff undefined and read EVERYTHING — measured at 17,534
119
+ // files and 35.9s for `sinceDays: 0`, which is the widest possible scan
120
+ // in answer to the narrowest possible request. Zero now means a
121
+ // zero-length window, which is what it reads as.
122
+ // NaN is not a window, and it is the case the previous fix missed:
123
+ // Math.max(0, NaN) is NaN, every comparison against NaN is false, so the
124
+ // filter passes EVERY file. Measured: sinceDays NaN read 17,537 files in
125
+ // 32.8s — the same unbounded sweep this guard exists to prevent, reached
126
+ // by a different door. The old guard caught it with Number.isFinite and
127
+ // the replacement dropped that check.
128
+ //
129
+ // On this reader NaN was worse than an unbounded scan: the value went
130
+ // into the SQL text, and SQLite parses a bare NaN as an identifier —
131
+ // "no such column: NaN" — so the whole scan failed rather than
132
+ // over-reading. The cutoff is a bound parameter now, so a value can
133
+ // never be SQL syntax whatever it is.
134
+ const requestedDays = options?.sinceDays ?? DEFAULT_SINCE_DAYS;
135
+ const sinceDays = Number.isNaN(requestedDays) ? 0 : requestedDays;
136
+ const cutoffMs = sinceDays === Infinity
137
+ ? 0
138
+ : Date.now() - Math.max(0, sinceDays) * 86_400_000;
121
139
  let db;
122
140
  try {
123
141
  // Read-only: this is the user's live store and OpenCode may be running.
@@ -125,9 +143,13 @@ export async function createOpenCodeReader() {
125
143
  // Filtered in SQL rather than in JS. `time_created` is epoch ms, and
126
144
  // the table holds thousands of rows whose `data` blobs are large — the
127
145
  // point of the time window is not reading them at all.
146
+ // Bound parameter, not interpolation. A number spliced into SQL text
147
+ // is still SQL text: NaN parsed as an identifier and failed the whole
148
+ // scan with "no such column: NaN". A bound value cannot become syntax
149
+ // whatever it holds.
128
150
  const rows = db
129
- .prepare(`SELECT data FROM message WHERE time_created >= ${cutoffMs}`)
130
- .all();
151
+ .prepare("SELECT data FROM message WHERE time_created >= ?")
152
+ .all(cutoffMs);
131
153
  for (const row of rows) {
132
154
  if (typeof row.data !== "string") {
133
155
  continue;
@@ -121,7 +121,7 @@ export type LocalUsageAggregateReport = {
121
121
  generatedAt: string;
122
122
  /** Only CLIs whose store was detected AND scanned appear here. */
123
123
  totals: Partial<Record<LocalUsageCliId, LocalUsageTotals>>;
124
- /** CLIs that were registered but produced nothing, and why. */
124
+ /** CLIs whose reader could not be created, detected, or scanned, and why. */
125
125
  failures: LocalUsageReaderFailure[];
126
126
  /** CLIs with no local store on this machine — absent, not failed. */
127
127
  notInstalled: LocalUsageCliId[];
@@ -161,7 +161,7 @@ export type LocalUsageCodexSessionRollup = {
161
161
  */
162
162
  export type LocalUsageSqliteDatabase = {
163
163
  prepare: (sql: string) => {
164
- all: () => unknown[];
164
+ all: (...params: unknown[]) => unknown[];
165
165
  };
166
166
  close: () => void;
167
167
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "11.22.1",
3
+ "version": "11.22.2",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI Ā· Anthropic Ā· Gemini Ā· Bedrock Ā· Azure Ā· Ollama Ā· DeepSeek Ā· NVIDIA NIM and more.",
6
6
  "author": {
@@ -1,3 +0,0 @@
1
- import type { Argv } from "yargs";
2
- export declare function addOllamaCommands(cli: Argv): void;
3
- export default addOllamaCommands;
@@ -1,334 +0,0 @@
1
- import { spawnSync } from "child_process";
2
- import chalk from "chalk";
3
- import ora from "ora";
4
- import inquirer from "inquirer";
5
- import { logger } from "../../utils/logger.js";
6
- import { OllamaUtils } from "../utils/ollamaUtils.js";
7
- export function addOllamaCommands(cli) {
8
- cli.command("ollama <command>", "Manage Ollama local AI models", (yargs) => {
9
- return yargs
10
- .command("list-models", "List installed Ollama models", {}, listModelsHandler)
11
- .command("pull <model>", "Download an Ollama model", {
12
- model: {
13
- describe: "Model name to download",
14
- type: "string",
15
- demandOption: true,
16
- },
17
- }, pullModelHandler)
18
- .command("remove <model>", "Remove an Ollama model", {
19
- model: {
20
- describe: "Model name to remove",
21
- type: "string",
22
- demandOption: true,
23
- },
24
- }, removeModelHandler)
25
- .command("status", "Check Ollama service status", {}, statusHandler)
26
- .command("start", "Start Ollama service", {}, startHandler)
27
- .command("stop", "Stop Ollama service", {}, stopHandler)
28
- .command("setup", "Interactive Ollama setup", {}, setupHandler)
29
- .demandCommand(1, "Please specify a command");
30
- }, () => { });
31
- }
32
- /** See the note on the identically-named constant in ../utils/ollamaUtils.ts. */
33
- const OLLAMA_QUERY_TIMEOUT_MS = 15_000;
34
- async function listModelsHandler() {
35
- const spinner = ora("Fetching installed models...").start();
36
- try {
37
- const res = spawnSync("ollama", ["list"], {
38
- encoding: "utf8",
39
- timeout: OLLAMA_QUERY_TIMEOUT_MS,
40
- killSignal: "SIGKILL",
41
- });
42
- if (res.error) {
43
- throw res.error;
44
- }
45
- spinner.succeed("Installed models:");
46
- const output = res.stdout?.toString().trim();
47
- if (output) {
48
- logger.always(output);
49
- }
50
- else {
51
- logger.always(chalk.yellow('No models installed. Use "neurolink ollama pull <model>" to download a model.'));
52
- }
53
- }
54
- catch (error) {
55
- spinner.fail("Failed to list models. Is Ollama installed?");
56
- const errorMessage = error instanceof Error ? error.message : String(error);
57
- logger.error(chalk.red("Error:", errorMessage));
58
- logger.always(chalk.blue("\nTip: Install Ollama from https://ollama.ai"));
59
- process.exit(1);
60
- }
61
- }
62
- async function pullModelHandler(argv) {
63
- const { model } = argv;
64
- logger.always(chalk.blue(`Downloading model: ${model}`));
65
- logger.always(chalk.gray("This may take several minutes..."));
66
- try {
67
- // Deliberately unbounded: a model pull is hundreds of megabytes and
68
- // legitimately runs for many minutes. It also inherits stdio, so the user
69
- // sees progress and can Ctrl-C — the two things a wedged query lacks.
70
- const res = spawnSync("ollama", ["pull", model], { stdio: "inherit" });
71
- if (res.error) {
72
- throw res.error;
73
- }
74
- if (res.status !== 0) {
75
- throw new Error(`ollama pull exited with code ${res.status}`);
76
- }
77
- logger.always(chalk.green(`\nāœ… Successfully downloaded ${model}`));
78
- logger.always(chalk.blue(`\nTest it with: npx @juspay/neurolink generate "Hello!" --provider ollama --model ${model}`));
79
- }
80
- catch (error) {
81
- logger.error(chalk.red(`\nāŒ Failed to download ${model}`));
82
- const errorMessage = error instanceof Error ? error.message : String(error);
83
- logger.error(chalk.red("Error:", errorMessage));
84
- process.exit(1);
85
- }
86
- }
87
- async function removeModelHandler(argv) {
88
- const { model } = argv;
89
- const { confirm } = await inquirer.prompt([
90
- {
91
- type: "confirm",
92
- name: "confirm",
93
- message: `Are you sure you want to remove model "${model}"?`,
94
- default: false,
95
- },
96
- ]);
97
- if (!confirm) {
98
- logger.always(chalk.yellow("Removal cancelled."));
99
- return;
100
- }
101
- const spinner = ora(`Removing model ${model}...`).start();
102
- try {
103
- const res = spawnSync("ollama", ["rm", model], {
104
- encoding: "utf8",
105
- timeout: OLLAMA_QUERY_TIMEOUT_MS,
106
- killSignal: "SIGKILL",
107
- });
108
- if (res.error) {
109
- throw res.error;
110
- }
111
- if (res.status !== 0) {
112
- throw new Error(`ollama rm exited with ${res.status}`);
113
- }
114
- spinner.succeed(`Successfully removed ${model}`);
115
- }
116
- catch (_error) {
117
- spinner.fail(`Failed to remove ${model}`);
118
- const errorMessage = _error instanceof Error ? _error.message : String(_error);
119
- logger.error(chalk.red("Error:", errorMessage));
120
- process.exit(1);
121
- }
122
- }
123
- async function statusHandler() {
124
- const spinner = ora("Checking Ollama service status...").start();
125
- try {
126
- const res = spawnSync("ollama", ["list"], {
127
- encoding: "utf8",
128
- timeout: OLLAMA_QUERY_TIMEOUT_MS,
129
- killSignal: "SIGKILL",
130
- });
131
- if (res.error) {
132
- throw res.error;
133
- }
134
- if (res.status !== 0) {
135
- throw new Error("Ollama not running");
136
- }
137
- spinner.succeed("Ollama service is running");
138
- }
139
- catch (error) {
140
- spinner.fail("Ollama service is not running");
141
- logger.debug("Ollama status check failed:", error);
142
- logger.always(chalk.yellow("\nStart Ollama with: ollama serve"));
143
- process.exit(1);
144
- }
145
- }
146
- async function startHandler() {
147
- await OllamaUtils.startOllamaService();
148
- }
149
- async function stopHandler() {
150
- const spinner = ora("Stopping Ollama service...").start();
151
- try {
152
- if (process.platform === "darwin") {
153
- try {
154
- spawnSync("pkill", ["ollama"], {
155
- encoding: "utf8",
156
- timeout: OLLAMA_QUERY_TIMEOUT_MS,
157
- killSignal: "SIGKILL",
158
- });
159
- }
160
- catch {
161
- spawnSync("killall", ["Ollama"], {
162
- encoding: "utf8",
163
- timeout: OLLAMA_QUERY_TIMEOUT_MS,
164
- killSignal: "SIGKILL",
165
- });
166
- }
167
- }
168
- else if (process.platform === "linux") {
169
- try {
170
- spawnSync("systemctl", ["stop", "ollama"], {
171
- encoding: "utf8",
172
- timeout: OLLAMA_QUERY_TIMEOUT_MS,
173
- killSignal: "SIGKILL",
174
- });
175
- }
176
- catch {
177
- spawnSync("pkill", ["ollama"], {
178
- encoding: "utf8",
179
- timeout: OLLAMA_QUERY_TIMEOUT_MS,
180
- killSignal: "SIGKILL",
181
- });
182
- }
183
- }
184
- else {
185
- spawnSync("taskkill", ["/F", "/IM", "ollama.exe"], {
186
- encoding: "utf8",
187
- timeout: OLLAMA_QUERY_TIMEOUT_MS,
188
- killSignal: "SIGKILL",
189
- });
190
- }
191
- spinner.succeed("Ollama service stopped");
192
- }
193
- catch (err) {
194
- spinner.fail("Failed to stop Ollama service");
195
- logger.error(chalk.red("It may not be running or requires manual stop"));
196
- logger.error(chalk.red(`Error details: ${err}`));
197
- }
198
- }
199
- async function setupHandler() {
200
- logger.always(chalk.blue("šŸ¦™ Welcome to Ollama Setup!\n"));
201
- // Check installation
202
- const checkSpinner = ora("Checking Ollama installation...").start();
203
- let isInstalled = false;
204
- try {
205
- spawnSync("ollama", ["--version"], {
206
- encoding: "utf8",
207
- timeout: OLLAMA_QUERY_TIMEOUT_MS,
208
- killSignal: "SIGKILL",
209
- });
210
- isInstalled = true;
211
- checkSpinner.succeed("Ollama is installed");
212
- }
213
- catch {
214
- checkSpinner.fail("Ollama is not installed");
215
- }
216
- if (!isInstalled) {
217
- logger.always(chalk.yellow("\nOllama needs to be installed first."));
218
- logger.always(chalk.blue("\nInstallation instructions:"));
219
- if (process.platform === "darwin") {
220
- logger.always("\nFor macOS:");
221
- logger.always(chalk.gray(" brew install ollama"));
222
- logger.always(chalk.gray(" # or download from https://ollama.ai"));
223
- }
224
- else if (process.platform === "linux") {
225
- logger.always("\nFor Linux:");
226
- logger.always(chalk.gray(" curl -fsSL https://ollama.ai/install.sh | sh"));
227
- }
228
- else {
229
- logger.always("\nFor Windows:");
230
- logger.always(chalk.gray(" Download from https://ollama.ai"));
231
- }
232
- const { proceedAnyway } = await inquirer.prompt([
233
- {
234
- type: "confirm",
235
- name: "proceedAnyway",
236
- message: "Would you like to continue with setup anyway?",
237
- default: false,
238
- },
239
- ]);
240
- if (!proceedAnyway) {
241
- logger.always(chalk.blue("\nInstall Ollama and run setup again!"));
242
- return;
243
- }
244
- }
245
- // Check if service is running
246
- let serviceRunning = false;
247
- try {
248
- spawnSync("ollama", ["list"], {
249
- encoding: "utf8",
250
- timeout: OLLAMA_QUERY_TIMEOUT_MS,
251
- killSignal: "SIGKILL",
252
- });
253
- serviceRunning = true;
254
- logger.always(chalk.green("\nāœ… Ollama service is running"));
255
- }
256
- catch {
257
- logger.always(chalk.yellow("\nāš ļø Ollama service is not running"));
258
- const { startService } = await inquirer.prompt([
259
- {
260
- type: "confirm",
261
- name: "startService",
262
- message: "Would you like to start the Ollama service?",
263
- default: true,
264
- },
265
- ]);
266
- if (startService) {
267
- await startHandler();
268
- serviceRunning = true;
269
- }
270
- }
271
- if (serviceRunning) {
272
- // List available models
273
- logger.always(chalk.blue("\nšŸ“¦ Popular Ollama models:"));
274
- logger.always(" • llama2 (7B) - General purpose");
275
- logger.always(" • codellama (7B) - Code generation");
276
- logger.always(" • mistral (7B) - Fast and efficient");
277
- logger.always(" • tinyllama (1B) - Lightweight");
278
- logger.always(" • phi (2.7B) - Microsoft's compact model");
279
- const { downloadModel } = await inquirer.prompt([
280
- {
281
- type: "confirm",
282
- name: "downloadModel",
283
- message: "Would you like to download a model?",
284
- default: true,
285
- },
286
- ]);
287
- if (downloadModel) {
288
- const { selectedModel } = await inquirer.prompt([
289
- {
290
- type: "select",
291
- name: "selectedModel",
292
- message: "Select a model to download:",
293
- choices: [
294
- {
295
- name: "llama2 (7B) - Recommended for general use",
296
- value: "llama2",
297
- },
298
- {
299
- name: "codellama (7B) - Best for code generation",
300
- value: "codellama",
301
- },
302
- { name: "mistral (7B) - Fast and efficient", value: "mistral" },
303
- { name: "tinyllama (1B) - Lightweight, fast", value: "tinyllama" },
304
- { name: "phi (2.7B) - Microsoft's compact model", value: "phi" },
305
- { name: "Other (enter manually)", value: "other" },
306
- ],
307
- },
308
- ]);
309
- let modelToDownload = selectedModel;
310
- if (selectedModel === "other") {
311
- const { customModel } = await inquirer.prompt([
312
- {
313
- type: "input",
314
- name: "customModel",
315
- message: "Enter the model name:",
316
- validate: (input) => input.trim().length > 0 || "Model name is required",
317
- },
318
- ]);
319
- modelToDownload = customModel;
320
- }
321
- await pullModelHandler({ model: modelToDownload });
322
- }
323
- }
324
- logger.always(chalk.green("\nāœ… Setup complete!\n"));
325
- logger.always(chalk.blue("Next steps:"));
326
- logger.always("1. List models: " + chalk.gray("neurolink ollama list-models"));
327
- logger.always("2. Generate text: " +
328
- chalk.gray('neurolink generate "Hello!" --provider ollama'));
329
- logger.always("3. Use specific model: " +
330
- chalk.gray('neurolink generate "Hello!" --provider ollama --model codellama'));
331
- logger.always(chalk.gray("\nFor more information, see: https://docs.neurolink.ai/providers/ollama"));
332
- }
333
- export default addOllamaCommands;
334
- //# sourceMappingURL=ollama.js.map