solid-logic 4.0.8-test.0 → 5.0.0

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.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("$rdf")):"function"==typeof define&&define.amd?define("SolidLogic",["$rdf"],t):"object"==typeof exports?exports.SolidLogic=t(require("$rdf")):e.SolidLogic=t(e.$rdf)}(this,e=>(()=>{var t={386(e){const t={acl:"http://www.w3.org/ns/auth/acl#",arg:"http://www.w3.org/ns/pim/arg#",as:"https://www.w3.org/ns/activitystreams#",bookmark:"http://www.w3.org/2002/01/bookmark#",cal:"http://www.w3.org/2002/12/cal/ical#",cco:"http://www.ontologyrepository.com/CommonCoreOntologies/",cert:"http://www.w3.org/ns/auth/cert#",contact:"http://www.w3.org/2000/10/swap/pim/contact#",dc:"http://purl.org/dc/elements/1.1/",dct:"http://purl.org/dc/terms/",doap:"http://usefulinc.com/ns/doap#",foaf:"http://xmlns.com/foaf/0.1/",geo:"http://www.w3.org/2003/01/geo/wgs84_pos#",gpx:"http://www.w3.org/ns/pim/gpx#",gr:"http://purl.org/goodrelations/v1#",http:"http://www.w3.org/2007/ont/http#",httph:"http://www.w3.org/2007/ont/httph#",icalTZ:"http://www.w3.org/2002/12/cal/icaltzd#",ldp:"http://www.w3.org/ns/ldp#",link:"http://www.w3.org/2007/ont/link#",log:"http://www.w3.org/2000/10/swap/log#",meeting:"http://www.w3.org/ns/pim/meeting#",mo:"http://purl.org/ontology/mo/",org:"http://www.w3.org/ns/org#",owl:"http://www.w3.org/2002/07/owl#",pad:"http://www.w3.org/ns/pim/pad#",patch:"http://www.w3.org/ns/pim/patch#",prov:"http://www.w3.org/ns/prov#",pto:"http://www.productontology.org/id/",qu:"http://www.w3.org/2000/10/swap/pim/qif#",trip:"http://www.w3.org/ns/pim/trip#",rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",rss:"http://purl.org/rss/1.0/",sched:"http://www.w3.org/ns/pim/schedule#",schema:"http://schema.org/",sioc:"http://rdfs.org/sioc/ns#",skos:"http://www.w3.org/2004/02/skos/core#",solid:"http://www.w3.org/ns/solid/terms#",space:"http://www.w3.org/ns/pim/space#",stat:"http://www.w3.org/ns/posix/stat#",tab:"http://www.w3.org/2007/ont/link#",tabont:"http://www.w3.org/2007/ont/link#",ui:"http://www.w3.org/ns/ui#",vann:"http://purl.org/vocab/vann/",vcard:"http://www.w3.org/2006/vcard/ns#",wf:"http://www.w3.org/2005/01/wf/flow#",xsd:"http://www.w3.org/2001/XMLSchema#"};e.exports=function(e={namedNode:e=>e}){const r={};for(const n in t){const o=t[n];r[n]=function(t=""){return e.namedNode(o+t)}}return r}},552(e,t,r){"use strict";e.exports=r.p+"2729812e0bfc062ee77a.js"},264(t){"use strict";t.exports=e}},r={};function n(e){var o=r[e];if(void 0!==o)return o.exports;var i=r[e]={exports:{}};return t[e](i,i.exports,n),i.exports}n.m=t,n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.p="",n.b="undefined"!=typeof document&&document.baseURI||self.location.href;var o={};return(()=>{"use strict";n.r(o),n.d(o,{ACL_LINK:()=>Jr,CrossOriginForbiddenError:()=>Zr,FetchError:()=>nn,NotEditableError:()=>tn,NotFoundError:()=>en,SameOriginForbiddenError:()=>Qr,UnauthorizedError:()=>Yr,WebOperationError:()=>rn,appContext:()=>Kr,authSession:()=>bn,authn:()=>vn,createTypeIndexLogic:()=>ln,getSuggestedIssuers:()=>gn,offlineTestID:()=>Mr,performServerSideLogout:()=>yn,solidLogicSingleton:()=>fn,store:()=>En});var e={};function t(...e){console.log(...e)}function r(...e){console.warn(...e)}n.r(e),n.d(e,{SessionCore:()=>Ar,SessionEvents:()=>kr});var i=crypto;const a=e=>e instanceof CryptoKey;var s=async(e,t)=>{const r=`SHA-${e.slice(-3)}`;return new Uint8Array(await i.subtle.digest(r,t))};const c=new TextEncoder,d=new TextDecoder;function l(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const h=e=>(e=>{let t=e;"string"==typeof t&&(t=c.encode(t));const r=[];for(let e=0;e<t.length;e+=32768)r.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(r.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),u=e=>{let t=e;t instanceof Uint8Array&&(t=d.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class p extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}p.code="ERR_JOSE_GENERIC";class w extends p{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}w.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class f extends p{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}f.code="ERR_JWT_EXPIRED";class y extends p{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}y.code="ERR_JOSE_ALG_NOT_ALLOWED";class m extends p{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}m.code="ERR_JOSE_NOT_SUPPORTED";(class extends p{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends p{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class g extends p{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}g.code="ERR_JWS_INVALID";class v extends p{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}v.code="ERR_JWT_INVALID";class b extends p{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}b.code="ERR_JWK_INVALID";class E extends p{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}E.code="ERR_JWKS_INVALID";class S extends p{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}S.code="ERR_JWKS_NO_MATCHING_KEY";class _ extends p{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}_.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class k extends p{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}k.code="ERR_JWKS_TIMEOUT";class A extends p{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function T(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function I(e,t){return e.name===t}function P(e){return parseInt(e.name.slice(4),10)}function R(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!I(e.algorithm,"HMAC"))throw T("HMAC");const r=parseInt(t.slice(2),10);if(P(e.algorithm.hash)!==r)throw T(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!I(e.algorithm,"RSASSA-PKCS1-v1_5"))throw T("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(P(e.algorithm.hash)!==r)throw T(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!I(e.algorithm,"RSA-PSS"))throw T("RSA-PSS");const r=parseInt(t.slice(2),10);if(P(e.algorithm.hash)!==r)throw T(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw T("Ed25519 or Ed448");break;case"Ed25519":if(!I(e.algorithm,"Ed25519"))throw T("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!I(e.algorithm,"ECDSA"))throw T("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw T(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}function C(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}A.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var x=(e,...t)=>C("Key must be ",e,...t);function D(e,t,...r){return C(`Key for the ${e} algorithm must be `,t,...r)}var W=e=>!!a(e)||"KeyObject"===e?.[Symbol.toStringTag];const O=["CryptoKey"];var H=(...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0};function $(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}var N=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function U(e){return $(e)&&"string"==typeof e.kty}var j=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new m('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,i.subtle.importKey("jwk",o,...n)};const J=e=>u(e);let L,K;const M=e=>"KeyObject"===e?.[Symbol.toStringTag],F=async(e,t,r,n,o=!1)=>{let i=e.get(t);if(i?.[n])return i[n];const a=await j({...r,alg:n});return o&&Object.freeze(t),i?i[n]=a:e.set(t,{[n]:a}),a};var V=(e,t)=>{if(M(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?J(r.k):(K||(K=new WeakMap),F(K,e,r,t))}if(U(e)){if(e.k)return u(e.k);K||(K=new WeakMap);return F(K,e,e,t,!0)}return e},B=(e,t)=>{if(M(e)){let r=e.export({format:"jwk"});return r.k?J(r.k):(L||(L=new WeakMap),F(L,e,r,t))}if(U(e)){if(e.k)return u(e.k);L||(L=new WeakMap);return F(L,e,e,t,!0)}return e};async function G(e,t){if(!$(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return u(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new m('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return j({...e,alg:t});default:throw new m('Unsupported "kty" (Key Type) Parameter value')}}const q=e=>e?.[Symbol.toStringTag],z=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},X=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&U(t)){if(function(e){return U(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&z(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!W(t))throw new TypeError(D(e,t,...O,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${q(t)} instances for symmetric algorithms must be of type "secret"`)}};function Y(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?X(t,r,n,e):((e,t,r,n)=>{if(n&&U(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&z(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&z(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!W(t))throw new TypeError(D(e,t,...O,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}Y.bind(void 0,!1);const Z=Y.bind(void 0,!0);function Q(e,t,r,n,o){if(void 0!==o.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!i.has(t))throw new m(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}var ee=(e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};var te=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:h(e)};if(!a(e))throw new TypeError(x(e,...O,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:t,key_ops:r,alg:n,use:o,...s}=await i.subtle.exportKey("jwk",e);return s};async function re(e){return te(e)}function ne(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function oe(e,t,r){if("sign"===r&&(t=await B(t,e)),"verify"===r&&(t=await V(t,e)),a(t))return R(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(x(t,...O));return i.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(x(t,...O,"Uint8Array","JSON Web Key"))}var ie=async(e,t,r,n)=>{const o=await oe(e,t,"verify");N(e,o);const a=ne(e,o.algorithm);try{return await i.subtle.verify(a,o,r,n)}catch{return!1}};async function ae(e,t,r){if(e instanceof Uint8Array&&(e=d.decode(e)),"string"!=typeof e)throw new g("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:i,length:a}=e.split(".");if(3!==a)throw new g("Invalid Compact JWS");const s=await async function(e,t,r){if(!$(e))throw new g("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new g('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new g("JWS Protected Header incorrect type");if(void 0===e.payload)throw new g("JWS Payload missing");if("string"!=typeof e.signature)throw new g("JWS Signature missing or incorrect type");if(void 0!==e.header&&!$(e.header))throw new g("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=u(e.protected);n=JSON.parse(d.decode(t))}catch{throw new g("JWS Protected Header is invalid")}if(!H(n,e.header))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header};let i=!0;if(Q(g,new Map([["b64",!0]]),r?.crit,n,o).has("b64")&&(i=n.b64,"boolean"!=typeof i))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if("string"!=typeof a||!a)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');const s=r&&ee("algorithms",r.algorithms);if(s&&!s.has(a))throw new y('"alg" (Algorithm) Header Parameter value not allowed');if(i){if("string"!=typeof e.payload)throw new g("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new g("JWS Payload must be a string or an Uint8Array instance");let h=!1;"function"==typeof t?(t=await t(n,e),h=!0,Z(a,t,"verify"),U(t)&&(t=await G(t,a))):Z(a,t,"verify");const p=l(c.encode(e.protected??""),c.encode("."),"string"==typeof e.payload?c.encode(e.payload):e.payload);let w,f;try{w=u(e.signature)}catch{throw new g("Failed to base64url decode the signature")}if(!await ie(a,t,w,p))throw new A;if(i)try{f=u(e.payload)}catch{throw new g("Failed to base64url decode the payload")}else f="string"==typeof e.payload?c.encode(e.payload):e.payload;const m={payload:f};return void 0!==e.protected&&(m.protectedHeader=n),void 0!==e.header&&(m.unprotectedHeader=e.header),h?{...m,key:t}:m}({payload:o,protected:n,signature:i},t,r),h={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...h,key:s.key}:h}var se=e=>Math.floor(e.getTime()/1e3);const ce=86400,de=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var le=e=>{const t=de.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(r*ce);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n};const he=e=>e.toLowerCase().replace(/^application\//,"");var ue=(e,t,r={})=>{let n;try{n=JSON.parse(d.decode(t))}catch{}if(!$(n))throw new v("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&("string"!=typeof e.typ||he(e.typ)!==he(o)))throw new w('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:l}=r,h=[...i];void 0!==l&&h.push("iat"),void 0!==c&&h.push("aud"),void 0!==s&&h.push("sub"),void 0!==a&&h.push("iss");for(const e of new Set(h.reverse()))if(!(e in n))throw new w(`missing required "${e}" claim`,n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new w('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new w('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(u=n.aud,p="string"==typeof c?[c]:c,!("string"==typeof u?p.includes(u):Array.isArray(u)&&p.some(Set.prototype.has.bind(new Set(u))))))throw new w('unexpected "aud" claim value',n,"aud","check_failed");var u,p;let y;switch(typeof r.clockTolerance){case"string":y=le(r.clockTolerance);break;case"number":y=r.clockTolerance;break;case"undefined":y=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,g=se(m||new Date);if((void 0!==n.iat||l)&&"number"!=typeof n.iat)throw new w('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new w('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>g+y)throw new w('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new w('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=g-y)throw new f('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){const e=g-n.iat;if(e-y>("number"==typeof l?l:le(l)))throw new f('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-y)throw new w('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function pe(e,t,r){const n=await ae(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new v("JWTs MUST NOT use unencoded payload");const o={payload:ue(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...o,key:n.key}:o}var we=async(e,t,r)=>{const n=await oe(e,t,"sign");N(e,n);const o=await i.subtle.sign(ne(e,n.algorithm),n,r);return new Uint8Array(o)};class fe{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new g("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!H(this._protectedHeader,this._unprotectedHeader))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(Q(g,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=r;if("string"!=typeof o||!o)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');Z(o,e,"sign");let i,a=this._payload;n&&(a=c.encode(h(a))),i=this._protectedHeader?c.encode(h(JSON.stringify(this._protectedHeader))):c.encode("");const s=l(i,c.encode("."),a),u=await we(o,e,s),p={signature:h(u),payload:""};return n&&(p.payload=d.decode(a)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=d.decode(i)),p}}class ye{constructor(e){this._flattened=new fe(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function me(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ge{constructor(e={}){if(!$(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:me("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:me("setNotBefore",se(e))}:this._payload={...this._payload,nbf:se(new Date)+le(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:me("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:me("setExpirationTime",se(e))}:this._payload={...this._payload,exp:se(new Date)+le(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:se(new Date)}:e instanceof Date?this._payload={...this._payload,iat:me("setIssuedAt",se(e))}:this._payload="string"==typeof e?{...this._payload,iat:me("setIssuedAt",se(new Date)+le(e))}:{...this._payload,iat:me("setIssuedAt",e)},this}}class ve extends ge{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new ye(c.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new v("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}const be=(e,t)=>{if("string"!=typeof e||!e)throw new b(`${t} missing or invalid`)};async function Ee(e,t){if(!$(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),"sha256"!==t&&"sha384"!==t&&"sha512"!==t)throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":be(e.crv,'"crv" (Curve) Parameter'),be(e.x,'"x" (X Coordinate) Parameter'),be(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":be(e.crv,'"crv" (Subtype of Key Pair) Parameter'),be(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":be(e.e,'"e" (Exponent) Parameter'),be(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":be(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new m('"kty" (Key Type) Parameter missing or unsupported')}const n=c.encode(JSON.stringify(r));return h(await s(t,n))}function Se(e){return $(e)}function _e(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class ke{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(Se)}(e))throw new E("JSON Web Key Set malformed");this._jwks=_e(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},o=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new m('Unsupported "alg" value for a JSON Web Key Set')}}(r),i=this._jwks.keys.filter(e=>{let t=o===e.kty;if(t&&"string"==typeof n&&(t=n===e.kid),t&&"string"==typeof e.alg&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":t="Ed25519"===e.crv;break;case"EdDSA":t="Ed25519"===e.crv||"Ed448"===e.crv}return t}),{0:a,length:s}=i;if(0===s)throw new S;if(1!==s){const e=new _,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of i)try{yield await Ae(t,e,r)}catch{}},e}return Ae(this._cached,a,r)}}async function Ae(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await G({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new E("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function Te(e){const t=new ke(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>_e(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var Ie=async(e,t,r)=>{let n,o,i=!1;"function"==typeof AbortController&&(n=new AbortController,o=setTimeout(()=>{i=!0,n.abort()},t));const a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(e=>{if(i)throw new k;throw e});if(void 0!==o&&clearTimeout(o),200!==a.status)throw new p("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new p("Failed to parse the JSON Web Key Set HTTP response as JSON")}};let Pe;if("undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){Pe=`${"jose"}/${"v5.10.0"}`}const Re=Symbol();class Ce{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");var r,n;this._url=new URL(e.href),this._options={agent:t?.agent,headers:t?.headers},this._timeoutDuration="number"==typeof t?.timeoutDuration?t?.timeoutDuration:5e3,this._cooldownDuration="number"==typeof t?.cooldownDuration?t?.cooldownDuration:3e4,this._cacheMaxAge="number"==typeof t?.cacheMaxAge?t?.cacheMaxAge:6e5,void 0!==t?.[Re]&&(this._cache=t?.[Re],r=t?.[Re],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&$(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,$)&&(this._jwksTimestamp=this._cache.uat,this._local=Te(this._cache.jwks)))}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){this._local&&this.fresh()||await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof S&&!1===this.coolingDown())return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Pe&&!e.has("User-Agent")&&(e.set("User-Agent",Pe),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Ie(this._url,this._timeoutDuration,this._options).then(e=>{this._local=Te(e),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=e),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}}function xe(e,t){const r=new Ce(e,t),n=async(e,t)=>r.getKey(e,t);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}const De=u;function We(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new m("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function Oe(e,t){return async function(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:We(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:We(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:We(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":r={name:"Ed25519"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];const e=t?.crv??"Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new m("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];const e=t?.crv??"P-256";switch(e){case"P-256":case"P-384":case"P-521":r={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":r={name:e};break;default:throw new m("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return i.subtle.generateKey(r,t?.extractable??!1,n)}(e,t)}const He=async(e,t,r)=>{const n=new URL(t),o=n.origin+n.pathname+n.search,i=new URL(e).origin,a=await fetch(`${i}/.well-known/openid-configuration`).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),s=a.issuer,c=e=>e.endsWith("/")?e.slice(0,-1):e;if(c(e)!==c(s))throw new Error("RFC 9207 - iss !== idp - "+s+" !== "+e);sessionStorage.setItem("idp",s),sessionStorage.setItem("token_endpoint",a.token_endpoint),sessionStorage.setItem("jwks_uri",a.jwks_uri);let d=r?.client_id;if(!d){const e=a.registration_endpoint,t=await(async(e,t)=>{const r={...t,grant_types:["authorization_code","refresh_token"],token_endpoint_auth_method:"none",application_type:"web",subject_type:"public"};return fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})})(e,r??{redirect_uris:[o]}).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()});d=t.client_id}try{new URL(d)}catch{sessionStorage.setItem("client_id",d)}const{pkce_code_verifier:l,pkce_code_challenge:h}=await $e();sessionStorage.setItem("pkce_code_verifier",l);const u=window.crypto.randomUUID();sessionStorage.setItem("csrf_token",u);const p=a.authorization_endpoint+"?response_type=code"+`&redirect_uri=${encodeURIComponent(o)}&scope=openid offline_access webid`+`&client_id=${encodeURIComponent(d)}&code_challenge_method=S256`+`&code_challenge=${h}`+`&state=${u}&prompt=consent`;window.location.href=p},$e=async()=>{const e=window.crypto.randomUUID()+"-"+window.crypto.randomUUID(),t=new Uint8Array(await window.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)));return{pkce_code_verifier:e,pkce_code_challenge:btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}},Ne=async(e,t,r,n,o,i)=>{const a=await re(i.publicKey);a.alg="ES256";const s=await new ve({htu:o,htm:"POST"}).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:a}).sign(i.privateKey);return fetch(o,{method:"POST",headers:{dpop:s,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:r,client_id:n})})},Ue=async(e,t,r,n)=>{const o=await re(n.publicKey);o.alg="ES256";const i=await new ve({htu:r,htm:"POST"}).setIssuedAt().setJti(self.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:o}).sign(n.privateKey);return fetch(r,{method:"POST",headers:{dpop:i,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:t})})};var je;!function(e){e.STATE_CHANGE="sessionStateChange",e.EXPIRATION_WARNING="sessionExpirationWarning",e.EXPIRATION="sessionExpiration"}(je||(je={}));class Je extends EventTarget{isActive_=!1;exp_;webId_=void 0;currentAth_=void 0;information;database;refreshPromise;resolveRefresh;rejectRefresh;constructor(e,t){super(),this.authFetch=this.authFetch.bind(this),this.information={clientDetails:e},this.database=t?.database,t?.onSessionStateChange&&this.addEventListener(je.STATE_CHANGE,e=>t.onSessionStateChange?.(e)),t?.onSessionExpirationWarning&&this.addEventListener(je.EXPIRATION_WARNING,e=>t?.onSessionExpirationWarning?.(e)),t?.onSessionExpiration&&this.addEventListener(je.EXPIRATION,e=>t?.onSessionExpiration?.(e))}async login(e,t){await He(e,t,this.information.clientDetails)}async handleRedirectFromLogin(){const e=await(async(e,t)=>{const r=new URL(window.location.href),n=r.searchParams.get("code");if(null===n)return{clientDetails:e};const o=sessionStorage.getItem("idp");if(null===o||r.searchParams.get("iss")!==o)throw new Error("RFC 9207 - iss !== idp - "+r.searchParams.get("iss")+" !== "+o);if(r.searchParams.get("state")!==sessionStorage.getItem("csrf_token"))throw new Error("RFC 6749 - state !== csrf_token - "+r.searchParams.get("state")+" !== "+sessionStorage.getItem("csrf_token"));r.searchParams.delete("iss"),r.searchParams.delete("state"),r.searchParams.delete("code"),window.history.pushState({},document.title,r.toString());const i=sessionStorage.getItem("pkce_code_verifier");if(null===i)throw new Error("Access Token Request preparation - Could not find in sessionStorage: pkce_code_verifier");const a=e?.client_id||sessionStorage.getItem("client_id");if(!a)throw new Error("Access Token Request preparation - Could not find in sessionStorage: client_id (dynamic registration)");const s=sessionStorage.getItem("token_endpoint");if(null===s)throw new Error("Access Token Request preparation - Could not find in sessionStorage: token_endpoint");const c=await Oe("ES256"),d=await Ne(n,i,r.toString(),a,s,c).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),l=d.access_token,h=sessionStorage.getItem("jwks_uri");if(null===h)throw new Error("Access Token validation preparation - Could not find in sessionStorage: jwks_uri");const u=xe(new URL(h)),{payload:p}=await pe(l,u,{issuer:o,audience:"solid"}),w=await Ee(await re(c.publicKey));if(p.cnf.jkt!==w)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+p.cnf.jkt+" !== "+w);if(p.client_id!==a)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+p.client_id+" !== "+a);const f={...d,dpop_key_pair:c},y={idp:o,jwks_uri:h,token_endpoint:s};return e||(e={redirect_uris:[r.toString()]}),e.client_id=a,t&&(await t.init(),await Promise.all([t.setItem("idp",o),t.setItem("jwks_uri",h),t.setItem("token_endpoint",s),t.setItem("client_id",a),t.setItem("dpop_keypair",c),t.setItem("refresh_token",d.refresh_token)]),t.close()),sessionStorage.removeItem("csrf_token"),sessionStorage.removeItem("pkce_code_verifier"),sessionStorage.removeItem("idp"),sessionStorage.removeItem("jwks_uri"),sessionStorage.removeItem("token_endpoint"),sessionStorage.removeItem("client_id"),{clientDetails:e,idpDetails:y,tokenDetails:f}})(this.information.clientDetails,this.database);e.tokenDetails&&(this.information.clientDetails=e.clientDetails,this.information.idpDetails=e.idpDetails,await this.setTokenDetails(e.tokenDetails),this.dispatchStateChangeEvent())}async restore(){if(!this.database)throw new Error("Could not refresh tokens: missing database. Provide database in sessionOption.");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=new Promise((e,t)=>{this.resolveRefresh=e,this.rejectRefresh=t});const e=this.isActive;return(async e=>{try{await e.init();const t=await e.getItem("client_id"),r=await e.getItem("token_endpoint"),n=await e.getItem("dpop_keypair"),o=await e.getItem("refresh_token");if(null===t||null===r||null===n||null===o)throw new Error("Could not refresh tokens: details missing from database.");const i=await Ue(o,t,r,n).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),a=i.access_token,s=await e.getItem("idp");if(null===s)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: idp");const c=await e.getItem("jwks_uri");if(null===c)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: jwks_uri");const d=xe(new URL(c)),{payload:l}=await pe(a,d,{issuer:s,audience:"solid"}),h=await Ee(await re(n.publicKey));if(l.cnf.jkt!==h)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+l.cnf.jkt+" !== "+h);if(l.client_id!==t)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+l.client_id+" !== "+t);return await e.setItem("refresh_token",i.refresh_token),{...i,dpop_key_pair:n}}finally{e.close()}})(this.database).then(e=>this.setTokenDetails(e)).then(()=>this.resolveRefresh()).catch(e=>{this.isActive?(this.rejectRefresh(new Error(e||"Token refresh failed")),this.isExpired()?this.dispatchExpirationEvent():this.dispatchExpirationWarningEvent()):this.rejectRefresh(new Error("No session to restore."))}).finally(()=>{this.clearRefreshPromise(),e!==this.isActive&&this.dispatchStateChangeEvent()}),this.refreshPromise}async logout(){this.isActive_=!1,this.exp_=void 0,this.webId_=void 0,this.currentAth_=void 0,this.information.idpDetails=void 0,this.information.tokenDetails=void 0,this.refreshPromise&&this.rejectRefresh&&(this.rejectRefresh(new Error("Logout during token refresh.")),this.clearRefreshPromise()),this.database&&(await this.database.init(),await this.database.clear(),this.database.close()),this.dispatchStateChangeEvent()}async authFetch(e,t,r){if(!this.isActive)return fetch(e,t);let n,o,i;e instanceof Request?(n=new URL(e.url),o=t?.method||e?.method||"GET",i=new Headers(e.headers)):(t=t||{},n=new URL(e.toString()),o=t.method||"GET",i=t.headers?new Headers(t.headers):new Headers),await this._renewTokensIfExpired(),r=r??{htu:`${n.origin}${n.pathname}`,htm:o.toUpperCase()};const a=await this._createSignedDPoPToken(r);return i.set("dpop",a),i.set("authorization",`DPoP ${this.information.tokenDetails.access_token}`),e instanceof Request?fetch(new Request(e,{...t,headers:i})):fetch(n,{...t,headers:i})}async setTokenDetails(e){this.information.tokenDetails=e,await this._updateSessionDetailsFromToken(e.access_token)}clearRefreshPromise(){this.refreshPromise=void 0,this.resolveRefresh=void 0,this.rejectRefresh=void 0}get isActive(){return this.isActive_}get webId(){return this.webId_}isExpired(){return!this.exp_||this._isTokenExpired(this.exp_)}getExpiresIn(){return this.exp_?this._getTokenTTL(this.exp_):-1}getTokenDetails(){return this.information.tokenDetails}async _renewTokensIfExpired(){this.isExpired()&&(this.refreshPromise?await this.refreshPromise:await this.restore())}async _computeAth(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),n=Array.from(new Uint8Array(r));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async _createSignedDPoPToken(e){if(!this.information.tokenDetails||!this.currentAth_)throw new Error("Session not established.");e.ath=this.currentAth_;const t=await re(this.information.tokenDetails.dpop_key_pair.publicKey);return new ve(e).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:t}).sign(this.information.tokenDetails.dpop_key_pair.privateKey)}async _updateSessionDetailsFromToken(e){if(e)try{const t=function(e){if("string"!=typeof e)throw new v("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new v("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new v("Invalid JWT");if(!t)throw new v("JWTs must contain a payload");let n,o;try{n=De(t)}catch{throw new v("Failed to base64url decode the payload")}try{o=JSON.parse(d.decode(n))}catch{throw new v("Failed to parse the decoded payload as JSON")}if(!$(o))throw new v("Invalid JWT Claims Set");return o}(e),r=t.webid;if(!r)throw new Error("Missing webid claim in access token");const n=t.exp;if(!n)throw new Error("Missing exp claim in access token");this.currentAth_=await this._computeAth(e),this.webId_=r,this.exp_=n,this.isActive_=!0}catch(e){await this.logout()}else await this.logout()}_isTokenExpired(e,t=0){return!("number"==typeof e&&!isNaN(e))||this._getTokenTTL(e,t)<0}_getTokenTTL(e,t=0){return e-(Math.floor(Date.now()/1e3)+t)}dispatchStateChangeEvent(){this.dispatchEvent(new CustomEvent(je.STATE_CHANGE,{detail:{isActive:this.isActive,webId:this.webId}}))}dispatchExpirationWarningEvent(){this.dispatchEvent(new CustomEvent(je.EXPIRATION_WARNING,{detail:{expires_in:this.getExpiresIn()}}))}dispatchExpirationEvent(){this.dispatchEvent(new CustomEvent(je.EXPIRATION))}}var Le;!function(e){e.SCHEDULE="SCHEDULE",e.REFRESH="REFRESH",e.STOP="STOP",e.DISCONNECT="DISCONNECT",e.TOKEN_DETAILS="TOKEN_DETAILS",e.ERROR_ON_REFRESH="ERROR_ON_REFRESH",e.EXPIRED="EXPIRED"}(Le||(Le={}));class Ke{dbName;storeName;dbVersion;db=null;constructor(e="soidc",t="session",r=1){this.dbName=e,this.storeName=t,this.dbVersion=r}async init(){return new Promise((e,t)=>{const r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=e=>{t(new Error(`Database error: ${e.target.error}`))},r.onsuccess=t=>{this.db=t.target.result,e(this)},r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.storeName)||t.createObjectStore(this.storeName)}})}async setItem(e,t){return this.db||await this.init(),new Promise((r,n)=>{const o=this.db.transaction(this.storeName,"readwrite");o.oncomplete=()=>{r()},o.onerror=t=>{n(new Error(`Transaction error for setItem(${e},...): ${t.target.error}`))},o.onabort=t=>{n(new Error(`Transaction aborted for setItem(${e},...): ${t.target.error}`))};o.objectStore(this.storeName).put(t,e)})}async getItem(e){return this.db||await this.init(),new Promise((t,r)=>{const n=this.db.transaction(this.storeName,"readonly");n.onerror=t=>{r(new Error(`Transaction error for getItem(${e}): ${t.target.error}`))},n.onabort=t=>{r(new Error(`Transaction aborted for getItem(${e}): ${t.target.error}`))};const o=n.objectStore(this.storeName).get(e);o.onsuccess=()=>{t(o.result||null)}})}async deleteItem(e){return this.db||await this.init(),new Promise((t,r)=>{const n=this.db.transaction(this.storeName,"readwrite");n.oncomplete=()=>{t()},n.onerror=t=>{r(new Error(`Transaction error for deleteItem(${e}): ${t.target.error}`))},n.onabort=t=>{r(new Error(`Transaction aborted for deleteItem(${e}): ${t.target.error}`))};n.objectStore(this.storeName).delete(e)})}async clear(){return this.db||await this.init(),new Promise((e,t)=>{const r=this.db.transaction(this.storeName,"readwrite");r.oncomplete=()=>{e()},r.onerror=e=>{t(new Error(`Transaction error for clear(): ${e.target.error}`))},r.onabort=e=>{t(new Error(`Transaction aborted for clear(): ${e.target.error}`))};r.objectStore(this.storeName).clear()})}close(){this.db&&(this.db.close(),this.db=null)}}class Me extends Je{worker;constructor(e,t){const r=new Ke;super(e,{...t,database:r});const o=t?.workerUrl??new URL(n(552),n.b);this.worker=new SharedWorker(o,{type:"module"}),this.worker.port.onmessage=e=>{this.handleWorkerMessage(e.data).catch(console.error)},window.addEventListener("beforeunload",()=>{this.worker.port.postMessage({type:Le.DISCONNECT})})}async handleWorkerMessage(e){const{type:t,payload:r,error:n}=e;switch(t){case Le.TOKEN_DETAILS:const e=this.isActive;await this.setTokenDetails(r.tokenDetails),e!==this.isActive&&this.dispatchStateChangeEvent(),this.refreshPromise&&this.resolveRefresh&&(this.resolveRefresh(),this.clearRefreshPromise());break;case Le.ERROR_ON_REFRESH:this.isActive&&this.dispatchExpirationWarningEvent(),this.refreshPromise&&this.rejectRefresh&&(this.isActive?this.rejectRefresh(new Error(n||"Token refresh failed")):this.rejectRefresh(new Error("No session to restore")),this.clearRefreshPromise());break;case Le.EXPIRED:this.isActive&&(this.dispatchExpirationEvent(),await this.logout()),this.refreshPromise&&this.rejectRefresh&&(this.rejectRefresh(new Error(n||"Token refresh failed")),this.clearRefreshPromise())}}async handleRedirectFromLogin(){await super.handleRedirectFromLogin(),this.isActive&&this.worker.port.postMessage({type:Le.SCHEDULE,payload:{...this.getTokenDetails(),expires_in:this.getExpiresIn()}})}async restore(){return this.refreshPromise||(this.refreshPromise=new Promise((e,t)=>{this.resolveRefresh=e,this.rejectRefresh=t}),this.worker.port.postMessage({type:Le.REFRESH})),this.refreshPromise}async logout(){this.worker.port.postMessage({type:Le.STOP}),await super.logout()}}var Fe=crypto;const Ve=e=>e instanceof CryptoKey;var Be=async(e,t)=>{const r=`SHA-${e.slice(-3)}`;return new Uint8Array(await Fe.subtle.digest(r,t))};const Ge=new TextEncoder,qe=new TextDecoder;function ze(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const Xe=e=>(e=>{let t=e;"string"==typeof t&&(t=Ge.encode(t));const r=[];for(let e=0;e<t.length;e+=32768)r.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(r.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),Ye=e=>{let t=e;t instanceof Uint8Array&&(t=qe.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Ze extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}Ze.code="ERR_JOSE_GENERIC";class Qe extends Ze{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}Qe.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class et extends Ze{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}et.code="ERR_JWT_EXPIRED";class tt extends Ze{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}tt.code="ERR_JOSE_ALG_NOT_ALLOWED";class rt extends Ze{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}rt.code="ERR_JOSE_NOT_SUPPORTED";(class extends Ze{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends Ze{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class nt extends Ze{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}nt.code="ERR_JWS_INVALID";class ot extends Ze{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}ot.code="ERR_JWT_INVALID";class it extends Ze{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}it.code="ERR_JWK_INVALID";class at extends Ze{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}at.code="ERR_JWKS_INVALID";class st extends Ze{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}st.code="ERR_JWKS_NO_MATCHING_KEY";class ct extends Ze{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}ct.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class dt extends Ze{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}dt.code="ERR_JWKS_TIMEOUT";class lt extends Ze{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function ht(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ut(e,t){return e.name===t}function pt(e){return parseInt(e.name.slice(4),10)}function wt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ut(e.algorithm,"HMAC"))throw ht("HMAC");const r=parseInt(t.slice(2),10);if(pt(e.algorithm.hash)!==r)throw ht(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ut(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ht("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(pt(e.algorithm.hash)!==r)throw ht(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ut(e.algorithm,"RSA-PSS"))throw ht("RSA-PSS");const r=parseInt(t.slice(2),10);if(pt(e.algorithm.hash)!==r)throw ht(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw ht("Ed25519 or Ed448");break;case"Ed25519":if(!ut(e.algorithm,"Ed25519"))throw ht("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!ut(e.algorithm,"ECDSA"))throw ht("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw ht(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}function ft(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}lt.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var yt=(e,...t)=>ft("Key must be ",e,...t);function mt(e,t,...r){return ft(`Key for the ${e} algorithm must be `,t,...r)}var gt=e=>!!Ve(e)||"KeyObject"===e?.[Symbol.toStringTag];const vt=["CryptoKey"];var bt=(...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0};function Et(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}var St=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function _t(e){return Et(e)&&"string"==typeof e.kty}var kt=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new rt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new rt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new rt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new rt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,Fe.subtle.importKey("jwk",o,...n)};const At=e=>Ye(e);let Tt,It;const Pt=e=>"KeyObject"===e?.[Symbol.toStringTag],Rt=async(e,t,r,n,o=!1)=>{let i=e.get(t);if(i?.[n])return i[n];const a=await kt({...r,alg:n});return o&&Object.freeze(t),i?i[n]=a:e.set(t,{[n]:a}),a};var Ct=(e,t)=>{if(Pt(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?At(r.k):(It||(It=new WeakMap),Rt(It,e,r,t))}if(_t(e)){if(e.k)return Ye(e.k);It||(It=new WeakMap);return Rt(It,e,e,t,!0)}return e},xt=(e,t)=>{if(Pt(e)){let r=e.export({format:"jwk"});return r.k?At(r.k):(Tt||(Tt=new WeakMap),Rt(Tt,e,r,t))}if(_t(e)){if(e.k)return Ye(e.k);Tt||(Tt=new WeakMap);return Rt(Tt,e,e,t,!0)}return e};async function Dt(e,t){if(!Et(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Ye(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new rt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return kt({...e,alg:t});default:throw new rt('Unsupported "kty" (Key Type) Parameter value')}}const Wt=e=>e?.[Symbol.toStringTag],Ot=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Ht=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&_t(t)){if(function(e){return _t(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&Ot(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!gt(t))throw new TypeError(mt(e,t,...vt,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${Wt(t)} instances for symmetric algorithms must be of type "secret"`)}};function $t(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Ht(t,r,n,e):((e,t,r,n)=>{if(n&&_t(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&Ot(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&Ot(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!gt(t))throw new TypeError(mt(e,t,...vt,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}$t.bind(void 0,!1);const Nt=$t.bind(void 0,!0);function Ut(e,t,r,n,o){if(void 0!==o.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!i.has(t))throw new rt(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}var jt=(e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};var Jt=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:Xe(e)};if(!Ve(e))throw new TypeError(yt(e,...vt,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:t,key_ops:r,alg:n,use:o,...i}=await Fe.subtle.exportKey("jwk",e);return i};async function Lt(e){return Jt(e)}function Kt(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new rt(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Mt(e,t,r){if("sign"===r&&(t=await xt(t,e)),"verify"===r&&(t=await Ct(t,e)),Ve(t))return wt(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(yt(t,...vt));return Fe.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(yt(t,...vt,"Uint8Array","JSON Web Key"))}var Ft=async(e,t,r,n)=>{const o=await Mt(e,t,"verify");St(e,o);const i=Kt(e,o.algorithm);try{return await Fe.subtle.verify(i,o,r,n)}catch{return!1}};async function Vt(e,t,r){if(e instanceof Uint8Array&&(e=qe.decode(e)),"string"!=typeof e)throw new nt("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:i,length:a}=e.split(".");if(3!==a)throw new nt("Invalid Compact JWS");const s=await async function(e,t,r){if(!Et(e))throw new nt("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new nt('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new nt("JWS Protected Header incorrect type");if(void 0===e.payload)throw new nt("JWS Payload missing");if("string"!=typeof e.signature)throw new nt("JWS Signature missing or incorrect type");if(void 0!==e.header&&!Et(e.header))throw new nt("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=Ye(e.protected);n=JSON.parse(qe.decode(t))}catch{throw new nt("JWS Protected Header is invalid")}if(!bt(n,e.header))throw new nt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header};let i=!0;if(Ut(nt,new Map([["b64",!0]]),r?.crit,n,o).has("b64")&&(i=n.b64,"boolean"!=typeof i))throw new nt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if("string"!=typeof a||!a)throw new nt('JWS "alg" (Algorithm) Header Parameter missing or invalid');const s=r&&jt("algorithms",r.algorithms);if(s&&!s.has(a))throw new tt('"alg" (Algorithm) Header Parameter value not allowed');if(i){if("string"!=typeof e.payload)throw new nt("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new nt("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t?(t=await t(n,e),c=!0,Nt(a,t,"verify"),_t(t)&&(t=await Dt(t,a))):Nt(a,t,"verify");const d=ze(Ge.encode(e.protected??""),Ge.encode("."),"string"==typeof e.payload?Ge.encode(e.payload):e.payload);let l,h;try{l=Ye(e.signature)}catch{throw new nt("Failed to base64url decode the signature")}if(!await Ft(a,t,l,d))throw new lt;if(i)try{h=Ye(e.payload)}catch{throw new nt("Failed to base64url decode the payload")}else h="string"==typeof e.payload?Ge.encode(e.payload):e.payload;const u={payload:h};return void 0!==e.protected&&(u.protectedHeader=n),void 0!==e.header&&(u.unprotectedHeader=e.header),c?{...u,key:t}:u}({payload:o,protected:n,signature:i},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...c,key:s.key}:c}var Bt=e=>Math.floor(e.getTime()/1e3);const Gt=86400,qt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var zt=e=>{const t=qt.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(r*Gt);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n};const Xt=e=>e.toLowerCase().replace(/^application\//,"");var Yt=(e,t,r={})=>{let n;try{n=JSON.parse(qe.decode(t))}catch{}if(!Et(n))throw new ot("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&("string"!=typeof e.typ||Xt(e.typ)!==Xt(o)))throw new Qe('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:d}=r,l=[...i];void 0!==d&&l.push("iat"),void 0!==c&&l.push("aud"),void 0!==s&&l.push("sub"),void 0!==a&&l.push("iss");for(const e of new Set(l.reverse()))if(!(e in n))throw new Qe(`missing required "${e}" claim`,n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new Qe('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new Qe('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(h=n.aud,u="string"==typeof c?[c]:c,!("string"==typeof h?u.includes(h):Array.isArray(h)&&u.some(Set.prototype.has.bind(new Set(h))))))throw new Qe('unexpected "aud" claim value',n,"aud","check_failed");var h,u;let p;switch(typeof r.clockTolerance){case"string":p=zt(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:w}=r,f=Bt(w||new Date);if((void 0!==n.iat||d)&&"number"!=typeof n.iat)throw new Qe('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new Qe('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>f+p)throw new Qe('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new Qe('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=f-p)throw new et('"exp" claim timestamp check failed',n,"exp","check_failed")}if(d){const e=f-n.iat;if(e-p>("number"==typeof d?d:zt(d)))throw new et('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-p)throw new Qe('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Zt(e,t,r){const n=await Vt(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new ot("JWTs MUST NOT use unencoded payload");const o={payload:Yt(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...o,key:n.key}:o}var Qt=async(e,t,r)=>{const n=await Mt(e,t,"sign");St(e,n);const o=await Fe.subtle.sign(Kt(e,n.algorithm),n,r);return new Uint8Array(o)};class er{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new nt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!bt(this._protectedHeader,this._unprotectedHeader))throw new nt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(Ut(nt,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new nt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=r;if("string"!=typeof o||!o)throw new nt('JWS "alg" (Algorithm) Header Parameter missing or invalid');Nt(o,e,"sign");let i,a=this._payload;n&&(a=Ge.encode(Xe(a))),i=this._protectedHeader?Ge.encode(Xe(JSON.stringify(this._protectedHeader))):Ge.encode("");const s=ze(i,Ge.encode("."),a),c=await Qt(o,e,s),d={signature:Xe(c),payload:""};return n&&(d.payload=qe.decode(a)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=qe.decode(i)),d}}class tr{constructor(e){this._flattened=new er(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function rr(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class nr{constructor(e={}){if(!Et(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:rr("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:rr("setNotBefore",Bt(e))}:this._payload={...this._payload,nbf:Bt(new Date)+zt(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:rr("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:rr("setExpirationTime",Bt(e))}:this._payload={...this._payload,exp:Bt(new Date)+zt(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:Bt(new Date)}:e instanceof Date?this._payload={...this._payload,iat:rr("setIssuedAt",Bt(e))}:this._payload="string"==typeof e?{...this._payload,iat:rr("setIssuedAt",Bt(new Date)+zt(e))}:{...this._payload,iat:rr("setIssuedAt",e)},this}}class or extends nr{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new tr(Ge.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new ot("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}const ir=(e,t)=>{if("string"!=typeof e||!e)throw new it(`${t} missing or invalid`)};async function ar(e,t){if(!Et(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),"sha256"!==t&&"sha384"!==t&&"sha512"!==t)throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":ir(e.crv,'"crv" (Curve) Parameter'),ir(e.x,'"x" (X Coordinate) Parameter'),ir(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":ir(e.crv,'"crv" (Subtype of Key Pair) Parameter'),ir(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":ir(e.e,'"e" (Exponent) Parameter'),ir(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":ir(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new rt('"kty" (Key Type) Parameter missing or unsupported')}const n=Ge.encode(JSON.stringify(r));return Xe(await Be(t,n))}function sr(e){return Et(e)}function cr(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class dr{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(sr)}(e))throw new at("JSON Web Key Set malformed");this._jwks=cr(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},o=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new rt('Unsupported "alg" value for a JSON Web Key Set')}}(r),i=this._jwks.keys.filter(e=>{let t=o===e.kty;if(t&&"string"==typeof n&&(t=n===e.kid),t&&"string"==typeof e.alg&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":t="Ed25519"===e.crv;break;case"EdDSA":t="Ed25519"===e.crv||"Ed448"===e.crv}return t}),{0:a,length:s}=i;if(0===s)throw new st;if(1!==s){const e=new ct,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of i)try{yield await lr(t,e,r)}catch{}},e}return lr(this._cached,a,r)}}async function lr(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await Dt({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new at("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function hr(e){const t=new dr(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>cr(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var ur=async(e,t,r)=>{let n,o,i=!1;"function"==typeof AbortController&&(n=new AbortController,o=setTimeout(()=>{i=!0,n.abort()},t));const a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(e=>{if(i)throw new dt;throw e});if(void 0!==o&&clearTimeout(o),200!==a.status)throw new Ze("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new Ze("Failed to parse the JSON Web Key Set HTTP response as JSON")}};let pr;if("undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){pr=`${"jose"}/${"v5.10.0"}`}const wr=Symbol();class fr{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");var r,n;this._url=new URL(e.href),this._options={agent:t?.agent,headers:t?.headers},this._timeoutDuration="number"==typeof t?.timeoutDuration?t?.timeoutDuration:5e3,this._cooldownDuration="number"==typeof t?.cooldownDuration?t?.cooldownDuration:3e4,this._cacheMaxAge="number"==typeof t?.cacheMaxAge?t?.cacheMaxAge:6e5,void 0!==t?.[wr]&&(this._cache=t?.[wr],r=t?.[wr],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&Et(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,Et)&&(this._jwksTimestamp=this._cache.uat,this._local=hr(this._cache.jwks)))}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){this._local&&this.fresh()||await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof st&&!1===this.coolingDown())return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);pr&&!e.has("User-Agent")&&(e.set("User-Agent",pr),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=ur(this._url,this._timeoutDuration,this._options).then(e=>{this._local=hr(e),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=e),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}}function yr(e,t){const r=new fr(e,t),n=async(e,t)=>r.getKey(e,t);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}const mr=Ye;function gr(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new rt("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function vr(e,t){return async function(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:gr(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:gr(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:gr(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":r={name:"Ed25519"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];const e=t?.crv??"Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new rt("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];const e=t?.crv??"P-256";switch(e){case"P-256":case"P-384":case"P-521":r={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":r={name:e};break;default:throw new rt("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new rt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return Fe.subtle.generateKey(r,t?.extractable??!1,n)}(e,t)}const br=async(e,t,r)=>{const n=new URL(t),o=n.origin+n.pathname+n.search,i=new URL(e).origin,a=await fetch(`${i}/.well-known/openid-configuration`).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),s=a.issuer,c=e=>e.endsWith("/")?e.slice(0,-1):e;if(c(e)!==c(s))throw new Error("RFC 9207 - iss !== idp - "+s+" !== "+e);sessionStorage.setItem("idp",s),sessionStorage.setItem("token_endpoint",a.token_endpoint),sessionStorage.setItem("jwks_uri",a.jwks_uri);let d=r?.client_id;if(!d){const e=a.registration_endpoint,t=await(async(e,t)=>{const r={...t,grant_types:["authorization_code","refresh_token"],token_endpoint_auth_method:"none",application_type:"web",subject_type:"public"};return fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})})(e,r??{redirect_uris:[o]}).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()});d=t.client_id}try{new URL(d)}catch{sessionStorage.setItem("client_id",d)}const{pkce_code_verifier:l,pkce_code_challenge:h}=await Er();sessionStorage.setItem("pkce_code_verifier",l);const u=window.crypto.randomUUID();sessionStorage.setItem("csrf_token",u);const p=a.authorization_endpoint+"?response_type=code"+`&redirect_uri=${encodeURIComponent(o)}&scope=openid offline_access webid`+`&client_id=${encodeURIComponent(d)}&code_challenge_method=S256`+`&code_challenge=${h}`+`&state=${u}&prompt=consent`;window.location.href=p},Er=async()=>{const e=window.crypto.randomUUID()+"-"+window.crypto.randomUUID(),t=new Uint8Array(await window.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)));return{pkce_code_verifier:e,pkce_code_challenge:btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}},Sr=async(e,t,r,n,o,i)=>{const a=await Lt(i.publicKey);a.alg="ES256";const s=await new or({htu:o,htm:"POST"}).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:a}).sign(i.privateKey);return fetch(o,{method:"POST",headers:{dpop:s,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:r,client_id:n})})},_r=async(e,t,r,n)=>{const o=await Lt(n.publicKey);o.alg="ES256";const i=await new or({htu:r,htm:"POST"}).setIssuedAt().setJti(self.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:o}).sign(n.privateKey);return fetch(r,{method:"POST",headers:{dpop:i,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:t})})};var kr;!function(e){e.STATE_CHANGE="sessionStateChange",e.EXPIRATION_WARNING="sessionExpirationWarning",e.EXPIRATION="sessionExpiration"}(kr||(kr={}));class Ar extends EventTarget{isActive_=!1;exp_;webId_=void 0;currentAth_=void 0;information;database;refreshPromise;resolveRefresh;rejectRefresh;constructor(e,t){super(),this.authFetch=this.authFetch.bind(this),this.information={clientDetails:e},this.database=t?.database,t?.onSessionStateChange&&this.addEventListener(kr.STATE_CHANGE,e=>t.onSessionStateChange?.(e)),t?.onSessionExpirationWarning&&this.addEventListener(kr.EXPIRATION_WARNING,e=>t?.onSessionExpirationWarning?.(e)),t?.onSessionExpiration&&this.addEventListener(kr.EXPIRATION,e=>t?.onSessionExpiration?.(e))}async login(e,t){await br(e,t,this.information.clientDetails)}async handleRedirectFromLogin(){const e=await(async(e,t)=>{const r=new URL(window.location.href),n=r.searchParams.get("code");if(null===n)return{clientDetails:e};const o=sessionStorage.getItem("idp");if(null===o||r.searchParams.get("iss")!==o)throw new Error("RFC 9207 - iss !== idp - "+r.searchParams.get("iss")+" !== "+o);if(r.searchParams.get("state")!==sessionStorage.getItem("csrf_token"))throw new Error("RFC 6749 - state !== csrf_token - "+r.searchParams.get("state")+" !== "+sessionStorage.getItem("csrf_token"));r.searchParams.delete("iss"),r.searchParams.delete("state"),r.searchParams.delete("code"),window.history.pushState({},document.title,r.toString());const i=sessionStorage.getItem("pkce_code_verifier");if(null===i)throw new Error("Access Token Request preparation - Could not find in sessionStorage: pkce_code_verifier");const a=e?.client_id||sessionStorage.getItem("client_id");if(!a)throw new Error("Access Token Request preparation - Could not find in sessionStorage: client_id (dynamic registration)");const s=sessionStorage.getItem("token_endpoint");if(null===s)throw new Error("Access Token Request preparation - Could not find in sessionStorage: token_endpoint");const c=await vr("ES256"),d=await Sr(n,i,r.toString(),a,s,c).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),l=d.access_token,h=sessionStorage.getItem("jwks_uri");if(null===h)throw new Error("Access Token validation preparation - Could not find in sessionStorage: jwks_uri");const u=yr(new URL(h)),{payload:p}=await Zt(l,u,{issuer:o,audience:"solid"}),w=await ar(await Lt(c.publicKey));if(p.cnf.jkt!==w)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+p.cnf.jkt+" !== "+w);if(p.client_id!==a)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+p.client_id+" !== "+a);const f={...d,dpop_key_pair:c},y={idp:o,jwks_uri:h,token_endpoint:s};return e||(e={redirect_uris:[r.toString()]}),e.client_id=a,t&&(await t.init(),await Promise.all([t.setItem("idp",o),t.setItem("jwks_uri",h),t.setItem("token_endpoint",s),t.setItem("client_id",a),t.setItem("dpop_keypair",c),t.setItem("refresh_token",d.refresh_token)]),t.close()),sessionStorage.removeItem("csrf_token"),sessionStorage.removeItem("pkce_code_verifier"),sessionStorage.removeItem("idp"),sessionStorage.removeItem("jwks_uri"),sessionStorage.removeItem("token_endpoint"),sessionStorage.removeItem("client_id"),{clientDetails:e,idpDetails:y,tokenDetails:f}})(this.information.clientDetails,this.database);e.tokenDetails&&(this.information.clientDetails=e.clientDetails,this.information.idpDetails=e.idpDetails,await this.setTokenDetails(e.tokenDetails),this.dispatchStateChangeEvent())}async restore(){if(!this.database)throw new Error("Could not refresh tokens: missing database. Provide database in sessionOption.");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=new Promise((e,t)=>{this.resolveRefresh=e,this.rejectRefresh=t});const e=this.isActive;return(async e=>{try{await e.init();const t=await e.getItem("client_id"),r=await e.getItem("token_endpoint"),n=await e.getItem("dpop_keypair"),o=await e.getItem("refresh_token");if(null===t||null===r||null===n||null===o)throw new Error("Could not refresh tokens: details missing from database.");const i=await _r(o,t,r,n).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),a=i.access_token,s=await e.getItem("idp");if(null===s)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: idp");const c=await e.getItem("jwks_uri");if(null===c)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: jwks_uri");const d=yr(new URL(c)),{payload:l}=await Zt(a,d,{issuer:s,audience:"solid"}),h=await ar(await Lt(n.publicKey));if(l.cnf.jkt!==h)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+l.cnf.jkt+" !== "+h);if(l.client_id!==t)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+l.client_id+" !== "+t);return await e.setItem("refresh_token",i.refresh_token),{...i,dpop_key_pair:n}}finally{e.close()}})(this.database).then(e=>this.setTokenDetails(e)).then(()=>this.resolveRefresh()).catch(e=>{this.isActive?(this.rejectRefresh(new Error(e||"Token refresh failed")),this.isExpired()?this.dispatchExpirationEvent():this.dispatchExpirationWarningEvent()):this.rejectRefresh(new Error("No session to restore."))}).finally(()=>{this.clearRefreshPromise(),e!==this.isActive&&this.dispatchStateChangeEvent()}),this.refreshPromise}async logout(){this.isActive_=!1,this.exp_=void 0,this.webId_=void 0,this.currentAth_=void 0,this.information.idpDetails=void 0,this.information.tokenDetails=void 0,this.refreshPromise&&this.rejectRefresh&&(this.rejectRefresh(new Error("Logout during token refresh.")),this.clearRefreshPromise()),this.database&&(await this.database.init(),await this.database.clear(),this.database.close()),this.dispatchStateChangeEvent()}async authFetch(e,t,r){if(!this.isActive)return fetch(e,t);let n,o,i;e instanceof Request?(n=new URL(e.url),o=t?.method||e?.method||"GET",i=new Headers(e.headers)):(t=t||{},n=new URL(e.toString()),o=t.method||"GET",i=t.headers?new Headers(t.headers):new Headers),await this._renewTokensIfExpired(),r=r??{htu:`${n.origin}${n.pathname}`,htm:o.toUpperCase()};const a=await this._createSignedDPoPToken(r);return i.set("dpop",a),i.set("authorization",`DPoP ${this.information.tokenDetails.access_token}`),e instanceof Request?fetch(new Request(e,{...t,headers:i})):fetch(n,{...t,headers:i})}async setTokenDetails(e){this.information.tokenDetails=e,await this._updateSessionDetailsFromToken(e.access_token)}clearRefreshPromise(){this.refreshPromise=void 0,this.resolveRefresh=void 0,this.rejectRefresh=void 0}get isActive(){return this.isActive_}get webId(){return this.webId_}isExpired(){return!this.exp_||this._isTokenExpired(this.exp_)}getExpiresIn(){return this.exp_?this._getTokenTTL(this.exp_):-1}getTokenDetails(){return this.information.tokenDetails}async _renewTokensIfExpired(){this.isExpired()&&(this.refreshPromise?await this.refreshPromise:await this.restore())}async _computeAth(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),n=Array.from(new Uint8Array(r));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async _createSignedDPoPToken(e){if(!this.information.tokenDetails||!this.currentAth_)throw new Error("Session not established.");e.ath=this.currentAth_;const t=await Lt(this.information.tokenDetails.dpop_key_pair.publicKey);return new or(e).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:t}).sign(this.information.tokenDetails.dpop_key_pair.privateKey)}async _updateSessionDetailsFromToken(e){if(e)try{const t=function(e){if("string"!=typeof e)throw new ot("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new ot("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new ot("Invalid JWT");if(!t)throw new ot("JWTs must contain a payload");let n,o;try{n=mr(t)}catch{throw new ot("Failed to base64url decode the payload")}try{o=JSON.parse(qe.decode(n))}catch{throw new ot("Failed to parse the decoded payload as JSON")}if(!Et(o))throw new ot("Invalid JWT Claims Set");return o}(e),r=t.webid;if(!r)throw new Error("Missing webid claim in access token");const n=t.exp;if(!n)throw new Error("Missing exp claim in access token");this.currentAth_=await this._computeAth(e),this.webId_=r,this.exp_=n,this.isActive_=!0}catch(e){await this.logout()}else await this.logout()}_isTokenExpired(e,t=0){return!("number"==typeof e&&!isNaN(e))||this._getTokenTTL(e,t)<0}_getTokenTTL(e,t=0){return e-(Math.floor(Date.now()/1e3)+t)}dispatchStateChangeEvent(){this.dispatchEvent(new CustomEvent(kr.STATE_CHANGE,{detail:{isActive:this.isActive,webId:this.webId}}))}dispatchExpirationWarningEvent(){this.dispatchEvent(new CustomEvent(kr.EXPIRATION_WARNING,{detail:{expires_in:this.getExpiresIn()}}))}dispatchExpirationEvent(){this.dispatchEvent(new CustomEvent(kr.EXPIRATION))}}class Tr{constructor(){this.map=new Map}shouldPreserveExistingRefreshToken(e,t){return"refresh_token"===e&&(null==t||""===t)&&this.map.has(e)}async init(){return this}async setItem(e,t){this.shouldPreserveExistingRefreshToken(e,t)||this.map.set(e,t)}async getItem(e){return this.map.has(e)?this.map.get(e):null}async deleteItem(e){this.map.delete(e)}async clear(){this.map.clear()}close(){}}class Ir{constructor(){this.db=null,this.dbName="soidc",this.storeName="session",this.dbVersion=1}async shouldPreserveExistingRefreshToken(e,t){if("refresh_token"!==e||null!=t&&""!==t)return!1;const r=await this.getItem(e);return null!=r&&""!==r}async init(){if(this.db)return this;if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available in this environment");return await new Promise((e,t)=>{const r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=()=>t(r.error),r.onsuccess=()=>{this.db=r.result,e()},r.onupgradeneeded=()=>{const e=r.result;e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName)}}),this}async setItem(e,t){await this.init(),await this.shouldPreserveExistingRefreshToken(e,t)||await this.withStore("readwrite",r=>r.put(t,e))}async getItem(e){return await this.init(),this.withStore("readonly",t=>t.get(e))}async deleteItem(e){await this.init(),await this.withStore("readwrite",t=>t.delete(e))}async clear(){await this.init(),await this.withStore("readwrite",e=>e.clear())}close(){this.db&&(this.db.close(),this.db=null)}withStore(e,t){return new Promise((r,n)=>{if(!this.db)return void n(new Error("Session database not initialized"));const o=this.db.transaction(this.storeName,e),i=o.objectStore(this.storeName),a=t(i);let s=null;o.onerror=()=>{var e;return n(null!==(e=o.error)&&void 0!==e?e:a.error)},o.onabort=()=>{var e,t;return n(null!==(t=null!==(e=o.error)&&void 0!==e?e:a.error)&&void 0!==t?t:new Error("IndexedDB transaction aborted"))},o.oncomplete=()=>r(s),a.onerror=()=>n(a.error),a.onsuccess=()=>{var e;s=null!==(e=a.result)&&void 0!==e?e:null}})}}const Pr=function(){var t,r,n;const o=e,i=null!==(n=null!==(t=o.SessionCore)&&void 0!==t?t:null===(r=o.default)||void 0===r?void 0:r.SessionCore)&&void 0!==n?n:o.default;return"function"!=typeof i?null:i}();const Rr=function(){if("undefined"!=typeof window&&(()=>{const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e||e.endsWith(".localhost")})())return Pr?new Pr(void 0,{database:new Ir}):new Me;try{return new Me}catch(e){console.warn("solid-logic: falling back to non-worker auth session:",e);try{return Pr?new Pr(void 0,{database:new Ir}):new Me}catch(e){return console.warn("solid-logic: IndexedDB unavailable, using in-memory session database:",e),Pr?new Pr(void 0,{database:new Tr}):new Me}}}();async function Cr(e){const t=await async function(e){try{const t=new URL(e),r=new URL("/.well-known/openid-configuration",t.origin),n=await fetch(r.toString(),{credentials:"include"});if(!n.ok)return null;const o=await n.json();return"string"==typeof(null==o?void 0:o.issuer)&&o.issuer?o.issuer.replace(/\/$/,""):null}catch(e){return null}}(e);return t||e}var xr;const Dr=Rr,Wr="function"==typeof Dr.login?Dr.login.bind(Rr):void 0;if(Wr){const e=async(e,t)=>{var r,n,o,i;if(e&&"object"==typeof e&&!Array.isArray(e)){const t=null!==(n=null!==(r=e.oidcIssuer)&&void 0!==r?r:e.idp)&&void 0!==n?n:e.issuer,a=null!==(i=null!==(o=e.redirectUrl)&&void 0!==o?o:e.redirect_uri)&&void 0!==i?i:e.redirectUri;if("string"==typeof t&&"string"==typeof a)return Wr(await Cr(t),a)}return Wr("string"==typeof e?await Cr(e):e,t)};Dr.login=e}const Or=new class{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){var r;null===(r=this.listeners.get(e))||void 0===r||r.delete(t)}emit(e,...t){var r;null===(r=this.listeners.get(e))||void 0===r||r.forEach(e=>e(...t))}};let Hr=null!==(xr=Rr.isActive)&&void 0!==xr?xr:Boolean(Rr.webId);"function"==typeof Rr.addEventListener&&Rr.addEventListener("sessionStateChange",()=>{var e;const t=null!==(e=Rr.isActive)&&void 0!==e?e:Boolean(Rr.webId);Hr&&!t&&Or.emit("logout"),Hr=t});const $r=Object.assign(Rr,{events:Or});var Nr=n(264),Ur=n(386);const jr=n.n(Ur)()(Nr),Jr=(0,Nr.sym)("http://www.iana.org/assignments/link-relations/acl");function Lr(e){const t=jr;function r(e,r,n,o={}){const i=o.public||[],a=(0,Nr.graph)(),s=(0,Nr.Namespace)("http://www.w3.org/ns/auth/acl#");let c=a.sym(`${n}#a1`);const d=a.sym(n),l=a.sym(e);if(a.add(c,t.rdf("type"),s("Authorization"),d),a.add(c,s("accessTo"),l,d),o.defaultForNew&&a.add(c,s("default"),l,d),a.add(c,s("agent"),r,d),a.add(c,s("mode"),s("Read"),d),a.add(c,s("mode"),s("Write"),d),a.add(c,s("mode"),s("Control"),d),i.length){c=a.sym(`${n}#a2`),a.add(c,t.rdf("type"),s("Authorization"),d),a.add(c,s("accessTo"),l,d),a.add(c,s("agentClass"),t.foaf("Agent"),d);for(let e=0;e<i.length;e++)a.add(c,s("mode"),s(i[e]),d)}return(0,Nr.serialize)(d,a,n)}return{findAclDocUrl:async function(t){await e.fetcher.load(t);const r=e.any(t,Jr);if(!r)throw new Error(`No ACL link discovered for ${t}`);return r.value},setACLUserPublic:function(t,n,o){const i=e.any(e.sym(t),Jr);return Promise.resolve().then(()=>i||function(t){const r=e.fetcher;if(!r)throw new Error("Cannot fetch ACL rel, store has no fetcher");return r.load(t).then(r=>{if(!r.ok)throw new Error("fetchACLRel: While loading:"+r.error);const n=e.any(e.sym(t),Jr);if(!n)throw new Error("fetchACLRel: No Link rel=ACL header for "+t);return n})}(t).catch(e=>{throw new Error(`Error fetching rel=ACL header for ${t}: ${e}`)})).then(i=>{const a=r(t,n,i.uri,o);if(!e.fetcher)throw new Error("Cannot PUT this, store has no fetcher");return e.fetcher.webOperation("PUT",i.uri,{data:a,contentType:"text/turtle"}).then(e=>{if(!e.ok)throw new Error("Error writing ACL text: "+e.error);return i})})},genACLText:r}}const Kr=()=>{let{SolidAppContext:e}=window;if(e||(e={}),e.viewingNoAuthPage=!1,e.noAuth&&window.document){if(window.document.location.href.startsWith(e.noAuth)){e.viewingNoAuthPage=!0;const t=new URLSearchParams(window.document.location.search);if(t){let r=e.viewedPage=t.get("uri")||null;if(r&&(r=decodeURI(r),!r.startsWith(e.noAuth))){const t=r.split(/\//);e.idp=t[0]+"//"+t[2],e.viewingNoAuthPage=!1}}}}return e};function Mr(){const{$SolidTestEnvironment:e}=window;if(void 0!==e&&e.username)return t("Assuming the user is "+e.username),(0,Nr.sym)(e.username);if("undefined"!=typeof document&&document.location&&"http://localhost"===(""+document.location).slice(0,16)){const e=document.getElementById("appTarget");if(!e)return null;const r=e.getAttribute("testID");return r?(t("Assuming user is "+r),(0,Nr.sym)(r)):null}return null}class Fr{constructor(e){this.checkUserInFlight=null,this.sessionRestoreHookAttached=!1,this.fallbackWebId=null,this.session=e}get authSession(){return this.session}currentUser(){var e,t;const r=Kr();if(r.viewingNoAuthPage)return(0,Nr.sym)(r.webId);const n=this.session,o=null===(e=null==n?void 0:n.info)||void 0===e?void 0:e.webId,i=null==n?void 0:n.webId,a=o||i||this.fallbackWebId,s=null===(t=null==n?void 0:n.info)||void 0===t?void 0:t.isLoggedIn,c=null==n?void 0:n.isActive,d=!0===s||!0===c||null==s&&null==c&&Boolean(a)||Boolean(this.fallbackWebId);return this&&this.session&&a&&d?(0,Nr.sym)(a):Mr()}async checkUser(e){var r;const n=new URL(window.location.href).hash;n&&window.localStorage.setItem("preLoginRedirectHash",n);const o=this.session;this.sessionRestoreHookAttached||"function"!=typeof(null===(r=null==o?void 0:o.events)||void 0===r?void 0:r.on)||(o.events.on("sessionRestore",e=>{t(`Session restored to ${e}`),document.location.toString()!==e&&history.replaceState(null,"",e)}),this.sessionRestoreHookAttached=!0),this.checkUserInFlight||(this.checkUserInFlight=this.resolveCurrentUser());const i=this.checkUserInFlight;let a;try{a=await i}finally{this.checkUserInFlight===i&&(this.checkUserInFlight=null)}return Promise.resolve(e?e(a):a)}async resolveCurrentUser(){var e,r,n,o,i,a;const s=this.session,c=new URL(window.location.href);if(c.hash="","function"==typeof(null==s?void 0:s.handleIncomingRedirect))await s.handleIncomingRedirect({restorePreviousSession:!0,url:c.href});else{if("function"==typeof(null==s?void 0:s.restore)){const o=null!==(e=null==s?void 0:s.isActive)&&void 0!==e?e:Boolean(null==s?void 0:s.webId);try{await s.restore()}catch(e){const r=e instanceof Error?e.message:String(e);if(!/no session to restore/i.test(r))throw e;t("No previous session to restore")}const i=null!==(r=null==s?void 0:s.isActive)&&void 0!==r?r:Boolean(null==s?void 0:s.webId);!o&&i&&(null===(n=s.events)||void 0===n||n.emit("sessionRestore",window.location.href))}if("function"==typeof(null==s?void 0:s.handleRedirectFromLogin)){const e=null!==(o=null==s?void 0:s.isActive)&&void 0!==o?o:Boolean(null==s?void 0:s.webId);await s.handleRedirectFromLogin();const t=null!==(i=null==s?void 0:s.isActive)&&void 0!==i?i:Boolean(null==s?void 0:s.webId);!e&&t&&(null===(a=s.events)||void 0===a||a.emit("login"))}}const d=window.localStorage.getItem("preLoginRedirectHash");if(d){const e=new URL(window.location.href);e.hash!==d&&(history.pushState?history.pushState(null,document.title,d):location.hash=d,e.hash=d),window.localStorage.setItem("preLoginRedirectHash","")}let l=Mr();if(l)return l;let h=this.webIdFromSession(null==s?void 0:s.info,s);return h||(h=await this.probeNssCookieBackedWebId()),this.fallbackWebId=h||null,h&&(l=this.saveUser(h)),l&&t(`(Logged in as ${l} by authentication)`),l}async probeNssCookieBackedWebId(){if("undefined"==typeof window)return null;const{hostname:e,port:t,protocol:r}=window.location,n=".localhost";if(!e.endsWith(n))return null;const o=e.slice(0,-10);if(!o||"localhost"===o||o.includes("."))return null;try{if(403!==(await fetch("/account/password/change",{credentials:"include",redirect:"manual",cache:"no-store"})).status)return null;return`${`${r}//${e}${t?`:${t}`:""}`}/profile/card#me`}catch(e){return null}}saveUser(e,t){let r;if(e){r="string"==typeof e?e:e.uri;const n=(0,Nr.namedNode)(r);return t&&(t.me=n),n}return null}webIdFromSession(e,t){const r=(null==e?void 0:e.webId)||(null==t?void 0:t.webId);if(!r)return null;const n=null==e?void 0:e.isLoggedIn,o=null==t?void 0:t.isLoggedIn,i=null==t?void 0:t.isActive;return!0===n||!0===o||!0===i?r:!1===n&&!1===o&&!1===i?null:r}}function Vr(e){return(0,Nr.sym)(e.uri+"#id"+Date.now())}function Br(e){return!e||`${window.location.origin}/`!==new URL(e.value).origin}const Gr="index.ttl#this";function qr(e,t){const r=jr;async function n(t,r,n){await e.fetcher.load(t);const o=e.any(t,new Nr.NamedNode("http://www.iana.org/assignments/link-relations/acl"));if(!o)throw new Error("Chat ACL doc not found!");const i=`\n @prefix acl: <http://www.w3.org/ns/auth/acl#>.\n <#owner>\n a acl:Authorization;\n acl:agent <${r.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Write, acl:Control.\n <#invitee>\n a acl:Authorization;\n acl:agent <${n.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Append.\n `;await e.fetcher.webOperation("PUT",o.value,{data:i,contentType:"text/turtle"})}async function o(t,n){const o=e.any(n,r.solid("privateTypeIndex"));if(!o)throw new Error("Private type index not found!");await e.fetcher.load(o);const i=Vr(o),a=[(0,Nr.st)(i,r.rdf("type"),r.solid("TypeRegistration"),o.doc()),(0,Nr.st)(i,r.solid("forClass"),r.meeting("LongChat"),o.doc()),(0,Nr.st)(i,r.solid("instance"),t,o.doc())];await new Promise((t,r)=>{e.updater.update([],a,function(e,n,o){n?t(null):r(new Error(o))})})}async function i(r){const n=await t.loadMe(),o=function(e,t){const r=new URL(`IndividualChats/${new URL(e.value).host}/`,t.value).toString();return new Nr.NamedNode(r)}(r,await t.getPodRoot(n));let i=!0;try{await e.fetcher.load(new Nr.NamedNode(o.value+"index.ttl#this"))}catch(e){i=!1}return{me:n,chatContainer:o,exists:i}}async function a(e,t){return(await s({me:t,newBase:e.value})).newInstance}function s(t){const n=e,o=n.updater;if(t.me&&!t.me.uri)throw new Error("chat mintNew: Invalid userid "+t.me);const i=t.newInstance=t.newInstance||n.sym(t.newBase+Gr),a=i.doc();return n.add(i,r.rdf("type"),r.meeting("LongChat"),a),n.add(i,r.dc("title"),"Chat channel",a),n.add(i,r.dc("created"),(0,Nr.term)(new Date(Date.now())),a),t.me&&n.add(i,r.dc("author"),t.me,a),new Promise(function(e,r){null==o||o.put(a,n.statementsMatching(void 0,void 0,void 0,a),"text/turtle",function(n,o,a){o?e({...t,newInstance:i}):r(new Error("FAILED to save new chat channel at: "+n+" : "+a))})})}async function c(t,n){var o;await e.fetcher.load(t.doc());const i=e.any(t,r.ldp("inbox"),void 0,t.doc());if(!i)throw new Error(`Invitee inbox not found! ${t.value}`);const a=`\n <> a <http://www.w3.org/ns/pim/meeting#LongChatInvite> ;\n ${r.rdf("seeAlso")} <${n.value}> .\n `,s=await(null===(o=e.fetcher)||void 0===o?void 0:o.webOperation("POST",i.value,{data:a,contentType:"text/turtle"}));if(!(null==s?void 0:s.headers.get("location")))throw new Error(`Invite sending returned a ${null==s?void 0:s.status}`)}return{setAcl:n,addToPrivateTypeIndex:o,findChat:i,createChatThing:a,getChat:async function(e,t=!0){const{me:r,chatContainer:s,exists:d}=await i(e);if(d)return new Nr.NamedNode(s.value+Gr);if(t){const t=await a(s,r);return await c(e,t),await n(s,r,e),await o(t,r),t}return null},sendInvite:c,mintNew:s}}function zr(e,t,r,n,o){return{createInboxFor:async function(e,o){const i=await t.loadMe(),a=`${(await t.getPodRoot(i)).value}p2p-inboxes/${encodeURIComponent(o)}/`;return await n.createContainer(a),await r.setSinglePeerAccess({ownerWebId:i.value,peerWebId:e,accessToModes:"acl:Append",target:a}),a},getNewMessages:async function(e){e||(e=await t.loadMe());const r=await t.getMainInbox(e);return(await n.getContainerMembers(r)).filter(e=>!n.isContainer(e))},markAsRead:async function(t,r){const n=await e.fetcher._fetch(t);if(200!==n.status)throw new Error(`Not OK! ${t}`);const o=function(e,t){const r=t.getUTCFullYear(),n=("0"+(t.getUTCMonth()+1)).slice(-2),o=("0"+t.getUTCDate()).slice(-2),i=e.split("/"),a=i[i.length-1];return new URL(`./archive/${r}/${n}/${o}/${a}`,e).toString()}(t,r),i={method:"PUT",body:await n.text(),headers:[["Content-Type",n.headers.get("Content-Type")||"application/octet-stream"]]};"2"===(await e.fetcher._fetch(o,i)).status.toString()[0]&&await e.fetcher._fetch(t,{method:"DELETE"})}}}class Xr extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}}class Yr extends Xr{}class Zr extends Xr{}class Qr extends Xr{}class en extends Xr{}class tn extends Xr{}class rn extends Xr{}class nn extends Xr{constructor(e,t){super(t),this.status=e}}function on(){return["@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a solid:TypeIndex ;"," a solid:ListedDocument."].join("\n")}function an(){return["@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a solid:TypeIndex ;"," a solid:UnlistedDocument."].join("\n")}function sn(e,t){const r=new URL(t).pathname.split("/").pop()||"publicTypeIndex.ttl";return["# ACL resource for the Public Type Index","","@prefix acl: <http://www.w3.org/ns/auth/acl#>.","@prefix foaf: <http://xmlns.com/foaf/0.1/>.","","<#owner>"," a acl:Authorization;",""," acl:agent",` <${e}>;`,"",` acl:accessTo <./${r}>;`,""," acl:mode"," acl:Read, acl:Write, acl:Control.","","# Public-readable","<#public>"," a acl:Authorization;",""," acl:agentClass foaf:Agent;","",` acl:accessTo <./${r}>;`,""," acl:mode acl:Read."].join("\n")}function cn(e){function t(t){return e.statementsMatching(t,(0,Nr.sym)("http://www.w3.org/ns/ldp#contains"),void 0).map(e=>e.object)}function r(e){const t=e.value;return"/"===t.charAt(t.length-1)}return{isContainer:r,createContainer:async function(t){if(!r((0,Nr.sym)(t)))throw new Error(`Not a container URL ${t}`);const n=await e.fetcher._fetch(t,{method:"PUT",headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:'<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'},body:" "});if(409!==n.status&&"2"!==n.status.toString()[0])throw new Error(`Not OK: got ${n.status} response while creating container at ${t}`)},getContainerElements:t,getContainerMembers:async function(r){return await e.fetcher.load(r),t(r)}}}function dn(e,t,n){const o=jr,i=cn(e),a=new Map,s=new Map;function c(e){return!!e&&(e.startsWith("https://")||e.startsWith("http://"))}function d(e){const t=e.doc(),r=t.dir();if((null==r?void 0:r.uri)&&c(r.uri))return r.uri;const n=t.uri;if(!n||!c(n))return null;const o=n.split("#")[0],i=o.lastIndexOf("/");return-1===i?null:o.slice(0,i+1)}function l(e,t){const r=d(e);if(!r)throw new Error(`Cannot derive directory for preferences file ${e.uri}`);return(0,Nr.sym)(r+t)}function h(e){var t;if(404===(null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.status))return!0;const r=`${(null==e?void 0:e.message)||e||""}`;return r.includes("404")||r.includes("Not Found")}async function u(t,r){var n;const o=d(r);if(!o)throw new Error(`Cannot derive settings directory from ${r.uri}`);await async function(t){const r=(0,Nr.sym)(t);try{return void await e.fetcher.load(r)}catch(e){if(!h(e))throw e}await i.createContainer(t)}(o);const a=(0,Nr.sym)(o);let s;try{await e.fetcher.load(a),s=null===(n=e.any(a,Jr))||void 0===n?void 0:n.value}catch(e){if(!h(e))throw e}s||(s=`${o}.acl`);const c=(0,Nr.sym)(s);try{return void await e.fetcher.load(c)}catch(e){if(!h(e))throw e}var l;await e.fetcher.webOperation("PUT",c.uri,{data:(l=t.uri,["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","","<#owner>","a acl:Authorization;",`acl:agent <${l}>;`,"acl:accessTo <./>;","acl:default <./>;","acl:mode acl:Read, acl:Write, acl:Control."].join("\n")),contentType:"text/turtle"})}async function p(t,r){const i=r.doc(),a=t.doc();await e.fetcher.load(i);const s=e.any(t,o.solid("publicTypeIndex"),null,a),c=e.any(t,o.solid("publicTypeIndex"),null,i),d=s||c||l(r,"publicTypeIndex.ttl"),u=e.any(t,o.solid("privateTypeIndex"),null,i)||l(r,"privateTypeIndex.ttl"),p=!s;p&&await n.followOrCreateLinkWithContentOnCreate(t,o.solid("publicTypeIndex"),d,a,on());const w=[];e.holds(i,o.rdf("type"),o.space("ConfigurationFile"),i)||w.push((0,Nr.st)(i,o.rdf("type"),o.space("ConfigurationFile"),i)),e.holds(i,o.dct("title"),void 0,i)||w.push((0,Nr.st)(i,o.dct("title"),(0,Nr.literal)("Preferences file"),i)),e.holds(t,o.solid("publicTypeIndex"),d,i)||w.push((0,Nr.st)(t,o.solid("publicTypeIndex"),d,i)),e.holds(t,o.solid("privateTypeIndex"),u,i)||w.push((0,Nr.st)(t,o.solid("privateTypeIndex"),u,i)),w.length>0&&(await e.updater.update([],w),await e.fetcher.load(i)),await async function(t,r,o=!1){var i,a,s;if(!await n.loadOrCreateWithContentOnCreate(r,on())&&!o)return;let c;try{await e.fetcher.load(r),c=null===(i=e.any(r,Jr))||void 0===i?void 0:i.value}catch(e){if(!h(e))throw e}c||(c=`${r.uri}.acl`);const d=(0,Nr.sym)(c);try{await e.fetcher.webOperation("PUT",d.uri,{data:sn(t.uri,r.uri),contentType:"text/turtle",headers:{"If-None-Match":"*"}})}catch(e){if(412!==(null!==(s=null===(a=null==e?void 0:e.response)||void 0===a?void 0:a.status)&&void 0!==s?s:null==e?void 0:e.status))throw e}}(t,d,p),await async function(e){await n.loadOrCreateWithContentOnCreate(e,an())}(u)}async function w(e){var t,r;try{return!!await n.loadOrCreateWithContentOnCreate(e,["@prefix dct: <http://purl.org/dc/terms/>.","@prefix pim: <http://www.w3.org/ns/pim/space#>.","@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a pim:ConfigurationFile ;",' dct:title "Preferences file".'].join("\n"))}catch(n){if(401===(null===(t=n.response)||void 0===t?void 0:t.status))throw new Yr;if(403===(null===(r=n.response)||void 0===r?void 0:r.status)){if(Br(e))throw new Zr;throw new Qr}throw n}}async function f(t){const i=s.get(t.uri);if(i)return i;const c=a.get(t.uri);if(c)return c;const d=(async()=>{var i;await y(t);const a=function(e){const t=e.uri.replace("/profile/","/").replace("/public/","/").split("/").slice(0,-1).join("/")+"/settings/prefs.ttl";return(0,Nr.sym)(t)}(t);let c;try{const r=e.any(t,o.space("preferencesFile"),null,t.doc());c=r||await n.followOrCreateLink(t,o.space("preferencesFile"),a,t.doc()),await u(t,c),await w(c),await p(t,c)}catch(e){if(r(`User ${t} has no pointer in profile to preferences file.`),e instanceof tn)throw e;if(e instanceof rn)throw e;if(e instanceof Yr)throw e;if(e instanceof Zr)throw e;if(e instanceof Qr)throw e;if(e instanceof nn)throw e;throw e}try{await e.fetcher.load(c)}catch(n){const o=`Unable to load preference of user ${t}: ${n}`;if(404===(null===(i=n.response)||void 0===i?void 0:i.status))return await u(t,c),await w(c),await p(t,c),await e.fetcher.load(c),c;if(r(o),401===n.response.status)throw new Yr;if(403===n.response.status){if(Br(c))throw new Zr;throw new Qr}throw new Error(o)}return s.set(t.uri,c),c})();a.set(t.uri,d);try{return await d}finally{a.get(t.uri)===d&&a.delete(t.uri)}}async function y(t){if(!t)throw new Error("loadProfile: no user given.");try{await e.fetcher.load(t.doc())}catch(e){throw new Error(`Unable to load profile of user ${t}: ${e}`)}return t.doc()}function m(t){return e.any(t,o.space("storage"),void 0,t.doc())}return{loadMe:async function(){const r=t.currentUser();if(null===r)throw new Error("Current user not found! Not logged in?");return await e.fetcher.load(r.doc()),r},getPodRoot:function(e){const t=m(e);if(!t)throw new Error("User pod root not found!");return t},getMainInbox:async function(t){await e.fetcher.load(t);const r=e.any(t,o.ldp("inbox"),void 0,t.doc());if(!r)throw new Error("User main inbox not found!");return r},findStorage:m,loadPreferences:f,loadProfile:y,silencedLoadPreferences:async function(e){try{return await f(e)}catch(e){return}}}}function ln(e,n,o,i){const a=jr;function s(e){return!!e&&(e.startsWith("https://")||e.startsWith("http://"))}async function c(t){if(!t)throw new Error("loadTypeIndexesFor: No user given");const n=await o.loadProfile(t);let s,c=null;try{c=p(t)}catch(e){r(`User ${t} has no usable profile document directory for publicTypeIndex.`)}try{const r=e.any(t,a.solid("publicTypeIndex"),void 0,n);s=r||(c?await i.followOrCreateLinkWithContentOnCreate(t,a.solid("publicTypeIndex"),c,n,on()):null)}catch(e){r(`User ${t} has no pointer in profile to publicTypeIndex file: ${e}`)}const d=s?[{label:"public",index:s,agent:t}]:[];let l,h;try{l=await o.silencedLoadPreferences(t)}catch(e){l=null}if(l){let o,s=null;try{s=w(l)}catch(e){r(`User ${t} has no usable preferences document directory for privateTypeIndex.`)}try{const r=e.any(t,a.solid("privateTypeIndex"),void 0,n);o=r||(s?await i.followOrCreateLinkWithContentOnCreate(t,a.solid("privateTypeIndex"),s,l,an()):null)}catch(e){r(`User ${t} has no pointer in preference file to privateTypeIndex file: ${e}`)}h=o?[{label:"private",index:o,agent:t}]:[]}else h=[];const u=d.concat(h);if(0===u.length)return u;const f=u.map(e=>e.index);try{await e.fetcher.load(f)}catch(e){r("Problems loading type index: ",e)}return u}async function d(t){let n;try{n=await o.silencedLoadPreferences(t)}catch(e){r(`User ${t} has no pointer in profile to preferences file.`)}if(n){const o=e.each(t,a.solid("community"),void 0,n).concat(e.each(t,a.solid("community"),void 0,t.doc()));let i=[];for(const e of o)if("NamedNode"===e.termType&&s(e.uri))try{i=i.concat(await c(e))}catch(t){r(`Skipping community type indexes for ${e.uri}: ${t}`)}else r(`Skipping malformed community node for ${t}: ${e}`);return i}return[]}async function l(e){return(await c(e)).concat(await d(e))}async function h(e,t){const r=await l(t);let n=[];for(const t of r){const r=await f(t,e);n=n.concat(r)}return n}function u(e){const r=e.doc(),n=r.dir();if((null==n?void 0:n.uri)&&s(n.uri))return n.uri;const o=r.uri;if(!o||!s(o))return t(`docDirUri: missing or non-http(s) doc uri for ${null==e?void 0:e.uri}`),null;const i=o.split("#")[0],a=i.lastIndexOf("/");return-1===a?(t(`docDirUri: no slash in doc uri ${o}`),null):i.slice(0,a+1)}function p(e){const t=u(e);if(!t)throw new Error(`suggestPublicTypeIndex: Cannot derive directory for ${e.uri}`);return(0,Nr.sym)(t+"publicTypeIndex.ttl")}function w(e){const t=u(e);if(!t)throw new Error(`suggestPrivateTypeIndex: Cannot derive directory for ${e.uri}`);return(0,Nr.sym)(t+"privateTypeIndex.ttl")}async function f(t,r){const n=t.index,o=[],i=e.statementsMatching(null,a.solid("instance"),null,n).concat(e.statementsMatching(null,a.solid("instanceContainer"),null,n)).map(e=>e.subject);for(const s of i){const i=e.any(s,a.solid("forClass"),null,n);if(!r||i.sameTerm(r)){const r=e.each(s,a.solid("instance"),null,n);for(const e of r)o.push({instance:e,type:i,scope:t});const c=e.each(s,a.solid("instanceContainer"),null,n);for(const r of c)await e.fetcher.load(r),o.push({instance:(0,Nr.sym)(r.value),type:i,scope:t})}}return o}return{registerInTypeIndex:async function(t,r,n){const o=Vr(r),i=[(0,Nr.st)(o,a.rdf("type"),a.solid("TypeRegistration"),r),(0,Nr.st)(o,a.solid("forClass"),n,r),(0,Nr.st)(o,a.solid("instance"),t,r)];try{await e.updater.update([],i)}catch(e){const n=`Unable to register ${t} in index ${r}: ${e}`;return console.warn(n),null}return o},getRegistrations:function(t,r){return e.each(void 0,a.solid("instance"),t).filter(t=>e.holds(t,a.solid("forClass"),r))},loadTypeIndexesFor:c,loadCommunityTypeIndexes:d,loadAllTypeIndexes:l,getScopedAppInstances:h,getAppInstances:async function(e){const t=n.currentUser();if(!t)throw new Error("getAppInstances: Must be logged in to find apps.");return(await h(e,t)).map(e=>e.instance)},suggestPublicTypeIndex:p,suggestPrivateTypeIndex:w,deleteTypeIndexRegistration:async function(t){const r=e.the(null,a.solid("instance"),t.instance,t.scope.index);if(!r)throw new Error(`deleteTypeIndexRegistration: No registration found for ${t.instance}`);const n=e.statementsMatching(r,null,null,t.scope.index);await e.updater.update(n,[])},getScopedAppsFromIndex:f}}function hn(e,n){t("SolidLogic: Unique instance created. There should only be one of these.");const o=Nr.graph();Nr.fetcher(o,{fetch:e.fetch}),o.updater=new Nr.UpdateManager(o),o.features=[];const i=new Fr(n),a=Lr(o),s=cn(o),c=function(e,n,o){async function i(t){var r,n,o,i,a;try{return await e.fetcher.load(t)}catch(s){if(404===(null===(r=null==s?void 0:s.response)||void 0===r?void 0:r.status)){try{await e.fetcher.webOperation("PUT",t.uri,{data:"",contentType:"text/turtle",headers:{"If-None-Match":"*"}})}catch(e){if(412!==(null!==(o=null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status)&&void 0!==o?o:null==e?void 0:e.status))throw new rn(`createIfNotExists: PUT FAILED: ${t}: ${e}`)}return await e.fetcher.load(t)}if(401===(null===(i=null==s?void 0:s.response)||void 0===i?void 0:i.status))throw new Yr;if(403===(null===(a=null==s?void 0:s.response)||void 0===a?void 0:a.status)){if(Br(t))throw new Zr;throw new Qr}const c=`createIfNotExists doc load error: ${t}: ${s}`;throw new nn(null==s?void 0:s.status,`${(null==s?void 0:s.message)||""}${c}`)}}async function a(t,r){var n,o,i,a;try{return await e.fetcher.load(t),!1}catch(e){if(404!==(null!==(o=null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status)&&void 0!==o?o:null==e?void 0:e.status))throw e}try{return await e.fetcher.webOperation("PUT",t.uri,{data:r,contentType:"text/turtle",headers:{"If-None-Match":"*"}}),!0}catch(e){if(412===(null!==(a=null===(i=null==e?void 0:e.response)||void 0===i?void 0:i.status)&&void 0!==a?a:null==e?void 0:e.status))return!1;throw e}}return{recursiveDelete:async function r(i){try{if(o.isContainer(i)){const t=await n.findAclDocUrl(i);await e.fetcher._fetch(t,{method:"DELETE"});const a=await o.getContainerMembers(i);await Promise.all(a.map(e=>r(e)))}return e.fetcher._fetch(i.value,{method:"DELETE"})}catch(e){t(`Please manually remove ${i.value} from your system.`,e)}},setSinglePeerAccess:async function(t){let r=["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","","<#alice> a acl:Authorization;\n acl:agent <"+t.ownerWebId+">;",` acl:accessTo <${t.target}>;`,` acl:default <${t.target}>;`," acl:mode acl:Read, acl:Write, acl:Control.",""].join("\n");t.accessToModes&&(r+=["<#bobAccessTo> a acl:Authorization;",` acl:agent <${t.peerWebId}>;`,` acl:accessTo <${t.target}>;`,` acl:mode ${t.accessToModes}.`,""].join("\n")),t.defaultModes&&(r+=["<#bobDefault> a acl:Authorization;",` acl:agent <${t.peerWebId}>;`,` acl:default <${t.target}>;`,` acl:mode ${t.defaultModes}.`,""].join("\n"));const o=await n.findAclDocUrl((0,Nr.sym)(t.target));return e.fetcher._fetch(o,{method:"PUT",body:r,headers:[["Content-Type","text/turtle"]]})},createEmptyRdfDoc:async function(t,r){await e.fetcher.webOperation("PUT",t.uri,{data:`# ${new Date} ${r}\n`,contentType:"text/turtle"})},followOrCreateLink:async function(t,n,o,a){await e.fetcher.load(a);const s=e.any(t,n,null,a);if(s)return s;if(!e.updater.editable(a)){const e=`followOrCreateLink: cannot edit ${a.value}`;throw r(e),new tn(e)}try{await e.updater.update([],[(0,Nr.st)(t,n,o,a)])}catch(e){throw r(`followOrCreateLink: Error making link in ${a} to ${o}: ${e}`),new rn(e)}try{await i(o)}catch(e){throw r(`followOrCreateLink: Error loading or saving new linked document: ${o}: ${e}`),e}return o},followOrCreateLinkWithContentOnCreate:async function(t,n,o,i,s){await e.fetcher.load(i);const c=e.any(t,n,null,i);if(c)return c;if(!e.updater.editable(i)){const e=`followOrCreateLinkWithContentOnCreate: cannot edit ${i.value}`;throw r(e),new tn(e)}try{await e.updater.update([],[(0,Nr.st)(t,n,o,i)])}catch(e){const t=`followOrCreateLinkWithContentOnCreate: Error making link in ${i} to ${o}: ${e}`;throw r(t),new rn(t)}try{await a(o,s)}catch(e){throw r(`followOrCreateLinkWithContentOnCreate: Error loading or saving new linked document: ${o}: ${e}`),e}return o},loadOrCreateIfNotExists:i,loadOrCreateWithContentOnCreate:a}}(o,a,s),d=dn(o,i,c),l=qr(o,d),h=zr(o,d,c,s),u=ln(o,i,d,c);return t("SolidAuthnLogic initialized"),{store:o,authn:i,acl:a,inbox:h,chat:l,profile:d,typeIndex:u,load:function(e){return o.fetcher.load(e)},updatePromise:function(e,t=[]){return new Promise((r,n)=>{o.updater.update(e,t,function(e,t,o){t?r():n(new Error(o))})})},clearStore:function(){o.statements.slice().forEach(o.remove.bind(o))}}}const un=async(e,t)=>{var r;const n=t&&t.credentials&&"omit"==t.credentials,o=$r;if(((null===(r=null==o?void 0:o.info)||void 0===r?void 0:r.webId)||(null==o?void 0:o.webId))&&!n){const r="function"==typeof o.fetch?o.fetch.bind(o):"function"==typeof o.authFetch?o.authFetch.bind(o):null;return r?r(e,t):window.fetch(e,t)}return window.fetch(e,t)},pn=Symbol.for("solid-logic-singleton"),wn="undefined"!=typeof window?window:n.g;const fn=(wn[pn]?t("SolidLogic: Using existing global singleton instance."):(t("SolidLogic: Creating new global singleton instance."),wn[pn]=hn({fetch:un},$r),t("Unique quadstore initialized.")),wn[pn]);async function yn(e={}){if("undefined"==typeof window)return!1;const t=e.issuer||"",r=e.postLogoutRedirectPath||"/";try{if(t){const e=new URL(t);e.pathname="/.well-known/openid-configuration";const r=await fetch(e.toString(),{credentials:"include"});if(200===r.status){const e=await r.json();e&&e.end_session_endpoint&&await fetch(e.end_session_endpoint,{credentials:"include"})}}}catch(e){}try{const e=await fetch("/.well-known/solid/logout",{credentials:"include"});if(e.ok||e.redirected)return window.location.assign(r),!0}catch(e){}return!1}const mn=[{name:"Solid Community",uri:"https://solidcommunity.net"},{name:"Solid Web",uri:"https://solidweb.org"},{name:"Solid Web ME",uri:"https://solidweb.me"},{name:"Inrupt.com",uri:"https://login.inrupt.com"}];function gn(){const e=[...mn],{host:t,origin:r}=new URL(location.href);return e.map(({uri:e})=>new URL(e).host).includes(t)||e.unshift({name:t,uri:r}),e}const vn=fn.authn,bn=fn.authn.authSession,En=fn.store})(),o})());
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("$rdf")):"function"==typeof define&&define.amd?define("SolidLogic",["$rdf"],t):"object"==typeof exports?exports.SolidLogic=t(require("$rdf")):e.SolidLogic=t(e.$rdf)}(this,e=>(()=>{var t={386(e){const t={acl:"http://www.w3.org/ns/auth/acl#",arg:"http://www.w3.org/ns/pim/arg#",as:"https://www.w3.org/ns/activitystreams#",bookmark:"http://www.w3.org/2002/01/bookmark#",cal:"http://www.w3.org/2002/12/cal/ical#",cco:"http://www.ontologyrepository.com/CommonCoreOntologies/",cert:"http://www.w3.org/ns/auth/cert#",contact:"http://www.w3.org/2000/10/swap/pim/contact#",dc:"http://purl.org/dc/elements/1.1/",dct:"http://purl.org/dc/terms/",doap:"http://usefulinc.com/ns/doap#",foaf:"http://xmlns.com/foaf/0.1/",geo:"http://www.w3.org/2003/01/geo/wgs84_pos#",gpx:"http://www.w3.org/ns/pim/gpx#",gr:"http://purl.org/goodrelations/v1#",http:"http://www.w3.org/2007/ont/http#",httph:"http://www.w3.org/2007/ont/httph#",icalTZ:"http://www.w3.org/2002/12/cal/icaltzd#",ldp:"http://www.w3.org/ns/ldp#",link:"http://www.w3.org/2007/ont/link#",log:"http://www.w3.org/2000/10/swap/log#",meeting:"http://www.w3.org/ns/pim/meeting#",mo:"http://purl.org/ontology/mo/",org:"http://www.w3.org/ns/org#",owl:"http://www.w3.org/2002/07/owl#",pad:"http://www.w3.org/ns/pim/pad#",patch:"http://www.w3.org/ns/pim/patch#",prov:"http://www.w3.org/ns/prov#",pto:"http://www.productontology.org/id/",qu:"http://www.w3.org/2000/10/swap/pim/qif#",trip:"http://www.w3.org/ns/pim/trip#",rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",rss:"http://purl.org/rss/1.0/",sched:"http://www.w3.org/ns/pim/schedule#",schema:"http://schema.org/",sioc:"http://rdfs.org/sioc/ns#",skos:"http://www.w3.org/2004/02/skos/core#",solid:"http://www.w3.org/ns/solid/terms#",space:"http://www.w3.org/ns/pim/space#",stat:"http://www.w3.org/ns/posix/stat#",tab:"http://www.w3.org/2007/ont/link#",tabont:"http://www.w3.org/2007/ont/link#",ui:"http://www.w3.org/ns/ui#",vann:"http://purl.org/vocab/vann/",vcard:"http://www.w3.org/2006/vcard/ns#",wf:"http://www.w3.org/2005/01/wf/flow#",xsd:"http://www.w3.org/2001/XMLSchema#"};e.exports=function(e={namedNode:e=>e}){const r={};for(const n in t){const o=t[n];r[n]=function(t=""){return e.namedNode(o+t)}}return r}},552(e,t,r){"use strict";e.exports=r.p+"2729812e0bfc062ee77a.js"},264(t){"use strict";t.exports=e}},r={};function n(e){var o=r[e];if(void 0!==o)return o.exports;var i=r[e]={exports:{}};return t[e](i,i.exports,n),i.exports}n.m=t,n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.p="",n.b="undefined"!=typeof document&&document.baseURI||self.location.href;var o={};return(()=>{"use strict";n.r(o),n.d(o,{ACL_LINK:()=>Jr,CrossOriginForbiddenError:()=>Zr,FetchError:()=>nn,NotEditableError:()=>tn,NotFoundError:()=>en,SameOriginForbiddenError:()=>Qr,UnauthorizedError:()=>Yr,WebOperationError:()=>rn,appContext:()=>Kr,authSession:()=>bn,authn:()=>vn,createTypeIndexLogic:()=>ln,getSuggestedIssuers:()=>gn,offlineTestID:()=>Mr,performServerSideLogout:()=>yn,solidLogicSingleton:()=>fn,store:()=>En});var e={};function t(...e){console.log(...e)}function r(...e){console.warn(...e)}n.r(e),n.d(e,{SessionCore:()=>Ar,SessionEvents:()=>kr});var i=crypto;const a=e=>e instanceof CryptoKey;var s=async(e,t)=>{const r=`SHA-${e.slice(-3)}`;return new Uint8Array(await i.subtle.digest(r,t))};const c=new TextEncoder,d=new TextDecoder;function l(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const h=e=>(e=>{let t=e;"string"==typeof t&&(t=c.encode(t));const r=[];for(let e=0;e<t.length;e+=32768)r.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(r.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),u=e=>{let t=e;t instanceof Uint8Array&&(t=d.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class p extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}p.code="ERR_JOSE_GENERIC";class w extends p{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}w.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class f extends p{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}f.code="ERR_JWT_EXPIRED";class y extends p{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}y.code="ERR_JOSE_ALG_NOT_ALLOWED";class m extends p{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}m.code="ERR_JOSE_NOT_SUPPORTED";(class extends p{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends p{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class g extends p{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}g.code="ERR_JWS_INVALID";class v extends p{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}v.code="ERR_JWT_INVALID";class b extends p{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}b.code="ERR_JWK_INVALID";class E extends p{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}E.code="ERR_JWKS_INVALID";class S extends p{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}S.code="ERR_JWKS_NO_MATCHING_KEY";class _ extends p{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}_.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class k extends p{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}k.code="ERR_JWKS_TIMEOUT";class A extends p{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function T(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function I(e,t){return e.name===t}function P(e){return parseInt(e.name.slice(4),10)}function R(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!I(e.algorithm,"HMAC"))throw T("HMAC");const r=parseInt(t.slice(2),10);if(P(e.algorithm.hash)!==r)throw T(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!I(e.algorithm,"RSASSA-PKCS1-v1_5"))throw T("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(P(e.algorithm.hash)!==r)throw T(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!I(e.algorithm,"RSA-PSS"))throw T("RSA-PSS");const r=parseInt(t.slice(2),10);if(P(e.algorithm.hash)!==r)throw T(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw T("Ed25519 or Ed448");break;case"Ed25519":if(!I(e.algorithm,"Ed25519"))throw T("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!I(e.algorithm,"ECDSA"))throw T("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw T(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}function C(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}A.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var x=(e,...t)=>C("Key must be ",e,...t);function D(e,t,...r){return C(`Key for the ${e} algorithm must be `,t,...r)}var W=e=>!!a(e)||"KeyObject"===e?.[Symbol.toStringTag];const O=["CryptoKey"];var H=(...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0};function $(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}var N=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function U(e){return $(e)&&"string"==typeof e.kty}var j=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new m('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,i.subtle.importKey("jwk",o,...n)};const J=e=>u(e);let L,K;const M=e=>"KeyObject"===e?.[Symbol.toStringTag],F=async(e,t,r,n,o=!1)=>{let i=e.get(t);if(i?.[n])return i[n];const a=await j({...r,alg:n});return o&&Object.freeze(t),i?i[n]=a:e.set(t,{[n]:a}),a};var B=(e,t)=>{if(M(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?J(r.k):(K||(K=new WeakMap),F(K,e,r,t))}if(U(e)){if(e.k)return u(e.k);K||(K=new WeakMap);return F(K,e,e,t,!0)}return e},V=(e,t)=>{if(M(e)){let r=e.export({format:"jwk"});return r.k?J(r.k):(L||(L=new WeakMap),F(L,e,r,t))}if(U(e)){if(e.k)return u(e.k);L||(L=new WeakMap);return F(L,e,e,t,!0)}return e};async function G(e,t){if(!$(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return u(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new m('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return j({...e,alg:t});default:throw new m('Unsupported "kty" (Key Type) Parameter value')}}const q=e=>e?.[Symbol.toStringTag],z=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},X=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&U(t)){if(function(e){return U(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&z(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!W(t))throw new TypeError(D(e,t,...O,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${q(t)} instances for symmetric algorithms must be of type "secret"`)}};function Y(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?X(t,r,n,e):((e,t,r,n)=>{if(n&&U(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&z(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&z(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!W(t))throw new TypeError(D(e,t,...O,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}Y.bind(void 0,!1);const Z=Y.bind(void 0,!0);function Q(e,t,r,n,o){if(void 0!==o.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!i.has(t))throw new m(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}var ee=(e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};var te=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:h(e)};if(!a(e))throw new TypeError(x(e,...O,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:t,key_ops:r,alg:n,use:o,...s}=await i.subtle.exportKey("jwk",e);return s};async function re(e){return te(e)}function ne(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function oe(e,t,r){if("sign"===r&&(t=await V(t,e)),"verify"===r&&(t=await B(t,e)),a(t))return R(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(x(t,...O));return i.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(x(t,...O,"Uint8Array","JSON Web Key"))}var ie=async(e,t,r,n)=>{const o=await oe(e,t,"verify");N(e,o);const a=ne(e,o.algorithm);try{return await i.subtle.verify(a,o,r,n)}catch{return!1}};async function ae(e,t,r){if(e instanceof Uint8Array&&(e=d.decode(e)),"string"!=typeof e)throw new g("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:i,length:a}=e.split(".");if(3!==a)throw new g("Invalid Compact JWS");const s=await async function(e,t,r){if(!$(e))throw new g("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new g('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new g("JWS Protected Header incorrect type");if(void 0===e.payload)throw new g("JWS Payload missing");if("string"!=typeof e.signature)throw new g("JWS Signature missing or incorrect type");if(void 0!==e.header&&!$(e.header))throw new g("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=u(e.protected);n=JSON.parse(d.decode(t))}catch{throw new g("JWS Protected Header is invalid")}if(!H(n,e.header))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header};let i=!0;if(Q(g,new Map([["b64",!0]]),r?.crit,n,o).has("b64")&&(i=n.b64,"boolean"!=typeof i))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if("string"!=typeof a||!a)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');const s=r&&ee("algorithms",r.algorithms);if(s&&!s.has(a))throw new y('"alg" (Algorithm) Header Parameter value not allowed');if(i){if("string"!=typeof e.payload)throw new g("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new g("JWS Payload must be a string or an Uint8Array instance");let h=!1;"function"==typeof t?(t=await t(n,e),h=!0,Z(a,t,"verify"),U(t)&&(t=await G(t,a))):Z(a,t,"verify");const p=l(c.encode(e.protected??""),c.encode("."),"string"==typeof e.payload?c.encode(e.payload):e.payload);let w,f;try{w=u(e.signature)}catch{throw new g("Failed to base64url decode the signature")}if(!await ie(a,t,w,p))throw new A;if(i)try{f=u(e.payload)}catch{throw new g("Failed to base64url decode the payload")}else f="string"==typeof e.payload?c.encode(e.payload):e.payload;const m={payload:f};return void 0!==e.protected&&(m.protectedHeader=n),void 0!==e.header&&(m.unprotectedHeader=e.header),h?{...m,key:t}:m}({payload:o,protected:n,signature:i},t,r),h={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...h,key:s.key}:h}var se=e=>Math.floor(e.getTime()/1e3);const ce=86400,de=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var le=e=>{const t=de.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(r*ce);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n};const he=e=>e.toLowerCase().replace(/^application\//,"");var ue=(e,t,r={})=>{let n;try{n=JSON.parse(d.decode(t))}catch{}if(!$(n))throw new v("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&("string"!=typeof e.typ||he(e.typ)!==he(o)))throw new w('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:l}=r,h=[...i];void 0!==l&&h.push("iat"),void 0!==c&&h.push("aud"),void 0!==s&&h.push("sub"),void 0!==a&&h.push("iss");for(const e of new Set(h.reverse()))if(!(e in n))throw new w(`missing required "${e}" claim`,n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new w('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new w('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(u=n.aud,p="string"==typeof c?[c]:c,!("string"==typeof u?p.includes(u):Array.isArray(u)&&p.some(Set.prototype.has.bind(new Set(u))))))throw new w('unexpected "aud" claim value',n,"aud","check_failed");var u,p;let y;switch(typeof r.clockTolerance){case"string":y=le(r.clockTolerance);break;case"number":y=r.clockTolerance;break;case"undefined":y=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,g=se(m||new Date);if((void 0!==n.iat||l)&&"number"!=typeof n.iat)throw new w('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new w('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>g+y)throw new w('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new w('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=g-y)throw new f('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){const e=g-n.iat;if(e-y>("number"==typeof l?l:le(l)))throw new f('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-y)throw new w('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function pe(e,t,r){const n=await ae(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new v("JWTs MUST NOT use unencoded payload");const o={payload:ue(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...o,key:n.key}:o}var we=async(e,t,r)=>{const n=await oe(e,t,"sign");N(e,n);const o=await i.subtle.sign(ne(e,n.algorithm),n,r);return new Uint8Array(o)};class fe{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new g("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!H(this._protectedHeader,this._unprotectedHeader))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(Q(g,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=r;if("string"!=typeof o||!o)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');Z(o,e,"sign");let i,a=this._payload;n&&(a=c.encode(h(a))),i=this._protectedHeader?c.encode(h(JSON.stringify(this._protectedHeader))):c.encode("");const s=l(i,c.encode("."),a),u=await we(o,e,s),p={signature:h(u),payload:""};return n&&(p.payload=d.decode(a)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=d.decode(i)),p}}class ye{constructor(e){this._flattened=new fe(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function me(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ge{constructor(e={}){if(!$(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:me("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:me("setNotBefore",se(e))}:this._payload={...this._payload,nbf:se(new Date)+le(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:me("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:me("setExpirationTime",se(e))}:this._payload={...this._payload,exp:se(new Date)+le(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:se(new Date)}:e instanceof Date?this._payload={...this._payload,iat:me("setIssuedAt",se(e))}:this._payload="string"==typeof e?{...this._payload,iat:me("setIssuedAt",se(new Date)+le(e))}:{...this._payload,iat:me("setIssuedAt",e)},this}}class ve extends ge{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new ye(c.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new v("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}const be=(e,t)=>{if("string"!=typeof e||!e)throw new b(`${t} missing or invalid`)};async function Ee(e,t){if(!$(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),"sha256"!==t&&"sha384"!==t&&"sha512"!==t)throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":be(e.crv,'"crv" (Curve) Parameter'),be(e.x,'"x" (X Coordinate) Parameter'),be(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":be(e.crv,'"crv" (Subtype of Key Pair) Parameter'),be(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":be(e.e,'"e" (Exponent) Parameter'),be(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":be(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new m('"kty" (Key Type) Parameter missing or unsupported')}const n=c.encode(JSON.stringify(r));return h(await s(t,n))}function Se(e){return $(e)}function _e(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class ke{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(Se)}(e))throw new E("JSON Web Key Set malformed");this._jwks=_e(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},o=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new m('Unsupported "alg" value for a JSON Web Key Set')}}(r),i=this._jwks.keys.filter(e=>{let t=o===e.kty;if(t&&"string"==typeof n&&(t=n===e.kid),t&&"string"==typeof e.alg&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":t="Ed25519"===e.crv;break;case"EdDSA":t="Ed25519"===e.crv||"Ed448"===e.crv}return t}),{0:a,length:s}=i;if(0===s)throw new S;if(1!==s){const e=new _,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of i)try{yield await Ae(t,e,r)}catch{}},e}return Ae(this._cached,a,r)}}async function Ae(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await G({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new E("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function Te(e){const t=new ke(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>_e(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var Ie=async(e,t,r)=>{let n,o,i=!1;"function"==typeof AbortController&&(n=new AbortController,o=setTimeout(()=>{i=!0,n.abort()},t));const a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(e=>{if(i)throw new k;throw e});if(void 0!==o&&clearTimeout(o),200!==a.status)throw new p("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new p("Failed to parse the JSON Web Key Set HTTP response as JSON")}};let Pe;if("undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){Pe=`${"jose"}/${"v5.10.0"}`}const Re=Symbol();class Ce{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");var r,n;this._url=new URL(e.href),this._options={agent:t?.agent,headers:t?.headers},this._timeoutDuration="number"==typeof t?.timeoutDuration?t?.timeoutDuration:5e3,this._cooldownDuration="number"==typeof t?.cooldownDuration?t?.cooldownDuration:3e4,this._cacheMaxAge="number"==typeof t?.cacheMaxAge?t?.cacheMaxAge:6e5,void 0!==t?.[Re]&&(this._cache=t?.[Re],r=t?.[Re],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&$(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,$)&&(this._jwksTimestamp=this._cache.uat,this._local=Te(this._cache.jwks)))}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){this._local&&this.fresh()||await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof S&&!1===this.coolingDown())return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Pe&&!e.has("User-Agent")&&(e.set("User-Agent",Pe),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Ie(this._url,this._timeoutDuration,this._options).then(e=>{this._local=Te(e),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=e),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}}function xe(e,t){const r=new Ce(e,t),n=async(e,t)=>r.getKey(e,t);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}const De=u;function We(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new m("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function Oe(e,t){return async function(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:We(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:We(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:We(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":r={name:"Ed25519"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];const e=t?.crv??"Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new m("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];const e=t?.crv??"P-256";switch(e){case"P-256":case"P-384":case"P-521":r={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":r={name:e};break;default:throw new m("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return i.subtle.generateKey(r,t?.extractable??!1,n)}(e,t)}const He=async(e,t,r)=>{const n=new URL(t),o=n.origin+n.pathname+n.search,i=new URL(e).origin,a=await fetch(`${i}/.well-known/openid-configuration`).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),s=a.issuer,c=e=>e.endsWith("/")?e.slice(0,-1):e;if(c(e)!==c(s))throw new Error("RFC 9207 - iss !== idp - "+s+" !== "+e);sessionStorage.setItem("idp",s),sessionStorage.setItem("token_endpoint",a.token_endpoint),sessionStorage.setItem("jwks_uri",a.jwks_uri);let d=r?.client_id;if(!d){const e=a.registration_endpoint,t=await(async(e,t)=>{const r={...t,grant_types:["authorization_code","refresh_token"],token_endpoint_auth_method:"none",application_type:"web",subject_type:"public"};return fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})})(e,r??{redirect_uris:[o]}).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()});d=t.client_id}try{new URL(d)}catch{sessionStorage.setItem("client_id",d)}const{pkce_code_verifier:l,pkce_code_challenge:h}=await $e();sessionStorage.setItem("pkce_code_verifier",l);const u=window.crypto.randomUUID();sessionStorage.setItem("csrf_token",u);const p=a.authorization_endpoint+"?response_type=code"+`&redirect_uri=${encodeURIComponent(o)}&scope=openid offline_access webid`+`&client_id=${encodeURIComponent(d)}&code_challenge_method=S256`+`&code_challenge=${h}`+`&state=${u}&prompt=consent`;window.location.href=p},$e=async()=>{const e=window.crypto.randomUUID()+"-"+window.crypto.randomUUID(),t=new Uint8Array(await window.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)));return{pkce_code_verifier:e,pkce_code_challenge:btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}},Ne=async(e,t,r,n,o,i)=>{const a=await re(i.publicKey);a.alg="ES256";const s=await new ve({htu:o,htm:"POST"}).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:a}).sign(i.privateKey);return fetch(o,{method:"POST",headers:{dpop:s,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:r,client_id:n})})},Ue=async(e,t,r,n)=>{const o=await re(n.publicKey);o.alg="ES256";const i=await new ve({htu:r,htm:"POST"}).setIssuedAt().setJti(self.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:o}).sign(n.privateKey);return fetch(r,{method:"POST",headers:{dpop:i,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:t})})};var je;!function(e){e.STATE_CHANGE="sessionStateChange",e.EXPIRATION_WARNING="sessionExpirationWarning",e.EXPIRATION="sessionExpiration"}(je||(je={}));class Je extends EventTarget{isActive_=!1;exp_;webId_=void 0;currentAth_=void 0;information;database;refreshPromise;resolveRefresh;rejectRefresh;constructor(e,t){super(),this.authFetch=this.authFetch.bind(this),this.information={clientDetails:e},this.database=t?.database,t?.onSessionStateChange&&this.addEventListener(je.STATE_CHANGE,e=>t.onSessionStateChange?.(e)),t?.onSessionExpirationWarning&&this.addEventListener(je.EXPIRATION_WARNING,e=>t?.onSessionExpirationWarning?.(e)),t?.onSessionExpiration&&this.addEventListener(je.EXPIRATION,e=>t?.onSessionExpiration?.(e))}async login(e,t){await He(e,t,this.information.clientDetails)}async handleRedirectFromLogin(){const e=await(async(e,t)=>{const r=new URL(window.location.href),n=r.searchParams.get("code");if(null===n)return{clientDetails:e};const o=sessionStorage.getItem("idp");if(null===o||r.searchParams.get("iss")!==o)throw new Error("RFC 9207 - iss !== idp - "+r.searchParams.get("iss")+" !== "+o);if(r.searchParams.get("state")!==sessionStorage.getItem("csrf_token"))throw new Error("RFC 6749 - state !== csrf_token - "+r.searchParams.get("state")+" !== "+sessionStorage.getItem("csrf_token"));r.searchParams.delete("iss"),r.searchParams.delete("state"),r.searchParams.delete("code"),window.history.pushState({},document.title,r.toString());const i=sessionStorage.getItem("pkce_code_verifier");if(null===i)throw new Error("Access Token Request preparation - Could not find in sessionStorage: pkce_code_verifier");const a=e?.client_id||sessionStorage.getItem("client_id");if(!a)throw new Error("Access Token Request preparation - Could not find in sessionStorage: client_id (dynamic registration)");const s=sessionStorage.getItem("token_endpoint");if(null===s)throw new Error("Access Token Request preparation - Could not find in sessionStorage: token_endpoint");const c=await Oe("ES256"),d=await Ne(n,i,r.toString(),a,s,c).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),l=d.access_token,h=sessionStorage.getItem("jwks_uri");if(null===h)throw new Error("Access Token validation preparation - Could not find in sessionStorage: jwks_uri");const u=xe(new URL(h)),{payload:p}=await pe(l,u,{issuer:o,audience:"solid"}),w=await Ee(await re(c.publicKey));if(p.cnf.jkt!==w)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+p.cnf.jkt+" !== "+w);if(p.client_id!==a)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+p.client_id+" !== "+a);const f={...d,dpop_key_pair:c},y={idp:o,jwks_uri:h,token_endpoint:s};return e||(e={redirect_uris:[r.toString()]}),e.client_id=a,t&&(await t.init(),await Promise.all([t.setItem("idp",o),t.setItem("jwks_uri",h),t.setItem("token_endpoint",s),t.setItem("client_id",a),t.setItem("dpop_keypair",c),t.setItem("refresh_token",d.refresh_token)]),t.close()),sessionStorage.removeItem("csrf_token"),sessionStorage.removeItem("pkce_code_verifier"),sessionStorage.removeItem("idp"),sessionStorage.removeItem("jwks_uri"),sessionStorage.removeItem("token_endpoint"),sessionStorage.removeItem("client_id"),{clientDetails:e,idpDetails:y,tokenDetails:f}})(this.information.clientDetails,this.database);e.tokenDetails&&(this.information.clientDetails=e.clientDetails,this.information.idpDetails=e.idpDetails,await this.setTokenDetails(e.tokenDetails),this.dispatchStateChangeEvent())}async restore(){if(!this.database)throw new Error("Could not refresh tokens: missing database. Provide database in sessionOption.");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=new Promise((e,t)=>{this.resolveRefresh=e,this.rejectRefresh=t});const e=this.isActive;return(async e=>{try{await e.init();const t=await e.getItem("client_id"),r=await e.getItem("token_endpoint"),n=await e.getItem("dpop_keypair"),o=await e.getItem("refresh_token");if(null===t||null===r||null===n||null===o)throw new Error("Could not refresh tokens: details missing from database.");const i=await Ue(o,t,r,n).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),a=i.access_token,s=await e.getItem("idp");if(null===s)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: idp");const c=await e.getItem("jwks_uri");if(null===c)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: jwks_uri");const d=xe(new URL(c)),{payload:l}=await pe(a,d,{issuer:s,audience:"solid"}),h=await Ee(await re(n.publicKey));if(l.cnf.jkt!==h)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+l.cnf.jkt+" !== "+h);if(l.client_id!==t)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+l.client_id+" !== "+t);return await e.setItem("refresh_token",i.refresh_token),{...i,dpop_key_pair:n}}finally{e.close()}})(this.database).then(e=>this.setTokenDetails(e)).then(()=>this.resolveRefresh()).catch(e=>{this.isActive?(this.rejectRefresh(new Error(e||"Token refresh failed")),this.isExpired()?this.dispatchExpirationEvent():this.dispatchExpirationWarningEvent()):this.rejectRefresh(new Error("No session to restore."))}).finally(()=>{this.clearRefreshPromise(),e!==this.isActive&&this.dispatchStateChangeEvent()}),this.refreshPromise}async logout(){this.isActive_=!1,this.exp_=void 0,this.webId_=void 0,this.currentAth_=void 0,this.information.idpDetails=void 0,this.information.tokenDetails=void 0,this.refreshPromise&&this.rejectRefresh&&(this.rejectRefresh(new Error("Logout during token refresh.")),this.clearRefreshPromise()),this.database&&(await this.database.init(),await this.database.clear(),this.database.close()),this.dispatchStateChangeEvent()}async authFetch(e,t,r){if(!this.isActive)return fetch(e,t);let n,o,i;e instanceof Request?(n=new URL(e.url),o=t?.method||e?.method||"GET",i=new Headers(e.headers)):(t=t||{},n=new URL(e.toString()),o=t.method||"GET",i=t.headers?new Headers(t.headers):new Headers),await this._renewTokensIfExpired(),r=r??{htu:`${n.origin}${n.pathname}`,htm:o.toUpperCase()};const a=await this._createSignedDPoPToken(r);return i.set("dpop",a),i.set("authorization",`DPoP ${this.information.tokenDetails.access_token}`),e instanceof Request?fetch(new Request(e,{...t,headers:i})):fetch(n,{...t,headers:i})}async setTokenDetails(e){this.information.tokenDetails=e,await this._updateSessionDetailsFromToken(e.access_token)}clearRefreshPromise(){this.refreshPromise=void 0,this.resolveRefresh=void 0,this.rejectRefresh=void 0}get isActive(){return this.isActive_}get webId(){return this.webId_}isExpired(){return!this.exp_||this._isTokenExpired(this.exp_)}getExpiresIn(){return this.exp_?this._getTokenTTL(this.exp_):-1}getTokenDetails(){return this.information.tokenDetails}async _renewTokensIfExpired(){this.isExpired()&&(this.refreshPromise?await this.refreshPromise:await this.restore())}async _computeAth(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),n=Array.from(new Uint8Array(r));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async _createSignedDPoPToken(e){if(!this.information.tokenDetails||!this.currentAth_)throw new Error("Session not established.");e.ath=this.currentAth_;const t=await re(this.information.tokenDetails.dpop_key_pair.publicKey);return new ve(e).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:t}).sign(this.information.tokenDetails.dpop_key_pair.privateKey)}async _updateSessionDetailsFromToken(e){if(e)try{const t=function(e){if("string"!=typeof e)throw new v("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new v("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new v("Invalid JWT");if(!t)throw new v("JWTs must contain a payload");let n,o;try{n=De(t)}catch{throw new v("Failed to base64url decode the payload")}try{o=JSON.parse(d.decode(n))}catch{throw new v("Failed to parse the decoded payload as JSON")}if(!$(o))throw new v("Invalid JWT Claims Set");return o}(e),r=t.webid;if(!r)throw new Error("Missing webid claim in access token");const n=t.exp;if(!n)throw new Error("Missing exp claim in access token");this.currentAth_=await this._computeAth(e),this.webId_=r,this.exp_=n,this.isActive_=!0}catch(e){await this.logout()}else await this.logout()}_isTokenExpired(e,t=0){return!("number"==typeof e&&!isNaN(e))||this._getTokenTTL(e,t)<0}_getTokenTTL(e,t=0){return e-(Math.floor(Date.now()/1e3)+t)}dispatchStateChangeEvent(){this.dispatchEvent(new CustomEvent(je.STATE_CHANGE,{detail:{isActive:this.isActive,webId:this.webId}}))}dispatchExpirationWarningEvent(){this.dispatchEvent(new CustomEvent(je.EXPIRATION_WARNING,{detail:{expires_in:this.getExpiresIn()}}))}dispatchExpirationEvent(){this.dispatchEvent(new CustomEvent(je.EXPIRATION))}}var Le;!function(e){e.SCHEDULE="SCHEDULE",e.REFRESH="REFRESH",e.STOP="STOP",e.DISCONNECT="DISCONNECT",e.TOKEN_DETAILS="TOKEN_DETAILS",e.ERROR_ON_REFRESH="ERROR_ON_REFRESH",e.EXPIRED="EXPIRED"}(Le||(Le={}));class Ke{dbName;storeName;dbVersion;db=null;constructor(e="soidc",t="session",r=1){this.dbName=e,this.storeName=t,this.dbVersion=r}async init(){return new Promise((e,t)=>{const r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=e=>{t(new Error(`Database error: ${e.target.error}`))},r.onsuccess=t=>{this.db=t.target.result,e(this)},r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.storeName)||t.createObjectStore(this.storeName)}})}async setItem(e,t){return this.db||await this.init(),new Promise((r,n)=>{const o=this.db.transaction(this.storeName,"readwrite");o.oncomplete=()=>{r()},o.onerror=t=>{n(new Error(`Transaction error for setItem(${e},...): ${t.target.error}`))},o.onabort=t=>{n(new Error(`Transaction aborted for setItem(${e},...): ${t.target.error}`))};o.objectStore(this.storeName).put(t,e)})}async getItem(e){return this.db||await this.init(),new Promise((t,r)=>{const n=this.db.transaction(this.storeName,"readonly");n.onerror=t=>{r(new Error(`Transaction error for getItem(${e}): ${t.target.error}`))},n.onabort=t=>{r(new Error(`Transaction aborted for getItem(${e}): ${t.target.error}`))};const o=n.objectStore(this.storeName).get(e);o.onsuccess=()=>{t(o.result||null)}})}async deleteItem(e){return this.db||await this.init(),new Promise((t,r)=>{const n=this.db.transaction(this.storeName,"readwrite");n.oncomplete=()=>{t()},n.onerror=t=>{r(new Error(`Transaction error for deleteItem(${e}): ${t.target.error}`))},n.onabort=t=>{r(new Error(`Transaction aborted for deleteItem(${e}): ${t.target.error}`))};n.objectStore(this.storeName).delete(e)})}async clear(){return this.db||await this.init(),new Promise((e,t)=>{const r=this.db.transaction(this.storeName,"readwrite");r.oncomplete=()=>{e()},r.onerror=e=>{t(new Error(`Transaction error for clear(): ${e.target.error}`))},r.onabort=e=>{t(new Error(`Transaction aborted for clear(): ${e.target.error}`))};r.objectStore(this.storeName).clear()})}close(){this.db&&(this.db.close(),this.db=null)}}class Me extends Je{worker;constructor(e,t){const r=new Ke;super(e,{...t,database:r});const o=t?.workerUrl??new URL(n(552),n.b);this.worker=new SharedWorker(o,{type:"module"}),this.worker.port.onmessage=e=>{this.handleWorkerMessage(e.data).catch(console.error)},window.addEventListener("beforeunload",()=>{this.worker.port.postMessage({type:Le.DISCONNECT})})}async handleWorkerMessage(e){const{type:t,payload:r,error:n}=e;switch(t){case Le.TOKEN_DETAILS:const e=this.isActive;await this.setTokenDetails(r.tokenDetails),e!==this.isActive&&this.dispatchStateChangeEvent(),this.refreshPromise&&this.resolveRefresh&&(this.resolveRefresh(),this.clearRefreshPromise());break;case Le.ERROR_ON_REFRESH:this.isActive&&this.dispatchExpirationWarningEvent(),this.refreshPromise&&this.rejectRefresh&&(this.isActive?this.rejectRefresh(new Error(n||"Token refresh failed")):this.rejectRefresh(new Error("No session to restore")),this.clearRefreshPromise());break;case Le.EXPIRED:this.isActive&&(this.dispatchExpirationEvent(),await this.logout()),this.refreshPromise&&this.rejectRefresh&&(this.rejectRefresh(new Error(n||"Token refresh failed")),this.clearRefreshPromise())}}async handleRedirectFromLogin(){await super.handleRedirectFromLogin(),this.isActive&&this.worker.port.postMessage({type:Le.SCHEDULE,payload:{...this.getTokenDetails(),expires_in:this.getExpiresIn()}})}async restore(){return this.refreshPromise||(this.refreshPromise=new Promise((e,t)=>{this.resolveRefresh=e,this.rejectRefresh=t}),this.worker.port.postMessage({type:Le.REFRESH})),this.refreshPromise}async logout(){this.worker.port.postMessage({type:Le.STOP}),await super.logout()}}var Fe=crypto;const Be=e=>e instanceof CryptoKey;var Ve=async(e,t)=>{const r=`SHA-${e.slice(-3)}`;return new Uint8Array(await Fe.subtle.digest(r,t))};const Ge=new TextEncoder,qe=new TextDecoder;function ze(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const Xe=e=>(e=>{let t=e;"string"==typeof t&&(t=Ge.encode(t));const r=[];for(let e=0;e<t.length;e+=32768)r.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(r.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),Ye=e=>{let t=e;t instanceof Uint8Array&&(t=qe.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Ze extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}Ze.code="ERR_JOSE_GENERIC";class Qe extends Ze{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}Qe.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class et extends Ze{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}et.code="ERR_JWT_EXPIRED";class tt extends Ze{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}tt.code="ERR_JOSE_ALG_NOT_ALLOWED";class rt extends Ze{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}rt.code="ERR_JOSE_NOT_SUPPORTED";(class extends Ze{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends Ze{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class nt extends Ze{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}nt.code="ERR_JWS_INVALID";class ot extends Ze{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}ot.code="ERR_JWT_INVALID";class it extends Ze{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}it.code="ERR_JWK_INVALID";class at extends Ze{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}at.code="ERR_JWKS_INVALID";class st extends Ze{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}st.code="ERR_JWKS_NO_MATCHING_KEY";class ct extends Ze{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}ct.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class dt extends Ze{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}dt.code="ERR_JWKS_TIMEOUT";class lt extends Ze{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function ht(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ut(e,t){return e.name===t}function pt(e){return parseInt(e.name.slice(4),10)}function wt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ut(e.algorithm,"HMAC"))throw ht("HMAC");const r=parseInt(t.slice(2),10);if(pt(e.algorithm.hash)!==r)throw ht(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ut(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ht("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(pt(e.algorithm.hash)!==r)throw ht(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ut(e.algorithm,"RSA-PSS"))throw ht("RSA-PSS");const r=parseInt(t.slice(2),10);if(pt(e.algorithm.hash)!==r)throw ht(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw ht("Ed25519 or Ed448");break;case"Ed25519":if(!ut(e.algorithm,"Ed25519"))throw ht("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!ut(e.algorithm,"ECDSA"))throw ht("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw ht(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}function ft(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}lt.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var yt=(e,...t)=>ft("Key must be ",e,...t);function mt(e,t,...r){return ft(`Key for the ${e} algorithm must be `,t,...r)}var gt=e=>!!Be(e)||"KeyObject"===e?.[Symbol.toStringTag];const vt=["CryptoKey"];var bt=(...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0};function Et(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}var St=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function _t(e){return Et(e)&&"string"==typeof e.kty}var kt=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new rt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new rt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new rt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new rt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,Fe.subtle.importKey("jwk",o,...n)};const At=e=>Ye(e);let Tt,It;const Pt=e=>"KeyObject"===e?.[Symbol.toStringTag],Rt=async(e,t,r,n,o=!1)=>{let i=e.get(t);if(i?.[n])return i[n];const a=await kt({...r,alg:n});return o&&Object.freeze(t),i?i[n]=a:e.set(t,{[n]:a}),a};var Ct=(e,t)=>{if(Pt(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?At(r.k):(It||(It=new WeakMap),Rt(It,e,r,t))}if(_t(e)){if(e.k)return Ye(e.k);It||(It=new WeakMap);return Rt(It,e,e,t,!0)}return e},xt=(e,t)=>{if(Pt(e)){let r=e.export({format:"jwk"});return r.k?At(r.k):(Tt||(Tt=new WeakMap),Rt(Tt,e,r,t))}if(_t(e)){if(e.k)return Ye(e.k);Tt||(Tt=new WeakMap);return Rt(Tt,e,e,t,!0)}return e};async function Dt(e,t){if(!Et(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Ye(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new rt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return kt({...e,alg:t});default:throw new rt('Unsupported "kty" (Key Type) Parameter value')}}const Wt=e=>e?.[Symbol.toStringTag],Ot=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Ht=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&_t(t)){if(function(e){return _t(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&Ot(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!gt(t))throw new TypeError(mt(e,t,...vt,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${Wt(t)} instances for symmetric algorithms must be of type "secret"`)}};function $t(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Ht(t,r,n,e):((e,t,r,n)=>{if(n&&_t(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&Ot(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&Ot(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!gt(t))throw new TypeError(mt(e,t,...vt,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}$t.bind(void 0,!1);const Nt=$t.bind(void 0,!0);function Ut(e,t,r,n,o){if(void 0!==o.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!i.has(t))throw new rt(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}var jt=(e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};var Jt=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:Xe(e)};if(!Be(e))throw new TypeError(yt(e,...vt,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:t,key_ops:r,alg:n,use:o,...i}=await Fe.subtle.exportKey("jwk",e);return i};async function Lt(e){return Jt(e)}function Kt(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new rt(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Mt(e,t,r){if("sign"===r&&(t=await xt(t,e)),"verify"===r&&(t=await Ct(t,e)),Be(t))return wt(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(yt(t,...vt));return Fe.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(yt(t,...vt,"Uint8Array","JSON Web Key"))}var Ft=async(e,t,r,n)=>{const o=await Mt(e,t,"verify");St(e,o);const i=Kt(e,o.algorithm);try{return await Fe.subtle.verify(i,o,r,n)}catch{return!1}};async function Bt(e,t,r){if(e instanceof Uint8Array&&(e=qe.decode(e)),"string"!=typeof e)throw new nt("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:i,length:a}=e.split(".");if(3!==a)throw new nt("Invalid Compact JWS");const s=await async function(e,t,r){if(!Et(e))throw new nt("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new nt('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new nt("JWS Protected Header incorrect type");if(void 0===e.payload)throw new nt("JWS Payload missing");if("string"!=typeof e.signature)throw new nt("JWS Signature missing or incorrect type");if(void 0!==e.header&&!Et(e.header))throw new nt("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=Ye(e.protected);n=JSON.parse(qe.decode(t))}catch{throw new nt("JWS Protected Header is invalid")}if(!bt(n,e.header))throw new nt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header};let i=!0;if(Ut(nt,new Map([["b64",!0]]),r?.crit,n,o).has("b64")&&(i=n.b64,"boolean"!=typeof i))throw new nt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if("string"!=typeof a||!a)throw new nt('JWS "alg" (Algorithm) Header Parameter missing or invalid');const s=r&&jt("algorithms",r.algorithms);if(s&&!s.has(a))throw new tt('"alg" (Algorithm) Header Parameter value not allowed');if(i){if("string"!=typeof e.payload)throw new nt("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new nt("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t?(t=await t(n,e),c=!0,Nt(a,t,"verify"),_t(t)&&(t=await Dt(t,a))):Nt(a,t,"verify");const d=ze(Ge.encode(e.protected??""),Ge.encode("."),"string"==typeof e.payload?Ge.encode(e.payload):e.payload);let l,h;try{l=Ye(e.signature)}catch{throw new nt("Failed to base64url decode the signature")}if(!await Ft(a,t,l,d))throw new lt;if(i)try{h=Ye(e.payload)}catch{throw new nt("Failed to base64url decode the payload")}else h="string"==typeof e.payload?Ge.encode(e.payload):e.payload;const u={payload:h};return void 0!==e.protected&&(u.protectedHeader=n),void 0!==e.header&&(u.unprotectedHeader=e.header),c?{...u,key:t}:u}({payload:o,protected:n,signature:i},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...c,key:s.key}:c}var Vt=e=>Math.floor(e.getTime()/1e3);const Gt=86400,qt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var zt=e=>{const t=qt.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(r*Gt);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n};const Xt=e=>e.toLowerCase().replace(/^application\//,"");var Yt=(e,t,r={})=>{let n;try{n=JSON.parse(qe.decode(t))}catch{}if(!Et(n))throw new ot("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&("string"!=typeof e.typ||Xt(e.typ)!==Xt(o)))throw new Qe('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:d}=r,l=[...i];void 0!==d&&l.push("iat"),void 0!==c&&l.push("aud"),void 0!==s&&l.push("sub"),void 0!==a&&l.push("iss");for(const e of new Set(l.reverse()))if(!(e in n))throw new Qe(`missing required "${e}" claim`,n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new Qe('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new Qe('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(h=n.aud,u="string"==typeof c?[c]:c,!("string"==typeof h?u.includes(h):Array.isArray(h)&&u.some(Set.prototype.has.bind(new Set(h))))))throw new Qe('unexpected "aud" claim value',n,"aud","check_failed");var h,u;let p;switch(typeof r.clockTolerance){case"string":p=zt(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:w}=r,f=Vt(w||new Date);if((void 0!==n.iat||d)&&"number"!=typeof n.iat)throw new Qe('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new Qe('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>f+p)throw new Qe('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new Qe('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=f-p)throw new et('"exp" claim timestamp check failed',n,"exp","check_failed")}if(d){const e=f-n.iat;if(e-p>("number"==typeof d?d:zt(d)))throw new et('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-p)throw new Qe('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Zt(e,t,r){const n=await Bt(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new ot("JWTs MUST NOT use unencoded payload");const o={payload:Yt(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...o,key:n.key}:o}var Qt=async(e,t,r)=>{const n=await Mt(e,t,"sign");St(e,n);const o=await Fe.subtle.sign(Kt(e,n.algorithm),n,r);return new Uint8Array(o)};class er{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new nt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!bt(this._protectedHeader,this._unprotectedHeader))throw new nt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(Ut(nt,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new nt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=r;if("string"!=typeof o||!o)throw new nt('JWS "alg" (Algorithm) Header Parameter missing or invalid');Nt(o,e,"sign");let i,a=this._payload;n&&(a=Ge.encode(Xe(a))),i=this._protectedHeader?Ge.encode(Xe(JSON.stringify(this._protectedHeader))):Ge.encode("");const s=ze(i,Ge.encode("."),a),c=await Qt(o,e,s),d={signature:Xe(c),payload:""};return n&&(d.payload=qe.decode(a)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=qe.decode(i)),d}}class tr{constructor(e){this._flattened=new er(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function rr(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class nr{constructor(e={}){if(!Et(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:rr("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:rr("setNotBefore",Vt(e))}:this._payload={...this._payload,nbf:Vt(new Date)+zt(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:rr("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:rr("setExpirationTime",Vt(e))}:this._payload={...this._payload,exp:Vt(new Date)+zt(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:Vt(new Date)}:e instanceof Date?this._payload={...this._payload,iat:rr("setIssuedAt",Vt(e))}:this._payload="string"==typeof e?{...this._payload,iat:rr("setIssuedAt",Vt(new Date)+zt(e))}:{...this._payload,iat:rr("setIssuedAt",e)},this}}class or extends nr{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new tr(Ge.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new ot("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}const ir=(e,t)=>{if("string"!=typeof e||!e)throw new it(`${t} missing or invalid`)};async function ar(e,t){if(!Et(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),"sha256"!==t&&"sha384"!==t&&"sha512"!==t)throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":ir(e.crv,'"crv" (Curve) Parameter'),ir(e.x,'"x" (X Coordinate) Parameter'),ir(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":ir(e.crv,'"crv" (Subtype of Key Pair) Parameter'),ir(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":ir(e.e,'"e" (Exponent) Parameter'),ir(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":ir(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new rt('"kty" (Key Type) Parameter missing or unsupported')}const n=Ge.encode(JSON.stringify(r));return Xe(await Ve(t,n))}function sr(e){return Et(e)}function cr(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class dr{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(sr)}(e))throw new at("JSON Web Key Set malformed");this._jwks=cr(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},o=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new rt('Unsupported "alg" value for a JSON Web Key Set')}}(r),i=this._jwks.keys.filter(e=>{let t=o===e.kty;if(t&&"string"==typeof n&&(t=n===e.kid),t&&"string"==typeof e.alg&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":t="Ed25519"===e.crv;break;case"EdDSA":t="Ed25519"===e.crv||"Ed448"===e.crv}return t}),{0:a,length:s}=i;if(0===s)throw new st;if(1!==s){const e=new ct,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of i)try{yield await lr(t,e,r)}catch{}},e}return lr(this._cached,a,r)}}async function lr(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await Dt({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new at("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function hr(e){const t=new dr(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>cr(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var ur=async(e,t,r)=>{let n,o,i=!1;"function"==typeof AbortController&&(n=new AbortController,o=setTimeout(()=>{i=!0,n.abort()},t));const a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(e=>{if(i)throw new dt;throw e});if(void 0!==o&&clearTimeout(o),200!==a.status)throw new Ze("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new Ze("Failed to parse the JSON Web Key Set HTTP response as JSON")}};let pr;if("undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){pr=`${"jose"}/${"v5.10.0"}`}const wr=Symbol();class fr{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");var r,n;this._url=new URL(e.href),this._options={agent:t?.agent,headers:t?.headers},this._timeoutDuration="number"==typeof t?.timeoutDuration?t?.timeoutDuration:5e3,this._cooldownDuration="number"==typeof t?.cooldownDuration?t?.cooldownDuration:3e4,this._cacheMaxAge="number"==typeof t?.cacheMaxAge?t?.cacheMaxAge:6e5,void 0!==t?.[wr]&&(this._cache=t?.[wr],r=t?.[wr],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&Et(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,Et)&&(this._jwksTimestamp=this._cache.uat,this._local=hr(this._cache.jwks)))}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){this._local&&this.fresh()||await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof st&&!1===this.coolingDown())return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);pr&&!e.has("User-Agent")&&(e.set("User-Agent",pr),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=ur(this._url,this._timeoutDuration,this._options).then(e=>{this._local=hr(e),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=e),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}}function yr(e,t){const r=new fr(e,t),n=async(e,t)=>r.getKey(e,t);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}const mr=Ye;function gr(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new rt("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function vr(e,t){return async function(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:gr(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:gr(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:gr(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":r={name:"Ed25519"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];const e=t?.crv??"Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new rt("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];const e=t?.crv??"P-256";switch(e){case"P-256":case"P-384":case"P-521":r={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":r={name:e};break;default:throw new rt("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new rt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return Fe.subtle.generateKey(r,t?.extractable??!1,n)}(e,t)}const br=async(e,t,r)=>{const n=new URL(t),o=n.origin+n.pathname+n.search,i=new URL(e).origin,a=await fetch(`${i}/.well-known/openid-configuration`).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),s=a.issuer,c=e=>e.endsWith("/")?e.slice(0,-1):e;if(c(e)!==c(s))throw new Error("RFC 9207 - iss !== idp - "+s+" !== "+e);sessionStorage.setItem("idp",s),sessionStorage.setItem("token_endpoint",a.token_endpoint),sessionStorage.setItem("jwks_uri",a.jwks_uri);let d=r?.client_id;if(!d){const e=a.registration_endpoint,t=await(async(e,t)=>{const r={...t,grant_types:["authorization_code","refresh_token"],token_endpoint_auth_method:"none",application_type:"web",subject_type:"public"};return fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})})(e,r??{redirect_uris:[o]}).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()});d=t.client_id}try{new URL(d)}catch{sessionStorage.setItem("client_id",d)}const{pkce_code_verifier:l,pkce_code_challenge:h}=await Er();sessionStorage.setItem("pkce_code_verifier",l);const u=window.crypto.randomUUID();sessionStorage.setItem("csrf_token",u);const p=a.authorization_endpoint+"?response_type=code"+`&redirect_uri=${encodeURIComponent(o)}&scope=openid offline_access webid`+`&client_id=${encodeURIComponent(d)}&code_challenge_method=S256`+`&code_challenge=${h}`+`&state=${u}&prompt=consent`;window.location.href=p},Er=async()=>{const e=window.crypto.randomUUID()+"-"+window.crypto.randomUUID(),t=new Uint8Array(await window.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)));return{pkce_code_verifier:e,pkce_code_challenge:btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}},Sr=async(e,t,r,n,o,i)=>{const a=await Lt(i.publicKey);a.alg="ES256";const s=await new or({htu:o,htm:"POST"}).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:a}).sign(i.privateKey);return fetch(o,{method:"POST",headers:{dpop:s,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:r,client_id:n})})},_r=async(e,t,r,n)=>{const o=await Lt(n.publicKey);o.alg="ES256";const i=await new or({htu:r,htm:"POST"}).setIssuedAt().setJti(self.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:o}).sign(n.privateKey);return fetch(r,{method:"POST",headers:{dpop:i,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:t})})};var kr;!function(e){e.STATE_CHANGE="sessionStateChange",e.EXPIRATION_WARNING="sessionExpirationWarning",e.EXPIRATION="sessionExpiration"}(kr||(kr={}));class Ar extends EventTarget{isActive_=!1;exp_;webId_=void 0;currentAth_=void 0;information;database;refreshPromise;resolveRefresh;rejectRefresh;constructor(e,t){super(),this.authFetch=this.authFetch.bind(this),this.information={clientDetails:e},this.database=t?.database,t?.onSessionStateChange&&this.addEventListener(kr.STATE_CHANGE,e=>t.onSessionStateChange?.(e)),t?.onSessionExpirationWarning&&this.addEventListener(kr.EXPIRATION_WARNING,e=>t?.onSessionExpirationWarning?.(e)),t?.onSessionExpiration&&this.addEventListener(kr.EXPIRATION,e=>t?.onSessionExpiration?.(e))}async login(e,t){await br(e,t,this.information.clientDetails)}async handleRedirectFromLogin(){const e=await(async(e,t)=>{const r=new URL(window.location.href),n=r.searchParams.get("code");if(null===n)return{clientDetails:e};const o=sessionStorage.getItem("idp");if(null===o||r.searchParams.get("iss")!==o)throw new Error("RFC 9207 - iss !== idp - "+r.searchParams.get("iss")+" !== "+o);if(r.searchParams.get("state")!==sessionStorage.getItem("csrf_token"))throw new Error("RFC 6749 - state !== csrf_token - "+r.searchParams.get("state")+" !== "+sessionStorage.getItem("csrf_token"));r.searchParams.delete("iss"),r.searchParams.delete("state"),r.searchParams.delete("code"),window.history.pushState({},document.title,r.toString());const i=sessionStorage.getItem("pkce_code_verifier");if(null===i)throw new Error("Access Token Request preparation - Could not find in sessionStorage: pkce_code_verifier");const a=e?.client_id||sessionStorage.getItem("client_id");if(!a)throw new Error("Access Token Request preparation - Could not find in sessionStorage: client_id (dynamic registration)");const s=sessionStorage.getItem("token_endpoint");if(null===s)throw new Error("Access Token Request preparation - Could not find in sessionStorage: token_endpoint");const c=await vr("ES256"),d=await Sr(n,i,r.toString(),a,s,c).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),l=d.access_token,h=sessionStorage.getItem("jwks_uri");if(null===h)throw new Error("Access Token validation preparation - Could not find in sessionStorage: jwks_uri");const u=yr(new URL(h)),{payload:p}=await Zt(l,u,{issuer:o,audience:"solid"}),w=await ar(await Lt(c.publicKey));if(p.cnf.jkt!==w)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+p.cnf.jkt+" !== "+w);if(p.client_id!==a)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+p.client_id+" !== "+a);const f={...d,dpop_key_pair:c},y={idp:o,jwks_uri:h,token_endpoint:s};return e||(e={redirect_uris:[r.toString()]}),e.client_id=a,t&&(await t.init(),await Promise.all([t.setItem("idp",o),t.setItem("jwks_uri",h),t.setItem("token_endpoint",s),t.setItem("client_id",a),t.setItem("dpop_keypair",c),t.setItem("refresh_token",d.refresh_token)]),t.close()),sessionStorage.removeItem("csrf_token"),sessionStorage.removeItem("pkce_code_verifier"),sessionStorage.removeItem("idp"),sessionStorage.removeItem("jwks_uri"),sessionStorage.removeItem("token_endpoint"),sessionStorage.removeItem("client_id"),{clientDetails:e,idpDetails:y,tokenDetails:f}})(this.information.clientDetails,this.database);e.tokenDetails&&(this.information.clientDetails=e.clientDetails,this.information.idpDetails=e.idpDetails,await this.setTokenDetails(e.tokenDetails),this.dispatchStateChangeEvent())}async restore(){if(!this.database)throw new Error("Could not refresh tokens: missing database. Provide database in sessionOption.");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=new Promise((e,t)=>{this.resolveRefresh=e,this.rejectRefresh=t});const e=this.isActive;return(async e=>{try{await e.init();const t=await e.getItem("client_id"),r=await e.getItem("token_endpoint"),n=await e.getItem("dpop_keypair"),o=await e.getItem("refresh_token");if(null===t||null===r||null===n||null===o)throw new Error("Could not refresh tokens: details missing from database.");const i=await _r(o,t,r,n).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),a=i.access_token,s=await e.getItem("idp");if(null===s)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: idp");const c=await e.getItem("jwks_uri");if(null===c)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: jwks_uri");const d=yr(new URL(c)),{payload:l}=await Zt(a,d,{issuer:s,audience:"solid"}),h=await ar(await Lt(n.publicKey));if(l.cnf.jkt!==h)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+l.cnf.jkt+" !== "+h);if(l.client_id!==t)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+l.client_id+" !== "+t);return await e.setItem("refresh_token",i.refresh_token),{...i,dpop_key_pair:n}}finally{e.close()}})(this.database).then(e=>this.setTokenDetails(e)).then(()=>this.resolveRefresh()).catch(e=>{this.isActive?(this.rejectRefresh(new Error(e||"Token refresh failed")),this.isExpired()?this.dispatchExpirationEvent():this.dispatchExpirationWarningEvent()):this.rejectRefresh(new Error("No session to restore."))}).finally(()=>{this.clearRefreshPromise(),e!==this.isActive&&this.dispatchStateChangeEvent()}),this.refreshPromise}async logout(){this.isActive_=!1,this.exp_=void 0,this.webId_=void 0,this.currentAth_=void 0,this.information.idpDetails=void 0,this.information.tokenDetails=void 0,this.refreshPromise&&this.rejectRefresh&&(this.rejectRefresh(new Error("Logout during token refresh.")),this.clearRefreshPromise()),this.database&&(await this.database.init(),await this.database.clear(),this.database.close()),this.dispatchStateChangeEvent()}async authFetch(e,t,r){if(!this.isActive)return fetch(e,t);let n,o,i;e instanceof Request?(n=new URL(e.url),o=t?.method||e?.method||"GET",i=new Headers(e.headers)):(t=t||{},n=new URL(e.toString()),o=t.method||"GET",i=t.headers?new Headers(t.headers):new Headers),await this._renewTokensIfExpired(),r=r??{htu:`${n.origin}${n.pathname}`,htm:o.toUpperCase()};const a=await this._createSignedDPoPToken(r);return i.set("dpop",a),i.set("authorization",`DPoP ${this.information.tokenDetails.access_token}`),e instanceof Request?fetch(new Request(e,{...t,headers:i})):fetch(n,{...t,headers:i})}async setTokenDetails(e){this.information.tokenDetails=e,await this._updateSessionDetailsFromToken(e.access_token)}clearRefreshPromise(){this.refreshPromise=void 0,this.resolveRefresh=void 0,this.rejectRefresh=void 0}get isActive(){return this.isActive_}get webId(){return this.webId_}isExpired(){return!this.exp_||this._isTokenExpired(this.exp_)}getExpiresIn(){return this.exp_?this._getTokenTTL(this.exp_):-1}getTokenDetails(){return this.information.tokenDetails}async _renewTokensIfExpired(){this.isExpired()&&(this.refreshPromise?await this.refreshPromise:await this.restore())}async _computeAth(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),n=Array.from(new Uint8Array(r));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async _createSignedDPoPToken(e){if(!this.information.tokenDetails||!this.currentAth_)throw new Error("Session not established.");e.ath=this.currentAth_;const t=await Lt(this.information.tokenDetails.dpop_key_pair.publicKey);return new or(e).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:t}).sign(this.information.tokenDetails.dpop_key_pair.privateKey)}async _updateSessionDetailsFromToken(e){if(e)try{const t=function(e){if("string"!=typeof e)throw new ot("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new ot("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new ot("Invalid JWT");if(!t)throw new ot("JWTs must contain a payload");let n,o;try{n=mr(t)}catch{throw new ot("Failed to base64url decode the payload")}try{o=JSON.parse(qe.decode(n))}catch{throw new ot("Failed to parse the decoded payload as JSON")}if(!Et(o))throw new ot("Invalid JWT Claims Set");return o}(e),r=t.webid;if(!r)throw new Error("Missing webid claim in access token");const n=t.exp;if(!n)throw new Error("Missing exp claim in access token");this.currentAth_=await this._computeAth(e),this.webId_=r,this.exp_=n,this.isActive_=!0}catch(e){await this.logout()}else await this.logout()}_isTokenExpired(e,t=0){return!("number"==typeof e&&!isNaN(e))||this._getTokenTTL(e,t)<0}_getTokenTTL(e,t=0){return e-(Math.floor(Date.now()/1e3)+t)}dispatchStateChangeEvent(){this.dispatchEvent(new CustomEvent(kr.STATE_CHANGE,{detail:{isActive:this.isActive,webId:this.webId}}))}dispatchExpirationWarningEvent(){this.dispatchEvent(new CustomEvent(kr.EXPIRATION_WARNING,{detail:{expires_in:this.getExpiresIn()}}))}dispatchExpirationEvent(){this.dispatchEvent(new CustomEvent(kr.EXPIRATION))}}class Tr{constructor(){this.map=new Map}shouldPreserveExistingRefreshToken(e,t){return"refresh_token"===e&&(null==t||""===t)&&this.map.has(e)}async init(){return this}async setItem(e,t){this.shouldPreserveExistingRefreshToken(e,t)||this.map.set(e,t)}async getItem(e){return this.map.has(e)?this.map.get(e):null}async deleteItem(e){this.map.delete(e)}async clear(){this.map.clear()}close(){}}class Ir{constructor(){this.db=null,this.dbName="soidc",this.storeName="session",this.dbVersion=1}async shouldPreserveExistingRefreshToken(e,t){if("refresh_token"!==e||null!=t&&""!==t)return!1;const r=await this.getItem(e);return null!=r&&""!==r}async init(){if(this.db)return this;if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available in this environment");return await new Promise((e,t)=>{const r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=()=>t(r.error),r.onsuccess=()=>{this.db=r.result,e()},r.onupgradeneeded=()=>{const e=r.result;e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName)}}),this}async setItem(e,t){await this.init(),await this.shouldPreserveExistingRefreshToken(e,t)||await this.withStore("readwrite",r=>r.put(t,e))}async getItem(e){return await this.init(),this.withStore("readonly",t=>t.get(e))}async deleteItem(e){await this.init(),await this.withStore("readwrite",t=>t.delete(e))}async clear(){await this.init(),await this.withStore("readwrite",e=>e.clear())}close(){this.db&&(this.db.close(),this.db=null)}withStore(e,t){return new Promise((r,n)=>{if(!this.db)return void n(new Error("Session database not initialized"));const o=this.db.transaction(this.storeName,e),i=o.objectStore(this.storeName),a=t(i);let s=null;o.onerror=()=>{var e;return n(null!==(e=o.error)&&void 0!==e?e:a.error)},o.onabort=()=>{var e,t;return n(null!==(t=null!==(e=o.error)&&void 0!==e?e:a.error)&&void 0!==t?t:new Error("IndexedDB transaction aborted"))},o.oncomplete=()=>r(s),a.onerror=()=>n(a.error),a.onsuccess=()=>{var e;s=null!==(e=a.result)&&void 0!==e?e:null}})}}const Pr=function(){var t,r,n;const o=e,i=null!==(n=null!==(t=o.SessionCore)&&void 0!==t?t:null===(r=o.default)||void 0===r?void 0:r.SessionCore)&&void 0!==n?n:o.default;return"function"!=typeof i?null:i}();const Rr=function(){if("undefined"!=typeof window&&(()=>{const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e||e.endsWith(".localhost")})())return Pr?new Pr(void 0,{database:new Ir}):new Me;try{return new Me}catch(e){console.warn("solid-logic: falling back to non-worker auth session:",e);try{return Pr?new Pr(void 0,{database:new Ir}):new Me}catch(e){return console.warn("solid-logic: IndexedDB unavailable, using in-memory session database:",e),Pr?new Pr(void 0,{database:new Tr}):new Me}}}();async function Cr(e){const t=await async function(e){try{const t=new URL(e),r=new URL("/.well-known/openid-configuration",t.origin),n=await fetch(r.toString(),{credentials:"include"});if(!n.ok)return null;const o=await n.json();return"string"==typeof(null==o?void 0:o.issuer)&&o.issuer?o.issuer.replace(/\/$/,""):null}catch(e){return null}}(e);return t||e}var xr;const Dr=Rr,Wr="function"==typeof Dr.login?Dr.login.bind(Rr):void 0;if(Wr){const e=async(e,t)=>{var r,n,o,i;if(e&&"object"==typeof e&&!Array.isArray(e)){const t=null!==(n=null!==(r=e.oidcIssuer)&&void 0!==r?r:e.idp)&&void 0!==n?n:e.issuer,a=null!==(i=null!==(o=e.redirectUrl)&&void 0!==o?o:e.redirect_uri)&&void 0!==i?i:e.redirectUri;if("string"==typeof t&&"string"==typeof a)return Wr(await Cr(t),a)}return Wr("string"==typeof e?await Cr(e):e,t)};Dr.login=e}const Or=new class{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){var r;null===(r=this.listeners.get(e))||void 0===r||r.delete(t)}emit(e,...t){var r;null===(r=this.listeners.get(e))||void 0===r||r.forEach(e=>e(...t))}};let Hr=null!==(xr=Rr.isActive)&&void 0!==xr?xr:Boolean(Rr.webId);"function"==typeof Rr.addEventListener&&Rr.addEventListener("sessionStateChange",()=>{var e;const t=null!==(e=Rr.isActive)&&void 0!==e?e:Boolean(Rr.webId);Hr&&!t&&Or.emit("logout"),Hr=t});const $r=Object.assign(Rr,{events:Or});Object.defineProperty($r,"info",{enumerable:!0,configurable:!0,get(){const e=Rr,t=!0===e.isActive||Boolean(e.webId);return{webId:e.webId,isLoggedIn:t}}});var Nr=n(264),Ur=n(386);const jr=n.n(Ur)()(Nr),Jr=(0,Nr.sym)("http://www.iana.org/assignments/link-relations/acl");function Lr(e){const t=jr;function r(e,r,n,o={}){const i=o.public||[],a=(0,Nr.graph)(),s=(0,Nr.Namespace)("http://www.w3.org/ns/auth/acl#");let c=a.sym(`${n}#a1`);const d=a.sym(n),l=a.sym(e);if(a.add(c,t.rdf("type"),s("Authorization"),d),a.add(c,s("accessTo"),l,d),o.defaultForNew&&a.add(c,s("default"),l,d),a.add(c,s("agent"),r,d),a.add(c,s("mode"),s("Read"),d),a.add(c,s("mode"),s("Write"),d),a.add(c,s("mode"),s("Control"),d),i.length){c=a.sym(`${n}#a2`),a.add(c,t.rdf("type"),s("Authorization"),d),a.add(c,s("accessTo"),l,d),a.add(c,s("agentClass"),t.foaf("Agent"),d);for(let e=0;e<i.length;e++)a.add(c,s("mode"),s(i[e]),d)}return(0,Nr.serialize)(d,a,n)}return{findAclDocUrl:async function(t){await e.fetcher.load(t);const r=e.any(t,Jr);if(!r)throw new Error(`No ACL link discovered for ${t}`);return r.value},setACLUserPublic:function(t,n,o){const i=e.any(e.sym(t),Jr);return Promise.resolve().then(()=>i||function(t){const r=e.fetcher;if(!r)throw new Error("Cannot fetch ACL rel, store has no fetcher");return r.load(t).then(r=>{if(!r.ok)throw new Error("fetchACLRel: While loading:"+r.error);const n=e.any(e.sym(t),Jr);if(!n)throw new Error("fetchACLRel: No Link rel=ACL header for "+t);return n})}(t).catch(e=>{throw new Error(`Error fetching rel=ACL header for ${t}: ${e}`)})).then(i=>{const a=r(t,n,i.uri,o);if(!e.fetcher)throw new Error("Cannot PUT this, store has no fetcher");return e.fetcher.webOperation("PUT",i.uri,{data:a,contentType:"text/turtle"}).then(e=>{if(!e.ok)throw new Error("Error writing ACL text: "+e.error);return i})})},genACLText:r}}const Kr=()=>{let{SolidAppContext:e}=window;if(e||(e={}),e.viewingNoAuthPage=!1,e.noAuth&&window.document){if(window.document.location.href.startsWith(e.noAuth)){e.viewingNoAuthPage=!0;const t=new URLSearchParams(window.document.location.search);if(t){let r=e.viewedPage=t.get("uri")||null;if(r&&(r=decodeURI(r),!r.startsWith(e.noAuth))){const t=r.split(/\//);e.idp=t[0]+"//"+t[2],e.viewingNoAuthPage=!1}}}}return e};function Mr(){const{$SolidTestEnvironment:e}=window;if(void 0!==e&&e.username)return t("Assuming the user is "+e.username),(0,Nr.sym)(e.username);if("undefined"!=typeof document&&document.location&&"http://localhost"===(""+document.location).slice(0,16)){const e=document.getElementById("appTarget");if(!e)return null;const r=e.getAttribute("testID");return r?(t("Assuming user is "+r),(0,Nr.sym)(r)):null}return null}class Fr{constructor(e){this.checkUserInFlight=null,this.sessionRestoreHookAttached=!1,this.fallbackWebId=null,this.session=e}get authSession(){return this.session}currentUser(){var e,t;const r=Kr();if(r.viewingNoAuthPage)return(0,Nr.sym)(r.webId);const n=this.session,o=null===(e=null==n?void 0:n.info)||void 0===e?void 0:e.webId,i=null==n?void 0:n.webId,a=o||i||this.fallbackWebId,s=null===(t=null==n?void 0:n.info)||void 0===t?void 0:t.isLoggedIn,c=null==n?void 0:n.isActive,d=!0===s||!0===c||null==s&&null==c&&Boolean(a)||Boolean(this.fallbackWebId);return this&&this.session&&a&&d?(0,Nr.sym)(a):Mr()}async checkUser(e){var r;const n=new URL(window.location.href).hash;n&&window.localStorage.setItem("preLoginRedirectHash",n);const o=this.session;this.sessionRestoreHookAttached||"function"!=typeof(null===(r=null==o?void 0:o.events)||void 0===r?void 0:r.on)||(o.events.on("sessionRestore",e=>{t(`Session restored to ${e}`),document.location.toString()!==e&&history.replaceState(null,"",e)}),this.sessionRestoreHookAttached=!0),this.checkUserInFlight||(this.checkUserInFlight=this.resolveCurrentUser());const i=this.checkUserInFlight;let a;try{a=await i}finally{this.checkUserInFlight===i&&(this.checkUserInFlight=null)}return Promise.resolve(e?e(a):a)}async resolveCurrentUser(){var e,r,n,o,i,a;const s=this.session,c=new URL(window.location.href);if(c.hash="","function"==typeof(null==s?void 0:s.handleIncomingRedirect))await s.handleIncomingRedirect({restorePreviousSession:!0,url:c.href});else{if("function"==typeof(null==s?void 0:s.restore)){const o=null!==(e=null==s?void 0:s.isActive)&&void 0!==e?e:Boolean(null==s?void 0:s.webId);try{await s.restore()}catch(e){const r=e instanceof Error?e.message:String(e);if(!/no session to restore/i.test(r))throw e;t("No previous session to restore")}const i=null!==(r=null==s?void 0:s.isActive)&&void 0!==r?r:Boolean(null==s?void 0:s.webId);!o&&i&&(null===(n=s.events)||void 0===n||n.emit("sessionRestore",window.location.href))}if("function"==typeof(null==s?void 0:s.handleRedirectFromLogin)){const e=null!==(o=null==s?void 0:s.isActive)&&void 0!==o?o:Boolean(null==s?void 0:s.webId);await s.handleRedirectFromLogin();const t=null!==(i=null==s?void 0:s.isActive)&&void 0!==i?i:Boolean(null==s?void 0:s.webId);!e&&t&&(null===(a=s.events)||void 0===a||a.emit("login"))}}const d=window.localStorage.getItem("preLoginRedirectHash");if(d){const e=new URL(window.location.href);e.hash!==d&&(history.pushState?history.pushState(null,document.title,d):location.hash=d,e.hash=d),window.localStorage.setItem("preLoginRedirectHash","")}let l=Mr();if(l)return l;let h=this.webIdFromSession(null==s?void 0:s.info,s);return h||(h=await this.probeNssCookieBackedWebId()),this.fallbackWebId=h||null,h&&(l=this.saveUser(h)),l&&t(`(Logged in as ${l} by authentication)`),l}async probeNssCookieBackedWebId(){if("undefined"==typeof window)return null;const{hostname:e,port:t,protocol:r}=window.location,n=".localhost";if(!e.endsWith(n))return null;const o=e.slice(0,-10);if(!o||"localhost"===o||o.includes("."))return null;try{if(403!==(await fetch("/account/password/change",{credentials:"include",redirect:"manual",cache:"no-store"})).status)return null;return`${`${r}//${e}${t?`:${t}`:""}`}/profile/card#me`}catch(e){return null}}saveUser(e,t){let r;if(e){r="string"==typeof e?e:e.uri;const n=(0,Nr.namedNode)(r);return t&&(t.me=n),n}return null}webIdFromSession(e,t){const r=(null==e?void 0:e.webId)||(null==t?void 0:t.webId);if(!r)return null;const n=null==e?void 0:e.isLoggedIn,o=null==t?void 0:t.isLoggedIn,i=null==t?void 0:t.isActive;return!0===n||!0===o||!0===i?r:!1===n&&!1===o&&!1===i?null:r}}function Br(e){return(0,Nr.sym)(e.uri+"#id"+Date.now())}function Vr(e){return!e||`${window.location.origin}/`!==new URL(e.value).origin}const Gr="index.ttl#this";function qr(e,t){const r=jr;async function n(t,r,n){await e.fetcher.load(t);const o=e.any(t,new Nr.NamedNode("http://www.iana.org/assignments/link-relations/acl"));if(!o)throw new Error("Chat ACL doc not found!");const i=`\n @prefix acl: <http://www.w3.org/ns/auth/acl#>.\n <#owner>\n a acl:Authorization;\n acl:agent <${r.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Write, acl:Control.\n <#invitee>\n a acl:Authorization;\n acl:agent <${n.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Append.\n `;await e.fetcher.webOperation("PUT",o.value,{data:i,contentType:"text/turtle"})}async function o(t,n){const o=e.any(n,r.solid("privateTypeIndex"));if(!o)throw new Error("Private type index not found!");await e.fetcher.load(o);const i=Br(o),a=[(0,Nr.st)(i,r.rdf("type"),r.solid("TypeRegistration"),o.doc()),(0,Nr.st)(i,r.solid("forClass"),r.meeting("LongChat"),o.doc()),(0,Nr.st)(i,r.solid("instance"),t,o.doc())];await new Promise((t,r)=>{e.updater.update([],a,function(e,n,o){n?t(null):r(new Error(o))})})}async function i(r){const n=await t.loadMe(),o=function(e,t){const r=new URL(`IndividualChats/${new URL(e.value).host}/`,t.value).toString();return new Nr.NamedNode(r)}(r,await t.getPodRoot(n));let i=!0;try{await e.fetcher.load(new Nr.NamedNode(o.value+"index.ttl#this"))}catch(e){i=!1}return{me:n,chatContainer:o,exists:i}}async function a(e,t){return(await s({me:t,newBase:e.value})).newInstance}function s(t){const n=e,o=n.updater;if(t.me&&!t.me.uri)throw new Error("chat mintNew: Invalid userid "+t.me);const i=t.newInstance=t.newInstance||n.sym(t.newBase+Gr),a=i.doc();return n.add(i,r.rdf("type"),r.meeting("LongChat"),a),n.add(i,r.dc("title"),"Chat channel",a),n.add(i,r.dc("created"),(0,Nr.term)(new Date(Date.now())),a),t.me&&n.add(i,r.dc("author"),t.me,a),new Promise(function(e,r){null==o||o.put(a,n.statementsMatching(void 0,void 0,void 0,a),"text/turtle",function(n,o,a){o?e({...t,newInstance:i}):r(new Error("FAILED to save new chat channel at: "+n+" : "+a))})})}async function c(t,n){var o;await e.fetcher.load(t.doc());const i=e.any(t,r.ldp("inbox"),void 0,t.doc());if(!i)throw new Error(`Invitee inbox not found! ${t.value}`);const a=`\n <> a <http://www.w3.org/ns/pim/meeting#LongChatInvite> ;\n ${r.rdf("seeAlso")} <${n.value}> .\n `,s=await(null===(o=e.fetcher)||void 0===o?void 0:o.webOperation("POST",i.value,{data:a,contentType:"text/turtle"}));if(!(null==s?void 0:s.headers.get("location")))throw new Error(`Invite sending returned a ${null==s?void 0:s.status}`)}return{setAcl:n,addToPrivateTypeIndex:o,findChat:i,createChatThing:a,getChat:async function(e,t=!0){const{me:r,chatContainer:s,exists:d}=await i(e);if(d)return new Nr.NamedNode(s.value+Gr);if(t){const t=await a(s,r);return await c(e,t),await n(s,r,e),await o(t,r),t}return null},sendInvite:c,mintNew:s}}function zr(e,t,r,n,o){return{createInboxFor:async function(e,o){const i=await t.loadMe(),a=`${(await t.getPodRoot(i)).value}p2p-inboxes/${encodeURIComponent(o)}/`;return await n.createContainer(a),await r.setSinglePeerAccess({ownerWebId:i.value,peerWebId:e,accessToModes:"acl:Append",target:a}),a},getNewMessages:async function(e){e||(e=await t.loadMe());const r=await t.getMainInbox(e);return(await n.getContainerMembers(r)).filter(e=>!n.isContainer(e))},markAsRead:async function(t,r){const n=await e.fetcher._fetch(t);if(200!==n.status)throw new Error(`Not OK! ${t}`);const o=function(e,t){const r=t.getUTCFullYear(),n=("0"+(t.getUTCMonth()+1)).slice(-2),o=("0"+t.getUTCDate()).slice(-2),i=e.split("/"),a=i[i.length-1];return new URL(`./archive/${r}/${n}/${o}/${a}`,e).toString()}(t,r),i={method:"PUT",body:await n.text(),headers:[["Content-Type",n.headers.get("Content-Type")||"application/octet-stream"]]};"2"===(await e.fetcher._fetch(o,i)).status.toString()[0]&&await e.fetcher._fetch(t,{method:"DELETE"})}}}class Xr extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}}class Yr extends Xr{}class Zr extends Xr{}class Qr extends Xr{}class en extends Xr{}class tn extends Xr{}class rn extends Xr{}class nn extends Xr{constructor(e,t){super(t),this.status=e}}function on(){return["@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a solid:TypeIndex ;"," a solid:ListedDocument."].join("\n")}function an(){return["@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a solid:TypeIndex ;"," a solid:UnlistedDocument."].join("\n")}function sn(e,t){const r=new URL(t).pathname.split("/").pop()||"publicTypeIndex.ttl";return["# ACL resource for the Public Type Index","","@prefix acl: <http://www.w3.org/ns/auth/acl#>.","@prefix foaf: <http://xmlns.com/foaf/0.1/>.","","<#owner>"," a acl:Authorization;",""," acl:agent",` <${e}>;`,"",` acl:accessTo <./${r}>;`,""," acl:mode"," acl:Read, acl:Write, acl:Control.","","# Public-readable","<#public>"," a acl:Authorization;",""," acl:agentClass foaf:Agent;","",` acl:accessTo <./${r}>;`,""," acl:mode acl:Read."].join("\n")}function cn(e){function t(t){return e.statementsMatching(t,(0,Nr.sym)("http://www.w3.org/ns/ldp#contains"),void 0).map(e=>e.object)}function r(e){const t=e.value;return"/"===t.charAt(t.length-1)}return{isContainer:r,createContainer:async function(t){if(!r((0,Nr.sym)(t)))throw new Error(`Not a container URL ${t}`);const n=await e.fetcher._fetch(t,{method:"PUT",headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:'<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'},body:" "});if(409!==n.status&&"2"!==n.status.toString()[0])throw new Error(`Not OK: got ${n.status} response while creating container at ${t}`)},getContainerElements:t,getContainerMembers:async function(r){return await e.fetcher.load(r),t(r)}}}function dn(e,t,n){const o=jr,i=cn(e),a=new Map,s=new Map;function c(e){return!!e&&(e.startsWith("https://")||e.startsWith("http://"))}function d(e){const t=e.doc(),r=t.dir();if((null==r?void 0:r.uri)&&c(r.uri))return r.uri;const n=t.uri;if(!n||!c(n))return null;const o=n.split("#")[0],i=o.lastIndexOf("/");return-1===i?null:o.slice(0,i+1)}function l(e,t){const r=d(e);if(!r)throw new Error(`Cannot derive directory for preferences file ${e.uri}`);return(0,Nr.sym)(r+t)}function h(e){var t;if(404===(null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.status))return!0;const r=`${(null==e?void 0:e.message)||e||""}`;return r.includes("404")||r.includes("Not Found")}async function u(t,r){var n;const o=d(r);if(!o)throw new Error(`Cannot derive settings directory from ${r.uri}`);await async function(t){const r=(0,Nr.sym)(t);try{return void await e.fetcher.load(r)}catch(e){if(!h(e))throw e}await i.createContainer(t)}(o);const a=(0,Nr.sym)(o);let s;try{await e.fetcher.load(a),s=null===(n=e.any(a,Jr))||void 0===n?void 0:n.value}catch(e){if(!h(e))throw e}s||(s=`${o}.acl`);const c=(0,Nr.sym)(s);try{return void await e.fetcher.load(c)}catch(e){if(!h(e))throw e}var l;await e.fetcher.webOperation("PUT",c.uri,{data:(l=t.uri,["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","","<#owner>","a acl:Authorization;",`acl:agent <${l}>;`,"acl:accessTo <./>;","acl:default <./>;","acl:mode acl:Read, acl:Write, acl:Control."].join("\n")),contentType:"text/turtle"})}async function p(t,r){const i=r.doc(),a=t.doc();await e.fetcher.load(i);const s=e.any(t,o.solid("publicTypeIndex"),null,a),c=e.any(t,o.solid("publicTypeIndex"),null,i),d=s||c||l(r,"publicTypeIndex.ttl"),u=e.any(t,o.solid("privateTypeIndex"),null,i)||l(r,"privateTypeIndex.ttl"),p=!s;p&&await n.followOrCreateLinkWithContentOnCreate(t,o.solid("publicTypeIndex"),d,a,on());const w=[];e.holds(i,o.rdf("type"),o.space("ConfigurationFile"),i)||w.push((0,Nr.st)(i,o.rdf("type"),o.space("ConfigurationFile"),i)),e.holds(i,o.dct("title"),void 0,i)||w.push((0,Nr.st)(i,o.dct("title"),(0,Nr.literal)("Preferences file"),i)),e.holds(t,o.solid("publicTypeIndex"),d,i)||w.push((0,Nr.st)(t,o.solid("publicTypeIndex"),d,i)),e.holds(t,o.solid("privateTypeIndex"),u,i)||w.push((0,Nr.st)(t,o.solid("privateTypeIndex"),u,i)),w.length>0&&(await e.updater.update([],w),await e.fetcher.load(i)),await async function(t,r,o=!1){var i,a,s;if(!await n.loadOrCreateWithContentOnCreate(r,on())&&!o)return;let c;try{await e.fetcher.load(r),c=null===(i=e.any(r,Jr))||void 0===i?void 0:i.value}catch(e){if(!h(e))throw e}c||(c=`${r.uri}.acl`);const d=(0,Nr.sym)(c);try{await e.fetcher.webOperation("PUT",d.uri,{data:sn(t.uri,r.uri),contentType:"text/turtle",headers:{"If-None-Match":"*"}})}catch(e){if(412!==(null!==(s=null===(a=null==e?void 0:e.response)||void 0===a?void 0:a.status)&&void 0!==s?s:null==e?void 0:e.status))throw e}}(t,d,p),await async function(e){await n.loadOrCreateWithContentOnCreate(e,an())}(u)}async function w(e){var t,r;try{return!!await n.loadOrCreateWithContentOnCreate(e,["@prefix dct: <http://purl.org/dc/terms/>.","@prefix pim: <http://www.w3.org/ns/pim/space#>.","@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a pim:ConfigurationFile ;",' dct:title "Preferences file".'].join("\n"))}catch(n){if(401===(null===(t=n.response)||void 0===t?void 0:t.status))throw new Yr;if(403===(null===(r=n.response)||void 0===r?void 0:r.status)){if(Vr(e))throw new Zr;throw new Qr}throw n}}async function f(t){const i=s.get(t.uri);if(i)return i;const c=a.get(t.uri);if(c)return c;const d=(async()=>{var i;await y(t);const a=function(e){const t=e.uri.replace("/profile/","/").replace("/public/","/").split("/").slice(0,-1).join("/")+"/settings/prefs.ttl";return(0,Nr.sym)(t)}(t);let c;try{const r=e.any(t,o.space("preferencesFile"),null,t.doc());c=r||await n.followOrCreateLink(t,o.space("preferencesFile"),a,t.doc()),await u(t,c),await w(c),await p(t,c)}catch(e){if(r(`User ${t} has no pointer in profile to preferences file.`),e instanceof tn)throw e;if(e instanceof rn)throw e;if(e instanceof Yr)throw e;if(e instanceof Zr)throw e;if(e instanceof Qr)throw e;if(e instanceof nn)throw e;throw e}try{await e.fetcher.load(c)}catch(n){const o=`Unable to load preference of user ${t}: ${n}`;if(404===(null===(i=n.response)||void 0===i?void 0:i.status))return await u(t,c),await w(c),await p(t,c),await e.fetcher.load(c),c;if(r(o),401===n.response.status)throw new Yr;if(403===n.response.status){if(Vr(c))throw new Zr;throw new Qr}throw new Error(o)}return s.set(t.uri,c),c})();a.set(t.uri,d);try{return await d}finally{a.get(t.uri)===d&&a.delete(t.uri)}}async function y(t){if(!t)throw new Error("loadProfile: no user given.");try{await e.fetcher.load(t.doc())}catch(e){throw new Error(`Unable to load profile of user ${t}: ${e}`)}return t.doc()}function m(t){return e.any(t,o.space("storage"),void 0,t.doc())}return{loadMe:async function(){const r=t.currentUser();if(null===r)throw new Error("Current user not found! Not logged in?");return await e.fetcher.load(r.doc()),r},getPodRoot:function(e){const t=m(e);if(!t)throw new Error("User pod root not found!");return t},getMainInbox:async function(t){await e.fetcher.load(t);const r=e.any(t,o.ldp("inbox"),void 0,t.doc());if(!r)throw new Error("User main inbox not found!");return r},findStorage:m,loadPreferences:f,loadProfile:y,silencedLoadPreferences:async function(e){try{return await f(e)}catch(e){return}}}}function ln(e,n,o,i){const a=jr;function s(e){return!!e&&(e.startsWith("https://")||e.startsWith("http://"))}async function c(t){if(!t)throw new Error("loadTypeIndexesFor: No user given");const n=await o.loadProfile(t);let s,c=null;try{c=p(t)}catch(e){r(`User ${t} has no usable profile document directory for publicTypeIndex.`)}try{const r=e.any(t,a.solid("publicTypeIndex"),void 0,n);s=r||(c?await i.followOrCreateLinkWithContentOnCreate(t,a.solid("publicTypeIndex"),c,n,on()):null)}catch(e){r(`User ${t} has no pointer in profile to publicTypeIndex file: ${e}`)}const d=s?[{label:"public",index:s,agent:t}]:[];let l,h;try{l=await o.silencedLoadPreferences(t)}catch(e){l=null}if(l){let o,s=null;try{s=w(l)}catch(e){r(`User ${t} has no usable preferences document directory for privateTypeIndex.`)}try{const r=e.any(t,a.solid("privateTypeIndex"),void 0,n);o=r||(s?await i.followOrCreateLinkWithContentOnCreate(t,a.solid("privateTypeIndex"),s,l,an()):null)}catch(e){r(`User ${t} has no pointer in preference file to privateTypeIndex file: ${e}`)}h=o?[{label:"private",index:o,agent:t}]:[]}else h=[];const u=d.concat(h);if(0===u.length)return u;const f=u.map(e=>e.index);try{await e.fetcher.load(f)}catch(e){r("Problems loading type index: ",e)}return u}async function d(t){let n;try{n=await o.silencedLoadPreferences(t)}catch(e){r(`User ${t} has no pointer in profile to preferences file.`)}if(n){const o=e.each(t,a.solid("community"),void 0,n).concat(e.each(t,a.solid("community"),void 0,t.doc()));let i=[];for(const e of o)if("NamedNode"===e.termType&&s(e.uri))try{i=i.concat(await c(e))}catch(t){r(`Skipping community type indexes for ${e.uri}: ${t}`)}else r(`Skipping malformed community node for ${t}: ${e}`);return i}return[]}async function l(e){return(await c(e)).concat(await d(e))}async function h(e,t){const r=await l(t);let n=[];for(const t of r){const r=await f(t,e);n=n.concat(r)}return n}function u(e){const r=e.doc(),n=r.dir();if((null==n?void 0:n.uri)&&s(n.uri))return n.uri;const o=r.uri;if(!o||!s(o))return t(`docDirUri: missing or non-http(s) doc uri for ${null==e?void 0:e.uri}`),null;const i=o.split("#")[0],a=i.lastIndexOf("/");return-1===a?(t(`docDirUri: no slash in doc uri ${o}`),null):i.slice(0,a+1)}function p(e){const t=u(e);if(!t)throw new Error(`suggestPublicTypeIndex: Cannot derive directory for ${e.uri}`);return(0,Nr.sym)(t+"publicTypeIndex.ttl")}function w(e){const t=u(e);if(!t)throw new Error(`suggestPrivateTypeIndex: Cannot derive directory for ${e.uri}`);return(0,Nr.sym)(t+"privateTypeIndex.ttl")}async function f(t,r){const n=t.index,o=[],i=e.statementsMatching(null,a.solid("instance"),null,n).concat(e.statementsMatching(null,a.solid("instanceContainer"),null,n)).map(e=>e.subject);for(const s of i){const i=e.any(s,a.solid("forClass"),null,n);if(!r||i.sameTerm(r)){const r=e.each(s,a.solid("instance"),null,n);for(const e of r)o.push({instance:e,type:i,scope:t});const c=e.each(s,a.solid("instanceContainer"),null,n);for(const r of c)await e.fetcher.load(r),o.push({instance:(0,Nr.sym)(r.value),type:i,scope:t})}}return o}return{registerInTypeIndex:async function(t,r,n){const o=Br(r),i=[(0,Nr.st)(o,a.rdf("type"),a.solid("TypeRegistration"),r),(0,Nr.st)(o,a.solid("forClass"),n,r),(0,Nr.st)(o,a.solid("instance"),t,r)];try{await e.updater.update([],i)}catch(e){const n=`Unable to register ${t} in index ${r}: ${e}`;return console.warn(n),null}return o},getRegistrations:function(t,r){return e.each(void 0,a.solid("instance"),t).filter(t=>e.holds(t,a.solid("forClass"),r))},loadTypeIndexesFor:c,loadCommunityTypeIndexes:d,loadAllTypeIndexes:l,getScopedAppInstances:h,getAppInstances:async function(e){const t=n.currentUser();if(!t)throw new Error("getAppInstances: Must be logged in to find apps.");return(await h(e,t)).map(e=>e.instance)},suggestPublicTypeIndex:p,suggestPrivateTypeIndex:w,deleteTypeIndexRegistration:async function(t){const r=e.the(null,a.solid("instance"),t.instance,t.scope.index);if(!r)throw new Error(`deleteTypeIndexRegistration: No registration found for ${t.instance}`);const n=e.statementsMatching(r,null,null,t.scope.index);await e.updater.update(n,[])},getScopedAppsFromIndex:f}}function hn(e,n){t("SolidLogic: Unique instance created. There should only be one of these.");const o=Nr.graph();Nr.fetcher(o,{fetch:e.fetch}),o.updater=new Nr.UpdateManager(o),o.features=[];const i=new Fr(n),a=Lr(o),s=cn(o),c=function(e,n,o){async function i(t){var r,n,o,i,a;try{return await e.fetcher.load(t)}catch(s){if(404===(null===(r=null==s?void 0:s.response)||void 0===r?void 0:r.status)){try{await e.fetcher.webOperation("PUT",t.uri,{data:"",contentType:"text/turtle",headers:{"If-None-Match":"*"}})}catch(e){if(412!==(null!==(o=null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status)&&void 0!==o?o:null==e?void 0:e.status))throw new rn(`createIfNotExists: PUT FAILED: ${t}: ${e}`)}return await e.fetcher.load(t)}if(401===(null===(i=null==s?void 0:s.response)||void 0===i?void 0:i.status))throw new Yr;if(403===(null===(a=null==s?void 0:s.response)||void 0===a?void 0:a.status)){if(Vr(t))throw new Zr;throw new Qr}const c=`createIfNotExists doc load error: ${t}: ${s}`;throw new nn(null==s?void 0:s.status,`${(null==s?void 0:s.message)||""}${c}`)}}async function a(t,r){var n,o,i,a;try{return await e.fetcher.load(t),!1}catch(e){if(404!==(null!==(o=null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status)&&void 0!==o?o:null==e?void 0:e.status))throw e}try{return await e.fetcher.webOperation("PUT",t.uri,{data:r,contentType:"text/turtle",headers:{"If-None-Match":"*"}}),!0}catch(e){if(412===(null!==(a=null===(i=null==e?void 0:e.response)||void 0===i?void 0:i.status)&&void 0!==a?a:null==e?void 0:e.status))return!1;throw e}}return{recursiveDelete:async function r(i){try{if(o.isContainer(i)){const t=await n.findAclDocUrl(i);await e.fetcher._fetch(t,{method:"DELETE"});const a=await o.getContainerMembers(i);await Promise.all(a.map(e=>r(e)))}return e.fetcher._fetch(i.value,{method:"DELETE"})}catch(e){t(`Please manually remove ${i.value} from your system.`,e)}},setSinglePeerAccess:async function(t){let r=["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","","<#alice> a acl:Authorization;\n acl:agent <"+t.ownerWebId+">;",` acl:accessTo <${t.target}>;`,` acl:default <${t.target}>;`," acl:mode acl:Read, acl:Write, acl:Control.",""].join("\n");t.accessToModes&&(r+=["<#bobAccessTo> a acl:Authorization;",` acl:agent <${t.peerWebId}>;`,` acl:accessTo <${t.target}>;`,` acl:mode ${t.accessToModes}.`,""].join("\n")),t.defaultModes&&(r+=["<#bobDefault> a acl:Authorization;",` acl:agent <${t.peerWebId}>;`,` acl:default <${t.target}>;`,` acl:mode ${t.defaultModes}.`,""].join("\n"));const o=await n.findAclDocUrl((0,Nr.sym)(t.target));return e.fetcher._fetch(o,{method:"PUT",body:r,headers:[["Content-Type","text/turtle"]]})},createEmptyRdfDoc:async function(t,r){await e.fetcher.webOperation("PUT",t.uri,{data:`# ${new Date} ${r}\n`,contentType:"text/turtle"})},followOrCreateLink:async function(t,n,o,a){await e.fetcher.load(a);const s=e.any(t,n,null,a);if(s)return s;if(!e.updater.editable(a)){const e=`followOrCreateLink: cannot edit ${a.value}`;throw r(e),new tn(e)}try{await e.updater.update([],[(0,Nr.st)(t,n,o,a)])}catch(e){throw r(`followOrCreateLink: Error making link in ${a} to ${o}: ${e}`),new rn(e)}try{await i(o)}catch(e){throw r(`followOrCreateLink: Error loading or saving new linked document: ${o}: ${e}`),e}return o},followOrCreateLinkWithContentOnCreate:async function(t,n,o,i,s){await e.fetcher.load(i);const c=e.any(t,n,null,i);if(c)return c;if(!e.updater.editable(i)){const e=`followOrCreateLinkWithContentOnCreate: cannot edit ${i.value}`;throw r(e),new tn(e)}try{await e.updater.update([],[(0,Nr.st)(t,n,o,i)])}catch(e){const t=`followOrCreateLinkWithContentOnCreate: Error making link in ${i} to ${o}: ${e}`;throw r(t),new rn(t)}try{await a(o,s)}catch(e){throw r(`followOrCreateLinkWithContentOnCreate: Error loading or saving new linked document: ${o}: ${e}`),e}return o},loadOrCreateIfNotExists:i,loadOrCreateWithContentOnCreate:a}}(o,a,s),d=dn(o,i,c),l=qr(o,d),h=zr(o,d,c,s),u=ln(o,i,d,c);return t("SolidAuthnLogic initialized"),{store:o,authn:i,acl:a,inbox:h,chat:l,profile:d,typeIndex:u,load:function(e){return o.fetcher.load(e)},updatePromise:function(e,t=[]){return new Promise((r,n)=>{o.updater.update(e,t,function(e,t,o){t?r():n(new Error(o))})})},clearStore:function(){o.statements.slice().forEach(o.remove.bind(o))}}}const un=async(e,t)=>{var r;const n=t&&t.credentials&&"omit"==t.credentials,o=$r;if(((null===(r=null==o?void 0:o.info)||void 0===r?void 0:r.webId)||(null==o?void 0:o.webId))&&!n){const r="function"==typeof o.fetch?o.fetch.bind(o):"function"==typeof o.authFetch?o.authFetch.bind(o):null;return r?r(e,t):window.fetch(e,t)}return window.fetch(e,t)},pn=Symbol.for("solid-logic-singleton"),wn="undefined"!=typeof window?window:n.g;const fn=(wn[pn]?t("SolidLogic: Using existing global singleton instance."):(t("SolidLogic: Creating new global singleton instance."),wn[pn]=hn({fetch:un},$r),t("Unique quadstore initialized.")),wn[pn]);async function yn(e={}){if("undefined"==typeof window)return!1;const t=e.issuer||"",r=e.postLogoutRedirectPath||"/";try{if(t){const e=new URL(t);e.pathname="/.well-known/openid-configuration";const r=await fetch(e.toString(),{credentials:"include"});if(200===r.status){const e=await r.json();e&&e.end_session_endpoint&&await fetch(e.end_session_endpoint,{credentials:"include"})}}}catch(e){}try{const e=await fetch("/.well-known/solid/logout",{credentials:"include"});if(e.ok||e.redirected)return window.location.assign(r),!0}catch(e){}return!1}const mn=[{name:"Solid Community",uri:"https://solidcommunity.net"},{name:"Solid Web",uri:"https://solidweb.org"},{name:"Solid Web ME",uri:"https://solidweb.me"},{name:"Inrupt.com",uri:"https://login.inrupt.com"}];function gn(){const e=[...mn],{host:t,origin:r}=new URL(location.href);return e.map(({uri:e})=>new URL(e).host).includes(t)||e.unshift({name:t,uri:r}),e}const vn=fn.authn,bn=fn.authn.authSession,En=fn.store})(),o})());
2
2
  //# sourceMappingURL=solid-logic.min.js.map