"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DidWebResolver=void 0,exports.didWebToUrl=didWebToUrl;const shared_1=require("../_deps/shared/index.js"),crypto_utils_js_1=require("./crypto-utils.js");class DidWebResolver{fetchFn;cacheTtlMs;cache=new Map;constructor(e){this.fetchFn=e?.fetch??globalThis.fetch.bind(globalThis),this.cacheTtlMs=e?.cacheTtlMs??3e5}async register(e){return(0,shared_1.err)("ALREADY_REGISTERED")}async resolve(e){const t=await this.fetchEntry(e);return t.ok?t.value.revoked?(0,shared_1.err)("REVOKED"):(0,shared_1.ok)(t.value.publicKey):t}async hasScope(e,t){const r=await this.fetchEntry(e);return!!r.ok&&r.value.scopes.has(t)}async hasReceiveScope(e,t){const r=await this.fetchEntry(e);return!!r.ok&&(!r.value.receiveScopes||r.value.receiveScopes.has(t))}async revoke(e){return(0,shared_1.err)("NOT_FOUND")}async getEntry(e){return this.fetchEntry(e)}get cacheSize(){return this.cache.size}async fetchEntry(e){const t=this.cache.get(e);if(t&&Date.now()-t.fetchedAt<this.cacheTtlMs)return(0,shared_1.ok)(t.entry);const r=didWebToUrl(e);if(!r)return(0,shared_1.err)("NOT_FOUND");try{const t=await this.fetchFn(r);if(!t.ok)return(0,shared_1.err)("NOT_FOUND");const n=parseDidDocument(e,await t.json());return n?(this.cache.set(e,{entry:n,fetchedAt:Date.now()}),(0,shared_1.ok)(n)):(0,shared_1.err)("NOT_FOUND")}catch{return(0,shared_1.err)("NETWORK_ERROR")}}}function didWebToUrl(e){if(!e.startsWith("did:web:"))return null;const t=e.slice(8).split(":");if(0===t.length||!t[0])return null;const r=decodeURIComponent(t[0]);if(1===t.length)return`https://${r}/.well-known/did.json`;return`https://${r}/${t.slice(1).map(decodeURIComponent).join("/")}/did.json`}function parseDidDocument(e,t){if(!t.verificationMethod||0===t.verificationMethod.length)return null;const r=t.verificationMethod[0];if(!r)return null;let n=null;return r.publicKeyMultibase?n=decodeMultibase(r.publicKeyMultibase):r.publicKeyBase64&&(n=(0,crypto_utils_js_1.fromBase64)(r.publicKeyBase64)),n?{did:e,publicKey:n,name:t.xailName??e,scopes:new Set(t.xailScopes??[]),revoked:!0===t.deactivated,rotation_sequence:1}:null}function decodeMultibase(e){return e.startsWith("z")?base58Decode(e.slice(1)):null}function base58Decode(e){const t=BigInt(58);let r=BigInt(0);for(const n of e){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".indexOf(n);if(e<0)return new Uint8Array(0);r=r*t+BigInt(e)}const n=r.toString(16),s=n.length%2?"0"+n:n,i=new Uint8Array(s.length/2);for(let e=0;e<i.length;e++)i[e]=parseInt(s.slice(2*e,2*e+2),16);let c=0;for(const t of e){if("1"!==t)break;c++}if(c>0){const e=new Uint8Array(c+i.length);return e.set(i,c),e}return i}exports.DidWebResolver=DidWebResolver;