@graffiti-garden/implementation-decentralized 0.1.4 → 0.1.5

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.
@@ -7,7 +7,7 @@ import{a as vp,b as Ap,c as Tp}from"./chunk-O4MIY67H.js";var Wf=vp((vt,Vf)=>{var
7
7
  `);s=a===-1?"":i.slice(a+1)}if(!r.stack)r.stack=s;else if(s){let a=s.indexOf(`
8
8
  `),c=a===-1?-1:s.indexOf(`
9
9
  `,a+1),u=c===-1?"":s.slice(c+1);String(r.stack).endsWith(u)||(r.stack+=`
10
- `+s)}}catch{}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Be(this.defaults,n);let{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Or.assertOptions(r,{silentJSONParsing:he.transitional(he.boolean),forcedJSONParsing:he.transitional(he.boolean),clarifyTimeoutError:he.transitional(he.boolean),legacyInterceptorReqResOrdering:he.transitional(he.boolean),advertiseZstdAcceptEncoding:he.transitional(he.boolean),validateStatusUndefinedResolves:he.transitional(he.boolean)},!1),o!=null&&(p.isFunction(o)?n.paramsSerializer={serialize:o}:Or.assertOptions(o,{encode:he.function,serialize:he.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Or.assertOptions(n,{baseUrl:he.spelling("baseURL"),withXsrfToken:he.spelling("withXSRFToken")},!0),n.method=(p.getSafeProp(n,"method")||p.getSafeProp(this.defaults,"method")||"get").toLowerCase();let s=i&&p.merge(i.common,i[n.method]);i&&p.forEach(Uo.concat("common"),w=>{delete i[w]}),n.headers=ee.concat(s,i);let a=[],c=!0;this.interceptors.request.forEach(function(E){if(typeof E.runWhen=="function"&&E.runWhen(n)===!1)return;c=c&&E.synchronous;let v=n.transitional||Sn;v&&v.legacyInterceptorReqResOrdering?a.unshift(E.fulfilled,E.rejected):a.push(E.fulfilled,E.rejected)});let u=[];this.interceptors.response.forEach(function(E){u.push(E.fulfilled,E.rejected)});let l,f=0,d;if(!c){let w=[Pr.bind(this),void 0];for(w.unshift(...a),w.push(...u),d=w.length,l=Promise.resolve(n);f<d;)l=l.then(w[f++],w[f++]);return l}d=a.length;let g=n;for(;f<d;){let w=a[f++],E=a[f++];try{g=w?w(g):g}catch(v){if(!E){l=Promise.reject(v);break}try{let h=E.call(this,v);p.isThenable(h)&&(l=Promise.resolve(h).then(()=>Pr.call(this,g)))}catch(h){l=Promise.reject(h)}break}}if(!l)try{l=Pr.call(this,g)}catch(w){l=Promise.reject(w)}for(f=0,d=u.length;f<d;)l=l.then(u[f++],u[f++]);return l}getUri(t){t=Be(this.defaults,t);let n=Rr(t.baseURL,t.url,t.allowAbsoluteUrls,t);return _r(n,t.params,t.paramsSerializer)}};p.forEach(["delete","get","head","options"],function(t){Pn.prototype[t]=function(n,r){return this.request(Be(r||{},{method:t,url:n,data:r&&p.hasOwnProp(r,"data")?r.data:void 0}))}});p.forEach(["post","put","patch","query"],function(t){function n(r){return function(i,s,a){return this.request(Be(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:i,data:s}))}}Pn.prototype[t]=n(),t!=="query"&&(Pn.prototype[t+"Form"]=n(!0))});var kr=Pn;var Ys=class e{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(i){n=i});let r=this;this.promise.then(o=>{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i,s=new Promise(a=>{r.subscribe(a),i=a}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,a){r.reason||(r.reason=new Ve(i,s,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){let t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new e(function(o){t=o}),cancel:t}}},Gf=Ys;function Xs(e){return function(n){return e.apply(null,n)}}function Qs(e){return p.isObject(e)&&e.isAxiosError===!0}var jo={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(jo).forEach(([e,t])=>{jo[t]===void 0&&(jo[t]=e)});var qf=jo;function Jf(e){let t=new kr(e),n=dr(kr.prototype.request,t);return p.extend(n,kr.prototype,t,{allOwnKeys:!0}),p.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Jf(Be(e,o))},n}var re=Jf(An);re.Axios=kr;re.CanceledError=Ve;re.CancelToken=Gf;re.isCancel=Sr;re.VERSION=Rn;re.toFormData=St;re.AxiosError=R;re.Cancel=re.CanceledError;re.all=function(t){return Promise.all(t)};re.spread=Xs;re.isAxiosError=Qs;re.mergeConfig=Be;re.AxiosHeaders=ee;re.formToJSON=e=>Do(p.isHTMLForm(e)?new FormData(e):e);re.getAdapter=No.getAdapter;re.HttpStatusCode=qf;re.default=re;var Zo=re;var{Axios:KR,AxiosError:VR,CanceledError:WR,isCancel:YR,CancelToken:XR,VERSION:QR,all:eP,Cancel:tP,isAxiosError:nP,spread:rP,toFormData:oP,AxiosHeaders:iP,HttpStatusCode:sP,formToJSON:aP,getAdapter:cP,mergeConfig:uP,create:lP}=Zo;function qy(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}function Pe(e,t,n){if(!e.s){if(n instanceof ea)if(n.s)t&1&&(t=n.s),n=n.v;else{n.o=Pe.bind(null,e,t);return}if(n&&n.then){n.then(Pe.bind(null,e,t),Pe.bind(null,e,2));return}e.s=t,e.v=n;let r=e.o;r&&r(e)}}var ea=(function(){function e(){}return e.prototype.then=function(t,n){let r=new e,o=this.s;if(o){let i=o&1?t:n;if(i){try{Pe(r,1,i(this.v))}catch(s){Pe(r,2,s)}return r}else return this}return this.o=function(i){try{let s=i.v;i.s&1?Pe(r,1,t?t(s):s):n?Pe(r,1,n(s)):Pe(r,2,s)}catch(s){Pe(r,2,s)}},r},e})();function On(e){return e instanceof ea&&e.s&1}function Jy(e,t){var n;do{var r=e();if(r&&r.then)if(On(r))r=r.v;else{n=!0;break}var o=t();if(On(o)&&(o=o.v),!o)return r}while(!o.then);let i=new ea,s=Pe.bind(null,i,2);return(n?r.then(a):o.then(c)).then(void 0,s),i;function a(u){for(r=u;o=t(),On(o)&&(o=o.v),!!o;){if(o.then){o.then(c).then(void 0,s);return}if(r=e(),r&&r.then)if(On(r))r=r.v;else{r.then(a).then(void 0,s);return}}Pe(i,1,r)}function c(u){if(u){do{if(r=e(),r&&r.then)if(On(r))r=r.v;else{r.then(a).then(void 0,s);return}if(u=t(),On(u)&&(u=u.v),!u){Pe(i,1,r);return}}while(!u.then);u.then(c).then(void 0,s)}else Pe(i,1,r)}}function Kf(){return{plc:function(t,n){try{let o=function(){let l=typeof c?.["@context"]<"u"?"application/did+ld+json":"application/did+json";return i?{didDocument:c,didDocumentMetadata:a,didResolutionMetadata:{error:"notFound",message:i}}:{didDocument:c,didDocumentMetadata:a,didResolutionMetadata:{contentType:l}}},r,i=null,s=`https://plc.directory/${encodeURIComponent(t)}`,a={},c=null,u=Jy(function(){function l(){r||c?.id===t||(i="resolver_error: DID document id does not match requested did")}let f=qy(function(){return Promise.resolve(Zo.get(s)).then(function(d){c=d.data})},function(d){i=`resolver_error: '"https://plc.directory/" + DID' must resolve to a valid https URL containing a JSON document: ${d}`,r=1});return f&&f.then?f.then(l):l(f)},function(){return!r&&!1});return Promise.resolve(u&&u.then?u.then(o):o(u))}catch(r){return Promise.reject(r)}}}}var Yf=Tp(Wf(),1);function Ky(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}var Vy=function(e){try{return Promise.resolve((0,Yf.default)(e,{mode:"cors"})).then(function(t){if(t.status>=400)throw new Error(`Bad response ${t.statusText}`);return t.json()})}catch(t){return Promise.reject(t)}};function Oe(e,t,n){if(!e.s){if(n instanceof ta)if(n.s)t&1&&(t=n.s),n=n.v;else{n.o=Oe.bind(null,e,t);return}if(n&&n.then){n.then(Oe.bind(null,e,t),Oe.bind(null,e,2));return}e.s=t,e.v=n;let r=e.o;r&&r(e)}}var Wy="/.well-known/did.json",ta=(function(){function e(){}return e.prototype.then=function(t,n){let r=new e,o=this.s;if(o){let i=o&1?t:n;if(i){try{Oe(r,1,i(this.v))}catch(s){Oe(r,2,s)}return r}else return this}return this.o=function(i){try{let s=i.v;i.s&1?Oe(r,1,t?t(s):s):n?Oe(r,1,n(s)):Oe(r,2,s)}catch(s){Oe(r,2,s)}},r},e})();function In(e){return e instanceof ta&&e.s&1}function Yy(e,t){var n;do{var r=e();if(r&&r.then)if(In(r))r=r.v;else{n=!0;break}var o=t();if(In(o)&&(o=o.v),!o)return r}while(!o.then);let i=new ta,s=Oe.bind(null,i,2);return(n?r.then(a):o.then(c)).then(void 0,s),i;function a(u){for(r=u;o=t(),In(o)&&(o=o.v),!!o;){if(o.then){o.then(c).then(void 0,s);return}if(r=e(),r&&r.then)if(In(r))r=r.v;else{r.then(a).then(void 0,s);return}}Oe(i,1,r)}function c(u){if(u){do{if(r=e(),r&&r.then)if(In(r))r=r.v;else{r.then(a).then(void 0,s);return}if(u=t(),In(u)&&(u=u.v),!u){Oe(i,1,r);return}}while(!u.then);u.then(c).then(void 0,s)}else Oe(i,1,r)}}function Xf(){return{web:function(t,n){try{let o=function(){let d=typeof l?.["@context"]<"u"?"application/did+ld+json":"application/did+json";return i?{didDocument:l,didDocumentMetadata:u,didResolutionMetadata:{error:"notFound",message:i}}:{didDocument:l,didDocumentMetadata:u,didResolutionMetadata:{contentType:d}}},r,i=null,s=decodeURIComponent(n.id)+Wy,a=n.id.split(":");a.length>1&&(s=a.map(decodeURIComponent).join("/")+"/did.json");let c=`https://${s}`,u={},l=null,f=Yy(function(){function d(){r||l?.id===t||(i="resolver_error: DID document id does not match requested did")}let g=Ky(function(){return Promise.resolve(Vy(c)).then(function(w){l=w})},function(w){i=`resolver_error: DID must resolve to a valid https URL containing a JSON document: ${w}`,r=1});return g&&g.then?g.then(d):d(g)},function(){return!r&&!1});return Promise.resolve(f&&f.then?f.then(o):o(f))}catch(r){return Promise.reject(r)}}}}var Go=class{methods={...Kf(),...Xf()};resolver=new Oo(this.methods,{cache:!0});inFlight=new Map;async resolve(t){if(!Object.keys(this.methods).some(o=>t.startsWith(`did:${o}:`)))throw new Error(`Unrecognized DID method: ${t}`);let n=this.inFlight.get(t);if(n)return n;let r=this.resolver.resolve(t).then(({didDocument:o})=>{if(!o)throw new Q(`DID not found: ${t}`);return o});this.inFlight.set(t,r);try{return await r}finally{this.inFlight.delete(t)}}};var oa;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(oa="oauth4webapi/v3.8.7");function Dr(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var xe="ERR_INVALID_ARG_VALUE",$e="ERR_INVALID_ARG_TYPE";function K(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var Jt=Symbol(),Wo=Symbol(),Yo=Symbol(),Kt=Symbol();var qo=Symbol();var Xy=new TextEncoder,Qy=new TextDecoder;function Qf(e){return typeof e=="string"?Xy.encode(e):Qy.decode(e)}var ia;Uint8Array.prototype.toBase64?ia=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):ia=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=32768)n.push(String.fromCharCode.apply(null,t.subarray(r,r+32768)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var sa;Uint8Array.fromBase64?sa=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw K("The input to be decoded is not correctly encoded.",xe,t)}}:sa=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch(t){throw K("The input to be decoded is not correctly encoded.",xe,t)}};function aa(e){return typeof e=="string"?sa(e):ia(e)}var At=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=ri,Error.captureStackTrace?.(this,this.constructor)}},zr=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,n?.code&&(this.code=n?.code),Error.captureStackTrace?.(this,this.constructor)}};function D(e,t,n){return new zr(e,{code:t,cause:n})}function Jo(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function ca(e){Dr(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(oa&&!t.has("user-agent")&&t.set("user-agent",oa),t.has("authorization"))throw K('"options.headers" must not include the "authorization" header name',xe);return t}function td(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw K('"options.signal" must return or be an instance of AbortSignal',$e);return t}}function nd(e){return e.includes("//")?e.replace("//","/"):e}function ew(e,t,n=!1){return e.pathname==="/"?e.pathname=t:e.pathname=nd(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function tw(e,t){return e.pathname=nd(`${e.pathname}/${t}`),e}async function nw(e,t,n,r){if(!(e instanceof URL))throw K(`"${t}" must be an instance of URL`,$e);ei(e,r?.[Jt]!==!0);let o=n(new URL(e.href)),i=ca(r?.headers);return i.set("accept","application/json"),(r?.[Kt]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:td(o,r?.signal)})}async function rd(e,t){return nw(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case"oidc":tw(n,".well-known/openid-configuration");break;case"oauth2":ew(n,".well-known/oauth-authorization-server");break;default:throw K('"options.algorithm" must be "oidc" (default), or "oauth2"',xe)}return n},t)}function Ir(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw K(`${n} must be a number`,$e,o);if(e>0)return;if(t){if(e!==0)throw K(`${n} must be a non-negative number`,xe,o);return}throw K(`${n} must be a positive number`,xe,o)}catch(i){throw r?D(i.message,r,o):i}}function be(e,t,n,r){try{if(typeof e!="string")throw K(`${t} must be a string`,$e,r);if(e.length===0)throw K(`${t} must not be empty`,xe,r)}catch(o){throw n?D(o.message,n,r):o}}async function od(e,t){let n=e;if(!(n instanceof URL)&&n!==Vo)throw K('"expectedIssuerIdentifier" must be an instance of URL',$e);if(!Dr(t,Response))throw K('"response" must be an instance of Response',$e);if(t.status!==200)throw D('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',oi,t);_a(t);let r=await bd(t);if(be(r.issuer,'"response" body "issuer" property',F,{body:r}),n!==Vo&&new URL(r.issuer).href!==n.href)throw D('"response" body "issuer" property does not match the expected value',ii,{expected:n.href,body:r,attribute:"issuer"});return r}function id(e){ow(e,"application/json")}function rw(e,...t){let n='"response" content-type must be ';if(t.length>2){let r=t.pop();n+=`${t.join(", ")}, or ${r}`}else t.length===2?n+=`${t[0]} or ${t[1]}`:n+=t[0];return D(n,ga,e)}function ow(e,t){if(pa(e)!==t)throw rw(e,t)}function iw(){return aa(crypto.getRandomValues(new Uint8Array(32)))}function sd(){return iw()}function ua(e){let t=e?.[Wo];return typeof t=="number"&&Number.isFinite(t)?t:0}function la(e){let t=e?.[Yo];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function fa(){return Math.floor(Date.now()/1e3)}function Xo(e){if(typeof e!="object"||e===null)throw K('"as" must be an object',$e);be(e.issuer,'"as.issuer"')}function Qo(e){if(typeof e!="object"||e===null)throw K('"client" must be an object',$e);be(e.client_id,'"client.client_id"')}function da(e){return be(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e)}}function ad(){return(e,t,n,r)=>{n.set("client_id",t.client_id)}}var sw=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function ei(e,t){if(t&&e.protocol!=="https:")throw D("only requests to HTTPS are allowed",ya,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw D("only HTTP and HTTPS requests are allowed",wa,e)}function ed(e,t,n,r){let o;if(typeof e!="string"||!(o=sw(e)))throw D(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Iw:zw,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return ei(o,r),o}function ti(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?ed(e.mtls_endpoint_aliases[t],t,n,r):ed(e[t],t,n,r)}function cd(e){if(e instanceof $n){let{0:t,length:n}=e.cause;return n===1&&t.scheme==="dpop"&&t.parameters.error==="use_dpop_nonce"}return e instanceof zn?e.error==="use_dpop_nonce":!1}var zn=class extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Ow,this.cause=n.cause,this.error=n.cause.error,this.status=n.response.status,this.error_description=n.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:n.response}),Error.captureStackTrace?.(this,this.constructor)}},$r=class extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=kw,this.cause=n.cause,this.error=n.cause.get("error"),this.error_description=n.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},$n=class extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Pw,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Ko="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",aw="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",cw='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',uw="("+Ko+")\\s*=\\s*"+cw,lw="("+Ko+")\\s*=\\s*("+Ko+")",fw=new RegExp("^[,\\s]*("+Ko+")"),dw=new RegExp("^[,\\s]*"+uw+"[,\\s]*(.*)"),pw=new RegExp("^[,\\s]*"+lw+"[,\\s]*(.*)"),hw=new RegExp("^("+aw+")(?:$|[,\\s])(.*)");function mw(e){if(!Dr(e,Response))throw K('"response" must be an instance of Response',$e);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(fw),i=o?.[1].toLowerCase();if(!i)return;let s=r.substring(o[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;r=a?a[1]:void 0;let u={},l;if(c)for(;r;){let d,g;if(o=r.match(dw)){if([,d,g,r]=o,g.includes("\\"))try{g=JSON.parse(`"${g}"`)}catch{}u[d.toLowerCase()]=g;continue}if(o=r.match(pw)){[,d,g,r]=o,u[d.toLowerCase()]=g;continue}if(o=r.match(hw)){if(Object.keys(u).length)break;[,l,r]=o;break}return}else r=s||void 0;let f={scheme:i,parameters:u};l&&(f.token68=l),n.push(f)}if(n.length)return n}async function gw(e){if(e.status>399&&e.status<500){_a(e),id(e);try{let t=await e.clone().json();if(Jo(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function ud(e,t,n){if(e.status!==t){bw(e);let r;throw(r=await gw(e))?(await e.body?.cancel(),new zn("server responded with an error in the response body",{cause:r,response:e})):D(`"response" is not a conform ${n} response (unexpected HTTP status code)`,oi,e)}}function yw(e){if(!ha.has(e))throw K('"options.DPoP" is not a valid DPoPHandle',xe)}function pa(e){return e.headers.get("content-type")?.split(";")[0]}async function ld(e,t,n,r,o,i,s){return await n(e,t,o,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[Kt]||fetch)(r.href,{body:o,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:td(r,s?.signal)})}async function ww(e,t,n,r,o,i){let s=ti(e,"token_endpoint",t.use_mtls_endpoint_aliases,i?.[Jt]!==!0);o.set("grant_type",r);let a=ca(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(yw(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await ld(e,t,n,s,o,a,i);return i?.DPoP?.cacheNonce(c,s),c}var fd=new WeakMap,_w=new WeakMap;function ni(e){if(!e.id_token)return;let t=fd.get(e);if(!t)throw K('"ref" was already garbage collected or did not resolve from the proper sources',xe);return t}async function dd(e,t,n,r,o,i){if(Xo(e),Qo(t),!Dr(n,Response))throw K('"response" must be an instance of Response',$e);await ud(n,200,"Token Endpoint"),_a(n);let s=await bd(n);if(be(s.access_token,'"response" body "access_token" property',F,{body:s}),be(s.token_type,'"response" body "token_type" property',F,{body:s}),s.token_type=s.token_type.toLowerCase(),s.expires_in!==void 0){let a=typeof s.expires_in!="number"?parseFloat(s.expires_in):s.expires_in;Ir(a,!0,'"response" body "expires_in" property',F,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&be(s.refresh_token,'"response" body "refresh_token" property',F,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw D('"response" body "scope" property must be a string',F,{body:s});if(s.id_token!==void 0){be(s.id_token,'"response" body "id_token" property',F,{body:s});let a=["aud","exp","iat","iss","sub"];t.require_auth_time===!0&&a.push("auth_time"),t.default_max_age!==void 0&&(Ir(t.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),r?.length&&a.push(...r);let{claims:c,jwt:u}=await $w(s.id_token,Dw.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),ua(t),la(t),o).then(Aw.bind(void 0,a)).then(Ew.bind(void 0,e)).then(xw.bind(void 0,t.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw D('ID Token "aud" (audience) claim includes additional untrusted audiences',We,{claims:c,claim:"aud"});if(c.azp!==t.client_id)throw D('unexpected ID Token "azp" (authorized party) claim value',We,{expected:t.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&Ir(c.auth_time,!0,'ID Token "auth_time" (authentication time)',F,{claims:c}),_w.set(n,u),fd.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](n,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new At("unsupported `token_type` value",{cause:{body:s}});return s}function bw(e){let t;if(t=mw(e))throw new $n("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}function xw(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw D('unexpected JWT "aud" (audience) claim value',We,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw D('unexpected JWT "aud" (audience) claim value',We,{expected:e,claims:t.claims,claim:"aud"});return t}function Ew(e,t){let n=e[ba]?.(t)??e.issuer;if(t.claims.iss!==n)throw D('unexpected JWT "iss" (issuer) claim value',We,{expected:n,claims:t.claims,claim:"iss"});return t}var ha=new WeakSet;function Sw(e){return ha.add(e),e}var ma=Symbol();async function pd(e,t,n,r,o,i,s){if(Xo(e),Qo(t),!ha.has(r))throw K('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',xe);be(o,'"redirectUri"');let a=qt(r,"code");if(!a)throw D('no authorization code in "callbackParameters"',F);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),i!==ma&&(be(i,'"codeVerifier"'),c.set("code_verifier",i)),ww(e,t,n,"authorization_code",c,s)}var vw={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function Aw(e,t){for(let n of e)if(t.claims[n]===void 0)throw D(`JWT "${n}" (${vw[n]}) claim missing`,F,{claims:t.claims});return t}var na=Symbol(),ra=Symbol();async function hd(e,t,n,r){return typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number"||r?.requireIdToken?Tw(e,t,n,r.expectedNonce,r.maxAge,r[qo],r.recognizedTokenTypes):Rw(e,t,n,r?.[qo],r?.recognizedTokenTypes)}async function Tw(e,t,n,r,o,i,s){let a=[];switch(r){case void 0:r=na;break;case na:break;default:be(r,'"expectedNonce" argument'),a.push("nonce")}switch(o??=t.default_max_age,o){case void 0:o=ra;break;case ra:break;default:Ir(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await dd(e,t,n,a,i,s);be(c.id_token,'"response" body "id_token" property',F,{body:c});let u=ni(c);if(o!==ra){let l=fa()+ua(t),f=la(t);if(u.auth_time+o<l-f)throw D("too much time has elapsed since the last End-User authentication",Cn,{claims:u,now:l,tolerance:f,claim:"auth_time"})}if(r===na){if(u.nonce!==void 0)throw D('unexpected ID Token "nonce" claim value',We,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==r)throw D('unexpected ID Token "nonce" claim value',We,{expected:r,claims:u,claim:"nonce"});return c}async function Rw(e,t,n,r,o){let i=await dd(e,t,n,void 0,r,o),s=ni(i);if(s){if(t.default_max_age!==void 0){Ir(t.default_max_age,!0,'"client.default_max_age"');let a=fa()+ua(t),c=la(t);if(s.auth_time+t.default_max_age<a-c)throw D("too much time has elapsed since the last End-User authentication",Cn,{claims:s,now:a,tolerance:c,claim:"auth_time"})}if(s.nonce!==void 0)throw D('unexpected ID Token "nonce" claim value',We,{expected:void 0,claims:s,claim:"nonce"})}return i}var Pw="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Ow="OAUTH_RESPONSE_BODY_ERROR",ri="OAUTH_UNSUPPORTED_OPERATION",kw="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var Cr="OAUTH_PARSE_ERROR",F="OAUTH_INVALID_RESPONSE";var ga="OAUTH_RESPONSE_IS_NOT_JSON",oi="OAUTH_RESPONSE_IS_NOT_CONFORM",ya="OAUTH_HTTP_REQUEST_FORBIDDEN",wa="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",Cn="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",We="OAUTH_JWT_CLAIM_COMPARISON_FAILED",ii="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Iw="OAUTH_MISSING_SERVER_METADATA",zw="OAUTH_INVALID_SERVER_METADATA";async function md(e,t,n,r,o){Xo(e),Qo(t),be(r,'"token"');let i=ti(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,o?.[Jt]!==!0),s=new URLSearchParams(o?.additionalParameters);s.set("token",r);let a=ca(o?.headers);return a.delete("accept"),ld(e,t,n,i,s,a,o)}async function gd(e){if(!Dr(e,Response))throw K('"response" must be an instance of Response',$e);await ud(e,200,"Revocation Endpoint")}function _a(e){if(e.bodyUsed)throw K('"response" body has been used already',xe)}async function $w(e,t,n,r,o){let{0:i,1:s,length:a}=e.split(".");if(a===5)if(o!==void 0)e=await o(e),{0:i,1:s,length:a}=e.split(".");else throw new At("JWE decryption is not configured",{cause:e});if(a!==3)throw D("Invalid JWT",F,e);let c;try{c=JSON.parse(Qf(aa(i)))}catch(f){throw D("failed to parse JWT Header body as base64url encoded JSON",Cr,f)}if(!Jo(c))throw D("JWT Header must be a top level object",F,e);if(t(c),c.crit!==void 0)throw new At('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(Qf(aa(s)))}catch(f){throw D("failed to parse JWT Payload body as base64url encoded JSON",Cr,f)}if(!Jo(u))throw D("JWT Payload must be a top level object",F,e);let l=fa()+n;if(u.exp!==void 0){if(typeof u.exp!="number")throw D('unexpected JWT "exp" (expiration time) claim type',F,{claims:u});if(u.exp<=l-r)throw D('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',Cn,{claims:u,now:l,tolerance:r,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw D('unexpected JWT "iat" (issued at) claim type',F,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw D('unexpected JWT "iss" (issuer) claim type',F,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw D('unexpected JWT "nbf" (not before) claim type',F,{claims:u});if(u.nbf>l+r)throw D('unexpected JWT "nbf" (not before) claim value',Cn,{claims:u,now:l,tolerance:r,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw D('unexpected JWT "aud" (audience) claim type',F,{claims:u});return{header:c,claims:u,jwt:e}}async function Cw(e){if(e.bodyUsed)throw K("form_post Request instances must contain a readable body",xe,{cause:e});return e.text()}async function yd(e){if(e.method!=="POST")throw K("form_post responses are expected to use the POST method",xe,{cause:e});if(pa(e)!=="application/x-www-form-urlencoded")throw K("form_post responses are expected to use the application/x-www-form-urlencoded content-type",xe,{cause:e});return Cw(e)}function Dw(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw D('unexpected JWT "alg" header parameter',F,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw D('unexpected JWT "alg" header parameter',F,{header:r,expected:t,reason:"authorization server metadata"});return}if(n!==void 0){if(typeof n=="string"?r.alg!==n:typeof n=="function"?!n(r.alg):!n.includes(r.alg))throw D('unexpected JWT "alg" header parameter',F,{header:r,expected:n,reason:"default value"});return}throw D('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}function qt(e,t){let{0:n,length:r}=e.getAll(t);if(r>1)throw D(`"${t}" parameter must be provided only once`,F);return n}var wd=Symbol(),Uw=Symbol();function _d(e,t,n,r){if(Xo(e),Qo(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw K('"parameters" must be an instance of URLSearchParams, or URL',$e);if(qt(n,"response"))throw D('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',F,{parameters:n});let o=qt(n,"iss"),i=qt(n,"state");if(!o&&e.authorization_response_iss_parameter_supported)throw D('response parameter "iss" (issuer) missing',F,{parameters:n});if(o&&o!==e.issuer)throw D('unexpected "iss" (issuer) response parameter value',F,{expected:e.issuer,parameters:n});switch(r){case void 0:case Uw:if(i!==void 0)throw D('unexpected "state" response parameter encountered',F,{expected:void 0,parameters:n});break;case wd:break;default:if(be(r,'"expectedState" argument'),i!==r)throw D(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',F,{expected:r,parameters:n})}if(qt(n,"error"))throw new $r("authorization response from the server is an error",{cause:n});let a=qt(n,"id_token"),c=qt(n,"token");if(a!==void 0||c!==void 0)throw new At("implicit and hybrid flows are not supported");return Sw(new URLSearchParams(n))}async function bd(e,t=id){let n;try{n=await e.json()}catch(r){throw t(e),D('failed to parse "response" body as JSON',Cr,r)}if(!Jo(n))throw D('"response" body must be a top level object',F,{body:n});return n}var Vo=Symbol(),ba=Symbol();var Mr,xd;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(xd="openid-client/v6.8.7",Mr={"user-agent":xd});var je=e=>Ea.get(e),Ea,xa;function Lw(e){return e!==void 0?da(e):(xa||=new WeakMap,(t,n,r,o)=>{let i;return(i=xa.get(n))||(Nw(n.client_secret,'"metadata.client_secret"'),i=da(n.client_secret),xa.set(n,i)),i(t,n,r,o)})}function Nw(e,t){if(typeof e!="string")throw Ye(`${t} must be a string`,Nr);if(e.length===0)throw Ye(`${t} must not be empty`,Lr)}function Bw(){return ad()}var Dn=Kt;var Lr="ERR_INVALID_ARG_VALUE",Nr="ERR_INVALID_ARG_TYPE";function Ye(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}function Sd(){return sd()}var Un=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor)}},sO=new TextDecoder;function ge(e,t,n){return new Un(e,{cause:t,code:n})}function Ur(e){if(e instanceof TypeError||e instanceof Un||e instanceof zn||e instanceof $r||e instanceof $n)throw e;if(e instanceof zr)switch(e.code){case ya:throw ge("only requests to HTTPS are allowed",e,e.code);case wa:throw ge("only requests to HTTP or HTTPS are allowed",e,e.code);case oi:throw ge("unexpected HTTP response status code",e.cause,e.code);case ga:throw ge("unexpected response content-type",e.cause,e.code);case Cr:throw ge("parsing error occured",e,e.code);case F:throw ge("invalid response encountered",e,e.code);case We:throw ge("unexpected JWT claim value encountered",e,e.code);case ii:throw ge("unexpected JSON attribute value encountered",e,e.code);case Cn:throw ge("JWT timestamp claim value failed validation",e,e.code);default:throw ge(e.message,e,e.code)}if(e instanceof At)throw ge("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw ge("runtime operation error",e,ri);case"NotSupportedError":throw ge("runtime unsupported operation",e,ri);case"TimeoutError":throw ge("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw ge("operation aborted",e,"OAUTH_ABORT")}throw new Un("something went wrong",{cause:e})}function jw(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[Ad]=!0,!0):!1}function Zw(e,t){return!!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function vd(e,t,n,r,o){let i=await Fw(e,o),s=new Mn(i,t,n,r),a=je(s);if(o?.[Dn]&&(a.fetch=o[Dn]),o?.timeout&&(a.timeout=o.timeout),o?.execute)for(let c of o.execute)c(s);return s}async function Fw(e,t){if(!(e instanceof URL))throw Ye('"server" must be an instance of URL',Nr);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),i=await(n?rd(e,{algorithm:t?.algorithm,[Kt]:t?.[Dn],[Jt]:t?.execute?.includes(Ed),signal:o,headers:new Headers(Mr)}):(t?.[Dn]||fetch)((ei(e,!t?.execute?.includes(Ed)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...Mr}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(s=>od(Vo,s)).catch(Ur);return n&&new URL(i.issuer).href!==e.href&&(jw(e,i,t)||Zw(e,t)||(()=>{throw new Un("discovered metadata issuer does not match the expected issuer",{code:ii,cause:{expected:e.href,body:i,attribute:"issuer"}})})()),i}function Hw(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function Gw(e){Object.defineProperties(e,Hw(e))}var Ad=Symbol(),Mn=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw Ye('"clientId" must be a non-empty string',Nr);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw Ye('"clientId" and "metadata.client_id" must be the same',Lr);let i={...structuredClone(r),client_id:n};i[Wo]=r?.[Wo]??0,i[Yo]=r?.[Yo]??30;let s;o?s=o:typeof i.client_secret=="string"&&i.client_secret.length?s=Lw(i.client_secret):s=Bw();let a=Object.freeze(i),c=structuredClone(t);Ad in t&&(c[ba]=({claims:{tid:l}})=>t.issuer.replace("{tenantid}",l));let u=Object.freeze(c);Ea||=new WeakMap,Ea.set(this,{__proto__:null,as:u,c:a,auth:s,tlsOnly:!0,jwksCache:{}})}serverMetadata(){let t=structuredClone(je(this).as);return Gw(t),t}clientMetadata(){return structuredClone(je(this).c)}get timeout(){return je(this).timeout}set timeout(t){je(this).timeout=t}get[Dn](){return je(this).fetch}set[Dn](t){je(this).fetch=t}};Object.freeze(Mn.prototype);function qw(e){let t;if(e.expires_in!==void 0){let n=new Date;n.setSeconds(n.getSeconds()+e.expires_in),t=n.getTime()}return{expiresIn:{__proto__:null,value(){if(t){let n=Date.now();return t>n?Math.floor((t-n)/1e3):0}}},claims:{__proto__:null,value(){return ni(e)}}}}function Jw(e){Object.defineProperties(e,qw(e))}function Ed(e){je(e).tlsOnly=!1}function Kw(e){return e=new URL(e),e.search="",e.hash="",e.href}function Vw(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}async function Sa(e,t,n,r,o){if(va(e),o?.flag!==si&&!(t instanceof URL)&&!Vw(t,"Request"))throw Ye('"currentUrl" must be an instance of URL, or Request',Nr);let i,s,{as:a,c,auth:u,fetch:l,tlsOnly:f,jarm:d,hybrid:g,nonRepudiation:w,timeout:E,decrypt:v,implicit:h}=je(e);if(o?.flag===si)i=o.authResponse,s=o.redirectUri;else{if(!(t instanceof URL)){let A=t;switch(t=new URL(t.url),A.method){case"GET":break;case"POST":let k=new URLSearchParams(await yd(A));if(g)t.hash=k.toString();else for(let[I,z]of k.entries())t.searchParams.append(I,z);break;default:throw Ye("unexpected Request HTTP method",Lr)}}switch(s=Kw(t),!0){case!!d:i=await d(t,n?.expectedState);break;case!!g:i=await g(t,n?.expectedNonce,n?.expectedState,n?.maxAge);break;case!!h:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=_d(a,c,t.searchParams,n?.expectedState)}catch(A){Ur(A)}}}let b=await pd(a,c,u,i,s,n?.pkceCodeVerifier||ma,{additionalParameters:r,[Kt]:l,[Jt]:!f,DPoP:o?.DPoP,headers:new Headers(Mr),signal:Rd(E)}).catch(Ur);(typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number")&&(n.idTokenExpected=!0);let _=hd(a,c,b,{expectedNonce:n?.expectedNonce,maxAge:n?.maxAge,requireIdToken:n?.idTokenExpected,[qo]:v}),x;try{x=await _}catch(A){if(Ww(A,o))return Sa(e,void 0,n,r,{...o,flag:si,authResponse:i,redirectUri:s});Ur(A)}return x.id_token&&await w?.(b),Jw(x),x}function Td(e,t){va(e);let{as:n,c:r,tlsOnly:o,hybrid:i,jarm:s,implicit:a}=je(e),c=ti(n,"authorization_endpoint",!1,o);if(t=new URLSearchParams(t),t.has("client_id")||t.set("client_id",r.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",i?"code id_token":a?"id_token":"code"),a&&!t.has("nonce"))throw Ye("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",Lr);s&&t.set("response_mode","jwt")}for(let[u,l]of t.entries())c.searchParams.append(u,l);return c}function va(e){if(!(e instanceof Mn))throw Ye('"config" must be an instance of Configuration',Nr);if(Object.getPrototypeOf(e)!==Mn.prototype)throw Ye("subclassing Configuration is not allowed",Lr)}function Rd(e){return e?AbortSignal.timeout(e*1e3):void 0}function Ww(e,t){return t?.DPoP&&t.flag!==si?cd(e):!1}var si=Symbol();async function Pd(e,t,n){va(e);let{as:r,c:o,auth:i,fetch:s,tlsOnly:a,timeout:c}=je(e);return md(r,o,i,t,{[Kt]:s,[Jt]:!a,additionalParameters:new URLSearchParams(n),headers:new Headers(Mr),signal:Rd(c)}).then(gd).catch(Ur)}var Od="oauth2:",Br="graffiti-auth-oauth2-data",ai=class{eventTarget=new EventTarget;constructor(){let t=this.completeOauth();(async()=>{await new Promise(r=>setTimeout(r,0)),await t;let n=new CustomEvent("initialized");this.eventTarget.dispatchEvent(n)})()}async login(...t){try{await this.login_(...t)}catch(n){let r=n instanceof Error?n:new Error("Unknown error"),o={loginId:t[1],error:r};this.eventTarget.dispatchEvent(new CustomEvent("login",{detail:o}))}}async login_(t,n,r){let o=await this.getAuthorizationConfiguration(t),i=r.map(encodeURIComponent).join(" "),s=Sd(),a,c;if(typeof window<"u"){a=window.location.href;let f={loginId:n,redirectUri:a,authorizationEndpoint:t,state:s,serviceEndpoints:r};window.localStorage.setItem(Br,JSON.stringify(f))}else{let d=(await import("node:http").catch(w=>{throw new Error("Unrecognized environment: cannot find window or node:http")})).createServer();try{await new Promise((w,E)=>{d.once("error",E),d.listen(0,"::1",w)})}catch{try{d.close()}catch{}throw new Error("Failed to start local oauth callback server.")}let g=d.address();if(!g){try{d.close()}catch{}throw new Error("Failed to get local oauth callback server address.")}a=typeof g=="string"?`http://${g}`:`http://${g.family==="IPv6"?`[${g.address}]`:g.address}:${g.port}`,c=new Promise((w,E)=>{let v=setTimeout(()=>{try{d.close()}catch{}E("Oauth callback timed out.")},3e5),h=new Set;d.on("connection",_=>{h.add(_),_.on("close",()=>{h.delete(_)})});let b=async(_,x)=>{try{let A=new URL(_.url??"/",a);await this.onCallbackUrl({loginId:n,callbackUrl:A,configuration:o,expectedState:s,serviceEndpoints:r}),x.statusCode=200,x.setHeader("Content-Type","text/plain"),x.end("You may now close this window.")}catch(A){throw x.statusCode=500,x.setHeader("Content-Type","text/plain"),x.end("Error processing OAuth callback."),A}finally{clearTimeout(v),d.off("request",b);for(let A of h)A.destroy();d.close(()=>w())}};d.on("request",b)})}let u=new URL(a);u.hash="",u.search="";let l=Td(o,{scope:i,redirect_uri:u.toString(),state:s});typeof window<"u"?window.location.href=l.toString():(console.log("Please open the following URL in your browser:"),console.log(l.toString()),await c)}completeOauth(){if(typeof window>"u")return;let t=window.localStorage.getItem(Br);if(!t)return;let n;try{n=JSON.parse(t)}catch{console.error("Invalid OAuth2 login data in local storage."),window.localStorage.removeItem(Br);return}let r=Yw.safeParse(n);if(!r.success){console.error("Invalid OAuth2 login data structure in local storage.",r.error),window.localStorage.removeItem(Br);return}let{loginId:o,redirectUri:i,authorizationEndpoint:s,state:a,serviceEndpoints:c}=r.data;try{let u=new URL(i),l=new URL(window.location.href);if(u.pathname!==l.pathname)return;let f=l.searchParams;return!f.has("code")&&!f.has("error")?void 0:(window.history.replaceState({},document.title,u.toString()),window.localStorage.removeItem(Br),new Promise(d=>setTimeout(d,0)).then(()=>this.getAuthorizationConfiguration(s)).then(d=>this.onCallbackUrl({loginId:o,callbackUrl:l,configuration:d,expectedState:a,serviceEndpoints:c})).catch(d=>{let g=d instanceof Error?d:new Error("Unknown error"),w={loginId:o,error:g};this.eventTarget.dispatchEvent(new CustomEvent("login",{detail:w}))}))}catch(u){console.error(u)}}async onCallbackUrl(t){let{loginId:n,callbackUrl:r,configuration:o,expectedState:i,serviceEndpoints:s}=t,a=await Sa(o,r,{expectedState:i}),c=a.access_token,l=a.scope?.split(" ").map(decodeURIComponent)||s;if(!s.every(d=>l.includes(d)))throw new Error("Not all requested service endpoints were granted.");let f=new CustomEvent("login",{detail:{loginId:n,token:c}});this.eventTarget.dispatchEvent(f)}async logout(t,n,r){try{await this.logout_(t,n,r)}catch(o){let i=o instanceof Error?o:new Error("Unknown error"),s={logoutId:n,error:i};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:s}))}}async logout_(t,n,r){let o=await this.getAuthorizationConfiguration(t);await Pd(o,r);let i={logoutId:n};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:i}))}async getAuthorizationConfiguration(t){if(!t.startsWith(Od))throw new Error(`Unrecognized authorization endpoint method: ${t}`);let n=t.slice(Od.length),r;try{r=new URL(n)}catch{throw new Error("Invalid issuer URL.")}return await vd(r,"graffiti-client")}},kd=Eu(Se({loginId:B()}),ct([Se({token:B(),error:X(xu())}),Se({error:on(Error)})])),Id=Se({logoutId:B(),error:X(on(Error))}),zd=X(Ue(Se({error:X(on(Error))}))),Yw=Se({loginId:B(),redirectUri:Z(),authorizationEndpoint:Z(),state:B(),serviceEndpoints:q(Z())});var Xw="https://";function Ce(e){if(!e.startsWith(Xw))throw new Error("Unrecognized storage bucket endpoint type")}async function ci(e){Ce(e);let t=`${e}/auth`,n=await fetch(t);if(!n.ok)throw new Error("Failed to get storage bucket authorization endpoint");return await n.text()}var Vt=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorUnauthorized",Object.setPrototypeOf(this,e.prototype)}};async function Xe(...e){let t=await fetch(...e);if(!t.ok){let n;try{n=await t.text()}catch{n=t.statusText}throw t.status===401?new Vt(n):t.status===403?new mt(n):t.status===404?new Q(n):t.status===410?new Me(n):t.status===413?new gt(n):new Error(n)}return t}var Qw=32,e_=1024*1024,t_=2;function $d(e){return Math.min(Qw,Math.floor(e_/e))}var ui=class{getAuthorizationEndpoint=ci;queues=new Map;unsupportedBatchEndpoints=new Set;async put(t,n,r,o){Ce(t);let i=`${t}/value/${encodeURIComponent(n)}`;await Xe(i,{method:"PUT",headers:{"Content-Type":"application/octet-stream",Authorization:`Bearer ${o}`},body:r.slice()})}async delete(t,n,r){Ce(t);let o=`${t}/value/${encodeURIComponent(n)}`;await Xe(o,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}async get(t,n,r){return Ce(t),r!==void 0&&Number.isSafeInteger(r)&&r>0&&$d(r)>=2&&!this.unsupportedBatchEndpoints.has(t)?new Promise((o,i)=>{let s=this.queues.get(t);s||(s=new Map,this.queues.set(t,s));let a=s.get(r);a||(a={requests:[]},s.set(r,a)),a.requests.push({key:n,resolve:o,reject:i}),a.requests.length===$d(r)?this.flush(t,r,a):a.timer===void 0&&(a.timer=setTimeout(()=>this.flush(t,r,a),t_))}):this.getOne(t,n,r)}flush(t,n,r){r.timer!==void 0&&clearTimeout(r.timer);let o=r.requests,i=this.queues.get(t);i.delete(n),i.size===0&&this.queues.delete(t),o.length===1||this.unsupportedBatchEndpoints.has(t)?o.forEach(({key:s,resolve:a,reject:c})=>{this.getOne(t,s,n).then(a,c)}):this.getBatch(t,n,o)}async getBatch(t,n,r){try{let o=await fetch(`${t}/values`,{method:"POST",headers:{"Content-Type":"application/cbor",Accept:"application/cbor"},body:pe({keys:r.map(({key:s})=>s),maxValueBytes:n}).slice()});if(o.status===404){this.unsupportedBatchEndpoints.add(t),await Promise.all(r.map(async({key:s,resolve:a,reject:c})=>{try{a(await this.getOne(t,s,n))}catch(u){c(u)}}));return}if(!o.ok)throw new Error(await o.text());let i=Ne(await o.arrayBuffer());if(!i||typeof i!="object"||!("results"in i)||!Array.isArray(i.results)||i.results.length!==r.length)throw new Error("Invalid storage batch response");i.results.forEach((s,a)=>{let{resolve:c,reject:u}=r[a];!s||typeof s!="object"||!("status"in s)?u(new Error("Invalid storage batch result")):s.status===200&&"value"in s&&s.value instanceof Uint8Array&&s.value.byteLength<=n?c(s.value):s.status===404?u(new Q("Value not found")):s.status===413?u(new gt("Value exceeds maximum byte limit")):u(new Error("Invalid storage batch result"))})}catch(o){r.forEach(({reject:i})=>i(o))}}async getOne(t,n,r){let o=`${t}/value/${encodeURIComponent(n)}`,i=await Xe(o),s=i.body?.getReader();if(!s)throw new Error("Failed to read value from storage bucket");let a=i.headers.get("Content-Length"),c=a?Number(a):void 0;if(!!c&&!!Number.isFinite(c)&&c>=0){let w=c;if(r!==void 0&&w>r)throw new Error("Value exceeds maximum byte limit");let E=new Uint8Array(w),v=0,h=!1;try{for(;v<=E.length;){let{done:b,value:_}=await s.read();if(b){h=!0;break}if(!_||_.length===0)continue;let x=v+_.length;if(x>E.length)throw new Error("Received more data than expected");E.set(_,v),v=x}}finally{s.releaseLock()}if(!h)throw new Error("Failed to read complete value from storage bucket");return v===w?E:E.slice(0,v)}let l=[],f=0;try{for(;;){let{done:w,value:E}=await s.read();if(w)break;if(!(!E||E.length===0)){if(f+=E.length,r!==void 0&&f>r)throw new Error("Value exceeds maximum byte limit");l.push(E.slice())}}}finally{s.releaseLock()}let d=new Uint8Array(f),g=0;for(let w of l)d.set(w,g),g+=w.length;return d}async*export(t,n){Ce(t);let r=`${t}/export`,o;for(;;){let s=await(await Xe(o?`${r}?cursor=${encodeURIComponent(o)}`:r,{headers:{Authorization:`Bearer ${n}`}})).blob(),a=Ne(await s.arrayBuffer()),c=n_.parse(a);for(let u of c.keys)yield{key:u};if(c.cursor)o=c.cursor;else break}}},n_=Se({keys:q(B()),cursor:X(Ue(B()))});var r_=ye({value:we({}),channels:q(B()),allowed:X(Ue(q(Z()))),url:Z(),actor:Z()}),Aa=Mt(e=>e instanceof Uint8Array),Cd=q(Aa),Ln="t",Ze="o",Nn="m",Dd=ye({[Ln]:Cd,[Ze]:r_,[Nn]:Aa}),jr="id",ft="m",Zr="l",li=ye({[jr]:B(),[ft]:Dd,[Zr]:bu()}),Ud=ye({id:B()}),Md=ye({results:q(li),hasMore:rn(),cursor:B()});async function Ta(){try{return globalThis.indexedDB?(await new Promise((e,t)=>{let n=indexedDB.open("__idb_probe__",1);n.onupgradeneeded=()=>n.result.createObjectStore("k"),n.onsuccess=()=>{n.result.close(),e()},n.onerror=()=>t(n.error)}),!0):!1}catch{return!1}}function Fr(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}async function Nd(e,t,n,r,o=0){let i=r.messageIds.slice(o);return Promise.all(i.map(async s=>{let a=await e.messages.get(Fr(t,s));if(!a){try{await e.messageIds.del(n)}catch{}throw new Error("Cache out of sync - perhaps clear browser storage")}return a}))}async function Bd(e,t,n,r,o){await e.messages.setMany(o.messages.map(s=>[Fr(t,s[jr]),s]));let i={cursor:o.cursor,version:r?.version??crypto.randomUUID(),messageIds:[...r?.messageIds??[],...o.messages.map(s=>s[jr])],generation:crypto.randomUUID(),hasMore:o.hasMore,waitTil:o.waitTil};return await e.messageIds.set(n,i),i}async function jd(e,t,n){let r=pe({inboxUrl:e,type:t,body:n??null});return crypto.subtle.digest("SHA-256",new Uint8Array(r)).then(o=>Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join(""))}async function Ld(){await new Promise(e=>{let t=indexedDB.deleteDatabase("graffiti-inbox-cache");t.onsuccess=()=>e(),t.onerror=()=>e(),t.onblocked=()=>e()})}async function Zd(){if(await Ta()){let{openDB:n}=await import("./build-KAK33G4E.js"),r=await n("graffiti-inbox-cache",1,{upgrade(o){o.objectStoreNames.contains("m")||o.createObjectStore("m"),o.objectStoreNames.contains("q")||o.createObjectStore("q")}});return{messages:{get:async o=>{try{return r.get("m",o)}catch(i){console.error("Error getting message from cache:",i),console.error("resetting cache..."),await Ld();return}},set:async(o,i)=>{await r.put("m",i,o)},setMany:async o=>{if(o.length===0)return;let i=r.transaction("m","readwrite");await Promise.all([...o.map(([s,a])=>i.store.put(a,s)),i.done])},del:o=>r.delete("m",o)},messageIds:{get:async o=>{try{return await r.get("q",o)}catch(i){console.error("Error getting message IDs from cache:",i),console.error("resetting cache..."),await Ld();return}},set:async(o,i)=>{await r.put("q",i,o)},del:o=>r.delete("q",o)}}}let e=new Map,t=new Map;return{messages:{get:async n=>e.get(n),set:async(n,r)=>{e.set(n,r)},setMany:async n=>{for(let[r,o]of n)e.set(r,o)},del:async n=>{e.delete(n)}},messageIds:{get:async n=>t.get(n),set:async(n,r)=>{t.set(n,r)},del:async n=>{t.delete(n)}}}}var o_=3e4,i_=3e4,fi=class{getAuthorizationEndpoint=ci;cache_=null;get cache(){return this.cache_||(this.cache_=Zd()),this.cache_}async send(t,n){Ce(t);let r=`${t}/send`,i=await(await Xe(r,{method:"PUT",headers:{"Content-Type":"application/cbor"},body:new Uint8Array(pe({m:n}))})).blob(),s=Ne(await i.arrayBuffer());return Ud.parse(s).id}async get(t,n,r){let o=Fr(t,n),i=await this.cache,s=await i.messages.get(o);if(s!==void 0)return s;let a=`${t}/message/${n}`,c=null;try{c=await Xe(a,{method:"GET",headers:{...r?{Authorization:`Bearer ${r}`}:{}}})}catch(d){if(d instanceof Q)return await i.messages.set(o,null),null;throw d}let u=await c.blob(),l=Ne(await u.arrayBuffer()),f=li.parse(l);return await i.messages.set(o,f),f}async label(t,n,r,o){if(Ce(t),o){let c=`${t}/label/${n}`;await Xe(c,{method:"PUT",headers:{"Content-Type":"application/cbor",Authorization:`Bearer ${o}`},body:new Uint8Array(pe({l:r}))})}let i=await this.cache,s=Fr(t,n),a=await i.messages.get(s);a&&await i.messages.set(s,{...a,l:r})}async fetchMessageBatch(t,n,r,o,i,s){let a=AbortSignal.timeout(o_),c=await Xe(`${t}/${n}${i?`?cursor=${encodeURIComponent(i)}`:""}`,{method:"POST",headers:{"Content-Type":"application/cbor",...o?{Authorization:`Bearer ${o}`}:{}},body:r,signal:s?AbortSignal.any([s,a]):a}),u=c.headers.get("Retry-After"),l=u?parseInt(u):void 0,f=l&&Number.isFinite(l)?Date.now()+l*1e3:void 0;return{response:c,waitTil:f}}async withQueryLock(t,n,r,o){if(!n)return r();let i=AbortSignal.timeout(i_),s=!1;try{return await window.navigator.locks.request(`graffiti:inbox:${t}`,{mode:"exclusive",signal:o?AbortSignal.any([o,i]):i},async()=>(s=!0,r()))}catch(a){throw!s&&i.aborted?new Error("Timed out waiting for another tab's inbox query",{cause:a}):a}}async*messageStreamer(t){let{inboxUrl:n,inboxToken:r}=t,o=t.kind==="export"?"export":"query",i=t.kind==="query"?t.schema:t.kind==="continue"?t.cursor.objectSchema:{},s=await so(i),a=t.kind==="query"?t.body:void 0,c=t.kind==="continue"?t.cursor.messageIdsCacheKey:await jd(n,o,a),u=t.kind==="continue"?t.cursor.version:void 0,l=await this.cache,f=typeof window<"u"&&await Ta(),d=await l.messageIds.get(c),g=d?.generation,w=d?.version,E=t.kind==="continue"?t.cursor.numSeen:0,v=!0,h=async _=>{for(;;){_?.throwIfAborted();let x=await this.withQueryLock(c,f,async()=>{_?.throwIfAborted();let A=await l.messageIds.get(c);if(u!==void 0&&u!==A?.version)throw new Me("Cursor is stale");if(A?.version!==w){if(!v)throw new Me("Cursor is stale");E=0}if(A?.generation&&A.generation!==g)return{query:A};if(A?.waitTil!==void 0&&A.waitTil>Date.now())return{waitTil:A.waitTil};let k;try{k=await this.fetchMessageBatch(n,o,v?a:void 0,r,A?.cursor,_)}catch(S){if(!(S instanceof Me&&A?.cursor)){if(v&&!_?.aborted)return{initialFetchError:S};throw S}if(!v||(await l.messageIds.del(c),u!==void 0))throw S;A=void 0,E=0,k=await this.fetchMessageBatch(n,o,a,r,void 0,_)}let I=Ne(new Uint8Array(await k.response.arrayBuffer())),{results:z,hasMore:V,cursor:J}=Md.parse(I),m=z.map(S=>{let U=S[ft][Ze];if(!s(U))throw new Error("Server returned data that does not match schema");return{...S,[ft]:{...S[ft],[Ze]:U}}});return A=await Bd(l,n,c,A,{messages:m,cursor:J,hasMore:V,waitTil:k.waitTil}),{query:A}},_);if("initialFetchError"in x)throw console.error("Unexpected error in stream, waiting 5 seconds before continuing..."),await new Promise(A=>setTimeout(A,5e3)),x.initialFetchError;if("waitTil"in x){await a_(x.waitTil);continue}return x.query}},b;for(;;){let _=b?await b:await h().then(z=>({query:z}),z=>({error:z}));if(b=void 0,"error"in _)throw _.error;let x=_.query,A=await Nd(l,n,c,x,E);E=x.messageIds.length,g=x.generation,w=x.version,v=!1;let k=new AbortController;x.hasMore&&(b=h(k.signal).then(z=>({query:z}),z=>({error:z})));let I=!1;try{for(let z of A)yield z;I=!0}finally{I||k.abort()}if(!x.hasMore){let z={numSeen:E,version:x.version,messageIdsCacheKey:c,objectSchema:i};return JSON.stringify(z)}}}query(t,n,r,o){Ce(t);let i=new Uint8Array(pe({tags:n,schema:r}));return this.messageStreamer({kind:"query",inboxUrl:t,body:i,schema:r,inboxToken:o})}continueQuery(t,n,r){Ce(t);let o=JSON.parse(n),i=s_.parse(o);return this.messageStreamer({kind:"continue",inboxUrl:t,cursor:i,inboxToken:r})}export(t,n){return Ce(t),this.messageStreamer({kind:"export",inboxUrl:t,inboxToken:n})}},s_=ye({messageIdsCacheKey:B(),version:B(),numSeen:nn().check(Ut()),objectSchema:ct([we({}),rn()])});async function a_(e){if(e!==void 0){let t=e-Date.now();t>0&&await new Promise(n=>setTimeout(n,t))}}var Bn="base64url";var di=class{async encode(t,n){if(t!==Bn)throw new Error(`Unsupported string encoding method: ${t}`);return"u"+btoa(String.fromCodePoint(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")}async decode(t){if(!t.startsWith("u"))throw new Error(`Unsupported string encoding prefix: ${t[0]}`);t=t.slice(1);let n=t.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";return Uint8Array.from(atob(n),r=>r.charCodeAt(0))}};function Fd(){let t=(typeof globalThis=="object"?globalThis.crypto:null)?.subtle;if(typeof t=="object"&&t!=null)return t;throw new Error("crypto.subtle must be defined")}function Hd(e,t,n){let r=async o=>{Qn(o);let i=Fd();return new Uint8Array(await i.digest(e,o))};return r.webCryptoName=e,r.outputLen=n,r.blockLen=t,r.create=()=>{throw new Error("not implemented")},Object.freeze(r)}function c_(e){zu(e);let t=e.webCryptoName;if(typeof t!="string")throw new Error("non-web hash");return t}var Wt=Hd("SHA-256",64,32);var Gd=Hd("SHA-512",128,64),Ra=(()=>{let e=async(t,n,r)=>{let o=Fd();Qn(n,void 0,"key"),Qn(r,void 0,"message");let i=c_(t),s=Iu(r);try{let a=await o.importKey("raw",n,{name:"HMAC",hash:i},!1,["sign"]);return new Uint8Array(await o.sign("HMAC",a,s))}finally{$u(s)}};return e.create=(t,n)=>{throw new Error("not implemented")},e})();var pi="sha2-256",Hr=18,jn=32,hi=class{async register(t,n){if(t!==pi)throw new Error(`Unsupported content address method: ${t}`);let r=await Wt(n),o=new Uint8Array(2+r.length);return o[0]=Hr,o[1]=jn,o.set(r,2),o}async getMethod(t){if(t[0]===Hr&&t[1]===jn&&t.length===2+jn)return pi;throw new Error("Unrecognized content address format.")}};var Yd=Object.freeze,Zn=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,yi=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,mi=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Oa=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,ka=0x6666666666666666666666666666666666666666666666666666666666666658n,gi=Zn-1n,u_=Yd({p:Zn,n:yi,h:8n,a:gi,d:mi,Gx:Oa,Gy:ka}),Gr=32,qd=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,et=(e,t,n="")=>{if(qd(e)&&(t===void 0||e.length===t))return e;let r=qd(e),o=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,s=(n?`"${n}" `:"")+"expected Uint8Array"+o+", got "+i;throw r?new RangeError(s):new TypeError(s)},Ia=(e,t="",n)=>Uint8Array.from(et(e,n,t)),Xd=(e,t)=>e.toString(16).padStart(t,"0"),Qd=e=>{let t="";for(let n of et(e))t+=Xd(n,2);return t},ep=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let n=new Uint8Array(e.length/2);for(let r=0,o=0;r<n.length;r++,o+=2){let i=e.charCodeAt(o),s=e.charCodeAt(o+1);n[r]=((i&15)+(i>>6)*9)*16+(s&15)+(s>>6)*9}return n},qr=(...e)=>{let t=0;for(let o of e)t+=et(o).length;let n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n};var Yt=(e,t,n,r="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},Y=(e,t=Zn)=>(e%=t)>=0n?e:t+e,Jd=(1n<<255n)-1n,O=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&Jd);return t=(t>>255n)*19n+(t&Jd),t%Zn},tp=e=>Y(e,yi),l_=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let n=Y(e,t),r=t,o=0n,i=1n;for(;n!==0n;){let a=r/n,c=r-n*a,u=o-i*a;r=n,n=c,o=i,i=u}if(r!==1n)throw new Error("invert: does not exist");return Y(o,t)},f_=e=>{let t=Ca[e];if(typeof t!="function")throw new Error("hashes."+e+" not set");return t};var za=async(e,...t)=>et(await f_(e)(qr(...t)),64,"digest");var Pa=e=>{if(e instanceof dt)return e;throw new TypeError("Point expected")},np=2n**256n,dt=class e{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,o){let i=np;this.X=Yt(t,0n,i),this.Y=Yt(n,0n,i),this.Z=Yt(r,1n,i),this.T=Yt(o,0n,i),Yd(this)}static CURVE(){return u_}static fromAffine(t){return new e(t.x,t.y,1n,O(t.x*t.y))}static fromBytes(t,n=!1){let r=Ia(t,"point",Gr),o=r[31];r[31]=o&-129;let i=$a(r);n||Yt(i,0n,Zn);let s=O(i*i),a=Y(s-1n),c=O(mi*s+1n),{isValid:u,value:l}=p_(a,c);if(!u)throw new Error("bad point: y not sqrt");let f=!!(o&128);if(!n&&l===0n&&f)throw new Error("bad point: x==0, isLastByteOdd");return f!==!!(l&1n)&&(l=Y(-l)),new e(l,i,1n,O(l*i))}static fromHex(t,n){return e.fromBytes(ep(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=gi,n=mi,r=this;if(r.is0())throw new Error("bad point: ZERO");let{X:o,Y:i,Z:s,T:a}=r,c=O(o*o),u=O(i*i),l=O(s*s),f=O(l*l),d=O(c*t),g=O(l*(d+u)),w=Y(f+O(n*O(c*u)));if(g!==w)throw new Error("bad point: equation left != right (1)");let E=O(o*i),v=O(s*a);if(E!==v)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:n,Y:r,Z:o}=this,{X:i,Y:s,Z:a}=Pa(t);return O(n*a)===O(i*o)&&O(r*a)===O(s*o)}is0(){return this.equals(Xt)}negate(){return new e(Y(-this.X),this.Y,this.Z,Y(-this.T))}double(){let{X:t,Y:n,Z:r}=this,o=gi,i=O(t*t),s=O(n*n),a=O(2n*r*r),c=O(o*i),u=Y(t+n),l=Y(O(u*u)-i-s),f=Y(c+s),d=Y(f-a),g=Y(c-s),w=O(l*d),E=O(f*g),v=O(l*g),h=O(d*f);return new e(w,E,h,v)}add(t){let{X:n,Y:r,Z:o,T:i}=this,{X:s,Y:a,Z:c,T:u}=Pa(t),l=gi,f=mi,d=O(n*s),g=O(r*a),w=O(O(i*f)*u),E=O(o*c),v=Y(O(Y(n+r)*Y(s+a))-d-g),h=Y(E-w),b=Y(E+w),_=Y(g-O(l*d)),x=O(v*h),A=O(b*_),k=O(v*_),I=O(h*b);return new e(x,A,I,k)}subtract(t){return this.add(Pa(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Yt(t,1n,yi),!n&&this.is0()))return Xt;if(t===1n)return this;if(this.equals(Tt))return __(t).p;let r=Xt,o=Tt,i=this;for(let s=0;n?s<256:t>0n;s++)t&1n?r=r.add(i):n&&(o=o.add(i)),i=i.double(),t>>=1n;return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Xt))return{x:0n,y:1n};let o=l_(r,Zn);if(O(r*o)!==1n)throw new Error("invalid inverse");return{x:O(t*o),y:O(n*o)}}toBytes(){let{x:t,y:n}=this.toAffine(),r=rp(n);return r[31]|=t&1n?128:0,r}toHex(){return Qd(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(yi/2n,!1).double().add(this).is0()}},Tt=new dt(Oa,ka,1n,Y(Oa*ka)),Xt=new dt(0n,1n,1n,0n);dt.BASE=Tt;dt.ZERO=Xt;var rp=e=>ep(Xd(Yt(e,0n,np),64)).reverse(),$a=e=>BigInt("0x"+Qd(Uint8Array.from(et(e)).reverse())),Qe=(e,t)=>{let n=e;for(;t-- >0;)n=O(n*n);return n},d_=e=>{let t=O(e*e),n=O(t*e),r=O(Qe(n,2)*n),o=O(Qe(r,1)*e),i=O(Qe(o,5)*o),s=O(Qe(i,10)*i),a=O(Qe(s,20)*s),c=O(Qe(a,40)*a),u=O(Qe(c,80)*c),l=O(Qe(u,80)*c),f=O(Qe(l,10)*i);return O(Qe(f,2)*e)},Kd=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,p_=(e,t)=>{let n=O(t*O(t*t)),r=O(O(n*n)*t),o=d_(O(e*r)),i=O(e*O(n*o)),s=O(t*O(i*i)),a=i,c=O(i*Kd),u=s===e,l=s===Y(-e),f=s===Y(-e*Kd);return u&&(i=a),(l||f)&&(i=c),(Y(i)&1n)===1n&&(i=Y(-i)),{isValid:u||l,value:i}},wi=e=>tp($a(e)),h_=e=>{let t=Ia(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32),o=wi(n),i=Tt.multiply(o),s=i.toBytes();return{head:n,prefix:r,scalar:o,point:i,pointBytes:s}},op=e=>za("sha512Async",et(e,Gr,"secretKey")).then(h_);var ip=e=>op(e).then(t=>t.pointBytes);var sp=async e=>e[1](await za("sha512Async",e[0]));var m_=(e,t,n)=>{let{pointBytes:r,scalar:o}=e,i=wi(t),s=Tt.multiply(i).toBytes();return[qr(s,r,n),u=>{let l=tp(i+wi(u)*o);return et(qr(s,rp(l)),64)}]},ap=async(e,t)=>{let n=Ia(e,"message"),r=await op(t);return sp(m_(r,await za("sha512Async",r.prefix,n),n))};var g_=e=>{if(e===null||typeof e!="object")throw new TypeError("expected valid options object");return e.zip215??!0},y_=(e,t,n,r)=>{e=et(e,64,"signature"),t=et(t,void 0,"message"),n=et(n,Gr,"publicKey");let o=g_(r),i=e.subarray(0,Gr),s=$a(e.subarray(Gr,64)),a,c,u,l=Uint8Array.of(),f=!1;try{a=dt.fromBytes(n,o),c=dt.fromBytes(i,o),u=Tt.multiply(s,!1),l=qr(i,n,t),f=!0}catch{}return[l,g=>{if(!f||!o&&a.isSmallOrder())return!1;let w=wi(g);return c.add(a.multiply(w,!1)).subtract(u).clearCofactor().is0()}]},cp=async(e,t,n,r={})=>sp(y_(e,t,n,r));var Ca={sha512Async:async e=>{let t=globalThis?.crypto?.subtle;if(!t)throw new Error("crypto.subtle must be defined, consider polyfill");return new Uint8Array(await t.digest("SHA-512",qr(e)))},sha512:void 0};var w_=()=>{let e=[],t=Tt,n;for(let r=0;r<33;r++){n=t,e.push(n);for(let o=1;o<128;o++)n=n.add(t),e.push(n);t=n.double()}return e},Vd,Wd=(e,t)=>{let n=t.negate();return e?n:t},__=e=>{let t=Vd||(Vd=w_()),n=Xt,r=Tt;for(let o=0;o<33;o++){let i=Number(e&255n);e>>=8n,i>128&&(i-=256,e+=1n);let s=o*128,a=s+Math.abs(i)-1,c=o%2!==0,u=i<0;i===0?r=r.add(Wd(c,t[s])):n=n.add(Wd(u,t[a]))}if(e!==0n)throw new Error("invalid wnaf");return{p:n,f:r}};Ca.sha512Async=Gd;var Qt="pk:sha2-256+ed25519",Da=0,_i=class{async register(t,n){if(t!==Qt)throw new Error(`Unsupported channel attestation method: ${t}`);let r=await this.channelToPrivateKey(n);return await this.channelPublicIdFromPrivateKey(r)}async getMethod(t){if(t[0]===Da)return Qt;throw new Error("Unrecognized channel attestation method.")}async channelToPrivateKey(t){let n=new TextEncoder().encode(t);return await Wt(n)}async channelPublicIdFromPrivateKey(t){let n=await ip(t),r=new Uint8Array(n.length+1);return r[0]=Da,r.set(n,1),r}async attest(t,n,r){if(t!==Qt)throw new Error(`Unsupported channel attestation method: ${t}`);let o=await this.channelToPrivateKey(r),i=await this.channelPublicIdFromPrivateKey(o),s=new TextEncoder().encode(n);return{attestation:await ap(s,o),channelPublicId:i}}async validate(t,n,r){let o=r[0];if(o!==Da)throw new Error(`Unrecognized channel attestation method prefix: ${o}`);return await cp(t,new TextEncoder().encode(n),r.slice(1))}};var Ua="hmac:sha2-256",up=0,bi=class{async attest(t,n){if(t!==Ua)throw new Error(`Unsupported allowed attestation method: ${t}`);let r=Lt(),o=await Ra(Wt,r,new TextEncoder().encode(n)),i=new Uint8Array(r.length+3);return i[0]=up,i[1]=Hr,i[2]=jn,i.set(r,3),{attestation:o,ticket:i}}async validate(t,n,r){let o=r[0],i=r[1],s=r[2];if(o!==up||i!==Hr||s!==jn)throw new Error("Unrecognized allowed ticket format");let a=await Ra(Wt,r.slice(3),new TextEncoder().encode(n));return t.length!==a.length?!1:a.every((c,u)=>t[u]===c)}};var Ma="did:web:",xi=class{constructor(t){this.services=t}services;actorToHandle=async t=>{let r=(await this.services.dids.resolve(t)).alsoKnownAs?.find(s=>s.startsWith(Ma));if(!r)throw new Q(`Handle for actor DID ${t} not found`);let o=r.slice(Ma.length),i=await this.services.dids.resolve(r);if(!i.alsoKnownAs||!i.alsoKnownAs.includes(t))throw new Error(`Handle ${o} does not match actor ${t}`);return o};handleToActor=async t=>{let n=`${Ma}${t}`,o=(await this.services.dids.resolve(n)).alsoKnownAs?.at(0);if(!o)throw new Q(`Actor for handle DID ${n} not found`);let i=await this.services.dids.resolve(o);if(!i.alsoKnownAs||!i.alsoKnownAs.includes(n))throw new Error(`Actor ${o} does not match handle ${t}`);return o}};function Ei(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)r!=="__proto__"&&(e[r]=n[r])}return e}var b_={read:function(e){return e[0]==='"'&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function La(e,t){function n(o,i,s){if(!(typeof document>"u")){s=Ei({},t,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),o=encodeURIComponent(o).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var c in s)s[c]&&(a+="; "+c,s[c]!==!0&&(a+="="+s[c].split(";")[0]));return document.cookie=o+"="+e.write(i,o)+a}}function r(o){if(!(typeof document>"u"||arguments.length&&!o)){for(var i=document.cookie?document.cookie.split("; "):[],s={},a=0;a<i.length;a++){var c=i[a].split("="),u=c.slice(1).join("=");try{var l=decodeURIComponent(c[0]);if(l in s||(s[l]=e.read(u,l)),o===l)break}catch{}}return o?s[o]:s}}return Object.create({set:n,get:r,remove:function(o,i){n(o,"",Ei({},i,{expires:-1}))},withAttributes:function(o){return La(this.converter,Ei({},this.attributes,o))},withConverter:function(o){return La(Ei({},this.converter,o),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(e)}})}var Si=La(b_,{path:"/"});var x_=365;function lp(e,t){Si.set(e,t,dp())}function fp(e){return Si.get(e)}function Na(e){Si.remove(e,dp())}function dp(){let e={expires:x_,path:"/",sameSite:"lax"};return typeof window<"u"&&window.location.protocol==="https:"&&(e.sameSite="none",e.secure=!0),e}var Ri="GraffitiInbox",Oi="GraffitiStorageBucket",Fa="#graffitiPersonalInbox",ki="#graffitiStorageBucket",E_="#graffitiSharedInbox_",Pi=class{constructor(t){this.services=t;let n=new Promise(o=>{this.services.authorization.eventTarget.addEventListener("initialized",i=>{if(!(i instanceof CustomEvent))return;let s=zd.safeParse(i.detail);if(!s.success)return;let a=s.data?.error;a&&console.error(a),o()})});this.services.authorization.eventTarget.addEventListener("login",this.onLogin.bind(this)),this.services.authorization.eventTarget.addEventListener("logout",this.onLogout.bind(this));let r;if(typeof window<"u"){let o=new URLSearchParams(window.location.search).get("actor");if(o)try{let i=decodeURIComponent(o),s=new URL(window.location.toString());s.searchParams.delete("actor"),window.history.replaceState({},"",s.toString()),r=this.login(i)}catch(i){console.error("Error decoding actor:",i)}}(async()=>{await new Promise(i=>setTimeout(i,0)),await r;for(let i of this.loggedInSessions){let s=new CustomEvent("login",{detail:{session:{actor:i.actor}}});this.sessionEvents.dispatchEvent(s)}await n;let o=new CustomEvent("initialized");this.sessionEvents.dispatchEvent(o)})()}services;sessionEvents=new EventTarget;inProgressLogin=void 0;inProgressLogout=void 0;async login(t){try{await this.login_(t)}catch(n){let r=new CustomEvent("login",{detail:{error:n instanceof Error?n:new Error(String(n)),session:{actor:t}}});this.sessionEvents.dispatchEvent(r)}}async login_(t){if(this.loggedInSessions.find(_=>_.actor===t)){this.sessionEvents.dispatchEvent(new CustomEvent("login",{detail:{session:{actor:t}}}));return}let o=(await this.services.dids.resolve(t)).service;if(!o)throw new Error(`No services found in actor document for ${t}`);let i=o.find(_=>_.id===ki&&_.type===Oi),s=o.find(_=>_.id===Fa&&_.type===Ri),a=o.filter(_=>_.id.match(new RegExp(`^${E_}\\d+$`))&&_.type===Ri);if(!s||!i||a.length===0)throw new Error(`Required services not found in actor document for ${t}`);let c=ja(i),u=ja(s),l=a.map(ja),f=[{endpoint:c,type:"bucket"},{endpoint:u,type:"personal-inbox"},...l.map(_=>({endpoint:_,type:"shared-inbox"}))],d=await Promise.all(f.map(async({endpoint:_,type:x})=>{let A=await(x==="bucket"?this.services.storageBuckets.getAuthorizationEndpoint(_):this.services.inboxes.getAuthorizationEndpoint(_));return{endpoint:_,authorizationEndpoint:A,type:x}})),g=new Map;d.forEach(({authorizationEndpoint:_,endpoint:x,type:A})=>{g.has(_)||g.set(_,[]),g.get(_).push({endpoint:x,type:A})});let w=[...g.entries()],v={...{actor:t},tokens:[],servicesByAuthorization:w};typeof window<"u"?window.localStorage.setItem(vi,JSON.stringify(v)):this.inProgressLogin=v;let[h,b]=w[0];await this.services.authorization.login(h,t,b.map(_=>_.endpoint))}async onLogin(t){if(!(t instanceof CustomEvent))return;let n=kd.safeParse(t.detail);if(!n.success)return;let r=n.data.loginId;try{await this.onLogin_(n.data)}catch(o){let i=new CustomEvent("login",{detail:{error:o instanceof Error?o:new Error(String(o)),session:{actor:r}}});this.sessionEvents.dispatchEvent(i)}}async onLogin_(t){if(t.error)throw t.error;let n=t.token,r=t.loginId,o;if(typeof window<"u"){let i=window.localStorage.getItem(vi);if(!i)throw new Error("No in-progress login found");let s=JSON.parse(i);o=Za.parse(s)}else{if(!this.inProgressLogin)throw new Error("No in-progress login found");o=this.inProgressLogin}if(o.actor!==r)throw new Error("Actor mismatch in login response - concurrent logins?");if(o.tokens.push(n),o.tokens.length===o.servicesByAuthorization.length){typeof window>"u"?this.inProgressLogin=void 0:window.localStorage.removeItem(vi);let i=o.servicesByAuthorization.flatMap(([u,l],f)=>l.map(d=>({token:o.tokens[f],serviceEndpoint:d.endpoint,authorizationEndpoint:u,type:d.type}))),s={...o,storageBucket:i.find(u=>u.type==="bucket"),personalInbox:i.find(u=>u.type==="personal-inbox"),sharedInboxes:i.filter(u=>u.type==="shared-inbox")},a=this.loggedInSessions;a.push(s),this.loggedInSessions=a;let c=new CustomEvent("login",{detail:{session:{actor:r}}});this.sessionEvents.dispatchEvent(c)}else{typeof window<"u"?window.localStorage.setItem(vi,JSON.stringify(o)):this.inProgressLogin=o;let[i,s]=o.servicesByAuthorization[o.tokens.length];await this.services.authorization.login(i,r,s.map(a=>a.endpoint))}}async logout(t){try{await this.logout_(t)}catch(n){let r=new CustomEvent("logout",{detail:{error:n instanceof Vt?void 0:n instanceof Error?n:new Error(String(n)),actor:t}});this.sessionEvents.dispatchEvent(r)}}async logout_(t){let n=this.loggedInSessions.find(s=>s.actor===t);if(!n)throw new Error(`No session found for actor ${t}`);this.loggedInSessions=this.loggedInSessions.filter(s=>s.actor!==t);let r=n.tokens.pop();if(!r)throw new Error("No tokens found in session");typeof window<"u"?window.localStorage.setItem(Ai,JSON.stringify(n)):this.inProgressLogout=n;let[o,i]=n.servicesByAuthorization[n.tokens.length];await this.services.authorization.logout(o,t,r)}async onLogout(t){if(!(t instanceof CustomEvent))return;let n=Id.safeParse(t.detail);if(!n.success)return;let r=n.data.logoutId;try{await this.onLogout_(n.data)}catch(o){let i=new CustomEvent("logout",{detail:{error:o instanceof Error?o:new Error(String(o)),actor:r}});this.sessionEvents.dispatchEvent(i)}}async onLogout_(t){if(t.error)throw t.error;let n=t.logoutId,r;if(typeof window<"u"){let i=window.localStorage.getItem(Ai);if(!i)throw new Error("No in-progress logout found");let s=JSON.parse(i);r=Za.parse(s)}else{if(!this.inProgressLogout)throw new Error("No in-progress logout found");r=this.inProgressLogout}if(r.actor!==n)throw new Error("Actor mismatch in logout response - concurrent logouts?");let o=r.tokens.pop();if(o){typeof window<"u"?window.localStorage.setItem(Ai,JSON.stringify(r)):this.inProgressLogout=r;let[i,s]=r.servicesByAuthorization[r.tokens.length];await this.services.authorization.logout(i,n,o)}else{typeof window>"u"?this.inProgressLogout=void 0:window.localStorage.removeItem(Ai);let i=new CustomEvent("logout",{detail:{actor:n}});this.sessionEvents.dispatchEvent(i)}}get loggedInSessions(){if(typeof window>"u")return pp;let t=fp(Ti);if(!t)return[];let n;try{n=JSON.parse(t)}catch{return console.error("Error parsing stored session data"),Na(Ti),[]}let r=q(A_).safeParse(n);return r.success?r.data:(console.error("Stored session data is invalid"),Na(Ti),[])}set loggedInSessions(t){if(typeof window>"u"){pp=t;return}lp(Ti,JSON.stringify(t))}resolveSession(t){let n=this.loggedInSessions.find(r=>r.actor===t.actor);if(!n){let r=new CustomEvent("logout",{detail:{actor:t.actor}});throw this.sessionEvents.dispatchEvent(r),new Error("Not logged in")}return n}},pp=[],vi="graffiti-login-in-progress",Ai="graffiti-logout-in-progress",Ti="graffiti-sessions-logged-in",S_=Se({actor:Z()}),Ba=Se({token:B(),serviceEndpoint:Z(),authorizationEndpoint:Z()}),v_=q(me([Z(),q(Se({endpoint:Z(),type:vu(["bucket","personal-inbox","shared-inbox"])}))])),Za=at(S_,{tokens:q(B()),servicesByAuthorization:v_}),A_=at(Za,{storageBucket:Ba,personalInbox:Ba,sharedInboxes:q(Ba)});function ja(e){if(typeof e.serviceEndpoint=="string")return e.serviceEndpoint;throw new Error(`Service endpoint for ${e.id} is not a string`)}var Ii=32*1024,zi=class{constructor(t){this.primitives=t}primitives;async encode(t,n){t=Va(t);let r=[...new Set(t.channels)],o=await Promise.all(r.map(E=>this.primitives.channelAttestations.attest(Qt,n,E))),i=o.map(E=>E.attestation),s=o.map(E=>E.channelPublicId),a={[Ga]:t.value,[qa]:i,[gp]:Lt(32)},c;if(Array.isArray(t.allowed)){let E=await Promise.all(t.allowed.map(async v=>this.primitives.allowedAttestations.attest(Ua,v)));a[Ja]=E.map(v=>v.attestation),c=E.map(v=>v.ticket)}let u=pe(a);if(u.byteLength>Ii)throw new Error("The object is too large");let l=await this.primitives.contentAddresses.register(pi,u),f=await this.primitives.stringEncoder.encode(Bn,l),d=R_(n,f),g=[new TextEncoder().encode(d),...s];return{object:{value:t.value,channels:r,url:d,actor:n,...t.allowed?{allowed:t.allowed}:{}},tags:g,objectBytes:u,allowedTickets:c}}async validate(t,n,r,o){if(r.byteLength>Ii)throw new Error("Object is too big");let{actor:i,contentAddress:s}=Wa(t.url);if(i!==t.actor)throw new Error("Object actor does not match URL actor");let a=n.at(0);if(!a)throw new Error("No object URL tag");if(new TextDecoder().decode(a)!==t.url)throw new Error("Object URL tag does not match object URL");let c=n.slice(1),u=await this.primitives.stringEncoder.decode(s),l=await this.primitives.contentAddresses.getMethod(u),f=await this.primitives.contentAddresses.register(l,r);if(f.length!==u.length||!f.every((_,x)=>_===u[x]))throw new Error("Content address is invalid");let d=Ne(r),g=T_.parse(d),w=g[Ga],E=g[qa],v=g[Ja],h=pe(w),b=pe(t.value);if(h.length!==b.length||!h.every((_,x)=>_===b[x]))throw new Error("Object value does not match storage value");if(E.length!==c.length)throw new Error("Not as many channel attestations and public ids");for(let[_,x]of E.entries()){let A=c[_];if(!await this.primitives.channelAttestations.validate(x,i,A))throw new Error("Invalid channel attestation")}if(t.channels.length){if(t.channels.length!==c.length)throw new Error("Number of claimed channels does not match attestations/public IDs");let _=await this.primitives.channelAttestations.getMethod(c[0]),x=await Promise.all(t.channels.map(A=>this.primitives.channelAttestations.register(_,A)));for(let[A,k]of x.entries()){let I=c[A];if(k.length!==I.length||!k.every((z,V)=>z===I[V]))throw new Error("Channel public id does not match expected")}}if(o){if(!v)throw new Error("Object is public but thought to be private");let _,x,A;if("recipient"in o?(_=[o.recipient],x=[o.allowedTicket],A=v.filter((k,I)=>I===o.allowedIndex)):(_=[...t.allowed??[]],x=o.allowedTickets,A=v),_.length!==t.allowed?.length)throw new Error("Recipient count does not match object allowed list");if(!_.every(k=>t.allowed?.includes(k)))throw new Error("Recipient not in object allowed list");for(let[k,I]of _.entries()){let z=x.at(k),V=A.at(k);if(!z)throw new Error("Missing allowed ticket for recipient");if(!V)throw new Error("Missing allowed attestation for recipient");if(!await this.primitives.allowedAttestations.validate(V,I,z))throw new Error("Invalid allowed attestation for recipient")}}else if(v)throw new Error("Object is private but no recipient info provided")}},Ga="v",qa="c",Ja="a",gp="n",Ha=Mt(e=>e instanceof Uint8Array),T_=ye({[Ga]:we({}),[qa]:q(Ha),[Ja]:X(q(Ha)),[gp]:Ha}),Ka="graffiti:";function hp(e){let t=e.replace(/:/g,"!").replace(/\//g,"~");return encodeURIComponent(t)}function mp(e){return decodeURIComponent(e).replace(/!/g,":").replace(/~/g,"/")}function R_(e,t){return`${Ka}${hp(e)}:${hp(t)}`}function Wa(e){if(!e.startsWith(Ka))throw new Error("Invalid object URL");let n=e.slice(Ka.length).split(":");if(n.length!==2)throw new Error("Invalid object URL format");let[r,o]=n;return{actor:mp(r),contentAddress:mp(o)}}function Va(e){return e===void 0?null:Array.isArray(e)?e.map(Va):typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,n])=>[t,Va(n)])):e}var yp=class{dialog=document.createElement("dialog");shadow;main_;useTemplateHTML;templates_;onManualClose;displayTemplateSeq=0;constructor(e){this.useTemplateHTML=e.useTemplateHTML,this.onManualClose=e.onManualClose,this.dialog.className="graffiti-modal",this.dialog.addEventListener("click",n=>{if("pointerType"in n&&!n.pointerType)return;let r=this.dialog.getBoundingClientRect();(r.top>n.clientY||r.left>n.clientX||n.clientY>r.top+r.height||n.clientX>r.left+r.width)&&(this.close(),this.onManualClose?.())});let t=document.createElement("div");this.shadow=t.attachShadow({mode:"closed"}),this.shadow.appendChild(this.dialog),document.body.append(t)}get templates(){return this.templates_||(this.main_,this.templates_=new Promise(async e=>e(await this.useTemplateHTML())).then(e=>{let t=new DOMParser().parseFromString(e,"text/html"),n=new Map;return t.querySelectorAll("template").forEach(r=>{let o=r.id;o&&n.set(o,r)}),n})),this.templates_}get main(){return this.main_||(this.templates_,this.main_=Promise.all([import("./style-BOBMBTYJ-2YZTO5FX.js"),import("./graffiti-KV3G3O72-QD3APAKT.js"),import("./rock-salt-LI7DAH66-M6W5PPFD.js")]).then(async([{default:e},{default:t},{default:n}])=>{let r=document.createElement("header"),o=document.createElement("button");o.className="secondary",o.textContent="Close",o?.addEventListener("click",()=>{this.close(),this.onManualClose?.()}),r.appendChild(o);let i=document.createElement("main");this.dialog.appendChild(r),this.dialog.appendChild(i);let s=new FontFace("Rock Salt",`url(${n})`,{style:"normal",weight:"400"});document.fonts.add(s),await s.load(),e=e.replace("url(graffiti.jpg)",`url(${t})`);let a=new CSSStyleSheet;return a.replace(e).then(()=>{this.shadow.adoptedStyleSheets=[a]}),i})),this.main_}async open(){await this.main,this.dialog.showModal(),this.dialog.focus()}close(){this.dialog.close()}async displayTemplate(e){let t=++this.displayTemplateSeq,n=()=>{if(t!==this.displayTemplateSeq)throw new Error(`displayTemplate(${e}) overridden by concurrent call`)},r=await this.main;n();let o=(await this.templates).get(e);if(n(),!o)throw new Error(`Template not found: ${e}`);let i=o.content.cloneNode(!0);return r.replaceChildren(i),r}};var bp=Mt(e=>e instanceof Uint8Array),Qa="k",Fn="t",nc=ye({[Qa]:B(),[Fn]:X(B())}),en="id",ec="e",Jr="a",P_=q(ye({[en]:B(),[ec]:X(Z()),[Jr]:X(Z())})),$i="s",Ci="n",O_=at(nc,{[$i]:X(q(bp)),[Ci]:P_}),Kr="a",tc="i",k_=at(nc,{[Kr]:bp,[tc]:nn().check(Ut())}),I_=ct([nc,O_,k_]),z_=0,Ya=1,Rt=2,Xa=3,$_=128,wp="graffiti-login-remembered-handle",Di=class{dids=new Go;authorization=new ai;storageBuckets=new ui;inboxes=new fi;stringEncoder=new di;contentAddresses=new hi;channelAttestations=new _i;allowedAttestations=new bi;sessions=new Pi({dids:this.dids,authorization:this.authorization,storageBuckets:this.storageBuckets,inboxes:this.inboxes});handles=new xi({dids:this.dids});objectEncoding=new zi({stringEncoder:this.stringEncoder,contentAddresses:this.contentAddresses,channelAttestations:this.channelAttestations,allowedAttestations:this.allowedAttestations});modal=typeof window>"u"?void 0:new yp({useTemplateHTML:()=>import("./login-dialog.html-WIDO3XZF.js").then(({template:t})=>t),onManualClose:()=>{let t=new CustomEvent("login",{detail:{error:new Error("User cancelled login"),manual:!0}});this.sessionEvents.dispatchEvent(t)}});defaultInboxEndpoints;identityCreatorEndpoint;constructor(t){this.defaultInboxEndpoints=t?.defaultInboxEndpoints??["https://graffiti.actor/i/shared"],this.identityCreatorEndpoint=t?.identityCreatorEndpoint??"https://graffiti.actor/create",this.sessionEvents.addEventListener("login",async n=>{if(!(n instanceof CustomEvent))return;let r=n.detail;if(r.error!==void 0){if("manual"in r&&r.manual)return;alert("Login failed: "+r.error.message);let s=r.session?.actor,a;if(s)try{a=await this.actorToHandle(s)}catch(c){console.error("Failed to handle actor:",c)}this.login_(a);return}let o=r.session.actor,i;try{i=await this.actorToHandle(o)}catch(s){console.error("Failed to load handle from actor:",s)}i&&this.rememberHandleInBrowserStorage(i)});for(let n of["post","get","delete","postMedia","getMedia","deleteMedia"]){let r=this[n];this[n]=async(...o)=>{try{return await r(...o)}catch(i){let s=o[o.length-1];throw await this.tryLogoutIfUnauthorized(i,s),i}}}}actorToHandle=this.handles.actorToHandle.bind(this.handles);handleToActor=this.handles.handleToActor.bind(this.handles);sessionEvents=this.sessions.sessionEvents;login=async t=>{try{let n;try{n=t?await this.actorToHandle(t):void 0}catch(r){console.error("Error fetching handle for actor:",r)}await this.login_(n)}catch(n){let r=new CustomEvent("login",{detail:{error:n instanceof Error?n:new Error(String(n))}});this.sessionEvents.dispatchEvent(r)}};async login_(t){if(typeof window<"u"){let n;if(t!==void 0){n=await this.modal?.displayTemplate("graffiti-login-handle");let o=n?.querySelector("#username"),i=t||this.getRememberedHandleFromBrowserStorage();o&&(o.value=i??""),o?.addEventListener("focus",()=>o?.select()),setTimeout(()=>o?.focus(),0),n?.querySelector("#graffiti-login-handle-form")?.addEventListener("submit",async s=>{s.preventDefault(),o?.setAttribute("disabled","true");let a=n?.querySelector("#graffiti-login-handle-submit");if(a?.setAttribute("disabled","true"),a&&(a.innerHTML="Logging in..."),!o?.value){alert("No handle provided"),this.login_("");return}let c=o.value;if(!c.includes(".")&&!c.startsWith("localhost")){let l=new URL(this.identityCreatorEndpoint).host;c=`${c}.${l}`}let u;try{u=await this.handleToActor(c)}catch{alert("Could not find an identity associated with that handle."),this.login_(c);return}try{await this.sessions.login(u)}catch(l){alert("Error logging in."),console.error(l),this.login_(c)}}),n?.querySelector("#graffiti-login-forgot")?.addEventListener("click",s=>{s.preventDefault(),this.loginWithoutHandle()})}else n=await this.modal?.displayTemplate("graffiti-login-welcome"),n?.querySelector("#graffiti-login-existing")?.addEventListener("click",o=>{o.preventDefault(),this.login_("")}),setTimeout(()=>n?.querySelector("#graffiti-login-new")?.focus(),0);let r=new URL(this.identityCreatorEndpoint);r.searchParams.set("redirect_uri",encodeURIComponent(window.location.toString())),n?.querySelector("#graffiti-login-new")?.setAttribute("href",r.toString()),await this.modal?.open()}else{let n=await import("readline").catch(s=>{throw new Error("Unrecognized environment: neither window nor readline")});console.log("If you do not already have a Graffiti handle, you can create one here:"),console.log(this.identityCreatorEndpoint);let r=n.createInterface({input:process.stdin,output:process.stdout}),o=await new Promise(s=>{r.question(`Please enter your handle${t?` (default: ${t})`:""}: `,a=>{r.close(),s(a||t)})});if(!o)throw new Error("No handle provided");let i=await this.handleToActor(o);await this.sessions.login(i)}}async loginWithoutHandle(){let t=await this.modal?.displayTemplate("graffiti-login-provider"),n=new URL("/",this.identityCreatorEndpoint),r=t?.querySelector("#graffiti-provider");r&&(r.value=n.host),r?.addEventListener("focus",()=>r.select()),setTimeout(()=>r?.focus(),0),t?.querySelector("#graffiti-login-provider-form")?.addEventListener("submit",o=>{o.preventDefault();try{let i=r?.value.trim()??"",s=i===n.host?n:new URL(`https://${i}`);if(!s.hostname||s.username||s.password||s.pathname!=="/"||s.search||s.hash)throw new Error("Invalid provider domain");let a=new URL("/forgot-handle",s);a.searchParams.set("redirect_uri",window.location.toString()),window.location.assign(a.toString())}catch{alert("Enter a valid provider domain.")}}),t?.querySelector("#graffiti-login-provider-back")?.addEventListener("click",o=>{o.preventDefault(),this.login_("")}),await this.modal?.open()}rememberHandleInBrowserStorage(t){if(!(typeof window>"u"))try{window.localStorage.setItem(wp,t)}catch(n){console.error("Failed to remember handle in browser storage:",n)}}getRememberedHandleFromBrowserStorage(){if(!(typeof window>"u"))try{return window.localStorage.getItem(wp)??void 0}catch(t){console.error("Failed to load handle from browser storage:",t);return}}logout=async t=>{await this.sessions.logout(t.actor)};post=async(...t)=>{let[n,r]=t,o=this.sessions.resolveSession(r),{object:i,tags:s,objectBytes:a,allowedTickets:c}=await this.objectEncoding.encode(n,r.actor),u=Lt(),l=await this.stringEncoder.encode(Bn,u);return await this.storageBuckets.put(o.storageBucket.serviceEndpoint,l,a,o.storageBucket.token),await this.announceObject(i,s,c,l,r),i};get=async(...t)=>{let[n,r,o]=t,i,s=await so(r);if(o){let u=this.sessions.resolveSession(o);i=[u.personalInbox,...u.sharedInboxes]}else i=this.defaultInboxEndpoints.map(u=>({serviceEndpoint:u}));let a=ns(n),c=[new TextEncoder().encode(a)];for(let u of i){let l,f=this.querySingleEndpoint(u.serviceEndpoint,{tags:c,objectSchema:{}},u.token,o?.actor);for await(let d of f)d.object.url===a&&(d.tombstone?l=void 0:l=d.object);if(l){if(!s(l))throw new oo("Object exists but does not match the supplied schema");return l}}throw new Q("Object not found")};delete=async(t,n)=>{let r=this.sessions.resolveSession(n),o=ns(t),{actor:i}=Wa(o);if(i!==n.actor)throw new mt("Cannot delete someone else's actor");let s=this.querySingleEndpoint(r.personalInbox.serviceEndpoint,{tags:[new TextEncoder().encode(o)],objectSchema:{}},r.personalInbox.token),a;for await(let w of s)w.object.url===o&&(w.tombstone?a=void 0:a=w);if(!a)throw new Q(`Object ${o} not found`);let{object:c,storageBucketKey:u,tags:l,allowedTickets:f,announcements:d,messageId:g}=a;return await this.storageBuckets.delete(r.storageBucket.serviceEndpoint,u,r.storageBucket.token),await this.announceObject(c,l,f,u,n,[...d??[],{[Jr]:n.actor,[en]:g}]),c};postMedia=async(...t)=>{let[n,r]=t,o=n.data.type,i=this.sessions.resolveSession(r),s=Lt(),a=await this.stringEncoder.encode(Bn,s);await this.storageBuckets.put(i.storageBucket.serviceEndpoint,a,new Uint8Array(await n.data.arrayBuffer()),i.storageBucket.token);let{url:c}=await this.post({value:{key:a,type:o,size:n.data.size},channels:[],allowed:n.allowed},r);return c};getMedia=async(...t)=>{let[n,r,o]=t;if(r?.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<0))throw new TypeError("maxBytes must be a nonnegative safe integer");let i=await this.get(n,C_,o),{key:s,type:a,size:c}=i.value;if(r?.maxBytes!==void 0&&c>r.maxBytes)throw new gt("File size exceeds limit");if(r?.types&&!Ou(a,r.types))throw new io(`Unacceptable media type, ${a}`);let l=(await this.dids.resolve(i.actor))?.service?.find(w=>w.id===ki&&w.type===Oi);if(!l)throw new Q(`Actor ${i.actor} has no storage bucket service`);if(typeof l.serviceEndpoint!="string")throw new Q(`Actor ${i.actor} does not have a valid storage bucket endpoint`);let f=l.serviceEndpoint,d=await this.storageBuckets.get(f,s,c);return{data:new Blob([d.slice()],{type:a}),actor:i.actor,allowed:i.allowed}};deleteMedia=async(...t)=>{let[n,r]=t,o=this.sessions.resolveSession(r),i=await this.delete(n,r);if(!("key"in i.value&&typeof i.value.key=="string"))throw new Error("Deleted object was not media: "+JSON.stringify(i,null,2));await this.storageBuckets.delete(o.storageBucket.serviceEndpoint,i.value.key,o.storageBucket.token)};async*discoverMeta(t,n,r,o){let i=new Map,s;if(o){let f=this.sessions.resolveSession(o);s=[f.personalInbox,...f.sharedInboxes]}else s=this.defaultInboxEndpoints.map(f=>({serviceEndpoint:f}));for(let f in r)if(!s.some(d=>d.serviceEndpoint===f))throw new mt("Cursor does not match actor's inboxes");let a=await Promise.all(t.map(f=>this.channelAttestations.register(Qt,f))),c=s.map(f=>{let d=r[f.serviceEndpoint];return this.querySingleEndpoint(f.serviceEndpoint,d?{cursor:d}:{tags:a,objectSchema:n},f.token,o?.actor)}),u=c.map(async(f,d)=>_p(f,d)),l=u.length;try{for(;l>0;){let f=await Promise.race(u);if(f.error!==void 0)u[f.index]=new Promise(()=>{}),l--,yield{error:f.error,origin:s[f.index].serviceEndpoint},this.tryLogoutIfUnauthorized(f.error,o);else if(f.result.done){let d=s[f.index];r[d.serviceEndpoint]=f.result.value,u[f.index]=new Promise(()=>{}),l--}else{u[f.index]=_p(c[f.index],f.index);let{object:d,tombstone:g,tags:w}=f.result.value;if(g){if(i.get(d.url)===!0)continue;i.set(d.url,!0),yield{tombstone:g,object:{url:d.url}}}else{if(i.get(d.url)===!1)continue;let v=a.reduce((h,b,_)=>{for(let x of w)if(b.length===x.length&&b.every((A,k)=>x[k]===A)){h.push(_);break}return h},[]).map(h=>t[h]);v.length===0&&(yield{error:new Error("Inbox returned object without matching channels"),origin:s[f.index].serviceEndpoint}),i.set(d.url,!1),yield{object:{...d,channels:v}}}}}}catch(f){throw this.tryLogoutIfUnauthorized(f,o),f}finally{await Promise.all(c.map(async f=>{await f.return("")}))}return{cursor:JSON.stringify({channels:t,cursors:r})}}discover=(...t)=>{let[n,r,o]=t;return this.discoverMeta(n,r,{},o)};continueDiscover=(...t)=>{let[n,r]=t,o,i;try{let s=JSON.parse(n),a=D_.parse(s);o=a.channels,i=a.cursors}catch{return(async function*(){throw new Me("Invalid cursor")})()}return this.discoverMeta(o,{},i,r)};async tryLogoutIfUnauthorized(t,n){t instanceof Vt&&n&&await this.sessions.logout(n.actor)}async announceObject(t,n,r,o,i,s){let a=this.sessions.resolveSession(i),c={[Qa]:o},u=[],l=t.allowed;if(Array.isArray(l)){if(!r||r.length!==l.length)throw new Error("If allowed actors are specified, there must be a corresponding ticket for each allowed actor");let g=await Promise.allSettled(l.map(async(w,E)=>{let v=JSON.parse(JSON.stringify(t)),h=rs(v,[],w),_=(await this.dids.resolve(w)).service?.find(I=>I.type===Ri&&I.id===Fa);if(!_)throw new Error(`Recipient ${w} does not have a personal inbox`);if(typeof _.serviceEndpoint!="string")throw new Error(`Recipient ${w} does not have a valid personal inbox endpoint`);let x=s?s.find(I=>I[Jr]===w)?.[en]:void 0,A={...c,...x?{[Fn]:x}:{},[Kr]:r[E],[tc]:E},k=await this.inboxes.send(_.serviceEndpoint,{[Ln]:n,[Ze]:h,[Nn]:pe(A)});u.push({[en]:k,[Jr]:w})}));for(let[w,E]of g.entries())if(E.status==="rejected"){let v=l[w];console.error("Error sending to recipient:",v),console.error(E.reason)}}else{let g=JSON.parse(JSON.stringify(t)),w=rs(g,[]),E=a.sharedInboxes,v=await Promise.allSettled(E.map(async h=>{let b=s?s.find(A=>A[ec]===h.serviceEndpoint)?.[en]:void 0,_={...c,...b?{[Fn]:b}:{}},x=await this.inboxes.send(h.serviceEndpoint,{...b?{[Fn]:b}:{},[Ln]:n,[Ze]:w,[Nn]:pe(_)});u.push({[en]:x,[ec]:h.serviceEndpoint})}));for(let[h,b]of v.entries())if(b.status==="rejected"){let _=E[h];console.error("Error sending to inbox:",_),console.error(b.reason)}}let f=s?s.find(g=>g[Jr]===i.actor)?.[en]:void 0,d={...c,...r?{[$i]:r}:{},...f?{[Fn]:f}:{},[Ci]:u};await this.inboxes.send(a.personalInbox.serviceEndpoint,{[Ln]:n,[Ze]:t,[Nn]:pe(d)})}async*querySingleEndpoint(t,n,r,o){let i="tags"in n?this.inboxes.query(t,n.tags,n.objectSchema,r):this.inboxes.continueQuery(t,n.cursor,r),s=[],a=null;try{for(;;){for(;a===null&&s.length<$_;){let l=await i.next();if(l.done){a=l.value;break}let f=this.processOneLabeledMessage(t,l.value,r,o).catch(d=>{throw d});s.push(f)}let c=s.shift();if(!c){if(a!==null)return a;throw new Error("Process queue empty but no return value")}let u=await c;u&&(yield u)}}finally{await i.return("")}}labelInboxMessage(t,n,r,o){this.inboxes.label(t,n,r,o).catch(i=>console.error("Could not label inbox message:",i))}async processOneLabeledMessage(t,n,r,o){let i=n.l;if(i!==Ya&&i!==z_&&i!==Rt)return;let s=n.id,{o:a,m:c,t:u}=n.m,l;try{let v=Ne(c);l=I_.parse(v)}catch{this.labelInboxMessage(t,s,Xa,r);return}let{[Qa]:f,[Fn]:d}=l,g=$i in l?l[$i]:void 0,w=Ci in l?l[Ci]:void 0;if(i===Ya)return{messageId:s,object:a,storageBucketKey:f,allowedTickets:g,tags:u,announcements:w};if(i===Rt){if(!d)return;let v=await this.inboxes.get(t,d,r);return!v||v[ft][Ze].url!==a.url?void 0:(v[Zr]!==Rt&&this.labelInboxMessage(t,d,Rt,r),{messageId:s,tombstone:!0,object:a,storageBucketKey:f,allowedTickets:g,tags:u,announcements:w})}let E;try{let v=a.actor,b=(await this.dids.resolve(v))?.service?.find(k=>k.id===ki&&k.type===Oi);if(!b)throw new Q(`Actor ${v} has no storage bucket service`);if(typeof b.serviceEndpoint!="string")throw new Q(`Actor ${v} does not have a valid storage bucket endpoint`);let _=b.serviceEndpoint,x=await this.storageBuckets.get(_,f,Ii);if(Kr in l&&!o)throw new mt("Recipient is required when allowed ticket is present");let A=g?{allowedTickets:g}:Kr in l?{recipient:o??"null",allowedTicket:l[Kr],allowedIndex:l[tc]}:void 0;await this.objectEncoding.validate(a,u,x,A)}catch(v){E=v}if(d){if(E instanceof Q)return this.inboxes.get(t,d,r).then(v=>{v&&v[ft][Ze].url===a.url&&v[Zr]!==Rt&&this.labelInboxMessage(t,d,Rt,r),this.labelInboxMessage(t,s,Rt,r)}).catch(v=>console.error("Could not inspect tombstone message:",v)),{messageId:s,tombstone:!0,object:a,storageBucketKey:f,allowedTickets:g,tags:u,announcements:w};console.error("Recieved an incorrect tombstone object"),console.error(E),this.labelInboxMessage(t,s,Xa,r)}else{if(E===void 0)return this.labelInboxMessage(t,s,Ya,r),{messageId:s,object:a,storageBucketKey:f,tags:u,allowedTickets:g,announcements:w};E instanceof Q?this.labelInboxMessage(t,s,Rt,r):(console.error("Recieved an incorrect object"),console.error(E),this.labelInboxMessage(t,s,Xa,r))}}},C_={properties:{value:{properties:{type:{type:"string"},size:{type:"number"},key:{type:"string"}},required:["type","size","key"]}}},D_=ye({cursors:Su(Z(),B()),channels:q(B())});async function _p(e,t){try{return{index:t,result:await e.next()}}catch(n){if(n instanceof Me||n instanceof an)throw n;return{index:t,error:n instanceof Error?n:new Error(String(n))}}}var xp=class extends ro{constructor(t){let n=new Di(t);super(n)}};export{xp as GraffitiDecentralized};
10
+ `+s)}}catch{}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Be(this.defaults,n);let{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Or.assertOptions(r,{silentJSONParsing:he.transitional(he.boolean),forcedJSONParsing:he.transitional(he.boolean),clarifyTimeoutError:he.transitional(he.boolean),legacyInterceptorReqResOrdering:he.transitional(he.boolean),advertiseZstdAcceptEncoding:he.transitional(he.boolean),validateStatusUndefinedResolves:he.transitional(he.boolean)},!1),o!=null&&(p.isFunction(o)?n.paramsSerializer={serialize:o}:Or.assertOptions(o,{encode:he.function,serialize:he.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Or.assertOptions(n,{baseUrl:he.spelling("baseURL"),withXsrfToken:he.spelling("withXSRFToken")},!0),n.method=(p.getSafeProp(n,"method")||p.getSafeProp(this.defaults,"method")||"get").toLowerCase();let s=i&&p.merge(i.common,i[n.method]);i&&p.forEach(Uo.concat("common"),w=>{delete i[w]}),n.headers=ee.concat(s,i);let a=[],c=!0;this.interceptors.request.forEach(function(E){if(typeof E.runWhen=="function"&&E.runWhen(n)===!1)return;c=c&&E.synchronous;let v=n.transitional||Sn;v&&v.legacyInterceptorReqResOrdering?a.unshift(E.fulfilled,E.rejected):a.push(E.fulfilled,E.rejected)});let u=[];this.interceptors.response.forEach(function(E){u.push(E.fulfilled,E.rejected)});let l,f=0,d;if(!c){let w=[Pr.bind(this),void 0];for(w.unshift(...a),w.push(...u),d=w.length,l=Promise.resolve(n);f<d;)l=l.then(w[f++],w[f++]);return l}d=a.length;let g=n;for(;f<d;){let w=a[f++],E=a[f++];try{g=w?w(g):g}catch(v){if(!E){l=Promise.reject(v);break}try{let h=E.call(this,v);p.isThenable(h)&&(l=Promise.resolve(h).then(()=>Pr.call(this,g)))}catch(h){l=Promise.reject(h)}break}}if(!l)try{l=Pr.call(this,g)}catch(w){l=Promise.reject(w)}for(f=0,d=u.length;f<d;)l=l.then(u[f++],u[f++]);return l}getUri(t){t=Be(this.defaults,t);let n=Rr(t.baseURL,t.url,t.allowAbsoluteUrls,t);return _r(n,t.params,t.paramsSerializer)}};p.forEach(["delete","get","head","options"],function(t){Pn.prototype[t]=function(n,r){return this.request(Be(r||{},{method:t,url:n,data:r&&p.hasOwnProp(r,"data")?r.data:void 0}))}});p.forEach(["post","put","patch","query"],function(t){function n(r){return function(i,s,a){return this.request(Be(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:i,data:s}))}}Pn.prototype[t]=n(),t!=="query"&&(Pn.prototype[t+"Form"]=n(!0))});var kr=Pn;var Ys=class e{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(i){n=i});let r=this;this.promise.then(o=>{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i,s=new Promise(a=>{r.subscribe(a),i=a}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,a){r.reason||(r.reason=new Ve(i,s,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){let t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new e(function(o){t=o}),cancel:t}}},Gf=Ys;function Xs(e){return function(n){return e.apply(null,n)}}function Qs(e){return p.isObject(e)&&e.isAxiosError===!0}var jo={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(jo).forEach(([e,t])=>{jo[t]===void 0&&(jo[t]=e)});var qf=jo;function Jf(e){let t=new kr(e),n=dr(kr.prototype.request,t);return p.extend(n,kr.prototype,t,{allOwnKeys:!0}),p.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Jf(Be(e,o))},n}var re=Jf(An);re.Axios=kr;re.CanceledError=Ve;re.CancelToken=Gf;re.isCancel=Sr;re.VERSION=Rn;re.toFormData=St;re.AxiosError=R;re.Cancel=re.CanceledError;re.all=function(t){return Promise.all(t)};re.spread=Xs;re.isAxiosError=Qs;re.mergeConfig=Be;re.AxiosHeaders=ee;re.formToJSON=e=>Do(p.isHTMLForm(e)?new FormData(e):e);re.getAdapter=No.getAdapter;re.HttpStatusCode=qf;re.default=re;var Zo=re;var{Axios:KR,AxiosError:VR,CanceledError:WR,isCancel:YR,CancelToken:XR,VERSION:QR,all:eP,Cancel:tP,isAxiosError:nP,spread:rP,toFormData:oP,AxiosHeaders:iP,HttpStatusCode:sP,formToJSON:aP,getAdapter:cP,mergeConfig:uP,create:lP}=Zo;function qy(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}function Pe(e,t,n){if(!e.s){if(n instanceof ea)if(n.s)t&1&&(t=n.s),n=n.v;else{n.o=Pe.bind(null,e,t);return}if(n&&n.then){n.then(Pe.bind(null,e,t),Pe.bind(null,e,2));return}e.s=t,e.v=n;let r=e.o;r&&r(e)}}var ea=(function(){function e(){}return e.prototype.then=function(t,n){let r=new e,o=this.s;if(o){let i=o&1?t:n;if(i){try{Pe(r,1,i(this.v))}catch(s){Pe(r,2,s)}return r}else return this}return this.o=function(i){try{let s=i.v;i.s&1?Pe(r,1,t?t(s):s):n?Pe(r,1,n(s)):Pe(r,2,s)}catch(s){Pe(r,2,s)}},r},e})();function On(e){return e instanceof ea&&e.s&1}function Jy(e,t){var n;do{var r=e();if(r&&r.then)if(On(r))r=r.v;else{n=!0;break}var o=t();if(On(o)&&(o=o.v),!o)return r}while(!o.then);let i=new ea,s=Pe.bind(null,i,2);return(n?r.then(a):o.then(c)).then(void 0,s),i;function a(u){for(r=u;o=t(),On(o)&&(o=o.v),!!o;){if(o.then){o.then(c).then(void 0,s);return}if(r=e(),r&&r.then)if(On(r))r=r.v;else{r.then(a).then(void 0,s);return}}Pe(i,1,r)}function c(u){if(u){do{if(r=e(),r&&r.then)if(On(r))r=r.v;else{r.then(a).then(void 0,s);return}if(u=t(),On(u)&&(u=u.v),!u){Pe(i,1,r);return}}while(!u.then);u.then(c).then(void 0,s)}else Pe(i,1,r)}}function Kf(){return{plc:function(t,n){try{let o=function(){let l=typeof c?.["@context"]<"u"?"application/did+ld+json":"application/did+json";return i?{didDocument:c,didDocumentMetadata:a,didResolutionMetadata:{error:"notFound",message:i}}:{didDocument:c,didDocumentMetadata:a,didResolutionMetadata:{contentType:l}}},r,i=null,s=`https://plc.directory/${encodeURIComponent(t)}`,a={},c=null,u=Jy(function(){function l(){r||c?.id===t||(i="resolver_error: DID document id does not match requested did")}let f=qy(function(){return Promise.resolve(Zo.get(s)).then(function(d){c=d.data})},function(d){i=`resolver_error: '"https://plc.directory/" + DID' must resolve to a valid https URL containing a JSON document: ${d}`,r=1});return f&&f.then?f.then(l):l(f)},function(){return!r&&!1});return Promise.resolve(u&&u.then?u.then(o):o(u))}catch(r){return Promise.reject(r)}}}}var Yf=Tp(Wf(),1);function Ky(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}var Vy=function(e){try{return Promise.resolve((0,Yf.default)(e,{mode:"cors"})).then(function(t){if(t.status>=400)throw new Error(`Bad response ${t.statusText}`);return t.json()})}catch(t){return Promise.reject(t)}};function Oe(e,t,n){if(!e.s){if(n instanceof ta)if(n.s)t&1&&(t=n.s),n=n.v;else{n.o=Oe.bind(null,e,t);return}if(n&&n.then){n.then(Oe.bind(null,e,t),Oe.bind(null,e,2));return}e.s=t,e.v=n;let r=e.o;r&&r(e)}}var Wy="/.well-known/did.json",ta=(function(){function e(){}return e.prototype.then=function(t,n){let r=new e,o=this.s;if(o){let i=o&1?t:n;if(i){try{Oe(r,1,i(this.v))}catch(s){Oe(r,2,s)}return r}else return this}return this.o=function(i){try{let s=i.v;i.s&1?Oe(r,1,t?t(s):s):n?Oe(r,1,n(s)):Oe(r,2,s)}catch(s){Oe(r,2,s)}},r},e})();function In(e){return e instanceof ta&&e.s&1}function Yy(e,t){var n;do{var r=e();if(r&&r.then)if(In(r))r=r.v;else{n=!0;break}var o=t();if(In(o)&&(o=o.v),!o)return r}while(!o.then);let i=new ta,s=Oe.bind(null,i,2);return(n?r.then(a):o.then(c)).then(void 0,s),i;function a(u){for(r=u;o=t(),In(o)&&(o=o.v),!!o;){if(o.then){o.then(c).then(void 0,s);return}if(r=e(),r&&r.then)if(In(r))r=r.v;else{r.then(a).then(void 0,s);return}}Oe(i,1,r)}function c(u){if(u){do{if(r=e(),r&&r.then)if(In(r))r=r.v;else{r.then(a).then(void 0,s);return}if(u=t(),In(u)&&(u=u.v),!u){Oe(i,1,r);return}}while(!u.then);u.then(c).then(void 0,s)}else Oe(i,1,r)}}function Xf(){return{web:function(t,n){try{let o=function(){let d=typeof l?.["@context"]<"u"?"application/did+ld+json":"application/did+json";return i?{didDocument:l,didDocumentMetadata:u,didResolutionMetadata:{error:"notFound",message:i}}:{didDocument:l,didDocumentMetadata:u,didResolutionMetadata:{contentType:d}}},r,i=null,s=decodeURIComponent(n.id)+Wy,a=n.id.split(":");a.length>1&&(s=a.map(decodeURIComponent).join("/")+"/did.json");let c=`https://${s}`,u={},l=null,f=Yy(function(){function d(){r||l?.id===t||(i="resolver_error: DID document id does not match requested did")}let g=Ky(function(){return Promise.resolve(Vy(c)).then(function(w){l=w})},function(w){i=`resolver_error: DID must resolve to a valid https URL containing a JSON document: ${w}`,r=1});return g&&g.then?g.then(d):d(g)},function(){return!r&&!1});return Promise.resolve(f&&f.then?f.then(o):o(f))}catch(r){return Promise.reject(r)}}}}var Go=class{methods={...Kf(),...Xf()};resolver=new Oo(this.methods,{cache:!0});inFlight=new Map;async resolve(t){if(!Object.keys(this.methods).some(o=>t.startsWith(`did:${o}:`)))throw new Error(`Unrecognized DID method: ${t}`);let n=this.inFlight.get(t);if(n)return n;let r=this.resolver.resolve(t).then(({didDocument:o})=>{if(!o)throw new Q(`DID not found: ${t}`);return o});this.inFlight.set(t,r);try{return await r}finally{this.inFlight.delete(t)}}};var oa;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(oa="oauth4webapi/v3.8.7");function Dr(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var xe="ERR_INVALID_ARG_VALUE",$e="ERR_INVALID_ARG_TYPE";function K(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var Jt=Symbol(),Wo=Symbol(),Yo=Symbol(),Kt=Symbol();var qo=Symbol();var Xy=new TextEncoder,Qy=new TextDecoder;function Qf(e){return typeof e=="string"?Xy.encode(e):Qy.decode(e)}var ia;Uint8Array.prototype.toBase64?ia=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):ia=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=32768)n.push(String.fromCharCode.apply(null,t.subarray(r,r+32768)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var sa;Uint8Array.fromBase64?sa=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw K("The input to be decoded is not correctly encoded.",xe,t)}}:sa=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch(t){throw K("The input to be decoded is not correctly encoded.",xe,t)}};function aa(e){return typeof e=="string"?sa(e):ia(e)}var At=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=ri,Error.captureStackTrace?.(this,this.constructor)}},zr=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,n?.code&&(this.code=n?.code),Error.captureStackTrace?.(this,this.constructor)}};function D(e,t,n){return new zr(e,{code:t,cause:n})}function Jo(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function ca(e){Dr(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(oa&&!t.has("user-agent")&&t.set("user-agent",oa),t.has("authorization"))throw K('"options.headers" must not include the "authorization" header name',xe);return t}function td(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw K('"options.signal" must return or be an instance of AbortSignal',$e);return t}}function nd(e){return e.includes("//")?e.replace("//","/"):e}function ew(e,t,n=!1){return e.pathname==="/"?e.pathname=t:e.pathname=nd(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function tw(e,t){return e.pathname=nd(`${e.pathname}/${t}`),e}async function nw(e,t,n,r){if(!(e instanceof URL))throw K(`"${t}" must be an instance of URL`,$e);ei(e,r?.[Jt]!==!0);let o=n(new URL(e.href)),i=ca(r?.headers);return i.set("accept","application/json"),(r?.[Kt]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:td(o,r?.signal)})}async function rd(e,t){return nw(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case"oidc":tw(n,".well-known/openid-configuration");break;case"oauth2":ew(n,".well-known/oauth-authorization-server");break;default:throw K('"options.algorithm" must be "oidc" (default), or "oauth2"',xe)}return n},t)}function Ir(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw K(`${n} must be a number`,$e,o);if(e>0)return;if(t){if(e!==0)throw K(`${n} must be a non-negative number`,xe,o);return}throw K(`${n} must be a positive number`,xe,o)}catch(i){throw r?D(i.message,r,o):i}}function be(e,t,n,r){try{if(typeof e!="string")throw K(`${t} must be a string`,$e,r);if(e.length===0)throw K(`${t} must not be empty`,xe,r)}catch(o){throw n?D(o.message,n,r):o}}async function od(e,t){let n=e;if(!(n instanceof URL)&&n!==Vo)throw K('"expectedIssuerIdentifier" must be an instance of URL',$e);if(!Dr(t,Response))throw K('"response" must be an instance of Response',$e);if(t.status!==200)throw D('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',oi,t);_a(t);let r=await bd(t);if(be(r.issuer,'"response" body "issuer" property',F,{body:r}),n!==Vo&&new URL(r.issuer).href!==n.href)throw D('"response" body "issuer" property does not match the expected value',ii,{expected:n.href,body:r,attribute:"issuer"});return r}function id(e){ow(e,"application/json")}function rw(e,...t){let n='"response" content-type must be ';if(t.length>2){let r=t.pop();n+=`${t.join(", ")}, or ${r}`}else t.length===2?n+=`${t[0]} or ${t[1]}`:n+=t[0];return D(n,ga,e)}function ow(e,t){if(pa(e)!==t)throw rw(e,t)}function iw(){return aa(crypto.getRandomValues(new Uint8Array(32)))}function sd(){return iw()}function ua(e){let t=e?.[Wo];return typeof t=="number"&&Number.isFinite(t)?t:0}function la(e){let t=e?.[Yo];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function fa(){return Math.floor(Date.now()/1e3)}function Xo(e){if(typeof e!="object"||e===null)throw K('"as" must be an object',$e);be(e.issuer,'"as.issuer"')}function Qo(e){if(typeof e!="object"||e===null)throw K('"client" must be an object',$e);be(e.client_id,'"client.client_id"')}function da(e){return be(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e)}}function ad(){return(e,t,n,r)=>{n.set("client_id",t.client_id)}}var sw=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function ei(e,t){if(t&&e.protocol!=="https:")throw D("only requests to HTTPS are allowed",ya,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw D("only HTTP and HTTPS requests are allowed",wa,e)}function ed(e,t,n,r){let o;if(typeof e!="string"||!(o=sw(e)))throw D(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Iw:zw,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return ei(o,r),o}function ti(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?ed(e.mtls_endpoint_aliases[t],t,n,r):ed(e[t],t,n,r)}function cd(e){if(e instanceof $n){let{0:t,length:n}=e.cause;return n===1&&t.scheme==="dpop"&&t.parameters.error==="use_dpop_nonce"}return e instanceof zn?e.error==="use_dpop_nonce":!1}var zn=class extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Ow,this.cause=n.cause,this.error=n.cause.error,this.status=n.response.status,this.error_description=n.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:n.response}),Error.captureStackTrace?.(this,this.constructor)}},$r=class extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=kw,this.cause=n.cause,this.error=n.cause.get("error"),this.error_description=n.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},$n=class extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Pw,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Ko="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",aw="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",cw='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',uw="("+Ko+")\\s*=\\s*"+cw,lw="("+Ko+")\\s*=\\s*("+Ko+")",fw=new RegExp("^[,\\s]*("+Ko+")"),dw=new RegExp("^[,\\s]*"+uw+"[,\\s]*(.*)"),pw=new RegExp("^[,\\s]*"+lw+"[,\\s]*(.*)"),hw=new RegExp("^("+aw+")(?:$|[,\\s])(.*)");function mw(e){if(!Dr(e,Response))throw K('"response" must be an instance of Response',$e);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(fw),i=o?.[1].toLowerCase();if(!i)return;let s=r.substring(o[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;r=a?a[1]:void 0;let u={},l;if(c)for(;r;){let d,g;if(o=r.match(dw)){if([,d,g,r]=o,g.includes("\\"))try{g=JSON.parse(`"${g}"`)}catch{}u[d.toLowerCase()]=g;continue}if(o=r.match(pw)){[,d,g,r]=o,u[d.toLowerCase()]=g;continue}if(o=r.match(hw)){if(Object.keys(u).length)break;[,l,r]=o;break}return}else r=s||void 0;let f={scheme:i,parameters:u};l&&(f.token68=l),n.push(f)}if(n.length)return n}async function gw(e){if(e.status>399&&e.status<500){_a(e),id(e);try{let t=await e.clone().json();if(Jo(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function ud(e,t,n){if(e.status!==t){bw(e);let r;throw(r=await gw(e))?(await e.body?.cancel(),new zn("server responded with an error in the response body",{cause:r,response:e})):D(`"response" is not a conform ${n} response (unexpected HTTP status code)`,oi,e)}}function yw(e){if(!ha.has(e))throw K('"options.DPoP" is not a valid DPoPHandle',xe)}function pa(e){return e.headers.get("content-type")?.split(";")[0]}async function ld(e,t,n,r,o,i,s){return await n(e,t,o,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[Kt]||fetch)(r.href,{body:o,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:td(r,s?.signal)})}async function ww(e,t,n,r,o,i){let s=ti(e,"token_endpoint",t.use_mtls_endpoint_aliases,i?.[Jt]!==!0);o.set("grant_type",r);let a=ca(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(yw(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await ld(e,t,n,s,o,a,i);return i?.DPoP?.cacheNonce(c,s),c}var fd=new WeakMap,_w=new WeakMap;function ni(e){if(!e.id_token)return;let t=fd.get(e);if(!t)throw K('"ref" was already garbage collected or did not resolve from the proper sources',xe);return t}async function dd(e,t,n,r,o,i){if(Xo(e),Qo(t),!Dr(n,Response))throw K('"response" must be an instance of Response',$e);await ud(n,200,"Token Endpoint"),_a(n);let s=await bd(n);if(be(s.access_token,'"response" body "access_token" property',F,{body:s}),be(s.token_type,'"response" body "token_type" property',F,{body:s}),s.token_type=s.token_type.toLowerCase(),s.expires_in!==void 0){let a=typeof s.expires_in!="number"?parseFloat(s.expires_in):s.expires_in;Ir(a,!0,'"response" body "expires_in" property',F,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&be(s.refresh_token,'"response" body "refresh_token" property',F,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw D('"response" body "scope" property must be a string',F,{body:s});if(s.id_token!==void 0){be(s.id_token,'"response" body "id_token" property',F,{body:s});let a=["aud","exp","iat","iss","sub"];t.require_auth_time===!0&&a.push("auth_time"),t.default_max_age!==void 0&&(Ir(t.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),r?.length&&a.push(...r);let{claims:c,jwt:u}=await $w(s.id_token,Dw.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),ua(t),la(t),o).then(Aw.bind(void 0,a)).then(Ew.bind(void 0,e)).then(xw.bind(void 0,t.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw D('ID Token "aud" (audience) claim includes additional untrusted audiences',We,{claims:c,claim:"aud"});if(c.azp!==t.client_id)throw D('unexpected ID Token "azp" (authorized party) claim value',We,{expected:t.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&Ir(c.auth_time,!0,'ID Token "auth_time" (authentication time)',F,{claims:c}),_w.set(n,u),fd.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](n,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new At("unsupported `token_type` value",{cause:{body:s}});return s}function bw(e){let t;if(t=mw(e))throw new $n("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}function xw(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw D('unexpected JWT "aud" (audience) claim value',We,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw D('unexpected JWT "aud" (audience) claim value',We,{expected:e,claims:t.claims,claim:"aud"});return t}function Ew(e,t){let n=e[ba]?.(t)??e.issuer;if(t.claims.iss!==n)throw D('unexpected JWT "iss" (issuer) claim value',We,{expected:n,claims:t.claims,claim:"iss"});return t}var ha=new WeakSet;function Sw(e){return ha.add(e),e}var ma=Symbol();async function pd(e,t,n,r,o,i,s){if(Xo(e),Qo(t),!ha.has(r))throw K('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',xe);be(o,'"redirectUri"');let a=qt(r,"code");if(!a)throw D('no authorization code in "callbackParameters"',F);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),i!==ma&&(be(i,'"codeVerifier"'),c.set("code_verifier",i)),ww(e,t,n,"authorization_code",c,s)}var vw={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function Aw(e,t){for(let n of e)if(t.claims[n]===void 0)throw D(`JWT "${n}" (${vw[n]}) claim missing`,F,{claims:t.claims});return t}var na=Symbol(),ra=Symbol();async function hd(e,t,n,r){return typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number"||r?.requireIdToken?Tw(e,t,n,r.expectedNonce,r.maxAge,r[qo],r.recognizedTokenTypes):Rw(e,t,n,r?.[qo],r?.recognizedTokenTypes)}async function Tw(e,t,n,r,o,i,s){let a=[];switch(r){case void 0:r=na;break;case na:break;default:be(r,'"expectedNonce" argument'),a.push("nonce")}switch(o??=t.default_max_age,o){case void 0:o=ra;break;case ra:break;default:Ir(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await dd(e,t,n,a,i,s);be(c.id_token,'"response" body "id_token" property',F,{body:c});let u=ni(c);if(o!==ra){let l=fa()+ua(t),f=la(t);if(u.auth_time+o<l-f)throw D("too much time has elapsed since the last End-User authentication",Cn,{claims:u,now:l,tolerance:f,claim:"auth_time"})}if(r===na){if(u.nonce!==void 0)throw D('unexpected ID Token "nonce" claim value',We,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==r)throw D('unexpected ID Token "nonce" claim value',We,{expected:r,claims:u,claim:"nonce"});return c}async function Rw(e,t,n,r,o){let i=await dd(e,t,n,void 0,r,o),s=ni(i);if(s){if(t.default_max_age!==void 0){Ir(t.default_max_age,!0,'"client.default_max_age"');let a=fa()+ua(t),c=la(t);if(s.auth_time+t.default_max_age<a-c)throw D("too much time has elapsed since the last End-User authentication",Cn,{claims:s,now:a,tolerance:c,claim:"auth_time"})}if(s.nonce!==void 0)throw D('unexpected ID Token "nonce" claim value',We,{expected:void 0,claims:s,claim:"nonce"})}return i}var Pw="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Ow="OAUTH_RESPONSE_BODY_ERROR",ri="OAUTH_UNSUPPORTED_OPERATION",kw="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var Cr="OAUTH_PARSE_ERROR",F="OAUTH_INVALID_RESPONSE";var ga="OAUTH_RESPONSE_IS_NOT_JSON",oi="OAUTH_RESPONSE_IS_NOT_CONFORM",ya="OAUTH_HTTP_REQUEST_FORBIDDEN",wa="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",Cn="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",We="OAUTH_JWT_CLAIM_COMPARISON_FAILED",ii="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Iw="OAUTH_MISSING_SERVER_METADATA",zw="OAUTH_INVALID_SERVER_METADATA";async function md(e,t,n,r,o){Xo(e),Qo(t),be(r,'"token"');let i=ti(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,o?.[Jt]!==!0),s=new URLSearchParams(o?.additionalParameters);s.set("token",r);let a=ca(o?.headers);return a.delete("accept"),ld(e,t,n,i,s,a,o)}async function gd(e){if(!Dr(e,Response))throw K('"response" must be an instance of Response',$e);await ud(e,200,"Revocation Endpoint")}function _a(e){if(e.bodyUsed)throw K('"response" body has been used already',xe)}async function $w(e,t,n,r,o){let{0:i,1:s,length:a}=e.split(".");if(a===5)if(o!==void 0)e=await o(e),{0:i,1:s,length:a}=e.split(".");else throw new At("JWE decryption is not configured",{cause:e});if(a!==3)throw D("Invalid JWT",F,e);let c;try{c=JSON.parse(Qf(aa(i)))}catch(f){throw D("failed to parse JWT Header body as base64url encoded JSON",Cr,f)}if(!Jo(c))throw D("JWT Header must be a top level object",F,e);if(t(c),c.crit!==void 0)throw new At('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(Qf(aa(s)))}catch(f){throw D("failed to parse JWT Payload body as base64url encoded JSON",Cr,f)}if(!Jo(u))throw D("JWT Payload must be a top level object",F,e);let l=fa()+n;if(u.exp!==void 0){if(typeof u.exp!="number")throw D('unexpected JWT "exp" (expiration time) claim type',F,{claims:u});if(u.exp<=l-r)throw D('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',Cn,{claims:u,now:l,tolerance:r,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw D('unexpected JWT "iat" (issued at) claim type',F,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw D('unexpected JWT "iss" (issuer) claim type',F,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw D('unexpected JWT "nbf" (not before) claim type',F,{claims:u});if(u.nbf>l+r)throw D('unexpected JWT "nbf" (not before) claim value',Cn,{claims:u,now:l,tolerance:r,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw D('unexpected JWT "aud" (audience) claim type',F,{claims:u});return{header:c,claims:u,jwt:e}}async function Cw(e){if(e.bodyUsed)throw K("form_post Request instances must contain a readable body",xe,{cause:e});return e.text()}async function yd(e){if(e.method!=="POST")throw K("form_post responses are expected to use the POST method",xe,{cause:e});if(pa(e)!=="application/x-www-form-urlencoded")throw K("form_post responses are expected to use the application/x-www-form-urlencoded content-type",xe,{cause:e});return Cw(e)}function Dw(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw D('unexpected JWT "alg" header parameter',F,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw D('unexpected JWT "alg" header parameter',F,{header:r,expected:t,reason:"authorization server metadata"});return}if(n!==void 0){if(typeof n=="string"?r.alg!==n:typeof n=="function"?!n(r.alg):!n.includes(r.alg))throw D('unexpected JWT "alg" header parameter',F,{header:r,expected:n,reason:"default value"});return}throw D('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}function qt(e,t){let{0:n,length:r}=e.getAll(t);if(r>1)throw D(`"${t}" parameter must be provided only once`,F);return n}var wd=Symbol(),Uw=Symbol();function _d(e,t,n,r){if(Xo(e),Qo(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw K('"parameters" must be an instance of URLSearchParams, or URL',$e);if(qt(n,"response"))throw D('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',F,{parameters:n});let o=qt(n,"iss"),i=qt(n,"state");if(!o&&e.authorization_response_iss_parameter_supported)throw D('response parameter "iss" (issuer) missing',F,{parameters:n});if(o&&o!==e.issuer)throw D('unexpected "iss" (issuer) response parameter value',F,{expected:e.issuer,parameters:n});switch(r){case void 0:case Uw:if(i!==void 0)throw D('unexpected "state" response parameter encountered',F,{expected:void 0,parameters:n});break;case wd:break;default:if(be(r,'"expectedState" argument'),i!==r)throw D(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',F,{expected:r,parameters:n})}if(qt(n,"error"))throw new $r("authorization response from the server is an error",{cause:n});let a=qt(n,"id_token"),c=qt(n,"token");if(a!==void 0||c!==void 0)throw new At("implicit and hybrid flows are not supported");return Sw(new URLSearchParams(n))}async function bd(e,t=id){let n;try{n=await e.json()}catch(r){throw t(e),D('failed to parse "response" body as JSON',Cr,r)}if(!Jo(n))throw D('"response" body must be a top level object',F,{body:n});return n}var Vo=Symbol(),ba=Symbol();var Mr,xd;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(xd="openid-client/v6.8.7",Mr={"user-agent":xd});var je=e=>Ea.get(e),Ea,xa;function Lw(e){return e!==void 0?da(e):(xa||=new WeakMap,(t,n,r,o)=>{let i;return(i=xa.get(n))||(Nw(n.client_secret,'"metadata.client_secret"'),i=da(n.client_secret),xa.set(n,i)),i(t,n,r,o)})}function Nw(e,t){if(typeof e!="string")throw Ye(`${t} must be a string`,Nr);if(e.length===0)throw Ye(`${t} must not be empty`,Lr)}function Bw(){return ad()}var Dn=Kt;var Lr="ERR_INVALID_ARG_VALUE",Nr="ERR_INVALID_ARG_TYPE";function Ye(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}function Sd(){return sd()}var Un=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor)}},sO=new TextDecoder;function ge(e,t,n){return new Un(e,{cause:t,code:n})}function Ur(e){if(e instanceof TypeError||e instanceof Un||e instanceof zn||e instanceof $r||e instanceof $n)throw e;if(e instanceof zr)switch(e.code){case ya:throw ge("only requests to HTTPS are allowed",e,e.code);case wa:throw ge("only requests to HTTP or HTTPS are allowed",e,e.code);case oi:throw ge("unexpected HTTP response status code",e.cause,e.code);case ga:throw ge("unexpected response content-type",e.cause,e.code);case Cr:throw ge("parsing error occured",e,e.code);case F:throw ge("invalid response encountered",e,e.code);case We:throw ge("unexpected JWT claim value encountered",e,e.code);case ii:throw ge("unexpected JSON attribute value encountered",e,e.code);case Cn:throw ge("JWT timestamp claim value failed validation",e,e.code);default:throw ge(e.message,e,e.code)}if(e instanceof At)throw ge("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw ge("runtime operation error",e,ri);case"NotSupportedError":throw ge("runtime unsupported operation",e,ri);case"TimeoutError":throw ge("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw ge("operation aborted",e,"OAUTH_ABORT")}throw new Un("something went wrong",{cause:e})}function jw(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[Ad]=!0,!0):!1}function Zw(e,t){return!!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function vd(e,t,n,r,o){let i=await Fw(e,o),s=new Mn(i,t,n,r),a=je(s);if(o?.[Dn]&&(a.fetch=o[Dn]),o?.timeout&&(a.timeout=o.timeout),o?.execute)for(let c of o.execute)c(s);return s}async function Fw(e,t){if(!(e instanceof URL))throw Ye('"server" must be an instance of URL',Nr);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),i=await(n?rd(e,{algorithm:t?.algorithm,[Kt]:t?.[Dn],[Jt]:t?.execute?.includes(Ed),signal:o,headers:new Headers(Mr)}):(t?.[Dn]||fetch)((ei(e,!t?.execute?.includes(Ed)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...Mr}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(s=>od(Vo,s)).catch(Ur);return n&&new URL(i.issuer).href!==e.href&&(jw(e,i,t)||Zw(e,t)||(()=>{throw new Un("discovered metadata issuer does not match the expected issuer",{code:ii,cause:{expected:e.href,body:i,attribute:"issuer"}})})()),i}function Hw(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function Gw(e){Object.defineProperties(e,Hw(e))}var Ad=Symbol(),Mn=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw Ye('"clientId" must be a non-empty string',Nr);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw Ye('"clientId" and "metadata.client_id" must be the same',Lr);let i={...structuredClone(r),client_id:n};i[Wo]=r?.[Wo]??0,i[Yo]=r?.[Yo]??30;let s;o?s=o:typeof i.client_secret=="string"&&i.client_secret.length?s=Lw(i.client_secret):s=Bw();let a=Object.freeze(i),c=structuredClone(t);Ad in t&&(c[ba]=({claims:{tid:l}})=>t.issuer.replace("{tenantid}",l));let u=Object.freeze(c);Ea||=new WeakMap,Ea.set(this,{__proto__:null,as:u,c:a,auth:s,tlsOnly:!0,jwksCache:{}})}serverMetadata(){let t=structuredClone(je(this).as);return Gw(t),t}clientMetadata(){return structuredClone(je(this).c)}get timeout(){return je(this).timeout}set timeout(t){je(this).timeout=t}get[Dn](){return je(this).fetch}set[Dn](t){je(this).fetch=t}};Object.freeze(Mn.prototype);function qw(e){let t;if(e.expires_in!==void 0){let n=new Date;n.setSeconds(n.getSeconds()+e.expires_in),t=n.getTime()}return{expiresIn:{__proto__:null,value(){if(t){let n=Date.now();return t>n?Math.floor((t-n)/1e3):0}}},claims:{__proto__:null,value(){return ni(e)}}}}function Jw(e){Object.defineProperties(e,qw(e))}function Ed(e){je(e).tlsOnly=!1}function Kw(e){return e=new URL(e),e.search="",e.hash="",e.href}function Vw(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}async function Sa(e,t,n,r,o){if(va(e),o?.flag!==si&&!(t instanceof URL)&&!Vw(t,"Request"))throw Ye('"currentUrl" must be an instance of URL, or Request',Nr);let i,s,{as:a,c,auth:u,fetch:l,tlsOnly:f,jarm:d,hybrid:g,nonRepudiation:w,timeout:E,decrypt:v,implicit:h}=je(e);if(o?.flag===si)i=o.authResponse,s=o.redirectUri;else{if(!(t instanceof URL)){let A=t;switch(t=new URL(t.url),A.method){case"GET":break;case"POST":let k=new URLSearchParams(await yd(A));if(g)t.hash=k.toString();else for(let[I,z]of k.entries())t.searchParams.append(I,z);break;default:throw Ye("unexpected Request HTTP method",Lr)}}switch(s=Kw(t),!0){case!!d:i=await d(t,n?.expectedState);break;case!!g:i=await g(t,n?.expectedNonce,n?.expectedState,n?.maxAge);break;case!!h:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=_d(a,c,t.searchParams,n?.expectedState)}catch(A){Ur(A)}}}let b=await pd(a,c,u,i,s,n?.pkceCodeVerifier||ma,{additionalParameters:r,[Kt]:l,[Jt]:!f,DPoP:o?.DPoP,headers:new Headers(Mr),signal:Rd(E)}).catch(Ur);(typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number")&&(n.idTokenExpected=!0);let _=hd(a,c,b,{expectedNonce:n?.expectedNonce,maxAge:n?.maxAge,requireIdToken:n?.idTokenExpected,[qo]:v}),x;try{x=await _}catch(A){if(Ww(A,o))return Sa(e,void 0,n,r,{...o,flag:si,authResponse:i,redirectUri:s});Ur(A)}return x.id_token&&await w?.(b),Jw(x),x}function Td(e,t){va(e);let{as:n,c:r,tlsOnly:o,hybrid:i,jarm:s,implicit:a}=je(e),c=ti(n,"authorization_endpoint",!1,o);if(t=new URLSearchParams(t),t.has("client_id")||t.set("client_id",r.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",i?"code id_token":a?"id_token":"code"),a&&!t.has("nonce"))throw Ye("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",Lr);s&&t.set("response_mode","jwt")}for(let[u,l]of t.entries())c.searchParams.append(u,l);return c}function va(e){if(!(e instanceof Mn))throw Ye('"config" must be an instance of Configuration',Nr);if(Object.getPrototypeOf(e)!==Mn.prototype)throw Ye("subclassing Configuration is not allowed",Lr)}function Rd(e){return e?AbortSignal.timeout(e*1e3):void 0}function Ww(e,t){return t?.DPoP&&t.flag!==si?cd(e):!1}var si=Symbol();async function Pd(e,t,n){va(e);let{as:r,c:o,auth:i,fetch:s,tlsOnly:a,timeout:c}=je(e);return md(r,o,i,t,{[Kt]:s,[Jt]:!a,additionalParameters:new URLSearchParams(n),headers:new Headers(Mr),signal:Rd(c)}).then(gd).catch(Ur)}var Od="oauth2:",Br="graffiti-auth-oauth2-data",ai=class{eventTarget=new EventTarget;constructor(){let t=this.completeOauth();(async()=>{await new Promise(r=>setTimeout(r,0)),await t;let n=new CustomEvent("initialized");this.eventTarget.dispatchEvent(n)})()}async login(...t){try{await this.login_(...t)}catch(n){let r=n instanceof Error?n:new Error("Unknown error"),o={loginId:t[1],error:r};this.eventTarget.dispatchEvent(new CustomEvent("login",{detail:o}))}}async login_(t,n,r){let o=await this.getAuthorizationConfiguration(t),i=r.map(encodeURIComponent).join(" "),s=Sd(),a,c;if(typeof window<"u"){a=window.location.href;let f={loginId:n,redirectUri:a,authorizationEndpoint:t,state:s,serviceEndpoints:r};window.localStorage.setItem(Br,JSON.stringify(f))}else{let d=(await import("node:http").catch(w=>{throw new Error("Unrecognized environment: cannot find window or node:http")})).createServer();try{await new Promise((w,E)=>{d.once("error",E),d.listen(0,"::1",w)})}catch{try{d.close()}catch{}throw new Error("Failed to start local oauth callback server.")}let g=d.address();if(!g){try{d.close()}catch{}throw new Error("Failed to get local oauth callback server address.")}a=typeof g=="string"?`http://${g}`:`http://${g.family==="IPv6"?`[${g.address}]`:g.address}:${g.port}`,c=new Promise((w,E)=>{let v=setTimeout(()=>{try{d.close()}catch{}E("Oauth callback timed out.")},3e5),h=new Set;d.on("connection",_=>{h.add(_),_.on("close",()=>{h.delete(_)})});let b=async(_,x)=>{try{let A=new URL(_.url??"/",a);await this.onCallbackUrl({loginId:n,callbackUrl:A,configuration:o,expectedState:s,serviceEndpoints:r}),x.statusCode=200,x.setHeader("Content-Type","text/plain"),x.end("You may now close this window.")}catch(A){throw x.statusCode=500,x.setHeader("Content-Type","text/plain"),x.end("Error processing OAuth callback."),A}finally{clearTimeout(v),d.off("request",b);for(let A of h)A.destroy();d.close(()=>w())}};d.on("request",b)})}let u=new URL(a);u.hash="",u.search="";let l=Td(o,{scope:i,redirect_uri:u.toString(),state:s});typeof window<"u"?window.location.replace(l.toString()):(console.log("Please open the following URL in your browser:"),console.log(l.toString()),await c)}completeOauth(){if(typeof window>"u")return;let t=window.localStorage.getItem(Br);if(!t)return;let n;try{n=JSON.parse(t)}catch{console.error("Invalid OAuth2 login data in local storage."),window.localStorage.removeItem(Br);return}let r=Yw.safeParse(n);if(!r.success){console.error("Invalid OAuth2 login data structure in local storage.",r.error),window.localStorage.removeItem(Br);return}let{loginId:o,redirectUri:i,authorizationEndpoint:s,state:a,serviceEndpoints:c}=r.data;try{let u=new URL(i),l=new URL(window.location.href);if(u.pathname!==l.pathname)return;let f=l.searchParams;return!f.has("code")&&!f.has("error")?void 0:(window.history.replaceState({},document.title,u.toString()),window.localStorage.removeItem(Br),new Promise(d=>setTimeout(d,0)).then(()=>this.getAuthorizationConfiguration(s)).then(d=>this.onCallbackUrl({loginId:o,callbackUrl:l,configuration:d,expectedState:a,serviceEndpoints:c})).catch(d=>{let g=d instanceof Error?d:new Error("Unknown error"),w={loginId:o,error:g};this.eventTarget.dispatchEvent(new CustomEvent("login",{detail:w}))}))}catch(u){console.error(u)}}async onCallbackUrl(t){let{loginId:n,callbackUrl:r,configuration:o,expectedState:i,serviceEndpoints:s}=t,a=await Sa(o,r,{expectedState:i}),c=a.access_token,l=a.scope?.split(" ").map(decodeURIComponent)||s;if(!s.every(d=>l.includes(d)))throw new Error("Not all requested service endpoints were granted.");let f=new CustomEvent("login",{detail:{loginId:n,token:c}});this.eventTarget.dispatchEvent(f)}async logout(t,n,r){try{await this.logout_(t,n,r)}catch(o){let i=o instanceof Error?o:new Error("Unknown error"),s={logoutId:n,error:i};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:s}))}}async logout_(t,n,r){let o=await this.getAuthorizationConfiguration(t);await Pd(o,r);let i={logoutId:n};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:i}))}async getAuthorizationConfiguration(t){if(!t.startsWith(Od))throw new Error(`Unrecognized authorization endpoint method: ${t}`);let n=t.slice(Od.length),r;try{r=new URL(n)}catch{throw new Error("Invalid issuer URL.")}return await vd(r,"graffiti-client")}},kd=Eu(Se({loginId:B()}),ct([Se({token:B(),error:X(xu())}),Se({error:on(Error)})])),Id=Se({logoutId:B(),error:X(on(Error))}),zd=X(Ue(Se({error:X(on(Error))}))),Yw=Se({loginId:B(),redirectUri:Z(),authorizationEndpoint:Z(),state:B(),serviceEndpoints:q(Z())});var Xw="https://";function Ce(e){if(!e.startsWith(Xw))throw new Error("Unrecognized storage bucket endpoint type")}async function ci(e){Ce(e);let t=`${e}/auth`,n=await fetch(t);if(!n.ok)throw new Error("Failed to get storage bucket authorization endpoint");return await n.text()}var Vt=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorUnauthorized",Object.setPrototypeOf(this,e.prototype)}};async function Xe(...e){let t=await fetch(...e);if(!t.ok){let n;try{n=await t.text()}catch{n=t.statusText}throw t.status===401?new Vt(n):t.status===403?new mt(n):t.status===404?new Q(n):t.status===410?new Me(n):t.status===413?new gt(n):new Error(n)}return t}var Qw=32,e_=1024*1024,t_=2;function $d(e){return Math.min(Qw,Math.floor(e_/e))}var ui=class{getAuthorizationEndpoint=ci;queues=new Map;unsupportedBatchEndpoints=new Set;async put(t,n,r,o){Ce(t);let i=`${t}/value/${encodeURIComponent(n)}`;await Xe(i,{method:"PUT",headers:{"Content-Type":"application/octet-stream",Authorization:`Bearer ${o}`},body:r.slice()})}async delete(t,n,r){Ce(t);let o=`${t}/value/${encodeURIComponent(n)}`;await Xe(o,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}async get(t,n,r){return Ce(t),r!==void 0&&Number.isSafeInteger(r)&&r>0&&$d(r)>=2&&!this.unsupportedBatchEndpoints.has(t)?new Promise((o,i)=>{let s=this.queues.get(t);s||(s=new Map,this.queues.set(t,s));let a=s.get(r);a||(a={requests:[]},s.set(r,a)),a.requests.push({key:n,resolve:o,reject:i}),a.requests.length===$d(r)?this.flush(t,r,a):a.timer===void 0&&(a.timer=setTimeout(()=>this.flush(t,r,a),t_))}):this.getOne(t,n,r)}flush(t,n,r){r.timer!==void 0&&clearTimeout(r.timer);let o=r.requests,i=this.queues.get(t);i.delete(n),i.size===0&&this.queues.delete(t),o.length===1||this.unsupportedBatchEndpoints.has(t)?o.forEach(({key:s,resolve:a,reject:c})=>{this.getOne(t,s,n).then(a,c)}):this.getBatch(t,n,o)}async getBatch(t,n,r){try{let o=await fetch(`${t}/values`,{method:"POST",headers:{"Content-Type":"application/cbor",Accept:"application/cbor"},body:pe({keys:r.map(({key:s})=>s),maxValueBytes:n}).slice()});if(o.status===404){this.unsupportedBatchEndpoints.add(t),await Promise.all(r.map(async({key:s,resolve:a,reject:c})=>{try{a(await this.getOne(t,s,n))}catch(u){c(u)}}));return}if(!o.ok)throw new Error(await o.text());let i=Ne(await o.arrayBuffer());if(!i||typeof i!="object"||!("results"in i)||!Array.isArray(i.results)||i.results.length!==r.length)throw new Error("Invalid storage batch response");i.results.forEach((s,a)=>{let{resolve:c,reject:u}=r[a];!s||typeof s!="object"||!("status"in s)?u(new Error("Invalid storage batch result")):s.status===200&&"value"in s&&s.value instanceof Uint8Array&&s.value.byteLength<=n?c(s.value):s.status===404?u(new Q("Value not found")):s.status===413?u(new gt("Value exceeds maximum byte limit")):u(new Error("Invalid storage batch result"))})}catch(o){r.forEach(({reject:i})=>i(o))}}async getOne(t,n,r){let o=`${t}/value/${encodeURIComponent(n)}`,i=await Xe(o),s=i.body?.getReader();if(!s)throw new Error("Failed to read value from storage bucket");let a=i.headers.get("Content-Length"),c=a?Number(a):void 0;if(!!c&&!!Number.isFinite(c)&&c>=0){let w=c;if(r!==void 0&&w>r)throw new Error("Value exceeds maximum byte limit");let E=new Uint8Array(w),v=0,h=!1;try{for(;v<=E.length;){let{done:b,value:_}=await s.read();if(b){h=!0;break}if(!_||_.length===0)continue;let x=v+_.length;if(x>E.length)throw new Error("Received more data than expected");E.set(_,v),v=x}}finally{s.releaseLock()}if(!h)throw new Error("Failed to read complete value from storage bucket");return v===w?E:E.slice(0,v)}let l=[],f=0;try{for(;;){let{done:w,value:E}=await s.read();if(w)break;if(!(!E||E.length===0)){if(f+=E.length,r!==void 0&&f>r)throw new Error("Value exceeds maximum byte limit");l.push(E.slice())}}}finally{s.releaseLock()}let d=new Uint8Array(f),g=0;for(let w of l)d.set(w,g),g+=w.length;return d}async*export(t,n){Ce(t);let r=`${t}/export`,o;for(;;){let s=await(await Xe(o?`${r}?cursor=${encodeURIComponent(o)}`:r,{headers:{Authorization:`Bearer ${n}`}})).blob(),a=Ne(await s.arrayBuffer()),c=n_.parse(a);for(let u of c.keys)yield{key:u};if(c.cursor)o=c.cursor;else break}}},n_=Se({keys:q(B()),cursor:X(Ue(B()))});var r_=ye({value:we({}),channels:q(B()),allowed:X(Ue(q(Z()))),url:Z(),actor:Z()}),Aa=Mt(e=>e instanceof Uint8Array),Cd=q(Aa),Ln="t",Ze="o",Nn="m",Dd=ye({[Ln]:Cd,[Ze]:r_,[Nn]:Aa}),jr="id",ft="m",Zr="l",li=ye({[jr]:B(),[ft]:Dd,[Zr]:bu()}),Ud=ye({id:B()}),Md=ye({results:q(li),hasMore:rn(),cursor:B()});async function Ta(){try{return globalThis.indexedDB?(await new Promise((e,t)=>{let n=indexedDB.open("__idb_probe__",1);n.onupgradeneeded=()=>n.result.createObjectStore("k"),n.onsuccess=()=>{n.result.close(),e()},n.onerror=()=>t(n.error)}),!0):!1}catch{return!1}}function Fr(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}async function Nd(e,t,n,r,o=0){let i=r.messageIds.slice(o);return Promise.all(i.map(async s=>{let a=await e.messages.get(Fr(t,s));if(!a){try{await e.messageIds.del(n)}catch{}throw new Error("Cache out of sync - perhaps clear browser storage")}return a}))}async function Bd(e,t,n,r,o){await e.messages.setMany(o.messages.map(s=>[Fr(t,s[jr]),s]));let i={cursor:o.cursor,version:r?.version??crypto.randomUUID(),messageIds:[...r?.messageIds??[],...o.messages.map(s=>s[jr])],generation:crypto.randomUUID(),hasMore:o.hasMore,waitTil:o.waitTil};return await e.messageIds.set(n,i),i}async function jd(e,t,n){let r=pe({inboxUrl:e,type:t,body:n??null});return crypto.subtle.digest("SHA-256",new Uint8Array(r)).then(o=>Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join(""))}async function Ld(){await new Promise(e=>{let t=indexedDB.deleteDatabase("graffiti-inbox-cache");t.onsuccess=()=>e(),t.onerror=()=>e(),t.onblocked=()=>e()})}async function Zd(){if(await Ta()){let{openDB:n}=await import("./build-KAK33G4E.js"),r=await n("graffiti-inbox-cache",1,{upgrade(o){o.objectStoreNames.contains("m")||o.createObjectStore("m"),o.objectStoreNames.contains("q")||o.createObjectStore("q")}});return{messages:{get:async o=>{try{return r.get("m",o)}catch(i){console.error("Error getting message from cache:",i),console.error("resetting cache..."),await Ld();return}},set:async(o,i)=>{await r.put("m",i,o)},setMany:async o=>{if(o.length===0)return;let i=r.transaction("m","readwrite");await Promise.all([...o.map(([s,a])=>i.store.put(a,s)),i.done])},del:o=>r.delete("m",o)},messageIds:{get:async o=>{try{return await r.get("q",o)}catch(i){console.error("Error getting message IDs from cache:",i),console.error("resetting cache..."),await Ld();return}},set:async(o,i)=>{await r.put("q",i,o)},del:o=>r.delete("q",o)}}}let e=new Map,t=new Map;return{messages:{get:async n=>e.get(n),set:async(n,r)=>{e.set(n,r)},setMany:async n=>{for(let[r,o]of n)e.set(r,o)},del:async n=>{e.delete(n)}},messageIds:{get:async n=>t.get(n),set:async(n,r)=>{t.set(n,r)},del:async n=>{t.delete(n)}}}}var o_=3e4,i_=3e4,fi=class{getAuthorizationEndpoint=ci;cache_=null;get cache(){return this.cache_||(this.cache_=Zd()),this.cache_}async send(t,n){Ce(t);let r=`${t}/send`,i=await(await Xe(r,{method:"PUT",headers:{"Content-Type":"application/cbor"},body:new Uint8Array(pe({m:n}))})).blob(),s=Ne(await i.arrayBuffer());return Ud.parse(s).id}async get(t,n,r){let o=Fr(t,n),i=await this.cache,s=await i.messages.get(o);if(s!==void 0)return s;let a=`${t}/message/${n}`,c=null;try{c=await Xe(a,{method:"GET",headers:{...r?{Authorization:`Bearer ${r}`}:{}}})}catch(d){if(d instanceof Q)return await i.messages.set(o,null),null;throw d}let u=await c.blob(),l=Ne(await u.arrayBuffer()),f=li.parse(l);return await i.messages.set(o,f),f}async label(t,n,r,o){if(Ce(t),o){let c=`${t}/label/${n}`;await Xe(c,{method:"PUT",headers:{"Content-Type":"application/cbor",Authorization:`Bearer ${o}`},body:new Uint8Array(pe({l:r}))})}let i=await this.cache,s=Fr(t,n),a=await i.messages.get(s);a&&await i.messages.set(s,{...a,l:r})}async fetchMessageBatch(t,n,r,o,i,s){let a=AbortSignal.timeout(o_),c=await Xe(`${t}/${n}${i?`?cursor=${encodeURIComponent(i)}`:""}`,{method:"POST",headers:{"Content-Type":"application/cbor",...o?{Authorization:`Bearer ${o}`}:{}},body:r,signal:s?AbortSignal.any([s,a]):a}),u=c.headers.get("Retry-After"),l=u?parseInt(u):void 0,f=l&&Number.isFinite(l)?Date.now()+l*1e3:void 0;return{response:c,waitTil:f}}async withQueryLock(t,n,r,o){if(!n)return r();let i=AbortSignal.timeout(i_),s=!1;try{return await window.navigator.locks.request(`graffiti:inbox:${t}`,{mode:"exclusive",signal:o?AbortSignal.any([o,i]):i},async()=>(s=!0,r()))}catch(a){throw!s&&i.aborted?new Error("Timed out waiting for another tab's inbox query",{cause:a}):a}}async*messageStreamer(t){let{inboxUrl:n,inboxToken:r}=t,o=t.kind==="export"?"export":"query",i=t.kind==="query"?t.schema:t.kind==="continue"?t.cursor.objectSchema:{},s=await so(i),a=t.kind==="query"?t.body:void 0,c=t.kind==="continue"?t.cursor.messageIdsCacheKey:await jd(n,o,a),u=t.kind==="continue"?t.cursor.version:void 0,l=await this.cache,f=typeof window<"u"&&await Ta(),d=await l.messageIds.get(c),g=d?.generation,w=d?.version,E=t.kind==="continue"?t.cursor.numSeen:0,v=!0,h=async _=>{for(;;){_?.throwIfAborted();let x=await this.withQueryLock(c,f,async()=>{_?.throwIfAborted();let A=await l.messageIds.get(c);if(u!==void 0&&u!==A?.version)throw new Me("Cursor is stale");if(A?.version!==w){if(!v)throw new Me("Cursor is stale");E=0}if(A?.generation&&A.generation!==g)return{query:A};if(A?.waitTil!==void 0&&A.waitTil>Date.now())return{waitTil:A.waitTil};let k;try{k=await this.fetchMessageBatch(n,o,v?a:void 0,r,A?.cursor,_)}catch(S){if(!(S instanceof Me&&A?.cursor)){if(v&&!_?.aborted)return{initialFetchError:S};throw S}if(!v||(await l.messageIds.del(c),u!==void 0))throw S;A=void 0,E=0,k=await this.fetchMessageBatch(n,o,a,r,void 0,_)}let I=Ne(new Uint8Array(await k.response.arrayBuffer())),{results:z,hasMore:V,cursor:J}=Md.parse(I),m=z.map(S=>{let U=S[ft][Ze];if(!s(U))throw new Error("Server returned data that does not match schema");return{...S,[ft]:{...S[ft],[Ze]:U}}});return A=await Bd(l,n,c,A,{messages:m,cursor:J,hasMore:V,waitTil:k.waitTil}),{query:A}},_);if("initialFetchError"in x)throw console.error("Unexpected error in stream, waiting 5 seconds before continuing..."),await new Promise(A=>setTimeout(A,5e3)),x.initialFetchError;if("waitTil"in x){await a_(x.waitTil);continue}return x.query}},b;for(;;){let _=b?await b:await h().then(z=>({query:z}),z=>({error:z}));if(b=void 0,"error"in _)throw _.error;let x=_.query,A=await Nd(l,n,c,x,E);E=x.messageIds.length,g=x.generation,w=x.version,v=!1;let k=new AbortController;x.hasMore&&(b=h(k.signal).then(z=>({query:z}),z=>({error:z})));let I=!1;try{for(let z of A)yield z;I=!0}finally{I||k.abort()}if(!x.hasMore){let z={numSeen:E,version:x.version,messageIdsCacheKey:c,objectSchema:i};return JSON.stringify(z)}}}query(t,n,r,o){Ce(t);let i=new Uint8Array(pe({tags:n,schema:r}));return this.messageStreamer({kind:"query",inboxUrl:t,body:i,schema:r,inboxToken:o})}continueQuery(t,n,r){Ce(t);let o=JSON.parse(n),i=s_.parse(o);return this.messageStreamer({kind:"continue",inboxUrl:t,cursor:i,inboxToken:r})}export(t,n){return Ce(t),this.messageStreamer({kind:"export",inboxUrl:t,inboxToken:n})}},s_=ye({messageIdsCacheKey:B(),version:B(),numSeen:nn().check(Ut()),objectSchema:ct([we({}),rn()])});async function a_(e){if(e!==void 0){let t=e-Date.now();t>0&&await new Promise(n=>setTimeout(n,t))}}var Bn="base64url";var di=class{async encode(t,n){if(t!==Bn)throw new Error(`Unsupported string encoding method: ${t}`);return"u"+btoa(String.fromCodePoint(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")}async decode(t){if(!t.startsWith("u"))throw new Error(`Unsupported string encoding prefix: ${t[0]}`);t=t.slice(1);let n=t.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";return Uint8Array.from(atob(n),r=>r.charCodeAt(0))}};function Fd(){let t=(typeof globalThis=="object"?globalThis.crypto:null)?.subtle;if(typeof t=="object"&&t!=null)return t;throw new Error("crypto.subtle must be defined")}function Hd(e,t,n){let r=async o=>{Qn(o);let i=Fd();return new Uint8Array(await i.digest(e,o))};return r.webCryptoName=e,r.outputLen=n,r.blockLen=t,r.create=()=>{throw new Error("not implemented")},Object.freeze(r)}function c_(e){zu(e);let t=e.webCryptoName;if(typeof t!="string")throw new Error("non-web hash");return t}var Wt=Hd("SHA-256",64,32);var Gd=Hd("SHA-512",128,64),Ra=(()=>{let e=async(t,n,r)=>{let o=Fd();Qn(n,void 0,"key"),Qn(r,void 0,"message");let i=c_(t),s=Iu(r);try{let a=await o.importKey("raw",n,{name:"HMAC",hash:i},!1,["sign"]);return new Uint8Array(await o.sign("HMAC",a,s))}finally{$u(s)}};return e.create=(t,n)=>{throw new Error("not implemented")},e})();var pi="sha2-256",Hr=18,jn=32,hi=class{async register(t,n){if(t!==pi)throw new Error(`Unsupported content address method: ${t}`);let r=await Wt(n),o=new Uint8Array(2+r.length);return o[0]=Hr,o[1]=jn,o.set(r,2),o}async getMethod(t){if(t[0]===Hr&&t[1]===jn&&t.length===2+jn)return pi;throw new Error("Unrecognized content address format.")}};var Yd=Object.freeze,Zn=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,yi=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,mi=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Oa=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,ka=0x6666666666666666666666666666666666666666666666666666666666666658n,gi=Zn-1n,u_=Yd({p:Zn,n:yi,h:8n,a:gi,d:mi,Gx:Oa,Gy:ka}),Gr=32,qd=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,et=(e,t,n="")=>{if(qd(e)&&(t===void 0||e.length===t))return e;let r=qd(e),o=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,s=(n?`"${n}" `:"")+"expected Uint8Array"+o+", got "+i;throw r?new RangeError(s):new TypeError(s)},Ia=(e,t="",n)=>Uint8Array.from(et(e,n,t)),Xd=(e,t)=>e.toString(16).padStart(t,"0"),Qd=e=>{let t="";for(let n of et(e))t+=Xd(n,2);return t},ep=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let n=new Uint8Array(e.length/2);for(let r=0,o=0;r<n.length;r++,o+=2){let i=e.charCodeAt(o),s=e.charCodeAt(o+1);n[r]=((i&15)+(i>>6)*9)*16+(s&15)+(s>>6)*9}return n},qr=(...e)=>{let t=0;for(let o of e)t+=et(o).length;let n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n};var Yt=(e,t,n,r="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},Y=(e,t=Zn)=>(e%=t)>=0n?e:t+e,Jd=(1n<<255n)-1n,O=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&Jd);return t=(t>>255n)*19n+(t&Jd),t%Zn},tp=e=>Y(e,yi),l_=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let n=Y(e,t),r=t,o=0n,i=1n;for(;n!==0n;){let a=r/n,c=r-n*a,u=o-i*a;r=n,n=c,o=i,i=u}if(r!==1n)throw new Error("invert: does not exist");return Y(o,t)},f_=e=>{let t=Ca[e];if(typeof t!="function")throw new Error("hashes."+e+" not set");return t};var za=async(e,...t)=>et(await f_(e)(qr(...t)),64,"digest");var Pa=e=>{if(e instanceof dt)return e;throw new TypeError("Point expected")},np=2n**256n,dt=class e{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,o){let i=np;this.X=Yt(t,0n,i),this.Y=Yt(n,0n,i),this.Z=Yt(r,1n,i),this.T=Yt(o,0n,i),Yd(this)}static CURVE(){return u_}static fromAffine(t){return new e(t.x,t.y,1n,O(t.x*t.y))}static fromBytes(t,n=!1){let r=Ia(t,"point",Gr),o=r[31];r[31]=o&-129;let i=$a(r);n||Yt(i,0n,Zn);let s=O(i*i),a=Y(s-1n),c=O(mi*s+1n),{isValid:u,value:l}=p_(a,c);if(!u)throw new Error("bad point: y not sqrt");let f=!!(o&128);if(!n&&l===0n&&f)throw new Error("bad point: x==0, isLastByteOdd");return f!==!!(l&1n)&&(l=Y(-l)),new e(l,i,1n,O(l*i))}static fromHex(t,n){return e.fromBytes(ep(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=gi,n=mi,r=this;if(r.is0())throw new Error("bad point: ZERO");let{X:o,Y:i,Z:s,T:a}=r,c=O(o*o),u=O(i*i),l=O(s*s),f=O(l*l),d=O(c*t),g=O(l*(d+u)),w=Y(f+O(n*O(c*u)));if(g!==w)throw new Error("bad point: equation left != right (1)");let E=O(o*i),v=O(s*a);if(E!==v)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:n,Y:r,Z:o}=this,{X:i,Y:s,Z:a}=Pa(t);return O(n*a)===O(i*o)&&O(r*a)===O(s*o)}is0(){return this.equals(Xt)}negate(){return new e(Y(-this.X),this.Y,this.Z,Y(-this.T))}double(){let{X:t,Y:n,Z:r}=this,o=gi,i=O(t*t),s=O(n*n),a=O(2n*r*r),c=O(o*i),u=Y(t+n),l=Y(O(u*u)-i-s),f=Y(c+s),d=Y(f-a),g=Y(c-s),w=O(l*d),E=O(f*g),v=O(l*g),h=O(d*f);return new e(w,E,h,v)}add(t){let{X:n,Y:r,Z:o,T:i}=this,{X:s,Y:a,Z:c,T:u}=Pa(t),l=gi,f=mi,d=O(n*s),g=O(r*a),w=O(O(i*f)*u),E=O(o*c),v=Y(O(Y(n+r)*Y(s+a))-d-g),h=Y(E-w),b=Y(E+w),_=Y(g-O(l*d)),x=O(v*h),A=O(b*_),k=O(v*_),I=O(h*b);return new e(x,A,I,k)}subtract(t){return this.add(Pa(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Yt(t,1n,yi),!n&&this.is0()))return Xt;if(t===1n)return this;if(this.equals(Tt))return __(t).p;let r=Xt,o=Tt,i=this;for(let s=0;n?s<256:t>0n;s++)t&1n?r=r.add(i):n&&(o=o.add(i)),i=i.double(),t>>=1n;return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Xt))return{x:0n,y:1n};let o=l_(r,Zn);if(O(r*o)!==1n)throw new Error("invalid inverse");return{x:O(t*o),y:O(n*o)}}toBytes(){let{x:t,y:n}=this.toAffine(),r=rp(n);return r[31]|=t&1n?128:0,r}toHex(){return Qd(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(yi/2n,!1).double().add(this).is0()}},Tt=new dt(Oa,ka,1n,Y(Oa*ka)),Xt=new dt(0n,1n,1n,0n);dt.BASE=Tt;dt.ZERO=Xt;var rp=e=>ep(Xd(Yt(e,0n,np),64)).reverse(),$a=e=>BigInt("0x"+Qd(Uint8Array.from(et(e)).reverse())),Qe=(e,t)=>{let n=e;for(;t-- >0;)n=O(n*n);return n},d_=e=>{let t=O(e*e),n=O(t*e),r=O(Qe(n,2)*n),o=O(Qe(r,1)*e),i=O(Qe(o,5)*o),s=O(Qe(i,10)*i),a=O(Qe(s,20)*s),c=O(Qe(a,40)*a),u=O(Qe(c,80)*c),l=O(Qe(u,80)*c),f=O(Qe(l,10)*i);return O(Qe(f,2)*e)},Kd=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,p_=(e,t)=>{let n=O(t*O(t*t)),r=O(O(n*n)*t),o=d_(O(e*r)),i=O(e*O(n*o)),s=O(t*O(i*i)),a=i,c=O(i*Kd),u=s===e,l=s===Y(-e),f=s===Y(-e*Kd);return u&&(i=a),(l||f)&&(i=c),(Y(i)&1n)===1n&&(i=Y(-i)),{isValid:u||l,value:i}},wi=e=>tp($a(e)),h_=e=>{let t=Ia(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32),o=wi(n),i=Tt.multiply(o),s=i.toBytes();return{head:n,prefix:r,scalar:o,point:i,pointBytes:s}},op=e=>za("sha512Async",et(e,Gr,"secretKey")).then(h_);var ip=e=>op(e).then(t=>t.pointBytes);var sp=async e=>e[1](await za("sha512Async",e[0]));var m_=(e,t,n)=>{let{pointBytes:r,scalar:o}=e,i=wi(t),s=Tt.multiply(i).toBytes();return[qr(s,r,n),u=>{let l=tp(i+wi(u)*o);return et(qr(s,rp(l)),64)}]},ap=async(e,t)=>{let n=Ia(e,"message"),r=await op(t);return sp(m_(r,await za("sha512Async",r.prefix,n),n))};var g_=e=>{if(e===null||typeof e!="object")throw new TypeError("expected valid options object");return e.zip215??!0},y_=(e,t,n,r)=>{e=et(e,64,"signature"),t=et(t,void 0,"message"),n=et(n,Gr,"publicKey");let o=g_(r),i=e.subarray(0,Gr),s=$a(e.subarray(Gr,64)),a,c,u,l=Uint8Array.of(),f=!1;try{a=dt.fromBytes(n,o),c=dt.fromBytes(i,o),u=Tt.multiply(s,!1),l=qr(i,n,t),f=!0}catch{}return[l,g=>{if(!f||!o&&a.isSmallOrder())return!1;let w=wi(g);return c.add(a.multiply(w,!1)).subtract(u).clearCofactor().is0()}]},cp=async(e,t,n,r={})=>sp(y_(e,t,n,r));var Ca={sha512Async:async e=>{let t=globalThis?.crypto?.subtle;if(!t)throw new Error("crypto.subtle must be defined, consider polyfill");return new Uint8Array(await t.digest("SHA-512",qr(e)))},sha512:void 0};var w_=()=>{let e=[],t=Tt,n;for(let r=0;r<33;r++){n=t,e.push(n);for(let o=1;o<128;o++)n=n.add(t),e.push(n);t=n.double()}return e},Vd,Wd=(e,t)=>{let n=t.negate();return e?n:t},__=e=>{let t=Vd||(Vd=w_()),n=Xt,r=Tt;for(let o=0;o<33;o++){let i=Number(e&255n);e>>=8n,i>128&&(i-=256,e+=1n);let s=o*128,a=s+Math.abs(i)-1,c=o%2!==0,u=i<0;i===0?r=r.add(Wd(c,t[s])):n=n.add(Wd(u,t[a]))}if(e!==0n)throw new Error("invalid wnaf");return{p:n,f:r}};Ca.sha512Async=Gd;var Qt="pk:sha2-256+ed25519",Da=0,_i=class{async register(t,n){if(t!==Qt)throw new Error(`Unsupported channel attestation method: ${t}`);let r=await this.channelToPrivateKey(n);return await this.channelPublicIdFromPrivateKey(r)}async getMethod(t){if(t[0]===Da)return Qt;throw new Error("Unrecognized channel attestation method.")}async channelToPrivateKey(t){let n=new TextEncoder().encode(t);return await Wt(n)}async channelPublicIdFromPrivateKey(t){let n=await ip(t),r=new Uint8Array(n.length+1);return r[0]=Da,r.set(n,1),r}async attest(t,n,r){if(t!==Qt)throw new Error(`Unsupported channel attestation method: ${t}`);let o=await this.channelToPrivateKey(r),i=await this.channelPublicIdFromPrivateKey(o),s=new TextEncoder().encode(n);return{attestation:await ap(s,o),channelPublicId:i}}async validate(t,n,r){let o=r[0];if(o!==Da)throw new Error(`Unrecognized channel attestation method prefix: ${o}`);return await cp(t,new TextEncoder().encode(n),r.slice(1))}};var Ua="hmac:sha2-256",up=0,bi=class{async attest(t,n){if(t!==Ua)throw new Error(`Unsupported allowed attestation method: ${t}`);let r=Lt(),o=await Ra(Wt,r,new TextEncoder().encode(n)),i=new Uint8Array(r.length+3);return i[0]=up,i[1]=Hr,i[2]=jn,i.set(r,3),{attestation:o,ticket:i}}async validate(t,n,r){let o=r[0],i=r[1],s=r[2];if(o!==up||i!==Hr||s!==jn)throw new Error("Unrecognized allowed ticket format");let a=await Ra(Wt,r.slice(3),new TextEncoder().encode(n));return t.length!==a.length?!1:a.every((c,u)=>t[u]===c)}};var Ma="did:web:",xi=class{constructor(t){this.services=t}services;actorToHandle=async t=>{let r=(await this.services.dids.resolve(t)).alsoKnownAs?.find(s=>s.startsWith(Ma));if(!r)throw new Q(`Handle for actor DID ${t} not found`);let o=r.slice(Ma.length),i=await this.services.dids.resolve(r);if(!i.alsoKnownAs||!i.alsoKnownAs.includes(t))throw new Error(`Handle ${o} does not match actor ${t}`);return o};handleToActor=async t=>{let n=`${Ma}${t}`,o=(await this.services.dids.resolve(n)).alsoKnownAs?.at(0);if(!o)throw new Q(`Actor for handle DID ${n} not found`);let i=await this.services.dids.resolve(o);if(!i.alsoKnownAs||!i.alsoKnownAs.includes(n))throw new Error(`Actor ${o} does not match handle ${t}`);return o}};function Ei(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)r!=="__proto__"&&(e[r]=n[r])}return e}var b_={read:function(e){return e[0]==='"'&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function La(e,t){function n(o,i,s){if(!(typeof document>"u")){s=Ei({},t,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),o=encodeURIComponent(o).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var c in s)s[c]&&(a+="; "+c,s[c]!==!0&&(a+="="+s[c].split(";")[0]));return document.cookie=o+"="+e.write(i,o)+a}}function r(o){if(!(typeof document>"u"||arguments.length&&!o)){for(var i=document.cookie?document.cookie.split("; "):[],s={},a=0;a<i.length;a++){var c=i[a].split("="),u=c.slice(1).join("=");try{var l=decodeURIComponent(c[0]);if(l in s||(s[l]=e.read(u,l)),o===l)break}catch{}}return o?s[o]:s}}return Object.create({set:n,get:r,remove:function(o,i){n(o,"",Ei({},i,{expires:-1}))},withAttributes:function(o){return La(this.converter,Ei({},this.attributes,o))},withConverter:function(o){return La(Ei({},this.converter,o),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(e)}})}var Si=La(b_,{path:"/"});var x_=365;function lp(e,t){Si.set(e,t,dp())}function fp(e){return Si.get(e)}function Na(e){Si.remove(e,dp())}function dp(){let e={expires:x_,path:"/",sameSite:"lax"};return typeof window<"u"&&window.location.protocol==="https:"&&(e.sameSite="none",e.secure=!0),e}var Ri="GraffitiInbox",Oi="GraffitiStorageBucket",Fa="#graffitiPersonalInbox",ki="#graffitiStorageBucket",E_="#graffitiSharedInbox_",Pi=class{constructor(t){this.services=t;let n=new Promise(o=>{this.services.authorization.eventTarget.addEventListener("initialized",i=>{if(!(i instanceof CustomEvent))return;let s=zd.safeParse(i.detail);if(!s.success)return;let a=s.data?.error;a&&console.error(a),o()})});this.services.authorization.eventTarget.addEventListener("login",this.onLogin.bind(this)),this.services.authorization.eventTarget.addEventListener("logout",this.onLogout.bind(this));let r;if(typeof window<"u"){let o=new URLSearchParams(window.location.search).get("actor");if(o)try{let i=decodeURIComponent(o),s=new URL(window.location.toString());s.searchParams.delete("actor"),window.history.replaceState({},"",s.toString()),r=this.login(i)}catch(i){console.error("Error decoding actor:",i)}}(async()=>{await new Promise(i=>setTimeout(i,0)),await r;for(let i of this.loggedInSessions){let s=new CustomEvent("login",{detail:{session:{actor:i.actor}}});this.sessionEvents.dispatchEvent(s)}await n;let o=new CustomEvent("initialized");this.sessionEvents.dispatchEvent(o)})()}services;sessionEvents=new EventTarget;inProgressLogin=void 0;inProgressLogout=void 0;async login(t){try{await this.login_(t)}catch(n){let r=new CustomEvent("login",{detail:{error:n instanceof Error?n:new Error(String(n)),session:{actor:t}}});this.sessionEvents.dispatchEvent(r)}}async login_(t){if(this.loggedInSessions.find(_=>_.actor===t)){this.sessionEvents.dispatchEvent(new CustomEvent("login",{detail:{session:{actor:t}}}));return}let o=(await this.services.dids.resolve(t)).service;if(!o)throw new Error(`No services found in actor document for ${t}`);let i=o.find(_=>_.id===ki&&_.type===Oi),s=o.find(_=>_.id===Fa&&_.type===Ri),a=o.filter(_=>_.id.match(new RegExp(`^${E_}\\d+$`))&&_.type===Ri);if(!s||!i||a.length===0)throw new Error(`Required services not found in actor document for ${t}`);let c=ja(i),u=ja(s),l=a.map(ja),f=[{endpoint:c,type:"bucket"},{endpoint:u,type:"personal-inbox"},...l.map(_=>({endpoint:_,type:"shared-inbox"}))],d=await Promise.all(f.map(async({endpoint:_,type:x})=>{let A=await(x==="bucket"?this.services.storageBuckets.getAuthorizationEndpoint(_):this.services.inboxes.getAuthorizationEndpoint(_));return{endpoint:_,authorizationEndpoint:A,type:x}})),g=new Map;d.forEach(({authorizationEndpoint:_,endpoint:x,type:A})=>{g.has(_)||g.set(_,[]),g.get(_).push({endpoint:x,type:A})});let w=[...g.entries()],v={...{actor:t},tokens:[],servicesByAuthorization:w};typeof window<"u"?window.localStorage.setItem(vi,JSON.stringify(v)):this.inProgressLogin=v;let[h,b]=w[0];await this.services.authorization.login(h,t,b.map(_=>_.endpoint))}async onLogin(t){if(!(t instanceof CustomEvent))return;let n=kd.safeParse(t.detail);if(!n.success)return;let r=n.data.loginId;try{await this.onLogin_(n.data)}catch(o){let i=new CustomEvent("login",{detail:{error:o instanceof Error?o:new Error(String(o)),session:{actor:r}}});this.sessionEvents.dispatchEvent(i)}}async onLogin_(t){if(t.error)throw t.error;let n=t.token,r=t.loginId,o;if(typeof window<"u"){let i=window.localStorage.getItem(vi);if(!i)throw new Error("No in-progress login found");let s=JSON.parse(i);o=Za.parse(s)}else{if(!this.inProgressLogin)throw new Error("No in-progress login found");o=this.inProgressLogin}if(o.actor!==r)throw new Error("Actor mismatch in login response - concurrent logins?");if(o.tokens.push(n),o.tokens.length===o.servicesByAuthorization.length){typeof window>"u"?this.inProgressLogin=void 0:window.localStorage.removeItem(vi);let i=o.servicesByAuthorization.flatMap(([u,l],f)=>l.map(d=>({token:o.tokens[f],serviceEndpoint:d.endpoint,authorizationEndpoint:u,type:d.type}))),s={...o,storageBucket:i.find(u=>u.type==="bucket"),personalInbox:i.find(u=>u.type==="personal-inbox"),sharedInboxes:i.filter(u=>u.type==="shared-inbox")},a=this.loggedInSessions;a.push(s),this.loggedInSessions=a;let c=new CustomEvent("login",{detail:{session:{actor:r}}});this.sessionEvents.dispatchEvent(c)}else{typeof window<"u"?window.localStorage.setItem(vi,JSON.stringify(o)):this.inProgressLogin=o;let[i,s]=o.servicesByAuthorization[o.tokens.length];await this.services.authorization.login(i,r,s.map(a=>a.endpoint))}}async logout(t){try{await this.logout_(t)}catch(n){let r=new CustomEvent("logout",{detail:{error:n instanceof Vt?void 0:n instanceof Error?n:new Error(String(n)),actor:t}});this.sessionEvents.dispatchEvent(r)}}async logout_(t){let n=this.loggedInSessions.find(s=>s.actor===t);if(!n)throw new Error(`No session found for actor ${t}`);this.loggedInSessions=this.loggedInSessions.filter(s=>s.actor!==t);let r=n.tokens.pop();if(!r)throw new Error("No tokens found in session");typeof window<"u"?window.localStorage.setItem(Ai,JSON.stringify(n)):this.inProgressLogout=n;let[o,i]=n.servicesByAuthorization[n.tokens.length];await this.services.authorization.logout(o,t,r)}async onLogout(t){if(!(t instanceof CustomEvent))return;let n=Id.safeParse(t.detail);if(!n.success)return;let r=n.data.logoutId;try{await this.onLogout_(n.data)}catch(o){let i=new CustomEvent("logout",{detail:{error:o instanceof Error?o:new Error(String(o)),actor:r}});this.sessionEvents.dispatchEvent(i)}}async onLogout_(t){if(t.error)throw t.error;let n=t.logoutId,r;if(typeof window<"u"){let i=window.localStorage.getItem(Ai);if(!i)throw new Error("No in-progress logout found");let s=JSON.parse(i);r=Za.parse(s)}else{if(!this.inProgressLogout)throw new Error("No in-progress logout found");r=this.inProgressLogout}if(r.actor!==n)throw new Error("Actor mismatch in logout response - concurrent logouts?");let o=r.tokens.pop();if(o){typeof window<"u"?window.localStorage.setItem(Ai,JSON.stringify(r)):this.inProgressLogout=r;let[i,s]=r.servicesByAuthorization[r.tokens.length];await this.services.authorization.logout(i,n,o)}else{typeof window>"u"?this.inProgressLogout=void 0:window.localStorage.removeItem(Ai);let i=new CustomEvent("logout",{detail:{actor:n}});this.sessionEvents.dispatchEvent(i)}}get loggedInSessions(){if(typeof window>"u")return pp;let t=fp(Ti);if(!t)return[];let n;try{n=JSON.parse(t)}catch{return console.error("Error parsing stored session data"),Na(Ti),[]}let r=q(A_).safeParse(n);return r.success?r.data:(console.error("Stored session data is invalid"),Na(Ti),[])}set loggedInSessions(t){if(typeof window>"u"){pp=t;return}lp(Ti,JSON.stringify(t))}resolveSession(t){let n=this.loggedInSessions.find(r=>r.actor===t.actor);if(!n){let r=new CustomEvent("logout",{detail:{actor:t.actor}});throw this.sessionEvents.dispatchEvent(r),new Error("Not logged in")}return n}},pp=[],vi="graffiti-login-in-progress",Ai="graffiti-logout-in-progress",Ti="graffiti-sessions-logged-in",S_=Se({actor:Z()}),Ba=Se({token:B(),serviceEndpoint:Z(),authorizationEndpoint:Z()}),v_=q(me([Z(),q(Se({endpoint:Z(),type:vu(["bucket","personal-inbox","shared-inbox"])}))])),Za=at(S_,{tokens:q(B()),servicesByAuthorization:v_}),A_=at(Za,{storageBucket:Ba,personalInbox:Ba,sharedInboxes:q(Ba)});function ja(e){if(typeof e.serviceEndpoint=="string")return e.serviceEndpoint;throw new Error(`Service endpoint for ${e.id} is not a string`)}var Ii=32*1024,zi=class{constructor(t){this.primitives=t}primitives;async encode(t,n){t=Va(t);let r=[...new Set(t.channels)],o=await Promise.all(r.map(E=>this.primitives.channelAttestations.attest(Qt,n,E))),i=o.map(E=>E.attestation),s=o.map(E=>E.channelPublicId),a={[Ga]:t.value,[qa]:i,[gp]:Lt(32)},c;if(Array.isArray(t.allowed)){let E=await Promise.all(t.allowed.map(async v=>this.primitives.allowedAttestations.attest(Ua,v)));a[Ja]=E.map(v=>v.attestation),c=E.map(v=>v.ticket)}let u=pe(a);if(u.byteLength>Ii)throw new Error("The object is too large");let l=await this.primitives.contentAddresses.register(pi,u),f=await this.primitives.stringEncoder.encode(Bn,l),d=R_(n,f),g=[new TextEncoder().encode(d),...s];return{object:{value:t.value,channels:r,url:d,actor:n,...t.allowed?{allowed:t.allowed}:{}},tags:g,objectBytes:u,allowedTickets:c}}async validate(t,n,r,o){if(r.byteLength>Ii)throw new Error("Object is too big");let{actor:i,contentAddress:s}=Wa(t.url);if(i!==t.actor)throw new Error("Object actor does not match URL actor");let a=n.at(0);if(!a)throw new Error("No object URL tag");if(new TextDecoder().decode(a)!==t.url)throw new Error("Object URL tag does not match object URL");let c=n.slice(1),u=await this.primitives.stringEncoder.decode(s),l=await this.primitives.contentAddresses.getMethod(u),f=await this.primitives.contentAddresses.register(l,r);if(f.length!==u.length||!f.every((_,x)=>_===u[x]))throw new Error("Content address is invalid");let d=Ne(r),g=T_.parse(d),w=g[Ga],E=g[qa],v=g[Ja],h=pe(w),b=pe(t.value);if(h.length!==b.length||!h.every((_,x)=>_===b[x]))throw new Error("Object value does not match storage value");if(E.length!==c.length)throw new Error("Not as many channel attestations and public ids");for(let[_,x]of E.entries()){let A=c[_];if(!await this.primitives.channelAttestations.validate(x,i,A))throw new Error("Invalid channel attestation")}if(t.channels.length){if(t.channels.length!==c.length)throw new Error("Number of claimed channels does not match attestations/public IDs");let _=await this.primitives.channelAttestations.getMethod(c[0]),x=await Promise.all(t.channels.map(A=>this.primitives.channelAttestations.register(_,A)));for(let[A,k]of x.entries()){let I=c[A];if(k.length!==I.length||!k.every((z,V)=>z===I[V]))throw new Error("Channel public id does not match expected")}}if(o){if(!v)throw new Error("Object is public but thought to be private");let _,x,A;if("recipient"in o?(_=[o.recipient],x=[o.allowedTicket],A=v.filter((k,I)=>I===o.allowedIndex)):(_=[...t.allowed??[]],x=o.allowedTickets,A=v),_.length!==t.allowed?.length)throw new Error("Recipient count does not match object allowed list");if(!_.every(k=>t.allowed?.includes(k)))throw new Error("Recipient not in object allowed list");for(let[k,I]of _.entries()){let z=x.at(k),V=A.at(k);if(!z)throw new Error("Missing allowed ticket for recipient");if(!V)throw new Error("Missing allowed attestation for recipient");if(!await this.primitives.allowedAttestations.validate(V,I,z))throw new Error("Invalid allowed attestation for recipient")}}else if(v)throw new Error("Object is private but no recipient info provided")}},Ga="v",qa="c",Ja="a",gp="n",Ha=Mt(e=>e instanceof Uint8Array),T_=ye({[Ga]:we({}),[qa]:q(Ha),[Ja]:X(q(Ha)),[gp]:Ha}),Ka="graffiti:";function hp(e){let t=e.replace(/:/g,"!").replace(/\//g,"~");return encodeURIComponent(t)}function mp(e){return decodeURIComponent(e).replace(/!/g,":").replace(/~/g,"/")}function R_(e,t){return`${Ka}${hp(e)}:${hp(t)}`}function Wa(e){if(!e.startsWith(Ka))throw new Error("Invalid object URL");let n=e.slice(Ka.length).split(":");if(n.length!==2)throw new Error("Invalid object URL format");let[r,o]=n;return{actor:mp(r),contentAddress:mp(o)}}function Va(e){return e===void 0?null:Array.isArray(e)?e.map(Va):typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,n])=>[t,Va(n)])):e}var yp=class{dialog=document.createElement("dialog");shadow;main_;useTemplateHTML;templates_;onManualClose;displayTemplateSeq=0;constructor(e){this.useTemplateHTML=e.useTemplateHTML,this.onManualClose=e.onManualClose,this.dialog.className="graffiti-modal",this.dialog.addEventListener("click",n=>{if("pointerType"in n&&!n.pointerType)return;let r=this.dialog.getBoundingClientRect();(r.top>n.clientY||r.left>n.clientX||n.clientY>r.top+r.height||n.clientX>r.left+r.width)&&(this.close(),this.onManualClose?.())});let t=document.createElement("div");this.shadow=t.attachShadow({mode:"closed"}),this.shadow.appendChild(this.dialog),document.body.append(t)}get templates(){return this.templates_||(this.main_,this.templates_=new Promise(async e=>e(await this.useTemplateHTML())).then(e=>{let t=new DOMParser().parseFromString(e,"text/html"),n=new Map;return t.querySelectorAll("template").forEach(r=>{let o=r.id;o&&n.set(o,r)}),n})),this.templates_}get main(){return this.main_||(this.templates_,this.main_=Promise.all([import("./style-BOBMBTYJ-2YZTO5FX.js"),import("./graffiti-KV3G3O72-QD3APAKT.js"),import("./rock-salt-LI7DAH66-M6W5PPFD.js")]).then(async([{default:e},{default:t},{default:n}])=>{let r=document.createElement("header"),o=document.createElement("button");o.className="secondary",o.textContent="Close",o?.addEventListener("click",()=>{this.close(),this.onManualClose?.()}),r.appendChild(o);let i=document.createElement("main");this.dialog.appendChild(r),this.dialog.appendChild(i);let s=new FontFace("Rock Salt",`url(${n})`,{style:"normal",weight:"400"});document.fonts.add(s),await s.load(),e=e.replace("url(graffiti.jpg)",`url(${t})`);let a=new CSSStyleSheet;return a.replace(e).then(()=>{this.shadow.adoptedStyleSheets=[a]}),i})),this.main_}async open(){await this.main,this.dialog.showModal(),this.dialog.focus()}close(){this.dialog.close()}async displayTemplate(e){let t=++this.displayTemplateSeq,n=()=>{if(t!==this.displayTemplateSeq)throw new Error(`displayTemplate(${e}) overridden by concurrent call`)},r=await this.main;n();let o=(await this.templates).get(e);if(n(),!o)throw new Error(`Template not found: ${e}`);let i=o.content.cloneNode(!0);return r.replaceChildren(i),r}};var bp=Mt(e=>e instanceof Uint8Array),Qa="k",Fn="t",nc=ye({[Qa]:B(),[Fn]:X(B())}),en="id",ec="e",Jr="a",P_=q(ye({[en]:B(),[ec]:X(Z()),[Jr]:X(Z())})),$i="s",Ci="n",O_=at(nc,{[$i]:X(q(bp)),[Ci]:P_}),Kr="a",tc="i",k_=at(nc,{[Kr]:bp,[tc]:nn().check(Ut())}),I_=ct([nc,O_,k_]),z_=0,Ya=1,Rt=2,Xa=3,$_=128,wp="graffiti-login-remembered-handle",Di=class{dids=new Go;authorization=new ai;storageBuckets=new ui;inboxes=new fi;stringEncoder=new di;contentAddresses=new hi;channelAttestations=new _i;allowedAttestations=new bi;sessions=new Pi({dids:this.dids,authorization:this.authorization,storageBuckets:this.storageBuckets,inboxes:this.inboxes});handles=new xi({dids:this.dids});objectEncoding=new zi({stringEncoder:this.stringEncoder,contentAddresses:this.contentAddresses,channelAttestations:this.channelAttestations,allowedAttestations:this.allowedAttestations});modal=typeof window>"u"?void 0:new yp({useTemplateHTML:()=>import("./login-dialog.html-WIDO3XZF.js").then(({template:t})=>t),onManualClose:()=>{let t=new CustomEvent("login",{detail:{error:new Error("User cancelled login"),manual:!0}});this.sessionEvents.dispatchEvent(t)}});defaultInboxEndpoints;identityCreatorEndpoint;constructor(t){this.defaultInboxEndpoints=t?.defaultInboxEndpoints??["https://graffiti.actor/i/shared"],this.identityCreatorEndpoint=t?.identityCreatorEndpoint??"https://graffiti.actor/create",this.sessionEvents.addEventListener("login",async n=>{if(!(n instanceof CustomEvent))return;let r=n.detail;if(r.error!==void 0){if("manual"in r&&r.manual)return;alert("Login failed: "+r.error.message);let s=r.session?.actor,a;if(s)try{a=await this.actorToHandle(s)}catch(c){console.error("Failed to handle actor:",c)}this.login_(a);return}let o=r.session.actor,i;try{i=await this.actorToHandle(o)}catch(s){console.error("Failed to load handle from actor:",s)}i&&this.rememberHandleInBrowserStorage(i)});for(let n of["post","get","delete","postMedia","getMedia","deleteMedia"]){let r=this[n];this[n]=async(...o)=>{try{return await r(...o)}catch(i){let s=o[o.length-1];throw await this.tryLogoutIfUnauthorized(i,s),i}}}}actorToHandle=this.handles.actorToHandle.bind(this.handles);handleToActor=this.handles.handleToActor.bind(this.handles);sessionEvents=this.sessions.sessionEvents;login=async t=>{try{let n;try{n=t?await this.actorToHandle(t):void 0}catch(r){console.error("Error fetching handle for actor:",r)}await this.login_(n)}catch(n){let r=new CustomEvent("login",{detail:{error:n instanceof Error?n:new Error(String(n))}});this.sessionEvents.dispatchEvent(r)}};async login_(t){if(typeof window<"u"){let n;if(t!==void 0){n=await this.modal?.displayTemplate("graffiti-login-handle");let o=n?.querySelector("#username"),i=t||this.getRememberedHandleFromBrowserStorage();o&&(o.value=i??""),o?.addEventListener("focus",()=>o?.select()),setTimeout(()=>o?.focus(),0),n?.querySelector("#graffiti-login-handle-form")?.addEventListener("submit",async s=>{s.preventDefault(),o?.setAttribute("disabled","true");let a=n?.querySelector("#graffiti-login-handle-submit");if(a?.setAttribute("disabled","true"),a&&(a.innerHTML="Logging in..."),!o?.value){alert("No handle provided"),this.login_("");return}let c=o.value;if(!c.includes(".")&&!c.startsWith("localhost")){let l=new URL(this.identityCreatorEndpoint).host;c=`${c}.${l}`}let u;try{u=await this.handleToActor(c)}catch{alert("Could not find an identity associated with that handle."),this.login_(c);return}try{await this.sessions.login(u)}catch(l){alert("Error logging in."),console.error(l),this.login_(c)}}),n?.querySelector("#graffiti-login-forgot")?.addEventListener("click",s=>{s.preventDefault(),this.loginWithoutHandle()})}else n=await this.modal?.displayTemplate("graffiti-login-welcome"),n?.querySelector("#graffiti-login-existing")?.addEventListener("click",o=>{o.preventDefault(),this.login_("")}),setTimeout(()=>n?.querySelector("#graffiti-login-new")?.focus(),0);let r=new URL(this.identityCreatorEndpoint);r.searchParams.set("redirect_uri",encodeURIComponent(window.location.toString())),n?.querySelector("#graffiti-login-new")?.setAttribute("href",r.toString()),await this.modal?.open()}else{let n=await import("readline").catch(s=>{throw new Error("Unrecognized environment: neither window nor readline")});console.log("If you do not already have a Graffiti handle, you can create one here:"),console.log(this.identityCreatorEndpoint);let r=n.createInterface({input:process.stdin,output:process.stdout}),o=await new Promise(s=>{r.question(`Please enter your handle${t?` (default: ${t})`:""}: `,a=>{r.close(),s(a||t)})});if(!o)throw new Error("No handle provided");let i=await this.handleToActor(o);await this.sessions.login(i)}}async loginWithoutHandle(){let t=await this.modal?.displayTemplate("graffiti-login-provider"),n=new URL("/",this.identityCreatorEndpoint),r=t?.querySelector("#graffiti-provider");r&&(r.value=n.host),r?.addEventListener("focus",()=>r.select()),setTimeout(()=>r?.focus(),0),t?.querySelector("#graffiti-login-provider-form")?.addEventListener("submit",o=>{o.preventDefault();try{let i=r?.value.trim()??"",s=i===n.host?n:new URL(`https://${i}`);if(!s.hostname||s.username||s.password||s.pathname!=="/"||s.search||s.hash)throw new Error("Invalid provider domain");let a=new URL("/forgot-handle",s);a.searchParams.set("redirect_uri",window.location.toString()),window.location.assign(a.toString())}catch{alert("Enter a valid provider domain.")}}),t?.querySelector("#graffiti-login-provider-back")?.addEventListener("click",o=>{o.preventDefault(),this.login_("")}),await this.modal?.open()}rememberHandleInBrowserStorage(t){if(!(typeof window>"u"))try{window.localStorage.setItem(wp,t)}catch(n){console.error("Failed to remember handle in browser storage:",n)}}getRememberedHandleFromBrowserStorage(){if(!(typeof window>"u"))try{return window.localStorage.getItem(wp)??void 0}catch(t){console.error("Failed to load handle from browser storage:",t);return}}logout=async t=>{await this.sessions.logout(t.actor)};post=async(...t)=>{let[n,r]=t,o=this.sessions.resolveSession(r),{object:i,tags:s,objectBytes:a,allowedTickets:c}=await this.objectEncoding.encode(n,r.actor),u=Lt(),l=await this.stringEncoder.encode(Bn,u);return await this.storageBuckets.put(o.storageBucket.serviceEndpoint,l,a,o.storageBucket.token),await this.announceObject(i,s,c,l,r),i};get=async(...t)=>{let[n,r,o]=t,i,s=await so(r);if(o){let u=this.sessions.resolveSession(o);i=[u.personalInbox,...u.sharedInboxes]}else i=this.defaultInboxEndpoints.map(u=>({serviceEndpoint:u}));let a=ns(n),c=[new TextEncoder().encode(a)];for(let u of i){let l,f=this.querySingleEndpoint(u.serviceEndpoint,{tags:c,objectSchema:{}},u.token,o?.actor);for await(let d of f)d.object.url===a&&(d.tombstone?l=void 0:l=d.object);if(l){if(!s(l))throw new oo("Object exists but does not match the supplied schema");return l}}throw new Q("Object not found")};delete=async(t,n)=>{let r=this.sessions.resolveSession(n),o=ns(t),{actor:i}=Wa(o);if(i!==n.actor)throw new mt("Cannot delete someone else's actor");let s=this.querySingleEndpoint(r.personalInbox.serviceEndpoint,{tags:[new TextEncoder().encode(o)],objectSchema:{}},r.personalInbox.token),a;for await(let w of s)w.object.url===o&&(w.tombstone?a=void 0:a=w);if(!a)throw new Q(`Object ${o} not found`);let{object:c,storageBucketKey:u,tags:l,allowedTickets:f,announcements:d,messageId:g}=a;return await this.storageBuckets.delete(r.storageBucket.serviceEndpoint,u,r.storageBucket.token),await this.announceObject(c,l,f,u,n,[...d??[],{[Jr]:n.actor,[en]:g}]),c};postMedia=async(...t)=>{let[n,r]=t,o=n.data.type,i=this.sessions.resolveSession(r),s=Lt(),a=await this.stringEncoder.encode(Bn,s);await this.storageBuckets.put(i.storageBucket.serviceEndpoint,a,new Uint8Array(await n.data.arrayBuffer()),i.storageBucket.token);let{url:c}=await this.post({value:{key:a,type:o,size:n.data.size},channels:[],allowed:n.allowed},r);return c};getMedia=async(...t)=>{let[n,r,o]=t;if(r?.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<0))throw new TypeError("maxBytes must be a nonnegative safe integer");let i=await this.get(n,C_,o),{key:s,type:a,size:c}=i.value;if(r?.maxBytes!==void 0&&c>r.maxBytes)throw new gt("File size exceeds limit");if(r?.types&&!Ou(a,r.types))throw new io(`Unacceptable media type, ${a}`);let l=(await this.dids.resolve(i.actor))?.service?.find(w=>w.id===ki&&w.type===Oi);if(!l)throw new Q(`Actor ${i.actor} has no storage bucket service`);if(typeof l.serviceEndpoint!="string")throw new Q(`Actor ${i.actor} does not have a valid storage bucket endpoint`);let f=l.serviceEndpoint,d=await this.storageBuckets.get(f,s,c);return{data:new Blob([d.slice()],{type:a}),actor:i.actor,allowed:i.allowed}};deleteMedia=async(...t)=>{let[n,r]=t,o=this.sessions.resolveSession(r),i=await this.delete(n,r);if(!("key"in i.value&&typeof i.value.key=="string"))throw new Error("Deleted object was not media: "+JSON.stringify(i,null,2));await this.storageBuckets.delete(o.storageBucket.serviceEndpoint,i.value.key,o.storageBucket.token)};async*discoverMeta(t,n,r,o){let i=new Map,s;if(o){let f=this.sessions.resolveSession(o);s=[f.personalInbox,...f.sharedInboxes]}else s=this.defaultInboxEndpoints.map(f=>({serviceEndpoint:f}));for(let f in r)if(!s.some(d=>d.serviceEndpoint===f))throw new mt("Cursor does not match actor's inboxes");let a=await Promise.all(t.map(f=>this.channelAttestations.register(Qt,f))),c=s.map(f=>{let d=r[f.serviceEndpoint];return this.querySingleEndpoint(f.serviceEndpoint,d?{cursor:d}:{tags:a,objectSchema:n},f.token,o?.actor)}),u=c.map(async(f,d)=>_p(f,d)),l=u.length;try{for(;l>0;){let f=await Promise.race(u);if(f.error!==void 0)u[f.index]=new Promise(()=>{}),l--,yield{error:f.error,origin:s[f.index].serviceEndpoint},this.tryLogoutIfUnauthorized(f.error,o);else if(f.result.done){let d=s[f.index];r[d.serviceEndpoint]=f.result.value,u[f.index]=new Promise(()=>{}),l--}else{u[f.index]=_p(c[f.index],f.index);let{object:d,tombstone:g,tags:w}=f.result.value;if(g){if(i.get(d.url)===!0)continue;i.set(d.url,!0),yield{tombstone:g,object:{url:d.url}}}else{if(i.get(d.url)===!1)continue;let v=a.reduce((h,b,_)=>{for(let x of w)if(b.length===x.length&&b.every((A,k)=>x[k]===A)){h.push(_);break}return h},[]).map(h=>t[h]);v.length===0&&(yield{error:new Error("Inbox returned object without matching channels"),origin:s[f.index].serviceEndpoint}),i.set(d.url,!1),yield{object:{...d,channels:v}}}}}}catch(f){throw this.tryLogoutIfUnauthorized(f,o),f}finally{await Promise.all(c.map(async f=>{await f.return("")}))}return{cursor:JSON.stringify({channels:t,cursors:r})}}discover=(...t)=>{let[n,r,o]=t;return this.discoverMeta(n,r,{},o)};continueDiscover=(...t)=>{let[n,r]=t,o,i;try{let s=JSON.parse(n),a=D_.parse(s);o=a.channels,i=a.cursors}catch{return(async function*(){throw new Me("Invalid cursor")})()}return this.discoverMeta(o,{},i,r)};async tryLogoutIfUnauthorized(t,n){t instanceof Vt&&n&&await this.sessions.logout(n.actor)}async announceObject(t,n,r,o,i,s){let a=this.sessions.resolveSession(i),c={[Qa]:o},u=[],l=t.allowed;if(Array.isArray(l)){if(!r||r.length!==l.length)throw new Error("If allowed actors are specified, there must be a corresponding ticket for each allowed actor");let g=await Promise.allSettled(l.map(async(w,E)=>{let v=JSON.parse(JSON.stringify(t)),h=rs(v,[],w),_=(await this.dids.resolve(w)).service?.find(I=>I.type===Ri&&I.id===Fa);if(!_)throw new Error(`Recipient ${w} does not have a personal inbox`);if(typeof _.serviceEndpoint!="string")throw new Error(`Recipient ${w} does not have a valid personal inbox endpoint`);let x=s?s.find(I=>I[Jr]===w)?.[en]:void 0,A={...c,...x?{[Fn]:x}:{},[Kr]:r[E],[tc]:E},k=await this.inboxes.send(_.serviceEndpoint,{[Ln]:n,[Ze]:h,[Nn]:pe(A)});u.push({[en]:k,[Jr]:w})}));for(let[w,E]of g.entries())if(E.status==="rejected"){let v=l[w];console.error("Error sending to recipient:",v),console.error(E.reason)}}else{let g=JSON.parse(JSON.stringify(t)),w=rs(g,[]),E=a.sharedInboxes,v=await Promise.allSettled(E.map(async h=>{let b=s?s.find(A=>A[ec]===h.serviceEndpoint)?.[en]:void 0,_={...c,...b?{[Fn]:b}:{}},x=await this.inboxes.send(h.serviceEndpoint,{...b?{[Fn]:b}:{},[Ln]:n,[Ze]:w,[Nn]:pe(_)});u.push({[en]:x,[ec]:h.serviceEndpoint})}));for(let[h,b]of v.entries())if(b.status==="rejected"){let _=E[h];console.error("Error sending to inbox:",_),console.error(b.reason)}}let f=s?s.find(g=>g[Jr]===i.actor)?.[en]:void 0,d={...c,...r?{[$i]:r}:{},...f?{[Fn]:f}:{},[Ci]:u};await this.inboxes.send(a.personalInbox.serviceEndpoint,{[Ln]:n,[Ze]:t,[Nn]:pe(d)})}async*querySingleEndpoint(t,n,r,o){let i="tags"in n?this.inboxes.query(t,n.tags,n.objectSchema,r):this.inboxes.continueQuery(t,n.cursor,r),s=[],a=null;try{for(;;){for(;a===null&&s.length<$_;){let l=await i.next();if(l.done){a=l.value;break}let f=this.processOneLabeledMessage(t,l.value,r,o).catch(d=>{throw d});s.push(f)}let c=s.shift();if(!c){if(a!==null)return a;throw new Error("Process queue empty but no return value")}let u=await c;u&&(yield u)}}finally{await i.return("")}}labelInboxMessage(t,n,r,o){this.inboxes.label(t,n,r,o).catch(i=>console.error("Could not label inbox message:",i))}async processOneLabeledMessage(t,n,r,o){let i=n.l;if(i!==Ya&&i!==z_&&i!==Rt)return;let s=n.id,{o:a,m:c,t:u}=n.m,l;try{let v=Ne(c);l=I_.parse(v)}catch{this.labelInboxMessage(t,s,Xa,r);return}let{[Qa]:f,[Fn]:d}=l,g=$i in l?l[$i]:void 0,w=Ci in l?l[Ci]:void 0;if(i===Ya)return{messageId:s,object:a,storageBucketKey:f,allowedTickets:g,tags:u,announcements:w};if(i===Rt){if(!d)return;let v=await this.inboxes.get(t,d,r);return!v||v[ft][Ze].url!==a.url?void 0:(v[Zr]!==Rt&&this.labelInboxMessage(t,d,Rt,r),{messageId:s,tombstone:!0,object:a,storageBucketKey:f,allowedTickets:g,tags:u,announcements:w})}let E;try{let v=a.actor,b=(await this.dids.resolve(v))?.service?.find(k=>k.id===ki&&k.type===Oi);if(!b)throw new Q(`Actor ${v} has no storage bucket service`);if(typeof b.serviceEndpoint!="string")throw new Q(`Actor ${v} does not have a valid storage bucket endpoint`);let _=b.serviceEndpoint,x=await this.storageBuckets.get(_,f,Ii);if(Kr in l&&!o)throw new mt("Recipient is required when allowed ticket is present");let A=g?{allowedTickets:g}:Kr in l?{recipient:o??"null",allowedTicket:l[Kr],allowedIndex:l[tc]}:void 0;await this.objectEncoding.validate(a,u,x,A)}catch(v){E=v}if(d){if(E instanceof Q)return this.inboxes.get(t,d,r).then(v=>{v&&v[ft][Ze].url===a.url&&v[Zr]!==Rt&&this.labelInboxMessage(t,d,Rt,r),this.labelInboxMessage(t,s,Rt,r)}).catch(v=>console.error("Could not inspect tombstone message:",v)),{messageId:s,tombstone:!0,object:a,storageBucketKey:f,allowedTickets:g,tags:u,announcements:w};console.error("Recieved an incorrect tombstone object"),console.error(E),this.labelInboxMessage(t,s,Xa,r)}else{if(E===void 0)return this.labelInboxMessage(t,s,Ya,r),{messageId:s,object:a,storageBucketKey:f,tags:u,allowedTickets:g,announcements:w};E instanceof Q?this.labelInboxMessage(t,s,Rt,r):(console.error("Recieved an incorrect object"),console.error(E),this.labelInboxMessage(t,s,Xa,r))}}},C_={properties:{value:{properties:{type:{type:"string"},size:{type:"number"},key:{type:"string"}},required:["type","size","key"]}}},D_=ye({cursors:Su(Z(),B()),channels:q(B())});async function _p(e,t){try{return{index:t,result:await e.next()}}catch(n){if(n instanceof Me||n instanceof an)throw n;return{index:t,error:n instanceof Error?n:new Error(String(n))}}}var xp=class extends ro{constructor(t){let n=new Di(t);super(n)}};export{xp as GraffitiDecentralized};
11
11
  /*! Bundled license information:
12
12
 
13
13
  @noble/ed25519/index.js: