import{ok,err}from"./_deps/shared/index.js";import{fromBase64}from"./crypto-utils.js";export 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 err("ALREADY_REGISTERED")}async resolve(e){const t=await this.fetchEntry(e);return t.ok?t.value.revoked?err("REVOKED"):ok(t.value.publicKey):t}async hasScope(e,t){const n=await this.fetchEntry(e);return!!n.ok&&n.value.scopes.has(t)}async hasReceiveScope(e,t){const n=await this.fetchEntry(e);return!!n.ok&&(!n.value.receiveScopes||n.value.receiveScopes.has(t))}async revoke(e){return 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 ok(t.entry);const n=didWebToUrl(e);if(!n)return err("NOT_FOUND");try{const t=await this.fetchFn(n);if(!t.ok)return err("NOT_FOUND");const r=parseDidDocument(e,await t.json());return r?(this.cache.set(e,{entry:r,fetchedAt:Date.now()}),ok(r)):err("NOT_FOUND")}catch{return err("NETWORK_ERROR")}}}export 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 n=decodeURIComponent(t[0]);if(1===t.length)return`https://${n}/.well-known/did.json`;return`https://${n}/${t.slice(1).map(decodeURIComponent).join("/")}/did.json`}function parseDidDocument(e,t){if(!t.verificationMethod||0===t.verificationMethod.length)return null;const n=t.verificationMethod[0];if(!n)return null;let r=null;return n.publicKeyMultibase?r=decodeMultibase(n.publicKeyMultibase):n.publicKeyBase64&&(r=fromBase64(n.publicKeyBase64)),r?{did:e,publicKey:r,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 n=BigInt(0);for(const r of e){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".indexOf(r);if(e<0)return new Uint8Array(0);n=n*t+BigInt(e)}const r=n.toString(16),c=r.length%2?"0"+r:r,s=new Uint8Array(c.length/2);for(let e=0;e<s.length;e++)s[e]=parseInt(c.slice(2*e,2*e+2),16);let i=0;for(const t of e){if("1"!==t)break;i++}if(i>0){const e=new Uint8Array(i+s.length);return e.set(s,i),e}return s}