diff --git a/release/remotestorage.js b/release/remotestorage.js index 72b84052f..d36e8af4b 100644 --- a/release/remotestorage.js +++ b/release/remotestorage.js @@ -1,3 +1,3 @@ /*! For license information please see remotestorage.js.LICENSE.txt */ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("RemoteStorage",[],t):"object"==typeof exports?exports.RemoteStorage=t():e.RemoteStorage=t()}(this,(function(){return function(){var e={608:function(e,t,r){var{Buffer:n}=r(8287),i={},o=i.LEFT_BRACE=1,s=i.RIGHT_BRACE=2,a=i.LEFT_BRACKET=3,c=i.RIGHT_BRACKET=4,l=i.COLON=5,u=i.COMMA=6,d=i.TRUE=7,h=i.FALSE=8,f=i.NULL=9,p=i.STRING=10,g=i.NUMBER=11,y=i.START=17,m=i.STOP=18,v=i.TRUE1=33,b=i.TRUE2=34,w=i.TRUE3=35,_=i.FALSE1=49,S=i.FALSE2=50,E=i.FALSE3=51,A=i.FALSE4=52,R=i.NULL1=65,I=i.NULL2=66,T=i.NULL3=67,x=i.NUMBER1=81,P=i.NUMBER3=83,C=i.STRING1=97,k=i.STRING2=98,O=i.STRING3=99,F=i.STRING4=100,N=i.STRING5=101,D=i.STRING6=102,L=i.VALUE=113,U=i.KEY=114,j=i.OBJECT=129,M=i.ARRAY=130,B="\\".charCodeAt(0),H="/".charCodeAt(0),W="\b".charCodeAt(0),$="\f".charCodeAt(0),V="\n".charCodeAt(0),K="\r".charCodeAt(0),J="\t".charCodeAt(0),G=65536;function q(e){return n.alloc?n.alloc(e):new n(e)}function z(){this.tState=y,this.value=void 0,this.string=void 0,this.stringBuffer=q(G),this.stringBufferOffset=0,this.unicode=void 0,this.highSurrogate=void 0,this.key=void 0,this.mode=void 0,this.stack=[],this.state=L,this.bytes_remaining=0,this.bytes_in_sequence=0,this.temp_buffs={2:q(2),3:q(3),4:q(4)},this.offset=-1}z.toknam=function(e){for(var t=Object.keys(i),r=0,n=t.length;r=G&&(this.string+=this.stringBuffer.toString("utf8"),this.stringBufferOffset=0),this.stringBuffer[this.stringBufferOffset++]=e},Y.appendStringBuf=function(e,t,r){var n=e.length;"number"==typeof t&&(n="number"==typeof r?r<0?e.length-t+r:r-t:e.length-t),n<0&&(n=0),this.stringBufferOffset+n>G&&(this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0),e.copy(this.stringBuffer,this.stringBufferOffset,t,r),this.stringBufferOffset+=n},Y.write=function(e){var t;"string"==typeof e&&(e=new n(e));for(var r=0,i=e.length;r=48&&t<64)this.string=String.fromCharCode(t),this.tState=P;else if(32!==t&&9!==t&&10!==t&&13!==t)return this.charError(e,r)}else if(this.tState===C)if(t=e[r],this.bytes_remaining>0){for(var g=0;g=128){if(t<=193||t>244)return this.onError(new Error("Invalid UTF-8 character at position "+r+" in state "+z.toknam(this.tState)));if(t>=194&&t<=223&&(this.bytes_in_sequence=2),t>=224&&t<=239&&(this.bytes_in_sequence=3),t>=240&&t<=244&&(this.bytes_in_sequence=4),this.bytes_in_sequence+r>e.length){for(var m=0;m<=e.length-1-r;m++)this.temp_buffs[this.bytes_in_sequence][m]=e[r+m];this.bytes_remaining=r+this.bytes_in_sequence-e.length,r=e.length-1}else this.appendStringBuf(e,r,r+this.bytes_in_sequence),r=r+this.bytes_in_sequence-1}else if(34===t)this.tState=y,this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0,this.onToken(p,this.string),this.offset+=n.byteLength(this.string,"utf8")+1,this.string=void 0;else if(92===t)this.tState=k;else{if(!(t>=32))return this.charError(e,r);this.appendStringChar(t)}else if(this.tState===k)if(34===(t=e[r]))this.appendStringChar(t),this.tState=C;else if(92===t)this.appendStringChar(B),this.tState=C;else if(47===t)this.appendStringChar(H),this.tState=C;else if(98===t)this.appendStringChar(W),this.tState=C;else if(102===t)this.appendStringChar($),this.tState=C;else if(110===t)this.appendStringChar(V),this.tState=C;else if(114===t)this.appendStringChar(K),this.tState=C;else if(116===t)this.appendStringChar(J),this.tState=C;else{if(117!==t)return this.charError(e,r);this.unicode="",this.tState=O}else if(this.tState===O||this.tState===F||this.tState===N||this.tState===D){if(!((t=e[r])>=48&&t<64||t>64&&t<=70||t>96&&t<=102))return this.charError(e,r);if(this.unicode+=String.fromCharCode(t),this.tState++===D){var L=parseInt(this.unicode,16);this.unicode=void 0,void 0!==this.highSurrogate&&L>=56320&&L<57344?(this.appendStringBuf(new n(String.fromCharCode(this.highSurrogate,L))),this.highSurrogate=void 0):void 0===this.highSurrogate&&L>=55296&&L<56320?this.highSurrogate=L:(void 0!==this.highSurrogate&&(this.appendStringBuf(new n(String.fromCharCode(this.highSurrogate))),this.highSurrogate=void 0),this.appendStringBuf(new n(String.fromCharCode(L)))),this.tState=C}}else if(this.tState===x||this.tState===P)switch(t=e[r]){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 46:case 101:case 69:case 43:case 45:this.string+=String.fromCharCode(t),this.tState=P;break;default:this.tState=y;var U=this.numberReviver(this.string,e,r);if(U)return U;this.offset+=this.string.length-1,this.string=void 0,r--}else if(this.tState===v){if(114!==e[r])return this.charError(e,r);this.tState=b}else if(this.tState===b){if(117!==e[r])return this.charError(e,r);this.tState=w}else if(this.tState===w){if(101!==e[r])return this.charError(e,r);this.tState=y,this.onToken(d,!0),this.offset+=3}else if(this.tState===_){if(97!==e[r])return this.charError(e,r);this.tState=S}else if(this.tState===S){if(108!==e[r])return this.charError(e,r);this.tState=E}else if(this.tState===E){if(115!==e[r])return this.charError(e,r);this.tState=A}else if(this.tState===A){if(101!==e[r])return this.charError(e,r);this.tState=y,this.onToken(h,!1),this.offset+=4}else if(this.tState===R){if(117!==e[r])return this.charError(e,r);this.tState=I}else if(this.tState===I){if(108!==e[r])return this.charError(e,r);this.tState=T}else if(this.tState===T){if(108!==e[r])return this.charError(e,r);this.tState=y,this.onToken(f,null),this.offset+=3}},Y.onToken=function(e,t){},Y.parseError=function(e,t){this.tState=m,this.onError(new Error("Unexpected "+z.toknam(e)+(t?"("+JSON.stringify(t)+")":"")+" in state "+z.toknam(this.state)))},Y.push=function(){this.stack.push({value:this.value,key:this.key,mode:this.mode})},Y.pop=function(){var e=this.value,t=this.stack.pop();this.value=t.value,this.key=t.key,this.mode=t.mode,this.emit(e),this.mode||(this.state=L)},Y.emit=function(e){this.mode&&(this.state=u),this.onValue(e)},Y.onValue=function(e){},Y.onToken=function(e,t){if(this.state===L)if(e===p||e===g||e===d||e===h||e===f)this.value&&(this.value[this.key]=t),this.emit(t);else if(e===o)this.push(),this.value?this.value=this.value[this.key]={}:this.value={},this.key=void 0,this.state=U,this.mode=j;else if(e===a)this.push(),this.value?this.value=this.value[this.key]=[]:this.value=[],this.key=0,this.mode=M,this.state=L;else if(e===s){if(this.mode!==j)return this.parseError(e,t);this.pop()}else{if(e!==c)return this.parseError(e,t);if(this.mode!==M)return this.parseError(e,t);this.pop()}else if(this.state===U)if(e===p)this.key=t,this.state=l;else{if(e!==s)return this.parseError(e,t);this.pop()}else if(this.state===l){if(e!==l)return this.parseError(e,t);this.state=L}else{if(this.state!==u)return this.parseError(e,t);if(e===u)this.mode===M?(this.key++,this.state=L):this.mode===j&&(this.state=U);else{if(!(e===c&&this.mode===M||e===s&&this.mode===j))return this.parseError(e,t);this.pop()}}},Y.numberReviver=function(e,t,r){var n=Number(e);if(isNaN(n))return this.charError(t,r);e.match(/[0-9]+/)==e&&n.toString()!=e?this.onToken(p,e):this.onToken(g,n)},z.C=i,e.exports=z},2741:function(e,t,r){"use strict";r.r(t),r.d(t,{CordovaIFrameNavigator:function(){return n.CordovaIFrameNavigator},CordovaPopupNavigator:function(){return n.CordovaPopupNavigator},InMemoryWebStorage:function(){return n.InMemoryWebStorage},Log:function(){return n.Log},OidcClient:function(){return n.OidcClient},SessionMonitor:function(){return n.SessionMonitor},User:function(){return n.User},UserManager:function(){return n.UserManager},Version:function(){return n.Version},WebStorageStateStore:function(){return n.WebStorageStateStore},clearOidcPersistentStorage:function(){return N},getBearerToken:function(){return P},getDpopToken:function(){return C},normalizeCallbackUrl:function(){return F},refresh:function(){return O},registerClient:function(){return I}});var n=r(6516);r(7007),globalThis.fetch;const{fetch:i,Response:o,Request:s,Headers:a}=globalThis;var c=r(9380),l=r(8136),u=r(7248),d=r(7307),h=r(5130),f={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let p;const g=new Uint8Array(16);function y(){if(!p&&(p="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!p))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return p(g)}const m=[];for(let e=0;e<256;++e)m.push((e+256).toString(16).slice(1));var v=function(e,t,r){if(f.randomUUID&&!t&&!e)return f.randomUUID();const n=(e=e||{}).random||(e.rng||y)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=n[e];return t}return function(e,t=0){return m[e[t+0]]+m[e[t+1]]+m[e[t+2]]+m[e[t+3]]+"-"+m[e[t+4]]+m[e[t+5]]+"-"+m[e[t+6]]+m[e[t+7]]+"-"+m[e[t+8]]+m[e[t+9]]+"-"+m[e[t+10]]+m[e[t+11]]+m[e[t+12]]+m[e[t+13]]+m[e[t+14]]+m[e[t+15]]}(n)};const b=["ES256","RS256"],w=["openid","offline_access","webid"].join(" ");async function _(e,t,r,n){const o=await async function(e,t){const r=await i.call(globalThis,e);if(200!==r.status)throw new Error(`Could not fetch JWKS for [${t}] at [${e}]: ${r.status} ${r.statusText}`);let n;try{n=(await r.json()).keys[0]}catch(r){throw new Error(`Malformed JWKS for [${t}] at [${e}]: ${r.message}`)}return n}(t,r);let s;try{const{payload:t}=await(0,c.V)(e,await(0,l.Og)(o),{issuer:r,audience:n});s=t}catch(e){throw new Error(`Token verification failed: ${e.stack}`)}if("string"==typeof s.webid)return s.webid;if("string"!=typeof s.sub)throw new Error(`The token ${JSON.stringify(s)} is invalid: it has no 'webid' claim and no 'sub' claim.`);try{return new URL(s.sub),s.sub}catch(e){throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${s.sub}] is invalid as a URL - error [${e}].`)}}Error,Error;class S extends Error{constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class E extends Error{constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function A(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function R(e,t,r){return new u.P({htu:A(e),htm:t.toUpperCase(),jti:v()}).setProtectedHeader({alg:b[0],jwk:r.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(r.privateKey,{})}async function I(e,t){var r;if(!t.registrationEndpoint)throw new Error("Dynamic Registration could not be completed because the issuer has no registration endpoint.");if(!Array.isArray(t.idTokenSigningAlgValuesSupported))throw new Error("The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.");const n=function(e,t){var r;return null!==(r=t.find((t=>e.includes(t))))&&void 0!==r?r:null}(t.idTokenSigningAlgValuesSupported,b),i={client_name:e.clientName,application_type:"web",redirect_uris:[null===(r=e.redirectUrl)||void 0===r?void 0:r.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:n,grant_types:["authorization_code","refresh_token"]},o=await fetch(t.registrationEndpoint.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(o.ok){const t=await o.json();return function(e,t){if(void 0===e.client_id)throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(e)}`);if(t.redirectUrl&&(void 0===e.redirect_uris||e.redirect_uris[0]!==t.redirectUrl.toString()))throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(e.redirect_uris)} don't match the provided ${JSON.stringify([t.redirectUrl.toString()])}`)}(t,e),{clientId:t.client_id,clientSecret:t.client_secret,idTokenSignedResponseAlg:t.id_token_signed_response_alg,clientType:"dynamic"}}throw 400===o.status&&function(e,t){var r,n,i,o;if("invalid_redirect_uri"===e.error)throw new Error(`Dynamic client registration failed: the provided redirect uri [${null===(r=t.redirectUrl)||void 0===r?void 0:r.toString()}] is invalid - ${null!==(n=e.error_description)&&void 0!==n?n:""}`);if("invalid_client_metadata"===e.error)throw new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(t)} is invalid - ${null!==(i=e.error_description)&&void 0!==i?i:""}`);throw new Error(`Dynamic client registration failed: ${e.error} - ${null!==(o=e.error_description)&&void 0!==o?o:""}`)}(await o.json(),e),new Error(`Dynamic client registration failed: the server returned ${o.status} ${o.statusText} - ${await o.text()}`)}function T(e){return void 0!==e.error_description&&"string"==typeof e.error_description}function x(e,t){if(void 0!==(r=e).error&&"string"==typeof r.error)throw new E(`Token endpoint returned error [${e.error}]${T(e)?`: ${e.error_description}`:""}${function(e){return void 0!==e.error_uri&&"string"==typeof e.error_uri}(e)?` (see ${e.error_uri})`:""}`,e.error,T(e)?e.error_description:void 0);var r;if(!function(e){return void 0!==e.access_token&&"string"==typeof e.access_token}(e))throw new S(["access_token"]);if(!function(e){return void 0!==e.id_token&&"string"==typeof e.id_token}(e))throw new S(["id_token"]);if(!function(e){return void 0!==e.token_type&&"string"==typeof e.token_type}(e))throw new S(["token_type"]);if(!function(e){return void 0===e.expires_in||"number"==typeof e.expires_in}(e))throw new S(["expires_in"]);if(!t&&"bearer"!==e.token_type.toLowerCase())throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${e.token_type}].`);return e}async function P(e){let t;try{const r=new n.OidcClient({response_mode:"query",loadUserInfo:!1});if(t=await r.processSigninResponse(e),void 0===r.settings.metadata)throw new Error("Cannot retrieve issuer metadata from client information in storage.");if(void 0===r.settings.metadata.jwks_uri)throw new Error("Missing some issuer metadata from client information in storage: 'jwks_uri' is undefined");if(void 0===r.settings.metadata.issuer)throw new Error("Missing some issuer metadata from client information in storage: 'issuer' is undefined");if(void 0===r.settings.client_id)throw new Error("Missing some client information in storage: 'client_id' is undefined");const i=await _(t.id_token,r.settings.metadata.jwks_uri,r.settings.metadata.issuer,r.settings.client_id);return{accessToken:t.access_token,idToken:t.id_token,webId:i,refreshToken:t.refresh_token}}catch(t){throw new Error(`Problem handling Auth Code Grant (Flow) redirect - URL [${e}]: ${t}`)}}async function C(e,t,r){return async function(e,t,r,n){!function(e,t){if(t.grantType&&(!e.grantTypesSupported||!e.grantTypesSupported.includes(t.grantType)))throw new Error(`The issuer [${e.issuer}] does not support the [${t.grantType}] grant`);if(!e.tokenEndpoint)throw new Error(`This issuer [${e.issuer}] does not have a token endpoint`)}(e,r);const o={"content-type":"application/x-www-form-urlencoded"};let s;n&&(s=await async function(){const{privateKey:e,publicKey:t}=await(0,d.T)(b[0]),r={privateKey:e,publicKey:await(0,h.JU)(t)};return[r.publicKey.alg]=b,r}(),o.DPoP=await R(e.tokenEndpoint,"POST",s)),t.clientSecret&&(o.Authorization=`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`);const a={grant_type:r.grantType,redirect_uri:r.redirectUrl,code:r.code,code_verifier:r.codeVerifier,client_id:t.clientId},c={method:"POST",headers:o,body:new URLSearchParams(a).toString()},l=await i(e.tokenEndpoint,c),u=x(await l.json(),n),f=await _(u.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:u.access_token,idToken:u.id_token,refreshToken:(p=u,void 0!==p.refresh_token&&"string"==typeof p.refresh_token?u.refresh_token:void 0),webId:f,dpopKey:s,expiresIn:u.expires_in};var p}(e,t,r,!0)}const k=e=>{try{return new URL(e),!0}catch(e){return!1}};async function O(e,t,r,n){if(void 0===r.clientId)throw new Error("No client ID available when trying to refresh the access token.");const o={grant_type:"refresh_token",refresh_token:e,scope:w};let s={};void 0!==n&&(s={DPoP:await R(t.tokenEndpoint,"POST",n)});let a={};void 0!==r.clientSecret?a={Authorization:`Basic ${btoa(`${r.clientId}:${r.clientSecret}`)}`}:k(r.clientId)&&(o.client_id=r.clientId);const c=await i(t.tokenEndpoint,{method:"POST",body:new URLSearchParams(o).toString(),headers:{...s,...a,"Content-Type":"application/x-www-form-urlencoded"}});let l;try{l=await c.json()}catch(e){throw new Error(`The token endpoint of issuer ${t.issuer} returned a malformed response.`)}const u=x(l,void 0!==n),d=await _(u.id_token,t.jwksUri,t.issuer,r.clientId);return{accessToken:u.access_token,idToken:u.id_token,refreshToken:"string"==typeof u.refresh_token?u.refresh_token:void 0,webId:d,dpopKey:n,expiresIn:u.expires_in}}function F(e){const t=function(e){const t=new URL(e);return t.searchParams.delete("state"),t.searchParams.delete("code"),t.searchParams.delete("error"),t.searchParams.delete("error_description"),t.searchParams.delete("iss"),t}(e);return t.hash="",e.includes(`${t.origin}/`)?t.href:`${t.origin}${t.href.substring(t.origin.length+1)}`}async function N(){const e=new n.OidcClient({response_mode:"query"});await e.clearStaleState(new n.WebStorageStateStore({}));const t=window.localStorage,r=[];for(let e=0;e<=t.length;e+=1){const n=t.key(e);n&&(n.match(/^oidc\..+$/)||n.match(/^solidClientAuthenticationUser:.+$/))&&r.push(n)}r.forEach((e=>t.removeItem(e)))}},6516:function(e){var t;t=function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=22)}([function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r=4){for(var e=arguments.length,t=Array(e),r=0;r=3){for(var e=arguments.length,t=Array(e),r=0;r=2){for(var e=arguments.length,t=Array(e),r=0;r=1){for(var e=arguments.length,t=Array(e),r=0;r1&&void 0!==arguments[1]?arguments[1]:o.JsonService;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw i.Log.error("MetadataService: No settings passed to MetadataService"),new Error("settings");this._settings=t,this._jsonService=new r(["application/jwk-set+json"])}return e.prototype.resetSigningKeys=function(){this._settings=this._settings||{},this._settings.signingKeys=void 0},e.prototype.getMetadata=function(){var e=this;return this._settings.metadata?(i.Log.debug("MetadataService.getMetadata: Returning metadata from settings"),Promise.resolve(this._settings.metadata)):this.metadataUrl?(i.Log.debug("MetadataService.getMetadata: getting metadata from",this.metadataUrl),this._jsonService.getJson(this.metadataUrl).then((function(t){i.Log.debug("MetadataService.getMetadata: json received");var r=e._settings.metadataSeed||{};return e._settings.metadata=Object.assign({},r,t),e._settings.metadata}))):(i.Log.error("MetadataService.getMetadata: No authority or metadataUrl configured on settings"),Promise.reject(new Error("No authority or metadataUrl configured on settings")))},e.prototype.getIssuer=function(){return this._getMetadataProperty("issuer")},e.prototype.getAuthorizationEndpoint=function(){return this._getMetadataProperty("authorization_endpoint")},e.prototype.getUserInfoEndpoint=function(){return this._getMetadataProperty("userinfo_endpoint")},e.prototype.getTokenEndpoint=function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._getMetadataProperty("token_endpoint",e)},e.prototype.getCheckSessionIframe=function(){return this._getMetadataProperty("check_session_iframe",!0)},e.prototype.getEndSessionEndpoint=function(){return this._getMetadataProperty("end_session_endpoint",!0)},e.prototype.getRevocationEndpoint=function(){return this._getMetadataProperty("revocation_endpoint",!0)},e.prototype.getKeysEndpoint=function(){return this._getMetadataProperty("jwks_uri",!0)},e.prototype._getMetadataProperty=function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return i.Log.debug("MetadataService.getMetadataProperty for: "+e),this.getMetadata().then((function(r){if(i.Log.debug("MetadataService.getMetadataProperty: metadata recieved"),void 0===r[e]){if(!0===t)return void i.Log.warn("MetadataService.getMetadataProperty: Metadata does not contain optional property "+e);throw i.Log.error("MetadataService.getMetadataProperty: Metadata does not contain property "+e),new Error("Metadata does not contain property "+e)}return r[e]}))},e.prototype.getSigningKeys=function(){var e=this;return this._settings.signingKeys?(i.Log.debug("MetadataService.getSigningKeys: Returning signingKeys from settings"),Promise.resolve(this._settings.signingKeys)):this._getMetadataProperty("jwks_uri").then((function(t){return i.Log.debug("MetadataService.getSigningKeys: jwks_uri received",t),e._jsonService.getJson(t).then((function(t){if(i.Log.debug("MetadataService.getSigningKeys: key set received",t),!t.keys)throw i.Log.error("MetadataService.getSigningKeys: Missing keys on keyset"),new Error("Missing keys on keyset");return e._settings.signingKeys=t.keys,e._settings.signingKeys}))}))},n(e,[{key:"metadataUrl",get:function(){return this._metadataUrl||(this._settings.metadataUrl?this._metadataUrl=this._settings.metadataUrl:(this._metadataUrl=this._settings.authority,this._metadataUrl&&this._metadataUrl.indexOf(s)<0&&("/"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+="/"),this._metadataUrl+=s))),this._metadataUrl}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UrlUtility=void 0;var n=r(0),i=r(1);t.UrlUtility=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.addQueryParam=function(e,t,r){return e.indexOf("?")<0&&(e+="?"),"?"!==e[e.length-1]&&(e+="&"),e+=encodeURIComponent(t),(e+="=")+encodeURIComponent(r)},e.parseUrlFragment=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"#",r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.Global;"string"!=typeof e&&(e=r.location.href);var o=e.lastIndexOf(t);o>=0&&(e=e.substr(o+1)),"?"===t&&(o=e.indexOf("#"))>=0&&(e=e.substr(0,o));for(var s,a={},c=/([^&=]+)=([^&]*)/g,l=0;s=c.exec(e);)if(a[decodeURIComponent(s[1])]=decodeURIComponent(s[2].replace(/\+/g," ")),l++>50)return n.Log.error("UrlUtility.parseUrlFragment: response exceeded expected number of parameters",e),{error:"Response exceeded expected number of parameters"};for(var u in a)return a;return{}},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JoseUtil=void 0;var n=r(26),i=function(e){return e&&e.__esModule?e:{default:e}}(r(33));t.JoseUtil=(0,i.default)({jws:n.jws,KeyUtil:n.KeyUtil,X509:n.X509,crypto:n.crypto,hextob64u:n.hextob64u,b64tohex:n.b64tohex,AllowedSigningAlgs:n.AllowedSigningAlgs})},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OidcClientSettings=void 0;var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},r=t.authority,i=t.metadataUrl,o=t.metadata,u=t.signingKeys,d=t.metadataSeed,h=t.client_id,f=t.client_secret,p=t.response_type,g=void 0===p?"id_token":p,y=t.scope,m=void 0===y?"openid":y,v=t.redirect_uri,b=t.post_logout_redirect_uri,w=t.client_authentication,_=void 0===w?"client_secret_post":w,S=t.prompt,E=t.display,A=t.max_age,R=t.ui_locales,I=t.acr_values,T=t.resource,x=t.response_mode,P=t.filterProtocolClaims,C=void 0===P||P,k=t.loadUserInfo,O=void 0===k||k,F=t.staleStateAge,N=void 0===F?900:F,D=t.clockSkew,L=void 0===D?300:D,U=t.clockService,j=void 0===U?new s.ClockService:U,M=t.userInfoJwtIssuer,B=void 0===M?"OP":M,H=t.mergeClaims,W=void 0!==H&&H,$=t.stateStore,V=void 0===$?new a.WebStorageStateStore:$,K=t.ResponseValidatorCtor,J=void 0===K?c.ResponseValidator:K,G=t.MetadataServiceCtor,q=void 0===G?l.MetadataService:G,z=t.extraQueryParams,Y=void 0===z?{}:z,Q=t.extraTokenParams,X=void 0===Q?{}:Q;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._authority=r,this._metadataUrl=i,this._metadata=o,this._metadataSeed=d,this._signingKeys=u,this._client_id=h,this._client_secret=f,this._response_type=g,this._scope=m,this._redirect_uri=v,this._post_logout_redirect_uri=b,this._client_authentication=_,this._prompt=S,this._display=E,this._max_age=A,this._ui_locales=R,this._acr_values=I,this._resource=T,this._response_mode=x,this._filterProtocolClaims=!!C,this._loadUserInfo=!!O,this._staleStateAge=N,this._clockSkew=L,this._clockService=j,this._userInfoJwtIssuer=B,this._mergeClaims=!!W,this._stateStore=V,this._validator=new J(this),this._metadataService=new q(this),this._extraQueryParams="object"===(void 0===Y?"undefined":n(Y))?Y:{},this._extraTokenParams="object"===(void 0===X?"undefined":n(X))?X:{}}return e.prototype.getEpochTime=function(){return this._clockService.getEpochTime()},i(e,[{key:"client_id",get:function(){return this._client_id},set:function(e){if(this._client_id)throw o.Log.error("OidcClientSettings.set_client_id: client_id has already been assigned."),new Error("client_id has already been assigned.");this._client_id=e}},{key:"client_secret",get:function(){return this._client_secret}},{key:"response_type",get:function(){return this._response_type}},{key:"scope",get:function(){return this._scope}},{key:"redirect_uri",get:function(){return this._redirect_uri}},{key:"post_logout_redirect_uri",get:function(){return this._post_logout_redirect_uri}},{key:"client_authentication",get:function(){return this._client_authentication}},{key:"prompt",get:function(){return this._prompt}},{key:"display",get:function(){return this._display}},{key:"max_age",get:function(){return this._max_age}},{key:"ui_locales",get:function(){return this._ui_locales}},{key:"acr_values",get:function(){return this._acr_values}},{key:"resource",get:function(){return this._resource}},{key:"response_mode",get:function(){return this._response_mode}},{key:"authority",get:function(){return this._authority},set:function(e){if(this._authority)throw o.Log.error("OidcClientSettings.set_authority: authority has already been assigned."),new Error("authority has already been assigned.");this._authority=e}},{key:"metadataUrl",get:function(){return this._metadataUrl||(this._metadataUrl=this.authority,this._metadataUrl&&this._metadataUrl.indexOf(u)<0&&("/"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+="/"),this._metadataUrl+=u)),this._metadataUrl}},{key:"metadata",get:function(){return this._metadata},set:function(e){this._metadata=e}},{key:"metadataSeed",get:function(){return this._metadataSeed},set:function(e){this._metadataSeed=e}},{key:"signingKeys",get:function(){return this._signingKeys},set:function(e){this._signingKeys=e}},{key:"filterProtocolClaims",get:function(){return this._filterProtocolClaims}},{key:"loadUserInfo",get:function(){return this._loadUserInfo}},{key:"staleStateAge",get:function(){return this._staleStateAge}},{key:"clockSkew",get:function(){return this._clockSkew}},{key:"userInfoJwtIssuer",get:function(){return this._userInfoJwtIssuer}},{key:"mergeClaims",get:function(){return this._mergeClaims}},{key:"stateStore",get:function(){return this._stateStore}},{key:"validator",get:function(){return this._validator}},{key:"metadataService",get:function(){return this._metadataService}},{key:"extraQueryParams",get:function(){return this._extraQueryParams},set:function(e){"object"===(void 0===e?"undefined":n(e))?this._extraQueryParams=e:this._extraQueryParams={}}},{key:"extraTokenParams",get:function(){return this._extraTokenParams},set:function(e){"object"===(void 0===e?"undefined":n(e))?this._extraTokenParams=e:this._extraTokenParams={}}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebStorageStateStore=void 0;var n=r(0),i=r(1);t.WebStorageStateStore=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.prefix,n=void 0===r?"oidc.":r,o=t.store,s=void 0===o?i.Global.localStorage:o;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._store=s,this._prefix=n}return e.prototype.set=function(e,t){return n.Log.debug("WebStorageStateStore.set",e),e=this._prefix+e,this._store.setItem(e,t),Promise.resolve()},e.prototype.get=function(e){n.Log.debug("WebStorageStateStore.get",e),e=this._prefix+e;var t=this._store.getItem(e);return Promise.resolve(t)},e.prototype.remove=function(e){n.Log.debug("WebStorageStateStore.remove",e),e=this._prefix+e;var t=this._store.getItem(e);return this._store.removeItem(e),Promise.resolve(t)},e.prototype.getAllKeys=function(){n.Log.debug("WebStorageStateStore.getAllKeys");for(var e=[],t=0;t0&&void 0!==arguments[0]?arguments[0]:null,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i.Global.XMLHttpRequest,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),t&&Array.isArray(t)?this._contentTypes=t.slice():this._contentTypes=[],this._contentTypes.push("application/json"),n&&this._contentTypes.push("application/jwt"),this._XMLHttpRequest=r,this._jwtHandler=n}return e.prototype.getJson=function(e,t){var r=this;if(!e)throw n.Log.error("JsonService.getJson: No url passed"),new Error("url");return n.Log.debug("JsonService.getJson, url: ",e),new Promise((function(i,o){var s=new r._XMLHttpRequest;s.open("GET",e);var a=r._contentTypes,c=r._jwtHandler;s.onload=function(){if(n.Log.debug("JsonService.getJson: HTTP response received, status",s.status),200===s.status){var t=s.getResponseHeader("Content-Type");if(t){var r=a.find((function(e){if(t.startsWith(e))return!0}));if("application/jwt"==r)return void c(s).then(i,o);if(r)try{return void i(JSON.parse(s.responseText))}catch(e){return n.Log.error("JsonService.getJson: Error parsing JSON response",e.message),void o(e)}}o(Error("Invalid response Content-Type: "+t+", from URL: "+e))}else o(Error(s.statusText+" ("+s.status+")"))},s.onerror=function(){n.Log.error("JsonService.getJson: network error"),o(Error("Network Error"))},t&&(n.Log.debug("JsonService.getJson: token passed, setting Authorization header"),s.setRequestHeader("Authorization","Bearer "+t)),s.send()}))},e.prototype.postForm=function(e,t,r){var i=this;if(!e)throw n.Log.error("JsonService.postForm: No url passed"),new Error("url");return n.Log.debug("JsonService.postForm, url: ",e),new Promise((function(o,s){var a=new i._XMLHttpRequest;a.open("POST",e);var c=i._contentTypes;a.onload=function(){if(n.Log.debug("JsonService.postForm: HTTP response received, status",a.status),200!==a.status){if(400===a.status&&(r=a.getResponseHeader("Content-Type"))&&c.find((function(e){if(r.startsWith(e))return!0})))try{var t=JSON.parse(a.responseText);if(t&&t.error)return n.Log.error("JsonService.postForm: Error from server: ",t.error),void s(new Error(t.error))}catch(e){return n.Log.error("JsonService.postForm: Error parsing JSON response",e.message),void s(e)}s(Error(a.statusText+" ("+a.status+")"))}else{var r;if((r=a.getResponseHeader("Content-Type"))&&c.find((function(e){if(r.startsWith(e))return!0})))try{return void o(JSON.parse(a.responseText))}catch(e){return n.Log.error("JsonService.postForm: Error parsing JSON response",e.message),void s(e)}s(Error("Invalid response Content-Type: "+r+", from URL: "+e))}},a.onerror=function(){n.Log.error("JsonService.postForm: network error"),s(Error("Network Error"))};var l="";for(var u in t){var d=t[u];d&&(l.length>0&&(l+="&"),l+=encodeURIComponent(u),l+="=",l+=encodeURIComponent(d))}a.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),void 0!==r&&a.setRequestHeader("Authorization","Basic "+btoa(r)),a.send(l)}))},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SigninRequest=void 0;var n=r(0),i=r(3),o=r(13);t.SigninRequest=function(){function e(t){var r=t.url,s=t.client_id,a=t.redirect_uri,c=t.response_type,l=t.scope,u=t.authority,d=t.data,h=t.prompt,f=t.display,p=t.max_age,g=t.ui_locales,y=t.id_token_hint,m=t.login_hint,v=t.acr_values,b=t.resource,w=t.response_mode,_=t.request,S=t.request_uri,E=t.extraQueryParams,A=t.request_type,R=t.client_secret,I=t.extraTokenParams,T=t.skipUserInfo;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!r)throw n.Log.error("SigninRequest.ctor: No url passed"),new Error("url");if(!s)throw n.Log.error("SigninRequest.ctor: No client_id passed"),new Error("client_id");if(!a)throw n.Log.error("SigninRequest.ctor: No redirect_uri passed"),new Error("redirect_uri");if(!c)throw n.Log.error("SigninRequest.ctor: No response_type passed"),new Error("response_type");if(!l)throw n.Log.error("SigninRequest.ctor: No scope passed"),new Error("scope");if(!u)throw n.Log.error("SigninRequest.ctor: No authority passed"),new Error("authority");var x=e.isOidc(c),P=e.isCode(c);w||(w=e.isCode(c)?"query":null),this.state=new o.SigninState({nonce:x,data:d,client_id:s,authority:u,redirect_uri:a,code_verifier:P,request_type:A,response_mode:w,client_secret:R,scope:l,extraTokenParams:I,skipUserInfo:T}),r=i.UrlUtility.addQueryParam(r,"client_id",s),r=i.UrlUtility.addQueryParam(r,"redirect_uri",a),r=i.UrlUtility.addQueryParam(r,"response_type",c),r=i.UrlUtility.addQueryParam(r,"scope",l),r=i.UrlUtility.addQueryParam(r,"state",this.state.id),x&&(r=i.UrlUtility.addQueryParam(r,"nonce",this.state.nonce)),P&&(r=i.UrlUtility.addQueryParam(r,"code_challenge",this.state.code_challenge),r=i.UrlUtility.addQueryParam(r,"code_challenge_method","S256"));var C={prompt:h,display:f,max_age:p,ui_locales:g,id_token_hint:y,login_hint:m,acr_values:v,resource:b,request:_,request_uri:S,response_mode:w};for(var k in C)C[k]&&(r=i.UrlUtility.addQueryParam(r,k,C[k]));for(var O in E)r=i.UrlUtility.addQueryParam(r,O,E[O]);this.url=r}return e.isOidc=function(e){return!!e.split(/\s+/g).filter((function(e){return"id_token"===e}))[0]},e.isOAuth=function(e){return!!e.split(/\s+/g).filter((function(e){return"token"===e}))[0]},e.isCode=function(e){return!!e.split(/\s+/g).filter((function(e){return"code"===e}))[0]},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.State=void 0;var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},r=t.id,n=t.data,i=t.created,s=t.request_type;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._id=r||(0,o.default)(),this._data=n,this._created="number"==typeof i&&i>0?i:parseInt(Date.now()/1e3),this._request_type=s}return e.prototype.toStorageString=function(){return i.Log.debug("State.toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type})},e.fromStorageString=function(t){return i.Log.debug("State.fromStorageString"),new e(JSON.parse(t))},e.clearStaleState=function(t,r){var n=Date.now()/1e3-r;return t.getAllKeys().then((function(r){i.Log.debug("State.clearStaleState: got keys",r);for(var o=[],s=function(s){var a=r[s];c=t.get(a).then((function(r){var o=!1;if(r)try{var s=e.fromStorageString(r);i.Log.debug("State.clearStaleState: got item from key: ",a,s.created),s.created<=n&&(o=!0)}catch(e){i.Log.error("State.clearStaleState: Error parsing state for key",a,e.message),o=!0}else i.Log.debug("State.clearStaleState: no item in storage for key: ",a),o=!0;if(o)return i.Log.debug("State.clearStaleState: removed item for key: ",a),t.remove(a)})),o.push(c)},a=0;a0&&void 0!==arguments[0]?arguments[0]:{};(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),t instanceof o.OidcClientSettings?this._settings=t:this._settings=new o.OidcClientSettings(t)}return e.prototype.createSigninRequest=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.response_type,n=t.scope,o=t.redirect_uri,s=t.data,c=t.state,l=t.prompt,u=t.display,d=t.max_age,h=t.ui_locales,f=t.id_token_hint,p=t.login_hint,g=t.acr_values,y=t.resource,m=t.request,v=t.request_uri,b=t.response_mode,w=t.extraQueryParams,_=t.extraTokenParams,S=t.request_type,E=t.skipUserInfo,A=arguments[1];i.Log.debug("OidcClient.createSigninRequest");var R=this._settings.client_id;r=r||this._settings.response_type,n=n||this._settings.scope,o=o||this._settings.redirect_uri,l=l||this._settings.prompt,u=u||this._settings.display,d=d||this._settings.max_age,h=h||this._settings.ui_locales,g=g||this._settings.acr_values,y=y||this._settings.resource,b=b||this._settings.response_mode,w=w||this._settings.extraQueryParams,_=_||this._settings.extraTokenParams;var I=this._settings.authority;return a.SigninRequest.isCode(r)&&"code"!==r?Promise.reject(new Error("OpenID Connect hybrid flow is not supported")):this._metadataService.getAuthorizationEndpoint().then((function(t){i.Log.debug("OidcClient.createSigninRequest: Received authorization endpoint",t);var T=new a.SigninRequest({url:t,client_id:R,redirect_uri:o,response_type:r,scope:n,data:s||c,authority:I,prompt:l,display:u,max_age:d,ui_locales:h,id_token_hint:f,login_hint:p,acr_values:g,resource:y,request:m,request_uri:v,extraQueryParams:w,extraTokenParams:_,request_type:S,response_mode:b,client_secret:e._settings.client_secret,skipUserInfo:E}),x=T.state;return(A=A||e._stateStore).set(x.id,x.toStorageString()).then((function(){return T}))}))},e.prototype.readSigninResponseState=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];i.Log.debug("OidcClient.readSigninResponseState");var n="query"===this._settings.response_mode||!this._settings.response_mode&&a.SigninRequest.isCode(this._settings.response_type)?"?":"#",o=new c.SigninResponse(e,n);return o.state?(t=t||this._stateStore,(r?t.remove.bind(t):t.get.bind(t))(o.state).then((function(e){if(!e)throw i.Log.error("OidcClient.readSigninResponseState: No matching state found in storage"),new Error("No matching state found in storage");return{state:d.SigninState.fromStorageString(e),response:o}}))):(i.Log.error("OidcClient.readSigninResponseState: No state in response"),Promise.reject(new Error("No state in response")))},e.prototype.processSigninResponse=function(e,t){var r=this;return i.Log.debug("OidcClient.processSigninResponse"),this.readSigninResponseState(e,t,!0).then((function(e){var t=e.state,n=e.response;return i.Log.debug("OidcClient.processSigninResponse: Received state from storage; validating response"),r._validator.validateSigninResponse(t,n)}))},e.prototype.createSignoutRequest=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.id_token_hint,n=t.data,o=t.state,s=t.post_logout_redirect_uri,a=t.extraQueryParams,c=t.request_type,u=arguments[1];return i.Log.debug("OidcClient.createSignoutRequest"),s=s||this._settings.post_logout_redirect_uri,a=a||this._settings.extraQueryParams,this._metadataService.getEndSessionEndpoint().then((function(t){if(!t)throw i.Log.error("OidcClient.createSignoutRequest: No end session endpoint url returned"),new Error("no end session endpoint");i.Log.debug("OidcClient.createSignoutRequest: Received end session endpoint",t);var d=new l.SignoutRequest({url:t,id_token_hint:r,post_logout_redirect_uri:s,data:n||o,extraQueryParams:a,request_type:c}),h=d.state;return h&&(i.Log.debug("OidcClient.createSignoutRequest: Signout request has state to persist"),(u=u||e._stateStore).set(h.id,h.toStorageString())),d}))},e.prototype.readSignoutResponseState=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];i.Log.debug("OidcClient.readSignoutResponseState");var n=new u.SignoutResponse(e);if(!n.state)return i.Log.debug("OidcClient.readSignoutResponseState: No state in response"),n.error?(i.Log.warn("OidcClient.readSignoutResponseState: Response was error: ",n.error),Promise.reject(new s.ErrorResponse(n))):Promise.resolve({state:void 0,response:n});var o=n.state;return t=t||this._stateStore,(r?t.remove.bind(t):t.get.bind(t))(o).then((function(e){if(!e)throw i.Log.error("OidcClient.readSignoutResponseState: No matching state found in storage"),new Error("No matching state found in storage");return{state:h.State.fromStorageString(e),response:n}}))},e.prototype.processSignoutResponse=function(e,t){var r=this;return i.Log.debug("OidcClient.processSignoutResponse"),this.readSignoutResponseState(e,t,!0).then((function(e){var t=e.state,n=e.response;return t?(i.Log.debug("OidcClient.processSignoutResponse: Received state from storage; validating response"),r._validator.validateSignoutResponse(t,n)):(i.Log.debug("OidcClient.processSignoutResponse: No state from storage; skipping validating response"),n)}))},e.prototype.clearStaleState=function(e){return i.Log.debug("OidcClient.clearStaleState"),e=e||this._stateStore,h.State.clearStaleState(e,this.settings.staleStateAge)},n(e,[{key:"_stateStore",get:function(){return this.settings.stateStore}},{key:"_validator",get:function(){return this.settings.validator}},{key:"_metadataService",get:function(){return this.settings.metadataService}},{key:"settings",get:function(){return this._settings}},{key:"metadataService",get:function(){return this._metadataService}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TokenClient=void 0;var n=r(7),i=r(2),o=r(0);t.TokenClient=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.JsonService,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.MetadataService;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw o.Log.error("TokenClient.ctor: No settings passed"),new Error("settings");this._settings=t,this._jsonService=new r,this._metadataService=new s(this._settings)}return e.prototype.exchangeCode=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(t=Object.assign({},t)).grant_type=t.grant_type||"authorization_code",t.client_id=t.client_id||this._settings.client_id,t.client_secret=t.client_secret||this._settings.client_secret,t.redirect_uri=t.redirect_uri||this._settings.redirect_uri;var r=void 0,n=t._client_authentication||this._settings._client_authentication;return delete t._client_authentication,t.code?t.redirect_uri?t.code_verifier?t.client_id?t.client_secret||"client_secret_basic"!=n?("client_secret_basic"==n&&(r=t.client_id+":"+t.client_secret,delete t.client_id,delete t.client_secret),this._metadataService.getTokenEndpoint(!1).then((function(n){return o.Log.debug("TokenClient.exchangeCode: Received token endpoint"),e._jsonService.postForm(n,t,r).then((function(e){return o.Log.debug("TokenClient.exchangeCode: response received"),e}))}))):(o.Log.error("TokenClient.exchangeCode: No client_secret passed"),Promise.reject(new Error("A client_secret is required"))):(o.Log.error("TokenClient.exchangeCode: No client_id passed"),Promise.reject(new Error("A client_id is required"))):(o.Log.error("TokenClient.exchangeCode: No code_verifier passed"),Promise.reject(new Error("A code_verifier is required"))):(o.Log.error("TokenClient.exchangeCode: No redirect_uri passed"),Promise.reject(new Error("A redirect_uri is required"))):(o.Log.error("TokenClient.exchangeCode: No code passed"),Promise.reject(new Error("A code is required")))},e.prototype.exchangeRefreshToken=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(t=Object.assign({},t)).grant_type=t.grant_type||"refresh_token",t.client_id=t.client_id||this._settings.client_id,t.client_secret=t.client_secret||this._settings.client_secret;var r=void 0,n=t._client_authentication||this._settings._client_authentication;return delete t._client_authentication,t.refresh_token?t.client_id?("client_secret_basic"==n&&(r=t.client_id+":"+t.client_secret,delete t.client_id,delete t.client_secret),this._metadataService.getTokenEndpoint(!1).then((function(n){return o.Log.debug("TokenClient.exchangeRefreshToken: Received token endpoint"),e._jsonService.postForm(n,t,r).then((function(e){return o.Log.debug("TokenClient.exchangeRefreshToken: response received"),e}))}))):(o.Log.error("TokenClient.exchangeRefreshToken: No client_id passed"),Promise.reject(new Error("A client_id is required"))):(o.Log.error("TokenClient.exchangeRefreshToken: No refresh_token passed"),Promise.reject(new Error("A refresh_token is required")))},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorResponse=void 0;var n=r(0);t.ErrorResponse=function(e){function t(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=r.error,o=r.error_description,s=r.error_uri,a=r.state,c=r.session_state;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),!i)throw n.Log.error("No error passed to ErrorResponse"),new Error("error");var l=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,o||i));return l.name="ErrorResponse",l.error=i,l.error_description=o,l.error_uri=s,l.state=a,l.session_state=c,l}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t}(Error)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SigninState=void 0;var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=r.nonce,i=r.authority,o=r.client_id,c=r.redirect_uri,l=r.code_verifier,u=r.response_mode,d=r.client_secret,h=r.scope,f=r.extraTokenParams,p=r.skipUserInfo;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var g=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,arguments[0]));if(!0===n?g._nonce=(0,a.default)():n&&(g._nonce=n),!0===l?g._code_verifier=(0,a.default)()+(0,a.default)()+(0,a.default)():l&&(g._code_verifier=l),g.code_verifier){var y=s.JoseUtil.hashString(g.code_verifier,"SHA256");g._code_challenge=s.JoseUtil.hexToBase64Url(y)}return g._redirect_uri=c,g._authority=i,g._client_id=o,g._response_mode=u,g._client_secret=d,g._scope=h,g._extraTokenParams=f,g._skipUserInfo=p,g}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.toStorageString=function(){return i.Log.debug("SigninState.toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,nonce:this.nonce,code_verifier:this.code_verifier,redirect_uri:this.redirect_uri,authority:this.authority,client_id:this.client_id,response_mode:this.response_mode,client_secret:this.client_secret,scope:this.scope,extraTokenParams:this.extraTokenParams,skipUserInfo:this.skipUserInfo})},t.fromStorageString=function(e){return i.Log.debug("SigninState.fromStorageString"),new t(JSON.parse(e))},n(t,[{key:"nonce",get:function(){return this._nonce}},{key:"authority",get:function(){return this._authority}},{key:"client_id",get:function(){return this._client_id}},{key:"redirect_uri",get:function(){return this._redirect_uri}},{key:"code_verifier",get:function(){return this._code_verifier}},{key:"code_challenge",get:function(){return this._code_challenge}},{key:"response_mode",get:function(){return this._response_mode}},{key:"client_secret",get:function(){return this._client_secret}},{key:"scope",get:function(){return this._scope}},{key:"extraTokenParams",get:function(){return this._extraTokenParams}},{key:"skipUserInfo",get:function(){return this._skipUserInfo}}]),t}(o.State)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return("undefined"!=n&&null!==n&&void 0!==n.getRandomValues?i:o)().replace(/-/g,"")};var n="undefined"!=typeof window?window.crypto||window.msCrypto:null;function i(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(function(e){return(e^n.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16)}))}function o(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(function(e){return(e^16*Math.random()>>e/4).toString(16)}))}e.exports=t.default},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.User=void 0;var n=function(){function e(e,t){for(var r=0;r0){var r=parseInt(Date.now()/1e3);this.expires_at=r+t}}},{key:"expired",get:function(){var e=this.expires_in;if(void 0!==e)return e<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AccessTokenEvents=void 0;var n=r(0),i=r(46);t.AccessTokenEvents=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.accessTokenExpiringNotificationTime,n=void 0===r?60:r,o=t.accessTokenExpiringTimer,s=void 0===o?new i.Timer("Access token expiring"):o,a=t.accessTokenExpiredTimer,c=void 0===a?new i.Timer("Access token expired"):a;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._accessTokenExpiringNotificationTime=n,this._accessTokenExpiring=s,this._accessTokenExpired=c}return e.prototype.load=function(e){if(e.access_token&&void 0!==e.expires_in){var t=e.expires_in;if(n.Log.debug("AccessTokenEvents.load: access token present, remaining duration:",t),t>0){var r=t-this._accessTokenExpiringNotificationTime;r<=0&&(r=1),n.Log.debug("AccessTokenEvents.load: registering expiring timer in:",r),this._accessTokenExpiring.init(r)}else n.Log.debug("AccessTokenEvents.load: canceling existing expiring timer becase we're past expiration."),this._accessTokenExpiring.cancel();var i=t+1;n.Log.debug("AccessTokenEvents.load: registering expired timer in:",i),this._accessTokenExpired.init(i)}else this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},e.prototype.unload=function(){n.Log.debug("AccessTokenEvents.unload: canceling existing access token timers"),this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},e.prototype.addAccessTokenExpiring=function(e){this._accessTokenExpiring.addHandler(e)},e.prototype.removeAccessTokenExpiring=function(e){this._accessTokenExpiring.removeHandler(e)},e.prototype.addAccessTokenExpired=function(e){this._accessTokenExpired.addHandler(e)},e.prototype.removeAccessTokenExpired=function(e){this._accessTokenExpired.removeHandler(e)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Event=void 0;var n=r(0);t.Event=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._name=t,this._callbacks=[]}return e.prototype.addHandler=function(e){this._callbacks.push(e)},e.prototype.removeHandler=function(e){var t=this._callbacks.findIndex((function(t){return t===e}));t>=0&&this._callbacks.splice(t,1)},e.prototype.raise=function(){n.Log.debug("Event: Raising event: "+this._name);for(var e=0;e1&&void 0!==arguments[1]?arguments[1]:o.CheckSessionIFrame,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.Global.timer;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw i.Log.error("SessionMonitor.ctor: No user manager passed to SessionMonitor"),new Error("userManager");this._userManager=t,this._CheckSessionIFrameCtor=n,this._timer=a,this._userManager.events.addUserLoaded(this._start.bind(this)),this._userManager.events.addUserUnloaded(this._stop.bind(this)),Promise.resolve(this._userManager.getUser().then((function(e){e?r._start(e):r._settings.monitorAnonymousSession&&r._userManager.querySessionStatus().then((function(e){var t={session_state:e.session_state};e.sub&&e.sid&&(t.profile={sub:e.sub,sid:e.sid}),r._start(t)})).catch((function(e){i.Log.error("SessionMonitor ctor: error from querySessionStatus:",e.message)}))})).catch((function(e){i.Log.error("SessionMonitor ctor: error from getUser:",e.message)})))}return e.prototype._start=function(e){var t=this,r=e.session_state;r&&(e.profile?(this._sub=e.profile.sub,this._sid=e.profile.sid,i.Log.debug("SessionMonitor._start: session_state:",r,", sub:",this._sub)):(this._sub=void 0,this._sid=void 0,i.Log.debug("SessionMonitor._start: session_state:",r,", anonymous user")),this._checkSessionIFrame?this._checkSessionIFrame.start(r):this._metadataService.getCheckSessionIframe().then((function(e){if(e){i.Log.debug("SessionMonitor._start: Initializing check session iframe");var n=t._client_id,o=t._checkSessionInterval,s=t._stopCheckSessionOnError;t._checkSessionIFrame=new t._CheckSessionIFrameCtor(t._callback.bind(t),n,e,o,s),t._checkSessionIFrame.load().then((function(){t._checkSessionIFrame.start(r)}))}else i.Log.warn("SessionMonitor._start: No check session iframe found in the metadata")})).catch((function(e){i.Log.error("SessionMonitor._start: Error from getCheckSessionIframe:",e.message)})))},e.prototype._stop=function(){var e=this;if(this._sub=void 0,this._sid=void 0,this._checkSessionIFrame&&(i.Log.debug("SessionMonitor._stop"),this._checkSessionIFrame.stop()),this._settings.monitorAnonymousSession)var t=this._timer.setInterval((function(){e._timer.clearInterval(t),e._userManager.querySessionStatus().then((function(t){var r={session_state:t.session_state};t.sub&&t.sid&&(r.profile={sub:t.sub,sid:t.sid}),e._start(r)})).catch((function(e){i.Log.error("SessionMonitor: error from querySessionStatus:",e.message)}))}),1e3)},e.prototype._callback=function(){var e=this;this._userManager.querySessionStatus().then((function(t){var r=!0;t?t.sub===e._sub?(r=!1,e._checkSessionIFrame.start(t.session_state),t.sid===e._sid?i.Log.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",t.session_state):(i.Log.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",t.session_state),e._userManager.events._raiseUserSessionChanged())):i.Log.debug("SessionMonitor._callback: Different subject signed into OP:",t.sub):i.Log.debug("SessionMonitor._callback: Subject no longer signed into OP"),r&&(e._sub?(i.Log.debug("SessionMonitor._callback: SessionMonitor._callback; raising signed out event"),e._userManager.events._raiseUserSignedOut()):(i.Log.debug("SessionMonitor._callback: SessionMonitor._callback; raising signed in event"),e._userManager.events._raiseUserSignedIn()))})).catch((function(t){e._sub&&(i.Log.debug("SessionMonitor._callback: Error calling queryCurrentSigninSession; raising signed out event",t.message),e._userManager.events._raiseUserSignedOut())}))},n(e,[{key:"_settings",get:function(){return this._userManager.settings}},{key:"_metadataService",get:function(){return this._userManager.metadataService}},{key:"_client_id",get:function(){return this._settings.client_id}},{key:"_checkSessionInterval",get:function(){return this._settings.checkSessionInterval}},{key:"_stopCheckSessionOnError",get:function(){return this._settings.stopCheckSessionOnError}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckSessionIFrame=void 0;var n=r(0);t.CheckSessionIFrame=function(){function e(t,r,n,i){var o=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._callback=t,this._client_id=r,this._url=n,this._interval=i||2e3,this._stopOnError=o;var s=n.indexOf("/",n.indexOf("//")+2);this._frame_origin=n.substr(0,s),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.style.display="none",this._frame.width=0,this._frame.height=0,this._frame.src=n}return e.prototype.load=function(){var e=this;return new Promise((function(t){e._frame.onload=function(){t()},window.document.body.appendChild(e._frame),e._boundMessageEvent=e._message.bind(e),window.addEventListener("message",e._boundMessageEvent,!1)}))},e.prototype._message=function(e){e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(n.Log.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(n.Log.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):n.Log.debug("CheckSessionIFrame: "+e.data+" message from check session op iframe"))},e.prototype.start=function(e){var t=this;if(this._session_state!==e){n.Log.debug("CheckSessionIFrame.start"),this.stop(),this._session_state=e;var r=function(){t._frame.contentWindow.postMessage(t._client_id+" "+t._session_state,t._frame_origin)};r(),this._timer=window.setInterval(r,this._interval)}},e.prototype.stop=function(){this._session_state=null,this._timer&&(n.Log.debug("CheckSessionIFrame.stop"),window.clearInterval(this._timer),this._timer=null)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TokenRevocationClient=void 0;var n=r(0),i=r(2),o=r(1);t.TokenRevocationClient=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o.Global.XMLHttpRequest,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.MetadataService;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw n.Log.error("TokenRevocationClient.ctor: No settings provided"),new Error("No settings provided.");this._settings=t,this._XMLHttpRequestCtor=r,this._metadataService=new s(this._settings)}return e.prototype.revoke=function(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"access_token";if(!e)throw n.Log.error("TokenRevocationClient.revoke: No token provided"),new Error("No token provided.");if("access_token"!==i&&"refresh_token"!=i)throw n.Log.error("TokenRevocationClient.revoke: Invalid token type"),new Error("Invalid token type.");return this._metadataService.getRevocationEndpoint().then((function(o){if(o){n.Log.debug("TokenRevocationClient.revoke: Revoking "+i);var s=r._settings.client_id,a=r._settings.client_secret;return r._revoke(o,s,a,e,i)}if(t)throw n.Log.error("TokenRevocationClient.revoke: Revocation not supported"),new Error("Revocation not supported")}))},e.prototype._revoke=function(e,t,r,i,o){var s=this;return new Promise((function(a,c){var l=new s._XMLHttpRequestCtor;l.open("POST",e),l.onload=function(){n.Log.debug("TokenRevocationClient.revoke: HTTP response received, status",l.status),200===l.status?a():c(Error(l.statusText+" ("+l.status+")"))},l.onerror=function(){n.Log.debug("TokenRevocationClient.revoke: Network Error."),c("Network Error")};var u="client_id="+encodeURIComponent(t);r&&(u+="&client_secret="+encodeURIComponent(r)),u+="&token_type_hint="+encodeURIComponent(o),u+="&token="+encodeURIComponent(i),l.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),l.send(u)}))},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CordovaPopupWindow=void 0;var n=function(){function e(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:o.MetadataService,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.UserInfoService,c=arguments.length>3&&void 0!==arguments[3]?arguments[3]:l.JoseUtil,u=arguments.length>4&&void 0!==arguments[4]?arguments[4]:a.TokenClient;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw i.Log.error("ResponseValidator.ctor: No settings passed to ResponseValidator"),new Error("settings");this._settings=t,this._metadataService=new r(this._settings),this._userInfoService=new n(this._settings),this._joseUtil=c,this._tokenClient=new u(this._settings)}return e.prototype.validateSigninResponse=function(e,t){var r=this;return i.Log.debug("ResponseValidator.validateSigninResponse"),this._processSigninParams(e,t).then((function(t){return i.Log.debug("ResponseValidator.validateSigninResponse: state processed"),r._validateTokens(e,t).then((function(t){return i.Log.debug("ResponseValidator.validateSigninResponse: tokens validated"),r._processClaims(e,t).then((function(e){return i.Log.debug("ResponseValidator.validateSigninResponse: claims processed"),e}))}))}))},e.prototype.validateSignoutResponse=function(e,t){return e.id!==t.state?(i.Log.error("ResponseValidator.validateSignoutResponse: State does not match"),Promise.reject(new Error("State does not match"))):(i.Log.debug("ResponseValidator.validateSignoutResponse: state validated"),t.state=e.data,t.error?(i.Log.warn("ResponseValidator.validateSignoutResponse: Response was error",t.error),Promise.reject(new c.ErrorResponse(t))):Promise.resolve(t))},e.prototype._processSigninParams=function(e,t){if(e.id!==t.state)return i.Log.error("ResponseValidator._processSigninParams: State does not match"),Promise.reject(new Error("State does not match"));if(!e.client_id)return i.Log.error("ResponseValidator._processSigninParams: No client_id on state"),Promise.reject(new Error("No client_id on state"));if(!e.authority)return i.Log.error("ResponseValidator._processSigninParams: No authority on state"),Promise.reject(new Error("No authority on state"));if(this._settings.authority){if(this._settings.authority&&this._settings.authority!==e.authority)return i.Log.error("ResponseValidator._processSigninParams: authority mismatch on settings vs. signin state"),Promise.reject(new Error("authority mismatch on settings vs. signin state"))}else this._settings.authority=e.authority;if(this._settings.client_id){if(this._settings.client_id&&this._settings.client_id!==e.client_id)return i.Log.error("ResponseValidator._processSigninParams: client_id mismatch on settings vs. signin state"),Promise.reject(new Error("client_id mismatch on settings vs. signin state"))}else this._settings.client_id=e.client_id;return i.Log.debug("ResponseValidator._processSigninParams: state validated"),t.state=e.data,t.error?(i.Log.warn("ResponseValidator._processSigninParams: Response was error",t.error),Promise.reject(new c.ErrorResponse(t))):e.nonce&&!t.id_token?(i.Log.error("ResponseValidator._processSigninParams: Expecting id_token in response"),Promise.reject(new Error("No id_token in response"))):!e.nonce&&t.id_token?(i.Log.error("ResponseValidator._processSigninParams: Not expecting id_token in response"),Promise.reject(new Error("Unexpected id_token in response"))):e.code_verifier&&!t.code?(i.Log.error("ResponseValidator._processSigninParams: Expecting code in response"),Promise.reject(new Error("No code in response"))):!e.code_verifier&&t.code?(i.Log.error("ResponseValidator._processSigninParams: Not expecting code in response"),Promise.reject(new Error("Unexpected code in response"))):(t.scope||(t.scope=e.scope),Promise.resolve(t))},e.prototype._processClaims=function(e,t){var r=this;if(t.isOpenIdConnect){if(i.Log.debug("ResponseValidator._processClaims: response is OIDC, processing claims"),t.profile=this._filterProtocolClaims(t.profile),!0!==e.skipUserInfo&&this._settings.loadUserInfo&&t.access_token)return i.Log.debug("ResponseValidator._processClaims: loading user info"),this._userInfoService.getClaims(t.access_token).then((function(e){return i.Log.debug("ResponseValidator._processClaims: user info claims received from user info endpoint"),e.sub!==t.profile.sub?(i.Log.error("ResponseValidator._processClaims: sub from user info endpoint does not match sub in id_token"),Promise.reject(new Error("sub from user info endpoint does not match sub in id_token"))):(t.profile=r._mergeClaims(t.profile,e),i.Log.debug("ResponseValidator._processClaims: user info claims received, updated profile:",t.profile),t)}));i.Log.debug("ResponseValidator._processClaims: not loading user info")}else i.Log.debug("ResponseValidator._processClaims: response is not OIDC, not processing claims");return Promise.resolve(t)},e.prototype._mergeClaims=function(e,t){var r=Object.assign({},e);for(var i in t){var o=t[i];Array.isArray(o)||(o=[o]);for(var s=0;s1)return i.Log.error("ResponseValidator._validateIdToken: No kid found in id_token and more than one key found in metadata"),Promise.reject(new Error("No kid found in id_token and more than one key found in metadata"));o=r[0]}return Promise.resolve(o)}))},e.prototype._getSigningKeyForJwtWithSingleRetry=function(e){var t=this;return this._getSigningKeyForJwt(e).then((function(r){return r?Promise.resolve(r):(t._metadataService.resetSigningKeys(),t._getSigningKeyForJwt(e))}))},e.prototype._validateIdToken=function(e,t){var r=this;if(!e.nonce)return i.Log.error("ResponseValidator._validateIdToken: No nonce on state"),Promise.reject(new Error("No nonce on state"));var n=this._joseUtil.parseJwt(t.id_token);return n&&n.header&&n.payload?e.nonce!==n.payload.nonce?(i.Log.error("ResponseValidator._validateIdToken: Invalid nonce in id_token"),Promise.reject(new Error("Invalid nonce in id_token"))):this._metadataService.getIssuer().then((function(o){return i.Log.debug("ResponseValidator._validateIdToken: Received issuer"),r._getSigningKeyForJwtWithSingleRetry(n).then((function(s){if(!s)return i.Log.error("ResponseValidator._validateIdToken: No key matching kid or alg found in signing keys"),Promise.reject(new Error("No key matching kid or alg found in signing keys"));var a=e.client_id,c=r._settings.clockSkew;return i.Log.debug("ResponseValidator._validateIdToken: Validaing JWT; using clock skew (in seconds) of: ",c),r._joseUtil.validateJwt(t.id_token,s,o,a,c).then((function(){return i.Log.debug("ResponseValidator._validateIdToken: JWT validation successful"),n.payload.sub?(t.profile=n.payload,t):(i.Log.error("ResponseValidator._validateIdToken: No sub present in id_token"),Promise.reject(new Error("No sub present in id_token")))}))}))})):(i.Log.error("ResponseValidator._validateIdToken: Failed to parse id_token",n),Promise.reject(new Error("Failed to parse id_token")))},e.prototype._filterByAlg=function(e,t){var r=null;if(t.startsWith("RS"))r="RSA";else if(t.startsWith("PS"))r="PS";else{if(!t.startsWith("ES"))return i.Log.debug("ResponseValidator._filterByAlg: alg not supported: ",t),[];r="EC"}return i.Log.debug("ResponseValidator._filterByAlg: Looking for keys that match kty: ",r),e=e.filter((function(e){return e.kty===r})),i.Log.debug("ResponseValidator._filterByAlg: Number of keys that match kty: ",r,e.length),e},e.prototype._validateAccessToken=function(e){if(!e.profile)return i.Log.error("ResponseValidator._validateAccessToken: No profile loaded from id_token"),Promise.reject(new Error("No profile loaded from id_token"));if(!e.profile.at_hash)return i.Log.error("ResponseValidator._validateAccessToken: No at_hash in id_token"),Promise.reject(new Error("No at_hash in id_token"));if(!e.id_token)return i.Log.error("ResponseValidator._validateAccessToken: No id_token"),Promise.reject(new Error("No id_token"));var t=this._joseUtil.parseJwt(e.id_token);if(!t||!t.header)return i.Log.error("ResponseValidator._validateAccessToken: Failed to parse id_token",t),Promise.reject(new Error("Failed to parse id_token"));var r=t.header.alg;if(!r||5!==r.length)return i.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",r),Promise.reject(new Error("Unsupported alg: "+r));var n=r.substr(2,3);if(!n)return i.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",r,n),Promise.reject(new Error("Unsupported alg: "+r));if(256!==(n=parseInt(n))&&384!==n&&512!==n)return i.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",r,n),Promise.reject(new Error("Unsupported alg: "+r));var o="sha"+n,s=this._joseUtil.hashString(e.access_token,o);if(!s)return i.Log.error("ResponseValidator._validateAccessToken: access_token hash failed:",o),Promise.reject(new Error("Failed to validate at_hash"));var a=s.substr(0,s.length/2),c=this._joseUtil.hexToBase64Url(a);return c!==e.profile.at_hash?(i.Log.error("ResponseValidator._validateAccessToken: Failed to validate at_hash",c,e.profile.at_hash),Promise.reject(new Error("Failed to validate at_hash"))):(i.Log.debug("ResponseValidator._validateAccessToken: success"),Promise.resolve(e))},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserInfoService=void 0;var n=r(7),i=r(2),o=r(0),s=r(4);t.UserInfoService=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.JsonService,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.MetadataService,c=arguments.length>3&&void 0!==arguments[3]?arguments[3]:s.JoseUtil;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw o.Log.error("UserInfoService.ctor: No settings passed"),new Error("settings");this._settings=t,this._jsonService=new r(void 0,void 0,this._getClaimsFromJwt.bind(this)),this._metadataService=new a(this._settings),this._joseUtil=c}return e.prototype.getClaims=function(e){var t=this;return e?this._metadataService.getUserInfoEndpoint().then((function(r){return o.Log.debug("UserInfoService.getClaims: received userinfo url",r),t._jsonService.getJson(r,e).then((function(e){return o.Log.debug("UserInfoService.getClaims: claims received",e),e}))})):(o.Log.error("UserInfoService.getClaims: No token passed"),Promise.reject(new Error("A token is required")))},e.prototype._getClaimsFromJwt=function e(t){var r=this;try{var n=this._joseUtil.parseJwt(t.responseText);if(!n||!n.header||!n.payload)return o.Log.error("UserInfoService._getClaimsFromJwt: Failed to parse JWT",n),Promise.reject(new Error("Failed to parse id_token"));var i=n.header.kid,s=void 0;switch(this._settings.userInfoJwtIssuer){case"OP":s=this._metadataService.getIssuer();break;case"ANY":s=Promise.resolve(n.payload.iss);break;default:s=Promise.resolve(this._settings.userInfoJwtIssuer)}return s.then((function(e){return o.Log.debug("UserInfoService._getClaimsFromJwt: Received issuer:"+e),r._metadataService.getSigningKeys().then((function(s){if(!s)return o.Log.error("UserInfoService._getClaimsFromJwt: No signing keys from metadata"),Promise.reject(new Error("No signing keys from metadata"));o.Log.debug("UserInfoService._getClaimsFromJwt: Received signing keys");var a=void 0;if(i)a=s.filter((function(e){return e.kid===i}))[0];else{if((s=r._filterByAlg(s,n.header.alg)).length>1)return o.Log.error("UserInfoService._getClaimsFromJwt: No kid found in id_token and more than one key found in metadata"),Promise.reject(new Error("No kid found in id_token and more than one key found in metadata"));a=s[0]}if(!a)return o.Log.error("UserInfoService._getClaimsFromJwt: No key matching kid or alg found in signing keys"),Promise.reject(new Error("No key matching kid or alg found in signing keys"));var c=r._settings.client_id,l=r._settings.clockSkew;return o.Log.debug("UserInfoService._getClaimsFromJwt: Validaing JWT; using clock skew (in seconds) of: ",l),r._joseUtil.validateJwt(t.responseText,a,e,c,l,void 0,!0).then((function(){return o.Log.debug("UserInfoService._getClaimsFromJwt: JWT validation successful"),n.payload}))}))}))}catch(e){return o.Log.error("UserInfoService._getClaimsFromJwt: Error parsing JWT response",e.message),void reject(e)}},e.prototype._filterByAlg=function(e,t){var r=null;if(t.startsWith("RS"))r="RSA";else if(t.startsWith("PS"))r="PS";else{if(!t.startsWith("ES"))return o.Log.debug("UserInfoService._filterByAlg: alg not supported: ",t),[];r="EC"}return o.Log.debug("UserInfoService._filterByAlg: Looking for keys that match kty: ",r),e=e.filter((function(e){return e.kty===r})),o.Log.debug("UserInfoService._filterByAlg: Number of keys that match kty: ",r,e.length),e},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AllowedSigningAlgs=t.b64tohex=t.hextob64u=t.crypto=t.X509=t.KeyUtil=t.jws=void 0;var n=r(27);t.jws=n.jws,t.KeyUtil=n.KEYUTIL,t.X509=n.X509,t.crypto=n.crypto,t.hextob64u=n.hextob64u,t.b64tohex=n.b64tohex,t.AllowedSigningAlgs=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"]},function(e,t,r){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0});var r,n,i,o,s,a,c,l,u,d,h,f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},p={userAgent:!1},g={},y=y||(r=Math,i=(n={}).lib={},o=i.Base=function(){function e(){}return{extend:function(t){e.prototype=this;var r=new e;return t&&r.mixIn(t),r.hasOwnProperty("init")||(r.init=function(){r.$super.init.apply(this,arguments)}),r.init.prototype=r,r.$super=this,r},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),s=i.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,i=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[n+o>>>2]|=s<<24-(n+o)%4*8}else for(o=0;o>>2]=r[o>>>2];return this.sigBytes+=i,this},clamp:function(){var e=this.words,t=this.sigBytes;e[t>>>2]&=4294967295<<32-t%4*8,e.length=r.ceil(t/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],n=0;n>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new s.init(r,t/2)}},l=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new s.init(r,t)}},u=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(l.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return l.parse(unescape(encodeURIComponent(e)))}},d=i.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=u.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(e){var t=this._data,n=t.words,i=t.sigBytes,o=this.blockSize,a=i/(4*o),c=(a=e?r.ceil(a):r.max((0|a)-this._minBufferSize,0))*o,l=r.min(4*c,i);if(c){for(var u=0;u>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,s=0;4>s&&i+.75*s>>6*(3-s)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var r=e.length,n=this._map;(i=n.charAt(64))&&-1!=(i=e.indexOf(i))&&(r=i);for(var i=[],o=0,s=0;s>>6-s%4*2;i[o>>>2]|=(a|c)<<24-o%4*8,o++}return t.create(i,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),function(e){for(var t=y,r=(i=t.lib).WordArray,n=i.Hasher,i=t.algo,o=[],s=[],a=function(e){return 4294967296*(e-(0|e))|0},c=2,l=0;64>l;){var u;e:{u=c;for(var d=e.sqrt(u),h=2;h<=d;h++)if(!(u%h)){u=!1;break e}u=!0}u&&(8>l&&(o[l]=a(e.pow(c,.5))),s[l]=a(e.pow(c,1/3)),l++),c++}var f=[];i=i.SHA256=n.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],i=r[1],o=r[2],a=r[3],c=r[4],l=r[5],u=r[6],d=r[7],h=0;64>h;h++){if(16>h)f[h]=0|e[t+h];else{var p=f[h-15],g=f[h-2];f[h]=((p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3)+f[h-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+f[h-16]}p=d+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&l^~c&u)+s[h]+f[h],g=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&i^n&o^i&o),d=u,u=l,l=c,c=a+p|0,a=o,o=i,i=n,n=p+g|0}r[0]=r[0]+n|0,r[1]=r[1]+i|0,r[2]=r[2]+o|0,r[3]=r[3]+a|0,r[4]=r[4]+c|0,r[5]=r[5]+l|0,r[6]=r[6]+u|0,r[7]=r[7]+d|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;return r[i>>>5]|=128<<24-i%32,r[14+(i+64>>>9<<4)]=e.floor(n/4294967296),r[15+(i+64>>>9<<4)]=n,t.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}}),t.SHA256=n._createHelper(i),t.HmacSHA256=n._createHmacHelper(i)}(Math),function(){function e(){return n.create.apply(n,arguments)}for(var t=y,r=t.lib.Hasher,n=(o=t.x64).Word,i=o.WordArray,o=t.algo,s=[e(1116352408,3609767458),e(1899447441,602891725),e(3049323471,3964484399),e(3921009573,2173295548),e(961987163,4081628472),e(1508970993,3053834265),e(2453635748,2937671579),e(2870763221,3664609560),e(3624381080,2734883394),e(310598401,1164996542),e(607225278,1323610764),e(1426881987,3590304994),e(1925078388,4068182383),e(2162078206,991336113),e(2614888103,633803317),e(3248222580,3479774868),e(3835390401,2666613458),e(4022224774,944711139),e(264347078,2341262773),e(604807628,2007800933),e(770255983,1495990901),e(1249150122,1856431235),e(1555081692,3175218132),e(1996064986,2198950837),e(2554220882,3999719339),e(2821834349,766784016),e(2952996808,2566594879),e(3210313671,3203337956),e(3336571891,1034457026),e(3584528711,2466948901),e(113926993,3758326383),e(338241895,168717936),e(666307205,1188179964),e(773529912,1546045734),e(1294757372,1522805485),e(1396182291,2643833823),e(1695183700,2343527390),e(1986661051,1014477480),e(2177026350,1206759142),e(2456956037,344077627),e(2730485921,1290863460),e(2820302411,3158454273),e(3259730800,3505952657),e(3345764771,106217008),e(3516065817,3606008344),e(3600352804,1432725776),e(4094571909,1467031594),e(275423344,851169720),e(430227734,3100823752),e(506948616,1363258195),e(659060556,3750685593),e(883997877,3785050280),e(958139571,3318307427),e(1322822218,3812723403),e(1537002063,2003034995),e(1747873779,3602036899),e(1955562222,1575990012),e(2024104815,1125592928),e(2227730452,2716904306),e(2361852424,442776044),e(2428436474,593698344),e(2756734187,3733110249),e(3204031479,2999351573),e(3329325298,3815920427),e(3391569614,3928383900),e(3515267271,566280711),e(3940187606,3454069534),e(4118630271,4000239992),e(116418474,1914138554),e(174292421,2731055270),e(289380356,3203993006),e(460393269,320620315),e(685471733,587496836),e(852142971,1086792851),e(1017036298,365543100),e(1126000580,2618297676),e(1288033470,3409855158),e(1501505948,4234509866),e(1607167915,987167468),e(1816402316,1246189591)],a=[],c=0;80>c;c++)a[c]=e();o=o.SHA512=r.extend({_doReset:function(){this._hash=new i.init([new n.init(1779033703,4089235720),new n.init(3144134277,2227873595),new n.init(1013904242,4271175723),new n.init(2773480762,1595750129),new n.init(1359893119,2917565137),new n.init(2600822924,725511199),new n.init(528734635,4215389547),new n.init(1541459225,327033209)])},_doProcessBlock:function(e,t){for(var r=(d=this._hash.words)[0],n=d[1],i=d[2],o=d[3],c=d[4],l=d[5],u=d[6],d=d[7],h=r.high,f=r.low,p=n.high,g=n.low,y=i.high,m=i.low,v=o.high,b=o.low,w=c.high,_=c.low,S=l.high,E=l.low,A=u.high,R=u.low,I=d.high,T=d.low,x=h,P=f,C=p,k=g,O=y,F=m,N=v,D=b,L=w,U=_,j=S,M=E,B=A,H=R,W=I,$=T,V=0;80>V;V++){var K=a[V];if(16>V)var J=K.high=0|e[t+2*V],G=K.low=0|e[t+2*V+1];else{J=((G=(J=a[V-15]).high)>>>1|(q=J.low)<<31)^(G>>>8|q<<24)^G>>>7;var q=(q>>>1|G<<31)^(q>>>8|G<<24)^(q>>>7|G<<25),z=((G=(z=a[V-2]).high)>>>19|(Y=z.low)<<13)^(G<<3|Y>>>29)^G>>>6,Y=(Y>>>19|G<<13)^(Y<<3|G>>>29)^(Y>>>6|G<<26),Q=(G=a[V-7]).high,X=(Z=a[V-16]).high,Z=Z.low;J=(J=(J=J+Q+((G=q+G.low)>>>0>>0?1:0))+z+((G+=Y)>>>0>>0?1:0))+X+((G+=Z)>>>0>>0?1:0),K.high=J,K.low=G}Q=L&j^~L&B,Z=U&M^~U&H,K=x&C^x&O^C&O;var ee=P&k^P&F^k&F,te=(q=(x>>>28|P<<4)^(x<<30|P>>>2)^(x<<25|P>>>7),z=(P>>>28|x<<4)^(P<<30|x>>>2)^(P<<25|x>>>7),(Y=s[V]).high),re=Y.low;X=W+((L>>>14|U<<18)^(L>>>18|U<<14)^(L<<23|U>>>9))+((Y=$+((U>>>14|L<<18)^(U>>>18|L<<14)^(U<<23|L>>>9)))>>>0<$>>>0?1:0),W=B,$=H,B=j,H=M,j=L,M=U,L=N+(X=(X=(X=X+Q+((Y+=Z)>>>0>>0?1:0))+te+((Y+=re)>>>0>>0?1:0))+J+((Y+=G)>>>0>>0?1:0))+((U=D+Y|0)>>>0>>0?1:0)|0,N=O,D=F,O=C,F=k,C=x,k=P,x=X+(K=q+K+((G=z+ee)>>>0>>0?1:0))+((P=Y+G|0)>>>0>>0?1:0)|0}f=r.low=f+P,r.high=h+x+(f>>>0

>>0?1:0),g=n.low=g+k,n.high=p+C+(g>>>0>>0?1:0),m=i.low=m+F,i.high=y+O+(m>>>0>>0?1:0),b=o.low=b+D,o.high=v+N+(b>>>0>>0?1:0),_=c.low=_+U,c.high=w+L+(_>>>0>>0?1:0),E=l.low=E+M,l.high=S+j+(E>>>0>>0?1:0),R=u.low=R+H,u.high=A+B+(R>>>0>>0?1:0),T=d.low=T+$,d.high=I+W+(T>>>0<$>>>0?1:0)},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[30+(n+128>>>10<<5)]=Math.floor(r/4294967296),t[31+(n+128>>>10<<5)]=r,e.sigBytes=4*t.length,this._process(),this._hash.toX32()},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32}),t.SHA512=r._createHelper(o),t.HmacSHA512=r._createHmacHelper(o)}(),function(){var e=y,t=(i=e.x64).Word,r=i.WordArray,n=(i=e.algo).SHA512,i=i.SHA384=n.extend({_doReset:function(){this._hash=new r.init([new t.init(3418070365,3238371032),new t.init(1654270250,914150663),new t.init(2438529370,812702999),new t.init(355462360,4144912697),new t.init(1731405415,4290775857),new t.init(2394180231,1750603025),new t.init(3675008525,1694076839),new t.init(1203062813,3204075428)])},_doFinalize:function(){var e=n._doFinalize.call(this);return e.sigBytes-=16,e}});e.SHA384=n._createHelper(i),e.HmacSHA384=n._createHmacHelper(i)}();var m,v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function b(e){var t,r,n="";for(t=0;t+3<=e.length;t+=3)r=parseInt(e.substring(t,t+3),16),n+=v.charAt(r>>6)+v.charAt(63&r);for(t+1==e.length?(r=parseInt(e.substring(t,t+1),16),n+=v.charAt(r<<2)):t+2==e.length&&(r=parseInt(e.substring(t,t+2),16),n+=v.charAt(r>>2)+v.charAt((3&r)<<4));(3&n.length)>0;)n+="=";return n}function w(e){var t,r,n,i="",o=0;for(t=0;t>2),r=3&n,o=1):1==o?(i+=T(r<<2|n>>4),r=15&n,o=2):2==o?(i+=T(r),i+=T(n>>2),r=3&n,o=3):(i+=T(r<<2|n>>4),i+=T(15&n),o=0));return 1==o&&(i+=T(r<<2)),i}function _(e){var t,r=w(e),n=new Array;for(t=0;2*t>15;--o>=0;){var c=32767&this[e],l=this[e++]>>15,u=a*c+l*s;i=((c=s*c+((32767&u)<<15)+r[n]+(1073741823&i))>>>30)+(u>>>15)+a*l+(i>>>30),r[n++]=1073741823&c}return i},m=30):"Netscape"!=p.appName?(S.prototype.am=function(e,t,r,n,i,o){for(;--o>=0;){var s=t*this[e++]+r[n]+i;i=Math.floor(s/67108864),r[n++]=67108863&s}return i},m=26):(S.prototype.am=function(e,t,r,n,i,o){for(var s=16383&t,a=t>>14;--o>=0;){var c=16383&this[e],l=this[e++]>>14,u=a*c+l*s;i=((c=s*c+((16383&u)<<14)+r[n]+i)>>28)+(u>>14)+a*l,r[n++]=268435455&c}return i},m=28),S.prototype.DB=m,S.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function k(e){this.m=e}function O(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),!(255&e)&&(e>>=8,t+=8),!(15&e)&&(e>>=4,t+=4),!(3&e)&&(e>>=2,t+=2),!(1&e)&&++t,t}function j(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function M(){}function B(e){return e}function H(e){this.r2=E(),this.q3=E(),S.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}k.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},k.prototype.revert=function(e){return e},k.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},k.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},k.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},O.prototype.convert=function(e){var t=E();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(S.ZERO)>0&&this.m.subTo(t,t),t},O.prototype.revert=function(e){var t=E();return e.copyTo(t),this.reduce(t),t},O.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(e[r=t+this.m.t]+=this.m.am(0,n,e,t,0,this.m.t);e[r]>=e.DV;)e[r]-=e.DV,e[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},O.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},O.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},S.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},S.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},S.prototype.fromString=function(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,i=!1,o=0;--n>=0;){var s=8==r?255&e[n]:x(e,n);s<0?"-"==e.charAt(n)&&(i=!0):(i=!1,0==o?this[this.t++]=s:o+r>this.DB?(this[this.t-1]|=(s&(1<>this.DB-o):this[this.t-1]|=s<=this.DB&&(o-=this.DB))}8==r&&!!(128&e[0])&&(this.s=-1,o>0&&(this[this.t-1]|=(1<0&&this[this.t-1]==e;)--this.t},S.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t[r+e]=this[r];for(r=e-1;r>=0;--r)t[r]=0;t.t=this.t+e,t.s=this.s},S.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t[r+s+1]=this[r]>>i|a,a=(this[r]&o)<=0;--r)t[r]=0;t[s]=a,t.t=this.t+s+1,t.s=this.s,t.clamp()},S.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,i=this.DB-n,o=(1<>n;for(var s=r+1;s>n;n>0&&(t[this.t-r-1]|=(this.s&o)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t[r++]=this.DV+n:n>0&&(t[r++]=n),t.t=r,t.clamp()},S.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t[i]=0;for(i=0;i=0;)e[r]=0;for(r=0;r=t.DV&&(e[r+t.t]-=t.DV,e[r+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(r,t[r],e,2*r,0,1)),e.s=0,e.clamp()},S.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(c,o),i.lShiftTo(c,r)):(n.copyTo(o),i.copyTo(r));var l=o.t,u=o[l-1];if(0!=u){var d=u*(1<1?o[l-2]>>this.F2:0),h=this.FV/d,f=(1<=0&&(r[r.t++]=1,r.subTo(m,r)),S.ONE.dlShiftTo(l,m),m.subTo(o,o);o.t=0;){var v=r[--g]==u?this.DM:Math.floor(r[g]*h+(r[g-1]+p)*f);if((r[g]+=o.am(0,v,r,y,0,l))0&&r.rShiftTo(c,r),s<0&&S.ZERO.subTo(r,r)}}},S.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},S.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},S.prototype.exp=function(e,t){if(e>4294967295||e<1)return S.ONE;var r=E(),n=E(),i=t.convert(this),o=C(e)-1;for(i.copyTo(r);--o>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,i,r);else{var s=r;r=n,n=s}return t.revert(r)},S.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<0)for(a>a)>0&&(i=!0,o=T(r));s>=0;)a>(a+=this.DB-t)):(r=this[s]>>(a-=t)&n,a<=0&&(a+=this.DB,--s)),r>0&&(i=!0),i&&(o+=T(r));return i?o:"0"},S.prototype.negate=function(){var e=E();return S.ZERO.subTo(this,e),e},S.prototype.abs=function(){return this.s<0?this.negate():this},S.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this[r]-e[r]))return t;return 0},S.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+C(this[this.t-1]^this.s&this.DM)},S.prototype.mod=function(e){var t=E();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(S.ZERO)>0&&e.subTo(t,t),t},S.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new k(t):new O(t),this.exp(e,r)},S.ZERO=P(0),S.ONE=P(1),M.prototype.convert=B,M.prototype.revert=B,M.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},M.prototype.sqrTo=function(e,t){e.squareTo(t)},H.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=E();return e.copyTo(t),this.reduce(t),t},H.prototype.revert=function(e){return e},H.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},H.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},H.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var W,$,V,K=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],J=(1<<26)/K[K.length-1];function G(){this.i=0,this.j=0,this.S=new Array}function q(){!function(e){$[V++]^=255&e,$[V++]^=e>>8&255,$[V++]^=e>>16&255,$[V++]^=e>>24&255,V>=256&&(V-=256)}((new Date).getTime())}if(S.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},S.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=P(r),i=E(),o=E(),s="";for(this.divRemTo(n,i,o);i.signum()>0;)s=(r+o.intValue()).toString(e).substr(1)+s,i.divRemTo(n,i,o);return o.intValue().toString(e)+s},S.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,o=0,s=0,a=0;a=r&&(this.dMultiply(n),this.dAddOffset(s,0),o=0,s=0))}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(s,0)),i&&S.ZERO.subTo(this,this)},S.prototype.fromNumber=function(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(S.ONE.shiftLeft(e-1),N,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(S.ONE.shiftLeft(e-1),this);else{var n=new Array,i=7&e;n.length=1+(e>>3),t.nextBytes(n),i>0?n[0]&=(1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t[r++]=n:n<-1&&(t[r++]=this.DV+n),t.t=r,t.clamp()},S.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},S.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},S.prototype.multiplyLowerTo=function(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r[--i]=0;for(n=r.t-this.t;i=0;)r[n]=0;for(n=Math.max(t-this.t,0);n0)if(0==t)r=this[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this[n])%e;return r},S.prototype.millerRabin=function(e){var t=this.subtract(S.ONE),r=t.getLowestSetBit();if(r<=0)return!1;var n=t.shiftRight(r);(e=e+1>>1)>K.length&&(e=K.length);for(var i=E(),o=0;o>24},S.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},S.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},S.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<=0;)n<8?(r=(this[e]&(1<>(n+=this.DB-8)):(r=this[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),!!(128&r)&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t},S.prototype.equals=function(e){return 0==this.compareTo(e)},S.prototype.min=function(e){return this.compareTo(e)<0?this:e},S.prototype.max=function(e){return this.compareTo(e)>0?this:e},S.prototype.and=function(e){var t=E();return this.bitwiseTo(e,F,t),t},S.prototype.or=function(e){var t=E();return this.bitwiseTo(e,N,t),t},S.prototype.xor=function(e){var t=E();return this.bitwiseTo(e,D,t),t},S.prototype.andNot=function(e){var t=E();return this.bitwiseTo(e,L,t),t},S.prototype.not=function(){for(var e=E(),t=0;t=this.t?0!=this.s:!!(this[t]&1<1){var u=E();for(n.sqrTo(s[1],u);a<=l;)s[a]=E(),n.mulTo(u,s[a-2],s[a]),a+=2}var d,h,f=e.t-1,p=!0,g=E();for(i=C(e[f])-1;f>=0;){for(i>=c?d=e[f]>>i-c&l:(d=(e[f]&(1<0&&(d|=e[f-1]>>this.DB+i-c)),a=r;!(1&d);)d>>=1,--a;if((i-=a)<0&&(i+=this.DB,--f),p)s[d].copyTo(o),p=!1;else{for(;a>1;)n.sqrTo(o,g),n.sqrTo(g,o),a-=2;a>0?n.sqrTo(o,g):(h=o,o=g,g=h),n.mulTo(g,s[d],o)}for(;f>=0&&!(e[f]&1<=0?(r.subTo(n,r),t&&i.subTo(s,i),o.subTo(a,o)):(n.subTo(r,n),t&&s.subTo(i,s),a.subTo(o,a))}return 0!=n.compareTo(S.ONE)?S.ZERO:a.compareTo(e)>=0?a.subtract(e):a.signum()<0?(a.addTo(e,a),a.signum()<0?a.add(e):a):a},S.prototype.pow=function(e){return this.exp(e,new M)},S.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var i=t.getLowestSetBit(),o=r.getLowestSetBit();if(o<0)return t;for(i0&&(t.rShiftTo(o,t),r.rShiftTo(o,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return o>0&&r.lShiftTo(o,r),r},S.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r[0]<=K[K.length-1]){for(t=0;t>>8,$[V++]=255&z;V=0,q()}function Z(){if(null==W){for(q(),(W=new G).init($),V=0;V<$.length;++V)$[V]=0;V=0}return W.next()}function ee(){}function te(e,t){return new S(e,t)}function re(e,t,r){for(var n="",i=0;n.length>24,(16711680&i)>>16,(65280&i)>>8,255&i]))),i+=1;return n}function ne(){this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null}function ie(e,t){this.x=t,this.q=e}function oe(e,t,r,n){this.curve=e,this.x=t,this.y=r,this.z=null==n?S.ONE:n,this.zinv=null}function se(e,t,r){this.q=e,this.a=this.fromBigInteger(t),this.b=this.fromBigInteger(r),this.infinity=new oe(this,null,null)}ee.prototype.nextBytes=function(e){var t;for(t=0;t0&&t.length>0))throw"Invalid RSA public key";this.n=te(e,16),this.e=parseInt(t,16)}},ne.prototype.encrypt=function(e){var t=function(e,t){if(t=0&&t>0;){var i=e.charCodeAt(n--);i<128?r[--t]=i:i>127&&i<2048?(r[--t]=63&i|128,r[--t]=i>>6|192):(r[--t]=63&i|128,r[--t]=i>>6&63|128,r[--t]=i>>12|224)}r[--t]=0;for(var o=new ee,s=new Array;t>2;){for(s[0]=0;0==s[0];)o.nextBytes(s);r[--t]=s[0]}return r[--t]=2,r[--t]=0,new S(r)}(e,this.n.bitLength()+7>>3);if(null==t)return null;var r=this.doPublic(t);if(null==r)return null;var n=r.toString(16);return 1&n.length?"0"+n:n},ne.prototype.encryptOAEP=function(e,t,r){var n=function(e,t,r,n){var i=ce.crypto.MessageDigest,o=ce.crypto.Util,s=null;if(r||(r="sha1"),"string"==typeof r&&(s=i.getCanonicalAlgName(r),n=i.getHashLength(s),r=function(e){return Se(o.hashHex(Ee(e),s))}),e.length+2*n+2>t)throw"Message too long for RSA";var a,c="";for(a=0;a>3,t,r);if(null==n)return null;var i=this.doPublic(n);if(null==i)return null;var o=i.toString(16);return 1&o.length?"0"+o:o},ne.prototype.type="RSA",ie.prototype.equals=function(e){return e==this||this.q.equals(e.q)&&this.x.equals(e.x)},ie.prototype.toBigInteger=function(){return this.x},ie.prototype.negate=function(){return new ie(this.q,this.x.negate().mod(this.q))},ie.prototype.add=function(e){return new ie(this.q,this.x.add(e.toBigInteger()).mod(this.q))},ie.prototype.subtract=function(e){return new ie(this.q,this.x.subtract(e.toBigInteger()).mod(this.q))},ie.prototype.multiply=function(e){return new ie(this.q,this.x.multiply(e.toBigInteger()).mod(this.q))},ie.prototype.square=function(){return new ie(this.q,this.x.square().mod(this.q))},ie.prototype.divide=function(e){return new ie(this.q,this.x.multiply(e.toBigInteger().modInverse(this.q)).mod(this.q))},oe.prototype.getX=function(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))},oe.prototype.getY=function(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))},oe.prototype.equals=function(e){return e==this||(this.isInfinity()?e.isInfinity():e.isInfinity()?this.isInfinity():!!e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(S.ZERO)&&e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(S.ZERO))},oe.prototype.isInfinity=function(){return null==this.x&&null==this.y||this.z.equals(S.ZERO)&&!this.y.toBigInteger().equals(S.ZERO)},oe.prototype.negate=function(){return new oe(this.curve,this.x,this.y.negate(),this.z)},oe.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q),r=e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q);if(S.ZERO.equals(r))return S.ZERO.equals(t)?this.twice():this.curve.getInfinity();var n=new S("3"),i=this.x.toBigInteger(),o=this.y.toBigInteger(),s=(e.x.toBigInteger(),e.y.toBigInteger(),r.square()),a=s.multiply(r),c=i.multiply(s),l=t.square().multiply(this.z),u=l.subtract(c.shiftLeft(1)).multiply(e.z).subtract(a).multiply(r).mod(this.curve.q),d=c.multiply(n).multiply(t).subtract(o.multiply(a)).subtract(l.multiply(t)).multiply(e.z).add(t.multiply(a)).mod(this.curve.q),h=a.multiply(this.z).multiply(e.z).mod(this.curve.q);return new oe(this.curve,this.curve.fromBigInteger(u),this.curve.fromBigInteger(d),h)},oe.prototype.twice=function(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=new S("3"),t=this.x.toBigInteger(),r=this.y.toBigInteger(),n=r.multiply(this.z),i=n.multiply(r).mod(this.curve.q),o=this.curve.a.toBigInteger(),s=t.square().multiply(e);S.ZERO.equals(o)||(s=s.add(this.z.square().multiply(o)));var a=(s=s.mod(this.curve.q)).square().subtract(t.shiftLeft(3).multiply(i)).shiftLeft(1).multiply(n).mod(this.curve.q),c=s.multiply(e).multiply(t).subtract(i.shiftLeft(1)).shiftLeft(2).multiply(i).subtract(s.square().multiply(s)).mod(this.curve.q),l=n.square().multiply(n).shiftLeft(3).mod(this.curve.q);return new oe(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(c),l)},oe.prototype.multiply=function(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();var t,r=e,n=r.multiply(new S("3")),i=this.negate(),o=this,s=this.curve.q.subtract(e),a=s.multiply(new S("3")),c=new oe(this.curve,this.x,this.y),l=c.negate();for(t=n.bitLength()-2;t>0;--t){o=o.twice();var u=n.testBit(t);u!=r.testBit(t)&&(o=o.add(u?this:i))}for(t=a.bitLength()-2;t>0;--t){c=c.twice();var d=a.testBit(t);d!=s.testBit(t)&&(c=c.add(d?c:l))}return o},oe.prototype.multiplyTwo=function(e,t,r){var n;n=e.bitLength()>r.bitLength()?e.bitLength()-1:r.bitLength()-1;for(var i=this.curve.getInfinity(),o=this.add(t);n>=0;)i=i.twice(),e.testBit(n)?i=r.testBit(n)?i.add(o):i.add(this):r.testBit(n)&&(i=i.add(t)),--n;return i},se.prototype.getQ=function(){return this.q},se.prototype.getA=function(){return this.a},se.prototype.getB=function(){return this.b},se.prototype.equals=function(e){return e==this||this.q.equals(e.q)&&this.a.equals(e.a)&&this.b.equals(e.b)},se.prototype.getInfinity=function(){return this.infinity},se.prototype.fromBigInteger=function(e){return new ie(this.q,e)},se.prototype.decodePointHex=function(e){switch(parseInt(e.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:default:return null;case 4:case 6:case 7:var t=(e.length-2)/2,r=e.substr(2,t),n=e.substr(t+2,t);return new oe(this,this.fromBigInteger(new S(r,16)),this.fromBigInteger(new S(n,16)))}},ie.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)},oe.prototype.getEncoded=function(e){var t=function(e,t){var r=e.toByteArrayUnsigned();if(tr.length;)r.unshift(0);return r},r=this.getX().toBigInteger(),n=this.getY().toBigInteger(),i=t(r,32);return e?n.isEven()?i.unshift(2):i.unshift(3):(i.unshift(4),i=i.concat(t(n,32))),i},oe.decodeFrom=function(e,t){t[0];var r=t.length-1,n=t.slice(1,1+r/2),i=t.slice(1+r/2,1+r);n.unshift(0),i.unshift(0);var o=new S(n),s=new S(i);return new oe(e,e.fromBigInteger(o),e.fromBigInteger(s))},oe.decodeFromHex=function(e,t){t.substr(0,2);var r=t.length-2,n=t.substr(2,r/2),i=t.substr(2+r/2,r/2),o=new S(n,16),s=new S(i,16);return new oe(e,e.fromBigInteger(o),e.fromBigInteger(s))},oe.prototype.add2D=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;if(this.x.equals(e.x))return this.y.equals(e.y)?this.twice():this.curve.getInfinity();var t=e.x.subtract(this.x),r=e.y.subtract(this.y).divide(t),n=r.square().subtract(this.x).subtract(e.x),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new oe(this.curve,n,i)},oe.prototype.twice2D=function(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=this.curve.fromBigInteger(S.valueOf(2)),t=this.curve.fromBigInteger(S.valueOf(3)),r=this.x.square().multiply(t).add(this.curve.a).divide(this.y.multiply(e)),n=r.square().subtract(this.x.multiply(e)),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new oe(this.curve,n,i)},oe.prototype.multiply2D=function(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();var t,r=e,n=r.multiply(new S("3")),i=this.negate(),o=this;for(t=n.bitLength()-2;t>0;--t){o=o.twice();var s=n.testBit(t);s!=r.testBit(t)&&(o=o.add2D(s?this:i))}return o},oe.prototype.isOnCurve=function(){var e=this.getX().toBigInteger(),t=this.getY().toBigInteger(),r=this.curve.getA().toBigInteger(),n=this.curve.getB().toBigInteger(),i=this.curve.getQ(),o=t.multiply(t).mod(i),s=e.multiply(e).multiply(e).add(r.multiply(e)).add(n).mod(i);return o.equals(s)},oe.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"},oe.prototype.validate=function(){var e=this.curve.getQ();if(this.isInfinity())throw new Error("Point is at infinity.");var t=this.getX().toBigInteger(),r=this.getY().toBigInteger();if(t.compareTo(S.ONE)<0||t.compareTo(e.subtract(S.ONE))>0)throw new Error("x coordinate out of bounds");if(r.compareTo(S.ONE)<0||r.compareTo(e.subtract(S.ONE))>0)throw new Error("y coordinate out of bounds");if(!this.isOnCurve())throw new Error("Point is not on the curve.");if(this.multiply(e).isInfinity())throw new Error("Point is not a scalar multiple of G.");return!0};var ae=function(){var e=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]|(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)|(?:"(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))*"))',"g"),t=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),r={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};function n(e,t,n){return t?r[t]:String.fromCharCode(parseInt(n,16))}var i=new String(""),o=Object.hasOwnProperty;return function(r,s){var a,c,l=r.match(e),u=l[0],d=!1;"{"===u?a={}:"["===u?a=[]:(a=[],d=!0);for(var h=[a],p=1-d,g=l.length;p=0;)delete n[i[l]]}return s.call(t,r,n)}({"":a},"")),a}}();void 0!==ce&&ce||(t.KJUR=ce={}),void 0!==ce.asn1&&ce.asn1||(ce.asn1={}),ce.asn1.ASN1Util=new function(){this.integerToByteHex=function(e){var t=e.toString(16);return t.length%2==1&&(t="0"+t),t},this.bigIntToMinTwosComplementsHex=function(e){var t=e.toString(16);if("-"!=t.substr(0,1))t.length%2==1?t="0"+t:t.match(/^[0-7]/)||(t="00"+t);else{var r=t.substr(1).length;r%2==1?r+=1:t.match(/^[0-7]/)||(r+=2);for(var n="",i=0;i15)throw"ASN.1 length too long to represent by 8x: n = "+e.toString(16);return(128+r).toString(16)+t},this.getEncodedHex=function(){return(null==this.hTLV||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getValueHex=function(){return this.getEncodedHex(),this.hV},this.getFreshValueHex=function(){return""},this.setByParam=function(e){this.params=e},null!=e&&null!=e.tlv&&(this.hTLV=e.tlv,this.isModified=!1)},ce.asn1.DERAbstractString=function(e){ce.asn1.DERAbstractString.superclass.constructor.call(this),this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=we(this.s).toLowerCase()},this.setStringHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e?this.setString(e):void 0!==e.str?this.setString(e.str):void 0!==e.hex&&this.setStringHex(e.hex))},He(ce.asn1.DERAbstractString,ce.asn1.ASN1Object),ce.asn1.DERAbstractTime=function(e){ce.asn1.DERAbstractTime.superclass.constructor.call(this),this.localDateToUTC=function(e){var t=e.getTime()+6e4*e.getTimezoneOffset();return new Date(t)},this.formatDate=function(e,t,r){var n=this.zeroPadding,i=this.localDateToUTC(e),o=String(i.getFullYear());"utc"==t&&(o=o.substr(2,2));var s=o+n(String(i.getMonth()+1),2)+n(String(i.getDate()),2)+n(String(i.getHours()),2)+n(String(i.getMinutes()),2)+n(String(i.getSeconds()),2);if(!0===r){var a=i.getMilliseconds();if(0!=a){var c=n(String(a),3);s=s+"."+(c=c.replace(/[0]+$/,""))}}return s+"Z"},this.zeroPadding=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=ge(e)},this.setByDateValue=function(e,t,r,n,i,o){var s=new Date(Date.UTC(e,t-1,r,n,i,o,0));this.setByDate(s)},this.getFreshValueHex=function(){return this.hV}},He(ce.asn1.DERAbstractTime,ce.asn1.ASN1Object),ce.asn1.DERAbstractStructured=function(e){ce.asn1.DERAbstractString.superclass.constructor.call(this),this.setByASN1ObjectArray=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array=e},this.appendASN1Object=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array.push(e)},this.asn1Array=new Array,void 0!==e&&void 0!==e.array&&(this.asn1Array=e.array)},He(ce.asn1.DERAbstractStructured,ce.asn1.ASN1Object),ce.asn1.DERBoolean=function(e){ce.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=0==e?"010100":"0101ff"},He(ce.asn1.DERBoolean,ce.asn1.ASN1Object),ce.asn1.DERInteger=function(e){ce.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=ce.asn1.ASN1Util.bigIntToMinTwosComplementsHex(e)},this.setByInteger=function(e){var t=new S(String(e),10);this.setByBigInteger(t)},this.setValueHex=function(e){this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&(void 0!==e.bigint?this.setByBigInteger(e.bigint):void 0!==e.int?this.setByInteger(e.int):"number"==typeof e?this.setByInteger(e):void 0!==e.hex&&this.setValueHex(e.hex))},He(ce.asn1.DERInteger,ce.asn1.ASN1Object),ce.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=ce.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.getEncodedHex()}ce.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(e){this.hTLV=null,this.isModified=!0,this.hV=e},this.setUnusedBitsAndHexValue=function(e,t){if(e<0||7i.length&&(i=n[r]);return(e=e.replace(i,"::")).slice(1,-1)}function De(e){var t="malformed hex value";if(!e.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/))throw t;if(8!=e.length)return 32==e.length?Ne(e):e;try{return parseInt(e.substr(0,2),16)+"."+parseInt(e.substr(2,2),16)+"."+parseInt(e.substr(4,2),16)+"."+parseInt(e.substr(6,2),16)}catch(e){throw t}}function Le(e){return e.match(/.{4}/g).map((function(e){var t=parseInt(e.substr(0,2),16),r=parseInt(e.substr(2),16);if(0==t&r<128)return String.fromCharCode(r);if(t<8){var n=128|63&r;return _e((192|(7&t)<<3|(192&r)>>6).toString(16)+n.toString(16))}n=128|(15&t)<<2|(192&r)>>6;var i=128|63&r;return _e((224|(240&t)>>4).toString(16)+n.toString(16)+i.toString(16))})).join("")}function Ue(e){for(var t=encodeURIComponent(e),r="",n=0;n"7"?"00"+e:e}de.getLblen=function(e,t){if("8"!=e.substr(t+2,1))return 1;var r=parseInt(e.substr(t+3,1));return 0==r?-1:0=n)break}return s},de.getNthChildIdx=function(e,t,r){return de.getChildIdx(e,t)[r]},de.getIdxbyList=function(e,t,r,n){var i,o,s=de;return 0==r.length?void 0!==n&&e.substr(t,2)!==n?-1:t:(i=r.shift())>=(o=s.getChildIdx(e,t)).length?-1:s.getIdxbyList(e,o[i],r,n)},de.getIdxbyListEx=function(e,t,r,n){var i,o,s=de;if(0==r.length)return void 0!==n&&e.substr(t,2)!==n?-1:t;i=r.shift(),o=s.getChildIdx(e,t);for(var a=0,c=0;c=e.length?null:i.getTLV(e,o)},de.getTLVbyListEx=function(e,t,r,n){var i=de,o=i.getIdxbyListEx(e,t,r,n);return-1==o?null:i.getTLV(e,o)},de.getVbyList=function(e,t,r,n,i){var o,s,a=de;return-1==(o=a.getIdxbyList(e,t,r,n))||o>=e.length?null:(s=a.getV(e,o),!0===i&&(s=s.substr(2)),s)},de.getVbyListEx=function(e,t,r,n,i){var o,s,a=de;return-1==(o=a.getIdxbyListEx(e,t,r,n))?null:(s=a.getV(e,o),"03"==e.substr(o,2)&&!1!==i&&(s=s.substr(2)),s)},de.getInt=function(e,t,r){null==r&&(r=-1);try{var n=e.substr(t,2);if("02"!=n&&"03"!=n)return r;var i=de.getV(e,t);return"02"==n?parseInt(i,16):function(e){try{var t=e.substr(0,2);if("00"==t)return parseInt(e.substr(2),16);var r=parseInt(t,16),n=e.substr(2),i=parseInt(n,16).toString(2);return"0"==i&&(i="00000000"),i=i.slice(0,0-r),parseInt(i,2)}catch(e){return-1}}(i)}catch(e){return r}},de.getOID=function(e,t,r){null==r&&(r=null);try{return"06"!=e.substr(t,2)?r:function(e){if(!je(e))return null;try{var t=[],r=e.substr(0,2),n=parseInt(r,16);t[0]=new String(Math.floor(n/40)),t[1]=new String(n%40);for(var i=e.substr(2),o=[],s=0;s0&&(l=l+"."+a.join(".")),l}catch(e){return null}}(de.getV(e,t))}catch(e){return r}},de.getOIDName=function(e,t,r){null==r&&(r=null);try{var n=de.getOID(e,t,r);if(n==r)return r;var i=ce.asn1.x509.OID.oid2name(n);return""==i?n:i}catch(e){return r}},de.getString=function(e,t,r){null==r&&(r=null);try{return Se(de.getV(e,t))}catch(e){return r}},de.hextooidstr=function(e){var t=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},r=[],n=e.substr(0,2),i=parseInt(n,16);r[0]=new String(Math.floor(i/40)),r[1]=new String(i%40);for(var o=e.substr(2),s=[],a=0;a0&&(u=u+"."+c.join(".")),u},de.dump=function(e,t,r,n){var i=de,o=i.getV,s=i.dump,a=i.getChildIdx,c=e;e instanceof ce.asn1.ASN1Object&&(c=e.getEncodedHex());var l=function(e,t){return e.length<=2*t?e:e.substr(0,t)+"..(total "+e.length/2+"bytes).."+e.substr(e.length-t,t)};void 0===t&&(t={ommit_long_octet:32}),void 0===r&&(r=0),void 0===n&&(n="");var u,d=t.ommit_long_octet;if("01"==(u=c.substr(r,2)))return"00"==(h=o(c,r))?n+"BOOLEAN FALSE\n":n+"BOOLEAN TRUE\n";if("02"==u)return n+"INTEGER "+l(h=o(c,r),d)+"\n";if("03"==u){var h=o(c,r);return i.isASN1HEX(h.substr(2))?(_=n+"BITSTRING, encapsulates\n")+s(h.substr(2),t,0,n+" "):n+"BITSTRING "+l(h,d)+"\n"}if("04"==u)return h=o(c,r),i.isASN1HEX(h)?(_=n+"OCTETSTRING, encapsulates\n")+s(h,t,0,n+" "):n+"OCTETSTRING "+l(h,d)+"\n";if("05"==u)return n+"NULL\n";if("06"==u){var f=o(c,r),p=ce.asn1.ASN1Util.oidHexToInt(f),g=ce.asn1.x509.OID.oid2name(p),y=p.replace(/\./g," ");return""!=g?n+"ObjectIdentifier "+g+" ("+y+")\n":n+"ObjectIdentifier ("+y+")\n"}if("0a"==u)return n+"ENUMERATED "+parseInt(o(c,r))+"\n";if("0c"==u)return n+"UTF8String '"+_e(o(c,r))+"'\n";if("13"==u)return n+"PrintableString '"+_e(o(c,r))+"'\n";if("14"==u)return n+"TeletexString '"+_e(o(c,r))+"'\n";if("16"==u)return n+"IA5String '"+_e(o(c,r))+"'\n";if("17"==u)return n+"UTCTime "+_e(o(c,r))+"\n";if("18"==u)return n+"GeneralizedTime "+_e(o(c,r))+"\n";if("1a"==u)return n+"VisualString '"+_e(o(c,r))+"'\n";if("1e"==u)return n+"BMPString '"+Le(o(c,r))+"'\n";if("30"==u){if("3000"==c.substr(r,4))return n+"SEQUENCE {}\n";_=n+"SEQUENCE\n";var m=t;if((2==(w=a(c,r)).length||3==w.length)&&"06"==c.substr(w[0],2)&&"04"==c.substr(w[w.length-1],2)){g=i.oidname(o(c,w[0]));var v=JSON.parse(JSON.stringify(t));v.x509ExtName=g,m=v}for(var b=0;b31)&&128==(192&r)&&(31&r)==n}catch(e){return!1}},de.isASN1HEX=function(e){var t=de;if(e.length%2==1)return!1;var r=t.getVblen(e,0),n=e.substr(0,2),i=t.getL(e,0);return e.length-n.length-i.length==2*r},de.checkStrictDER=function(e,t,r,n,i){var o=de;if(void 0===r){if("string"!=typeof e)throw new Error("not hex string");if(e=e.toLowerCase(),!ce.lang.String.isHex(e))throw new Error("not hex string");r=e.length,i=(n=e.length/2)<128?1:Math.ceil(n.toString(16))+1}if(o.getL(e,t).length>2*i)throw new Error("L of TLV too long: idx="+t);var s=o.getVblen(e,t);if(s>n)throw new Error("value of L too long than hex: idx="+t);var a=o.getTLV(e,t),c=a.length-2-o.getL(e,t).length;if(c!==2*s)throw new Error("V string length and L's value not the same:"+c+"/"+2*s);if(0===t&&e.length!=a.length)throw new Error("total length and TLV length unmatch:"+e.length+"!="+a.length);var l=e.substr(t,2);if("02"===l){var u=o.getVidx(e,t);if("00"==e.substr(u,2)&&e.charCodeAt(u+2)<56)throw new Error("not least zeros for DER INTEGER")}if(32&parseInt(l,16)){for(var d=o.getVblen(e,t),h=0,f=o.getChildIdx(e,t),p=0;p=t?e:new Array(t-e.length+1).join(r)+e};function He(e,t){var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e,e.superclass=t.prototype,t.prototype.constructor==Object.prototype.constructor&&(t.prototype.constructor=t)}void 0!==ce&&ce||(t.KJUR=ce={}),void 0!==ce.crypto&&ce.crypto||(ce.crypto={}),ce.crypto.Util=new function(){this.DIGESTINFOHEAD={sha1:"3021300906052b0e03021a05000414",sha224:"302d300d06096086480165030402040500041c",sha256:"3031300d060960864801650304020105000420",sha384:"3041300d060960864801650304020205000430",sha512:"3051300d060960864801650304020305000440",md2:"3020300c06082a864886f70d020205000410",md5:"3020300c06082a864886f70d020505000410",ripemd160:"3021300906052b2403020105000414"},this.DEFAULTPROVIDER={md5:"cryptojs",sha1:"cryptojs",sha224:"cryptojs",sha256:"cryptojs",sha384:"cryptojs",sha512:"cryptojs",ripemd160:"cryptojs",hmacmd5:"cryptojs",hmacsha1:"cryptojs",hmacsha224:"cryptojs",hmacsha256:"cryptojs",hmacsha384:"cryptojs",hmacsha512:"cryptojs",hmacripemd160:"cryptojs",MD5withRSA:"cryptojs/jsrsa",SHA1withRSA:"cryptojs/jsrsa",SHA224withRSA:"cryptojs/jsrsa",SHA256withRSA:"cryptojs/jsrsa",SHA384withRSA:"cryptojs/jsrsa",SHA512withRSA:"cryptojs/jsrsa",RIPEMD160withRSA:"cryptojs/jsrsa",MD5withECDSA:"cryptojs/jsrsa",SHA1withECDSA:"cryptojs/jsrsa",SHA224withECDSA:"cryptojs/jsrsa",SHA256withECDSA:"cryptojs/jsrsa",SHA384withECDSA:"cryptojs/jsrsa",SHA512withECDSA:"cryptojs/jsrsa",RIPEMD160withECDSA:"cryptojs/jsrsa",SHA1withDSA:"cryptojs/jsrsa",SHA224withDSA:"cryptojs/jsrsa",SHA256withDSA:"cryptojs/jsrsa",MD5withRSAandMGF1:"cryptojs/jsrsa",SHAwithRSAandMGF1:"cryptojs/jsrsa",SHA1withRSAandMGF1:"cryptojs/jsrsa",SHA224withRSAandMGF1:"cryptojs/jsrsa",SHA256withRSAandMGF1:"cryptojs/jsrsa",SHA384withRSAandMGF1:"cryptojs/jsrsa",SHA512withRSAandMGF1:"cryptojs/jsrsa",RIPEMD160withRSAandMGF1:"cryptojs/jsrsa"},this.CRYPTOJSMESSAGEDIGESTNAME={md5:y.algo.MD5,sha1:y.algo.SHA1,sha224:y.algo.SHA224,sha256:y.algo.SHA256,sha384:y.algo.SHA384,sha512:y.algo.SHA512,ripemd160:y.algo.RIPEMD160},this.getDigestInfoHex=function(e,t){if(void 0===this.DIGESTINFOHEAD[t])throw"alg not supported in Util.DIGESTINFOHEAD: "+t;return this.DIGESTINFOHEAD[t]+e},this.getPaddedDigestInfoHex=function(e,t,r){var n=this.getDigestInfoHex(e,t),i=r/4;if(n.length+22>i)throw"key is too short for SigAlg: keylen="+r+","+t;for(var o="00"+n,s="",a=i-4-o.length,c=0;c=0)return!1;if(n.compareTo(r.ONE)<0||n.compareTo(o)>=0)return!1;var a=n.modInverse(o),c=e.multiply(a).mod(o),l=t.multiply(a).mod(o);return s.multiply(c).add(i.multiply(l)).getX().toBigInteger().mod(o).equals(t)},this.serializeSig=function(e,t){var r=e.toByteArraySigned(),n=t.toByteArraySigned(),i=[];return i.push(2),i.push(r.length),(i=i.concat(r)).push(2),i.push(n.length),(i=i.concat(n)).unshift(i.length),i.unshift(48),i},this.parseSig=function(e){var t;if(48!=e[0])throw new Error("Signature not a valid DERSequence");if(2!=e[t=2])throw new Error("First element in signature must be a DERInteger");var n=e.slice(t+2,t+2+e[t+1]);if(2!=e[t+=2+e[t+1]])throw new Error("Second element in signature must be a DERInteger");var i=e.slice(t+2,t+2+e[t+1]);return t+=2+e[t+1],{r:r.fromByteArrayUnsigned(n),s:r.fromByteArrayUnsigned(i)}},this.parseSigCompact=function(e){if(65!==e.length)throw"Signature has the wrong length";var t=e[0]-27;if(t<0||t>7)throw"Invalid signature type";var n=this.ecparams.n;return{r:r.fromByteArrayUnsigned(e.slice(1,33)).mod(n),s:r.fromByteArrayUnsigned(e.slice(33,65)).mod(n),i:t}},this.readPKCS5PrvKeyHex=function(e){if(!1===l(e))throw new Error("not ASN.1 hex string");var t,r,n;try{t=c(e,0,["[0]",0],"06"),r=c(e,0,[1],"04");try{n=c(e,0,["[1]",0],"03")}catch(e){}}catch(e){throw new Error("malformed PKCS#1/5 plain ECC private key")}if(this.curveName=s(t),void 0===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(n),this.setPrivateKeyHex(r),this.isPublic=!1},this.readPKCS8PrvKeyHex=function(e){if(!1===l(e))throw new t("not ASN.1 hex string");var r,n,i;try{c(e,0,[1,0],"06"),r=c(e,0,[1,1],"06"),n=c(e,0,[2,0,1],"04");try{i=c(e,0,[2,0,"[1]",0],"03")}catch(e){}}catch(e){throw new t("malformed PKCS#8 plain ECC private key")}if(this.curveName=s(r),void 0===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i),this.setPrivateKeyHex(n),this.isPublic=!1},this.readPKCS8PubKeyHex=function(e){if(!1===l(e))throw new t("not ASN.1 hex string");var r,n;try{c(e,0,[0,0],"06"),r=c(e,0,[0,1],"06"),n=c(e,0,[1],"03")}catch(e){throw new t("malformed PKCS#8 ECC public key")}if(this.curveName=s(r),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(n)},this.readCertPubKeyHex=function(e,r){if(!1===l(e))throw new t("not ASN.1 hex string");var n,i;try{n=c(e,0,[0,5,0,1],"06"),i=c(e,0,[0,5,1],"03")}catch(e){throw new t("malformed X.509 certificate ECC public key")}if(this.curveName=s(n),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i)},void 0!==e&&void 0!==e.curve&&(this.curveName=e.curve),void 0===this.curveName&&(this.curveName="secp256r1"),this.setNamedCurve(this.curveName),void 0!==e&&(void 0!==e.prv&&this.setPrivateKeyHex(e.prv),void 0!==e.pub&&this.setPublicKeyHex(e.pub))},ce.crypto.ECDSA.parseSigHex=function(e){var t=ce.crypto.ECDSA.parseSigHexInHexRS(e);return{r:new S(t.r,16),s:new S(t.s,16)}},ce.crypto.ECDSA.parseSigHexInHexRS=function(e){var t=de,r=t.getChildIdx,n=t.getV;if(t.checkStrictDER(e,0),"30"!=e.substr(0,2))throw new Error("signature is not a ASN.1 sequence");var i=r(e,0);if(2!=i.length)throw new Error("signature shall have two elements");var o=i[0],s=i[1];if("02"!=e.substr(o,2))throw new Error("1st item not ASN.1 integer");if("02"!=e.substr(s,2))throw new Error("2nd item not ASN.1 integer");return{r:n(e,o),s:n(e,s)}},ce.crypto.ECDSA.asn1SigToConcatSig=function(e){var t=ce.crypto.ECDSA.parseSigHexInHexRS(e),r=t.r,n=t.s;if("00"==r.substr(0,2)&&r.length%32==2&&(r=r.substr(2)),"00"==n.substr(0,2)&&n.length%32==2&&(n=n.substr(2)),r.length%32==30&&(r="00"+r),n.length%32==30&&(n="00"+n),r.length%32!=0)throw"unknown ECDSA sig r length error";if(n.length%32!=0)throw"unknown ECDSA sig s length error";return r+n},ce.crypto.ECDSA.concatSigToASN1Sig=function(e){if(e.length/2*8%128!=0)throw"unknown ECDSA concatinated r-s sig length error";var t=e.substr(0,e.length/2),r=e.substr(e.length/2);return ce.crypto.ECDSA.hexRSSigToASN1Sig(t,r)},ce.crypto.ECDSA.hexRSSigToASN1Sig=function(e,t){var r=new S(e,16),n=new S(t,16);return ce.crypto.ECDSA.biRSSigToASN1Sig(r,n)},ce.crypto.ECDSA.biRSSigToASN1Sig=function(e,t){var r=ce.asn1,n=new r.DERInteger({bigint:e}),i=new r.DERInteger({bigint:t});return new r.DERSequence({array:[n,i]}).getEncodedHex()},ce.crypto.ECDSA.getName=function(e){return"2b8104001f"===e?"secp192k1":"2a8648ce3d030107"===e?"secp256r1":"2b8104000a"===e?"secp256k1":"2b81040021"===e?"secp224r1":"2b81040022"===e?"secp384r1":-1!=="|secp256r1|NIST P-256|P-256|prime256v1|".indexOf(e)?"secp256r1":-1!=="|secp256k1|".indexOf(e)?"secp256k1":-1!=="|secp224r1|NIST P-224|P-224|".indexOf(e)?"secp224r1":-1!=="|secp384r1|NIST P-384|P-384|".indexOf(e)?"secp384r1":null},void 0!==ce&&ce||(t.KJUR=ce={}),void 0!==ce.crypto&&ce.crypto||(ce.crypto={}),ce.crypto.ECParameterDB=new function(){var e={},t={};function r(e){return new S(e,16)}this.getByName=function(r){var n=r;if(void 0!==t[n]&&(n=t[r]),void 0!==e[n])return e[n];throw"unregistered EC curve name: "+n},this.regist=function(n,i,o,s,a,c,l,u,d,h,f,p){e[n]={};var g=r(o),y=r(s),m=r(a),v=r(c),b=r(l),w=new se(g,y,m),_=w.decodePointHex("04"+u+d);e[n].name=n,e[n].keylen=i,e[n].curve=w,e[n].G=_,e[n].n=v,e[n].h=b,e[n].oid=f,e[n].info=p;for(var S=0;S=2*a)break}var d={};return d.keyhex=c.substr(0,2*i[e].keylen),d.ivhex=c.substr(2*i[e].keylen,2*i[e].ivlen),d},a=function(e,t,r,n){var o=y.enc.Base64.parse(e),s=y.enc.Hex.stringify(o);return(0,i[t].proc)(s,r,n)};return{version:"1.0.0",parsePKCS5PEM:function(e){return o(e)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(e,t,r){return s(e,t,r)},decryptKeyB64:function(e,t,r,n){return a(e,t,r,n)},getDecryptedKeyHex:function(e,t){var r=o(e),n=(r.type,r.cipher),i=r.ivsalt,c=r.data,l=s(n,t,i).keyhex;return a(c,n,l,i)},getEncryptedPKCS5PEMFromPrvKeyHex:function(e,t,r,n,o){var a="";if(void 0!==n&&null!=n||(n="AES-256-CBC"),void 0===i[n])throw new Error("KEYUTIL unsupported algorithm: "+n);void 0!==o&&null!=o||(o=function(e){var t=y.lib.WordArray.random(e);return y.enc.Hex.stringify(t)}(i[n].ivlen).toUpperCase());var c=function(e,t,r,n){return(0,i[t].eproc)(e,r,n)}(t,n,s(n,r,o).keyhex,o);return a="-----BEGIN "+e+" PRIVATE KEY-----\r\n",a+="Proc-Type: 4,ENCRYPTED\r\n",a+="DEK-Info: "+n+","+o+"\r\n",a+="\r\n",(a+=c.replace(/(.{64})/g,"$1\r\n"))+"\r\n-----END "+e+" PRIVATE KEY-----\r\n"},parseHexOfEncryptedPKCS8:function(e){var t=de,r=t.getChildIdx,n=t.getV,i={},o=r(e,0);if(2!=o.length)throw new Error("malformed format: SEQUENCE(0).items != 2: "+o.length);i.ciphertext=n(e,o[1]);var s=r(e,o[0]);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0.0).items != 2: "+s.length);if("2a864886f70d01050d"!=n(e,s[0]))throw new Error("this only supports pkcs5PBES2");var a=r(e,s[1]);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: "+a.length);var c=r(e,a[1]);if(2!=c.length)throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: "+c.length);if("2a864886f70d0307"!=n(e,c[0]))throw"this only supports TripleDES";i.encryptionSchemeAlg="TripleDES",i.encryptionSchemeIV=n(e,c[1]);var l=r(e,a[0]);if(2!=l.length)throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: "+l.length);if("2a864886f70d01050c"!=n(e,l[0]))throw new Error("this only supports pkcs5PBKDF2");var u=r(e,l[1]);if(u.length<2)throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+u.length);i.pbkdf2Salt=n(e,u[0]);var d=n(e,u[1]);try{i.pbkdf2Iter=parseInt(d,16)}catch(e){throw new Error("malformed format pbkdf2Iter: "+d)}return i},getPBKDF2KeyHexFromParam:function(e,t){var r=y.enc.Hex.parse(e.pbkdf2Salt),n=e.pbkdf2Iter,i=y.PBKDF2(t,r,{keySize:6,iterations:n});return y.enc.Hex.stringify(i)},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function(e,t){var r=xe(e,"ENCRYPTED PRIVATE KEY"),n=this.parseHexOfEncryptedPKCS8(r),i=We.getPBKDF2KeyHexFromParam(n,t),o={};o.ciphertext=y.enc.Hex.parse(n.ciphertext);var s=y.enc.Hex.parse(i),a=y.enc.Hex.parse(n.encryptionSchemeIV),c=y.TripleDES.decrypt(o,s,{iv:a});return y.enc.Hex.stringify(c)},getKeyFromEncryptedPKCS8PEM:function(e,t){var r=this._getPlainPKCS8HexFromEncryptedPKCS8PEM(e,t);return this.getKeyFromPlainPrivatePKCS8Hex(r)},parsePlainPrivatePKCS8Hex:function(e){var t=de,r=t.getChildIdx,n=t.getV,i={algparam:null};if("30"!=e.substr(0,2))throw new Error("malformed plain PKCS8 private key(code:001)");var o=r(e,0);if(o.length<3)throw new Error("malformed plain PKCS8 private key(code:002)");if("30"!=e.substr(o[1],2))throw new Error("malformed PKCS8 private key(code:003)");var s=r(e,o[1]);if(2!=s.length)throw new Error("malformed PKCS8 private key(code:004)");if("06"!=e.substr(s[0],2))throw new Error("malformed PKCS8 private key(code:005)");if(i.algoid=n(e,s[0]),"06"==e.substr(s[1],2)&&(i.algparam=n(e,s[1])),"04"!=e.substr(o[2],2))throw new Error("malformed PKCS8 private key(code:006)");return i.keyidx=t.getVidx(e,o[2]),i},getKeyFromPlainPrivatePKCS8PEM:function(e){var t=xe(e,"PRIVATE KEY");return this.getKeyFromPlainPrivatePKCS8Hex(t)},getKeyFromPlainPrivatePKCS8Hex:function(e){var t,r=this.parsePlainPrivatePKCS8Hex(e);if("2a864886f70d010101"==r.algoid)t=new ne;else if("2a8648ce380401"==r.algoid)t=new ce.crypto.DSA;else{if("2a8648ce3d0201"!=r.algoid)throw new Error("unsupported private key algorithm");t=new ce.crypto.ECDSA}return t.readPKCS8PrvKeyHex(e),t},_getKeyFromPublicPKCS8Hex:function(e){var t,r=de.getVbyList(e,0,[0,0],"06");if("2a864886f70d010101"===r)t=new ne;else if("2a8648ce380401"===r)t=new ce.crypto.DSA;else{if("2a8648ce3d0201"!==r)throw new Error("unsupported PKCS#8 public key hex");t=new ce.crypto.ECDSA}return t.readPKCS8PubKeyHex(e),t},parsePublicRawRSAKeyHex:function(e){var t=de,r=t.getChildIdx,n=t.getV,i={};if("30"!=e.substr(0,2))throw new Error("malformed RSA key(code:001)");var o=r(e,0);if(2!=o.length)throw new Error("malformed RSA key(code:002)");if("02"!=e.substr(o[0],2))throw new Error("malformed RSA key(code:003)");if(i.n=n(e,o[0]),"02"!=e.substr(o[1],2))throw new Error("malformed RSA key(code:004)");return i.e=n(e,o[1]),i},parsePublicPKCS8Hex:function(e){var t=de,r=t.getChildIdx,n=t.getV,i={algparam:null},o=r(e,0);if(2!=o.length)throw new Error("outer DERSequence shall have 2 elements: "+o.length);var s=o[0];if("30"!=e.substr(s,2))throw new Error("malformed PKCS8 public key(code:001)");var a=r(e,s);if(2!=a.length)throw new Error("malformed PKCS8 public key(code:002)");if("06"!=e.substr(a[0],2))throw new Error("malformed PKCS8 public key(code:003)");if(i.algoid=n(e,a[0]),"06"==e.substr(a[1],2)?i.algparam=n(e,a[1]):"30"==e.substr(a[1],2)&&(i.algparam={},i.algparam.p=t.getVbyList(e,a[1],[0],"02"),i.algparam.q=t.getVbyList(e,a[1],[1],"02"),i.algparam.g=t.getVbyList(e,a[1],[2],"02")),"03"!=e.substr(o[1],2))throw new Error("malformed PKCS8 public key(code:004)");return i.key=n(e,o[1]).substr(2),i}}}();function $e(e,t){for(var r="",n=t/4-e.length,i=0;i>24,(16711680&i)>>16,(65280&i)>>8,255&i])))),i+=1;return n}function Ke(e){for(var t in ce.crypto.Util.DIGESTINFOHEAD){var r=ce.crypto.Util.DIGESTINFOHEAD[t],n=r.length;if(e.substring(0,n)==r)return[t,e.substring(n)]}return[]}function Je(e){var t,r=de,n=r.getChildIdx,i=r.getV,o=r.getTLV,s=r.getVbyList,a=r.getVbyListEx,c=r.getTLVbyList,l=r.getTLVbyListEx,u=r.getIdxbyList,d=r.getIdxbyListEx,h=r.getVidx,f=r.getInt,p=r.oidname,g=r.hextooidstr,y=xe;try{t=ce.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV}catch(e){}this.HEX2STAG={"0c":"utf8",13:"prn",16:"ia5","1a":"vis","1e":"bmp"},this.hex=null,this.version=0,this.foffset=0,this.aExtInfo=null,this.getVersion=function(){if(null===this.hex||0!==this.version)return this.version;var e=c(this.hex,0,[0,0]);if("a0"==e.substr(0,2)){var t=c(e,0,[0]),r=f(t,0);if(r<0||21){var a=o(e,s[1]),c=this.getGeneralName(a);null!=c.uri&&(i.uri=c.uri)}if(s.length>2){var l=o(e,s[2]);"0101ff"==l&&(i.reqauth=!0),"010100"==l&&(i.reqauth=!1)}return i},this.getX500NameRule=function(e){for(var t=null,r=[],n=0;n0&&(e.ext=this.getExtParamArray()),e.sighex=this.getSignatureValueHex(),e},this.getExtParamArray=function(e){null==e&&-1!=d(this.hex,0,[0,"[3]"])&&(e=l(this.hex,0,[0,"[3]",0],"30"));for(var t=[],r=n(e,0),i=0;i2&&"04"===y.substr(g[1],2)))throw new Error("unsupported PKCS#1/5 hexadecimal key");(P=new a).readPKCS5PrvKeyHex(y)}return P}if("pkcs8prv"===r)return d.getKeyFromPlainPrivatePKCS8Hex(e);if("pkcs8pub"===r)return d._getKeyFromPublicPKCS8Hex(e);if("x509pub"===r)return Je.getPublicKeyFromCertHex(e);if(-1!=e.indexOf("-END CERTIFICATE-",0)||-1!=e.indexOf("-END X509 CERTIFICATE-",0)||-1!=e.indexOf("-END TRUSTED CERTIFICATE-",0))return Je.getPublicKeyFromCertPEM(e);if(-1!=e.indexOf("-END PUBLIC KEY-")){var v=xe(e,"PUBLIC KEY");return d._getKeyFromPublicPKCS8Hex(v)}if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var b=u(e,"RSA PRIVATE KEY");return d.getKey(b,null,"pkcs5prv")}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var w=o(n=u(e,"DSA PRIVATE KEY"),0,[1],"02"),_=o(n,0,[2],"02"),E=o(n,0,[3],"02"),A=o(n,0,[4],"02"),R=o(n,0,[5],"02");return(P=new c).setPrivate(new S(w,16),new S(_,16),new S(E,16),new S(A,16),new S(R,16)),P}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED"))return b=u(e,"EC PRIVATE KEY"),d.getKey(b,null,"pkcs5prv");if(-1!=e.indexOf("-END PRIVATE KEY-"))return d.getKeyFromPlainPrivatePKCS8PEM(e);if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var I=d.getDecryptedKeyHex(e,t),T=new ne;return T.readPKCS5PrvKeyHex(I),T}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var x,P=o(n=d.getDecryptedKeyHex(e,t),0,[1],"04"),C=o(n,0,[2,0],"06"),k=o(n,0,[3,0],"03").substr(2);if(void 0===ce.crypto.OID.oidhex2name[C])throw new Error("undefined OID(hex) in KJUR.crypto.OID: "+C);return(x=new a({curve:ce.crypto.OID.oidhex2name[C]})).setPublicKeyHex(k),x.setPrivateKeyHex(P),x.isPublic=!1,x}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED"))return w=o(n=d.getDecryptedKeyHex(e,t),0,[1],"02"),_=o(n,0,[2],"02"),E=o(n,0,[3],"02"),A=o(n,0,[4],"02"),R=o(n,0,[5],"02"),(P=new c).setPrivate(new S(w,16),new S(_,16),new S(E,16),new S(A,16),new S(R,16)),P;if(-1!=e.indexOf("-END ENCRYPTED PRIVATE KEY-"))return d.getKeyFromEncryptedPKCS8PEM(e,t);throw new Error("not supported argument")},We.generateKeypair=function(e,t){if("RSA"==e){var r=t;(s=new ne).generate(r,"10001"),s.isPrivate=!0,s.isPublic=!0;var n=new ne,i=s.n.toString(16),o=s.e.toString(16);return n.setPublic(i,o),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=s,a.pubKeyObj=n,a}if("EC"==e){var s,a,c=t,l=new ce.crypto.ECDSA({curve:c}).generateKeyPairHex();return(s=new ce.crypto.ECDSA({curve:c})).setPublicKeyHex(l.ecpubhex),s.setPrivateKeyHex(l.ecprvhex),s.isPrivate=!0,s.isPublic=!1,(n=new ce.crypto.ECDSA({curve:c})).setPublicKeyHex(l.ecpubhex),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=s,a.pubKeyObj=n,a}throw new Error("unknown algorithm: "+e)},We.getPEM=function(e,t,r,n,i,o){var s=ce,a=s.asn1,c=a.DERObjectIdentifier,l=a.DERInteger,u=a.ASN1Util.newObject,d=a.x509.SubjectPublicKeyInfo,h=s.crypto,f=h.DSA,p=h.ECDSA,g=ne;function m(e){return u({seq:[{int:0},{int:{bigint:e.n}},{int:e.e},{int:{bigint:e.d}},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.dmp1}},{int:{bigint:e.dmq1}},{int:{bigint:e.coeff}}]})}function v(e){return u({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a0",!0,{oid:{name:e.curveName}}]},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]})}function b(e){return u({seq:[{int:0},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}},{int:{bigint:e.y}},{int:{bigint:e.x}}]})}if((void 0!==g&&e instanceof g||void 0!==f&&e instanceof f||void 0!==p&&e instanceof p)&&1==e.isPublic&&(void 0===t||"PKCS8PUB"==t))return Te(E=new d(e).getEncodedHex(),"PUBLIC KEY");if("PKCS1PRV"==t&&void 0!==g&&e instanceof g&&(void 0===r||null==r)&&1==e.isPrivate)return Te(E=m(e).getEncodedHex(),"RSA PRIVATE KEY");if("PKCS1PRV"==t&&void 0!==p&&e instanceof p&&(void 0===r||null==r)&&1==e.isPrivate){var w=new c({name:e.curveName}).getEncodedHex(),_=v(e).getEncodedHex(),S="";return(S+=Te(w,"EC PARAMETERS"))+Te(_,"EC PRIVATE KEY")}if("PKCS1PRV"==t&&void 0!==f&&e instanceof f&&(void 0===r||null==r)&&1==e.isPrivate)return Te(E=b(e).getEncodedHex(),"DSA PRIVATE KEY");if("PKCS5PRV"==t&&void 0!==g&&e instanceof g&&void 0!==r&&null!=r&&1==e.isPrivate){var E=m(e).getEncodedHex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",E,r,n,o)}if("PKCS5PRV"==t&&void 0!==p&&e instanceof p&&void 0!==r&&null!=r&&1==e.isPrivate)return E=v(e).getEncodedHex(),void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",E,r,n,o);if("PKCS5PRV"==t&&void 0!==f&&e instanceof f&&void 0!==r&&null!=r&&1==e.isPrivate)return E=b(e).getEncodedHex(),void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",E,r,n,o);var A=function(e,t){var r=R(e,t);return new u({seq:[{seq:[{oid:{name:"pkcs5PBES2"}},{seq:[{seq:[{oid:{name:"pkcs5PBKDF2"}},{seq:[{octstr:{hex:r.pbkdf2Salt}},{int:r.pbkdf2Iter}]}]},{seq:[{oid:{name:"des-EDE3-CBC"}},{octstr:{hex:r.encryptionSchemeIV}}]}]}]},{octstr:{hex:r.ciphertext}}]}).getEncodedHex()},R=function(e,t){var r=y.lib.WordArray.random(8),n=y.lib.WordArray.random(8),i=y.PBKDF2(t,r,{keySize:6,iterations:100}),o=y.enc.Hex.parse(e),s=y.TripleDES.encrypt(o,i,{iv:n})+"",a={};return a.ciphertext=s,a.pbkdf2Salt=y.enc.Hex.stringify(r),a.pbkdf2Iter=100,a.encryptionSchemeAlg="DES-EDE3-CBC",a.encryptionSchemeIV=y.enc.Hex.stringify(n),a};if("PKCS8PRV"==t&&null!=g&&e instanceof g&&1==e.isPrivate){var I=m(e).getEncodedHex();return E=u({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:I}}]}).getEncodedHex(),void 0===r||null==r?Te(E,"PRIVATE KEY"):Te(_=A(E,r),"ENCRYPTED PRIVATE KEY")}if("PKCS8PRV"==t&&void 0!==p&&e instanceof p&&1==e.isPrivate)return I=new u({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]}).getEncodedHex(),E=u({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:e.curveName}}]},{octstr:{hex:I}}]}).getEncodedHex(),void 0===r||null==r?Te(E,"PRIVATE KEY"):Te(_=A(E,r),"ENCRYPTED PRIVATE KEY");if("PKCS8PRV"==t&&void 0!==f&&e instanceof f&&1==e.isPrivate)return I=new l({bigint:e.x}).getEncodedHex(),E=u({seq:[{int:0},{seq:[{oid:{name:"dsa"}},{seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]}]},{octstr:{hex:I}}]}).getEncodedHex(),void 0===r||null==r?Te(E,"PRIVATE KEY"):Te(_=A(E,r),"ENCRYPTED PRIVATE KEY");throw new Error("unsupported object nor format")},We.getKeyFromCSRPEM=function(e){var t=xe(e,"CERTIFICATE REQUEST");return We.getKeyFromCSRHex(t)},We.getKeyFromCSRHex=function(e){var t=We.parseCSRHex(e);return We.getKey(t.p8pubkeyhex,null,"pkcs8pub")},We.parseCSRHex=function(e){var t=de,r=t.getChildIdx,n=t.getTLV,i={},o=e;if("30"!=o.substr(0,2))throw new Error("malformed CSR(code:001)");var s=r(o,0);if(s.length<1)throw new Error("malformed CSR(code:002)");if("30"!=o.substr(s[0],2))throw new Error("malformed CSR(code:003)");var a=r(o,s[0]);if(a.length<3)throw new Error("malformed CSR(code:004)");return i.p8pubkeyhex=n(o,a[2]),i},We.getKeyID=function(e){var t=We,r=de;"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&(e=t.getKey(e));var n=xe(t.getPEM(e)),i=r.getIdxbyList(n,0,[1]),o=r.getV(n,i).substring(2);return ce.crypto.Util.hashHex(o,"sha1")},We.getJWKFromKey=function(e){var t={};if(e instanceof ne&&e.isPrivate)return t.kty="RSA",t.n=ve(e.n.toString(16)),t.e=ve(e.e.toString(16)),t.d=ve(e.d.toString(16)),t.p=ve(e.p.toString(16)),t.q=ve(e.q.toString(16)),t.dp=ve(e.dmp1.toString(16)),t.dq=ve(e.dmq1.toString(16)),t.qi=ve(e.coeff.toString(16)),t;if(e instanceof ne&&e.isPublic)return t.kty="RSA",t.n=ve(e.n.toString(16)),t.e=ve(e.e.toString(16)),t;if(e instanceof ce.crypto.ECDSA&&e.isPrivate){if("P-256"!==(n=e.getShortNISTPCurveName())&&"P-384"!==n)throw new Error("unsupported curve name for JWT: "+n);var r=e.getPublicKeyXYHex();return t.kty="EC",t.crv=n,t.x=ve(r.x),t.y=ve(r.y),t.d=ve(e.prvKeyHex),t}if(e instanceof ce.crypto.ECDSA&&e.isPublic){var n;if("P-256"!==(n=e.getShortNISTPCurveName())&&"P-384"!==n)throw new Error("unsupported curve name for JWT: "+n);return r=e.getPublicKeyXYHex(),t.kty="EC",t.crv=n,t.x=ve(r.x),t.y=ve(r.y),t}throw new Error("not supported key object")},ne.getPosArrayOfChildrenFromHex=function(e){return de.getChildIdx(e,0)},ne.getHexValueArrayOfChildrenFromHex=function(e){var t,r=de.getV,n=r(e,(t=ne.getPosArrayOfChildrenFromHex(e))[0]),i=r(e,t[1]),o=r(e,t[2]),s=r(e,t[3]),a=r(e,t[4]),c=r(e,t[5]),l=r(e,t[6]),u=r(e,t[7]),d=r(e,t[8]);return(t=new Array).push(n,i,o,s,a,c,l,u,d),t},ne.prototype.readPrivateKeyFromPEMString=function(e){var t=xe(e),r=ne.getHexValueArrayOfChildrenFromHex(t);this.setPrivateEx(r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8])},ne.prototype.readPKCS5PrvKeyHex=function(e){var t=ne.getHexValueArrayOfChildrenFromHex(e);this.setPrivateEx(t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])},ne.prototype.readPKCS8PrvKeyHex=function(e){var t,r,n,i,o,s,a,c,l=de,u=l.getVbyListEx;if(!1===l.isASN1HEX(e))throw new Error("not ASN.1 hex string");try{t=u(e,0,[2,0,1],"02"),r=u(e,0,[2,0,2],"02"),n=u(e,0,[2,0,3],"02"),i=u(e,0,[2,0,4],"02"),o=u(e,0,[2,0,5],"02"),s=u(e,0,[2,0,6],"02"),a=u(e,0,[2,0,7],"02"),c=u(e,0,[2,0,8],"02")}catch(e){throw new Error("malformed PKCS#8 plain RSA private key")}this.setPrivateEx(t,r,n,i,o,s,a,c)},ne.prototype.readPKCS5PubKeyHex=function(e){var t=de,r=t.getV;if(!1===t.isASN1HEX(e))throw new Error("keyHex is not ASN.1 hex string");var n=t.getChildIdx(e,0);if(2!==n.length||"02"!==e.substr(n[0],2)||"02"!==e.substr(n[1],2))throw new Error("wrong hex for PKCS#5 public key");var i=r(e,n[0]),o=r(e,n[1]);this.setPublic(i,o)},ne.prototype.readPKCS8PubKeyHex=function(e){var t=de;if(!1===t.isASN1HEX(e))throw new Error("not ASN.1 hex string");if("06092a864886f70d010101"!==t.getTLVbyListEx(e,0,[0,0]))throw new Error("not PKCS8 RSA public key");var r=t.getTLVbyListEx(e,0,[1,0]);this.readPKCS5PubKeyHex(r)},ne.prototype.readCertPubKeyHex=function(e,t){var r,n;(r=new Je).readCertHex(e),n=r.getPublicKeyHex(),this.readPKCS8PubKeyHex(n)},new RegExp("[^0-9a-f]","gi"),ne.prototype.sign=function(e,t){var r=function(e){return ce.crypto.Util.hashString(e,t)}(e);return this.signWithMessageHash(r,t)},ne.prototype.signWithMessageHash=function(e,t){var r=te(ce.crypto.Util.getPaddedDigestInfoHex(e,t,this.n.bitLength()),16);return $e(this.doPrivate(r).toString(16),this.n.bitLength())},ne.prototype.signPSS=function(e,t,r){var n=function(e){return ce.crypto.Util.hashHex(e,t)}(Ee(e));return void 0===r&&(r=-1),this.signWithMessageHashPSS(n,t,r)},ne.prototype.signWithMessageHashPSS=function(e,t,r){var n,i=Se(e),o=i.length,s=this.n.bitLength()-1,a=Math.ceil(s/8),c=function(e){return ce.crypto.Util.hashHex(e,t)};if(-1===r||void 0===r)r=o;else if(-2===r)r=a-o-2;else if(r<-2)throw new Error("invalid salt length");if(a0&&(l=new Array(r),(new ee).nextBytes(l),l=String.fromCharCode.apply(String,l));var u=Se(c(Ee("\0\0\0\0\0\0\0\0"+i+l))),d=[];for(n=0;n>8*a-s&255;for(p[0]&=~g,n=0;nn)return!1;var i=this.doPublic(r).toString(16);if(i.length+3!=n/4)return!1;var o=Ke(i.replace(/^1f+00/,""));if(0==o.length)return!1;var s=o[0];return o[1]==function(e){return ce.crypto.Util.hashString(e,s)}(e)},ne.prototype.verifyWithMessageHash=function(e,t){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var r=te(t,16);if(r.bitLength()>this.n.bitLength())return 0;var n=Ke(this.doPublic(r).toString(16).replace(/^1f+00/,""));return 0!=n.length&&(n[0],n[1]==e)},ne.prototype.verifyPSS=function(e,t,r,n){var i=function(e){return ce.crypto.Util.hashHex(e,r)}(Ee(e));return void 0===n&&(n=-1),this.verifyWithMessageHashPSS(i,t,r,n)},ne.prototype.verifyWithMessageHashPSS=function(e,t,r,n){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var i,o=new S(t,16),s=function(e){return ce.crypto.Util.hashHex(e,r)},a=Se(e),c=a.length,l=this.n.bitLength()-1,u=Math.ceil(l/8);if(-1===n||void 0===n)n=c;else if(-2===n)n=u-c-2;else if(n<-2)throw new Error("invalid salt length");if(u>8*u-l&255;if(h.charCodeAt(0)&p)throw new Error("bits beyond keysize not zero");var g=Ve(f,h.length,s),y=[];for(i=0;i0&&-1==(":"+r.join(":")+":").indexOf(":"+m+":"))throw"algorithm '"+m+"' not accepted in the list";if("none"!=m&&null===t)throw"key shall be specified to verify.";if("string"==typeof t&&-1!=t.indexOf("-----BEGIN ")&&(t=We.getKey(t)),!("RS"!=h&&"PS"!=h||t instanceof n))throw"key shall be a RSAKey obj for RS* and PS* algs";if("ES"==h&&!(t instanceof c))throw"key shall be a ECDSA obj for ES* algs";var v=null;if(void 0===o.jwsalg2sigalg[y.alg])throw"unsupported alg name: "+m;if("none"==(v=o.jwsalg2sigalg[m]))throw"not supported";if("Hmac"==v.substr(0,4)){if(void 0===t)throw"hexadecimal key shall be specified for HMAC";var b=new l({alg:v,pass:t});return b.updateString(p),g==b.doFinal()}if(-1!=v.indexOf("withECDSA")){var w,_=null;try{_=c.concatSigToASN1Sig(g)}catch(e){return!1}return(w=new u({alg:v})).init(t),w.updateString(p),w.verify(_)}return(w=new u({alg:v})).init(t),w.updateString(p),w.verify(g)},ce.jws.JWS.parse=function(e){var t,r,n,i=e.split("."),o={};if(2!=i.length&&3!=i.length)throw"malformed sJWS: wrong number of '.' splitted elements";return t=i[0],r=i[1],3==i.length&&(n=i[2]),o.headerObj=ce.jws.JWS.readSafeJSONString(ue(t)),o.payloadObj=ce.jws.JWS.readSafeJSONString(ue(r)),o.headerPP=JSON.stringify(o.headerObj,null," "),null==o.payloadObj?o.payloadPP=ue(r):o.payloadPP=JSON.stringify(o.payloadObj,null," "),void 0!==n&&(o.sigHex=be(n)),o},ce.jws.JWS.verifyJWT=function(e,t,r){var n=ce.jws,i=n.JWS,o=i.readSafeJSONString,s=i.inArray,a=i.includedArray,c=e.split("."),l=c[0],u=c[1],d=(be(c[2]),o(ue(l))),h=o(ue(u));if(void 0===d.alg)return!1;if(void 0===r.alg)throw"acceptField.alg shall be specified";if(!s(d.alg,r.alg))return!1;if(void 0!==h.iss&&"object"===f(r.iss)&&!s(h.iss,r.iss))return!1;if(void 0!==h.sub&&"object"===f(r.sub)&&!s(h.sub,r.sub))return!1;if(void 0!==h.aud&&"object"===f(r.aud))if("string"==typeof h.aud){if(!s(h.aud,r.aud))return!1}else if("object"==f(h.aud)&&!a(h.aud,r.aud))return!1;var p=n.IntDate.getNow();return void 0!==r.verifyAt&&"number"==typeof r.verifyAt&&(p=r.verifyAt),void 0!==r.gracePeriod&&"number"==typeof r.gracePeriod||(r.gracePeriod=0),!(void 0!==h.exp&&"number"==typeof h.exp&&h.exp+r.gracePeriodt.length&&(r=t.length);for(var n=0;n=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function p(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return H(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return W(e).length;default:if(n)return H(e).length;t=(""+t).toLowerCase(),n=!0}}function g(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,r);case"utf8":case"utf-8":return I(this,t,r);case"ascii":return x(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return R(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function y(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function m(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=c.from(t,n)),c.isBuffer(t))return 0===t.length?-1:v(e,t,r,n,i);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):v(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function v(e,t,r,n,i){var o,s=1,a=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){var u=-1;for(o=r;oa&&(r=a-c),o=r;o>=0;o--){for(var d=!0,h=0;hi&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function R(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function I(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:l>223?3:l>191?2:1;if(i+d<=r)switch(d){case 1:l<128&&(u=l);break;case 2:128==(192&(o=e[i+1]))&&(c=(31&l)<<6|63&o)>127&&(u=c);break;case 3:o=e[i+1],s=e[i+2],128==(192&o)&&128==(192&s)&&(c=(15&l)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(u=c);break;case 4:o=e[i+1],s=e[i+2],a=e[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(c=(15&l)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(u=c)}null===u?(u=65533,d=1):u>65535&&(u-=65536,n.push(u>>>10&1023|55296),u=56320|1023&u),n.push(u),i+=d}return function(e){var t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);for(var r="",n=0;n0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),""},c.prototype.compare=function(e,t,r,n,i){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0),a=Math.min(o,s),l=this.slice(n,i),u=e.slice(t,r),d=0;di)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return b(this,e,t,r);case"utf8":case"utf-8":return w(this,e,t,r);case"ascii":return _(this,e,t,r);case"latin1":case"binary":return S(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var T=4096;function x(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function F(e,t,r,n,i,o){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function N(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);i>>8*(n?i:1-i)}function D(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-r,4);i>>8*(n?i:3-i)&255}function L(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,o){return o||L(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function j(e,t,r,n,o){return o||L(e,0,r,8),i.write(e,t,r,n,52,8),r+8}c.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(i*=256);)n+=this[e+--t]*i;return n},c.prototype.readUInt8=function(e,t){return t||O(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||O(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||O(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||O(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},c.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||O(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},c.prototype.readInt8=function(e,t){return t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||O(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){t||O(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||O(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||O(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||O(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||O(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,r,n){e=+e,t|=0,r|=0,n||F(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+r},c.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):D(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);F(this,e,t,r,i-1,-i)}var o=0,s=1,a=0;for(this[t]=255&e;++o=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s|0)-a&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):D(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return j(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3||!c.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function W(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(M,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function $(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}}).call(this,r(29))},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){"use strict";t.byteLength=function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,n=c(e),s=n[0],a=n[1],l=new o(function(e,t,r){return 3*(t+r)/4-r}(0,s,a)),u=0,d=a>0?s-4:s;for(r=0;r>16&255,l[u++]=t>>8&255,l[u++]=255&t;return 2===a&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,l[u++]=255&t),1===a&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t),l},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],s=16383,a=0,c=r-i;ac?c:a+s));return 1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)n[a]=s[a],i[s.charCodeAt(a)]=a;function c(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function l(e,t,r){for(var i,o,s=[],a=t;a>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,r,n,i){var o,s,a=8*i-n-1,c=(1<>1,u=-7,d=r?i-1:0,h=r?-1:1,f=e[t+d];for(d+=h,o=f&(1<<-u)-1,f>>=-u,u+=a;u>0;o=256*o+e[t+d],d+=h,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=n;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),o-=l}return(f?-1:1)*s*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var s,a,c,l=8*o-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(s++,c/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(t*c-1)*Math.pow(2,i),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),s=0));i>=8;e[r+f]=255&a,f+=p,a/=256,i-=8);for(s=s<0;e[r+f]=255&s,f+=p,s/=256,l-=8);e[r+f-p]|=128*g}},function(e,t){var r={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.jws,r=e.KeyUtil,i=e.X509,o=e.crypto,s=e.hextob64u,a=e.b64tohex,c=e.AllowedSigningAlgs;return function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.parseJwt=function e(r){n.Log.debug("JoseUtil.parseJwt");try{var i=t.JWS.parse(r);return{header:i.headerObj,payload:i.payloadObj}}catch(e){n.Log.error(e)}},e.validateJwt=function(t,o,s,c,l,u,d){n.Log.debug("JoseUtil.validateJwt");try{if("RSA"===o.kty)if(o.e&&o.n)o=r.getKey(o);else{if(!o.x5c||!o.x5c.length)return n.Log.error("JoseUtil.validateJwt: RSA key missing key material",o),Promise.reject(new Error("RSA key missing key material"));var h=a(o.x5c[0]);o=i.getPublicKeyFromCertHex(h)}else{if("EC"!==o.kty)return n.Log.error("JoseUtil.validateJwt: Unsupported key type",o&&o.kty),Promise.reject(new Error(o.kty));if(!(o.crv&&o.x&&o.y))return n.Log.error("JoseUtil.validateJwt: EC key missing key material",o),Promise.reject(new Error("EC key missing key material"));o=r.getKey(o)}return e._validateJwt(t,o,s,c,l,u,d)}catch(e){return n.Log.error(e&&e.message||e),Promise.reject("JWT validation failed")}},e.validateJwtAttributes=function(t,r,i,o,s,a){o||(o=0),s||(s=parseInt(Date.now()/1e3));var c=e.parseJwt(t).payload;if(!c.iss)return n.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(c.iss!==r)return n.Log.error("JoseUtil._validateJwt: Invalid issuer in token",c.iss),Promise.reject(new Error("Invalid issuer in token: "+c.iss));if(!c.aud)return n.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(c.aud===i||Array.isArray(c.aud)&&c.aud.indexOf(i)>=0))return n.Log.error("JoseUtil._validateJwt: Invalid audience in token",c.aud),Promise.reject(new Error("Invalid audience in token: "+c.aud));if(c.azp&&c.azp!==i)return n.Log.error("JoseUtil._validateJwt: Invalid azp in token",c.azp),Promise.reject(new Error("Invalid azp in token: "+c.azp));if(!a){var l=s+o,u=s-o;if(!c.iat)return n.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(l1&&void 0!==arguments[1]?arguments[1]:"#";!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var n=i.UrlUtility.parseUrlFragment(t,r);this.error=n.error,this.error_description=n.error_description,this.error_uri=n.error_uri,this.code=n.code,this.state=n.state,this.id_token=n.id_token,this.session_state=n.session_state,this.access_token=n.access_token,this.token_type=n.token_type,this.scope=n.scope,this.profile=void 0,this.expires_in=n.expires_in}return n(e,[{key:"expires_in",get:function(){if(this.expires_at){var e=parseInt(Date.now()/1e3);return this.expires_at-e}},set:function(e){var t=parseInt(e);if("number"==typeof t&&t>0){var r=parseInt(Date.now()/1e3);this.expires_at=r+t}}},{key:"expired",get:function(){var e=this.expires_in;if(void 0!==e)return e<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf("openid")>=0||!!this.id_token}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignoutRequest=void 0;var n=r(0),i=r(3),o=r(9);t.SignoutRequest=function e(t){var r=t.url,s=t.id_token_hint,a=t.post_logout_redirect_uri,c=t.data,l=t.extraQueryParams,u=t.request_type;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!r)throw n.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var d in s&&(r=i.UrlUtility.addQueryParam(r,"id_token_hint",s)),a&&(r=i.UrlUtility.addQueryParam(r,"post_logout_redirect_uri",a),c&&(this.state=new o.State({data:c,request_type:u}),r=i.UrlUtility.addQueryParam(r,"state",this.state.id))),l)r=i.UrlUtility.addQueryParam(r,d,l[d]);this.url=r}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignoutResponse=void 0;var n=r(3);t.SignoutResponse=function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var r=n.UrlUtility.parseUrlFragment(t,"?");this.error=r.error,this.error_description=r.error_description,this.error_uri=r.error_uri,this.state=r.state}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InMemoryWebStorage=void 0;var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:l.SilentRenewService,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:u.SessionMonitor,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:h.TokenRevocationClient,d=arguments.length>4&&void 0!==arguments[4]?arguments[4]:f.TokenClient,g=arguments.length>5&&void 0!==arguments[5]?arguments[5]:p.JoseUtil;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,t),r instanceof s.UserManagerSettings||(r=new s.UserManagerSettings(r));var y=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r));return y._events=new c.UserManagerEvents(r),y._silentRenewService=new n(y),y.settings.automaticSilentRenew&&(i.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),y.startSilentRenew()),y.settings.monitorSession&&(i.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),y._sessionMonitor=new o(y)),y._tokenRevocationClient=new a(y._settings),y._tokenClient=new d(y._settings),y._joseUtil=g,y}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.getUser=function(){var e=this;return this._loadUser().then((function(t){return t?(i.Log.info("UserManager.getUser: user loaded"),e._events.load(t,!1),t):(i.Log.info("UserManager.getUser: user not found in storage"),null)}))},t.prototype.removeUser=function(){var e=this;return this.storeUser(null).then((function(){i.Log.info("UserManager.removeUser: user removed from storage"),e._events.unload()}))},t.prototype.signinRedirect=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type="si:r";var t={useReplaceToNavigate:e.useReplaceToNavigate};return this._signinStart(e,this._redirectNavigator,t).then((function(){i.Log.info("UserManager.signinRedirect: successful")}))},t.prototype.signinRedirectCallback=function(e){return this._signinEnd(e||this._redirectNavigator.url).then((function(e){return e.profile&&e.profile.sub?i.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinRedirectCallback: no sub"),e}))},t.prototype.signinPopup=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type="si:p";var t=e.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return t?(e.redirect_uri=t,e.display="popup",this._signin(e,this._popupNavigator,{startUrl:t,popupWindowFeatures:e.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:e.popupWindowTarget||this.settings.popupWindowTarget}).then((function(e){return e&&(e.profile&&e.profile.sub?i.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinPopup: no sub")),e}))):(i.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},t.prototype.signinPopupCallback=function(e){return this._signinCallback(e,this._popupNavigator).then((function(e){return e&&(e.profile&&e.profile.sub?i.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinPopupCallback: no sub")),e})).catch((function(e){i.Log.error(e.message)}))},t.prototype.signinSilent=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=Object.assign({},t),this._loadUser().then((function(r){return r&&r.refresh_token?(t.refresh_token=r.refresh_token,e._useRefreshToken(t)):(t.request_type="si:s",t.id_token_hint=t.id_token_hint||e.settings.includeIdTokenInSilentRenew&&r&&r.id_token,r&&e._settings.validateSubOnSilentRenew&&(i.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",r.profile.sub),t.current_sub=r.profile.sub),e._signinSilentIframe(t))}))},t.prototype._useRefreshToken=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this._tokenClient.exchangeRefreshToken(t).then((function(t){return t?t.access_token?e._loadUser().then((function(r){if(r){var n=Promise.resolve();return t.id_token&&(n=e._validateIdTokenFromTokenRefreshToken(r.profile,t.id_token)),n.then((function(){return i.Log.debug("UserManager._useRefreshToken: refresh token response success"),r.id_token=t.id_token||r.id_token,r.access_token=t.access_token,r.refresh_token=t.refresh_token||r.refresh_token,r.expires_in=t.expires_in,e.storeUser(r).then((function(){return e._events.load(r),r}))}))}return null})):(i.Log.error("UserManager._useRefreshToken: No access token returned from token endpoint"),Promise.reject("No access token returned from token endpoint")):(i.Log.error("UserManager._useRefreshToken: No response returned from token endpoint"),Promise.reject("No response returned from token endpoint"))}))},t.prototype._validateIdTokenFromTokenRefreshToken=function(e,t){var r=this;return this._metadataService.getIssuer().then((function(n){return r.settings.getEpochTime().then((function(o){return r._joseUtil.validateJwtAttributes(t,n,r._settings.client_id,r._settings.clockSkew,o).then((function(t){return t?t.sub!==e.sub?(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: sub in id_token does not match current sub"),Promise.reject(new Error("sub in id_token does not match current sub"))):t.auth_time&&t.auth_time!==e.auth_time?(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: auth_time in id_token does not match original auth_time"),Promise.reject(new Error("auth_time in id_token does not match original auth_time"))):t.azp&&t.azp!==e.azp?(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp in id_token does not match original azp"),Promise.reject(new Error("azp in id_token does not match original azp"))):!t.azp&&e.azp?(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp not in id_token, but present in original id_token"),Promise.reject(new Error("azp not in id_token, but present in original id_token"))):void 0:(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token"),Promise.reject(new Error("Failed to validate id_token")))}))}))}))},t.prototype._signinSilentIframe=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return t?(e.redirect_uri=t,e.prompt=e.prompt||"none",this._signin(e,this._iframeNavigator,{startUrl:t,silentRequestTimeout:e.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(e){return e&&(e.profile&&e.profile.sub?i.Log.info("UserManager.signinSilent: successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinSilent: no sub")),e}))):(i.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},t.prototype.signinSilentCallback=function(e){return this._signinCallback(e,this._iframeNavigator).then((function(e){return e&&(e.profile&&e.profile.sub?i.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinSilentCallback: no sub")),e}))},t.prototype.signinCallback=function(e){var t=this;return this.readSigninResponseState(e).then((function(r){var n=r.state;return r.response,"si:r"===n.request_type?t.signinRedirectCallback(e):"si:p"===n.request_type?t.signinPopupCallback(e):"si:s"===n.request_type?t.signinSilentCallback(e):Promise.reject(new Error("invalid response_type in state"))}))},t.prototype.signoutCallback=function(e,t){var r=this;return this.readSignoutResponseState(e).then((function(n){var i=n.state,o=n.response;return i?"so:r"===i.request_type?r.signoutRedirectCallback(e):"so:p"===i.request_type?r.signoutPopupCallback(e,t):Promise.reject(new Error("invalid response_type in state")):o}))},t.prototype.querySessionStatus=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(t=Object.assign({},t)).request_type="si:s";var r=t.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return r?(t.redirect_uri=r,t.prompt="none",t.response_type=t.response_type||this.settings.query_status_response_type,t.scope=t.scope||"openid",t.skipUserInfo=!0,this._signinStart(t,this._iframeNavigator,{startUrl:r,silentRequestTimeout:t.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(t){return e.processSigninResponse(t.url).then((function(e){if(i.Log.debug("UserManager.querySessionStatus: got signin response"),e.session_state&&e.profile.sub)return i.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",e.profile.sub),{session_state:e.session_state,sub:e.profile.sub,sid:e.profile.sid};i.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(t){if(t.session_state&&e.settings.monitorAnonymousSession&&("login_required"==t.message||"consent_required"==t.message||"interaction_required"==t.message||"account_selection_required"==t.message))return i.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:t.session_state};throw t}))}))):(i.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},t.prototype._signin=function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this._signinStart(e,t,n).then((function(t){return r._signinEnd(t.url,e)}))},t.prototype._signinStart=function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return t.prepare(n).then((function(t){return i.Log.debug("UserManager._signinStart: got navigator window handle"),r.createSigninRequest(e).then((function(e){return i.Log.debug("UserManager._signinStart: got signin request"),n.url=e.url,n.id=e.state.id,t.navigate(n)})).catch((function(e){throw t.close&&(i.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),t.close()),e}))}))},t.prototype._signinEnd=function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.processSigninResponse(e).then((function(e){i.Log.debug("UserManager._signinEnd: got signin response");var n=new a.User(e);if(r.current_sub){if(r.current_sub!==n.profile.sub)return i.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",n.profile.sub),Promise.reject(new Error("login_required"));i.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return t.storeUser(n).then((function(){return i.Log.debug("UserManager._signinEnd: user stored"),t._events.load(n),n}))}))},t.prototype._signinCallback=function(e,t){i.Log.debug("UserManager._signinCallback");var r="query"===this._settings.response_mode||!this._settings.response_mode&&d.SigninRequest.isCode(this._settings.response_type)?"?":"#";return t.callback(e,void 0,r)},t.prototype.signoutRedirect=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type="so:r";var t=e.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;t&&(e.post_logout_redirect_uri=t);var r={useReplaceToNavigate:e.useReplaceToNavigate};return this._signoutStart(e,this._redirectNavigator,r).then((function(){i.Log.info("UserManager.signoutRedirect: successful")}))},t.prototype.signoutRedirectCallback=function(e){return this._signoutEnd(e||this._redirectNavigator.url).then((function(e){return i.Log.info("UserManager.signoutRedirectCallback: successful"),e}))},t.prototype.signoutPopup=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type="so:p";var t=e.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return e.post_logout_redirect_uri=t,e.display="popup",e.post_logout_redirect_uri&&(e.state=e.state||{}),this._signout(e,this._popupNavigator,{startUrl:t,popupWindowFeatures:e.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:e.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){i.Log.info("UserManager.signoutPopup: successful")}))},t.prototype.signoutPopupCallback=function(e,t){return void 0===t&&"boolean"==typeof e&&(t=e,e=null),this._popupNavigator.callback(e,t,"?").then((function(){i.Log.info("UserManager.signoutPopupCallback: successful")}))},t.prototype._signout=function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this._signoutStart(e,t,n).then((function(e){return r._signoutEnd(e.url)}))},t.prototype._signoutStart=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return arguments[1].prepare(r).then((function(n){return i.Log.debug("UserManager._signoutStart: got navigator window handle"),t._loadUser().then((function(o){return i.Log.debug("UserManager._signoutStart: loaded current user from storage"),(t._settings.revokeAccessTokenOnSignout?t._revokeInternal(o):Promise.resolve()).then((function(){var s=e.id_token_hint||o&&o.id_token;return s&&(i.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),e.id_token_hint=s),t.removeUser().then((function(){return i.Log.debug("UserManager._signoutStart: user removed, creating signout request"),t.createSignoutRequest(e).then((function(e){return i.Log.debug("UserManager._signoutStart: got signout request"),r.url=e.url,e.state&&(r.id=e.state.id),n.navigate(r)}))}))}))})).catch((function(e){throw n.close&&(i.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),n.close()),e}))}))},t.prototype._signoutEnd=function(e){return this.processSignoutResponse(e).then((function(e){return i.Log.debug("UserManager._signoutEnd: got signout response"),e}))},t.prototype.revokeAccessToken=function(){var e=this;return this._loadUser().then((function(t){return e._revokeInternal(t,!0).then((function(r){if(r)return i.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),t.access_token=null,t.refresh_token=null,t.expires_at=null,t.token_type=null,e.storeUser(t).then((function(){i.Log.debug("UserManager.revokeAccessToken: user stored"),e._events.load(t)}))}))})).then((function(){i.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},t.prototype._revokeInternal=function(e,t){var r=this;if(e){var n=e.access_token,o=e.refresh_token;return this._revokeAccessTokenInternal(n,t).then((function(e){return r._revokeRefreshTokenInternal(o,t).then((function(t){return e||t||i.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),e||t}))}))}return Promise.resolve(!1)},t.prototype._revokeAccessTokenInternal=function(e,t){return!e||e.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(e,t).then((function(){return!0}))},t.prototype._revokeRefreshTokenInternal=function(e,t){return e?this._tokenRevocationClient.revoke(e,t,"refresh_token").then((function(){return!0})):Promise.resolve(!1)},t.prototype.startSilentRenew=function(){this._silentRenewService.start()},t.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},t.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then((function(e){return e?(i.Log.debug("UserManager._loadUser: user storageString loaded"),a.User.fromStorageString(e)):(i.Log.debug("UserManager._loadUser: no user storageString"),null)}))},t.prototype.storeUser=function(e){if(e){i.Log.debug("UserManager.storeUser: storing user");var t=e.toStorageString();return this._userStore.set(this._userStoreKey,t)}return i.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},n(t,[{key:"_redirectNavigator",get:function(){return this.settings.redirectNavigator}},{key:"_popupNavigator",get:function(){return this.settings.popupNavigator}},{key:"_iframeNavigator",get:function(){return this.settings.iframeNavigator}},{key:"_userStore",get:function(){return this.settings.userStore}},{key:"events",get:function(){return this._events}},{key:"_userStoreKey",get:function(){return"user:"+this.settings.authority+":"+this.settings.client_id}}]),t}(o.OidcClient)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserManagerSettings=void 0;var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=r.popup_redirect_uri,i=r.popup_post_logout_redirect_uri,d=r.popupWindowFeatures,h=r.popupWindowTarget,f=r.silent_redirect_uri,p=r.silentRequestTimeout,g=r.automaticSilentRenew,y=void 0!==g&&g,m=r.validateSubOnSilentRenew,v=void 0!==m&&m,b=r.includeIdTokenInSilentRenew,w=void 0===b||b,_=r.monitorSession,S=void 0===_||_,E=r.monitorAnonymousSession,A=void 0!==E&&E,R=r.checkSessionInterval,I=void 0===R?2e3:R,T=r.stopCheckSessionOnError,x=void 0===T||T,P=r.query_status_response_type,C=r.revokeAccessTokenOnSignout,k=void 0!==C&&C,O=r.accessTokenExpiringNotificationTime,F=void 0===O?60:O,N=r.redirectNavigator,D=void 0===N?new o.RedirectNavigator:N,L=r.popupNavigator,U=void 0===L?new s.PopupNavigator:L,j=r.iframeNavigator,M=void 0===j?new a.IFrameNavigator:j,B=r.userStore,H=void 0===B?new c.WebStorageStateStore({store:l.Global.sessionStorage}):B;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var W=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,arguments[0]));return W._popup_redirect_uri=n,W._popup_post_logout_redirect_uri=i,W._popupWindowFeatures=d,W._popupWindowTarget=h,W._silent_redirect_uri=f,W._silentRequestTimeout=p,W._automaticSilentRenew=y,W._validateSubOnSilentRenew=v,W._includeIdTokenInSilentRenew=w,W._accessTokenExpiringNotificationTime=F,W._monitorSession=S,W._monitorAnonymousSession=A,W._checkSessionInterval=I,W._stopCheckSessionOnError=x,P?W._query_status_response_type=P:arguments[0]&&arguments[0].response_type?W._query_status_response_type=u.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":W._query_status_response_type="id_token",W._revokeAccessTokenOnSignout=k,W._redirectNavigator=D,W._popupNavigator=U,W._iframeNavigator=M,W._userStore=H,W}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),n(t,[{key:"popup_redirect_uri",get:function(){return this._popup_redirect_uri}},{key:"popup_post_logout_redirect_uri",get:function(){return this._popup_post_logout_redirect_uri}},{key:"popupWindowFeatures",get:function(){return this._popupWindowFeatures}},{key:"popupWindowTarget",get:function(){return this._popupWindowTarget}},{key:"silent_redirect_uri",get:function(){return this._silent_redirect_uri}},{key:"silentRequestTimeout",get:function(){return this._silentRequestTimeout}},{key:"automaticSilentRenew",get:function(){return this._automaticSilentRenew}},{key:"validateSubOnSilentRenew",get:function(){return this._validateSubOnSilentRenew}},{key:"includeIdTokenInSilentRenew",get:function(){return this._includeIdTokenInSilentRenew}},{key:"accessTokenExpiringNotificationTime",get:function(){return this._accessTokenExpiringNotificationTime}},{key:"monitorSession",get:function(){return this._monitorSession}},{key:"monitorAnonymousSession",get:function(){return this._monitorAnonymousSession}},{key:"checkSessionInterval",get:function(){return this._checkSessionInterval}},{key:"stopCheckSessionOnError",get:function(){return this._stopCheckSessionOnError}},{key:"query_status_response_type",get:function(){return this._query_status_response_type}},{key:"revokeAccessTokenOnSignout",get:function(){return this._revokeAccessTokenOnSignout}},{key:"redirectNavigator",get:function(){return this._redirectNavigator}},{key:"popupNavigator",get:function(){return this._popupNavigator}},{key:"iframeNavigator",get:function(){return this._iframeNavigator}},{key:"userStore",get:function(){return this._userStore}}]),t}(i.OidcClientSettings)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedirectNavigator=void 0;var n=function(){function e(e,t){for(var r=0;r1&&void 0!==arguments[1])||arguments[1];n.Log.debug("UserManagerEvents.load"),e.prototype.load.call(this,t),r&&this._userLoaded.raise(t)},t.prototype.unload=function(){n.Log.debug("UserManagerEvents.unload"),e.prototype.unload.call(this),this._userUnloaded.raise()},t.prototype.addUserLoaded=function(e){this._userLoaded.addHandler(e)},t.prototype.removeUserLoaded=function(e){this._userLoaded.removeHandler(e)},t.prototype.addUserUnloaded=function(e){this._userUnloaded.addHandler(e)},t.prototype.removeUserUnloaded=function(e){this._userUnloaded.removeHandler(e)},t.prototype.addSilentRenewError=function(e){this._silentRenewError.addHandler(e)},t.prototype.removeSilentRenewError=function(e){this._silentRenewError.removeHandler(e)},t.prototype._raiseSilentRenewError=function(e){n.Log.debug("UserManagerEvents._raiseSilentRenewError",e.message),this._silentRenewError.raise(e)},t.prototype.addUserSignedIn=function(e){this._userSignedIn.addHandler(e)},t.prototype.removeUserSignedIn=function(e){this._userSignedIn.removeHandler(e)},t.prototype._raiseUserSignedIn=function(){n.Log.debug("UserManagerEvents._raiseUserSignedIn"),this._userSignedIn.raise()},t.prototype.addUserSignedOut=function(e){this._userSignedOut.addHandler(e)},t.prototype.removeUserSignedOut=function(e){this._userSignedOut.removeHandler(e)},t.prototype._raiseUserSignedOut=function(){n.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise()},t.prototype.addUserSessionChanged=function(e){this._userSessionChanged.addHandler(e)},t.prototype.removeUserSessionChanged=function(e){this._userSessionChanged.removeHandler(e)},t.prototype._raiseUserSessionChanged=function(){n.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise()},t}(i.AccessTokenEvents)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timer=void 0;var n=function(){function e(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:o.Global.timer,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var s=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r));return s._timer=n,s._nowFunc=i||function(){return Date.now()/1e3},s}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.init=function(e){e<=0&&(e=1),e=parseInt(e);var t=this.now+e;if(this.expiration===t&&this._timerHandle)i.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);else{this.cancel(),i.Log.debug("Timer.init timer "+this._name+" for duration:",e),this._expiration=t;var r=5;e{var r,i;await this.sessionInfoManager.clear(e.sessionId);const o=null!==(r=e.redirectUrl)&&void 0!==r?r:s.normalizeCallbackUrl(window.location.href);if(!n.isValidRedirectUrl(o))throw new Error(`${o} is not a valid redirect URL, it is either a malformed IRI, includes a hash fragment, or reserved query parameters ('code' or 'state').`);await this.loginHandler.handle({...e,redirectUrl:o,clientName:null!==(i=e.clientName)&&void 0!==i?i:e.clientId,eventEmitter:t})},this.validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return void 0===t||void 0===t.clientAppId||void 0===t.issuer?null:t},this.handleIncomingRedirect=async(e,t)=>{try{const r=await this.redirectHandler.handle(e,t);return this.fetch=r.fetch.bind(window),this.boundLogout=r.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:r.isLoggedIn,webId:r.webId,sessionId:r.sessionId,expirationDate:r.expirationDate}}catch(r){return await this.cleanUrlAfterRedirect(e),void t.emit(n.EVENTS.ERROR,"redirect",r)}}}async cleanUrlAfterRedirect(e){const t=n.removeOpenIdParams(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise((e=>{setTimeout((()=>e()),1)}))}}function u(e){return"string"==typeof e.oidcIssuer}function d(e){return"string"==typeof e.redirectUrl}class h{constructor(e,t,r,n){this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=r,this.clientRegistrar=n,this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=r,this.clientRegistrar=n}async canHandle(e){return u(e)&&d(e)}async handle(e){if(!u(e))throw new n.ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!d(e))throw new n.ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),r=await n.handleRegistration(e,t,this.storageUtility,this.clientRegistrar),i={issuer:t.issuer,dpop:"dpop"===e.tokenType.toLowerCase(),...e,issuerConfiguration:t,client:r};return this.oidcHandler.handle(i)}}class f extends n.AuthorizationCodeWithPkceOidcHandlerBase{async handle(e){var t;const r={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl.toString(),post_logout_redirect_uri:e.redirectUrl.toString(),response_type:"code",scope:n.DEFAULT_SCOPES,filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:null!==(t=e.prompt)&&void 0!==t?t:"consent"},i=new s.OidcClient(r);try{const t=await i.createSigninRequest();return await this.handleRedirect({oidcLoginOptions:e,state:t.state._id,codeVerifier:t.state._code_verifier,targetUrl:t.url.toString()})}catch(e){console.error(e)}}}const p={issuer:{toKey:"issuer",convertToUrl:!0},authorization_endpoint:{toKey:"authorizationEndpoint",convertToUrl:!0},token_endpoint:{toKey:"tokenEndpoint",convertToUrl:!0},userinfo_endpoint:{toKey:"userinfoEndpoint",convertToUrl:!0},jwks_uri:{toKey:"jwksUri",convertToUrl:!0},registration_endpoint:{toKey:"registrationEndpoint",convertToUrl:!0},end_session_endpoint:{toKey:"endSessionEndpoint",convertToUrl:!0},scopes_supported:{toKey:"scopesSupported"},response_types_supported:{toKey:"responseTypesSupported"},response_modes_supported:{toKey:"responseModesSupported"},grant_types_supported:{toKey:"grantTypesSupported"},acr_values_supported:{toKey:"acrValuesSupported"},subject_types_supported:{toKey:"subjectTypesSupported"},id_token_signing_alg_values_supported:{toKey:"idTokenSigningAlgValuesSupported"},id_token_encryption_alg_values_supported:{toKey:"idTokenEncryptionAlgValuesSupported"},id_token_encryption_enc_values_supported:{toKey:"idTokenEncryptionEncValuesSupported"},userinfo_signing_alg_values_supported:{toKey:"userinfoSigningAlgValuesSupported"},userinfo_encryption_alg_values_supported:{toKey:"userinfoEncryptionAlgValuesSupported"},userinfo_encryption_enc_values_supported:{toKey:"userinfoEncryptionEncValuesSupported"},request_object_signing_alg_values_supported:{toKey:"requestObjectSigningAlgValuesSupported"},request_object_encryption_alg_values_supported:{toKey:"requestObjectEncryptionAlgValuesSupported"},request_object_encryption_enc_values_supported:{toKey:"requestObjectEncryptionEncValuesSupported"},token_endpoint_auth_methods_supported:{toKey:"tokenEndpointAuthMethodsSupported"},token_endpoint_auth_signing_alg_values_supported:{toKey:"tokenEndpointAuthSigningAlgValuesSupported"},display_values_supported:{toKey:"displayValuesSupported"},claim_types_supported:{toKey:"claimTypesSupported"},claims_supported:{toKey:"claimsSupported"},service_documentation:{toKey:"serviceDocumentation"},claims_locales_supported:{toKey:"claimsLocalesSupported"},ui_locales_supported:{toKey:"uiLocalesSupported"},claims_parameter_supported:{toKey:"claimsParameterSupported"},request_parameter_supported:{toKey:"requestParameterSupported"},request_uri_parameter_supported:{toKey:"requestUriParameterSupported"},require_request_uri_registration:{toKey:"requireRequestUriRegistration"},op_policy_uri:{toKey:"opPolicyUri",convertToUrl:!0},op_tos_uri:{toKey:"opTosUri",convertToUrl:!0}};class g{constructor(e){this.storageUtility=e,this.storageUtility=e}static getLocalStorageKey(e){return`issuerConfig:${e}`}async fetchConfig(e){let t;const r=new URL(".well-known/openid-configuration",e.endsWith("/")?e:`${e}/`).href,i=await a.fetch.call(globalThis,r);try{t=function(e){const t={};return Object.keys(e).forEach((r=>{p[r]&&(t[p[r].toKey]=e[r])})),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(await i.json())}catch(t){throw new n.ConfigurationError(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return await this.storageUtility.set(g.getLocalStorageKey(e),JSON.stringify(t)),t}}class y extends n.SessionInfoManagerBase{async get(e){const[t,r,i,o,s,a,c,l]=await Promise.all([this.storageUtility.getForUser(e,"isLoggedIn",{secure:!0}),this.storageUtility.getForUser(e,"webId",{secure:!0}),this.storageUtility.getForUser(e,"clientId",{secure:!1}),this.storageUtility.getForUser(e,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e,"redirectUrl",{secure:!1}),this.storageUtility.getForUser(e,"refreshToken",{secure:!0}),this.storageUtility.getForUser(e,"issuer",{secure:!1}),this.storageUtility.getForUser(e,"tokenType",{secure:!1})]);if("string"!=typeof s||n.isValidRedirectUrl(s)){if(void 0!==l&&!n.isSupportedTokenType(l))throw new Error(`Tokens of type [${l}] are not supported.`);if(void 0!==i||void 0!==t||void 0!==r||void 0!==a)return{sessionId:e,webId:r,isLoggedIn:"true"===t,redirectUrl:s,refreshToken:a,issuer:c,clientAppId:i,clientAppSecret:o,tokenType:null!=l?l:"DPoP"}}else await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})])}async clear(e){return async function(e,t){await n.clear(e,t),await s.clearOidcPersistentStorage()}(e,this.storageUtility)}}class m{async canHandle(e){try{return new URL(e),!0}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e){return n.getUnauthenticatedSession()}}const v=(...e)=>a.fetch.call(globalThis,...e);class b{constructor(e,t,r,n,i){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=r,this.clientRegistrar=n,this.tokerRefresher=i,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=r,this.clientRegistrar=n,this.tokerRefresher=i}async canHandle(e){try{const t=new URL(e);return null!==t.searchParams.get("code")&&null!==t.searchParams.get("state")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(!await this.canHandle(e))throw new Error(`AuthCodeRedirectHandler cannot handle [${e}]: it is missing one of [code, state].`);const r=new URL(e),i=r.searchParams.get("state"),o=await this.storageUtility.getForUser(i,"sessionId",{errorIfNull:!0}),{issuerConfig:a,codeVerifier:c,redirectUrl:l,dpop:u}=await n.loadOidcContextFromStorage(o,this.storageUtility,this.issuerConfigFetcher),d=r.searchParams.get("iss");if("string"==typeof d&&d!==a.issuer)throw new Error(`The value of the iss parameter (${d}) does not match the issuer identifier of the authorization server (${a.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(void 0===c)throw new Error(`The code verifier for session ${o} is missing from storage.`);if(void 0===l)throw new Error(`The redirect URL for session ${o} is missing from storage.`);const h=await this.clientRegistrar.getClient({sessionId:o},a);let f;const p=Date.now();let g;u?(f=await s.getDpopToken(a,h,{grantType:"authorization_code",code:r.searchParams.get("code"),codeVerifier:c,redirectUrl:l}),window.localStorage.removeItem(`oidc.${i}`)):f=await s.getBearerToken(r.toString()),void 0!==f.refreshToken&&(g={sessionId:o,refreshToken:f.refreshToken,tokenRefresher:this.tokerRefresher});const y=await n.buildAuthenticatedFetch(v,f.accessToken,{dpopKey:f.dpopKey,refreshOptions:g,eventEmitter:t,expiresIn:f.expiresIn});await this.storageUtility.setForUser(o,{webId:f.webId,isLoggedIn:"true"},{secure:!0});const m=await this.sessionInfoManager.get(o);if(!m)throw new Error(`Could not retrieve session: [${o}].`);return Object.assign(m,{fetch:y,getLogoutUrl:n.maybeBuildRpInitiatedLogout({idTokenHint:f.idToken,endSessionEndpoint:a.endSessionEndpoint}),expirationDate:"number"==typeof f.expiresIn?p+1e3*f.expiresIn:void 0})}}class w extends n.AggregateHandler{constructor(e){super(e)}}class _{get storage(){return window.localStorage}async get(e){return this.storage.getItem(e)||void 0}async set(e,t){this.storage.setItem(e,t)}async delete(e){this.storage.removeItem(e)}}class S{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class E{constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[r,n]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1})]);if(r)return{clientId:r,clientSecret:n,clientType:"dynamic"};try{const r=await s.registerClient(e,t),n={clientId:r.clientId};return r.clientSecret&&(n.clientSecret=r.clientSecret),r.idTokenSignedResponseAlg&&(n.idTokenSignedResponseAlg=r.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,n,{secure:!1}),r}catch(e){throw new Error(`Client registration failed: [${e}]`)}}}class A{async canHandle(e){try{return new URL(e).searchParams.has("error")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(void 0!==t){const r=new URL(e),i=r.searchParams.get("error"),o=r.searchParams.get("error_description");t.emit(n.EVENTS.ERROR,i,o)}return n.getUnauthenticatedSession()}}class R{constructor(e,t,r){this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=r,this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=r}async refresh(e,t,r,i){const o=await n.loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),a=await this.clientRegistrar.getClient({sessionId:e},o.issuerConfig);if(void 0===t)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(o.dpop&&void 0===r)throw new Error(`For session [${e}], the key bound to the DPoP access token must be provided to refresh said access token.`);const c=await s.refresh(t,o.issuerConfig,a,r);return void 0!==c.refreshToken&&(null==i||i.emit(n.EVENTS.NEW_REFRESH_TOKEN,c.refreshToken),await this.storageUtility.setForUser(e,{refreshToken:c.refreshToken})),c}}function I(e){const t=new n.InMemoryStorage,r=e.secureStorage||t,i=e.insecureStorage||new _,o=new c(r,i),s=new g(o),a=new E(o),u=new y(o),d=new R(o,s,a),p=new S,v=new h(o,new f(o,p),s,a),I=new w([new A,new b(o,u,s,a,d),new m]);return new l(v,I,new n.IWaterfallLogoutHandler(u,p),u,s)}const T=`${n.SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`,x=`${n.SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;class P extends o{constructor(e={},t=void 0){super(),this.tokenRequestInProgress=!1,this.login=async e=>{var t;return await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:null!==(t=e.tokenType)&&void 0!==t?t:"DPoP"},this.events),new Promise((()=>{}))},this.fetch=(e,t)=>this.clientAuthentication.fetch(e,t),this.internalLogout=async(e,t)=>{window.localStorage.removeItem(T),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(n.EVENTS.LOGOUT)},this.logout=async e=>this.internalLogout(!0,e),this.handleIncomingRedirect=async(e={})=>{var t;if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const r="string"==typeof e?{url:e}:e,i=null!==(t=r.url)&&void 0!==t?t:window.location.href;this.tokenRequestInProgress=!0;const o=await this.clientAuthentication.handleIncomingRedirect(i,this.events);if(function(e){return!!(null==e?void 0:e.isLoggedIn)}(o)){this.setSessionInfo(o);const e=window.localStorage.getItem(x);null===e?this.events.emit(n.EVENTS.LOGIN):(window.localStorage.removeItem(x),this.events.emit(n.EVENTS.SESSION_RESTORED,e))}else if(!0===r.restorePreviousSession){const e=window.localStorage.getItem(T);if(null!==e){const t=await async function(e,t,r){var n;const i=await t.validateCurrentSession(e);return null!==i&&(window.localStorage.setItem(x,window.location.href),await t.login({sessionId:e,prompt:"none",oidcIssuer:i.issuer,redirectUrl:i.redirectUrl,clientId:i.clientAppId,clientSecret:i.clientAppSecret,tokenType:null!==(n=i.tokenType)&&void 0!==n?n:"DPoP"},r.events),!0)}(e,this.clientAuthentication,this);if(t)return new Promise((()=>{}))}}return this.tokenRequestInProgress=!1,o},this.events=new Proxy(this,n.buildProxyHandler(P.prototype,"events only implements ISessionEventListener")),e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=I({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage}):this.clientAuthentication=I({}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId}:this.info={sessionId:null!=t?t:i.v4(),isLoggedIn:!1},this.events.on(n.EVENTS.LOGIN,(()=>window.localStorage.setItem(T,this.info.sessionId))),this.events.on(n.EVENTS.SESSION_EXPIRED,(()=>this.internalLogout(!1))),this.events.on(n.EVENTS.ERROR,(()=>this.internalLogout(!1)))}onLogin(e){this.events.on(n.EVENTS.LOGIN,e)}onLogout(e){this.events.on(n.EVENTS.LOGOUT,e)}onError(e){this.events.on(n.EVENTS.ERROR,e)}onSessionRestore(e){this.events.on(n.EVENTS.SESSION_RESTORED,e)}onSessionExpiration(e){this.events.on(n.EVENTS.SESSION_EXPIRED,e)}setSessionInfo(e){this.info.isLoggedIn=e.isLoggedIn,this.info.webId=e.webId,this.info.sessionId=e.sessionId,this.info.expirationDate=e.expirationDate,this.events.on(n.EVENTS.SESSION_EXTENDED,(e=>{this.info.expirationDate=Date.now()+1e3*e}))}}let C;function k(){return void 0===C&&(C=new P),C}Object.defineProperty(t,"ConfigurationError",{enumerable:!0,get:function(){return n.ConfigurationError}}),Object.defineProperty(t,"EVENTS",{enumerable:!0,get:function(){return n.EVENTS}}),Object.defineProperty(t,"InMemoryStorage",{enumerable:!0,get:function(){return n.InMemoryStorage}}),Object.defineProperty(t,"NotImplementedError",{enumerable:!0,get:function(){return n.NotImplementedError}}),t.Session=P,t.events=()=>k().events,t.fetch=(...e)=>k().fetch(...e),t.getClientAuthenticationWithDependencies=I,t.getDefaultSession=k,t.handleIncomingRedirect=(...e)=>k().handleIncomingRedirect(...e),t.login=(...e)=>k().login(...e),t.logout=(...e)=>k().logout(...e),t.onLogin=(...e)=>k().onLogin(...e),t.onLogout=(...e)=>k().onLogout(...e),t.onSessionRestore=(...e)=>k().onSessionRestore(...e)},4667:function(e,t,r){"use strict";var n=r(7007),i=r(5914),o=r(6438),s=r(2831);const a=["ES256","RS256"],c={ERROR:"error",LOGIN:"login",LOGOUT:"logout",NEW_REFRESH_TOKEN:"newRefreshToken",SESSION_EXPIRED:"sessionExpired",SESSION_EXTENDED:"sessionExtended",SESSION_RESTORED:"sessionRestore",TIMEOUT_SET:"timeoutSet"},l=["openid","offline_access","webid"].join(" ");async function u(e,t){const r=await i.fetch.call(globalThis,e);if(200!==r.status)throw new Error(`Could not fetch JWKS for [${t}] at [${e}]: ${r.status} ${r.statusText}`);let n;try{n=(await r.json()).keys[0]}catch(r){throw new Error(`Malformed JWKS for [${t}] at [${e}]: ${r.message}`)}return n}class d{constructor(e){this.sessionInfoManager=e,this.sessionInfoManager=e}async canHandle(){return!0}async handle(e){await this.sessionInfoManager.clear(e)}}class h{constructor(e){this.redirector=e,this.redirector=e}async canHandle(e,t){return"idp"===(null==t?void 0:t.logoutType)}async handle(e,t){if("idp"!==(null==t?void 0:t.logoutType))throw new Error("Attempting to call idp logout handler to perform app logout");if(void 0===t.toLogoutUrl)throw new Error("Cannot perform IDP logout. Did you log in using the OIDC authentication flow?");this.redirector.redirect(t.toLogoutUrl(t),{handleRedirect:t.handleRedirect})}}async function f(e,t){await Promise.all([t.deleteAllUserData(e,{secure:!1}),t.deleteAllUserData(e,{secure:!0})])}function p({endSessionEndpoint:e,idTokenHint:t,postLogoutRedirectUri:r,state:n}){const i=new URL(e);return void 0!==t&&i.searchParams.append("id_token_hint",t),void 0!==r&&(i.searchParams.append("post_logout_redirect_uri",r),void 0!==n&&i.searchParams.append("state",n)),i.toString()}function g(e){try{return new URL(e),!0}catch(e){return!1}}const y=(e,t)=>i.fetch.call(globalThis,e,t);class m{constructor(e,t){this.secureStorage=e,this.insecureStorage=t,this.secureStorage=e,this.insecureStorage=t}getKey(e){return`solidClientAuthenticationUser:${e}`}async getUserData(e,t){const r=await(t?this.secureStorage:this.insecureStorage).get(this.getKey(e));if(void 0===r)return{};try{return JSON.parse(r)}catch(n){throw new Error(`Data for user [${e}] in [${t?"secure":"unsecure"}] storage is corrupted - expected valid JSON, but got: ${r}`)}}async setUserData(e,t,r){await(r?this.secureStorage:this.insecureStorage).set(this.getKey(e),JSON.stringify(t))}async get(e,t){const r=await((null==t?void 0:t.secure)?this.secureStorage:this.insecureStorage).get(e);if(void 0===r&&(null==t?void 0:t.errorIfNull))throw new Error(`[${e}] is not stored`);return r}async set(e,t,r){return((null==r?void 0:r.secure)?this.secureStorage:this.insecureStorage).set(e,t)}async delete(e,t){return((null==t?void 0:t.secure)?this.secureStorage:this.insecureStorage).delete(e)}async getForUser(e,t,r){const n=await this.getUserData(e,null==r?void 0:r.secure);let i;if(n&&n[t]||(i=void 0),i=n[t],void 0===i&&(null==r?void 0:r.errorIfNull))throw new Error(`Field [${t}] for user [${e}] is not stored`);return i||void 0}async setForUser(e,t,r){let n;try{n=await this.getUserData(e,null==r?void 0:r.secure)}catch(e){n={}}await this.setUserData(e,{...n,...t},null==r?void 0:r.secure)}async deleteForUser(e,t,r){const n=await this.getUserData(e,null==r?void 0:r.secure);delete n[t],await this.setUserData(e,n,null==r?void 0:r.secure)}async deleteAllUserData(e,t){await((null==t?void 0:t.secure)?this.secureStorage:this.insecureStorage).delete(this.getKey(e))}}class v extends Error{constructor(e){super(e)}}class b extends Error{constructor(e){super(`[${e}] is not implemented`)}}class w extends Error{constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class _ extends Error{constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function S(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function E(e,t,r){return new o.SignJWT({htu:S(e),htm:t.toUpperCase(),jti:s.v4()}).setProtectedHeader({alg:a[0],jwk:r.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(r.privateKey,{})}async function A(e,t,r,n,o){return e(r,await async function(e,t,r,n){if(void 0!==r)return async function(e,t,r,n){var o;const s=new i.Headers(null==n?void 0:n.headers);return s.set("Authorization",`DPoP ${t}`),s.set("DPoP",await E(e,null!==(o=null==n?void 0:n.method)&&void 0!==o?o:"get",r)),{...n,headers:s}}(e,t,r,n);const o=new i.Headers(null==n?void 0:n.headers);return o.set("Authorization",`Bearer ${t}`),{...n,headers:o}}(r.toString(),t,o,n))}const R=e=>void 0!==e?e-5>0?e-5:e:600,I="getResponse",T={get:async(e,t)=>I,set:async(e,t)=>{},delete:async e=>{},getForUser:async(e,t,r)=>I,setForUser:async(e,t,r)=>{},deleteForUser:async(e,t,r)=>{},deleteAllUserData:async(e,t)=>{}},x=e=>{const t=e;return{get:async e=>{if(void 0!==t[e])return"string"==typeof t[e]?t[e]:JSON.stringify(t[e])},set:async(e,r)=>{t[e]=r},delete:async e=>{delete t[e]}}};t.AggregateHandler=class{constructor(e){this.handleables=e,this.handleables=e}async getProperHandler(e){const t=await Promise.all(this.handleables.map((t=>t.canHandle(...e))));for(let e=0;e{try{return JSON.stringify(e)}catch(t){return e.toString()}})).join(", ")}`)}},t.AuthorizationCodeWithPkceOidcHandlerBase=class{constructor(e,t){this.storageUtility=e,this.redirector=t,this.storageUtility=e,this.redirector=t}async canHandle(e){return!!(e.issuerConfiguration.grantTypesSupported&&e.issuerConfiguration.grantTypesSupported.indexOf("authorization_code")>-1)}async handleRedirect({oidcLoginOptions:e,state:t,codeVerifier:r,targetUrl:n}){await Promise.all([this.storageUtility.setForUser(t,{sessionId:e.sessionId}),this.storageUtility.setForUser(e.sessionId,{codeVerifier:r,issuer:e.issuer.toString(),redirectUrl:e.redirectUrl,dpop:e.dpop?"true":"false"})]),this.redirector.redirect(n,{handleRedirect:e.handleRedirect})}},t.ClientAuthentication=class{constructor(e,t,r,n,i){this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=n,this.issuerConfigFetcher=i,this.fetch=y,this.logout=async(e,t)=>{await this.logoutHandler.handle(e,"idp"===(null==t?void 0:t.logoutType)?{...t,toLogoutUrl:this.boundLogout}:t),this.fetch=y,delete this.boundLogout},this.getSessionInfo=async e=>this.sessionInfoManager.get(e),this.getAllSessionInfo=async()=>this.sessionInfoManager.getAll(),this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=n,this.issuerConfigFetcher=i}},t.ConfigurationError=v,t.DEFAULT_SCOPES=l,t.EVENTS=c,t.GeneralLogoutHandler=d,t.IRpLogoutHandler=h,t.IWaterfallLogoutHandler=class{constructor(e,t){this.handlers=[new d(e),new h(t)]}async canHandle(){return!0}async handle(e,t){for(const r of this.handlers)await r.canHandle(e,t)&&await r.handle(e,t)}},t.InMemoryStorage=class{constructor(){this.map={}}async get(e){return this.map[e]||void 0}async set(e,t){this.map[e]=t}async delete(e){delete this.map[e]}},t.InvalidResponseError=w,t.NotImplementedError=b,t.OidcProviderError=_,t.PREFERRED_SIGNING_ALG=a,t.REFRESH_BEFORE_EXPIRATION_SECONDS=5,t.SOLID_CLIENT_AUTHN_KEY_PREFIX="solidClientAuthn:",t.SessionInfoManagerBase=class{constructor(e){this.storageUtility=e,this.storageUtility=e}update(e,t){throw new Error("Not Implemented")}get(e){throw new Error("Not implemented")}async getAll(){throw new Error("Not implemented")}async clear(e){return f(e,this.storageUtility)}async register(e){throw new Error("Not implemented")}async getRegisteredSessionIdAll(){throw new Error("Not implemented")}async clearAll(){throw new Error("Not implemented")}},t.StorageUtility=m,t.StorageUtilityGetResponse=I,t.StorageUtilityMock=T,t.USER_SESSION_PREFIX="solidClientAuthenticationUser",t.buildAuthenticatedFetch=async function(e,t,r){var n;let i,o=t;const s=null==r?void 0:r.refreshOptions;if(void 0!==s){const e=async()=>{var t,n,a,l;try{const{accessToken:n,refreshToken:a,expiresIn:l}=await async function(e,t,r){var n;const i=await e.tokenRefresher.refresh(e.sessionId,e.refreshToken,t);return null==r||r.emit(c.SESSION_EXTENDED,null!==(n=i.expiresIn)&&void 0!==n?n:600),"string"==typeof i.refreshToken&&(null==r||r.emit(c.NEW_REFRESH_TOKEN,i.refreshToken)),{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn}}(s,r.dpopKey,r.eventEmitter);o=n,void 0!==a&&(s.refreshToken=a),clearTimeout(i),i=setTimeout(e,1e3*R(l)),null===(t=r.eventEmitter)||void 0===t||t.emit(c.TIMEOUT_SET,i)}catch(e){e instanceof _&&(null===(n=null==r?void 0:r.eventEmitter)||void 0===n||n.emit(c.ERROR,e.error,e.errorDescription),null===(a=null==r?void 0:r.eventEmitter)||void 0===a||a.emit(c.SESSION_EXPIRED)),e instanceof w&&e.missingFields.includes("access_token")&&(null===(l=null==r?void 0:r.eventEmitter)||void 0===l||l.emit(c.SESSION_EXPIRED))}};i=setTimeout(e,1e3*R(r.expiresIn)),null===(n=r.eventEmitter)||void 0===n||n.emit(c.TIMEOUT_SET,i)}else if(void 0!==r&&void 0!==r.eventEmitter){const e=setTimeout((()=>{r.eventEmitter.emit(c.SESSION_EXPIRED)}),1e3*R(r.expiresIn));r.eventEmitter.emit(c.TIMEOUT_SET,e)}return async(t,n)=>{let i=await A(e,o,t,n,null==r?void 0:r.dpopKey);const s=!i.ok&&(a=i.status,![401,403].includes(a));var a;return i.ok||s||i.url!==t&&void 0!==(null==r?void 0:r.dpopKey)&&(i=await A(e,o,i.url,n,r.dpopKey)),i}},t.buildProxyHandler=(e,t)=>({get(r,i,o){if(!Object.getOwnPropertyNames(n.EventEmitter).includes(i)&&Object.getOwnPropertyNames(e).includes(i))throw new Error(`${t}: [${i}] is not supported`);return Reflect.get(r,i,o)}}),t.clear=f,t.createDpopHeader=E,t.determineSigningAlg=function(e,t){var r;return null!==(r=t.find((t=>e.includes(t))))&&void 0!==r?r:null},t.fetchJwks=u,t.generateDpopKeyPair=async function(){const{privateKey:e,publicKey:t}=await o.generateKeyPair(a[0]),r={privateKey:e,publicKey:await o.exportJWK(t)};return[r.publicKey.alg]=a,r},t.getEndSessionUrl=p,t.getSessionIdFromOauthState=async function(e,t){return e.getForUser(t,"sessionId")},t.getUnauthenticatedSession=function(){return{isLoggedIn:!1,sessionId:s.v4(),fetch:(...e)=>i.fetch.call(globalThis,...e)}},t.getWebidFromTokenPayload=async function(e,t,r,n){const i=await u(t,r);let s;try{const{payload:t}=await o.jwtVerify(e,await o.importJWK(i),{issuer:r,audience:n});s=t}catch(e){throw new Error(`Token verification failed: ${e.stack}`)}if("string"==typeof s.webid)return s.webid;if("string"!=typeof s.sub)throw new Error(`The token ${JSON.stringify(s)} is invalid: it has no 'webid' claim and no 'sub' claim.`);try{return new URL(s.sub),s.sub}catch(e){throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${s.sub}] is invalid as a URL - error [${e}].`)}},t.handleRegistration=async function(e,t,r,n){const i=function(e,t){return void 0===e.clientId||g(e.clientId)?t.scopesSupported.includes("webid")&&void 0!==e.clientId&&g(e.clientId)?"solid-oidc":"dynamic":"static"}(e,t);return"dynamic"===i?n.getClient({sessionId:e.sessionId,clientName:e.clientName,redirectUrl:e.redirectUrl},t):(await r.setForUser(e.sessionId,{clientId:e.clientId}),e.clientSecret&&await r.setForUser(e.sessionId,{clientSecret:e.clientSecret}),e.clientName&&await r.setForUser(e.sessionId,{clientName:e.clientName}),{clientId:e.clientId,clientSecret:e.clientSecret,clientName:e.clientName,clientType:i})},t.isSupportedTokenType=function(e){return"string"==typeof e&&["DPoP","Bearer"].includes(e)},t.isValidRedirectUrl=function(e){try{const t=new URL(e),r=!t.searchParams.has("code")&&!t.searchParams.has("state"),n=""===t.hash;return r&&n}catch(e){return!1}},t.loadOidcContextFromStorage=async function(e,t,r){try{const[n,i,o,s]=await Promise.all([t.getForUser(e,"issuer",{errorIfNull:!0}),t.getForUser(e,"codeVerifier"),t.getForUser(e,"redirectUrl"),t.getForUser(e,"dpop",{errorIfNull:!0})]);return await t.deleteForUser(e,"codeVerifier"),{codeVerifier:i,redirectUrl:o,issuerConfig:await r.fetchConfig(n),dpop:"true"===s}}catch(t){throw new Error(`Failed to retrieve OIDC context from storage associated with session [${e}]: ${t}`)}},t.maybeBuildRpInitiatedLogout=function({endSessionEndpoint:e,idTokenHint:t}){if(void 0!==e)return function({state:r,postLogoutUrl:n}){return p({endSessionEndpoint:e,idTokenHint:t,state:r,postLogoutRedirectUri:n})}},t.mockStorage=x,t.mockStorageUtility=(e,t=!1)=>t?new m(x(e),x({})):new m(x({}),x(e)),t.removeOpenIdParams=function(e){const t=new URL(e);return t.searchParams.delete("state"),t.searchParams.delete("code"),t.searchParams.delete("error"),t.searchParams.delete("error_description"),t.searchParams.delete("iss"),t},t.saveSessionInfoToStorage=async function(e,t,r,n,i,s,a){void 0!==i&&await e.setForUser(t,{refreshToken:i},{secure:s}),void 0!==r&&await e.setForUser(t,{webId:r},{secure:s}),void 0!==n&&await e.setForUser(t,{isLoggedIn:n},{secure:s}),void 0!==a&&await e.setForUser(t,{publicKey:JSON.stringify(a.publicKey),privateKey:JSON.stringify(await o.exportJWK(a.privateKey))},{secure:s})}},4848:function(e,t,r){"use strict";var n=r(8690),i=r(2395),o=r(5914),s=r(2384),a=r(8518),c=r(4727),l=r(6565),u=r(2831);function d(e){return"object"==typeof e&&"object"==typeof e.internal_resourceInfo}function h(e){const t=e;return"object"==typeof t&&"object"==typeof t.internal_resourceInfo&&"object"==typeof t.internal_resourceInfo.linkedResources}function f(e){const t=e;return"object"==typeof t.internal_changeLog&&Array.isArray(t.internal_changeLog.additions)&&Array.isArray(t.internal_changeLog.deletions)}class p extends Error{}function g(e){return"string"==typeof e?e:e.value}const y=o.fetch.bind(globalThis);function m(e){var t,r,n,i,o;const a=null!==(r=null===(t=e.headers.get("Content-Type"))||void 0===t?void 0:t.split(";"))&&void 0!==r?r:[],c=a.length>0&&["text/turtle","application/ld+json"].includes(a[0]),l={sourceIri:e.url,isRawData:!c,contentLocation:null!==(n=e.headers.get("Content-Location"))&&void 0!==n?n:void 0,contentType:null!==(i=e.headers.get("Content-Type"))&&void 0!==i?i:void 0,linkedResources:{},location:null!==(o=e.headers.get("Location"))&&void 0!==o?o:void 0},u=e.headers.get("Link");if(u){const e=s.parse(u),t=e.get("rel","acl");1===t.length&&(l.aclUrl=new URL(t[0].uri,l.sourceIri).href),l.linkedResources=e.refs.reduce(((e,t)=>{var r,n;return null!==(r=e[n=t.rel])&&void 0!==r||(e[n]=[]),e[t.rel].push(new URL(t.uri,l.sourceIri).href),e}),l.linkedResources)}const d=e.headers.get("WAC-Allow");return d&&(l.permissions=function(e){function t(e){const t=e.split(" ");return t.includes("write")?{read:t.includes("read"),append:!0,write:!0,control:t.includes("control")}:{read:t.includes("read"),append:t.includes("append"),write:!1,control:t.includes("control")}}function r(e,t){const r=e.split(",").map((e=>e.split("="))).filter((e=>2===e.length&&e[0].trim()===t));if(1!==r.length)return"";const n=r[0][1].trim();return'"'!==n.charAt(0)||'"'!==n.charAt(n.length-1)?"":n.substring(1,n.length-1)}return{user:t(r(e,"user")),public:t(r(e,"public"))}}(d)),l}function v(e){let t;return t="function"==typeof e.slice?Object.assign(e.slice(),{...e}):{...e},t}function b(e){return!e.ok}const w="http://www.w3.org/ns/auth/acl#Authorization",_="http://www.w3.org/ns/auth/acl#accessTo",S="http://www.w3.org/ns/auth/acl#agent",E="http://www.w3.org/ns/auth/acl#agentGroup",A="http://www.w3.org/ns/auth/acl#agentClass",R="http://www.w3.org/ns/auth/acl#default",I="http://www.w3.org/ns/auth/acl#defaultForNew",T="http://www.w3.org/ns/auth/acl#mode",x="http://www.w3.org/ns/auth/acl#origin",P="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",C="http://www.w3.org/ns/ldp#BasicContainer",k="http://www.w3.org/ns/ldp#Resource",O="http://www.w3.org/ns/ldp#contains",F="http://xmlns.com/foaf/0.1/Agent",N={AccessControlResource:"http://www.w3.org/ns/solid/acp#AccessControlResource",Policy:"http://www.w3.org/ns/solid/acp#Policy",AccessControl:"http://www.w3.org/ns/solid/acp#AccessControl",Read:"http://www.w3.org/ns/solid/acp#Read",Append:"http://www.w3.org/ns/solid/acp#Append",Write:"http://www.w3.org/ns/solid/acp#Write",Rule:"http://www.w3.org/ns/solid/acp#Rule",Matcher:"http://www.w3.org/ns/solid/acp#Matcher",accessControl:"http://www.w3.org/ns/solid/acp#accessControl",memberAccessControl:"http://www.w3.org/ns/solid/acp#memberAccessControl",apply:"http://www.w3.org/ns/solid/acp#apply",applyMembers:"http://www.w3.org/ns/solid/acp#applyMembers",allow:"http://www.w3.org/ns/solid/acp#allow",deny:"http://www.w3.org/ns/solid/acp#deny",allOf:"http://www.w3.org/ns/solid/acp#allOf",anyOf:"http://www.w3.org/ns/solid/acp#anyOf",noneOf:"http://www.w3.org/ns/solid/acp#noneOf",access:"http://www.w3.org/ns/solid/acp#access",accessMembers:"http://www.w3.org/ns/solid/acp#accessMembers",agent:"http://www.w3.org/ns/solid/acp#agent",group:"http://www.w3.org/ns/solid/acp#group",client:"http://www.w3.org/ns/solid/acp#client",PublicAgent:"http://www.w3.org/ns/solid/acp#PublicAgent",AuthenticatedAgent:"http://www.w3.org/ns/solid/acp#AuthenticatedAgent",CreatorAgent:"http://www.w3.org/ns/solid/acp#CreatorAgent"},D="http://www.w3.org/ns/solid/terms#PublicOidcClient",L="https://w3id.org/security#publicKey",U="http://www.w3.org/ns/pim/space#storage",j={fetch:y};async function M(e,t={...j,ignoreAuthenticationErrors:!1}){var r;const n={...j,...t};return B(await n.fetch(e,{method:"HEAD"}),{ignoreAuthenticationErrors:null!==(r=t.ignoreAuthenticationErrors)&&void 0!==r&&r})}function B(e,t={ignoreAuthenticationErrors:!1}){if(b(e)&&(!function(e){return 401===e.status||403===e.status}(e)||!t.ignoreAuthenticationErrors))throw new G(`Fetching the metadata of the Resource at [${e.url}] failed: [${e.status}] [${e.statusText}].`,e);return{internal_resourceInfo:m(e)}}function H(e){return(d(e)?$(e):g(e)).endsWith("/")}function W(e){var t;return null!==(t=e.internal_resourceInfo.contentType)&&void 0!==t?t:null}function $(e){return d(e)?e.internal_resourceInfo.sourceIri:null}const V=$;function K(e){var t;if(!h(e))return null;const r=null!==(t=J(e)["http://www.w3.org/ns/solid/terms#podOwner"])&&void 0!==t?t:[];return 1===r.length?r[0]:null}function J(e){return e.internal_resourceInfo.linkedResources}class G extends p{get statusCode(){return this.response.status}get statusText(){return this.response.statusText}constructor(e,t){super(e),this.response=t}}const q=()=>{const e=[],t=[],r=[];return{onQuad:t=>{e.push(t)},onError:e=>{r.push(e)},onComplete:e=>{t.push(e)},parse:async(o,s)=>new Promise((a=>{const c=new n.JsonLdParser({baseIRI:$(s),documentLoader:new i.FetchDocumentLoader(y)});let l=!1;function u(){l||(l=!0,t.forEach((e=>e())),a())}c.on("end",u),c.on("error",(e=>{r.forEach((t=>t(e))),u()})),e.forEach((e=>c.on("data",e))),c.write(o),c.end()}))}};l.dataset;const z="https://inrupt.com/.well-known/sdk-local-node/",{freeze:Y}=Object;function Q(e){return e.substring(0,46)===z}function X(e){return e.substring(46)}function Z(e){return"string"==typeof e&&"_:"===e.substring(0,2)}function ee(e){return e.substring(2)}function te(e){return`_:${e.value}`}const re="http://www.w3.org/2001/XMLSchema#boolean",ne="http://www.w3.org/2001/XMLSchema#dateTime",ie="http://www.w3.org/2001/XMLSchema#date",oe="http://www.w3.org/2001/XMLSchema#time",se="http://www.w3.org/2001/XMLSchema#decimal",ae="http://www.w3.org/2001/XMLSchema#integer",ce="http://www.w3.org/2001/XMLSchema#string",le="http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";function ue(e){return"true"===e||"1"===e||"false"!==e&&"0"!==e&&null}function de(e){if(!/\d\d:\d\d:\d\d(\.\d+)?(Z|(\+|-)\d\d:\d\d)?/.test(e))return null;const[t,r]=pe(e),[n,i,o]=t.split(":");let s=Number.parseInt(n,10),a=Number.parseInt(i,10);const[c,l]=o.split("."),u=Number.parseInt(c,10),d=l?Number.parseInt(l,10):void 0;a>=60&&(s+=1,a-=60);const h={hour:s,minute:a,second:u};if("number"==typeof d&&(h.millisecond=d),"string"==typeof r){const[e,t]=ge(r);if("number"!=typeof e||e>24||"number"!=typeof t||t>59)return null;h.timezoneHourOffset=e,h.timezoneMinuteOffset=t}return h}function he(e){if(!/-?\d{4,}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|(\+|-)\d\d:\d\d)?/.test(e))return null;const[t,r]=e.split("T"),[n,i]="-"===t.charAt(0)?[-1,t.substring(1)]:[1,t],[o,s,a]=i.split("-"),c=Number.parseInt(o,10)*n,l=Number.parseInt(s,10)-1,u=Number.parseInt(a,10),[d,h]=pe(r),[f,p]="string"==typeof h?ge(h):[0,0],[g,y,m]=d.split(":"),v=Number.parseInt(g,10)+f,b=Number.parseInt(y,10)+p,[w,_]=m.split("."),S=Number.parseInt(w,10),E=_?Number.parseInt(_,10):0,A=new Date(Date.UTC(c,l,u,v,b,S,E));return c>=0&&c<100&&A.setUTCFullYear(A.getUTCFullYear()-1900),A}function fe(e){if(!/-?\d{4,}-\d\d-\d\d(Z|(\+|-)\d\d:\d\d)?/.test(e))return null;const t=e,[r,n]="-"===t.charAt(0)?[-1,t.substring(1)]:[1,t],[i,o,s]=n.split("-"),a=s.length>2?s.substring(0,2):s,c=Number.parseInt(i,10)*r,l=Number.parseInt(o,10)-1,u=Number.parseInt(a,10),d=new Date(Date.UTC(c,l,u,12));return c>=0&&c<100&&d.setUTCFullYear(d.getUTCFullYear()-1900),d}function pe(e){if(e.endsWith("Z"))return[e.substring(0,e.length-1),"Z"];const t=e.split("+"),r=e.split("-");return 1===t.length&&1===r.length?[t[0],void 0]:t.length>r.length?[t[0],`+${t[1]}`]:[r[0],`-${r[1]}`]}function ge(e){if("Z"===e)return[0,0];const t="+"===e.charAt(0)?1:-1,[r,n]=e.substring(1).split(":");return[Number.parseInt(r,10)*t,Number.parseInt(n,10)*t]}function ye(e){const t=Number.parseFloat(e);return Number.isNaN(t)?null:t}function me(e){const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function ve(e){return e.toLowerCase()}function be(e){return we(e)&&"NamedNode"===e.termType}function we(e){return null!==e&&"object"==typeof e&&"string"==typeof e.termType&&"string"==typeof e.value&&"function"==typeof e.equals}function _e(e){return be(e)&&Q(e.value)}function Se(e){const t=g(e);if("function"!=typeof URL)return!0;try{return new URL(t),!0}catch(e){return!1}}function Ee(e,t){return Re.namedNode(Ae(X(e.value),t))}function Ae(e,t){if("function"!=typeof URL)throw new Error("The URL interface is not available, so an IRI cannot be determined.");const r=new URL(t);return r.hash=e,r.href}const Re=c;function Ie(e,t,r={}){var n;if(!["NamedNode","DefaultGraph"].includes(t.graph.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.graph.termType}] as their Graph node.`);const i="DefaultGraph"===t.graph.termType?"default":t.graph.value,o=null!==(n=e.graphs[i])&&void 0!==n?n:{};return Y({...e,graphs:Y({...e.graphs,[i]:Te(o,t,r)})})}function Te(e,t,r){var n;if(!["NamedNode","BlankNode"].includes(t.subject.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.subject.termType}] as their Subject node.`);const i="BlankNode"===t.subject.termType?`_:${t.subject.value}`:t.subject.value,o=null!==(n=e[i])&&void 0!==n?n:{type:"Subject",url:i,predicates:{}};return Y({...e,[i]:xe(o,t,r)})}function xe(e,t,r){return Y({...e,predicates:Pe(e.predicates,t,r)})}function Pe(e,t,r){var n;if(!["NamedNode"].includes(t.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.predicate.termType}] as their Predicate node.`);const i=t.predicate.value,o=null!==(n=e[i])&&void 0!==n?n:{};return Y({...e,[i]:Ce(o,t,r)})}function Ce(e,t,r){var n,i,o,s,a,c,l,u;if("NamedNode"===t.object.termType){const r=Y([...null!==(n=e.namedNodes)&&void 0!==n?n:[],t.object.value]);return Y({...e,namedNodes:r})}if("Literal"===t.object.termType){if(t.object.datatype.value===le){const r=t.object.language.toLowerCase(),n=Y([...null!==(o=null===(i=e.langStrings)||void 0===i?void 0:i[r])&&void 0!==o?o:[],t.object.value]),a=Y({...null!==(s=e.langStrings)&&void 0!==s?s:{},[r]:n});return Y({...e,langStrings:a})}const r=Y([...null!==(c=null===(a=e.literals)||void 0===a?void 0:a[t.object.datatype.value])&&void 0!==c?c:[],t.object.value]),n=Y({...null!==(l=e.literals)&&void 0!==l?l:{},[t.object.datatype.value]:r});return Y({...e,literals:n})}if("BlankNode"===t.object.termType){const n=ke(t.object,r),i=Y([...null!==(u=e.blankNodes)&&void 0!==u?u:[],n]);return Y({...e,blankNodes:i})}throw new Error(`Objects of type [${t.object.termType}] are not supported.`)}function ke(e,t){var r,n;if(void 0===(null!==(r=t.chainBlankNodes)&&void 0!==r?r:[]).find((t=>t.equals(e))))return te(e);const i=(null!==(n=t.otherQuads)&&void 0!==n?n:[]).filter((t=>t.subject.equals(e))),o=i.filter((e=>!Le(e.object))).reduce(((e,r)=>{var n;if(!["NamedNode"].includes(r.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${r.predicate.termType}] as their Predicate node.`);const i=null!==(n=e[r.predicate.value])&&void 0!==n?n:{};return Y({...e,[r.predicate.value]:Ce(i,r,t)})}),{});return i.filter((e=>Le(e.object))).reduce(((e,r)=>{var n,i;if(!["NamedNode"].includes(r.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${r.predicate.termType}] as their Predicate node.`);const o=null!==(n=e[r.predicate.value])&&void 0!==n?n:{},s=null!==(i=o.blankNodes)&&void 0!==i?i:[];return Y({...e,[r.predicate.value]:{...o,blankNodes:[...s,ke(r.object,t)]}})}),o)}function Oe(e){const t=e.map((e=>e.subject)).filter(Le),r=e.map((e=>e.object)).filter(Le),n=[];return r.forEach((t=>{n.push(...De(t,e))})),t.concat(r).filter((t=>{if(n.some((e=>e.equals(t))))return!1;const r=e.filter((e=>e.object.equals(t))).map((e=>e.subject));return r.length>0&&(i=r).every((e=>i.every((t=>e.equals(t)))));var i}))}function Fe(e,t={}){var r;const n=[],i=null!==(r=t.dataFactory)&&void 0!==r?r:c;return Object.keys(e.graphs).forEach((r=>{const o=e.graphs[r],s="default"===r?i.defaultGraph():i.namedNode(r);Object.keys(o).forEach((e=>{const{predicates:r}=o[e],a=Z(e)?i.blankNode(ee(e)):i.namedNode(e);n.push(...Ne(r,a,s,t))}))})),n}function Ne(e,t,r,n={}){var i;const o=[],s=null!==(i=n.dataFactory)&&void 0!==i?i:c;return Object.keys(e).forEach((n=>{var i,a,c,l;const u=s.namedNode(n),d=null!==(i=e[n].langStrings)&&void 0!==i?i:{},h=null!==(a=e[n].namedNodes)&&void 0!==a?a:[],f=null!==(c=e[n].literals)&&void 0!==c?c:{},p=null!==(l=e[n].blankNodes)&&void 0!==l?l:[];Object.keys(f).forEach((e=>{const n=s.namedNode(e);f[e].forEach((e=>{const i=s.literal(e,n);o.push(s.quad(t,u,i,r))}))})),Object.keys(d).forEach((e=>{d[e].forEach((n=>{const i=s.literal(n,e);o.push(s.quad(t,u,i,r))}))})),h.forEach((e=>{const n=s.namedNode(e);o.push(s.quad(t,u,n,r))})),p.forEach((e=>{if(Z(e)){const n=s.blankNode(ee(e));o.push(s.quad(t,u,n,r))}else{const n=s.blankNode(),i=s.quad(t,u,n,r),a=Ne(e,n,r);o.push(i),o.push(...a)}}))})),o}function De(e,t,r=[]){if(void 0!==r.find((t=>t.equals(e))))return r;const n=t.filter((t=>t.subject.equals(e)&&Le(t.object))).map((e=>e.object));if(0===n.length)return[];const i=[...r,e],o=n.map((e=>De(e,t,i))),s=[];for(const e of o)s.push(...e);return s}function Le(e){return"BlankNode"===e.termType}const Ue=()=>{const e=[],t=[],r=[];return{onQuad:t=>{e.push(t)},onError:e=>{r.push(e)},onComplete:e=>{t.push(e)},parse:async(n,i)=>{(await async function(e){return new a.Parser({format:"text/turtle",baseIRI:e})}($(i))).parse(n,((n,i)=>{n?r.forEach((e=>e(n))):i?e.forEach((e=>e(i))):t.forEach((e=>e()))}))}}};async function je(e,t){const r=new a.Writer({format:"text/turtle",prefixes:null==t?void 0:t.prefixes}),n=e.map((e=>Re.quad(e.subject,e.predicate,e.object,void 0)));r.addQuads(n);const i=new Promise(((e,t)=>{r.end(((r,n)=>{r?t(r):e(n)}))}));return await i}const Me={acl:"http://www.w3.org/ns/auth/acl#",acp:"http://www.w3.org/ns/solid/acp#",cc:"http://creativecommons.org/ns#",cert:"http://www.w3.org/ns/auth/cert#",csvw:"http://www.w3.org/ns/csvw#",current:"#",dc:"http://purl.org/dc/terms/",dcam:"http://purl.org/dc/dcam/",dcat:"http://www.w3.org/ns/dcat#",dctype:"http://purl.org/dc/dcmitype/",foaf:"http://xmlns.com/foaf/0.1/",ldp:"http://www.w3.org/ns/ldp#",owl:"http://www.w3.org/2002/07/owl#",posixstat:"http://www.w3.org/ns/posix/stat#",rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",schema:"https://schema.org/",shacl:"http://www.w3.org/ns/shacl#",skos:"http://www.w3.org/2004/02/skos/core#",skosxl:"http://www.w3.org/2008/05/skos-xl#",solid:"http://www.w3.org/ns/solid/terms#",swapdoc:"http://www.w3.org/2000/10/swap/pim/doc#",ui:"http://www.w3.org/ns/ui#",vann:"http://purl.org/vocab/vann/",vcard:"http://www.w3.org/2006/vcard/ns#",ws:"http://www.w3.org/ns/pim/space#",xsd:"http://www.w3.org/2001/XMLSchema#"},Be=l.dataset;function He(e,t={}){var r,n;return(null!==(n=null===(r=t.datasetFactory)||void 0===r?void 0:r.dataset)&&void 0!==n?n:Be)(Fe(e,t))}var We=Object.freeze({__proto__:null,getJsonLdParser:q,getTurtleParser:Ue,solidDatasetAsTurtle:async function(e,t){const{prefixes:r=Me,thing:n}={...t},i=new a.Writer({format:"application/turtle",prefixes:r}),o=n?new a.NamedNode(n):void 0;for(const t of He(e).match(o))i.addQuad(t);return new Promise(((e,t)=>{i.end(((r,n)=>{r?t(r):e(n)}))}))}});const $e={fetch:y},Ve=["Slug","If-None-Match","Content-Type"];async function Ke(e,t=$e){const r={...$e,...t},n=g(e),i=await r.fetch(n,r.init);if(b(i))throw new G(`Fetching the File failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i);const o=m(i),s=await i.blob();return Object.assign(s,{internal_resourceInfo:o})}async function Je(e,t,r=$e){const n=g(e),i=await Ge(n,t,"PUT",r);if(b(i))throw new G(`Overwriting the file at [${n}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i);const o=v(t),s=m(i);return s.sourceIri=n,s.isRawData=!0,Object.assign(o,{internal_resourceInfo:s})}async function Ge(e,t,r,n){var i,o;const s={...$e,...n},a=function(e){if(void 0===e)return{};let t={};var r;return r=e,Array.isArray(r)?e.forEach((([e,r])=>{t[e]=r})):function(e){return"function"==typeof e.forEach}(e)?e.forEach(((e,r)=>{t[r]=e})):t=e,t}(null!==(o=null===(i=s.init)||void 0===i?void 0:i.headers)&&void 0!==o?o:{});if(c=a,Ve.some((e=>void 0!==c[e])))throw new Error(`No reserved header (${Ve.join(", ")}) should be set in the optional RequestInit.`);var c;void 0!==s.slug&&(a.Slug=s.slug),a["Content-Type"]=qe(t,n.contentType);const l=g(e);return s.fetch(l,{...s.init,headers:a,method:r,body:t})}function qe(e,t){if("string"==typeof t)return t;const r="object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&e.type.length>0?e.type:void 0;return null!=r?r:"application/octet-stream"}function ze(e){var t,r,n,i,o,s,a,c;if(be(e))return`<${e.value}> (URL)`;if(function(e){return we(e)&&"Literal"===e.termType}(e)){if(!be(e.datatype))return`[${e.value}] (RDF/JS Literal of unknown type)`;let l;switch(e.datatype.value){case re:return l=null!==(r=null===(t=ue(e.value))||void 0===t?void 0:t.valueOf())&&void 0!==r?r:`Invalid data: \`${e.value}\``,`${l} (boolean)`;case ne:return l=null!==(i=null===(n=he(e.value))||void 0===n?void 0:n.toUTCString())&&void 0!==i?i:`Invalid data: \`${e.value}\``,`${l} (datetime)`;case se:return l=null!==(s=null===(o=ye(e.value))||void 0===o?void 0:o.toString())&&void 0!==s?s:`Invalid data: \`${e.value}\``,`${l} (decimal)`;case ae:return l=null!==(c=null===(a=me(e.value))||void 0===a?void 0:a.toString())&&void 0!==c?c:`Invalid data: \`${e.value}\``,`${l} (integer)`;case le:return`"${e.value}" (${e.language} string)`;case ce:return`"${e.value}" (string)`;default:return`[${e.value}] (RDF/JS Literal of type: \`${e.datatype.value}\`)`}}return"BlankNode"===e.termType?`[${e.value}] (RDF/JS BlankNode)`:"Quad"===e.termType?"??? (nested RDF* Quad)":"Variable"===e.termType?`?${e.value} (RDF/JS Variable)`:e}function Ye(e){if(!bt(e))throw new At(e)}function Qe(e,t){const r=f(e)?e.internal_changeLog:{additions:[],deletions:[]},[n,i]=t.filter((e=>!Xe(e))).reduce((([e,t],r)=>void 0!==e.find((e=>e.equals(r)))?[e.filter((e=>!e.equals(r))),t]:[e,t.concat(r)]),[r.additions,r.deletions]);return Y({...e,internal_changeLog:{additions:n,deletions:i}})}function Xe(e){return"BlankNode"===e.subject.termType||"BlankNode"===e.object.termType}function Ze(e,t){var r,n,i;if(Ye(e),!Se(t))throw new Rt(t);const o=g(t),s=null!==(i=null===(n=null===(r=e.predicates[o])||void 0===r?void 0:r.namedNodes)||void 0===n?void 0:n[0])&&void 0!==i?i:null;return null===s?null:Q(s)?`#${X(s)}`:s}const et=Ze;function tt(e,t){var r,n,i;if(Ye(e),!Se(t))throw new Rt(t);const o=g(t);return null!==(i=null===(n=null===(r=e.predicates[o])||void 0===r?void 0:r.namedNodes)||void 0===n?void 0:n.map((e=>Q(e)?`#${X(e)}`:e)))&&void 0!==i?i:[]}const rt=tt;function nt(e,t,r){var n,i;if(Ye(e),!Se(t))throw new Rt(t);const o=g(t),s=null!==(i=null===(n=e.predicates[o])||void 0===n?void 0:n.langStrings)&&void 0!==i?i:{},a=Object.keys(s).find((e=>e.toLowerCase()===r.toLowerCase()&&Array.isArray(s[e])&&s[e].length>0));return"string"==typeof a?s[a][0]:null}function it(e,t,r){var n,i;if(Ye(e),!Se(t))throw new Rt(t);const o=g(t),s=null!==(i=null===(n=e.predicates[o])||void 0===n?void 0:n.langStrings)&&void 0!==i?i:{},a=Object.keys(s).find((e=>e.toLowerCase()===r.toLowerCase()&&Array.isArray(s[e])&&s[e].length>0));return"string"==typeof a?[...s[a]]:[]}function ot(e,t){return Ye(e),ft(e,t,ce)}function st(e,t){const r=et(e,t);return null===r?null:Re.namedNode(r)}function at(e,t){return rt(e,t).map((e=>Re.namedNode(e)))}function ct(e,t){var r,n,i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=g(t),a=null!==(n=null===(r=e.predicates[s])||void 0===r?void 0:r.langStrings)&&void 0!==n?n:{},c=Object.keys(a);if(c.length>0){const e=c.find((e=>Array.isArray(a[e])&&a[e].length>0));if("string"==typeof e)return Re.literal(a[e][0],e)}const l=null!==(o=null===(i=e.predicates[s])||void 0===i?void 0:i.literals)&&void 0!==o?o:{},u=Object.keys(l);if(u.length>0){const e=u.find((e=>Array.isArray(l[e])&&l[e].length>0));if("string"==typeof e)return Re.literal(l[e][0],Re.namedNode(e))}return null}function lt(e,t){var r,n,i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=g(t);let a=[];const c=null!==(n=null===(r=e.predicates[s])||void 0===r?void 0:r.langStrings)&&void 0!==n?n:{},l=Object.keys(c);for(const e of l){const t=c[e].map((t=>Re.literal(t,e)));a=a.concat(t)}const u=null!==(o=null===(i=e.predicates[s])||void 0===i?void 0:i.literals)&&void 0!==o?o:{},d=Object.keys(u);for(const e of d){const t=u[e],r=Re.namedNode(e),n=t.map((e=>Re.literal(e,r)));a=a.concat(n)}return a}function ut(e,t){var r,n;Ye(e);const i=st(e,t);if(null!==i)return i;const o=ct(e,t);if(null!==o)return o;const s=g(t),a=null!==(n=null===(r=e.predicates[s])||void 0===r?void 0:r.blankNodes)&&void 0!==n?n:[];if(a.length>0){const e=Z(a[0])?ee(a[0]):void 0;return Re.blankNode(e)}return null}function dt(e,t){var r,n;Ye(e);const i=at(e,t),o=lt(e,t),s=g(t),a=(null!==(n=null===(r=e.predicates[s])||void 0===r?void 0:r.blankNodes)&&void 0!==n?n:[]).map((e=>{const t=Z(e)?ee(e):void 0;return Re.blankNode(t)}));return i.concat(o).concat(a)}function ht(e,t,r){var n,i,o,s;if(!Se(t))throw new Rt(t);const a=g(t);return null!==(s=null===(o=null===(i=null===(n=e.predicates[a])||void 0===n?void 0:n.literals)||void 0===i?void 0:i[r])||void 0===o?void 0:o[0])&&void 0!==s?s:null}function ft(e,t,r){var n,i,o;if(!Se(t))throw new Rt(t);const s=g(t);return[...null!==(o=null===(i=null===(n=e.predicates[s])||void 0===n?void 0:n.literals)||void 0===i?void 0:i[r])&&void 0!==o?o:[]]}function pt(e,t,r={}){var n;if(!Se(t))throw new Tt(t);const i=void 0!==r.scope?g(r.scope):"default",o=null!==(n=e.graphs[i])&&void 0!==n?n:{},s=g(t),a=o[Q(s)&&h(e)?Ae(X(s),$(e)):s];return void 0===a?null:a}function gt(e,t={acceptBlankNodes:!1}){var r;const n=void 0!==t.scope?g(t.scope):"default",i=null!==(r=e.graphs[n])&&void 0!==r?r:{};return Object.values(i).filter((e=>!Z(e.url)||t.acceptBlankNodes))}function yt(e,t){var r;const n=Et(t)&&h(e)?Ae(X(t.url),$(e)):t.url,i=e.graphs.default,o=Y({...i,[n]:Y({...t,url:n})}),s=Y({...e.graphs,default:o}),a=Re.namedNode(n),c=null===(r=e.graphs.default[n])||void 0===r?void 0:r.predicates,l=void 0!==c?Ne(c,a,Re.defaultGraph()):[],u=Ne(t.predicates,a,Re.defaultGraph());return function(e,t){const r=f(e)?e.internal_changeLog:{additions:[],deletions:[]},[n,i]=t.filter((e=>!Xe(e))).reduce((([e,t],r)=>void 0!==t.find((e=>e.equals(r)))?[e,t.filter((e=>!e.equals(r)))]:[e.concat(r),t]),[r.additions,r.deletions]);return Y({...e,internal_changeLog:{additions:n,deletions:i}})}(Qe(Y({...e,graphs:s}),l),u)}function mt(e,t){var r;let n;n=be(t)?t.value:"string"==typeof t?Q(t)&&h(e)?Ae(X(t),$(e)):t:Et(t)?t.url:_t(t);const i={...e.graphs.default};delete i[n];const o=Y({...e.graphs,default:Y(i)}),s=Re.namedNode(n),a=null===(r=e.graphs.default[n])||void 0===r?void 0:r.predicates,c=void 0!==a?Ne(a,s,Re.defaultGraph()):[];return Qe(Y({...e,graphs:o}),c)}function vt(e={}){var t;if(void 0!==e.url){const{url:t}=e;if(!Se(t))throw new Tt(t);return Y({type:"Subject",predicates:Y({}),url:t})}const r=null!==(t=e.name)&&void 0!==t?t:xt(),n=`${z}${r}`;return Y({type:"Subject",predicates:Y({}),url:n})}function bt(e){return"object"==typeof e&&null!==e&&"string"==typeof e.type&&"Subject"===e.type}function wt(e,t){if(Et(e)){if(void 0===t)throw new Error("The URL of a Thing that has not been persisted cannot be determined without a base URL.");return Ae(X(e.url),t)}return e.url}const _t=wt;function St(e){let t="";Et(e)?t+=`## Thing (no URL yet — identifier: \`#${X(e.url)}\`)\n`:t+=`## Thing: ${e.url}\n`;const r=Object.keys(e.predicates);if(0===r.length)t+="\n\n";else for(const n of r)t+=`\nProperty: ${n}\n`,t+=dt(e,n).reduce(((e,t)=>`${e}- ${ze(t)}\n`),"");return t}function Et(e){return Q(e.url)}class At extends p{constructor(e){super(`Expected a Thing, but received: [${e}].`),this.receivedValue=e}}class Rt extends p{constructor(e){const t=be(e)?e.value:e;super(`Expected a valid URL to identify a property, but received: [${t}].`),this.receivedProperty=t}}class It extends p{constructor(e){const t=be(e)?e.value:e;super(`Expected a valid URL value, but received: [${t}].`),this.receivedValue=t}}class Tt extends p{constructor(e){const t=be(e)?e.value:e;super(`Expected a valid URL to identify a Thing, but received: [${t}].`),this.receivedValue=t}}const xt=()=>u.v4();function Pt(e){const t=new URL(e);return t.hash="",t.href}function Ct(){return Y({type:"Dataset",graphs:{default:{}}})}async function kt(e,t={}){if(b(e))throw new G(`Fetching the SolidDataset at [${e.url}] failed: [${e.status}] [${e.statusText}] ${await e.text()}.`,e);const r=B(e),n={"text/turtle":Ue(),...t.parsers},i=W(r);if(null===i)throw new Error(`Could not determine the content type of the Resource at [${$(r)}].`);const o=i.split(";")[0],s=n[o];if(void 0===s)throw new Error(`The Resource at [${$(r)}] has a MIME type of [${o}], but the only parsers available are for the following MIME types: [${Object.keys(n).join(", ")}].`);const a=await e.text();return new Promise(((e,t)=>{let n=Y({graphs:Y({default:Y({})}),type:"Dataset"});const o=[],c=[];s.onError((e=>{t(new Error(`Encountered an error parsing the Resource at [${$(r)}] with content type [${i}]: ${e}`))})),s.onQuad((e=>{c.push(e),"BlankNode"===e.subject.termType||"BlankNode"===e.object.termType?o.push(e):n=Ie(n,e)})),s.onComplete((async()=>{const t=o.length<=20?Oe(o):[],i=o.filter((e=>t.every((t=>!t.equals(e.subject)))));n=i.reduce(((e,r)=>Ie(e,r,{otherQuads:c,chainBlankNodes:t})),n);const s=Y({...n,...r});e(s)})),s.parse(a,r)}))}async function Ot(e,t=j){var r;e=g(e);const n={...j,...t},i=Object.keys(null!==(r=t.parsers)&&void 0!==r?r:{}),o=i.length>0?i.join(", "):"text/turtle",s=await n.fetch(e,{headers:{Accept:o}});if(b(s))throw new G(`Fetching the Resource at [${e}] failed: [${s.status}] [${s.statusText}] ${await s.text()}.`,s);return await kt(s,t)}async function Ft(e,t,r=j){e=g(e);const n={...j,...r},i=function(e){return f(e)?e:Y({...e,internal_changeLog:{additions:[],deletions:[]}})}(t),o=Nt(i,e)?await async function(e){return{method:"PATCH",body:`${e.internal_changeLog.deletions.length>0?`DELETE DATA {${(await je(e.internal_changeLog.deletions.map(jt))).trim()}};`:""} ${e.internal_changeLog.additions.length>0?`INSERT DATA {${(await je(e.internal_changeLog.additions.map(jt))).trim()}};`:""}`,headers:{"Content-Type":"application/sparql-update"}}}(i):await async function(e,t){return{method:"PUT",body:await je(Fe(e).map(jt),t),headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:`<${k}>; rel="type"`}}}(i,r),s=await n.fetch(e,o);if(b(s)){const t=Nt(i,e)?`The changes that were sent to the Pod are listed below.\n\n${Ut(i)}`:`The SolidDataset that was sent to the Pod is listed below.\n\n${Lt(i)}`;throw new G(`Storing the Resource at [${e}] failed: [${s.status}] [${s.statusText}] ${await s.text()}.\n\n${t}`,s)}const a={...m(s),isRawData:!1};return Bt(Y({...t,internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:a}))}function Nt(e,t){return f(e)&&d(e)&&"string"==typeof e.internal_resourceInfo.sourceIri&&(r=t,Pt(e.internal_resourceInfo.sourceIri)===Pt(r));var r}function Dt(e,t){const r=new URL(t),n=new URL(e),i=n.href.startsWith(r.href),o=n.pathname.substring(r.pathname.length,n.pathname.length).replace(/(^\/)|(\/$)/g,"");return i&&o.length>=1&&!o.includes("/")}function Lt(e){let t="";d(e)?t+=`# SolidDataset: ${$(e)}\n`:t+="# SolidDataset (no URL yet)\n";const r=gt(e);return 0===r.length?t+="\n\n":r.forEach((r=>{t+=`\n${St(r)}`,f(e)&&(t+=`\n${function(e,t){const r=Re.namedNode(t.url),n=e.internal_changeLog.additions.reduce(((e,t)=>t.subject.equals(r)?e+1:e),0),i=e.internal_changeLog.deletions.reduce(((e,t)=>t.subject.equals(r)?e+1:e),0);return`(${1===n?"1 new value added":`${n} new values added`} / ${1===i?"1 value removed":`${i} values removed`})`}(e,r)}\n`)})),t}function Ut(e){if(!d(e))return"This is a newly initialized SolidDataset, so there is no source to compare it to.";if(!f(e)||0===e.internal_changeLog.additions.length&&0===e.internal_changeLog.deletions.length)return`## Changes compared to ${$(e)}\n\nThis SolidDataset has not been modified since it was fetched from ${$(e)}.\n`;let t=`## Changes compared to ${$(e)}\n`;const r=function(e){const t=Object.create(null);return e.internal_changeLog.deletions.forEach((r=>{var n,i,o;const s=_e(r.subject)?Ee(r.subject,$(e)):r.subject;if(!be(s)||!be(r.predicate))return;const a=g(s),c=g(r.predicate);null!==(n=t[a])&&void 0!==n||(t[a]=Object.create(null)),null!==(i=(o=t[a])[c])&&void 0!==i||(o[c]={added:[],deleted:[]}),t[a][c].deleted.push(r.object)})),e.internal_changeLog.additions.forEach((r=>{var n,i,o;const s=_e(r.subject)?Ee(r.subject,$(e)):r.subject;if(!be(s)||!be(r.predicate))return;const a=g(s),c=g(r.predicate);null!==(n=t[a])&&void 0!==n||(t[a]=Object.create(null)),null!==(i=(o=t[a])[c])&&void 0!==i||(o[c]={added:[],deleted:[]}),t[a][c].added.push(r.object)})),t}(e);return Object.keys(r).forEach((e=>{t+=`\n### Thing: ${e}\n`;const n=r[e];Object.keys(n).forEach((e=>{t+=`\nProperty: ${e}\n`;const{deleted:r}=n[e],{added:i}=n[e];r.length>0&&(t+="- Removed:\n",t+=r.reduce(((e,t)=>`${e} - ${ze(t)}\n`),"")),i.length>0&&(t+="- Added:\n",t+=i.reduce(((e,t)=>`${e} - ${ze(t)}\n`),""))}))})),t}function jt(e){const t=be(e.subject)?Mt(e.subject):e.subject,r=be(e.object)?Mt(e.object):e.object;return Re.quad(t,e.predicate,r,e.graph)}function Mt(e){return Q(e.value)?Re.namedNode(`#${X(e.value)}`):e}function Bt(e){const t=$(e),r=e.graphs.default,n=Object.keys(r).reduce(((e,r)=>{const n=function(e,t){const r=Object.keys(e.predicates).reduce(((e,r)=>{var n;const i=null!==(n=e[r].namedNodes)&&void 0!==n?n:[];if(i.every((e=>!Q(e))))return e;const o=Y(i.map((e=>Q(e)?`${t}#${X(e)}`:e))),s=Y({...e[r],namedNodes:o});return Y({...e,[r]:s})}),e.predicates);return Y({...e,predicates:r,url:Q(e.url)?`${t}#${X(e.url)}`:e.url})}(e[r],t),i=Q(r)?`${t}#${X(r)}`:r,o={...e};return delete o[r],o[i]=n,Y(o)}),r),i=Y({...e.graphs,default:n});return Y({...e,graphs:i})}function Ht(e){return{...Ct(),internal_resourceInfo:{sourceIri:g(e),isRawData:!1,contentType:"text/turtle",linkedResources:{}}}}function Wt(e){const t=g(e);if(!t.endsWith("/"))throw new Error("A Container's URL should end in a slash. Please update your tests.");return Ht(t)}const $t=(e,t,r)=>{var n,i;if(Ye(e),!Se(t))throw new Rt(t);if(!bt(r)&&!Se(r))throw new It(r);const o=g(t),s=null!==(n=e.predicates[o])&&void 0!==n?n:{},a=null!==(i=s.namedNodes)&&void 0!==i?i:[];let c;c=be(r)?r.value:"string"==typeof r?r:Et(r)?r.url:_t(r);const l=Y(a.concat(g(c))),u=Y({...s,namedNodes:l}),d=Y({...e.predicates,[o]:u});return Y({...e,predicates:d})},Vt=$t,Kt=(e,t,r)=>(Ye(e),rr(e,t,function(e){return e?"true":"false"}(r),re)),Jt=(e,t,r)=>(Ye(e),rr(e,t,function(e){return e.toISOString()}(r),ne)),Gt=(e,t,r)=>(Ye(e),rr(e,t,function(e){const t=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),[,i]=pe(e.toISOString());return`${t}-${String(r).padStart(2,"0")}-${String(n).padStart(2,"0")}${i}`}(r),ie)),qt=(e,t,r)=>(Ye(e),rr(e,t,function(e){let t,r;if(e.millisecond&&(t=e.millisecond<10?`00${e.millisecond}`:e.millisecond<100?`0${e.millisecond}`:e.millisecond),"number"==typeof e.timezoneHourOffset){const t=Math.abs(e.timezoneHourOffset)<10?`0${Math.abs(e.timezoneHourOffset)}`:Math.abs(e.timezoneHourOffset);r=e.timezoneHourOffset>=0?`+${t}`:`-${t}`,e.timezoneMinuteOffset?r=`${r}:${e.timezoneMinuteOffset<10?`0${e.timezoneMinuteOffset}`:e.timezoneMinuteOffset}`:r+=":00"}return`${e.hour<10?`0${e.hour}`:e.hour}:${e.minute<10?`0${e.minute}`:e.minute}:${e.second<10?`0${e.second}`:e.second}${e.millisecond?`.${t}`:""}${r||""}`}(r),oe)),zt=(e,t,r)=>(Ye(e),rr(e,t,function(e){return e.toString()}(r),se)),Yt=(e,t,r)=>(Ye(e),rr(e,t,function(e){return e.toString()}(r),ae));function Qt(e,t,r,n){var i,o,s;if(Ye(e),!Se(t))throw new Rt(t);const a=g(t),c=ve(n),l=null!==(i=e.predicates[a])&&void 0!==i?i:{},u=null!==(o=l.langStrings)&&void 0!==o?o:{},d=null!==(s=u[c])&&void 0!==s?s:[],h=Y(d.concat(r)),f=Y({...u,[c]:h}),p=Y({...l,langStrings:f}),y=Y({...e.predicates,[a]:p});return Y({...e,predicates:y})}const Xt=(e,t,r)=>(Ye(e),rr(e,t,r,ce));function Zt(e,t,r){return $t(e,t,r.value)}function er(e,t,r){if(Ye(e),!Se(t))throw new Rt(t);return r.datatype.value===le?Qt(e,t,r.value,r.language):rr(e,t,r.value,r.datatype.value)}function tr(e,t,r){var n,i;if("NamedNode"===r.termType)return Zt(e,t,r);if("Literal"===r.termType)return er(e,t,r);if("BlankNode"===r.termType){if(Ye(e),!Se(t))throw new Rt(t);const o=g(t),s=null!==(n=e.predicates[o])&&void 0!==n?n:{},a=null!==(i=s.blankNodes)&&void 0!==i?i:[],c=Y(a.concat(te(r))),l=Y({...s,blankNodes:c}),u=Y({...e.predicates,[o]:l});return Y({...e,predicates:u})}throw new Error(`Term type [${r.termType}] is not supported by @inrupt/solid-client.`)}function rr(e,t,r,n){var i,o,s;if(Ye(e),!Se(t))throw new Rt(t);const a=g(t),c=null!==(i=e.predicates[a])&&void 0!==i?i:{},l=null!==(o=c.literals)&&void 0!==o?o:{},u=null!==(s=l[n])&&void 0!==s?s:[],d=Y(u.concat(r)),h=Y({...l,[n]:d}),f=Y({...c,literals:h}),p=Y({...e.predicates,[a]:f});return Y({...e,predicates:p})}function nr(e,t){if(Ye(e),!Se(t))throw new Rt(t);const r=g(t),n={...e.predicates};return delete n[r],Y({...e,predicates:Y(n)})}const ir=(e,t,r)=>{var n,i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=g(t);if(!bt(r)&&!Se(r))throw new It(r);const a=bt(r)?_t(r):g(r),c=Y(null!==(o=null===(i=null===(n=e.predicates[s])||void 0===n?void 0:n.namedNodes)||void 0===i?void 0:i.filter((e=>e.toLowerCase()!==a.toLowerCase())))&&void 0!==o?o:[]),l=Y({...e.predicates[s],namedNodes:c}),u=Y({...e.predicates,[s]:l});return Y({...e,predicates:u})},or=ir,sr=(e,t,r)=>(Ye(e),yr(e,t,re,(e=>ue(e)===r))),ar=(e,t,r)=>(Ye(e),yr(e,t,ne,(e=>{var t;return(null===(t=he(e))||void 0===t?void 0:t.getTime())===r.getTime()}))),cr=(e,t,r)=>(Ye(e),yr(e,t,ie,(function(e){const t=fe(e);return!!t&&t.getFullYear()===r.getFullYear()&&t.getMonth()===r.getMonth()&&t.getUTCDate()===r.getUTCDate()}))),lr=(e,t,r)=>(Ye(e),yr(e,t,oe,(function(e){const t=de(e);return!!t&&t.hour===r.hour&&t.minute===r.minute&&t.second===r.second&&t.millisecond===r.millisecond&&t.timezoneHourOffset===r.timezoneHourOffset&&t.timezoneMinuteOffset===r.timezoneMinuteOffset}))),ur=(e,t,r)=>(Ye(e),yr(e,t,se,(e=>ye(e)===r))),dr=(e,t,r)=>(Ye(e),yr(e,t,ae,(e=>me(e)===r)));function hr(e,t,r,n){var i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=g(t),a=null!==(o=null===(i=e.predicates[s])||void 0===i?void 0:i.langStrings)&&void 0!==o?o:{},c=Object.keys(a).find((e=>ve(e)===ve(n)&&Array.isArray(a[e])&&a[e].length>0));if("string"!=typeof c)return e;const l=a[c],u=Y(l.filter((e=>e!==r))),d=Y({...a,[c]:u}),h=Y({...e.predicates[s],langStrings:d}),f=Y({...e.predicates,[s]:h});return Y({...e,predicates:f})}const fr=(e,t,r)=>(Ye(e),yr(e,t,ce,(e=>e===r)));function pr(e,t,r){return ir(e,t,r.value)}function gr(e,t,r){var n,i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=r.datatype.value;if(s===le)return hr(e,t,r.value,r.language);const a=g(t),c=null!==(n=e.predicates[a])&&void 0!==n?n:{},l=null!==(i=c.literals)&&void 0!==i?i:{},u=null!==(o=l[s])&&void 0!==o?o:[],d=Y(u.filter((e=>e!==r.value))),h=Y({...l,[s]:d}),f=Y({...c,literals:h}),p=Y({...e.predicates,[a]:f});return Y({...e,predicates:p})}function yr(e,t,r,n){var i,o,s;if(!Se(t))throw new Rt(t);const a=g(t),c=null!==(i=e.predicates[a])&&void 0!==i?i:{},l=null!==(o=c.literals)&&void 0!==o?o:{},u=null!==(s=l[r])&&void 0!==s?s:[],d=Y(u.filter((e=>!n(e)))),h=Y({...l,[r]:d}),f=Y({...c,literals:h}),p=Y({...e.predicates,[a]:f});return Y({...e,predicates:p})}const mr=(e,t,r)=>{if(Ye(e),!Se(t))throw new Rt(t);if(!bt(r)&&!Se(r))throw new It(r);return $t(nr(e,t),t,r)},vr=mr,br=(e,t,r)=>(Ye(e),Kt(nr(e,t),t,r)),wr=(e,t,r)=>(Ye(e),Jt(nr(e,t),t,r)),_r=(e,t,r)=>(Ye(e),Gt(nr(e,t),t,r)),Sr=(e,t,r)=>(Ye(e),qt(nr(e,t),t,r)),Er=(e,t,r)=>(Ye(e),zt(nr(e,t),t,r)),Ar=(e,t,r)=>(Ye(e),Yt(nr(e,t),t,r));function Rr(e,t,r,n){return Ye(e),Qt(nr(e,t),t,r,n)}const Ir=(e,t,r)=>(Ye(e),Xt(nr(e,t),t,r));function Tr(e,t,r){return Ye(e),Zt(nr(e,t),t,r)}function xr(e,t,r){return Ye(e),er(nr(e,t),t,r)}function Pr(e,t,r){if(Ye(e),!Se(t))throw new Rt(t);return tr(nr(e,t),t,r)}function Cr(e=vt()){let t=bt(e)?e:vt(e);function r(e){return(r,n)=>(t=e(t,r,n),o)}function n(e){return(r,n)=>(t=e(t,r,n),o)}function i(e){return(r,n)=>(t=e(t,r,n),o)}const o={build:()=>t,addUrl:r($t),addIri:r(Vt),addBoolean:r(Kt),addDatetime:r(Jt),addDate:r(Gt),addTime:r(qt),addDecimal:r(zt),addInteger:r(Yt),addStringNoLocale:r(Xt),addStringEnglish:(e,r)=>(t=Qt(t,e,r,"en"),o),addStringWithLocale:(e,r,n)=>(t=Qt(t,e,r,n),o),addNamedNode:r(Zt),addLiteral:r(er),addTerm:r(tr),setUrl:n(mr),setIri:n(vr),setBoolean:n(br),setDatetime:n(wr),setDate:n(_r),setTime:n(Sr),setDecimal:n(Er),setInteger:n(Ar),setStringNoLocale:n(Ir),setStringEnglish:(e,r)=>(t=Rr(t,e,r,"en"),o),setStringWithLocale:(e,r,n)=>(t=Rr(t,e,r,n),o),setNamedNode:n(Tr),setLiteral:n(xr),setTerm:n(Pr),removeAll:e=>(t=nr(t,e),o),removeUrl:i(ir),removeIri:i(or),removeBoolean:i(sr),removeDatetime:i(ar),removeDate:i(cr),removeTime:i(lr),removeDecimal:i(ur),removeInteger:i(dr),removeStringNoLocale:i(fr),removeStringEnglish:(e,r)=>Cr(hr(t,e,r,"en")),removeStringWithLocale:(e,r,n)=>Cr(hr(t,e,r,n)),removeNamedNode:i(pr),removeLiteral:i(gr)};return o}function kr(e){const t=J(e).type;return Array.isArray(t)&&t.includes(N.AccessControlResource)}async function Or(e,t=j){if(!sn(e))return{resourceAcl:null,fallbackAcl:null};try{const r=await Fr(e,t);return null===r?{resourceAcl:null,fallbackAcl:await Nr(e,t)}:{resourceAcl:r,fallbackAcl:null}}catch(e){if(e instanceof Qr)return{resourceAcl:null,fallbackAcl:null};throw e}}async function Fr(e,t=j){if(!sn(e))return null;try{const r=await Ot(e.internal_resourceInfo.aclUrl,t);if(kr(r))throw new Qr(e,r);return Y({...r,internal_accessTo:$(e)})}catch(e){if(e instanceof Qr)throw e;return null}}async function Nr(e,t=j){const r=new URL($(e)),n=r.pathname;if("/"===n)return null;const i=Dr(n),o=new URL(i,r.origin).href,s=await M(o,t);if(!sn(s))return null;const a=await Fr(s,t);return null===a?Nr(s,t):a}function Dr(e){const t="/"===e.substring(e.length-1)?e.substring(0,e.length-1):e;return`${e.substring(0,t.lastIndexOf("/"))}/`}function Lr(e){return gt(e).filter(Ur)}function Ur(e){return rt(e,P).includes(w)}function jr(e,t){return e.filter((e=>function(e,t){return rt(e,_).includes(t)}(e,t)))}function Mr(e,t){return e.filter((e=>function(e,t){return rt(e,R).includes(t)||rt(e,I).includes(t)}(e,t)))}function Br(e){const t=rt(e,T);return t.includes($r.write)?{read:t.includes($r.read),append:!0,write:!0,control:t.includes($r.control)}:{read:t.includes($r.read),append:t.includes($r.append),write:!1,control:t.includes($r.control)}}function Hr(e){return e.reduce(((e,t)=>e.write||t.write?{read:e.read||t.read,append:!0,write:!0,control:e.control||t.control}:{read:e.read||t.read,append:e.append||t.append,write:!1,control:e.control||t.control}),{read:!1,append:!1,write:!1,control:!1})}function Wr(e){return!Ne(e.predicates,Re.namedNode(e.url),Re.defaultGraph()).some((e=>!function(e){const{predicate:t}=e,{object:r}=e;return!(!t.equals(Re.namedNode(P))||!r.equals(Re.namedNode(w)))||(!!(t.equals(Re.namedNode(_))||t.equals(Re.namedNode(R))||t.equals(Re.namedNode(I)))||(!(!t.equals(Re.namedNode(T))||!Object.values($r).some((e=>r.equals(Re.namedNode(e)))))||(!!(t.equals(Re.namedNode(S))||t.equals(Re.namedNode(E))||t.equals(Re.namedNode(A)))||!!t.equals(Re.namedNode(x)))))}(e)))&&(null===et(e,_)&&null===et(e,R)&&null===et(e,I)||null===et(e,T)||null===et(e,S)&&null===et(e,E)&&null===et(e,A))}const $r={read:"http://www.w3.org/ns/auth/acl#Read",append:"http://www.w3.org/ns/auth/acl#Append",write:"http://www.w3.org/ns/auth/acl#Write",control:"http://www.w3.org/ns/auth/acl#Control"};function Vr(e,t,r){return e.filter((e=>rt(e,r).includes(t)))}function Kr(e,t){const r={};return e.forEach((e=>{const n=rt(e,t),i=Br(e);n.forEach((e=>{r[e]=void 0===r[e]?i:Hr([r[e],i])}))})),r}function Jr(e){let t=vt();return t=vr(t,P,w),e.read&&(t=Vt(t,T,$r.read)),e.append&&!e.write&&(t=Vt(t,T,$r.append)),e.write&&(t=Vt(t,T,$r.write)),e.control&&(t=Vt(t,T,$r.control)),t}function Gr(e,t){return Object.assign(v(e),{internal_acl:t})}const qr=[S,A,E,x];function zr(e,t,r,n,i){let o=e;gt(e).forEach((t=>{const[s,a]=function(e,t,r,n,i){if(!rt(e,r).includes(t))return[e,Jr({read:!1,append:!1,write:!1,control:!1})];const o=or(e,r,t);let s=function(e){let t=vt();function r(e,t,r){return rt(e,r).reduce(((e,t)=>Vt(e,r,t)),t)}return t=vr(t,P,w),t=r(e,t,_),t=r(e,t,R),t=r(e,t,I),t=r(e,t,S),t=r(e,t,E),t=r(e,t,A),t=r(e,t,x),t=r(e,t,T),t}(e);return s=or(s,"resource"===i?_:R,n),"default"===i&&(s=or(s,I,n)),s=vr(s,r,t),qr.filter((e=>e!==r)).forEach((e=>{s=nr(s,e)})),[o,s]}(t,i,r,e.internal_accessTo,n);o=yt(o,s),o=yt(o,a)}));let s=Jr(t);return s=vr(s,"resource"===n?_:R,e.internal_accessTo),s=vr(s,r,i),function(e){return Lr(e).filter(Wr).reduce(mt,e)}(yt(o,s))}function Yr(e,t){return Gr(e,{resourceAcl:t,fallbackAcl:null})}class Qr extends Error{constructor(e,t){super(`[${V(e)}] is governed by Access Control Policies in [${V(t)}] rather than by Web Access Control.`)}}function Xr(e){return null!==e.internal_acl.resourceAcl&&$(e)===e.internal_acl.resourceAcl.internal_accessTo&&e.internal_resourceInfo.aclUrl===$(e.internal_acl.resourceAcl)}function Zr(e){return Xr(e)?e.internal_acl.resourceAcl:null}function en(e){return null!==e.internal_acl.fallbackAcl}function tn(e){return en(e)?e.internal_acl.fallbackAcl:null}function rn(e){return Y({...Ct(),internal_accessTo:$(e),internal_resourceInfo:{sourceIri:e.internal_resourceInfo.aclUrl,isRawData:!1,linkedResources:{}}})}function nn(e){const t=rn(e);return Mr(Lr(e.internal_acl.fallbackAcl),e.internal_acl.fallbackAcl.internal_accessTo).map((t=>(t=nr(t,R),t=nr(t,I),t=vr(t,_,$(e)),vr(t,R,$(e))))).reduce(yt,t)}async function on(e,t,r=j){if(!sn(e))throw new Error(`Could not determine the location of the ACL for the Resource at [${$(e)}]; possibly the current user does not have Control access to that Resource. Try calling \`hasAccessibleAcl()\` before calling \`saveAclFor()\`.`);return{...await Ft(e.internal_resourceInfo.aclUrl,t,r),internal_accessTo:$(e)}}function sn(e){return"string"==typeof e.internal_resourceInfo.aclUrl}function an(e,t){return Xr(e)?ln(e.internal_acl.resourceAcl,t):en(e)?hn(e.internal_acl.fallbackAcl,t):null}function cn(e){return Xr(e)?un(Zr(e)):en(e)?fn(tn(e)):null}function ln(e,t){return Hr(pn(jr(Lr(e),e.internal_accessTo),t).map(Br))}function un(e){return mn(gn(jr(Lr(e),e.internal_accessTo)))}function dn(e,t,r){return zr(e,r,S,"resource",t)}function hn(e,t){return Hr(pn(Mr(Lr(e),e.internal_accessTo),t).map(Br))}function fn(e){return mn(gn(Mr(Lr(e),e.internal_accessTo)))}function pn(e,t){return Vr(e,t,S)}function gn(e){return e.filter(yn)}function yn(e){return null!==et(e,S)}function mn(e){return Kr(e,S)}function vn(e,t){return Xr(e)?wn(e.internal_acl.resourceAcl,t):en(e)?Sn(e.internal_acl.fallbackAcl,t):null}function bn(e){return Xr(e)?_n(Zr(e)):en(e)?En(tn(e)):null}function wn(e,t){return Hr(An(jr(Lr(e),e.internal_accessTo),t).map(Br))}function _n(e){return Rn(jr(Lr(e),e.internal_accessTo))}function Sn(e,t){return Hr(An(Mr(Lr(e),e.internal_accessTo),t).map(Br))}function En(e){return Rn(Mr(Lr(e),e.internal_accessTo))}function An(e,t){return Vr(e,t,E)}function Rn(e){return Kr(e,E)}function In(e,t,r){return zr(e,r,E,"resource",t)}function Tn(e){return Xr(e)?xn(e.internal_acl.resourceAcl):en(e)?Pn(e.internal_acl.fallbackAcl):null}function xn(e){return Hr(kn(jr(Lr(e),e.internal_accessTo),F).map(Br))}function Pn(e){return Hr(kn(Mr(Lr(e),e.internal_accessTo),F).map(Br))}function Cn(e,t){return zr(e,t,A,"resource",F)}function kn(e,t){return e.filter((e=>function(e,t){return rt(e,A).includes(t)}(e,t)))}function On(e,t){const r=pt(e,t);if(null===r)throw new Error(`Profile document [${$(e)}] does not include WebID [${t}]`);return r}function Fn(e,t){return Ze(On(e,t),L)}async function Nn(e,t,r=j){const n={...j,...r},i=await n.fetch(t);if(!i.ok)throw new Error(`Fetching [${t}] returned an error: ${i.status} ${i.statusText}`);try{const r=await i.json();if(!(e=>void 0!==e.keys)(r))throw new Error(`[${t}] does not dereference to a valid JWKS: ${JSON.stringify(r)}`);return{keys:[...r.keys,e]}}catch(e){throw new Error(`Parsing the document at [${t}] failed: ${e}`)}}function Dn(e,t){const r=pt(t,e),n=gt(t).filter((e=>rt(e,"http://xmlns.com/foaf/0.1/primaryTopic").length>0)).map(_t).concat(r?rt(r,"http://www.w3.org/2000/01/rdf-schema#seeAlso"):[]).concat(r?rt(r,"http://xmlns.com/foaf/0.1/isPrimaryTopicOf"):[]).filter((e=>e!==V(t)));return Array.from(new Set(n))}async function Ln(e,t=j){var r,n;const i=null!==(r=t.fetch)&&void 0!==r?r:y,o=null!==(n=t.webIdProfile)&&void 0!==n?n:await Ot(e,{fetch:y});return{webIdProfile:o,altProfileAll:(await Promise.allSettled(Dn(e,o).map((e=>Ot(e,{fetch:i}))))).filter((e=>"fulfilled"===e.status)).map((e=>e.value))}}function Un(e,t){const r=new Set;return[e.webIdProfile,...e.altProfileAll].forEach((e=>{const n=pt(e,t);null!==n&&rt(n,U).forEach((e=>r.add(e)))})),Array.from(r)}function jn(e){if(!Hi(e))throw new Error(`An Access Control Resource for [${$(e)}] is not available. This could be because the current user is not allowed to see it, or because their Pod Server does not support Access Control Resources.`);return e.internal_acp.acr}function Mn(e,t){return Object.assign(v(e),{internal_acp:{...e.internal_acp,acr:t}})}function Bn(e){let t=vt(e);return t=vr(t,P,N.AccessControl),t}function Hn(e,t){const r=gt(jn(e),t),n=r.filter((e=>rt(e,P).includes(N.AccessControl))),i=r.filter((e=>rt(e,N.accessControl).length>0)).map((e=>vt({url:rt(e,N.accessControl)[0]})));return n.concat(i)}function Wn(e,t){return Mn(e,yt(jn(e),t))}function $n(e,t){return Vt(e,N.apply,t)}function Vn(e){return rt(e,N.apply)}function Kn(e,t){return or(e,N.apply,t)}function Jn(e){return nr(e,N.apply)}function Gn(e,t){return Vt(e,N.applyMembers,t)}function qn(e){return rt(e,N.applyMembers)}function zn(e){return nr(e,N.applyMembers)}function Yn(e){const t=Hn(e);return 0===t.length?Bn():t[0]}function Qn(e){return h(e)&&Array.isArray(e.internal_resourceInfo.linkedResources[N.accessControl])&&1===e.internal_resourceInfo.linkedResources[N.accessControl].length}function Xn(e,t){var r;const n=jn(e),i=$(n);let o=null!==(r=pt(n,i))&&void 0!==r?r:vt({url:i});return o=Vt(o,N.access,t),Mn(e,yt(n,o))}function Zn(e,t){var r;const n=jn(e),i=$(n);let o=null!==(r=pt(n,i))&&void 0!==r?r:vt({url:i});return o=Vt(o,N.accessMembers,t),Mn(e,yt(n,o))}function ei(e){const t=jn(e),r=pt(t,$(t));return null===r?[]:rt(r,N.access)}function ti(e){const t=jn(e),r=pt(t,$(t));return null===r?[]:rt(r,N.accessMembers)}function ri(e,t){const r=jn(e),n=pt(r,$(r));return null===n?e:Mn(e,yt(r,or(n,N.access,t)))}function ni(e,t){const r=jn(e),n=pt(r,$(r));return null===n?e:Mn(e,yt(r,or(n,N.accessMembers,t)))}function ii(e){const t=jn(e),r=pt(t,$(t));return null===r?e:Mn(e,yt(t,nr(r,N.access)))}function oi(e){const t=jn(e),r=pt(t,$(t));return null===r?e:Mn(e,yt(t,nr(r,N.accessMembers)))}function si(e,t){return Wn(e,$n(Yn(e),t))}function ai(e,t){return Wn(e,Gn(Yn(e),t))}function ci(e){const t=Hn(e).map((e=>Vn(e))),r=new Set;return t.forEach((e=>{e.forEach((e=>r.add(e)))})),Array.from(r)}function li(e){const t=Hn(e).map((e=>qn(e))),r=new Set;return t.forEach((e=>{e.forEach((e=>r.add(e)))})),Array.from(r)}function ui(e,t){return Hn(e).map((e=>Kn(e,t))).reduce(Wn,e)}function di(e,t){const r=Hn(e).map((e=>function(e,t){return or(e,N.applyMembers,t)}(e,t)));return r.reduce(Wn,e)}function hi(e){return Hn(e).map((e=>Jn(e))).reduce(Wn,e)}function fi(e){return Hn(e).map((e=>zn(e))).reduce(Wn,e)}function pi(e){let t=`# Access controls for ${$(e)}\n`;const r=ci(e),n=li(e),i=ei(e),o=ti(e);return 0===r.length&&0===n.length&&0===i.length&&0===o.length&&(t+="\n\n"),r.length>0&&(t+="\nThe following policies apply to this resource:\n- ",t+=`${r.join("\n- ")}\n`),i.length>0&&(t+="\nThe following policies apply to the access control resource for this resource:\n- ",t+=`${i.join("\n- ")}\n`),n.length>0&&(t+="\nThe following policies apply to the children of this resource:\n- ",t+=`${n.join("\n- ")}\n`),o.length>0&&(t+="\nThe following policies apply to the access control resources for children of this resource:\n- ",t+=`${o.join("\n- ")}\n`),t}const gi="http://www.w3.org/ns/solid/acp#",yi={AccessControl:gi.concat("AccessControl"),AccessControlResource:gi.concat("AccessControlResource"),AuthenticatedAgent:gi.concat("AuthenticatedAgent"),CreatorAgent:gi.concat("CreatorAgent"),Matcher:gi.concat("Matcher"),Policy:gi.concat("Policy"),PublicAgent:gi.concat("PublicAgent"),access:gi.concat("access"),accessControl:gi.concat("accessControl"),agent:gi.concat("agent"),allOf:gi.concat("allOf"),allow:gi.concat("allow"),anyOf:gi.concat("anyOf"),apply:gi.concat("apply"),client:gi.concat("client"),deny:gi.concat("deny"),memberAccessControl:gi.concat("memberAccessControl"),noneOf:gi.concat("noneOf"),vc:gi.concat("vc")},mi="http://www.w3.org/ns/auth/acl#",vi={Append:mi.concat("Append"),Control:mi.concat("Control"),Read:mi.concat("Read"),Write:mi.concat("Write")};function bi(e){const t=jn(e);return pt(t,$(t))}const wi="defaultAccessControl",_i="defaultAcrAccessControl",Si="defaultMemberAccessControl",Ei="defaultMemberAcrAccessControl";function Ai(e,t){return $(jn(e)).concat("#").concat(t)}function Ri(e,t){const r=jn(e),n=Ai(e,t),i=pt(r,n);return null==i?vt({url:n}):i}function Ii(e,t){const r=rt(e,t);return{read:r.includes(vi.Read),append:r.includes(vi.Append),write:r.includes(vi.Write),controlRead:!1,controlWrite:!1}}function Ti(e,t,r){let n=nr(e,r);return(t.read||t.controlRead)&&(n=Vt(n,r,vi.Read)),t.append&&(n=Vt(n,r,vi.Append)),(t.write||t.controlWrite)&&(n=Vt(n,r,vi.Write)),n}const xi="defaultVcPolicy",Pi="defaultVcMatcher";function Ci(e,t,r={inherit:!1}){var n;let i=jn(e);const o=`${V(i)}#${xi}`,s=`${V(i)}#${Pi}`,{policy:a,matcher:c}=function(e,t,r,n){var i;let o=pt(e,t);null===o&&(o=Cr({url:t}).addIri(P,yi.Policy).addIri(yi.anyOf,r).build());const s=null!==(i=pt(e,r))&&void 0!==i?i:Cr({url:r}).addIri(P,yi.Matcher).addIri(yi.vc,"http://www.w3.org/ns/solid/vc#SolidAccessGrant").build();return o=Ti(o,{...Ii(o,yi.allow),...n},yi.allow),{matcher:s,policy:o}}(i,o,s,t);let l=Ri(e,"defaultAccessControl");rt(l,yi.apply).includes(_t(a))||(l=Vt(l,yi.apply,a));let u=Ri(e,"defaultMemberAccessControl"),d=null!==(n=bi(e))&&void 0!==n?n:vt({url:V(i)});return rt(d,yi.accessControl).includes(_t(l))||(d=Vt(d,yi.accessControl,l)),i=[d,l,a,c].reduce(yt,i),r.inherit&&(rt(u,yi.apply).includes(_t(a))||(u=Vt(u,yi.apply,a)),rt(d,yi.memberAccessControl).includes(_t(u))||(d=Vt(d,yi.memberAccessControl,u)),i=[d,u].reduce(yt,i)),function(e,t){return Object.assign(v(e),{internal_acp:{acr:t}})}(e,i)}const ki={read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1},Oi=(e,t,r)=>rt(e,t).includes(_t(r));function Fi(e){const t=jn(e),r=Ri(e,"defaultAccessControl"),n=bi(e);if(null===n||!Oi(n,yi.accessControl,r))return ki;const i=pt(t,`${V(t)}#${xi}`);if(null===i||!Oi(r,yi.apply,i))return ki;const o=pt(t,`${V(t)}#${Pi}`);return null!==o&&Oi(i,yi.anyOf,o)?Ii(i,yi.allow):ki}async function Ni(e,t=j){const r=g(e),n={...j,...t},i=await Ot(r,n),o=await Wi(i,n);return{...i,...o}}async function Di(e,t=j){const r=g(e),n={...j,...t},i=await Ke(r,n),o=await Wi(i,n);return Object.assign(i,o)}async function Li(e,t=j){const r=g(e),n={...j,...t},i=await M(r,n),o=await Wi(i,n);return{...i,...o}}async function Ui(e,t=j){const r=g(e),n={...j,...t},i=await Ot(r,n);if(sn(i))return Gr(i,await Or(i,n));const o=await Wi(i,n);return{...i,...o}}async function ji(e,t=j){const r=g(e),n={...j,...t},i=await Ke(r,n);if(sn(i))return Gr(i,await Or(i,n));const o=await Wi(i,n);return Object.assign(i,o)}async function Mi(e,t=j){const r=g(e),n={...j,...t},i=await M(r,n);if(sn(i))return Gr(i,await Or(i,n));const o=await Wi(i,n);return{...i,...o}}async function Bi(e,t=j){const r=jn(e),n={...j,...t};return Mn(e,await Ft($(r),r,n))}function Hi(e){return"object"==typeof e.internal_acp&&null!==e.internal_acp&&"object"==typeof e.internal_acp.acr&&null!==e.internal_acp.acr}async function Wi(e,t){let r,n;if(Qn(e)){const{linkedResources:t}=e.internal_resourceInfo;[r]=t[N.accessControl]}else if(sn(e)){let n;try{n=await M(e.internal_resourceInfo.aclUrl,t)}catch(e){}n&&kr(n)&&(r=$(n))}if("string"!=typeof r)return{internal_acp:{acr:null}};try{n=await Ot(r,t)}catch(e){return{internal_acp:{acr:null}}}return{internal_acp:{acr:{...n,accessTo:$(e)}}}}function $i(e){const t=ci(e).map(Pt).concat(li(e).map(Pt)).concat(ei(e).map(Pt)).concat(ti(e).map(Pt));return Array.from(new Set(t))}async function Vi(e,t=j){const r=g(e),n={...j,...t},i=await M(r,n);return Hi(await Wi(i,n))}function Ki(e){if(h(e))return[N.accessControl,"acl"].map((t=>{if(Array.isArray(e.internal_resourceInfo.linkedResources[t])&&1===e.internal_resourceInfo.linkedResources[t].length)return e.internal_resourceInfo.linkedResources[t][0]})).find((e=>void 0!==e))}function Ji(e){return rt(e,P).includes(N.Rule)}function Gi(e,t){return Vt(e,N.allOf,t)}function qi(e,t){return or(e,N.allOf,t)}function zi(e,t){return vr(e,N.allOf,t)}function Yi(e){return rt(e,N.allOf)}function Qi(e,t){return Vt(e,N.anyOf,t)}function Xi(e,t){return or(e,N.anyOf,t)}function Zi(e,t){return vr(e,N.anyOf,t)}function eo(e){return rt(e,N.anyOf)}function to(e,t){return Vt(e,N.noneOf,t)}function ro(e,t){return or(e,N.noneOf,t)}function no(e,t){return vr(e,N.noneOf,t)}function io(e){return rt(e,N.noneOf)}function oo(e){let t=vt({url:g(e)});return t=mr(t,P,N.Rule),t}function so(e,t){const r=jn(e),n=new URL($(r));n.hash=`#${t}`;let i=vt({url:n.href});return i=mr(i,P,N.Rule),i}function ao(e,t){const r=pt(e,t);return null===r||Ze(r,P)!==N.Rule?null:r}function co(e,t){const r=jn(e),n=$(r),i=new URL(n);i.hash=`#${t}`;const o=pt(r,i.href);return null!==o&&Ji(o)?o:null}function lo(e){return gt(e).filter(Ji)}function uo(e){return gt(jn(e)).filter(Ji)}function ho(e,t){return mt(e,t)}function fo(e,t){const r=jn(e);let n;if("string"==typeof t)if(Se(t))n=t;else{const e=new URL($(r));e.hash=`#${t}`,n=e.href}else n=be(t)?g(t):wt(t);const i=co(e,new URL(n).hash.substring(1));return null===i?e:Mn(e,mt(r,i))}function po(e,t){return yt(e,t)}function go(e,t){return Mn(e,yt(jn(e),t))}function yo(e){return rt(e,N.agent).filter((e=>e!==N.PublicAgent&&e!==N.AuthenticatedAgent&&e!==N.CreatorAgent))}function mo(e,t){const r=Ao(e),n=To(e),i=Co(e);let o=vr(e,N.agent,t);return r&&(o=Ro(o)),n&&(o=xo(o)),i&&(o=ko(o)),o}function vo(e,t){return Vt(e,N.agent,t)}function bo(e,t){return or(e,N.agent,t)}function wo(e){return rt(e,N.group)}function _o(e,t){return vr(e,N.group,t)}function So(e,t){return Vt(e,N.group,t)}function Eo(e,t){return or(e,N.group,t)}function Ao(e){return rt(e,N.agent).filter((e=>e===N.PublicAgent)).length>0}function Ro(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setPublic` no longer takes a second parameter. It is now used together with `removePublic` instead.");return Vt(e,N.agent,N.PublicAgent)}function Io(e){return or(e,N.agent,N.PublicAgent)}function To(e){return rt(e,N.agent).filter((e=>e===N.AuthenticatedAgent)).length>0}function xo(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setAuthenticated` no longer takes a second parameter. It is now used together with `removeAuthenticated` instead.");return Vt(e,N.agent,N.AuthenticatedAgent)}function Po(e){return or(e,N.agent,N.AuthenticatedAgent)}function Co(e){return rt(e,N.agent).filter((e=>e===N.CreatorAgent)).length>0}function ko(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setCreator` no longer takes a second parameter. It is now used together with `removeCreator` instead.");return Vt(e,N.agent,N.CreatorAgent)}function Oo(e){return or(e,N.agent,N.CreatorAgent)}function Fo(e){return rt(e,N.client).filter((e=>e!==D))}function No(e,t){const r=Uo(e);let n=vr(e,N.client,t);return r&&(n=jo(n)),n}function Do(e,t){return Vt(e,N.client,t)}function Lo(e,t){return or(e,N.client,t)}function Uo(e){return rt(e,N.client).filter((e=>e===D)).length>0}function jo(e){return Vt(e,N.client,D)}function Mo(e){return or(e,N.client,D)}function Bo(e){let t=`## Rule: ${wt(e)}\n\n`,r="";Ao(e)&&(r+="- Everyone\n"),To(e)&&(r+="- All authenticated agents\n"),Co(e)&&(r+="- The creator of this resource\n"),Uo(e)&&(r+="- Users of any client application\n");const n=yo(e);n.length>0&&(r+="- The following agents:\n - ",r+=`${n.join("\n - ")}\n`);const i=wo(e);i.length>0&&(r+="- Members of the following groups:\n - ",r+=`${i.join("\n - ")}\n`);const o=Fo(e);return o.length>0&&(r+="- Users of the following client applications:\n - ",r+=`${o.join("\n - ")}\n`),t+=r.length>0?`This rule applies to:\n${r}`:"\n",t}function Ho(e){return rt(e,P).includes(N.Policy)}function Wo(e){let t=vt({url:g(e)});return t=mr(t,P,N.Policy),t}function $o(e,t){const r=pt(e,t);return null!==r&&Ho(r)?r:null}function Vo(e){return gt(e).filter((e=>!Et(e)&&Ho(e)))}function Ko(e,t){return mt(e,t)}function Jo(e,t){return yt(e,t)}function Go(e,t){let r=nr(e,N.allow);return!0===t.read&&(r=Vt(r,N.allow,$r.read)),!0===t.append&&(r=Vt(r,N.allow,$r.append)),!0===t.write&&(r=Vt(r,N.allow,$r.write)),r}function qo(e,t){let r=nr(e,N.allow);return!0===t.read&&(r=Vt(r,N.allow,N.Read)),!0===t.append&&(r=Vt(r,N.allow,N.Append)),!0===t.write&&(r=Vt(r,N.allow,N.Write)),r}function zo(e){const t=rt(e,N.allow);return{read:t.includes($r.read),append:t.includes($r.append),write:t.includes($r.write)}}function Yo(e){const t=rt(e,N.allow);return{read:t.includes(N.Read),append:t.includes(N.Append),write:t.includes(N.Write)}}function Qo(e,t){let r=nr(e,N.deny);return!0===t.read&&(r=Vt(r,N.deny,$r.read)),!0===t.append&&(r=Vt(r,N.deny,$r.append)),!0===t.write&&(r=Vt(r,N.deny,$r.write)),r}function Xo(e,t){let r=nr(e,N.deny);return!0===t.read&&(r=Vt(r,N.deny,N.Read)),!0===t.append&&(r=Vt(r,N.deny,N.Append)),!0===t.write&&(r=Vt(r,N.deny,N.Write)),r}function Zo(e){const t=rt(e,N.deny);return{read:t.includes($r.read),append:t.includes($r.append),write:t.includes($r.write)}}function es(e){const t=rt(e,N.deny);return{read:t.includes(N.Read),append:t.includes(N.Append),write:t.includes(N.Write)}}function ts(e,t){const r=jn(e),n=new URL($(r));n.hash=`#${t}`;let i=vt({url:n.href});return i=mr(i,P,N.Policy),i}function rs(e,t){const r=jn(e),n=$(r),i=new URL(n);i.hash=`#${t}`;const o=pt(r,i.href);return ci(e).includes(i.href)&&null!==o&&Ho(o)?o:null}function ns(e,t){const r=jn(e),n=$(r),i=new URL(n);i.hash=`#${t}`;const o=pt(r,i.href);return ei(e).includes(i.href)&&null!==o&&Ho(o)?o:null}function is(e){const t=jn(e);return ci(e).map((e=>pt(t,e))).filter((e=>null!==e&&Ho(e)))}function os(e){const t=jn(e);return ei(e).map((e=>pt(t,e))).filter((e=>null!==e&&Ho(e)))}function ss(e,t){const r=jn(e);let n,i=t;if("string"==typeof i&&!1===Se(i)){const e=new URL($(r));e.hash=`#${t}`,i=e.href}return n="string"==typeof i?i:be(i)?g(i):wt(i,$(r)),null===rs(e,new URL(n).hash.substring(1))?e:ui(Mn(e,mt(r,i)),n)}function as(e,t){const r=jn(e);let n,i=t;if("string"==typeof i&&!1===Se(i)){const e=new URL($(r));e.hash=`#${t}`,i=e.href}return n="string"==typeof i?i:be(i)?g(i):wt(i,$(r)),null===ns(e,new URL(n).hash.substring(1))?e:ri(Mn(e,mt(r,i)),n)}function cs(e,t){const r=jn(e);return si(Mn(e,yt(r,t)),wt(t,$(r)))}function ls(e,t){const r=jn(e);return Xn(Mn(e,yt(r,t)),wt(t,$(r)))}function us(e){function t(e,t){return t?"denied":e?"allowed":"unspecified"}const r=Yo(e),n=es(e);let i=`## Policy: ${wt(e)}\n\n`;i+=`- Read: ${t(r.read,n.read)}\n`,i+=`- Append: ${t(r.append,n.append)}\n`,i+=`- Write: ${t(r.write,n.write)}\n`;const o=Yi(e),s=eo(e),a=io(e);return 0===o.length&&0===s.length&&0===a.length&&(i+="\n\n"),o.length>0&&(i+="\nAll of these rules should match:\n",i+=`- ${o.join("\n- ")}\n`),s.length>0&&(i+="\nAt least one of these rules should match:\n",i+=`- ${s.join("\n- ")}\n`),a.length>0&&(i+="\nNone of these rules should match:\n",i+=`- ${a.join("\n- ")}\n`),i}function ds(e){return{...Ht(new URL("access-control-resource",e).href),accessTo:e}}function hs(e,t=ds($(e))){return Object.assign(v(e),{internal_acp:{acr:t,aprs:{}}})}function fs(e,t){return t?Ro(e):Io(e)}function ps(e,t){return t?xo(e):Po(e)}function gs(e,t){return t?ko(e):Oo(e)}const ys={getFileWithAccessDatasets:ji,getFileWithAcr:Di,getReferencedPolicyUrlAll:$i,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,saveAcrFor:Bi,acrAsMarkdown:pi,addAcrPolicyUrl:Xn,addMemberAcrPolicyUrl:Zn,addMemberPolicyUrl:ai,addPolicyUrl:si,getAcrPolicyUrlAll:ei,getMemberAcrPolicyUrlAll:ti,getMemberPolicyUrlAll:li,getPolicyUrlAll:ci,hasLinkedAcr:Qn,removeAcrPolicyUrl:ri,removeAcrPolicyUrlAll:ii,removeMemberAcrPolicyUrl:ni,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:di,removeMemberPolicyUrlAll:fi,removePolicyUrl:ui,removePolicyUrlAll:hi,createPolicy:Wo,getAllowModes:Yo,getDenyModes:es,getPolicy:$o,getPolicyAll:Vo,policyAsMarkdown:us,removePolicy:Ko,setAllowModes:qo,setDenyModes:Xo,setPolicy:Jo,addAgent:vo,addForbiddenRuleUrl:to,addGroup:So,addOptionalRuleUrl:Qi,addRequiredRuleUrl:Gi,createRule:oo,getAgentAll:yo,getForbiddenRuleUrlAll:io,getGroupAll:wo,getOptionalRuleUrlAll:eo,getRequiredRuleUrlAll:Yi,getRule:ao,getRuleAll:lo,hasAuthenticated:To,hasCreator:Co,hasPublic:Ao,removeAgent:bo,removeForbiddenRuleUrl:ro,removeGroup:Eo,removeOptionalRuleUrl:Xi,removeRequiredRuleUrl:qi,removeRule:ho,ruleAsMarkdown:Bo,setAgent:mo,setForbiddenRuleUrl:no,setGroup:_o,setOptionalRuleUrl:Zi,setRequiredRuleUrl:zi,setRule:po,addMockAcrTo:hs,mockAcrFor:ds,getForbiddenRuleurlAll:io,setPublic:fs,setAuthenticated:ps,setCreator:gs},ms={getFileWithAccessDatasets:ji,getFileWithAcr:Di,getReferencedPolicyUrlAll:$i,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,saveAcrFor:Bi,createPolicy:Wo,getAllowModes:Yo,getDenyModes:es,getPolicy:$o,getPolicyAll:Vo,policyAsMarkdown:us,removePolicy:Ko,setAllowModes:qo,setDenyModes:Xo,setPolicy:Jo,addAgent:vo,addForbiddenRuleUrl:to,addGroup:So,addOptionalRuleUrl:Qi,addRequiredRuleUrl:Gi,createRule:oo,getAgentAll:yo,getForbiddenRuleUrlAll:io,getGroupAll:wo,getOptionalRuleUrlAll:eo,getRequiredRuleUrlAll:Yi,getRule:ao,getRuleAll:lo,hasAuthenticated:To,hasCreator:Co,hasPublic:Ao,removeAgent:bo,removeForbiddenRuleUrl:ro,removeGroup:Eo,removeOptionalRuleUrl:Xi,removeRequiredRuleUrl:qi,removeRule:ho,ruleAsMarkdown:Bo,setAgent:mo,setForbiddenRuleUrl:no,setGroup:_o,setOptionalRuleUrl:Zi,setRequiredRuleUrl:zi,setRule:po,addMockAcrTo:hs,mockAcrFor:ds,hasLinkedAcr:Qn,addAcrPolicyUrl:Xn,addMemberAcrPolicyUrl:Zn,getAcrPolicyUrlAll:ei,getMemberAcrPolicyUrlAll:ti,removeAcrPolicyUrl:ri,removeAcrPolicyUrlAll:ii,removeMemberAcrPolicyUrl:ni,removeMemberAcrPolicyUrlAll:oi,createControl:Bn,getControl:function(e,t,r){const n=pt(jn(e),t,r);return null!==n&&rt(n,P).includes(N.AccessControl)?n:null},getAllControl:Hn,getControlAll:Hn,setControl:Wn,removeControl:function(e,t){return Mn(e,mt(jn(e),t))},addPolicyUrl:$n,getPolicyUrlAll:Vn,removePolicyUrl:Kn,removePolicyUrlAll:Jn,addMemberPolicyUrl:Gn,getMemberPolicyUrlAll:qn,removeMemberPolicyUrl:qn,removeMemberPolicyUrlAll:zn,getForbiddenRuleurlAll:io,setPublic:fs,setAuthenticated:ps,setCreator:gs},vs={getFileWithAccessDatasets:ji,getFileWithAcr:Di,getLinkedAcrUrl:Ki,getReferencedPolicyUrlAll:$i,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,saveAcrFor:Bi,isAcpControlled:Vi,acrAsMarkdown:pi,addAcrPolicyUrl:Xn,addMemberAcrPolicyUrl:Zn,addMemberPolicyUrl:ai,addPolicyUrl:si,getAcrPolicyUrlAll:ei,getMemberAcrPolicyUrlAll:ti,getMemberPolicyUrlAll:li,getPolicyUrlAll:ci,hasLinkedAcr:Qn,removeAcrPolicyUrl:ri,removeAcrPolicyUrlAll:ii,removeMemberAcrPolicyUrl:ni,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:di,removeMemberPolicyUrlAll:fi,removePolicyUrl:ui,removePolicyUrlAll:hi,createPolicy:Wo,getAllowModes:Yo,getDenyModes:es,getPolicy:$o,getPolicyAll:Vo,policyAsMarkdown:us,removePolicy:Ko,setAllowModes:qo,setDenyModes:Xo,setPolicy:Jo,createResourcePolicyFor:ts,getResourceAcrPolicy:ns,getResourceAcrPolicyAll:os,getResourcePolicy:rs,getResourcePolicyAll:is,removeResourceAcrPolicy:as,removeResourcePolicy:ss,setResourceAcrPolicy:ls,setResourcePolicy:cs,addAgent:vo,addGroup:So,createRule:oo,getAgentAll:yo,getGroupAll:wo,getRule:ao,getRuleAll:lo,removeAgent:bo,removeGroup:Eo,removeRule:ho,ruleAsMarkdown:Bo,setAgent:mo,setGroup:_o,setRule:po,addClient:Do,getClientAll:Fo,hasAnyClient:Uo,removeClient:Lo,setAnyClient:jo,setClient:No,removeAnyClient:Mo,hasAuthenticated:To,hasCreator:Co,hasPublic:Ao,setAuthenticated:xo,setCreator:ko,setPublic:Ro,removeAuthenticated:Po,removeCreator:Oo,removePublic:Io,getAnyOfRuleUrlAll:eo,addAnyOfRuleUrl:Qi,removeAnyOfRuleUrl:Xi,setAnyOfRuleUrl:Zi,getAllOfRuleUrlAll:Yi,addAllOfRuleUrl:Gi,removeAllOfRuleUrl:qi,setAllOfRuleUrl:zi,getNoneOfRuleUrlAll:io,addNoneOfRuleUrl:to,removeNoneOfRuleUrl:ro,setNoneOfRuleUrl:no,createResourceRuleFor:so,getResourceRule:co,getResourceRuleAll:uo,removeResourceRule:fo,setResourceRule:go,addMockAcrTo:hs,mockAcrFor:ds};function bs(e,t){return Object.assign(v(e),{internal_acp:{...e.internal_acp,acr:yt(e.internal_acp.acr,t)}})}function ws(e){return e.includes("Member")?yi.memberAccessControl:yi.accessControl}function _s(e,t){const r=Ai(e,t),n=jn(e);let i=bi(e);return null==i&&(i=vt({url:$(n)})),rt(i,ws(t)).includes(r)?e:(i=Cr(i).addUrl(ws(t),r).build(),bs(e,i))}function Ss(e,t){const r=_s(e,_i);return bs(r,Cr(Ri(r,_i)).addUrl(yi.access,t).build())}function Es(e,t){const r=_s(e,Ei);return bs(r,Cr(Ri(r,Ei)).addUrl(yi.access,t).build())}function As(e,t){const r=_s(e,Si);return bs(r,Cr(Ri(r,Si)).addUrl(yi.apply,t).build())}function Rs(e,t){const r=_s(e,wi);return bs(r,Cr(Ri(r,wi)).addUrl(yi.apply,t).build())}function Is(e){const t=bi(e);return null===t?[]:rt(t,yi.accessControl)}function Ts(e,t,r){const n=jn(e);return Array.from(new Set(t.map((e=>{const t=pt(n,e);return null!==t?rt(t,r):[]})).reduce(((e,t)=>e.concat(t)),[])))}function xs(e){return Ts(e,Is(e),yi.access)}function Ps(e){const t=bi(e);return null===t?[]:rt(t,yi.memberAccessControl)}function Cs(e){return Ts(e,Ps(e),yi.access)}function ks(e){return Ts(e,Ps(e),yi.apply)}function Os(e){return Ts(e,Is(e),yi.apply)}function Fs(e,t){const r=Ri(e,_i);return bs(e,or(r,yi.access,t))}function Ns(e,t){const r=Ri(e,Ei);return bs(e,or(r,yi.access,t))}function Ds(e,t){const r=Ri(e,Si);return bs(e,or(r,yi.apply,t))}function Ls(e,t){const r=Ri(e,wi);return bs(e,or(r,yi.apply,t))}function Us(e,t){return bs(e,t)}function js(e){return rt(e,P).includes(N.Matcher)}function Ms(e,t){return Vt(e,N.allOf,t)}function Bs(e,t){return or(e,N.allOf,t)}function Hs(e,t){return vr(e,N.allOf,t)}function Ws(e){return rt(e,N.allOf)}function $s(e,t){return Vt(e,N.anyOf,t)}function Vs(e,t){return or(e,N.anyOf,t)}function Ks(e,t){return vr(e,N.anyOf,t)}function Js(e){return rt(e,N.anyOf)}function Gs(e,t){return Vt(e,N.noneOf,t)}function qs(e,t){return or(e,N.noneOf,t)}function zs(e,t){return vr(e,N.noneOf,t)}function Ys(e){return rt(e,N.noneOf)}function Qs(e){let t=vt({url:g(e)});return t=mr(t,P,N.Matcher),t}function Xs(e,t){const r=jn(e),n=new URL($(r));n.hash=`#${t}`;let i=vt({url:n.href});return i=mr(i,P,N.Matcher),i}function Zs(e,t){const r=pt(e,t);return null!==r&&js(r)?r:null}function ea(e,t){const r=jn(e),n=$(r),i=new URL(n);i.hash=`#${t}`;const o=pt(r,i.href);return null!==o&&js(o)?o:null}function ta(e){return gt(e).filter(js)}function ra(e){return gt(jn(e)).filter(js)}function na(e,t){return mt(e,t)}function ia(e,t){const r=jn(e);let n;if("string"==typeof t)if(Se(t))n=t;else{const e=new URL($(r));e.hash=`#${t}`,n=e.href}else n=be(t)?g(t):wt(t);const i=ea(e,new URL(n).hash.substring(1));return null===i?e:Mn(e,mt(r,i))}function oa(e,t){return yt(e,t)}function sa(e,t){return Mn(e,yt(jn(e),t))}function aa(e){return rt(e,N.agent).filter((e=>e!==N.PublicAgent&&e!==N.AuthenticatedAgent&&e!==N.CreatorAgent))}function ca(e,t){const r=da(e),n=pa(e),i=ma(e);let o=vr(e,N.agent,t);return r&&(o=ha(o)),n&&(o=ga(o)),i&&(o=va(o)),o}function la(e,t){return Vt(e,N.agent,t)}function ua(e,t){return or(e,N.agent,t)}function da(e){return rt(e,N.agent).filter((e=>e===N.PublicAgent)).length>0}function ha(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setPublic` no longer takes a second parameter. It is now used together with `removePublic` instead.");return Vt(e,N.agent,N.PublicAgent)}function fa(e){return or(e,N.agent,N.PublicAgent)}function pa(e){return rt(e,N.agent).filter((e=>e===N.AuthenticatedAgent)).length>0}function ga(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setAuthenticated` no longer takes a second parameter. It is now used together with `removeAuthenticated` instead.");return Vt(e,N.agent,N.AuthenticatedAgent)}function ya(e){return or(e,N.agent,N.AuthenticatedAgent)}function ma(e){return rt(e,N.agent).filter((e=>e===N.CreatorAgent)).length>0}function va(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setCreator` no longer takes a second parameter. It is now used together with `removeCreator` instead.");return Vt(e,N.agent,N.CreatorAgent)}function ba(e){return or(e,N.agent,N.CreatorAgent)}function wa(e){return rt(e,N.client).filter((e=>e!==D)).concat(ot(e,N.client))}function _a(e,t){return Se(t)?Vt(e,N.client,t):Xt(e,N.client,t)}function Sa(e,t){return Se(t)?or(e,N.client,t):fr(e,N.client,t)}function Ea(e){return rt(e,N.client).filter((e=>e===D)).length>0}function Aa(e){return Vt(e,N.client,D)}const Ra={getFileWithAccessDatasets:ji,getFileWithAcr:Di,getReferencedPolicyUrlAll:$i,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,saveAcrFor:Bi,isAcpControlled:Vi,getVcAccess:Fi,setVcAccess:Ci,addAcrPolicyUrl:Ss,addMemberAcrPolicyUrl:Es,addMemberPolicyUrl:As,addPolicyUrl:Rs,getAcrPolicyUrlAll:xs,getMemberAcrPolicyUrlAll:Cs,getMemberPolicyUrlAll:ks,getPolicyUrlAll:Os,hasLinkedAcr:Qn,removeAcrPolicyUrl:Fs,removeAcrPolicyUrlAll:ii,removeMemberAcrPolicyUrl:Ns,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:Ds,removeMemberPolicyUrlAll:fi,removePolicyUrl:Ls,removePolicyUrlAll:hi,createPolicy:Wo,getAllowModes:zo,getDenyModes:Zo,getPolicy:$o,getPolicyAll:Vo,removePolicy:Ko,setAllowModes:Go,setDenyModes:Qo,setPolicy:Jo,createResourcePolicyFor:ts,getResourceAcrPolicy:ns,getResourceAcrPolicyAll:os,getResourcePolicy:rs,getResourcePolicyAll:is,removeResourceAcrPolicy:as,removeResourcePolicy:ss,setResourcePolicy:Us,addAgent:la,createMatcher:Qs,getAgentAll:aa,getMatcher:Zs,getMatcherAll:ta,removeAgent:ua,removeMatcher:na,setAgent:ca,setMatcher:oa,addClient:_a,getClientAll:wa,hasAnyClient:Ea,removeClient:Sa,setAnyClient:Aa,setClient:function(e,t){const r=Ea(e);let n=vr(e,N.client,t);return r&&(n=Aa(n)),n},removeAnyClient:function(e){return or(e,N.client,D)},hasAuthenticated:pa,hasCreator:ma,hasPublic:da,setAuthenticated:ga,setCreator:va,setPublic:ha,removeAuthenticated:ya,removeCreator:ba,removePublic:fa,getAnyOfMatcherUrlAll:Js,addAnyOfMatcherUrl:$s,removeAnyOfMatcherUrl:Vs,setAnyOfMatcherUrl:Ks,getAllOfMatcherUrlAll:Ws,addAllOfMatcherUrl:Ms,removeAllOfMatcherUrl:Bs,setAllOfMatcherUrl:Hs,getNoneOfMatcherUrlAll:Ys,addNoneOfMatcherUrl:Gs,removeNoneOfMatcherUrl:qs,setNoneOfMatcherUrl:zs,createResourceMatcherFor:Xs,getResourceMatcher:ea,getResourceMatcherAll:ra,removeResourceMatcher:ia,setResourceMatcher:sa,addMockAcrTo:hs,mockAcrFor:ds},Ia=[N.agent,N.group];function Ta(e,t,r){if(e.inaccessibleUrls.length>0)return null;const n=e.acrPolicies.filter((n=>xa(n,t,r,e))),i=e.policies.filter((n=>xa(n,t,r,e))),o=n.reduce(((e,t)=>{const r={...e},n=Yo(t);return n.read&&(r.controlRead=!0),n.write&&(r.controlWrite=!0),r}),{read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1}),s=i.reduce(((e,t)=>{const r={...e},n=Yo(t);return n.read&&(r.read=!0),n.append&&(r.append=!0),n.write&&(r.write=!0),r}),o),a=n.reduce(((e,t)=>{const r={...e},n=es(t);return!0===n.read&&(r.controlRead=!1),!0===n.write&&(r.controlWrite=!1),r}),s);return i.reduce(((e,t)=>{const r={...e},n=es(t);return!0===n.read&&(r.read=!1),!0===n.append&&(r.append=!1),!0===n.write&&(r.write=!1),r}),a)}function xa(e,t,r,n){const i=rt(e,N.allow),o=rt(e,N.deny);if(i.length+o.length===0)return!1;const s=Yi(e).map((e=>n.rules.find((t=>_t(t)===e)))),a=eo(e).map((e=>n.rules.find((t=>_t(t)===e)))),c=io(e).map((e=>n.rules.find((t=>_t(t)===e))));return s.every((e=>Ca(e,t,r)))&&(0===a.length||a.some((e=>Ca(e,t,r))))&&0===c.length}function Pa(e,t){const r=rt(e,N.allow),n=rt(e,N.deny);return!0===t.read&&n.includes(N.Read)||!1===t.read&&r.includes(N.Read)&&!n.includes(N.Read)||!0===t.append&&n.includes(N.Append)||!1===t.append&&r.includes(N.Append)&&!n.includes(N.Append)||!0===t.write&&n.includes(N.Write)||!1===t.write&&r.includes(N.Write)&&!n.includes(N.Write)}function Ca(e,t,r){let n=!0;return Ia.forEach((t=>{n&&(n=null===et(e,t))})),n||rt(e,t).includes(r)}function ka(e,t){if(e.inaccessibleUrls.length>0)return null;const r={},n=function(e,t){const r=new Set;return e.rules.forEach((e=>{rt(e,t).filter((e=>![N.PublicAgent,N.CreatorAgent,N.AuthenticatedAgent].includes(e)||t!==N.agent)).forEach((e=>r.add(e)))})),r}(e,t);return n.forEach((n=>{const i=Ta(e,t,n);r[n]=i})),r}function Oa(e,t,r,n,i){var o,s,a,c,l;if(!Hi(e)||t.inaccessibleUrls.length>0)return null;const d=Ta(t,r,n);if(null===d)return null;const h=t.acrPolicies.filter((e=>xa(e,r,n,t))),f=t.policies.filter((e=>xa(e,r,n,t))),p=h.filter((e=>Pa(e,{read:i.controlRead,write:i.controlWrite}))),g=f.filter((e=>Pa(e,{read:i.read,append:i.append,write:i.write}))),y=p.filter((e=>Fa(e,r,n,t))),m=g.filter((e=>Fa(e,r,n,t))),v=Ta({...t,acrPolicies:t.acrPolicies.filter((e=>!y.includes(e))),policies:t.policies.filter((e=>!m.includes(e)))},r,n);if(null===v)return null;let b=e;y.forEach((i=>{const[o,s]=Da(i,e,t,r,n);b=ls(b,o),b=s.reduce(go,b)})),m.forEach((i=>{const[o,s]=Da(i,e,t,r,n);b=cs(b,o),b=s.reduce(go,b)}));const w=`rule_${encodeURIComponent(`${r}_${n}`)}`;let _=so(e,w);_=vr(_,r,n);const S=null!==(o=i.controlRead)&&void 0!==o?o:d.controlRead,E=null!==(s=i.controlWrite)&&void 0!==s?s:d.controlWrite;let A=y;if(S!==v.controlRead||E!==v.controlWrite){const t=u.v4();let r=ts(e,t);r=qo(r,{read:!0===S,append:!1,write:!0===E}),r=Vt(r,N.allOf,_),b=ls(b,r),b=go(b,_),A=p}const R=null!==(a=i.read)&&void 0!==a?a:d.read,I=null!==(c=i.append)&&void 0!==c?c:d.append,T=null!==(l=i.write)&&void 0!==l?l:d.write;let x=m;if(R!==v.read||I!==v.append||T!==v.write){const t=u.v4();let r=ts(e,t);r=qo(r,{read:!0===R,append:!0===I,write:!0===T}),r=Vt(r,N.allOf,_),b=cs(b,r),b=go(b,_),x=g}return A.forEach((e=>{b=ri(b,_t(e))})),x.forEach((e=>{b=ui(b,_t(e))})),b}function Fa(e,t,r,n){const i=rt(e,N.allOf).map((e=>n.rules.find((t=>_t(t)===e)))).some((e=>Na(e,t,r))),o=rt(e,N.anyOf).map((e=>n.rules.find((t=>_t(t)===e)))).some((e=>Na(e,t,r))),s=rt(e,N.noneOf).map((e=>n.rules.find((t=>_t(t)===e)))).some((e=>Na(e,t,r)));return i||o||s}function Na(e,t,r){const n=[];return Ia.forEach((i=>{const o=rt(e,i).filter((e=>e!==r||i!==t));n.push(...o)})),n.length>0}function Da(e,t,r,n,i){const o=u.v4(),s=La(rt(e,N.allOf),t,r,o,n,i),a=La(rt(e,N.anyOf),t,r,o,n,i),c=La(rt(e,N.noneOf),t,r,o,n,i);let l=ts(t,encodeURI(_t(e))+o);return rt(e,N.allow).forEach((e=>{l=Vt(l,N.allow,e)})),rt(e,N.deny).forEach((e=>{l=Vt(l,N.deny,e)})),s.forEach((e=>{l=Vt(l,N.allOf,e)})),a.forEach((e=>{l=Vt(l,N.anyOf,e)})),c.forEach((e=>{l=Vt(l,N.noneOf,e)})),[l,s.concat(a).concat(c)]}function La(e,t,r,n,i,o){return e.map((e=>{const s=r.rules.find((t=>_t(t)===e));if(void 0===s)return null;let a=so(t,encodeURI(_t(s))+n),c=!1;return Ia.forEach((e=>{rt(s,e).forEach((t=>{e===i&&t===o||(c=!0,a=Vt(a,e,t))}))})),c?a:null})).filter(Ua)}function Ua(e){return null!==e}async function ja(e,t=j){const r=ei(e),n=ci(e),i=Ba(r).concat(Ba(n)),o=await Ha(i,t),s=Wa(r,o).filter(Ua),a=Wa(n,o).filter(Ua),c=new Set;s.forEach((e=>{$a(e).forEach((e=>{c.add(e)}))})),a.forEach((e=>{$a(e).forEach((e=>{c.add(e)}))}));const l=Array.from(c),u=l.map((e=>Ma(e))).filter((e=>!i.includes(e))),d=await Ha(u,t),h={...o,...d},f=Wa(l,h).filter(Ua);return{inaccessibleUrls:Object.keys(h).filter((e=>null===h[e])),acrPolicies:s,policies:a,rules:f}}function Ma(e){const t=new URL(e);return t.hash="",t.href}function Ba(e){const t=[];return e.forEach((e=>{const r=Ma(e);t.includes(r)||t.push(r)})),t}async function Ha(e,t){const r=Array.from(new Set(e)),n={};return await Promise.all(r.map((async e=>{try{const r=await Ot(e,t);n[e]=r}catch(t){n[e]=null}}))),n}function Wa(e,t){return e.map((e=>{const r=Ma(e),n=t[r];return n?pt(n,e):null}))}function $a(e){return Yi(e).concat(eo(e)).concat(io(e))}function Va(e,t){var r,n,i,o;if(e.controlRead!==e.controlWrite)throw new Error("For Pods using Web Access Control, controlRead and controlWrite must be equal.");return{read:null!==(r=e.read)&&void 0!==r?r:t.read,append:null!==(n=e.append)&&void 0!==n?n:t.append,write:null!==(i=e.write)&&void 0!==i?i:t.write,control:null!==(o=e.controlRead)&&void 0!==o?o:t.control}}function Ka(e){return{read:e.read,write:e.write,append:e.append,controlRead:e.control,controlWrite:e.control}}async function Ja(e,t,r,n){const i=r(Gr(e,await Or(e,n)),t);return null===i?null:Ka(i)}async function Ga(e,t,r){const n=t(Gr(e,await Or(e,r)));if(null===n)return null;const i={};for(const[e,t]of Object.entries(n))i[e]=Ka(t);return i}function qa(e,t,r=j){return Ja(e,t,an,r)}function za(e,t,r=j){return Ja(e,t,vn,r)}function Ya(e,t=j){return async function(e,t,r){const n=t(Gr(e,await Or(e,r)));return null===n?null:Ka(n)}(e,Tn,t)}function Qa(e,t=j){return Ga(e,cn,t)}async function Xa(e,t){if(!sn(e))return null;const r=Gr(e,await Or(e,t));let n;if(Xr(r))n=function(e){return e.internal_acl.resourceAcl}(r);else{if(!en(r))return null;n=nn(r)}return Yr(r,n)}async function Za(e,t,r){let n=null;try{return n=await on(e,t,r),Yr(e,n)}catch(e){return null}}async function ec(e,t,r,n,i,o){const s=await Xa(e,o);if(null===s)return null;const a=n(s,t);return Za(s,i(Zr(s),t,Va(r,a)),o)}async function tc(e,t,r,n=j){return ec(e,t,r,an,dn,n)}async function rc(e,t,r=j){return async function(e,t,r,n,i){const o=await Xa(e,i);return null===o?null:Za(o,n(Zr(o),Va(t,r(o))),i)}(e,t,Tn,Cn,r)}var nc=Object.freeze({__proto__:null,getAccessFor:ic,getAccessForAll:oc,getAgentAccess:ac,getAgentAccessAll:lc,getGroupAccess:uc,getGroupAccessAll:dc,getPublicAccess:fc,setAccessFor:sc,setAgentAccess:cc,setGroupAccess:hc,setPublicAccess:pc});async function ic(e,t,r=j,n=j){if("agent"===t){if("string"!=typeof r)throw new Error("When reading Agent-specific access, the given agent cannot be left undefined.");return ac(e,r,n)}if("group"===t){if("string"!=typeof r)throw new Error("When reading Group-specific access, the given group cannot be left undefined.");return uc(e,r,n)}if("public"===t){if("string"==typeof r)throw new Error(`When reading public access, no actor type should be specified (here [${r}]).`);return fc(e,r)}return null}async function oc(e,t,r=j){return"agent"===t?lc(e,r):"group"===t?dc(e,r):null}async function sc(e,t,r,n=j,i=j){if("agent"===t){if("string"!=typeof n)throw new Error("When writing Agent-specific access, the given agent cannot be left undefined.");return cc(e,n,r,i)}if("group"===t){if("string"!=typeof n)throw new Error("When writing Group-specific access, the given group cannot be left undefined.");return hc(e,n,r,i)}if("public"===t){if("string"==typeof n)throw new Error(`When writing public access, no actor type should be specified (here [${n}]).`);return pc(e,r,n)}return null}async function ac(e,t,r=j){const n=await Li(e,r);return Hi(n)?function(e,t){return Ta(e,N.agent,t)}(await ja(n,r),t):sn(n)?qa(n,t,r):null}async function cc(e,t,r,n=j){const i=await Li(e,n);if(Hi(i)){const o=function(e,t,r,n){return Oa(e,t,N.agent,r,n)}(i,await ja(i,n),t,r);if(o)try{return await Bi(o,n),await ac(e,t,n)}catch(e){return null}return null}if(sn(i)){if(r.controlRead!==r.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(i)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=r;return await tc(i,t,e,n),qa(i,t,n)}return null}async function lc(e,t=j){const r=await Li(e,t);return Hi(r)?ka(await ja(r,t),N.agent):sn(r)?Qa(r,t):null}async function uc(e,t,r=j){const n=await Li(e,r);return Hi(n)?(i=await ja(n,r),o=t,Ta(i,N.group,o)):sn(n)?za(n,t,r):null;var i,o}async function dc(e,t=j){const r=await Li(e,t);return Hi(r)?ka(await ja(r,t),N.group):sn(r)?function(e,t=j){return Ga(e,bn,t)}(r,t):null}async function hc(e,t,r,n=j){const i=await Li(e,n);if(Hi(i)){const o=function(e,t,r,n){return Oa(e,t,N.group,r,n)}(i,await ja(i,n),t,r);if(o)try{return await Bi(o,n),await uc(e,t,n)}catch(e){return null}return null}if(sn(i)){if(r.controlRead!==r.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(i)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=r;return await async function(e,t,r,n=j){return ec(e,t,r,vn,In,n)}(i,t,e,n),za(i,t,n)}return null}async function fc(e,t=j){const r=await Li(e,t);return Hi(r)?Ta(await ja(r,t),N.agent,N.PublicAgent):sn(r)?Ya(r,t):null}async function pc(e,t,r=j){const n=await Li(e,r);if(Hi(n)){const i=function(e,t,r){return Oa(e,t,N.agent,N.PublicAgent,r)}(n,await ja(n,r),t);if(i)try{return await Bi(i,r),await fc(e,r)}catch(e){return null}return null}if(sn(n)){if(t.controlRead!==t.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(n)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=t;return await rc(n,e,r),Ya(n,r)}return null}var gc=Object.freeze({__proto__:null,getAccessFor:ic,getAccessForAll:oc,getAgentAccess:ac,getAgentAccessAll:lc,getGroupAccess:uc,getGroupAccessAll:dc,getPublicAccess:fc,setAccessFor:sc,setAgentAccess:cc,setGroupAccess:hc,setPublicAccess:pc});const yc=[N.agent];function mc(e,t,r){if(e.inaccessibleUrls.length>0)return null;const n=e.acrPolicies.filter((n=>vc(n,t,r,e))),i=e.policies.filter((n=>vc(n,t,r,e))),o=n.reduce(((e,t)=>{const r={...e},n=zo(t);return n.read&&(r.controlRead=!0),n.write&&(r.controlWrite=!0),r}),{read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1}),s=i.reduce(((e,t)=>{const r={...e},n=zo(t);return n.read&&(r.read=!0),n.append&&(r.append=!0),n.write&&(r.write=!0),r}),o),a=n.reduce(((e,t)=>{const r={...e},n=Zo(t);return!0===n.read&&(r.controlRead=!1),!0===n.write&&(r.controlWrite=!1),r}),s);return i.reduce(((e,t)=>{const r={...e},n=Zo(t);return!0===n.read&&(r.read=!1),!0===n.append&&(r.append=!1),!0===n.write&&(r.write=!1),r}),a)}function vc(e,t,r,n){const i=rt(e,N.allow),o=rt(e,N.deny);if(i.length+o.length===0)return!1;const s=Ws(e).map((e=>n.matchers.find((t=>_t(t)===e)))),a=Js(e).map((e=>n.matchers.find((t=>_t(t)===e)))),c=Ys(e).map((e=>n.matchers.find((t=>_t(t)===e))));return s.every((e=>wc(e,t,r)))&&(0===a.length||a.some((e=>wc(e,t,r))))&&s.length+a.length>0&&0===c.length}function bc(e,t){const r=rt(e,N.allow),n=rt(e,N.deny);return!0===t.read&&n.includes($r.read)||!1===t.read&&r.includes($r.read)&&!n.includes($r.read)||!0===t.append&&n.includes($r.append)||!1===t.append&&r.includes($r.append)&&!n.includes($r.append)||!0===t.write&&n.includes($r.write)||!1===t.write&&r.includes($r.write)&&!n.includes($r.write)}function wc(e,t,r){return rt(e,t).includes(r)}function _c(e,t,r,n,i){var o,s,a,c,l;if(!Hi(e)||t.inaccessibleUrls.length>0)return null;const d=mc(t,r,n);if(null===d)return null;const h=t.acrPolicies.filter((e=>vc(e,r,n,t))),f=t.policies.filter((e=>vc(e,r,n,t))),p=h.filter((e=>bc(e,{read:i.controlRead,write:i.controlWrite}))),g=f.filter((e=>bc(e,{read:i.read,append:i.append,write:i.write}))),y=p.filter((e=>Sc(e,r,n,t))),m=g.filter((e=>Sc(e,r,n,t))),v=mc({...t,acrPolicies:t.acrPolicies.filter((e=>!y.includes(e))),policies:t.policies.filter((e=>!m.includes(e)))},r,n);if(null===v)return null;let b=e;y.forEach((i=>{const[o,s]=Ac(i,e,t,r,n);b=ls(b,o),b=s.reduce(sa,b)})),m.forEach((i=>{const[o,s]=Ac(i,e,t,r,n);b=cs(b,o),b=s.reduce(sa,b)}));const w=`matcher_${encodeURIComponent(`${r}_${n}`)}`;let _=Xs(e,w);_=vr(_,r,n);const S=null!==(o=i.controlRead)&&void 0!==o?o:d.controlRead,E=null!==(s=i.controlWrite)&&void 0!==s?s:d.controlWrite;let A=y;if(S!==v.controlRead||E!==v.controlWrite){const t=u.v4();let r=ts(e,t);r=Go(r,{read:!0===S,append:!1,write:!0===E}),r=Vt(r,N.allOf,_),b=ls(b,r),b=sa(b,_),A=p}const R=null!==(a=i.read)&&void 0!==a?a:d.read,I=null!==(c=i.append)&&void 0!==c?c:d.append,T=null!==(l=i.write)&&void 0!==l?l:d.write;let x=m;if(R!==v.read||I!==v.append||T!==v.write){const t=u.v4();let r=ts(e,t);r=Go(r,{read:!0===R,append:!0===I,write:!0===T}),r=Vt(r,N.allOf,_),b=cs(b,r),b=sa(b,_),x=g}return A.forEach((e=>{b=ri(b,_t(e))})),x.forEach((e=>{b=ui(b,_t(e))})),b}function Sc(e,t,r,n){const i=rt(e,N.allOf).map((e=>n.matchers.find((t=>_t(t)===e)))).some((e=>Ec(e,t,r))),o=rt(e,N.anyOf).map((e=>n.matchers.find((t=>_t(t)===e)))).some((e=>Ec(e,t,r))),s=rt(e,N.noneOf).map((e=>n.matchers.find((t=>_t(t)===e)))).some((e=>Ec(e,t,r)));return i||o||s}function Ec(e,t,r){const n=[];return yc.forEach((i=>{const o=rt(e,i).filter((e=>e!==r||i!==t));n.push(...o)})),n.length>0}function Ac(e,t,r,n,i){const o=u.v4(),s=Rc(rt(e,N.allOf),t,r,o,n,i),a=Rc(rt(e,N.anyOf),t,r,o,n,i),c=Rc(rt(e,N.noneOf),t,r,o,n,i);let l=ts(t,encodeURI(_t(e))+o);return rt(e,N.allow).forEach((e=>{l=Vt(l,N.allow,e)})),rt(e,N.deny).forEach((e=>{l=Vt(l,N.deny,e)})),s.forEach((e=>{l=Vt(l,N.allOf,e)})),a.forEach((e=>{l=Vt(l,N.anyOf,e)})),c.forEach((e=>{l=Vt(l,N.noneOf,e)})),[l,s.concat(a).concat(c)]}function Rc(e,t,r,n,i,o){return e.map((e=>{const s=r.matchers.find((t=>_t(t)===e));if(void 0===s)return null;let a=Xs(t,encodeURI(_t(s))+n),c=!1;return yc.forEach((e=>{rt(s,e).forEach((t=>{e===i&&t===o||(c=!0,a=Vt(a,e,t))}))})),c?a:null})).filter(Ic)}function Ic(e){return null!==e}async function Tc(e,t=j){const r=ei(e),n=ci(e),i=Pc(r).concat(Pc(n)),o=await Cc(i,t),s=kc(r,o).filter(Ic),a=kc(n,o).filter(Ic),c=new Set;s.forEach((e=>{Oc(e).forEach((e=>{c.add(e)}))})),a.forEach((e=>{Oc(e).forEach((e=>{c.add(e)}))}));const l=Array.from(c),u=l.map((e=>xc(e))).filter((e=>!i.includes(e))),d=await Cc(u,t),h={...o,...d},f=kc(l,h).filter(Ic);return{inaccessibleUrls:Object.keys(h).filter((e=>null===h[e])),acrPolicies:s,policies:a,matchers:f}}function xc(e){const t=new URL(e);return t.hash="",t.href}function Pc(e){const t=[];return e.forEach((e=>{const r=xc(e);t.includes(r)||t.push(r)})),t}async function Cc(e,t){const r=Array.from(new Set(e)),n={};return await Promise.all(r.map((async e=>{try{const r=await Ot(e,t);n[e]=r}catch(t){n[e]=null}}))),n}function kc(e,t){return e.map((e=>{const r=xc(e),n=t[r];return n?pt(n,e):null}))}function Oc(e){return Ws(e).concat(Js(e)).concat(Ys(e))}async function Fc(e,t,r=j){const n=await Li(e,r);return Hi(n)?function(e,t){return mc(e,N.agent,t)}(await Tc(n,r),t):sn(n)?qa(n,t,r):null}async function Nc(e,t=j){const r=await Li(e,t);return Hi(r)?mc(await Tc(r,t),N.agent,N.PublicAgent):sn(r)?Ya(r,t):null}var Dc=Object.freeze({__proto__:null,getAccessFor:ic,getAccessForAll:oc,getAgentAccess:Fc,getAgentAccessAll:async function(e,t=j){const r=await Li(e,t);return Hi(r)?function(e,t){if(e.inaccessibleUrls.length>0)return null;const r={},n=function(e,t){const r=new Set;return e.matchers.forEach((e=>{rt(e,t).filter((e=>![N.PublicAgent,N.CreatorAgent,N.AuthenticatedAgent].includes(e)||t!==N.agent)).forEach((e=>r.add(e)))})),r}(e,t);return n.forEach((n=>{const i=mc(e,t,n);r[n]=i})),r}(await Tc(r,t),N.agent):sn(r)?Qa(r,t):null},getPublicAccess:Nc,setAccessFor:sc,setAgentAccess:async function(e,t,r,n=j){const i=await Li(e,n);if(Hi(i)){const o=function(e,t,r,n){return _c(e,t,N.agent,r,n)}(i,await Tc(i,n),t,r);if(o)try{return await Bi(o,n),await Fc(e,t,n)}catch(e){return null}return null}if(sn(i)){if(r.controlRead!==r.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(i)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=r;return await tc(i,t,e,n),qa(i,t,n)}return null},setPublicAccess:async function(e,t,r=j){const n=await Li(e,r);if(Hi(n)){const i=function(e,t,r){return _c(e,t,N.agent,N.PublicAgent,r)}(n,await Tc(n,r),t);if(i)try{return await Bi(i,r),await Nc(e,r)}catch(e){return null}return null}if(sn(n)){if(t.controlRead!==t.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(n)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=t;return await rc(n,e,r),Ya(n,r)}return null}});async function Lc(e,t){if("string"!=typeof e.internal_resourceInfo.aclUrl)return null;try{return await M(e.internal_resourceInfo.aclUrl,t)}catch(e){return null}}function Uc(e,t,r){const n=tt(t,yi.allOf).map((t=>pt(jn(e),t))).filter((e=>null!==e)),i=n.every((e=>tt(e,yi.agent).includes(r))),o=tt(t,yi.anyOf).map((t=>pt(jn(e),t))).filter((e=>null!==e)),s=o.some((e=>tt(e,yi.agent).includes(r))),a=tt(t,yi.noneOf).map((t=>pt(jn(e),t))).filter((e=>null!==e)),c=a.some((e=>tt(e,yi.agent).includes(r)));return n.length+o.length>0&&(0===n.length||i)&&(0===o.length||s)&&(0===a.length||!c)}function jc(e,t,r){const n=function(e){return Ii(e,yi.allow)}(e),i=function(e){return Ii(e,yi.deny)}(e);return"control"===r?{read:t.read,append:t.append,write:t.write,controlRead:(t.controlRead||n.read)&&!i.read,controlWrite:(t.controlWrite||n.write)&&!i.write}:{read:(t.read||n.read)&&!i.read,append:(t.append||n.append)&&!i.append,write:(t.write||n.write)&&!i.write,controlRead:t.controlRead,controlWrite:t.controlWrite}}async function Mc(e,t){let r={read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1};return Os(e).map((t=>pt(jn(e),t))).filter((e=>null!==e)).forEach((n=>{Uc(e,n,t)&&(r=jc(n,r,"resource"))})),xs(e).map((t=>pt(jn(e),t))).filter((e=>null!==e)).forEach((n=>{Uc(e,n,t)&&(r=jc(n,r,"control"))})),r}async function Bc(e,t){const r=await async function(e,t){const r=function(e){const t=e.internal_resourceInfo.linkedResources[yi.accessControl];return Array.isArray(t)&&1===t.length?t[0]:null}(e);if(null!==r)return r;const n=await Lc(e,t);if(null===n)return null;const i=J(n).type;return Array.isArray(i)&&i.includes(yi.AccessControlResource)?$(n):null}(e,t);if(null===r)return null;let n;try{n=await Ot(r,t)}catch(e){return null}return{...e,internal_acp:{acr:{...n,accessTo:$(e)}}}}async function Hc(e,t,r){const n=await M(e,r),i=await Bc(n,r);return null===i?qa(n,t,r):Mc(i,t)}async function Wc(e,t){const r=await M(e,t),n=await Bc(r,t);return null===n?Ya(r,t):async function(e){return Mc(e,yi.PublicAgent)}(n)}function $c(e,t,r){return Ai(e,t).concat("AgentMatcher").concat(r.charAt(0).toUpperCase()+r.slice(1)).concat("Policy")}function Vc(e,t,r){return $c(e,t,r).concat("Matcher")}const Kc=yi.anyOf;function Jc(e,t,r,n,i){var o;const s=Vc(e,r,n),a=function(e,t,r){const n=$c(e,t,r),i=Vc(e,t,r);let o=pt(jn(e),n);return o||(e=function(e,t,r){const n=$c(e,t,r);return n.includes("Acr")?Ss(e,n):Rs(e,n)}(e,t,r),o=vt({url:n}),o=Ti(o,{[r]:!0},yi.allow)),rt(o,Kc).includes(i)?e:(o=Cr(o).addUrl(Kc,i).build(),bs(e,o))}(e,r,n),c=null!==(o=pt(jn(a),s))&&void 0!==o?o:vt({url:s});return bs(a,"add"===i?la(c,t):ua(c,t))}async function Gc(e,t,r){const n=await Mc(e,t);return"boolean"==typeof r.read&&n.read!==r.read&&(e=Jc(e,t,wi,"read",r.read?"add":"remove")),"boolean"==typeof r.append&&n.append!==r.append&&(e=Jc(e,t,wi,"append",r.append?"add":"remove")),"boolean"==typeof r.write&&n.write!==r.write&&(e=Jc(e,t,wi,"write",r.write?"add":"remove")),"boolean"==typeof r.controlRead&&n.controlRead!==r.controlRead&&(e=Jc(e,t,_i,"controlRead",r.controlRead?"add":"remove")),"boolean"==typeof r.controlWrite&&n.controlWrite!==r.controlWrite&&(e=Jc(e,t,_i,"controlWrite",r.controlWrite?"add":"remove")),e}var qc=Object.freeze({__proto__:null,getAclServerResourceInfo:Lc,getAgentAccess:Hc,getAgentAccessAll:async function(e,t){const r=await M(e,t),n=await Bc(r,t);return null===n?Qa(r,t):async function(e){return(await Promise.all((t=e,Array.from(new Set(gt(jn(t)).map((e=>tt(e,yi.agent))).reduce(((e,t)=>e.concat(t)),[])))).map((async t=>({[t]:await Mc(e,t)}))))).reduce(((e,t)=>({...e,...t})),{});var t}(n)},getPublicAccess:Wc,setAgentAccess:async function(e,t,r,n){const i=await M(e,n),o=await Bc(i,n);if(null===o)return await tc(i,t,r,n),qa(i,t,n);try{return await Bi(await Gc(o,t,r),n),await Hc(e,t,n)}catch(e){return null}},setPublicAccess:async function(e,t,r){const n=await M(e,r),i=await Bc(n,r);if(null===i)return await rc(n,t,r),Ya(n,r);try{return await Bi(await async function(e,t){return Gc(e,yi.PublicAgent,t)}(i,t),r),await Wc(e,r)}catch(e){return null}}}),zc=Object.freeze({__proto__:null,acrAsMarkdown:pi,addAcrPolicyUrl:Xn,addAgent:vo,addAllOfRuleUrl:Gi,addAnyOfRuleUrl:Qi,addClient:Do,addGroup:So,addMemberAcrPolicyUrl:Zn,addMemberPolicyUrl:ai,addMockAcrTo:hs,addNoneOfRuleUrl:to,addPolicyUrl:si,createPolicy:Wo,createResourcePolicyFor:ts,createResourceRuleFor:so,createRule:oo,getAcrPolicyUrlAll:ei,getAgentAll:yo,getAllOfRuleUrlAll:Yi,getAllowModes:Yo,getAnyOfRuleUrlAll:eo,getClientAll:Fo,getDenyModes:es,getFileWithAccessDatasets:ji,getFileWithAcr:Di,getGroupAll:wo,getLinkedAcrUrl:Ki,getMemberAcrPolicyUrlAll:ti,getMemberPolicyUrlAll:li,getNoneOfRuleUrlAll:io,getPolicy:$o,getPolicyAll:Vo,getPolicyUrlAll:ci,getReferencedPolicyUrlAll:$i,getResourceAcrPolicy:ns,getResourceAcrPolicyAll:os,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getResourcePolicy:rs,getResourcePolicyAll:is,getResourceRule:co,getResourceRuleAll:uo,getRule:ao,getRuleAll:lo,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,hasAnyClient:Uo,hasAuthenticated:To,hasCreator:Co,hasLinkedAcr:Qn,hasPublic:Ao,isAcpControlled:Vi,mockAcrFor:ds,policyAsMarkdown:us,removeAcrPolicyUrl:ri,removeAcrPolicyUrlAll:ii,removeAgent:bo,removeAllOfRuleUrl:qi,removeAnyClient:Mo,removeAnyOfRuleUrl:Xi,removeAuthenticated:Po,removeClient:Lo,removeCreator:Oo,removeGroup:Eo,removeMemberAcrPolicyUrl:ni,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:di,removeMemberPolicyUrlAll:fi,removeNoneOfRuleUrl:ro,removePolicy:Ko,removePolicyUrl:ui,removePolicyUrlAll:hi,removePublic:Io,removeResourceAcrPolicy:as,removeResourcePolicy:ss,removeResourceRule:fo,removeRule:ho,ruleAsMarkdown:Bo,saveAcrFor:Bi,setAgent:mo,setAllOfRuleUrl:zi,setAllowModes:qo,setAnyClient:jo,setAnyOfRuleUrl:Zi,setAuthenticated:xo,setClient:No,setCreator:ko,setDenyModes:Xo,setGroup:_o,setNoneOfRuleUrl:no,setPolicy:Jo,setPublic:Ro,setResourceAcrPolicy:ls,setResourcePolicy:cs,setResourceRule:go,setRule:po}),Yc=Object.freeze({__proto__:null,addAcrPolicyUrl:Ss,addAgent:la,addAllOfMatcherUrl:Ms,addAnyOfMatcherUrl:$s,addClient:_a,addMemberAcrPolicyUrl:Es,addMemberPolicyUrl:As,addMockAcrTo:hs,addNoneOfMatcherUrl:Gs,addPolicyUrl:Rs,createMatcher:Qs,createPolicy:Wo,createResourceMatcherFor:Xs,createResourcePolicyFor:ts,getAcrPolicyUrlAll:xs,getAgentAll:aa,getAllOfMatcherUrlAll:Ws,getAllowModes:zo,getAnyOfMatcherUrlAll:Js,getClientAll:wa,getDenyModes:Zo,getFileWithAccessDatasets:ji,getFileWithAcr:Di,getLinkedAcrUrl:Ki,getMatcher:Zs,getMatcherAll:ta,getMemberAcrPolicyUrlAll:Cs,getMemberPolicyUrlAll:ks,getNoneOfMatcherUrlAll:Ys,getPolicy:$o,getPolicyAll:Vo,getPolicyUrlAll:Os,getReferencedPolicyUrlAll:$i,getResourceAcrPolicy:ns,getResourceAcrPolicyAll:os,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getResourceMatcher:ea,getResourceMatcherAll:ra,getResourcePolicy:rs,getResourcePolicyAll:is,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,getVcAccess:Fi,hasAccessibleAcr:Hi,hasAuthenticated:pa,hasCreator:ma,hasLinkedAcr:Qn,hasPublic:da,isAcpControlled:Vi,mockAcrFor:ds,removeAcrPolicyUrl:Fs,removeAcrPolicyUrlAll:ii,removeAgent:ua,removeAllOfMatcherUrl:Bs,removeAnyOfMatcherUrl:Vs,removeAuthenticated:ya,removeClient:Sa,removeCreator:ba,removeMatcher:na,removeMemberAcrPolicyUrl:Ns,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:Ds,removeMemberPolicyUrlAll:fi,removeNoneOfMatcherUrl:qs,removePolicy:Ko,removePolicyUrl:Ls,removePolicyUrlAll:hi,removePublic:fa,removeResourceAcrPolicy:as,removeResourceMatcher:ia,removeResourcePolicy:ss,saveAcrFor:Bi,setAgent:ca,setAllOfMatcherUrl:Hs,setAllowModes:Go,setAnyOfMatcherUrl:Ks,setAuthenticated:ga,setCreator:va,setDenyModes:Qo,setMatcher:oa,setNoneOfMatcherUrl:zs,setPolicy:Jo,setPublic:ha,setResourceMatcher:sa,setResourcePolicy:Us,setVcAccess:Ci});const{getJsonLdParser:Qc,getTurtleParser:Xc,solidDatasetAsTurtle:Zc}=We;t.FetchError=G,t.SolidClientError=p,t.ThingExpectedError=At,t.access=nc,t.access_v1=gc,t.access_v2=Dc,t.acp_ess_1=zc,t.acp_ess_2=Yc,t.acp_v1=ms,t.acp_v2=ys,t.acp_v3=vs,t.acp_v4=Ra,t.addBoolean=Kt,t.addDate=Gt,t.addDatetime=Jt,t.addDecimal=zt,t.addInteger=Yt,t.addIri=Vt,t.addJwkToJwks=Nn,t.addLiteral=er,t.addMockFallbackAclTo=function(e){const t=Dr(V(e)),r=`${t}.acl`,n=rn(function(e,t){return Object.assign(v(e),{internal_resourceInfo:{...e.internal_resourceInfo,aclUrl:t}})}(Wt(t),r));return Gr(v(e),{resourceAcl:null,fallbackAcl:n})},t.addMockResourceAclTo=function(e){var t;const r=null!==(t=e.internal_resourceInfo.aclUrl)&&void 0!==t?t:"https://your.pod/mock-acl.ttl",n=Object.assign(v(e),{internal_resourceInfo:{...e.internal_resourceInfo,aclUrl:r}});return Gr(n,{resourceAcl:rn(n),fallbackAcl:null})},t.addNamedNode=Zt,t.addPublicKeyToProfileJwks=async function(e,t,r=j){const n=await Ot(t,{fetch:r.fetch});if(null===n)throw new Error(`The profile document associated with WebID [${t}] could not be retrieved.`);const i=Fn(n,t);if(null===i)throw new Error(`No key set is declared for the property [${L}] in the profile of [${t}]`);const o=await Nn(e,i,r);return Je(i,new Blob([JSON.stringify(o)]),{contentType:"application/json",fetch:r.fetch})},t.addStringEnglish=function(e,t,r){return Qt(e,t,r,"en")},t.addStringNoLocale=Xt,t.addStringWithLocale=Qt,t.addTerm=tr,t.addTime=qt,t.addUrl=$t,t.asIri=_t,t.asUrl=wt,t.buildThing=Cr,t.changeLogAsMarkdown=Ut,t.createAcl=rn,t.createAclFromFallbackAcl=nn,t.createContainerAt=async function(e,t=j){var r;e=(e=g(e)).endsWith("/")?e:`${e}/`;const n={...j,...t},i=await n.fetch(e,{method:"PUT",body:n.initialContent?await je(Fe(n.initialContent).map(jt)):void 0,headers:{Accept:"text/turtle","Content-Type":"text/turtle","If-None-Match":"*",Link:`<${C}>; rel="type"`}});if(b(i)){const t=void 0===n.initialContent?"empty":"non-empty";throw new G(`Creating the ${t} Container at [${e}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i)}const o=m(i);return Y({...null!==(r=t.initialContent)&&void 0!==r?r:Ct(),internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:o})},t.createContainerInContainer=async function(e,t=j){e=g(e);const r={...j,...t},n={"Content-Type":"text/turtle",Link:`<${C}>; rel="type"`};t.slugSuggestion&&(n.slug=t.slugSuggestion);const i=await r.fetch(e,{method:"POST",headers:n});if(b(i))throw new G(`Creating an empty Container in the Container at [${e}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i);const o=m(i);if(!o.location)throw new Error("Could not determine the location of the newly created Container.");try{const e=new URL(o.location).toString();return Y({...Ct(),internal_resourceInfo:{...o,sourceIri:e}})}catch(e){}return Y({...Ct(),internal_resourceInfo:{...o,sourceIri:new URL(o.location,i.url).href}})},t.createSolidDataset=Ct,t.createThing=vt,t.deleteAclFor=async function(e,t=j){const r={...j,...t},n=await r.fetch(e.internal_resourceInfo.aclUrl,{method:"DELETE"});if(!n.ok)throw new Error(`Deleting the ACL of the Resource at [${$(e)}] failed: [${n.status}] [${n.statusText}].`);return Object.assign(v(e),{acl:{resourceAcl:null}})},t.deleteContainer=async function(e,t=j){const r=d(e)?g($(e)):g(e);if(!H(e))throw new Error(`You're trying to delete the Container at [${r}], but Container URLs should end in a \`/\`. Are you sure this is a Container?`);const n={...j,...t},i=await n.fetch(r,{method:"DELETE"});if(b(i))throw new G(`Deleting the Container at [${r}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i)},t.deleteFile=async function(e,t=$e){const r={...$e,...t},n=d(e)?g(V(e)):g(e),i=await r.fetch(n,{...r.init,method:"DELETE"});if(b(i))throw new G(`Deleting the file at [${n}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i)},t.deleteSolidDataset=async function(e,t=j){const r={...j,...t},n=d(e)?g($(e)):g(e),i=await r.fetch(n,{method:"DELETE"});if(b(i))throw new G(`Deleting the SolidDataset at [${n}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i)},t.fromRdfJsDataset=function(e){const t=Array.from(e),r=Oe(t);return t.filter((e=>r.every((t=>!t.equals(e.subject))))).reduce(((e,n)=>Ie(e,n,{otherQuads:t,chainBlankNodes:r})),{graphs:{default:{}},type:"Dataset"})},t.getAgentAccess=an,t.getAgentAccessAll=cn,t.getAgentDefaultAccess=hn,t.getAgentDefaultAccessAll=fn,t.getAgentResourceAccess=ln,t.getAgentResourceAccessAll=un,t.getAltProfileUrlAllFrom=Dn,t.getBoolean=function(e,t){Ye(e);const r=ht(e,t,re);return null===r?null:ue(r)},t.getBooleanAll=function(e,t){return Ye(e),ft(e,t,re).map(ue).filter((e=>null!==e))},t.getContainedResourceUrlAll=function(e){const t=$(e),r=pt(e,t);return null===r?[]:rt(r,O).filter((e=>Dt(e,t)))},t.getContentType=W,t.getDate=function(e,t){Ye(e);const r=ht(e,t,ie);return null===r?null:fe(r)},t.getDateAll=function(e,t){return Ye(e),ft(e,t,ie).map(fe).filter((e=>null!==e))},t.getDatetime=function(e,t){Ye(e);const r=ht(e,t,ne);return null===r?null:he(r)},t.getDatetimeAll=function(e,t){return Ye(e),ft(e,t,ne).map(he).filter((e=>null!==e))},t.getDecimal=function(e,t){Ye(e);const r=ht(e,t,se);return null===r?null:ye(r)},t.getDecimalAll=function(e,t){return Ye(e),ft(e,t,se).map((e=>ye(e))).filter((e=>null!==e))},t.getEffectiveAccess=function(e){var t,r,n,i,o,s,a;if("object"==typeof e.internal_resourceInfo.permissions)return{user:{read:e.internal_resourceInfo.permissions.user.read,append:e.internal_resourceInfo.permissions.user.append,write:e.internal_resourceInfo.permissions.user.write},public:{read:e.internal_resourceInfo.permissions.public.read,append:e.internal_resourceInfo.permissions.public.append,write:e.internal_resourceInfo.permissions.public.write}};const c=J(e);return{user:{read:null!==(r=null===(t=c[N.allow])||void 0===t?void 0:t.includes(N.Read))&&void 0!==r&&r,append:null!==(o=(null===(n=c[N.allow])||void 0===n?void 0:n.includes(N.Append))||(null===(i=c[N.allow])||void 0===i?void 0:i.includes(N.Write)))&&void 0!==o&&o,write:null!==(a=null===(s=c[N.allow])||void 0===s?void 0:s.includes(N.Write))&&void 0!==a&&a}}},t.getFallbackAcl=tn,t.getFile=Ke,t.getFileWithAcl=async function(e,t=j){const r=await Ke(e,t);return Gr(r,await Or(r,t))},t.getGroupAccess=vn,t.getGroupAccessAll=bn,t.getGroupDefaultAccess=Sn,t.getGroupDefaultAccessAll=En,t.getGroupResourceAccess=wn,t.getGroupResourceAccessAll=_n,t.getInteger=function(e,t){Ye(e);const r=ht(e,t,ae);return null===r?null:me(r)},t.getIntegerAll=function(e,t){return Ye(e),ft(e,t,ae).map((e=>me(e))).filter((e=>null!==e))},t.getIri=et,t.getIriAll=rt,t.getJsonLdParser=Qc,t.getLinkedResourceUrlAll=J,t.getLiteral=ct,t.getLiteralAll=lt,t.getNamedNode=st,t.getNamedNodeAll=at,t.getPodOwner=K,t.getPodUrlAll=async function(e,t=j){return Un(await Ln(e,t),e)},t.getPodUrlAllFrom=Un,t.getProfileAll=Ln,t.getProfileJwksIri=Fn,t.getPropertyAll=function(e){return Object.keys(e.predicates).filter((t=>null!==ut(e,t)))},t.getPublicAccess=Tn,t.getPublicDefaultAccess=Pn,t.getPublicResourceAccess=xn,t.getResourceAcl=Zr,t.getResourceInfo=M,t.getResourceInfoWithAcl=async function(e,t=j){const r=await M(e,t);return Gr(r,await Or(r,t))},t.getSolidDataset=Ot,t.getSolidDatasetWithAcl=async function(e,t=j){const r=await Ot(e,t);return Gr(r,await Or(r,t))},t.getSourceIri=V,t.getSourceUrl=$,t.getStringByLocaleAll=function(e,t){var r,n;if(Ye(e),!Se(t))throw new Rt(t);const i=g(t),o=null!==(n=null===(r=e.predicates[i])||void 0===r?void 0:r.langStrings)&&void 0!==n?n:{};return new Map(Object.entries(o).map((([e,t])=>[e,[...t]])))},t.getStringEnglish=function(e,t){return nt(e,t,"en")},t.getStringEnglishAll=function(e,t){return it(e,t,"en")},t.getStringNoLocale=function(e,t){return Ye(e),ht(e,t,ce)},t.getStringNoLocaleAll=ot,t.getStringWithLocale=nt,t.getStringWithLocaleAll=it,t.getTerm=ut,t.getTermAll=dt,t.getThing=pt,t.getThingAll=gt,t.getTime=function(e,t){Ye(e);const r=ht(e,t,oe);return null===r?null:de(r)},t.getTimeAll=function(e,t){return Ye(e),ft(e,t,oe).map(de).filter((e=>null!==e))},t.getTurtleParser=Xc,t.getUrl=Ze,t.getUrlAll=tt,t.getWebIdDataset=async function(e){return Ot(e,{fetch:y})},t.getWellKnownSolid=async function(e,t=j){const r=g(e);try{const e=new URL("/.well-known/solid",new URL(r).origin).href;return await Ot(e,{fetch:y})}catch(e){}const n=J(await M(r,{fetch:t.fetch,ignoreAuthenticationErrors:!0}))[U],i=1===(null==n?void 0:n.length)?n[0]:null;if(null!==i)return Ot(new URL(".well-known/solid",i.endsWith("/")?i:`${i}/`).href,{...t,parsers:{"application/ld+json":q()}});throw new Error("Could not determine storage root or well-known solid resource.")},t.hasAccessibleAcl=sn,t.hasAcl=function(e){return"object"==typeof e.internal_acl},t.hasFallbackAcl=en,t.hasResourceAcl=Xr,t.hasResourceInfo=d,t.hasServerResourceInfo=h,t.isContainer=H,t.isPodOwner=function(e,t){const r=K(t);return"string"!=typeof r?null:r===e},t.isRawData=function(e){return e.internal_resourceInfo.isRawData},t.isThing=bt,t.isThingLocal=Et,t.mockContainerFrom=Wt,t.mockFetchError=function(e,t=404,r="Not Found"){const n=new o.Response(void 0,{status:t,statusText:r});return new G(`Fetching the Resource at [${e}] failed: [${n.status}] [${n.statusText}].`,n)},t.mockFileFrom=function(e,t){const r=new Blob;return Object.assign(r,{internal_resourceInfo:{sourceIri:g(e),isRawData:!0,contentType:null==t?void 0:t.contentType,linkedResources:{}}})},t.mockSolidDatasetFrom=Ht,t.mockThingFrom=function(e){return{type:"Subject",predicates:{},url:g(e)}},t.overwriteFile=Je,t.removeAll=nr,t.removeBoolean=sr,t.removeDate=cr,t.removeDatetime=ar,t.removeDecimal=ur,t.removeInteger=dr,t.removeIri=or,t.removeLiteral=gr,t.removeNamedNode=pr,t.removeStringEnglish=function(e,t,r){return hr(e,t,r,"en")},t.removeStringNoLocale=fr,t.removeStringWithLocale=hr,t.removeThing=mt,t.removeTime=lr,t.removeUrl=ir,t.responseToResourceInfo=B,t.responseToSolidDataset=kt,t.saveAclFor=on,t.saveFileInContainer=async function(e,t,r=$e){const n=g(e),i=await Ge(n,t,"POST",r);if(b(i))throw new G(`Saving the file in [${e}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i);const o=i.headers.get("Location");if(null===o)throw new Error("Could not determine the location of the newly saved file.");const s=new URL(o,new URL(n).origin).href,a=v(t),c={internal_resourceInfo:{isRawData:!0,sourceIri:s,contentType:qe(t,r.contentType)}};return Object.assign(a,c)},t.saveSolidDatasetAt=Ft,t.saveSolidDatasetInContainer=async function(e,t,r=j){const n={...j,...r};e=g(e);const i=await je(Fe(t).map(jt)),o={"Content-Type":"text/turtle",Link:`<${k}>; rel="type"`};r.slugSuggestion&&(o.slug=r.slugSuggestion);const s=await n.fetch(e,{method:"POST",body:i,headers:o});if(b(s))throw new G(`Storing the Resource in the Container at [${e}] failed: [${s.status}] [${s.statusText}] ${await s.text()}.\n\nThe SolidDataset that was sent to the Pod is listed below.\n\n${Lt(t)}`,s);const a=m(s);if(!a.location)throw new Error("Could not determine the location of the newly saved SolidDataset.");let c;try{c=new URL(a.location).href}catch(e){c=new URL(a.location,s.url).href}const l={internal_resourceInfo:{isRawData:!1,sourceIri:c}};return Bt(Y({...t,...l}))},t.setAgentDefaultAccess=function(e,t,r){return zr(e,r,S,"default",t)},t.setAgentResourceAccess=dn,t.setBoolean=br,t.setDate=_r,t.setDatetime=wr,t.setDecimal=Er,t.setGroupDefaultAccess=function(e,t,r){return zr(e,r,E,"default",t)},t.setGroupResourceAccess=In,t.setInteger=Ar,t.setIri=vr,t.setLiteral=xr,t.setNamedNode=Tr,t.setProfileJwks=function(e,t,r){return yt(e,vr(On(e,t),L,r))},t.setPublicDefaultAccess=function(e,t){return zr(e,t,A,"default",F)},t.setPublicResourceAccess=Cn,t.setStringNoLocale=Ir,t.setStringWithLocale=Rr,t.setTerm=Pr,t.setThing=yt,t.setTime=Sr,t.setUrl=mr,t.solidDatasetAsMarkdown=Lt,t.solidDatasetAsTurtle=Zc,t.thingAsMarkdown=St,t.toRdfJsDataset=He,t.universalAccess=qc,t.validateContainedResourceAll=function(e){const t=$(e),r=pt(e,t);if(null===r)return{isValid:!0,invalidContainedResources:[]};const n=rt(r,O).filter((e=>!Dt(e,t)));return n.length>0?{isValid:!1,invalidContainedResources:n}:{isValid:!0,invalidContainedResources:[]}}},5914:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=globalThis.fetch;const{fetch:n,Response:i,Request:o,Headers:s}=globalThis;t.Headers=s,t.Request=o,t.Response=i,t.default=r,t.fetch=n},4727:function(e,t,r){const n=r(37);e.exports=n},377:function(e){class t{constructor(e){this.value=e||"b"+ ++t.nextId}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}t.prototype.termType="BlankNode",t.nextId=0,e.exports=t},37:function(e,t,r){const n=r(377),i=r(8144),o=r(3257),s=r(2704),a=r(9938),c=r(5304),l=r(7427),u={namedNode:function(e){return new a(e)},blankNode:function(e){return new n(e)},literal:function(e,t){return"string"==typeof t?-1===t.indexOf(":")?new s(e,t):new s(e,null,u.namedNode(t)):new s(e,null,t)},variable:function(e){return new l(e)},defaultGraph:function(){return u.defaultGraphInstance},triple:function(e,t,r){return u.quad(e,t,r)},quad:function(e,t,r,n){return new c(e,t,r,n||u.defaultGraphInstance)},fromTerm:function(e){return o.call(u,e)},fromQuad:function(e){return o.call(u,e)},defaultGraphInstance:new i};e.exports=u},8144:function(e){class t{equals(e){return!!e&&e.termType===this.termType}}t.prototype.termType="DefaultGraph",t.prototype.value="",e.exports=t},2704:function(e,t,r){const n=r(9938);class i{constructor(e,t,r){this.value=e,this.datatype=i.stringDatatype,this.language="",t?(this.language=t,this.datatype=i.langStringDatatype):r&&(this.datatype=r)}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value&&e.language===this.language&&e.datatype.equals(this.datatype)}}i.prototype.termType="Literal",i.langStringDatatype=new n("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),i.stringDatatype=new n("http://www.w3.org/2001/XMLSchema#string"),e.exports=i},9938:function(e){class t{constructor(e){this.value=e}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}t.prototype.termType="NamedNode",e.exports=t},5304:function(e,t,r){const n=r(8144);class i{constructor(e,t,r,i){this.subject=e,this.predicate=t,this.object=r,this.graph=i||new n}equals(e){return!!e&&("Quad"===e.termType||!e.termType)&&e.subject.equals(this.subject)&&e.predicate.equals(this.predicate)&&e.object.equals(this.object)&&e.graph.equals(this.graph)}}i.prototype.termType="Quad",i.prototype.value="",e.exports=i},7427:function(e){class t{constructor(e){this.value=e}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}t.prototype.termType="Variable",e.exports=t},3257:function(e){e.exports=function(e){if(!e)return null;if("BlankNode"===e.termType)return this.blankNode(e.value);if("DefaultGraph"===e.termType)return this.defaultGraph();if("Literal"===e.termType)return this.literal(e.value,e.language||this.namedNode(e.datatype.value));if("NamedNode"===e.termType)return this.namedNode(e.value);if("Quad"===e.termType){const t=this.fromTerm(e.subject),r=this.fromTerm(e.predicate),n=this.fromTerm(e.object),i=this.fromTerm(e.graph);return this.quad(t,r,n,i)}if("Variable"===e.termType)return this.variable(e.value);throw new Error(`unknown termType ${e.termType}`)}},2442:function(e){function t(e){return"string"==typeof e||e instanceof String}function r(e){if("string"==typeof e)return e;if(!e)return"";if(void 0!==e.id&&"Quad"!==e.termType)return e.id;let t,n,o,s;switch(e.termType){case"NamedNode":return e.value;case"BlankNode":return`_:${e.value}`;case"Variable":return`?${e.value}`;case"DefaultGraph":return"";case"Literal":return e.language?`"${e.value}"@${e.language}`:`"${e.value}"${e.datatype&&"http://www.w3.org/2001/XMLSchema#string"!==e.datatype.value?`^^${e.datatype.value}`:""}`;case"Quad":return t=i(r(e.subject)),n=i(r(e.predicate)),o=i(r(e.object)),s="DefaultGraph"===e.graph.termType?"":` ${r(e.graph)}`,`<<${t} ${n} ${o}${s}>>`;default:throw new Error(`Unexpected termType: ${e.termType}`)}}const n=/^"(.*".*)(?="[^"]*$)/;function i(e){return e.replace(n,((e,t)=>`"${t.replace(/"/g,'""')}`))}class o{constructor(e){if(this._size=0,this._graphs=Object.create(null),this._id=0,this._ids=Object.create(null),this._ids["><"]=0,this._entities=Object.create(null),this._quads=new Map,e)for(const t of e)this.add(t)}get size(){let e=this._size;if(null!==e)return e;e=0;const t=this._graphs;let r,n;for(const i in t)for(const o in r=t[i].subjects)for(const t in n=r[o])e+=Object.keys(n[t]).length;return this._size=e,this._size}add(e){let t=r(e.subject),n=r(e.predicate),i=r(e.object);const o=r(e.graph);let s=this._graphs[o];s||(s=this._graphs[o]={subjects:{},predicates:{},objects:{}},Object.freeze(s));const a=this._ids,c=this._entities;return t=a[t]||(a[c[++this._id]=t]=this._id),n=a[n]||(a[c[++this._id]=n]=this._id),i=a[i]||(a[c[++this._id]=i]=this._id),this._addToIndex(s.subjects,t,n,i),this._addToIndex(s.predicates,n,i,t),this._addToIndex(s.objects,i,t,n),this._setQuad(t,n,i,o,e),this._size=null,this}delete(e){let t=r(e.subject),n=r(e.predicate),i=r(e.object);const o=r(e.graph),s=this._ids,a=this._graphs;let c,l,u;if(!((t=s[t])&&(n=s[n])&&(i=s[i])&&(c=a[o])&&(l=c.subjects[t])&&(u=l[n])&&i in u))return this;for(t in this._removeFromIndex(c.subjects,t,n,i),this._removeFromIndex(c.predicates,n,i,t),this._removeFromIndex(c.objects,i,t,n),null!==this._size&&this._size--,this._deleteQuad(t,n,i,o),c.subjects)return this;return delete a[o],this}has(e){const n=r(e.subject),i=r(e.predicate),o=r(e.object),s=r(e.graph),a=this._graphs[s];if(!a)return!1;const c=this._ids;let l,u,d;return!(t(n)&&!(l=c[n])||t(i)&&!(u=c[i])||t(o)&&!(d=c[o]))&&1===this._countInIndex(a.objects,d,l,u)}match(e,t,r,n){return this._createDataset(this._match(e,t,r,n))}[Symbol.iterator](){return this._match()[Symbol.iterator]()}_addToIndex(e,t,r,n){const i=e[t]||(e[t]={}),o=i[r]||(i[r]={}),s=n in o;return s||(o[n]=null),!s}_removeFromIndex(e,t,r,n){const i=e[t],o=i[r];delete o[n];for(const e in o)return;delete i[r];for(const e in i)return;delete e[t]}_findInIndex(e,t,r,n,i,o,s,a,c,l){let u,d,h;t&&((u=e,e={})[t]=u[t]);for(const t in e)if(d=e[t],d){r&&((u=d,d={})[r]=u[r]);for(const e in d)if(h=d[e],h){const r=n?n in h?[n]:[]:Object.keys(h);for(let n=0;n0?s-4:s;for(r=0;r>16&255,l[u++]=t>>8&255,l[u++]=255&t;return 2===c&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,l[u++]=255&t),1===c&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t),l},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,o=[],s=16383,a=0,l=n-i;al?l:a+s));return 1===i?(t=e[n-1],o.push(r[t>>2]+r[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],o.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),o.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)r[s]=o[s],n[o.charCodeAt(s)]=s;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function c(e,t,n){for(var i,o,s=[],a=t;a>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return s.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},8849:function(e,t,r){"use strict";r.r(t);var n=void 0!==n?n:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,i=function(){try{return 2===new Blob(["hi"]).size}catch(e){return!1}}(),o=i&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(e){return!1}}(),s=n&&n.prototype.append&&n.prototype.getBlob;function a(e){return e.map((function(e){if(e.buffer instanceof ArrayBuffer){var t=e.buffer;if(e.byteLength!==t.byteLength){var r=new Uint8Array(e.byteLength);r.set(new Uint8Array(t,e.byteOffset,e.byteLength)),t=r.buffer}return t}return e}))}function c(e,t){t=t||{};var r=new n;return a(e).forEach((function(e){r.append(e)})),t.type?r.getBlob(t.type):r.getBlob()}function l(e,t){return new Blob(a(e),t||{})}"undefined"!=typeof Blob&&(c.prototype=Blob.prototype,l.prototype=Blob.prototype),t.default=i?o?Blob:l:s?c:void 0},8287:function(e,t,r){"use strict";const n=r(7526),i=r(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=c,t.SlowBuffer=function(e){return+e!=e&&(e=0),c.alloc(+e)},t.INSPECT_MAX_BYTES=50;const s=2147483647;function a(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,c.prototype),t}function c(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return d(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!c.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|g(e,t);let n=a(r);const i=n.write(e,t);return i!==r&&(n=n.slice(0,i)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(z(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(z(e,ArrayBuffer)||e&&z(e.buffer,ArrayBuffer))return f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(z(e,SharedArrayBuffer)||e&&z(e.buffer,SharedArrayBuffer)))return f(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return c.from(n,t,r);const i=function(e){if(c.isBuffer(e)){const t=0|p(e.length),r=a(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?a(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return c.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e){return u(e),a(e<0?0:0|p(e))}function h(e){const t=e.length<0?0:0|p(e.length),r=a(t);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function g(e,t){if(c.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||z(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return J(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(i)return n?-1:J(e).length;t=(""+t).toLowerCase(),i=!0}}function y(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,r);case"utf8":case"utf-8":return I(this,t,r);case"ascii":return x(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return R(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function m(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function v(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Y(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=c.from(t,n)),c.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,i){let o,s=1,a=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){let n=-1;for(o=r;oa&&(r=a-c),o=r;o>=0;o--){let r=!0;for(let n=0;ni&&(n=i):n=i;const o=t.length;let s;for(n>o/2&&(n=o/2),s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function R(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function I(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i239?4:t>223?3:t>191?2:1;if(i+s<=r){let r,n,a,c;switch(s){case 1:t<128&&(o=t);break;case 2:r=e[i+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(o=c));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(c=(15&t)<<12|(63&r)<<6|63&n,c>2047&&(c<55296||c>57343)&&(o=c));break;case 4:r=e[i+1],n=e[i+2],a=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(c=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&a,c>65535&&c<1114112&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(c.isBuffer(t)||(t=c.from(t)),t.copy(n,i)):Uint8Array.prototype.set.call(n,t,i);else{if(!c.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},c.byteLength=g,c.prototype._isBuffer=!0,c.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},o&&(c.prototype[o]=c.prototype.inspect),c.prototype.compare=function(e,t,r,n,i){if(z(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;let o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0);const a=Math.min(o,s),l=this.slice(n,i),u=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return _(this,e,t,r);case"ascii":case"latin1":case"binary":return S(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function x(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;in)&&(r=n);let i="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function F(e,t,r,n,i,o){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function N(e,t,r,n,i){W(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,r}function D(e,t,r,n,i){W(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o>>=8,e[r+6]=o,o>>=8,e[r+5]=o,o>>=8,e[r+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s>>=8,e[r+2]=s,s>>=8,e[r+1]=s,s>>=8,e[r]=s,r+8}function L(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,o){return t=+t,r>>>=0,o||L(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function j(e,t,r,n,o){return t=+t,r>>>=0,o||L(e,0,r,8),i.write(e,t,r,n,52,8),r+8}c.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||O(e,t,this.length);let n=this[e],i=1,o=0;for(;++o>>=0,t>>>=0,r||O(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},c.prototype.readUint8=c.prototype.readUInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),this[e]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readBigUInt64LE=X((function(e){$(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||O(e,t,this.length);let n=this[e],i=1,o=0;for(;++o=i&&(n-=Math.pow(2,8*t)),n},c.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||O(e,t,this.length);let n=t,i=1,o=this[e+--n];for(;n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},c.prototype.readInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||O(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){e>>>=0,t||O(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readBigInt64LE=X((function(e){$(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||O(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||O(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||O(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||O(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUintLE=c.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||F(this,e,t,r,Math.pow(2,8*r)-1,0);let i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n||F(this,e,t,r,Math.pow(2,8*r)-1,0);let i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},c.prototype.writeUint8=c.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigUInt64LE=X((function(e,t=0){return N(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeBigUInt64BE=X((function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);F(this,e,t,r,n-1,-n)}let i=0,o=1,s=0;for(this[t]=255&e;++i>>=0,!n){const n=Math.pow(2,8*r-1);F(this,e,t,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigInt64LE=X((function(e,t=0){return N(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeBigInt64BE=X((function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return j(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,n){if(!c.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function W(e,t,r,n,i,o){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new M.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){$(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(n,i,o)}function $(e,t){if("number"!=typeof e)throw new M.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,r){if(Math.floor(e)!==e)throw $(e,r),new M.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new M.ERR_BUFFER_OUT_OF_BOUNDS;throw new M.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}B("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),B("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),B("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=H(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=H(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n}),RangeError);const K=/[^+/0-9A-Za-z-_]/g;function J(e,t){let r;t=t||1/0;const n=e.length;let i=null;const o=[];for(let s=0;s55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,r,n){let i;for(i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function z(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}const Q=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)t[n+i]=e[r]+e[i]}return t}();function X(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},2341:function(e){"use strict";e.exports=function e(t){return null===t||"object"!=typeof t||null!=t.toJSON?JSON.stringify(t):Array.isArray(t)?"["+t.reduce(((t,r,n)=>t+(0===n?"":",")+e(void 0===r||"symbol"==typeof r?null:r)),"")+"]":"{"+Object.keys(t).sort().reduce(((r,n,i)=>void 0===t[n]||"symbol"==typeof t[n]?r:r+(0===r.length?"":",")+e(n)+":"+e(t[n])),"")+"}"}},6547:function(){!function(e){!function(t){var r="URLSearchParams"in e,n="Symbol"in e&&"iterator"in Symbol,i="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),o="FormData"in e,s="ArrayBuffer"in e;if(s)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function l(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function d(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return n&&(t[Symbol.iterator]=function(){return t}),t}function h(e){this.map={},e instanceof h?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function f(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function p(e){return new Promise((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function g(e){var t=new FileReader,r=p(t);return t.readAsArrayBuffer(e),r}function y(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:i&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():s&&i&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=y(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(e)||c(e))?this._bodyArrayBuffer=y(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var e=f(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?f(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(g)}),this.text=function(){var e,t,r,n=f(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,r=p(t=new FileReader),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?n:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function w(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}})),t}function _(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new h(t.headers),this.url=t.url||"",this._initBody(e)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})},m.call(b.prototype),m.call(_.prototype),_.prototype.clone=function(){return new _(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new h(this.headers),url:this.url})},_.error=function(){var e=new _(null,{status:0,statusText:""});return e.type="error",e};var S=[301,302,303,307,308];_.redirect=function(e,t){if(-1===S.indexOf(t))throw new RangeError("Invalid status code");return new _(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function E(e,r){return new Promise((function(n,o){var s=new b(e,r);if(s.signal&&s.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function c(){a.abort()}a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new h,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();t.append(n,i)}})),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;n(new _(i,r))},a.onerror=function(){o(new TypeError("Network request failed"))},a.ontimeout=function(){o(new TypeError("Network request failed"))},a.onabort=function(){o(new t.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&i&&(a.responseType="blob"),s.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),s.signal&&(s.signal.addEventListener("abort",c),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",c)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}E.polyfill=!0,e.fetch||(e.fetch=E,e.Headers=h,e.Request=b,e.Response=_),t.Headers=h,t.Request=b,t.Response=_,t.fetch=E,Object.defineProperty(t,"__esModule",{value:!0})}({})}("undefined"!=typeof self?self:this)},7007:function(e){"use strict";var t,r="object"==typeof Reflect?Reflect:null,n=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise((function(r,n){function i(r){e.removeListener(t,o),n(r)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}g(e,t,o,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&g(e,"error",t,{once:!0})}(e,i)}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function l(e,t,r,n){var i,o,s,l;if(a(r),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),s=o[t]),void 0===s)s=o[t]=r,++e._eventsCount;else if("function"==typeof s?s=o[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),(i=c(e))>0&&s.length>i&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,l=u,console&&console.warn&&console.warn(l)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=u.bind(n);return i.listener=r,n.wrapFn=i,i}function h(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var l=c.length,u=p(c,l);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){s=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},o.prototype.listeners=function(e){return h(this,e,!0)},o.prototype.rawListeners=function(e){return h(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},o.prototype.listenerCount=f,o.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},2384:function(e){"use strict";var t=/^utf-?8|ascii|utf-?16-?le|ucs-?2|base-?64|latin-?1$/i,r=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,n=/\s|\uFEFF|\xA0/,i=/\r?\n[\x20\x09]+/g,o=/[;,"]/,s=/[;,"]|\s/,a=/^[!#$%&'*+\-\.^_`|~\da-zA-Z]+$/;function c(e){return e.replace(r,"")}function l(e){return n.test(e)}function u(e,t){for(;l(e[t]);)t++;return t}function d(e){return s.test(e)||!a.test(e)}class h{constructor(e){this.refs=[],e&&this.parse(e)}rel(e){for(var t=[],r=e.toLowerCase(),n=0;n{return r=t,n=e,Object.keys(r).length===Object.keys(n).length&&Object.keys(r).every((e=>e in n&&r[e]===n[e]));var r,n}))||this.refs.push(e),this}has(e,t){e=e.toLowerCase(),t=t.toLowerCase();for(var r=0;r",t)))throw new Error("Expected end of URI delimiter at offset "+t);s={uri:e.slice(t+1,f)},t=f,r=2,t++}else if(2===r){if(l(e[t])){t++;continue}if(";"===e[t])r=4,t++;else{if(","!==e[t])throw new Error('Unexpected character "'+e[t]+'" at offset '+t);r=1,t++}}else{if(4!==r)throw new Error('Unknown parser state "'+r+'"');if(";"===e[t]||l(e[t])){t++;continue}-1===(f=e.indexOf("=",t))&&(f=e.indexOf(";",t)),-1===f&&(f=e.length);var a=c(e.slice(t,f)).toLowerCase(),d="";if('"'===e[t=u(e,t=f+1)])for(t++;t"),e.push(t);return e.join(", ")}}h.isCompatibleEncoding=function(e){return t.test(e)},h.parse=function(e,t){return(new h).parse(e,t)},h.isSingleOccurenceAttr=function(e){return"rel"===e||"type"===e||"media"===e||"title"===e||"title*"===e},h.isTokenAttr=function(e){return"rel"===e||"type"===e||"anchor"===e},h.escapeQuotes=function(e){return e.replace(/"/g,'\\"')},h.expandRelations=function(e){return e.rel.split(" ").map((function(t){var r=Object.assign({},e);return r.rel=t,r}))},h.parseExtendedValue=function(e){var t=/([^']+)?(?:'([^']*)')?(.+)/.exec(e);return{language:t[2].toLowerCase(),encoding:h.isCompatibleEncoding(t[1])?null:t[1].toLowerCase(),value:h.isCompatibleEncoding(t[1])?decodeURIComponent(t[3]):t[3]}},h.formatExtendedAttribute=function(e,t){var r=(t.encoding||"utf-8").toUpperCase();return e+"="+r+"'"+(t.language||"en")+"'"+(Buffer.isBuffer(t.value)&&h.isCompatibleEncoding(r)?t.value.toString(r):Buffer.isBuffer(t.value)?t.value.toString("hex").replace(/[0-9a-f]{2}/gi,"%$1"):encodeURIComponent(t.value))},h.formatAttribute=function(e,t){return Array.isArray(t)?t.map((t=>h.formatAttribute(e,t))).join("; "):"*"===e[e.length-1]||"string"!=typeof t?h.formatExtendedAttribute(e,t):(h.isTokenAttr(e)?t=d(t)?'"'+h.escapeQuotes(t)+'"':h.escapeQuotes(t):d(t)&&(t='"'+(t=(t=encodeURIComponent(t)).replace(/%20/g," ").replace(/%2C/g,",").replace(/%3B/g,";"))+'"'),e+"="+t)},e.exports=h},251:function(e,t){t.read=function(e,t,r,n,i){var o,s,a=8*i-n-1,c=(1<>1,u=-7,d=r?i-1:0,h=r?-1:1,f=e[t+d];for(d+=h,o=f&(1<<-u)-1,f>>=-u,u+=a;u>0;o=256*o+e[t+d],d+=h,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=n;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),o-=l}return(f?-1:1)*s*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var s,a,c,l=8*o-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(s++,c/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(t*c-1)*Math.pow(2,i),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),s=0));i>=8;e[r+f]=255&a,f+=p,a/=256,i-=8);for(s=s<0;e[r+f]=255&s,f+=p,s/=256,l-=8);e[r+f-p]|=128*g}},2395:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(2803),t),i(r(5094),t),i(r(585),t),i(r(9146),t),i(r(5086),t),i(r(5215),t),i(r(4931),t)},2803:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextParser=void 0,r(6547);const n=r(742),i=r(5094),o=r(585),s=r(5215),a=r(4931);class c{constructor(e){e=e||{},this.documentLoader=e.documentLoader||new o.FetchDocumentLoader,this.documentCache={},this.validateContext=!e.skipValidation,this.expandContentTypeToBase=!!e.expandContentTypeToBase,this.remoteContextsDepthLimit=e.remoteContextsDepthLimit||32,this.redirectSchemaOrgHttps=!("redirectSchemaOrgHttps"in e)||!!e.redirectSchemaOrgHttps}static validateLanguage(e,t,r){if("string"!=typeof e)throw new i.ErrorCoded(`The value of an '@language' must be a string, got '${JSON.stringify(e)}'`,r);if(!a.Util.REGEX_LANGUAGE_TAG.test(e)){if(t)throw new i.ErrorCoded(`The value of an '@language' must be a valid language tag, got '${JSON.stringify(e)}'`,r);return!1}return!0}static validateDirection(e,t){if("string"!=typeof e)throw new i.ErrorCoded(`The value of an '@direction' must be a string, got '${JSON.stringify(e)}'`,i.ERROR_CODES.INVALID_BASE_DIRECTION);if(!a.Util.REGEX_DIRECTION_TAG.test(e)){if(t)throw new i.ErrorCoded(`The value of an '@direction' must be 'ltr' or 'rtl', got '${JSON.stringify(e)}'`,i.ERROR_CODES.INVALID_BASE_DIRECTION);return!1}return!0}idifyReverseTerms(e){for(const t of Object.keys(e)){let r=e[t];if(r&&"object"==typeof r&&r["@reverse"]&&!r["@id"]){if("string"!=typeof r["@reverse"]||a.Util.isValidKeyword(r["@reverse"]))throw new i.ErrorCoded(`Invalid @reverse value, must be absolute IRI or blank node: '${r["@reverse"]}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);r=e[t]=Object.assign(Object.assign({},r),{"@id":r["@reverse"]}),r["@id"]=r["@reverse"],a.Util.isPotentialKeyword(r["@reverse"])?delete r["@reverse"]:r["@reverse"]=!0}}return e}expandPrefixedTerms(e,t,r){const n=e.getContextRaw();for(const o of r||Object.keys(n))if(a.Util.EXPAND_KEYS_BLACKLIST.indexOf(o)<0&&!a.Util.isReservedInternalKeyword(o)){const r=n[o];if(a.Util.isPotentialKeyword(o)&&a.Util.ALIAS_DOMAIN_BLACKLIST.indexOf(o)>=0&&("@type"!==o||"object"==typeof n[o]&&!n[o]["@protected"]&&"@set"!==n[o]["@container"]))throw new i.ErrorCoded(`Keywords can not be aliased to something else.\nTried mapping ${o} to ${JSON.stringify(r)}`,i.ERROR_CODES.KEYWORD_REDEFINITION);if(a.Util.ALIAS_RANGE_BLACKLIST.indexOf(a.Util.getContextValueId(r))>=0)throw new i.ErrorCoded(`Aliasing to certain keywords is not allowed.\nTried mapping ${o} to ${JSON.stringify(r)}`,i.ERROR_CODES.INVALID_KEYWORD_ALIAS);if(r&&a.Util.isPotentialKeyword(a.Util.getContextValueId(r))&&!0===r["@prefix"])throw new i.ErrorCoded(`Tried to use keyword aliases as prefix: '${o}': '${JSON.stringify(r)}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION);for(;a.Util.isPrefixValue(n[o]);){const r=n[o];let i=!1;if("string"==typeof r)n[o]=e.expandTerm(r,!0),i=i||r!==n[o];else{const s=r["@id"],c=r["@type"],l=!("@prefix"in r)||a.Util.isValidIri(o);if("@id"in r)null!=s&&"string"==typeof s&&(n[o]=Object.assign(Object.assign({},n[o]),{"@id":e.expandTerm(s,!0)}),i=i||s!==n[o]["@id"]);else if(!a.Util.isPotentialKeyword(o)&&l){const t=e.expandTerm(o,!0);t!==o&&(n[o]=Object.assign(Object.assign({},n[o]),{"@id":t}),i=!0)}if(c&&"string"==typeof c&&"@vocab"!==c&&(!r["@container"]||!r["@container"]["@type"])&&l){let r=e.expandTerm(c,!0);t&&c===r&&(r=e.expandTerm(c,!1)),r!==c&&(i=!0,n[o]=Object.assign(Object.assign({},n[o]),{"@type":r}))}}if(!i)break}}}normalize(e,{processingMode:t,normalizeLanguageTags:r}){if(r||1===t)for(const t of Object.keys(e))if("@language"===t&&"string"==typeof e[t])e[t]=e[t].toLowerCase();else{const r=e[t];if(r&&"object"==typeof r&&"string"==typeof r["@language"]){const n=r["@language"].toLowerCase();n!==r["@language"]&&(e[t]=Object.assign(Object.assign({},r),{"@language":n}))}}}containersToHash(e){for(const t of Object.keys(e)){const r=e[t];if(r&&"object"==typeof r)if("string"==typeof r["@container"])e[t]=Object.assign(Object.assign({},r),{"@container":{[r["@container"]]:!0}});else if(Array.isArray(r["@container"])){const n={};for(const e of r["@container"])n[e]=!0;e[t]=Object.assign(Object.assign({},r),{"@container":n})}}}applyScopedProtected(e,{processingMode:t},r){if(t&&t>=1.1&&e["@protected"]){for(const t of Object.keys(e))if(!a.Util.isReservedInternalKeyword(t)&&!a.Util.isPotentialKeyword(t)&&!a.Util.isTermProtected(e,t)){const n=e[t];n&&"object"==typeof n?"@protected"in e[t]||(e[t]=Object.assign(Object.assign({},e[t]),{"@protected":!0})):(e[t]={"@id":n,"@protected":!0},a.Util.isSimpleTermDefinitionPrefix(n,r)&&(e[t]=Object.assign(Object.assign({},e[t]),{"@prefix":!0})))}delete e["@protected"]}}validateKeywordRedefinitions(e,t,r,n){for(const r of null!=n?n:Object.keys(t))if(a.Util.isTermProtected(e,r)&&("string"==typeof t[r]?t[r]={"@id":t[r],"@protected":!0}:t[r]=Object.assign(Object.assign({},t[r]),{"@protected":!0}),!a.Util.deepEqual(e[r],t[r])))throw new i.ErrorCoded(`Attempted to override the protected keyword ${r} from ${JSON.stringify(a.Util.getContextValueId(e[r]))} to ${JSON.stringify(a.Util.getContextValueId(t[r]))}`,i.ERROR_CODES.PROTECTED_TERM_REDEFINITION)}validate(e,{processingMode:t}){for(const r of Object.keys(e)){if(a.Util.isReservedInternalKeyword(r))continue;if(""===r)throw new i.ErrorCoded(`The empty term is not allowed, got: '${r}': '${JSON.stringify(e[r])}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION);const n=e[r],o=typeof n;if(a.Util.isPotentialKeyword(r)){switch(r.substr(1)){case"vocab":if(null!==n&&"string"!==o)throw new i.ErrorCoded(`Found an invalid @vocab IRI: ${n}`,i.ERROR_CODES.INVALID_VOCAB_MAPPING);break;case"base":if(null!==n&&"string"!==o)throw new i.ErrorCoded(`Found an invalid @base IRI: ${e[r]}`,i.ERROR_CODES.INVALID_BASE_IRI);break;case"language":null!==n&&c.validateLanguage(n,!0,i.ERROR_CODES.INVALID_DEFAULT_LANGUAGE);break;case"version":if(null!==n&&"number"!==o)throw new i.ErrorCoded(`Found an invalid @version number: ${n}`,i.ERROR_CODES.INVALID_VERSION_VALUE);break;case"direction":null!==n&&c.validateDirection(n,!0);break;case"propagate":if(1===t)throw new i.ErrorCoded(`Found an illegal @propagate keyword: ${n}`,i.ERROR_CODES.INVALID_CONTEXT_ENTRY);if(null!==n&&"boolean"!==o)throw new i.ErrorCoded(`Found an invalid @propagate value: ${n}`,i.ERROR_CODES.INVALID_PROPAGATE_VALUE)}if(a.Util.isValidKeyword(r)&&a.Util.isValidKeyword(a.Util.getContextValueId(n)))throw new i.ErrorCoded(`Illegal keyword alias in term value, found: '${r}': '${a.Util.getContextValueId(n)}'`,i.ERROR_CODES.KEYWORD_REDEFINITION)}else if(null!==n)switch(o){case"string":if(a.Util.getPrefix(n,e)===r)throw new i.ErrorCoded(`Detected cyclical IRI mapping in context entry: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.CYCLIC_IRI_MAPPING);if(a.Util.isValidIriWeak(r)){if("@type"===n)throw new i.ErrorCoded(`IRIs can not be mapped to @type, found: '${r}': '${n}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);if(a.Util.isValidIri(n)&&n!==new s.JsonLdContextNormalized(e).expandTerm(r))throw new i.ErrorCoded(`IRIs can not be mapped to other IRIs, found: '${r}': '${n}'`,i.ERROR_CODES.INVALID_IRI_MAPPING)}break;case"object":if(!(a.Util.isCompactIri(r)||"@id"in n||("@id"===n["@type"]?e["@base"]:e["@vocab"])))throw new i.ErrorCoded(`Missing @id in context entry: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);for(const l of Object.keys(n)){const u=n[l];if(u)switch(l){case"@id":if(a.Util.isValidKeyword(u)&&"@type"!==u&&"@id"!==u&&"@graph"!==u&&"@nest"!==u)throw new i.ErrorCoded(`Illegal keyword alias in term value, found: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);if(a.Util.isValidIriWeak(r)){if("@type"===u)throw new i.ErrorCoded(`IRIs can not be mapped to @type, found: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);if(a.Util.isValidIri(u)&&u!==new s.JsonLdContextNormalized(e).expandTerm(r))throw new i.ErrorCoded(`IRIs can not be mapped to other IRIs, found: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING)}if("string"!=typeof u)throw new i.ErrorCoded(`Detected non-string @id in context entry: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);if(a.Util.getPrefix(u,e)===r)throw new i.ErrorCoded(`Detected cyclical IRI mapping in context entry: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.CYCLIC_IRI_MAPPING);break;case"@type":if("@type"===n["@container"]&&"@id"!==u&&"@vocab"!==u)throw new i.ErrorCoded(`@container: @type only allows @type: @id or @vocab, but got: '${r}': '${u}'`,i.ERROR_CODES.INVALID_TYPE_MAPPING);if("string"!=typeof u)throw new i.ErrorCoded(`The value of an '@type' must be a string, got '${JSON.stringify(o)}'`,i.ERROR_CODES.INVALID_TYPE_MAPPING);if(!("@id"===u||"@vocab"===u||1!==t&&"@json"===u||1!==t&&"@none"===u||"_"!==u[0]&&a.Util.isValidIri(u)))throw new i.ErrorCoded(`A context @type must be an absolute IRI, found: '${r}': '${u}'`,i.ERROR_CODES.INVALID_TYPE_MAPPING);break;case"@reverse":if("string"==typeof u&&n["@id"]&&n["@id"]!==u)throw new i.ErrorCoded(`Found non-matching @id and @reverse term values in '${r}':'${u}' and '${n["@id"]}'`,i.ERROR_CODES.INVALID_REVERSE_PROPERTY);if("@nest"in n)throw new i.ErrorCoded(`@nest is not allowed in the reverse property '${r}'`,i.ERROR_CODES.INVALID_REVERSE_PROPERTY);break;case"@container":if(1===t&&(Object.keys(u).length>1||a.Util.CONTAINERS_1_0.indexOf(Object.keys(u)[0])<0))throw new i.ErrorCoded(`Invalid term @container for '${r}' ('${Object.keys(u)}') in 1.0, must be only one of ${a.Util.CONTAINERS_1_0.join(", ")}`,i.ERROR_CODES.INVALID_CONTAINER_MAPPING);for(const e of Object.keys(u)){if("@list"===e&&n["@reverse"])throw new i.ErrorCoded(`Term value can not be @container: @list and @reverse at the same time on '${r}'`,i.ERROR_CODES.INVALID_REVERSE_PROPERTY);if(a.Util.CONTAINERS.indexOf(e)<0)throw new i.ErrorCoded(`Invalid term @container for '${r}' ('${e}'), must be one of ${a.Util.CONTAINERS.join(", ")}`,i.ERROR_CODES.INVALID_CONTAINER_MAPPING)}break;case"@language":c.validateLanguage(u,!0,i.ERROR_CODES.INVALID_LANGUAGE_MAPPING);break;case"@direction":c.validateDirection(u,!0);break;case"@prefix":if(null!==u&&"boolean"!=typeof u)throw new i.ErrorCoded(`Found an invalid term @prefix boolean in: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_PREFIX_VALUE);if(!("@id"in n)&&!a.Util.isValidIri(r))throw new i.ErrorCoded(`Invalid @prefix definition for '${r}' ('${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION);break;case"@index":if(1===t||!n["@container"]||!n["@container"]["@index"])throw new i.ErrorCoded(`Attempt to add illegal key to value object: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION);break;case"@nest":if(a.Util.isPotentialKeyword(u)&&"@nest"!==u)throw new i.ErrorCoded(`Found an invalid term @nest value in: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_NEST_VALUE)}}break;default:throw new i.ErrorCoded(`Found an invalid term value: '${r}': '${n}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION)}}}applyBaseEntry(e,t,r){return"string"==typeof e||(r&&!("@base"in e)&&t.parentContext&&"object"==typeof t.parentContext&&"@base"in t.parentContext&&(e["@base"]=t.parentContext["@base"],t.parentContext["@__baseDocument"]&&(e["@__baseDocument"]=!0)),t.baseIRI&&!t.external&&("@base"in e?null===e["@base"]||"string"!=typeof e["@base"]||a.Util.isValidIri(e["@base"])||(e["@base"]=(0,n.resolve)(e["@base"],t.parentContext&&t.parentContext["@base"]||t.baseIRI)):(e["@base"]=t.baseIRI,e["@__baseDocument"]=!0))),e}normalizeContextIri(e,t){if(!a.Util.isValidIri(e))try{e=(0,n.resolve)(e,t)}catch(t){throw new Error(`Invalid context IRI: ${e}`)}return this.redirectSchemaOrgHttps&&e.startsWith("http://schema.org")&&(e="https://schema.org/"),e}async parseInnerContexts(e,t,r){for(const n of null!=r?r:Object.keys(e)){const r=e[n];if(r&&"object"==typeof r&&"@context"in r&&null!==r["@context"]&&!t.ignoreScopedContexts){if(this.validateContext)try{const i=Object.assign(Object.assign({},e),{[n]:Object.assign({},e[n])});delete i[n]["@context"],await this.parse(r["@context"],Object.assign(Object.assign({},t),{external:!1,parentContext:i,ignoreProtection:!0,ignoreRemoteScopedContexts:!0,ignoreScopedContexts:!0}))}catch(e){throw new i.ErrorCoded(e.message,i.ERROR_CODES.INVALID_SCOPED_CONTEXT)}e[n]=Object.assign(Object.assign({},r),{"@context":(await this.parse(r["@context"],Object.assign(Object.assign({},t),{external:!1,minimalProcessing:!0,ignoreRemoteScopedContexts:!0,parentContext:e}))).getContextRaw()})}}return e}async parse(e,t={},r={}){const{baseIRI:n,parentContext:o,external:l,processingMode:u=c.DEFAULT_PROCESSING_MODE,normalizeLanguageTags:d,ignoreProtection:h,minimalProcessing:f}=t,p=t.remoteContexts||{};if(Object.keys(p).length>=this.remoteContextsDepthLimit)throw new i.ErrorCoded("Detected an overflow in remote context inclusions: "+Object.keys(p),i.ERROR_CODES.CONTEXT_OVERFLOW);if(null==e){if(!h&&o&&a.Util.hasProtectedTerms(o))throw new i.ErrorCoded("Illegal context nullification when terms are protected",i.ERROR_CODES.INVALID_CONTEXT_NULLIFICATION);return new s.JsonLdContextNormalized(this.applyBaseEntry({},t,!1))}if("string"==typeof e){const r=this.normalizeContextIri(e,n),i=this.getOverriddenLoad(r,t);if(i)return new s.JsonLdContextNormalized(i);const o=await this.parse(await this.load(r),Object.assign(Object.assign({},t),{baseIRI:r,external:!0,remoteContexts:Object.assign(Object.assign({},p),{[r]:!0})}));return this.applyBaseEntry(o.getContextRaw(),t,!0),o}if(Array.isArray(e)){const r=[],i=await Promise.all(e.map(((e,i)=>{if("string"==typeof e){const o=this.normalizeContextIri(e,n);r[i]=o;return this.getOverriddenLoad(o,t)||this.load(o)}return e})));if(f)return new s.JsonLdContextNormalized(i);const a=await i.reduce(((e,n,o)=>e.then((e=>this.parse(n,Object.assign(Object.assign({},t),{baseIRI:r[o]||t.baseIRI,external:!!r[o]||t.external,parentContext:e.getContextRaw(),remoteContexts:r[o]?Object.assign(Object.assign({},p),{[r[o]]:!0}):p}),{skipValidation:o=1.1))throw new i.ErrorCoded("Context importing is not supported in JSON-LD 1.0",i.ERROR_CODES.INVALID_CONTEXT_ENTRY);if("string"!=typeof e["@import"])throw new i.ErrorCoded("An @import value must be a string, but got "+typeof e["@import"],i.ERROR_CODES.INVALID_IMPORT_VALUE);p=await this.loadImportContext(this.normalizeContextIri(e["@import"],n)),delete e["@import"]}this.applyScopedProtected(p,{processingMode:u},s.defaultExpandOptions);const g=Object.assign(p,e);this.idifyReverseTerms(g),this.normalize(g,{processingMode:u,normalizeLanguageTags:d}),this.applyScopedProtected(g,{processingMode:u},s.defaultExpandOptions);const y=Object.keys(g),m=[];if("object"==typeof o)for(const e in o)e in g?m.push(e):g[e]=o[e];await this.parseInnerContexts(g,t,y);const v=new s.JsonLdContextNormalized(g);return(g&&g["@version"]||c.DEFAULT_PROCESSING_MODE)>=1.1&&(e["@vocab"]&&"string"==typeof e["@vocab"]||""===e["@vocab"])&&(o&&"@vocab"in o&&e["@vocab"].indexOf(":")<0?g["@vocab"]=o["@vocab"]+e["@vocab"]:(a.Util.isCompactIri(e["@vocab"])||e["@vocab"]in g)&&(g["@vocab"]=v.expandTerm(e["@vocab"],!0))),this.expandPrefixedTerms(v,this.expandContentTypeToBase,y),!h&&o&&u>=1.1&&this.validateKeywordRedefinitions(o,g,s.defaultExpandOptions,m),this.validateContext&&!r.skipValidation&&this.validate(g,{processingMode:u}),v}throw new i.ErrorCoded(`Tried parsing a context that is not a string, array or object, but got ${e}`,i.ERROR_CODES.INVALID_LOCAL_CONTEXT)}async load(e){const t=this.documentCache[e];if(t)return t;let r;try{r=await this.documentLoader.load(e)}catch(t){throw new i.ErrorCoded(`Failed to load remote context ${e}: ${t.message}`,i.ERROR_CODES.LOADING_REMOTE_CONTEXT_FAILED)}if(!("@context"in r))throw new i.ErrorCoded(`Missing @context in remote context at ${e}`,i.ERROR_CODES.INVALID_REMOTE_CONTEXT);return this.documentCache[e]=r["@context"]}getOverriddenLoad(e,t){if(e in(t.remoteContexts||{})){if(t.ignoreRemoteScopedContexts)return e;throw new i.ErrorCoded("Detected a cyclic context inclusion of "+e,i.ERROR_CODES.RECURSIVE_CONTEXT_INCLUSION)}return null}async loadImportContext(e){let t=await this.load(e);if("object"!=typeof t||Array.isArray(t))throw new i.ErrorCoded("An imported context must be a single object: "+e,i.ERROR_CODES.INVALID_REMOTE_CONTEXT);if("@import"in t)throw new i.ErrorCoded("An imported context can not import another context: "+e,i.ERROR_CODES.INVALID_CONTEXT_ENTRY);return t=Object.assign({},t),this.containersToHash(t),t}}c.DEFAULT_PROCESSING_MODE=1.1,t.ContextParser=c},5094:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ERROR_CODES=t.ErrorCoded=void 0;class r extends Error{constructor(e,t){super(e),this.code=t}}var n;t.ErrorCoded=r,(n=t.ERROR_CODES||(t.ERROR_CODES={})).COLLIDING_KEYWORDS="colliding keywords",n.CONFLICTING_INDEXES="conflicting indexes",n.CYCLIC_IRI_MAPPING="cyclic IRI mapping",n.INVALID_ID_VALUE="invalid @id value",n.INVALID_INDEX_VALUE="invalid @index value",n.INVALID_NEST_VALUE="invalid @nest value",n.INVALID_PREFIX_VALUE="invalid @prefix value",n.INVALID_PROPAGATE_VALUE="invalid @propagate value",n.INVALID_REVERSE_VALUE="invalid @reverse value",n.INVALID_IMPORT_VALUE="invalid @import value",n.INVALID_VERSION_VALUE="invalid @version value",n.INVALID_BASE_IRI="invalid base IRI",n.INVALID_CONTAINER_MAPPING="invalid container mapping",n.INVALID_CONTEXT_ENTRY="invalid context entry",n.INVALID_CONTEXT_NULLIFICATION="invalid context nullification",n.INVALID_DEFAULT_LANGUAGE="invalid default language",n.INVALID_INCLUDED_VALUE="invalid @included value",n.INVALID_IRI_MAPPING="invalid IRI mapping",n.INVALID_JSON_LITERAL="invalid JSON literal",n.INVALID_KEYWORD_ALIAS="invalid keyword alias",n.INVALID_LANGUAGE_MAP_VALUE="invalid language map value",n.INVALID_LANGUAGE_MAPPING="invalid language mapping",n.INVALID_LANGUAGE_TAGGED_STRING="invalid language-tagged string",n.INVALID_LANGUAGE_TAGGED_VALUE="invalid language-tagged value",n.INVALID_LOCAL_CONTEXT="invalid local context",n.INVALID_REMOTE_CONTEXT="invalid remote context",n.INVALID_REVERSE_PROPERTY="invalid reverse property",n.INVALID_REVERSE_PROPERTY_MAP="invalid reverse property map",n.INVALID_REVERSE_PROPERTY_VALUE="invalid reverse property value",n.INVALID_SCOPED_CONTEXT="invalid scoped context",n.INVALID_SCRIPT_ELEMENT="invalid script element",n.INVALID_SET_OR_LIST_OBJECT="invalid set or list object",n.INVALID_TERM_DEFINITION="invalid term definition",n.INVALID_TYPE_MAPPING="invalid type mapping",n.INVALID_TYPE_VALUE="invalid type value",n.INVALID_TYPED_VALUE="invalid typed value",n.INVALID_VALUE_OBJECT="invalid value object",n.INVALID_VALUE_OBJECT_VALUE="invalid value object value",n.INVALID_VOCAB_MAPPING="invalid vocab mapping",n.IRI_CONFUSED_WITH_PREFIX="IRI confused with prefix",n.KEYWORD_REDEFINITION="keyword redefinition",n.LOADING_DOCUMENT_FAILED="loading document failed",n.LOADING_REMOTE_CONTEXT_FAILED="loading remote context failed",n.MULTIPLE_CONTEXT_LINK_HEADERS="multiple context link headers",n.PROCESSING_MODE_CONFLICT="processing mode conflict",n.PROTECTED_TERM_REDEFINITION="protected term redefinition",n.CONTEXT_OVERFLOW="context overflow",n.INVALID_BASE_DIRECTION="invalid base direction",n.RECURSIVE_CONTEXT_INCLUSION="recursive context inclusion",n.INVALID_STREAMING_KEY_ORDER="invalid streaming key order",n.INVALID_EMBEDDED_NODE="invalid embedded node",n.INVALID_ANNOTATION="invalid annotation"},585:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FetchDocumentLoader=void 0,r(6547);const n=r(5094),i=r(2384),o=r(742);t.FetchDocumentLoader=class{constructor(e){this.fetcher=e}async load(e){const t=await(this.fetcher||fetch)(e,{headers:new Headers({accept:"application/ld+json"})});if(t.ok&&t.headers){let r=t.headers.get("Content-Type");if(r){const e=r.indexOf(";");e>0&&(r=r.substr(0,e))}if("application/ld+json"===r)return await t.json();if(t.headers.has("Link")){let r;if(t.headers.forEach(((t,n)=>{if("link"===n){const n=(0,i.parse)(t);for(const t of n.get("type","application/ld+json"))if("alternate"===t.rel){if(r)throw new Error("Multiple JSON-LD alternate links were found on "+e);r=(0,o.resolve)(t.uri,e)}}})),r)return this.load(r)}throw new n.ErrorCoded(`Unsupported JSON-LD media type ${r}`,n.ERROR_CODES.LOADING_DOCUMENT_FAILED)}throw new Error(t.statusText||`Status code: ${t.status}`)}}},9146:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},5086:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},5215:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultExpandOptions=t.JsonLdContextNormalized=void 0;const n=r(742),i=r(5094),o=r(4931);t.JsonLdContextNormalized=class{constructor(e){this.contextRaw=e}getContextRaw(){return this.contextRaw}expandTerm(e,r,s=t.defaultExpandOptions){const a=this.contextRaw[e];if(null===a||a&&null===a["@id"])return null;let c=!0;if(a&&r){const t=o.Util.getContextValueId(a);if(t&&t!==e){if("string"==typeof t&&(o.Util.isValidIri(t)||o.Util.isValidKeyword(t)))return t;o.Util.isPotentialKeyword(t)||(c=!1)}}const l=o.Util.getPrefix(e,this.contextRaw),u=this.contextRaw["@vocab"],d=(!!u||""===u)&&u.indexOf(":")<0,h=this.contextRaw["@base"],f=o.Util.isPotentialKeyword(e);if(l){const t=this.contextRaw[l],r=o.Util.getContextValueId(t);if(r){if("string"!=typeof t&&s.allowPrefixForcing){if("_"!==r[0]&&!f&&!t["@prefix"]&&!(e in this.contextRaw))return e}else if(!o.Util.isSimpleTermDefinitionPrefix(r,s))return e;return r+e.substr(l.length+1)}}else{if(r&&(u||""===u||s.allowVocabRelativeToBase&&h&&d)&&!f&&!o.Util.isCompactIri(e)){if(d){if(s.allowVocabRelativeToBase)return(u||h?(0,n.resolve)(u,h):"")+e;throw new i.ErrorCoded(`Relative vocab expansion for term '${e}' with vocab '${u}' is not allowed.`,i.ERROR_CODES.INVALID_VOCAB_MAPPING)}return u+e}if(!r&&h&&!f&&!o.Util.isCompactIri(e))return(0,n.resolve)(e,h)}if(c)return e;throw new i.ErrorCoded(`Invalid IRI mapping found for context entry '${e}': '${JSON.stringify(a)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING)}compactIri(e,t){if(t&&this.contextRaw["@vocab"]&&e.startsWith(this.contextRaw["@vocab"]))return e.substr(this.contextRaw["@vocab"].length);if(!t&&this.contextRaw["@base"]&&e.startsWith(this.contextRaw["@base"]))return e.substr(this.contextRaw["@base"].length);const r={prefix:"",suffix:e};for(const n in this.contextRaw){const i=this.contextRaw[n];if(i&&!o.Util.isPotentialKeyword(n)){const s=o.Util.getContextValueId(i);if(e.startsWith(s)){const i=e.substr(s.length);if(i)i.length0&&!(e&&"#"===e[0])}static getPrefix(e,t){if(e&&"#"===e[0])return null;const r=e.indexOf(":");if(r>=0){if(e.length>r+1&&"/"===e.charAt(r+1)&&"/"===e.charAt(r+2))return null;const n=e.substr(0,r);if("_"===n)return null;if(t[n])return n}return null}static getContextValueId(e){if(null===e||"string"==typeof e)return e;return e["@id"]||null}static isSimpleTermDefinitionPrefix(e,t){return!r.isPotentialKeyword(e)&&(t.allowPrefixNonGenDelims||"string"==typeof e&&("_"===e[0]||r.isPrefixIriEndingWithGenDelim(e)))}static isPotentialKeyword(e){return"string"==typeof e&&r.KEYWORD_REGEX.test(e)}static isPrefixIriEndingWithGenDelim(e){return r.ENDS_WITH_GEN_DELIM.test(e)}static isPrefixValue(e){return e&&("string"==typeof e||e&&"object"==typeof e)}static isValidIri(e){return Boolean(e&&r.IRI_REGEX.test(e))}static isValidIriWeak(e){return!!e&&":"!==e[0]&&r.IRI_REGEX_WEAK.test(e)}static isValidKeyword(e){return r.VALID_KEYWORDS[e]}static isTermProtected(e,t){const r=e[t];return!("string"==typeof r)&&r&&r["@protected"]}static hasProtectedTerms(e){for(const t of Object.keys(e))if(r.isTermProtected(e,t))return!0;return!1}static isReservedInternalKeyword(e){return e.startsWith("@__")}static deepEqual(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every((r=>{const n=e[r],i=t[r];return n===i||null!==n&&null!==i&&"object"==typeof n&&"object"==typeof i&&this.deepEqual(n,i)}))}}r.IRI_REGEX=/^([A-Za-z][A-Za-z0-9+-.]*|_):[^ "<>{}|\\\[\]`#]*(#[^#]*)?$/,r.IRI_REGEX_WEAK=/(?::[^:])|\//,r.KEYWORD_REGEX=/^@[a-z]+$/i,r.ENDS_WITH_GEN_DELIM=/[:/?#\[\]@]$/,r.REGEX_LANGUAGE_TAG=/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/,r.REGEX_DIRECTION_TAG=/^(ltr)|(rtl)$/,r.VALID_KEYWORDS={"@annotation":!0,"@base":!0,"@container":!0,"@context":!0,"@direction":!0,"@graph":!0,"@id":!0,"@import":!0,"@included":!0,"@index":!0,"@json":!0,"@language":!0,"@list":!0,"@nest":!0,"@none":!0,"@prefix":!0,"@propagate":!0,"@protected":!0,"@reverse":!0,"@set":!0,"@type":!0,"@value":!0,"@version":!0,"@vocab":!0},r.EXPAND_KEYS_BLACKLIST=["@base","@vocab","@language","@version","@direction"],r.ALIAS_DOMAIN_BLACKLIST=["@container","@graph","@id","@index","@list","@nest","@none","@prefix","@reverse","@set","@type","@value","@version"],r.ALIAS_RANGE_BLACKLIST=["@context","@preserve"],r.CONTAINERS=["@list","@set","@index","@language","@graph","@id","@type"],r.CONTAINERS_1_0=["@list","@set","@index"],t.Util=r},8690:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(2277),t)},4405:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextTree=void 0;class r{constructor(){this.subTrees={}}getContext(e){if(e.length>0){const[t,...r]=e,n=this.subTrees[t];if(n){const e=n.getContext(r);if(e)return e.then((({context:e,depth:t})=>({context:e,depth:t+1})))}}return this.context?this.context.then((e=>({context:e,depth:0}))):null}setContext(e,t){if(0===e.length)this.context=t;else{const[n,...i]=e;let o=this.subTrees[n];o||(o=this.subTrees[n]=new r),o.setContext(i,t)}}removeContext(e){this.setContext(e,null)}}t.ContextTree=r},2277:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonLdParser=void 0;const n=r(608),i=r(2395),o=r(2225),s=r(9693),a=r(4860),c=r(2386),l=r(6970),u=r(3809),d=r(5998),h=r(5517),f=r(736),p=r(4910),g=r(2036),y=r(6454),m=r(3283),v=r(3099),b=r(888),w=r(2384),_=r(6105);class S extends o.Transform{constructor(e){super({readableObjectMode:!0}),e=e||{},this.options=e,this.parsingContext=new v.ParsingContext(Object.assign({parser:this},e)),this.util=new b.Util({dataFactory:e.dataFactory,parsingContext:this.parsingContext}),this.jsonParser=new n,this.contextJobs=[],this.typeJobs=[],this.contextAwaitingJobs=[],this.lastDepth=0,this.lastKeys=[],this.lastOnValueJob=Promise.resolve(),this.attachJsonParserListeners(),this.on("end",(()=>{void 0!==this.jsonParser.mode&&this.emit("error",new Error("Unclosed document"))}))}static fromHttpResponse(e,t,r,n){let o,s,a=["application/activity+json"];if(n&&n.wellKnownMediaTypes&&(a=n.wellKnownMediaTypes),"application/ld+json"!==t&&!a.includes(t)){if("application/json"!==t&&!t.endsWith("+json"))throw new i.ErrorCoded(`Unsupported JSON-LD media type ${t}`,i.ERROR_CODES.LOADING_DOCUMENT_FAILED);if(r&&r.has("Link")&&r.forEach(((t,r)=>{if("link"===r){const r=(0,w.parse)(t);for(const t of r.get("rel","http://www.w3.org/ns/json-ld#context")){if(o)throw new i.ErrorCoded("Multiple JSON-LD context link headers were found on "+e,i.ERROR_CODES.MULTIPLE_CONTEXT_LINK_HEADERS);o=t.uri}}})),!o&&!(null==n?void 0:n.ignoreMissingContextLinkHeader))throw new i.ErrorCoded(`Missing context link header for media type ${t} on ${e}`,i.ERROR_CODES.LOADING_DOCUMENT_FAILED)}if(r&&r.has("Content-Type")){const e=r.get("Content-Type"),t=/; *profile=([^"]*)/.exec(e);t&&"http://www.w3.org/ns/json-ld#streaming"===t[1]&&(s=!0)}return new S(Object.assign({baseIRI:e,context:o,streamingProfile:s},n||{}))}import(e){if("pipe"in e){e.on("error",(e=>t.emit("error",e)));const t=e.pipe(new S(this.options));return t}{const t=new o.PassThrough({readableObjectMode:!0});e.on("error",(e=>r.emit("error",e))),e.on("data",(e=>t.push(e))),e.on("end",(()=>t.push(null)));const r=t.pipe(new S(this.options));return r}}_transform(e,t,r){this.jsonParser.write(e),this.lastOnValueJob.then((()=>r()),(e=>r(e)))}async newOnValueJob(e,t,r,n){let o=!0;if(n&&r1&&(u=this.parsingContext.validationStack[this.parsingContext.validationStack.length-1].property);for(let t=Math.max(1,this.parsingContext.validationStack.length-1);t=0?this.parsingContext.idStack[e-r-1]:[await this.util.getGraphContainerValue(t,e)];if(o)for(const t of o){this.parsingContext.emittedStack[e]=!0;for(const r of n)this.util.emitQuadChecked(e,i,r.predicate,r.object,t,r.reverse,r.isEmbedded)}else{const r=this.parsingContext.getUnidentifiedGraphBufferSafe(e-await this.util.getDepthOffsetGraph(e,t)-1);for(const e of n)e.reverse?r.push({object:i,predicate:e.predicate,subject:e.object,isEmbedded:e.isEmbedded}):r.push({object:e.object,predicate:e.predicate,subject:i,isEmbedded:e.isEmbedded})}}this.parsingContext.unidentifiedValuesBuffer.splice(e,1),this.parsingContext.literalStack.splice(e,1),this.parsingContext.jsonLiteralStack.splice(e,1)}const o=this.parsingContext.unidentifiedGraphsBuffer[e];if(o){for(const t of r){const r=1!==e||"BlankNode"!==t.termType||this.parsingContext.topLevelProperties?t:this.util.getDefaultGraph();this.parsingContext.emittedStack[e]=!0;for(const t of o)this.parsingContext.emitQuad(e,this.util.dataFactory.quad(t.subject,t.predicate,t.object,r))}this.parsingContext.unidentifiedGraphsBuffer.splice(e,1)}const s=this.parsingContext.annotationsBuffer[e];if(s){s.length>0&&1===e&&this.parsingContext.emitError(new i.ErrorCoded("Annotations can not be made on top-level nodes",i.ERROR_CODES.INVALID_ANNOTATION));const t=this.parsingContext.getAnnotationsBufferSafe(e-1);for(const e of s)t.push(e);delete this.parsingContext.annotationsBuffer[e]}}async validateKey(e,t,r){for(const n of S.ENTRY_HANDLERS)if(await n.validate(this.parsingContext,this.util,e,t,r))return{valid:!0,property:r||n.isPropertyHandler()};return{valid:!1,property:!1}}attachJsonParserListeners(){this.jsonParser.onValue=e=>{const t=this.jsonParser.stack.length,r=new Array(t+1).fill(0).map(((e,r)=>r===t?this.jsonParser.key:this.jsonParser.stack[r].key));if(!this.isParsingContextInner(t)){const n=()=>this.newOnValueJob(r,e,t,!0);if(this.parsingContext.streamingProfile||this.parsingContext.contextTree.getContext(r.slice(0,-1)))this.lastOnValueJob=this.lastOnValueJob.then(n);else if("@context"===r[t]){let e=this.contextJobs[t];e||(e=this.contextJobs[t]=[]),e.push(n)}else this.contextAwaitingJobs.push({job:n,keys:r,depth:t});this.parsingContext.streamingProfile||0!==t||(this.lastOnValueJob=this.lastOnValueJob.then((()=>this.executeBufferedJobs())))}},this.jsonParser.onError=e=>{this.emit("error",e)}}isParsingContextInner(e){for(let t=e;t>0;t--)if("@context"===this.jsonParser.stack[t-1].key)return!0;return!1}async executeBufferedJobs(){for(const e of this.contextJobs)if(e)for(const t of e)await t();this.parsingContext.unaliasedKeywordCacheStack.splice(0);const e=[];for(const t of this.contextAwaitingJobs)"@type"===await this.util.unaliasKeyword(t.keys[t.depth],t.keys,t.depth,!0)||"number"==typeof t.keys[t.depth]&&"@type"===await this.util.unaliasKeyword(t.keys[t.depth-1],t.keys,t.depth-1,!0)?this.typeJobs.push({job:t.job,keys:t.keys.slice(0,t.keys.length-1)}):e.push(t);for(const t of e){if(this.typeJobs.length>0){const e=[],r=[];for(let n=0;ne.keys.length-t.keys.length));for(const e of n)await e.job();const i=r.sort().reverse();for(const e of i)this.typeJobs.splice(e,1)}await t.job()}}}S.DEFAULT_PROCESSING_MODE="1.1",S.ENTRY_HANDLERS=[new s.EntryHandlerArrayValue,new u.EntryHandlerKeywordContext,new h.EntryHandlerKeywordId,new f.EntryHandlerKeywordIncluded,new d.EntryHandlerKeywordGraph,new p.EntryHandlerKeywordNest,new g.EntryHandlerKeywordType,new m.EntryHandlerKeywordValue,new _.EntryHandlerKeywordAnnotation,new a.EntryHandlerContainer,new y.EntryHandlerKeywordUnknownFallback,new l.EntryHandlerPredicate,new c.EntryHandlerInvalidFallback],t.JsonLdParser=S},3099:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ParsingContext=void 0;const n=r(2395),i=r(5094),o=r(4405),s=r(2277);class a{constructor(e){this.contextParser=new n.ContextParser({documentLoader:e.documentLoader,skipValidation:e.skipContextValidation}),this.streamingProfile=!!e.streamingProfile,this.baseIRI=e.baseIRI,this.produceGeneralizedRdf=!!e.produceGeneralizedRdf,this.allowSubjectList=!!e.allowSubjectList,this.processingMode=e.processingMode||s.JsonLdParser.DEFAULT_PROCESSING_MODE,this.strictValues=!!e.strictValues,this.validateValueIndexes=!!e.validateValueIndexes,this.defaultGraph=e.defaultGraph,this.rdfDirection=e.rdfDirection,this.normalizeLanguageTags=e.normalizeLanguageTags,this.streamingProfileAllowOutOfOrderPlainType=e.streamingProfileAllowOutOfOrderPlainType,this.rdfstar=!1!==e.rdfstar,this.rdfstarReverseInEmbedded=e.rdfstarReverseInEmbedded,this.topLevelProperties=!1,this.activeProcessingMode=parseFloat(this.processingMode),this.processingStack=[],this.processingType=[],this.emittedStack=[],this.idStack=[],this.graphStack=[],this.graphContainerTermStack=[],this.listPointerStack=[],this.contextTree=new o.ContextTree,this.literalStack=[],this.validationStack=[],this.unaliasedKeywordCacheStack=[],this.jsonLiteralStack=[],this.unidentifiedValuesBuffer=[],this.unidentifiedGraphsBuffer=[],this.annotationsBuffer=[],this.pendingContainerFlushBuffers=[],this.parser=e.parser,e.context?(this.rootContext=this.parseContext(e.context),this.rootContext.then((e=>this.validateContext(e)))):this.rootContext=Promise.resolve(new n.JsonLdContextNormalized(this.baseIRI?{"@base":this.baseIRI,"@__baseDocument":!0}:{}))}async parseContext(e,t,r){return this.contextParser.parse(e,{baseIRI:this.baseIRI,ignoreProtection:r,normalizeLanguageTags:this.normalizeLanguageTags,parentContext:t,processingMode:this.activeProcessingMode})}validateContext(e){const t=e.getContextRaw()["@version"];if(t){if(this.activeProcessingMode&&t>this.activeProcessingMode)throw new i.ErrorCoded(`Unsupported JSON-LD version '${t}' under active processing mode ${this.activeProcessingMode}.`,i.ERROR_CODES.PROCESSING_MODE_CONFLICT);if(this.activeProcessingMode&&t0&&!1===i.context.getContextRaw()["@propagate"]&&i.depth!==t&&!r);return 0===i.depth&&!1===i.context.getContextRaw()["@propagate"]&&i.depth!==t&&(i.context=new n.JsonLdContextNormalized({})),i}async newOnValueJob(e,t,r,n){await this.parser.newOnValueJob(e,t,r,n)}async handlePendingContainerFlushBuffers(){if(this.pendingContainerFlushBuffers.length>0){for(const e of this.pendingContainerFlushBuffers)await this.parser.flushBuffer(e.depth,e.keys),this.parser.flushStacks(e.depth);return this.pendingContainerFlushBuffers.splice(0,this.pendingContainerFlushBuffers.length),!0}return!1}emitQuad(e,t){1===e&&(this.topLevelProperties=!0),this.parser.push(t)}emitError(e){this.parser.emit("error",e)}emitContext(e){this.parser.emit("context",e)}getUnidentifiedValueBufferSafe(e){let t=this.unidentifiedValuesBuffer[e];return t||(t=[],this.unidentifiedValuesBuffer[e]=t),t}getUnidentifiedGraphBufferSafe(e){let t=this.unidentifiedGraphsBuffer[e];return t||(t=[],this.unidentifiedGraphsBuffer[e]=t),t}getAnnotationsBufferSafe(e){let t=this.annotationsBuffer[e];return t||(t=[],this.annotationsBuffer[e]=t),t}getExpandOptions(){return a.EXPAND_OPTIONS[this.activeProcessingMode]}shiftStack(e,t){const r=this.idStack[e+t];if(r&&(this.idStack[e]=r,this.emittedStack[e]=!0,delete this.idStack[e+t]),this.pendingContainerFlushBuffers.length)for(const r of this.pendingContainerFlushBuffers)r.depth>=e+t&&(r.depth-=t,r.keys.splice(e,t));this.unidentifiedValuesBuffer[e+t]&&(this.unidentifiedValuesBuffer[e]=this.unidentifiedValuesBuffer[e+t],delete this.unidentifiedValuesBuffer[e+t]),this.annotationsBuffer[e+t-1]&&(this.annotationsBuffer[e-1]||(this.annotationsBuffer[e-1]=[]),this.annotationsBuffer[e-1]=[...this.annotationsBuffer[e-1],...this.annotationsBuffer[e+t-1]],delete this.annotationsBuffer[e+t-1])}}a.EXPAND_OPTIONS={1:{allowPrefixForcing:!1,allowPrefixNonGenDelims:!1,allowVocabRelativeToBase:!1},1.1:{allowPrefixForcing:!0,allowPrefixNonGenDelims:!1,allowVocabRelativeToBase:!0}},t.ParsingContext=a},888:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Util=void 0;const n=r(2395),i=r(7793),o=r(4860),s=r(2341);class a{constructor(e){this.parsingContext=e.parsingContext,this.dataFactory=e.dataFactory||new i.DataFactory,this.rdfFirst=this.dataFactory.namedNode(a.RDF+"first"),this.rdfRest=this.dataFactory.namedNode(a.RDF+"rest"),this.rdfNil=this.dataFactory.namedNode(a.RDF+"nil"),this.rdfType=this.dataFactory.namedNode(a.RDF+"type"),this.rdfJson=this.dataFactory.namedNode(a.RDF+"JSON")}static getContextValue(e,t,r,n){const i=e.getContextRaw()[r];if(!i)return n;const o=i[t];return void 0===o?n:o}static getContextValueContainer(e,t){return a.getContextValue(e,"@container",t,{"@set":!0})}static getContextValueType(e,t){const r=a.getContextValue(e,"@type",t,null);return"@none"===r?null:r}static getContextValueLanguage(e,t){return a.getContextValue(e,"@language",t,e.getContextRaw()["@language"]||null)}static getContextValueDirection(e,t){return a.getContextValue(e,"@direction",t,e.getContextRaw()["@direction"]||null)}static isContextValueReverse(e,t){return!!a.getContextValue(e,"@reverse",t,null)}static getContextValueIndex(e,t){return a.getContextValue(e,"@index",t,e.getContextRaw()["@index"]||null)}static isPropertyReverse(e,t,r){return"@reverse"===r!==a.isContextValueReverse(e,t)}static isPropertyInEmbeddedNode(e){return"@id"===e}static isPropertyInAnnotationObject(e){return"@annotation"===e}static isValidIri(e){return null!==e&&n.Util.isValidIri(e)}static isPrefixArray(e,t){if(e.length>t.length)return!1;for(let r=0;r1)throw new n.ErrorCoded(`Found illegal neighbouring entries next to @set for key: '${t}'`,n.ERROR_CODES.INVALID_SET_OR_LIST_OBJECT);return[]}if("@list"in r){if(Object.keys(r).length>1)throw new n.ErrorCoded(`Found illegal neighbouring entries next to @list for key: '${t}'`,n.ERROR_CODES.INVALID_SET_OR_LIST_OBJECT);const e=r["@list"];return Array.isArray(e)?0===e.length?[this.rdfNil]:this.parsingContext.idStack[i+1]||[]:await this.valueToTerm(await this.parsingContext.getContext(o),t,e,i-1,o.slice(0,-1))}if("@reverse"in r&&"boolean"==typeof r["@reverse"])return[];if("@graph"in a.getContextValueContainer(await this.parsingContext.getContext(o),t)){const e=this.parsingContext.graphContainerTermStack[i+1];return e?Object.values(e):[this.dataFactory.blankNode()]}if("@id"in r){if(Object.keys(r).length>1&&(e=await this.parsingContext.getContext(o,0)),"@context"in r&&(e=await this.parsingContext.parseContext(r["@context"],e.getContextRaw())),"@vocab"===r["@type"])return this.nullableTermToArray(this.createVocabOrBaseTerm(e,r["@id"]));{const t=r["@id"];let o;if("object"==typeof t){if(!this.parsingContext.rdfstar)throw new n.ErrorCoded(`Found illegal @id '${r}'`,n.ERROR_CODES.INVALID_ID_VALUE);o=this.parsingContext.idStack[i+1][0]}else o=this.resourceToTerm(e,t);return this.nullableTermToArray(o)}}return this.parsingContext.emittedStack[i+1]||r&&"object"==typeof r&&0===Object.keys(r).length?this.parsingContext.idStack[i+1]||(this.parsingContext.idStack[i+1]=[this.dataFactory.blankNode()]):[];case"string":return this.nullableTermToArray(this.stringValueToTerm(i,await this.getContextSelfOrPropertyScoped(e,t),t,r,null));case"boolean":return this.nullableTermToArray(this.stringValueToTerm(i,await this.getContextSelfOrPropertyScoped(e,t),t,Boolean(r).toString(),this.dataFactory.namedNode(a.XSD_BOOLEAN)));case"number":return this.nullableTermToArray(this.stringValueToTerm(i,await this.getContextSelfOrPropertyScoped(e,t),t,r,this.dataFactory.namedNode(r%1==0&&r<1e21?a.XSD_INTEGER:a.XSD_DOUBLE)));default:return this.parsingContext.emitError(new Error(`Could not determine the RDF type of a ${s}`)),[]}}async getContextSelfOrPropertyScoped(e,t){const r=e.getContextRaw()[t];return r&&"object"==typeof r&&"@context"in r&&(e=await this.parsingContext.parseContext(r,e.getContextRaw(),!0)),e}nullableTermToArray(e){return e?[e]:[]}predicateToTerm(e,t){const r=e.expandTerm(t,!0,this.parsingContext.getExpandOptions());return r?"_"===r[0]&&":"===r[1]?this.parsingContext.produceGeneralizedRdf?this.dataFactory.blankNode(r.substr(2)):null:a.isValidIri(r)?this.dataFactory.namedNode(r):r&&this.parsingContext.strictValues?(this.parsingContext.emitError(new n.ErrorCoded(`Invalid predicate IRI: ${r}`,n.ERROR_CODES.INVALID_IRI_MAPPING)),null):null:null}resourceToTerm(e,t){if(t.startsWith("_:"))return this.dataFactory.blankNode(t.substr(2));const r=e.expandTerm(t,!1,this.parsingContext.getExpandOptions());if(!a.isValidIri(r)){if(!r||!this.parsingContext.strictValues)return null;this.parsingContext.emitError(new Error(`Invalid resource IRI: ${r}`))}return this.dataFactory.namedNode(r)}createVocabOrBaseTerm(e,t){if(t.startsWith("_:"))return this.dataFactory.blankNode(t.substr(2));const r=this.parsingContext.getExpandOptions();let n=e.expandTerm(t,!0,r);if(n===t&&(n=e.expandTerm(t,!1,r)),!a.isValidIri(n)){if(!n||!this.parsingContext.strictValues||n.startsWith("@"))return null;this.parsingContext.emitError(new Error(`Invalid term IRI: ${n}`))}return this.dataFactory.namedNode(n)}intToString(e,t){return"number"==typeof e?Number.isFinite(e)?e%1!=0||t&&t.value===a.XSD_DOUBLE?e.toExponential(15).replace(/(\d)0*e\+?/,"$1E"):Number(e).toString():e>0?"INF":"-INF":e}stringValueToTerm(e,t,r,n,i){const o=a.getContextValueType(t,r);if(o)if("@id"===o){if(!i)return this.resourceToTerm(t,this.intToString(n,i))}else if("@vocab"===o){if(!i)return this.createVocabOrBaseTerm(t,this.intToString(n,i))}else i=this.dataFactory.namedNode(o);if(!i){const o=a.getContextValueLanguage(t,r),s=a.getContextValueDirection(t,r);return s&&this.parsingContext.rdfDirection?this.createLanguageDirectionLiteral(e,this.intToString(n,i),o,s):this.dataFactory.literal(this.intToString(n,i),o)}return this.dataFactory.literal(this.intToString(n,i),i)}createLanguageDirectionLiteral(e,t,r,n){if("i18n-datatype"===this.parsingContext.rdfDirection)return r||(r=""),this.dataFactory.literal(t,this.dataFactory.namedNode(`https://www.w3.org/ns/i18n#${r}_${n}`));{const i=this.dataFactory.blankNode(),o=this.getDefaultGraph();return this.parsingContext.emitQuad(e,this.dataFactory.quad(i,this.dataFactory.namedNode(a.RDF+"value"),this.dataFactory.literal(t),o)),r&&this.parsingContext.emitQuad(e,this.dataFactory.quad(i,this.dataFactory.namedNode(a.RDF+"language"),this.dataFactory.literal(r),o)),this.parsingContext.emitQuad(e,this.dataFactory.quad(i,this.dataFactory.namedNode(a.RDF+"direction"),this.dataFactory.literal(n),o)),i}}valueToJsonString(e){return s(e)}async unaliasKeyword(e,t,r,i,o){if(Number.isInteger(e))return e;if(!i){const e=this.parsingContext.unaliasedKeywordCacheStack[r];if(e)return e}if(!n.Util.isPotentialKeyword(e)){let r=(o=o||await this.parsingContext.getContext(t)).getContextRaw()[e];r&&"object"==typeof r&&(r=r["@id"]),n.Util.isValidKeyword(r)&&(e=r)}return i?e:this.parsingContext.unaliasedKeywordCacheStack[r]=e}async unaliasKeywordParent(e,t){return await this.unaliasKeyword(t>0&&e[t-1],e,t-1)}async unaliasKeywords(e,t,r,n){const i={};for(const o in e)i[await this.unaliasKeyword(o,t,r+1,!0,n)]=e[o];return i}async isLiteral(e,t){for(let r=t;r>=0;r--){if("@annotation"===await this.unaliasKeyword(e[r],e,r))return!1;if(this.parsingContext.literalStack[r]||this.parsingContext.jsonLiteralStack[r])return!0}return!1}async getDepthOffsetGraph(e,t){for(let r=e-1;r>0;r--)if("@graph"===await this.unaliasKeyword(t[r],t,r)){const n=(await o.EntryHandlerContainer.getContainerHandler(this.parsingContext,t,r)).containers;return o.EntryHandlerContainer.isComplexGraphContainer(n)?-1:e-r-1}return-1}validateReverseSubject(e){if("Literal"===e.termType)throw new n.ErrorCoded(`Found illegal literal in subject position: ${e.value}`,n.ERROR_CODES.INVALID_REVERSE_PROPERTY_VALUE)}getDefaultGraph(){return this.parsingContext.defaultGraph||this.dataFactory.defaultGraph()}async getGraphContainerValue(e,t){let r=this.getDefaultGraph();const{containers:n,depth:i}=await o.EntryHandlerContainer.getContainerHandler(this.parsingContext,e,t);if("@graph"in n){const t=o.EntryHandlerContainer.getContainerGraphIndex(n,i,e),s=this.parsingContext.graphContainerTermStack[i];if(r=s?s[t]:null,!r){let o=null;if("@id"in n){const t=await this.getContainerKey(e[i],e,i);null!==t&&(o=await this.resourceToTerm(await this.parsingContext.getContext(e),t))}o||(o=this.dataFactory.blankNode()),this.parsingContext.graphContainerTermStack[i]||(this.parsingContext.graphContainerTermStack[i]={}),r=this.parsingContext.graphContainerTermStack[i][t]=o}}return r}async getPropertiesDepth(e,t){let r=t;for(let n=t-1;n>0;n--)if("number"!=typeof e[n]){const t=await this.unaliasKeyword(e[n],e,n);if("@reverse"===t)return n;if("@nest"!==t)return r;r=n}return r}async getContainerKey(e,t,r){const n=await this.unaliasKeyword(e,t,r);return"@none"===n?null:n}validateReverseInEmbeddedNode(e,t,r){if(r&&t&&!this.parsingContext.rdfstarReverseInEmbedded)throw new n.ErrorCoded(`Illegal reverse property in embedded node in ${e}`,n.ERROR_CODES.INVALID_EMBEDDED_NODE)}emitQuadChecked(e,t,r,i,o,s,a){let c;if(s?(this.validateReverseSubject(i),c=this.dataFactory.quad(i,r,t,o)):c=this.dataFactory.quad(t,r,i,o),a){if("DefaultGraph"!==c.graph.termType&&(c=this.dataFactory.quad(c.subject,c.predicate,c.object)),this.parsingContext.idStack[e-1])throw new n.ErrorCoded("Illegal multiple properties in an embedded node",n.ERROR_CODES.INVALID_EMBEDDED_NODE);this.parsingContext.idStack[e-1]=[c]}else this.parsingContext.emitQuad(e,c);const l=this.parsingContext.annotationsBuffer[e];if(l){for(const t of l)this.emitAnnotation(e,c,t);delete this.parsingContext.annotationsBuffer[e]}}emitAnnotation(e,t,r){let n;r.reverse?(this.validateReverseSubject(r.object),n=this.dataFactory.quad(r.object,r.predicate,t)):n=this.dataFactory.quad(t,r.predicate,r.object),this.parsingContext.emitQuad(e,n);for(const t of r.nestedAnnotations)this.emitAnnotation(e,n,t)}}a.XSD="http://www.w3.org/2001/XMLSchema#",a.XSD_BOOLEAN=a.XSD+"boolean",a.XSD_INTEGER=a.XSD+"integer",a.XSD_DOUBLE=a.XSD+"double",a.RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",t.Util=a},7986:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContainerHandlerIdentifier=void 0,t.ContainerHandlerIdentifier=class{canCombineWithGraph(){return!0}async handle(e,t,r,n,i,o){let s;if(t.emittedStack[o+1]&&t.idStack[o+1])s=t.idStack[o+1][0];else{const e=null!==await r.getContainerKey(n[o],n,o)?await r.resourceToTerm(await t.getContext(n),n[o]):r.dataFactory.blankNode();if(!e)return void(t.emittedStack[o]=!1);s=e,t.idStack[o+1]=[s]}let a=t.idStack[o];a||(a=t.idStack[o]=[]),a.some((e=>e.equals(s)))||a.push(s),await t.handlePendingContainerFlushBuffers()||(t.emittedStack[o]=!1)}}},1977:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContainerHandlerIndex=void 0;const n=r(2395),i=r(6970),o=r(888);t.ContainerHandlerIndex=class{canCombineWithGraph(){return!0}async handle(e,t,r,s,a,c){if(!Array.isArray(a)){const l="@graph"in e,u=await t.getContext(s),d=s[c-1],h=o.Util.getContextValueIndex(u,d);if(h){if(n.Util.isPotentialKeyword(h))throw new n.ErrorCoded(`Keywords can not be used as @index value, got: ${h}`,n.ERROR_CODES.INVALID_TERM_DEFINITION);if("string"!=typeof h)throw new n.ErrorCoded(`@index values must be strings, got: ${h}`,n.ERROR_CODES.INVALID_TERM_DEFINITION);if("object"!=typeof a){if("@id"!==o.Util.getContextValueType(u,d))throw new n.ErrorCoded(`Property-based index containers require nodes as values or strings with @type: @id, but got: ${a}`,n.ERROR_CODES.INVALID_VALUE_OBJECT);const e=r.resourceToTerm(u,a);e&&(t.idStack[c+1]=[e])}const e=r.createVocabOrBaseTerm(u,h);if(e){const n=await r.valueToTerm(u,h,await r.getContainerKey(s[c],s,c),c,s);if(l){const i=await r.getGraphContainerValue(s,c+1);for(const o of n)t.emitQuad(c,r.dataFactory.quad(i,e,o,r.getDefaultGraph()))}else for(const o of n)await i.EntryHandlerPredicate.handlePredicateObject(t,r,s,c+1,e,o,!1,!1,!1)}}const f=l?2:1;await t.newOnValueJob(s.slice(0,s.length-f),a,c-f,!0),await t.handlePendingContainerFlushBuffers()}t.emittedStack[c]=!1}}},3847:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContainerHandlerLanguage=void 0;const n=r(2395);t.ContainerHandlerLanguage=class{canCombineWithGraph(){return!1}async handle(e,t,r,i,o,s){const a=await r.getContainerKey(i[s],i,s);if(Array.isArray(o))o=o.map((e=>({"@value":e,"@language":a})));else{if("string"!=typeof o)throw new n.ErrorCoded(`Got invalid language map value, got '${JSON.stringify(o)}', but expected string`,n.ERROR_CODES.INVALID_LANGUAGE_MAP_VALUE);o={"@value":o,"@language":a}}await t.newOnValueJob(i.slice(0,i.length-1),o,s-1,!0),t.emittedStack[s]=!1}}},7229:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContainerHandlerType=void 0;const n=r(6970),i=r(888);t.ContainerHandlerType=class{canCombineWithGraph(){return!1}async handle(e,t,r,o,s,a){if(!Array.isArray(s)){if("string"==typeof s){const e=await t.getContext(o),n="@vocab"===i.Util.getContextValueType(e,o[a-1])?await r.createVocabOrBaseTerm(e,s):await r.resourceToTerm(e,s);if(n){const e={"@id":"NamedNode"===n.termType?n.value:s};await t.newOnValueJob(o.slice(0,o.length-1),e,a-1,!0),t.idStack[a+1]=[n]}}else{const e=!!t.idStack[a+1];e||delete t.idStack[a],await t.newOnValueJob(o.slice(0,o.length-1),s,a-1,!0),e||(t.idStack[a+1]=t.idStack[a])}const e=await r.getContainerKey(o[a],o,a),c=null!==e?r.createVocabOrBaseTerm(await t.getContext(o),e):null;c&&await n.EntryHandlerPredicate.handlePredicateObject(t,r,o,a+1,r.rdfType,c,!1,!1,!1),await t.handlePendingContainerFlushBuffers()}t.emittedStack[a]=!1}}},9693:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerArrayValue=void 0;const n=r(888),i=r(2395);t.EntryHandlerArrayValue=class{isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,n,i){return this.test(e,t,null,r,n)}async test(e,t,r,n,i){return"number"==typeof n[i]}async handle(e,t,r,i,o,s){let a=await t.unaliasKeywordParent(i,s);if("@list"===a){let r=null,n=0;for(let e=s-2;e>0;e--){const t=i[e];if("string"==typeof t||"number"==typeof t){n=e,r=t;break}}if(null!==r){const a=await t.valueToTerm(await e.getContext(i),r,o,s,i);for(const r of a)await this.handleListElement(e,t,r,o,s,i.slice(0,n),n);0===a.length&&await this.handleListElement(e,t,null,o,s,i.slice(0,n),n)}}else if("@set"===a)await e.newOnValueJob(i.slice(0,-2),o,s-2,!1);else if(void 0!==a&&"@type"!==a){for(let e=s-1;e>0;e--)if("number"!=typeof i[e]){a=await t.unaliasKeyword(i[e],i,e);break}const r=await e.getContext(i.slice(0,-1));if("@list"in n.Util.getContextValueContainer(r,a)){e.emittedStack[s+1]=!0;const r=await t.valueToTerm(await e.getContext(i),a,o,s,i);for(const n of r)await this.handleListElement(e,t,n,o,s,i.slice(0,-1),s-1);0===r.length&&await this.handleListElement(e,t,null,o,s,i.slice(0,-1),s-1)}else e.shiftStack(s,1),await e.newOnValueJob(i.slice(0,-1),o,s-1,!1),e.contextTree.removeContext(i.slice(0,-1))}}async handleListElement(e,t,r,n,o,s,a){let c=e.listPointerStack[o];if(null!==n&&null!==(await t.unaliasKeywords(n,s,o))["@value"]){if(c&&c.value){const r=t.dataFactory.blankNode();e.emitQuad(o,t.dataFactory.quad(c.value,t.rdfRest,r,t.getDefaultGraph())),c.value=r}else{const e=t.dataFactory.blankNode();c={value:e,listRootDepth:a,listId:e}}r&&e.emitQuad(o,t.dataFactory.quad(c.value,t.rdfFirst,r,t.getDefaultGraph()))}else c||(c={listRootDepth:a,listId:t.rdfNil});e.listPointerStack[o]=c,e.rdfstar&&e.annotationsBuffer[o]&&e.emitError(new i.ErrorCoded("Found an illegal annotation inside a list",i.ERROR_CODES.INVALID_ANNOTATION))}}},4860:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerContainer=void 0;const n=r(7986),i=r(1977),o=r(3847),s=r(7229),a=r(888);class c{static isSimpleGraphContainer(e){return"@graph"in e&&("@set"in e&&2===Object.keys(e).length||1===Object.keys(e).length)}static isComplexGraphContainer(e){return"@graph"in e&&("@set"in e&&Object.keys(e).length>2||!("@set"in e)&&Object.keys(e).length>1)}static getContainerGraphIndex(e,t,r){let n=c.isSimpleGraphContainer(e),i="";for(let e=t;e=0;e--)if("number"!=typeof t[e]){const r=a.Util.getContextValue(o,"@container",t[e],!1);if(r&&c.isSimpleGraphContainer(r))return{containers:r,depth:e+1,fallback:!1};const s=a.Util.getContextValue(o,"@container",t[e-1],!1);if(s){const t="@graph"in s;for(const r in c.CONTAINER_HANDLERS)if(s[r])return t?c.CONTAINER_HANDLERS[r].canCombineWithGraph()?{containers:s,depth:e,fallback:!1}:n:i?n:{containers:s,depth:e,fallback:!1};return n}if(i)return n;i=!0}return n}static async isBufferableContainerHandler(e,t,r){const n=await c.getContainerHandler(e,t,r);return!n.fallback&&!("@graph"in n.containers)}isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,n,i){return!!await this.test(e,t,null,r,n)}async test(e,t,r,n,i){const o=a.Util.getContextValueContainer(await e.getContext(n,2),n[i-1]);for(const e in c.CONTAINER_HANDLERS)if(o[e])return{containers:o,handler:c.CONTAINER_HANDLERS[e]};return null}async handle(e,t,r,n,i,o,s){return s.handler.handle(s.containers,e,t,n,i,o)}}c.CONTAINER_HANDLERS={"@id":new n.ContainerHandlerIdentifier,"@index":new i.ContainerHandlerIndex,"@language":new o.ContainerHandlerLanguage,"@type":new s.ContainerHandlerType},t.EntryHandlerContainer=c},2386:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerInvalidFallback=void 0,t.EntryHandlerInvalidFallback=class{isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,n,i){return!1}async test(e,t,r,n,i){return!0}async handle(e,t,r,n,i,o){e.emittedStack[o]=!1}}},6970:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerPredicate=void 0;const n=r(2395),i=r(888);class o{static async handlePredicateObject(e,t,r,i,o,s,a,c,l){const u=await t.getPropertiesDepth(r,i),d=await t.getDepthOffsetGraph(i,r),h=i-d,f=e.idStack[u];if(f&&!l)for(const n of f)if(d>=0){const r=e.idStack[h-1];if(r)for(const e of r)t.emitQuadChecked(i,n,o,s,e,a,c);else a?(t.validateReverseSubject(s),e.getUnidentifiedGraphBufferSafe(h-1).push({subject:s,predicate:o,object:n,isEmbedded:c})):e.getUnidentifiedGraphBufferSafe(h-1).push({subject:n,predicate:o,object:s,isEmbedded:c})}else{const e=await t.getGraphContainerValue(r,u);t.emitQuadChecked(i,n,o,s,e,a,c)}else if(a&&t.validateReverseSubject(s),l){if(e.rdfstar){e.idStack[i]&&e.emitError(new n.ErrorCoded(`Found an illegal @id inside an annotation: ${e.idStack[i][0].value}`,n.ERROR_CODES.INVALID_ANNOTATION));for(let o=0;o=0;e--){const t=c[e];t.depth>u&&(l.nestedAnnotations.push(t),c.splice(e,1))}}}else e.getUnidentifiedValueBufferSafe(u).push({predicate:o,object:s,reverse:a,isEmbedded:c})}isPropertyHandler(){return!0}isStackProcessor(){return!0}async validate(e,t,r,n,o){const s=r[n];if(s){const o=await e.getContext(r);if(!e.jsonLiteralStack[n]&&await t.predicateToTerm(o,r[n]))return"@json"===i.Util.getContextValueType(o,s)&&(e.jsonLiteralStack[n+1]=!0),!0}return!1}async test(e,t,r,n,i){return n[i]}async handle(e,t,r,s,a,c,l){const u=s[c],d=await e.getContext(s),h=await t.predicateToTerm(d,r);if(h){const l=await t.valueToTerm(d,r,a,c,s);if(l.length)for(let f of l){let l=await t.unaliasKeywordParent(s,c);const p=i.Util.isPropertyReverse(d,u,l);let g=0;for(;"@reverse"===l||"number"==typeof l;)"number"==typeof l?g++:c--,l=await t.unaliasKeywordParent(s,c-g);const y=i.Util.isPropertyInEmbeddedNode(l);t.validateReverseInEmbeddedNode(r,p,y);const m=i.Util.isPropertyInAnnotationObject(l);if(a){const o="@list"in i.Util.getContextValueContainer(d,r);if(o||a["@list"]){if((o&&!Array.isArray(a)&&!a["@list"]||a["@list"]&&!Array.isArray(a["@list"]))&&f!==t.rdfNil){const r=t.dataFactory.blankNode();e.emitQuad(c,t.dataFactory.quad(r,t.rdfRest,t.rdfNil,t.getDefaultGraph())),e.emitQuad(c,t.dataFactory.quad(r,t.rdfFirst,f,t.getDefaultGraph())),f=r}if(p&&!e.allowSubjectList)throw new n.ErrorCoded(`Found illegal list value in subject position at ${r}`,n.ERROR_CODES.INVALID_REVERSE_PROPERTY_VALUE)}}await o.handlePredicateObject(e,t,s,c,h,f,p,y,m)}}}}t.EntryHandlerPredicate=o},1548:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeyword=void 0,t.EntryHandlerKeyword=class{constructor(e){this.keyword=e}isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,n,i){return!1}async test(e,t,r,n,i){return r===this.keyword}}},6105:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordAnnotation=void 0;const n=r(1548),i=r(2395);class o extends n.EntryHandlerKeyword{constructor(){super("@annotation")}async handle(e,t,r,n,o,s){("string"==typeof o||"object"==typeof o&&o["@value"])&&e.emitError(new i.ErrorCoded(`Found illegal annotation value: ${JSON.stringify(o)}`,i.ERROR_CODES.INVALID_ANNOTATION))}}t.EntryHandlerKeywordAnnotation=o},3809:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordContext=void 0;const n=r(2395),i=r(1548);class o extends i.EntryHandlerKeyword{constructor(){super("@context")}isStackProcessor(){return!1}async handle(e,t,r,i,o,s){e.streamingProfile&&(e.processingStack[s]||e.processingType[s]||void 0!==e.idStack[s])&&e.emitError(new n.ErrorCoded("Found an out-of-order context, while streaming is enabled.(disable `streamingProfile`)",n.ERROR_CODES.INVALID_STREAMING_KEY_ORDER));const a=e.getContext(i),c=e.parseContext(o,(await a).getContextRaw());e.contextTree.setContext(i.slice(0,-1),c),e.emitContext(o),await e.validateContext(await c)}}t.EntryHandlerKeywordContext=o},5998:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordGraph=void 0;const n=r(1548);class i extends n.EntryHandlerKeyword{constructor(){super("@graph")}async handle(e,t,r,n,i,o){e.graphStack[o+1]=!0}}t.EntryHandlerKeywordGraph=i},5517:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordId=void 0;const n=r(2395),i=r(1548);class o extends i.EntryHandlerKeyword{constructor(){super("@id")}isStackProcessor(){return!1}async handle(e,t,r,i,o,s){if("string"!=typeof o){if(e.rdfstar&&"object"==typeof o){const t=Object.keys(o);1===t.length&&"@id"===t[0]&&e.emitError(new n.ErrorCoded(`Invalid embedded node without property with @id ${o["@id"]}`,n.ERROR_CODES.INVALID_EMBEDDED_NODE))}else e.emitError(new n.ErrorCoded(`Found illegal @id '${o}'`,n.ERROR_CODES.INVALID_ID_VALUE));return}const a=await t.getPropertiesDepth(i,s);if(void 0!==e.idStack[a]&&(e.idStack[a][0].listHead?e.emitError(new n.ErrorCoded(`Found illegal neighbouring entries next to @list for key: '${i[s-1]}'`,n.ERROR_CODES.INVALID_SET_OR_LIST_OBJECT)):e.emitError(new n.ErrorCoded(`Found duplicate @ids '${e.idStack[a][0].value}' and '${o}'`,n.ERROR_CODES.COLLIDING_KEYWORDS))),e.rdfstar&&e.annotationsBuffer[s])for(const t of e.annotationsBuffer[s])t.depth===s&&e.emitError(new n.ErrorCoded(`Found an illegal @id inside an annotation: ${o}`,n.ERROR_CODES.INVALID_ANNOTATION));e.idStack[a]=t.nullableTermToArray(await t.resourceToTerm(await e.getContext(i),o))}}t.EntryHandlerKeywordId=o},736:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordIncluded=void 0;const n=r(2395),i=r(1548);class o extends i.EntryHandlerKeyword{constructor(){super("@included")}async handle(e,t,r,i,o,s){"object"!=typeof o&&e.emitError(new n.ErrorCoded(`Found illegal @included '${o}'`,n.ERROR_CODES.INVALID_INCLUDED_VALUE));const a=await t.unaliasKeywords(o,i,s,await e.getContext(i));"@value"in a&&e.emitError(new n.ErrorCoded(`Found an illegal @included @value node '${JSON.stringify(o)}'`,n.ERROR_CODES.INVALID_INCLUDED_VALUE)),"@list"in a&&e.emitError(new n.ErrorCoded(`Found an illegal @included @list node '${JSON.stringify(o)}'`,n.ERROR_CODES.INVALID_INCLUDED_VALUE)),e.emittedStack[s]=!1}}t.EntryHandlerKeywordIncluded=o},4910:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordNest=void 0;const n=r(2395),i=r(1548);class o extends i.EntryHandlerKeyword{constructor(){super("@nest")}async handle(e,t,r,i,o,s){"object"!=typeof o&&e.emitError(new n.ErrorCoded(`Found invalid @nest entry for '${r}': '${o}'`,n.ERROR_CODES.INVALID_NEST_VALUE)),"@value"in await t.unaliasKeywords(o,i,s,await e.getContext(i))&&e.emitError(new n.ErrorCoded(`Found an invalid @value node for '${r}'`,n.ERROR_CODES.INVALID_NEST_VALUE)),e.emittedStack[s]=!1}}t.EntryHandlerKeywordNest=o},2036:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordType=void 0;const n=r(2395),i=r(888),o=r(6970),s=r(1548);class a extends s.EntryHandlerKeyword{constructor(){super("@type")}isStackProcessor(){return!1}async handle(e,t,r,s,a,c){const l=s[c],u=await e.getContext(s),d=t.rdfType,h=await t.unaliasKeywordParent(s,c),f=i.Util.isPropertyReverse(u,l,h),p=i.Util.isPropertyInEmbeddedNode(h);t.validateReverseInEmbeddedNode(r,f,p);const g=i.Util.isPropertyInAnnotationObject(h),y=Array.isArray(a)?a:[a];for(const r of y){"string"!=typeof r&&e.emitError(new n.ErrorCoded(`Found illegal @type '${r}'`,n.ERROR_CODES.INVALID_TYPE_VALUE));const i=t.createVocabOrBaseTerm(u,r);i&&await o.EntryHandlerPredicate.handlePredicateObject(e,t,s,c,d,i,f,p,g)}let m=Promise.resolve(u),v=!1;for(const t of y.sort()){const r=i.Util.getContextValue(u,"@context",t,null);r&&(v=!0,m=m.then((t=>e.parseContext(r,t.getContextRaw()))))}!e.streamingProfile||!v&&e.streamingProfileAllowOutOfOrderPlainType||!e.processingStack[c]&&!e.idStack[c]||e.emitError(new n.ErrorCoded("Found an out-of-order type-scoped context, while streaming is enabled.(disable `streamingProfile`)",n.ERROR_CODES.INVALID_STREAMING_KEY_ORDER)),v&&(m=m.then((e=>!0!==e.getContextRaw()["@propagate"]?new n.JsonLdContextNormalized(Object.assign(Object.assign({},e.getContextRaw()),{"@propagate":!1,"@__propagateFallback":u.getContextRaw()})):e)),e.contextTree.setContext(s.slice(0,s.length-1),m)),e.processingType[c]=!0}}t.EntryHandlerKeywordType=a},6454:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordUnknownFallback=void 0;const n=r(2395);class i{isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,i,o){const s=await t.unaliasKeyword(r[i],r,i);return!(!n.Util.isPotentialKeyword(s)||!o&&"@list"===s)}async test(e,t,r,i,o){return n.Util.isPotentialKeyword(r)}async handle(e,t,r,o,s,a){const c=i.VALID_KEYWORDS_TYPES[r];void 0!==c?c&&typeof s!==c.type&&e.emitError(new n.ErrorCoded(`Invalid value type for '${r}' with value '${s}'`,c.errorCode)):e.strictValues&&e.emitError(new Error(`Unknown keyword '${r}' with value '${s}'`)),e.emittedStack[a]=!1}}i.VALID_KEYWORDS_TYPES={"@index":{type:"string",errorCode:n.ERROR_CODES.INVALID_INDEX_VALUE},"@list":null,"@reverse":{type:"object",errorCode:n.ERROR_CODES.INVALID_REVERSE_VALUE},"@set":null,"@value":null},t.EntryHandlerKeywordUnknownFallback=i},3283:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordValue=void 0;const n=r(1548);class i extends n.EntryHandlerKeyword{constructor(){super("@value")}async validate(e,t,r,n,i){const o=r[n];return o&&!e.literalStack[n]&&await this.test(e,t,o,r,n)&&(e.literalStack[n]=!0),super.validate(e,t,r,n,i)}async test(e,t,r,n,i){return"@value"===await t.unaliasKeyword(n[i],n.slice(0,n.length-1),i-1,!0)}async handle(e,t,r,n,i,o){e.literalStack[o]=!0,delete e.unidentifiedValuesBuffer[o],delete e.unidentifiedGraphsBuffer[o],e.emittedStack[o]=!1}}t.EntryHandlerKeywordValue=i},2194:function(e,t,r){"use strict";const{SymbolDispose:n}=r(2057),{AbortError:i,codes:o}=r(54),{isNodeStream:s,isWebStream:a,kControllerErrorFunction:c}=r(9232),l=r(3789),{ERR_INVALID_ARG_TYPE:u}=o;let d;e.exports.addAbortSignal=function(t,r){if((e=>{if("object"!=typeof e||!("aborted"in e))throw new u("signal","AbortSignal",e)})(t),!s(r)&&!a(r))throw new u("stream",["ReadableStream","WritableStream","Stream"],r);return e.exports.addAbortSignalNoValidate(t,r)},e.exports.addAbortSignalNoValidate=function(e,t){if("object"!=typeof e||!("aborted"in e))return t;const o=s(t)?()=>{t.destroy(new i(void 0,{cause:e.reason}))}:()=>{t[c](new i(void 0,{cause:e.reason}))};if(e.aborted)o();else{d=d||r(6745).addAbortListener;const i=d(e,o);l(t,i[n])}return t}},6442:function(e,t,r){"use strict";const{StringPrototypeSlice:n,SymbolIterator:i,TypedArrayPrototypeSet:o,Uint8Array:s}=r(2057),{Buffer:a}=r(8287),{inspect:c}=r(6745);e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(e){const t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}unshift(e){const t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}shift(){if(0===this.length)return;const e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(0===this.length)return"";let t=this.head,r=""+t.data;for(;null!==(t=t.next);)r+=e+t.data;return r}concat(e){if(0===this.length)return a.alloc(0);const t=a.allocUnsafe(e>>>0);let r=this.head,n=0;for(;r;)o(t,r.data,n),n+=r.data.length,r=r.next;return t}consume(e,t){const r=this.head.data;if(eo.length)){e===o.length?(t+=o,++i,r.next?this.head=r.next:this.head=this.tail=null):(t+=n(o,0,e),this.head=r,r.data=n(o,e));break}t+=o,e-=o.length,++i}while(null!==(r=r.next));return this.length-=i,t}_getBuffer(e){const t=a.allocUnsafe(e),r=e;let n=this.head,i=0;do{const a=n.data;if(!(e>a.length)){e===a.length?(o(t,a,r-e),++i,n.next?this.head=n.next:this.head=this.tail=null):(o(t,new s(a.buffer,a.byteOffset,e),r-e),this.head=n,n.data=a.slice(e));break}o(t,a,r-e),e-=a.length,++i}while(null!==(n=n.next));return this.length-=i,t}[Symbol.for("nodejs.util.inspect.custom")](e,t){return c(this,{...t,depth:0,customInspect:!1})}}},769:function(e,t,r){"use strict";const{pipeline:n}=r(5783),i=r(399),{destroyer:o}=r(2295),{isNodeStream:s,isReadable:a,isWritable:c,isWebStream:l,isTransformStream:u,isWritableStream:d,isReadableStream:h}=r(9232),{AbortError:f,codes:{ERR_INVALID_ARG_VALUE:p,ERR_MISSING_ARGS:g}}=r(54),y=r(3789);e.exports=function(...e){if(0===e.length)throw new g("streams");if(1===e.length)return i.from(e[0]);const t=[...e];if("function"==typeof e[0]&&(e[0]=i.from(e[0])),"function"==typeof e[e.length-1]){const t=e.length-1;e[t]=i.from(e[t])}for(let r=0;r0&&!(c(e[r])||d(e[r])||u(e[r])))throw new p(`streams[${r}]`,t[r],"must be writable")}let r,m,v,b,w;const _=e[0],S=n(e,(function(e){const t=b;b=null,t?t(e):e?w.destroy(e):A||E||w.destroy()})),E=!!(c(_)||d(_)||u(_)),A=!!(a(S)||h(S)||u(S));if(w=new i({writableObjectMode:!(null==_||!_.writableObjectMode),readableObjectMode:!(null==S||!S.readableObjectMode),writable:E,readable:A}),E){if(s(_))w._write=function(e,t,n){_.write(e,t)?n():r=n},w._final=function(e){_.end(),m=e},_.on("drain",(function(){if(r){const e=r;r=null,e()}}));else if(l(_)){const e=(u(_)?_.writable:_).getWriter();w._write=async function(t,r,n){try{await e.ready,e.write(t).catch((()=>{})),n()}catch(e){n(e)}},w._final=async function(t){try{await e.ready,e.close().catch((()=>{})),m=t}catch(e){t(e)}}}const e=u(S)?S.readable:S;y(e,(()=>{if(m){const e=m;m=null,e()}}))}if(A)if(s(S))S.on("readable",(function(){if(v){const e=v;v=null,e()}})),S.on("end",(function(){w.push(null)})),w._read=function(){for(;;){const e=S.read();if(null===e)return void(v=w._read);if(!w.push(e))return}};else if(l(S)){const e=(u(S)?S.readable:S).getReader();w._read=async function(){for(;;)try{const{value:t,done:r}=await e.read();if(!w.push(t))return;if(r)return void w.push(null)}catch{return}}}return w._destroy=function(e,t){e||null===b||(e=new f),v=null,r=null,m=null,null===b?t(e):(b=t,s(S)&&o(S,e))},w}},2295:function(e,t,r){"use strict";const n=r(5606),{aggregateTwoErrors:i,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:s}=r(54),{Symbol:a}=r(2057),{kIsDestroyed:c,isDestroyed:l,isFinished:u,isServerRequest:d}=r(9232),h=a("kDestroy"),f=a("kConstruct");function p(e,t,r){e&&(e.stack,t&&!t.errored&&(t.errored=e),r&&!r.errored&&(r.errored=e))}function g(e,t,r){let i=!1;function o(t){if(i)return;i=!0;const o=e._readableState,s=e._writableState;p(t,s,o),s&&(s.closed=!0),o&&(o.closed=!0),"function"==typeof r&&r(t),t?n.nextTick(y,e,t):n.nextTick(m,e)}try{e._destroy(t||null,o)}catch(t){o(t)}}function y(e,t){v(e,t),m(e)}function m(e){const t=e._readableState,r=e._writableState;r&&(r.closeEmitted=!0),t&&(t.closeEmitted=!0),(null!=r&&r.emitClose||null!=t&&t.emitClose)&&e.emit("close")}function v(e,t){const r=e._readableState,n=e._writableState;null!=n&&n.errorEmitted||null!=r&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),e.emit("error",t))}function b(e,t,r){const i=e._readableState,o=e._writableState;if(null!=o&&o.destroyed||null!=i&&i.destroyed)return this;null!=i&&i.autoDestroy||null!=o&&o.autoDestroy?e.destroy(t):t&&(t.stack,o&&!o.errored&&(o.errored=t),i&&!i.errored&&(i.errored=t),r?n.nextTick(v,e,t):v(e,t))}function w(e){let t=!1;function r(r){if(t)return void b(e,null!=r?r:new o);t=!0;const i=e._readableState,s=e._writableState,a=s||i;i&&(i.constructed=!0),s&&(s.constructed=!0),a.destroyed?e.emit(h,r):r?b(e,r,!0):n.nextTick(_,e)}try{e._construct((e=>{n.nextTick(r,e)}))}catch(e){n.nextTick(r,e)}}function _(e){e.emit(f)}function S(e){return(null==e?void 0:e.setHeader)&&"function"==typeof e.abort}function E(e){e.emit("close")}function A(e,t){e.emit("error",t),n.nextTick(E,e)}e.exports={construct:function(e,t){if("function"!=typeof e._construct)return;const r=e._readableState,i=e._writableState;r&&(r.constructed=!1),i&&(i.constructed=!1),e.once(f,t),e.listenerCount(f)>1||n.nextTick(w,e)},destroyer:function(e,t){e&&!l(e)&&(t||u(e)||(t=new s),d(e)?(e.socket=null,e.destroy(t)):S(e)?e.abort():S(e.req)?e.req.abort():"function"==typeof e.destroy?e.destroy(t):"function"==typeof e.close?e.close():t?n.nextTick(A,e,t):n.nextTick(E,e),e.destroyed||(e[c]=!0))},destroy:function(e,t){const r=this._readableState,n=this._writableState,o=n||r;return null!=n&&n.destroyed||null!=r&&r.destroyed?("function"==typeof t&&t(),this):(p(e,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),o.constructed?g(this,e,t):this.once(h,(function(r){g(this,i(r,e),t)})),this)},undestroy:function(){const e=this._readableState,t=this._writableState;e&&(e.constructed=!0,e.closed=!1,e.closeEmitted=!1,e.destroyed=!1,e.errored=null,e.errorEmitted=!1,e.reading=!1,e.ended=!1===e.readable,e.endEmitted=!1===e.readable),t&&(t.constructed=!0,t.destroyed=!1,t.closed=!1,t.closeEmitted=!1,t.errored=null,t.errorEmitted=!1,t.finalCalled=!1,t.prefinished=!1,t.ended=!1===t.writable,t.ending=!1===t.writable,t.finished=!1===t.writable)},errorOrDestroy:b}},399:function(e,t,r){"use strict";const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:i,ObjectKeys:o,ObjectSetPrototypeOf:s}=r(2057);e.exports=l;const a=r(5277),c=r(4461);s(l.prototype,a.prototype),s(l,a);{const e=o(c.prototype);for(let t=0;t{d=!1,e&&v(t,e),h(e)})),l._write=function(e,t,i){r.write(e,t)?i():n=i},l._final=function(e){r.end(),i=e},r.on("drain",(function(){if(n){const e=n;n=null,e()}})),r.on("finish",(function(){if(i){const e=i;i=null,e()}}))),u&&(p(t,(e=>{u=!1,e&&v(t,e),h(e)})),t.on("readable",(function(){if(a){const e=a;a=null,e()}})),t.on("end",(function(){l.push(null)})),l._read=function(){for(;;){const e=t.read();if(null===e)return void(a=l._read);if(!l.push(e))return}}),l._destroy=function(e,o){e||null===c||(e=new g),a=null,n=null,i=null,null===c?o(e):(c=o,v(r,e),v(t,e))},l}e.exports=function e(t,r){if(d(t))return t;if(l(t))return P({readable:t});if(u(t))return P({writable:t});if(c(t))return P({writable:!1,readable:!1});if(h(t))return P({readable:w.fromWeb(t)});if(f(t))return P({writable:_.fromWeb(t)});if("function"==typeof t){const{value:e,write:i,final:o,destroy:s}=function(e){let{promise:t,resolve:r}=S();const i=new I,o=i.signal;return{value:e(async function*(){for(;;){const e=t;t=null;const{chunk:i,done:s,cb:a}=await e;if(n.nextTick(a),s)return;if(o.aborted)throw new g(void 0,{cause:o.reason});({promise:t,resolve:r}=S()),yield i}}(),{signal:o}),write(e,t,n){const i=r;r=null,i({chunk:e,done:!1,cb:n})},final(e){const t=r;r=null,t({done:!0,cb:e})},destroy(e,t){i.abort(),t(e)}}}(t);if(a(e))return E(x,e,{objectMode:!0,write:i,final:o,destroy:s});const c=null==e?void 0:e.then;if("function"==typeof c){let t;const r=T(c,e,(e=>{if(null!=e)throw new m("nully","body",e)}),(e=>{v(t,e)}));return t=new x({objectMode:!0,readable:!1,write:i,final(e){o((async()=>{try{await r,n.nextTick(e,null)}catch(t){n.nextTick(e,t)}}))},destroy:s})}throw new m("Iterable, AsyncIterable or AsyncFunction",r,e)}if(R(t))return e(t.arrayBuffer());if(a(t))return E(x,t,{objectMode:!0,writable:!1});if(h(null==t?void 0:t.readable)&&f(null==t?void 0:t.writable))return x.fromWeb(t);if("object"==typeof(null==t?void 0:t.writable)||"object"==typeof(null==t?void 0:t.readable))return P({readable:null!=t&&t.readable?l(null==t?void 0:t.readable)?null==t?void 0:t.readable:e(t.readable):void 0,writable:null!=t&&t.writable?u(null==t?void 0:t.writable)?null==t?void 0:t.writable:e(t.writable):void 0});const i=null==t?void 0:t.then;if("function"==typeof i){let e;return T(i,t,(t=>{null!=t&&e.push(t),e.push(null)}),(t=>{v(e,t)})),e=new x({objectMode:!0,writable:!1,read(){}})}throw new y(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],t)}},3789:function(e,t,r){const n=r(5606),{AbortError:i,codes:o}=r(54),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_PREMATURE_CLOSE:a}=o,{kEmptyObject:c,once:l}=r(6745),{validateAbortSignal:u,validateFunction:d,validateObject:h,validateBoolean:f}=r(5432),{Promise:p,PromisePrototypeThen:g,SymbolDispose:y}=r(2057),{isClosed:m,isReadable:v,isReadableNodeStream:b,isReadableStream:w,isReadableFinished:_,isReadableErrored:S,isWritable:E,isWritableNodeStream:A,isWritableStream:R,isWritableFinished:I,isWritableErrored:T,isNodeStream:x,willEmitClose:P,kIsClosedPromise:C}=r(9232);let k;const O=()=>{};function F(e,t,o){var f,p;if(2===arguments.length?(o=t,t=c):null==t?t=c:h(t,"options"),d(o,"callback"),u(t.signal,"options.signal"),o=l(o),w(e)||R(e))return function(e,t,o){let s=!1,a=O;if(t.signal)if(a=()=>{s=!0,o.call(e,new i(void 0,{cause:t.signal.reason}))},t.signal.aborted)n.nextTick(a);else{k=k||r(6745).addAbortListener;const n=k(t.signal,a),i=o;o=l(((...t)=>{n[y](),i.apply(e,t)}))}const c=(...t)=>{s||n.nextTick((()=>o.apply(e,t)))};return g(e[C].promise,c,c),O}(e,t,o);if(!x(e))throw new s("stream",["ReadableStream","WritableStream","Stream"],e);const F=null!==(f=t.readable)&&void 0!==f?f:b(e),N=null!==(p=t.writable)&&void 0!==p?p:A(e),D=e._writableState,L=e._readableState,U=()=>{e.writable||B()};let j=P(e)&&b(e)===F&&A(e)===N,M=I(e,!1);const B=()=>{M=!0,e.destroyed&&(j=!1),(!j||e.readable&&!F)&&(F&&!H||o.call(e))};let H=_(e,!1);const W=()=>{H=!0,e.destroyed&&(j=!1),(!j||e.writable&&!N)&&(N&&!M||o.call(e))},$=t=>{o.call(e,t)};let V=m(e);const K=()=>{V=!0;const t=T(e)||S(e);return t&&"boolean"!=typeof t?o.call(e,t):F&&!H&&b(e,!0)&&!_(e,!1)?o.call(e,new a):!N||M||I(e,!1)?void o.call(e):o.call(e,new a)},J=()=>{V=!0;const t=T(e)||S(e);if(t&&"boolean"!=typeof t)return o.call(e,t);o.call(e)},G=()=>{e.req.on("finish",B)};!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?N&&!D&&(e.on("end",U),e.on("close",U)):(e.on("complete",B),j||e.on("abort",K),e.req?G():e.on("request",G)),j||"boolean"!=typeof e.aborted||e.on("aborted",K),e.on("end",W),e.on("finish",B),!1!==t.error&&e.on("error",$),e.on("close",K),V?n.nextTick(K):null!=D&&D.errorEmitted||null!=L&&L.errorEmitted?j||n.nextTick(J):(F||j&&!v(e)||!M&&!1!==E(e))&&(N||j&&!E(e)||!H&&!1!==v(e))?L&&e.req&&e.aborted&&n.nextTick(J):n.nextTick(J);const q=()=>{o=O,e.removeListener("aborted",K),e.removeListener("complete",B),e.removeListener("abort",K),e.removeListener("request",G),e.req&&e.req.removeListener("finish",B),e.removeListener("end",U),e.removeListener("close",U),e.removeListener("finish",B),e.removeListener("end",W),e.removeListener("error",$),e.removeListener("close",K)};if(t.signal&&!V){const s=()=>{const r=o;q(),r.call(e,new i(void 0,{cause:t.signal.reason}))};if(t.signal.aborted)n.nextTick(s);else{k=k||r(6745).addAbortListener;const n=k(t.signal,s),i=o;o=l(((...t)=>{n[y](),i.apply(e,t)}))}}return q}e.exports=F,e.exports.finished=function(e,t){var r;let n=!1;return null===t&&(t=c),null!==(r=t)&&void 0!==r&&r.cleanup&&(f(t.cleanup,"cleanup"),n=t.cleanup),new p(((r,i)=>{const o=F(e,t,(e=>{n&&o(),e?i(e):r()}))}))}},4181:function(e,t,r){"use strict";const n=r(5606),{PromisePrototypeThen:i,SymbolAsyncIterator:o,SymbolIterator:s}=r(2057),{Buffer:a}=r(8287),{ERR_INVALID_ARG_TYPE:c,ERR_STREAM_NULL_VALUES:l}=r(54).codes;e.exports=function(e,t,r){let u,d;if("string"==typeof t||t instanceof a)return new e({objectMode:!0,...r,read(){this.push(t),this.push(null)}});if(t&&t[o])d=!0,u=t[o]();else{if(!t||!t[s])throw new c("iterable",["Iterable"],t);d=!1,u=t[s]()}const h=new e({objectMode:!0,highWaterMark:1,...r});let f=!1;return h._read=function(){f||(f=!0,async function(){for(;;){try{const{value:e,done:t}=d?await u.next():u.next();if(t)h.push(null);else{const t=e&&"function"==typeof e.then?await e:e;if(null===t)throw f=!1,new l;if(h.push(t))continue;f=!1}}catch(e){h.destroy(e)}break}}())},h._destroy=function(e,t){i(async function(e){const t=null!=e,r="function"==typeof u.throw;if(t&&r){const{value:t,done:r}=await u.throw(e);if(await t,r)return}if("function"==typeof u.return){const{value:e}=await u.return();await e}}(e),(()=>n.nextTick(t,e)),(r=>n.nextTick(t,r||e)))},h}},9526:function(e,t,r){"use strict";const{ArrayIsArray:n,ObjectSetPrototypeOf:i}=r(2057),{EventEmitter:o}=r(7007);function s(e){o.call(this,e)}function a(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?n(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}i(s.prototype,o.prototype),i(s,o),s.prototype.pipe=function(e,t){const r=this;function n(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function i(){r.readable&&r.resume&&r.resume()}r.on("data",n),e.on("drain",i),e._isStdio||t&&!1===t.end||(r.on("end",c),r.on("close",l));let s=!1;function c(){s||(s=!0,e.end())}function l(){s||(s=!0,"function"==typeof e.destroy&&e.destroy())}function u(e){d(),0===o.listenerCount(this,"error")&&this.emit("error",e)}function d(){r.removeListener("data",n),e.removeListener("drain",i),r.removeListener("end",c),r.removeListener("close",l),r.removeListener("error",u),e.removeListener("error",u),r.removeListener("end",d),r.removeListener("close",d),e.removeListener("close",d)}return a(r,"error",u),a(e,"error",u),r.on("end",d),r.on("close",d),e.on("close",d),e.emit("pipe",r),e},e.exports={Stream:s,prependListener:a}},2892:function(e,t,r){"use strict";const n=globalThis.AbortController||r(5568).AbortController,{codes:{ERR_INVALID_ARG_VALUE:i,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:s,ERR_OUT_OF_RANGE:a},AbortError:c}=r(54),{validateAbortSignal:l,validateInteger:u,validateObject:d}=r(5432),h=r(2057).Symbol("kWeak"),f=r(2057).Symbol("kResistStopPropagation"),{finished:p}=r(3789),g=r(769),{addAbortSignalNoValidate:y}=r(2194),{isWritable:m,isNodeStream:v}=r(9232),{deprecate:b}=r(6745),{ArrayPrototypePush:w,Boolean:_,MathFloor:S,Number:E,NumberIsNaN:A,Promise:R,PromiseReject:I,PromiseResolve:T,PromisePrototypeThen:x,Symbol:P}=r(2057),C=P("kEmpty"),k=P("kEof");function O(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal");let n=1;null!=(null==t?void 0:t.concurrency)&&(n=S(t.concurrency));let i=n-1;return null!=(null==t?void 0:t.highWaterMark)&&(i=S(t.highWaterMark)),u(n,"options.concurrency",1),u(i,"options.highWaterMark",0),i+=n,async function*(){const o=r(6745).AbortSignalAny([null==t?void 0:t.signal].filter(_)),s=this,a=[],l={signal:o};let u,d,h=!1,f=0;function p(){h=!0,g()}function g(){f-=1,y()}function y(){d&&!h&&f=i||f>=n)&&await new R((e=>{d=e}))}a.push(k)}catch(e){const t=I(e);x(t,g,p),a.push(t)}finally{h=!0,u&&(u(),u=null)}}();try{for(;;){for(;a.length>0;){const e=await a[0];if(e===k)return;if(o.aborted)throw new c;e!==C&&(yield e),a.shift(),y()}await new R((e=>{u=e}))}}finally{h=!0,d&&(d(),d=null)}}.call(this)}async function F(e,t=void 0){for await(const r of N.call(this,e,t))return!0;return!1}function N(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return O.call(this,(async function(t,r){return await e(t,r)?t:C}),t)}class D extends s{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}function L(e){if(e=E(e),A(e))return 0;if(e<0)throw new a("number",">= 0",e);return e}e.exports.streamReturningOperators={asIndexedPairs:b((function(e=void 0){return null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(e.signal,"options.signal"),async function*(){let t=0;for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new c({cause:e.signal.reason});yield[t++,n]}}.call(this)}),"readable.asIndexedPairs will be removed in a future version."),drop:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=L(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;e--<=0&&(yield r)}}.call(this)},filter:N,flatMap:function(e,t){const r=O.call(this,e,t);return async function*(){for await(const e of r)yield*e}.call(this)},map:O,take:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=L(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;if(e-- >0&&(yield r),e<=0)return}}.call(this)},compose:function(e,t){if(null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),v(e)&&!m(e))throw new i("stream",e,"must be writable");const r=g(this,e);return null!=t&&t.signal&&y(t.signal,r),r}},e.exports.promiseReturningOperators={every:async function(e,t=void 0){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return!await F.call(this,(async(...t)=>!await e(...t)),t)},forEach:async function(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);for await(const r of O.call(this,(async function(t,r){return await e(t,r),C}),t));},reduce:async function(e,t,r){var i;if("function"!=typeof e)throw new o("reducer",["Function","AsyncFunction"],e);null!=r&&d(r,"options"),null!=(null==r?void 0:r.signal)&&l(r.signal,"options.signal");let s=arguments.length>1;if(null!=r&&null!==(i=r.signal)&&void 0!==i&&i.aborted){const e=new c(void 0,{cause:r.signal.reason});throw this.once("error",(()=>{})),await p(this.destroy(e)),e}const a=new n,u=a.signal;if(null!=r&&r.signal){const e={once:!0,[h]:this,[f]:!0};r.signal.addEventListener("abort",(()=>a.abort()),e)}let g=!1;try{for await(const n of this){var y;if(g=!0,null!=r&&null!==(y=r.signal)&&void 0!==y&&y.aborted)throw new c;s?t=await e(t,n,{signal:u}):(t=n,s=!0)}if(!g&&!s)throw new D}finally{a.abort()}return t},toArray:async function(e){null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(e.signal,"options.signal");const t=[];for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new c(void 0,{cause:e.signal.reason});w(t,n)}return t},some:F,find:async function(e,t){for await(const r of N.call(this,e,t))return r}}},2163:function(e,t,r){"use strict";const{ObjectSetPrototypeOf:n}=r(2057);e.exports=o;const i=r(97);function o(e){if(!(this instanceof o))return new o(e);i.call(this,e)}n(o.prototype,i.prototype),n(o,i),o.prototype._transform=function(e,t,r){r(null,e)}},5783:function(e,t,r){const n=r(5606),{ArrayIsArray:i,Promise:o,SymbolAsyncIterator:s,SymbolDispose:a}=r(2057),c=r(3789),{once:l}=r(6745),u=r(2295),d=r(399),{aggregateTwoErrors:h,codes:{ERR_INVALID_ARG_TYPE:f,ERR_INVALID_RETURN_VALUE:p,ERR_MISSING_ARGS:g,ERR_STREAM_DESTROYED:y,ERR_STREAM_PREMATURE_CLOSE:m},AbortError:v}=r(54),{validateFunction:b,validateAbortSignal:w}=r(5432),{isIterable:_,isReadable:S,isReadableNodeStream:E,isNodeStream:A,isTransformStream:R,isWebStream:I,isReadableStream:T,isReadableFinished:x}=r(9232),P=globalThis.AbortController||r(5568).AbortController;let C,k,O;function F(e,t,r){let n=!1;return e.on("close",(()=>{n=!0})),{destroy:t=>{n||(n=!0,u.destroyer(e,t||new y("pipe")))},cleanup:c(e,{readable:t,writable:r},(e=>{n=!e}))}}function N(e){if(_(e))return e;if(E(e))return async function*(e){k||(k=r(5277)),yield*k.prototype[s].call(e)}(e);throw new f("val",["Readable","Iterable","AsyncIterable"],e)}async function D(e,t,r,{end:n}){let i,s=null;const a=e=>{if(e&&(i=e),s){const e=s;s=null,e()}},l=()=>new o(((e,t)=>{i?t(i):s=()=>{i?t(i):e()}}));t.on("drain",a);const u=c(t,{readable:!1},a);try{t.writableNeedDrain&&await l();for await(const r of e)t.write(r)||await l();n&&(t.end(),await l()),r()}catch(e){r(i!==e?h(i,e):e)}finally{u(),t.off("drain",a)}}async function L(e,t,r,{end:n}){R(t)&&(t=t.writable);const i=t.getWriter();try{for await(const t of e)await i.ready,i.write(t).catch((()=>{}));await i.ready,n&&await i.close(),r()}catch(e){try{await i.abort(e),r(e)}catch(e){r(e)}}}function U(e,t,o){if(1===e.length&&i(e[0])&&(e=e[0]),e.length<2)throw new g("streams");const s=new P,c=s.signal,l=null==o?void 0:o.signal,u=[];function h(){B(new v)}let y,m,b;w(l,"options.signal"),O=O||r(6745).addAbortListener,l&&(y=O(l,h));const x=[];let k,U=0;function M(e){B(e,0==--U)}function B(e,r){var i;if(!e||m&&"ERR_STREAM_PREMATURE_CLOSE"!==m.code||(m=e),m||r){for(;x.length;)x.shift()(m);null===(i=y)||void 0===i||i[a](),s.abort(),r&&(m||u.forEach((e=>e())),n.nextTick(t,m,b))}}for(let V=0;V0,q=J||!1!==(null==o?void 0:o.end),z=V===e.length-1;if(A(K)){if(q){const{destroy:Y,cleanup:Q}=F(K,J,G);x.push(Y),S(K)&&z&&u.push(Q)}function H(e){e&&"AbortError"!==e.name&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code&&M(e)}K.on("error",H),S(K)&&z&&u.push((()=>{K.removeListener("error",H)}))}if(0===V)if("function"==typeof K){if(k=K({signal:c}),!_(k))throw new p("Iterable, AsyncIterable or Stream","source",k)}else k=_(K)||E(K)||R(K)?K:d.from(K);else if("function"==typeof K){var W;if(k=R(k)?N(null===(W=k)||void 0===W?void 0:W.readable):N(k),k=K(k,{signal:c}),J){if(!_(k,!0))throw new p("AsyncIterable",`transform[${V-1}]`,k)}else{var $;C||(C=r(2163));const X=new C({objectMode:!0}),Z=null===($=k)||void 0===$?void 0:$.then;if("function"==typeof Z)U++,Z.call(k,(e=>{b=e,null!=e&&X.write(e),q&&X.end(),n.nextTick(M)}),(e=>{X.destroy(e),n.nextTick(M,e)}));else if(_(k,!0))U++,D(k,X,M,{end:q});else{if(!T(k)&&!R(k))throw new p("AsyncIterable or Promise","destination",k);{const re=k.readable||k;U++,D(re,X,M,{end:q})}}k=X;const{destroy:ee,cleanup:te}=F(k,!1,!0);x.push(ee),z&&u.push(te)}}else if(A(K)){if(E(k)){U+=2;const ne=j(k,K,M,{end:q});S(K)&&z&&u.push(ne)}else if(R(k)||T(k)){const ie=k.readable||k;U++,D(ie,K,M,{end:q})}else{if(!_(k))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],k);U++,D(k,K,M,{end:q})}k=K}else if(I(K)){if(E(k))U++,L(N(k),K,M,{end:q});else if(T(k)||_(k))U++,L(k,K,M,{end:q});else{if(!R(k))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],k);U++,L(k.readable,K,M,{end:q})}k=K}else k=d.from(K)}return(null!=c&&c.aborted||null!=l&&l.aborted)&&n.nextTick(h),k}function j(e,t,r,{end:i}){let o=!1;if(t.on("close",(()=>{o||r(new m)})),e.pipe(t,{end:!1}),i){function s(){o=!0,t.end()}x(e)?n.nextTick(s):e.once("end",s)}else r();return c(e,{readable:!0,writable:!1},(t=>{const n=e._readableState;t&&"ERR_STREAM_PREMATURE_CLOSE"===t.code&&n&&n.ended&&!n.errored&&!n.errorEmitted?e.once("end",r).once("error",r):r(t)})),c(t,{readable:!1,writable:!0},r)}e.exports={pipelineImpl:U,pipeline:function(...e){return U(e,l(function(e){return b(e[e.length-1],"streams[stream.length - 1]"),e.pop()}(e)))}}},5277:function(e,t,r){const n=r(5606),{ArrayPrototypeIndexOf:i,NumberIsInteger:o,NumberIsNaN:s,NumberParseInt:a,ObjectDefineProperties:c,ObjectKeys:l,ObjectSetPrototypeOf:u,Promise:d,SafeSet:h,SymbolAsyncDispose:f,SymbolAsyncIterator:p,Symbol:g}=r(2057);e.exports=G,G.ReadableState=J;const{EventEmitter:y}=r(7007),{Stream:m,prependListener:v}=r(9526),{Buffer:b}=r(8287),{addAbortSignal:w}=r(2194),_=r(3789);let S=r(6745).debuglog("stream",(e=>{S=e}));const E=r(6442),A=r(2295),{getHighWaterMark:R,getDefaultHighWaterMark:I}=r(936),{aggregateTwoErrors:T,codes:{ERR_INVALID_ARG_TYPE:x,ERR_METHOD_NOT_IMPLEMENTED:P,ERR_OUT_OF_RANGE:C,ERR_STREAM_PUSH_AFTER_EOF:k,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:O},AbortError:F}=r(54),{validateObject:N}=r(5432),D=g("kPaused"),{StringDecoder:L}=r(704),U=r(4181);u(G.prototype,m.prototype),u(G,m);const j=()=>{},{errorOrDestroy:M}=A,B=1,H=16,W=32,$=2048,V=4096;function K(e){return{enumerable:!1,get(){return!!(this.state&e)},set(t){t?this.state|=e:this.state&=~e}}}function J(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(399)),this.state=$|V|H|W,e&&e.objectMode&&(this.state|=B),n&&e&&e.readableObjectMode&&(this.state|=B),this.highWaterMark=e?R(this,e,"readableHighWaterMark",n):I(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[D]=null,e&&!1===e.emitClose&&(this.state&=~$),e&&!1===e.autoDestroy&&(this.state&=~V),this.errored=null,this.defaultEncoding=e&&e.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,e&&e.encoding&&(this.decoder=new L(e.encoding),this.encoding=e.encoding)}function G(e){if(!(this instanceof G))return new G(e);const t=this instanceof r(399);this._readableState=new J(e,this,t),e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.construct&&(this._construct=e.construct),e.signal&&!t&&w(e.signal,this)),m.call(this,e),A.construct(this,(()=>{this._readableState.needReadable&&Z(this,this._readableState)}))}function q(e,t,r,n){S("readableAddChunk",t);const i=e._readableState;let o;if(i.state&B||("string"==typeof t?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?t=b.from(t,r).toString(i.encoding):(t=b.from(t,r),r=""))):t instanceof b?r="":m._isUint8Array(t)?(t=m._uint8ArrayToBuffer(t),r=""):null!=t&&(o=new x("chunk",["string","Buffer","Uint8Array"],t))),o)M(e,o);else if(null===t)i.state&=-9,function(e,t){if(S("onEofChunk"),!t.ended){if(t.decoder){const e=t.decoder.end();e&&e.length&&(t.buffer.push(e),t.length+=t.objectMode?1:e.length)}t.ended=!0,t.sync?Q(e):(t.needReadable=!1,t.emittedReadable=!0,X(e))}}(e,i);else if(i.state&B||t&&t.length>0)if(n)if(4&i.state)M(e,new O);else{if(i.destroyed||i.errored)return!1;z(e,i,t,!0)}else if(i.ended)M(e,new k);else{if(i.destroyed||i.errored)return!1;i.state&=-9,i.decoder&&!r?(t=i.decoder.write(t),i.objectMode||0!==t.length?z(e,i,t,!1):Z(e,i)):z(e,i,t,!1)}else n||(i.state&=-9,Z(e,i));return!i.ended&&(i.length0?(65536&t.state?t.awaitDrainWriters.clear():t.awaitDrainWriters=null,t.dataEmitted=!0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),64&t.state&&Q(e)),Z(e,t)}function Y(e,t){return e<=0||0===t.length&&t.ended?0:t.state&B?1:s(e)?t.flowing&&t.length?t.buffer.first().length:t.length:e<=t.length?e:t.ended?t.length:0}function Q(e){const t=e._readableState;S("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(S("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(X,e))}function X(e){const t=e._readableState;S("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||t.errored||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,ie(e)}function Z(e,t){!t.readingMore&&t.constructed&&(t.readingMore=!0,n.nextTick(ee,e,t))}function ee(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!1===t[D]?t.flowing=!0:e.listenerCount("data")>0?e.resume():t.readableListening||(t.flowing=null)}function re(e){S("readable nexttick read 0"),e.read(0)}function ne(e,t){S("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),ie(e),t.flowing&&!t.reading&&e.read(0)}function ie(e){const t=e._readableState;for(S("flow",t.flowing);t.flowing&&null!==e.read(););}function oe(e,t){"function"!=typeof e.read&&(e=G.wrap(e,{objectMode:!0}));const r=async function*(e,t){let r,n=j;function i(t){this===e?(n(),n=j):n=t}e.on("readable",i);const o=_(e,{writable:!1},(e=>{r=e?T(r,e):null,n(),n=j}));try{for(;;){const t=e.destroyed?null:e.read();if(null!==t)yield t;else{if(r)throw r;if(null===r)return;await new d(i)}}}catch(e){throw r=T(r,e),r}finally{!r&&!1===(null==t?void 0:t.destroyOnReturn)||void 0!==r&&!e._readableState.autoDestroy?(e.off("readable",i),o()):A.destroyer(e,null)}}(e,t);return r.stream=e,r}function se(e,t){if(0===t.length)return null;let r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}function ae(e){const t=e._readableState;S("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(ce,t,e))}function ce(e,t){if(S("endReadableNT",e.endEmitted,e.length),!e.errored&&!e.closeEmitted&&!e.endEmitted&&0===e.length)if(e.endEmitted=!0,t.emit("end"),t.writable&&!1===t.allowHalfOpen)n.nextTick(le,t);else if(e.autoDestroy){const e=t._writableState;(!e||e.autoDestroy&&(e.finished||!1===e.writable))&&t.destroy()}}function le(e){e.writable&&!e.writableEnded&&!e.destroyed&&e.end()}let ue;function de(){return void 0===ue&&(ue={}),ue}c(J.prototype,{objectMode:K(B),ended:K(2),endEmitted:K(4),reading:K(8),constructed:K(H),sync:K(W),needReadable:K(64),emittedReadable:K(128),readableListening:K(256),resumeScheduled:K(512),errorEmitted:K(1024),emitClose:K($),autoDestroy:K(V),destroyed:K(8192),closed:K(16384),closeEmitted:K(32768),multiAwaitDrain:K(65536),readingMore:K(1<<17),dataEmitted:K(1<<18)}),G.prototype.destroy=A.destroy,G.prototype._undestroy=A.undestroy,G.prototype._destroy=function(e,t){t(e)},G.prototype[y.captureRejectionSymbol]=function(e){this.destroy(e)},G.prototype[f]=function(){let e;return this.destroyed||(e=this.readableEnded?null:new F,this.destroy(e)),new d(((t,r)=>_(this,(n=>n&&n!==e?r(n):t(null)))))},G.prototype.push=function(e,t){return q(this,e,t,!1)},G.prototype.unshift=function(e,t){return q(this,e,t,!0)},G.prototype.isPaused=function(){const e=this._readableState;return!0===e[D]||!1===e.flowing},G.prototype.setEncoding=function(e){const t=new L(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;const r=this._readableState.buffer;let n="";for(const e of r)n+=t.write(e);return r.clear(),""!==n&&r.push(n),this._readableState.length=n.length,this},G.prototype.read=function(e){S("read",e),void 0===e?e=NaN:o(e)||(e=a(e,10));const t=this._readableState,r=e;if(e>t.highWaterMark&&(t.highWaterMark=function(e){if(e>1073741824)throw new C("size","<= 1GiB",e);return e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,++e}(e)),0!==e&&(t.state&=-129),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return S("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?ae(this):Q(this),null;if(0===(e=Y(e,t))&&t.ended)return 0===t.length&&ae(this),null;let n,i=!!(64&t.state);if(S("need readable",i),(0===t.length||t.length-e0?se(e,t):null,null===n?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.multiAwaitDrain?t.awaitDrainWriters.clear():t.awaitDrainWriters=null),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&ae(this)),null===n||t.errorEmitted||t.closeEmitted||(t.dataEmitted=!0,this.emit("data",n)),n},G.prototype._read=function(e){throw new P("_read()")},G.prototype.pipe=function(e,t){const r=this,i=this._readableState;1===i.pipes.length&&(i.multiAwaitDrain||(i.multiAwaitDrain=!0,i.awaitDrainWriters=new h(i.awaitDrainWriters?[i.awaitDrainWriters]:[]))),i.pipes.push(e),S("pipe count=%d opts=%j",i.pipes.length,t);const o=t&&!1===t.end||e===n.stdout||e===n.stderr?g:s;function s(){S("onend"),e.end()}let a;i.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",(function t(n,o){S("onunpipe"),n===r&&o&&!1===o.hasUnpiped&&(o.hasUnpiped=!0,S("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),a&&e.removeListener("drain",a),e.removeListener("error",d),e.removeListener("unpipe",t),r.removeListener("end",s),r.removeListener("end",g),r.removeListener("data",u),c=!0,a&&i.awaitDrainWriters&&(!e._writableState||e._writableState.needDrain)&&a())}));let c=!1;function l(){c||(1===i.pipes.length&&i.pipes[0]===e?(S("false write response, pause",0),i.awaitDrainWriters=e,i.multiAwaitDrain=!1):i.pipes.length>1&&i.pipes.includes(e)&&(S("false write response, pause",i.awaitDrainWriters.size),i.awaitDrainWriters.add(e)),r.pause()),a||(a=function(e,t){return function(){const r=e._readableState;r.awaitDrainWriters===t?(S("pipeOnDrain",1),r.awaitDrainWriters=null):r.multiAwaitDrain&&(S("pipeOnDrain",r.awaitDrainWriters.size),r.awaitDrainWriters.delete(t)),r.awaitDrainWriters&&0!==r.awaitDrainWriters.size||!e.listenerCount("data")||e.resume()}}(r,e),e.on("drain",a))}function u(t){S("ondata");const r=e.write(t);S("dest.write",r),!1===r&&l()}function d(t){if(S("onerror",t),g(),e.removeListener("error",d),0===e.listenerCount("error")){const r=e._writableState||e._readableState;r&&!r.errorEmitted?M(e,t):e.emit("error",t)}}function f(){e.removeListener("finish",p),g()}function p(){S("onfinish"),e.removeListener("close",f),g()}function g(){S("unpipe"),r.unpipe(e)}return r.on("data",u),v(e,"error",d),e.once("close",f),e.once("finish",p),e.emit("pipe",r),!0===e.writableNeedDrain?l():i.flowing||(S("pipe resume"),r.resume()),e},G.prototype.unpipe=function(e){const t=this._readableState;if(0===t.pipes.length)return this;if(!e){const e=t.pipes;t.pipes=[],this.pause();for(let t=0;t0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,S("on readable",i.length,i.reading),i.length?Q(this):i.reading||n.nextTick(re,this))),r},G.prototype.addListener=G.prototype.on,G.prototype.removeListener=function(e,t){const r=m.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(te,this),r},G.prototype.off=G.prototype.removeListener,G.prototype.removeAllListeners=function(e){const t=m.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(te,this),t},G.prototype.resume=function(){const e=this._readableState;return e.flowing||(S("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(ne,e,t))}(this,e)),e[D]=!1,this},G.prototype.pause=function(){return S("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(S("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[D]=!0,this},G.prototype.wrap=function(e){let t=!1;e.on("data",(r=>{!this.push(r)&&e.pause&&(t=!0,e.pause())})),e.on("end",(()=>{this.push(null)})),e.on("error",(e=>{M(this,e)})),e.on("close",(()=>{this.destroy()})),e.on("destroy",(()=>{this.destroy()})),this._read=()=>{t&&e.resume&&(t=!1,e.resume())};const r=l(e);for(let t=1;t{t?e?e(t):this.destroy(t):(null!=r&&this.push(r),this.push(null),e&&e())}))}function d(){this._final!==u&&u.call(this)}l.prototype._final=u,l.prototype._transform=function(e,t,r){throw new o("_transform()")},l.prototype._write=function(e,t,r){const n=this._readableState,i=this._writableState,o=n.length;this._transform(e,t,((e,t)=>{e?r(e):(null!=t&&this.push(t),i.ended||o===n.length||n.length{const e=this._writableState;e.writing||W(this,e),V(this,e)}))}function D(e,t,r,i){const o=e._writableState;if("function"==typeof r)i=r,r=o.defaultEncoding;else{if(r){if("buffer"!==r&&!g.isEncoding(r))throw new x(r)}else r=o.defaultEncoding;"function"!=typeof i&&(i=C)}if(null===t)throw new I;if(!o.objectMode)if("string"==typeof t)!1!==o.decodeStrings&&(t=g.from(t,r),r="buffer");else if(t instanceof g)r="buffer";else{if(!p._isUint8Array(t))throw new w("chunk",["string","Buffer","Uint8Array"],t);t=p._uint8ArrayToBuffer(t),r="buffer"}let s;return o.ending?s=new T:o.destroyed&&(s=new A("write")),s?(n.nextTick(i,s),P(e,s,!0),s):(o.pendingcb++,function(e,t,r,n,i){const o=t.objectMode?1:r.length;t.length+=o;const s=t.lengthr.bufferedIndex&&W(e,r),i?null!==r.afterWriteTickInfo&&r.afterWriteTickInfo.cb===o?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:o,stream:e,state:r},n.nextTick(M,r.afterWriteTickInfo)):B(e,r,1,o))):P(e,new S)}function M({stream:e,state:t,count:r,cb:n}){return t.afterWriteTickInfo=null,B(e,t,r,n)}function B(e,t,r,n){for(!t.ending&&!e.destroyed&&0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"));r-- >0;)t.pendingcb--,n();t.destroyed&&H(t),V(e,t)}function H(e){if(e.writing)return;for(let r=e.bufferedIndex;r1&&e._writev){t.pendingcb-=s-1;const n=t.allNoop?C:e=>{for(let t=a;t256?(r.splice(0,a),t.bufferedIndex=0):t.bufferedIndex=a}t.bufferProcessing=!1}function $(e){return e.ending&&!e.destroyed&&e.constructed&&0===e.length&&!e.errored&&0===e.buffered.length&&!e.finished&&!e.writing&&!e.errorEmitted&&!e.closeEmitted}function V(e,t,r){$(t)&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.finalCalled=!0,function(e,t){let r=!1;function i(i){if(r)P(e,null!=i?i:S());else if(r=!0,t.pendingcb--,i){const r=t[k].splice(0);for(let e=0;e{$(t)?K(e,t):t.pendingcb--}),e,t)):$(t)&&(t.pendingcb++,K(e,t))))}function K(e,t){t.pendingcb--,t.finished=!0;const r=t[k].splice(0);for(let e=0;e{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);if(en)throw new _(t,`>= ${r} && <= ${n}`,e)})),P=m(((e,t,r=-2147483648,n=2147483647)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);if(en)throw new _(t,`>= ${r} && <= ${n}`,e)})),C=m(((e,t,r=!1)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);const n=r?1:0,i=4294967295;if(ei)throw new _(t,`>= ${n} && <= ${i}`,e)}));function k(e,t){if("string"!=typeof e)throw new b(t,"string",e)}const O=m(((e,t,r)=>{if(!i(r,e)){const n=o(s(r,(e=>"string"==typeof e?`'${e}'`:p(e))),", ");throw new w(t,e,"must be one of: "+n)}}));function F(e,t){if("boolean"!=typeof e)throw new b(t,"boolean",e)}function N(e,t,r){return null!=e&&h(e,t)?e[t]:r}const D=m(((e,t,r=null)=>{const i=N(r,"allowArray",!1),o=N(r,"allowFunction",!1);if(!N(r,"nullable",!1)&&null===e||!i&&n(e)||"object"!=typeof e&&(!o||"function"!=typeof e))throw new b(t,"Object",e)})),L=m(((e,t)=>{if(null!=e&&"object"!=typeof e&&"function"!=typeof e)throw new b(t,"a dictionary",e)})),U=m(((e,t,r=0)=>{if(!n(e))throw new b(t,"Array",e);if(e.length{if(!R(e))throw new b(t,["Buffer","TypedArray","DataView"],e)})),M=m(((e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new b(t,"AbortSignal",e)})),B=m(((e,t)=>{if("function"!=typeof e)throw new b(t,"Function",e)})),H=m(((e,t)=>{if("function"!=typeof e||A(e))throw new b(t,"Function",e)})),W=m(((e,t)=>{if(void 0!==e)throw new b(t,"undefined",e)})),$=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function V(e,t){if(void 0===e||!f($,e))throw new w(t,e,'must be an array or string of format "; rel=preload; as=style"')}e.exports={isInt32:function(e){return e===(0|e)},isUint32:function(e){return e===e>>>0},parseFileMode:function(e,t,r){if(void 0===e&&(e=r),"string"==typeof e){if(null===f(T,e))throw new w(t,e,"must be a 32-bit unsigned integer or an octal string");e=d(e,8)}return C(e,t),e},validateArray:U,validateStringArray:function(e,t){U(e,t);for(let r=0;rn||(null!=r||null!=n)&&c(e))throw new _(t,`${null!=r?`>= ${r}`:""}${null!=r&&null!=n?" && ":""}${null!=n?`<= ${n}`:""}`,e)},validateObject:D,validateOneOf:O,validatePlainFunction:H,validatePort:function(e,t="Port",r=!0){if("number"!=typeof e&&"string"!=typeof e||"string"==typeof e&&0===y(e).length||+e!=+e>>>0||e>65535||0===e&&!r)throw new v(t,e,r);return 0|e},validateSignalName:function(e,t="signal"){if(k(e,t),void 0===I[e]){if(void 0!==I[g(e)])throw new S(e+" (signals must use all capital letters)");throw new S(e)}},validateString:k,validateUint32:C,validateUndefined:W,validateUnion:function(e,t,r){if(!i(r,e))throw new b(t,`('${o(r,"|")}')`,e)},validateAbortSignal:M,validateLinkHeaderValue:function(e){if("string"==typeof e)return V(e,"hints"),e;if(n(e)){const t=e.length;let r="";if(0===t)return r;for(let n=0;n; rel=preload; as=style"')}}},2225:function(e,t,r){"use strict";const n=r(6897),i=r(7698),o=n.Readable.destroy;e.exports=n.Readable,e.exports._uint8ArrayToBuffer=n._uint8ArrayToBuffer,e.exports._isUint8Array=n._isUint8Array,e.exports.isDisturbed=n.isDisturbed,e.exports.isErrored=n.isErrored,e.exports.isReadable=n.isReadable,e.exports.Readable=n.Readable,e.exports.Writable=n.Writable,e.exports.Duplex=n.Duplex,e.exports.Transform=n.Transform,e.exports.PassThrough=n.PassThrough,e.exports.addAbortSignal=n.addAbortSignal,e.exports.finished=n.finished,e.exports.destroy=n.destroy,e.exports.destroy=o,e.exports.pipeline=n.pipeline,e.exports.compose=n.compose,Object.defineProperty(n,"promises",{configurable:!0,enumerable:!0,get(){return i}}),e.exports.Stream=n.Stream,e.exports.default=e.exports},54:function(e,t,r){"use strict";const{format:n,inspect:i,AggregateError:o}=r(6745),s=globalThis.AggregateError||o,a=Symbol("kIsNodeError"),c=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,u={};function d(e,t){if(!e)throw new u.ERR_INTERNAL_ASSERTION(t)}function h(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function f(e,t,r){r||(r=Error);class i extends r{constructor(...r){super(function(e,t,r){if("function"==typeof t)return d(t.length<=r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`),t(...r);const i=(t.match(/%[dfijoOs]/g)||[]).length;return d(i===r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${i}).`),0===r.length?t:n(t,...r)}(e,t,r))}toString(){return`${this.name} [${e}]: ${this.message}`}}Object.defineProperties(i.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${e}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),i.prototype.code=e,i.prototype[a]=!0,u[e]=i}function p(e){const t="__node_internal_"+e.name;return Object.defineProperty(e,"name",{value:t}),e}class g extends Error{constructor(e="The operation was aborted",t=void 0){if(void 0!==t&&"object"!=typeof t)throw new u.ERR_INVALID_ARG_TYPE("options","Object",t);super(e,t),this.code="ABORT_ERR",this.name="AbortError"}}f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",((e,t,r)=>{d("string"==typeof e,"'name' must be a string"),Array.isArray(t)||(t=[t]);let n="The ";e.endsWith(" argument")?n+=`${e} `:n+=`"${e}" ${e.includes(".")?"property":"argument"} `,n+="must be ";const o=[],s=[],a=[];for(const e of t)d("string"==typeof e,"All expected entries have to be of type string"),c.includes(e)?o.push(e.toLowerCase()):l.test(e)?s.push(e):(d("object"!==e,'The value "object" should be written as "Object"'),a.push(e));if(s.length>0){const e=o.indexOf("object");-1!==e&&(o.splice(o,e,1),s.push("Object"))}if(o.length>0){switch(o.length){case 1:n+=`of type ${o[0]}`;break;case 2:n+=`one of type ${o[0]} or ${o[1]}`;break;default:{const e=o.pop();n+=`one of type ${o.join(", ")}, or ${e}`}}(s.length>0||a.length>0)&&(n+=" or ")}if(s.length>0){switch(s.length){case 1:n+=`an instance of ${s[0]}`;break;case 2:n+=`an instance of ${s[0]} or ${s[1]}`;break;default:{const e=s.pop();n+=`an instance of ${s.join(", ")}, or ${e}`}}a.length>0&&(n+=" or ")}switch(a.length){case 0:break;case 1:a[0].toLowerCase()!==a[0]&&(n+="an "),n+=`${a[0]}`;break;case 2:n+=`one of ${a[0]} or ${a[1]}`;break;default:{const e=a.pop();n+=`one of ${a.join(", ")}, or ${e}`}}if(null==r)n+=`. Received ${r}`;else if("function"==typeof r&&r.name)n+=`. Received function ${r.name}`;else if("object"==typeof r){var u;null!==(u=r.constructor)&&void 0!==u&&u.name?n+=`. Received an instance of ${r.constructor.name}`:n+=`. Received ${i(r,{depth:-1})}`}else{let e=i(r,{colors:!1});e.length>25&&(e=`${e.slice(0,25)}...`),n+=`. Received type ${typeof r} (${e})`}return n}),TypeError),f("ERR_INVALID_ARG_VALUE",((e,t,r="is invalid")=>{let n=i(t);return n.length>128&&(n=n.slice(0,128)+"..."),`The ${e.includes(".")?"property":"argument"} '${e}' ${r}. Received ${n}`}),TypeError),f("ERR_INVALID_RETURN_VALUE",((e,t,r)=>{var n;return`Expected ${e} to be returned from the "${t}" function but got ${null!=r&&null!==(n=r.constructor)&&void 0!==n&&n.name?`instance of ${r.constructor.name}`:"type "+typeof r}.`}),TypeError),f("ERR_MISSING_ARGS",((...e)=>{let t;d(e.length>0,"At least one arg needs to be specified");const r=e.length;switch(e=(Array.isArray(e)?e:[e]).map((e=>`"${e}"`)).join(" or "),r){case 1:t+=`The ${e[0]} argument`;break;case 2:t+=`The ${e[0]} and ${e[1]} arguments`;break;default:{const r=e.pop();t+=`The ${e.join(", ")}, and ${r} arguments`}}return`${t} must be specified`}),TypeError),f("ERR_OUT_OF_RANGE",((e,t,r)=>{let n;return d(t,'Missing "range" argument'),Number.isInteger(r)&&Math.abs(r)>2**32?n=h(String(r)):"bigint"==typeof r?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=h(n)),n+="n"):n=i(r),`The value of "${e}" is out of range. It must be ${t}. Received ${n}`}),RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:g,aggregateTwoErrors:p((function(e,t){if(e&&t&&e!==t){if(Array.isArray(t.errors))return t.errors.push(e),t;const r=new s([t,e],t.message);return r.code=t.code,r}return e||t})),hideStackFrames:p,codes:u}},2057:function(e){"use strict";e.exports={ArrayIsArray(e){return Array.isArray(e)},ArrayPrototypeIncludes(e,t){return e.includes(t)},ArrayPrototypeIndexOf(e,t){return e.indexOf(t)},ArrayPrototypeJoin(e,t){return e.join(t)},ArrayPrototypeMap(e,t){return e.map(t)},ArrayPrototypePop(e,t){return e.pop(t)},ArrayPrototypePush(e,t){return e.push(t)},ArrayPrototypeSlice(e,t,r){return e.slice(t,r)},Error:Error,FunctionPrototypeCall(e,t,...r){return e.call(t,...r)},FunctionPrototypeSymbolHasInstance(e,t){return Function.prototype[Symbol.hasInstance].call(e,t)},MathFloor:Math.floor,Number:Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(e,t){return Object.defineProperties(e,t)},ObjectDefineProperty(e,t,r){return Object.defineProperty(e,t,r)},ObjectGetOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)},ObjectKeys(e){return Object.keys(e)},ObjectSetPrototypeOf(e,t){return Object.setPrototypeOf(e,t)},Promise:Promise,PromisePrototypeCatch(e,t){return e.catch(t)},PromisePrototypeThen(e,t,r){return e.then(t,r)},PromiseReject(e){return Promise.reject(e)},PromiseResolve(e){return Promise.resolve(e)},ReflectApply:Reflect.apply,RegExpPrototypeTest(e,t){return e.test(t)},SafeSet:Set,String:String,StringPrototypeSlice(e,t,r){return e.slice(t,r)},StringPrototypeToLowerCase(e){return e.toLowerCase()},StringPrototypeToUpperCase(e){return e.toUpperCase()},StringPrototypeTrim(e){return e.trim()},Symbol:Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(e,t,r){return e.set(t,r)},Boolean:Boolean,Uint8Array:Uint8Array}},6745:function(e,t,r){"use strict";const n=r(8287),{kResistStopPropagation:i,SymbolDispose:o}=r(2057),s=globalThis.AbortSignal||r(5568).AbortSignal,a=globalThis.AbortController||r(5568).AbortController,c=Object.getPrototypeOf((async function(){})).constructor,l=globalThis.Blob||n.Blob,u=void 0!==l?function(e){return e instanceof l}:function(e){return!1},d=(e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new ERR_INVALID_ARG_TYPE(t,"AbortSignal",e)};class h extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError("Expected input to be an Array, got "+typeof e);let t="";for(let r=0;r{e=r,t=n})),resolve:e,reject:t}},promisify(e){return new Promise(((t,r)=>{e(((e,...n)=>e?r(e):t(...n)))}))},debuglog(){return function(){}},format(e,...t){return e.replace(/%([sdifj])/g,(function(...[e,r]){const n=t.shift();return"f"===r?n.toFixed(6):"j"===r?JSON.stringify(n):"s"===r&&"object"==typeof n?`${n.constructor!==Object?n.constructor.name:""} {}`.trim():n.toString()}))},inspect(e){switch(typeof e){case"string":if(e.includes("'")){if(!e.includes('"'))return`"${e}"`;if(!e.includes("`")&&!e.includes("${"))return`\`${e}\``}return`'${e}'`;case"number":return isNaN(e)?"NaN":Object.is(e,-0)?String(e):e;case"bigint":return`${String(e)}n`;case"boolean":case"undefined":return String(e);case"object":return"{}"}},types:{isAsyncFunction(e){return e instanceof c},isArrayBufferView(e){return ArrayBuffer.isView(e)}},isBlob:u,deprecate(e,t){return e},addAbortListener:r(7007).addAbortListener||function(e,t){if(void 0===e)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);let r;return d(e,"signal"),(e=>{if("function"!=typeof e)throw new ERR_INVALID_ARG_TYPE("listener","Function",e)})(t),e.aborted?queueMicrotask((()=>t())):(e.addEventListener("abort",t,{__proto__:null,once:!0,[i]:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,[o](){var e;null===(e=r)||void 0===e||e()}}},AbortSignalAny:s.any||function(e){if(1===e.length)return e[0];const t=new a,r=()=>t.abort();return e.forEach((e=>{d(e,"signals"),e.addEventListener("abort",r,{once:!0})})),t.signal.addEventListener("abort",(()=>{e.forEach((e=>e.removeEventListener("abort",r)))}),{once:!0}),t.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")},6897:function(e,t,r){const{Buffer:n}=r(8287),{ObjectDefineProperty:i,ObjectKeys:o,ReflectApply:s}=r(2057),{promisify:{custom:a}}=r(6745),{streamReturningOperators:c,promiseReturningOperators:l}=r(2892),{codes:{ERR_ILLEGAL_CONSTRUCTOR:u}}=r(54),d=r(769),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:f}=r(936),{pipeline:p}=r(5783),{destroyer:g}=r(2295),y=r(3789),m=r(7698),v=r(9232),b=e.exports=r(9526).Stream;b.isDestroyed=v.isDestroyed,b.isDisturbed=v.isDisturbed,b.isErrored=v.isErrored,b.isReadable=v.isReadable,b.isWritable=v.isWritable,b.Readable=r(5277);for(const S of o(c)){const E=c[S];function w(...e){if(new.target)throw u();return b.Readable.from(s(E,this,e))}i(w,"name",{__proto__:null,value:E.name}),i(w,"length",{__proto__:null,value:E.length}),i(b.Readable.prototype,S,{__proto__:null,value:w,enumerable:!1,configurable:!0,writable:!0})}for(const A of o(l)){const R=l[A];function w(...e){if(new.target)throw u();return s(R,this,e)}i(w,"name",{__proto__:null,value:R.name}),i(w,"length",{__proto__:null,value:R.length}),i(b.Readable.prototype,A,{__proto__:null,value:w,enumerable:!1,configurable:!0,writable:!0})}b.Writable=r(4461),b.Duplex=r(399),b.Transform=r(97),b.PassThrough=r(2163),b.pipeline=p;const{addAbortSignal:_}=r(2194);b.addAbortSignal=_,b.finished=y,b.destroy=g,b.compose=d,b.setDefaultHighWaterMark=h,b.getDefaultHighWaterMark=f,i(b,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return m}}),i(p,a,{__proto__:null,enumerable:!0,get(){return m.pipeline}}),i(y,a,{__proto__:null,enumerable:!0,get(){return m.finished}}),b.Stream=b,b._isUint8Array=function(e){return e instanceof Uint8Array},b._uint8ArrayToBuffer=function(e){return n.from(e.buffer,e.byteOffset,e.byteLength)}},7698:function(e,t,r){"use strict";const{ArrayPrototypePop:n,Promise:i}=r(2057),{isIterable:o,isNodeStream:s,isWebStream:a}=r(9232),{pipelineImpl:c}=r(5783),{finished:l}=r(3789);r(6897),e.exports={finished:l,pipeline:function(...e){return new i(((t,r)=>{let i,l;const u=e[e.length-1];if(u&&"object"==typeof u&&!s(u)&&!o(u)&&!a(u)){const t=n(e);i=t.signal,l=t.end}c(e,((e,n)=>{e?r(e):t(n)}),{signal:i,end:l})}))}}},8572:function(e,t,r){var n=r(8287),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(o(n,t),t.Buffer=s),s.prototype=Object.create(i.prototype),o(i,s),s.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},s.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},704:function(e,t,r){"use strict";var n=r(8572).Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=l,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=u,this.end=d,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,r=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function l(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function u(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function d(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0?(i>0&&(e.lastNeed=i-1),i):--n=0?(i>0&&(e.lastNeed=i-2),i):--n=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},810:function(e,t,r){"use strict";const{SymbolDispose:n}=r(4641),{AbortError:i,codes:o}=r(8526),{isNodeStream:s,isWebStream:a,kControllerErrorFunction:c}=r(136),l=r(9365),{ERR_INVALID_ARG_TYPE:u}=o;let d;e.exports.addAbortSignal=function(t,r){if((e=>{if("object"!=typeof e||!("aborted"in e))throw new u("signal","AbortSignal",e)})(t),!s(r)&&!a(r))throw new u("stream",["ReadableStream","WritableStream","Stream"],r);return e.exports.addAbortSignalNoValidate(t,r)},e.exports.addAbortSignalNoValidate=function(e,t){if("object"!=typeof e||!("aborted"in e))return t;const o=s(t)?()=>{t.destroy(new i(void 0,{cause:e.reason}))}:()=>{t[c](new i(void 0,{cause:e.reason}))};if(e.aborted)o();else{d=d||r(6017).addAbortListener;const i=d(e,o);l(t,i[n])}return t}},5586:function(e,t,r){"use strict";const{StringPrototypeSlice:n,SymbolIterator:i,TypedArrayPrototypeSet:o,Uint8Array:s}=r(4641),{Buffer:a}=r(8287),{inspect:c}=r(6017);e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(e){const t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}unshift(e){const t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}shift(){if(0===this.length)return;const e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(0===this.length)return"";let t=this.head,r=""+t.data;for(;null!==(t=t.next);)r+=e+t.data;return r}concat(e){if(0===this.length)return a.alloc(0);const t=a.allocUnsafe(e>>>0);let r=this.head,n=0;for(;r;)o(t,r.data,n),n+=r.data.length,r=r.next;return t}consume(e,t){const r=this.head.data;if(eo.length)){e===o.length?(t+=o,++i,r.next?this.head=r.next:this.head=this.tail=null):(t+=n(o,0,e),this.head=r,r.data=n(o,e));break}t+=o,e-=o.length,++i}while(null!==(r=r.next));return this.length-=i,t}_getBuffer(e){const t=a.allocUnsafe(e),r=e;let n=this.head,i=0;do{const a=n.data;if(!(e>a.length)){e===a.length?(o(t,a,r-e),++i,n.next?this.head=n.next:this.head=this.tail=null):(o(t,new s(a.buffer,a.byteOffset,e),r-e),this.head=n,n.data=a.slice(e));break}o(t,a,r-e),e-=a.length,++i}while(null!==(n=n.next));return this.length-=i,t}[Symbol.for("nodejs.util.inspect.custom")](e,t){return c(this,{...t,depth:0,customInspect:!1})}}},8489:function(e,t,r){"use strict";const{pipeline:n}=r(8431),i=r(3559),{destroyer:o}=r(7647),{isNodeStream:s,isReadable:a,isWritable:c,isWebStream:l,isTransformStream:u,isWritableStream:d,isReadableStream:h}=r(136),{AbortError:f,codes:{ERR_INVALID_ARG_VALUE:p,ERR_MISSING_ARGS:g}}=r(8526),y=r(9365);e.exports=function(...e){if(0===e.length)throw new g("streams");if(1===e.length)return i.from(e[0]);const t=[...e];if("function"==typeof e[0]&&(e[0]=i.from(e[0])),"function"==typeof e[e.length-1]){const t=e.length-1;e[t]=i.from(e[t])}for(let r=0;r0&&!(c(e[r])||d(e[r])||u(e[r])))throw new p(`streams[${r}]`,t[r],"must be writable")}let r,m,v,b,w;const _=e[0],S=n(e,(function(e){const t=b;b=null,t?t(e):e?w.destroy(e):A||E||w.destroy()})),E=!!(c(_)||d(_)||u(_)),A=!!(a(S)||h(S)||u(S));if(w=new i({writableObjectMode:!(null==_||!_.writableObjectMode),readableObjectMode:!(null==S||!S.readableObjectMode),writable:E,readable:A}),E){if(s(_))w._write=function(e,t,n){_.write(e,t)?n():r=n},w._final=function(e){_.end(),m=e},_.on("drain",(function(){if(r){const e=r;r=null,e()}}));else if(l(_)){const e=(u(_)?_.writable:_).getWriter();w._write=async function(t,r,n){try{await e.ready,e.write(t).catch((()=>{})),n()}catch(e){n(e)}},w._final=async function(t){try{await e.ready,e.close().catch((()=>{})),m=t}catch(e){t(e)}}}const e=u(S)?S.readable:S;y(e,(()=>{if(m){const e=m;m=null,e()}}))}if(A)if(s(S))S.on("readable",(function(){if(v){const e=v;v=null,e()}})),S.on("end",(function(){w.push(null)})),w._read=function(){for(;;){const e=S.read();if(null===e)return void(v=w._read);if(!w.push(e))return}};else if(l(S)){const e=(u(S)?S.readable:S).getReader();w._read=async function(){for(;;)try{const{value:t,done:r}=await e.read();if(!w.push(t))return;if(r)return void w.push(null)}catch{return}}}return w._destroy=function(e,t){e||null===b||(e=new f),v=null,r=null,m=null,null===b?t(e):(b=t,s(S)&&o(S,e))},w}},7647:function(e,t,r){"use strict";const n=r(5606),{aggregateTwoErrors:i,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:s}=r(8526),{Symbol:a}=r(4641),{kIsDestroyed:c,isDestroyed:l,isFinished:u,isServerRequest:d}=r(136),h=a("kDestroy"),f=a("kConstruct");function p(e,t,r){e&&(e.stack,t&&!t.errored&&(t.errored=e),r&&!r.errored&&(r.errored=e))}function g(e,t,r){let i=!1;function o(t){if(i)return;i=!0;const o=e._readableState,s=e._writableState;p(t,s,o),s&&(s.closed=!0),o&&(o.closed=!0),"function"==typeof r&&r(t),t?n.nextTick(y,e,t):n.nextTick(m,e)}try{e._destroy(t||null,o)}catch(t){o(t)}}function y(e,t){v(e,t),m(e)}function m(e){const t=e._readableState,r=e._writableState;r&&(r.closeEmitted=!0),t&&(t.closeEmitted=!0),(null!=r&&r.emitClose||null!=t&&t.emitClose)&&e.emit("close")}function v(e,t){const r=e._readableState,n=e._writableState;null!=n&&n.errorEmitted||null!=r&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),e.emit("error",t))}function b(e,t,r){const i=e._readableState,o=e._writableState;if(null!=o&&o.destroyed||null!=i&&i.destroyed)return this;null!=i&&i.autoDestroy||null!=o&&o.autoDestroy?e.destroy(t):t&&(t.stack,o&&!o.errored&&(o.errored=t),i&&!i.errored&&(i.errored=t),r?n.nextTick(v,e,t):v(e,t))}function w(e){let t=!1;function r(r){if(t)return void b(e,null!=r?r:new o);t=!0;const i=e._readableState,s=e._writableState,a=s||i;i&&(i.constructed=!0),s&&(s.constructed=!0),a.destroyed?e.emit(h,r):r?b(e,r,!0):n.nextTick(_,e)}try{e._construct((e=>{n.nextTick(r,e)}))}catch(e){n.nextTick(r,e)}}function _(e){e.emit(f)}function S(e){return(null==e?void 0:e.setHeader)&&"function"==typeof e.abort}function E(e){e.emit("close")}function A(e,t){e.emit("error",t),n.nextTick(E,e)}e.exports={construct:function(e,t){if("function"!=typeof e._construct)return;const r=e._readableState,i=e._writableState;r&&(r.constructed=!1),i&&(i.constructed=!1),e.once(f,t),e.listenerCount(f)>1||n.nextTick(w,e)},destroyer:function(e,t){e&&!l(e)&&(t||u(e)||(t=new s),d(e)?(e.socket=null,e.destroy(t)):S(e)?e.abort():S(e.req)?e.req.abort():"function"==typeof e.destroy?e.destroy(t):"function"==typeof e.close?e.close():t?n.nextTick(A,e,t):n.nextTick(E,e),e.destroyed||(e[c]=!0))},destroy:function(e,t){const r=this._readableState,n=this._writableState,o=n||r;return null!=n&&n.destroyed||null!=r&&r.destroyed?("function"==typeof t&&t(),this):(p(e,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),o.constructed?g(this,e,t):this.once(h,(function(r){g(this,i(r,e),t)})),this)},undestroy:function(){const e=this._readableState,t=this._writableState;e&&(e.constructed=!0,e.closed=!1,e.closeEmitted=!1,e.destroyed=!1,e.errored=null,e.errorEmitted=!1,e.reading=!1,e.ended=!1===e.readable,e.endEmitted=!1===e.readable),t&&(t.constructed=!0,t.destroyed=!1,t.closed=!1,t.closeEmitted=!1,t.errored=null,t.errorEmitted=!1,t.finalCalled=!1,t.prefinished=!1,t.ended=!1===t.writable,t.ending=!1===t.writable,t.finished=!1===t.writable)},errorOrDestroy:b}},3559:function(e,t,r){"use strict";const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:i,ObjectKeys:o,ObjectSetPrototypeOf:s}=r(4641);e.exports=l;const a=r(3125),c=r(7221);s(l.prototype,a.prototype),s(l,a);{const e=o(c.prototype);for(let t=0;t{d=!1,e&&v(t,e),h(e)})),l._write=function(e,t,i){r.write(e,t)?i():n=i},l._final=function(e){r.end(),i=e},r.on("drain",(function(){if(n){const e=n;n=null,e()}})),r.on("finish",(function(){if(i){const e=i;i=null,e()}}))),u&&(p(t,(e=>{u=!1,e&&v(t,e),h(e)})),t.on("readable",(function(){if(a){const e=a;a=null,e()}})),t.on("end",(function(){l.push(null)})),l._read=function(){for(;;){const e=t.read();if(null===e)return void(a=l._read);if(!l.push(e))return}}),l._destroy=function(e,o){e||null===c||(e=new g),a=null,n=null,i=null,null===c?o(e):(c=o,v(r,e),v(t,e))},l}e.exports=function e(t,r){if(d(t))return t;if(l(t))return P({readable:t});if(u(t))return P({writable:t});if(c(t))return P({writable:!1,readable:!1});if(h(t))return P({readable:w.fromWeb(t)});if(f(t))return P({writable:_.fromWeb(t)});if("function"==typeof t){const{value:e,write:i,final:o,destroy:s}=function(e){let{promise:t,resolve:r}=S();const i=new I,o=i.signal;return{value:e(async function*(){for(;;){const e=t;t=null;const{chunk:i,done:s,cb:a}=await e;if(n.nextTick(a),s)return;if(o.aborted)throw new g(void 0,{cause:o.reason});({promise:t,resolve:r}=S()),yield i}}(),{signal:o}),write(e,t,n){const i=r;r=null,i({chunk:e,done:!1,cb:n})},final(e){const t=r;r=null,t({done:!0,cb:e})},destroy(e,t){i.abort(),t(e)}}}(t);if(a(e))return E(x,e,{objectMode:!0,write:i,final:o,destroy:s});const c=null==e?void 0:e.then;if("function"==typeof c){let t;const r=T(c,e,(e=>{if(null!=e)throw new m("nully","body",e)}),(e=>{v(t,e)}));return t=new x({objectMode:!0,readable:!1,write:i,final(e){o((async()=>{try{await r,n.nextTick(e,null)}catch(t){n.nextTick(e,t)}}))},destroy:s})}throw new m("Iterable, AsyncIterable or AsyncFunction",r,e)}if(R(t))return e(t.arrayBuffer());if(a(t))return E(x,t,{objectMode:!0,writable:!1});if(h(null==t?void 0:t.readable)&&f(null==t?void 0:t.writable))return x.fromWeb(t);if("object"==typeof(null==t?void 0:t.writable)||"object"==typeof(null==t?void 0:t.readable))return P({readable:null!=t&&t.readable?l(null==t?void 0:t.readable)?null==t?void 0:t.readable:e(t.readable):void 0,writable:null!=t&&t.writable?u(null==t?void 0:t.writable)?null==t?void 0:t.writable:e(t.writable):void 0});const i=null==t?void 0:t.then;if("function"==typeof i){let e;return T(i,t,(t=>{null!=t&&e.push(t),e.push(null)}),(t=>{v(e,t)})),e=new x({objectMode:!0,writable:!1,read(){}})}throw new y(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],t)}},9365:function(e,t,r){const n=r(5606),{AbortError:i,codes:o}=r(8526),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_PREMATURE_CLOSE:a}=o,{kEmptyObject:c,once:l}=r(6017),{validateAbortSignal:u,validateFunction:d,validateObject:h,validateBoolean:f}=r(2224),{Promise:p,PromisePrototypeThen:g,SymbolDispose:y}=r(4641),{isClosed:m,isReadable:v,isReadableNodeStream:b,isReadableStream:w,isReadableFinished:_,isReadableErrored:S,isWritable:E,isWritableNodeStream:A,isWritableStream:R,isWritableFinished:I,isWritableErrored:T,isNodeStream:x,willEmitClose:P,kIsClosedPromise:C}=r(136);let k;const O=()=>{};function F(e,t,o){var f,p;if(2===arguments.length?(o=t,t=c):null==t?t=c:h(t,"options"),d(o,"callback"),u(t.signal,"options.signal"),o=l(o),w(e)||R(e))return function(e,t,o){let s=!1,a=O;if(t.signal)if(a=()=>{s=!0,o.call(e,new i(void 0,{cause:t.signal.reason}))},t.signal.aborted)n.nextTick(a);else{k=k||r(6017).addAbortListener;const n=k(t.signal,a),i=o;o=l(((...t)=>{n[y](),i.apply(e,t)}))}const c=(...t)=>{s||n.nextTick((()=>o.apply(e,t)))};return g(e[C].promise,c,c),O}(e,t,o);if(!x(e))throw new s("stream",["ReadableStream","WritableStream","Stream"],e);const F=null!==(f=t.readable)&&void 0!==f?f:b(e),N=null!==(p=t.writable)&&void 0!==p?p:A(e),D=e._writableState,L=e._readableState,U=()=>{e.writable||B()};let j=P(e)&&b(e)===F&&A(e)===N,M=I(e,!1);const B=()=>{M=!0,e.destroyed&&(j=!1),(!j||e.readable&&!F)&&(F&&!H||o.call(e))};let H=_(e,!1);const W=()=>{H=!0,e.destroyed&&(j=!1),(!j||e.writable&&!N)&&(N&&!M||o.call(e))},$=t=>{o.call(e,t)};let V=m(e);const K=()=>{V=!0;const t=T(e)||S(e);return t&&"boolean"!=typeof t?o.call(e,t):F&&!H&&b(e,!0)&&!_(e,!1)?o.call(e,new a):!N||M||I(e,!1)?void o.call(e):o.call(e,new a)},J=()=>{V=!0;const t=T(e)||S(e);if(t&&"boolean"!=typeof t)return o.call(e,t);o.call(e)},G=()=>{e.req.on("finish",B)};!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?N&&!D&&(e.on("end",U),e.on("close",U)):(e.on("complete",B),j||e.on("abort",K),e.req?G():e.on("request",G)),j||"boolean"!=typeof e.aborted||e.on("aborted",K),e.on("end",W),e.on("finish",B),!1!==t.error&&e.on("error",$),e.on("close",K),V?n.nextTick(K):null!=D&&D.errorEmitted||null!=L&&L.errorEmitted?j||n.nextTick(J):(F||j&&!v(e)||!M&&!1!==E(e))&&(N||j&&!E(e)||!H&&!1!==v(e))?L&&e.req&&e.aborted&&n.nextTick(J):n.nextTick(J);const q=()=>{o=O,e.removeListener("aborted",K),e.removeListener("complete",B),e.removeListener("abort",K),e.removeListener("request",G),e.req&&e.req.removeListener("finish",B),e.removeListener("end",U),e.removeListener("close",U),e.removeListener("finish",B),e.removeListener("end",W),e.removeListener("error",$),e.removeListener("close",K)};if(t.signal&&!V){const s=()=>{const r=o;q(),r.call(e,new i(void 0,{cause:t.signal.reason}))};if(t.signal.aborted)n.nextTick(s);else{k=k||r(6017).addAbortListener;const n=k(t.signal,s),i=o;o=l(((...t)=>{n[y](),i.apply(e,t)}))}}return q}e.exports=F,e.exports.finished=function(e,t){var r;let n=!1;return null===t&&(t=c),null!==(r=t)&&void 0!==r&&r.cleanup&&(f(t.cleanup,"cleanup"),n=t.cleanup),new p(((r,i)=>{const o=F(e,t,(e=>{n&&o(),e?i(e):r()}))}))}},333:function(e,t,r){"use strict";const n=r(5606),{PromisePrototypeThen:i,SymbolAsyncIterator:o,SymbolIterator:s}=r(4641),{Buffer:a}=r(8287),{ERR_INVALID_ARG_TYPE:c,ERR_STREAM_NULL_VALUES:l}=r(8526).codes;e.exports=function(e,t,r){let u,d;if("string"==typeof t||t instanceof a)return new e({objectMode:!0,...r,read(){this.push(t),this.push(null)}});if(t&&t[o])d=!0,u=t[o]();else{if(!t||!t[s])throw new c("iterable",["Iterable"],t);d=!1,u=t[s]()}const h=new e({objectMode:!0,highWaterMark:1,...r});let f=!1;return h._read=function(){f||(f=!0,async function(){for(;;){try{const{value:e,done:t}=d?await u.next():u.next();if(t)h.push(null);else{const t=e&&"function"==typeof e.then?await e:e;if(null===t)throw f=!1,new l;if(h.push(t))continue;f=!1}}catch(e){h.destroy(e)}break}}())},h._destroy=function(e,t){i(async function(e){const t=null!=e,r="function"==typeof u.throw;if(t&&r){const{value:t,done:r}=await u.throw(e);if(await t,r)return}if("function"==typeof u.return){const{value:e}=await u.return();await e}}(e),(()=>n.nextTick(t,e)),(r=>n.nextTick(t,r||e)))},h}},334:function(e,t,r){"use strict";const{ArrayIsArray:n,ObjectSetPrototypeOf:i}=r(4641),{EventEmitter:o}=r(7007);function s(e){o.call(this,e)}function a(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?n(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}i(s.prototype,o.prototype),i(s,o),s.prototype.pipe=function(e,t){const r=this;function n(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function i(){r.readable&&r.resume&&r.resume()}r.on("data",n),e.on("drain",i),e._isStdio||t&&!1===t.end||(r.on("end",c),r.on("close",l));let s=!1;function c(){s||(s=!0,e.end())}function l(){s||(s=!0,"function"==typeof e.destroy&&e.destroy())}function u(e){d(),0===o.listenerCount(this,"error")&&this.emit("error",e)}function d(){r.removeListener("data",n),e.removeListener("drain",i),r.removeListener("end",c),r.removeListener("close",l),r.removeListener("error",u),e.removeListener("error",u),r.removeListener("end",d),r.removeListener("close",d),e.removeListener("close",d)}return a(r,"error",u),a(e,"error",u),r.on("end",d),r.on("close",d),e.on("close",d),e.emit("pipe",r),e},e.exports={Stream:s,prependListener:a}},1284:function(e,t,r){"use strict";const n=globalThis.AbortController||r(5568).AbortController,{codes:{ERR_INVALID_ARG_VALUE:i,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:s,ERR_OUT_OF_RANGE:a},AbortError:c}=r(8526),{validateAbortSignal:l,validateInteger:u,validateObject:d}=r(2224),h=r(4641).Symbol("kWeak"),f=r(4641).Symbol("kResistStopPropagation"),{finished:p}=r(9365),g=r(8489),{addAbortSignalNoValidate:y}=r(810),{isWritable:m,isNodeStream:v}=r(136),{deprecate:b}=r(6017),{ArrayPrototypePush:w,Boolean:_,MathFloor:S,Number:E,NumberIsNaN:A,Promise:R,PromiseReject:I,PromiseResolve:T,PromisePrototypeThen:x,Symbol:P}=r(4641),C=P("kEmpty"),k=P("kEof");function O(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal");let n=1;null!=(null==t?void 0:t.concurrency)&&(n=S(t.concurrency));let i=n-1;return null!=(null==t?void 0:t.highWaterMark)&&(i=S(t.highWaterMark)),u(n,"options.concurrency",1),u(i,"options.highWaterMark",0),i+=n,async function*(){const o=r(6017).AbortSignalAny([null==t?void 0:t.signal].filter(_)),s=this,a=[],l={signal:o};let u,d,h=!1,f=0;function p(){h=!0,g()}function g(){f-=1,y()}function y(){d&&!h&&f=i||f>=n)&&await new R((e=>{d=e}))}a.push(k)}catch(e){const t=I(e);x(t,g,p),a.push(t)}finally{h=!0,u&&(u(),u=null)}}();try{for(;;){for(;a.length>0;){const e=await a[0];if(e===k)return;if(o.aborted)throw new c;e!==C&&(yield e),a.shift(),y()}await new R((e=>{u=e}))}}finally{h=!0,d&&(d(),d=null)}}.call(this)}async function F(e,t=void 0){for await(const r of N.call(this,e,t))return!0;return!1}function N(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return O.call(this,(async function(t,r){return await e(t,r)?t:C}),t)}class D extends s{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}function L(e){if(e=E(e),A(e))return 0;if(e<0)throw new a("number",">= 0",e);return e}e.exports.streamReturningOperators={asIndexedPairs:b((function(e=void 0){return null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(e.signal,"options.signal"),async function*(){let t=0;for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new c({cause:e.signal.reason});yield[t++,n]}}.call(this)}),"readable.asIndexedPairs will be removed in a future version."),drop:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=L(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;e--<=0&&(yield r)}}.call(this)},filter:N,flatMap:function(e,t){const r=O.call(this,e,t);return async function*(){for await(const e of r)yield*e}.call(this)},map:O,take:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=L(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;if(e-- >0&&(yield r),e<=0)return}}.call(this)},compose:function(e,t){if(null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),v(e)&&!m(e))throw new i("stream",e,"must be writable");const r=g(this,e);return null!=t&&t.signal&&y(t.signal,r),r}},e.exports.promiseReturningOperators={every:async function(e,t=void 0){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return!await F.call(this,(async(...t)=>!await e(...t)),t)},forEach:async function(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);for await(const r of O.call(this,(async function(t,r){return await e(t,r),C}),t));},reduce:async function(e,t,r){var i;if("function"!=typeof e)throw new o("reducer",["Function","AsyncFunction"],e);null!=r&&d(r,"options"),null!=(null==r?void 0:r.signal)&&l(r.signal,"options.signal");let s=arguments.length>1;if(null!=r&&null!==(i=r.signal)&&void 0!==i&&i.aborted){const e=new c(void 0,{cause:r.signal.reason});throw this.once("error",(()=>{})),await p(this.destroy(e)),e}const a=new n,u=a.signal;if(null!=r&&r.signal){const e={once:!0,[h]:this,[f]:!0};r.signal.addEventListener("abort",(()=>a.abort()),e)}let g=!1;try{for await(const n of this){var y;if(g=!0,null!=r&&null!==(y=r.signal)&&void 0!==y&&y.aborted)throw new c;s?t=await e(t,n,{signal:u}):(t=n,s=!0)}if(!g&&!s)throw new D}finally{a.abort()}return t},toArray:async function(e){null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(e.signal,"options.signal");const t=[];for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new c(void 0,{cause:e.signal.reason});w(t,n)}return t},some:F,find:async function(e,t){for await(const r of N.call(this,e,t))return r}}},2091:function(e,t,r){"use strict";const{ObjectSetPrototypeOf:n}=r(4641);e.exports=o;const i=r(8649);function o(e){if(!(this instanceof o))return new o(e);i.call(this,e)}n(o.prototype,i.prototype),n(o,i),o.prototype._transform=function(e,t,r){r(null,e)}},8431:function(e,t,r){const n=r(5606),{ArrayIsArray:i,Promise:o,SymbolAsyncIterator:s,SymbolDispose:a}=r(4641),c=r(9365),{once:l}=r(6017),u=r(7647),d=r(3559),{aggregateTwoErrors:h,codes:{ERR_INVALID_ARG_TYPE:f,ERR_INVALID_RETURN_VALUE:p,ERR_MISSING_ARGS:g,ERR_STREAM_DESTROYED:y,ERR_STREAM_PREMATURE_CLOSE:m},AbortError:v}=r(8526),{validateFunction:b,validateAbortSignal:w}=r(2224),{isIterable:_,isReadable:S,isReadableNodeStream:E,isNodeStream:A,isTransformStream:R,isWebStream:I,isReadableStream:T,isReadableFinished:x}=r(136),P=globalThis.AbortController||r(5568).AbortController;let C,k,O;function F(e,t,r){let n=!1;return e.on("close",(()=>{n=!0})),{destroy:t=>{n||(n=!0,u.destroyer(e,t||new y("pipe")))},cleanup:c(e,{readable:t,writable:r},(e=>{n=!e}))}}function N(e){if(_(e))return e;if(E(e))return async function*(e){k||(k=r(3125)),yield*k.prototype[s].call(e)}(e);throw new f("val",["Readable","Iterable","AsyncIterable"],e)}async function D(e,t,r,{end:n}){let i,s=null;const a=e=>{if(e&&(i=e),s){const e=s;s=null,e()}},l=()=>new o(((e,t)=>{i?t(i):s=()=>{i?t(i):e()}}));t.on("drain",a);const u=c(t,{readable:!1},a);try{t.writableNeedDrain&&await l();for await(const r of e)t.write(r)||await l();n&&(t.end(),await l()),r()}catch(e){r(i!==e?h(i,e):e)}finally{u(),t.off("drain",a)}}async function L(e,t,r,{end:n}){R(t)&&(t=t.writable);const i=t.getWriter();try{for await(const t of e)await i.ready,i.write(t).catch((()=>{}));await i.ready,n&&await i.close(),r()}catch(e){try{await i.abort(e),r(e)}catch(e){r(e)}}}function U(e,t,o){if(1===e.length&&i(e[0])&&(e=e[0]),e.length<2)throw new g("streams");const s=new P,c=s.signal,l=null==o?void 0:o.signal,u=[];function h(){B(new v)}let y,m,b;w(l,"options.signal"),O=O||r(6017).addAbortListener,l&&(y=O(l,h));const x=[];let k,U=0;function M(e){B(e,0==--U)}function B(e,r){var i;if(!e||m&&"ERR_STREAM_PREMATURE_CLOSE"!==m.code||(m=e),m||r){for(;x.length;)x.shift()(m);null===(i=y)||void 0===i||i[a](),s.abort(),r&&(m||u.forEach((e=>e())),n.nextTick(t,m,b))}}for(let V=0;V0,q=J||!1!==(null==o?void 0:o.end),z=V===e.length-1;if(A(K)){if(q){const{destroy:Y,cleanup:Q}=F(K,J,G);x.push(Y),S(K)&&z&&u.push(Q)}function H(e){e&&"AbortError"!==e.name&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code&&M(e)}K.on("error",H),S(K)&&z&&u.push((()=>{K.removeListener("error",H)}))}if(0===V)if("function"==typeof K){if(k=K({signal:c}),!_(k))throw new p("Iterable, AsyncIterable or Stream","source",k)}else k=_(K)||E(K)||R(K)?K:d.from(K);else if("function"==typeof K){var W;if(k=R(k)?N(null===(W=k)||void 0===W?void 0:W.readable):N(k),k=K(k,{signal:c}),J){if(!_(k,!0))throw new p("AsyncIterable",`transform[${V-1}]`,k)}else{var $;C||(C=r(2091));const X=new C({objectMode:!0}),Z=null===($=k)||void 0===$?void 0:$.then;if("function"==typeof Z)U++,Z.call(k,(e=>{b=e,null!=e&&X.write(e),q&&X.end(),n.nextTick(M)}),(e=>{X.destroy(e),n.nextTick(M,e)}));else if(_(k,!0))U++,D(k,X,M,{end:q});else{if(!T(k)&&!R(k))throw new p("AsyncIterable or Promise","destination",k);{const re=k.readable||k;U++,D(re,X,M,{end:q})}}k=X;const{destroy:ee,cleanup:te}=F(k,!1,!0);x.push(ee),z&&u.push(te)}}else if(A(K)){if(E(k)){U+=2;const ne=j(k,K,M,{end:q});S(K)&&z&&u.push(ne)}else if(R(k)||T(k)){const ie=k.readable||k;U++,D(ie,K,M,{end:q})}else{if(!_(k))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],k);U++,D(k,K,M,{end:q})}k=K}else if(I(K)){if(E(k))U++,L(N(k),K,M,{end:q});else if(T(k)||_(k))U++,L(k,K,M,{end:q});else{if(!R(k))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],k);U++,L(k.readable,K,M,{end:q})}k=K}else k=d.from(K)}return(null!=c&&c.aborted||null!=l&&l.aborted)&&n.nextTick(h),k}function j(e,t,r,{end:i}){let o=!1;if(t.on("close",(()=>{o||r(new m)})),e.pipe(t,{end:!1}),i){function s(){o=!0,t.end()}x(e)?n.nextTick(s):e.once("end",s)}else r();return c(e,{readable:!0,writable:!1},(t=>{const n=e._readableState;t&&"ERR_STREAM_PREMATURE_CLOSE"===t.code&&n&&n.ended&&!n.errored&&!n.errorEmitted?e.once("end",r).once("error",r):r(t)})),c(t,{readable:!1,writable:!0},r)}e.exports={pipelineImpl:U,pipeline:function(...e){return U(e,l(function(e){return b(e[e.length-1],"streams[stream.length - 1]"),e.pop()}(e)))}}},3125:function(e,t,r){const n=r(5606),{ArrayPrototypeIndexOf:i,NumberIsInteger:o,NumberIsNaN:s,NumberParseInt:a,ObjectDefineProperties:c,ObjectKeys:l,ObjectSetPrototypeOf:u,Promise:d,SafeSet:h,SymbolAsyncDispose:f,SymbolAsyncIterator:p,Symbol:g}=r(4641);e.exports=G,G.ReadableState=J;const{EventEmitter:y}=r(7007),{Stream:m,prependListener:v}=r(334),{Buffer:b}=r(8287),{addAbortSignal:w}=r(810),_=r(9365);let S=r(6017).debuglog("stream",(e=>{S=e}));const E=r(5586),A=r(7647),{getHighWaterMark:R,getDefaultHighWaterMark:I}=r(3920),{aggregateTwoErrors:T,codes:{ERR_INVALID_ARG_TYPE:x,ERR_METHOD_NOT_IMPLEMENTED:P,ERR_OUT_OF_RANGE:C,ERR_STREAM_PUSH_AFTER_EOF:k,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:O},AbortError:F}=r(8526),{validateObject:N}=r(2224),D=g("kPaused"),{StringDecoder:L}=r(6600),U=r(333);u(G.prototype,m.prototype),u(G,m);const j=()=>{},{errorOrDestroy:M}=A,B=1,H=16,W=32,$=2048,V=4096;function K(e){return{enumerable:!1,get(){return!!(this.state&e)},set(t){t?this.state|=e:this.state&=~e}}}function J(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(3559)),this.state=$|V|H|W,e&&e.objectMode&&(this.state|=B),n&&e&&e.readableObjectMode&&(this.state|=B),this.highWaterMark=e?R(this,e,"readableHighWaterMark",n):I(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[D]=null,e&&!1===e.emitClose&&(this.state&=~$),e&&!1===e.autoDestroy&&(this.state&=~V),this.errored=null,this.defaultEncoding=e&&e.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,e&&e.encoding&&(this.decoder=new L(e.encoding),this.encoding=e.encoding)}function G(e){if(!(this instanceof G))return new G(e);const t=this instanceof r(3559);this._readableState=new J(e,this,t),e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.construct&&(this._construct=e.construct),e.signal&&!t&&w(e.signal,this)),m.call(this,e),A.construct(this,(()=>{this._readableState.needReadable&&Z(this,this._readableState)}))}function q(e,t,r,n){S("readableAddChunk",t);const i=e._readableState;let o;if(i.state&B||("string"==typeof t?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?t=b.from(t,r).toString(i.encoding):(t=b.from(t,r),r=""))):t instanceof b?r="":m._isUint8Array(t)?(t=m._uint8ArrayToBuffer(t),r=""):null!=t&&(o=new x("chunk",["string","Buffer","Uint8Array"],t))),o)M(e,o);else if(null===t)i.state&=-9,function(e,t){if(S("onEofChunk"),!t.ended){if(t.decoder){const e=t.decoder.end();e&&e.length&&(t.buffer.push(e),t.length+=t.objectMode?1:e.length)}t.ended=!0,t.sync?Q(e):(t.needReadable=!1,t.emittedReadable=!0,X(e))}}(e,i);else if(i.state&B||t&&t.length>0)if(n)if(4&i.state)M(e,new O);else{if(i.destroyed||i.errored)return!1;z(e,i,t,!0)}else if(i.ended)M(e,new k);else{if(i.destroyed||i.errored)return!1;i.state&=-9,i.decoder&&!r?(t=i.decoder.write(t),i.objectMode||0!==t.length?z(e,i,t,!1):Z(e,i)):z(e,i,t,!1)}else n||(i.state&=-9,Z(e,i));return!i.ended&&(i.length0?(65536&t.state?t.awaitDrainWriters.clear():t.awaitDrainWriters=null,t.dataEmitted=!0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),64&t.state&&Q(e)),Z(e,t)}function Y(e,t){return e<=0||0===t.length&&t.ended?0:t.state&B?1:s(e)?t.flowing&&t.length?t.buffer.first().length:t.length:e<=t.length?e:t.ended?t.length:0}function Q(e){const t=e._readableState;S("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(S("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(X,e))}function X(e){const t=e._readableState;S("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||t.errored||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,ie(e)}function Z(e,t){!t.readingMore&&t.constructed&&(t.readingMore=!0,n.nextTick(ee,e,t))}function ee(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!1===t[D]?t.flowing=!0:e.listenerCount("data")>0?e.resume():t.readableListening||(t.flowing=null)}function re(e){S("readable nexttick read 0"),e.read(0)}function ne(e,t){S("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),ie(e),t.flowing&&!t.reading&&e.read(0)}function ie(e){const t=e._readableState;for(S("flow",t.flowing);t.flowing&&null!==e.read(););}function oe(e,t){"function"!=typeof e.read&&(e=G.wrap(e,{objectMode:!0}));const r=async function*(e,t){let r,n=j;function i(t){this===e?(n(),n=j):n=t}e.on("readable",i);const o=_(e,{writable:!1},(e=>{r=e?T(r,e):null,n(),n=j}));try{for(;;){const t=e.destroyed?null:e.read();if(null!==t)yield t;else{if(r)throw r;if(null===r)return;await new d(i)}}}catch(e){throw r=T(r,e),r}finally{!r&&!1===(null==t?void 0:t.destroyOnReturn)||void 0!==r&&!e._readableState.autoDestroy?(e.off("readable",i),o()):A.destroyer(e,null)}}(e,t);return r.stream=e,r}function se(e,t){if(0===t.length)return null;let r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}function ae(e){const t=e._readableState;S("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(ce,t,e))}function ce(e,t){if(S("endReadableNT",e.endEmitted,e.length),!e.errored&&!e.closeEmitted&&!e.endEmitted&&0===e.length)if(e.endEmitted=!0,t.emit("end"),t.writable&&!1===t.allowHalfOpen)n.nextTick(le,t);else if(e.autoDestroy){const e=t._writableState;(!e||e.autoDestroy&&(e.finished||!1===e.writable))&&t.destroy()}}function le(e){e.writable&&!e.writableEnded&&!e.destroyed&&e.end()}let ue;function de(){return void 0===ue&&(ue={}),ue}c(J.prototype,{objectMode:K(B),ended:K(2),endEmitted:K(4),reading:K(8),constructed:K(H),sync:K(W),needReadable:K(64),emittedReadable:K(128),readableListening:K(256),resumeScheduled:K(512),errorEmitted:K(1024),emitClose:K($),autoDestroy:K(V),destroyed:K(8192),closed:K(16384),closeEmitted:K(32768),multiAwaitDrain:K(65536),readingMore:K(1<<17),dataEmitted:K(1<<18)}),G.prototype.destroy=A.destroy,G.prototype._undestroy=A.undestroy,G.prototype._destroy=function(e,t){t(e)},G.prototype[y.captureRejectionSymbol]=function(e){this.destroy(e)},G.prototype[f]=function(){let e;return this.destroyed||(e=this.readableEnded?null:new F,this.destroy(e)),new d(((t,r)=>_(this,(n=>n&&n!==e?r(n):t(null)))))},G.prototype.push=function(e,t){return q(this,e,t,!1)},G.prototype.unshift=function(e,t){return q(this,e,t,!0)},G.prototype.isPaused=function(){const e=this._readableState;return!0===e[D]||!1===e.flowing},G.prototype.setEncoding=function(e){const t=new L(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;const r=this._readableState.buffer;let n="";for(const e of r)n+=t.write(e);return r.clear(),""!==n&&r.push(n),this._readableState.length=n.length,this},G.prototype.read=function(e){S("read",e),void 0===e?e=NaN:o(e)||(e=a(e,10));const t=this._readableState,r=e;if(e>t.highWaterMark&&(t.highWaterMark=function(e){if(e>1073741824)throw new C("size","<= 1GiB",e);return e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,++e}(e)),0!==e&&(t.state&=-129),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return S("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?ae(this):Q(this),null;if(0===(e=Y(e,t))&&t.ended)return 0===t.length&&ae(this),null;let n,i=!!(64&t.state);if(S("need readable",i),(0===t.length||t.length-e0?se(e,t):null,null===n?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.multiAwaitDrain?t.awaitDrainWriters.clear():t.awaitDrainWriters=null),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&ae(this)),null===n||t.errorEmitted||t.closeEmitted||(t.dataEmitted=!0,this.emit("data",n)),n},G.prototype._read=function(e){throw new P("_read()")},G.prototype.pipe=function(e,t){const r=this,i=this._readableState;1===i.pipes.length&&(i.multiAwaitDrain||(i.multiAwaitDrain=!0,i.awaitDrainWriters=new h(i.awaitDrainWriters?[i.awaitDrainWriters]:[]))),i.pipes.push(e),S("pipe count=%d opts=%j",i.pipes.length,t);const o=t&&!1===t.end||e===n.stdout||e===n.stderr?g:s;function s(){S("onend"),e.end()}let a;i.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",(function t(n,o){S("onunpipe"),n===r&&o&&!1===o.hasUnpiped&&(o.hasUnpiped=!0,S("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),a&&e.removeListener("drain",a),e.removeListener("error",d),e.removeListener("unpipe",t),r.removeListener("end",s),r.removeListener("end",g),r.removeListener("data",u),c=!0,a&&i.awaitDrainWriters&&(!e._writableState||e._writableState.needDrain)&&a())}));let c=!1;function l(){c||(1===i.pipes.length&&i.pipes[0]===e?(S("false write response, pause",0),i.awaitDrainWriters=e,i.multiAwaitDrain=!1):i.pipes.length>1&&i.pipes.includes(e)&&(S("false write response, pause",i.awaitDrainWriters.size),i.awaitDrainWriters.add(e)),r.pause()),a||(a=function(e,t){return function(){const r=e._readableState;r.awaitDrainWriters===t?(S("pipeOnDrain",1),r.awaitDrainWriters=null):r.multiAwaitDrain&&(S("pipeOnDrain",r.awaitDrainWriters.size),r.awaitDrainWriters.delete(t)),r.awaitDrainWriters&&0!==r.awaitDrainWriters.size||!e.listenerCount("data")||e.resume()}}(r,e),e.on("drain",a))}function u(t){S("ondata");const r=e.write(t);S("dest.write",r),!1===r&&l()}function d(t){if(S("onerror",t),g(),e.removeListener("error",d),0===e.listenerCount("error")){const r=e._writableState||e._readableState;r&&!r.errorEmitted?M(e,t):e.emit("error",t)}}function f(){e.removeListener("finish",p),g()}function p(){S("onfinish"),e.removeListener("close",f),g()}function g(){S("unpipe"),r.unpipe(e)}return r.on("data",u),v(e,"error",d),e.once("close",f),e.once("finish",p),e.emit("pipe",r),!0===e.writableNeedDrain?l():i.flowing||(S("pipe resume"),r.resume()),e},G.prototype.unpipe=function(e){const t=this._readableState;if(0===t.pipes.length)return this;if(!e){const e=t.pipes;t.pipes=[],this.pause();for(let t=0;t0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,S("on readable",i.length,i.reading),i.length?Q(this):i.reading||n.nextTick(re,this))),r},G.prototype.addListener=G.prototype.on,G.prototype.removeListener=function(e,t){const r=m.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(te,this),r},G.prototype.off=G.prototype.removeListener,G.prototype.removeAllListeners=function(e){const t=m.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(te,this),t},G.prototype.resume=function(){const e=this._readableState;return e.flowing||(S("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(ne,e,t))}(this,e)),e[D]=!1,this},G.prototype.pause=function(){return S("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(S("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[D]=!0,this},G.prototype.wrap=function(e){let t=!1;e.on("data",(r=>{!this.push(r)&&e.pause&&(t=!0,e.pause())})),e.on("end",(()=>{this.push(null)})),e.on("error",(e=>{M(this,e)})),e.on("close",(()=>{this.destroy()})),e.on("destroy",(()=>{this.destroy()})),this._read=()=>{t&&e.resume&&(t=!1,e.resume())};const r=l(e);for(let t=1;t{t?e?e(t):this.destroy(t):(null!=r&&this.push(r),this.push(null),e&&e())}))}function d(){this._final!==u&&u.call(this)}l.prototype._final=u,l.prototype._transform=function(e,t,r){throw new o("_transform()")},l.prototype._write=function(e,t,r){const n=this._readableState,i=this._writableState,o=n.length;this._transform(e,t,((e,t)=>{e?r(e):(null!=t&&this.push(t),i.ended||o===n.length||n.length{const e=this._writableState;e.writing||W(this,e),V(this,e)}))}function D(e,t,r,i){const o=e._writableState;if("function"==typeof r)i=r,r=o.defaultEncoding;else{if(r){if("buffer"!==r&&!g.isEncoding(r))throw new x(r)}else r=o.defaultEncoding;"function"!=typeof i&&(i=C)}if(null===t)throw new I;if(!o.objectMode)if("string"==typeof t)!1!==o.decodeStrings&&(t=g.from(t,r),r="buffer");else if(t instanceof g)r="buffer";else{if(!p._isUint8Array(t))throw new w("chunk",["string","Buffer","Uint8Array"],t);t=p._uint8ArrayToBuffer(t),r="buffer"}let s;return o.ending?s=new T:o.destroyed&&(s=new A("write")),s?(n.nextTick(i,s),P(e,s,!0),s):(o.pendingcb++,function(e,t,r,n,i){const o=t.objectMode?1:r.length;t.length+=o;const s=t.lengthr.bufferedIndex&&W(e,r),i?null!==r.afterWriteTickInfo&&r.afterWriteTickInfo.cb===o?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:o,stream:e,state:r},n.nextTick(M,r.afterWriteTickInfo)):B(e,r,1,o))):P(e,new S)}function M({stream:e,state:t,count:r,cb:n}){return t.afterWriteTickInfo=null,B(e,t,r,n)}function B(e,t,r,n){for(!t.ending&&!e.destroyed&&0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"));r-- >0;)t.pendingcb--,n();t.destroyed&&H(t),V(e,t)}function H(e){if(e.writing)return;for(let r=e.bufferedIndex;r1&&e._writev){t.pendingcb-=s-1;const n=t.allNoop?C:e=>{for(let t=a;t256?(r.splice(0,a),t.bufferedIndex=0):t.bufferedIndex=a}t.bufferProcessing=!1}function $(e){return e.ending&&!e.destroyed&&e.constructed&&0===e.length&&!e.errored&&0===e.buffered.length&&!e.finished&&!e.writing&&!e.errorEmitted&&!e.closeEmitted}function V(e,t,r){$(t)&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.finalCalled=!0,function(e,t){let r=!1;function i(i){if(r)P(e,null!=i?i:S());else if(r=!0,t.pendingcb--,i){const r=t[k].splice(0);for(let e=0;e{$(t)?K(e,t):t.pendingcb--}),e,t)):$(t)&&(t.pendingcb++,K(e,t))))}function K(e,t){t.pendingcb--,t.finished=!0;const r=t[k].splice(0);for(let e=0;e{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);if(en)throw new _(t,`>= ${r} && <= ${n}`,e)})),P=m(((e,t,r=-2147483648,n=2147483647)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);if(en)throw new _(t,`>= ${r} && <= ${n}`,e)})),C=m(((e,t,r=!1)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);const n=r?1:0,i=4294967295;if(ei)throw new _(t,`>= ${n} && <= ${i}`,e)}));function k(e,t){if("string"!=typeof e)throw new b(t,"string",e)}const O=m(((e,t,r)=>{if(!i(r,e)){const n=o(s(r,(e=>"string"==typeof e?`'${e}'`:p(e))),", ");throw new w(t,e,"must be one of: "+n)}}));function F(e,t){if("boolean"!=typeof e)throw new b(t,"boolean",e)}function N(e,t,r){return null!=e&&h(e,t)?e[t]:r}const D=m(((e,t,r=null)=>{const i=N(r,"allowArray",!1),o=N(r,"allowFunction",!1);if(!N(r,"nullable",!1)&&null===e||!i&&n(e)||"object"!=typeof e&&(!o||"function"!=typeof e))throw new b(t,"Object",e)})),L=m(((e,t)=>{if(null!=e&&"object"!=typeof e&&"function"!=typeof e)throw new b(t,"a dictionary",e)})),U=m(((e,t,r=0)=>{if(!n(e))throw new b(t,"Array",e);if(e.length{if(!R(e))throw new b(t,["Buffer","TypedArray","DataView"],e)})),M=m(((e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new b(t,"AbortSignal",e)})),B=m(((e,t)=>{if("function"!=typeof e)throw new b(t,"Function",e)})),H=m(((e,t)=>{if("function"!=typeof e||A(e))throw new b(t,"Function",e)})),W=m(((e,t)=>{if(void 0!==e)throw new b(t,"undefined",e)})),$=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function V(e,t){if(void 0===e||!f($,e))throw new w(t,e,'must be an array or string of format "; rel=preload; as=style"')}e.exports={isInt32:function(e){return e===(0|e)},isUint32:function(e){return e===e>>>0},parseFileMode:function(e,t,r){if(void 0===e&&(e=r),"string"==typeof e){if(null===f(T,e))throw new w(t,e,"must be a 32-bit unsigned integer or an octal string");e=d(e,8)}return C(e,t),e},validateArray:U,validateStringArray:function(e,t){U(e,t);for(let r=0;rn||(null!=r||null!=n)&&c(e))throw new _(t,`${null!=r?`>= ${r}`:""}${null!=r&&null!=n?" && ":""}${null!=n?`<= ${n}`:""}`,e)},validateObject:D,validateOneOf:O,validatePlainFunction:H,validatePort:function(e,t="Port",r=!0){if("number"!=typeof e&&"string"!=typeof e||"string"==typeof e&&0===y(e).length||+e!=+e>>>0||e>65535||0===e&&!r)throw new v(t,e,r);return 0|e},validateSignalName:function(e,t="signal"){if(k(e,t),void 0===I[e]){if(void 0!==I[g(e)])throw new S(e+" (signals must use all capital letters)");throw new S(e)}},validateString:k,validateUint32:C,validateUndefined:W,validateUnion:function(e,t,r){if(!i(r,e))throw new b(t,`('${o(r,"|")}')`,e)},validateAbortSignal:M,validateLinkHeaderValue:function(e){if("string"==typeof e)return V(e,"hints"),e;if(n(e)){const t=e.length;let r="";if(0===t)return r;for(let n=0;n; rel=preload; as=style"')}}},5721:function(e,t,r){"use strict";const n=r(2825),i=r(5018),o=n.Readable.destroy;e.exports=n.Readable,e.exports._uint8ArrayToBuffer=n._uint8ArrayToBuffer,e.exports._isUint8Array=n._isUint8Array,e.exports.isDisturbed=n.isDisturbed,e.exports.isErrored=n.isErrored,e.exports.isReadable=n.isReadable,e.exports.Readable=n.Readable,e.exports.Writable=n.Writable,e.exports.Duplex=n.Duplex,e.exports.Transform=n.Transform,e.exports.PassThrough=n.PassThrough,e.exports.addAbortSignal=n.addAbortSignal,e.exports.finished=n.finished,e.exports.destroy=n.destroy,e.exports.destroy=o,e.exports.pipeline=n.pipeline,e.exports.compose=n.compose,Object.defineProperty(n,"promises",{configurable:!0,enumerable:!0,get(){return i}}),e.exports.Stream=n.Stream,e.exports.default=e.exports},8526:function(e,t,r){"use strict";const{format:n,inspect:i,AggregateError:o}=r(6017),s=globalThis.AggregateError||o,a=Symbol("kIsNodeError"),c=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,u={};function d(e,t){if(!e)throw new u.ERR_INTERNAL_ASSERTION(t)}function h(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function f(e,t,r){r||(r=Error);class i extends r{constructor(...r){super(function(e,t,r){if("function"==typeof t)return d(t.length<=r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`),t(...r);const i=(t.match(/%[dfijoOs]/g)||[]).length;return d(i===r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${i}).`),0===r.length?t:n(t,...r)}(e,t,r))}toString(){return`${this.name} [${e}]: ${this.message}`}}Object.defineProperties(i.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${e}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),i.prototype.code=e,i.prototype[a]=!0,u[e]=i}function p(e){const t="__node_internal_"+e.name;return Object.defineProperty(e,"name",{value:t}),e}class g extends Error{constructor(e="The operation was aborted",t=void 0){if(void 0!==t&&"object"!=typeof t)throw new u.ERR_INVALID_ARG_TYPE("options","Object",t);super(e,t),this.code="ABORT_ERR",this.name="AbortError"}}f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",((e,t,r)=>{d("string"==typeof e,"'name' must be a string"),Array.isArray(t)||(t=[t]);let n="The ";e.endsWith(" argument")?n+=`${e} `:n+=`"${e}" ${e.includes(".")?"property":"argument"} `,n+="must be ";const o=[],s=[],a=[];for(const e of t)d("string"==typeof e,"All expected entries have to be of type string"),c.includes(e)?o.push(e.toLowerCase()):l.test(e)?s.push(e):(d("object"!==e,'The value "object" should be written as "Object"'),a.push(e));if(s.length>0){const e=o.indexOf("object");-1!==e&&(o.splice(o,e,1),s.push("Object"))}if(o.length>0){switch(o.length){case 1:n+=`of type ${o[0]}`;break;case 2:n+=`one of type ${o[0]} or ${o[1]}`;break;default:{const e=o.pop();n+=`one of type ${o.join(", ")}, or ${e}`}}(s.length>0||a.length>0)&&(n+=" or ")}if(s.length>0){switch(s.length){case 1:n+=`an instance of ${s[0]}`;break;case 2:n+=`an instance of ${s[0]} or ${s[1]}`;break;default:{const e=s.pop();n+=`an instance of ${s.join(", ")}, or ${e}`}}a.length>0&&(n+=" or ")}switch(a.length){case 0:break;case 1:a[0].toLowerCase()!==a[0]&&(n+="an "),n+=`${a[0]}`;break;case 2:n+=`one of ${a[0]} or ${a[1]}`;break;default:{const e=a.pop();n+=`one of ${a.join(", ")}, or ${e}`}}if(null==r)n+=`. Received ${r}`;else if("function"==typeof r&&r.name)n+=`. Received function ${r.name}`;else if("object"==typeof r){var u;null!==(u=r.constructor)&&void 0!==u&&u.name?n+=`. Received an instance of ${r.constructor.name}`:n+=`. Received ${i(r,{depth:-1})}`}else{let e=i(r,{colors:!1});e.length>25&&(e=`${e.slice(0,25)}...`),n+=`. Received type ${typeof r} (${e})`}return n}),TypeError),f("ERR_INVALID_ARG_VALUE",((e,t,r="is invalid")=>{let n=i(t);return n.length>128&&(n=n.slice(0,128)+"..."),`The ${e.includes(".")?"property":"argument"} '${e}' ${r}. Received ${n}`}),TypeError),f("ERR_INVALID_RETURN_VALUE",((e,t,r)=>{var n;return`Expected ${e} to be returned from the "${t}" function but got ${null!=r&&null!==(n=r.constructor)&&void 0!==n&&n.name?`instance of ${r.constructor.name}`:"type "+typeof r}.`}),TypeError),f("ERR_MISSING_ARGS",((...e)=>{let t;d(e.length>0,"At least one arg needs to be specified");const r=e.length;switch(e=(Array.isArray(e)?e:[e]).map((e=>`"${e}"`)).join(" or "),r){case 1:t+=`The ${e[0]} argument`;break;case 2:t+=`The ${e[0]} and ${e[1]} arguments`;break;default:{const r=e.pop();t+=`The ${e.join(", ")}, and ${r} arguments`}}return`${t} must be specified`}),TypeError),f("ERR_OUT_OF_RANGE",((e,t,r)=>{let n;return d(t,'Missing "range" argument'),Number.isInteger(r)&&Math.abs(r)>2**32?n=h(String(r)):"bigint"==typeof r?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=h(n)),n+="n"):n=i(r),`The value of "${e}" is out of range. It must be ${t}. Received ${n}`}),RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:g,aggregateTwoErrors:p((function(e,t){if(e&&t&&e!==t){if(Array.isArray(t.errors))return t.errors.push(e),t;const r=new s([t,e],t.message);return r.code=t.code,r}return e||t})),hideStackFrames:p,codes:u}},4641:function(e){"use strict";e.exports={ArrayIsArray(e){return Array.isArray(e)},ArrayPrototypeIncludes(e,t){return e.includes(t)},ArrayPrototypeIndexOf(e,t){return e.indexOf(t)},ArrayPrototypeJoin(e,t){return e.join(t)},ArrayPrototypeMap(e,t){return e.map(t)},ArrayPrototypePop(e,t){return e.pop(t)},ArrayPrototypePush(e,t){return e.push(t)},ArrayPrototypeSlice(e,t,r){return e.slice(t,r)},Error:Error,FunctionPrototypeCall(e,t,...r){return e.call(t,...r)},FunctionPrototypeSymbolHasInstance(e,t){return Function.prototype[Symbol.hasInstance].call(e,t)},MathFloor:Math.floor,Number:Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(e,t){return Object.defineProperties(e,t)},ObjectDefineProperty(e,t,r){return Object.defineProperty(e,t,r)},ObjectGetOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)},ObjectKeys(e){return Object.keys(e)},ObjectSetPrototypeOf(e,t){return Object.setPrototypeOf(e,t)},Promise:Promise,PromisePrototypeCatch(e,t){return e.catch(t)},PromisePrototypeThen(e,t,r){return e.then(t,r)},PromiseReject(e){return Promise.reject(e)},PromiseResolve(e){return Promise.resolve(e)},ReflectApply:Reflect.apply,RegExpPrototypeTest(e,t){return e.test(t)},SafeSet:Set,String:String,StringPrototypeSlice(e,t,r){return e.slice(t,r)},StringPrototypeToLowerCase(e){return e.toLowerCase()},StringPrototypeToUpperCase(e){return e.toUpperCase()},StringPrototypeTrim(e){return e.trim()},Symbol:Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(e,t,r){return e.set(t,r)},Boolean:Boolean,Uint8Array:Uint8Array}},6017:function(e,t,r){"use strict";const n=r(8287),{kResistStopPropagation:i,SymbolDispose:o}=r(4641),s=globalThis.AbortSignal||r(5568).AbortSignal,a=globalThis.AbortController||r(5568).AbortController,c=Object.getPrototypeOf((async function(){})).constructor,l=globalThis.Blob||n.Blob,u=void 0!==l?function(e){return e instanceof l}:function(e){return!1},d=(e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new ERR_INVALID_ARG_TYPE(t,"AbortSignal",e)};class h extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError("Expected input to be an Array, got "+typeof e);let t="";for(let r=0;r{e=r,t=n})),resolve:e,reject:t}},promisify(e){return new Promise(((t,r)=>{e(((e,...n)=>e?r(e):t(...n)))}))},debuglog(){return function(){}},format(e,...t){return e.replace(/%([sdifj])/g,(function(...[e,r]){const n=t.shift();return"f"===r?n.toFixed(6):"j"===r?JSON.stringify(n):"s"===r&&"object"==typeof n?`${n.constructor!==Object?n.constructor.name:""} {}`.trim():n.toString()}))},inspect(e){switch(typeof e){case"string":if(e.includes("'")){if(!e.includes('"'))return`"${e}"`;if(!e.includes("`")&&!e.includes("${"))return`\`${e}\``}return`'${e}'`;case"number":return isNaN(e)?"NaN":Object.is(e,-0)?String(e):e;case"bigint":return`${String(e)}n`;case"boolean":case"undefined":return String(e);case"object":return"{}"}},types:{isAsyncFunction(e){return e instanceof c},isArrayBufferView(e){return ArrayBuffer.isView(e)}},isBlob:u,deprecate(e,t){return e},addAbortListener:r(7007).addAbortListener||function(e,t){if(void 0===e)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);let r;return d(e,"signal"),(e=>{if("function"!=typeof e)throw new ERR_INVALID_ARG_TYPE("listener","Function",e)})(t),e.aborted?queueMicrotask((()=>t())):(e.addEventListener("abort",t,{__proto__:null,once:!0,[i]:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,[o](){var e;null===(e=r)||void 0===e||e()}}},AbortSignalAny:s.any||function(e){if(1===e.length)return e[0];const t=new a,r=()=>t.abort();return e.forEach((e=>{d(e,"signals"),e.addEventListener("abort",r,{once:!0})})),t.signal.addEventListener("abort",(()=>{e.forEach((e=>e.removeEventListener("abort",r)))}),{once:!0}),t.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")},2825:function(e,t,r){const{Buffer:n}=r(8287),{ObjectDefineProperty:i,ObjectKeys:o,ReflectApply:s}=r(4641),{promisify:{custom:a}}=r(6017),{streamReturningOperators:c,promiseReturningOperators:l}=r(1284),{codes:{ERR_ILLEGAL_CONSTRUCTOR:u}}=r(8526),d=r(8489),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:f}=r(3920),{pipeline:p}=r(8431),{destroyer:g}=r(7647),y=r(9365),m=r(5018),v=r(136),b=e.exports=r(334).Stream;b.isDestroyed=v.isDestroyed,b.isDisturbed=v.isDisturbed,b.isErrored=v.isErrored,b.isReadable=v.isReadable,b.isWritable=v.isWritable,b.Readable=r(3125);for(const S of o(c)){const E=c[S];function w(...e){if(new.target)throw u();return b.Readable.from(s(E,this,e))}i(w,"name",{__proto__:null,value:E.name}),i(w,"length",{__proto__:null,value:E.length}),i(b.Readable.prototype,S,{__proto__:null,value:w,enumerable:!1,configurable:!0,writable:!0})}for(const A of o(l)){const R=l[A];function w(...e){if(new.target)throw u();return s(R,this,e)}i(w,"name",{__proto__:null,value:R.name}),i(w,"length",{__proto__:null,value:R.length}),i(b.Readable.prototype,A,{__proto__:null,value:w,enumerable:!1,configurable:!0,writable:!0})}b.Writable=r(7221),b.Duplex=r(3559),b.Transform=r(8649),b.PassThrough=r(2091),b.pipeline=p;const{addAbortSignal:_}=r(810);b.addAbortSignal=_,b.finished=y,b.destroy=g,b.compose=d,b.setDefaultHighWaterMark=h,b.getDefaultHighWaterMark=f,i(b,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return m}}),i(p,a,{__proto__:null,enumerable:!0,get(){return m.pipeline}}),i(y,a,{__proto__:null,enumerable:!0,get(){return m.finished}}),b.Stream=b,b._isUint8Array=function(e){return e instanceof Uint8Array},b._uint8ArrayToBuffer=function(e){return n.from(e.buffer,e.byteOffset,e.byteLength)}},5018:function(e,t,r){"use strict";const{ArrayPrototypePop:n,Promise:i}=r(4641),{isIterable:o,isNodeStream:s,isWebStream:a}=r(136),{pipelineImpl:c}=r(8431),{finished:l}=r(9365);r(2825),e.exports={finished:l,pipeline:function(...e){return new i(((t,r)=>{let i,l;const u=e[e.length-1];if(u&&"object"==typeof u&&!s(u)&&!o(u)&&!a(u)){const t=n(e);i=t.signal,l=t.end}c(e,((e,n)=>{e?r(e):t(n)}),{signal:i,end:l})}))}}},2692:function(e,t,r){var n=r(8287),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(o(n,t),t.Buffer=s),s.prototype=Object.create(i.prototype),o(i,s),s.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},s.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},6600:function(e,t,r){"use strict";var n=r(2692).Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=l,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=u,this.end=d,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,r=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function l(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function u(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function d(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0?(i>0&&(e.lastNeed=i-1),i):--n=0?(i>0&&(e.lastNeed=i-2),i):--n=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},8518:function(e,t,r){"use strict";r.r(t),r.d(t,{BlankNode:function(){return T},DataFactory:function(){return E},DefaultGraph:function(){return P},EntityIndex:function(){return fe},Lexer:function(){return m},Literal:function(){return I},NamedNode:function(){return R},Parser:function(){return H},Quad:function(){return O},Reasoner:function(){return be},Store:function(){return pe},StoreFactory:function(){return me},StreamParser:function(){return Se},StreamWriter:function(){return Ee},Term:function(){return A},Triple:function(){return O},Util:function(){return n},Variable:function(){return x},Writer:function(){return oe},default:function(){return Ae},getRulesFromDataset:function(){return ve},termFromId:function(){return C},termToId:function(){return k}});var n={};r.r(n),r.d(n,{inDefaultGraph:function(){return z},isBlankNode:function(){return K},isDefaultGraph:function(){return q},isLiteral:function(){return J},isNamedNode:function(){return V},isVariable:function(){return G},prefix:function(){return Y},prefixes:function(){return Q}});var i=r(8287),o=r(9596),s=r.n(o);const a="http://www.w3.org/1999/02/22-rdf-syntax-ns#",c="http://www.w3.org/2001/XMLSchema#",l="http://www.w3.org/2000/10/swap/";var u={xsd:{decimal:`${c}decimal`,boolean:`${c}boolean`,double:`${c}double`,integer:`${c}integer`,string:`${c}string`},rdf:{type:`${a}type`,nil:`${a}nil`,first:`${a}first`,rest:`${a}rest`,langString:`${a}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${l}reify#forSome`,forAll:`${l}reify#forAll`},log:{implies:`${l}log#implies`}};const{xsd:d}=u,h=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,f={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},p=/[\x00-\x20<>\\"\{\}\|\^\`]/,g={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},y=/$0^/;class m{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const e in this)!(e in g)&&this[e]instanceof RegExp&&(this[e]=y)}else this._n3Mode=!1!==e.n3;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let r=this._input,n=r.length;for(;;){let e,s;for(;e=this._newline.exec(r);)this.comments&&(s=this._comment.exec(e[0]))&&i("comment",s[1],"",this._line,e[0].length),r=r.substr(e[0].length,r.length),n=r.length,this._line++;if(!e&&(e=this._whitespace.exec(r))&&(r=r.substr(e[0].length,r.length)),this._endOfFile.test(r))return t&&(this.comments&&(s=this._comment.exec(r))&&i("comment",s[1],"",this._line,r.length),r=null,i("eof","","",this._line,0)),this._input=r;const a=this._line,c=r[0];let l="",u="",h="",f=null,g=0,y=!1;switch(c){case"^":if(r.length<3)break;if("^"!==r[1]){this._n3Mode&&(g=1,l="^");break}if(this._previousMarker="^^",r=r.substr(2),"<"!==r[0]){y=!0;break}case"<":if(f=this._unescapedIri.exec(r))l="IRI",u=f[1];else if(f=this._iri.exec(r)){if(u=this._unescape(f[1]),null===u||p.test(u))return o(this);l="IRI"}else r.length>1&&"<"===r[1]?(l="<<",g=2):this._n3Mode&&r.length>1&&"="===r[1]&&(l="inverse",g=2,u=">");break;case">":r.length>1&&">"===r[1]&&(l=">>",g=2);break;case"_":((f=this._blank.exec(r))||t&&(f=this._blank.exec(`${r} `)))&&(l="blank",h="_",u=f[1]);break;case'"':if(f=this._simpleQuotedString.exec(r))u=f[1];else if(({value:u,matchLength:g}=this._parseLiteral(r)),null===u)return o(this);null===f&&0===g||(l="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(f=this._simpleApostropheString.exec(r))u=f[1];else if(({value:u,matchLength:g}=this._parseLiteral(r)),null===u)return o(this);null===f&&0===g||(l="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(f=this._variable.exec(r))&&(l="var",u=f[0]);break;case"@":"literal"===this._previousMarker&&(f=this._langcode.exec(r))?(l="langcode",u=f[1]):(f=this._keyword.exec(r))&&(l=f[0]);break;case".":if(1===r.length?t:r[1]<"0"||r[1]>"9"){l=".",g=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(f=this._number.exec(r)||t&&(f=this._number.exec(`${r} `)))&&(l="literal",u=f[0],h="string"==typeof f[1]?d.double:"string"==typeof f[2]?d.decimal:d.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(f=this._sparqlKeyword.exec(r))?l=f[0].toUpperCase():y=!0;break;case"f":case"t":(f=this._boolean.exec(r))?(l="literal",u=f[0],h=d.boolean):y=!0;break;case"a":(f=this._shortPredicates.exec(r))?(l="abbreviation",u="a"):y=!0;break;case"=":this._n3Mode&&r.length>1&&(l="abbreviation",">"!==r[1]?(g=1,u="="):(g=2,u=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(g=1,l=c);break;case"{":!this._lineMode&&r.length>=2&&("|"===r[1]?(l="{|",g=2):(l=c,g=1));break;case"|":r.length>=2&&"}"===r[1]&&(l="|}",g=2);break;default:y=!0}if(y&&("@prefix"!==this._previousMarker&&"PREFIX"!==this._previousMarker||!(f=this._prefix.exec(r))?((f=this._prefixed.exec(r))||t&&(f=this._prefixed.exec(`${r} `)))&&(l="prefixed",h=f[1]||"",u=this._unescape(f[2])):(l="prefix",u=f[1]||"")),"^^"===this._previousMarker)switch(l){case"prefixed":l="type";break;case"IRI":l="typeIRI";break;default:l=""}if(!l)return t||!/^'''|^"""/.test(r)&&/\n|\r/.test(r)?o(this):this._input=r;const m=g||f[0].length,v=i(l,u,h,a,m);this.previousToken=v,this._previousMarker=l,r=r.substr(m,r.length)}function i(t,i,o,s,a){const c=r?n-r.length:n,l={type:t,value:i,prefix:o,line:s,start:c,end:c+a};return e(null,l),l}function o(t){e(t._syntaxError(/^\S*/.exec(r)[0]))}}_unescape(e){let t=!1;const r=e.replace(h,((e,r,n,i)=>{if("string"==typeof r)return String.fromCharCode(Number.parseInt(r,16));if("string"==typeof n){let e=Number.parseInt(n,16);return e<=65535?String.fromCharCode(Number.parseInt(n,16)):String.fromCharCode(55296+((e-=65536)>>10),56320+(1023&e))}return i in f?f[i]:(t=!0,"")}));return t?null:r}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],r=t.length;let n=Math.max(this._literalClosingPos,r);for(;(n=e.indexOf(t,n))>0;){let t=0;for(;"\\"===e[n-t-1];)t++;if(t%2==0){const t=e.substring(r,n),i=t.split(/\r\n|\r|\n/).length-1,o=n+r;if(1===r&&0!==i||3===r&&this._lineMode)break;return this._line+=i,{value:this._unescape(t),matchLength:o}}n++}this._literalClosingPos=e.length-r+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\ufeff")?e.substr(1):e}tokenize(e,t){if(this._line=1,"string"==typeof e){if(this._input=this._readStartingBom(e),"function"!=typeof t){const e=[];let t;if(this._tokenizeToEnd(((r,n)=>r?t=r:e.push(n)),!0),t)throw t;return e}s()((()=>this._tokenizeToEnd(t,!0)))}else this._pendingBuffer=null,"function"==typeof e.setEncoding&&e.setEncoding("utf8"),e.on("data",(e=>{null!==this._input&&0!==e.length&&(this._pendingBuffer&&(e=i.Buffer.concat([this._pendingBuffer,e]),this._pendingBuffer=null),128&e[e.length-1]?this._pendingBuffer=e:(void 0===this._input?this._input=this._readStartingBom("string"==typeof e?e:e.toString()):this._input+=e,this._tokenizeToEnd(t,!1)))})),e.on("end",(()=>{"string"==typeof this._input&&this._tokenizeToEnd(t,!0)})),e.on("error",t)}}const{rdf:v,xsd:b}=u;let w,_=0;const S={namedNode:F,blankNode:N,variable:L,literal:D,defaultGraph:function(){return w},quad:U,triple:U,fromTerm:j,fromQuad:M};var E=S;class A{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof A?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}class R extends A{get termType(){return"NamedNode"}}class I extends A{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let t=e.lastIndexOf('"')+1;return t0?"INF":"-INF")))),""===r||r===b.string?new I(`"${e}"`):new I(`"${e}"^^${r}`)}function L(e){return new x(e)}function U(e,t,r,n){return new O(e,t,r,n)}function j(e){if(e instanceof A)return e;switch(e.termType){case"NamedNode":return F(e.value);case"BlankNode":return N(e.value);case"Variable":return L(e.value);case"DefaultGraph":return w;case"Literal":return D(e.value,e.language||e.datatype);case"Quad":return M(e);default:throw new Error(`Unexpected termType: ${e.termType}`)}}function M(e){if(e instanceof O)return e;if("Quad"!==e.termType)throw new Error(`Unexpected termType: ${e.termType}`);return U(j(e.subject),j(e.predicate),j(e.object),j(e.graph))}let B=0;class H{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&$(this,e.factory);const t="string"==typeof e.format?e.format.match(/\w*$/)[0].toLowerCase():"",r=/turtle/.test(t),n=/trig/.test(t),i=/triple/.test(t),o=/quad/.test(t),s=this._n3Mode=/n3/.test(t),a=i||o;(this._supportsNamedGraphs=!(r||s))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||n||i||s),this._supportsRDFStar=""===t||/star|\*$/.test(t),a&&(this._resolveRelativeIRI=e=>null),this._blankNodePrefix="string"!=typeof e.blankNodePrefix?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new m({lineMode:a,n3:s}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){B=0}_setBase(e){if(e){const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}else this._base="",this._basePath=""}_saveContext(e,t,r,n,i){const o=this._n3Mode;this._contextStack.push({type:e,subject:r,predicate:n,object:i,graph:t,inverse:!!o&&this._inversePredicate,blankPrefix:o?this._prefixes._:"",quantified:o?this._quantified:null}),o&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const r=this._contextStack.pop();if(!r||r.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=r.subject,this._predicate=r.predicate,this._object=r.object,this._graph=r.graph,this._n3Mode&&(this._inversePredicate=r.inverse,this._prefixes._=r.blankPrefix,this._quantified=r.quantified)}_readInTopContext(e){switch(e.type){case"eof":return null!==this._graph?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let r;switch(e.type){case"IRI":case"typeIRI":const t=this._resolveIRI(e.value);if(null===t)return this._error("Invalid IRI",e);r=this._factory.namedNode(t);break;case"type":case"prefixed":const n=this._prefixes[e.prefix];if(void 0===n)return this._error(`Undefined prefix "${e.prefix}:"`,e);r=this._factory.namedNode(n+e.value);break;case"blank":r=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":r=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&r.id in this._quantified&&(r=this._quantified[r.id]),r}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(0===e.prefix.length)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if(void 0===(this._subject=this._readEntity(e)))return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return null===this._predicate?this._error(`Unexpected ${t}`,e):(this._subject=null,"]"===t?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return null!==this._predicate?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if(void 0===(this._predicate=this._readEntity(e)))return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(0===e.prefix.length)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if(void 0===(this._object=this._readEntity(e)))return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return"{"===e.type?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return"{"!==e.type?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return"]"===e.type?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if("]"!==e.type)return this._readBlankNodePunctuation(e);null!==this._subject&&this._emit(this._subject,this._predicate,this._object,this._graph);const t=null===this._predicate;return this._restoreContext("blank",e),null!==this._object?this._getContextEndReader():null!==this._predicate?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,r=null,n=this._readListItem;const i=this._subject,o=this._contextStack,s=o[o.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),n=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),0!==o.length&&"list"===o[o.length-1].type&&this._emit(this._subject,this._predicate,this._object,this._graph),null===this._predicate){if(n=this._readPredicate,this._subject===this.RDF_NIL)return n}else if(n=this._getContextEndReader(),this._object===this.RDF_NIL)return n;r=this.RDF_NIL;break;case"literal":0===e.prefix.length?(this._literalValue=e.value,n=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),n=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if(void 0===(t=this._readEntity(e)))return}if(null===r&&(this._subject=r=this._factory.blankNode()),null===i?null===s.predicate?s.subject=r:s.object=r:this._emit(i,this.RDF_REST,r,this._graph),null!==t){if(this._n3Mode&&("IRI"===e.type||"prefixed"===e.type))return this._saveContext("item",this._graph,r,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(r,this.RDF_FIRST,t,this._graph)}return n}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const r=this._readEntity(e);if(void 0===r)return;t=this._factory.literal(this._literalValue,r),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){const r=this._completeLiteral(e);if(r)return this._object=r.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),null===r.token?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(r.token))}_readFormulaTail(e){return"}"!==e.type?this._readPunctuation(e):(null!==this._subject&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),null===this._object?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,r=this._graph;const n=this._subject,i=this._inversePredicate;switch(e.type){case"}":if(null===this._graph)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,t=this._contextStack.length?this._readSubject:this._readInTopContext,i&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const o=this._predicate,s=this._object;this._subject=this._factory.quad(n,o,s,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if("Quad"!==this._subject.termType)return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&null===this._graph&&void 0!==(r=this._readEntity(e))){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(null!==n){const e=this._predicate,t=this._object;i?this._emit(t,e,n,r):this._emit(n,e,t,r)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return"."!==e.type?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return"prefix"!==e.type?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if("IRI"!==e.type)return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){const t="IRI"===e.type&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return"]"!==e.type?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):"."!==e.type?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if(void 0!==(t=this._readEntity(e,!0)))break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(null===this._subject?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return","===e.type?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._contextStack,r=t.length&&t[t.length-1];if(r&&"item"===r.type){const t=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,t,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,r;const n=this._factory.blankNode();if(void 0!==(r=this._readEntity(e)))return null===this._predicate?(t=this._subject,this._subject=n):(t=this._object,this._object=n),this._emit(t,r,n,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let r,n;if(void 0!==(r=this._readEntity(e)))return null===this._predicate?(n=this._subject,this._subject=t):(n=this._object,this._object=t),this._emit(t,r,n,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return">>"!==e.type?this._supportsQuads&&null===this._graph&&void 0!==(this._graph=this._readEntity(e))?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(">>"!==e.type)return this._error(`Expected >> but got ${e.type}`,e);const t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),null===this._subject?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,r,n){this._callback(null,this._factory.quad(e,t,r,n||this.DEFAULTGRAPH))}_error(e,t){const r=new Error(`${e} on line ${t.line}.`);r.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(r),this._callback=W}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return("/"===e[1]?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const t=e.length;let r="",n=-1,i=-1,o=0,s="/";for(;n=i&&(r=r.substr(0,o)),"/"!==s)return`${r}/${e.substr(n+1)}`;o=n+1}}}s=e[++n]}return r+e.substring(o)}parse(e,t,r){let n,i,o;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(n=t.onQuad,i=t.onPrefix,o=t.onComment):(n=t,i=r),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${B++}_`,this._prefixCallback=i||W,this._inversePredicate=!1,this._quantified=Object.create(null),!n){const t=[];let r;if(this._callback=(e,n)=>{e?r=e:n&&t.push(n)},this._lexer.tokenize(e).every((e=>this._readCallback=this._readCallback(e))),r)throw r;return t}let s=(e,t)=>{null!==e?(this._callback(e),this._callback=W):this._readCallback&&(this._readCallback=this._readCallback(t))};o&&(this._lexer.comments=!0,s=(e,t)=>{null!==e?(this._callback(e),this._callback=W):this._readCallback&&("comment"===t.type?o(t.value):this._readCallback=this._readCallback(t))}),this._callback=n,this._lexer.tokenize(e,s)}}function W(){}function $(e,t){e._factory=t,e.DEFAULTGRAPH=t.defaultGraph(),e.RDF_FIRST=t.namedNode(u.rdf.first),e.RDF_REST=t.namedNode(u.rdf.rest),e.RDF_NIL=t.namedNode(u.rdf.nil),e.N3_FORALL=t.namedNode(u.r.forAll),e.N3_FORSOME=t.namedNode(u.r.forSome),e.ABBREVIATIONS={a:t.namedNode(u.rdf.type),"=":t.namedNode(u.owl.sameAs),">":t.namedNode(u.log.implies)},e.QUANTIFIERS_GRAPH=t.namedNode("urn:n3:quantifiers")}function V(e){return!!e&&"NamedNode"===e.termType}function K(e){return!!e&&"BlankNode"===e.termType}function J(e){return!!e&&"Literal"===e.termType}function G(e){return!!e&&"Variable"===e.termType}function q(e){return!!e&&"DefaultGraph"===e.termType}function z(e){return q(e.graph)}function Y(e,t){return Q({"":e.value||e},t)("")}function Q(e,t){const r=Object.create(null);for(const t in e)n(t,e[t]);function n(e,n){if("string"==typeof n){const i=Object.create(null);r[e]=e=>i[e]||(i[e]=t.namedNode(n+e))}else if(!(e in r))throw new Error(`Unknown prefix: ${e}`);return r[e]}return t=t||E,n}$(H.prototype,E);const X=E.defaultGraph(),{rdf:Z,xsd:ee}=u,te=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,re=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,ne={"\\":"\\\\",'"':'\\"',"\t":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class ie extends A{equals(e){return e===this}}class oe{constructor(e,t){if(this._prefixRegex=/$0^/,e&&"function"!=typeof e.write&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=void 0===t.end||!!t.end;else{let e="";this._outputStream={write(t,r,n){e+=t,n&&n()},end:t=>{t&&t(null,e)}},this._endStream=!0}this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine):(this._lineMode=!1,this._graph=X,this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes),t.baseIRI&&(this._baseMatcher=new RegExp(`^${ae(t.baseIRI)}${t.baseIRI.endsWith("/")?"":"[#?]"}`),this._baseLength=t.baseIRI.length))}get _inDefaultGraph(){return X.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_writeQuad(e,t,r,n,i){try{n.equals(this._graph)||(this._write((null===this._subject?"":this._inDefaultGraph?".\n":"\n}\n")+(X.equals(n)?"":`${this._encodeIriOrBlank(n)} {\n`)),this._graph=n,this._subject=null),e.equals(this._subject)?t.equals(this._predicate)?this._write(`, ${this._encodeObject(r)}`,i):this._write(`;\n ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,i):this._write(`${(null===this._subject?"":".\n")+this._encodeSubject(this._subject=e)} ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,i)}catch(e){i&&i(e)}}_writeQuadLine(e,t,r,n,i){delete this._prefixMatch,this._write(this.quadToString(e,t,r,n),i)}quadToString(e,t,r,n){return`${this._encodeSubject(e)} ${this._encodeIriOrBlank(t)} ${this._encodeObject(r)}${n&&n.value?` ${this._encodeIriOrBlank(n)} .\n`:" .\n"}`}quadsToString(e){let t="";for(const r of e)t+=this.quadToString(r.subject,r.predicate,r.object,r.graph);return t}_encodeSubject(e){return"Quad"===e.termType?this._encodeQuad(e):this._encodeIriOrBlank(e)}_encodeIriOrBlank(e){if("NamedNode"!==e.termType)return this._lists&&e.value in this._lists&&(e=this.list(this._lists[e.value])),"id"in e?e.id:`_:${e.value}`;let t=e.value;this._baseMatcher&&this._baseMatcher.test(t)&&(t=t.substr(this._baseLength)),te.test(t)&&(t=t.replace(re,se));const r=this._prefixRegex.exec(t);return r?r[1]?this._prefixIRIs[r[1]]+r[2]:t:`<${t}>`}_encodeLiteral(e){let t=e.value;if(te.test(t)&&(t=t.replace(re,se)),e.language)return`"${t}"@${e.language}`;if(this._lineMode){if(e.datatype.value===ee.string)return`"${t}"`}else switch(e.datatype.value){case ee.string:return`"${t}"`;case ee.boolean:if("true"===t||"false"===t)return t;break;case ee.integer:if(/^[+-]?\d+$/.test(t))return t;break;case ee.decimal:if(/^[+-]?\d*\.\d+$/.test(t))return t;break;case ee.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(t))return t}return`"${t}"^^${this._encodeIriOrBlank(e.datatype)}`}_encodePredicate(e){return e.value===Z.type?"a":this._encodeIriOrBlank(e)}_encodeObject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeQuad({subject:e,predicate:t,object:r,graph:n}){return`<<${this._encodeSubject(e)} ${this._encodePredicate(t)} ${this._encodeObject(r)}${q(n)?"":` ${this._encodeIriOrBlank(n)}`}>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(e,t,r,n,i){void 0===r?this._writeQuad(e.subject,e.predicate,e.object,e.graph,t):"function"==typeof n?this._writeQuad(e,t,r,X,n):this._writeQuad(e,t,r,n||X,i)}addQuads(e){for(let t=0;t.\n`)}if(r){let e="",t="";for(const r in this._prefixIRIs)e+=e?`|${r}`:r,t+=(t?"|":"")+this._prefixIRIs[r];e=ae(e),this._prefixRegex=new RegExp(`^(?:${t})[^/]*$|^(${e})([_a-zA-Z0-9][\\-_a-zA-Z0-9]*)$`)}this._write(r?"\n":"",t)}blank(e,t){let r,n,i=e;switch(void 0===e?i=[]:e.termType?i=[{predicate:e,object:t}]:"length"in e||(i=[e]),n=i.length){case 0:return new ie("[]");case 1:if(r=i[0],!(r.object instanceof ie))return new ie(`[ ${this._encodePredicate(r.predicate)} ${this._encodeObject(r.object)} ]`);default:let t="[";for(let o=0;o{t=null,e(r,n)});if(this._endStream)try{return this._outputStream.end(t)}catch(e){}t&&t()}}function se(e){let t=ne[e];return void 0===t&&(1===e.length?(t=e.charCodeAt(0).toString(16),t="\\u0000".substr(0,6-t.length)+t):(t=(1024*(e.charCodeAt(0)-55296)+e.charCodeAt(1)+9216).toString(16),t="\\U00000000".substr(0,10-t.length)+t)),t}function ae(e){return e.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}var ce=r(5721);const le=Symbol("iter");function ue(e,t,r=4){if(0===r)return Object.assign(e,t);for(const n in t)e[n]=ue(e[n]||Object.create(null),t[n],r-1);return e}function de(e,t,r=4){let n=!1;for(const i in e)if(i in t){const o=0===r?null:de(e[i],t[i],r-1);if(!1!==o)n=n||Object.create(null),n[i]=o;else if(3===r)return!1}return n}function he(e,t,r=4){let n=!1;for(const i in e)if(i in t){if(0!==r){const o=he(e[i],t[i],r-1);if(!1!==o)n=n||Object.create(null),n[i]=o;else if(3===r)return!1}}else n=n||Object.create(null),n[i]=0===r?null:ue({},e[i],r-1);return n}class fe{constructor(e={}){this._id=1,this._ids=Object.create(null),this._ids[""]=1,this._entities=Object.create(null),this._entities[1]="",this._blankNodeIndex=0,this._factory=e.factory||E}_termFromId(e){if("."===e[0]){const t=this._entities,r=e.split(".");return this._factory.quad(this._termFromId(t[r[1]]),this._termFromId(t[r[2]]),this._termFromId(t[r[3]]),r[4]&&this._termFromId(t[r[4]]))}return C(e,this._factory)}_termToNumericId(e){if("Quad"===e.termType){const t=this._termToNumericId(e.subject),r=this._termToNumericId(e.predicate),n=this._termToNumericId(e.object);let i;return t&&r&&n&&(q(e.graph)||(i=this._termToNumericId(e.graph)))&&this._ids[i?`.${t}.${r}.${n}.${i}`:`.${t}.${r}.${n}`]}return this._ids[k(e)]}_termToNewNumericId(e){const t=e&&"Quad"===e.termType?`.${this._termToNewNumericId(e.subject)}.${this._termToNewNumericId(e.predicate)}.${this._termToNewNumericId(e.object)}${q(e.graph)?"":`.${this._termToNewNumericId(e.graph)}`}`:k(e);return this._ids[t]||(this._ids[this._entities[++this._id]=t]=this._id)}createBlankNode(e){let t,r;if(e)for(t=e=`_:${e}`,r=1;this._ids[t];)t=e+r++;else do{t="_:b"+this._blankNodeIndex++}while(this._ids[t]);return this._ids[t]=++this._id,this._entities[this._id]=t,this._factory.blankNode(t.substr(2))}}class pe{constructor(e,t){this._size=0,this._graphs=Object.create(null),t||!e||e[0]||(t=e,e=null),t=t||{},this._factory=t.factory||E,this._entityIndex=t.entityIndex||new fe({factory:this._factory}),this._entities=this._entityIndex._entities,this._termFromId=this._entityIndex._termFromId.bind(this._entityIndex),this._termToNumericId=this._entityIndex._termToNumericId.bind(this._entityIndex),this._termToNewNumericId=this._entityIndex._termToNewNumericId.bind(this._entityIndex),e&&this.addQuads(e)}get size(){let e=this._size;if(null!==e)return e;e=0;const t=this._graphs;let r,n;for(const i in t)for(const o in r=t[i].subjects)for(const t in n=r[o])e+=Object.keys(n[t]).length;return this._size=e}_addToIndex(e,t,r,n){const i=e[t]||(e[t]={}),o=i[r]||(i[r]={}),s=n in o;return s||(o[n]=null),!s}_removeFromIndex(e,t,r,n){const i=e[t],o=i[r];delete o[n];for(const e in o)return;delete i[r];for(const e in i)return;delete e[t]}*_findInIndex(e,t,r,n,i,o,s,a){let c,l,u;const d=this._entities,h=this._termFromId(d[a]),f={subject:null,predicate:null,object:null};t&&((c=e,e={})[t]=c[t]);for(const t in e)if(l=e[t]){f[i]=this._termFromId(d[t]),r&&((c=l,l={})[r]=c[r]);for(const e in l)if(u=l[e]){f[o]=this._termFromId(d[e]);const t=n?n in u?[n]:[]:Object.keys(u);for(let e=0;e{r in t||(t[r]=!0,e(this._termFromId(this._entities[r],this._factory)))}}add(e){return this.addQuad(e),this}addQuad(e,t,r,n){t||(n=e.graph,r=e.object,t=e.predicate,e=e.subject),n=n?this._termToNewNumericId(n):1;let i=this._graphs[n];return i||(i=this._graphs[n]={subjects:{},predicates:{},objects:{}},Object.freeze(i)),e=this._termToNewNumericId(e),t=this._termToNewNumericId(t),r=this._termToNewNumericId(r),!!this._addToIndex(i.subjects,e,t,r)&&(this._addToIndex(i.predicates,t,r,e),this._addToIndex(i.objects,r,e,t),this._size=null,!0)}addQuads(e){for(let t=0;t{this.addQuad(e)})),e}removeQuad(e,t,r,n){t||({subject:e,predicate:t,object:r,graph:n}=e),n=n?this._termToNumericId(n):1;const i=this._graphs;let o,s,a;if(!((e=e&&this._termToNumericId(e))&&(t=t&&this._termToNumericId(t))&&(r=r&&this._termToNumericId(r))&&(o=i[n])&&(s=o.subjects[e])&&(a=s[t])&&r in a))return!1;for(e in this._removeFromIndex(o.subjects,e,t,r),this._removeFromIndex(o.predicates,t,r,e),this._removeFromIndex(o.objects,r,e,t),null!==this._size&&this._size--,o.subjects)return!0;return delete i[n],!0}removeQuads(e){for(let t=0;t{this.removeQuad(e)})),e}removeMatches(e,t,r,n){const i=new ce.Readable({objectMode:!0}),o=this.readQuads(e,t,r,n);return i._read=e=>{for(;--e>=0;){const{done:e,value:t}=o.next();if(e)return void i.push(null);i.push(t)}},this.remove(i)}deleteGraph(e){return this.removeMatches(null,null,null,e)}getQuads(e,t,r,n){return[...this.readQuads(e,t,r,n)]}*readQuads(e,t,r,n){const i=this._getGraphs(n);let o,s,a,c;if(!(e&&!(s=this._termToNumericId(e))||t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r))))for(const e in i)(o=i[e])&&(s?c?yield*this._findInIndex(o.objects,c,s,a,"object","subject","predicate",e):yield*this._findInIndex(o.subjects,s,a,null,"subject","predicate","object",e):a?yield*this._findInIndex(o.predicates,a,c,null,"predicate","object","subject",e):c?yield*this._findInIndex(o.objects,c,null,null,"object","subject","predicate",e):yield*this._findInIndex(o.subjects,null,null,null,"subject","predicate","object",e))}match(e,t,r,n){return new ye(this,e,t,r,n,{entityIndex:this._entityIndex})}countQuads(e,t,r,n){const i=this._getGraphs(n);let o,s,a,c,l=0;if(e&&!(s=this._termToNumericId(e))||t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r)))return 0;for(const n in i)(o=i[n])&&(l+=e?r?this._countInIndex(o.objects,c,s,a):this._countInIndex(o.subjects,s,a,c):t?this._countInIndex(o.predicates,a,c,s):this._countInIndex(o.objects,c,s,a));return l}forEach(e,t,r,n,i){this.some((t=>(e(t,this),!1)),t,r,n,i)}every(e,t,r,n,i){return!this.some((t=>!e(t,this)),t,r,n,i)}some(e,t,r,n,i){for(const o of this.readQuads(t,r,n,i))if(e(o))return!0;return!1}getSubjects(e,t,r){const n=[];return this.forSubjects((e=>{n.push(e)}),e,t,r),n}forSubjects(e,t,r,n){const i=this._getGraphs(n);let o,s,a;if(e=this._uniqueEntities(e),!(t&&!(s=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(o=i[n])&&(s?a?this._loopBy2Keys(o.predicates,s,a,e):this._loopByKey1(o.subjects,s,e):a?this._loopByKey0(o.objects,a,e):this._loop(o.subjects,e))}getPredicates(e,t,r){const n=[];return this.forPredicates((e=>{n.push(e)}),e,t,r),n}forPredicates(e,t,r,n){const i=this._getGraphs(n);let o,s,a;if(e=this._uniqueEntities(e),!(t&&!(s=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(o=i[n])&&(s?a?this._loopBy2Keys(o.objects,a,s,e):this._loopByKey0(o.subjects,s,e):a?this._loopByKey1(o.predicates,a,e):this._loop(o.predicates,e))}getObjects(e,t,r){const n=[];return this.forObjects((e=>{n.push(e)}),e,t,r),n}forObjects(e,t,r,n){const i=this._getGraphs(n);let o,s,a;if(e=this._uniqueEntities(e),!(t&&!(s=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(o=i[n])&&(s?a?this._loopBy2Keys(o.subjects,s,a,e):this._loopByKey1(o.objects,s,e):a?this._loopByKey0(o.predicates,a,e):this._loop(o.objects,e))}getGraphs(e,t,r){const n=[];return this.forGraphs((e=>{n.push(e)}),e,t,r),n}forGraphs(e,t,r,n){for(const i in this._graphs)this.some((t=>(e(t.graph),!0)),t,r,n,this._termFromId(this._entities[i]))}createBlankNode(e){return this._entityIndex.createBlankNode(e)}extractLists({remove:e=!1,ignoreErrors:t=!1}={}){const r={},n=t?()=>!0:(e,t)=>{throw new Error(`${e.value} ${t}`)},i=this.getQuads(null,u.rdf.rest,u.rdf.nil,null),o=e?[...i]:[];return i.forEach((t=>{const i=[];let s,a,c=!1;const l=t.graph;let d=t.subject;for(;d&&!c;){const e=this.getQuads(null,null,d,null),t=this.getQuads(d,null,null,null);let r,h=null,f=null,p=null;for(let i=0;ithis.has(e)));const t=this._graphs,r=e._graphs;let n,i,o,s,a;for(const e in r){if(!(n=t[e]))return!1;n=n.subjects;for(const t in i=r[e].subjects){if(!(o=n[t]))return!1;for(const e in s=i[t]){if(!(a=o[e]))return!1;for(const t in s[e])if(!(t in a))return!1}}}return!0}deleteMatches(e,t,r,n){for(const i of this.match(e,t,r,n))this.removeQuad(i);return this}difference(e){if(e&&e instanceof ye&&(e=e.filtered),e===this)return new pe({entityIndex:this._entityIndex});if(e instanceof pe&&e._entityIndex===this._entityIndex){const t=new pe({entityIndex:this._entityIndex}),r=he(this._graphs,e._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter((t=>!e.has(t)))}equals(e){return e instanceof ye&&(e=e.filtered),e===this||this.size===e.size&&this.contains(e)}filter(e){const t=new pe({entityIndex:this._entityIndex});for(const r of this)e(r,this)&&t.add(r);return t}intersection(e){if(e instanceof ye&&(e=e.filtered),e===this){const e=new pe({entityIndex:this._entityIndex});return e._graphs=ue(Object.create(null),this._graphs),e._size=this._size,e}if(e instanceof pe&&this._entityIndex===e._entityIndex){const t=new pe({entityIndex:this._entityIndex}),r=de(e._graphs,this._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter((t=>e.has(t)))}map(e){const t=new pe({entityIndex:this._entityIndex});for(const r of this)t.add(e(r,this));return t}reduce(e,t){const r=this.readQuads();let n=void 0===t?r.next().value:t;for(const t of r)n=e(n,t,this);return n}toArray(){return this.getQuads()}toCanonical(){throw new Error("not implemented")}toStream(){return this.match()}toString(){return(new oe).quadsToString(this)}union(e){const t=new pe({entityIndex:this._entityIndex});return t._graphs=ue(Object.create(null),this._graphs),t._size=this._size,t.addAll(e),t}*[Symbol.iterator](){yield*this.readQuads()}}function ge(e,t,r=0){const n=t[r];if(n&&!(n in e))return!1;let i=!1;for(const o in n?{[n]:e[n]}:e){const n=2===r?null:ge(e[o],t,r+1);!1!==n&&(i=i||Object.create(null),i[o]=n)}return i}class ye extends ce.Readable{constructor(e,t,r,n,i,o){super({objectMode:!0}),Object.assign(this,{n3Store:e,subject:t,predicate:r,object:n,graph:i,options:o})}get filtered(){if(!this._filtered){const{n3Store:e,graph:t,object:r,predicate:n,subject:i}=this,o=this._filtered=new pe({factory:e._factory,entityIndex:this.options.entityIndex});let s,a,c;if(i&&!(s=o._termToNumericId(i))||n&&!(a=o._termToNumericId(n))||r&&!(c=o._termToNumericId(r)))return o;const l=e._getGraphs(t);for(const e in l){let t,r,n;!s&&a?(r=ge(l[e].predicates,[a,c,s]))&&(t=ge(l[e].subjects,[s,a,c]),n=ge(l[e].objects,[c,s,a])):c?(n=ge(l[e].objects,[c,s,a]))&&(t=ge(l[e].subjects,[s,a,c]),r=ge(l[e].predicates,[a,c,s])):(t=ge(l[e].subjects,[s,a,c]))&&(r=ge(l[e].predicates,[a,c,s]),n=ge(l[e].objects,[c,s,a])),t&&(o._graphs[e]={subjects:t,predicates:r,objects:n})}o._size=null}return this._filtered}get size(){return this.filtered.size}_read(e){e>0&&!this[le]&&(this[le]=this[Symbol.iterator]());const t=this[le];for(;--e>=0;){const{done:e,value:r}=t.next();if(e)return void this.push(null);this.push(r)}}addAll(e){return this.filtered.addAll(e)}contains(e){return this.filtered.contains(e)}deleteMatches(e,t,r,n){return this.filtered.deleteMatches(e,t,r,n)}difference(e){return this.filtered.difference(e)}equals(e){return this.filtered.equals(e)}every(e,t,r,n,i){return this.filtered.every(e,t,r,n,i)}filter(e){return this.filtered.filter(e)}forEach(e,t,r,n,i){return this.filtered.forEach(e,t,r,n,i)}import(e){return this.filtered.import(e)}intersection(e){return this.filtered.intersection(e)}map(e){return this.filtered.map(e)}some(e,t,r,n,i){return this.filtered.some(e,t,r,n,i)}toCanonical(){return this.filtered.toCanonical()}toStream(){return this._filtered?this._filtered.toStream():this.n3Store.match(this.subject,this.predicate,this.object,this.graph)}union(e){return this._filtered?this._filtered.union(e):this.n3Store.match(this.subject,this.predicate,this.object,this.graph).addAll(e)}toArray(){return this._filtered?this._filtered.toArray():this.n3Store.getQuads(this.subject,this.predicate,this.object,this.graph)}reduce(e,t){return this.filtered.reduce(e,t)}toString(){return(new oe).quadsToString(this)}add(e){return this.filtered.add(e)}delete(e){return this.filtered.delete(e)}has(e){return this.filtered.has(e)}match(e,t,r,n){return new ye(this.filtered,e,t,r,n,this.options)}*[Symbol.iterator](){yield*this._filtered||this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}}class me{dataset(e){return new pe(e)}}function ve(e){const t=[];for(const{subject:r,object:n}of e.match(null,E.namedNode("http://www.w3.org/2000/10/swap/log#implies"),null,E.defaultGraph())){const i=[...e.match(null,null,null,r)],o=[...e.match(null,null,null,n)];t.push({premise:i,conclusion:o})}return t}class be{constructor(e){this._store=e}_add(e,t,r,n,i){this._store._addToIndex(n.subjects,e,t,r)&&(this._store._addToIndex(n.predicates,t,r,e),this._store._addToIndex(n.objects,r,e,t),i())}_evaluatePremise(e,t,r,n=0){let i,o,s,a,c;const[l,u,d]=e.premise[n].value,h=t[e.premise[n].content],f=!(s=l.value);for(s in f?h:{[s]:h[s]})if(a=h[s]){for(s in f&&(l.value=Number(s)),i=!(s=u.value),i?a:{[s]:a[s]})if(c=a[s]){for(s in i&&(u.value=Number(s)),o=!(s=d.value),o?c:{[s]:c[s]})o&&(d.value=Number(s)),n===e.premise.length-1?e.conclusion.forEach((e=>{this._add(e.subject.value,e.predicate.value,e.object.value,t,(()=>{r(e)}))})):this._evaluatePremise(e,t,r,n+1);o&&(d.value=null)}i&&(u.value=null)}f&&(l.value=null)}_evaluateRules(e,t,r){for(let n=0;n{r.push([e.subject.value,e.predicate.value,e.object.value,t])}))}const i=e=>{e.forEach((e=>{this._add(e.subject.value,e.predicate.value,e.object.value,t,(()=>{n(e)}))}))};let o;for(this._evaluateRules(e,t,n);void 0!==(o=r.pop());){const[e,r,s,a]=o,c=a.basePremise.subject.value;c||(a.basePremise.subject.value=e);const l=a.basePremise.predicate.value;l||(a.basePremise.predicate.value=r);const u=a.basePremise.object.value;u||(a.basePremise.object.value=s),0===a.premise.length?i(a.conclusion):this._evaluatePremise(a,t,n),c||(a.basePremise.subject.value=null),l||(a.basePremise.predicate.value=null),u||(a.basePremise.object.value=null)}}_createRule({premise:e,conclusion:t}){const r={},n=e=>"Variable"===e.termType?r[e.value]=r[e.value]||{}:{value:this._store._termToNewNumericId(e)},i=e=>({subject:n(e.subject),predicate:n(e.predicate),object:n(e.object)});return{premise:e.map((e=>i(e))),conclusion:t.map((e=>i(e))),variables:Object.values(r)}}reason(e){Array.isArray(e)||(e=ve(e)),e=e.map((e=>this._createRule(e)));for(const t of e)for(const r of e)for(let e=0;e{e.value=null}))}}for(const t of e){const e=new Set;t.premise=t.premise.map((t=>we(t,e)))}const t=this._store._getGraphs();for(const r in t)this._reasonGraphNaive(e,t[r]);this._store._size=null}}function we({subject:e,predicate:t,object:r},n){const i=e.value||n.has(e)||(n.add(e),!1),o=t.value||n.has(t)||(n.add(t),!1),s=r.value||n.has(r)||(n.add(r),!1);return!i&&o?{content:"predicates",value:[t,r,e]}:s?{content:"objects",value:[r,e,t]}:{content:"subjects",value:[e,t,r]}}function _e(e,t){return null===e.value&&(e.value=t.value),e.value===t.value}class Se extends ce.Transform{constructor(e){super({decodeStrings:!0}),this._readableState.objectMode=!0;const t=new H(e);let r,n;const i={onQuad:(e,t)=>{e&&this.emit("error",e)||t&&this.push(t)},onPrefix:(e,t)=>{this.emit("prefix",e,t)}};e&&e.comments&&(i.onComment=e=>{this.emit("comment",e)}),t.parse({on:(e,t)=>{switch(e){case"data":r=t;break;case"end":n=t}}},i),this._transform=(e,t,n)=>{r(e),n()},this._flush=e=>{n(),e()}}import(e){return e.on("data",(e=>{this.write(e)})),e.on("end",(()=>{this.end()})),e.on("error",(e=>{this.emit("error",e)})),this}}class Ee extends ce.Transform{constructor(e){super({encoding:"utf8",writableObjectMode:!0});const t=this._writer=new oe({write:(e,t,r)=>{this.push(e),r&&r()},end:e=>{this.push(null),e&&e()}},e);this._transform=(e,r,n)=>{t.addQuad(e,n)},this._flush=e=>{t.end(e)}}import(e){return e.on("data",(e=>{this.write(e)})),e.on("end",(()=>{this.end()})),e.on("error",(e=>{this.emit("error",e)})),e.on("prefix",((e,t)=>{this._writer.addPrefix(e,t)})),this}}var Ae={Lexer:m,Parser:H,Writer:oe,Store:pe,StoreFactory:me,EntityIndex:fe,StreamParser:Se,StreamWriter:Ee,Util:n,Reasoner:be,DataFactory:E,Term:A,NamedNode:R,Literal:I,BlankNode:T,Variable:x,DefaultGraph:P,Quad:O,Triple:O,termFromId:C,termToId:k}},5606:function(e){var t,r,n=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function s(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:i}catch(e){t=i}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var a,c=[],l=!1,u=-1;function d(){l&&a&&(l=!1,a.length?c=a.concat(c):u=-1,c.length&&h())}function h(){if(!l){var e=s(d);l=!0;for(var t=c.length;t;){for(a=c,c=[];++u1)for(var r=1;r(n||(n=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0)))},7793:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(9931),t),i(r(8483),t),i(r(2142),t),i(r(2426),t),i(r(3988),t),i(r(6754),t),i(r(8401),t)},9931:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BlankNode=void 0,t.BlankNode=class{constructor(e){this.termType="BlankNode",this.value=e}equals(e){return!!e&&"BlankNode"===e.termType&&e.value===this.value}}},8483:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DataFactory=void 0;const n=r(9931),i=r(2142),o=r(2426),s=r(3988),a=r(6754),c=r(8401);let l=0;t.DataFactory=class{constructor(e){this.blankNodeCounter=0,e=e||{},this.blankNodePrefix=e.blankNodePrefix||`df_${l++}_`}namedNode(e){return new s.NamedNode(e)}blankNode(e){return new n.BlankNode(e||`${this.blankNodePrefix}${this.blankNodeCounter++}`)}literal(e,t){return new o.Literal(e,t)}variable(e){return new c.Variable(e)}defaultGraph(){return i.DefaultGraph.INSTANCE}quad(e,t,r,n){return new a.Quad(e,t,r,n||this.defaultGraph())}fromTerm(e){switch(e.termType){case"NamedNode":return this.namedNode(e.value);case"BlankNode":return this.blankNode(e.value);case"Literal":return e.language?this.literal(e.value,e.language):e.datatype.equals(o.Literal.XSD_STRING)?this.literal(e.value):this.literal(e.value,this.fromTerm(e.datatype));case"Variable":return this.variable(e.value);case"DefaultGraph":return this.defaultGraph();case"Quad":return this.quad(this.fromTerm(e.subject),this.fromTerm(e.predicate),this.fromTerm(e.object),this.fromTerm(e.graph))}}fromQuad(e){return this.fromTerm(e)}resetBlankNodeCounter(){this.blankNodeCounter=0}}},2142:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultGraph=void 0;class r{constructor(){this.termType="DefaultGraph",this.value=""}equals(e){return!!e&&"DefaultGraph"===e.termType}}t.DefaultGraph=r,r.INSTANCE=new r},2426:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Literal=void 0;const n=r(3988);class i{constructor(e,t){this.termType="Literal",this.value=e,"string"==typeof t?(this.language=t,this.datatype=i.RDF_LANGUAGE_STRING):t?(this.language="",this.datatype=t):(this.language="",this.datatype=i.XSD_STRING)}equals(e){return!!e&&"Literal"===e.termType&&e.value===this.value&&e.language===this.language&&this.datatype.equals(e.datatype)}}t.Literal=i,i.RDF_LANGUAGE_STRING=new n.NamedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),i.XSD_STRING=new n.NamedNode("http://www.w3.org/2001/XMLSchema#string")},3988:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NamedNode=void 0,t.NamedNode=class{constructor(e){this.termType="NamedNode",this.value=e}equals(e){return!!e&&"NamedNode"===e.termType&&e.value===this.value}}},6754:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Quad=void 0,t.Quad=class{constructor(e,t,r,n){this.termType="Quad",this.value="",this.subject=e,this.predicate=t,this.object=r,this.graph=n}equals(e){return!!e&&("Quad"===e.termType||!e.termType)&&this.subject.equals(e.subject)&&this.predicate.equals(e.predicate)&&this.object.equals(e.object)&&this.graph.equals(e.graph)}}},8401:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Variable=void 0,t.Variable=class{constructor(e){this.termType="Variable",this.value=e}equals(e){return!!e&&"Variable"===e.termType&&e.value===this.value}}},742:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(4806),t)},4806:function(e,t){"use strict";function r(e){const t=[];let r=0;for(;re.join(""))).join("/")}function n(e,t){let n=t+1;t>=0?"/"===e[t+1]&&"/"===e[t+2]&&(n=t+3):"/"===e[0]&&"/"===e[1]&&(n=2);const i=e.indexOf("/",n);return i<0?e:e.substr(0,i)+r(e.substr(i))}function i(e){return!e||"#"===e||"?"===e||"/"===e}Object.defineProperty(t,"__esModule",{value:!0}),t.removeDotSegmentsOfPath=t.removeDotSegments=t.resolve=void 0,t.resolve=function(e,t){const i=(t=t||"").indexOf("#");if(i>0&&(t=t.substr(0,i)),!e.length){if(t.indexOf(":")<0)throw new Error(`Found invalid baseIRI '${t}' for value '${e}'`);return t}if(e.startsWith("?")){const r=t.indexOf("?");return r>0&&(t=t.substr(0,r)),t+e}if(e.startsWith("#"))return t+e;if(!t.length){const t=e.indexOf(":");if(t<0)throw new Error(`Found invalid relative IRI '${e}' for a missing baseIRI`);return n(e,t)}const o=e.indexOf(":");if(o>=0)return n(e,o);const s=t.indexOf(":");if(s<0)throw new Error(`Found invalid baseIRI '${t}' for value '${e}'`);const a=t.substr(0,s+1);if(0===e.indexOf("//"))return a+n(e,o);let c;if(t.indexOf("//",s)===s+1){if(c=t.indexOf("/",s+3),c<0)return t.length>s+3?t+"/"+n(e,o):a+n(e,o)}else if(c=t.indexOf("/",s+1),c<0)return a+n(e,o);if(0===e.indexOf("/"))return t.substr(0,c)+r(e);let l=t.substr(c);const u=l.lastIndexOf("/");return u>=0&&u({name:e,mode:this.scopeModeMap[e]})))}get scopeParameter(){return this.scopes.map((e=>`${this._scopeNameForParameter(e)}:${e.mode}`)).join(" ")}claim(e,t){if("string"!=typeof e||-1!==e.indexOf("/")||0===e.length)throw new Error("Scope should be a non-empty string without forward slashes");if(!t.match(/^rw?$/))throw new Error("Mode should be either 'r' or 'rw'");this._adjustRootPaths(e),this.scopeModeMap[e]=t}get(e){return this.scopeModeMap[e]}remove(e){const t={};for(const e in this.scopeModeMap)t[e]=this.scopeModeMap[e];this.reset(),delete t[e];for(const e in t)this.claim(e,t[e])}checkPermission(e,t){const r=this.get(e);return r&&("r"===t||"rw"===r)}checkPathPermission(e,t){if(this.checkPermission("*",t))return!0;const r=this._getModuleName(e);return!!this.checkPermission(r,t)}reset(){this.rootPaths=[],this.scopeModeMap={}}_getModuleName(e){if("/"!==e[0])throw new Error("Path should start with a slash");const t=e.replace(/^\/public/,"").match(/^\/([^/]*)\//);return t?t[1]:"*"}_adjustRootPaths(e){"*"in this.scopeModeMap||"*"===e?this.rootPaths=["/"]:e in this.scopeModeMap||(this.rootPaths.push("/"+e+"/"),this.rootPaths.push("/public/"+e+"/"))}_scopeNameForParameter(e){if("*"===e.name&&this.storageType){if("2012.04"===this.storageType)return"";if(this.storageType.match(/remotestorage-0[01]/))return"root"}return e.name}setStorageType(e){this.storageType=e}}t.Access=r,t.default=r},3275:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Authorize=void 0;const o=i(r(3334)),s=r(7746),a=i(r(5503)),c=r(368);let l;function u(e){const t=e||d.getLocation().href,r={};for(const[e,n]of new URL(t).searchParams)r[e]=n;const n=t.indexOf("#");if(-1===n)return r;const i=t.substring(n+1);return i.includes("=")?i.split("&").reduce((function(e,t){const r=t.split("=");if("state"===r[0]&&r[1].match(/rsDiscovery/)){let t=decodeURIComponent(r[1]);const n=t.substr(t.indexOf("rsDiscovery=")).split("&")[0].split("=")[1];e.rsDiscovery=JSON.parse(atob(n)),t=t.replace(new RegExp("&?rsDiscovery="+n),""),t.length>0&&(e.state=t)}else e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]);return e}),r):r}class d{static authorize(e,t){if((0,o.default)("[Authorize] authURL = ",t.authURL,"scope = ",t.scope,"redirectUri = ",t.redirectUri,"clientId = ",t.clientId,"response_type =",t.response_type),!t.scope)throw new Error("Cannot authorize due to undefined or empty scope; did you forget to access.claim()?");if(!(0,s.localStorageAvailable)()&&"remotestorage"===e.backend){t.redirectUri+=t.redirectUri.indexOf("#")>0?"&":"#";const r={userAddress:e.remote.userAddress,href:e.remote.href,storageApi:e.remote.storageApi,properties:e.remote.properties};t.redirectUri+="rsDiscovery="+(0,s.toBase64)(JSON.stringify(r))}const r=function(e){const t=new URL(e.redirectUri);e.state||(e.state=t.hash?t.hash.substring(1):""),e.response_type||(e.response_type="token");const r=new URL(e.authURL);r.searchParams.set("redirect_uri",e.redirectUri.replace(/#.*$/,"")),r.searchParams.set("scope",e.scope),r.searchParams.set("client_id",e.clientId);for(const t of["state","response_type","code_challenge","code_challenge_method","token_access_type"]){const n=e[t];n&&r.searchParams.set(t,n)}return r.href}(t);s.globalContext.cordova?d.openWindow(r,t.redirectUri,"location=yes,clearsessioncache=yes,clearcache=yes").then((t=>{e.remote.configure({token:t.access_token})})):d.setLocation(r)}static refreshAccessToken(e,t,r){return n(this,void 0,void 0,(function*(){var e,n,i;yield t.configure({token:null,tokenType:null});const s=new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:r}),l=yield(0,c.requestWithTimeout)("POST",t.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString(),responseType:"json"});if(200!==(null==l?void 0:l.status))throw yield t.configure({refreshToken:null}),new a.default("refresh token rejected:"+JSON.stringify(l.response));{(0,o.default)(`[Authorize] access token good for ${null===(e=null==l?void 0:l.response)||void 0===e?void 0:e.expires_in} seconds`);const r={token:null===(n=null==l?void 0:l.response)||void 0===n?void 0:n.access_token,tokenType:null===(i=null==l?void 0:l.response)||void 0===i?void 0:i.token_type};if(!r.token)throw new Error(`no access_token in "successful" refresh: ${l.response}`);yield t.configure(r)}}))}static setLocation(e){if("string"==typeof e)document.location.href=e;else{if("object"!=typeof e)throw"Invalid location "+e;document.location=e}}static _rs_supported(){return"undefined"!=typeof document}static _rs_cleanup(e){e.removeEventListener("features-loaded",l)}}t.Authorize=d,d.IMPLIED_FAKE_TOKEN=!1,d.getLocation=function(){return document.location},d.openWindow=function(e,t,r){return new Promise(((n,i)=>{const o=open(e,"_blank",r);function s(){i("Authorization was canceled")}o&&!o.closed?(o.addEventListener("loadstart",(function(e){if(0!==e.url.indexOf(t))return;o.removeEventListener("exit",s),o.close();const r=u(e.url);r?n(r):i("Authorization error")})),o.addEventListener("exit",s)):i("Authorization popup was blocked")}))},d._rs_init=function(e){const t=u();let r;t&&(r=d.getLocation(),r.hash=""),l=function(){let i=!1;if(t){if(t.error)throw"access_denied"===t.error?new a.default("Authorization failed: access denied",{code:"access_denied"}):new a.default(`Authorization failed: ${t.error}`);t.rsDiscovery&&e.remote.configure(t.rsDiscovery),t.access_token&&(e.remote.configure({token:t.access_token}),i=!0),t.remotestorage&&(e.connect(t.remotestorage),i=!0),t.state&&(r=d.getLocation(),d.setLocation(r.href.split("#")[0]+"#"+t.state)),t.code&&(function(t){n(this,void 0,void 0,(function*(){var n,i,s,a;const l=sessionStorage.getItem("remotestorage:codeVerifier");if(!l)return void(0,o.default)("[Authorize] Ignoring OAuth code parameter, because no PKCE code verifier found in sessionStorage");r=d.getLocation();let u=r.origin;"/"!==r.pathname&&(u+=r.pathname);const h=new URLSearchParams({code:t,grant_type:"authorization_code",client_id:e.remote.clientId,redirect_uri:u,code_verifier:l}),f=yield(0,c.requestWithTimeout)("POST",e.remote.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:h.toString(),responseType:"json"});if(200===f.status){(0,o.default)(`[Authorize] access token good for ${null===(n=null==f?void 0:f.response)||void 0===n?void 0:n.expires_in} seconds`);const t={token:null===(i=null==f?void 0:f.response)||void 0===i?void 0:i.access_token,refreshToken:null===(s=null==f?void 0:f.response)||void 0===s?void 0:s.refresh_token,tokenType:null===(a=null==f?void 0:f.response)||void 0===a?void 0:a.token_type};t.token?e.remote.configure(t):e._emit("error",new Error(`no access_token in "successful" response: ${f.response}`)),sessionStorage.removeItem("remotestorage:codeVerifier")}else e._emit("error",new Error(`${f.statusText}: ${f.response}`))}))}(t.code),i=!0),i||e.remote.stopWaitingForToken()}else e.remote.stopWaitingForToken()},e.on("features-loaded",l)},t.default=d},6424:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClient=void 0;const o=i(r(439)),s=i(r(1613)),a=i(r(6491)),c=i(r(93)),l=i(r(7028)),u=r(7746);class d{constructor(e,t){if(this.schemas={configurable:!0,get(){return d.Types.inScope(this.moduleName)}},"/"!==t[t.length-1])throw"Not a folder: "+t;"/"===t&&(this.makePath=e=>("/"===e[0]?"":"/")+e),this.storage=e,this.base=t,this.moduleName=function(e){const t=e.split("/");return e.length>2?t[1]:"root"}(this.base),this.addEvents(["change"]),this.on=this.on.bind(this),e.onChange(this.base,this._fireChange.bind(this))}scope(e){return new d(this.storage,this.makePath(e))}getListing(e,t){return n(this,void 0,void 0,(function*(){if("string"!=typeof e)e="";else if(e.length>0&&!(0,u.isFolder)(e))return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then((e=>404===e.statusCode?{}:e.body))}))}getAll(e,t){return n(this,void 0,void 0,(function*(){if("string"!=typeof e)e="";else if(e.length>0&&!(0,u.isFolder)(e))return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then((r=>{if(404===r.statusCode)return{};if("object"==typeof r.body){const n=Object.keys(r.body);if(0===n.length)return{};const i=n.map((n=>this.storage.get(this.makePath(e+n),t).then((e=>{if("string"==typeof e.body)try{e.body=JSON.parse(e.body)}catch(e){}"object"==typeof e.body&&(r.body[n]=e.body)}))));return Promise.all(i).then((()=>r.body))}}))}))}getFile(e,t){return n(this,void 0,void 0,(function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getFile must be a string"):this.storage.get(this.makePath(e),t).then((e=>({data:e.body,contentType:e.contentType,revision:e.revision})))}))}storeFile(e,t,r){return n(this,void 0,void 0,(function*(){return"string"!=typeof e?Promise.reject("Argument 'mimeType' of baseClient.storeFile must be a string"):"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.storeFile must be a string"):"string"!=typeof r&&"object"!=typeof r?Promise.reject("Argument 'body' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView"):(this.storage.access.checkPathPermission(this.makePath(t),"rw")||console.warn("WARNING: Editing a document to which only read access ('r') was claimed"),this.storage.put(this.makePath(t),r,e).then((e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode))))}))}getObject(e,t){return n(this,void 0,void 0,(function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getObject must be a string"):this.storage.get(this.makePath(e),t).then((t=>{if("object"==typeof t.body)return t.body;if("string"==typeof t.body)try{return JSON.parse(t.body)}catch(t){throw new Error("Not valid JSON: "+this.makePath(e))}else if(void 0!==t.body&&200===t.statusCode)return Promise.reject("Not an object: "+this.makePath(e))}))}))}storeObject(e,t,r){return n(this,void 0,void 0,(function*(){if("string"!=typeof e)return Promise.reject("Argument 'typeAlias' of baseClient.storeObject must be a string");if("string"!=typeof t)return Promise.reject("Argument 'path' of baseClient.storeObject must be a string");if("object"!=typeof r)return Promise.reject("Argument 'object' of baseClient.storeObject must be an object");this._attachType(r,e);try{const e=this.validate(r);if(!e.valid)return Promise.reject(e)}catch(e){return Promise.reject(e)}return this.storage.put(this.makePath(t),JSON.stringify(r),"application/json; charset=UTF-8").then((e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode)))}))}remove(e){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.remove must be a string"):(this.storage.access.checkPathPermission(this.makePath(e),"rw")||console.warn("WARNING: Removing a document to which only read access ('r') was claimed"),this.storage.delete(this.makePath(e)))}getItemURL(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(e=(0,u.cleanPath)(this.makePath(e)),this.storage.remote.href+e):void 0}cache(e,t="ALL"){if("string"!=typeof e)throw"Argument 'path' of baseClient.cache must be a string";if("string"!=typeof t)throw"Argument 'strategy' of baseClient.cache must be a string or undefined";if("FLUSH"!==t&&"SEEN"!==t&&"ALL"!==t)throw'Argument \'strategy\' of baseclient.cache must be one of ["FLUSH", "SEEN", "ALL"]';return this.storage.caching.set(this.makePath(e),t),this}declareType(e,t,r){let n;if(r&&"string"==typeof t)n=t;else if(r||"string"==typeof t){if(!r&&"string"==typeof t)throw new Error("declareType() requires a JSON Schema object to be passed, in order to validate object types/formats")}else r=t,n=this._defaultTypeURI(e);d.Types.declare(this.moduleName,e,n,r)}validate(e){const t=d.Types.getSchema(e["@context"]);if(t)return o.default.validateResult(e,t);throw new a.default(e["@context"])}_defaultTypeURI(e){return"http://remotestorage.io/spec/modules/"+encodeURIComponent(this.moduleName)+"/"+encodeURIComponent(e)}_attachType(e,t){e["@context"]=d.Types.resolveAlias(this.moduleName+"/"+t)||this._defaultTypeURI(t)}makePath(e){return this.base+(e||"")}_fireChange(e){l.default.changeEvents[e.origin]&&(["new","old","lastCommon"].forEach((function(t){if((!e[t+"ContentType"]||/^application\/(.*)json(.*)/.exec(e[t+"ContentType"]))&&"string"==typeof e[t+"Value"])try{e[t+"Value"]=JSON.parse(e[t+"Value"])}catch(e){}})),this._emit("change",e))}static _rs_init(){}}t.BaseClient=d,d.Types=s.default,(0,u.applyMixins)(d,[c.default]),t.default=d},7285:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Caching=void 0;const i=r(7746),o=n(r(3334));class s{constructor(){this.pendingActivations=[],this.reset()}set(e,t){if("string"!=typeof e)throw new Error("path should be a string");if(!(0,i.isFolder)(e))throw new Error("path should be a folder");if(!t.match(/^(FLUSH|SEEN|ALL)$/))throw new Error("strategy should be 'FLUSH', 'SEEN', or 'ALL'");this._rootPaths[e]=t,"ALL"===t&&(this.activateHandler?this.activateHandler(e):this.pendingActivations.push(e))}enable(e){this.set(e,"ALL")}disable(e){this.set(e,"FLUSH")}onActivate(e){(0,o.default)("[Caching] Setting activate handler",e,this.pendingActivations),this.activateHandler=e;for(let t=0;t{const i=l(n[e]);return u(n,t)?r(e):i?{statusCode:200,body:i.body||i.itemsMap,contentType:i.contentType}:{statusCode:404}})):this.getNodes([e]).then((t=>{const r=l(t[e]);if(r){if((0,c.isFolder)(e))for(const e in r.itemsMap)r.itemsMap.hasOwnProperty(e)&&!1===r.itemsMap[e]&&delete r.itemsMap[e];return{statusCode:200,body:r.body||r.itemsMap,contentType:r.contentType}}return{statusCode:404}}))}))}put(e,t,r){return n(this,void 0,void 0,(function*(){const n=(0,c.pathsFromRoot)(e);return this._updateNodes(n,(function(e,n){try{for(let i=0,o=e.length;i0)break}else console.error("Cannot delete non-existing node "+n)}return t}))}flush(e){return this._getAllDescendentPaths(e).then((e=>this.getNodes(e))).then((e=>{for(const t in e){const r=e[t];r&&r.common&&r.local&&this._emitChange({path:r.path,origin:"local",oldValue:!1===r.local.body?void 0:r.local.body,newValue:!1===r.common.body?void 0:r.common.body}),e[t]=void 0}return this.setNodes(e)}))}_emitChange(e){s.default.changeEvents[e.origin]&&this._emit("change",e)}fireInitial(){s.default.changeEvents.local&&this.forAllNodes((e=>{if((0,c.isDocument)(e.path)){const t=l(e);t&&this._emitChange({path:e.path,origin:"local",oldValue:void 0,oldContentType:void 0,newValue:t.body,newContentType:t.contentType})}})).then((()=>{this._emit("local-events-done")}))}onDiff(e){this.diffHandler=e}migrate(e){return"object"!=typeof e||e.common||(e.common={},"string"==typeof e.path?"/"===e.path.substr(-1)&&"object"==typeof e.body&&(e.common.itemsMap=e.body):(e.local||(e.local={}),e.local.body=e.body,e.local.contentType=e.contentType)),e}_updateNodes(e,t){return new Promise(((r,n)=>{this._doUpdateNodes(e,t,{resolve:r,reject:n})}))}_doUpdateNodes(e,t,r){this._updateNodesRunning?this._updateNodesQueued.push({paths:e,cb:t,promise:r}):(this._updateNodesRunning=!0,this.getNodes(e).then((n=>{const i=(0,c.deepClone)(n),o=[];n=t(e,n);for(const e in n){const t=n[e];(0,c.equal)(t,i[e])?delete n[e]:(0,c.isDocument)(e)&&((0,c.equal)(t.local.body,t.local.previousBody)&&t.local.contentType===t.local.previousContentType||o.push({path:e,origin:"window",oldValue:t.local.previousBody,newValue:!1===t.local.body?void 0:t.local.body,oldContentType:t.local.previousContentType,newContentType:t.local.contentType}),delete t.local.previousBody,delete t.local.previousContentType)}this.setNodes(n).then((()=>{this._emitChangeEvents(o),r.resolve({statusCode:200})}))})).then((()=>Promise.resolve()),(e=>{r.reject(e)})).then((()=>{this._updateNodesRunning=!1;const e=this._updateNodesQueued.shift();e&&this._doUpdateNodes(e.paths,e.cb,e.promise)})))}_emitChangeEvents(e){for(let t=0,r=e.length;t{const r=[e],n=l(t[e]),i=Object.keys(n.itemsMap).map((t=>this._getAllDescendentPaths(e+t).then((e=>{for(let t=0,n=e.length;tr))})):Promise.resolve([e])}_getInternals(){return{getLatest:l,makeNode:d,isOutdated:u}}}(0,c.applyMixins)(f,[o.default]),e.exports=f},7028:function(e){"use strict";e.exports={cache:!0,changeEvents:{local:!0,window:!1,remote:!0,conflict:!0},cordovaRedirectUri:void 0,logging:!1,modules:[],backgroundSyncInterval:6e4,disableFeatures:[],discoveryTimeout:5e3,isBackground:!1,requestTimeout:3e4,syncInterval:1e4}},5373:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(4199)),o=n(r(7028)),s=n(r(3334)),a=r(7746);let c;const l="remotestorage:discover";let u={};const d=function(e){return new Promise(((t,r)=>{if(e in u)return t(u[e]);const n=new i.default({tls_only:!1,uri_fallback:!0,request_timeout:o.default.discoveryTimeout});return setTimeout((()=>r(new Error("timed out"))),o.default.discoveryTimeout),n.lookup(e,(function(n,i){if(n)return r(n);if("object"!=typeof i.idx.links.remotestorage||"number"!=typeof i.idx.links.remotestorage.length||i.idx.links.remotestorage.length<=0)return(0,s.default)("[Discover] WebFinger record for "+e+" does not have remotestorage defined in the links section ",JSON.stringify(i.json)),r("WebFinger record for "+e+" does not have remotestorage defined in the links section.");const o=i.idx.links.remotestorage[0],a=o.properties["http://tools.ietf.org/html/rfc6749#section-4.2"]||o.properties["auth-endpoint"],d=o.properties["http://remotestorage.io/spec/version"]||o.type;return u[e]={href:o.href,storageApi:d,authURL:a,properties:o.properties},c&&localStorage.setItem(l,JSON.stringify({cache:u})),t(u[e])}))}))};(d.DiscoveryError=function(e){this.name="DiscoveryError",this.message=e,this.stack=(new Error).stack}).prototype=Object.create(Error.prototype),d.DiscoveryError.prototype.constructor=d.DiscoveryError,d._rs_init=function(){if(c=(0,a.localStorageAvailable)(),c)try{const e=JSON.parse(localStorage[l]);u=e.cache}catch(e){}},d._rs_supported=function(){return Object.prototype.hasOwnProperty.call(a.globalContext,"fetch")||Object.prototype.hasOwnProperty.call(a.globalContext,"XMLHttpRequest")},d._rs_cleanup=function(){c&&delete localStorage[l]},e.exports=d},5706:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(93)),s=i(r(6424)),a=i(r(6941)),c=i(r(6982)),l=i(r(5503)),u=r(7746),d=r(368),h=r(3684),f=i(r(3275));let p;const g="remotestorage:dropbox",y="https://api.dropboxapi.com/2/files/list_folder",m="https://api.dropboxapi.com/2/files/list_folder/continue",v="/remotestorage";function b(e){return(v+"/"+e).replace(/\/+$/,"").replace(/\/+/g,"/")}const w=/[\u007f-\uffff]/g;function _(e){return JSON.stringify(e).replace(w,(function(e){return"\\u"+("000"+e.charCodeAt(0).toString(16)).slice(-4)}))}function S(e,t){return new RegExp("^"+t.join("\\/")+"(\\/|$)").test(e.error_summary)}function E(e){return e instanceof ArrayBuffer||(0,d.isArrayBufferView)(e)}class A extends h.RemoteBase{constructor(e){if(super(e),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this._initialFetchDone=!1,this.addEvents(["connected","not-connected"]),this.clientId=e.apiKeys.dropbox.appKey,this.TOKEN_URL="https://api.dropboxapi.com/oauth2/token",this._revCache=new a.default("rev"),this._fetchDeltaCursor=null,this._fetchDeltaPromise=null,this._itemRefs={},p=(0,u.localStorageAvailable)(),p){const e=(0,u.getJSONFromLocalStorage)(g);e&&this.configure(e),this._itemRefs=(0,u.getJSONFromLocalStorage)(`${g}:shares`)||{}}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}connect(){return n(this,void 0,void 0,(function*(){try{if(this.rs.setBackend("dropbox"),this.token)T(this.rs);else{const{codeVerifier:e,codeChallenge:t,state:r}=yield(0,u.generateCodeVerifier)();sessionStorage.setItem("remotestorage:codeVerifier",e),sessionStorage.setItem("remotestorage:state",r),this.rs.authorize({authURL:"https://www.dropbox.com/oauth2/authorize",scope:"account_info.read files.content.read files.content.write files.metadata.read files.metadata.write",clientId:this.clientId,response_type:"code",state:r,code_challenge:t,code_challenge_method:"S256",token_access_type:"offline"})}}catch(e){throw this.rs._emit("error",e),this.rs.setBackend(void 0),e}}))}configure(e){return n(this,void 0,void 0,(function*(){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token),void 0!==e.refreshToken&&(this.refreshToken=e.refreshToken),void 0!==e.tokenType&&(this.tokenType=e.tokenType);const t=()=>{p&&localStorage.setItem(g,JSON.stringify({userAddress:this.userAddress,token:this.token,refreshToken:this.refreshToken,tokenType:this.tokenType}))};if(this.refreshToken||this.token)if(this.connected=!0,this.userAddress)this._emit("connected"),t();else try{const e=yield this.info();this.userAddress=e.email,this._emit("connected"),t()}catch(e){this.connected=!1,this.rs._emit("error",new Error("Could not fetch user info.")),t.apply(this)}else(()=>{this.connected=!1,p&&localStorage.removeItem(g),this.rs.setBackend(void 0)})()}))}_getFolder(e){const t=this._revCache,r=r=>{let i;if(200!==r.status&&409!==r.status)return Promise.reject("Unexpected response status: "+r.status);try{i=JSON.parse(r.responseText)}catch(e){return Promise.reject(e)}if(409===r.status)return S(i,["path","not_found"])?Promise.resolve({}):Promise.reject(new Error("API returned an error: "+i.error_summary));const o=i.entries.reduce(((r,n)=>{try{const i="folder"===n[".tag"],o=n.path_display.split("/").slice(-1)[0]+(i?"/":"");if(i)r[o]={ETag:t.get(e+o)};else{const t=new Date(n.server_modified);r[o]={ETag:n.rev,"Content-Length":n.size,"Last-Modified":t.toUTCString()},this._revCache.set(e+o,n.rev)}}catch(t){console.error(`[Dropbox] folder “${e}” has entry ${JSON.stringify(n)}:`,t)}return r}),{});return i.has_more?n(i.cursor).then((function(e){return Object.assign(o,e)})):Promise.resolve(o)},n=e=>{const t={body:{cursor:e}};return this._request("POST",m,t).then(r)};return this._request("POST",y,{body:{path:b(e)}}).then(r).then((function(r){return Promise.resolve({statusCode:200,body:r,contentType:"application/json; charset=UTF-8",revision:t.get(e)})}))}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const r=this._revCache.get(e);if(null===r)return Promise.resolve({statusCode:404});if(t&&t.ifNoneMatch){if(!this._initialFetchDone)return this.fetchDelta().then((()=>this.get(e,t)));if(r&&r===t.ifNoneMatch)return Promise.resolve({statusCode:304})}if("/"===e.slice(-1))return this._getFolder(e);const n={headers:{"Dropbox-API-Arg":_({path:b(e)})},responseType:"arraybuffer"};return t&&t.ifNoneMatch&&(n.headers["If-None-Match"]=t.ifNoneMatch),this._request("GET","https://content.dropboxapi.com/2/files/download",n).then((t=>{const r=t.status;let n,i,o,s;return 200!==r&&409!==r?Promise.resolve({statusCode:r}):(n=t.getResponseHeader("Dropbox-API-Result"),(0,u.getTextFromArrayBuffer)(t.response,"UTF-8").then((a=>{i=a,409===r&&(n=i);try{n=JSON.parse(n)}catch(e){return Promise.reject(e)}if(409===r)return S(n,["path","not_found"])?{statusCode:404}:Promise.reject(new Error('API error while downloading file ("'+e+'"): '+n.error_summary));if(o=t.getResponseHeader("Content-Type"),s=n.rev,this._revCache.set(e,s),this._shareIfNeeded(e),(0,u.shouldBeTreatedAsBinary)(a,o))i=t.response;else try{i=JSON.parse(i),o="application/json; charset=UTF-8"}catch(e){}return{statusCode:r,body:i,contentType:o,revision:s}})))}))}put(e,t,r){return n(this,arguments,void 0,(function*(e,t,r,n={}){if(!this.connected)throw new Error("not connected (path: "+e+")");const i=this._revCache.get(e);if(n&&n.ifMatch&&i&&i!==n.ifMatch)return{statusCode:412,revision:i};if(n&&"*"===n.ifNoneMatch&&i&&"rev"!==i)return{statusCode:412,revision:i};if(!r.match(/charset=/)&&E(t)&&(r+="; charset=binary"),t.length>157286400)throw new Error("Cannot upload file larger than 150MB");const o={body:t,contentType:r,path:e};if(n&&(n.ifMatch||"*"===n.ifNoneMatch)){const t=yield this._getMetadata(e);if(n&&"*"===n.ifNoneMatch&&t)return{statusCode:412,revision:t.rev};if(n&&n.ifMatch&&t&&t.rev!==n.ifMatch)return{statusCode:412,revision:t.rev}}const s=yield this._uploadSimple(o);return this._shareIfNeeded(e),s}))}delete(e){return n(this,arguments,void 0,(function*(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");const r=this._revCache.get(e);if((null==t?void 0:t.ifMatch)&&r&&t.ifMatch!==r)return{statusCode:412,revision:r};if(null==t?void 0:t.ifMatch){const r=yield this._getMetadata(e);if((null==t?void 0:t.ifMatch)&&r&&r.rev!==t.ifMatch)return{statusCode:412,revision:r.rev}}return this._deleteSimple(e)}))}_shareIfNeeded(e){if(e.match(/^\/public\/.*[^/]$/)&&void 0===this._itemRefs[e])return this.share(e)}share(e){const t={body:{path:b(e)}};return this._request("POST","https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings",t).then((t=>{if(200!==t.status&&409!==t.status)return Promise.reject(new Error("Invalid response status:"+t.status));let r;try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+t.responseText))}return 409===t.status?S(r,["shared_link_already_exists"])?this._getSharedLink(e):Promise.reject(new Error("API error: "+r.error_summary)):Promise.resolve(r.url)})).then((t=>(this._itemRefs[e]=t,p&&localStorage.setItem(g+":shares",JSON.stringify(this._itemRefs)),Promise.resolve(t))),(t=>(t.message='Sharing Dropbox file or folder ("'+e+'") failed: '+t.message,Promise.reject(t))))}info(){return this._request("POST","https://api.dropboxapi.com/2/users/get_current_account",{}).then((function(e){let t;try{const r=JSON.parse(e.responseText);t=null==r?void 0:r.email}catch(t){return Promise.reject(new Error("Could not query current account info: Invalid API response: "+e.responseText))}return Promise.resolve({email:t})}))}_request(e,t,r){return n(this,arguments,void 0,(function*(e,t,r,n=1){if(this.isForbiddenRequestMethod(e,t))throw`Don't use ${e} on directories!`;if(!this.token)throw new l.default("No access token");r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,"object"!=typeof r.body||E(r.body)||(r.body=JSON.stringify(r.body),r.headers["Content-Type"]="application/json; charset=UTF-8"),this.rs._emit("wire-busy",{method:e,isFolder:(0,u.isFolder)(t)});try{const i=yield(0,d.requestWithTimeout)(e,t,r);return this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!0}),401===(null==i?void 0:i.status)&&this.refreshToken?n>=3?(console.error(`Abandoned after ${n} attempts: ${e} ${t}`),i):(this.rs._emit("wire-busy",{method:e,isFolder:(0,u.isFolder)(t)}),yield f.default.refreshAccessToken(this.rs,this,this.refreshToken),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!0}),this._request(e,t,r,n+1)):[503,429].includes(null==i?void 0:i.status)?(this.online&&(this.online=!1,this.rs._emit("network-offline")),n>=3?(console.warn(`Abandoned after ${n} attempts: ${e} ${t}`),i):(yield new Promise((e=>setTimeout(e,(0,d.retryAfterMs)(i)))),this._request(e,t,r,n+1))):i}catch(r){throw this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!1}),r}}))}fetchDelta(...e){if(this._fetchDeltaPromise)return this._fetchDeltaPromise;const t=e=>n(this,void 0,void 0,(function*(){let r,n;"string"==typeof e?(r=m,n={cursor:e}):(r=y,n={path:v,recursive:!0,include_deleted:!0});try{const i=yield this._request("POST",r,{body:n});if(401===i.status)throw new l.default;if(200!==i.status&&409!==i.status)throw new Error("Invalid response status: "+i.status);let o;try{o=JSON.parse(i.responseText)}catch(e){throw new Error("Invalid response body: "+i.responseText)}if(409===i.status){if(!S(o,["path","not_found"]))throw new Error("API returned an error: "+o.error_summary);o={cursor:null,entries:[],has_more:!1}}if(e||this._revCache.deactivatePropagation(),o.entries.forEach((e=>{const t=e.path_display.slice(14);"deleted"===e[".tag"]?(this._revCache.delete(t),this._revCache.delete(t+"/")):"file"===e[".tag"]&&this._revCache.set(t,e.rev)})),this._fetchDeltaCursor=o.cursor,o.has_more)return t(o.cursor);this._revCache.activatePropagation(),this._initialFetchDone=!0}catch(e){if("timeout"===e)return;throw e}}));return this._fetchDeltaPromise=t(this._fetchDeltaCursor).catch((e=>("object"==typeof e&&"message"in e?e.message="Dropbox: fetchDelta: "+e.message:e=`Dropbox: fetchDelta: ${e}`,this.rs._emit("error",e),this._fetchDeltaPromise=null,Promise.reject(e)))).then((()=>(this._fetchDeltaPromise=null,Promise.resolve(e)))),this._fetchDeltaPromise}_getMetadata(e){const t={path:b(e)};return this._request("POST","https://api.dropboxapi.com/2/files/get_metadata",{body:t}).then((e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status:"+e.status));let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?S(t,["path","not_found"])?Promise.resolve():Promise.reject(new Error("API error: "+t.error_summary)):Promise.resolve(t)})).then(void 0,(t=>(t.message='Could not load metadata for file or folder ("'+e+'"): '+t.message,Promise.reject(t))))}_uploadSimple(e){const t={path:b(e.path),mode:{".tag":"overwrite",update:void 0},mute:!0};return e.ifMatch&&(t.mode={".tag":"update",update:e.ifMatch}),this._request("POST","https://content.dropboxapi.com/2/files/upload",{body:e.body,headers:{"Content-Type":"application/octet-stream","Dropbox-API-Arg":_(t)}}).then((t=>{if(200!==t.status&&409!==t.status)return Promise.resolve({statusCode:t.status});let r;try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid API result: "+t.responseText))}return 409===t.status?S(r,["path","conflict"])?this._getMetadata(e.path).then((function(e){return Promise.resolve({statusCode:412,revision:e.rev})})):(this.rs._emit("error",new Error(r.error_summary)),Promise.resolve({statusCode:t.status})):(this._revCache.set(e.path,r.rev),Promise.resolve({statusCode:t.status,revision:r.rev}))}))}_deleteSimple(e){const t={path:b(e)};return this._request("POST","https://api.dropboxapi.com/2/files/delete",{body:t}).then((e=>{if(200!==e.status&&409!==e.status)return Promise.resolve({statusCode:e.status});let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}if(409===e.status){if(S(t,["path_lookup","not_found"]))return Promise.resolve({statusCode:404});this.rs._emit("error",new Error(t.error_summary))}return Promise.resolve({statusCode:e.status})})).then((t=>(200!==t.statusCode&&404!==t.statusCode||(this._revCache.delete(e),delete this._itemRefs[e]),Promise.resolve(t))),(t=>(t.message='Could not delete Dropbox file or folder ("'+e+'"): '+t.message,Promise.reject(t))))}_getSharedLink(e){return n(this,void 0,void 0,(function*(){const t={body:{path:b(e),direct_only:!0}};return this._request("POST","https://api.dropbox.com/2/sharing/list_shared_links",t).then((e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status: "+e.status));let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?Promise.reject(new Error("API error: "+(null==t?void 0:t.error_summary)||0)):t.links.length?Promise.resolve(t.links[0].url):Promise.reject(new Error("No links returned"))}),(t=>(t.message='Could not get link to a shared file or folder ("'+e+'"): '+t.message,Promise.reject(t))))}))}static _rs_init(e){p=(0,u.localStorageAvailable)(),e.apiKeys.dropbox&&(e.dropbox=new A(e)),"dropbox"===e.backend&&T(e)}static _rs_supported(){return!0}static _rs_cleanup(e){!function(e){(function(e){e._origRemote&&(e.remote=e._origRemote,delete e._origRemote)})(e),function(e){e._dropboxOrigSync&&(e.sync.sync=e._dropboxOrigSync,delete e._dropboxOrigSync)}(e),function(e){e._origBaseClientGetItemURL&&(s.default.prototype.getItemURL=e._origBaseClientGetItemURL,delete e._origBaseClientGetItemURL)}(e),I(e)}(e),p&&localStorage.removeItem(g),e.setBackend(void 0)}}function R(e,...t){e._dropboxOrigSync||(e._dropboxOrigSync=e.sync.sync.bind(e.sync),e.sync.sync=function(){return this.dropbox.fetchDelta(e,...t).then(e._dropboxOrigSync,(function(t){e._emit("error",new c.default(t)),e._emit("sync-done")}))}.bind(e))}function I(e){e._dropboxOrigSyncCycle&&(e.syncCycle=e._dropboxOrigSyncCycle,delete e._dropboxOrigSyncCycle)}function T(e){!function(e){e._origRemote||(e._origRemote=e.remote,e.remote=e.dropbox)}(e),e.sync?R(e):function(e,...t){e._dropboxOrigSyncCycle||(e._dropboxOrigSyncCycle=e.syncCycle,e.syncCycle=()=>{if(!e.sync)throw new Error("expected sync to be initialized by now");R(e),e._dropboxOrigSyncCycle(e,...t),I(e)})}(e),function(e){e._origBaseClientGetItemURL||(e._origBaseClientGetItemURL=s.default.prototype.getItemURL,s.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Dropbox yet")})}(e)}(0,u.applyMixins)(A,[o.default]),e.exports=A},9451:function(e,t,r){"use strict";const n=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(93)),i=r(7746);class o{constructor(){this.addEvents(["background","foreground"]),this.mode="undefined"!=typeof window?"browser":"node","browser"===this.mode&&(this.setBrowserPrefixedNames(),document.addEventListener(this.visibilityChangeEvent,this.setVisibility.bind(this),!1),this.setVisibility())}setBrowserPrefixedNames(){"browser"===this.mode&&(void 0!==document.hidden?(this.hiddenProperty="hidden",this.visibilityChangeEvent="visibilitychange"):void 0!==document.mozHidden?(this.hiddenProperty="mozHidden",this.visibilityChangeEvent="mozvisibilitychange"):void 0!==document.msHidden?(this.hiddenProperty="msHidden",this.visibilityChangeEvent="msvisibilitychange"):void 0!==document.webkitHidden&&(this.hiddenProperty="webkitHidden",this.visibilityChangeEvent="webkitvisibilitychange"))}setVisibility(){document[this.hiddenProperty]?this.goBackground():this.goForeground()}isBrowser(){return"browser"===this.mode}isNode(){return"node"===this.mode}goBackground(){this._emit("background")}goForeground(){this._emit("foreground")}static _rs_init(){}static _rs_cleanup(){}}(0,i.applyMixins)(o,[n.default]),e.exports=o},93:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.EventHandling=void 0;const i=n(r(3334));class o{addEvents(e){e.forEach((e=>this._addEvent(e)))}addEventListener(e,t){if("string"!=typeof e)throw new Error("Argument eventName should be a string");if("function"!=typeof t)throw new Error("Argument handler should be a function");(0,i.default)("[EventHandling] Adding event listener",e),this._validateEvent(e),this._handlers[e].push(t)}on(e,t){return this.addEventListener(e,t)}removeEventListener(e,t){this._validateEvent(e);const r=this._handlers[e].length;for(let n=0;n{e.apply(this,t)}))}_validateEvent(e){if(!(e in this._handlers))throw new Error("Unknown event: "+e)}_delegateEvent(e,t){t.on(e,(t=>{this._emit(e,t)}))}_addEvent(e){void 0===this._handlers&&(this._handlers={}),this._handlers[e]=[]}}t.EventHandling=o,t.default=o},6545:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(7028)),o=n(r(9451)),s=n(r(3334)),a=r(7746),c=n(r(1370)),l=n(r(2548)),u=n(r(3275)),d=n(r(5373)),h=n(r(6424)),f=n(r(1801)),p=n(r(5706)),g=n(r(6467)),y=n(r(600)),m=n(r(313)),v=n(r(7285)),b=n(r(8567)),w=n(r(7794)),_=n(r(8365)),S={features:[],featuresDone:0,readyFired:!1,loadFeatures(){this.features=[],this.featuresDone=0,this.readyFired=!1,this.featureModules={WireClient:y.default,Dropbox:p.default,GoogleDrive:f.default,Solid:g.default,Access:l.default,Discover:d.default,Authorize:u.default,BaseClient:h.default,Env:o.default},i.default.cache&&(0,a.extend)(this.featureModules,{Caching:v.default,IndexedDB:b.default,LocalStorage:w.default,InMemoryStorage:_.default,Sync:m.default}),i.default.disableFeatures.forEach((e=>{this.featureModules[e]&&delete this.featureModules[e]})),this._allLoaded=!1;for(const e in this.featureModules)this.loadFeature(e)},hasFeature(e){for(let t=this.features.length-1;t>=0;t--)if(this.features[t].name===e)return this.features[t].supported;return!1},loadFeature(e){const t=this.featureModules[e],r=!t._rs_supported||t._rs_supported();(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initializing ...`),"object"==typeof r?r.then((()=>{this.featureSupported(e,!0),this.initFeature(e)}),(()=>{this.featureSupported(e,!1)})):"boolean"==typeof r?(this.featureSupported(e,r),r&&this.initFeature(e)):this.featureSupported(e,!1)},initFeature(e){const t=this.featureModules[e];let r;try{r=t._rs_init(this)}catch(t){return void this.featureFailed(e,t)}"object"==typeof r&&"function"==typeof r.then?r.then((()=>{this.featureInitialized(e)}),(t=>{this.featureFailed(e,t)})):this.featureInitialized(e)},featureFailed(e,t){(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initialization failed (${t})`),this.featureDone()},featureSupported(e,t){(0,s.default)(`[RemoteStorage] [FEATURE ${e}]${t?"":"not "} supported`),t||this.featureDone()},featureInitialized(e){(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initialized`),this.features.push({name:e,init:this.featureModules[e]._rs_init,supported:!0,cleanup:this.featureModules[e]._rs_cleanup}),this.featureDone()},featureDone(){this.featuresDone++,this.featuresDone===Object.keys(this.featureModules).length&&setTimeout(this.featuresLoaded.bind(this),0)},_setCachingModule(){["IndexedDB","LocalStorage","InMemoryStorage"].some((e=>{if(this.features.some((t=>t.name===e)))return this.features.local=this.featureModules[e],!0}))},_fireReady(){try{this.readyFired||(this._emit("ready"),this.readyFired=!0)}catch(e){console.error("'ready' failed: ",e,e.stack),this._emit("error",e)}},featuresLoaded(){(0,s.default)("[RemoteStorage] All features loaded"),this._setCachingModule(),this.local=i.default.cache&&this.features.local&&new this.features.local,this.local&&this.remote?(this._setGPD(c.default,this),this._bindChange(this.local)):this.remote&&this._setGPD(this.remote,this.remote),this.remote&&(this.remote.on("connected",(()=>{this._fireReady(),this._emit("connected")})),this.remote.on("not-connected",(()=>{this._fireReady(),this._emit("not-connected")})),this.remote.connected&&(this._fireReady(),this._emit("connected")),this.hasFeature("Authorize")||this.remote.stopWaitingForToken()),this._collectCleanupFunctions();try{this._allLoaded=!0,this._emit("features-loaded")}catch(e){(0,a.logError)(e),this._emit("error",e)}this._processPending()},_collectCleanupFunctions(){this._cleanups=[];for(let e=0;e=r-this.maxAge?t.v:void 0}set(e,t){this._items[e]={v:t,t:(new Date).getTime()}}}class v extends c.RemoteBase{constructor(e,t){if(super(e),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this.addEvents(["connected","not-connected"]),this.clientId=t,this._fileIdCache=new m(300),h=(0,s.localStorageAvailable)(),h){const e=(0,s.getJSONFromLocalStorage)(u);e&&this.configure(e)}}configure(e){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token);const t=function(){h&&localStorage.setItem(u,JSON.stringify({userAddress:this.userAddress,token:this.token}))},r=function(){this.connected=!1,delete this.token,h&&localStorage.removeItem(u)};this.token?(this.connected=!0,this.userAddress?(this._emit("connected"),t.apply(this)):this.info().then((e=>{this.userAddress=e.user.emailAddress,this._emit("connected"),t.apply(this)})).catch((()=>{r.apply(this),this.rs._emit("error",new Error("Could not fetch user info."))}))):r.apply(this)}connect(){this.rs.setBackend("googledrive"),this.rs.authorize({authURL:"https://accounts.google.com/o/oauth2/auth",scope:"https://www.googleapis.com/auth/drive",clientId:this.clientId})}get(e,t={}){return(0,s.isFolder)(e)?this._getFolder(y(e)):this._getFile(y(e),t)}put(e,t,r,n={}){const i=y(e);function o(e){if(e.status>=200&&e.status<300){const t=JSON.parse(e.responseText),r=this.stripQuotes(t.etag);return Promise.resolve({statusCode:200,contentType:t.mimeType,revision:r})}return 412===e.status?Promise.resolve({statusCode:412,revision:"conflict"}):Promise.reject("PUT failed with status "+e.status+" ("+e.responseText+")")}return this._getFileId(i).then((e=>e?n&&"*"===n.ifNoneMatch?o({status:412}):this._updateFile(e,i,t,r,n).then(o):this._createFile(i,t,r).then(o)))}delete(e,t={}){const r=y(e);return this._getFileId(r).then((e=>e?this._getMeta(e).then((r=>{let n;return"object"==typeof r&&"string"==typeof r.etag&&(n=this.stripQuotes(r.etag)),t&&t.ifMatch&&t.ifMatch!==n?{statusCode:412,revision:n}:this._request("DELETE",l+"/drive/v2/files/"+e,{}).then((e=>200===e.status||204===e.status?{statusCode:200}:Promise.reject("Delete failed: "+e.status+" ("+e.responseText+")")))})):Promise.resolve({statusCode:200})))}info(){const e=l+"/drive/v2/about?fields=user";return this._request("GET",e,{}).then((function(e){try{const t=JSON.parse(e.responseText);return Promise.resolve(t)}catch(e){return Promise.reject(e)}}))}_updateFile(e,t,r,n,i){const o={mimeType:n},s={"Content-Type":"application/json; charset=UTF-8"};return i&&i.ifMatch&&(s["If-Match"]=this.addQuotes(i.ifMatch)),this._request("PUT",l+"/upload/drive/v2/files/"+e+"?uploadType=resumable",{body:JSON.stringify(o),headers:s}).then((e=>412===e.status?e:this._request("PUT",e.getResponseHeader("Location"),{body:n.match(/^application\/json/)?JSON.stringify(r):r})))}_createFile(e,t,r){return this._getParentId(e).then((n=>{const i={title:f(g(e)),mimeType:r,parents:[{kind:"drive#fileLink",id:n}]};return this._request("POST",l+"/upload/drive/v2/files?uploadType=resumable",{body:JSON.stringify(i),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then((e=>this._request("POST",e.getResponseHeader("Location"),{body:r.match(/^application\/json/)?JSON.stringify(t):t})))}))}_getFile(e,t){return this._getFileId(e).then((e=>this._getMeta(e).then((e=>{let r;if("object"==typeof e&&"string"==typeof e.etag&&(r=this.stripQuotes(e.etag)),t&&t.ifNoneMatch&&r===t.ifNoneMatch)return Promise.resolve({statusCode:304});if(!e.downloadUrl){if(!e.exportLinks||!e.exportLinks["text/html"])return Promise.resolve({statusCode:200,body:"",contentType:e.mimeType,revision:r});e.mimeType+=";export=text/html",e.downloadUrl=e.exportLinks["text/html"]}return this._request("GET",e.downloadUrl,{responseType:"arraybuffer"}).then((t=>(0,s.getTextFromArrayBuffer)(t.response,"UTF-8").then((function(n){let i=n;if(e.mimeType.match(/^application\/json/))try{i=JSON.parse(i)}catch(e){}else(0,s.shouldBeTreatedAsBinary)(n,e.mimeType)&&(i=t.response);return{statusCode:200,body:i,contentType:e.mimeType,revision:r}}))))}))))}_getFolder(e){return this._getFileId(e).then((t=>{let r,n,i;if(!t)return Promise.resolve({statusCode:404});const o="'"+t+"' in parents";return this._request("GET",l+"/drive/v2/files?q="+encodeURIComponent(o)+"&fields="+encodeURIComponent("items(downloadUrl,etag,fileSize,id,mimeType,title,labels)")+"&maxResults=1000&trashed=false",{}).then((t=>{var o;if(200!==t.status)return Promise.reject("request failed or something: "+t.status);try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject("non-JSON response from GoogleDrive")}i={};for(const t of r.items)(null===(o=t.labels)||void 0===o?void 0:o.trashed)||(n=this.stripQuotes(t.etag),t.mimeType===d?(this._fileIdCache.set(e+(0,s.cleanPath)(t.title)+"/",t.id),i[t.title+"/"]={ETag:n}):(this._fileIdCache.set(e+(0,s.cleanPath)(t.title),t.id),i[t.title]={ETag:n,"Content-Type":t.mimeType,"Content-Length":t.fileSize}));return Promise.resolve({statusCode:200,body:i,contentType:"application/json; charset=UTF-8",revision:void 0})}))}))}_getParentId(e){const t=p(e);return this._getFileId(t).then((e=>e?Promise.resolve(e):this._createFolder(t)))}_createFolder(e){return this._getParentId(e).then((t=>this._request("POST",l+"/drive/v2/files",{body:JSON.stringify({title:f(g(e)),mimeType:d,parents:[{id:t}]}),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then((e=>{const t=JSON.parse(e.responseText);return Promise.resolve(t.id)}))))}_getFileId(e){let t;return"/"===e?Promise.resolve("root"):(t=this._fileIdCache.get(e))?Promise.resolve(t):this._getFolder(p(e)).then((()=>(t=this._fileIdCache.get(e),t?Promise.resolve(t):"/"===e.substr(-1)?this._createFolder(e).then((()=>this._getFileId(e))):Promise.resolve())))}_getMeta(e){return this._request("GET",l+"/drive/v2/files/"+e,{}).then((function(t){return 200===t.status?Promise.resolve(JSON.parse(t.responseText)):Promise.reject("request (getting metadata for "+e+") failed with status: "+t.status)}))}_request(e,t,r){return this.isForbiddenRequestMethod(e,t)?Promise.reject(`Don't use ${e} on directories!`):(r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,this.rs._emit("wire-busy",{method:e,isFolder:(0,s.isFolder)(t)}),(0,a.requestWithTimeout)(e,t,r).then((r=>r&&401===r.status?void this.connect():(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!0}),Promise.resolve(r))),(r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!1}),Promise.reject(r)))))}static _rs_init(e){const t=e.apiKeys.googledrive;var r;t&&(e.googledrive=new v(e,t.clientId),"googledrive"===e.backend&&(e._origRemote=e.remote,e.remote=e.googledrive,(r=e)._origBaseClientGetItemURL||(r._origBaseClientGetItemURL=i.default.prototype.getItemURL,i.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Google Drive yet")})))}static _rs_supported(){return!0}static _rs_cleanup(e){var t;e.setBackend(void 0),e._origRemote&&(e.remote=e._origRemote,delete e._origRemote),(t=e)._origBaseClientGetItemURL&&(i.default.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)}}(0,s.applyMixins)(v,[o.default]),e.exports=v},8567:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(93)),s=i(r(3496)),a=i(r(3334)),c=r(7746),l="remotestorage";let u;class d extends s.default{constructor(e){super(),this.addEvents(["change","local-events-done"]),this.db=e||u,this.db?(this.getsRunning=0,this.putsRunning=0,this.changesQueued={},this.changesRunning={},this.commitSlownessWarning=null):(0,a.default)("[IndexedDB] Failed to open DB")}getNodes(e){return n(this,void 0,void 0,(function*(){const t=[],r={};for(let n=0,i=e.length;n0?this.getNodesFromDb(t).then((function(e){for(const t in r)e[t]=r[t];return e})):Promise.resolve(r)}))}setNodes(e){return n(this,void 0,void 0,(function*(){for(const t in e)this.changesQueued[t]=e[t]||!1;return this.maybeFlush(),Promise.resolve()}))}maybeFlush(){0===this.putsRunning?this.flushChangesQueued():this.commitSlownessWarning||(this.commitSlownessWarning=r.g.setInterval((function(){console.warn("WARNING: waited more than 10 seconds for previous commit to finish")}),1e4))}flushChangesQueued(){this.commitSlownessWarning&&(clearInterval(this.commitSlownessWarning),this.commitSlownessWarning=null),Object.keys(this.changesQueued).length>0&&(this.changesRunning=this.changesQueued,this.changesQueued={},this.setNodesInDb(this.changesRunning).then(this.flushChangesQueued.bind(this)))}getNodesFromDb(e){return new Promise(((t,r)=>{const n=this.db.transaction(["nodes"],"readonly"),i=n.objectStore("nodes"),o={};this.getsRunning++,e.map((e=>{i.get(e).onsuccess=t=>{o[e]=t.target.result}})),n.oncomplete=()=>{t(o),this.getsRunning--},n.onerror=n.onabort=()=>{r("get transaction error/abort"),this.getsRunning--}}))}setNodesInDb(e){return n(this,void 0,void 0,(function*(){return new Promise(((t,r)=>{const n=this.db.transaction(["nodes"],"readwrite"),i=n.objectStore("nodes"),o=(new Date).getTime();this.putsRunning++,(0,a.default)("[IndexedDB] Starting put",e,this.putsRunning);for(const t in e){const r=e[t];if("object"==typeof r)try{i.put(r)}catch(e){throw(0,a.default)("[IndexedDB] Error while putting",r,e),e}else try{i.delete(t)}catch(e){throw(0,a.default)("[IndexedDB] Error while removing",i,r,e),e}}n.oncomplete=()=>{this.putsRunning--,(0,a.default)("[IndexedDB] Finished put",e,this.putsRunning,(new Date).getTime()-o+"ms"),t()},n.onerror=()=>{this.putsRunning--,r("transaction error")},n.onabort=()=>{r("transaction abort"),this.putsRunning--}}))}))}reset(e){const t=this.db.name;this.db.close(),d.clean(this.db.name,(()=>{d.open(t,((t,r)=>{t?(0,a.default)("[IndexedDB] Error while resetting local storage",t):this.db=r,"function"==typeof e&&e(self)}))}))}forAllNodes(e){return n(this,void 0,void 0,(function*(){return new Promise((t=>{this.db.transaction(["nodes"],"readonly").objectStore("nodes").openCursor().onsuccess=r=>{const n=r.target.result;n?(e(this.migrate(n.value)),n.continue()):t()}}))}))}closeDB(){0===this.putsRunning?this.db.close():setTimeout(this.closeDB.bind(this),100)}static open(e,t){const r=setTimeout((function(){t("timeout trying to open db")}),1e4);try{const n=indexedDB.open(e,2);n.onerror=function(){(0,a.default)("[IndexedDB] Opening DB failed",n),clearTimeout(r),t(n.error)},n.onupgradeneeded=function(e){const t=n.result;(0,a.default)("[IndexedDB] Upgrade: from ",e.oldVersion," to ",e.newVersion),1!==e.oldVersion&&((0,a.default)("[IndexedDB] Creating object store: nodes"),t.createObjectStore("nodes",{keyPath:"path"})),(0,a.default)("[IndexedDB] Creating object store: changes"),t.createObjectStore("changes",{keyPath:"path"})},n.onsuccess=function(){clearTimeout(r);const i=n.result;if(!i.objectStoreNames.contains("nodes")||!i.objectStoreNames.contains("changes"))return(0,a.default)("[IndexedDB] Missing object store. Resetting the database."),void d.clean(e,(function(){d.open(e,t)}));t(null,n.result)}}catch(n){(0,a.default)("[IndexedDB] Failed to open database: "+n),(0,a.default)("[IndexedDB] Resetting database and trying again."),clearTimeout(r),d.clean(e,(function(){d.open(e,t)}))}}static clean(e,t){const r=indexedDB.deleteDatabase(e);r.onsuccess=function(){(0,a.default)("[IndexedDB] Done removing DB"),t()},r.onerror=r.onabort=function(t){console.error('Failed to remove database "'+e+'"',t)}}static _rs_init(e){return new Promise(((t,r)=>{d.open(l,(function(n,i){n?r(n):(u=i,i.onerror=()=>{e._emit("error",n)},t())}))}))}static _rs_supported(){return new Promise(((e,t)=>{const r=(0,c.getGlobalContext)();let n=!1;if("undefined"!=typeof navigator&&navigator.userAgent.match(/Android (2|3|4\.[0-3])/)&&(navigator.userAgent.match(/Chrome|Firefox/)||(n=!0)),"indexedDB"in r&&!n)try{const r=indexedDB.open("rs-check");r.onerror=function(){t()},r.onsuccess=function(){r.result.close(),indexedDB.deleteDatabase("rs-check"),e()}}catch(e){t()}else t()}))}static _rs_cleanup(e){return new Promise((t=>{e.local&&e.local.closeDB(),d.clean(l,t)}))}diffHandler(){}}(0,c.applyMixins)(d,[o.default]),e.exports=d},8365:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(93)),o=n(r(3496)),s=r(7746);class a extends o.default{constructor(){super(),this._storage={},this.addEvents(["change","local-events-done"])}getNodes(e){const t={};for(let r=0,n=e.length;r{(0,s.default)("[LocalStorage] Removing",e),delete localStorage[e]}))}}(0,a.applyMixins)(u,[o.default]),e.exports=u},3334:function(e,t,r){"use strict";const n=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(7028));e.exports=function(...e){n.default.logging&&console.log(...e)}},3684:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteBase=void 0;const i=n(r(93)),o=r(7746);class s extends i.default{constructor(e){super(),this.rs=e,this.connected=!1}stopWaitingForToken(){this.connected||this._emit("not-connected")}addQuotes(e){return"string"!=typeof e?e:"*"===e?"*":'"'+e+'"'}stripQuotes(e){return"string"!=typeof e?e:e.replace(/^["']|["']$/g,"")}isForbiddenRequestMethod(e,t){return("PUT"===e||"DELETE"===e)&&(0,o.isFolder)(t)}}t.RemoteBase=s},423:function(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s=2e3&&e<=36e5}var x;!function(e){e.GOOGLE="googledrive",e.DROPBOX="dropbox"}(x||(x={}));class P{constructor(e){if(this._pending=[],this._cleanups=[],this._pathHandlers={change:{}},this.apiKeys={},this._init=S.default.loadFeatures,this.features=S.default.features,this.loadFeature=S.default.loadFeature,this.featureSupported=S.default.featureSupported,this.featureDone=S.default.featureDone,this.featuresDone=S.default.featuresDone,this.featuresLoaded=S.default.featuresLoaded,this.featureInitialized=S.default.featureInitialized,this.featureFailed=S.default.featureFailed,this.hasFeature=S.default.hasFeature,this._setCachingModule=S.default._setCachingModule,this._collectCleanupFunctions=S.default._collectCleanupFunctions,this._fireReady=S.default._fireReady,this.initFeature=S.default.initFeature,"object"==typeof e&&(0,u.extend)(c.default,e),this.addEvents(["ready","authing","connecting","pod-not-selected","connected","disconnected","not-connected","conflict","error","features-loaded","sync-interval-change","sync-req-done","sync-done","wire-busy","wire-done","network-offline","network-online"]),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")}),R=(0,u.localStorageAvailable)(),R){this.apiKeys=(0,u.getJSONFromLocalStorage)("remotestorage:api-keys")||{};const e=localStorage.getItem("remotestorage:backend");"dropbox"===e||"googledrive"===e||"solid"===e?this.setBackend(e):this.setBackend("remotestorage")}const t=this.on;this.on=function(e,r){if(this._allLoaded)switch(e){case"features-loaded":setTimeout(r,0);break;case"ready":this.remote&&setTimeout(r,0);break;case"connected":this.remote&&this.remote.connected&&setTimeout(r,0);break;case"not-connected":this.remote&&!this.remote.connected&&setTimeout(r,0);break;case"pod-not-selected":this.remote instanceof v.default&&Array.isArray(this.remote.getPodURLs())&&this.remote.getPodURLs().length>0&&null===this.remote.getPodURL()&&setTimeout(r,0)}return t.call(this,e,r)},this._init(),this.fireInitial=function(){this.local&&setTimeout(this.local.fireInitial.bind(this.local),0)}.bind(this),this.on("ready",this.fireInitial.bind(this)),this.loadModules()}get connected(){return this.remote.connected}loadModules(){c.default.modules.forEach(this.addModule.bind(this))}authorize(e){if(this.access.setStorageType(this.remote.storageApi),void 0===e.scope&&(e.scope=this.access.scopeParameter),A.cordova)e.redirectUri=c.default.cordovaRedirectUri;else{const t=h.default.getLocation();let r=t.origin;"/"!==t.pathname&&(r+=t.pathname),e.redirectUri=r}void 0===e.clientId&&(e.clientId=e.redirectUri.match(/^(https?:\/\/[^/]+)/)[0]),h.default.authorize(this,e)}impliedauth(e,t){e=e||this.remote.storageApi,t=t||String(document.location),(0,l.default)("ImpliedAuth proceeding due to absent authURL; storageApi = "+e+" redirectUri = "+t),this.remote.configure({token:h.default.IMPLIED_FAKE_TOKEN}),document.location.href=t}connect(e,t){if(this.setBackend("remotestorage"),e.indexOf("@")<0&&!e.match(/^(https?:\/\/)?[^\s\/$\.?#]+\.[^\s]*$/))this._emit("error",new P.DiscoveryError("Not a valid user address or URL."));else{if(e.indexOf("@")<0&&!e.match(/^https?:\/\//)&&(e=`https://${e}`),A.cordova){if("string"!=typeof c.default.cordovaRedirectUri)return void this._emit("error",new P.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));if(!A.cordova.InAppBrowser)return void this._emit("error",new P.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"))}this.remote.configure({userAddress:e}),this._emit("connecting"),(0,b.default)(e).then((r=>{if(this._emit("authing"),r.userAddress=e,this.remote.configure(r),!this.remote.connected)if(r.authURL)if(void 0===t)this.authorize({authURL:r.authURL});else{if("string"!=typeof t)throw new Error("Supplied bearer token must be a string");(0,l.default)("Skipping authorization sequence and connecting with known token"),this.remote.configure({token:t})}else this.impliedauth()}),(()=>{this._emit("error",new P.DiscoveryError("No storage information found for this user address."))}))}}reconnect(){this.remote.configure({token:null}),"remotestorage"===this.backend?this.connect(this.remote.userAddress):this.remote.connect()}disconnect(){this.remote&&this.remote.configure({userAddress:null,href:null,storageApi:null,token:null,properties:null}),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")});const e=this._cleanups.length;let t=0;const r=()=>{t++,t>=e&&(this._init(),this._emit("disconnected"))};e>0?this._cleanups.forEach((e=>{const t=e(this);"object"==typeof t&&"function"==typeof t.then?t.then(r):r()})):r()}setBackend(e){this.backend=e,R&&(void 0!==e?localStorage.setItem("remotestorage:backend",e):localStorage.removeItem("remotestorage:backend"))}onChange(e,t){this._pathHandlers.change[e]||(this._pathHandlers.change[e]=[]),this._pathHandlers.change[e].push(t)}enableLog(){c.default.logging=!0}disableLog(){c.default.logging=!1}log(...e){l.default.apply(P,e)}setApiKeys(e){const t=[x.GOOGLE,x.DROPBOX];if("object"!=typeof e||!Object.keys(e).every((e=>t.includes(e))))return console.error("setApiKeys() was called with invalid arguments"),!1;Object.keys(e).forEach((t=>{const r=e[t];if(r){switch(t){case x.DROPBOX:this.apiKeys[x.DROPBOX]={appKey:r},void 0!==this.dropbox&&this.dropbox.clientId===r||m.default._rs_init(this);break;case x.GOOGLE:this.apiKeys[x.GOOGLE]={clientId:r},void 0!==this.googledrive&&this.googledrive.clientId===r||y.default._rs_init(this)}return!0}delete this.apiKeys[t]})),R&&localStorage.setItem("remotestorage:api-keys",JSON.stringify(this.apiKeys))}setCordovaRedirectUri(e){if("string"!=typeof e||!e.match(/http(s)?:\/\//))throw new Error("Cordova redirect URI must be a URI string");c.default.cordovaRedirectUri=e}_setGPD(e,t){function r(e){return function(...r){return e.apply(t,r).then(I.bind(this))}}this.get=r(e.get),this.put=r(e.put),this.delete=r(e.delete)}_pendingGPD(e){return(...t)=>{const r=Array.prototype.slice.call(t);return new Promise(((t,n)=>{this._pending.push({method:e,args:r,promise:{resolve:t,reject:n}})}))}}_processPending(){this._pending.forEach((e=>{try{this[e.method](...e.args).then(e.promise.resolve,e.promise.reject)}catch(t){e.promise.reject(t)}})),this._pending=[]}_bindChange(e){e.on("change",this._dispatchEvent.bind(this,"change"))}_dispatchEvent(e,t){Object.keys(this._pathHandlers[e]).forEach((r=>{const n=r.length;t.path.substr(0,n)===r&&this._pathHandlers[e][r].forEach((e=>{const n={};for(const e in t)n[e]=t[e];n.relativePath=t.path.replace(new RegExp("^"+r),"");try{e(n)}catch(e){console.error("'change' handler failed: ",e,e.stack),this._emit("error",e)}}))}))}scope(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.scope must be a string";return this.access.checkPathPermission(e,"r")||console.warn("WARNING: Please use remoteStorage.access.claim() to ask for access permissions first: https://remotestoragejs.readthedocs.io/en/latest/js-api/access.html#claim"),new f.default(this,e)}getSyncInterval(){return c.default.syncInterval}setSyncInterval(e){if(!T(e))throw e+" is not a valid sync interval";const t=c.default.syncInterval;c.default.syncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getBackgroundSyncInterval(){return c.default.backgroundSyncInterval}setBackgroundSyncInterval(e){if(!T(e))throw e+" is not a valid sync interval";const t=c.default.backgroundSyncInterval;c.default.backgroundSyncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getCurrentSyncInterval(){return c.default.isBackground?c.default.backgroundSyncInterval:c.default.syncInterval}getRequestTimeout(){return c.default.requestTimeout}setRequestTimeout(e){if("number"!=typeof e)throw e+" is not a valid request timeout";c.default.requestTimeout=e}syncCycle(){this.sync&&!this.sync.stopped&&(this.on("sync-done",(()=>{this.sync&&!this.sync.stopped&&(this._syncTimer&&(clearTimeout(this._syncTimer),this._syncTimer=void 0),this._syncTimer=setTimeout(this.sync.sync.bind(this.sync),this.getCurrentSyncInterval()))})),this.sync.sync())}startSync(){return c.default.cache?(this.sync.stopped=!1,this.syncStopped=!1,this.sync.sync()):(console.warn("Nothing to sync, because caching is disabled."),Promise.resolve())}stopSync(){clearTimeout(this._syncTimer),this._syncTimer=void 0,this.sync?this.sync.stopped=!0:this.syncStopped=!0}addModule(e){const t=e.name,r=e.builder;if(Object.defineProperty(this,t,{configurable:!0,get:function(){const e=this._loadModule(t,r);return Object.defineProperty(this,t,{value:e}),e}}),-1!==t.indexOf("-")){const e=t.replace(/\-[a-z]/g,(function(e){return e[1].toUpperCase()}));Object.defineProperty(this,e,{get:function(){return this[t]}})}}_loadModule(e,t){if(t)return t(new f.default(this,"/"+e+"/"),new f.default(this,"/public/"+e+"/")).exports;throw"Unknown module: "+e}}t.RemoteStorage=P,P.Authorize=h.default,P.SyncError=w.default,P.Unauthorized=_.default,P.DiscoveryError=b.default.DiscoveryError,P.util=E,Object.defineProperty(P.prototype,"access",{get:function(){const e=new d.default;return Object.defineProperty(this,"access",{value:e}),e},configurable:!0}),Object.defineProperty(P.prototype,"caching",{configurable:!0,get:function(){const e=new p.default;return Object.defineProperty(this,"caching",{value:e}),e}}),(0,u.applyMixins)(P,[g.EventHandling]),t.default=P},368:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isArrayBufferView=void 0,t.retryAfterMs=function(e){const t=1e3*parseInt(e.getResponseHeader("Retry-After"));return t>=1e3?t:Math.max(1500,Math.min(6e4,Math.round(s.default.syncInterval/(2.9+.2*Math.random()))))},t.requestWithTimeout=function(e,r,i){return n(this,void 0,void 0,(function*(){return"function"==typeof fetch?function(e,t,r){return n(this,void 0,void 0,(function*(){const n="function"==typeof AbortController?new AbortController:null;let i;const a=new Promise(((e,t)=>{i=setTimeout((()=>{n&&n.abort(),t("timeout")}),s.default.requestTimeout)}));let c;const l={},u=fetch(t,{method:e,headers:r.headers,body:r.body,signal:n?n.signal:void 0}).then((e=>{switch((0,o.default)("[requests fetch]",e),e.headers.forEach(((e,t)=>{l[t.toUpperCase()]=e})),c={readyState:4,status:e.status,statusText:e.statusText,response:void 0,getResponseHeader:e=>l[e.toUpperCase()]||null,responseType:r.responseType,responseURL:t},r.responseType){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json();case void 0:case"":case"text":return e.text();default:throw new Error("responseType 'document' is not currently supported using fetch")}})).then((e=>(c.response=e,r.responseType&&"text"!==r.responseType||(c.responseText=e),c))).finally((()=>{clearTimeout(i)}));return Promise.race([u,a])}))}(e,r,i):"function"==typeof XMLHttpRequest?function(e,r,i){return n(this,void 0,void 0,(function*(){return new Promise(((n,a)=>{(0,o.default)("[requests XHR]",e,r);let c=!1;const l=setTimeout((()=>{c=!0,a("timeout")}),s.default.requestTimeout),u=new XMLHttpRequest;if(u.open(e,r,!0),i.responseType&&(u.responseType=i.responseType),i.headers)for(const e in i.headers)u.setRequestHeader(e,i.headers[e]);u.onload=()=>{c||(clearTimeout(l),n(u))},u.onerror=e=>{c||(clearTimeout(l),a(e))};let d=i.body;"object"==typeof d&&!(0,t.isArrayBufferView)(d)&&d instanceof ArrayBuffer&&(d=new Uint8Array(d)),u.send(d)}))}))}(e,r,i):Promise.reject("[Requests] You need to add a polyfill for fetch or XMLHttpRequest")}))};const o=i(r(3334)),s=i(r(7028));if("function"==typeof(r.g||window).ArrayBufferView)t.isArrayBufferView=function(e){return e&&e instanceof(r.g||window).ArrayBufferView};else{const e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];t.isArrayBufferView=function(t){for(let r=0;r<8;r++)if(t instanceof e[r])return!0;return!1}}},6941:function(e){"use strict";e.exports=class{constructor(e){this._itemsRev={},this._storage={},this._canPropagate=!1,this.defaultValue=e,this.activatePropagation()}get(e){e=e.toLowerCase();let t=this._storage[e];return void 0===t&&(t=this.defaultValue,this._storage[e]=t),t}set(e,t){return e=e.toLowerCase(),this._storage[e]===t||(this._storage[e]=t,t||delete this._itemsRev[e],this._updateParentFolderItemRev(e,t),this._canPropagate&&this._propagate(e)),t}delete(e){return this.set(e,null)}deactivatePropagation(){return this._canPropagate=!1,!0}activatePropagation(){return this._canPropagate||(this._generateFolderRev("/"),this._canPropagate=!0),!0}_hashCode(e){let t=0;if(0===e.length)return t;for(let r=0;r0&&(r=this._generateHash(e))}return this.set(e,r),r}}},6491:function(e){"use strict";class t extends Error{constructor(e){super();const t=new Error("Schema not found: "+e);return t.name="SchemaNotFound",t}}e.exports=t},6467:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=r(2452),s=r(4848),a=i(r(6424)),c=i(r(93)),l=r(7746),u=r(3684),d=i(r(7398)),h=i(r(8849)),f="remotestorage:solid";let p;class g extends u.RemoteBase{constructor(e){if(super(e),this.podURLs=null,console.log("Solid constructor"),this.online=!0,this.addEvents(["connected","not-connected","pod-not-selected"]),this.configStorage=new d.default(this),this.session=new o.Session({secureStorage:new o.InMemoryStorage,insecureStorage:this.configStorage},"any"),p=(0,l.localStorageAvailable)(),p){const e=(0,l.getJSONFromLocalStorage)(f);e&&this.configure(e)}}onConfigChanged(e){if(e){const t=JSON.parse(e);if(void 0!==t.clientSecret){let e=(0,l.getJSONFromLocalStorage)(f);return e||(e={}),e.href=this.authURL,e.properties={sessionProperties:t,podURL:this.selectedPodURL},this.sessionProperties=t,void localStorage.setItem(f,JSON.stringify(e))}}this.podURLs=null,localStorage.removeItem(f)}configure(e){if(void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.href&&(this.authURL=e.href),void 0!==e.properties){const t=e.properties;t?(void 0!==t.sessionProperties?this.sessionProperties=t.sessionProperties:this.sessionProperties=null,void 0!==t.podURL?this.selectedPodURL=t.podURL:this.selectedPodURL=null):(this.sessionProperties=null,this.selectedPodURL=null)}this.sessionProperties?(this.configStorage.setConfig(JSON.stringify(this.sessionProperties)),this.connected=this.session.info&&this.session.info.isLoggedIn,function(){p&&localStorage.setItem(f,JSON.stringify({userAddress:this.userAddress,href:this.authURL,properties:{sessionProperties:this.sessionProperties,podURL:this.selectedPodURL}}))}.apply(this)):function(){this.connected=!1,this.sessionProperties=null,this.podURLs=null,p&&localStorage.removeItem(f)}.apply(this)}setAuthURL(e){this.authURL=e}getPodURLs(){return this.podURLs}setPodURL(e){if(this.selectedPodURL!==e&&(this.selectedPodURL=e,this.session.info&&this.session.info.isLoggedIn))if(this.selectedPodURL){let e=(0,l.getJSONFromLocalStorage)(f);e||(e={}),e.userAddress=this.session.info.webId,e.href=this.authURL,e.properties={sessionProperties:this.sessionProperties,podURL:this.selectedPodURL},localStorage.setItem(f,JSON.stringify(e)),this.connected=!0,this._emit("connected")}else this.connected=!1,this.rs._emit("pod-not-selected")}getPodURL(){return this.selectedPodURL}connect(){this.rs.setBackend("solid"),this.authURL?this.session.login({oidcIssuer:this.authURL,redirectUrl:new URL("/",window.location.href).toString(),clientName:"Remote Storage"}):this.rs._emit("error",new Error("No authURL is configured."))}getSession(){return this.session.info&&this.session.info.isLoggedIn?this.session:null}getFileURL(e){return e.startsWith("/")&&(e=e.substring(1)),0===e.length&&(e="/"),this.selectedPodURL+e}get(e,t={}){console.log("Solid get",e,t);const r=this.getFileURL(e);return"/"===e.slice(-1)?(0,s.getSolidDataset)(r,{fetch:this.session.fetch}).then((e=>{console.log("container data set",e);const t=(0,s.getContainedResourceUrlAll)(e).reduce(((t,n)=>{const i=n.substring(r.length),o=(0,s.getThing)(e,n);return t[i]={ETag:(0,s.getDecimal)(o,"http://www.w3.org/ns/posix/stat#mtime").toString(),"Last-Modified":(0,s.getDatetime)(o,"http://purl.org/dc/terms/modified").toUTCString()},"/"===i.slice(-1)||(t[i]["Content-Length"]=(0,s.getInteger)(o,"http://www.w3.org/ns/posix/stat#size")),t}),{});return Promise.resolve({statusCode:200,body:t,contentType:"application/json; charset=UTF-8"})})).catch((e=>e instanceof s.FetchError&&404===e.statusCode?Promise.resolve({statusCode:200,body:{},contentType:"application/json; charset=UTF-8"}):Promise.reject("Failed to get container: "+e.message))):(0,s.getFile)(r,{fetch:this.session.fetch}).then((e=>n(this,void 0,void 0,(function*(){return{statusCode:200,body:yield e.text(),contentType:(0,s.getContentType)(e)}})))).catch((e=>{const t=e.statusCode;return 401===t||403===t||404===t?{statusCode:t}:Promise.reject("Failed to get the file: "+e.message)}))}put(e,t,r,n={}){console.log("Solid put",e,r);const i=this.getFileURL(e),o=this.session.fetch,a=function(){const e=function(e){if("object"==typeof e){if(e instanceof h.default)return e;if(e instanceof DataView)return new h.default([e],{type:"application/octet-stream"});if(e instanceof ArrayBuffer)return new h.default([new DataView(e)]);if(ArrayBuffer.isView(e))return new h.default([e],{type:"application/octet-stream"});if(e instanceof FormData)return new h.default([new URLSearchParams([JSON.parse(JSON.stringify(e.entries()))]).toString()],{type:"application/x-www-form-urlencoded"});if(e instanceof URLSearchParams)return new h.default([e.toString()],{type:"application/x-www-form-urlencoded"})}return"string"==typeof e?new h.default([e],{type:"plain/text"}):new h.default([JSON.stringify(e)],{type:"application/json"})}(t);return(0,s.overwriteFile)(i,e,{contentType:r,fetch:o}).then((e=>({statusCode:201}))).catch((e=>Promise.reject("PUT failed with status "+e.statusCode+" ("+e.message+")")))};return(0,s.getFile)(i,{fetch:o}).then((e=>n&&"*"===n.ifNoneMatch?{statusCode:412,revision:"conflict"}:a())).catch((e=>{const t=e.statusCode;return 404===t?a():Promise.reject("PUT failed with status "+t+" ("+e.message+")")}))}delete(e,t={}){console.log("Solid delete",e);const r=this.getFileURL(e);return(0,s.deleteFile)(r,{fetch:this.session.fetch}).then((()=>({statusCode:200}))).catch((e=>{const t=e.statusCode;return 404===t?{statusCode:200}:Promise.reject("DELETE failed with status "+t+" ("+e.message+")")}))}static _rs_init(e){const t=new g(e);var r;e.solid=t,"solid"===e.backend&&(e._origRemote=e.remote,e.remote=e.solid,(r=e)._origBaseClientGetItemURL||(r._origBaseClientGetItemURL=a.default.prototype.getItemURL,a.default.prototype.getItemURL=function(e){if(console.log("getItemURL from",e),"string"!=typeof e)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(e.startsWith("/")&&(e=e.substring(1)),console.log("getItemURL to",this.selectedPodURL+(0,l.cleanPath)(e)),this.selectedPodURL+(0,l.cleanPath)(e)):void 0}),(()=>{n(this,void 0,void 0,(function*(){const r=t.session;if(yield r.handleIncomingRedirect(),r.info.isLoggedIn){const n=r.info.webId;t.userAddress=n,t.selectedPodURL?t._emit("connected"):(t.podURLs=yield(0,s.getPodUrlAll)(n,{fetch:fetch}),e._emit("pod-not-selected"))}else t.sessionProperties&&t.connect()}))})())}static _rs_supported(){return!0}static _rs_cleanup(e){var t;e.setBackend(void 0),e._origRemote&&(e.remote=e._origRemote,delete e._origRemote),(t=e)._origBaseClientGetItemURL&&(a.default.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)}}(0,l.applyMixins)(g,[c.default]),e.exports=g},7398:function(e,t){"use strict";var r=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});class n{get storage(){return window.localStorage}get(e){return r(this,void 0,void 0,(function*(){return this.storage.getItem(e)||void 0}))}set(e,t){return r(this,void 0,void 0,(function*(){this.storage.setItem(e,t)}))}delete(e){return r(this,void 0,void 0,(function*(){this.storage.removeItem(e)}))}}t.default=class{constructor(e){this.browserStorage=new n,this.observer=e}isConfigKey(e){return e.startsWith("solidClientAuthenticationUser")}setConfig(e){this.config=e}get(e){return r(this,void 0,void 0,(function*(){if(this.isConfigKey(e))return this.config;this.browserStorage.get(e)}))}set(e,t){return r(this,void 0,void 0,(function*(){if(this.isConfigKey(e)){if(this.config){const e=JSON.parse(this.config),r=JSON.parse(t),n=Object.assign(Object.assign({},e),r);this.config=JSON.stringify(n)}else this.config=t;this.observer.onConfigChanged(this.config)}else this.browserStorage.set(e,t)}))}delete(e){return r(this,void 0,void 0,(function*(){this.isConfigKey(e)?(this.config=void 0,this.observer.onConfigChanged(this.config)):this.browserStorage.delete(e)}))}}},6982:function(e){"use strict";class t extends Error{constructor(e){super(),this.name="SyncError",this.message="Sync failed: ","string"==typeof e?this.message+=e:(this.message+=e.message,this.stack=e.stack,this.originalError=e)}}e.exports=t},313:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Sync=void 0;const o=i(r(7028)),s=i(r(9451)),a=i(r(93)),c=i(r(3334)),l=i(r(3275)),u=i(r(6982)),d=i(r(5503)),h=r(7746);let f,p;function g(e,t,r){return{action:e,path:t,promise:r}}function y(e,t){return e.common.revision!==t&&(!e.remote||e.remote.revision!==t)}function m(e){return e.common&&e.common.revision}class v{constructor(e){this._finishedTasks=[],this.rs=e,this._tasks={},this._running={},this._timeStarted={},this.numThreads=10,this.rs.local.onDiff((e=>{this.addTask(e),this.doTasks()})),this.rs.caching.onActivate((e=>{this.addTask(e),this.doTasks()})),this.addEvents(["done","req-done"])}now(){return(new Date).getTime()}queueGetRequest(e){return new Promise(((t,r)=>{this.rs.remote.connected?this.rs.remote.online?(this.addTask(e,function(){this.rs.local.get(e).then((e=>t(e)))}.bind(this)),this.doTasks()):r("cannot fulfill maxAge requirement - remote is not online"):r("cannot fulfill maxAge requirement - remote is not connected")}))}corruptServerItemsMap(e,t){if("object"!=typeof e||Array.isArray(e))return!0;for(const r in e){const n=e[r];if("object"!=typeof n)return!0;if("string"!=typeof n.ETag)return!0;if((0,h.isFolder)(r)){if(-1!==r.substring(0,r.length-1).indexOf("/"))return!0}else{if(-1!==r.indexOf("/"))return!0;if(t){if("string"!=typeof n["Content-Type"])return!0;if("number"!=typeof n["Content-Length"])return!0}}}return!1}corruptItemsMap(e){if("object"!=typeof e||Array.isArray(e))return!0;for(const t in e)if("boolean"!=typeof e[t])return!0;return!1}corruptRevision(e){return"object"!=typeof e||Array.isArray(e)||e.revision&&"string"!=typeof e.revision||e.body&&"string"!=typeof e.body&&"object"!=typeof e.body||e.contentType&&"string"!=typeof e.contentType||e.contentLength&&"number"!=typeof e.contentLength||e.timestamp&&"number"!=typeof e.timestamp||e.itemsMap&&this.corruptItemsMap(e.itemsMap)}isCorrupt(e){return"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.path||this.corruptRevision(e.common)||e.local&&this.corruptRevision(e.local)||e.remote&&this.corruptRevision(e.remote)||e.push&&this.corruptRevision(e.push)}hasTasks(){return Object.getOwnPropertyNames(this._tasks).length>0}collectDiffTasks(){return n(this,void 0,void 0,(function*(){let e=0;return this.rs.local.forAllNodes((t=>{e>100||(this.isCorrupt(t)?((0,c.default)("[Sync] WARNING: corrupt node in local cache",t),"object"==typeof t&&t.path&&(this.addTask(t.path),e++)):(this.needsFetch(t)&&this.rs.access.checkPathPermission(t.path,"r")||(0,h.isDocument)(t.path)&&this.needsPush(t)&&this.rs.access.checkPathPermission(t.path,"rw"))&&(this.addTask(t.path),e++))})).then((()=>e)).catch((e=>{throw e}))}))}inConflict(e){return e.local&&e.remote&&(void 0!==e.remote.body||e.remote.itemsMap)}needsRefresh(e){return!!e.common&&(!e.common.timestamp||this.now()-e.common.timestamp>o.default.syncInterval)}needsFetch(e){return!!this.inConflict(e)||!(!e.common||void 0!==e.common.itemsMap||void 0!==e.common.body)||!(!e.remote||void 0!==e.remote.itemsMap||void 0!==e.remote.body)}needsPush(e){return!this.inConflict(e)&&(!(!e.local||e.push)||void 0)}needsRemotePut(e){return e.local&&e.local.body}needsRemoteDelete(e){return e.local&&!1===e.local.body}getParentPath(e){const t=e.match(/^(.*\/)([^\/]+\/?)$/);if(t)return t[1];throw new Error('Not a valid path: "'+e+'"')}deleteChildPathsFromTasks(){for(const e in this._tasks){const t=(0,h.pathsFromRoot)(e);for(let r=1;r{let t;if(this.needsRefresh(e)){try{t=this.getParentPath(e.path)}catch(e){}t&&this.rs.access.checkPathPermission(t,"r")?this.addTask(t):this.rs.access.checkPathPermission(e.path,"r")&&this.addTask(e.path)}})).then((()=>this.deleteChildPathsFromTasks())).catch((e=>{throw e}))}))}flush(e){for(const t in e)"FLUSH"===this.rs.caching.checkPath(t)&&e[t]&&!e[t].local&&((0,c.default)("[Sync] Flushing",t),e[t]=void 0);return e}doTask(e){return this.rs.local.getNodes([e]).then((t=>{const r=t[e];return void 0===r||function(e){return e.remote&&e.remote.revision&&!e.remote.itemsMap&&!e.remote.body}(r)?g("get",e,this.rs.remote.get(e)):this.needsRemotePut(r)?(r.push=(0,h.deepClone)(r.local),r.push.timestamp=this.now(),this.rs.local.setNodes(this.flush(t)).then((()=>{let t;return t=m(r)?{ifMatch:r.common.revision}:{ifNoneMatch:"*"},g("put",e,this.rs.remote.put(e,r.push.body,r.push.contentType,t))}))):this.needsRemoteDelete(r)?(r.push={body:!1,timestamp:this.now()},this.rs.local.setNodes(this.flush(t)).then((()=>m(r)?g("delete",e,this.rs.remote.delete(e,{ifMatch:r.common.revision})):g("get",e,this.rs.remote.get(e))))):m(r)?g("get",e,this.rs.remote.get(e,{ifNoneMatch:r.common.revision})):g("get",e,this.rs.remote.get(e))}))}autoMergeFolder(e){if(e.remote.itemsMap&&(e.common=e.remote,delete e.remote,e.common.itemsMap)){for(const t in e.common.itemsMap)e.local.itemsMap[t]||(e.local.itemsMap[t]=!1);(0,h.equal)(e.local.itemsMap,e.common.itemsMap)&&delete e.local}return e}autoMergeDocument(e){return function(e){return(!e.remote||!e.remote.revision||e.remote.revision===e.common.revision)&&(void 0===e.common.body&&!1===e.remote.body||e.remote.body===e.common.body&&e.remote.contentType===e.common.contentType)}(e)?delete(e=function(e){return e.remote&&!1===e.remote.body&&e.local&&!1===e.local.body&&delete e.local,e}(e)).remote:void 0!==e.remote.body&&((0,c.default)("[Sync] Emitting keep/revert"),this.rs.local._emitChange({origin:"conflict",path:e.path,oldValue:e.local.body,newValue:e.remote.body,lastCommonValue:e.common.body,oldContentType:e.local.contentType,newContentType:e.remote.contentType,lastCommonContentType:e.common.contentType}),e.remote.body?e.common=e.remote:e.common={},delete e.remote,delete e.local),e}autoMerge(e){if(e.remote){if(e.local)return(0,h.isFolder)(e.path)?this.autoMergeFolder(e):this.autoMergeDocument(e);if((0,h.isFolder)(e.path))void 0!==e.remote.itemsMap&&(e.common=e.remote,delete e.remote);else if(void 0!==e.remote.body){const t={origin:"remote",path:e.path,oldValue:!1===e.common.body?void 0:e.common.body,newValue:!1===e.remote.body?void 0:e.remote.body,oldContentType:e.common.contentType,newContentType:e.remote.contentType};if((t.oldValue||t.newValue)&&this.rs.local._emitChange(t),!e.remote.body)return;e.common=e.remote,delete e.remote}return e}e.common.body&&this.rs.local._emitChange({origin:"remote",path:e.path,oldValue:e.common.body,newValue:void 0,oldContentType:e.common.contentType,newContentType:void 0})}updateCommonTimestamp(e,t){return n(this,void 0,void 0,(function*(){return this.rs.local.getNodes([e]).then((r=>(r[e]&&r[e].common&&r[e].common.revision===t&&(r[e].common.timestamp=this.now()),this.rs.local.setNodes(this.flush(r)))))}))}markChildren(e,t,r,i){return n(this,void 0,void 0,(function*(){const n=[],o={},s={};for(const r in t)n.push(e+r),o[e+r]=t[r];for(const t in i)n.push(e+t);return this.rs.local.getNodes(n).then((t=>{let n,a;for(const c in t)if(a=t[c],o[c])a&&a.common?y(a,o[c].ETag)&&(r[c]=(0,h.deepClone)(a),r[c].remote={revision:o[c].ETag,timestamp:this.now()},r[c]=this.autoMerge(r[c])):(n=this.rs.caching.checkPath(c),"ALL"===n&&(r[c]={path:c,common:{timestamp:this.now()},remote:{revision:o[c].ETag,timestamp:this.now()}})),r[c]&&o[c]["Content-Type"]&&(r[c].remote.contentType=o[c]["Content-Type"]),r[c]&&o[c]["Content-Length"]&&(r[c].remote.contentLength=o[c]["Content-Length"]);else if(i[c.substring(e.length)]&&a&&a.common){if(a.common.itemsMap)for(const e in a.common.itemsMap)s[c+e]=!0;if(a.local&&a.local.itemsMap)for(const e in a.local.itemsMap)s[c+e]=!0;if(a.remote||(0,h.isFolder)(c))r[c]=void 0;else if(r[c]=this.autoMerge(a),void 0===r[c]){const t=this.getParentPath(c),n=r[t],i=c.substring(e.length);n&&n.local&&(delete n.local.itemsMap[i],(0,h.equal)(n.local.itemsMap,n.common.itemsMap)&&delete n.local)}}return this.deleteRemoteTrees(Object.keys(s),r).then((e=>this.rs.local.setNodes(this.flush(e))))}))}))}deleteRemoteTrees(e,t){return n(this,void 0,void 0,(function*(){return 0===e.length?Promise.resolve(t):this.rs.local.getNodes(e).then((e=>n(this,void 0,void 0,(function*(){const r={};function n(e,t){if(e&&e.itemsMap)for(const n in e.itemsMap)r[t+n]=!0}for(const r in e){const i=e[r];i&&((0,h.isFolder)(r)?(n(i.common,r),n(i.local,r)):i.common&&void 0!==typeof i.common.body&&(t[r]=(0,h.deepClone)(i),t[r].remote={body:!1,timestamp:this.now()},t[r]=this.autoMerge(t[r])))}return this.deleteRemoteTrees(Object.keys(r),t).then((e=>this.rs.local.setNodes(this.flush(e))))}))))}))}completeFetch(e,t,r,i){return n(this,void 0,void 0,(function*(){let n,o;const s=(0,h.pathsFromRoot)(e);return(0,h.isFolder)(e)?n=[e]:(o=s[1],n=[e,o]),this.rs.local.getNodes(n).then((n=>{let s,a,c=n[e];const l={};function u(e){if(e&&e.itemsMap)for(s in e.itemsMap)t[s]||(l[s]=!0)}if("object"==typeof c&&c.path===e&&"object"==typeof c.common||(c={path:e,common:{}},n[e]=c),c.remote={revision:i,timestamp:this.now()},(0,h.isFolder)(e))for(s in u(c.common),u(c.remote),c.remote.itemsMap={},t)c.remote.itemsMap[s]=!0;else c.remote.body=t,c.remote.contentType=r,a=n[o],a&&a.local&&a.local.itemsMap&&(s=e.substring(o.length),a.local.itemsMap[s]=!0,(0,h.equal)(a.local.itemsMap,a.common.itemsMap)&&delete a.local);return n[e]=this.autoMerge(c),{toBeSaved:n,missingChildren:l}}))}))}completePush(e,t,r,i){return n(this,void 0,void 0,(function*(){return this.rs.local.getNodes([e]).then((n=>{const o=n[e];if(!o.push)throw this.stopped=!0,new Error("completePush called but no push version!");return r?((0,c.default)("[Sync] We have a conflict"),o.remote&&o.remote.revision===i||(o.remote={revision:i||"conflict",timestamp:this.now()},delete o.push),n[e]=this.autoMerge(o)):(o.common={revision:i,timestamp:this.now()},"put"===t?(o.common.body=o.push.body,o.common.contentType=o.push.contentType,(0,h.equal)(o.local.body,o.push.body)&&o.local.contentType===o.push.contentType&&delete o.local,delete o.push):"delete"===t&&(!1===o.local.body?n[e]=void 0:delete o.push)),this.rs.local.setNodes(this.flush(n))}))}))}dealWithFailure(e){return n(this,void 0,void 0,(function*(){return this.rs.local.getNodes([e]).then((t=>{if(t[e])return delete t[e].push,this.rs.local.setNodes(this.flush(t))}))}))}interpretStatus(e){const t={statusCode:e,successful:void 0,conflict:void 0,unAuth:void 0,notFound:void 0,changed:void 0,networkProblems:void 0};if("string"==typeof e&&("offline"===e||"timeout"===e))return t.successful=!1,t.networkProblems=!0,t;if("number"==typeof e){const r=Math.floor(e/100);return t.successful=2===r||304===e||412===e||404===e,t.conflict=412===e,t.unAuth=401===e&&this.rs.remote.token!==l.default.IMPLIED_FAKE_TOKEN||402===e||403===e,t.notFound=404===e,t.changed=304!==e,t}}handleGetResponse(e,t,r,i,o){return n(this,void 0,void 0,(function*(){return t.notFound&&(r=!!(0,h.isFolder)(e)&&{}),t.changed?this.completeFetch(e,r,i,o).then((t=>(0,h.isFolder)(e)?this.corruptServerItemsMap(r)?((0,c.default)("[Sync] WARNING: Discarding corrupt folder description from server for "+e),!1):this.markChildren(e,r,t.toBeSaved,t.missingChildren).then((()=>!0)):this.rs.local.setNodes(this.flush(t.toBeSaved)).then((()=>!0)))):this.updateCommonTimestamp(e,o).then((()=>!0))}))}handleResponse(e,t,r){const n=this.interpretStatus(r.statusCode);if(n.successful){if("get"===t)return this.handleGetResponse(e,n,r.body,r.contentType,r.revision);if("put"===t||"delete"===t)return this.completePush(e,t,n.conflict,r.revision).then((function(){return!0}));throw new Error(`cannot handle response for unknown action ${t}`)}{let t;return t=n.unAuth?new d.default:n.networkProblems?new u.default("Network request failed."):new Error("HTTP response code "+n.statusCode+" received."),this.dealWithFailure(e).then((()=>{throw this.rs._emit("error",t),t}))}}finishTask(e,t=!0){if(void 0!==e.action){if(!(t&&((0,c.default)("[Sync] queue finished task:",e.path),this._finishedTasks.push(e),this._finishedTasks.length>1)))return(0,c.default)("[Sync] run task:",e.path),e.promise.then((t=>this.handleResponse(e.path,e.action,t)),(t=>((0,c.default)("[Sync] wireclient rejects its promise!",e.path,e.action,t),this.handleResponse(e.path,e.action,{statusCode:"offline"})))).then((t=>n(this,void 0,void 0,(function*(){if(this._finishedTasks.shift(),delete this._timeStarted[e.path],delete this._running[e.path],t&&this._tasks[e.path]){for(let t=0;t0?this.finishTask(this._finishedTasks[0],!1):yield this.collectTasks(!1).then((()=>{!this.hasTasks()||this.stopped?((0,c.default)("[Sync] Sync is done! Reschedule?",Object.getOwnPropertyNames(this._tasks).length,this.stopped),this.done||(this.done=!0,this.rs._emit("sync-done",{completed:!0}))):setTimeout((()=>{this.doTasks()}),10)}))}))),(t=>{(0,c.default)("[Sync] Error",t),this._finishedTasks.shift(),delete this._timeStarted[e.path],delete this._running[e.path],this.rs._emit("sync-req-done",{tasksRemaining:Object.keys(this._tasks).length}),this._finishedTasks.length>0?this.finishTask(this._finishedTasks[0],!1):this.done||(this.done=!0,this.rs._emit("sync-done",{completed:!1}))}));(0,c.default)("[Sync] delaying finished task:",e.path)}else delete this._running[e.path]}doTasks(){let e,t,r=0;e=this.rs.remote.connected?this.rs.remote.online?this.numThreads:1:0;const n=e-Object.getOwnPropertyNames(this._running).length;if(n<=0)return!0;for(t in this._tasks)if(!this._running[t]&&(this._timeStarted[t]=this.now(),this._running[t]=this.doTask(t),this._running[t].then(this.finishTask.bind(this)),r++,r>=n))return!0;return r>=n}collectTasks(e){return n(this,void 0,void 0,(function*(){return this.hasTasks()||this.stopped?Promise.resolve():this.collectDiffTasks().then((t=>t||!1===e?Promise.resolve():this.collectRefreshTasks()),(function(e){throw e}))}))}addTask(e,t){this._tasks[e]||(this._tasks[e]=[]),"function"==typeof t&&this._tasks[e].push(t)}sync(){return this.done=!1,this.doTasks()?Promise.resolve():this.collectTasks().then((()=>{try{this.doTasks()}catch(e){(0,c.default)("[Sync] doTasks error",e)}}),(function(e){throw(0,c.default)("[Sync] Sync error",e),new Error("Local cache unavailable")}))}static _rs_init(e){f=function(){(0,c.default)("[Sync] syncCycleCb calling syncCycle");const t=new s.default;t.isBrowser()&&function(e,t){function r(e){const r=t.getCurrentSyncInterval();o.default.isBackground=!e;const n=t.getCurrentSyncInterval();t._emit("sync-interval-change",{oldValue:r,newValue:n})}e.on("background",(()=>r(!1))),e.on("foreground",(()=>r(!0)))}(t,e),e.sync||(e.sync=new v(e),e.syncStopped&&((0,c.default)("[Sync] Instantiating sync stopped"),e.sync.stopped=!0,delete e.syncStopped)),(0,c.default)("[Sync] syncCycleCb calling syncCycle"),e.syncCycle()},p=function(){e.removeEventListener("connected",p),e.startSync()},e.on("ready",f),e.on("connected",p)}static _rs_cleanup(e){e.stopSync(),e.removeEventListener("ready",f),e.removeEventListener("connected",p),e.sync=void 0,delete e.sync}}t.Sync=v,(0,h.applyMixins)(v,[a.default]),t.default=v},1370:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};const i=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(3334));function o(e){return"dropbox"===this.backend&&!!e.match(/^\/public\/.*[^\/]$/)}const s={get:function(e,t){if(this.local){if(void 0===t)t="object"==typeof(r=this).remote&&r.remote.connected&&r.remote.online?2*r.getSyncInterval():((0,i.default)("Not setting default maxAge, because remote is offline or not connected"),!1);else if("number"!=typeof t&&!1!==t)return Promise.reject("Argument 'maxAge' must be 'false' or a number");return this.local.get(e,t,this.sync.queueGetRequest.bind(this.sync))}return this.remote.get(e);var r},put:function(e,t,r){return o.bind(this)(e)?s._wrapBusyDone.call(this,this.remote.put(e,t,r)):this.local?this.local.put(e,t,r):s._wrapBusyDone.call(this,this.remote.put(e,t,r))},delete:function(e){return this.local?this.local.delete(e):s._wrapBusyDone.call(this,this.remote.delete(e))},_wrapBusyDone:function(e){return n(this,void 0,void 0,(function*(){return this._emit("wire-busy"),e.then((e=>(this._emit("wire-done",{success:!0}),Promise.resolve(e))),(e=>(this._emit("wire-done",{success:!1}),Promise.reject(e))))}))}};e.exports=s},1613:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClientTypes=void 0;class r{constructor(){this.uris={},this.schemas={},this.aliases={}}declare(e,t,r,n){const i=e+"/"+t;if(n.extends){const t=n.extends.split("/"),r=1===t.length?e+"/"+t.shift():t.join("/"),o=this.uris[r];if(!o)throw"Type '"+i+"' tries to extend unknown schema '"+r+"'";n.extends=this.schemas[o]}this.uris[i]=r,this.aliases[r]=i,this.schemas[r]=n}resolveAlias(e){return this.uris[e]}getSchema(e){return this.schemas[e]}inScope(e){const t=e.length,r={};for(const n in this.uris)if(n.substr(0,t+1)===e+"/"){const e=this.uris[n];r[e]=this.schemas[e]}return r}}t.BaseClientTypes=r;const n=new r;t.default=n},5503:function(e){"use strict";class t extends Error{constructor(e,t={}){super(),this.name="Unauthorized",this.message=void 0===e?"App authorization expired or revoked.":e,void 0!==t.code&&(this.code=t.code),this.stack=(new Error).stack}}e.exports=t},7746:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};function i(e,t){if("object"==typeof e&&!Array.isArray(e)&&null!==e)for(const r in e)if("object"==typeof e[r]&&null!==e[r])if("[object ArrayBuffer]"===e[r].toString()){t[r]=new ArrayBuffer(e[r].byteLength);const n=new Int8Array(e[r]);new Int8Array(t[r]).set(n)}else i(e[r],t[r])}Object.defineProperty(t,"__esModule",{value:!0}),t.toBase64=t.getTextFromArrayBuffer=t.shouldBeTreatedAsBinary=t.getJSONFromLocalStorage=t.localStorageAvailable=t.pathsFromRoot=t.deepClone=t.equal=t.bindAll=t.cleanPath=t.baseName=t.isDocument=t.isFolder=t.containingFolder=t.extend=t.getGlobalContext=t.globalContext=t.logError=void 0,t.generateCodeVerifier=function(){return n(this,arguments,void 0,(function*(e=128){const t=new Uint8Array(e);crypto.getRandomValues(t);const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=Array.from(t).map((e=>r[e%66])),i=n.join(""),o=Uint8Array.from(n.map((e=>e.charCodeAt(0)))),s=(a=yield crypto.subtle.digest("SHA-256",o),btoa(String.fromCharCode.apply(null,new Uint8Array(a))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""));var a;return crypto.getRandomValues(t),{codeVerifier:i,codeChallenge:s,state:Array.from(t).map((e=>r[e%66])).join("")}}))},t.applyMixins=function(e,t){t.forEach((t=>{Object.getOwnPropertyNames(t.prototype).forEach((r=>{Object.defineProperty(e.prototype,r,Object.getOwnPropertyDescriptor(t.prototype,r))}))}))},t.logError=e=>{"string"==typeof e?console.error(e):console.error(e.message,e.stack)},t.globalContext="undefined"!=typeof window?window:"object"==typeof self?self:r.g,t.getGlobalContext=()=>"undefined"!=typeof window?window:"object"==typeof self?self:r.g,t.extend=(...e)=>{const t=e[0];return Array.prototype.slice.call(e,1).forEach((function(e){for(const r in e)t[r]=e[r]})),t},t.containingFolder=e=>{if(""===e)return"/";if(!e)throw"Path not given!";return e.replace(/\/+/g,"/").replace(/[^\/]+\/?$/,"")},t.isFolder=e=>"/"===e.slice(-1),t.isDocument=e=>!(0,t.isFolder)(e),t.baseName=e=>{const r=e.split("/");return(0,t.isFolder)(e)?r[r.length-2]+"/":r[r.length-1]},t.cleanPath=e=>e.replace(/\/+/g,"/").split("/").map(encodeURIComponent).join("/").replace(/'/g,"%27"),t.bindAll=e=>{for(const t in this)"function"==typeof e[t]&&(e[t]=e[t].bind(e))},t.equal=(e,r,n=[])=>{let i;if(typeof e!=typeof r)return!1;if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return e===r;if("function"==typeof e)return e.toString()===r.toString();if(e instanceof ArrayBuffer&&r instanceof ArrayBuffer&&(e=new Uint8Array(e),r=new Uint8Array(r)),e instanceof Array){if(e.length!==r.length)return!1;for(let i=0,o=e.length;i=0)continue;o=n.slice(),o.push(r[i])}if(!(0,t.equal)(e[i],r[i],o))return!1}}return!0},t.deepClone=e=>{if(void 0!==e){const t=JSON.parse(JSON.stringify(e));return i(e,t),t}},t.pathsFromRoot=e=>{const t=[e],r=e.replace(/\/$/,"").split("/");for(;r.length>1;)r.pop(),t.push(r.join("/")+"/");return t},t.localStorageAvailable=()=>{const e=(0,t.getGlobalContext)();if(!("localStorage"in e))return!1;try{return e.localStorage.setItem("rs-check","1"),e.localStorage.removeItem("rs-check"),!0}catch(e){return!1}},t.getJSONFromLocalStorage=e=>{const r=(0,t.getGlobalContext)();try{return JSON.parse(r.localStorage.getItem(e))}catch(e){}},t.shouldBeTreatedAsBinary=(e,t)=>!!(t&&t.match(/charset=binary/)||/[\x00-\x08\x0E-\x1F\uFFFD]/.test(e)),t.getTextFromArrayBuffer=(e,r)=>new Promise((n=>{if("undefined"==typeof Blob||"undefined"==typeof FileReader){const t=Buffer.from(e);n(t.toString(r))}else{let i;const o=t.globalContext;if(o.BlobBuilder=o.BlobBuilder||o.WebKitBlobBuilder,void 0!==o.BlobBuilder){const t=new o.BlobBuilder;t.append(e),i=t.getBlob()}else i=new Blob([e]);const s=new FileReader;"function"==typeof s.addEventListener?s.addEventListener("loadend",(function(e){n(e.target.result)})):s.onloadend=function(e){n(e.target.result)},s.readAsText(i,r)}})),t.toBase64=e=>{const r=(0,t.getGlobalContext)();return"btoa"in r?r.btoa(e):Buffer.from(e).toString("base64")}},600:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(3275)),s=i(r(93)),a=i(r(5503)),c=i(r(3334)),l=r(7746),u=r(368),d=r(3684);let h;const f="remotestorage:wireclient",p={"draft-dejong-remotestorage-00":2,"draft-dejong-remotestorage-01":3,"draft-dejong-remotestorage-02":4,"https://www.w3.org/community/rww/wiki/read-write-web-00#simple":1};class g extends d.RemoteBase{constructor(e){if(super(e),this._revisionCache={},h=(0,l.localStorageAvailable)(),this.addEvents(["connected","not-connected"]),h){const e=function(){const e=(0,l.getJSONFromLocalStorage)(f)||{},{userAddress:t,href:r,storageApi:n,token:i,properties:o}=e;return{userAddress:t,href:r,storageApi:n,token:i,properties:o}}();e&&setTimeout((()=>{this.configure(e)}),0)}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}get storageType(){if(this.storageApi){const e=this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/);return e?e[1]:"2012.04"}}_request(e,t,r,i,s,d,h){return n(this,void 0,void 0,(function*(){if(this.isForbiddenRequestMethod(e,t))return Promise.reject(`Don't use ${e} on directories!`);let n;return r!==o.default.IMPLIED_FAKE_TOKEN&&(i.Authorization="Bearer "+r),this.rs._emit("wire-busy",{method:e,isFolder:(0,l.isFolder)(t)}),(0,u.requestWithTimeout)(e,t,{body:s,headers:i,responseType:"arraybuffer"}).then((r=>{if(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,l.isFolder)(t),success:!0}),i=r.status,[401,403,404,412].indexOf(i)>=0)return(0,c.default)("[WireClient] Error response status",r.status),n=d?this.stripQuotes(r.getResponseHeader("ETag")):void 0,401===r.status&&this.rs._emit("error",new a.default),Promise.resolve({statusCode:r.status,revision:n});if(function(e){return[201,204,304].indexOf(e)>=0}(r.status)||200===r.status&&"GET"!==e)return n=this.stripQuotes(r.getResponseHeader("ETag")),(0,c.default)("[WireClient] Successful request",n),Promise.resolve({statusCode:r.status,revision:n});{const e=r.getResponseHeader("Content-Type");n=d?this.stripQuotes(r.getResponseHeader("ETag")):200===r.status?h:void 0;const t=function(e){let t,r="utf-8";return e&&(t=e.match(/charset=(.+)$/),t&&(r=t[1])),r}(e);return(0,l.shouldBeTreatedAsBinary)(r.response,e)?((0,c.default)("[WireClient] Successful request with unknown or binary mime-type",n),Promise.resolve({statusCode:r.status,body:r.response,contentType:e,revision:n})):(0,l.getTextFromArrayBuffer)(r.response,t).then((t=>((0,c.default)("[WireClient] Successful request",n),Promise.resolve({statusCode:r.status,body:t,contentType:e,revision:n}))))}var i}),(r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,l.isFolder)(t),success:!1}),Promise.reject(r))))}))}configure(e){if("object"!=typeof e)throw new Error("WireClient configure settings parameter should be an object");if(void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.href&&(this.href=e.href),void 0!==e.storageApi&&(this.storageApi=e.storageApi),void 0!==e.token&&(this.token=e.token),void 0!==e.properties&&(this.properties=e.properties),"string"==typeof this.storageApi){const e=p[this.storageApi]||5;this.supportsRevs=e>=2}this.href&&this.token?(this.connected=!0,this.online=!0,this._emit("connected")):this.connected=!1,h&&(localStorage[f]=JSON.stringify({userAddress:this.userAddress,href:this.href,storageApi:this.storageApi,token:this.token,properties:this.properties}))}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const r={};return this.supportsRevs&&t.ifNoneMatch&&(r["If-None-Match"]=this.addQuotes(t.ifNoneMatch)),this._request("GET",this.href+(0,l.cleanPath)(e),this.token,r,void 0,this.supportsRevs,this._revisionCache[e]).then((t=>{if(!(0,l.isFolder)(e))return Promise.resolve(t);let r={};if(void 0!==t.body)try{t.body=JSON.parse(t.body)}catch(t){return Promise.reject("Folder description at "+this.href+(0,l.cleanPath)(e)+" is not JSON")}if(200===t.statusCode&&"object"==typeof t.body){if(0===Object.keys(t.body).length)t.statusCode=404;else if("http://remotestorage.io/spec/folder-description"===(n=t.body)["@context"]&&"object"==typeof n.items){for(const r in t.body.items)this._revisionCache[e+r]=t.body.items[r].ETag;r=t.body.items}else Object.keys(t.body).forEach((n=>{this._revisionCache[e+n]=t.body[n],r[n]={ETag:t.body[n]}}));return t.body=r,Promise.resolve(t)}return Promise.resolve(t);var n}))}put(e,t,r,n={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");!r.match(/charset=/)&&(t instanceof ArrayBuffer||(0,u.isArrayBufferView)(t))&&(r+="; charset=binary");const i={"Content-Type":r};return this.supportsRevs&&(n.ifMatch&&(i["If-Match"]=this.addQuotes(n.ifMatch)),n.ifNoneMatch&&(i["If-None-Match"]=this.addQuotes(n.ifNoneMatch))),this._request("PUT",this.href+(0,l.cleanPath)(e),this.token,i,t,this.supportsRevs)}delete(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");t||(t={});const r={};return this.supportsRevs&&t.ifMatch&&(r["If-Match"]=this.addQuotes(t.ifMatch)),this._request("DELETE",this.href+(0,l.cleanPath)(e),this.token,r,void 0,this.supportsRevs)}static _rs_init(e){e.remote=new g(e),e.remote.online=!0}static _rs_supported(){return"function"==typeof fetch||"function"==typeof XMLHttpRequest}static _rs_cleanup(){h&&delete localStorage[f]}}(0,l.applyMixins)(g,[s.default]),e.exports=g},439:function(e,t){var r,n;r=function(){var e,t,r,n;Object.keys||(Object.keys=(e=Object.prototype.hasOwnProperty,t=!{toString:null}.propertyIsEnumerable("toString"),n=(r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length,function(i){if("object"!=typeof i&&"function"!=typeof i||null===i)throw new TypeError("Object.keys called on non-object");var o=[];for(var s in i)e.call(i,s)&&o.push(s);if(t)for(var a=0;a>>0;if(0===r)return-1;var n=0;if(arguments.length>1&&((n=Number(arguments[1]))!=n?n=0:0!==n&&n!==1/0&&n!==-1/0&&(n=(n>0||-1)*Math.floor(Math.abs(n)))),n>=r)return-1;for(var i=n>=0?n:Math.max(r-Math.abs(n),0);i0&&(t+=u.suffices["*"]&&r||",",u.suffices["*"]&&c&&(t+=u.name+"=")),t+=a?encodeURIComponent(d[f]).replace(/!/g,"%21"):s(d[f])}else if("object"==typeof d){c&&!u.suffices["*"]&&(t+=u.name+"=");var p=!0;for(var g in d)p||(t+=u.suffices["*"]&&r||","),p=!1,t+=a?encodeURIComponent(g).replace(/!/g,"%21"):s(g),t+=u.suffices["*"]?"=":",",t+=a?encodeURIComponent(d[g]).replace(/!/g,"%21"):s(d[g])}else c&&(t+=u.name,l&&""===d||(t+="=")),null!=u.truncate&&(d=d.substring(0,u.truncate)),t+=a?encodeURIComponent(d).replace(/!/g,"%21"):s(d)}return t};return w.varNames=u,{prefix:n,substitution:w}}function c(e){if(!(this instanceof c))return new c(e);for(var t=e.split("{"),r=[t.shift()],n=[],i=[],o=[];t.length>0;){var s=t.shift(),l=s.split("}")[0],u=s.substring(l.length+1),d=a(l);i.push(d.substitution),n.push(d.prefix),r.push(u),o=o.concat(d.substitution.varNames)}this.fill=function(e){for(var t=r[0],n=0;n0&&"/"===t.charAt(e.length-1)||"#"===r.charAt(0)||"?"===r.charAt(0))return!0}return!1}(t,e.id)&&void 0===this.schemas[e.id]&&(this.schemas[e.id]=e),e)if("enum"!==n)if("object"==typeof e[n])this.searchSchemas(e[n],t);else if("$ref"===n){var i=g(e[n]);i&&void 0===this.schemas[i]&&void 0===this.missingMap[i]&&(this.missingMap[i]=i)}},l.prototype.addSchema=function(e,t){if("string"!=typeof e||void 0===t){if("object"!=typeof e||"string"!=typeof e.id)return;e=(t=e).id}e===g(e)+"#"&&(e=g(e)),this.schemas[e]=t,delete this.missingMap[e],y(t,e),this.searchSchemas(t,e)},l.prototype.getSchemaMap=function(){var e={};for(var t in this.schemas)e[t]=this.schemas[t];return e},l.prototype.getSchemaUris=function(e){var t=[];for(var r in this.schemas)e&&!e.test(r)||t.push(r);return t},l.prototype.getMissingUris=function(e){var t=[];for(var r in this.missingMap)e&&!e.test(r)||t.push(r);return t},l.prototype.dropSchemas=function(){this.schemas={},this.reset()},l.prototype.reset=function(){this.missing=[],this.missingMap={},this.errors=[]},l.prototype.validateAll=function(e,t,r,n,i){var o;if(!(t=this.resolveRefs(t)))return null;if(t instanceof S)return this.errors.push(t),t;var s,a=this.errors.length,c=null,l=null;if(this.checkRecursive&&e&&"object"==typeof e){if(o=!this.scanned.length,e[this.validatedSchemasKey]){var u=e[this.validatedSchemasKey].indexOf(t);if(-1!==u)return this.errors=this.errors.concat(e[this.validationErrorsKey][u]),null}if(Object.isFrozen(e)&&-1!==(s=this.scannedFrozen.indexOf(e))){var d=this.scannedFrozenSchemas[s].indexOf(t);if(-1!==d)return this.errors=this.errors.concat(this.scannedFrozenValidationErrors[s][d]),null}if(this.scanned.push(e),Object.isFrozen(e))-1===s&&(s=this.scannedFrozen.length,this.scannedFrozen.push(e),this.scannedFrozenSchemas.push([])),c=this.scannedFrozenSchemas[s].length,this.scannedFrozenSchemas[s][c]=t,this.scannedFrozenValidationErrors[s][c]=[];else{if(!e[this.validatedSchemasKey])try{Object.defineProperty(e,this.validatedSchemasKey,{value:[],configurable:!0}),Object.defineProperty(e,this.validationErrorsKey,{value:[],configurable:!0})}catch(t){e[this.validatedSchemasKey]=[],e[this.validationErrorsKey]=[]}l=e[this.validatedSchemasKey].length,e[this.validatedSchemasKey][l]=t,e[this.validationErrorsKey][l]=[]}}var h=this.errors.length,f=this.validateBasic(e,t,i)||this.validateNumeric(e,t,i)||this.validateString(e,t,i)||this.validateArray(e,t,i)||this.validateObject(e,t,i)||this.validateCombinations(e,t,i)||this.validateHypermedia(e,t,i)||this.validateFormat(e,t,i)||this.validateDefinedKeywords(e,t,i)||null;if(o){for(;this.scanned.length;)delete this.scanned.pop()[this.validatedSchemasKey];this.scannedFrozen=[],this.scannedFrozenSchemas=[]}if(f||h!==this.errors.length)for(;r&&r.length||n&&n.length;){var p=r&&r.length?""+r.pop():null,g=n&&n.length?""+n.pop():null;f&&(f=f.prefixWith(p,g)),this.prefixErrors(h,p,g)}return null!==c?this.scannedFrozenValidationErrors[s][c]=this.errors.slice(a):null!==l&&(e[this.validationErrorsKey][l]=this.errors.slice(a)),this.handleError(f)},l.prototype.validateFormat=function(e,t){if("string"!=typeof t.format||!this.formatValidators[t.format])return null;var r=this.formatValidators[t.format].call(null,e,t);return"string"==typeof r||"number"==typeof r?this.createError(v.FORMAT_CUSTOM,{message:r},"","/format",null,e,t):r&&"object"==typeof r?this.createError(v.FORMAT_CUSTOM,{message:r.message||"?"},r.dataPath||"",r.schemaPath||"/format",null,e,t):null},l.prototype.validateDefinedKeywords=function(e,t,r){for(var n in this.definedKeywords)if(void 0!==t[n])for(var i=this.definedKeywords[n],o=0;o=d&&nt.maximum)return this.createError(v.NUMBER_MAXIMUM,{value:e,maximum:t.maximum},"","/maximum",null,e,t);if(t.exclusiveMaximum&&e===t.maximum)return this.createError(v.NUMBER_MAXIMUM_EXCLUSIVE,{value:e,maximum:t.maximum},"","/exclusiveMaximum",null,e,t)}return null},l.prototype.validateNaN=function(e,t){return"number"!=typeof e?null:!0===isNaN(e)||e===1/0||e===-1/0?this.createError(v.NUMBER_NOT_A_NUMBER,{value:e},"","/type",null,e,t):null},l.prototype.validateString=function(e,t,r){return this.validateStringLength(e,t,r)||this.validateStringPattern(e,t,r)||null},l.prototype.validateStringLength=function(e,t){return"string"!=typeof e?null:void 0!==t.minLength&&e.lengtht.maxLength?this.createError(v.STRING_LENGTH_LONG,{length:e.length,maximum:t.maxLength},"","/maxLength",null,e,t):null},l.prototype.validateStringPattern=function(e,t){if("string"!=typeof e||"string"!=typeof t.pattern&&!(t.pattern instanceof RegExp))return null;var r;if(t.pattern instanceof RegExp)r=t.pattern;else{var n,i="",o=t.pattern.match(/^\/(.+)\/([img]*)$/);o?(n=o[1],i=o[2]):n=t.pattern,r=new RegExp(n,i)}return r.test(e)?null:this.createError(v.STRING_PATTERN,{pattern:t.pattern},"","/pattern",null,e,t)},l.prototype.validateArray=function(e,t,r){return Array.isArray(e)&&(this.validateArrayLength(e,t,r)||this.validateArrayUniqueItems(e,t,r)||this.validateArrayItems(e,t,r))||null},l.prototype.validateArrayLength=function(e,t){var r;return void 0!==t.minItems&&e.lengtht.maxItems&&(r=this.createError(v.ARRAY_LENGTH_LONG,{length:e.length,maximum:t.maxItems},"","/maxItems",null,e,t),this.handleError(r))?r:null},l.prototype.validateArrayUniqueItems=function(e,t){if(t.uniqueItems)for(var r=0;rt.maxProperties&&(r=this.createError(v.OBJECT_PROPERTIES_MAXIMUM,{propertyCount:n.length,maximum:t.maxProperties},"","/maxProperties",null,e,t),this.handleError(r))?r:null},l.prototype.validateObjectRequiredProperties=function(e,t){if(void 0!==t.required)for(var r=0;r 10000");if(void 0!==v[e])throw new Error("Error already defined: "+e+" as "+v[e]);if(void 0!==b[t])throw new Error("Error code already used: "+b[t]+" as "+t);for(var n in v[e]=t,b[t]=e,_[e]=_[t]=r,E){var i=E[n];i[e]&&(i[t]=i[t]||i[e])}},reset:function(){i.reset(),this.error=null,this.missing=[],this.valid=!0},missing:[],error:null,valid:!0,normSchema:y,resolveUrl:p,getDocumentUri:g,errorCodes:v};return o.language(t||"en"),o}();return A.addLanguage("en-gb",_),A.tv4=A,A},void 0===(n=r.apply(t,[]))||(e.exports=n)},2831:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NIL",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(t,"parse",{enumerable:!0,get:function(){return d.default}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(t,"v1",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(t,"v3",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(t,"v4",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(t,"v5",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(t,"validate",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(t,"version",{enumerable:!0,get:function(){return c.default}});var n=h(r(3518)),i=h(r(4948)),o=h(r(5073)),s=h(r(7186)),a=h(r(4808)),c=h(r(7775)),l=h(r(7037)),u=h(r(9910)),d=h(r(6792));function h(e){return e&&e.__esModule?e:{default:e}}},2311:function(e,t){"use strict";function r(e){return 14+(e+64>>>9<<4)+1}function n(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function i(e,t,r,i,o,s){return n((a=n(n(t,e),n(i,s)))<<(c=o)|a>>>32-c,r);var a,c}function o(e,t,r,n,o,s,a){return i(t&r|~t&n,e,t,o,s,a)}function s(e,t,r,n,o,s,a){return i(t&n|r&~n,e,t,o,s,a)}function a(e,t,r,n,o,s,a){return i(t^r^n,e,t,o,s,a)}function c(e,t,r,n,o,s,a){return i(r^(t|~n),e,t,o,s,a)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;t.default=function(e){if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(let r=0;r>5]>>>i%32&255,o=parseInt(n.charAt(r>>>4&15)+n.charAt(15&r),16);t.push(o)}return t}(function(e,t){e[t>>5]|=128<>5]|=(255&e[r/8])<>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}},7656:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i},2858:function(e,t){"use strict";let r;Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){if(!r&&(r="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!r))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return r(n)};const n=new Uint8Array(16)},9042:function(e,t){"use strict";function r(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:case 3:return t^r^n;case 2:return t&r^t&n^r&n}}function n(e,t){return e<>>32-t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;t.default=function(e){const t=[1518500249,1859775393,2400959708,3395469782],i=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=[];for(let r=0;r>>0;d=u,u=l,l=n(c,30)>>>0,c=s,s=a}i[0]=i[0]+s>>>0,i[1]=i[1]+c>>>0,i[2]=i[2]+l>>>0,i[3]=i[3]+u>>>0,i[4]=i[4]+d>>>0}return[i[0]>>24&255,i[0]>>16&255,i[0]>>8&255,255&i[0],i[1]>>24&255,i[1]>>16&255,i[1]>>8&255,255&i[1],i[2]>>24&255,i[2]>>16&255,i[2]>>8&255,255&i[2],i[3]>>24&255,i[3]>>16&255,i[3]>>8&255,255&i[3],i[4]>>24&255,i[4]>>16&255,i[4]>>8&255,255&i[4]]}},9910:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.unsafeStringify=s;var n,i=(n=r(7037))&&n.__esModule?n:{default:n};const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));function s(e,t=0){return o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]}t.default=function(e,t=0){const r=s(e,t);if(!(0,i.default)(r))throw TypeError("Stringified UUID is invalid");return r}},3518:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,i=(n=r(2858))&&n.__esModule?n:{default:n},o=r(9910);let s,a,c=0,l=0;t.default=function(e,t,r){let n=t&&r||0;const u=t||new Array(16);let d=(e=e||{}).node||s,h=void 0!==e.clockseq?e.clockseq:a;if(null==d||null==h){const t=e.random||(e.rng||i.default)();null==d&&(d=s=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==h&&(h=a=16383&(t[6]<<8|t[7]))}let f=void 0!==e.msecs?e.msecs:Date.now(),p=void 0!==e.nsecs?e.nsecs:l+1;const g=f-c+(p-l)/1e4;if(g<0&&void 0===e.clockseq&&(h=h+1&16383),(g<0||f>c)&&void 0===e.nsecs&&(p=0),p>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");c=f,l=p,a=h,f+=122192928e5;const y=(1e4*(268435455&f)+p)%4294967296;u[n++]=y>>>24&255,u[n++]=y>>>16&255,u[n++]=y>>>8&255,u[n++]=255&y;const m=f/4294967296*1e4&268435455;u[n++]=m>>>8&255,u[n++]=255&m,u[n++]=m>>>24&15|16,u[n++]=m>>>16&255,u[n++]=h>>>8|128,u[n++]=255&h;for(let e=0;e<6;++e)u[n+e]=d[e];return t||(0,o.unsafeStringify)(u)}},4948:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=o(r(9025)),i=o(r(2311));function o(e){return e&&e.__esModule?e:{default:e}}var s=(0,n.default)("v3",48,i.default);t.default=s},9025:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.URL=t.DNS=void 0,t.default=function(e,t,r){function n(e,n,s,a){var c;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));const t=[];for(let r=0;r=301&&o.status<=302?function(e){return"string"==typeof e&&"https"===e.split("://")[0]}(o.getResponseHeader("Location"))?c():t(s({message:"no redirect URL found",url:e,status:o.status})):t(s({message:"error during request",url:e,status:o.status}))}function c(){o.onreadystatechange=function(){4===o.readyState&&a()},o.onload=function(){a()},o.ontimeout=function(){return t(s({message:"request timed out",url:e,status:o.status}))},o.open("GET",e,!0),o.timeout=n.config.request_timeout,o.setRequestHeader("Accept","application/jrd+json, application/json"),o.send()}return c()},a.prototype.__isValidJSON=function(e){try{JSON.parse(e)}catch(e){return!1}return!0},a.prototype.__isLocalhost=function(e){return/^localhost(\.localdomain)?(\:[0-9]+)?$/.test(e)},a.prototype.__processJRD=function(e,t,n,o){var a=JSON.parse(t);if("object"!=typeof a||"object"!=typeof a.links)return void 0!==a.error?n(s({message:a.error,request:e})):n(s({message:"unknown response from server",request:e}));var c=a.links;Array.isArray(c)||(c=[]);var l={object:a,json:t,idx:{}};l.idx.properties={name:void 0},l.idx.links=JSON.parse(JSON.stringify(i)),c.map((function(e,t){if(r.hasOwnProperty(e.rel)&&l.idx.links[r[e.rel]]){var n={};Object.keys(e).map((function(t,r){n[t]=e[t]})),l.idx.links[r[e.rel]].push(n)}}));var u=JSON.parse(t).properties;for(var d in u)u.hasOwnProperty(d)&&"http://packetizer.com/ns/name"===d&&(l.idx.properties.name=u[d]);return o(l)},a.prototype.lookup=function(e,t){if("string"!=typeof e)throw new Error("first parameter must be a user address");if("function"!=typeof t)throw new Error("second parameter must be a callback");var r=this,n="";n=e.indexOf("://")>-1?e.replace(/ /g,"").split("/")[2]:e.replace(/ /g,"").split("@")[1];var i=0,s="https";function a(){var t="";return e.split("://")[1]||(t="acct:"),s+"://"+n+"/.well-known/"+o[i]+"?resource="+t+e}function c(e){if(r.config.uri_fallback&&"webfist.org"!==n&&i!==o.length-1)return i+=1,l();if(!r.config.tls_only&&"https"===s)return i=0,s="http",l();if(!r.config.webfist_fallback||"webfist.org"===n)return t(e);i=0,s="http",n="webfist.org";var c=a();r.__fetchJRD(c,t,(function(e){r.__processJRD(c,e,t,(function(e){"object"==typeof e.idx.links.webfist&&"string"==typeof e.idx.links.webfist[0].href&&r.__fetchJRD(e.idx.links.webfist[0].href,t,(function(e){r.__processJRD(c,e,t,(function(e){return t(null,t)}))}))}))}))}function l(){var e=a();r.__fetchJRD(e,c,(function(n){r.__processJRD(e,n,t,(function(e){t(null,e)}))}))}return r.__isLocalhost(n)&&(s="http"),setTimeout(l,0)},a.prototype.lookupLink=function(e,t,r){if(!i.hasOwnProperty(t))return r("unsupported rel "+t);this.lookup(e,(function(e,n){var i=n.idx.links[t];return e?r(e):0===i.length?r('no links found with rel="'+t+'"'):r(null,i[0])}))},void 0===(n=function(){return a}.apply(t,[]))||(e.exports=n)}()},4317:function(e){e.exports=XMLHttpRequest},6438:function(e,t,r){"use strict";r.r(t),r.d(t,{CompactEncrypt:function(){return ee},CompactSign:function(){return te.T},EmbeddedJWK:function(){return he},EncryptJWT:function(){return ae},FlattenedEncrypt:function(){return K},FlattenedSign:function(){return re.n},GeneralEncrypt:function(){return G},GeneralSign:function(){return ie},SignJWT:function(){return oe.P},UnsecuredJWT:function(){return we},base64url:function(){return n},calculateJwkThumbprint:function(){return ue},calculateJwkThumbprintUri:function(){return de},compactDecrypt:function(){return B},compactVerify:function(){return q.B},createLocalJWKSet:function(){return me},createRemoteJWKSet:function(){return be},cryptoRuntime:function(){return xe},decodeJwt:function(){return Ae},decodeProtectedHeader:function(){return Ee},errors:function(){return s},exportJWK:function(){return W.JU},exportPKCS8:function(){return W.Yp},exportSPKI:function(){return W.Y5},flattenedDecrypt:function(){return M},flattenedVerify:function(){return z.Z},generalDecrypt:function(){return H},generalVerify:function(){return Y},generateKeyPair:function(){return Re.T},generateSecret:function(){return Te},importJWK:function(){return F.Og},importPKCS8:function(){return F.Lf},importSPKI:function(){return F.jU},importX509:function(){return F.Mh},jwtDecrypt:function(){return Z},jwtVerify:function(){return Q.V}});var n={};r.r(n),r.d(n,{decode:function(){return Se},encode:function(){return _e}});var i=r(1436),o=r(9095),s=r(7493),a=r(8057);function c(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new s.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}var l=e=>(0,a.A)(new Uint8Array(c(e)>>3)),u=(e,t)=>{if(t.length<<3!==c(e))throw new s.JWEInvalid("Invalid Initialization Vector length")},d=(e,t)=>{const r=e.byteLength<<3;if(r!==t)throw new s.JWEInvalid(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},h=r(7991),f=r(2698),p=r(1575),g=r(5994),y=async(e,t,r,n,i,a)=>{if(!((0,h.R)(t)||t instanceof Uint8Array))throw new TypeError((0,p.A)(t,...g.g,"Uint8Array"));switch(u(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&d(t,parseInt(e.slice(-3),10)),async function(e,t,r,n,i,a){if(!(t instanceof Uint8Array))throw new TypeError((0,p.A)(t,"Uint8Array"));const c=parseInt(e.slice(1,4),10),l=await h.A.subtle.importKey("raw",t.subarray(c>>3),"AES-CBC",!1,["decrypt"]),u=await h.A.subtle.importKey("raw",t.subarray(0,c>>3),{hash:"SHA-"+(c<<1),name:"HMAC"},!1,["sign"]),d=(0,o.xW)(a,n,r,(0,o.mx)(a.length<<3)),f=new Uint8Array((await h.A.subtle.sign("HMAC",u,d)).slice(0,c>>3));let g,y;try{g=((e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");const r=e.length;let n=0,i=-1;for(;++i{throw new s.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.')},v=async()=>{throw new s.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.')};var b=r(9874),w=r(149),_=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]];function S(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function E(e,t,r){if((0,h.R)(e))return(0,f.$)(e,t,r),e;if(e instanceof Uint8Array)return h.A.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError((0,p.A)(e,...g.g,"Uint8Array"))}const A=async(e,t,r)=>{const n=await E(t,e,"wrapKey");S(n,e);const i=await h.A.subtle.importKey("raw",r,..._);return new Uint8Array(await h.A.subtle.wrapKey("raw",i,n,"AES-KW"))},R=async(e,t,r)=>{const n=await E(t,e,"unwrapKey");S(n,e);const i=await h.A.subtle.unwrapKey("raw",r,n,"AES-KW",..._);return new Uint8Array(await h.A.subtle.exportKey("raw",i))};async function I(e,t,r,n,i=new Uint8Array(0),s=new Uint8Array(0)){if(!(0,h.R)(e))throw new TypeError((0,p.A)(e,...g.g));if((0,f.$)(e,"ECDH"),!(0,h.R)(t))throw new TypeError((0,p.A)(t,...g.g));(0,f.$)(t,"ECDH","deriveBits");const a=(0,o.xW)((0,o.Kp)(o.Rd.encode(r)),(0,o.Kp)(i),(0,o.Kp)(s),(0,o.VS)(n));let c;c="X25519"===e.algorithm.name?256:"X448"===e.algorithm.name?448:Math.ceil(parseInt(e.algorithm.namedCurve.substr(-3),10)/8)<<3;const l=new Uint8Array(await h.A.subtle.deriveBits({name:e.algorithm.name,public:e},t,c));return(0,o.yI)(l,n,a)}function T(e){if(!(0,h.R)(e))throw new TypeError((0,p.A)(e,...g.g));return["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||"X25519"===e.algorithm.name||"X448"===e.algorithm.name}async function x(e,t,r,n){!function(e){if(!(e instanceof Uint8Array)||e.length<8)throw new s.JWEInvalid("PBES2 Salt Input must be 8 or more octets")}(e);const i=(0,o.MT)(t,e),a=parseInt(t.slice(13,16),10),c={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},l={length:a,name:"AES-KW"},u=await function(e,t){if(e instanceof Uint8Array)return h.A.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if((0,h.R)(e))return(0,f.$)(e,t,"deriveBits","deriveKey"),e;throw new TypeError((0,p.A)(e,...g.g,"Uint8Array"))}(n,t);if(u.usages.includes("deriveBits"))return new Uint8Array(await h.A.subtle.deriveBits(c,u,a));if(u.usages.includes("deriveKey"))return h.A.subtle.deriveKey(c,u,l,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}function P(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new s.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var C=r(4495);function k(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new s.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}var O=e=>(0,a.A)(new Uint8Array(k(e)>>3)),F=r(8136),N=r(8858),D=async(e,t,r,n,i)=>{if(!((0,h.R)(r)||r instanceof Uint8Array))throw new TypeError((0,p.A)(r,...g.g,"Uint8Array"));switch(u(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&d(r,parseInt(e.slice(-3),10)),async function(e,t,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError((0,p.A)(r,"Uint8Array"));const s=parseInt(e.slice(1,4),10),a=await h.A.subtle.importKey("raw",r.subarray(s>>3),"AES-CBC",!1,["encrypt"]),c=await h.A.subtle.importKey("raw",r.subarray(0,s>>3),{hash:"SHA-"+(s<<1),name:"HMAC"},!1,["sign"]),l=new Uint8Array(await h.A.subtle.encrypt({iv:n,name:"AES-CBC"},a,t)),u=(0,o.xW)(i,n,l,(0,o.mx)(i.length<<3));return{ciphertext:l,tag:new Uint8Array((await h.A.subtle.sign("HMAC",c,u)).slice(0,s>>3))}}(e,t,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&d(r,parseInt(e.slice(1,4),10)),async function(e,t,r,n,i){let o;r instanceof Uint8Array?o=await h.A.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):((0,f.$)(r,e,"encrypt"),o=r);const s=new Uint8Array(await h.A.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},o,t)),a=s.slice(-16);return{ciphertext:s.slice(0,-16),tag:a}}(e,t,r,n,i);default:throw new s.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}},L=async function(e,t,r,n,o){switch((0,N.A)(e,t,"decrypt"),e){case"dir":if(void 0!==r)throw new s.JWEInvalid("Encountered unexpected JWE Encrypted Key");return t;case"ECDH-ES":if(void 0!==r)throw new s.JWEInvalid("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!(0,w.A)(n.epk))throw new s.JWEInvalid('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!T(t))throw new s.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");const o=await(0,F.Og)(n.epk,e);let a,c;if(void 0!==n.apu){if("string"!=typeof n.apu)throw new s.JWEInvalid('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{a=(0,i.D4)(n.apu)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the apu")}}if(void 0!==n.apv){if("string"!=typeof n.apv)throw new s.JWEInvalid('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{c=(0,i.D4)(n.apv)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the apv")}}const l=await I(o,t,"ECDH-ES"===e?n.enc:e,"ECDH-ES"===e?k(n.enc):parseInt(e.slice(-5,-2),10),a,c);if("ECDH-ES"===e)return l;if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");return R(e.slice(-6),l,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");return(async(e,t,r)=>{if(!(0,h.R)(t))throw new TypeError((0,p.A)(t,...g.g));if((0,f.$)(t,e,"decrypt","unwrapKey"),(0,C.A)(e,t),t.usages.includes("decrypt"))return new Uint8Array(await h.A.subtle.decrypt(P(e),t,r));if(t.usages.includes("unwrapKey")){const n=await h.A.subtle.unwrapKey("raw",r,t,P(e),..._);return new Uint8Array(await h.A.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')})(e,t,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");if("number"!=typeof n.p2c)throw new s.JWEInvalid('JOSE Header "p2c" (PBES2 Count) missing or invalid');const a=(null==o?void 0:o.maxPBES2Count)||1e4;if(n.p2c>a)throw new s.JWEInvalid('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof n.p2s)throw new s.JWEInvalid('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let c;try{c=(0,i.D4)(n.p2s)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the p2s")}return(async(e,t,r,n,i)=>{const o=await x(i,e,n,t);return R(e.slice(-6),o,r)})(e,t,r,n.p2c,c)}case"A128KW":case"A192KW":case"A256KW":if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");return R(e,t,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");if("string"!=typeof n.iv)throw new s.JWEInvalid('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof n.tag)throw new s.JWEInvalid('JOSE Header "tag" (Authentication Tag) missing or invalid');let o,a;try{o=(0,i.D4)(n.iv)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the iv")}try{a=(0,i.D4)(n.tag)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the tag")}return async function(e,t,r,n,i){const o=e.slice(0,7);return y(o,t,r,n,i,new Uint8Array(0))}(e,t,r,o,a)}default:throw new s.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}},U=r(2168),j=r(4618);async function M(e,t,r){var n;if(!(0,w.A)(e))throw new s.JWEInvalid("Flattened JWE must be an object");if(void 0===e.protected&&void 0===e.header&&void 0===e.unprotected)throw new s.JWEInvalid("JOSE Header missing");if("string"!=typeof e.iv)throw new s.JWEInvalid("JWE Initialization Vector missing or incorrect type");if("string"!=typeof e.ciphertext)throw new s.JWEInvalid("JWE Ciphertext missing or incorrect type");if("string"!=typeof e.tag)throw new s.JWEInvalid("JWE Authentication Tag missing or incorrect type");if(void 0!==e.protected&&"string"!=typeof e.protected)throw new s.JWEInvalid("JWE Protected Header incorrect type");if(void 0!==e.encrypted_key&&"string"!=typeof e.encrypted_key)throw new s.JWEInvalid("JWE Encrypted Key incorrect type");if(void 0!==e.aad&&"string"!=typeof e.aad)throw new s.JWEInvalid("JWE AAD incorrect type");if(void 0!==e.header&&!(0,w.A)(e.header))throw new s.JWEInvalid("JWE Shared Unprotected Header incorrect type");if(void 0!==e.unprotected&&!(0,w.A)(e.unprotected))throw new s.JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");let a;if(e.protected)try{const t=(0,i.D4)(e.protected);a=JSON.parse(o.D0.decode(t))}catch(e){throw new s.JWEInvalid("JWE Protected Header is invalid")}if(!(0,b.A)(a,e.header,e.unprotected))throw new s.JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");const c={...a,...e.header,...e.unprotected};if((0,U.A)(s.JWEInvalid,new Map,null==r?void 0:r.crit,a,c),void 0!==c.zip){if(!a||!a.zip)throw new s.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if("DEF"!==c.zip)throw new s.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}const{alg:l,enc:u}=c;if("string"!=typeof l||!l)throw new s.JWEInvalid("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof u||!u)throw new s.JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");const d=r&&(0,j.A)("keyManagementAlgorithms",r.keyManagementAlgorithms),h=r&&(0,j.A)("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(d&&!d.has(l))throw new s.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');if(h&&!h.has(u))throw new s.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed');let f;if(void 0!==e.encrypted_key)try{f=(0,i.D4)(e.encrypted_key)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the encrypted_key")}let p,g,v,_=!1;"function"==typeof t&&(t=await t(a,e),_=!0);try{p=await L(l,t,f,c,r)}catch(e){if(e instanceof TypeError||e instanceof s.JWEInvalid||e instanceof s.JOSENotSupported)throw e;p=O(u)}try{g=(0,i.D4)(e.iv)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the iv")}try{v=(0,i.D4)(e.tag)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the tag")}const S=o.Rd.encode(null!==(n=e.protected)&&void 0!==n?n:"");let E,A;E=void 0!==e.aad?(0,o.xW)(S,o.Rd.encode("."),o.Rd.encode(e.aad)):S;try{A=(0,i.D4)(e.ciphertext)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the ciphertext")}let R=await y(u,p,A,g,v,E);"DEF"===c.zip&&(R=await((null==r?void 0:r.inflateRaw)||m)(R));const I={plaintext:R};if(void 0!==e.protected&&(I.protectedHeader=a),void 0!==e.aad)try{I.additionalAuthenticatedData=(0,i.D4)(e.aad)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the aad")}return void 0!==e.unprotected&&(I.sharedUnprotectedHeader=e.unprotected),void 0!==e.header&&(I.unprotectedHeader=e.header),_?{...I,key:t}:I}async function B(e,t,r){if(e instanceof Uint8Array&&(e=o.D0.decode(e)),"string"!=typeof e)throw new s.JWEInvalid("Compact JWE must be a string or Uint8Array");const{0:n,1:i,2:a,3:c,4:l,length:u}=e.split(".");if(5!==u)throw new s.JWEInvalid("Invalid Compact JWE");const d=await M({ciphertext:c,iv:a||void 0,protected:n||void 0,tag:l||void 0,encrypted_key:i||void 0},t,r),h={plaintext:d.plaintext,protectedHeader:d.protectedHeader};return"function"==typeof t?{...h,key:d.key}:h}async function H(e,t,r){if(!(0,w.A)(e))throw new s.JWEInvalid("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(w.A))throw new s.JWEInvalid("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new s.JWEInvalid("JWE Recipients has no members");for(const n of e.recipients)try{return await M({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch(e){}throw new s.JWEDecryptionFailed}var W=r(5130),$=async function(e,t,r,n,o={}){let c,u,d;switch((0,N.A)(e,r,"encrypt"),e){case"dir":d=r;break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!T(r))throw new s.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");const{apu:a,apv:l}=o;let{epk:f}=o;f||(f=(await async function(e){if(!(0,h.R)(e))throw new TypeError((0,p.A)(e,...g.g));return h.A.subtle.generateKey(e.algorithm,!0,["deriveBits"])}(r)).privateKey);const{x:y,y:m,crv:v,kty:b}=await(0,W.JU)(f),w=await I(r,f,"ECDH-ES"===e?t:e,"ECDH-ES"===e?k(t):parseInt(e.slice(-5,-2),10),a,l);if(u={epk:{x:y,crv:v,kty:b}},"EC"===b&&(u.epk.y=m),a&&(u.apu=(0,i.lF)(a)),l&&(u.apv=(0,i.lF)(l)),"ECDH-ES"===e){d=w;break}d=n||O(t);const _=e.slice(-6);c=await A(_,w,d);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":d=n||O(t),c=await(async(e,t,r)=>{if(!(0,h.R)(t))throw new TypeError((0,p.A)(t,...g.g));if((0,f.$)(t,e,"encrypt","wrapKey"),(0,C.A)(e,t),t.usages.includes("encrypt"))return new Uint8Array(await h.A.subtle.encrypt(P(e),t,r));if(t.usages.includes("wrapKey")){const n=await h.A.subtle.importKey("raw",r,..._);return new Uint8Array(await h.A.subtle.wrapKey("raw",n,t,P(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')})(e,r,d);break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{d=n||O(t);const{p2c:s,p2s:l}=o;({encryptedKey:c,...u}=await(async(e,t,r,n=2048,o=(0,a.A)(new Uint8Array(16)))=>{const s=await x(o,e,n,t);return{encryptedKey:await A(e.slice(-6),s,r),p2c:n,p2s:(0,i.lF)(o)}})(e,r,d,s,l));break}case"A128KW":case"A192KW":case"A256KW":d=n||O(t),c=await A(e,r,d);break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{d=n||O(t);const{iv:s}=o;({encryptedKey:c,...u}=await async function(e,t,r,n){const o=e.slice(0,7);n||(n=l(o));const{ciphertext:s,tag:a}=await D(o,r,t,n,new Uint8Array(0));return{encryptedKey:s,iv:(0,i.lF)(n),tag:(0,i.lF)(a)}}(e,r,d,s));break}default:throw new s.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:d,encryptedKey:c,parameters:u}};const V=Symbol();class K{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=e}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}async encrypt(e,t){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new s.JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!(0,b.A)(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new s.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if((0,U.A)(s.JWEInvalid,new Map,null==t?void 0:t.crit,this._protectedHeader,r),void 0!==r.zip){if(!this._protectedHeader||!this._protectedHeader.zip)throw new s.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if("DEF"!==r.zip)throw new s.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}const{alg:n,enc:a}=r;if("string"!=typeof n||!n)throw new s.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof a||!a)throw new s.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let c,u,d,h,f,p,g;if("dir"===n){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if("ECDH-ES"===n&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");{let r;({cek:u,encryptedKey:c,parameters:r}=await $(n,a,e,this._cek,this._keyManagementParameters)),r&&(t&&V in t?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...r}:this.setUnprotectedHeader(r):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...r}:this.setProtectedHeader(r))}if(this._iv||(this._iv=l(a)),h=this._protectedHeader?o.Rd.encode((0,i.lF)(JSON.stringify(this._protectedHeader))):o.Rd.encode(""),this._aad?(f=(0,i.lF)(this._aad),d=(0,o.xW)(h,o.Rd.encode("."),o.Rd.encode(f))):d=h,"DEF"===r.zip){const e=await((null==t?void 0:t.deflateRaw)||v)(this._plaintext);({ciphertext:p,tag:g}=await D(a,e,u,this._iv,d))}else({ciphertext:p,tag:g}=await D(a,this._plaintext,u,this._iv,d));const y={ciphertext:(0,i.lF)(p),iv:(0,i.lF)(this._iv),tag:(0,i.lF)(g)};return c&&(y.encrypted_key=(0,i.lF)(c)),f&&(y.aad=f),this._protectedHeader&&(y.protected=o.D0.decode(h)),this._sharedUnprotectedHeader&&(y.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(y.header=this._unprotectedHeader),y}}class J{constructor(e,t,r){this.parent=e,this.key=t,this.options=r}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addRecipient(...e){return this.parent.addRecipient(...e)}encrypt(...e){return this.parent.encrypt(...e)}done(){return this.parent}}class G{constructor(e){this._recipients=[],this._plaintext=e}addRecipient(e,t){const r=new J(this,e,{crit:null==t?void 0:t.crit});return this._recipients.push(r),r}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}async encrypt(e){var t,r,n;if(!this._recipients.length)throw new s.JWEInvalid("at least one recipient must be added");if(e={deflateRaw:null==e?void 0:e.deflateRaw},1===this._recipients.length){const[t]=this._recipients,r=await new K(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(t.unprotectedHeader).encrypt(t.key,{...t.options,...e});let n={ciphertext:r.ciphertext,iv:r.iv,recipients:[{}],tag:r.tag};return r.aad&&(n.aad=r.aad),r.protected&&(n.protected=r.protected),r.unprotected&&(n.unprotected=r.unprotected),r.encrypted_key&&(n.recipients[0].encrypted_key=r.encrypted_key),r.header&&(n.recipients[0].header=r.header),n}let o;for(let e=0;e{if("string"!=typeof e||!e)throw new s.JWKInvalid(`${t} missing or invalid`)};async function ue(e,t){if(!(0,w.A)(e))throw new TypeError("JWK must be an object");if(null!=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":le(e.crv,'"crv" (Curve) Parameter'),le(e.x,'"x" (X Coordinate) Parameter'),le(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":le(e.crv,'"crv" (Subtype of Key Pair) Parameter'),le(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":le(e.e,'"e" (Exponent) Parameter'),le(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":le(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new s.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported')}const n=o.Rd.encode(JSON.stringify(r));return(0,i.lF)(await(0,ce.A)(t,n))}async function de(e,t){null!=t||(t="sha256");const r=await ue(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function he(e,t){const r={...e,...null==t?void 0:t.header};if(!(0,w.A)(r.jwk))throw new s.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');const n=await(0,F.Og)({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||"public"!==n.type)throw new s.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}function fe(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(pe)}function pe(e){return(0,w.A)(e)}class ge{constructor(e){if(this._cached=new WeakMap,!fe(e))throw new s.JWKSInvalid("JSON Web Key Set malformed");var t;this._jwks=(t=e,"function"==typeof structuredClone?structuredClone(t):JSON.parse(JSON.stringify(t)))}async getKey(e,t){const{alg:r,kid:n}={...e,...null==t?void 0:t.header},i=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 s.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set')}}(r),o=this._jwks.keys.filter((e=>{let t=i===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&&"EdDSA"===r&&(t="Ed25519"===e.crv||"Ed448"===e.crv),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}return t})),{0:a,length:c}=o;if(0===c)throw new s.JWKSNoMatchingKey;if(1!==c){const e=new s.JWKSMultipleMatchingKeys,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of o)try{yield await ye(t,e,r)}catch(e){continue}},e}return ye(this._cached,a,r)}}async function ye(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await(0,F.Og)({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new s.JWKSInvalid("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function me(e){const t=new ge(e);return async function(e,r){return t.getKey(e,r)}}class ve extends ge{constructor(e,t){if(super({keys:[]}),this._jwks=void 0,!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:null==t?void 0:t.agent,headers:null==t?void 0:t.headers},this._timeoutDuration="number"==typeof(null==t?void 0:t.timeoutDuration)?null==t?void 0:t.timeoutDuration:5e3,this._cooldownDuration="number"==typeof(null==t?void 0:t.cooldownDuration)?null==t?void 0:t.cooldownDuration:3e4,this._cacheMaxAge="number"==typeof(null==t?void 0:t.cacheMaxAge)?null==t?void 0:t.cacheMaxAge:6e5}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now(){let n,i,o=!1;"function"==typeof AbortController&&(n=new AbortController,i=setTimeout((()=>{o=!0,n.abort()}),t));const a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch((e=>{if(o)throw new s.JWKSTimeout;throw e}));if(void 0!==i&&clearTimeout(i),200!==a.status)throw new s.JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch(e){throw new s.JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON")}})(this._url,this._timeoutDuration,this._options).then((e=>{if(!fe(e))throw new s.JWKSInvalid("JSON Web Key Set malformed");this._jwks={keys:e.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0})).catch((e=>{throw this._pendingFetch=void 0,e}))),await this._pendingFetch}}function be(e,t){const r=new ve(e,t);return async function(e,t){return r.getKey(e,t)}}class we extends se.G{encode(){return`${i.lF(JSON.stringify({alg:"none"}))}.${i.lF(JSON.stringify(this._payload))}.`}static decode(e,t){if("string"!=typeof e)throw new s.JWTInvalid("Unsecured JWT must be a string");const{0:r,1:n,2:a,length:c}=e.split(".");if(3!==c||""!==a)throw new s.JWTInvalid("Invalid Unsecured JWT");let l;try{if(l=JSON.parse(o.D0.decode(i.D4(r))),"none"!==l.alg)throw new Error}catch(e){throw new s.JWTInvalid("Invalid Unsecured JWT")}return{payload:(0,X.A)(l,i.D4(n),t),header:l}}}const _e=i.lF,Se=i.D4;function Ee(e){let t;if("string"==typeof e){const r=e.split(".");3!==r.length&&5!==r.length||([t]=r)}else if("object"==typeof e&&e){if(!("protected"in e))throw new TypeError("Token does not contain a Protected Header");t=e.protected}try{if("string"!=typeof t||!t)throw new Error;const e=JSON.parse(o.D0.decode(Se(t)));if(!(0,w.A)(e))throw new Error;return e}catch(e){throw new TypeError("Invalid Token or Protected Header formatting")}}function Ae(e){if("string"!=typeof e)throw new s.JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new s.JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new s.JWTInvalid("Invalid JWT");if(!t)throw new s.JWTInvalid("JWTs must contain a payload");let n,i;try{n=Se(t)}catch(e){throw new s.JWTInvalid("Failed to base64url decode the payload")}try{i=JSON.parse(o.D0.decode(n))}catch(e){throw new s.JWTInvalid("Failed to parse the decoded payload as JSON")}if(!(0,w.A)(i))throw new s.JWTInvalid("Invalid JWT Claims Set");return i}var Re=r(7307),Ie=r(8793);async function Te(e,t){return(0,Ie.K)(e,t)}var xe="WebCryptoAPI"},2609:function(e,t,r){"use strict";r.d(t,{T:function(){return i}});var n=r(5550);class i{constructor(e){this._flattened=new n.n(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}`}}},5609:function(e,t,r){"use strict";r.d(t,{B:function(){return s}});var n=r(6711),i=r(7493),o=r(9095);async function s(e,t,r){if(e instanceof Uint8Array&&(e=o.D0.decode(e)),"string"!=typeof e)throw new i.JWSInvalid("Compact JWS must be a string or Uint8Array");const{0:s,1:a,2:c,length:l}=e.split(".");if(3!==l)throw new i.JWSInvalid("Invalid Compact JWS");const u=await(0,n.Z)({payload:a,protected:s,signature:c},t,r),d={payload:u.payload,protectedHeader:u.protectedHeader};return"function"==typeof t?{...d,key:u.key}:d}},5550:function(e,t,r){"use strict";r.d(t,{n:function(){return f}});var n=r(1436),i=r(1020),o=r(7991),s=r(4495),a=r(676),c=r(9874),l=r(7493),u=r(9095),d=r(8858),h=r(2168);class f{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 l.JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!(0,c.A)(this._protectedHeader,this._unprotectedHeader))throw new l.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let f=!0;if((0,h.A)(l.JWSInvalid,new Map([["b64",!0]]),null==t?void 0:t.crit,this._protectedHeader,r).has("b64")&&(f=this._protectedHeader.b64,"boolean"!=typeof f))throw new l.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:p}=r;if("string"!=typeof p||!p)throw new l.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');(0,d.A)(p,e,"sign");let g,y=this._payload;f&&(y=u.Rd.encode((0,n.lF)(y))),g=this._protectedHeader?u.Rd.encode((0,n.lF)(JSON.stringify(this._protectedHeader))):u.Rd.encode("");const m=(0,u.xW)(g,u.Rd.encode("."),y),v=await(async(e,t,r)=>{const n=await(0,a.A)(e,t,"sign");(0,s.A)(e,n);const c=await o.A.subtle.sign((0,i.A)(e,n.algorithm),n,r);return new Uint8Array(c)})(p,e,m),b={signature:(0,n.lF)(v),payload:""};return f&&(b.payload=u.D0.decode(y)),this._unprotectedHeader&&(b.header=this._unprotectedHeader),this._protectedHeader&&(b.protected=u.D0.decode(g)),b}}},6711:function(e,t,r){"use strict";r.d(t,{Z:function(){return y}});var n=r(1436),i=r(1020),o=r(7991),s=r(4495),a=r(676),c=async(e,t,r,n)=>{const c=await(0,a.A)(e,t,"verify");(0,s.A)(e,c);const l=(0,i.A)(e,c.algorithm);try{return await o.A.subtle.verify(l,c,r,n)}catch(e){return!1}},l=r(7493),u=r(9095),d=r(9874),h=r(149),f=r(8858),p=r(2168),g=r(4618);async function y(e,t,r){var i;if(!(0,h.A)(e))throw new l.JWSInvalid("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new l.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new l.JWSInvalid("JWS Protected Header incorrect type");if(void 0===e.payload)throw new l.JWSInvalid("JWS Payload missing");if("string"!=typeof e.signature)throw new l.JWSInvalid("JWS Signature missing or incorrect type");if(void 0!==e.header&&!(0,h.A)(e.header))throw new l.JWSInvalid("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{const t=(0,n.D4)(e.protected);o=JSON.parse(u.D0.decode(t))}catch(e){throw new l.JWSInvalid("JWS Protected Header is invalid")}if(!(0,d.A)(o,e.header))throw new l.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...o,...e.header};let a=!0;if((0,p.A)(l.JWSInvalid,new Map([["b64",!0]]),null==r?void 0:r.crit,o,s).has("b64")&&(a=o.b64,"boolean"!=typeof a))throw new l.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:y}=s;if("string"!=typeof y||!y)throw new l.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');const m=r&&(0,g.A)("algorithms",r.algorithms);if(m&&!m.has(y))throw new l.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');if(a){if("string"!=typeof e.payload)throw new l.JWSInvalid("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new l.JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let v=!1;"function"==typeof t&&(t=await t(o,e),v=!0),(0,f.A)(y,t,"verify");const b=(0,u.xW)(u.Rd.encode(null!==(i=e.protected)&&void 0!==i?i:""),u.Rd.encode("."),"string"==typeof e.payload?u.Rd.encode(e.payload):e.payload);let w,_;try{w=(0,n.D4)(e.signature)}catch(e){throw new l.JWSInvalid("Failed to base64url decode the signature")}if(!await c(y,t,w,b))throw new l.JWSSignatureVerificationFailed;if(a)try{_=(0,n.D4)(e.payload)}catch(e){throw new l.JWSInvalid("Failed to base64url decode the payload")}else _="string"==typeof e.payload?u.Rd.encode(e.payload):e.payload;const S={payload:_};return void 0!==e.protected&&(S.protectedHeader=o),void 0!==e.header&&(S.unprotectedHeader=e.header),v?{...S,key:t}:S}},3085:function(e,t,r){"use strict";r.d(t,{G:function(){return s}});var n=r(2222),i=r(149),o=r(6957);class s{constructor(e){if(!(0,i.A)(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 this._payload="number"==typeof e?{...this._payload,nbf:e}:{...this._payload,nbf:(0,n.A)(new Date)+(0,o.A)(e)},this}setExpirationTime(e){return this._payload="number"==typeof e?{...this._payload,exp:e}:{...this._payload,exp:(0,n.A)(new Date)+(0,o.A)(e)},this}setIssuedAt(e){return this._payload=void 0===e?{...this._payload,iat:(0,n.A)(new Date)}:{...this._payload,iat:e},this}}},7248:function(e,t,r){"use strict";r.d(t,{P:function(){return a}});var n=r(2609),i=r(7493),o=r(9095),s=r(3085);class a extends s.G{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){var r;const s=new n.T(o.Rd.encode(JSON.stringify(this._payload)));if(s.setProtectedHeader(this._protectedHeader),Array.isArray(null===(r=this._protectedHeader)||void 0===r?void 0:r.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new i.JWTInvalid("JWTs MUST NOT use unencoded payload");return s.sign(e,t)}}},9380:function(e,t,r){"use strict";r.d(t,{V:function(){return s}});var n=r(5609),i=r(9803),o=r(7493);async function s(e,t,r){var s;const a=await(0,n.B)(e,t,r);if((null===(s=a.protectedHeader.crit)||void 0===s?void 0:s.includes("b64"))&&!1===a.protectedHeader.b64)throw new o.JWTInvalid("JWTs MUST NOT use unencoded payload");const c={payload:(0,i.A)(a.protectedHeader,a.payload,r),protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}},5130:function(e,t,r){"use strict";r.d(t,{JU:function(){return d},Yp:function(){return u},Y5:function(){return l}});var n=r(5141),i=r(7991),o=r(1575),s=r(1436),a=r(5994),c=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:(0,s.lF)(e)};if(!(0,i.R)(e))throw new TypeError((0,o.A)(e,...a.g,"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:c,...l}=await i.A.subtle.exportKey("jwk",e);return l};async function l(e){return(0,n.Nj)(e)}async function u(e){return(0,n.Jq)(e)}async function d(e){return c(e)}},7307:function(e,t,r){"use strict";r.d(t,{T:function(){return i}});var n=r(8793);async function i(e,t){return(0,n.T)(e,t)}},8136:function(e,t,r){"use strict";r.d(t,{Og:function(){return h},Lf:function(){return d},jU:function(){return l},Mh:function(){return u}});var n=r(1436),i=r(5141),o=r(7991),s=r(7493),a=async e=>{var t,r;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:i,keyUsages:a}=function(e){let t,r;switch(e.kty){case"oct":switch(e.alg){case"HS256":case"HS384":case"HS512":t={name:"HMAC",hash:`SHA-${e.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new s.JOSENotSupported(`${e.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":t={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":t={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":t={name:"PBKDF2"},r=["deriveBits"];break;default:throw new s.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new s.JOSENotSupported('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 s.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){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 s.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new s.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),c=[i,null!==(t=e.ext)&&void 0!==t&&t,null!==(r=e.key_ops)&&void 0!==r?r:a];if("PBKDF2"===i.name)return o.A.subtle.importKey("raw",(0,n.D4)(e.k),...c);const l={...e};return delete l.alg,delete l.use,o.A.subtle.importKey("jwk",l,...c)},c=r(149);async function l(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw new TypeError('"spki" must be SPKI formatted string');return(0,i.sc)(e,t,r)}async function u(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN CERTIFICATE-----"))throw new TypeError('"x509" must be X.509 formatted string');return(0,i.zp)(e,t,r)}async function d(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return(0,i.IG)(e,t,r)}async function h(e,t,r){var i;if(!(0,c.A)(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 null!=r||(r=!0!==e.ext),r?a({...e,alg:t,ext:null!==(i=e.ext)&&void 0!==i&&i}):(0,n.D4)(e.k);case"RSA":if(void 0!==e.oth)throw new s.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return a({...e,alg:t});default:throw new s.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value')}}},9095:function(e,t,r){"use strict";r.d(t,{D0:function(){return o},Kp:function(){return h},MT:function(){return c},Rd:function(){return i},VS:function(){return d},mx:function(){return u},xW:function(){return a},yI:function(){return f}});var n=r(610);const i=new TextEncoder,o=new TextDecoder,s=2**32;function a(...e){const t=e.reduce(((e,{length:t})=>e+t),0),r=new Uint8Array(t);let n=0;return e.forEach((e=>{r.set(e,n),n+=e.length})),r}function c(e,t){return a(i.encode(e),new Uint8Array([0]),t)}function l(e,t,r){if(t<0||t>=s)throw new RangeError(`value must be >= 0 and <= ${s-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,255&t],r)}function u(e){const t=Math.floor(e/s),r=e%s,n=new Uint8Array(8);return l(n,t,0),l(n,r,4),n}function d(e){const t=new Uint8Array(4);return l(t,e),t}function h(e){return a(d(e.length),e)}async function f(e,t,r){const i=Math.ceil((t>>3)/32),o=new Uint8Array(32*i);for(let t=0;t>3)}},8858:function(e,t,r){"use strict";var n=r(1575),i=r(5994);t.A=(e,t,r)=>{e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?((e,t)=>{if(!(t instanceof Uint8Array)){if(!(0,i.A)(t))throw new TypeError((0,n.t)(e,t,...i.g,"Uint8Array"));if("secret"!==t.type)throw new TypeError(`${i.g.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}})(e,t):((e,t,r)=>{if(!(0,i.A)(t))throw new TypeError((0,n.t)(e,t,...i.g));if("secret"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)})(e,t,r)}},2698:function(e,t,r){"use strict";function n(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 o(e){return parseInt(e.name.slice(4),10)}function s(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)}}function a(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!i(e.algorithm,"HMAC"))throw n("HMAC");const r=parseInt(t.slice(2),10);if(o(e.algorithm.hash)!==r)throw n(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!i(e.algorithm,"RSASSA-PKCS1-v1_5"))throw n("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(o(e.algorithm.hash)!==r)throw n(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!i(e.algorithm,"RSA-PSS"))throw n("RSA-PSS");const r=parseInt(t.slice(2),10);if(o(e.algorithm.hash)!==r)throw n(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw n("Ed25519 or Ed448");break;case"ES256":case"ES384":case"ES512":{if(!i(e.algorithm,"ECDSA"))throw n("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 n(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}s(e,r)}function c(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!i(e.algorithm,"AES-GCM"))throw n("AES-GCM");const r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw n(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!i(e.algorithm,"AES-KW"))throw n("AES-KW");const r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw n(r,"algorithm.length");break}case"ECDH":switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw n("ECDH, X25519, or X448")}break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!i(e.algorithm,"PBKDF2"))throw n("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!i(e.algorithm,"RSA-OAEP"))throw n("RSA-OAEP");const r=parseInt(t.slice(9),10)||1;if(o(e.algorithm.hash)!==r)throw n(`SHA-${r}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}s(e,r)}r.d(t,{$:function(){return c},Y:function(){return a}})},2222:function(e,t){"use strict";t.A=e=>Math.floor(e.getTime()/1e3)},1575:function(e,t,r){"use strict";function n(e,t,...r){if(r.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&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function i(e,t,...r){return n(`Key for the ${e} algorithm must be `,t,...r)}r.d(t,{t:function(){return i}}),t.A=(e,...t)=>n("Key must be ",e,...t)},9874:function(e,t){"use strict";t.A=(...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}},149:function(e,t,r){"use strict";function n(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}r.d(t,{A:function(){return n}})},9803:function(e,t,r){"use strict";var n=r(7493),i=r(9095),o=r(2222),s=r(6957),a=r(149);const c=e=>e.toLowerCase().replace(/^application\//,"");t.A=(e,t,r={})=>{const{typ:l}=r;if(l&&("string"!=typeof e.typ||c(e.typ)!==c(l)))throw new n.JWTClaimValidationFailed('unexpected "typ" JWT header value',"typ","check_failed");let u;try{u=JSON.parse(i.D0.decode(t))}catch(e){}if(!(0,a.A)(u))throw new n.JWTInvalid("JWT Claims Set must be a top-level JSON object");const{requiredClaims:d=[],issuer:h,subject:f,audience:p,maxTokenAge:g}=r;void 0!==g&&d.push("iat"),void 0!==p&&d.push("aud"),void 0!==f&&d.push("sub"),void 0!==h&&d.push("iss");for(const e of new Set(d.reverse()))if(!(e in u))throw new n.JWTClaimValidationFailed(`missing required "${e}" claim`,e,"missing");if(h&&!(Array.isArray(h)?h:[h]).includes(u.iss))throw new n.JWTClaimValidationFailed('unexpected "iss" claim value',"iss","check_failed");if(f&&u.sub!==f)throw new n.JWTClaimValidationFailed('unexpected "sub" claim value',"sub","check_failed");if(p&&(m="string"==typeof p?[p]:p,!("string"==typeof(y=u.aud)?m.includes(y):Array.isArray(y)&&m.some(Set.prototype.has.bind(new Set(y))))))throw new n.JWTClaimValidationFailed('unexpected "aud" claim value',"aud","check_failed");var y,m;let v;switch(typeof r.clockTolerance){case"string":v=(0,s.A)(r.clockTolerance);break;case"number":v=r.clockTolerance;break;case"undefined":v=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:b}=r,w=(0,o.A)(b||new Date);if((void 0!==u.iat||g)&&"number"!=typeof u.iat)throw new n.JWTClaimValidationFailed('"iat" claim must be a number',"iat","invalid");if(void 0!==u.nbf){if("number"!=typeof u.nbf)throw new n.JWTClaimValidationFailed('"nbf" claim must be a number',"nbf","invalid");if(u.nbf>w+v)throw new n.JWTClaimValidationFailed('"nbf" claim timestamp check failed',"nbf","check_failed")}if(void 0!==u.exp){if("number"!=typeof u.exp)throw new n.JWTClaimValidationFailed('"exp" claim must be a number',"exp","invalid");if(u.exp<=w-v)throw new n.JWTExpired('"exp" claim timestamp check failed',"exp","check_failed")}if(g){const e=w-u.iat;if(e-v>("number"==typeof g?g:(0,s.A)(g)))throw new n.JWTExpired('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(e<0-v)throw new n.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return u}},6957:function(e,t){"use strict";const r=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;t.A=e=>{const t=r.exec(e);if(!t)throw new TypeError("Invalid time period format");const n=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(n);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(60*n);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(3600*n);case"day":case"days":case"d":return Math.round(86400*n);case"week":case"weeks":case"w":return Math.round(604800*n);default:return Math.round(31557600*n)}}},4618:function(e,t){"use strict";t.A=(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)}},2168:function(e,t,r){"use strict";var n=r(7493);t.A=function(e,t,r,i,o){if(void 0!==o.crit&&void 0===i.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||void 0===i.crit)return new Set;if(!Array.isArray(i.crit)||0===i.crit.length||i.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 s;s=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of i.crit){if(!s.has(t))throw new n.JOSENotSupported(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(s.get(t)&&void 0===i[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(i.crit)}},5141:function(e,t,r){"use strict";r.d(t,{IG:function(){return g},sc:function(){return y},zp:function(){return b},Jq:function(){return d},Nj:function(){return u}});var n=r(7991),i=r(1575),o=r(1436),s=(e,t)=>`-----BEGIN ${t}-----\n${(e.match(/.{1,64}/g)||[]).join("\n")}\n-----END ${t}-----`,a=r(7493),c=r(5994);const l=async(e,t,r)=>{if(!(0,n.R)(r))throw new TypeError((0,i.A)(r,...c.g));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return s((0,o.WG)(new Uint8Array(await n.A.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},u=e=>l("public","spki",e),d=e=>l("private","pkcs8",e),h=(e,t,r=0)=>{0===r&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(-1===n)return!1;const i=e.subarray(n,n+t.length);return i.length===t.length&&(i.every(((e,r)=>e===t[r]))||h(e,t,n+1))},f=e=>{switch(!0){case h(e,[42,134,72,206,61,3,1,7]):return"P-256";case h(e,[43,129,4,0,34]):return"P-384";case h(e,[43,129,4,0,35]):return"P-521";case h(e,[43,101,110]):return"X25519";case h(e,[43,101,111]):return"X448";case h(e,[43,101,112]):return"Ed25519";case h(e,[43,101,113]):return"Ed448";default:throw new a.JOSENotSupported("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},p=async(e,t,r,i,o)=>{var s;let c,l;const u=new Uint8Array(atob(r.replace(e,"")).split("").map((e=>e.charCodeAt(0)))),d="spki"===t;switch(i){case"PS256":case"PS384":case"PS512":c={name:"RSA-PSS",hash:`SHA-${i.slice(-3)}`},l=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":c={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${i.slice(-3)}`},l=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":c={name:"RSA-OAEP",hash:`SHA-${parseInt(i.slice(-3),10)||1}`},l=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":c={name:"ECDSA",namedCurve:"P-256"},l=d?["verify"]:["sign"];break;case"ES384":c={name:"ECDSA",namedCurve:"P-384"},l=d?["verify"]:["sign"];break;case"ES512":c={name:"ECDSA",namedCurve:"P-521"},l=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=f(u);c=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},l=d?[]:["deriveBits"];break}case"EdDSA":c={name:f(u)},l=d?["verify"]:["sign"];break;default:throw new a.JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value')}return n.A.subtle.importKey(t,u,c,null!==(s=null==o?void 0:o.extractable)&&void 0!==s&&s,l)},g=(e,t,r)=>p(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),y=(e,t,r)=>p(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function m(e){let t=[],r=0;for(;r=128;)r=128*r+e[t]-128,t++;r=128*r+e[t]-128,t++}let n=0;if(e[t]<128)n=e[t],t++;else{if(128===n){for(n=0;0!==e[t+n]||0!==e[t+n+1];){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++}const r=t+n+2;return{byteLength:r,contents:e.subarray(t,t+n),raw:e.subarray(0,r)}}{let r=127&e[t];t++,n=0;for(let i=0;i{let n;try{n=function(e){const t=e.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=(0,o.y4)(t);return s(function(e){const t=m(m(v(e).contents)[0].contents);return(0,o.WG)(t[160===t[0].raw[0]?6:5].raw)}(r),"PUBLIC KEY")}(e)}catch(e){throw new TypeError("Failed to parse the X.509 certificate",{cause:e})}return y(n,t,r)}},1436:function(e,t,r){"use strict";r.d(t,{D4:function(){return a},WG:function(){return i},lF:function(){return o},y4:function(){return s}});var n=r(9095);const i=e=>{let t=e;"string"==typeof t&&(t=n.Rd.encode(t));const r=[];for(let e=0;ei(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),s=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e{let t=e;t instanceof Uint8Array&&(t=n.D0.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return s(t)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.")}}},4495:function(e,t){"use strict";t.A=(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`)}}},610:function(e,t,r){"use strict";var n=r(7991);t.A=async(e,t)=>{const r=`SHA-${e.slice(-3)}`;return new Uint8Array(await n.A.subtle.digest(r,t))}},8793:function(e,t,r){"use strict";r.d(t,{K:function(){return s},T:function(){return c}});var n=r(7991),i=r(7493),o=r(8057);async function s(e,t){var r;let s,a,c;switch(e){case"HS256":case"HS384":case"HS512":s=parseInt(e.slice(-3),10),a={name:"HMAC",hash:`SHA-${s}`,length:s},c=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return s=parseInt(e.slice(-3),10),(0,o.A)(new Uint8Array(s>>3));case"A128KW":case"A192KW":case"A256KW":s=parseInt(e.slice(1,4),10),a={name:"AES-KW",length:s},c=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":s=parseInt(e.slice(1,4),10),a={name:"AES-GCM",length:s},c=["encrypt","decrypt"];break;default:throw new i.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return n.A.subtle.generateKey(a,null!==(r=null==t?void 0:t.extractable)&&void 0!==r&&r,c)}function a(e){var t;const r=null!==(t=null==e?void 0:e.modulusLength)&&void 0!==t?t:2048;if("number"!=typeof r||r<2048)throw new i.JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function c(e,t){var r,o,s;let c,l;switch(e){case"PS256":case"PS384":case"PS512":c={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:a(t)},l=["sign","verify"];break;case"RS256":case"RS384":case"RS512":c={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:a(t)},l=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":c={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:a(t)},l=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":c={name:"ECDSA",namedCurve:"P-256"},l=["sign","verify"];break;case"ES384":c={name:"ECDSA",namedCurve:"P-384"},l=["sign","verify"];break;case"ES512":c={name:"ECDSA",namedCurve:"P-521"},l=["sign","verify"];break;case"EdDSA":l=["sign","verify"];const n=null!==(r=null==t?void 0:t.crv)&&void 0!==r?r:"Ed25519";switch(n){case"Ed25519":case"Ed448":c={name:n};break;default:throw new i.JOSENotSupported("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{l=["deriveKey","deriveBits"];const e=null!==(o=null==t?void 0:t.crv)&&void 0!==o?o:"P-256";switch(e){case"P-256":case"P-384":case"P-521":c={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":c={name:e};break;default:throw new i.JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new i.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return n.A.subtle.generateKey(c,null!==(s=null==t?void 0:t.extractable)&&void 0!==s&&s,l)}},676:function(e,t,r){"use strict";r.d(t,{A:function(){return a}});var n=r(7991),i=r(2698),o=r(1575),s=r(5994);function a(e,t,r){if((0,n.R)(t))return(0,i.Y)(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError((0,o.A)(t,...s.g));return n.A.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError((0,o.A)(t,...s.g,"Uint8Array"))}},5994:function(e,t,r){"use strict";r.d(t,{g:function(){return i}});var n=r(7991);t.A=e=>(0,n.R)(e);const i=["CryptoKey"]},8057:function(e,t,r){"use strict";var n=r(7991);t.A=n.A.getRandomValues.bind(n.A)},1020:function(e,t,r){"use strict";r.d(t,{A:function(){return i}});var n=r(7493);function i(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"EdDSA":return{name:t.name};default:throw new n.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}},7991:function(e,t,r){"use strict";r.d(t,{R:function(){return n}}),t.A=crypto;const n=e=>e instanceof CryptoKey},7493:function(e,t,r){"use strict";r.r(t),r.d(t,{JOSEAlgNotAllowed:function(){return s},JOSEError:function(){return n},JOSENotSupported:function(){return a},JWEDecompressionFailed:function(){return l},JWEDecryptionFailed:function(){return c},JWEInvalid:function(){return u},JWKInvalid:function(){return f},JWKSInvalid:function(){return p},JWKSMultipleMatchingKeys:function(){return y},JWKSNoMatchingKey:function(){return g},JWKSTimeout:function(){return m},JWSInvalid:function(){return d},JWSSignatureVerificationFailed:function(){return v},JWTClaimValidationFailed:function(){return i},JWTExpired:function(){return o},JWTInvalid:function(){return h}});class n extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(e){var t;super(e),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor)}}class i extends n{static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(e,t="unspecified",r="unspecified"){super(e),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=r}}class o extends n{static get code(){return"ERR_JWT_EXPIRED"}constructor(e,t="unspecified",r="unspecified"){super(e),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=r}}class s extends n{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}}class a extends n{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class c extends n{constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}}class l extends n{constructor(){super(...arguments),this.code="ERR_JWE_DECOMPRESSION_FAILED",this.message="decompression operation failed"}static get code(){return"ERR_JWE_DECOMPRESSION_FAILED"}}class u extends n{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}}class d extends n{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class h extends n{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}class f extends n{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}}class p extends n{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}}class g extends n{constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_NO_MATCHING_KEY"}}class y extends n{constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Symbol.asyncIterator;class m extends n{constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}}class v extends n{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}}},t={};function r(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,r),o.exports}r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n=r(423);return n.default}()})); +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("RemoteStorage",[],t):"object"==typeof exports?exports.RemoteStorage=t():e.RemoteStorage=t()}(this,(function(){return function(){var e={608:function(e,t,r){var{Buffer:n}=r(8287),i={},o=i.LEFT_BRACE=1,s=i.RIGHT_BRACE=2,a=i.LEFT_BRACKET=3,c=i.RIGHT_BRACKET=4,l=i.COLON=5,u=i.COMMA=6,d=i.TRUE=7,h=i.FALSE=8,f=i.NULL=9,p=i.STRING=10,g=i.NUMBER=11,y=i.START=17,m=i.STOP=18,v=i.TRUE1=33,b=i.TRUE2=34,w=i.TRUE3=35,_=i.FALSE1=49,S=i.FALSE2=50,E=i.FALSE3=51,A=i.FALSE4=52,R=i.NULL1=65,I=i.NULL2=66,T=i.NULL3=67,x=i.NUMBER1=81,P=i.NUMBER3=83,C=i.STRING1=97,k=i.STRING2=98,O=i.STRING3=99,F=i.STRING4=100,N=i.STRING5=101,D=i.STRING6=102,L=i.VALUE=113,U=i.KEY=114,j=i.OBJECT=129,M=i.ARRAY=130,B="\\".charCodeAt(0),H="/".charCodeAt(0),W="\b".charCodeAt(0),$="\f".charCodeAt(0),V="\n".charCodeAt(0),K="\r".charCodeAt(0),J="\t".charCodeAt(0),G=65536;function q(e){return n.alloc?n.alloc(e):new n(e)}function z(){this.tState=y,this.value=void 0,this.string=void 0,this.stringBuffer=q(G),this.stringBufferOffset=0,this.unicode=void 0,this.highSurrogate=void 0,this.key=void 0,this.mode=void 0,this.stack=[],this.state=L,this.bytes_remaining=0,this.bytes_in_sequence=0,this.temp_buffs={2:q(2),3:q(3),4:q(4)},this.offset=-1}z.toknam=function(e){for(var t=Object.keys(i),r=0,n=t.length;r=G&&(this.string+=this.stringBuffer.toString("utf8"),this.stringBufferOffset=0),this.stringBuffer[this.stringBufferOffset++]=e},Y.appendStringBuf=function(e,t,r){var n=e.length;"number"==typeof t&&(n="number"==typeof r?r<0?e.length-t+r:r-t:e.length-t),n<0&&(n=0),this.stringBufferOffset+n>G&&(this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0),e.copy(this.stringBuffer,this.stringBufferOffset,t,r),this.stringBufferOffset+=n},Y.write=function(e){var t;"string"==typeof e&&(e=new n(e));for(var r=0,i=e.length;r=48&&t<64)this.string=String.fromCharCode(t),this.tState=P;else if(32!==t&&9!==t&&10!==t&&13!==t)return this.charError(e,r)}else if(this.tState===C)if(t=e[r],this.bytes_remaining>0){for(var g=0;g=128){if(t<=193||t>244)return this.onError(new Error("Invalid UTF-8 character at position "+r+" in state "+z.toknam(this.tState)));if(t>=194&&t<=223&&(this.bytes_in_sequence=2),t>=224&&t<=239&&(this.bytes_in_sequence=3),t>=240&&t<=244&&(this.bytes_in_sequence=4),this.bytes_in_sequence+r>e.length){for(var m=0;m<=e.length-1-r;m++)this.temp_buffs[this.bytes_in_sequence][m]=e[r+m];this.bytes_remaining=r+this.bytes_in_sequence-e.length,r=e.length-1}else this.appendStringBuf(e,r,r+this.bytes_in_sequence),r=r+this.bytes_in_sequence-1}else if(34===t)this.tState=y,this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0,this.onToken(p,this.string),this.offset+=n.byteLength(this.string,"utf8")+1,this.string=void 0;else if(92===t)this.tState=k;else{if(!(t>=32))return this.charError(e,r);this.appendStringChar(t)}else if(this.tState===k)if(34===(t=e[r]))this.appendStringChar(t),this.tState=C;else if(92===t)this.appendStringChar(B),this.tState=C;else if(47===t)this.appendStringChar(H),this.tState=C;else if(98===t)this.appendStringChar(W),this.tState=C;else if(102===t)this.appendStringChar($),this.tState=C;else if(110===t)this.appendStringChar(V),this.tState=C;else if(114===t)this.appendStringChar(K),this.tState=C;else if(116===t)this.appendStringChar(J),this.tState=C;else{if(117!==t)return this.charError(e,r);this.unicode="",this.tState=O}else if(this.tState===O||this.tState===F||this.tState===N||this.tState===D){if(!((t=e[r])>=48&&t<64||t>64&&t<=70||t>96&&t<=102))return this.charError(e,r);if(this.unicode+=String.fromCharCode(t),this.tState++===D){var L=parseInt(this.unicode,16);this.unicode=void 0,void 0!==this.highSurrogate&&L>=56320&&L<57344?(this.appendStringBuf(new n(String.fromCharCode(this.highSurrogate,L))),this.highSurrogate=void 0):void 0===this.highSurrogate&&L>=55296&&L<56320?this.highSurrogate=L:(void 0!==this.highSurrogate&&(this.appendStringBuf(new n(String.fromCharCode(this.highSurrogate))),this.highSurrogate=void 0),this.appendStringBuf(new n(String.fromCharCode(L)))),this.tState=C}}else if(this.tState===x||this.tState===P)switch(t=e[r]){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 46:case 101:case 69:case 43:case 45:this.string+=String.fromCharCode(t),this.tState=P;break;default:this.tState=y;var U=this.numberReviver(this.string,e,r);if(U)return U;this.offset+=this.string.length-1,this.string=void 0,r--}else if(this.tState===v){if(114!==e[r])return this.charError(e,r);this.tState=b}else if(this.tState===b){if(117!==e[r])return this.charError(e,r);this.tState=w}else if(this.tState===w){if(101!==e[r])return this.charError(e,r);this.tState=y,this.onToken(d,!0),this.offset+=3}else if(this.tState===_){if(97!==e[r])return this.charError(e,r);this.tState=S}else if(this.tState===S){if(108!==e[r])return this.charError(e,r);this.tState=E}else if(this.tState===E){if(115!==e[r])return this.charError(e,r);this.tState=A}else if(this.tState===A){if(101!==e[r])return this.charError(e,r);this.tState=y,this.onToken(h,!1),this.offset+=4}else if(this.tState===R){if(117!==e[r])return this.charError(e,r);this.tState=I}else if(this.tState===I){if(108!==e[r])return this.charError(e,r);this.tState=T}else if(this.tState===T){if(108!==e[r])return this.charError(e,r);this.tState=y,this.onToken(f,null),this.offset+=3}},Y.onToken=function(e,t){},Y.parseError=function(e,t){this.tState=m,this.onError(new Error("Unexpected "+z.toknam(e)+(t?"("+JSON.stringify(t)+")":"")+" in state "+z.toknam(this.state)))},Y.push=function(){this.stack.push({value:this.value,key:this.key,mode:this.mode})},Y.pop=function(){var e=this.value,t=this.stack.pop();this.value=t.value,this.key=t.key,this.mode=t.mode,this.emit(e),this.mode||(this.state=L)},Y.emit=function(e){this.mode&&(this.state=u),this.onValue(e)},Y.onValue=function(e){},Y.onToken=function(e,t){if(this.state===L)if(e===p||e===g||e===d||e===h||e===f)this.value&&(this.value[this.key]=t),this.emit(t);else if(e===o)this.push(),this.value?this.value=this.value[this.key]={}:this.value={},this.key=void 0,this.state=U,this.mode=j;else if(e===a)this.push(),this.value?this.value=this.value[this.key]=[]:this.value=[],this.key=0,this.mode=M,this.state=L;else if(e===s){if(this.mode!==j)return this.parseError(e,t);this.pop()}else{if(e!==c)return this.parseError(e,t);if(this.mode!==M)return this.parseError(e,t);this.pop()}else if(this.state===U)if(e===p)this.key=t,this.state=l;else{if(e!==s)return this.parseError(e,t);this.pop()}else if(this.state===l){if(e!==l)return this.parseError(e,t);this.state=L}else{if(this.state!==u)return this.parseError(e,t);if(e===u)this.mode===M?(this.key++,this.state=L):this.mode===j&&(this.state=U);else{if(!(e===c&&this.mode===M||e===s&&this.mode===j))return this.parseError(e,t);this.pop()}}},Y.numberReviver=function(e,t,r){var n=Number(e);if(isNaN(n))return this.charError(t,r);e.match(/[0-9]+/)==e&&n.toString()!=e?this.onToken(p,e):this.onToken(g,n)},z.C=i,e.exports=z},2741:function(e,t,r){"use strict";r.r(t),r.d(t,{CordovaIFrameNavigator:function(){return n.CordovaIFrameNavigator},CordovaPopupNavigator:function(){return n.CordovaPopupNavigator},InMemoryWebStorage:function(){return n.InMemoryWebStorage},Log:function(){return n.Log},OidcClient:function(){return n.OidcClient},SessionMonitor:function(){return n.SessionMonitor},User:function(){return n.User},UserManager:function(){return n.UserManager},Version:function(){return n.Version},WebStorageStateStore:function(){return n.WebStorageStateStore},clearOidcPersistentStorage:function(){return N},getBearerToken:function(){return P},getDpopToken:function(){return C},normalizeCallbackUrl:function(){return F},refresh:function(){return O},registerClient:function(){return I}});var n=r(6516);r(7007),globalThis.fetch;const{fetch:i,Response:o,Request:s,Headers:a}=globalThis;var c=r(9380),l=r(8136),u=r(7248),d=r(7307),h=r(5130),f={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let p;const g=new Uint8Array(16);function y(){if(!p&&(p="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!p))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return p(g)}const m=[];for(let e=0;e<256;++e)m.push((e+256).toString(16).slice(1));var v=function(e,t,r){if(f.randomUUID&&!t&&!e)return f.randomUUID();const n=(e=e||{}).random||(e.rng||y)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=n[e];return t}return function(e,t=0){return m[e[t+0]]+m[e[t+1]]+m[e[t+2]]+m[e[t+3]]+"-"+m[e[t+4]]+m[e[t+5]]+"-"+m[e[t+6]]+m[e[t+7]]+"-"+m[e[t+8]]+m[e[t+9]]+"-"+m[e[t+10]]+m[e[t+11]]+m[e[t+12]]+m[e[t+13]]+m[e[t+14]]+m[e[t+15]]}(n)};const b=["ES256","RS256"],w=["openid","offline_access","webid"].join(" ");async function _(e,t,r,n){const o=await async function(e,t){const r=await i.call(globalThis,e);if(200!==r.status)throw new Error(`Could not fetch JWKS for [${t}] at [${e}]: ${r.status} ${r.statusText}`);let n;try{n=(await r.json()).keys[0]}catch(r){throw new Error(`Malformed JWKS for [${t}] at [${e}]: ${r.message}`)}return n}(t,r);let s;try{const{payload:t}=await(0,c.V)(e,await(0,l.Og)(o),{issuer:r,audience:n});s=t}catch(e){throw new Error(`Token verification failed: ${e.stack}`)}if("string"==typeof s.webid)return s.webid;if("string"!=typeof s.sub)throw new Error(`The token ${JSON.stringify(s)} is invalid: it has no 'webid' claim and no 'sub' claim.`);try{return new URL(s.sub),s.sub}catch(e){throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${s.sub}] is invalid as a URL - error [${e}].`)}}Error,Error;class S extends Error{constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class E extends Error{constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function A(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function R(e,t,r){return new u.P({htu:A(e),htm:t.toUpperCase(),jti:v()}).setProtectedHeader({alg:b[0],jwk:r.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(r.privateKey,{})}async function I(e,t){var r;if(!t.registrationEndpoint)throw new Error("Dynamic Registration could not be completed because the issuer has no registration endpoint.");if(!Array.isArray(t.idTokenSigningAlgValuesSupported))throw new Error("The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.");const n=function(e,t){var r;return null!==(r=t.find((t=>e.includes(t))))&&void 0!==r?r:null}(t.idTokenSigningAlgValuesSupported,b),i={client_name:e.clientName,application_type:"web",redirect_uris:[null===(r=e.redirectUrl)||void 0===r?void 0:r.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:n,grant_types:["authorization_code","refresh_token"]},o=await fetch(t.registrationEndpoint.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(o.ok){const t=await o.json();return function(e,t){if(void 0===e.client_id)throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(e)}`);if(t.redirectUrl&&(void 0===e.redirect_uris||e.redirect_uris[0]!==t.redirectUrl.toString()))throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(e.redirect_uris)} don't match the provided ${JSON.stringify([t.redirectUrl.toString()])}`)}(t,e),{clientId:t.client_id,clientSecret:t.client_secret,idTokenSignedResponseAlg:t.id_token_signed_response_alg,clientType:"dynamic"}}throw 400===o.status&&function(e,t){var r,n,i,o;if("invalid_redirect_uri"===e.error)throw new Error(`Dynamic client registration failed: the provided redirect uri [${null===(r=t.redirectUrl)||void 0===r?void 0:r.toString()}] is invalid - ${null!==(n=e.error_description)&&void 0!==n?n:""}`);if("invalid_client_metadata"===e.error)throw new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(t)} is invalid - ${null!==(i=e.error_description)&&void 0!==i?i:""}`);throw new Error(`Dynamic client registration failed: ${e.error} - ${null!==(o=e.error_description)&&void 0!==o?o:""}`)}(await o.json(),e),new Error(`Dynamic client registration failed: the server returned ${o.status} ${o.statusText} - ${await o.text()}`)}function T(e){return void 0!==e.error_description&&"string"==typeof e.error_description}function x(e,t){if(void 0!==(r=e).error&&"string"==typeof r.error)throw new E(`Token endpoint returned error [${e.error}]${T(e)?`: ${e.error_description}`:""}${function(e){return void 0!==e.error_uri&&"string"==typeof e.error_uri}(e)?` (see ${e.error_uri})`:""}`,e.error,T(e)?e.error_description:void 0);var r;if(!function(e){return void 0!==e.access_token&&"string"==typeof e.access_token}(e))throw new S(["access_token"]);if(!function(e){return void 0!==e.id_token&&"string"==typeof e.id_token}(e))throw new S(["id_token"]);if(!function(e){return void 0!==e.token_type&&"string"==typeof e.token_type}(e))throw new S(["token_type"]);if(!function(e){return void 0===e.expires_in||"number"==typeof e.expires_in}(e))throw new S(["expires_in"]);if(!t&&"bearer"!==e.token_type.toLowerCase())throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${e.token_type}].`);return e}async function P(e){let t;try{const r=new n.OidcClient({response_mode:"query",loadUserInfo:!1});if(t=await r.processSigninResponse(e),void 0===r.settings.metadata)throw new Error("Cannot retrieve issuer metadata from client information in storage.");if(void 0===r.settings.metadata.jwks_uri)throw new Error("Missing some issuer metadata from client information in storage: 'jwks_uri' is undefined");if(void 0===r.settings.metadata.issuer)throw new Error("Missing some issuer metadata from client information in storage: 'issuer' is undefined");if(void 0===r.settings.client_id)throw new Error("Missing some client information in storage: 'client_id' is undefined");const i=await _(t.id_token,r.settings.metadata.jwks_uri,r.settings.metadata.issuer,r.settings.client_id);return{accessToken:t.access_token,idToken:t.id_token,webId:i,refreshToken:t.refresh_token}}catch(t){throw new Error(`Problem handling Auth Code Grant (Flow) redirect - URL [${e}]: ${t}`)}}async function C(e,t,r){return async function(e,t,r,n){!function(e,t){if(t.grantType&&(!e.grantTypesSupported||!e.grantTypesSupported.includes(t.grantType)))throw new Error(`The issuer [${e.issuer}] does not support the [${t.grantType}] grant`);if(!e.tokenEndpoint)throw new Error(`This issuer [${e.issuer}] does not have a token endpoint`)}(e,r);const o={"content-type":"application/x-www-form-urlencoded"};let s;n&&(s=await async function(){const{privateKey:e,publicKey:t}=await(0,d.T)(b[0]),r={privateKey:e,publicKey:await(0,h.JU)(t)};return[r.publicKey.alg]=b,r}(),o.DPoP=await R(e.tokenEndpoint,"POST",s)),t.clientSecret&&(o.Authorization=`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`);const a={grant_type:r.grantType,redirect_uri:r.redirectUrl,code:r.code,code_verifier:r.codeVerifier,client_id:t.clientId},c={method:"POST",headers:o,body:new URLSearchParams(a).toString()},l=await i(e.tokenEndpoint,c),u=x(await l.json(),n),f=await _(u.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:u.access_token,idToken:u.id_token,refreshToken:(p=u,void 0!==p.refresh_token&&"string"==typeof p.refresh_token?u.refresh_token:void 0),webId:f,dpopKey:s,expiresIn:u.expires_in};var p}(e,t,r,!0)}const k=e=>{try{return new URL(e),!0}catch(e){return!1}};async function O(e,t,r,n){if(void 0===r.clientId)throw new Error("No client ID available when trying to refresh the access token.");const o={grant_type:"refresh_token",refresh_token:e,scope:w};let s={};void 0!==n&&(s={DPoP:await R(t.tokenEndpoint,"POST",n)});let a={};void 0!==r.clientSecret?a={Authorization:`Basic ${btoa(`${r.clientId}:${r.clientSecret}`)}`}:k(r.clientId)&&(o.client_id=r.clientId);const c=await i(t.tokenEndpoint,{method:"POST",body:new URLSearchParams(o).toString(),headers:{...s,...a,"Content-Type":"application/x-www-form-urlencoded"}});let l;try{l=await c.json()}catch(e){throw new Error(`The token endpoint of issuer ${t.issuer} returned a malformed response.`)}const u=x(l,void 0!==n),d=await _(u.id_token,t.jwksUri,t.issuer,r.clientId);return{accessToken:u.access_token,idToken:u.id_token,refreshToken:"string"==typeof u.refresh_token?u.refresh_token:void 0,webId:d,dpopKey:n,expiresIn:u.expires_in}}function F(e){const t=function(e){const t=new URL(e);return t.searchParams.delete("state"),t.searchParams.delete("code"),t.searchParams.delete("error"),t.searchParams.delete("error_description"),t.searchParams.delete("iss"),t}(e);return t.hash="",e.includes(`${t.origin}/`)?t.href:`${t.origin}${t.href.substring(t.origin.length+1)}`}async function N(){const e=new n.OidcClient({response_mode:"query"});await e.clearStaleState(new n.WebStorageStateStore({}));const t=window.localStorage,r=[];for(let e=0;e<=t.length;e+=1){const n=t.key(e);n&&(n.match(/^oidc\..+$/)||n.match(/^solidClientAuthenticationUser:.+$/))&&r.push(n)}r.forEach((e=>t.removeItem(e)))}},6516:function(e){var t;t=function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=22)}([function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r=4){for(var e=arguments.length,t=Array(e),r=0;r=3){for(var e=arguments.length,t=Array(e),r=0;r=2){for(var e=arguments.length,t=Array(e),r=0;r=1){for(var e=arguments.length,t=Array(e),r=0;r1&&void 0!==arguments[1]?arguments[1]:o.JsonService;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw i.Log.error("MetadataService: No settings passed to MetadataService"),new Error("settings");this._settings=t,this._jsonService=new r(["application/jwk-set+json"])}return e.prototype.resetSigningKeys=function(){this._settings=this._settings||{},this._settings.signingKeys=void 0},e.prototype.getMetadata=function(){var e=this;return this._settings.metadata?(i.Log.debug("MetadataService.getMetadata: Returning metadata from settings"),Promise.resolve(this._settings.metadata)):this.metadataUrl?(i.Log.debug("MetadataService.getMetadata: getting metadata from",this.metadataUrl),this._jsonService.getJson(this.metadataUrl).then((function(t){i.Log.debug("MetadataService.getMetadata: json received");var r=e._settings.metadataSeed||{};return e._settings.metadata=Object.assign({},r,t),e._settings.metadata}))):(i.Log.error("MetadataService.getMetadata: No authority or metadataUrl configured on settings"),Promise.reject(new Error("No authority or metadataUrl configured on settings")))},e.prototype.getIssuer=function(){return this._getMetadataProperty("issuer")},e.prototype.getAuthorizationEndpoint=function(){return this._getMetadataProperty("authorization_endpoint")},e.prototype.getUserInfoEndpoint=function(){return this._getMetadataProperty("userinfo_endpoint")},e.prototype.getTokenEndpoint=function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._getMetadataProperty("token_endpoint",e)},e.prototype.getCheckSessionIframe=function(){return this._getMetadataProperty("check_session_iframe",!0)},e.prototype.getEndSessionEndpoint=function(){return this._getMetadataProperty("end_session_endpoint",!0)},e.prototype.getRevocationEndpoint=function(){return this._getMetadataProperty("revocation_endpoint",!0)},e.prototype.getKeysEndpoint=function(){return this._getMetadataProperty("jwks_uri",!0)},e.prototype._getMetadataProperty=function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return i.Log.debug("MetadataService.getMetadataProperty for: "+e),this.getMetadata().then((function(r){if(i.Log.debug("MetadataService.getMetadataProperty: metadata recieved"),void 0===r[e]){if(!0===t)return void i.Log.warn("MetadataService.getMetadataProperty: Metadata does not contain optional property "+e);throw i.Log.error("MetadataService.getMetadataProperty: Metadata does not contain property "+e),new Error("Metadata does not contain property "+e)}return r[e]}))},e.prototype.getSigningKeys=function(){var e=this;return this._settings.signingKeys?(i.Log.debug("MetadataService.getSigningKeys: Returning signingKeys from settings"),Promise.resolve(this._settings.signingKeys)):this._getMetadataProperty("jwks_uri").then((function(t){return i.Log.debug("MetadataService.getSigningKeys: jwks_uri received",t),e._jsonService.getJson(t).then((function(t){if(i.Log.debug("MetadataService.getSigningKeys: key set received",t),!t.keys)throw i.Log.error("MetadataService.getSigningKeys: Missing keys on keyset"),new Error("Missing keys on keyset");return e._settings.signingKeys=t.keys,e._settings.signingKeys}))}))},n(e,[{key:"metadataUrl",get:function(){return this._metadataUrl||(this._settings.metadataUrl?this._metadataUrl=this._settings.metadataUrl:(this._metadataUrl=this._settings.authority,this._metadataUrl&&this._metadataUrl.indexOf(s)<0&&("/"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+="/"),this._metadataUrl+=s))),this._metadataUrl}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UrlUtility=void 0;var n=r(0),i=r(1);t.UrlUtility=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.addQueryParam=function(e,t,r){return e.indexOf("?")<0&&(e+="?"),"?"!==e[e.length-1]&&(e+="&"),e+=encodeURIComponent(t),(e+="=")+encodeURIComponent(r)},e.parseUrlFragment=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"#",r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.Global;"string"!=typeof e&&(e=r.location.href);var o=e.lastIndexOf(t);o>=0&&(e=e.substr(o+1)),"?"===t&&(o=e.indexOf("#"))>=0&&(e=e.substr(0,o));for(var s,a={},c=/([^&=]+)=([^&]*)/g,l=0;s=c.exec(e);)if(a[decodeURIComponent(s[1])]=decodeURIComponent(s[2].replace(/\+/g," ")),l++>50)return n.Log.error("UrlUtility.parseUrlFragment: response exceeded expected number of parameters",e),{error:"Response exceeded expected number of parameters"};for(var u in a)return a;return{}},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JoseUtil=void 0;var n=r(26),i=function(e){return e&&e.__esModule?e:{default:e}}(r(33));t.JoseUtil=(0,i.default)({jws:n.jws,KeyUtil:n.KeyUtil,X509:n.X509,crypto:n.crypto,hextob64u:n.hextob64u,b64tohex:n.b64tohex,AllowedSigningAlgs:n.AllowedSigningAlgs})},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OidcClientSettings=void 0;var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},r=t.authority,i=t.metadataUrl,o=t.metadata,u=t.signingKeys,d=t.metadataSeed,h=t.client_id,f=t.client_secret,p=t.response_type,g=void 0===p?"id_token":p,y=t.scope,m=void 0===y?"openid":y,v=t.redirect_uri,b=t.post_logout_redirect_uri,w=t.client_authentication,_=void 0===w?"client_secret_post":w,S=t.prompt,E=t.display,A=t.max_age,R=t.ui_locales,I=t.acr_values,T=t.resource,x=t.response_mode,P=t.filterProtocolClaims,C=void 0===P||P,k=t.loadUserInfo,O=void 0===k||k,F=t.staleStateAge,N=void 0===F?900:F,D=t.clockSkew,L=void 0===D?300:D,U=t.clockService,j=void 0===U?new s.ClockService:U,M=t.userInfoJwtIssuer,B=void 0===M?"OP":M,H=t.mergeClaims,W=void 0!==H&&H,$=t.stateStore,V=void 0===$?new a.WebStorageStateStore:$,K=t.ResponseValidatorCtor,J=void 0===K?c.ResponseValidator:K,G=t.MetadataServiceCtor,q=void 0===G?l.MetadataService:G,z=t.extraQueryParams,Y=void 0===z?{}:z,Q=t.extraTokenParams,X=void 0===Q?{}:Q;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._authority=r,this._metadataUrl=i,this._metadata=o,this._metadataSeed=d,this._signingKeys=u,this._client_id=h,this._client_secret=f,this._response_type=g,this._scope=m,this._redirect_uri=v,this._post_logout_redirect_uri=b,this._client_authentication=_,this._prompt=S,this._display=E,this._max_age=A,this._ui_locales=R,this._acr_values=I,this._resource=T,this._response_mode=x,this._filterProtocolClaims=!!C,this._loadUserInfo=!!O,this._staleStateAge=N,this._clockSkew=L,this._clockService=j,this._userInfoJwtIssuer=B,this._mergeClaims=!!W,this._stateStore=V,this._validator=new J(this),this._metadataService=new q(this),this._extraQueryParams="object"===(void 0===Y?"undefined":n(Y))?Y:{},this._extraTokenParams="object"===(void 0===X?"undefined":n(X))?X:{}}return e.prototype.getEpochTime=function(){return this._clockService.getEpochTime()},i(e,[{key:"client_id",get:function(){return this._client_id},set:function(e){if(this._client_id)throw o.Log.error("OidcClientSettings.set_client_id: client_id has already been assigned."),new Error("client_id has already been assigned.");this._client_id=e}},{key:"client_secret",get:function(){return this._client_secret}},{key:"response_type",get:function(){return this._response_type}},{key:"scope",get:function(){return this._scope}},{key:"redirect_uri",get:function(){return this._redirect_uri}},{key:"post_logout_redirect_uri",get:function(){return this._post_logout_redirect_uri}},{key:"client_authentication",get:function(){return this._client_authentication}},{key:"prompt",get:function(){return this._prompt}},{key:"display",get:function(){return this._display}},{key:"max_age",get:function(){return this._max_age}},{key:"ui_locales",get:function(){return this._ui_locales}},{key:"acr_values",get:function(){return this._acr_values}},{key:"resource",get:function(){return this._resource}},{key:"response_mode",get:function(){return this._response_mode}},{key:"authority",get:function(){return this._authority},set:function(e){if(this._authority)throw o.Log.error("OidcClientSettings.set_authority: authority has already been assigned."),new Error("authority has already been assigned.");this._authority=e}},{key:"metadataUrl",get:function(){return this._metadataUrl||(this._metadataUrl=this.authority,this._metadataUrl&&this._metadataUrl.indexOf(u)<0&&("/"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+="/"),this._metadataUrl+=u)),this._metadataUrl}},{key:"metadata",get:function(){return this._metadata},set:function(e){this._metadata=e}},{key:"metadataSeed",get:function(){return this._metadataSeed},set:function(e){this._metadataSeed=e}},{key:"signingKeys",get:function(){return this._signingKeys},set:function(e){this._signingKeys=e}},{key:"filterProtocolClaims",get:function(){return this._filterProtocolClaims}},{key:"loadUserInfo",get:function(){return this._loadUserInfo}},{key:"staleStateAge",get:function(){return this._staleStateAge}},{key:"clockSkew",get:function(){return this._clockSkew}},{key:"userInfoJwtIssuer",get:function(){return this._userInfoJwtIssuer}},{key:"mergeClaims",get:function(){return this._mergeClaims}},{key:"stateStore",get:function(){return this._stateStore}},{key:"validator",get:function(){return this._validator}},{key:"metadataService",get:function(){return this._metadataService}},{key:"extraQueryParams",get:function(){return this._extraQueryParams},set:function(e){"object"===(void 0===e?"undefined":n(e))?this._extraQueryParams=e:this._extraQueryParams={}}},{key:"extraTokenParams",get:function(){return this._extraTokenParams},set:function(e){"object"===(void 0===e?"undefined":n(e))?this._extraTokenParams=e:this._extraTokenParams={}}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebStorageStateStore=void 0;var n=r(0),i=r(1);t.WebStorageStateStore=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.prefix,n=void 0===r?"oidc.":r,o=t.store,s=void 0===o?i.Global.localStorage:o;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._store=s,this._prefix=n}return e.prototype.set=function(e,t){return n.Log.debug("WebStorageStateStore.set",e),e=this._prefix+e,this._store.setItem(e,t),Promise.resolve()},e.prototype.get=function(e){n.Log.debug("WebStorageStateStore.get",e),e=this._prefix+e;var t=this._store.getItem(e);return Promise.resolve(t)},e.prototype.remove=function(e){n.Log.debug("WebStorageStateStore.remove",e),e=this._prefix+e;var t=this._store.getItem(e);return this._store.removeItem(e),Promise.resolve(t)},e.prototype.getAllKeys=function(){n.Log.debug("WebStorageStateStore.getAllKeys");for(var e=[],t=0;t0&&void 0!==arguments[0]?arguments[0]:null,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i.Global.XMLHttpRequest,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),t&&Array.isArray(t)?this._contentTypes=t.slice():this._contentTypes=[],this._contentTypes.push("application/json"),n&&this._contentTypes.push("application/jwt"),this._XMLHttpRequest=r,this._jwtHandler=n}return e.prototype.getJson=function(e,t){var r=this;if(!e)throw n.Log.error("JsonService.getJson: No url passed"),new Error("url");return n.Log.debug("JsonService.getJson, url: ",e),new Promise((function(i,o){var s=new r._XMLHttpRequest;s.open("GET",e);var a=r._contentTypes,c=r._jwtHandler;s.onload=function(){if(n.Log.debug("JsonService.getJson: HTTP response received, status",s.status),200===s.status){var t=s.getResponseHeader("Content-Type");if(t){var r=a.find((function(e){if(t.startsWith(e))return!0}));if("application/jwt"==r)return void c(s).then(i,o);if(r)try{return void i(JSON.parse(s.responseText))}catch(e){return n.Log.error("JsonService.getJson: Error parsing JSON response",e.message),void o(e)}}o(Error("Invalid response Content-Type: "+t+", from URL: "+e))}else o(Error(s.statusText+" ("+s.status+")"))},s.onerror=function(){n.Log.error("JsonService.getJson: network error"),o(Error("Network Error"))},t&&(n.Log.debug("JsonService.getJson: token passed, setting Authorization header"),s.setRequestHeader("Authorization","Bearer "+t)),s.send()}))},e.prototype.postForm=function(e,t,r){var i=this;if(!e)throw n.Log.error("JsonService.postForm: No url passed"),new Error("url");return n.Log.debug("JsonService.postForm, url: ",e),new Promise((function(o,s){var a=new i._XMLHttpRequest;a.open("POST",e);var c=i._contentTypes;a.onload=function(){if(n.Log.debug("JsonService.postForm: HTTP response received, status",a.status),200!==a.status){if(400===a.status&&(r=a.getResponseHeader("Content-Type"))&&c.find((function(e){if(r.startsWith(e))return!0})))try{var t=JSON.parse(a.responseText);if(t&&t.error)return n.Log.error("JsonService.postForm: Error from server: ",t.error),void s(new Error(t.error))}catch(e){return n.Log.error("JsonService.postForm: Error parsing JSON response",e.message),void s(e)}s(Error(a.statusText+" ("+a.status+")"))}else{var r;if((r=a.getResponseHeader("Content-Type"))&&c.find((function(e){if(r.startsWith(e))return!0})))try{return void o(JSON.parse(a.responseText))}catch(e){return n.Log.error("JsonService.postForm: Error parsing JSON response",e.message),void s(e)}s(Error("Invalid response Content-Type: "+r+", from URL: "+e))}},a.onerror=function(){n.Log.error("JsonService.postForm: network error"),s(Error("Network Error"))};var l="";for(var u in t){var d=t[u];d&&(l.length>0&&(l+="&"),l+=encodeURIComponent(u),l+="=",l+=encodeURIComponent(d))}a.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),void 0!==r&&a.setRequestHeader("Authorization","Basic "+btoa(r)),a.send(l)}))},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SigninRequest=void 0;var n=r(0),i=r(3),o=r(13);t.SigninRequest=function(){function e(t){var r=t.url,s=t.client_id,a=t.redirect_uri,c=t.response_type,l=t.scope,u=t.authority,d=t.data,h=t.prompt,f=t.display,p=t.max_age,g=t.ui_locales,y=t.id_token_hint,m=t.login_hint,v=t.acr_values,b=t.resource,w=t.response_mode,_=t.request,S=t.request_uri,E=t.extraQueryParams,A=t.request_type,R=t.client_secret,I=t.extraTokenParams,T=t.skipUserInfo;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!r)throw n.Log.error("SigninRequest.ctor: No url passed"),new Error("url");if(!s)throw n.Log.error("SigninRequest.ctor: No client_id passed"),new Error("client_id");if(!a)throw n.Log.error("SigninRequest.ctor: No redirect_uri passed"),new Error("redirect_uri");if(!c)throw n.Log.error("SigninRequest.ctor: No response_type passed"),new Error("response_type");if(!l)throw n.Log.error("SigninRequest.ctor: No scope passed"),new Error("scope");if(!u)throw n.Log.error("SigninRequest.ctor: No authority passed"),new Error("authority");var x=e.isOidc(c),P=e.isCode(c);w||(w=e.isCode(c)?"query":null),this.state=new o.SigninState({nonce:x,data:d,client_id:s,authority:u,redirect_uri:a,code_verifier:P,request_type:A,response_mode:w,client_secret:R,scope:l,extraTokenParams:I,skipUserInfo:T}),r=i.UrlUtility.addQueryParam(r,"client_id",s),r=i.UrlUtility.addQueryParam(r,"redirect_uri",a),r=i.UrlUtility.addQueryParam(r,"response_type",c),r=i.UrlUtility.addQueryParam(r,"scope",l),r=i.UrlUtility.addQueryParam(r,"state",this.state.id),x&&(r=i.UrlUtility.addQueryParam(r,"nonce",this.state.nonce)),P&&(r=i.UrlUtility.addQueryParam(r,"code_challenge",this.state.code_challenge),r=i.UrlUtility.addQueryParam(r,"code_challenge_method","S256"));var C={prompt:h,display:f,max_age:p,ui_locales:g,id_token_hint:y,login_hint:m,acr_values:v,resource:b,request:_,request_uri:S,response_mode:w};for(var k in C)C[k]&&(r=i.UrlUtility.addQueryParam(r,k,C[k]));for(var O in E)r=i.UrlUtility.addQueryParam(r,O,E[O]);this.url=r}return e.isOidc=function(e){return!!e.split(/\s+/g).filter((function(e){return"id_token"===e}))[0]},e.isOAuth=function(e){return!!e.split(/\s+/g).filter((function(e){return"token"===e}))[0]},e.isCode=function(e){return!!e.split(/\s+/g).filter((function(e){return"code"===e}))[0]},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.State=void 0;var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},r=t.id,n=t.data,i=t.created,s=t.request_type;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._id=r||(0,o.default)(),this._data=n,this._created="number"==typeof i&&i>0?i:parseInt(Date.now()/1e3),this._request_type=s}return e.prototype.toStorageString=function(){return i.Log.debug("State.toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type})},e.fromStorageString=function(t){return i.Log.debug("State.fromStorageString"),new e(JSON.parse(t))},e.clearStaleState=function(t,r){var n=Date.now()/1e3-r;return t.getAllKeys().then((function(r){i.Log.debug("State.clearStaleState: got keys",r);for(var o=[],s=function(s){var a=r[s];c=t.get(a).then((function(r){var o=!1;if(r)try{var s=e.fromStorageString(r);i.Log.debug("State.clearStaleState: got item from key: ",a,s.created),s.created<=n&&(o=!0)}catch(e){i.Log.error("State.clearStaleState: Error parsing state for key",a,e.message),o=!0}else i.Log.debug("State.clearStaleState: no item in storage for key: ",a),o=!0;if(o)return i.Log.debug("State.clearStaleState: removed item for key: ",a),t.remove(a)})),o.push(c)},a=0;a0&&void 0!==arguments[0]?arguments[0]:{};(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),t instanceof o.OidcClientSettings?this._settings=t:this._settings=new o.OidcClientSettings(t)}return e.prototype.createSigninRequest=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.response_type,n=t.scope,o=t.redirect_uri,s=t.data,c=t.state,l=t.prompt,u=t.display,d=t.max_age,h=t.ui_locales,f=t.id_token_hint,p=t.login_hint,g=t.acr_values,y=t.resource,m=t.request,v=t.request_uri,b=t.response_mode,w=t.extraQueryParams,_=t.extraTokenParams,S=t.request_type,E=t.skipUserInfo,A=arguments[1];i.Log.debug("OidcClient.createSigninRequest");var R=this._settings.client_id;r=r||this._settings.response_type,n=n||this._settings.scope,o=o||this._settings.redirect_uri,l=l||this._settings.prompt,u=u||this._settings.display,d=d||this._settings.max_age,h=h||this._settings.ui_locales,g=g||this._settings.acr_values,y=y||this._settings.resource,b=b||this._settings.response_mode,w=w||this._settings.extraQueryParams,_=_||this._settings.extraTokenParams;var I=this._settings.authority;return a.SigninRequest.isCode(r)&&"code"!==r?Promise.reject(new Error("OpenID Connect hybrid flow is not supported")):this._metadataService.getAuthorizationEndpoint().then((function(t){i.Log.debug("OidcClient.createSigninRequest: Received authorization endpoint",t);var T=new a.SigninRequest({url:t,client_id:R,redirect_uri:o,response_type:r,scope:n,data:s||c,authority:I,prompt:l,display:u,max_age:d,ui_locales:h,id_token_hint:f,login_hint:p,acr_values:g,resource:y,request:m,request_uri:v,extraQueryParams:w,extraTokenParams:_,request_type:S,response_mode:b,client_secret:e._settings.client_secret,skipUserInfo:E}),x=T.state;return(A=A||e._stateStore).set(x.id,x.toStorageString()).then((function(){return T}))}))},e.prototype.readSigninResponseState=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];i.Log.debug("OidcClient.readSigninResponseState");var n="query"===this._settings.response_mode||!this._settings.response_mode&&a.SigninRequest.isCode(this._settings.response_type)?"?":"#",o=new c.SigninResponse(e,n);return o.state?(t=t||this._stateStore,(r?t.remove.bind(t):t.get.bind(t))(o.state).then((function(e){if(!e)throw i.Log.error("OidcClient.readSigninResponseState: No matching state found in storage"),new Error("No matching state found in storage");return{state:d.SigninState.fromStorageString(e),response:o}}))):(i.Log.error("OidcClient.readSigninResponseState: No state in response"),Promise.reject(new Error("No state in response")))},e.prototype.processSigninResponse=function(e,t){var r=this;return i.Log.debug("OidcClient.processSigninResponse"),this.readSigninResponseState(e,t,!0).then((function(e){var t=e.state,n=e.response;return i.Log.debug("OidcClient.processSigninResponse: Received state from storage; validating response"),r._validator.validateSigninResponse(t,n)}))},e.prototype.createSignoutRequest=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.id_token_hint,n=t.data,o=t.state,s=t.post_logout_redirect_uri,a=t.extraQueryParams,c=t.request_type,u=arguments[1];return i.Log.debug("OidcClient.createSignoutRequest"),s=s||this._settings.post_logout_redirect_uri,a=a||this._settings.extraQueryParams,this._metadataService.getEndSessionEndpoint().then((function(t){if(!t)throw i.Log.error("OidcClient.createSignoutRequest: No end session endpoint url returned"),new Error("no end session endpoint");i.Log.debug("OidcClient.createSignoutRequest: Received end session endpoint",t);var d=new l.SignoutRequest({url:t,id_token_hint:r,post_logout_redirect_uri:s,data:n||o,extraQueryParams:a,request_type:c}),h=d.state;return h&&(i.Log.debug("OidcClient.createSignoutRequest: Signout request has state to persist"),(u=u||e._stateStore).set(h.id,h.toStorageString())),d}))},e.prototype.readSignoutResponseState=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];i.Log.debug("OidcClient.readSignoutResponseState");var n=new u.SignoutResponse(e);if(!n.state)return i.Log.debug("OidcClient.readSignoutResponseState: No state in response"),n.error?(i.Log.warn("OidcClient.readSignoutResponseState: Response was error: ",n.error),Promise.reject(new s.ErrorResponse(n))):Promise.resolve({state:void 0,response:n});var o=n.state;return t=t||this._stateStore,(r?t.remove.bind(t):t.get.bind(t))(o).then((function(e){if(!e)throw i.Log.error("OidcClient.readSignoutResponseState: No matching state found in storage"),new Error("No matching state found in storage");return{state:h.State.fromStorageString(e),response:n}}))},e.prototype.processSignoutResponse=function(e,t){var r=this;return i.Log.debug("OidcClient.processSignoutResponse"),this.readSignoutResponseState(e,t,!0).then((function(e){var t=e.state,n=e.response;return t?(i.Log.debug("OidcClient.processSignoutResponse: Received state from storage; validating response"),r._validator.validateSignoutResponse(t,n)):(i.Log.debug("OidcClient.processSignoutResponse: No state from storage; skipping validating response"),n)}))},e.prototype.clearStaleState=function(e){return i.Log.debug("OidcClient.clearStaleState"),e=e||this._stateStore,h.State.clearStaleState(e,this.settings.staleStateAge)},n(e,[{key:"_stateStore",get:function(){return this.settings.stateStore}},{key:"_validator",get:function(){return this.settings.validator}},{key:"_metadataService",get:function(){return this.settings.metadataService}},{key:"settings",get:function(){return this._settings}},{key:"metadataService",get:function(){return this._metadataService}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TokenClient=void 0;var n=r(7),i=r(2),o=r(0);t.TokenClient=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.JsonService,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.MetadataService;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw o.Log.error("TokenClient.ctor: No settings passed"),new Error("settings");this._settings=t,this._jsonService=new r,this._metadataService=new s(this._settings)}return e.prototype.exchangeCode=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(t=Object.assign({},t)).grant_type=t.grant_type||"authorization_code",t.client_id=t.client_id||this._settings.client_id,t.client_secret=t.client_secret||this._settings.client_secret,t.redirect_uri=t.redirect_uri||this._settings.redirect_uri;var r=void 0,n=t._client_authentication||this._settings._client_authentication;return delete t._client_authentication,t.code?t.redirect_uri?t.code_verifier?t.client_id?t.client_secret||"client_secret_basic"!=n?("client_secret_basic"==n&&(r=t.client_id+":"+t.client_secret,delete t.client_id,delete t.client_secret),this._metadataService.getTokenEndpoint(!1).then((function(n){return o.Log.debug("TokenClient.exchangeCode: Received token endpoint"),e._jsonService.postForm(n,t,r).then((function(e){return o.Log.debug("TokenClient.exchangeCode: response received"),e}))}))):(o.Log.error("TokenClient.exchangeCode: No client_secret passed"),Promise.reject(new Error("A client_secret is required"))):(o.Log.error("TokenClient.exchangeCode: No client_id passed"),Promise.reject(new Error("A client_id is required"))):(o.Log.error("TokenClient.exchangeCode: No code_verifier passed"),Promise.reject(new Error("A code_verifier is required"))):(o.Log.error("TokenClient.exchangeCode: No redirect_uri passed"),Promise.reject(new Error("A redirect_uri is required"))):(o.Log.error("TokenClient.exchangeCode: No code passed"),Promise.reject(new Error("A code is required")))},e.prototype.exchangeRefreshToken=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(t=Object.assign({},t)).grant_type=t.grant_type||"refresh_token",t.client_id=t.client_id||this._settings.client_id,t.client_secret=t.client_secret||this._settings.client_secret;var r=void 0,n=t._client_authentication||this._settings._client_authentication;return delete t._client_authentication,t.refresh_token?t.client_id?("client_secret_basic"==n&&(r=t.client_id+":"+t.client_secret,delete t.client_id,delete t.client_secret),this._metadataService.getTokenEndpoint(!1).then((function(n){return o.Log.debug("TokenClient.exchangeRefreshToken: Received token endpoint"),e._jsonService.postForm(n,t,r).then((function(e){return o.Log.debug("TokenClient.exchangeRefreshToken: response received"),e}))}))):(o.Log.error("TokenClient.exchangeRefreshToken: No client_id passed"),Promise.reject(new Error("A client_id is required"))):(o.Log.error("TokenClient.exchangeRefreshToken: No refresh_token passed"),Promise.reject(new Error("A refresh_token is required")))},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorResponse=void 0;var n=r(0);t.ErrorResponse=function(e){function t(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=r.error,o=r.error_description,s=r.error_uri,a=r.state,c=r.session_state;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),!i)throw n.Log.error("No error passed to ErrorResponse"),new Error("error");var l=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,o||i));return l.name="ErrorResponse",l.error=i,l.error_description=o,l.error_uri=s,l.state=a,l.session_state=c,l}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t}(Error)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SigninState=void 0;var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=r.nonce,i=r.authority,o=r.client_id,c=r.redirect_uri,l=r.code_verifier,u=r.response_mode,d=r.client_secret,h=r.scope,f=r.extraTokenParams,p=r.skipUserInfo;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var g=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,arguments[0]));if(!0===n?g._nonce=(0,a.default)():n&&(g._nonce=n),!0===l?g._code_verifier=(0,a.default)()+(0,a.default)()+(0,a.default)():l&&(g._code_verifier=l),g.code_verifier){var y=s.JoseUtil.hashString(g.code_verifier,"SHA256");g._code_challenge=s.JoseUtil.hexToBase64Url(y)}return g._redirect_uri=c,g._authority=i,g._client_id=o,g._response_mode=u,g._client_secret=d,g._scope=h,g._extraTokenParams=f,g._skipUserInfo=p,g}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.toStorageString=function(){return i.Log.debug("SigninState.toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,nonce:this.nonce,code_verifier:this.code_verifier,redirect_uri:this.redirect_uri,authority:this.authority,client_id:this.client_id,response_mode:this.response_mode,client_secret:this.client_secret,scope:this.scope,extraTokenParams:this.extraTokenParams,skipUserInfo:this.skipUserInfo})},t.fromStorageString=function(e){return i.Log.debug("SigninState.fromStorageString"),new t(JSON.parse(e))},n(t,[{key:"nonce",get:function(){return this._nonce}},{key:"authority",get:function(){return this._authority}},{key:"client_id",get:function(){return this._client_id}},{key:"redirect_uri",get:function(){return this._redirect_uri}},{key:"code_verifier",get:function(){return this._code_verifier}},{key:"code_challenge",get:function(){return this._code_challenge}},{key:"response_mode",get:function(){return this._response_mode}},{key:"client_secret",get:function(){return this._client_secret}},{key:"scope",get:function(){return this._scope}},{key:"extraTokenParams",get:function(){return this._extraTokenParams}},{key:"skipUserInfo",get:function(){return this._skipUserInfo}}]),t}(o.State)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return("undefined"!=n&&null!==n&&void 0!==n.getRandomValues?i:o)().replace(/-/g,"")};var n="undefined"!=typeof window?window.crypto||window.msCrypto:null;function i(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(function(e){return(e^n.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16)}))}function o(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(function(e){return(e^16*Math.random()>>e/4).toString(16)}))}e.exports=t.default},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.User=void 0;var n=function(){function e(e,t){for(var r=0;r0){var r=parseInt(Date.now()/1e3);this.expires_at=r+t}}},{key:"expired",get:function(){var e=this.expires_in;if(void 0!==e)return e<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AccessTokenEvents=void 0;var n=r(0),i=r(46);t.AccessTokenEvents=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.accessTokenExpiringNotificationTime,n=void 0===r?60:r,o=t.accessTokenExpiringTimer,s=void 0===o?new i.Timer("Access token expiring"):o,a=t.accessTokenExpiredTimer,c=void 0===a?new i.Timer("Access token expired"):a;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._accessTokenExpiringNotificationTime=n,this._accessTokenExpiring=s,this._accessTokenExpired=c}return e.prototype.load=function(e){if(e.access_token&&void 0!==e.expires_in){var t=e.expires_in;if(n.Log.debug("AccessTokenEvents.load: access token present, remaining duration:",t),t>0){var r=t-this._accessTokenExpiringNotificationTime;r<=0&&(r=1),n.Log.debug("AccessTokenEvents.load: registering expiring timer in:",r),this._accessTokenExpiring.init(r)}else n.Log.debug("AccessTokenEvents.load: canceling existing expiring timer becase we're past expiration."),this._accessTokenExpiring.cancel();var i=t+1;n.Log.debug("AccessTokenEvents.load: registering expired timer in:",i),this._accessTokenExpired.init(i)}else this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},e.prototype.unload=function(){n.Log.debug("AccessTokenEvents.unload: canceling existing access token timers"),this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},e.prototype.addAccessTokenExpiring=function(e){this._accessTokenExpiring.addHandler(e)},e.prototype.removeAccessTokenExpiring=function(e){this._accessTokenExpiring.removeHandler(e)},e.prototype.addAccessTokenExpired=function(e){this._accessTokenExpired.addHandler(e)},e.prototype.removeAccessTokenExpired=function(e){this._accessTokenExpired.removeHandler(e)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Event=void 0;var n=r(0);t.Event=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._name=t,this._callbacks=[]}return e.prototype.addHandler=function(e){this._callbacks.push(e)},e.prototype.removeHandler=function(e){var t=this._callbacks.findIndex((function(t){return t===e}));t>=0&&this._callbacks.splice(t,1)},e.prototype.raise=function(){n.Log.debug("Event: Raising event: "+this._name);for(var e=0;e1&&void 0!==arguments[1]?arguments[1]:o.CheckSessionIFrame,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.Global.timer;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw i.Log.error("SessionMonitor.ctor: No user manager passed to SessionMonitor"),new Error("userManager");this._userManager=t,this._CheckSessionIFrameCtor=n,this._timer=a,this._userManager.events.addUserLoaded(this._start.bind(this)),this._userManager.events.addUserUnloaded(this._stop.bind(this)),Promise.resolve(this._userManager.getUser().then((function(e){e?r._start(e):r._settings.monitorAnonymousSession&&r._userManager.querySessionStatus().then((function(e){var t={session_state:e.session_state};e.sub&&e.sid&&(t.profile={sub:e.sub,sid:e.sid}),r._start(t)})).catch((function(e){i.Log.error("SessionMonitor ctor: error from querySessionStatus:",e.message)}))})).catch((function(e){i.Log.error("SessionMonitor ctor: error from getUser:",e.message)})))}return e.prototype._start=function(e){var t=this,r=e.session_state;r&&(e.profile?(this._sub=e.profile.sub,this._sid=e.profile.sid,i.Log.debug("SessionMonitor._start: session_state:",r,", sub:",this._sub)):(this._sub=void 0,this._sid=void 0,i.Log.debug("SessionMonitor._start: session_state:",r,", anonymous user")),this._checkSessionIFrame?this._checkSessionIFrame.start(r):this._metadataService.getCheckSessionIframe().then((function(e){if(e){i.Log.debug("SessionMonitor._start: Initializing check session iframe");var n=t._client_id,o=t._checkSessionInterval,s=t._stopCheckSessionOnError;t._checkSessionIFrame=new t._CheckSessionIFrameCtor(t._callback.bind(t),n,e,o,s),t._checkSessionIFrame.load().then((function(){t._checkSessionIFrame.start(r)}))}else i.Log.warn("SessionMonitor._start: No check session iframe found in the metadata")})).catch((function(e){i.Log.error("SessionMonitor._start: Error from getCheckSessionIframe:",e.message)})))},e.prototype._stop=function(){var e=this;if(this._sub=void 0,this._sid=void 0,this._checkSessionIFrame&&(i.Log.debug("SessionMonitor._stop"),this._checkSessionIFrame.stop()),this._settings.monitorAnonymousSession)var t=this._timer.setInterval((function(){e._timer.clearInterval(t),e._userManager.querySessionStatus().then((function(t){var r={session_state:t.session_state};t.sub&&t.sid&&(r.profile={sub:t.sub,sid:t.sid}),e._start(r)})).catch((function(e){i.Log.error("SessionMonitor: error from querySessionStatus:",e.message)}))}),1e3)},e.prototype._callback=function(){var e=this;this._userManager.querySessionStatus().then((function(t){var r=!0;t?t.sub===e._sub?(r=!1,e._checkSessionIFrame.start(t.session_state),t.sid===e._sid?i.Log.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",t.session_state):(i.Log.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",t.session_state),e._userManager.events._raiseUserSessionChanged())):i.Log.debug("SessionMonitor._callback: Different subject signed into OP:",t.sub):i.Log.debug("SessionMonitor._callback: Subject no longer signed into OP"),r&&(e._sub?(i.Log.debug("SessionMonitor._callback: SessionMonitor._callback; raising signed out event"),e._userManager.events._raiseUserSignedOut()):(i.Log.debug("SessionMonitor._callback: SessionMonitor._callback; raising signed in event"),e._userManager.events._raiseUserSignedIn()))})).catch((function(t){e._sub&&(i.Log.debug("SessionMonitor._callback: Error calling queryCurrentSigninSession; raising signed out event",t.message),e._userManager.events._raiseUserSignedOut())}))},n(e,[{key:"_settings",get:function(){return this._userManager.settings}},{key:"_metadataService",get:function(){return this._userManager.metadataService}},{key:"_client_id",get:function(){return this._settings.client_id}},{key:"_checkSessionInterval",get:function(){return this._settings.checkSessionInterval}},{key:"_stopCheckSessionOnError",get:function(){return this._settings.stopCheckSessionOnError}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckSessionIFrame=void 0;var n=r(0);t.CheckSessionIFrame=function(){function e(t,r,n,i){var o=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._callback=t,this._client_id=r,this._url=n,this._interval=i||2e3,this._stopOnError=o;var s=n.indexOf("/",n.indexOf("//")+2);this._frame_origin=n.substr(0,s),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.style.display="none",this._frame.width=0,this._frame.height=0,this._frame.src=n}return e.prototype.load=function(){var e=this;return new Promise((function(t){e._frame.onload=function(){t()},window.document.body.appendChild(e._frame),e._boundMessageEvent=e._message.bind(e),window.addEventListener("message",e._boundMessageEvent,!1)}))},e.prototype._message=function(e){e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(n.Log.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(n.Log.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):n.Log.debug("CheckSessionIFrame: "+e.data+" message from check session op iframe"))},e.prototype.start=function(e){var t=this;if(this._session_state!==e){n.Log.debug("CheckSessionIFrame.start"),this.stop(),this._session_state=e;var r=function(){t._frame.contentWindow.postMessage(t._client_id+" "+t._session_state,t._frame_origin)};r(),this._timer=window.setInterval(r,this._interval)}},e.prototype.stop=function(){this._session_state=null,this._timer&&(n.Log.debug("CheckSessionIFrame.stop"),window.clearInterval(this._timer),this._timer=null)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TokenRevocationClient=void 0;var n=r(0),i=r(2),o=r(1);t.TokenRevocationClient=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o.Global.XMLHttpRequest,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.MetadataService;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw n.Log.error("TokenRevocationClient.ctor: No settings provided"),new Error("No settings provided.");this._settings=t,this._XMLHttpRequestCtor=r,this._metadataService=new s(this._settings)}return e.prototype.revoke=function(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"access_token";if(!e)throw n.Log.error("TokenRevocationClient.revoke: No token provided"),new Error("No token provided.");if("access_token"!==i&&"refresh_token"!=i)throw n.Log.error("TokenRevocationClient.revoke: Invalid token type"),new Error("Invalid token type.");return this._metadataService.getRevocationEndpoint().then((function(o){if(o){n.Log.debug("TokenRevocationClient.revoke: Revoking "+i);var s=r._settings.client_id,a=r._settings.client_secret;return r._revoke(o,s,a,e,i)}if(t)throw n.Log.error("TokenRevocationClient.revoke: Revocation not supported"),new Error("Revocation not supported")}))},e.prototype._revoke=function(e,t,r,i,o){var s=this;return new Promise((function(a,c){var l=new s._XMLHttpRequestCtor;l.open("POST",e),l.onload=function(){n.Log.debug("TokenRevocationClient.revoke: HTTP response received, status",l.status),200===l.status?a():c(Error(l.statusText+" ("+l.status+")"))},l.onerror=function(){n.Log.debug("TokenRevocationClient.revoke: Network Error."),c("Network Error")};var u="client_id="+encodeURIComponent(t);r&&(u+="&client_secret="+encodeURIComponent(r)),u+="&token_type_hint="+encodeURIComponent(o),u+="&token="+encodeURIComponent(i),l.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),l.send(u)}))},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CordovaPopupWindow=void 0;var n=function(){function e(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:o.MetadataService,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.UserInfoService,c=arguments.length>3&&void 0!==arguments[3]?arguments[3]:l.JoseUtil,u=arguments.length>4&&void 0!==arguments[4]?arguments[4]:a.TokenClient;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw i.Log.error("ResponseValidator.ctor: No settings passed to ResponseValidator"),new Error("settings");this._settings=t,this._metadataService=new r(this._settings),this._userInfoService=new n(this._settings),this._joseUtil=c,this._tokenClient=new u(this._settings)}return e.prototype.validateSigninResponse=function(e,t){var r=this;return i.Log.debug("ResponseValidator.validateSigninResponse"),this._processSigninParams(e,t).then((function(t){return i.Log.debug("ResponseValidator.validateSigninResponse: state processed"),r._validateTokens(e,t).then((function(t){return i.Log.debug("ResponseValidator.validateSigninResponse: tokens validated"),r._processClaims(e,t).then((function(e){return i.Log.debug("ResponseValidator.validateSigninResponse: claims processed"),e}))}))}))},e.prototype.validateSignoutResponse=function(e,t){return e.id!==t.state?(i.Log.error("ResponseValidator.validateSignoutResponse: State does not match"),Promise.reject(new Error("State does not match"))):(i.Log.debug("ResponseValidator.validateSignoutResponse: state validated"),t.state=e.data,t.error?(i.Log.warn("ResponseValidator.validateSignoutResponse: Response was error",t.error),Promise.reject(new c.ErrorResponse(t))):Promise.resolve(t))},e.prototype._processSigninParams=function(e,t){if(e.id!==t.state)return i.Log.error("ResponseValidator._processSigninParams: State does not match"),Promise.reject(new Error("State does not match"));if(!e.client_id)return i.Log.error("ResponseValidator._processSigninParams: No client_id on state"),Promise.reject(new Error("No client_id on state"));if(!e.authority)return i.Log.error("ResponseValidator._processSigninParams: No authority on state"),Promise.reject(new Error("No authority on state"));if(this._settings.authority){if(this._settings.authority&&this._settings.authority!==e.authority)return i.Log.error("ResponseValidator._processSigninParams: authority mismatch on settings vs. signin state"),Promise.reject(new Error("authority mismatch on settings vs. signin state"))}else this._settings.authority=e.authority;if(this._settings.client_id){if(this._settings.client_id&&this._settings.client_id!==e.client_id)return i.Log.error("ResponseValidator._processSigninParams: client_id mismatch on settings vs. signin state"),Promise.reject(new Error("client_id mismatch on settings vs. signin state"))}else this._settings.client_id=e.client_id;return i.Log.debug("ResponseValidator._processSigninParams: state validated"),t.state=e.data,t.error?(i.Log.warn("ResponseValidator._processSigninParams: Response was error",t.error),Promise.reject(new c.ErrorResponse(t))):e.nonce&&!t.id_token?(i.Log.error("ResponseValidator._processSigninParams: Expecting id_token in response"),Promise.reject(new Error("No id_token in response"))):!e.nonce&&t.id_token?(i.Log.error("ResponseValidator._processSigninParams: Not expecting id_token in response"),Promise.reject(new Error("Unexpected id_token in response"))):e.code_verifier&&!t.code?(i.Log.error("ResponseValidator._processSigninParams: Expecting code in response"),Promise.reject(new Error("No code in response"))):!e.code_verifier&&t.code?(i.Log.error("ResponseValidator._processSigninParams: Not expecting code in response"),Promise.reject(new Error("Unexpected code in response"))):(t.scope||(t.scope=e.scope),Promise.resolve(t))},e.prototype._processClaims=function(e,t){var r=this;if(t.isOpenIdConnect){if(i.Log.debug("ResponseValidator._processClaims: response is OIDC, processing claims"),t.profile=this._filterProtocolClaims(t.profile),!0!==e.skipUserInfo&&this._settings.loadUserInfo&&t.access_token)return i.Log.debug("ResponseValidator._processClaims: loading user info"),this._userInfoService.getClaims(t.access_token).then((function(e){return i.Log.debug("ResponseValidator._processClaims: user info claims received from user info endpoint"),e.sub!==t.profile.sub?(i.Log.error("ResponseValidator._processClaims: sub from user info endpoint does not match sub in id_token"),Promise.reject(new Error("sub from user info endpoint does not match sub in id_token"))):(t.profile=r._mergeClaims(t.profile,e),i.Log.debug("ResponseValidator._processClaims: user info claims received, updated profile:",t.profile),t)}));i.Log.debug("ResponseValidator._processClaims: not loading user info")}else i.Log.debug("ResponseValidator._processClaims: response is not OIDC, not processing claims");return Promise.resolve(t)},e.prototype._mergeClaims=function(e,t){var r=Object.assign({},e);for(var i in t){var o=t[i];Array.isArray(o)||(o=[o]);for(var s=0;s1)return i.Log.error("ResponseValidator._validateIdToken: No kid found in id_token and more than one key found in metadata"),Promise.reject(new Error("No kid found in id_token and more than one key found in metadata"));o=r[0]}return Promise.resolve(o)}))},e.prototype._getSigningKeyForJwtWithSingleRetry=function(e){var t=this;return this._getSigningKeyForJwt(e).then((function(r){return r?Promise.resolve(r):(t._metadataService.resetSigningKeys(),t._getSigningKeyForJwt(e))}))},e.prototype._validateIdToken=function(e,t){var r=this;if(!e.nonce)return i.Log.error("ResponseValidator._validateIdToken: No nonce on state"),Promise.reject(new Error("No nonce on state"));var n=this._joseUtil.parseJwt(t.id_token);return n&&n.header&&n.payload?e.nonce!==n.payload.nonce?(i.Log.error("ResponseValidator._validateIdToken: Invalid nonce in id_token"),Promise.reject(new Error("Invalid nonce in id_token"))):this._metadataService.getIssuer().then((function(o){return i.Log.debug("ResponseValidator._validateIdToken: Received issuer"),r._getSigningKeyForJwtWithSingleRetry(n).then((function(s){if(!s)return i.Log.error("ResponseValidator._validateIdToken: No key matching kid or alg found in signing keys"),Promise.reject(new Error("No key matching kid or alg found in signing keys"));var a=e.client_id,c=r._settings.clockSkew;return i.Log.debug("ResponseValidator._validateIdToken: Validaing JWT; using clock skew (in seconds) of: ",c),r._joseUtil.validateJwt(t.id_token,s,o,a,c).then((function(){return i.Log.debug("ResponseValidator._validateIdToken: JWT validation successful"),n.payload.sub?(t.profile=n.payload,t):(i.Log.error("ResponseValidator._validateIdToken: No sub present in id_token"),Promise.reject(new Error("No sub present in id_token")))}))}))})):(i.Log.error("ResponseValidator._validateIdToken: Failed to parse id_token",n),Promise.reject(new Error("Failed to parse id_token")))},e.prototype._filterByAlg=function(e,t){var r=null;if(t.startsWith("RS"))r="RSA";else if(t.startsWith("PS"))r="PS";else{if(!t.startsWith("ES"))return i.Log.debug("ResponseValidator._filterByAlg: alg not supported: ",t),[];r="EC"}return i.Log.debug("ResponseValidator._filterByAlg: Looking for keys that match kty: ",r),e=e.filter((function(e){return e.kty===r})),i.Log.debug("ResponseValidator._filterByAlg: Number of keys that match kty: ",r,e.length),e},e.prototype._validateAccessToken=function(e){if(!e.profile)return i.Log.error("ResponseValidator._validateAccessToken: No profile loaded from id_token"),Promise.reject(new Error("No profile loaded from id_token"));if(!e.profile.at_hash)return i.Log.error("ResponseValidator._validateAccessToken: No at_hash in id_token"),Promise.reject(new Error("No at_hash in id_token"));if(!e.id_token)return i.Log.error("ResponseValidator._validateAccessToken: No id_token"),Promise.reject(new Error("No id_token"));var t=this._joseUtil.parseJwt(e.id_token);if(!t||!t.header)return i.Log.error("ResponseValidator._validateAccessToken: Failed to parse id_token",t),Promise.reject(new Error("Failed to parse id_token"));var r=t.header.alg;if(!r||5!==r.length)return i.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",r),Promise.reject(new Error("Unsupported alg: "+r));var n=r.substr(2,3);if(!n)return i.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",r,n),Promise.reject(new Error("Unsupported alg: "+r));if(256!==(n=parseInt(n))&&384!==n&&512!==n)return i.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",r,n),Promise.reject(new Error("Unsupported alg: "+r));var o="sha"+n,s=this._joseUtil.hashString(e.access_token,o);if(!s)return i.Log.error("ResponseValidator._validateAccessToken: access_token hash failed:",o),Promise.reject(new Error("Failed to validate at_hash"));var a=s.substr(0,s.length/2),c=this._joseUtil.hexToBase64Url(a);return c!==e.profile.at_hash?(i.Log.error("ResponseValidator._validateAccessToken: Failed to validate at_hash",c,e.profile.at_hash),Promise.reject(new Error("Failed to validate at_hash"))):(i.Log.debug("ResponseValidator._validateAccessToken: success"),Promise.resolve(e))},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserInfoService=void 0;var n=r(7),i=r(2),o=r(0),s=r(4);t.UserInfoService=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.JsonService,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.MetadataService,c=arguments.length>3&&void 0!==arguments[3]?arguments[3]:s.JoseUtil;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw o.Log.error("UserInfoService.ctor: No settings passed"),new Error("settings");this._settings=t,this._jsonService=new r(void 0,void 0,this._getClaimsFromJwt.bind(this)),this._metadataService=new a(this._settings),this._joseUtil=c}return e.prototype.getClaims=function(e){var t=this;return e?this._metadataService.getUserInfoEndpoint().then((function(r){return o.Log.debug("UserInfoService.getClaims: received userinfo url",r),t._jsonService.getJson(r,e).then((function(e){return o.Log.debug("UserInfoService.getClaims: claims received",e),e}))})):(o.Log.error("UserInfoService.getClaims: No token passed"),Promise.reject(new Error("A token is required")))},e.prototype._getClaimsFromJwt=function e(t){var r=this;try{var n=this._joseUtil.parseJwt(t.responseText);if(!n||!n.header||!n.payload)return o.Log.error("UserInfoService._getClaimsFromJwt: Failed to parse JWT",n),Promise.reject(new Error("Failed to parse id_token"));var i=n.header.kid,s=void 0;switch(this._settings.userInfoJwtIssuer){case"OP":s=this._metadataService.getIssuer();break;case"ANY":s=Promise.resolve(n.payload.iss);break;default:s=Promise.resolve(this._settings.userInfoJwtIssuer)}return s.then((function(e){return o.Log.debug("UserInfoService._getClaimsFromJwt: Received issuer:"+e),r._metadataService.getSigningKeys().then((function(s){if(!s)return o.Log.error("UserInfoService._getClaimsFromJwt: No signing keys from metadata"),Promise.reject(new Error("No signing keys from metadata"));o.Log.debug("UserInfoService._getClaimsFromJwt: Received signing keys");var a=void 0;if(i)a=s.filter((function(e){return e.kid===i}))[0];else{if((s=r._filterByAlg(s,n.header.alg)).length>1)return o.Log.error("UserInfoService._getClaimsFromJwt: No kid found in id_token and more than one key found in metadata"),Promise.reject(new Error("No kid found in id_token and more than one key found in metadata"));a=s[0]}if(!a)return o.Log.error("UserInfoService._getClaimsFromJwt: No key matching kid or alg found in signing keys"),Promise.reject(new Error("No key matching kid or alg found in signing keys"));var c=r._settings.client_id,l=r._settings.clockSkew;return o.Log.debug("UserInfoService._getClaimsFromJwt: Validaing JWT; using clock skew (in seconds) of: ",l),r._joseUtil.validateJwt(t.responseText,a,e,c,l,void 0,!0).then((function(){return o.Log.debug("UserInfoService._getClaimsFromJwt: JWT validation successful"),n.payload}))}))}))}catch(e){return o.Log.error("UserInfoService._getClaimsFromJwt: Error parsing JWT response",e.message),void reject(e)}},e.prototype._filterByAlg=function(e,t){var r=null;if(t.startsWith("RS"))r="RSA";else if(t.startsWith("PS"))r="PS";else{if(!t.startsWith("ES"))return o.Log.debug("UserInfoService._filterByAlg: alg not supported: ",t),[];r="EC"}return o.Log.debug("UserInfoService._filterByAlg: Looking for keys that match kty: ",r),e=e.filter((function(e){return e.kty===r})),o.Log.debug("UserInfoService._filterByAlg: Number of keys that match kty: ",r,e.length),e},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AllowedSigningAlgs=t.b64tohex=t.hextob64u=t.crypto=t.X509=t.KeyUtil=t.jws=void 0;var n=r(27);t.jws=n.jws,t.KeyUtil=n.KEYUTIL,t.X509=n.X509,t.crypto=n.crypto,t.hextob64u=n.hextob64u,t.b64tohex=n.b64tohex,t.AllowedSigningAlgs=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"]},function(e,t,r){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0});var r,n,i,o,s,a,c,l,u,d,h,f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},p={userAgent:!1},g={},y=y||(r=Math,i=(n={}).lib={},o=i.Base=function(){function e(){}return{extend:function(t){e.prototype=this;var r=new e;return t&&r.mixIn(t),r.hasOwnProperty("init")||(r.init=function(){r.$super.init.apply(this,arguments)}),r.init.prototype=r,r.$super=this,r},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),s=i.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,i=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[n+o>>>2]|=s<<24-(n+o)%4*8}else for(o=0;o>>2]=r[o>>>2];return this.sigBytes+=i,this},clamp:function(){var e=this.words,t=this.sigBytes;e[t>>>2]&=4294967295<<32-t%4*8,e.length=r.ceil(t/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],n=0;n>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new s.init(r,t/2)}},l=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new s.init(r,t)}},u=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(l.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return l.parse(unescape(encodeURIComponent(e)))}},d=i.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=u.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(e){var t=this._data,n=t.words,i=t.sigBytes,o=this.blockSize,a=i/(4*o),c=(a=e?r.ceil(a):r.max((0|a)-this._minBufferSize,0))*o,l=r.min(4*c,i);if(c){for(var u=0;u>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,s=0;4>s&&i+.75*s>>6*(3-s)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var r=e.length,n=this._map;(i=n.charAt(64))&&-1!=(i=e.indexOf(i))&&(r=i);for(var i=[],o=0,s=0;s>>6-s%4*2;i[o>>>2]|=(a|c)<<24-o%4*8,o++}return t.create(i,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),function(e){for(var t=y,r=(i=t.lib).WordArray,n=i.Hasher,i=t.algo,o=[],s=[],a=function(e){return 4294967296*(e-(0|e))|0},c=2,l=0;64>l;){var u;e:{u=c;for(var d=e.sqrt(u),h=2;h<=d;h++)if(!(u%h)){u=!1;break e}u=!0}u&&(8>l&&(o[l]=a(e.pow(c,.5))),s[l]=a(e.pow(c,1/3)),l++),c++}var f=[];i=i.SHA256=n.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],i=r[1],o=r[2],a=r[3],c=r[4],l=r[5],u=r[6],d=r[7],h=0;64>h;h++){if(16>h)f[h]=0|e[t+h];else{var p=f[h-15],g=f[h-2];f[h]=((p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3)+f[h-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+f[h-16]}p=d+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&l^~c&u)+s[h]+f[h],g=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&i^n&o^i&o),d=u,u=l,l=c,c=a+p|0,a=o,o=i,i=n,n=p+g|0}r[0]=r[0]+n|0,r[1]=r[1]+i|0,r[2]=r[2]+o|0,r[3]=r[3]+a|0,r[4]=r[4]+c|0,r[5]=r[5]+l|0,r[6]=r[6]+u|0,r[7]=r[7]+d|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;return r[i>>>5]|=128<<24-i%32,r[14+(i+64>>>9<<4)]=e.floor(n/4294967296),r[15+(i+64>>>9<<4)]=n,t.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}}),t.SHA256=n._createHelper(i),t.HmacSHA256=n._createHmacHelper(i)}(Math),function(){function e(){return n.create.apply(n,arguments)}for(var t=y,r=t.lib.Hasher,n=(o=t.x64).Word,i=o.WordArray,o=t.algo,s=[e(1116352408,3609767458),e(1899447441,602891725),e(3049323471,3964484399),e(3921009573,2173295548),e(961987163,4081628472),e(1508970993,3053834265),e(2453635748,2937671579),e(2870763221,3664609560),e(3624381080,2734883394),e(310598401,1164996542),e(607225278,1323610764),e(1426881987,3590304994),e(1925078388,4068182383),e(2162078206,991336113),e(2614888103,633803317),e(3248222580,3479774868),e(3835390401,2666613458),e(4022224774,944711139),e(264347078,2341262773),e(604807628,2007800933),e(770255983,1495990901),e(1249150122,1856431235),e(1555081692,3175218132),e(1996064986,2198950837),e(2554220882,3999719339),e(2821834349,766784016),e(2952996808,2566594879),e(3210313671,3203337956),e(3336571891,1034457026),e(3584528711,2466948901),e(113926993,3758326383),e(338241895,168717936),e(666307205,1188179964),e(773529912,1546045734),e(1294757372,1522805485),e(1396182291,2643833823),e(1695183700,2343527390),e(1986661051,1014477480),e(2177026350,1206759142),e(2456956037,344077627),e(2730485921,1290863460),e(2820302411,3158454273),e(3259730800,3505952657),e(3345764771,106217008),e(3516065817,3606008344),e(3600352804,1432725776),e(4094571909,1467031594),e(275423344,851169720),e(430227734,3100823752),e(506948616,1363258195),e(659060556,3750685593),e(883997877,3785050280),e(958139571,3318307427),e(1322822218,3812723403),e(1537002063,2003034995),e(1747873779,3602036899),e(1955562222,1575990012),e(2024104815,1125592928),e(2227730452,2716904306),e(2361852424,442776044),e(2428436474,593698344),e(2756734187,3733110249),e(3204031479,2999351573),e(3329325298,3815920427),e(3391569614,3928383900),e(3515267271,566280711),e(3940187606,3454069534),e(4118630271,4000239992),e(116418474,1914138554),e(174292421,2731055270),e(289380356,3203993006),e(460393269,320620315),e(685471733,587496836),e(852142971,1086792851),e(1017036298,365543100),e(1126000580,2618297676),e(1288033470,3409855158),e(1501505948,4234509866),e(1607167915,987167468),e(1816402316,1246189591)],a=[],c=0;80>c;c++)a[c]=e();o=o.SHA512=r.extend({_doReset:function(){this._hash=new i.init([new n.init(1779033703,4089235720),new n.init(3144134277,2227873595),new n.init(1013904242,4271175723),new n.init(2773480762,1595750129),new n.init(1359893119,2917565137),new n.init(2600822924,725511199),new n.init(528734635,4215389547),new n.init(1541459225,327033209)])},_doProcessBlock:function(e,t){for(var r=(d=this._hash.words)[0],n=d[1],i=d[2],o=d[3],c=d[4],l=d[5],u=d[6],d=d[7],h=r.high,f=r.low,p=n.high,g=n.low,y=i.high,m=i.low,v=o.high,b=o.low,w=c.high,_=c.low,S=l.high,E=l.low,A=u.high,R=u.low,I=d.high,T=d.low,x=h,P=f,C=p,k=g,O=y,F=m,N=v,D=b,L=w,U=_,j=S,M=E,B=A,H=R,W=I,$=T,V=0;80>V;V++){var K=a[V];if(16>V)var J=K.high=0|e[t+2*V],G=K.low=0|e[t+2*V+1];else{J=((G=(J=a[V-15]).high)>>>1|(q=J.low)<<31)^(G>>>8|q<<24)^G>>>7;var q=(q>>>1|G<<31)^(q>>>8|G<<24)^(q>>>7|G<<25),z=((G=(z=a[V-2]).high)>>>19|(Y=z.low)<<13)^(G<<3|Y>>>29)^G>>>6,Y=(Y>>>19|G<<13)^(Y<<3|G>>>29)^(Y>>>6|G<<26),Q=(G=a[V-7]).high,X=(Z=a[V-16]).high,Z=Z.low;J=(J=(J=J+Q+((G=q+G.low)>>>0>>0?1:0))+z+((G+=Y)>>>0>>0?1:0))+X+((G+=Z)>>>0>>0?1:0),K.high=J,K.low=G}Q=L&j^~L&B,Z=U&M^~U&H,K=x&C^x&O^C&O;var ee=P&k^P&F^k&F,te=(q=(x>>>28|P<<4)^(x<<30|P>>>2)^(x<<25|P>>>7),z=(P>>>28|x<<4)^(P<<30|x>>>2)^(P<<25|x>>>7),(Y=s[V]).high),re=Y.low;X=W+((L>>>14|U<<18)^(L>>>18|U<<14)^(L<<23|U>>>9))+((Y=$+((U>>>14|L<<18)^(U>>>18|L<<14)^(U<<23|L>>>9)))>>>0<$>>>0?1:0),W=B,$=H,B=j,H=M,j=L,M=U,L=N+(X=(X=(X=X+Q+((Y+=Z)>>>0>>0?1:0))+te+((Y+=re)>>>0>>0?1:0))+J+((Y+=G)>>>0>>0?1:0))+((U=D+Y|0)>>>0>>0?1:0)|0,N=O,D=F,O=C,F=k,C=x,k=P,x=X+(K=q+K+((G=z+ee)>>>0>>0?1:0))+((P=Y+G|0)>>>0>>0?1:0)|0}f=r.low=f+P,r.high=h+x+(f>>>0

>>0?1:0),g=n.low=g+k,n.high=p+C+(g>>>0>>0?1:0),m=i.low=m+F,i.high=y+O+(m>>>0>>0?1:0),b=o.low=b+D,o.high=v+N+(b>>>0>>0?1:0),_=c.low=_+U,c.high=w+L+(_>>>0>>0?1:0),E=l.low=E+M,l.high=S+j+(E>>>0>>0?1:0),R=u.low=R+H,u.high=A+B+(R>>>0>>0?1:0),T=d.low=T+$,d.high=I+W+(T>>>0<$>>>0?1:0)},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[30+(n+128>>>10<<5)]=Math.floor(r/4294967296),t[31+(n+128>>>10<<5)]=r,e.sigBytes=4*t.length,this._process(),this._hash.toX32()},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32}),t.SHA512=r._createHelper(o),t.HmacSHA512=r._createHmacHelper(o)}(),function(){var e=y,t=(i=e.x64).Word,r=i.WordArray,n=(i=e.algo).SHA512,i=i.SHA384=n.extend({_doReset:function(){this._hash=new r.init([new t.init(3418070365,3238371032),new t.init(1654270250,914150663),new t.init(2438529370,812702999),new t.init(355462360,4144912697),new t.init(1731405415,4290775857),new t.init(2394180231,1750603025),new t.init(3675008525,1694076839),new t.init(1203062813,3204075428)])},_doFinalize:function(){var e=n._doFinalize.call(this);return e.sigBytes-=16,e}});e.SHA384=n._createHelper(i),e.HmacSHA384=n._createHmacHelper(i)}();var m,v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function b(e){var t,r,n="";for(t=0;t+3<=e.length;t+=3)r=parseInt(e.substring(t,t+3),16),n+=v.charAt(r>>6)+v.charAt(63&r);for(t+1==e.length?(r=parseInt(e.substring(t,t+1),16),n+=v.charAt(r<<2)):t+2==e.length&&(r=parseInt(e.substring(t,t+2),16),n+=v.charAt(r>>2)+v.charAt((3&r)<<4));(3&n.length)>0;)n+="=";return n}function w(e){var t,r,n,i="",o=0;for(t=0;t>2),r=3&n,o=1):1==o?(i+=T(r<<2|n>>4),r=15&n,o=2):2==o?(i+=T(r),i+=T(n>>2),r=3&n,o=3):(i+=T(r<<2|n>>4),i+=T(15&n),o=0));return 1==o&&(i+=T(r<<2)),i}function _(e){var t,r=w(e),n=new Array;for(t=0;2*t>15;--o>=0;){var c=32767&this[e],l=this[e++]>>15,u=a*c+l*s;i=((c=s*c+((32767&u)<<15)+r[n]+(1073741823&i))>>>30)+(u>>>15)+a*l+(i>>>30),r[n++]=1073741823&c}return i},m=30):"Netscape"!=p.appName?(S.prototype.am=function(e,t,r,n,i,o){for(;--o>=0;){var s=t*this[e++]+r[n]+i;i=Math.floor(s/67108864),r[n++]=67108863&s}return i},m=26):(S.prototype.am=function(e,t,r,n,i,o){for(var s=16383&t,a=t>>14;--o>=0;){var c=16383&this[e],l=this[e++]>>14,u=a*c+l*s;i=((c=s*c+((16383&u)<<14)+r[n]+i)>>28)+(u>>14)+a*l,r[n++]=268435455&c}return i},m=28),S.prototype.DB=m,S.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function k(e){this.m=e}function O(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),!(255&e)&&(e>>=8,t+=8),!(15&e)&&(e>>=4,t+=4),!(3&e)&&(e>>=2,t+=2),!(1&e)&&++t,t}function j(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function M(){}function B(e){return e}function H(e){this.r2=E(),this.q3=E(),S.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}k.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},k.prototype.revert=function(e){return e},k.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},k.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},k.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},O.prototype.convert=function(e){var t=E();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(S.ZERO)>0&&this.m.subTo(t,t),t},O.prototype.revert=function(e){var t=E();return e.copyTo(t),this.reduce(t),t},O.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(e[r=t+this.m.t]+=this.m.am(0,n,e,t,0,this.m.t);e[r]>=e.DV;)e[r]-=e.DV,e[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},O.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},O.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},S.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},S.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},S.prototype.fromString=function(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,i=!1,o=0;--n>=0;){var s=8==r?255&e[n]:x(e,n);s<0?"-"==e.charAt(n)&&(i=!0):(i=!1,0==o?this[this.t++]=s:o+r>this.DB?(this[this.t-1]|=(s&(1<>this.DB-o):this[this.t-1]|=s<=this.DB&&(o-=this.DB))}8==r&&!!(128&e[0])&&(this.s=-1,o>0&&(this[this.t-1]|=(1<0&&this[this.t-1]==e;)--this.t},S.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t[r+e]=this[r];for(r=e-1;r>=0;--r)t[r]=0;t.t=this.t+e,t.s=this.s},S.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t[r+s+1]=this[r]>>i|a,a=(this[r]&o)<=0;--r)t[r]=0;t[s]=a,t.t=this.t+s+1,t.s=this.s,t.clamp()},S.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,i=this.DB-n,o=(1<>n;for(var s=r+1;s>n;n>0&&(t[this.t-r-1]|=(this.s&o)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t[r++]=this.DV+n:n>0&&(t[r++]=n),t.t=r,t.clamp()},S.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t[i]=0;for(i=0;i=0;)e[r]=0;for(r=0;r=t.DV&&(e[r+t.t]-=t.DV,e[r+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(r,t[r],e,2*r,0,1)),e.s=0,e.clamp()},S.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(c,o),i.lShiftTo(c,r)):(n.copyTo(o),i.copyTo(r));var l=o.t,u=o[l-1];if(0!=u){var d=u*(1<1?o[l-2]>>this.F2:0),h=this.FV/d,f=(1<=0&&(r[r.t++]=1,r.subTo(m,r)),S.ONE.dlShiftTo(l,m),m.subTo(o,o);o.t=0;){var v=r[--g]==u?this.DM:Math.floor(r[g]*h+(r[g-1]+p)*f);if((r[g]+=o.am(0,v,r,y,0,l))0&&r.rShiftTo(c,r),s<0&&S.ZERO.subTo(r,r)}}},S.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},S.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},S.prototype.exp=function(e,t){if(e>4294967295||e<1)return S.ONE;var r=E(),n=E(),i=t.convert(this),o=C(e)-1;for(i.copyTo(r);--o>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,i,r);else{var s=r;r=n,n=s}return t.revert(r)},S.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<0)for(a>a)>0&&(i=!0,o=T(r));s>=0;)a>(a+=this.DB-t)):(r=this[s]>>(a-=t)&n,a<=0&&(a+=this.DB,--s)),r>0&&(i=!0),i&&(o+=T(r));return i?o:"0"},S.prototype.negate=function(){var e=E();return S.ZERO.subTo(this,e),e},S.prototype.abs=function(){return this.s<0?this.negate():this},S.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this[r]-e[r]))return t;return 0},S.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+C(this[this.t-1]^this.s&this.DM)},S.prototype.mod=function(e){var t=E();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(S.ZERO)>0&&e.subTo(t,t),t},S.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new k(t):new O(t),this.exp(e,r)},S.ZERO=P(0),S.ONE=P(1),M.prototype.convert=B,M.prototype.revert=B,M.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},M.prototype.sqrTo=function(e,t){e.squareTo(t)},H.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=E();return e.copyTo(t),this.reduce(t),t},H.prototype.revert=function(e){return e},H.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},H.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},H.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var W,$,V,K=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],J=(1<<26)/K[K.length-1];function G(){this.i=0,this.j=0,this.S=new Array}function q(){!function(e){$[V++]^=255&e,$[V++]^=e>>8&255,$[V++]^=e>>16&255,$[V++]^=e>>24&255,V>=256&&(V-=256)}((new Date).getTime())}if(S.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},S.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=P(r),i=E(),o=E(),s="";for(this.divRemTo(n,i,o);i.signum()>0;)s=(r+o.intValue()).toString(e).substr(1)+s,i.divRemTo(n,i,o);return o.intValue().toString(e)+s},S.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,o=0,s=0,a=0;a=r&&(this.dMultiply(n),this.dAddOffset(s,0),o=0,s=0))}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(s,0)),i&&S.ZERO.subTo(this,this)},S.prototype.fromNumber=function(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(S.ONE.shiftLeft(e-1),N,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(S.ONE.shiftLeft(e-1),this);else{var n=new Array,i=7&e;n.length=1+(e>>3),t.nextBytes(n),i>0?n[0]&=(1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t[r++]=n:n<-1&&(t[r++]=this.DV+n),t.t=r,t.clamp()},S.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},S.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},S.prototype.multiplyLowerTo=function(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r[--i]=0;for(n=r.t-this.t;i=0;)r[n]=0;for(n=Math.max(t-this.t,0);n0)if(0==t)r=this[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this[n])%e;return r},S.prototype.millerRabin=function(e){var t=this.subtract(S.ONE),r=t.getLowestSetBit();if(r<=0)return!1;var n=t.shiftRight(r);(e=e+1>>1)>K.length&&(e=K.length);for(var i=E(),o=0;o>24},S.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},S.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},S.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<=0;)n<8?(r=(this[e]&(1<>(n+=this.DB-8)):(r=this[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),!!(128&r)&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t},S.prototype.equals=function(e){return 0==this.compareTo(e)},S.prototype.min=function(e){return this.compareTo(e)<0?this:e},S.prototype.max=function(e){return this.compareTo(e)>0?this:e},S.prototype.and=function(e){var t=E();return this.bitwiseTo(e,F,t),t},S.prototype.or=function(e){var t=E();return this.bitwiseTo(e,N,t),t},S.prototype.xor=function(e){var t=E();return this.bitwiseTo(e,D,t),t},S.prototype.andNot=function(e){var t=E();return this.bitwiseTo(e,L,t),t},S.prototype.not=function(){for(var e=E(),t=0;t=this.t?0!=this.s:!!(this[t]&1<1){var u=E();for(n.sqrTo(s[1],u);a<=l;)s[a]=E(),n.mulTo(u,s[a-2],s[a]),a+=2}var d,h,f=e.t-1,p=!0,g=E();for(i=C(e[f])-1;f>=0;){for(i>=c?d=e[f]>>i-c&l:(d=(e[f]&(1<0&&(d|=e[f-1]>>this.DB+i-c)),a=r;!(1&d);)d>>=1,--a;if((i-=a)<0&&(i+=this.DB,--f),p)s[d].copyTo(o),p=!1;else{for(;a>1;)n.sqrTo(o,g),n.sqrTo(g,o),a-=2;a>0?n.sqrTo(o,g):(h=o,o=g,g=h),n.mulTo(g,s[d],o)}for(;f>=0&&!(e[f]&1<=0?(r.subTo(n,r),t&&i.subTo(s,i),o.subTo(a,o)):(n.subTo(r,n),t&&s.subTo(i,s),a.subTo(o,a))}return 0!=n.compareTo(S.ONE)?S.ZERO:a.compareTo(e)>=0?a.subtract(e):a.signum()<0?(a.addTo(e,a),a.signum()<0?a.add(e):a):a},S.prototype.pow=function(e){return this.exp(e,new M)},S.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var i=t.getLowestSetBit(),o=r.getLowestSetBit();if(o<0)return t;for(i0&&(t.rShiftTo(o,t),r.rShiftTo(o,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return o>0&&r.lShiftTo(o,r),r},S.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r[0]<=K[K.length-1]){for(t=0;t>>8,$[V++]=255&z;V=0,q()}function Z(){if(null==W){for(q(),(W=new G).init($),V=0;V<$.length;++V)$[V]=0;V=0}return W.next()}function ee(){}function te(e,t){return new S(e,t)}function re(e,t,r){for(var n="",i=0;n.length>24,(16711680&i)>>16,(65280&i)>>8,255&i]))),i+=1;return n}function ne(){this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null}function ie(e,t){this.x=t,this.q=e}function oe(e,t,r,n){this.curve=e,this.x=t,this.y=r,this.z=null==n?S.ONE:n,this.zinv=null}function se(e,t,r){this.q=e,this.a=this.fromBigInteger(t),this.b=this.fromBigInteger(r),this.infinity=new oe(this,null,null)}ee.prototype.nextBytes=function(e){var t;for(t=0;t0&&t.length>0))throw"Invalid RSA public key";this.n=te(e,16),this.e=parseInt(t,16)}},ne.prototype.encrypt=function(e){var t=function(e,t){if(t=0&&t>0;){var i=e.charCodeAt(n--);i<128?r[--t]=i:i>127&&i<2048?(r[--t]=63&i|128,r[--t]=i>>6|192):(r[--t]=63&i|128,r[--t]=i>>6&63|128,r[--t]=i>>12|224)}r[--t]=0;for(var o=new ee,s=new Array;t>2;){for(s[0]=0;0==s[0];)o.nextBytes(s);r[--t]=s[0]}return r[--t]=2,r[--t]=0,new S(r)}(e,this.n.bitLength()+7>>3);if(null==t)return null;var r=this.doPublic(t);if(null==r)return null;var n=r.toString(16);return 1&n.length?"0"+n:n},ne.prototype.encryptOAEP=function(e,t,r){var n=function(e,t,r,n){var i=ce.crypto.MessageDigest,o=ce.crypto.Util,s=null;if(r||(r="sha1"),"string"==typeof r&&(s=i.getCanonicalAlgName(r),n=i.getHashLength(s),r=function(e){return Se(o.hashHex(Ee(e),s))}),e.length+2*n+2>t)throw"Message too long for RSA";var a,c="";for(a=0;a>3,t,r);if(null==n)return null;var i=this.doPublic(n);if(null==i)return null;var o=i.toString(16);return 1&o.length?"0"+o:o},ne.prototype.type="RSA",ie.prototype.equals=function(e){return e==this||this.q.equals(e.q)&&this.x.equals(e.x)},ie.prototype.toBigInteger=function(){return this.x},ie.prototype.negate=function(){return new ie(this.q,this.x.negate().mod(this.q))},ie.prototype.add=function(e){return new ie(this.q,this.x.add(e.toBigInteger()).mod(this.q))},ie.prototype.subtract=function(e){return new ie(this.q,this.x.subtract(e.toBigInteger()).mod(this.q))},ie.prototype.multiply=function(e){return new ie(this.q,this.x.multiply(e.toBigInteger()).mod(this.q))},ie.prototype.square=function(){return new ie(this.q,this.x.square().mod(this.q))},ie.prototype.divide=function(e){return new ie(this.q,this.x.multiply(e.toBigInteger().modInverse(this.q)).mod(this.q))},oe.prototype.getX=function(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))},oe.prototype.getY=function(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))},oe.prototype.equals=function(e){return e==this||(this.isInfinity()?e.isInfinity():e.isInfinity()?this.isInfinity():!!e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(S.ZERO)&&e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(S.ZERO))},oe.prototype.isInfinity=function(){return null==this.x&&null==this.y||this.z.equals(S.ZERO)&&!this.y.toBigInteger().equals(S.ZERO)},oe.prototype.negate=function(){return new oe(this.curve,this.x,this.y.negate(),this.z)},oe.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q),r=e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q);if(S.ZERO.equals(r))return S.ZERO.equals(t)?this.twice():this.curve.getInfinity();var n=new S("3"),i=this.x.toBigInteger(),o=this.y.toBigInteger(),s=(e.x.toBigInteger(),e.y.toBigInteger(),r.square()),a=s.multiply(r),c=i.multiply(s),l=t.square().multiply(this.z),u=l.subtract(c.shiftLeft(1)).multiply(e.z).subtract(a).multiply(r).mod(this.curve.q),d=c.multiply(n).multiply(t).subtract(o.multiply(a)).subtract(l.multiply(t)).multiply(e.z).add(t.multiply(a)).mod(this.curve.q),h=a.multiply(this.z).multiply(e.z).mod(this.curve.q);return new oe(this.curve,this.curve.fromBigInteger(u),this.curve.fromBigInteger(d),h)},oe.prototype.twice=function(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=new S("3"),t=this.x.toBigInteger(),r=this.y.toBigInteger(),n=r.multiply(this.z),i=n.multiply(r).mod(this.curve.q),o=this.curve.a.toBigInteger(),s=t.square().multiply(e);S.ZERO.equals(o)||(s=s.add(this.z.square().multiply(o)));var a=(s=s.mod(this.curve.q)).square().subtract(t.shiftLeft(3).multiply(i)).shiftLeft(1).multiply(n).mod(this.curve.q),c=s.multiply(e).multiply(t).subtract(i.shiftLeft(1)).shiftLeft(2).multiply(i).subtract(s.square().multiply(s)).mod(this.curve.q),l=n.square().multiply(n).shiftLeft(3).mod(this.curve.q);return new oe(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(c),l)},oe.prototype.multiply=function(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();var t,r=e,n=r.multiply(new S("3")),i=this.negate(),o=this,s=this.curve.q.subtract(e),a=s.multiply(new S("3")),c=new oe(this.curve,this.x,this.y),l=c.negate();for(t=n.bitLength()-2;t>0;--t){o=o.twice();var u=n.testBit(t);u!=r.testBit(t)&&(o=o.add(u?this:i))}for(t=a.bitLength()-2;t>0;--t){c=c.twice();var d=a.testBit(t);d!=s.testBit(t)&&(c=c.add(d?c:l))}return o},oe.prototype.multiplyTwo=function(e,t,r){var n;n=e.bitLength()>r.bitLength()?e.bitLength()-1:r.bitLength()-1;for(var i=this.curve.getInfinity(),o=this.add(t);n>=0;)i=i.twice(),e.testBit(n)?i=r.testBit(n)?i.add(o):i.add(this):r.testBit(n)&&(i=i.add(t)),--n;return i},se.prototype.getQ=function(){return this.q},se.prototype.getA=function(){return this.a},se.prototype.getB=function(){return this.b},se.prototype.equals=function(e){return e==this||this.q.equals(e.q)&&this.a.equals(e.a)&&this.b.equals(e.b)},se.prototype.getInfinity=function(){return this.infinity},se.prototype.fromBigInteger=function(e){return new ie(this.q,e)},se.prototype.decodePointHex=function(e){switch(parseInt(e.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:default:return null;case 4:case 6:case 7:var t=(e.length-2)/2,r=e.substr(2,t),n=e.substr(t+2,t);return new oe(this,this.fromBigInteger(new S(r,16)),this.fromBigInteger(new S(n,16)))}},ie.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)},oe.prototype.getEncoded=function(e){var t=function(e,t){var r=e.toByteArrayUnsigned();if(tr.length;)r.unshift(0);return r},r=this.getX().toBigInteger(),n=this.getY().toBigInteger(),i=t(r,32);return e?n.isEven()?i.unshift(2):i.unshift(3):(i.unshift(4),i=i.concat(t(n,32))),i},oe.decodeFrom=function(e,t){t[0];var r=t.length-1,n=t.slice(1,1+r/2),i=t.slice(1+r/2,1+r);n.unshift(0),i.unshift(0);var o=new S(n),s=new S(i);return new oe(e,e.fromBigInteger(o),e.fromBigInteger(s))},oe.decodeFromHex=function(e,t){t.substr(0,2);var r=t.length-2,n=t.substr(2,r/2),i=t.substr(2+r/2,r/2),o=new S(n,16),s=new S(i,16);return new oe(e,e.fromBigInteger(o),e.fromBigInteger(s))},oe.prototype.add2D=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;if(this.x.equals(e.x))return this.y.equals(e.y)?this.twice():this.curve.getInfinity();var t=e.x.subtract(this.x),r=e.y.subtract(this.y).divide(t),n=r.square().subtract(this.x).subtract(e.x),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new oe(this.curve,n,i)},oe.prototype.twice2D=function(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=this.curve.fromBigInteger(S.valueOf(2)),t=this.curve.fromBigInteger(S.valueOf(3)),r=this.x.square().multiply(t).add(this.curve.a).divide(this.y.multiply(e)),n=r.square().subtract(this.x.multiply(e)),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new oe(this.curve,n,i)},oe.prototype.multiply2D=function(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();var t,r=e,n=r.multiply(new S("3")),i=this.negate(),o=this;for(t=n.bitLength()-2;t>0;--t){o=o.twice();var s=n.testBit(t);s!=r.testBit(t)&&(o=o.add2D(s?this:i))}return o},oe.prototype.isOnCurve=function(){var e=this.getX().toBigInteger(),t=this.getY().toBigInteger(),r=this.curve.getA().toBigInteger(),n=this.curve.getB().toBigInteger(),i=this.curve.getQ(),o=t.multiply(t).mod(i),s=e.multiply(e).multiply(e).add(r.multiply(e)).add(n).mod(i);return o.equals(s)},oe.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"},oe.prototype.validate=function(){var e=this.curve.getQ();if(this.isInfinity())throw new Error("Point is at infinity.");var t=this.getX().toBigInteger(),r=this.getY().toBigInteger();if(t.compareTo(S.ONE)<0||t.compareTo(e.subtract(S.ONE))>0)throw new Error("x coordinate out of bounds");if(r.compareTo(S.ONE)<0||r.compareTo(e.subtract(S.ONE))>0)throw new Error("y coordinate out of bounds");if(!this.isOnCurve())throw new Error("Point is not on the curve.");if(this.multiply(e).isInfinity())throw new Error("Point is not a scalar multiple of G.");return!0};var ae=function(){var e=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]|(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)|(?:"(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))*"))',"g"),t=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),r={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};function n(e,t,n){return t?r[t]:String.fromCharCode(parseInt(n,16))}var i=new String(""),o=Object.hasOwnProperty;return function(r,s){var a,c,l=r.match(e),u=l[0],d=!1;"{"===u?a={}:"["===u?a=[]:(a=[],d=!0);for(var h=[a],p=1-d,g=l.length;p=0;)delete n[i[l]]}return s.call(t,r,n)}({"":a},"")),a}}();void 0!==ce&&ce||(t.KJUR=ce={}),void 0!==ce.asn1&&ce.asn1||(ce.asn1={}),ce.asn1.ASN1Util=new function(){this.integerToByteHex=function(e){var t=e.toString(16);return t.length%2==1&&(t="0"+t),t},this.bigIntToMinTwosComplementsHex=function(e){var t=e.toString(16);if("-"!=t.substr(0,1))t.length%2==1?t="0"+t:t.match(/^[0-7]/)||(t="00"+t);else{var r=t.substr(1).length;r%2==1?r+=1:t.match(/^[0-7]/)||(r+=2);for(var n="",i=0;i15)throw"ASN.1 length too long to represent by 8x: n = "+e.toString(16);return(128+r).toString(16)+t},this.getEncodedHex=function(){return(null==this.hTLV||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getValueHex=function(){return this.getEncodedHex(),this.hV},this.getFreshValueHex=function(){return""},this.setByParam=function(e){this.params=e},null!=e&&null!=e.tlv&&(this.hTLV=e.tlv,this.isModified=!1)},ce.asn1.DERAbstractString=function(e){ce.asn1.DERAbstractString.superclass.constructor.call(this),this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=we(this.s).toLowerCase()},this.setStringHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e?this.setString(e):void 0!==e.str?this.setString(e.str):void 0!==e.hex&&this.setStringHex(e.hex))},He(ce.asn1.DERAbstractString,ce.asn1.ASN1Object),ce.asn1.DERAbstractTime=function(e){ce.asn1.DERAbstractTime.superclass.constructor.call(this),this.localDateToUTC=function(e){var t=e.getTime()+6e4*e.getTimezoneOffset();return new Date(t)},this.formatDate=function(e,t,r){var n=this.zeroPadding,i=this.localDateToUTC(e),o=String(i.getFullYear());"utc"==t&&(o=o.substr(2,2));var s=o+n(String(i.getMonth()+1),2)+n(String(i.getDate()),2)+n(String(i.getHours()),2)+n(String(i.getMinutes()),2)+n(String(i.getSeconds()),2);if(!0===r){var a=i.getMilliseconds();if(0!=a){var c=n(String(a),3);s=s+"."+(c=c.replace(/[0]+$/,""))}}return s+"Z"},this.zeroPadding=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=ge(e)},this.setByDateValue=function(e,t,r,n,i,o){var s=new Date(Date.UTC(e,t-1,r,n,i,o,0));this.setByDate(s)},this.getFreshValueHex=function(){return this.hV}},He(ce.asn1.DERAbstractTime,ce.asn1.ASN1Object),ce.asn1.DERAbstractStructured=function(e){ce.asn1.DERAbstractString.superclass.constructor.call(this),this.setByASN1ObjectArray=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array=e},this.appendASN1Object=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array.push(e)},this.asn1Array=new Array,void 0!==e&&void 0!==e.array&&(this.asn1Array=e.array)},He(ce.asn1.DERAbstractStructured,ce.asn1.ASN1Object),ce.asn1.DERBoolean=function(e){ce.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=0==e?"010100":"0101ff"},He(ce.asn1.DERBoolean,ce.asn1.ASN1Object),ce.asn1.DERInteger=function(e){ce.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=ce.asn1.ASN1Util.bigIntToMinTwosComplementsHex(e)},this.setByInteger=function(e){var t=new S(String(e),10);this.setByBigInteger(t)},this.setValueHex=function(e){this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&(void 0!==e.bigint?this.setByBigInteger(e.bigint):void 0!==e.int?this.setByInteger(e.int):"number"==typeof e?this.setByInteger(e):void 0!==e.hex&&this.setValueHex(e.hex))},He(ce.asn1.DERInteger,ce.asn1.ASN1Object),ce.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=ce.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.getEncodedHex()}ce.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(e){this.hTLV=null,this.isModified=!0,this.hV=e},this.setUnusedBitsAndHexValue=function(e,t){if(e<0||7i.length&&(i=n[r]);return(e=e.replace(i,"::")).slice(1,-1)}function De(e){var t="malformed hex value";if(!e.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/))throw t;if(8!=e.length)return 32==e.length?Ne(e):e;try{return parseInt(e.substr(0,2),16)+"."+parseInt(e.substr(2,2),16)+"."+parseInt(e.substr(4,2),16)+"."+parseInt(e.substr(6,2),16)}catch(e){throw t}}function Le(e){return e.match(/.{4}/g).map((function(e){var t=parseInt(e.substr(0,2),16),r=parseInt(e.substr(2),16);if(0==t&r<128)return String.fromCharCode(r);if(t<8){var n=128|63&r;return _e((192|(7&t)<<3|(192&r)>>6).toString(16)+n.toString(16))}n=128|(15&t)<<2|(192&r)>>6;var i=128|63&r;return _e((224|(240&t)>>4).toString(16)+n.toString(16)+i.toString(16))})).join("")}function Ue(e){for(var t=encodeURIComponent(e),r="",n=0;n"7"?"00"+e:e}de.getLblen=function(e,t){if("8"!=e.substr(t+2,1))return 1;var r=parseInt(e.substr(t+3,1));return 0==r?-1:0=n)break}return s},de.getNthChildIdx=function(e,t,r){return de.getChildIdx(e,t)[r]},de.getIdxbyList=function(e,t,r,n){var i,o,s=de;return 0==r.length?void 0!==n&&e.substr(t,2)!==n?-1:t:(i=r.shift())>=(o=s.getChildIdx(e,t)).length?-1:s.getIdxbyList(e,o[i],r,n)},de.getIdxbyListEx=function(e,t,r,n){var i,o,s=de;if(0==r.length)return void 0!==n&&e.substr(t,2)!==n?-1:t;i=r.shift(),o=s.getChildIdx(e,t);for(var a=0,c=0;c=e.length?null:i.getTLV(e,o)},de.getTLVbyListEx=function(e,t,r,n){var i=de,o=i.getIdxbyListEx(e,t,r,n);return-1==o?null:i.getTLV(e,o)},de.getVbyList=function(e,t,r,n,i){var o,s,a=de;return-1==(o=a.getIdxbyList(e,t,r,n))||o>=e.length?null:(s=a.getV(e,o),!0===i&&(s=s.substr(2)),s)},de.getVbyListEx=function(e,t,r,n,i){var o,s,a=de;return-1==(o=a.getIdxbyListEx(e,t,r,n))?null:(s=a.getV(e,o),"03"==e.substr(o,2)&&!1!==i&&(s=s.substr(2)),s)},de.getInt=function(e,t,r){null==r&&(r=-1);try{var n=e.substr(t,2);if("02"!=n&&"03"!=n)return r;var i=de.getV(e,t);return"02"==n?parseInt(i,16):function(e){try{var t=e.substr(0,2);if("00"==t)return parseInt(e.substr(2),16);var r=parseInt(t,16),n=e.substr(2),i=parseInt(n,16).toString(2);return"0"==i&&(i="00000000"),i=i.slice(0,0-r),parseInt(i,2)}catch(e){return-1}}(i)}catch(e){return r}},de.getOID=function(e,t,r){null==r&&(r=null);try{return"06"!=e.substr(t,2)?r:function(e){if(!je(e))return null;try{var t=[],r=e.substr(0,2),n=parseInt(r,16);t[0]=new String(Math.floor(n/40)),t[1]=new String(n%40);for(var i=e.substr(2),o=[],s=0;s0&&(l=l+"."+a.join(".")),l}catch(e){return null}}(de.getV(e,t))}catch(e){return r}},de.getOIDName=function(e,t,r){null==r&&(r=null);try{var n=de.getOID(e,t,r);if(n==r)return r;var i=ce.asn1.x509.OID.oid2name(n);return""==i?n:i}catch(e){return r}},de.getString=function(e,t,r){null==r&&(r=null);try{return Se(de.getV(e,t))}catch(e){return r}},de.hextooidstr=function(e){var t=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},r=[],n=e.substr(0,2),i=parseInt(n,16);r[0]=new String(Math.floor(i/40)),r[1]=new String(i%40);for(var o=e.substr(2),s=[],a=0;a0&&(u=u+"."+c.join(".")),u},de.dump=function(e,t,r,n){var i=de,o=i.getV,s=i.dump,a=i.getChildIdx,c=e;e instanceof ce.asn1.ASN1Object&&(c=e.getEncodedHex());var l=function(e,t){return e.length<=2*t?e:e.substr(0,t)+"..(total "+e.length/2+"bytes).."+e.substr(e.length-t,t)};void 0===t&&(t={ommit_long_octet:32}),void 0===r&&(r=0),void 0===n&&(n="");var u,d=t.ommit_long_octet;if("01"==(u=c.substr(r,2)))return"00"==(h=o(c,r))?n+"BOOLEAN FALSE\n":n+"BOOLEAN TRUE\n";if("02"==u)return n+"INTEGER "+l(h=o(c,r),d)+"\n";if("03"==u){var h=o(c,r);return i.isASN1HEX(h.substr(2))?(_=n+"BITSTRING, encapsulates\n")+s(h.substr(2),t,0,n+" "):n+"BITSTRING "+l(h,d)+"\n"}if("04"==u)return h=o(c,r),i.isASN1HEX(h)?(_=n+"OCTETSTRING, encapsulates\n")+s(h,t,0,n+" "):n+"OCTETSTRING "+l(h,d)+"\n";if("05"==u)return n+"NULL\n";if("06"==u){var f=o(c,r),p=ce.asn1.ASN1Util.oidHexToInt(f),g=ce.asn1.x509.OID.oid2name(p),y=p.replace(/\./g," ");return""!=g?n+"ObjectIdentifier "+g+" ("+y+")\n":n+"ObjectIdentifier ("+y+")\n"}if("0a"==u)return n+"ENUMERATED "+parseInt(o(c,r))+"\n";if("0c"==u)return n+"UTF8String '"+_e(o(c,r))+"'\n";if("13"==u)return n+"PrintableString '"+_e(o(c,r))+"'\n";if("14"==u)return n+"TeletexString '"+_e(o(c,r))+"'\n";if("16"==u)return n+"IA5String '"+_e(o(c,r))+"'\n";if("17"==u)return n+"UTCTime "+_e(o(c,r))+"\n";if("18"==u)return n+"GeneralizedTime "+_e(o(c,r))+"\n";if("1a"==u)return n+"VisualString '"+_e(o(c,r))+"'\n";if("1e"==u)return n+"BMPString '"+Le(o(c,r))+"'\n";if("30"==u){if("3000"==c.substr(r,4))return n+"SEQUENCE {}\n";_=n+"SEQUENCE\n";var m=t;if((2==(w=a(c,r)).length||3==w.length)&&"06"==c.substr(w[0],2)&&"04"==c.substr(w[w.length-1],2)){g=i.oidname(o(c,w[0]));var v=JSON.parse(JSON.stringify(t));v.x509ExtName=g,m=v}for(var b=0;b31)&&128==(192&r)&&(31&r)==n}catch(e){return!1}},de.isASN1HEX=function(e){var t=de;if(e.length%2==1)return!1;var r=t.getVblen(e,0),n=e.substr(0,2),i=t.getL(e,0);return e.length-n.length-i.length==2*r},de.checkStrictDER=function(e,t,r,n,i){var o=de;if(void 0===r){if("string"!=typeof e)throw new Error("not hex string");if(e=e.toLowerCase(),!ce.lang.String.isHex(e))throw new Error("not hex string");r=e.length,i=(n=e.length/2)<128?1:Math.ceil(n.toString(16))+1}if(o.getL(e,t).length>2*i)throw new Error("L of TLV too long: idx="+t);var s=o.getVblen(e,t);if(s>n)throw new Error("value of L too long than hex: idx="+t);var a=o.getTLV(e,t),c=a.length-2-o.getL(e,t).length;if(c!==2*s)throw new Error("V string length and L's value not the same:"+c+"/"+2*s);if(0===t&&e.length!=a.length)throw new Error("total length and TLV length unmatch:"+e.length+"!="+a.length);var l=e.substr(t,2);if("02"===l){var u=o.getVidx(e,t);if("00"==e.substr(u,2)&&e.charCodeAt(u+2)<56)throw new Error("not least zeros for DER INTEGER")}if(32&parseInt(l,16)){for(var d=o.getVblen(e,t),h=0,f=o.getChildIdx(e,t),p=0;p=t?e:new Array(t-e.length+1).join(r)+e};function He(e,t){var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e,e.superclass=t.prototype,t.prototype.constructor==Object.prototype.constructor&&(t.prototype.constructor=t)}void 0!==ce&&ce||(t.KJUR=ce={}),void 0!==ce.crypto&&ce.crypto||(ce.crypto={}),ce.crypto.Util=new function(){this.DIGESTINFOHEAD={sha1:"3021300906052b0e03021a05000414",sha224:"302d300d06096086480165030402040500041c",sha256:"3031300d060960864801650304020105000420",sha384:"3041300d060960864801650304020205000430",sha512:"3051300d060960864801650304020305000440",md2:"3020300c06082a864886f70d020205000410",md5:"3020300c06082a864886f70d020505000410",ripemd160:"3021300906052b2403020105000414"},this.DEFAULTPROVIDER={md5:"cryptojs",sha1:"cryptojs",sha224:"cryptojs",sha256:"cryptojs",sha384:"cryptojs",sha512:"cryptojs",ripemd160:"cryptojs",hmacmd5:"cryptojs",hmacsha1:"cryptojs",hmacsha224:"cryptojs",hmacsha256:"cryptojs",hmacsha384:"cryptojs",hmacsha512:"cryptojs",hmacripemd160:"cryptojs",MD5withRSA:"cryptojs/jsrsa",SHA1withRSA:"cryptojs/jsrsa",SHA224withRSA:"cryptojs/jsrsa",SHA256withRSA:"cryptojs/jsrsa",SHA384withRSA:"cryptojs/jsrsa",SHA512withRSA:"cryptojs/jsrsa",RIPEMD160withRSA:"cryptojs/jsrsa",MD5withECDSA:"cryptojs/jsrsa",SHA1withECDSA:"cryptojs/jsrsa",SHA224withECDSA:"cryptojs/jsrsa",SHA256withECDSA:"cryptojs/jsrsa",SHA384withECDSA:"cryptojs/jsrsa",SHA512withECDSA:"cryptojs/jsrsa",RIPEMD160withECDSA:"cryptojs/jsrsa",SHA1withDSA:"cryptojs/jsrsa",SHA224withDSA:"cryptojs/jsrsa",SHA256withDSA:"cryptojs/jsrsa",MD5withRSAandMGF1:"cryptojs/jsrsa",SHAwithRSAandMGF1:"cryptojs/jsrsa",SHA1withRSAandMGF1:"cryptojs/jsrsa",SHA224withRSAandMGF1:"cryptojs/jsrsa",SHA256withRSAandMGF1:"cryptojs/jsrsa",SHA384withRSAandMGF1:"cryptojs/jsrsa",SHA512withRSAandMGF1:"cryptojs/jsrsa",RIPEMD160withRSAandMGF1:"cryptojs/jsrsa"},this.CRYPTOJSMESSAGEDIGESTNAME={md5:y.algo.MD5,sha1:y.algo.SHA1,sha224:y.algo.SHA224,sha256:y.algo.SHA256,sha384:y.algo.SHA384,sha512:y.algo.SHA512,ripemd160:y.algo.RIPEMD160},this.getDigestInfoHex=function(e,t){if(void 0===this.DIGESTINFOHEAD[t])throw"alg not supported in Util.DIGESTINFOHEAD: "+t;return this.DIGESTINFOHEAD[t]+e},this.getPaddedDigestInfoHex=function(e,t,r){var n=this.getDigestInfoHex(e,t),i=r/4;if(n.length+22>i)throw"key is too short for SigAlg: keylen="+r+","+t;for(var o="00"+n,s="",a=i-4-o.length,c=0;c=0)return!1;if(n.compareTo(r.ONE)<0||n.compareTo(o)>=0)return!1;var a=n.modInverse(o),c=e.multiply(a).mod(o),l=t.multiply(a).mod(o);return s.multiply(c).add(i.multiply(l)).getX().toBigInteger().mod(o).equals(t)},this.serializeSig=function(e,t){var r=e.toByteArraySigned(),n=t.toByteArraySigned(),i=[];return i.push(2),i.push(r.length),(i=i.concat(r)).push(2),i.push(n.length),(i=i.concat(n)).unshift(i.length),i.unshift(48),i},this.parseSig=function(e){var t;if(48!=e[0])throw new Error("Signature not a valid DERSequence");if(2!=e[t=2])throw new Error("First element in signature must be a DERInteger");var n=e.slice(t+2,t+2+e[t+1]);if(2!=e[t+=2+e[t+1]])throw new Error("Second element in signature must be a DERInteger");var i=e.slice(t+2,t+2+e[t+1]);return t+=2+e[t+1],{r:r.fromByteArrayUnsigned(n),s:r.fromByteArrayUnsigned(i)}},this.parseSigCompact=function(e){if(65!==e.length)throw"Signature has the wrong length";var t=e[0]-27;if(t<0||t>7)throw"Invalid signature type";var n=this.ecparams.n;return{r:r.fromByteArrayUnsigned(e.slice(1,33)).mod(n),s:r.fromByteArrayUnsigned(e.slice(33,65)).mod(n),i:t}},this.readPKCS5PrvKeyHex=function(e){if(!1===l(e))throw new Error("not ASN.1 hex string");var t,r,n;try{t=c(e,0,["[0]",0],"06"),r=c(e,0,[1],"04");try{n=c(e,0,["[1]",0],"03")}catch(e){}}catch(e){throw new Error("malformed PKCS#1/5 plain ECC private key")}if(this.curveName=s(t),void 0===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(n),this.setPrivateKeyHex(r),this.isPublic=!1},this.readPKCS8PrvKeyHex=function(e){if(!1===l(e))throw new t("not ASN.1 hex string");var r,n,i;try{c(e,0,[1,0],"06"),r=c(e,0,[1,1],"06"),n=c(e,0,[2,0,1],"04");try{i=c(e,0,[2,0,"[1]",0],"03")}catch(e){}}catch(e){throw new t("malformed PKCS#8 plain ECC private key")}if(this.curveName=s(r),void 0===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i),this.setPrivateKeyHex(n),this.isPublic=!1},this.readPKCS8PubKeyHex=function(e){if(!1===l(e))throw new t("not ASN.1 hex string");var r,n;try{c(e,0,[0,0],"06"),r=c(e,0,[0,1],"06"),n=c(e,0,[1],"03")}catch(e){throw new t("malformed PKCS#8 ECC public key")}if(this.curveName=s(r),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(n)},this.readCertPubKeyHex=function(e,r){if(!1===l(e))throw new t("not ASN.1 hex string");var n,i;try{n=c(e,0,[0,5,0,1],"06"),i=c(e,0,[0,5,1],"03")}catch(e){throw new t("malformed X.509 certificate ECC public key")}if(this.curveName=s(n),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i)},void 0!==e&&void 0!==e.curve&&(this.curveName=e.curve),void 0===this.curveName&&(this.curveName="secp256r1"),this.setNamedCurve(this.curveName),void 0!==e&&(void 0!==e.prv&&this.setPrivateKeyHex(e.prv),void 0!==e.pub&&this.setPublicKeyHex(e.pub))},ce.crypto.ECDSA.parseSigHex=function(e){var t=ce.crypto.ECDSA.parseSigHexInHexRS(e);return{r:new S(t.r,16),s:new S(t.s,16)}},ce.crypto.ECDSA.parseSigHexInHexRS=function(e){var t=de,r=t.getChildIdx,n=t.getV;if(t.checkStrictDER(e,0),"30"!=e.substr(0,2))throw new Error("signature is not a ASN.1 sequence");var i=r(e,0);if(2!=i.length)throw new Error("signature shall have two elements");var o=i[0],s=i[1];if("02"!=e.substr(o,2))throw new Error("1st item not ASN.1 integer");if("02"!=e.substr(s,2))throw new Error("2nd item not ASN.1 integer");return{r:n(e,o),s:n(e,s)}},ce.crypto.ECDSA.asn1SigToConcatSig=function(e){var t=ce.crypto.ECDSA.parseSigHexInHexRS(e),r=t.r,n=t.s;if("00"==r.substr(0,2)&&r.length%32==2&&(r=r.substr(2)),"00"==n.substr(0,2)&&n.length%32==2&&(n=n.substr(2)),r.length%32==30&&(r="00"+r),n.length%32==30&&(n="00"+n),r.length%32!=0)throw"unknown ECDSA sig r length error";if(n.length%32!=0)throw"unknown ECDSA sig s length error";return r+n},ce.crypto.ECDSA.concatSigToASN1Sig=function(e){if(e.length/2*8%128!=0)throw"unknown ECDSA concatinated r-s sig length error";var t=e.substr(0,e.length/2),r=e.substr(e.length/2);return ce.crypto.ECDSA.hexRSSigToASN1Sig(t,r)},ce.crypto.ECDSA.hexRSSigToASN1Sig=function(e,t){var r=new S(e,16),n=new S(t,16);return ce.crypto.ECDSA.biRSSigToASN1Sig(r,n)},ce.crypto.ECDSA.biRSSigToASN1Sig=function(e,t){var r=ce.asn1,n=new r.DERInteger({bigint:e}),i=new r.DERInteger({bigint:t});return new r.DERSequence({array:[n,i]}).getEncodedHex()},ce.crypto.ECDSA.getName=function(e){return"2b8104001f"===e?"secp192k1":"2a8648ce3d030107"===e?"secp256r1":"2b8104000a"===e?"secp256k1":"2b81040021"===e?"secp224r1":"2b81040022"===e?"secp384r1":-1!=="|secp256r1|NIST P-256|P-256|prime256v1|".indexOf(e)?"secp256r1":-1!=="|secp256k1|".indexOf(e)?"secp256k1":-1!=="|secp224r1|NIST P-224|P-224|".indexOf(e)?"secp224r1":-1!=="|secp384r1|NIST P-384|P-384|".indexOf(e)?"secp384r1":null},void 0!==ce&&ce||(t.KJUR=ce={}),void 0!==ce.crypto&&ce.crypto||(ce.crypto={}),ce.crypto.ECParameterDB=new function(){var e={},t={};function r(e){return new S(e,16)}this.getByName=function(r){var n=r;if(void 0!==t[n]&&(n=t[r]),void 0!==e[n])return e[n];throw"unregistered EC curve name: "+n},this.regist=function(n,i,o,s,a,c,l,u,d,h,f,p){e[n]={};var g=r(o),y=r(s),m=r(a),v=r(c),b=r(l),w=new se(g,y,m),_=w.decodePointHex("04"+u+d);e[n].name=n,e[n].keylen=i,e[n].curve=w,e[n].G=_,e[n].n=v,e[n].h=b,e[n].oid=f,e[n].info=p;for(var S=0;S=2*a)break}var d={};return d.keyhex=c.substr(0,2*i[e].keylen),d.ivhex=c.substr(2*i[e].keylen,2*i[e].ivlen),d},a=function(e,t,r,n){var o=y.enc.Base64.parse(e),s=y.enc.Hex.stringify(o);return(0,i[t].proc)(s,r,n)};return{version:"1.0.0",parsePKCS5PEM:function(e){return o(e)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(e,t,r){return s(e,t,r)},decryptKeyB64:function(e,t,r,n){return a(e,t,r,n)},getDecryptedKeyHex:function(e,t){var r=o(e),n=(r.type,r.cipher),i=r.ivsalt,c=r.data,l=s(n,t,i).keyhex;return a(c,n,l,i)},getEncryptedPKCS5PEMFromPrvKeyHex:function(e,t,r,n,o){var a="";if(void 0!==n&&null!=n||(n="AES-256-CBC"),void 0===i[n])throw new Error("KEYUTIL unsupported algorithm: "+n);void 0!==o&&null!=o||(o=function(e){var t=y.lib.WordArray.random(e);return y.enc.Hex.stringify(t)}(i[n].ivlen).toUpperCase());var c=function(e,t,r,n){return(0,i[t].eproc)(e,r,n)}(t,n,s(n,r,o).keyhex,o);return a="-----BEGIN "+e+" PRIVATE KEY-----\r\n",a+="Proc-Type: 4,ENCRYPTED\r\n",a+="DEK-Info: "+n+","+o+"\r\n",a+="\r\n",(a+=c.replace(/(.{64})/g,"$1\r\n"))+"\r\n-----END "+e+" PRIVATE KEY-----\r\n"},parseHexOfEncryptedPKCS8:function(e){var t=de,r=t.getChildIdx,n=t.getV,i={},o=r(e,0);if(2!=o.length)throw new Error("malformed format: SEQUENCE(0).items != 2: "+o.length);i.ciphertext=n(e,o[1]);var s=r(e,o[0]);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0.0).items != 2: "+s.length);if("2a864886f70d01050d"!=n(e,s[0]))throw new Error("this only supports pkcs5PBES2");var a=r(e,s[1]);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: "+a.length);var c=r(e,a[1]);if(2!=c.length)throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: "+c.length);if("2a864886f70d0307"!=n(e,c[0]))throw"this only supports TripleDES";i.encryptionSchemeAlg="TripleDES",i.encryptionSchemeIV=n(e,c[1]);var l=r(e,a[0]);if(2!=l.length)throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: "+l.length);if("2a864886f70d01050c"!=n(e,l[0]))throw new Error("this only supports pkcs5PBKDF2");var u=r(e,l[1]);if(u.length<2)throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+u.length);i.pbkdf2Salt=n(e,u[0]);var d=n(e,u[1]);try{i.pbkdf2Iter=parseInt(d,16)}catch(e){throw new Error("malformed format pbkdf2Iter: "+d)}return i},getPBKDF2KeyHexFromParam:function(e,t){var r=y.enc.Hex.parse(e.pbkdf2Salt),n=e.pbkdf2Iter,i=y.PBKDF2(t,r,{keySize:6,iterations:n});return y.enc.Hex.stringify(i)},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function(e,t){var r=xe(e,"ENCRYPTED PRIVATE KEY"),n=this.parseHexOfEncryptedPKCS8(r),i=We.getPBKDF2KeyHexFromParam(n,t),o={};o.ciphertext=y.enc.Hex.parse(n.ciphertext);var s=y.enc.Hex.parse(i),a=y.enc.Hex.parse(n.encryptionSchemeIV),c=y.TripleDES.decrypt(o,s,{iv:a});return y.enc.Hex.stringify(c)},getKeyFromEncryptedPKCS8PEM:function(e,t){var r=this._getPlainPKCS8HexFromEncryptedPKCS8PEM(e,t);return this.getKeyFromPlainPrivatePKCS8Hex(r)},parsePlainPrivatePKCS8Hex:function(e){var t=de,r=t.getChildIdx,n=t.getV,i={algparam:null};if("30"!=e.substr(0,2))throw new Error("malformed plain PKCS8 private key(code:001)");var o=r(e,0);if(o.length<3)throw new Error("malformed plain PKCS8 private key(code:002)");if("30"!=e.substr(o[1],2))throw new Error("malformed PKCS8 private key(code:003)");var s=r(e,o[1]);if(2!=s.length)throw new Error("malformed PKCS8 private key(code:004)");if("06"!=e.substr(s[0],2))throw new Error("malformed PKCS8 private key(code:005)");if(i.algoid=n(e,s[0]),"06"==e.substr(s[1],2)&&(i.algparam=n(e,s[1])),"04"!=e.substr(o[2],2))throw new Error("malformed PKCS8 private key(code:006)");return i.keyidx=t.getVidx(e,o[2]),i},getKeyFromPlainPrivatePKCS8PEM:function(e){var t=xe(e,"PRIVATE KEY");return this.getKeyFromPlainPrivatePKCS8Hex(t)},getKeyFromPlainPrivatePKCS8Hex:function(e){var t,r=this.parsePlainPrivatePKCS8Hex(e);if("2a864886f70d010101"==r.algoid)t=new ne;else if("2a8648ce380401"==r.algoid)t=new ce.crypto.DSA;else{if("2a8648ce3d0201"!=r.algoid)throw new Error("unsupported private key algorithm");t=new ce.crypto.ECDSA}return t.readPKCS8PrvKeyHex(e),t},_getKeyFromPublicPKCS8Hex:function(e){var t,r=de.getVbyList(e,0,[0,0],"06");if("2a864886f70d010101"===r)t=new ne;else if("2a8648ce380401"===r)t=new ce.crypto.DSA;else{if("2a8648ce3d0201"!==r)throw new Error("unsupported PKCS#8 public key hex");t=new ce.crypto.ECDSA}return t.readPKCS8PubKeyHex(e),t},parsePublicRawRSAKeyHex:function(e){var t=de,r=t.getChildIdx,n=t.getV,i={};if("30"!=e.substr(0,2))throw new Error("malformed RSA key(code:001)");var o=r(e,0);if(2!=o.length)throw new Error("malformed RSA key(code:002)");if("02"!=e.substr(o[0],2))throw new Error("malformed RSA key(code:003)");if(i.n=n(e,o[0]),"02"!=e.substr(o[1],2))throw new Error("malformed RSA key(code:004)");return i.e=n(e,o[1]),i},parsePublicPKCS8Hex:function(e){var t=de,r=t.getChildIdx,n=t.getV,i={algparam:null},o=r(e,0);if(2!=o.length)throw new Error("outer DERSequence shall have 2 elements: "+o.length);var s=o[0];if("30"!=e.substr(s,2))throw new Error("malformed PKCS8 public key(code:001)");var a=r(e,s);if(2!=a.length)throw new Error("malformed PKCS8 public key(code:002)");if("06"!=e.substr(a[0],2))throw new Error("malformed PKCS8 public key(code:003)");if(i.algoid=n(e,a[0]),"06"==e.substr(a[1],2)?i.algparam=n(e,a[1]):"30"==e.substr(a[1],2)&&(i.algparam={},i.algparam.p=t.getVbyList(e,a[1],[0],"02"),i.algparam.q=t.getVbyList(e,a[1],[1],"02"),i.algparam.g=t.getVbyList(e,a[1],[2],"02")),"03"!=e.substr(o[1],2))throw new Error("malformed PKCS8 public key(code:004)");return i.key=n(e,o[1]).substr(2),i}}}();function $e(e,t){for(var r="",n=t/4-e.length,i=0;i>24,(16711680&i)>>16,(65280&i)>>8,255&i])))),i+=1;return n}function Ke(e){for(var t in ce.crypto.Util.DIGESTINFOHEAD){var r=ce.crypto.Util.DIGESTINFOHEAD[t],n=r.length;if(e.substring(0,n)==r)return[t,e.substring(n)]}return[]}function Je(e){var t,r=de,n=r.getChildIdx,i=r.getV,o=r.getTLV,s=r.getVbyList,a=r.getVbyListEx,c=r.getTLVbyList,l=r.getTLVbyListEx,u=r.getIdxbyList,d=r.getIdxbyListEx,h=r.getVidx,f=r.getInt,p=r.oidname,g=r.hextooidstr,y=xe;try{t=ce.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV}catch(e){}this.HEX2STAG={"0c":"utf8",13:"prn",16:"ia5","1a":"vis","1e":"bmp"},this.hex=null,this.version=0,this.foffset=0,this.aExtInfo=null,this.getVersion=function(){if(null===this.hex||0!==this.version)return this.version;var e=c(this.hex,0,[0,0]);if("a0"==e.substr(0,2)){var t=c(e,0,[0]),r=f(t,0);if(r<0||21){var a=o(e,s[1]),c=this.getGeneralName(a);null!=c.uri&&(i.uri=c.uri)}if(s.length>2){var l=o(e,s[2]);"0101ff"==l&&(i.reqauth=!0),"010100"==l&&(i.reqauth=!1)}return i},this.getX500NameRule=function(e){for(var t=null,r=[],n=0;n0&&(e.ext=this.getExtParamArray()),e.sighex=this.getSignatureValueHex(),e},this.getExtParamArray=function(e){null==e&&-1!=d(this.hex,0,[0,"[3]"])&&(e=l(this.hex,0,[0,"[3]",0],"30"));for(var t=[],r=n(e,0),i=0;i2&&"04"===y.substr(g[1],2)))throw new Error("unsupported PKCS#1/5 hexadecimal key");(P=new a).readPKCS5PrvKeyHex(y)}return P}if("pkcs8prv"===r)return d.getKeyFromPlainPrivatePKCS8Hex(e);if("pkcs8pub"===r)return d._getKeyFromPublicPKCS8Hex(e);if("x509pub"===r)return Je.getPublicKeyFromCertHex(e);if(-1!=e.indexOf("-END CERTIFICATE-",0)||-1!=e.indexOf("-END X509 CERTIFICATE-",0)||-1!=e.indexOf("-END TRUSTED CERTIFICATE-",0))return Je.getPublicKeyFromCertPEM(e);if(-1!=e.indexOf("-END PUBLIC KEY-")){var v=xe(e,"PUBLIC KEY");return d._getKeyFromPublicPKCS8Hex(v)}if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var b=u(e,"RSA PRIVATE KEY");return d.getKey(b,null,"pkcs5prv")}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var w=o(n=u(e,"DSA PRIVATE KEY"),0,[1],"02"),_=o(n,0,[2],"02"),E=o(n,0,[3],"02"),A=o(n,0,[4],"02"),R=o(n,0,[5],"02");return(P=new c).setPrivate(new S(w,16),new S(_,16),new S(E,16),new S(A,16),new S(R,16)),P}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED"))return b=u(e,"EC PRIVATE KEY"),d.getKey(b,null,"pkcs5prv");if(-1!=e.indexOf("-END PRIVATE KEY-"))return d.getKeyFromPlainPrivatePKCS8PEM(e);if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var I=d.getDecryptedKeyHex(e,t),T=new ne;return T.readPKCS5PrvKeyHex(I),T}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var x,P=o(n=d.getDecryptedKeyHex(e,t),0,[1],"04"),C=o(n,0,[2,0],"06"),k=o(n,0,[3,0],"03").substr(2);if(void 0===ce.crypto.OID.oidhex2name[C])throw new Error("undefined OID(hex) in KJUR.crypto.OID: "+C);return(x=new a({curve:ce.crypto.OID.oidhex2name[C]})).setPublicKeyHex(k),x.setPrivateKeyHex(P),x.isPublic=!1,x}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED"))return w=o(n=d.getDecryptedKeyHex(e,t),0,[1],"02"),_=o(n,0,[2],"02"),E=o(n,0,[3],"02"),A=o(n,0,[4],"02"),R=o(n,0,[5],"02"),(P=new c).setPrivate(new S(w,16),new S(_,16),new S(E,16),new S(A,16),new S(R,16)),P;if(-1!=e.indexOf("-END ENCRYPTED PRIVATE KEY-"))return d.getKeyFromEncryptedPKCS8PEM(e,t);throw new Error("not supported argument")},We.generateKeypair=function(e,t){if("RSA"==e){var r=t;(s=new ne).generate(r,"10001"),s.isPrivate=!0,s.isPublic=!0;var n=new ne,i=s.n.toString(16),o=s.e.toString(16);return n.setPublic(i,o),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=s,a.pubKeyObj=n,a}if("EC"==e){var s,a,c=t,l=new ce.crypto.ECDSA({curve:c}).generateKeyPairHex();return(s=new ce.crypto.ECDSA({curve:c})).setPublicKeyHex(l.ecpubhex),s.setPrivateKeyHex(l.ecprvhex),s.isPrivate=!0,s.isPublic=!1,(n=new ce.crypto.ECDSA({curve:c})).setPublicKeyHex(l.ecpubhex),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=s,a.pubKeyObj=n,a}throw new Error("unknown algorithm: "+e)},We.getPEM=function(e,t,r,n,i,o){var s=ce,a=s.asn1,c=a.DERObjectIdentifier,l=a.DERInteger,u=a.ASN1Util.newObject,d=a.x509.SubjectPublicKeyInfo,h=s.crypto,f=h.DSA,p=h.ECDSA,g=ne;function m(e){return u({seq:[{int:0},{int:{bigint:e.n}},{int:e.e},{int:{bigint:e.d}},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.dmp1}},{int:{bigint:e.dmq1}},{int:{bigint:e.coeff}}]})}function v(e){return u({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a0",!0,{oid:{name:e.curveName}}]},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]})}function b(e){return u({seq:[{int:0},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}},{int:{bigint:e.y}},{int:{bigint:e.x}}]})}if((void 0!==g&&e instanceof g||void 0!==f&&e instanceof f||void 0!==p&&e instanceof p)&&1==e.isPublic&&(void 0===t||"PKCS8PUB"==t))return Te(E=new d(e).getEncodedHex(),"PUBLIC KEY");if("PKCS1PRV"==t&&void 0!==g&&e instanceof g&&(void 0===r||null==r)&&1==e.isPrivate)return Te(E=m(e).getEncodedHex(),"RSA PRIVATE KEY");if("PKCS1PRV"==t&&void 0!==p&&e instanceof p&&(void 0===r||null==r)&&1==e.isPrivate){var w=new c({name:e.curveName}).getEncodedHex(),_=v(e).getEncodedHex(),S="";return(S+=Te(w,"EC PARAMETERS"))+Te(_,"EC PRIVATE KEY")}if("PKCS1PRV"==t&&void 0!==f&&e instanceof f&&(void 0===r||null==r)&&1==e.isPrivate)return Te(E=b(e).getEncodedHex(),"DSA PRIVATE KEY");if("PKCS5PRV"==t&&void 0!==g&&e instanceof g&&void 0!==r&&null!=r&&1==e.isPrivate){var E=m(e).getEncodedHex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",E,r,n,o)}if("PKCS5PRV"==t&&void 0!==p&&e instanceof p&&void 0!==r&&null!=r&&1==e.isPrivate)return E=v(e).getEncodedHex(),void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",E,r,n,o);if("PKCS5PRV"==t&&void 0!==f&&e instanceof f&&void 0!==r&&null!=r&&1==e.isPrivate)return E=b(e).getEncodedHex(),void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",E,r,n,o);var A=function(e,t){var r=R(e,t);return new u({seq:[{seq:[{oid:{name:"pkcs5PBES2"}},{seq:[{seq:[{oid:{name:"pkcs5PBKDF2"}},{seq:[{octstr:{hex:r.pbkdf2Salt}},{int:r.pbkdf2Iter}]}]},{seq:[{oid:{name:"des-EDE3-CBC"}},{octstr:{hex:r.encryptionSchemeIV}}]}]}]},{octstr:{hex:r.ciphertext}}]}).getEncodedHex()},R=function(e,t){var r=y.lib.WordArray.random(8),n=y.lib.WordArray.random(8),i=y.PBKDF2(t,r,{keySize:6,iterations:100}),o=y.enc.Hex.parse(e),s=y.TripleDES.encrypt(o,i,{iv:n})+"",a={};return a.ciphertext=s,a.pbkdf2Salt=y.enc.Hex.stringify(r),a.pbkdf2Iter=100,a.encryptionSchemeAlg="DES-EDE3-CBC",a.encryptionSchemeIV=y.enc.Hex.stringify(n),a};if("PKCS8PRV"==t&&null!=g&&e instanceof g&&1==e.isPrivate){var I=m(e).getEncodedHex();return E=u({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:I}}]}).getEncodedHex(),void 0===r||null==r?Te(E,"PRIVATE KEY"):Te(_=A(E,r),"ENCRYPTED PRIVATE KEY")}if("PKCS8PRV"==t&&void 0!==p&&e instanceof p&&1==e.isPrivate)return I=new u({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]}).getEncodedHex(),E=u({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:e.curveName}}]},{octstr:{hex:I}}]}).getEncodedHex(),void 0===r||null==r?Te(E,"PRIVATE KEY"):Te(_=A(E,r),"ENCRYPTED PRIVATE KEY");if("PKCS8PRV"==t&&void 0!==f&&e instanceof f&&1==e.isPrivate)return I=new l({bigint:e.x}).getEncodedHex(),E=u({seq:[{int:0},{seq:[{oid:{name:"dsa"}},{seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]}]},{octstr:{hex:I}}]}).getEncodedHex(),void 0===r||null==r?Te(E,"PRIVATE KEY"):Te(_=A(E,r),"ENCRYPTED PRIVATE KEY");throw new Error("unsupported object nor format")},We.getKeyFromCSRPEM=function(e){var t=xe(e,"CERTIFICATE REQUEST");return We.getKeyFromCSRHex(t)},We.getKeyFromCSRHex=function(e){var t=We.parseCSRHex(e);return We.getKey(t.p8pubkeyhex,null,"pkcs8pub")},We.parseCSRHex=function(e){var t=de,r=t.getChildIdx,n=t.getTLV,i={},o=e;if("30"!=o.substr(0,2))throw new Error("malformed CSR(code:001)");var s=r(o,0);if(s.length<1)throw new Error("malformed CSR(code:002)");if("30"!=o.substr(s[0],2))throw new Error("malformed CSR(code:003)");var a=r(o,s[0]);if(a.length<3)throw new Error("malformed CSR(code:004)");return i.p8pubkeyhex=n(o,a[2]),i},We.getKeyID=function(e){var t=We,r=de;"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&(e=t.getKey(e));var n=xe(t.getPEM(e)),i=r.getIdxbyList(n,0,[1]),o=r.getV(n,i).substring(2);return ce.crypto.Util.hashHex(o,"sha1")},We.getJWKFromKey=function(e){var t={};if(e instanceof ne&&e.isPrivate)return t.kty="RSA",t.n=ve(e.n.toString(16)),t.e=ve(e.e.toString(16)),t.d=ve(e.d.toString(16)),t.p=ve(e.p.toString(16)),t.q=ve(e.q.toString(16)),t.dp=ve(e.dmp1.toString(16)),t.dq=ve(e.dmq1.toString(16)),t.qi=ve(e.coeff.toString(16)),t;if(e instanceof ne&&e.isPublic)return t.kty="RSA",t.n=ve(e.n.toString(16)),t.e=ve(e.e.toString(16)),t;if(e instanceof ce.crypto.ECDSA&&e.isPrivate){if("P-256"!==(n=e.getShortNISTPCurveName())&&"P-384"!==n)throw new Error("unsupported curve name for JWT: "+n);var r=e.getPublicKeyXYHex();return t.kty="EC",t.crv=n,t.x=ve(r.x),t.y=ve(r.y),t.d=ve(e.prvKeyHex),t}if(e instanceof ce.crypto.ECDSA&&e.isPublic){var n;if("P-256"!==(n=e.getShortNISTPCurveName())&&"P-384"!==n)throw new Error("unsupported curve name for JWT: "+n);return r=e.getPublicKeyXYHex(),t.kty="EC",t.crv=n,t.x=ve(r.x),t.y=ve(r.y),t}throw new Error("not supported key object")},ne.getPosArrayOfChildrenFromHex=function(e){return de.getChildIdx(e,0)},ne.getHexValueArrayOfChildrenFromHex=function(e){var t,r=de.getV,n=r(e,(t=ne.getPosArrayOfChildrenFromHex(e))[0]),i=r(e,t[1]),o=r(e,t[2]),s=r(e,t[3]),a=r(e,t[4]),c=r(e,t[5]),l=r(e,t[6]),u=r(e,t[7]),d=r(e,t[8]);return(t=new Array).push(n,i,o,s,a,c,l,u,d),t},ne.prototype.readPrivateKeyFromPEMString=function(e){var t=xe(e),r=ne.getHexValueArrayOfChildrenFromHex(t);this.setPrivateEx(r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8])},ne.prototype.readPKCS5PrvKeyHex=function(e){var t=ne.getHexValueArrayOfChildrenFromHex(e);this.setPrivateEx(t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])},ne.prototype.readPKCS8PrvKeyHex=function(e){var t,r,n,i,o,s,a,c,l=de,u=l.getVbyListEx;if(!1===l.isASN1HEX(e))throw new Error("not ASN.1 hex string");try{t=u(e,0,[2,0,1],"02"),r=u(e,0,[2,0,2],"02"),n=u(e,0,[2,0,3],"02"),i=u(e,0,[2,0,4],"02"),o=u(e,0,[2,0,5],"02"),s=u(e,0,[2,0,6],"02"),a=u(e,0,[2,0,7],"02"),c=u(e,0,[2,0,8],"02")}catch(e){throw new Error("malformed PKCS#8 plain RSA private key")}this.setPrivateEx(t,r,n,i,o,s,a,c)},ne.prototype.readPKCS5PubKeyHex=function(e){var t=de,r=t.getV;if(!1===t.isASN1HEX(e))throw new Error("keyHex is not ASN.1 hex string");var n=t.getChildIdx(e,0);if(2!==n.length||"02"!==e.substr(n[0],2)||"02"!==e.substr(n[1],2))throw new Error("wrong hex for PKCS#5 public key");var i=r(e,n[0]),o=r(e,n[1]);this.setPublic(i,o)},ne.prototype.readPKCS8PubKeyHex=function(e){var t=de;if(!1===t.isASN1HEX(e))throw new Error("not ASN.1 hex string");if("06092a864886f70d010101"!==t.getTLVbyListEx(e,0,[0,0]))throw new Error("not PKCS8 RSA public key");var r=t.getTLVbyListEx(e,0,[1,0]);this.readPKCS5PubKeyHex(r)},ne.prototype.readCertPubKeyHex=function(e,t){var r,n;(r=new Je).readCertHex(e),n=r.getPublicKeyHex(),this.readPKCS8PubKeyHex(n)},new RegExp("[^0-9a-f]","gi"),ne.prototype.sign=function(e,t){var r=function(e){return ce.crypto.Util.hashString(e,t)}(e);return this.signWithMessageHash(r,t)},ne.prototype.signWithMessageHash=function(e,t){var r=te(ce.crypto.Util.getPaddedDigestInfoHex(e,t,this.n.bitLength()),16);return $e(this.doPrivate(r).toString(16),this.n.bitLength())},ne.prototype.signPSS=function(e,t,r){var n=function(e){return ce.crypto.Util.hashHex(e,t)}(Ee(e));return void 0===r&&(r=-1),this.signWithMessageHashPSS(n,t,r)},ne.prototype.signWithMessageHashPSS=function(e,t,r){var n,i=Se(e),o=i.length,s=this.n.bitLength()-1,a=Math.ceil(s/8),c=function(e){return ce.crypto.Util.hashHex(e,t)};if(-1===r||void 0===r)r=o;else if(-2===r)r=a-o-2;else if(r<-2)throw new Error("invalid salt length");if(a0&&(l=new Array(r),(new ee).nextBytes(l),l=String.fromCharCode.apply(String,l));var u=Se(c(Ee("\0\0\0\0\0\0\0\0"+i+l))),d=[];for(n=0;n>8*a-s&255;for(p[0]&=~g,n=0;nn)return!1;var i=this.doPublic(r).toString(16);if(i.length+3!=n/4)return!1;var o=Ke(i.replace(/^1f+00/,""));if(0==o.length)return!1;var s=o[0];return o[1]==function(e){return ce.crypto.Util.hashString(e,s)}(e)},ne.prototype.verifyWithMessageHash=function(e,t){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var r=te(t,16);if(r.bitLength()>this.n.bitLength())return 0;var n=Ke(this.doPublic(r).toString(16).replace(/^1f+00/,""));return 0!=n.length&&(n[0],n[1]==e)},ne.prototype.verifyPSS=function(e,t,r,n){var i=function(e){return ce.crypto.Util.hashHex(e,r)}(Ee(e));return void 0===n&&(n=-1),this.verifyWithMessageHashPSS(i,t,r,n)},ne.prototype.verifyWithMessageHashPSS=function(e,t,r,n){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var i,o=new S(t,16),s=function(e){return ce.crypto.Util.hashHex(e,r)},a=Se(e),c=a.length,l=this.n.bitLength()-1,u=Math.ceil(l/8);if(-1===n||void 0===n)n=c;else if(-2===n)n=u-c-2;else if(n<-2)throw new Error("invalid salt length");if(u>8*u-l&255;if(h.charCodeAt(0)&p)throw new Error("bits beyond keysize not zero");var g=Ve(f,h.length,s),y=[];for(i=0;i0&&-1==(":"+r.join(":")+":").indexOf(":"+m+":"))throw"algorithm '"+m+"' not accepted in the list";if("none"!=m&&null===t)throw"key shall be specified to verify.";if("string"==typeof t&&-1!=t.indexOf("-----BEGIN ")&&(t=We.getKey(t)),!("RS"!=h&&"PS"!=h||t instanceof n))throw"key shall be a RSAKey obj for RS* and PS* algs";if("ES"==h&&!(t instanceof c))throw"key shall be a ECDSA obj for ES* algs";var v=null;if(void 0===o.jwsalg2sigalg[y.alg])throw"unsupported alg name: "+m;if("none"==(v=o.jwsalg2sigalg[m]))throw"not supported";if("Hmac"==v.substr(0,4)){if(void 0===t)throw"hexadecimal key shall be specified for HMAC";var b=new l({alg:v,pass:t});return b.updateString(p),g==b.doFinal()}if(-1!=v.indexOf("withECDSA")){var w,_=null;try{_=c.concatSigToASN1Sig(g)}catch(e){return!1}return(w=new u({alg:v})).init(t),w.updateString(p),w.verify(_)}return(w=new u({alg:v})).init(t),w.updateString(p),w.verify(g)},ce.jws.JWS.parse=function(e){var t,r,n,i=e.split("."),o={};if(2!=i.length&&3!=i.length)throw"malformed sJWS: wrong number of '.' splitted elements";return t=i[0],r=i[1],3==i.length&&(n=i[2]),o.headerObj=ce.jws.JWS.readSafeJSONString(ue(t)),o.payloadObj=ce.jws.JWS.readSafeJSONString(ue(r)),o.headerPP=JSON.stringify(o.headerObj,null," "),null==o.payloadObj?o.payloadPP=ue(r):o.payloadPP=JSON.stringify(o.payloadObj,null," "),void 0!==n&&(o.sigHex=be(n)),o},ce.jws.JWS.verifyJWT=function(e,t,r){var n=ce.jws,i=n.JWS,o=i.readSafeJSONString,s=i.inArray,a=i.includedArray,c=e.split("."),l=c[0],u=c[1],d=(be(c[2]),o(ue(l))),h=o(ue(u));if(void 0===d.alg)return!1;if(void 0===r.alg)throw"acceptField.alg shall be specified";if(!s(d.alg,r.alg))return!1;if(void 0!==h.iss&&"object"===f(r.iss)&&!s(h.iss,r.iss))return!1;if(void 0!==h.sub&&"object"===f(r.sub)&&!s(h.sub,r.sub))return!1;if(void 0!==h.aud&&"object"===f(r.aud))if("string"==typeof h.aud){if(!s(h.aud,r.aud))return!1}else if("object"==f(h.aud)&&!a(h.aud,r.aud))return!1;var p=n.IntDate.getNow();return void 0!==r.verifyAt&&"number"==typeof r.verifyAt&&(p=r.verifyAt),void 0!==r.gracePeriod&&"number"==typeof r.gracePeriod||(r.gracePeriod=0),!(void 0!==h.exp&&"number"==typeof h.exp&&h.exp+r.gracePeriodt.length&&(r=t.length);for(var n=0;n=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function p(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return H(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return W(e).length;default:if(n)return H(e).length;t=(""+t).toLowerCase(),n=!0}}function g(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,r);case"utf8":case"utf-8":return I(this,t,r);case"ascii":return x(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return R(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function y(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function m(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=c.from(t,n)),c.isBuffer(t))return 0===t.length?-1:v(e,t,r,n,i);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):v(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function v(e,t,r,n,i){var o,s=1,a=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){var u=-1;for(o=r;oa&&(r=a-c),o=r;o>=0;o--){for(var d=!0,h=0;hi&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function R(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function I(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:l>223?3:l>191?2:1;if(i+d<=r)switch(d){case 1:l<128&&(u=l);break;case 2:128==(192&(o=e[i+1]))&&(c=(31&l)<<6|63&o)>127&&(u=c);break;case 3:o=e[i+1],s=e[i+2],128==(192&o)&&128==(192&s)&&(c=(15&l)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(u=c);break;case 4:o=e[i+1],s=e[i+2],a=e[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(c=(15&l)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(u=c)}null===u?(u=65533,d=1):u>65535&&(u-=65536,n.push(u>>>10&1023|55296),u=56320|1023&u),n.push(u),i+=d}return function(e){var t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);for(var r="",n=0;n0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),""},c.prototype.compare=function(e,t,r,n,i){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0),a=Math.min(o,s),l=this.slice(n,i),u=e.slice(t,r),d=0;di)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return b(this,e,t,r);case"utf8":case"utf-8":return w(this,e,t,r);case"ascii":return _(this,e,t,r);case"latin1":case"binary":return S(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var T=4096;function x(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function F(e,t,r,n,i,o){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function N(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);i>>8*(n?i:1-i)}function D(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-r,4);i>>8*(n?i:3-i)&255}function L(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,o){return o||L(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function j(e,t,r,n,o){return o||L(e,0,r,8),i.write(e,t,r,n,52,8),r+8}c.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(i*=256);)n+=this[e+--t]*i;return n},c.prototype.readUInt8=function(e,t){return t||O(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||O(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||O(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||O(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},c.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||O(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},c.prototype.readInt8=function(e,t){return t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||O(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){t||O(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||O(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||O(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||O(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||O(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,r,n){e=+e,t|=0,r|=0,n||F(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+r},c.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):D(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);F(this,e,t,r,i-1,-i)}var o=0,s=1,a=0;for(this[t]=255&e;++o=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s|0)-a&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):D(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return j(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3||!c.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function W(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(M,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function $(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}}).call(this,r(29))},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){"use strict";t.byteLength=function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,n=c(e),s=n[0],a=n[1],l=new o(function(e,t,r){return 3*(t+r)/4-r}(0,s,a)),u=0,d=a>0?s-4:s;for(r=0;r>16&255,l[u++]=t>>8&255,l[u++]=255&t;return 2===a&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,l[u++]=255&t),1===a&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t),l},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],s=16383,a=0,c=r-i;ac?c:a+s));return 1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)n[a]=s[a],i[s.charCodeAt(a)]=a;function c(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function l(e,t,r){for(var i,o,s=[],a=t;a>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,r,n,i){var o,s,a=8*i-n-1,c=(1<>1,u=-7,d=r?i-1:0,h=r?-1:1,f=e[t+d];for(d+=h,o=f&(1<<-u)-1,f>>=-u,u+=a;u>0;o=256*o+e[t+d],d+=h,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=n;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),o-=l}return(f?-1:1)*s*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var s,a,c,l=8*o-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(s++,c/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(t*c-1)*Math.pow(2,i),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),s=0));i>=8;e[r+f]=255&a,f+=p,a/=256,i-=8);for(s=s<0;e[r+f]=255&s,f+=p,s/=256,l-=8);e[r+f-p]|=128*g}},function(e,t){var r={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.jws,r=e.KeyUtil,i=e.X509,o=e.crypto,s=e.hextob64u,a=e.b64tohex,c=e.AllowedSigningAlgs;return function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.parseJwt=function e(r){n.Log.debug("JoseUtil.parseJwt");try{var i=t.JWS.parse(r);return{header:i.headerObj,payload:i.payloadObj}}catch(e){n.Log.error(e)}},e.validateJwt=function(t,o,s,c,l,u,d){n.Log.debug("JoseUtil.validateJwt");try{if("RSA"===o.kty)if(o.e&&o.n)o=r.getKey(o);else{if(!o.x5c||!o.x5c.length)return n.Log.error("JoseUtil.validateJwt: RSA key missing key material",o),Promise.reject(new Error("RSA key missing key material"));var h=a(o.x5c[0]);o=i.getPublicKeyFromCertHex(h)}else{if("EC"!==o.kty)return n.Log.error("JoseUtil.validateJwt: Unsupported key type",o&&o.kty),Promise.reject(new Error(o.kty));if(!(o.crv&&o.x&&o.y))return n.Log.error("JoseUtil.validateJwt: EC key missing key material",o),Promise.reject(new Error("EC key missing key material"));o=r.getKey(o)}return e._validateJwt(t,o,s,c,l,u,d)}catch(e){return n.Log.error(e&&e.message||e),Promise.reject("JWT validation failed")}},e.validateJwtAttributes=function(t,r,i,o,s,a){o||(o=0),s||(s=parseInt(Date.now()/1e3));var c=e.parseJwt(t).payload;if(!c.iss)return n.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(c.iss!==r)return n.Log.error("JoseUtil._validateJwt: Invalid issuer in token",c.iss),Promise.reject(new Error("Invalid issuer in token: "+c.iss));if(!c.aud)return n.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(c.aud===i||Array.isArray(c.aud)&&c.aud.indexOf(i)>=0))return n.Log.error("JoseUtil._validateJwt: Invalid audience in token",c.aud),Promise.reject(new Error("Invalid audience in token: "+c.aud));if(c.azp&&c.azp!==i)return n.Log.error("JoseUtil._validateJwt: Invalid azp in token",c.azp),Promise.reject(new Error("Invalid azp in token: "+c.azp));if(!a){var l=s+o,u=s-o;if(!c.iat)return n.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(l1&&void 0!==arguments[1]?arguments[1]:"#";!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var n=i.UrlUtility.parseUrlFragment(t,r);this.error=n.error,this.error_description=n.error_description,this.error_uri=n.error_uri,this.code=n.code,this.state=n.state,this.id_token=n.id_token,this.session_state=n.session_state,this.access_token=n.access_token,this.token_type=n.token_type,this.scope=n.scope,this.profile=void 0,this.expires_in=n.expires_in}return n(e,[{key:"expires_in",get:function(){if(this.expires_at){var e=parseInt(Date.now()/1e3);return this.expires_at-e}},set:function(e){var t=parseInt(e);if("number"==typeof t&&t>0){var r=parseInt(Date.now()/1e3);this.expires_at=r+t}}},{key:"expired",get:function(){var e=this.expires_in;if(void 0!==e)return e<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf("openid")>=0||!!this.id_token}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignoutRequest=void 0;var n=r(0),i=r(3),o=r(9);t.SignoutRequest=function e(t){var r=t.url,s=t.id_token_hint,a=t.post_logout_redirect_uri,c=t.data,l=t.extraQueryParams,u=t.request_type;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!r)throw n.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var d in s&&(r=i.UrlUtility.addQueryParam(r,"id_token_hint",s)),a&&(r=i.UrlUtility.addQueryParam(r,"post_logout_redirect_uri",a),c&&(this.state=new o.State({data:c,request_type:u}),r=i.UrlUtility.addQueryParam(r,"state",this.state.id))),l)r=i.UrlUtility.addQueryParam(r,d,l[d]);this.url=r}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignoutResponse=void 0;var n=r(3);t.SignoutResponse=function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var r=n.UrlUtility.parseUrlFragment(t,"?");this.error=r.error,this.error_description=r.error_description,this.error_uri=r.error_uri,this.state=r.state}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InMemoryWebStorage=void 0;var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:l.SilentRenewService,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:u.SessionMonitor,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:h.TokenRevocationClient,d=arguments.length>4&&void 0!==arguments[4]?arguments[4]:f.TokenClient,g=arguments.length>5&&void 0!==arguments[5]?arguments[5]:p.JoseUtil;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,t),r instanceof s.UserManagerSettings||(r=new s.UserManagerSettings(r));var y=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r));return y._events=new c.UserManagerEvents(r),y._silentRenewService=new n(y),y.settings.automaticSilentRenew&&(i.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),y.startSilentRenew()),y.settings.monitorSession&&(i.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),y._sessionMonitor=new o(y)),y._tokenRevocationClient=new a(y._settings),y._tokenClient=new d(y._settings),y._joseUtil=g,y}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.getUser=function(){var e=this;return this._loadUser().then((function(t){return t?(i.Log.info("UserManager.getUser: user loaded"),e._events.load(t,!1),t):(i.Log.info("UserManager.getUser: user not found in storage"),null)}))},t.prototype.removeUser=function(){var e=this;return this.storeUser(null).then((function(){i.Log.info("UserManager.removeUser: user removed from storage"),e._events.unload()}))},t.prototype.signinRedirect=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type="si:r";var t={useReplaceToNavigate:e.useReplaceToNavigate};return this._signinStart(e,this._redirectNavigator,t).then((function(){i.Log.info("UserManager.signinRedirect: successful")}))},t.prototype.signinRedirectCallback=function(e){return this._signinEnd(e||this._redirectNavigator.url).then((function(e){return e.profile&&e.profile.sub?i.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinRedirectCallback: no sub"),e}))},t.prototype.signinPopup=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type="si:p";var t=e.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return t?(e.redirect_uri=t,e.display="popup",this._signin(e,this._popupNavigator,{startUrl:t,popupWindowFeatures:e.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:e.popupWindowTarget||this.settings.popupWindowTarget}).then((function(e){return e&&(e.profile&&e.profile.sub?i.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinPopup: no sub")),e}))):(i.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},t.prototype.signinPopupCallback=function(e){return this._signinCallback(e,this._popupNavigator).then((function(e){return e&&(e.profile&&e.profile.sub?i.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinPopupCallback: no sub")),e})).catch((function(e){i.Log.error(e.message)}))},t.prototype.signinSilent=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=Object.assign({},t),this._loadUser().then((function(r){return r&&r.refresh_token?(t.refresh_token=r.refresh_token,e._useRefreshToken(t)):(t.request_type="si:s",t.id_token_hint=t.id_token_hint||e.settings.includeIdTokenInSilentRenew&&r&&r.id_token,r&&e._settings.validateSubOnSilentRenew&&(i.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",r.profile.sub),t.current_sub=r.profile.sub),e._signinSilentIframe(t))}))},t.prototype._useRefreshToken=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this._tokenClient.exchangeRefreshToken(t).then((function(t){return t?t.access_token?e._loadUser().then((function(r){if(r){var n=Promise.resolve();return t.id_token&&(n=e._validateIdTokenFromTokenRefreshToken(r.profile,t.id_token)),n.then((function(){return i.Log.debug("UserManager._useRefreshToken: refresh token response success"),r.id_token=t.id_token||r.id_token,r.access_token=t.access_token,r.refresh_token=t.refresh_token||r.refresh_token,r.expires_in=t.expires_in,e.storeUser(r).then((function(){return e._events.load(r),r}))}))}return null})):(i.Log.error("UserManager._useRefreshToken: No access token returned from token endpoint"),Promise.reject("No access token returned from token endpoint")):(i.Log.error("UserManager._useRefreshToken: No response returned from token endpoint"),Promise.reject("No response returned from token endpoint"))}))},t.prototype._validateIdTokenFromTokenRefreshToken=function(e,t){var r=this;return this._metadataService.getIssuer().then((function(n){return r.settings.getEpochTime().then((function(o){return r._joseUtil.validateJwtAttributes(t,n,r._settings.client_id,r._settings.clockSkew,o).then((function(t){return t?t.sub!==e.sub?(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: sub in id_token does not match current sub"),Promise.reject(new Error("sub in id_token does not match current sub"))):t.auth_time&&t.auth_time!==e.auth_time?(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: auth_time in id_token does not match original auth_time"),Promise.reject(new Error("auth_time in id_token does not match original auth_time"))):t.azp&&t.azp!==e.azp?(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp in id_token does not match original azp"),Promise.reject(new Error("azp in id_token does not match original azp"))):!t.azp&&e.azp?(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp not in id_token, but present in original id_token"),Promise.reject(new Error("azp not in id_token, but present in original id_token"))):void 0:(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token"),Promise.reject(new Error("Failed to validate id_token")))}))}))}))},t.prototype._signinSilentIframe=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return t?(e.redirect_uri=t,e.prompt=e.prompt||"none",this._signin(e,this._iframeNavigator,{startUrl:t,silentRequestTimeout:e.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(e){return e&&(e.profile&&e.profile.sub?i.Log.info("UserManager.signinSilent: successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinSilent: no sub")),e}))):(i.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},t.prototype.signinSilentCallback=function(e){return this._signinCallback(e,this._iframeNavigator).then((function(e){return e&&(e.profile&&e.profile.sub?i.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinSilentCallback: no sub")),e}))},t.prototype.signinCallback=function(e){var t=this;return this.readSigninResponseState(e).then((function(r){var n=r.state;return r.response,"si:r"===n.request_type?t.signinRedirectCallback(e):"si:p"===n.request_type?t.signinPopupCallback(e):"si:s"===n.request_type?t.signinSilentCallback(e):Promise.reject(new Error("invalid response_type in state"))}))},t.prototype.signoutCallback=function(e,t){var r=this;return this.readSignoutResponseState(e).then((function(n){var i=n.state,o=n.response;return i?"so:r"===i.request_type?r.signoutRedirectCallback(e):"so:p"===i.request_type?r.signoutPopupCallback(e,t):Promise.reject(new Error("invalid response_type in state")):o}))},t.prototype.querySessionStatus=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(t=Object.assign({},t)).request_type="si:s";var r=t.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return r?(t.redirect_uri=r,t.prompt="none",t.response_type=t.response_type||this.settings.query_status_response_type,t.scope=t.scope||"openid",t.skipUserInfo=!0,this._signinStart(t,this._iframeNavigator,{startUrl:r,silentRequestTimeout:t.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(t){return e.processSigninResponse(t.url).then((function(e){if(i.Log.debug("UserManager.querySessionStatus: got signin response"),e.session_state&&e.profile.sub)return i.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",e.profile.sub),{session_state:e.session_state,sub:e.profile.sub,sid:e.profile.sid};i.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(t){if(t.session_state&&e.settings.monitorAnonymousSession&&("login_required"==t.message||"consent_required"==t.message||"interaction_required"==t.message||"account_selection_required"==t.message))return i.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:t.session_state};throw t}))}))):(i.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},t.prototype._signin=function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this._signinStart(e,t,n).then((function(t){return r._signinEnd(t.url,e)}))},t.prototype._signinStart=function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return t.prepare(n).then((function(t){return i.Log.debug("UserManager._signinStart: got navigator window handle"),r.createSigninRequest(e).then((function(e){return i.Log.debug("UserManager._signinStart: got signin request"),n.url=e.url,n.id=e.state.id,t.navigate(n)})).catch((function(e){throw t.close&&(i.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),t.close()),e}))}))},t.prototype._signinEnd=function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.processSigninResponse(e).then((function(e){i.Log.debug("UserManager._signinEnd: got signin response");var n=new a.User(e);if(r.current_sub){if(r.current_sub!==n.profile.sub)return i.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",n.profile.sub),Promise.reject(new Error("login_required"));i.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return t.storeUser(n).then((function(){return i.Log.debug("UserManager._signinEnd: user stored"),t._events.load(n),n}))}))},t.prototype._signinCallback=function(e,t){i.Log.debug("UserManager._signinCallback");var r="query"===this._settings.response_mode||!this._settings.response_mode&&d.SigninRequest.isCode(this._settings.response_type)?"?":"#";return t.callback(e,void 0,r)},t.prototype.signoutRedirect=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type="so:r";var t=e.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;t&&(e.post_logout_redirect_uri=t);var r={useReplaceToNavigate:e.useReplaceToNavigate};return this._signoutStart(e,this._redirectNavigator,r).then((function(){i.Log.info("UserManager.signoutRedirect: successful")}))},t.prototype.signoutRedirectCallback=function(e){return this._signoutEnd(e||this._redirectNavigator.url).then((function(e){return i.Log.info("UserManager.signoutRedirectCallback: successful"),e}))},t.prototype.signoutPopup=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type="so:p";var t=e.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return e.post_logout_redirect_uri=t,e.display="popup",e.post_logout_redirect_uri&&(e.state=e.state||{}),this._signout(e,this._popupNavigator,{startUrl:t,popupWindowFeatures:e.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:e.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){i.Log.info("UserManager.signoutPopup: successful")}))},t.prototype.signoutPopupCallback=function(e,t){return void 0===t&&"boolean"==typeof e&&(t=e,e=null),this._popupNavigator.callback(e,t,"?").then((function(){i.Log.info("UserManager.signoutPopupCallback: successful")}))},t.prototype._signout=function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this._signoutStart(e,t,n).then((function(e){return r._signoutEnd(e.url)}))},t.prototype._signoutStart=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return arguments[1].prepare(r).then((function(n){return i.Log.debug("UserManager._signoutStart: got navigator window handle"),t._loadUser().then((function(o){return i.Log.debug("UserManager._signoutStart: loaded current user from storage"),(t._settings.revokeAccessTokenOnSignout?t._revokeInternal(o):Promise.resolve()).then((function(){var s=e.id_token_hint||o&&o.id_token;return s&&(i.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),e.id_token_hint=s),t.removeUser().then((function(){return i.Log.debug("UserManager._signoutStart: user removed, creating signout request"),t.createSignoutRequest(e).then((function(e){return i.Log.debug("UserManager._signoutStart: got signout request"),r.url=e.url,e.state&&(r.id=e.state.id),n.navigate(r)}))}))}))})).catch((function(e){throw n.close&&(i.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),n.close()),e}))}))},t.prototype._signoutEnd=function(e){return this.processSignoutResponse(e).then((function(e){return i.Log.debug("UserManager._signoutEnd: got signout response"),e}))},t.prototype.revokeAccessToken=function(){var e=this;return this._loadUser().then((function(t){return e._revokeInternal(t,!0).then((function(r){if(r)return i.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),t.access_token=null,t.refresh_token=null,t.expires_at=null,t.token_type=null,e.storeUser(t).then((function(){i.Log.debug("UserManager.revokeAccessToken: user stored"),e._events.load(t)}))}))})).then((function(){i.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},t.prototype._revokeInternal=function(e,t){var r=this;if(e){var n=e.access_token,o=e.refresh_token;return this._revokeAccessTokenInternal(n,t).then((function(e){return r._revokeRefreshTokenInternal(o,t).then((function(t){return e||t||i.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),e||t}))}))}return Promise.resolve(!1)},t.prototype._revokeAccessTokenInternal=function(e,t){return!e||e.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(e,t).then((function(){return!0}))},t.prototype._revokeRefreshTokenInternal=function(e,t){return e?this._tokenRevocationClient.revoke(e,t,"refresh_token").then((function(){return!0})):Promise.resolve(!1)},t.prototype.startSilentRenew=function(){this._silentRenewService.start()},t.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},t.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then((function(e){return e?(i.Log.debug("UserManager._loadUser: user storageString loaded"),a.User.fromStorageString(e)):(i.Log.debug("UserManager._loadUser: no user storageString"),null)}))},t.prototype.storeUser=function(e){if(e){i.Log.debug("UserManager.storeUser: storing user");var t=e.toStorageString();return this._userStore.set(this._userStoreKey,t)}return i.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},n(t,[{key:"_redirectNavigator",get:function(){return this.settings.redirectNavigator}},{key:"_popupNavigator",get:function(){return this.settings.popupNavigator}},{key:"_iframeNavigator",get:function(){return this.settings.iframeNavigator}},{key:"_userStore",get:function(){return this.settings.userStore}},{key:"events",get:function(){return this._events}},{key:"_userStoreKey",get:function(){return"user:"+this.settings.authority+":"+this.settings.client_id}}]),t}(o.OidcClient)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserManagerSettings=void 0;var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=r.popup_redirect_uri,i=r.popup_post_logout_redirect_uri,d=r.popupWindowFeatures,h=r.popupWindowTarget,f=r.silent_redirect_uri,p=r.silentRequestTimeout,g=r.automaticSilentRenew,y=void 0!==g&&g,m=r.validateSubOnSilentRenew,v=void 0!==m&&m,b=r.includeIdTokenInSilentRenew,w=void 0===b||b,_=r.monitorSession,S=void 0===_||_,E=r.monitorAnonymousSession,A=void 0!==E&&E,R=r.checkSessionInterval,I=void 0===R?2e3:R,T=r.stopCheckSessionOnError,x=void 0===T||T,P=r.query_status_response_type,C=r.revokeAccessTokenOnSignout,k=void 0!==C&&C,O=r.accessTokenExpiringNotificationTime,F=void 0===O?60:O,N=r.redirectNavigator,D=void 0===N?new o.RedirectNavigator:N,L=r.popupNavigator,U=void 0===L?new s.PopupNavigator:L,j=r.iframeNavigator,M=void 0===j?new a.IFrameNavigator:j,B=r.userStore,H=void 0===B?new c.WebStorageStateStore({store:l.Global.sessionStorage}):B;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var W=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,arguments[0]));return W._popup_redirect_uri=n,W._popup_post_logout_redirect_uri=i,W._popupWindowFeatures=d,W._popupWindowTarget=h,W._silent_redirect_uri=f,W._silentRequestTimeout=p,W._automaticSilentRenew=y,W._validateSubOnSilentRenew=v,W._includeIdTokenInSilentRenew=w,W._accessTokenExpiringNotificationTime=F,W._monitorSession=S,W._monitorAnonymousSession=A,W._checkSessionInterval=I,W._stopCheckSessionOnError=x,P?W._query_status_response_type=P:arguments[0]&&arguments[0].response_type?W._query_status_response_type=u.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":W._query_status_response_type="id_token",W._revokeAccessTokenOnSignout=k,W._redirectNavigator=D,W._popupNavigator=U,W._iframeNavigator=M,W._userStore=H,W}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),n(t,[{key:"popup_redirect_uri",get:function(){return this._popup_redirect_uri}},{key:"popup_post_logout_redirect_uri",get:function(){return this._popup_post_logout_redirect_uri}},{key:"popupWindowFeatures",get:function(){return this._popupWindowFeatures}},{key:"popupWindowTarget",get:function(){return this._popupWindowTarget}},{key:"silent_redirect_uri",get:function(){return this._silent_redirect_uri}},{key:"silentRequestTimeout",get:function(){return this._silentRequestTimeout}},{key:"automaticSilentRenew",get:function(){return this._automaticSilentRenew}},{key:"validateSubOnSilentRenew",get:function(){return this._validateSubOnSilentRenew}},{key:"includeIdTokenInSilentRenew",get:function(){return this._includeIdTokenInSilentRenew}},{key:"accessTokenExpiringNotificationTime",get:function(){return this._accessTokenExpiringNotificationTime}},{key:"monitorSession",get:function(){return this._monitorSession}},{key:"monitorAnonymousSession",get:function(){return this._monitorAnonymousSession}},{key:"checkSessionInterval",get:function(){return this._checkSessionInterval}},{key:"stopCheckSessionOnError",get:function(){return this._stopCheckSessionOnError}},{key:"query_status_response_type",get:function(){return this._query_status_response_type}},{key:"revokeAccessTokenOnSignout",get:function(){return this._revokeAccessTokenOnSignout}},{key:"redirectNavigator",get:function(){return this._redirectNavigator}},{key:"popupNavigator",get:function(){return this._popupNavigator}},{key:"iframeNavigator",get:function(){return this._iframeNavigator}},{key:"userStore",get:function(){return this._userStore}}]),t}(i.OidcClientSettings)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedirectNavigator=void 0;var n=function(){function e(e,t){for(var r=0;r1&&void 0!==arguments[1])||arguments[1];n.Log.debug("UserManagerEvents.load"),e.prototype.load.call(this,t),r&&this._userLoaded.raise(t)},t.prototype.unload=function(){n.Log.debug("UserManagerEvents.unload"),e.prototype.unload.call(this),this._userUnloaded.raise()},t.prototype.addUserLoaded=function(e){this._userLoaded.addHandler(e)},t.prototype.removeUserLoaded=function(e){this._userLoaded.removeHandler(e)},t.prototype.addUserUnloaded=function(e){this._userUnloaded.addHandler(e)},t.prototype.removeUserUnloaded=function(e){this._userUnloaded.removeHandler(e)},t.prototype.addSilentRenewError=function(e){this._silentRenewError.addHandler(e)},t.prototype.removeSilentRenewError=function(e){this._silentRenewError.removeHandler(e)},t.prototype._raiseSilentRenewError=function(e){n.Log.debug("UserManagerEvents._raiseSilentRenewError",e.message),this._silentRenewError.raise(e)},t.prototype.addUserSignedIn=function(e){this._userSignedIn.addHandler(e)},t.prototype.removeUserSignedIn=function(e){this._userSignedIn.removeHandler(e)},t.prototype._raiseUserSignedIn=function(){n.Log.debug("UserManagerEvents._raiseUserSignedIn"),this._userSignedIn.raise()},t.prototype.addUserSignedOut=function(e){this._userSignedOut.addHandler(e)},t.prototype.removeUserSignedOut=function(e){this._userSignedOut.removeHandler(e)},t.prototype._raiseUserSignedOut=function(){n.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise()},t.prototype.addUserSessionChanged=function(e){this._userSessionChanged.addHandler(e)},t.prototype.removeUserSessionChanged=function(e){this._userSessionChanged.removeHandler(e)},t.prototype._raiseUserSessionChanged=function(){n.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise()},t}(i.AccessTokenEvents)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timer=void 0;var n=function(){function e(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:o.Global.timer,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var s=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r));return s._timer=n,s._nowFunc=i||function(){return Date.now()/1e3},s}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.init=function(e){e<=0&&(e=1),e=parseInt(e);var t=this.now+e;if(this.expiration===t&&this._timerHandle)i.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);else{this.cancel(),i.Log.debug("Timer.init timer "+this._name+" for duration:",e),this._expiration=t;var r=5;e{var r,i;await this.sessionInfoManager.clear(e.sessionId);const o=null!==(r=e.redirectUrl)&&void 0!==r?r:s.normalizeCallbackUrl(window.location.href);if(!n.isValidRedirectUrl(o))throw new Error(`${o} is not a valid redirect URL, it is either a malformed IRI, includes a hash fragment, or reserved query parameters ('code' or 'state').`);await this.loginHandler.handle({...e,redirectUrl:o,clientName:null!==(i=e.clientName)&&void 0!==i?i:e.clientId,eventEmitter:t})},this.validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return void 0===t||void 0===t.clientAppId||void 0===t.issuer?null:t},this.handleIncomingRedirect=async(e,t)=>{try{const r=await this.redirectHandler.handle(e,t);return this.fetch=r.fetch.bind(window),this.boundLogout=r.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:r.isLoggedIn,webId:r.webId,sessionId:r.sessionId,expirationDate:r.expirationDate}}catch(r){return await this.cleanUrlAfterRedirect(e),void t.emit(n.EVENTS.ERROR,"redirect",r)}}}async cleanUrlAfterRedirect(e){const t=n.removeOpenIdParams(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise((e=>{setTimeout((()=>e()),1)}))}}function u(e){return"string"==typeof e.oidcIssuer}function d(e){return"string"==typeof e.redirectUrl}class h{constructor(e,t,r,n){this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=r,this.clientRegistrar=n,this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=r,this.clientRegistrar=n}async canHandle(e){return u(e)&&d(e)}async handle(e){if(!u(e))throw new n.ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!d(e))throw new n.ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),r=await n.handleRegistration(e,t,this.storageUtility,this.clientRegistrar),i={issuer:t.issuer,dpop:"dpop"===e.tokenType.toLowerCase(),...e,issuerConfiguration:t,client:r};return this.oidcHandler.handle(i)}}class f extends n.AuthorizationCodeWithPkceOidcHandlerBase{async handle(e){var t;const r={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl.toString(),post_logout_redirect_uri:e.redirectUrl.toString(),response_type:"code",scope:n.DEFAULT_SCOPES,filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:null!==(t=e.prompt)&&void 0!==t?t:"consent"},i=new s.OidcClient(r);try{const t=await i.createSigninRequest();return await this.handleRedirect({oidcLoginOptions:e,state:t.state._id,codeVerifier:t.state._code_verifier,targetUrl:t.url.toString()})}catch(e){console.error(e)}}}const p={issuer:{toKey:"issuer",convertToUrl:!0},authorization_endpoint:{toKey:"authorizationEndpoint",convertToUrl:!0},token_endpoint:{toKey:"tokenEndpoint",convertToUrl:!0},userinfo_endpoint:{toKey:"userinfoEndpoint",convertToUrl:!0},jwks_uri:{toKey:"jwksUri",convertToUrl:!0},registration_endpoint:{toKey:"registrationEndpoint",convertToUrl:!0},end_session_endpoint:{toKey:"endSessionEndpoint",convertToUrl:!0},scopes_supported:{toKey:"scopesSupported"},response_types_supported:{toKey:"responseTypesSupported"},response_modes_supported:{toKey:"responseModesSupported"},grant_types_supported:{toKey:"grantTypesSupported"},acr_values_supported:{toKey:"acrValuesSupported"},subject_types_supported:{toKey:"subjectTypesSupported"},id_token_signing_alg_values_supported:{toKey:"idTokenSigningAlgValuesSupported"},id_token_encryption_alg_values_supported:{toKey:"idTokenEncryptionAlgValuesSupported"},id_token_encryption_enc_values_supported:{toKey:"idTokenEncryptionEncValuesSupported"},userinfo_signing_alg_values_supported:{toKey:"userinfoSigningAlgValuesSupported"},userinfo_encryption_alg_values_supported:{toKey:"userinfoEncryptionAlgValuesSupported"},userinfo_encryption_enc_values_supported:{toKey:"userinfoEncryptionEncValuesSupported"},request_object_signing_alg_values_supported:{toKey:"requestObjectSigningAlgValuesSupported"},request_object_encryption_alg_values_supported:{toKey:"requestObjectEncryptionAlgValuesSupported"},request_object_encryption_enc_values_supported:{toKey:"requestObjectEncryptionEncValuesSupported"},token_endpoint_auth_methods_supported:{toKey:"tokenEndpointAuthMethodsSupported"},token_endpoint_auth_signing_alg_values_supported:{toKey:"tokenEndpointAuthSigningAlgValuesSupported"},display_values_supported:{toKey:"displayValuesSupported"},claim_types_supported:{toKey:"claimTypesSupported"},claims_supported:{toKey:"claimsSupported"},service_documentation:{toKey:"serviceDocumentation"},claims_locales_supported:{toKey:"claimsLocalesSupported"},ui_locales_supported:{toKey:"uiLocalesSupported"},claims_parameter_supported:{toKey:"claimsParameterSupported"},request_parameter_supported:{toKey:"requestParameterSupported"},request_uri_parameter_supported:{toKey:"requestUriParameterSupported"},require_request_uri_registration:{toKey:"requireRequestUriRegistration"},op_policy_uri:{toKey:"opPolicyUri",convertToUrl:!0},op_tos_uri:{toKey:"opTosUri",convertToUrl:!0}};class g{constructor(e){this.storageUtility=e,this.storageUtility=e}static getLocalStorageKey(e){return`issuerConfig:${e}`}async fetchConfig(e){let t;const r=new URL(".well-known/openid-configuration",e.endsWith("/")?e:`${e}/`).href,i=await a.fetch.call(globalThis,r);try{t=function(e){const t={};return Object.keys(e).forEach((r=>{p[r]&&(t[p[r].toKey]=e[r])})),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(await i.json())}catch(t){throw new n.ConfigurationError(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return await this.storageUtility.set(g.getLocalStorageKey(e),JSON.stringify(t)),t}}class y extends n.SessionInfoManagerBase{async get(e){const[t,r,i,o,s,a,c,l]=await Promise.all([this.storageUtility.getForUser(e,"isLoggedIn",{secure:!0}),this.storageUtility.getForUser(e,"webId",{secure:!0}),this.storageUtility.getForUser(e,"clientId",{secure:!1}),this.storageUtility.getForUser(e,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e,"redirectUrl",{secure:!1}),this.storageUtility.getForUser(e,"refreshToken",{secure:!0}),this.storageUtility.getForUser(e,"issuer",{secure:!1}),this.storageUtility.getForUser(e,"tokenType",{secure:!1})]);if("string"!=typeof s||n.isValidRedirectUrl(s)){if(void 0!==l&&!n.isSupportedTokenType(l))throw new Error(`Tokens of type [${l}] are not supported.`);if(void 0!==i||void 0!==t||void 0!==r||void 0!==a)return{sessionId:e,webId:r,isLoggedIn:"true"===t,redirectUrl:s,refreshToken:a,issuer:c,clientAppId:i,clientAppSecret:o,tokenType:null!=l?l:"DPoP"}}else await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})])}async clear(e){return async function(e,t){await n.clear(e,t),await s.clearOidcPersistentStorage()}(e,this.storageUtility)}}class m{async canHandle(e){try{return new URL(e),!0}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e){return n.getUnauthenticatedSession()}}const v=(...e)=>a.fetch.call(globalThis,...e);class b{constructor(e,t,r,n,i){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=r,this.clientRegistrar=n,this.tokerRefresher=i,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=r,this.clientRegistrar=n,this.tokerRefresher=i}async canHandle(e){try{const t=new URL(e);return null!==t.searchParams.get("code")&&null!==t.searchParams.get("state")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(!await this.canHandle(e))throw new Error(`AuthCodeRedirectHandler cannot handle [${e}]: it is missing one of [code, state].`);const r=new URL(e),i=r.searchParams.get("state"),o=await this.storageUtility.getForUser(i,"sessionId",{errorIfNull:!0}),{issuerConfig:a,codeVerifier:c,redirectUrl:l,dpop:u}=await n.loadOidcContextFromStorage(o,this.storageUtility,this.issuerConfigFetcher),d=r.searchParams.get("iss");if("string"==typeof d&&d!==a.issuer)throw new Error(`The value of the iss parameter (${d}) does not match the issuer identifier of the authorization server (${a.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(void 0===c)throw new Error(`The code verifier for session ${o} is missing from storage.`);if(void 0===l)throw new Error(`The redirect URL for session ${o} is missing from storage.`);const h=await this.clientRegistrar.getClient({sessionId:o},a);let f;const p=Date.now();let g;u?(f=await s.getDpopToken(a,h,{grantType:"authorization_code",code:r.searchParams.get("code"),codeVerifier:c,redirectUrl:l}),window.localStorage.removeItem(`oidc.${i}`)):f=await s.getBearerToken(r.toString()),void 0!==f.refreshToken&&(g={sessionId:o,refreshToken:f.refreshToken,tokenRefresher:this.tokerRefresher});const y=await n.buildAuthenticatedFetch(v,f.accessToken,{dpopKey:f.dpopKey,refreshOptions:g,eventEmitter:t,expiresIn:f.expiresIn});await this.storageUtility.setForUser(o,{webId:f.webId,isLoggedIn:"true"},{secure:!0});const m=await this.sessionInfoManager.get(o);if(!m)throw new Error(`Could not retrieve session: [${o}].`);return Object.assign(m,{fetch:y,getLogoutUrl:n.maybeBuildRpInitiatedLogout({idTokenHint:f.idToken,endSessionEndpoint:a.endSessionEndpoint}),expirationDate:"number"==typeof f.expiresIn?p+1e3*f.expiresIn:void 0})}}class w extends n.AggregateHandler{constructor(e){super(e)}}class _{get storage(){return window.localStorage}async get(e){return this.storage.getItem(e)||void 0}async set(e,t){this.storage.setItem(e,t)}async delete(e){this.storage.removeItem(e)}}class S{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class E{constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[r,n]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1})]);if(r)return{clientId:r,clientSecret:n,clientType:"dynamic"};try{const r=await s.registerClient(e,t),n={clientId:r.clientId};return r.clientSecret&&(n.clientSecret=r.clientSecret),r.idTokenSignedResponseAlg&&(n.idTokenSignedResponseAlg=r.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,n,{secure:!1}),r}catch(e){throw new Error(`Client registration failed: [${e}]`)}}}class A{async canHandle(e){try{return new URL(e).searchParams.has("error")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(void 0!==t){const r=new URL(e),i=r.searchParams.get("error"),o=r.searchParams.get("error_description");t.emit(n.EVENTS.ERROR,i,o)}return n.getUnauthenticatedSession()}}class R{constructor(e,t,r){this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=r,this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=r}async refresh(e,t,r,i){const o=await n.loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),a=await this.clientRegistrar.getClient({sessionId:e},o.issuerConfig);if(void 0===t)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(o.dpop&&void 0===r)throw new Error(`For session [${e}], the key bound to the DPoP access token must be provided to refresh said access token.`);const c=await s.refresh(t,o.issuerConfig,a,r);return void 0!==c.refreshToken&&(null==i||i.emit(n.EVENTS.NEW_REFRESH_TOKEN,c.refreshToken),await this.storageUtility.setForUser(e,{refreshToken:c.refreshToken})),c}}function I(e){const t=new n.InMemoryStorage,r=e.secureStorage||t,i=e.insecureStorage||new _,o=new c(r,i),s=new g(o),a=new E(o),u=new y(o),d=new R(o,s,a),p=new S,v=new h(o,new f(o,p),s,a),I=new w([new A,new b(o,u,s,a,d),new m]);return new l(v,I,new n.IWaterfallLogoutHandler(u,p),u,s)}const T=`${n.SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`,x=`${n.SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;class P extends o{constructor(e={},t=void 0){super(),this.tokenRequestInProgress=!1,this.login=async e=>{var t;return await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:null!==(t=e.tokenType)&&void 0!==t?t:"DPoP"},this.events),new Promise((()=>{}))},this.fetch=(e,t)=>this.clientAuthentication.fetch(e,t),this.internalLogout=async(e,t)=>{window.localStorage.removeItem(T),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(n.EVENTS.LOGOUT)},this.logout=async e=>this.internalLogout(!0,e),this.handleIncomingRedirect=async(e={})=>{var t;if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const r="string"==typeof e?{url:e}:e,i=null!==(t=r.url)&&void 0!==t?t:window.location.href;this.tokenRequestInProgress=!0;const o=await this.clientAuthentication.handleIncomingRedirect(i,this.events);if(function(e){return!!(null==e?void 0:e.isLoggedIn)}(o)){this.setSessionInfo(o);const e=window.localStorage.getItem(x);null===e?this.events.emit(n.EVENTS.LOGIN):(window.localStorage.removeItem(x),this.events.emit(n.EVENTS.SESSION_RESTORED,e))}else if(!0===r.restorePreviousSession){const e=window.localStorage.getItem(T);if(null!==e){const t=await async function(e,t,r){var n;const i=await t.validateCurrentSession(e);return null!==i&&(window.localStorage.setItem(x,window.location.href),await t.login({sessionId:e,prompt:"none",oidcIssuer:i.issuer,redirectUrl:i.redirectUrl,clientId:i.clientAppId,clientSecret:i.clientAppSecret,tokenType:null!==(n=i.tokenType)&&void 0!==n?n:"DPoP"},r.events),!0)}(e,this.clientAuthentication,this);if(t)return new Promise((()=>{}))}}return this.tokenRequestInProgress=!1,o},this.events=new Proxy(this,n.buildProxyHandler(P.prototype,"events only implements ISessionEventListener")),e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=I({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage}):this.clientAuthentication=I({}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId}:this.info={sessionId:null!=t?t:i.v4(),isLoggedIn:!1},this.events.on(n.EVENTS.LOGIN,(()=>window.localStorage.setItem(T,this.info.sessionId))),this.events.on(n.EVENTS.SESSION_EXPIRED,(()=>this.internalLogout(!1))),this.events.on(n.EVENTS.ERROR,(()=>this.internalLogout(!1)))}onLogin(e){this.events.on(n.EVENTS.LOGIN,e)}onLogout(e){this.events.on(n.EVENTS.LOGOUT,e)}onError(e){this.events.on(n.EVENTS.ERROR,e)}onSessionRestore(e){this.events.on(n.EVENTS.SESSION_RESTORED,e)}onSessionExpiration(e){this.events.on(n.EVENTS.SESSION_EXPIRED,e)}setSessionInfo(e){this.info.isLoggedIn=e.isLoggedIn,this.info.webId=e.webId,this.info.sessionId=e.sessionId,this.info.expirationDate=e.expirationDate,this.events.on(n.EVENTS.SESSION_EXTENDED,(e=>{this.info.expirationDate=Date.now()+1e3*e}))}}let C;function k(){return void 0===C&&(C=new P),C}Object.defineProperty(t,"ConfigurationError",{enumerable:!0,get:function(){return n.ConfigurationError}}),Object.defineProperty(t,"EVENTS",{enumerable:!0,get:function(){return n.EVENTS}}),Object.defineProperty(t,"InMemoryStorage",{enumerable:!0,get:function(){return n.InMemoryStorage}}),Object.defineProperty(t,"NotImplementedError",{enumerable:!0,get:function(){return n.NotImplementedError}}),t.Session=P,t.events=()=>k().events,t.fetch=(...e)=>k().fetch(...e),t.getClientAuthenticationWithDependencies=I,t.getDefaultSession=k,t.handleIncomingRedirect=(...e)=>k().handleIncomingRedirect(...e),t.login=(...e)=>k().login(...e),t.logout=(...e)=>k().logout(...e),t.onLogin=(...e)=>k().onLogin(...e),t.onLogout=(...e)=>k().onLogout(...e),t.onSessionRestore=(...e)=>k().onSessionRestore(...e)},4667:function(e,t,r){"use strict";var n=r(7007),i=r(5914),o=r(6438),s=r(2831);const a=["ES256","RS256"],c={ERROR:"error",LOGIN:"login",LOGOUT:"logout",NEW_REFRESH_TOKEN:"newRefreshToken",SESSION_EXPIRED:"sessionExpired",SESSION_EXTENDED:"sessionExtended",SESSION_RESTORED:"sessionRestore",TIMEOUT_SET:"timeoutSet"},l=["openid","offline_access","webid"].join(" ");async function u(e,t){const r=await i.fetch.call(globalThis,e);if(200!==r.status)throw new Error(`Could not fetch JWKS for [${t}] at [${e}]: ${r.status} ${r.statusText}`);let n;try{n=(await r.json()).keys[0]}catch(r){throw new Error(`Malformed JWKS for [${t}] at [${e}]: ${r.message}`)}return n}class d{constructor(e){this.sessionInfoManager=e,this.sessionInfoManager=e}async canHandle(){return!0}async handle(e){await this.sessionInfoManager.clear(e)}}class h{constructor(e){this.redirector=e,this.redirector=e}async canHandle(e,t){return"idp"===(null==t?void 0:t.logoutType)}async handle(e,t){if("idp"!==(null==t?void 0:t.logoutType))throw new Error("Attempting to call idp logout handler to perform app logout");if(void 0===t.toLogoutUrl)throw new Error("Cannot perform IDP logout. Did you log in using the OIDC authentication flow?");this.redirector.redirect(t.toLogoutUrl(t),{handleRedirect:t.handleRedirect})}}async function f(e,t){await Promise.all([t.deleteAllUserData(e,{secure:!1}),t.deleteAllUserData(e,{secure:!0})])}function p({endSessionEndpoint:e,idTokenHint:t,postLogoutRedirectUri:r,state:n}){const i=new URL(e);return void 0!==t&&i.searchParams.append("id_token_hint",t),void 0!==r&&(i.searchParams.append("post_logout_redirect_uri",r),void 0!==n&&i.searchParams.append("state",n)),i.toString()}function g(e){try{return new URL(e),!0}catch(e){return!1}}const y=(e,t)=>i.fetch.call(globalThis,e,t);class m{constructor(e,t){this.secureStorage=e,this.insecureStorage=t,this.secureStorage=e,this.insecureStorage=t}getKey(e){return`solidClientAuthenticationUser:${e}`}async getUserData(e,t){const r=await(t?this.secureStorage:this.insecureStorage).get(this.getKey(e));if(void 0===r)return{};try{return JSON.parse(r)}catch(n){throw new Error(`Data for user [${e}] in [${t?"secure":"unsecure"}] storage is corrupted - expected valid JSON, but got: ${r}`)}}async setUserData(e,t,r){await(r?this.secureStorage:this.insecureStorage).set(this.getKey(e),JSON.stringify(t))}async get(e,t){const r=await((null==t?void 0:t.secure)?this.secureStorage:this.insecureStorage).get(e);if(void 0===r&&(null==t?void 0:t.errorIfNull))throw new Error(`[${e}] is not stored`);return r}async set(e,t,r){return((null==r?void 0:r.secure)?this.secureStorage:this.insecureStorage).set(e,t)}async delete(e,t){return((null==t?void 0:t.secure)?this.secureStorage:this.insecureStorage).delete(e)}async getForUser(e,t,r){const n=await this.getUserData(e,null==r?void 0:r.secure);let i;if(n&&n[t]||(i=void 0),i=n[t],void 0===i&&(null==r?void 0:r.errorIfNull))throw new Error(`Field [${t}] for user [${e}] is not stored`);return i||void 0}async setForUser(e,t,r){let n;try{n=await this.getUserData(e,null==r?void 0:r.secure)}catch(e){n={}}await this.setUserData(e,{...n,...t},null==r?void 0:r.secure)}async deleteForUser(e,t,r){const n=await this.getUserData(e,null==r?void 0:r.secure);delete n[t],await this.setUserData(e,n,null==r?void 0:r.secure)}async deleteAllUserData(e,t){await((null==t?void 0:t.secure)?this.secureStorage:this.insecureStorage).delete(this.getKey(e))}}class v extends Error{constructor(e){super(e)}}class b extends Error{constructor(e){super(`[${e}] is not implemented`)}}class w extends Error{constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class _ extends Error{constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function S(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function E(e,t,r){return new o.SignJWT({htu:S(e),htm:t.toUpperCase(),jti:s.v4()}).setProtectedHeader({alg:a[0],jwk:r.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(r.privateKey,{})}async function A(e,t,r,n,o){return e(r,await async function(e,t,r,n){if(void 0!==r)return async function(e,t,r,n){var o;const s=new i.Headers(null==n?void 0:n.headers);return s.set("Authorization",`DPoP ${t}`),s.set("DPoP",await E(e,null!==(o=null==n?void 0:n.method)&&void 0!==o?o:"get",r)),{...n,headers:s}}(e,t,r,n);const o=new i.Headers(null==n?void 0:n.headers);return o.set("Authorization",`Bearer ${t}`),{...n,headers:o}}(r.toString(),t,o,n))}const R=e=>void 0!==e?e-5>0?e-5:e:600,I="getResponse",T={get:async(e,t)=>I,set:async(e,t)=>{},delete:async e=>{},getForUser:async(e,t,r)=>I,setForUser:async(e,t,r)=>{},deleteForUser:async(e,t,r)=>{},deleteAllUserData:async(e,t)=>{}},x=e=>{const t=e;return{get:async e=>{if(void 0!==t[e])return"string"==typeof t[e]?t[e]:JSON.stringify(t[e])},set:async(e,r)=>{t[e]=r},delete:async e=>{delete t[e]}}};t.AggregateHandler=class{constructor(e){this.handleables=e,this.handleables=e}async getProperHandler(e){const t=await Promise.all(this.handleables.map((t=>t.canHandle(...e))));for(let e=0;e{try{return JSON.stringify(e)}catch(t){return e.toString()}})).join(", ")}`)}},t.AuthorizationCodeWithPkceOidcHandlerBase=class{constructor(e,t){this.storageUtility=e,this.redirector=t,this.storageUtility=e,this.redirector=t}async canHandle(e){return!!(e.issuerConfiguration.grantTypesSupported&&e.issuerConfiguration.grantTypesSupported.indexOf("authorization_code")>-1)}async handleRedirect({oidcLoginOptions:e,state:t,codeVerifier:r,targetUrl:n}){await Promise.all([this.storageUtility.setForUser(t,{sessionId:e.sessionId}),this.storageUtility.setForUser(e.sessionId,{codeVerifier:r,issuer:e.issuer.toString(),redirectUrl:e.redirectUrl,dpop:e.dpop?"true":"false"})]),this.redirector.redirect(n,{handleRedirect:e.handleRedirect})}},t.ClientAuthentication=class{constructor(e,t,r,n,i){this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=n,this.issuerConfigFetcher=i,this.fetch=y,this.logout=async(e,t)=>{await this.logoutHandler.handle(e,"idp"===(null==t?void 0:t.logoutType)?{...t,toLogoutUrl:this.boundLogout}:t),this.fetch=y,delete this.boundLogout},this.getSessionInfo=async e=>this.sessionInfoManager.get(e),this.getAllSessionInfo=async()=>this.sessionInfoManager.getAll(),this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=n,this.issuerConfigFetcher=i}},t.ConfigurationError=v,t.DEFAULT_SCOPES=l,t.EVENTS=c,t.GeneralLogoutHandler=d,t.IRpLogoutHandler=h,t.IWaterfallLogoutHandler=class{constructor(e,t){this.handlers=[new d(e),new h(t)]}async canHandle(){return!0}async handle(e,t){for(const r of this.handlers)await r.canHandle(e,t)&&await r.handle(e,t)}},t.InMemoryStorage=class{constructor(){this.map={}}async get(e){return this.map[e]||void 0}async set(e,t){this.map[e]=t}async delete(e){delete this.map[e]}},t.InvalidResponseError=w,t.NotImplementedError=b,t.OidcProviderError=_,t.PREFERRED_SIGNING_ALG=a,t.REFRESH_BEFORE_EXPIRATION_SECONDS=5,t.SOLID_CLIENT_AUTHN_KEY_PREFIX="solidClientAuthn:",t.SessionInfoManagerBase=class{constructor(e){this.storageUtility=e,this.storageUtility=e}update(e,t){throw new Error("Not Implemented")}get(e){throw new Error("Not implemented")}async getAll(){throw new Error("Not implemented")}async clear(e){return f(e,this.storageUtility)}async register(e){throw new Error("Not implemented")}async getRegisteredSessionIdAll(){throw new Error("Not implemented")}async clearAll(){throw new Error("Not implemented")}},t.StorageUtility=m,t.StorageUtilityGetResponse=I,t.StorageUtilityMock=T,t.USER_SESSION_PREFIX="solidClientAuthenticationUser",t.buildAuthenticatedFetch=async function(e,t,r){var n;let i,o=t;const s=null==r?void 0:r.refreshOptions;if(void 0!==s){const e=async()=>{var t,n,a,l;try{const{accessToken:n,refreshToken:a,expiresIn:l}=await async function(e,t,r){var n;const i=await e.tokenRefresher.refresh(e.sessionId,e.refreshToken,t);return null==r||r.emit(c.SESSION_EXTENDED,null!==(n=i.expiresIn)&&void 0!==n?n:600),"string"==typeof i.refreshToken&&(null==r||r.emit(c.NEW_REFRESH_TOKEN,i.refreshToken)),{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn}}(s,r.dpopKey,r.eventEmitter);o=n,void 0!==a&&(s.refreshToken=a),clearTimeout(i),i=setTimeout(e,1e3*R(l)),null===(t=r.eventEmitter)||void 0===t||t.emit(c.TIMEOUT_SET,i)}catch(e){e instanceof _&&(null===(n=null==r?void 0:r.eventEmitter)||void 0===n||n.emit(c.ERROR,e.error,e.errorDescription),null===(a=null==r?void 0:r.eventEmitter)||void 0===a||a.emit(c.SESSION_EXPIRED)),e instanceof w&&e.missingFields.includes("access_token")&&(null===(l=null==r?void 0:r.eventEmitter)||void 0===l||l.emit(c.SESSION_EXPIRED))}};i=setTimeout(e,1e3*R(r.expiresIn)),null===(n=r.eventEmitter)||void 0===n||n.emit(c.TIMEOUT_SET,i)}else if(void 0!==r&&void 0!==r.eventEmitter){const e=setTimeout((()=>{r.eventEmitter.emit(c.SESSION_EXPIRED)}),1e3*R(r.expiresIn));r.eventEmitter.emit(c.TIMEOUT_SET,e)}return async(t,n)=>{let i=await A(e,o,t,n,null==r?void 0:r.dpopKey);const s=!i.ok&&(a=i.status,![401,403].includes(a));var a;return i.ok||s||i.url!==t&&void 0!==(null==r?void 0:r.dpopKey)&&(i=await A(e,o,i.url,n,r.dpopKey)),i}},t.buildProxyHandler=(e,t)=>({get(r,i,o){if(!Object.getOwnPropertyNames(n.EventEmitter).includes(i)&&Object.getOwnPropertyNames(e).includes(i))throw new Error(`${t}: [${i}] is not supported`);return Reflect.get(r,i,o)}}),t.clear=f,t.createDpopHeader=E,t.determineSigningAlg=function(e,t){var r;return null!==(r=t.find((t=>e.includes(t))))&&void 0!==r?r:null},t.fetchJwks=u,t.generateDpopKeyPair=async function(){const{privateKey:e,publicKey:t}=await o.generateKeyPair(a[0]),r={privateKey:e,publicKey:await o.exportJWK(t)};return[r.publicKey.alg]=a,r},t.getEndSessionUrl=p,t.getSessionIdFromOauthState=async function(e,t){return e.getForUser(t,"sessionId")},t.getUnauthenticatedSession=function(){return{isLoggedIn:!1,sessionId:s.v4(),fetch:(...e)=>i.fetch.call(globalThis,...e)}},t.getWebidFromTokenPayload=async function(e,t,r,n){const i=await u(t,r);let s;try{const{payload:t}=await o.jwtVerify(e,await o.importJWK(i),{issuer:r,audience:n});s=t}catch(e){throw new Error(`Token verification failed: ${e.stack}`)}if("string"==typeof s.webid)return s.webid;if("string"!=typeof s.sub)throw new Error(`The token ${JSON.stringify(s)} is invalid: it has no 'webid' claim and no 'sub' claim.`);try{return new URL(s.sub),s.sub}catch(e){throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${s.sub}] is invalid as a URL - error [${e}].`)}},t.handleRegistration=async function(e,t,r,n){const i=function(e,t){return void 0===e.clientId||g(e.clientId)?t.scopesSupported.includes("webid")&&void 0!==e.clientId&&g(e.clientId)?"solid-oidc":"dynamic":"static"}(e,t);return"dynamic"===i?n.getClient({sessionId:e.sessionId,clientName:e.clientName,redirectUrl:e.redirectUrl},t):(await r.setForUser(e.sessionId,{clientId:e.clientId}),e.clientSecret&&await r.setForUser(e.sessionId,{clientSecret:e.clientSecret}),e.clientName&&await r.setForUser(e.sessionId,{clientName:e.clientName}),{clientId:e.clientId,clientSecret:e.clientSecret,clientName:e.clientName,clientType:i})},t.isSupportedTokenType=function(e){return"string"==typeof e&&["DPoP","Bearer"].includes(e)},t.isValidRedirectUrl=function(e){try{const t=new URL(e),r=!t.searchParams.has("code")&&!t.searchParams.has("state"),n=""===t.hash;return r&&n}catch(e){return!1}},t.loadOidcContextFromStorage=async function(e,t,r){try{const[n,i,o,s]=await Promise.all([t.getForUser(e,"issuer",{errorIfNull:!0}),t.getForUser(e,"codeVerifier"),t.getForUser(e,"redirectUrl"),t.getForUser(e,"dpop",{errorIfNull:!0})]);return await t.deleteForUser(e,"codeVerifier"),{codeVerifier:i,redirectUrl:o,issuerConfig:await r.fetchConfig(n),dpop:"true"===s}}catch(t){throw new Error(`Failed to retrieve OIDC context from storage associated with session [${e}]: ${t}`)}},t.maybeBuildRpInitiatedLogout=function({endSessionEndpoint:e,idTokenHint:t}){if(void 0!==e)return function({state:r,postLogoutUrl:n}){return p({endSessionEndpoint:e,idTokenHint:t,state:r,postLogoutRedirectUri:n})}},t.mockStorage=x,t.mockStorageUtility=(e,t=!1)=>t?new m(x(e),x({})):new m(x({}),x(e)),t.removeOpenIdParams=function(e){const t=new URL(e);return t.searchParams.delete("state"),t.searchParams.delete("code"),t.searchParams.delete("error"),t.searchParams.delete("error_description"),t.searchParams.delete("iss"),t},t.saveSessionInfoToStorage=async function(e,t,r,n,i,s,a){void 0!==i&&await e.setForUser(t,{refreshToken:i},{secure:s}),void 0!==r&&await e.setForUser(t,{webId:r},{secure:s}),void 0!==n&&await e.setForUser(t,{isLoggedIn:n},{secure:s}),void 0!==a&&await e.setForUser(t,{publicKey:JSON.stringify(a.publicKey),privateKey:JSON.stringify(await o.exportJWK(a.privateKey))},{secure:s})}},4848:function(e,t,r){"use strict";var n=r(8690),i=r(2395),o=r(5914),s=r(2384),a=r(8518),c=r(4727),l=r(6565),u=r(2831);function d(e){return"object"==typeof e&&"object"==typeof e.internal_resourceInfo}function h(e){const t=e;return"object"==typeof t&&"object"==typeof t.internal_resourceInfo&&"object"==typeof t.internal_resourceInfo.linkedResources}function f(e){const t=e;return"object"==typeof t.internal_changeLog&&Array.isArray(t.internal_changeLog.additions)&&Array.isArray(t.internal_changeLog.deletions)}class p extends Error{}function g(e){return"string"==typeof e?e:e.value}const y=o.fetch.bind(globalThis);function m(e){var t,r,n,i,o;const a=null!==(r=null===(t=e.headers.get("Content-Type"))||void 0===t?void 0:t.split(";"))&&void 0!==r?r:[],c=a.length>0&&["text/turtle","application/ld+json"].includes(a[0]),l={sourceIri:e.url,isRawData:!c,contentLocation:null!==(n=e.headers.get("Content-Location"))&&void 0!==n?n:void 0,contentType:null!==(i=e.headers.get("Content-Type"))&&void 0!==i?i:void 0,linkedResources:{},location:null!==(o=e.headers.get("Location"))&&void 0!==o?o:void 0},u=e.headers.get("Link");if(u){const e=s.parse(u),t=e.get("rel","acl");1===t.length&&(l.aclUrl=new URL(t[0].uri,l.sourceIri).href),l.linkedResources=e.refs.reduce(((e,t)=>{var r,n;return null!==(r=e[n=t.rel])&&void 0!==r||(e[n]=[]),e[t.rel].push(new URL(t.uri,l.sourceIri).href),e}),l.linkedResources)}const d=e.headers.get("WAC-Allow");return d&&(l.permissions=function(e){function t(e){const t=e.split(" ");return t.includes("write")?{read:t.includes("read"),append:!0,write:!0,control:t.includes("control")}:{read:t.includes("read"),append:t.includes("append"),write:!1,control:t.includes("control")}}function r(e,t){const r=e.split(",").map((e=>e.split("="))).filter((e=>2===e.length&&e[0].trim()===t));if(1!==r.length)return"";const n=r[0][1].trim();return'"'!==n.charAt(0)||'"'!==n.charAt(n.length-1)?"":n.substring(1,n.length-1)}return{user:t(r(e,"user")),public:t(r(e,"public"))}}(d)),l}function v(e){let t;return t="function"==typeof e.slice?Object.assign(e.slice(),{...e}):{...e},t}function b(e){return!e.ok}const w="http://www.w3.org/ns/auth/acl#Authorization",_="http://www.w3.org/ns/auth/acl#accessTo",S="http://www.w3.org/ns/auth/acl#agent",E="http://www.w3.org/ns/auth/acl#agentGroup",A="http://www.w3.org/ns/auth/acl#agentClass",R="http://www.w3.org/ns/auth/acl#default",I="http://www.w3.org/ns/auth/acl#defaultForNew",T="http://www.w3.org/ns/auth/acl#mode",x="http://www.w3.org/ns/auth/acl#origin",P="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",C="http://www.w3.org/ns/ldp#BasicContainer",k="http://www.w3.org/ns/ldp#Resource",O="http://www.w3.org/ns/ldp#contains",F="http://xmlns.com/foaf/0.1/Agent",N={AccessControlResource:"http://www.w3.org/ns/solid/acp#AccessControlResource",Policy:"http://www.w3.org/ns/solid/acp#Policy",AccessControl:"http://www.w3.org/ns/solid/acp#AccessControl",Read:"http://www.w3.org/ns/solid/acp#Read",Append:"http://www.w3.org/ns/solid/acp#Append",Write:"http://www.w3.org/ns/solid/acp#Write",Rule:"http://www.w3.org/ns/solid/acp#Rule",Matcher:"http://www.w3.org/ns/solid/acp#Matcher",accessControl:"http://www.w3.org/ns/solid/acp#accessControl",memberAccessControl:"http://www.w3.org/ns/solid/acp#memberAccessControl",apply:"http://www.w3.org/ns/solid/acp#apply",applyMembers:"http://www.w3.org/ns/solid/acp#applyMembers",allow:"http://www.w3.org/ns/solid/acp#allow",deny:"http://www.w3.org/ns/solid/acp#deny",allOf:"http://www.w3.org/ns/solid/acp#allOf",anyOf:"http://www.w3.org/ns/solid/acp#anyOf",noneOf:"http://www.w3.org/ns/solid/acp#noneOf",access:"http://www.w3.org/ns/solid/acp#access",accessMembers:"http://www.w3.org/ns/solid/acp#accessMembers",agent:"http://www.w3.org/ns/solid/acp#agent",group:"http://www.w3.org/ns/solid/acp#group",client:"http://www.w3.org/ns/solid/acp#client",PublicAgent:"http://www.w3.org/ns/solid/acp#PublicAgent",AuthenticatedAgent:"http://www.w3.org/ns/solid/acp#AuthenticatedAgent",CreatorAgent:"http://www.w3.org/ns/solid/acp#CreatorAgent"},D="http://www.w3.org/ns/solid/terms#PublicOidcClient",L="https://w3id.org/security#publicKey",U="http://www.w3.org/ns/pim/space#storage",j={fetch:y};async function M(e,t={...j,ignoreAuthenticationErrors:!1}){var r;const n={...j,...t};return B(await n.fetch(e,{method:"HEAD"}),{ignoreAuthenticationErrors:null!==(r=t.ignoreAuthenticationErrors)&&void 0!==r&&r})}function B(e,t={ignoreAuthenticationErrors:!1}){if(b(e)&&(!function(e){return 401===e.status||403===e.status}(e)||!t.ignoreAuthenticationErrors))throw new G(`Fetching the metadata of the Resource at [${e.url}] failed: [${e.status}] [${e.statusText}].`,e);return{internal_resourceInfo:m(e)}}function H(e){return(d(e)?$(e):g(e)).endsWith("/")}function W(e){var t;return null!==(t=e.internal_resourceInfo.contentType)&&void 0!==t?t:null}function $(e){return d(e)?e.internal_resourceInfo.sourceIri:null}const V=$;function K(e){var t;if(!h(e))return null;const r=null!==(t=J(e)["http://www.w3.org/ns/solid/terms#podOwner"])&&void 0!==t?t:[];return 1===r.length?r[0]:null}function J(e){return e.internal_resourceInfo.linkedResources}class G extends p{get statusCode(){return this.response.status}get statusText(){return this.response.statusText}constructor(e,t){super(e),this.response=t}}const q=()=>{const e=[],t=[],r=[];return{onQuad:t=>{e.push(t)},onError:e=>{r.push(e)},onComplete:e=>{t.push(e)},parse:async(o,s)=>new Promise((a=>{const c=new n.JsonLdParser({baseIRI:$(s),documentLoader:new i.FetchDocumentLoader(y)});let l=!1;function u(){l||(l=!0,t.forEach((e=>e())),a())}c.on("end",u),c.on("error",(e=>{r.forEach((t=>t(e))),u()})),e.forEach((e=>c.on("data",e))),c.write(o),c.end()}))}};l.dataset;const z="https://inrupt.com/.well-known/sdk-local-node/",{freeze:Y}=Object;function Q(e){return e.substring(0,46)===z}function X(e){return e.substring(46)}function Z(e){return"string"==typeof e&&"_:"===e.substring(0,2)}function ee(e){return e.substring(2)}function te(e){return`_:${e.value}`}const re="http://www.w3.org/2001/XMLSchema#boolean",ne="http://www.w3.org/2001/XMLSchema#dateTime",ie="http://www.w3.org/2001/XMLSchema#date",oe="http://www.w3.org/2001/XMLSchema#time",se="http://www.w3.org/2001/XMLSchema#decimal",ae="http://www.w3.org/2001/XMLSchema#integer",ce="http://www.w3.org/2001/XMLSchema#string",le="http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";function ue(e){return"true"===e||"1"===e||"false"!==e&&"0"!==e&&null}function de(e){if(!/\d\d:\d\d:\d\d(\.\d+)?(Z|(\+|-)\d\d:\d\d)?/.test(e))return null;const[t,r]=pe(e),[n,i,o]=t.split(":");let s=Number.parseInt(n,10),a=Number.parseInt(i,10);const[c,l]=o.split("."),u=Number.parseInt(c,10),d=l?Number.parseInt(l,10):void 0;a>=60&&(s+=1,a-=60);const h={hour:s,minute:a,second:u};if("number"==typeof d&&(h.millisecond=d),"string"==typeof r){const[e,t]=ge(r);if("number"!=typeof e||e>24||"number"!=typeof t||t>59)return null;h.timezoneHourOffset=e,h.timezoneMinuteOffset=t}return h}function he(e){if(!/-?\d{4,}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|(\+|-)\d\d:\d\d)?/.test(e))return null;const[t,r]=e.split("T"),[n,i]="-"===t.charAt(0)?[-1,t.substring(1)]:[1,t],[o,s,a]=i.split("-"),c=Number.parseInt(o,10)*n,l=Number.parseInt(s,10)-1,u=Number.parseInt(a,10),[d,h]=pe(r),[f,p]="string"==typeof h?ge(h):[0,0],[g,y,m]=d.split(":"),v=Number.parseInt(g,10)+f,b=Number.parseInt(y,10)+p,[w,_]=m.split("."),S=Number.parseInt(w,10),E=_?Number.parseInt(_,10):0,A=new Date(Date.UTC(c,l,u,v,b,S,E));return c>=0&&c<100&&A.setUTCFullYear(A.getUTCFullYear()-1900),A}function fe(e){if(!/-?\d{4,}-\d\d-\d\d(Z|(\+|-)\d\d:\d\d)?/.test(e))return null;const t=e,[r,n]="-"===t.charAt(0)?[-1,t.substring(1)]:[1,t],[i,o,s]=n.split("-"),a=s.length>2?s.substring(0,2):s,c=Number.parseInt(i,10)*r,l=Number.parseInt(o,10)-1,u=Number.parseInt(a,10),d=new Date(Date.UTC(c,l,u,12));return c>=0&&c<100&&d.setUTCFullYear(d.getUTCFullYear()-1900),d}function pe(e){if(e.endsWith("Z"))return[e.substring(0,e.length-1),"Z"];const t=e.split("+"),r=e.split("-");return 1===t.length&&1===r.length?[t[0],void 0]:t.length>r.length?[t[0],`+${t[1]}`]:[r[0],`-${r[1]}`]}function ge(e){if("Z"===e)return[0,0];const t="+"===e.charAt(0)?1:-1,[r,n]=e.substring(1).split(":");return[Number.parseInt(r,10)*t,Number.parseInt(n,10)*t]}function ye(e){const t=Number.parseFloat(e);return Number.isNaN(t)?null:t}function me(e){const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function ve(e){return e.toLowerCase()}function be(e){return we(e)&&"NamedNode"===e.termType}function we(e){return null!==e&&"object"==typeof e&&"string"==typeof e.termType&&"string"==typeof e.value&&"function"==typeof e.equals}function _e(e){return be(e)&&Q(e.value)}function Se(e){const t=g(e);if("function"!=typeof URL)return!0;try{return new URL(t),!0}catch(e){return!1}}function Ee(e,t){return Re.namedNode(Ae(X(e.value),t))}function Ae(e,t){if("function"!=typeof URL)throw new Error("The URL interface is not available, so an IRI cannot be determined.");const r=new URL(t);return r.hash=e,r.href}const Re=c;function Ie(e,t,r={}){var n;if(!["NamedNode","DefaultGraph"].includes(t.graph.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.graph.termType}] as their Graph node.`);const i="DefaultGraph"===t.graph.termType?"default":t.graph.value,o=null!==(n=e.graphs[i])&&void 0!==n?n:{};return Y({...e,graphs:Y({...e.graphs,[i]:Te(o,t,r)})})}function Te(e,t,r){var n;if(!["NamedNode","BlankNode"].includes(t.subject.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.subject.termType}] as their Subject node.`);const i="BlankNode"===t.subject.termType?`_:${t.subject.value}`:t.subject.value,o=null!==(n=e[i])&&void 0!==n?n:{type:"Subject",url:i,predicates:{}};return Y({...e,[i]:xe(o,t,r)})}function xe(e,t,r){return Y({...e,predicates:Pe(e.predicates,t,r)})}function Pe(e,t,r){var n;if(!["NamedNode"].includes(t.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.predicate.termType}] as their Predicate node.`);const i=t.predicate.value,o=null!==(n=e[i])&&void 0!==n?n:{};return Y({...e,[i]:Ce(o,t,r)})}function Ce(e,t,r){var n,i,o,s,a,c,l,u;if("NamedNode"===t.object.termType){const r=Y([...null!==(n=e.namedNodes)&&void 0!==n?n:[],t.object.value]);return Y({...e,namedNodes:r})}if("Literal"===t.object.termType){if(t.object.datatype.value===le){const r=t.object.language.toLowerCase(),n=Y([...null!==(o=null===(i=e.langStrings)||void 0===i?void 0:i[r])&&void 0!==o?o:[],t.object.value]),a=Y({...null!==(s=e.langStrings)&&void 0!==s?s:{},[r]:n});return Y({...e,langStrings:a})}const r=Y([...null!==(c=null===(a=e.literals)||void 0===a?void 0:a[t.object.datatype.value])&&void 0!==c?c:[],t.object.value]),n=Y({...null!==(l=e.literals)&&void 0!==l?l:{},[t.object.datatype.value]:r});return Y({...e,literals:n})}if("BlankNode"===t.object.termType){const n=ke(t.object,r),i=Y([...null!==(u=e.blankNodes)&&void 0!==u?u:[],n]);return Y({...e,blankNodes:i})}throw new Error(`Objects of type [${t.object.termType}] are not supported.`)}function ke(e,t){var r,n;if(void 0===(null!==(r=t.chainBlankNodes)&&void 0!==r?r:[]).find((t=>t.equals(e))))return te(e);const i=(null!==(n=t.otherQuads)&&void 0!==n?n:[]).filter((t=>t.subject.equals(e))),o=i.filter((e=>!Le(e.object))).reduce(((e,r)=>{var n;if(!["NamedNode"].includes(r.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${r.predicate.termType}] as their Predicate node.`);const i=null!==(n=e[r.predicate.value])&&void 0!==n?n:{};return Y({...e,[r.predicate.value]:Ce(i,r,t)})}),{});return i.filter((e=>Le(e.object))).reduce(((e,r)=>{var n,i;if(!["NamedNode"].includes(r.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${r.predicate.termType}] as their Predicate node.`);const o=null!==(n=e[r.predicate.value])&&void 0!==n?n:{},s=null!==(i=o.blankNodes)&&void 0!==i?i:[];return Y({...e,[r.predicate.value]:{...o,blankNodes:[...s,ke(r.object,t)]}})}),o)}function Oe(e){const t=e.map((e=>e.subject)).filter(Le),r=e.map((e=>e.object)).filter(Le),n=[];return r.forEach((t=>{n.push(...De(t,e))})),t.concat(r).filter((t=>{if(n.some((e=>e.equals(t))))return!1;const r=e.filter((e=>e.object.equals(t))).map((e=>e.subject));return r.length>0&&(i=r).every((e=>i.every((t=>e.equals(t)))));var i}))}function Fe(e,t={}){var r;const n=[],i=null!==(r=t.dataFactory)&&void 0!==r?r:c;return Object.keys(e.graphs).forEach((r=>{const o=e.graphs[r],s="default"===r?i.defaultGraph():i.namedNode(r);Object.keys(o).forEach((e=>{const{predicates:r}=o[e],a=Z(e)?i.blankNode(ee(e)):i.namedNode(e);n.push(...Ne(r,a,s,t))}))})),n}function Ne(e,t,r,n={}){var i;const o=[],s=null!==(i=n.dataFactory)&&void 0!==i?i:c;return Object.keys(e).forEach((n=>{var i,a,c,l;const u=s.namedNode(n),d=null!==(i=e[n].langStrings)&&void 0!==i?i:{},h=null!==(a=e[n].namedNodes)&&void 0!==a?a:[],f=null!==(c=e[n].literals)&&void 0!==c?c:{},p=null!==(l=e[n].blankNodes)&&void 0!==l?l:[];Object.keys(f).forEach((e=>{const n=s.namedNode(e);f[e].forEach((e=>{const i=s.literal(e,n);o.push(s.quad(t,u,i,r))}))})),Object.keys(d).forEach((e=>{d[e].forEach((n=>{const i=s.literal(n,e);o.push(s.quad(t,u,i,r))}))})),h.forEach((e=>{const n=s.namedNode(e);o.push(s.quad(t,u,n,r))})),p.forEach((e=>{if(Z(e)){const n=s.blankNode(ee(e));o.push(s.quad(t,u,n,r))}else{const n=s.blankNode(),i=s.quad(t,u,n,r),a=Ne(e,n,r);o.push(i),o.push(...a)}}))})),o}function De(e,t,r=[]){if(void 0!==r.find((t=>t.equals(e))))return r;const n=t.filter((t=>t.subject.equals(e)&&Le(t.object))).map((e=>e.object));if(0===n.length)return[];const i=[...r,e],o=n.map((e=>De(e,t,i))),s=[];for(const e of o)s.push(...e);return s}function Le(e){return"BlankNode"===e.termType}const Ue=()=>{const e=[],t=[],r=[];return{onQuad:t=>{e.push(t)},onError:e=>{r.push(e)},onComplete:e=>{t.push(e)},parse:async(n,i)=>{(await async function(e){return new a.Parser({format:"text/turtle",baseIRI:e})}($(i))).parse(n,((n,i)=>{n?r.forEach((e=>e(n))):i?e.forEach((e=>e(i))):t.forEach((e=>e()))}))}}};async function je(e,t){const r=new a.Writer({format:"text/turtle",prefixes:null==t?void 0:t.prefixes}),n=e.map((e=>Re.quad(e.subject,e.predicate,e.object,void 0)));r.addQuads(n);const i=new Promise(((e,t)=>{r.end(((r,n)=>{r?t(r):e(n)}))}));return await i}const Me={acl:"http://www.w3.org/ns/auth/acl#",acp:"http://www.w3.org/ns/solid/acp#",cc:"http://creativecommons.org/ns#",cert:"http://www.w3.org/ns/auth/cert#",csvw:"http://www.w3.org/ns/csvw#",current:"#",dc:"http://purl.org/dc/terms/",dcam:"http://purl.org/dc/dcam/",dcat:"http://www.w3.org/ns/dcat#",dctype:"http://purl.org/dc/dcmitype/",foaf:"http://xmlns.com/foaf/0.1/",ldp:"http://www.w3.org/ns/ldp#",owl:"http://www.w3.org/2002/07/owl#",posixstat:"http://www.w3.org/ns/posix/stat#",rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",schema:"https://schema.org/",shacl:"http://www.w3.org/ns/shacl#",skos:"http://www.w3.org/2004/02/skos/core#",skosxl:"http://www.w3.org/2008/05/skos-xl#",solid:"http://www.w3.org/ns/solid/terms#",swapdoc:"http://www.w3.org/2000/10/swap/pim/doc#",ui:"http://www.w3.org/ns/ui#",vann:"http://purl.org/vocab/vann/",vcard:"http://www.w3.org/2006/vcard/ns#",ws:"http://www.w3.org/ns/pim/space#",xsd:"http://www.w3.org/2001/XMLSchema#"},Be=l.dataset;function He(e,t={}){var r,n;return(null!==(n=null===(r=t.datasetFactory)||void 0===r?void 0:r.dataset)&&void 0!==n?n:Be)(Fe(e,t))}var We=Object.freeze({__proto__:null,getJsonLdParser:q,getTurtleParser:Ue,solidDatasetAsTurtle:async function(e,t){const{prefixes:r=Me,thing:n}={...t},i=new a.Writer({format:"application/turtle",prefixes:r}),o=n?new a.NamedNode(n):void 0;for(const t of He(e).match(o))i.addQuad(t);return new Promise(((e,t)=>{i.end(((r,n)=>{r?t(r):e(n)}))}))}});const $e={fetch:y},Ve=["Slug","If-None-Match","Content-Type"];async function Ke(e,t=$e){const r={...$e,...t},n=g(e),i=await r.fetch(n,r.init);if(b(i))throw new G(`Fetching the File failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i);const o=m(i),s=await i.blob();return Object.assign(s,{internal_resourceInfo:o})}async function Je(e,t,r=$e){const n=g(e),i=await Ge(n,t,"PUT",r);if(b(i))throw new G(`Overwriting the file at [${n}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i);const o=v(t),s=m(i);return s.sourceIri=n,s.isRawData=!0,Object.assign(o,{internal_resourceInfo:s})}async function Ge(e,t,r,n){var i,o;const s={...$e,...n},a=function(e){if(void 0===e)return{};let t={};var r;return r=e,Array.isArray(r)?e.forEach((([e,r])=>{t[e]=r})):function(e){return"function"==typeof e.forEach}(e)?e.forEach(((e,r)=>{t[r]=e})):t=e,t}(null!==(o=null===(i=s.init)||void 0===i?void 0:i.headers)&&void 0!==o?o:{});if(c=a,Ve.some((e=>void 0!==c[e])))throw new Error(`No reserved header (${Ve.join(", ")}) should be set in the optional RequestInit.`);var c;void 0!==s.slug&&(a.Slug=s.slug),a["Content-Type"]=qe(t,n.contentType);const l=g(e);return s.fetch(l,{...s.init,headers:a,method:r,body:t})}function qe(e,t){if("string"==typeof t)return t;const r="object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&e.type.length>0?e.type:void 0;return null!=r?r:"application/octet-stream"}function ze(e){var t,r,n,i,o,s,a,c;if(be(e))return`<${e.value}> (URL)`;if(function(e){return we(e)&&"Literal"===e.termType}(e)){if(!be(e.datatype))return`[${e.value}] (RDF/JS Literal of unknown type)`;let l;switch(e.datatype.value){case re:return l=null!==(r=null===(t=ue(e.value))||void 0===t?void 0:t.valueOf())&&void 0!==r?r:`Invalid data: \`${e.value}\``,`${l} (boolean)`;case ne:return l=null!==(i=null===(n=he(e.value))||void 0===n?void 0:n.toUTCString())&&void 0!==i?i:`Invalid data: \`${e.value}\``,`${l} (datetime)`;case se:return l=null!==(s=null===(o=ye(e.value))||void 0===o?void 0:o.toString())&&void 0!==s?s:`Invalid data: \`${e.value}\``,`${l} (decimal)`;case ae:return l=null!==(c=null===(a=me(e.value))||void 0===a?void 0:a.toString())&&void 0!==c?c:`Invalid data: \`${e.value}\``,`${l} (integer)`;case le:return`"${e.value}" (${e.language} string)`;case ce:return`"${e.value}" (string)`;default:return`[${e.value}] (RDF/JS Literal of type: \`${e.datatype.value}\`)`}}return"BlankNode"===e.termType?`[${e.value}] (RDF/JS BlankNode)`:"Quad"===e.termType?"??? (nested RDF* Quad)":"Variable"===e.termType?`?${e.value} (RDF/JS Variable)`:e}function Ye(e){if(!bt(e))throw new At(e)}function Qe(e,t){const r=f(e)?e.internal_changeLog:{additions:[],deletions:[]},[n,i]=t.filter((e=>!Xe(e))).reduce((([e,t],r)=>void 0!==e.find((e=>e.equals(r)))?[e.filter((e=>!e.equals(r))),t]:[e,t.concat(r)]),[r.additions,r.deletions]);return Y({...e,internal_changeLog:{additions:n,deletions:i}})}function Xe(e){return"BlankNode"===e.subject.termType||"BlankNode"===e.object.termType}function Ze(e,t){var r,n,i;if(Ye(e),!Se(t))throw new Rt(t);const o=g(t),s=null!==(i=null===(n=null===(r=e.predicates[o])||void 0===r?void 0:r.namedNodes)||void 0===n?void 0:n[0])&&void 0!==i?i:null;return null===s?null:Q(s)?`#${X(s)}`:s}const et=Ze;function tt(e,t){var r,n,i;if(Ye(e),!Se(t))throw new Rt(t);const o=g(t);return null!==(i=null===(n=null===(r=e.predicates[o])||void 0===r?void 0:r.namedNodes)||void 0===n?void 0:n.map((e=>Q(e)?`#${X(e)}`:e)))&&void 0!==i?i:[]}const rt=tt;function nt(e,t,r){var n,i;if(Ye(e),!Se(t))throw new Rt(t);const o=g(t),s=null!==(i=null===(n=e.predicates[o])||void 0===n?void 0:n.langStrings)&&void 0!==i?i:{},a=Object.keys(s).find((e=>e.toLowerCase()===r.toLowerCase()&&Array.isArray(s[e])&&s[e].length>0));return"string"==typeof a?s[a][0]:null}function it(e,t,r){var n,i;if(Ye(e),!Se(t))throw new Rt(t);const o=g(t),s=null!==(i=null===(n=e.predicates[o])||void 0===n?void 0:n.langStrings)&&void 0!==i?i:{},a=Object.keys(s).find((e=>e.toLowerCase()===r.toLowerCase()&&Array.isArray(s[e])&&s[e].length>0));return"string"==typeof a?[...s[a]]:[]}function ot(e,t){return Ye(e),ft(e,t,ce)}function st(e,t){const r=et(e,t);return null===r?null:Re.namedNode(r)}function at(e,t){return rt(e,t).map((e=>Re.namedNode(e)))}function ct(e,t){var r,n,i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=g(t),a=null!==(n=null===(r=e.predicates[s])||void 0===r?void 0:r.langStrings)&&void 0!==n?n:{},c=Object.keys(a);if(c.length>0){const e=c.find((e=>Array.isArray(a[e])&&a[e].length>0));if("string"==typeof e)return Re.literal(a[e][0],e)}const l=null!==(o=null===(i=e.predicates[s])||void 0===i?void 0:i.literals)&&void 0!==o?o:{},u=Object.keys(l);if(u.length>0){const e=u.find((e=>Array.isArray(l[e])&&l[e].length>0));if("string"==typeof e)return Re.literal(l[e][0],Re.namedNode(e))}return null}function lt(e,t){var r,n,i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=g(t);let a=[];const c=null!==(n=null===(r=e.predicates[s])||void 0===r?void 0:r.langStrings)&&void 0!==n?n:{},l=Object.keys(c);for(const e of l){const t=c[e].map((t=>Re.literal(t,e)));a=a.concat(t)}const u=null!==(o=null===(i=e.predicates[s])||void 0===i?void 0:i.literals)&&void 0!==o?o:{},d=Object.keys(u);for(const e of d){const t=u[e],r=Re.namedNode(e),n=t.map((e=>Re.literal(e,r)));a=a.concat(n)}return a}function ut(e,t){var r,n;Ye(e);const i=st(e,t);if(null!==i)return i;const o=ct(e,t);if(null!==o)return o;const s=g(t),a=null!==(n=null===(r=e.predicates[s])||void 0===r?void 0:r.blankNodes)&&void 0!==n?n:[];if(a.length>0){const e=Z(a[0])?ee(a[0]):void 0;return Re.blankNode(e)}return null}function dt(e,t){var r,n;Ye(e);const i=at(e,t),o=lt(e,t),s=g(t),a=(null!==(n=null===(r=e.predicates[s])||void 0===r?void 0:r.blankNodes)&&void 0!==n?n:[]).map((e=>{const t=Z(e)?ee(e):void 0;return Re.blankNode(t)}));return i.concat(o).concat(a)}function ht(e,t,r){var n,i,o,s;if(!Se(t))throw new Rt(t);const a=g(t);return null!==(s=null===(o=null===(i=null===(n=e.predicates[a])||void 0===n?void 0:n.literals)||void 0===i?void 0:i[r])||void 0===o?void 0:o[0])&&void 0!==s?s:null}function ft(e,t,r){var n,i,o;if(!Se(t))throw new Rt(t);const s=g(t);return[...null!==(o=null===(i=null===(n=e.predicates[s])||void 0===n?void 0:n.literals)||void 0===i?void 0:i[r])&&void 0!==o?o:[]]}function pt(e,t,r={}){var n;if(!Se(t))throw new Tt(t);const i=void 0!==r.scope?g(r.scope):"default",o=null!==(n=e.graphs[i])&&void 0!==n?n:{},s=g(t),a=o[Q(s)&&h(e)?Ae(X(s),$(e)):s];return void 0===a?null:a}function gt(e,t={acceptBlankNodes:!1}){var r;const n=void 0!==t.scope?g(t.scope):"default",i=null!==(r=e.graphs[n])&&void 0!==r?r:{};return Object.values(i).filter((e=>!Z(e.url)||t.acceptBlankNodes))}function yt(e,t){var r;const n=Et(t)&&h(e)?Ae(X(t.url),$(e)):t.url,i=e.graphs.default,o=Y({...i,[n]:Y({...t,url:n})}),s=Y({...e.graphs,default:o}),a=Re.namedNode(n),c=null===(r=e.graphs.default[n])||void 0===r?void 0:r.predicates,l=void 0!==c?Ne(c,a,Re.defaultGraph()):[],u=Ne(t.predicates,a,Re.defaultGraph());return function(e,t){const r=f(e)?e.internal_changeLog:{additions:[],deletions:[]},[n,i]=t.filter((e=>!Xe(e))).reduce((([e,t],r)=>void 0!==t.find((e=>e.equals(r)))?[e,t.filter((e=>!e.equals(r)))]:[e.concat(r),t]),[r.additions,r.deletions]);return Y({...e,internal_changeLog:{additions:n,deletions:i}})}(Qe(Y({...e,graphs:s}),l),u)}function mt(e,t){var r;let n;n=be(t)?t.value:"string"==typeof t?Q(t)&&h(e)?Ae(X(t),$(e)):t:Et(t)?t.url:_t(t);const i={...e.graphs.default};delete i[n];const o=Y({...e.graphs,default:Y(i)}),s=Re.namedNode(n),a=null===(r=e.graphs.default[n])||void 0===r?void 0:r.predicates,c=void 0!==a?Ne(a,s,Re.defaultGraph()):[];return Qe(Y({...e,graphs:o}),c)}function vt(e={}){var t;if(void 0!==e.url){const{url:t}=e;if(!Se(t))throw new Tt(t);return Y({type:"Subject",predicates:Y({}),url:t})}const r=null!==(t=e.name)&&void 0!==t?t:xt(),n=`${z}${r}`;return Y({type:"Subject",predicates:Y({}),url:n})}function bt(e){return"object"==typeof e&&null!==e&&"string"==typeof e.type&&"Subject"===e.type}function wt(e,t){if(Et(e)){if(void 0===t)throw new Error("The URL of a Thing that has not been persisted cannot be determined without a base URL.");return Ae(X(e.url),t)}return e.url}const _t=wt;function St(e){let t="";Et(e)?t+=`## Thing (no URL yet — identifier: \`#${X(e.url)}\`)\n`:t+=`## Thing: ${e.url}\n`;const r=Object.keys(e.predicates);if(0===r.length)t+="\n\n";else for(const n of r)t+=`\nProperty: ${n}\n`,t+=dt(e,n).reduce(((e,t)=>`${e}- ${ze(t)}\n`),"");return t}function Et(e){return Q(e.url)}class At extends p{constructor(e){super(`Expected a Thing, but received: [${e}].`),this.receivedValue=e}}class Rt extends p{constructor(e){const t=be(e)?e.value:e;super(`Expected a valid URL to identify a property, but received: [${t}].`),this.receivedProperty=t}}class It extends p{constructor(e){const t=be(e)?e.value:e;super(`Expected a valid URL value, but received: [${t}].`),this.receivedValue=t}}class Tt extends p{constructor(e){const t=be(e)?e.value:e;super(`Expected a valid URL to identify a Thing, but received: [${t}].`),this.receivedValue=t}}const xt=()=>u.v4();function Pt(e){const t=new URL(e);return t.hash="",t.href}function Ct(){return Y({type:"Dataset",graphs:{default:{}}})}async function kt(e,t={}){if(b(e))throw new G(`Fetching the SolidDataset at [${e.url}] failed: [${e.status}] [${e.statusText}] ${await e.text()}.`,e);const r=B(e),n={"text/turtle":Ue(),...t.parsers},i=W(r);if(null===i)throw new Error(`Could not determine the content type of the Resource at [${$(r)}].`);const o=i.split(";")[0],s=n[o];if(void 0===s)throw new Error(`The Resource at [${$(r)}] has a MIME type of [${o}], but the only parsers available are for the following MIME types: [${Object.keys(n).join(", ")}].`);const a=await e.text();return new Promise(((e,t)=>{let n=Y({graphs:Y({default:Y({})}),type:"Dataset"});const o=[],c=[];s.onError((e=>{t(new Error(`Encountered an error parsing the Resource at [${$(r)}] with content type [${i}]: ${e}`))})),s.onQuad((e=>{c.push(e),"BlankNode"===e.subject.termType||"BlankNode"===e.object.termType?o.push(e):n=Ie(n,e)})),s.onComplete((async()=>{const t=o.length<=20?Oe(o):[],i=o.filter((e=>t.every((t=>!t.equals(e.subject)))));n=i.reduce(((e,r)=>Ie(e,r,{otherQuads:c,chainBlankNodes:t})),n);const s=Y({...n,...r});e(s)})),s.parse(a,r)}))}async function Ot(e,t=j){var r;e=g(e);const n={...j,...t},i=Object.keys(null!==(r=t.parsers)&&void 0!==r?r:{}),o=i.length>0?i.join(", "):"text/turtle",s=await n.fetch(e,{headers:{Accept:o}});if(b(s))throw new G(`Fetching the Resource at [${e}] failed: [${s.status}] [${s.statusText}] ${await s.text()}.`,s);return await kt(s,t)}async function Ft(e,t,r=j){e=g(e);const n={...j,...r},i=function(e){return f(e)?e:Y({...e,internal_changeLog:{additions:[],deletions:[]}})}(t),o=Nt(i,e)?await async function(e){return{method:"PATCH",body:`${e.internal_changeLog.deletions.length>0?`DELETE DATA {${(await je(e.internal_changeLog.deletions.map(jt))).trim()}};`:""} ${e.internal_changeLog.additions.length>0?`INSERT DATA {${(await je(e.internal_changeLog.additions.map(jt))).trim()}};`:""}`,headers:{"Content-Type":"application/sparql-update"}}}(i):await async function(e,t){return{method:"PUT",body:await je(Fe(e).map(jt),t),headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:`<${k}>; rel="type"`}}}(i,r),s=await n.fetch(e,o);if(b(s)){const t=Nt(i,e)?`The changes that were sent to the Pod are listed below.\n\n${Ut(i)}`:`The SolidDataset that was sent to the Pod is listed below.\n\n${Lt(i)}`;throw new G(`Storing the Resource at [${e}] failed: [${s.status}] [${s.statusText}] ${await s.text()}.\n\n${t}`,s)}const a={...m(s),isRawData:!1};return Bt(Y({...t,internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:a}))}function Nt(e,t){return f(e)&&d(e)&&"string"==typeof e.internal_resourceInfo.sourceIri&&(r=t,Pt(e.internal_resourceInfo.sourceIri)===Pt(r));var r}function Dt(e,t){const r=new URL(t),n=new URL(e),i=n.href.startsWith(r.href),o=n.pathname.substring(r.pathname.length,n.pathname.length).replace(/(^\/)|(\/$)/g,"");return i&&o.length>=1&&!o.includes("/")}function Lt(e){let t="";d(e)?t+=`# SolidDataset: ${$(e)}\n`:t+="# SolidDataset (no URL yet)\n";const r=gt(e);return 0===r.length?t+="\n\n":r.forEach((r=>{t+=`\n${St(r)}`,f(e)&&(t+=`\n${function(e,t){const r=Re.namedNode(t.url),n=e.internal_changeLog.additions.reduce(((e,t)=>t.subject.equals(r)?e+1:e),0),i=e.internal_changeLog.deletions.reduce(((e,t)=>t.subject.equals(r)?e+1:e),0);return`(${1===n?"1 new value added":`${n} new values added`} / ${1===i?"1 value removed":`${i} values removed`})`}(e,r)}\n`)})),t}function Ut(e){if(!d(e))return"This is a newly initialized SolidDataset, so there is no source to compare it to.";if(!f(e)||0===e.internal_changeLog.additions.length&&0===e.internal_changeLog.deletions.length)return`## Changes compared to ${$(e)}\n\nThis SolidDataset has not been modified since it was fetched from ${$(e)}.\n`;let t=`## Changes compared to ${$(e)}\n`;const r=function(e){const t=Object.create(null);return e.internal_changeLog.deletions.forEach((r=>{var n,i,o;const s=_e(r.subject)?Ee(r.subject,$(e)):r.subject;if(!be(s)||!be(r.predicate))return;const a=g(s),c=g(r.predicate);null!==(n=t[a])&&void 0!==n||(t[a]=Object.create(null)),null!==(i=(o=t[a])[c])&&void 0!==i||(o[c]={added:[],deleted:[]}),t[a][c].deleted.push(r.object)})),e.internal_changeLog.additions.forEach((r=>{var n,i,o;const s=_e(r.subject)?Ee(r.subject,$(e)):r.subject;if(!be(s)||!be(r.predicate))return;const a=g(s),c=g(r.predicate);null!==(n=t[a])&&void 0!==n||(t[a]=Object.create(null)),null!==(i=(o=t[a])[c])&&void 0!==i||(o[c]={added:[],deleted:[]}),t[a][c].added.push(r.object)})),t}(e);return Object.keys(r).forEach((e=>{t+=`\n### Thing: ${e}\n`;const n=r[e];Object.keys(n).forEach((e=>{t+=`\nProperty: ${e}\n`;const{deleted:r}=n[e],{added:i}=n[e];r.length>0&&(t+="- Removed:\n",t+=r.reduce(((e,t)=>`${e} - ${ze(t)}\n`),"")),i.length>0&&(t+="- Added:\n",t+=i.reduce(((e,t)=>`${e} - ${ze(t)}\n`),""))}))})),t}function jt(e){const t=be(e.subject)?Mt(e.subject):e.subject,r=be(e.object)?Mt(e.object):e.object;return Re.quad(t,e.predicate,r,e.graph)}function Mt(e){return Q(e.value)?Re.namedNode(`#${X(e.value)}`):e}function Bt(e){const t=$(e),r=e.graphs.default,n=Object.keys(r).reduce(((e,r)=>{const n=function(e,t){const r=Object.keys(e.predicates).reduce(((e,r)=>{var n;const i=null!==(n=e[r].namedNodes)&&void 0!==n?n:[];if(i.every((e=>!Q(e))))return e;const o=Y(i.map((e=>Q(e)?`${t}#${X(e)}`:e))),s=Y({...e[r],namedNodes:o});return Y({...e,[r]:s})}),e.predicates);return Y({...e,predicates:r,url:Q(e.url)?`${t}#${X(e.url)}`:e.url})}(e[r],t),i=Q(r)?`${t}#${X(r)}`:r,o={...e};return delete o[r],o[i]=n,Y(o)}),r),i=Y({...e.graphs,default:n});return Y({...e,graphs:i})}function Ht(e){return{...Ct(),internal_resourceInfo:{sourceIri:g(e),isRawData:!1,contentType:"text/turtle",linkedResources:{}}}}function Wt(e){const t=g(e);if(!t.endsWith("/"))throw new Error("A Container's URL should end in a slash. Please update your tests.");return Ht(t)}const $t=(e,t,r)=>{var n,i;if(Ye(e),!Se(t))throw new Rt(t);if(!bt(r)&&!Se(r))throw new It(r);const o=g(t),s=null!==(n=e.predicates[o])&&void 0!==n?n:{},a=null!==(i=s.namedNodes)&&void 0!==i?i:[];let c;c=be(r)?r.value:"string"==typeof r?r:Et(r)?r.url:_t(r);const l=Y(a.concat(g(c))),u=Y({...s,namedNodes:l}),d=Y({...e.predicates,[o]:u});return Y({...e,predicates:d})},Vt=$t,Kt=(e,t,r)=>(Ye(e),rr(e,t,function(e){return e?"true":"false"}(r),re)),Jt=(e,t,r)=>(Ye(e),rr(e,t,function(e){return e.toISOString()}(r),ne)),Gt=(e,t,r)=>(Ye(e),rr(e,t,function(e){const t=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),[,i]=pe(e.toISOString());return`${t}-${String(r).padStart(2,"0")}-${String(n).padStart(2,"0")}${i}`}(r),ie)),qt=(e,t,r)=>(Ye(e),rr(e,t,function(e){let t,r;if(e.millisecond&&(t=e.millisecond<10?`00${e.millisecond}`:e.millisecond<100?`0${e.millisecond}`:e.millisecond),"number"==typeof e.timezoneHourOffset){const t=Math.abs(e.timezoneHourOffset)<10?`0${Math.abs(e.timezoneHourOffset)}`:Math.abs(e.timezoneHourOffset);r=e.timezoneHourOffset>=0?`+${t}`:`-${t}`,e.timezoneMinuteOffset?r=`${r}:${e.timezoneMinuteOffset<10?`0${e.timezoneMinuteOffset}`:e.timezoneMinuteOffset}`:r+=":00"}return`${e.hour<10?`0${e.hour}`:e.hour}:${e.minute<10?`0${e.minute}`:e.minute}:${e.second<10?`0${e.second}`:e.second}${e.millisecond?`.${t}`:""}${r||""}`}(r),oe)),zt=(e,t,r)=>(Ye(e),rr(e,t,function(e){return e.toString()}(r),se)),Yt=(e,t,r)=>(Ye(e),rr(e,t,function(e){return e.toString()}(r),ae));function Qt(e,t,r,n){var i,o,s;if(Ye(e),!Se(t))throw new Rt(t);const a=g(t),c=ve(n),l=null!==(i=e.predicates[a])&&void 0!==i?i:{},u=null!==(o=l.langStrings)&&void 0!==o?o:{},d=null!==(s=u[c])&&void 0!==s?s:[],h=Y(d.concat(r)),f=Y({...u,[c]:h}),p=Y({...l,langStrings:f}),y=Y({...e.predicates,[a]:p});return Y({...e,predicates:y})}const Xt=(e,t,r)=>(Ye(e),rr(e,t,r,ce));function Zt(e,t,r){return $t(e,t,r.value)}function er(e,t,r){if(Ye(e),!Se(t))throw new Rt(t);return r.datatype.value===le?Qt(e,t,r.value,r.language):rr(e,t,r.value,r.datatype.value)}function tr(e,t,r){var n,i;if("NamedNode"===r.termType)return Zt(e,t,r);if("Literal"===r.termType)return er(e,t,r);if("BlankNode"===r.termType){if(Ye(e),!Se(t))throw new Rt(t);const o=g(t),s=null!==(n=e.predicates[o])&&void 0!==n?n:{},a=null!==(i=s.blankNodes)&&void 0!==i?i:[],c=Y(a.concat(te(r))),l=Y({...s,blankNodes:c}),u=Y({...e.predicates,[o]:l});return Y({...e,predicates:u})}throw new Error(`Term type [${r.termType}] is not supported by @inrupt/solid-client.`)}function rr(e,t,r,n){var i,o,s;if(Ye(e),!Se(t))throw new Rt(t);const a=g(t),c=null!==(i=e.predicates[a])&&void 0!==i?i:{},l=null!==(o=c.literals)&&void 0!==o?o:{},u=null!==(s=l[n])&&void 0!==s?s:[],d=Y(u.concat(r)),h=Y({...l,[n]:d}),f=Y({...c,literals:h}),p=Y({...e.predicates,[a]:f});return Y({...e,predicates:p})}function nr(e,t){if(Ye(e),!Se(t))throw new Rt(t);const r=g(t),n={...e.predicates};return delete n[r],Y({...e,predicates:Y(n)})}const ir=(e,t,r)=>{var n,i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=g(t);if(!bt(r)&&!Se(r))throw new It(r);const a=bt(r)?_t(r):g(r),c=Y(null!==(o=null===(i=null===(n=e.predicates[s])||void 0===n?void 0:n.namedNodes)||void 0===i?void 0:i.filter((e=>e.toLowerCase()!==a.toLowerCase())))&&void 0!==o?o:[]),l=Y({...e.predicates[s],namedNodes:c}),u=Y({...e.predicates,[s]:l});return Y({...e,predicates:u})},or=ir,sr=(e,t,r)=>(Ye(e),yr(e,t,re,(e=>ue(e)===r))),ar=(e,t,r)=>(Ye(e),yr(e,t,ne,(e=>{var t;return(null===(t=he(e))||void 0===t?void 0:t.getTime())===r.getTime()}))),cr=(e,t,r)=>(Ye(e),yr(e,t,ie,(function(e){const t=fe(e);return!!t&&t.getFullYear()===r.getFullYear()&&t.getMonth()===r.getMonth()&&t.getUTCDate()===r.getUTCDate()}))),lr=(e,t,r)=>(Ye(e),yr(e,t,oe,(function(e){const t=de(e);return!!t&&t.hour===r.hour&&t.minute===r.minute&&t.second===r.second&&t.millisecond===r.millisecond&&t.timezoneHourOffset===r.timezoneHourOffset&&t.timezoneMinuteOffset===r.timezoneMinuteOffset}))),ur=(e,t,r)=>(Ye(e),yr(e,t,se,(e=>ye(e)===r))),dr=(e,t,r)=>(Ye(e),yr(e,t,ae,(e=>me(e)===r)));function hr(e,t,r,n){var i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=g(t),a=null!==(o=null===(i=e.predicates[s])||void 0===i?void 0:i.langStrings)&&void 0!==o?o:{},c=Object.keys(a).find((e=>ve(e)===ve(n)&&Array.isArray(a[e])&&a[e].length>0));if("string"!=typeof c)return e;const l=a[c],u=Y(l.filter((e=>e!==r))),d=Y({...a,[c]:u}),h=Y({...e.predicates[s],langStrings:d}),f=Y({...e.predicates,[s]:h});return Y({...e,predicates:f})}const fr=(e,t,r)=>(Ye(e),yr(e,t,ce,(e=>e===r)));function pr(e,t,r){return ir(e,t,r.value)}function gr(e,t,r){var n,i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=r.datatype.value;if(s===le)return hr(e,t,r.value,r.language);const a=g(t),c=null!==(n=e.predicates[a])&&void 0!==n?n:{},l=null!==(i=c.literals)&&void 0!==i?i:{},u=null!==(o=l[s])&&void 0!==o?o:[],d=Y(u.filter((e=>e!==r.value))),h=Y({...l,[s]:d}),f=Y({...c,literals:h}),p=Y({...e.predicates,[a]:f});return Y({...e,predicates:p})}function yr(e,t,r,n){var i,o,s;if(!Se(t))throw new Rt(t);const a=g(t),c=null!==(i=e.predicates[a])&&void 0!==i?i:{},l=null!==(o=c.literals)&&void 0!==o?o:{},u=null!==(s=l[r])&&void 0!==s?s:[],d=Y(u.filter((e=>!n(e)))),h=Y({...l,[r]:d}),f=Y({...c,literals:h}),p=Y({...e.predicates,[a]:f});return Y({...e,predicates:p})}const mr=(e,t,r)=>{if(Ye(e),!Se(t))throw new Rt(t);if(!bt(r)&&!Se(r))throw new It(r);return $t(nr(e,t),t,r)},vr=mr,br=(e,t,r)=>(Ye(e),Kt(nr(e,t),t,r)),wr=(e,t,r)=>(Ye(e),Jt(nr(e,t),t,r)),_r=(e,t,r)=>(Ye(e),Gt(nr(e,t),t,r)),Sr=(e,t,r)=>(Ye(e),qt(nr(e,t),t,r)),Er=(e,t,r)=>(Ye(e),zt(nr(e,t),t,r)),Ar=(e,t,r)=>(Ye(e),Yt(nr(e,t),t,r));function Rr(e,t,r,n){return Ye(e),Qt(nr(e,t),t,r,n)}const Ir=(e,t,r)=>(Ye(e),Xt(nr(e,t),t,r));function Tr(e,t,r){return Ye(e),Zt(nr(e,t),t,r)}function xr(e,t,r){return Ye(e),er(nr(e,t),t,r)}function Pr(e,t,r){if(Ye(e),!Se(t))throw new Rt(t);return tr(nr(e,t),t,r)}function Cr(e=vt()){let t=bt(e)?e:vt(e);function r(e){return(r,n)=>(t=e(t,r,n),o)}function n(e){return(r,n)=>(t=e(t,r,n),o)}function i(e){return(r,n)=>(t=e(t,r,n),o)}const o={build:()=>t,addUrl:r($t),addIri:r(Vt),addBoolean:r(Kt),addDatetime:r(Jt),addDate:r(Gt),addTime:r(qt),addDecimal:r(zt),addInteger:r(Yt),addStringNoLocale:r(Xt),addStringEnglish:(e,r)=>(t=Qt(t,e,r,"en"),o),addStringWithLocale:(e,r,n)=>(t=Qt(t,e,r,n),o),addNamedNode:r(Zt),addLiteral:r(er),addTerm:r(tr),setUrl:n(mr),setIri:n(vr),setBoolean:n(br),setDatetime:n(wr),setDate:n(_r),setTime:n(Sr),setDecimal:n(Er),setInteger:n(Ar),setStringNoLocale:n(Ir),setStringEnglish:(e,r)=>(t=Rr(t,e,r,"en"),o),setStringWithLocale:(e,r,n)=>(t=Rr(t,e,r,n),o),setNamedNode:n(Tr),setLiteral:n(xr),setTerm:n(Pr),removeAll:e=>(t=nr(t,e),o),removeUrl:i(ir),removeIri:i(or),removeBoolean:i(sr),removeDatetime:i(ar),removeDate:i(cr),removeTime:i(lr),removeDecimal:i(ur),removeInteger:i(dr),removeStringNoLocale:i(fr),removeStringEnglish:(e,r)=>Cr(hr(t,e,r,"en")),removeStringWithLocale:(e,r,n)=>Cr(hr(t,e,r,n)),removeNamedNode:i(pr),removeLiteral:i(gr)};return o}function kr(e){const t=J(e).type;return Array.isArray(t)&&t.includes(N.AccessControlResource)}async function Or(e,t=j){if(!sn(e))return{resourceAcl:null,fallbackAcl:null};try{const r=await Fr(e,t);return null===r?{resourceAcl:null,fallbackAcl:await Nr(e,t)}:{resourceAcl:r,fallbackAcl:null}}catch(e){if(e instanceof Qr)return{resourceAcl:null,fallbackAcl:null};throw e}}async function Fr(e,t=j){if(!sn(e))return null;try{const r=await Ot(e.internal_resourceInfo.aclUrl,t);if(kr(r))throw new Qr(e,r);return Y({...r,internal_accessTo:$(e)})}catch(e){if(e instanceof Qr)throw e;return null}}async function Nr(e,t=j){const r=new URL($(e)),n=r.pathname;if("/"===n)return null;const i=Dr(n),o=new URL(i,r.origin).href,s=await M(o,t);if(!sn(s))return null;const a=await Fr(s,t);return null===a?Nr(s,t):a}function Dr(e){const t="/"===e.substring(e.length-1)?e.substring(0,e.length-1):e;return`${e.substring(0,t.lastIndexOf("/"))}/`}function Lr(e){return gt(e).filter(Ur)}function Ur(e){return rt(e,P).includes(w)}function jr(e,t){return e.filter((e=>function(e,t){return rt(e,_).includes(t)}(e,t)))}function Mr(e,t){return e.filter((e=>function(e,t){return rt(e,R).includes(t)||rt(e,I).includes(t)}(e,t)))}function Br(e){const t=rt(e,T);return t.includes($r.write)?{read:t.includes($r.read),append:!0,write:!0,control:t.includes($r.control)}:{read:t.includes($r.read),append:t.includes($r.append),write:!1,control:t.includes($r.control)}}function Hr(e){return e.reduce(((e,t)=>e.write||t.write?{read:e.read||t.read,append:!0,write:!0,control:e.control||t.control}:{read:e.read||t.read,append:e.append||t.append,write:!1,control:e.control||t.control}),{read:!1,append:!1,write:!1,control:!1})}function Wr(e){return!Ne(e.predicates,Re.namedNode(e.url),Re.defaultGraph()).some((e=>!function(e){const{predicate:t}=e,{object:r}=e;return!(!t.equals(Re.namedNode(P))||!r.equals(Re.namedNode(w)))||(!!(t.equals(Re.namedNode(_))||t.equals(Re.namedNode(R))||t.equals(Re.namedNode(I)))||(!(!t.equals(Re.namedNode(T))||!Object.values($r).some((e=>r.equals(Re.namedNode(e)))))||(!!(t.equals(Re.namedNode(S))||t.equals(Re.namedNode(E))||t.equals(Re.namedNode(A)))||!!t.equals(Re.namedNode(x)))))}(e)))&&(null===et(e,_)&&null===et(e,R)&&null===et(e,I)||null===et(e,T)||null===et(e,S)&&null===et(e,E)&&null===et(e,A))}const $r={read:"http://www.w3.org/ns/auth/acl#Read",append:"http://www.w3.org/ns/auth/acl#Append",write:"http://www.w3.org/ns/auth/acl#Write",control:"http://www.w3.org/ns/auth/acl#Control"};function Vr(e,t,r){return e.filter((e=>rt(e,r).includes(t)))}function Kr(e,t){const r={};return e.forEach((e=>{const n=rt(e,t),i=Br(e);n.forEach((e=>{r[e]=void 0===r[e]?i:Hr([r[e],i])}))})),r}function Jr(e){let t=vt();return t=vr(t,P,w),e.read&&(t=Vt(t,T,$r.read)),e.append&&!e.write&&(t=Vt(t,T,$r.append)),e.write&&(t=Vt(t,T,$r.write)),e.control&&(t=Vt(t,T,$r.control)),t}function Gr(e,t){return Object.assign(v(e),{internal_acl:t})}const qr=[S,A,E,x];function zr(e,t,r,n,i){let o=e;gt(e).forEach((t=>{const[s,a]=function(e,t,r,n,i){if(!rt(e,r).includes(t))return[e,Jr({read:!1,append:!1,write:!1,control:!1})];const o=or(e,r,t);let s=function(e){let t=vt();function r(e,t,r){return rt(e,r).reduce(((e,t)=>Vt(e,r,t)),t)}return t=vr(t,P,w),t=r(e,t,_),t=r(e,t,R),t=r(e,t,I),t=r(e,t,S),t=r(e,t,E),t=r(e,t,A),t=r(e,t,x),t=r(e,t,T),t}(e);return s=or(s,"resource"===i?_:R,n),"default"===i&&(s=or(s,I,n)),s=vr(s,r,t),qr.filter((e=>e!==r)).forEach((e=>{s=nr(s,e)})),[o,s]}(t,i,r,e.internal_accessTo,n);o=yt(o,s),o=yt(o,a)}));let s=Jr(t);return s=vr(s,"resource"===n?_:R,e.internal_accessTo),s=vr(s,r,i),function(e){return Lr(e).filter(Wr).reduce(mt,e)}(yt(o,s))}function Yr(e,t){return Gr(e,{resourceAcl:t,fallbackAcl:null})}class Qr extends Error{constructor(e,t){super(`[${V(e)}] is governed by Access Control Policies in [${V(t)}] rather than by Web Access Control.`)}}function Xr(e){return null!==e.internal_acl.resourceAcl&&$(e)===e.internal_acl.resourceAcl.internal_accessTo&&e.internal_resourceInfo.aclUrl===$(e.internal_acl.resourceAcl)}function Zr(e){return Xr(e)?e.internal_acl.resourceAcl:null}function en(e){return null!==e.internal_acl.fallbackAcl}function tn(e){return en(e)?e.internal_acl.fallbackAcl:null}function rn(e){return Y({...Ct(),internal_accessTo:$(e),internal_resourceInfo:{sourceIri:e.internal_resourceInfo.aclUrl,isRawData:!1,linkedResources:{}}})}function nn(e){const t=rn(e);return Mr(Lr(e.internal_acl.fallbackAcl),e.internal_acl.fallbackAcl.internal_accessTo).map((t=>(t=nr(t,R),t=nr(t,I),t=vr(t,_,$(e)),vr(t,R,$(e))))).reduce(yt,t)}async function on(e,t,r=j){if(!sn(e))throw new Error(`Could not determine the location of the ACL for the Resource at [${$(e)}]; possibly the current user does not have Control access to that Resource. Try calling \`hasAccessibleAcl()\` before calling \`saveAclFor()\`.`);return{...await Ft(e.internal_resourceInfo.aclUrl,t,r),internal_accessTo:$(e)}}function sn(e){return"string"==typeof e.internal_resourceInfo.aclUrl}function an(e,t){return Xr(e)?ln(e.internal_acl.resourceAcl,t):en(e)?hn(e.internal_acl.fallbackAcl,t):null}function cn(e){return Xr(e)?un(Zr(e)):en(e)?fn(tn(e)):null}function ln(e,t){return Hr(pn(jr(Lr(e),e.internal_accessTo),t).map(Br))}function un(e){return mn(gn(jr(Lr(e),e.internal_accessTo)))}function dn(e,t,r){return zr(e,r,S,"resource",t)}function hn(e,t){return Hr(pn(Mr(Lr(e),e.internal_accessTo),t).map(Br))}function fn(e){return mn(gn(Mr(Lr(e),e.internal_accessTo)))}function pn(e,t){return Vr(e,t,S)}function gn(e){return e.filter(yn)}function yn(e){return null!==et(e,S)}function mn(e){return Kr(e,S)}function vn(e,t){return Xr(e)?wn(e.internal_acl.resourceAcl,t):en(e)?Sn(e.internal_acl.fallbackAcl,t):null}function bn(e){return Xr(e)?_n(Zr(e)):en(e)?En(tn(e)):null}function wn(e,t){return Hr(An(jr(Lr(e),e.internal_accessTo),t).map(Br))}function _n(e){return Rn(jr(Lr(e),e.internal_accessTo))}function Sn(e,t){return Hr(An(Mr(Lr(e),e.internal_accessTo),t).map(Br))}function En(e){return Rn(Mr(Lr(e),e.internal_accessTo))}function An(e,t){return Vr(e,t,E)}function Rn(e){return Kr(e,E)}function In(e,t,r){return zr(e,r,E,"resource",t)}function Tn(e){return Xr(e)?xn(e.internal_acl.resourceAcl):en(e)?Pn(e.internal_acl.fallbackAcl):null}function xn(e){return Hr(kn(jr(Lr(e),e.internal_accessTo),F).map(Br))}function Pn(e){return Hr(kn(Mr(Lr(e),e.internal_accessTo),F).map(Br))}function Cn(e,t){return zr(e,t,A,"resource",F)}function kn(e,t){return e.filter((e=>function(e,t){return rt(e,A).includes(t)}(e,t)))}function On(e,t){const r=pt(e,t);if(null===r)throw new Error(`Profile document [${$(e)}] does not include WebID [${t}]`);return r}function Fn(e,t){return Ze(On(e,t),L)}async function Nn(e,t,r=j){const n={...j,...r},i=await n.fetch(t);if(!i.ok)throw new Error(`Fetching [${t}] returned an error: ${i.status} ${i.statusText}`);try{const r=await i.json();if(!(e=>void 0!==e.keys)(r))throw new Error(`[${t}] does not dereference to a valid JWKS: ${JSON.stringify(r)}`);return{keys:[...r.keys,e]}}catch(e){throw new Error(`Parsing the document at [${t}] failed: ${e}`)}}function Dn(e,t){const r=pt(t,e),n=gt(t).filter((e=>rt(e,"http://xmlns.com/foaf/0.1/primaryTopic").length>0)).map(_t).concat(r?rt(r,"http://www.w3.org/2000/01/rdf-schema#seeAlso"):[]).concat(r?rt(r,"http://xmlns.com/foaf/0.1/isPrimaryTopicOf"):[]).filter((e=>e!==V(t)));return Array.from(new Set(n))}async function Ln(e,t=j){var r,n;const i=null!==(r=t.fetch)&&void 0!==r?r:y,o=null!==(n=t.webIdProfile)&&void 0!==n?n:await Ot(e,{fetch:y});return{webIdProfile:o,altProfileAll:(await Promise.allSettled(Dn(e,o).map((e=>Ot(e,{fetch:i}))))).filter((e=>"fulfilled"===e.status)).map((e=>e.value))}}function Un(e,t){const r=new Set;return[e.webIdProfile,...e.altProfileAll].forEach((e=>{const n=pt(e,t);null!==n&&rt(n,U).forEach((e=>r.add(e)))})),Array.from(r)}function jn(e){if(!Hi(e))throw new Error(`An Access Control Resource for [${$(e)}] is not available. This could be because the current user is not allowed to see it, or because their Pod Server does not support Access Control Resources.`);return e.internal_acp.acr}function Mn(e,t){return Object.assign(v(e),{internal_acp:{...e.internal_acp,acr:t}})}function Bn(e){let t=vt(e);return t=vr(t,P,N.AccessControl),t}function Hn(e,t){const r=gt(jn(e),t),n=r.filter((e=>rt(e,P).includes(N.AccessControl))),i=r.filter((e=>rt(e,N.accessControl).length>0)).map((e=>vt({url:rt(e,N.accessControl)[0]})));return n.concat(i)}function Wn(e,t){return Mn(e,yt(jn(e),t))}function $n(e,t){return Vt(e,N.apply,t)}function Vn(e){return rt(e,N.apply)}function Kn(e,t){return or(e,N.apply,t)}function Jn(e){return nr(e,N.apply)}function Gn(e,t){return Vt(e,N.applyMembers,t)}function qn(e){return rt(e,N.applyMembers)}function zn(e){return nr(e,N.applyMembers)}function Yn(e){const t=Hn(e);return 0===t.length?Bn():t[0]}function Qn(e){return h(e)&&Array.isArray(e.internal_resourceInfo.linkedResources[N.accessControl])&&1===e.internal_resourceInfo.linkedResources[N.accessControl].length}function Xn(e,t){var r;const n=jn(e),i=$(n);let o=null!==(r=pt(n,i))&&void 0!==r?r:vt({url:i});return o=Vt(o,N.access,t),Mn(e,yt(n,o))}function Zn(e,t){var r;const n=jn(e),i=$(n);let o=null!==(r=pt(n,i))&&void 0!==r?r:vt({url:i});return o=Vt(o,N.accessMembers,t),Mn(e,yt(n,o))}function ei(e){const t=jn(e),r=pt(t,$(t));return null===r?[]:rt(r,N.access)}function ti(e){const t=jn(e),r=pt(t,$(t));return null===r?[]:rt(r,N.accessMembers)}function ri(e,t){const r=jn(e),n=pt(r,$(r));return null===n?e:Mn(e,yt(r,or(n,N.access,t)))}function ni(e,t){const r=jn(e),n=pt(r,$(r));return null===n?e:Mn(e,yt(r,or(n,N.accessMembers,t)))}function ii(e){const t=jn(e),r=pt(t,$(t));return null===r?e:Mn(e,yt(t,nr(r,N.access)))}function oi(e){const t=jn(e),r=pt(t,$(t));return null===r?e:Mn(e,yt(t,nr(r,N.accessMembers)))}function si(e,t){return Wn(e,$n(Yn(e),t))}function ai(e,t){return Wn(e,Gn(Yn(e),t))}function ci(e){const t=Hn(e).map((e=>Vn(e))),r=new Set;return t.forEach((e=>{e.forEach((e=>r.add(e)))})),Array.from(r)}function li(e){const t=Hn(e).map((e=>qn(e))),r=new Set;return t.forEach((e=>{e.forEach((e=>r.add(e)))})),Array.from(r)}function ui(e,t){return Hn(e).map((e=>Kn(e,t))).reduce(Wn,e)}function di(e,t){const r=Hn(e).map((e=>function(e,t){return or(e,N.applyMembers,t)}(e,t)));return r.reduce(Wn,e)}function hi(e){return Hn(e).map((e=>Jn(e))).reduce(Wn,e)}function fi(e){return Hn(e).map((e=>zn(e))).reduce(Wn,e)}function pi(e){let t=`# Access controls for ${$(e)}\n`;const r=ci(e),n=li(e),i=ei(e),o=ti(e);return 0===r.length&&0===n.length&&0===i.length&&0===o.length&&(t+="\n\n"),r.length>0&&(t+="\nThe following policies apply to this resource:\n- ",t+=`${r.join("\n- ")}\n`),i.length>0&&(t+="\nThe following policies apply to the access control resource for this resource:\n- ",t+=`${i.join("\n- ")}\n`),n.length>0&&(t+="\nThe following policies apply to the children of this resource:\n- ",t+=`${n.join("\n- ")}\n`),o.length>0&&(t+="\nThe following policies apply to the access control resources for children of this resource:\n- ",t+=`${o.join("\n- ")}\n`),t}const gi="http://www.w3.org/ns/solid/acp#",yi={AccessControl:gi.concat("AccessControl"),AccessControlResource:gi.concat("AccessControlResource"),AuthenticatedAgent:gi.concat("AuthenticatedAgent"),CreatorAgent:gi.concat("CreatorAgent"),Matcher:gi.concat("Matcher"),Policy:gi.concat("Policy"),PublicAgent:gi.concat("PublicAgent"),access:gi.concat("access"),accessControl:gi.concat("accessControl"),agent:gi.concat("agent"),allOf:gi.concat("allOf"),allow:gi.concat("allow"),anyOf:gi.concat("anyOf"),apply:gi.concat("apply"),client:gi.concat("client"),deny:gi.concat("deny"),memberAccessControl:gi.concat("memberAccessControl"),noneOf:gi.concat("noneOf"),vc:gi.concat("vc")},mi="http://www.w3.org/ns/auth/acl#",vi={Append:mi.concat("Append"),Control:mi.concat("Control"),Read:mi.concat("Read"),Write:mi.concat("Write")};function bi(e){const t=jn(e);return pt(t,$(t))}const wi="defaultAccessControl",_i="defaultAcrAccessControl",Si="defaultMemberAccessControl",Ei="defaultMemberAcrAccessControl";function Ai(e,t){return $(jn(e)).concat("#").concat(t)}function Ri(e,t){const r=jn(e),n=Ai(e,t),i=pt(r,n);return null==i?vt({url:n}):i}function Ii(e,t){const r=rt(e,t);return{read:r.includes(vi.Read),append:r.includes(vi.Append),write:r.includes(vi.Write),controlRead:!1,controlWrite:!1}}function Ti(e,t,r){let n=nr(e,r);return(t.read||t.controlRead)&&(n=Vt(n,r,vi.Read)),t.append&&(n=Vt(n,r,vi.Append)),(t.write||t.controlWrite)&&(n=Vt(n,r,vi.Write)),n}const xi="defaultVcPolicy",Pi="defaultVcMatcher";function Ci(e,t,r={inherit:!1}){var n;let i=jn(e);const o=`${V(i)}#${xi}`,s=`${V(i)}#${Pi}`,{policy:a,matcher:c}=function(e,t,r,n){var i;let o=pt(e,t);null===o&&(o=Cr({url:t}).addIri(P,yi.Policy).addIri(yi.anyOf,r).build());const s=null!==(i=pt(e,r))&&void 0!==i?i:Cr({url:r}).addIri(P,yi.Matcher).addIri(yi.vc,"http://www.w3.org/ns/solid/vc#SolidAccessGrant").build();return o=Ti(o,{...Ii(o,yi.allow),...n},yi.allow),{matcher:s,policy:o}}(i,o,s,t);let l=Ri(e,"defaultAccessControl");rt(l,yi.apply).includes(_t(a))||(l=Vt(l,yi.apply,a));let u=Ri(e,"defaultMemberAccessControl"),d=null!==(n=bi(e))&&void 0!==n?n:vt({url:V(i)});return rt(d,yi.accessControl).includes(_t(l))||(d=Vt(d,yi.accessControl,l)),i=[d,l,a,c].reduce(yt,i),r.inherit&&(rt(u,yi.apply).includes(_t(a))||(u=Vt(u,yi.apply,a)),rt(d,yi.memberAccessControl).includes(_t(u))||(d=Vt(d,yi.memberAccessControl,u)),i=[d,u].reduce(yt,i)),function(e,t){return Object.assign(v(e),{internal_acp:{acr:t}})}(e,i)}const ki={read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1},Oi=(e,t,r)=>rt(e,t).includes(_t(r));function Fi(e){const t=jn(e),r=Ri(e,"defaultAccessControl"),n=bi(e);if(null===n||!Oi(n,yi.accessControl,r))return ki;const i=pt(t,`${V(t)}#${xi}`);if(null===i||!Oi(r,yi.apply,i))return ki;const o=pt(t,`${V(t)}#${Pi}`);return null!==o&&Oi(i,yi.anyOf,o)?Ii(i,yi.allow):ki}async function Ni(e,t=j){const r=g(e),n={...j,...t},i=await Ot(r,n),o=await Wi(i,n);return{...i,...o}}async function Di(e,t=j){const r=g(e),n={...j,...t},i=await Ke(r,n),o=await Wi(i,n);return Object.assign(i,o)}async function Li(e,t=j){const r=g(e),n={...j,...t},i=await M(r,n),o=await Wi(i,n);return{...i,...o}}async function Ui(e,t=j){const r=g(e),n={...j,...t},i=await Ot(r,n);if(sn(i))return Gr(i,await Or(i,n));const o=await Wi(i,n);return{...i,...o}}async function ji(e,t=j){const r=g(e),n={...j,...t},i=await Ke(r,n);if(sn(i))return Gr(i,await Or(i,n));const o=await Wi(i,n);return Object.assign(i,o)}async function Mi(e,t=j){const r=g(e),n={...j,...t},i=await M(r,n);if(sn(i))return Gr(i,await Or(i,n));const o=await Wi(i,n);return{...i,...o}}async function Bi(e,t=j){const r=jn(e),n={...j,...t};return Mn(e,await Ft($(r),r,n))}function Hi(e){return"object"==typeof e.internal_acp&&null!==e.internal_acp&&"object"==typeof e.internal_acp.acr&&null!==e.internal_acp.acr}async function Wi(e,t){let r,n;if(Qn(e)){const{linkedResources:t}=e.internal_resourceInfo;[r]=t[N.accessControl]}else if(sn(e)){let n;try{n=await M(e.internal_resourceInfo.aclUrl,t)}catch(e){}n&&kr(n)&&(r=$(n))}if("string"!=typeof r)return{internal_acp:{acr:null}};try{n=await Ot(r,t)}catch(e){return{internal_acp:{acr:null}}}return{internal_acp:{acr:{...n,accessTo:$(e)}}}}function $i(e){const t=ci(e).map(Pt).concat(li(e).map(Pt)).concat(ei(e).map(Pt)).concat(ti(e).map(Pt));return Array.from(new Set(t))}async function Vi(e,t=j){const r=g(e),n={...j,...t},i=await M(r,n);return Hi(await Wi(i,n))}function Ki(e){if(h(e))return[N.accessControl,"acl"].map((t=>{if(Array.isArray(e.internal_resourceInfo.linkedResources[t])&&1===e.internal_resourceInfo.linkedResources[t].length)return e.internal_resourceInfo.linkedResources[t][0]})).find((e=>void 0!==e))}function Ji(e){return rt(e,P).includes(N.Rule)}function Gi(e,t){return Vt(e,N.allOf,t)}function qi(e,t){return or(e,N.allOf,t)}function zi(e,t){return vr(e,N.allOf,t)}function Yi(e){return rt(e,N.allOf)}function Qi(e,t){return Vt(e,N.anyOf,t)}function Xi(e,t){return or(e,N.anyOf,t)}function Zi(e,t){return vr(e,N.anyOf,t)}function eo(e){return rt(e,N.anyOf)}function to(e,t){return Vt(e,N.noneOf,t)}function ro(e,t){return or(e,N.noneOf,t)}function no(e,t){return vr(e,N.noneOf,t)}function io(e){return rt(e,N.noneOf)}function oo(e){let t=vt({url:g(e)});return t=mr(t,P,N.Rule),t}function so(e,t){const r=jn(e),n=new URL($(r));n.hash=`#${t}`;let i=vt({url:n.href});return i=mr(i,P,N.Rule),i}function ao(e,t){const r=pt(e,t);return null===r||Ze(r,P)!==N.Rule?null:r}function co(e,t){const r=jn(e),n=$(r),i=new URL(n);i.hash=`#${t}`;const o=pt(r,i.href);return null!==o&&Ji(o)?o:null}function lo(e){return gt(e).filter(Ji)}function uo(e){return gt(jn(e)).filter(Ji)}function ho(e,t){return mt(e,t)}function fo(e,t){const r=jn(e);let n;if("string"==typeof t)if(Se(t))n=t;else{const e=new URL($(r));e.hash=`#${t}`,n=e.href}else n=be(t)?g(t):wt(t);const i=co(e,new URL(n).hash.substring(1));return null===i?e:Mn(e,mt(r,i))}function po(e,t){return yt(e,t)}function go(e,t){return Mn(e,yt(jn(e),t))}function yo(e){return rt(e,N.agent).filter((e=>e!==N.PublicAgent&&e!==N.AuthenticatedAgent&&e!==N.CreatorAgent))}function mo(e,t){const r=Ao(e),n=To(e),i=Co(e);let o=vr(e,N.agent,t);return r&&(o=Ro(o)),n&&(o=xo(o)),i&&(o=ko(o)),o}function vo(e,t){return Vt(e,N.agent,t)}function bo(e,t){return or(e,N.agent,t)}function wo(e){return rt(e,N.group)}function _o(e,t){return vr(e,N.group,t)}function So(e,t){return Vt(e,N.group,t)}function Eo(e,t){return or(e,N.group,t)}function Ao(e){return rt(e,N.agent).filter((e=>e===N.PublicAgent)).length>0}function Ro(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setPublic` no longer takes a second parameter. It is now used together with `removePublic` instead.");return Vt(e,N.agent,N.PublicAgent)}function Io(e){return or(e,N.agent,N.PublicAgent)}function To(e){return rt(e,N.agent).filter((e=>e===N.AuthenticatedAgent)).length>0}function xo(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setAuthenticated` no longer takes a second parameter. It is now used together with `removeAuthenticated` instead.");return Vt(e,N.agent,N.AuthenticatedAgent)}function Po(e){return or(e,N.agent,N.AuthenticatedAgent)}function Co(e){return rt(e,N.agent).filter((e=>e===N.CreatorAgent)).length>0}function ko(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setCreator` no longer takes a second parameter. It is now used together with `removeCreator` instead.");return Vt(e,N.agent,N.CreatorAgent)}function Oo(e){return or(e,N.agent,N.CreatorAgent)}function Fo(e){return rt(e,N.client).filter((e=>e!==D))}function No(e,t){const r=Uo(e);let n=vr(e,N.client,t);return r&&(n=jo(n)),n}function Do(e,t){return Vt(e,N.client,t)}function Lo(e,t){return or(e,N.client,t)}function Uo(e){return rt(e,N.client).filter((e=>e===D)).length>0}function jo(e){return Vt(e,N.client,D)}function Mo(e){return or(e,N.client,D)}function Bo(e){let t=`## Rule: ${wt(e)}\n\n`,r="";Ao(e)&&(r+="- Everyone\n"),To(e)&&(r+="- All authenticated agents\n"),Co(e)&&(r+="- The creator of this resource\n"),Uo(e)&&(r+="- Users of any client application\n");const n=yo(e);n.length>0&&(r+="- The following agents:\n - ",r+=`${n.join("\n - ")}\n`);const i=wo(e);i.length>0&&(r+="- Members of the following groups:\n - ",r+=`${i.join("\n - ")}\n`);const o=Fo(e);return o.length>0&&(r+="- Users of the following client applications:\n - ",r+=`${o.join("\n - ")}\n`),t+=r.length>0?`This rule applies to:\n${r}`:"\n",t}function Ho(e){return rt(e,P).includes(N.Policy)}function Wo(e){let t=vt({url:g(e)});return t=mr(t,P,N.Policy),t}function $o(e,t){const r=pt(e,t);return null!==r&&Ho(r)?r:null}function Vo(e){return gt(e).filter((e=>!Et(e)&&Ho(e)))}function Ko(e,t){return mt(e,t)}function Jo(e,t){return yt(e,t)}function Go(e,t){let r=nr(e,N.allow);return!0===t.read&&(r=Vt(r,N.allow,$r.read)),!0===t.append&&(r=Vt(r,N.allow,$r.append)),!0===t.write&&(r=Vt(r,N.allow,$r.write)),r}function qo(e,t){let r=nr(e,N.allow);return!0===t.read&&(r=Vt(r,N.allow,N.Read)),!0===t.append&&(r=Vt(r,N.allow,N.Append)),!0===t.write&&(r=Vt(r,N.allow,N.Write)),r}function zo(e){const t=rt(e,N.allow);return{read:t.includes($r.read),append:t.includes($r.append),write:t.includes($r.write)}}function Yo(e){const t=rt(e,N.allow);return{read:t.includes(N.Read),append:t.includes(N.Append),write:t.includes(N.Write)}}function Qo(e,t){let r=nr(e,N.deny);return!0===t.read&&(r=Vt(r,N.deny,$r.read)),!0===t.append&&(r=Vt(r,N.deny,$r.append)),!0===t.write&&(r=Vt(r,N.deny,$r.write)),r}function Xo(e,t){let r=nr(e,N.deny);return!0===t.read&&(r=Vt(r,N.deny,N.Read)),!0===t.append&&(r=Vt(r,N.deny,N.Append)),!0===t.write&&(r=Vt(r,N.deny,N.Write)),r}function Zo(e){const t=rt(e,N.deny);return{read:t.includes($r.read),append:t.includes($r.append),write:t.includes($r.write)}}function es(e){const t=rt(e,N.deny);return{read:t.includes(N.Read),append:t.includes(N.Append),write:t.includes(N.Write)}}function ts(e,t){const r=jn(e),n=new URL($(r));n.hash=`#${t}`;let i=vt({url:n.href});return i=mr(i,P,N.Policy),i}function rs(e,t){const r=jn(e),n=$(r),i=new URL(n);i.hash=`#${t}`;const o=pt(r,i.href);return ci(e).includes(i.href)&&null!==o&&Ho(o)?o:null}function ns(e,t){const r=jn(e),n=$(r),i=new URL(n);i.hash=`#${t}`;const o=pt(r,i.href);return ei(e).includes(i.href)&&null!==o&&Ho(o)?o:null}function is(e){const t=jn(e);return ci(e).map((e=>pt(t,e))).filter((e=>null!==e&&Ho(e)))}function os(e){const t=jn(e);return ei(e).map((e=>pt(t,e))).filter((e=>null!==e&&Ho(e)))}function ss(e,t){const r=jn(e);let n,i=t;if("string"==typeof i&&!1===Se(i)){const e=new URL($(r));e.hash=`#${t}`,i=e.href}return n="string"==typeof i?i:be(i)?g(i):wt(i,$(r)),null===rs(e,new URL(n).hash.substring(1))?e:ui(Mn(e,mt(r,i)),n)}function as(e,t){const r=jn(e);let n,i=t;if("string"==typeof i&&!1===Se(i)){const e=new URL($(r));e.hash=`#${t}`,i=e.href}return n="string"==typeof i?i:be(i)?g(i):wt(i,$(r)),null===ns(e,new URL(n).hash.substring(1))?e:ri(Mn(e,mt(r,i)),n)}function cs(e,t){const r=jn(e);return si(Mn(e,yt(r,t)),wt(t,$(r)))}function ls(e,t){const r=jn(e);return Xn(Mn(e,yt(r,t)),wt(t,$(r)))}function us(e){function t(e,t){return t?"denied":e?"allowed":"unspecified"}const r=Yo(e),n=es(e);let i=`## Policy: ${wt(e)}\n\n`;i+=`- Read: ${t(r.read,n.read)}\n`,i+=`- Append: ${t(r.append,n.append)}\n`,i+=`- Write: ${t(r.write,n.write)}\n`;const o=Yi(e),s=eo(e),a=io(e);return 0===o.length&&0===s.length&&0===a.length&&(i+="\n\n"),o.length>0&&(i+="\nAll of these rules should match:\n",i+=`- ${o.join("\n- ")}\n`),s.length>0&&(i+="\nAt least one of these rules should match:\n",i+=`- ${s.join("\n- ")}\n`),a.length>0&&(i+="\nNone of these rules should match:\n",i+=`- ${a.join("\n- ")}\n`),i}function ds(e){return{...Ht(new URL("access-control-resource",e).href),accessTo:e}}function hs(e,t=ds($(e))){return Object.assign(v(e),{internal_acp:{acr:t,aprs:{}}})}function fs(e,t){return t?Ro(e):Io(e)}function ps(e,t){return t?xo(e):Po(e)}function gs(e,t){return t?ko(e):Oo(e)}const ys={getFileWithAccessDatasets:ji,getFileWithAcr:Di,getReferencedPolicyUrlAll:$i,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,saveAcrFor:Bi,acrAsMarkdown:pi,addAcrPolicyUrl:Xn,addMemberAcrPolicyUrl:Zn,addMemberPolicyUrl:ai,addPolicyUrl:si,getAcrPolicyUrlAll:ei,getMemberAcrPolicyUrlAll:ti,getMemberPolicyUrlAll:li,getPolicyUrlAll:ci,hasLinkedAcr:Qn,removeAcrPolicyUrl:ri,removeAcrPolicyUrlAll:ii,removeMemberAcrPolicyUrl:ni,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:di,removeMemberPolicyUrlAll:fi,removePolicyUrl:ui,removePolicyUrlAll:hi,createPolicy:Wo,getAllowModes:Yo,getDenyModes:es,getPolicy:$o,getPolicyAll:Vo,policyAsMarkdown:us,removePolicy:Ko,setAllowModes:qo,setDenyModes:Xo,setPolicy:Jo,addAgent:vo,addForbiddenRuleUrl:to,addGroup:So,addOptionalRuleUrl:Qi,addRequiredRuleUrl:Gi,createRule:oo,getAgentAll:yo,getForbiddenRuleUrlAll:io,getGroupAll:wo,getOptionalRuleUrlAll:eo,getRequiredRuleUrlAll:Yi,getRule:ao,getRuleAll:lo,hasAuthenticated:To,hasCreator:Co,hasPublic:Ao,removeAgent:bo,removeForbiddenRuleUrl:ro,removeGroup:Eo,removeOptionalRuleUrl:Xi,removeRequiredRuleUrl:qi,removeRule:ho,ruleAsMarkdown:Bo,setAgent:mo,setForbiddenRuleUrl:no,setGroup:_o,setOptionalRuleUrl:Zi,setRequiredRuleUrl:zi,setRule:po,addMockAcrTo:hs,mockAcrFor:ds,getForbiddenRuleurlAll:io,setPublic:fs,setAuthenticated:ps,setCreator:gs},ms={getFileWithAccessDatasets:ji,getFileWithAcr:Di,getReferencedPolicyUrlAll:$i,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,saveAcrFor:Bi,createPolicy:Wo,getAllowModes:Yo,getDenyModes:es,getPolicy:$o,getPolicyAll:Vo,policyAsMarkdown:us,removePolicy:Ko,setAllowModes:qo,setDenyModes:Xo,setPolicy:Jo,addAgent:vo,addForbiddenRuleUrl:to,addGroup:So,addOptionalRuleUrl:Qi,addRequiredRuleUrl:Gi,createRule:oo,getAgentAll:yo,getForbiddenRuleUrlAll:io,getGroupAll:wo,getOptionalRuleUrlAll:eo,getRequiredRuleUrlAll:Yi,getRule:ao,getRuleAll:lo,hasAuthenticated:To,hasCreator:Co,hasPublic:Ao,removeAgent:bo,removeForbiddenRuleUrl:ro,removeGroup:Eo,removeOptionalRuleUrl:Xi,removeRequiredRuleUrl:qi,removeRule:ho,ruleAsMarkdown:Bo,setAgent:mo,setForbiddenRuleUrl:no,setGroup:_o,setOptionalRuleUrl:Zi,setRequiredRuleUrl:zi,setRule:po,addMockAcrTo:hs,mockAcrFor:ds,hasLinkedAcr:Qn,addAcrPolicyUrl:Xn,addMemberAcrPolicyUrl:Zn,getAcrPolicyUrlAll:ei,getMemberAcrPolicyUrlAll:ti,removeAcrPolicyUrl:ri,removeAcrPolicyUrlAll:ii,removeMemberAcrPolicyUrl:ni,removeMemberAcrPolicyUrlAll:oi,createControl:Bn,getControl:function(e,t,r){const n=pt(jn(e),t,r);return null!==n&&rt(n,P).includes(N.AccessControl)?n:null},getAllControl:Hn,getControlAll:Hn,setControl:Wn,removeControl:function(e,t){return Mn(e,mt(jn(e),t))},addPolicyUrl:$n,getPolicyUrlAll:Vn,removePolicyUrl:Kn,removePolicyUrlAll:Jn,addMemberPolicyUrl:Gn,getMemberPolicyUrlAll:qn,removeMemberPolicyUrl:qn,removeMemberPolicyUrlAll:zn,getForbiddenRuleurlAll:io,setPublic:fs,setAuthenticated:ps,setCreator:gs},vs={getFileWithAccessDatasets:ji,getFileWithAcr:Di,getLinkedAcrUrl:Ki,getReferencedPolicyUrlAll:$i,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,saveAcrFor:Bi,isAcpControlled:Vi,acrAsMarkdown:pi,addAcrPolicyUrl:Xn,addMemberAcrPolicyUrl:Zn,addMemberPolicyUrl:ai,addPolicyUrl:si,getAcrPolicyUrlAll:ei,getMemberAcrPolicyUrlAll:ti,getMemberPolicyUrlAll:li,getPolicyUrlAll:ci,hasLinkedAcr:Qn,removeAcrPolicyUrl:ri,removeAcrPolicyUrlAll:ii,removeMemberAcrPolicyUrl:ni,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:di,removeMemberPolicyUrlAll:fi,removePolicyUrl:ui,removePolicyUrlAll:hi,createPolicy:Wo,getAllowModes:Yo,getDenyModes:es,getPolicy:$o,getPolicyAll:Vo,policyAsMarkdown:us,removePolicy:Ko,setAllowModes:qo,setDenyModes:Xo,setPolicy:Jo,createResourcePolicyFor:ts,getResourceAcrPolicy:ns,getResourceAcrPolicyAll:os,getResourcePolicy:rs,getResourcePolicyAll:is,removeResourceAcrPolicy:as,removeResourcePolicy:ss,setResourceAcrPolicy:ls,setResourcePolicy:cs,addAgent:vo,addGroup:So,createRule:oo,getAgentAll:yo,getGroupAll:wo,getRule:ao,getRuleAll:lo,removeAgent:bo,removeGroup:Eo,removeRule:ho,ruleAsMarkdown:Bo,setAgent:mo,setGroup:_o,setRule:po,addClient:Do,getClientAll:Fo,hasAnyClient:Uo,removeClient:Lo,setAnyClient:jo,setClient:No,removeAnyClient:Mo,hasAuthenticated:To,hasCreator:Co,hasPublic:Ao,setAuthenticated:xo,setCreator:ko,setPublic:Ro,removeAuthenticated:Po,removeCreator:Oo,removePublic:Io,getAnyOfRuleUrlAll:eo,addAnyOfRuleUrl:Qi,removeAnyOfRuleUrl:Xi,setAnyOfRuleUrl:Zi,getAllOfRuleUrlAll:Yi,addAllOfRuleUrl:Gi,removeAllOfRuleUrl:qi,setAllOfRuleUrl:zi,getNoneOfRuleUrlAll:io,addNoneOfRuleUrl:to,removeNoneOfRuleUrl:ro,setNoneOfRuleUrl:no,createResourceRuleFor:so,getResourceRule:co,getResourceRuleAll:uo,removeResourceRule:fo,setResourceRule:go,addMockAcrTo:hs,mockAcrFor:ds};function bs(e,t){return Object.assign(v(e),{internal_acp:{...e.internal_acp,acr:yt(e.internal_acp.acr,t)}})}function ws(e){return e.includes("Member")?yi.memberAccessControl:yi.accessControl}function _s(e,t){const r=Ai(e,t),n=jn(e);let i=bi(e);return null==i&&(i=vt({url:$(n)})),rt(i,ws(t)).includes(r)?e:(i=Cr(i).addUrl(ws(t),r).build(),bs(e,i))}function Ss(e,t){const r=_s(e,_i);return bs(r,Cr(Ri(r,_i)).addUrl(yi.access,t).build())}function Es(e,t){const r=_s(e,Ei);return bs(r,Cr(Ri(r,Ei)).addUrl(yi.access,t).build())}function As(e,t){const r=_s(e,Si);return bs(r,Cr(Ri(r,Si)).addUrl(yi.apply,t).build())}function Rs(e,t){const r=_s(e,wi);return bs(r,Cr(Ri(r,wi)).addUrl(yi.apply,t).build())}function Is(e){const t=bi(e);return null===t?[]:rt(t,yi.accessControl)}function Ts(e,t,r){const n=jn(e);return Array.from(new Set(t.map((e=>{const t=pt(n,e);return null!==t?rt(t,r):[]})).reduce(((e,t)=>e.concat(t)),[])))}function xs(e){return Ts(e,Is(e),yi.access)}function Ps(e){const t=bi(e);return null===t?[]:rt(t,yi.memberAccessControl)}function Cs(e){return Ts(e,Ps(e),yi.access)}function ks(e){return Ts(e,Ps(e),yi.apply)}function Os(e){return Ts(e,Is(e),yi.apply)}function Fs(e,t){const r=Ri(e,_i);return bs(e,or(r,yi.access,t))}function Ns(e,t){const r=Ri(e,Ei);return bs(e,or(r,yi.access,t))}function Ds(e,t){const r=Ri(e,Si);return bs(e,or(r,yi.apply,t))}function Ls(e,t){const r=Ri(e,wi);return bs(e,or(r,yi.apply,t))}function Us(e,t){return bs(e,t)}function js(e){return rt(e,P).includes(N.Matcher)}function Ms(e,t){return Vt(e,N.allOf,t)}function Bs(e,t){return or(e,N.allOf,t)}function Hs(e,t){return vr(e,N.allOf,t)}function Ws(e){return rt(e,N.allOf)}function $s(e,t){return Vt(e,N.anyOf,t)}function Vs(e,t){return or(e,N.anyOf,t)}function Ks(e,t){return vr(e,N.anyOf,t)}function Js(e){return rt(e,N.anyOf)}function Gs(e,t){return Vt(e,N.noneOf,t)}function qs(e,t){return or(e,N.noneOf,t)}function zs(e,t){return vr(e,N.noneOf,t)}function Ys(e){return rt(e,N.noneOf)}function Qs(e){let t=vt({url:g(e)});return t=mr(t,P,N.Matcher),t}function Xs(e,t){const r=jn(e),n=new URL($(r));n.hash=`#${t}`;let i=vt({url:n.href});return i=mr(i,P,N.Matcher),i}function Zs(e,t){const r=pt(e,t);return null!==r&&js(r)?r:null}function ea(e,t){const r=jn(e),n=$(r),i=new URL(n);i.hash=`#${t}`;const o=pt(r,i.href);return null!==o&&js(o)?o:null}function ta(e){return gt(e).filter(js)}function ra(e){return gt(jn(e)).filter(js)}function na(e,t){return mt(e,t)}function ia(e,t){const r=jn(e);let n;if("string"==typeof t)if(Se(t))n=t;else{const e=new URL($(r));e.hash=`#${t}`,n=e.href}else n=be(t)?g(t):wt(t);const i=ea(e,new URL(n).hash.substring(1));return null===i?e:Mn(e,mt(r,i))}function oa(e,t){return yt(e,t)}function sa(e,t){return Mn(e,yt(jn(e),t))}function aa(e){return rt(e,N.agent).filter((e=>e!==N.PublicAgent&&e!==N.AuthenticatedAgent&&e!==N.CreatorAgent))}function ca(e,t){const r=da(e),n=pa(e),i=ma(e);let o=vr(e,N.agent,t);return r&&(o=ha(o)),n&&(o=ga(o)),i&&(o=va(o)),o}function la(e,t){return Vt(e,N.agent,t)}function ua(e,t){return or(e,N.agent,t)}function da(e){return rt(e,N.agent).filter((e=>e===N.PublicAgent)).length>0}function ha(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setPublic` no longer takes a second parameter. It is now used together with `removePublic` instead.");return Vt(e,N.agent,N.PublicAgent)}function fa(e){return or(e,N.agent,N.PublicAgent)}function pa(e){return rt(e,N.agent).filter((e=>e===N.AuthenticatedAgent)).length>0}function ga(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setAuthenticated` no longer takes a second parameter. It is now used together with `removeAuthenticated` instead.");return Vt(e,N.agent,N.AuthenticatedAgent)}function ya(e){return or(e,N.agent,N.AuthenticatedAgent)}function ma(e){return rt(e,N.agent).filter((e=>e===N.CreatorAgent)).length>0}function va(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setCreator` no longer takes a second parameter. It is now used together with `removeCreator` instead.");return Vt(e,N.agent,N.CreatorAgent)}function ba(e){return or(e,N.agent,N.CreatorAgent)}function wa(e){return rt(e,N.client).filter((e=>e!==D)).concat(ot(e,N.client))}function _a(e,t){return Se(t)?Vt(e,N.client,t):Xt(e,N.client,t)}function Sa(e,t){return Se(t)?or(e,N.client,t):fr(e,N.client,t)}function Ea(e){return rt(e,N.client).filter((e=>e===D)).length>0}function Aa(e){return Vt(e,N.client,D)}const Ra={getFileWithAccessDatasets:ji,getFileWithAcr:Di,getReferencedPolicyUrlAll:$i,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,saveAcrFor:Bi,isAcpControlled:Vi,getVcAccess:Fi,setVcAccess:Ci,addAcrPolicyUrl:Ss,addMemberAcrPolicyUrl:Es,addMemberPolicyUrl:As,addPolicyUrl:Rs,getAcrPolicyUrlAll:xs,getMemberAcrPolicyUrlAll:Cs,getMemberPolicyUrlAll:ks,getPolicyUrlAll:Os,hasLinkedAcr:Qn,removeAcrPolicyUrl:Fs,removeAcrPolicyUrlAll:ii,removeMemberAcrPolicyUrl:Ns,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:Ds,removeMemberPolicyUrlAll:fi,removePolicyUrl:Ls,removePolicyUrlAll:hi,createPolicy:Wo,getAllowModes:zo,getDenyModes:Zo,getPolicy:$o,getPolicyAll:Vo,removePolicy:Ko,setAllowModes:Go,setDenyModes:Qo,setPolicy:Jo,createResourcePolicyFor:ts,getResourceAcrPolicy:ns,getResourceAcrPolicyAll:os,getResourcePolicy:rs,getResourcePolicyAll:is,removeResourceAcrPolicy:as,removeResourcePolicy:ss,setResourcePolicy:Us,addAgent:la,createMatcher:Qs,getAgentAll:aa,getMatcher:Zs,getMatcherAll:ta,removeAgent:ua,removeMatcher:na,setAgent:ca,setMatcher:oa,addClient:_a,getClientAll:wa,hasAnyClient:Ea,removeClient:Sa,setAnyClient:Aa,setClient:function(e,t){const r=Ea(e);let n=vr(e,N.client,t);return r&&(n=Aa(n)),n},removeAnyClient:function(e){return or(e,N.client,D)},hasAuthenticated:pa,hasCreator:ma,hasPublic:da,setAuthenticated:ga,setCreator:va,setPublic:ha,removeAuthenticated:ya,removeCreator:ba,removePublic:fa,getAnyOfMatcherUrlAll:Js,addAnyOfMatcherUrl:$s,removeAnyOfMatcherUrl:Vs,setAnyOfMatcherUrl:Ks,getAllOfMatcherUrlAll:Ws,addAllOfMatcherUrl:Ms,removeAllOfMatcherUrl:Bs,setAllOfMatcherUrl:Hs,getNoneOfMatcherUrlAll:Ys,addNoneOfMatcherUrl:Gs,removeNoneOfMatcherUrl:qs,setNoneOfMatcherUrl:zs,createResourceMatcherFor:Xs,getResourceMatcher:ea,getResourceMatcherAll:ra,removeResourceMatcher:ia,setResourceMatcher:sa,addMockAcrTo:hs,mockAcrFor:ds},Ia=[N.agent,N.group];function Ta(e,t,r){if(e.inaccessibleUrls.length>0)return null;const n=e.acrPolicies.filter((n=>xa(n,t,r,e))),i=e.policies.filter((n=>xa(n,t,r,e))),o=n.reduce(((e,t)=>{const r={...e},n=Yo(t);return n.read&&(r.controlRead=!0),n.write&&(r.controlWrite=!0),r}),{read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1}),s=i.reduce(((e,t)=>{const r={...e},n=Yo(t);return n.read&&(r.read=!0),n.append&&(r.append=!0),n.write&&(r.write=!0),r}),o),a=n.reduce(((e,t)=>{const r={...e},n=es(t);return!0===n.read&&(r.controlRead=!1),!0===n.write&&(r.controlWrite=!1),r}),s);return i.reduce(((e,t)=>{const r={...e},n=es(t);return!0===n.read&&(r.read=!1),!0===n.append&&(r.append=!1),!0===n.write&&(r.write=!1),r}),a)}function xa(e,t,r,n){const i=rt(e,N.allow),o=rt(e,N.deny);if(i.length+o.length===0)return!1;const s=Yi(e).map((e=>n.rules.find((t=>_t(t)===e)))),a=eo(e).map((e=>n.rules.find((t=>_t(t)===e)))),c=io(e).map((e=>n.rules.find((t=>_t(t)===e))));return s.every((e=>Ca(e,t,r)))&&(0===a.length||a.some((e=>Ca(e,t,r))))&&0===c.length}function Pa(e,t){const r=rt(e,N.allow),n=rt(e,N.deny);return!0===t.read&&n.includes(N.Read)||!1===t.read&&r.includes(N.Read)&&!n.includes(N.Read)||!0===t.append&&n.includes(N.Append)||!1===t.append&&r.includes(N.Append)&&!n.includes(N.Append)||!0===t.write&&n.includes(N.Write)||!1===t.write&&r.includes(N.Write)&&!n.includes(N.Write)}function Ca(e,t,r){let n=!0;return Ia.forEach((t=>{n&&(n=null===et(e,t))})),n||rt(e,t).includes(r)}function ka(e,t){if(e.inaccessibleUrls.length>0)return null;const r={},n=function(e,t){const r=new Set;return e.rules.forEach((e=>{rt(e,t).filter((e=>![N.PublicAgent,N.CreatorAgent,N.AuthenticatedAgent].includes(e)||t!==N.agent)).forEach((e=>r.add(e)))})),r}(e,t);return n.forEach((n=>{const i=Ta(e,t,n);r[n]=i})),r}function Oa(e,t,r,n,i){var o,s,a,c,l;if(!Hi(e)||t.inaccessibleUrls.length>0)return null;const d=Ta(t,r,n);if(null===d)return null;const h=t.acrPolicies.filter((e=>xa(e,r,n,t))),f=t.policies.filter((e=>xa(e,r,n,t))),p=h.filter((e=>Pa(e,{read:i.controlRead,write:i.controlWrite}))),g=f.filter((e=>Pa(e,{read:i.read,append:i.append,write:i.write}))),y=p.filter((e=>Fa(e,r,n,t))),m=g.filter((e=>Fa(e,r,n,t))),v=Ta({...t,acrPolicies:t.acrPolicies.filter((e=>!y.includes(e))),policies:t.policies.filter((e=>!m.includes(e)))},r,n);if(null===v)return null;let b=e;y.forEach((i=>{const[o,s]=Da(i,e,t,r,n);b=ls(b,o),b=s.reduce(go,b)})),m.forEach((i=>{const[o,s]=Da(i,e,t,r,n);b=cs(b,o),b=s.reduce(go,b)}));const w=`rule_${encodeURIComponent(`${r}_${n}`)}`;let _=so(e,w);_=vr(_,r,n);const S=null!==(o=i.controlRead)&&void 0!==o?o:d.controlRead,E=null!==(s=i.controlWrite)&&void 0!==s?s:d.controlWrite;let A=y;if(S!==v.controlRead||E!==v.controlWrite){const t=u.v4();let r=ts(e,t);r=qo(r,{read:!0===S,append:!1,write:!0===E}),r=Vt(r,N.allOf,_),b=ls(b,r),b=go(b,_),A=p}const R=null!==(a=i.read)&&void 0!==a?a:d.read,I=null!==(c=i.append)&&void 0!==c?c:d.append,T=null!==(l=i.write)&&void 0!==l?l:d.write;let x=m;if(R!==v.read||I!==v.append||T!==v.write){const t=u.v4();let r=ts(e,t);r=qo(r,{read:!0===R,append:!0===I,write:!0===T}),r=Vt(r,N.allOf,_),b=cs(b,r),b=go(b,_),x=g}return A.forEach((e=>{b=ri(b,_t(e))})),x.forEach((e=>{b=ui(b,_t(e))})),b}function Fa(e,t,r,n){const i=rt(e,N.allOf).map((e=>n.rules.find((t=>_t(t)===e)))).some((e=>Na(e,t,r))),o=rt(e,N.anyOf).map((e=>n.rules.find((t=>_t(t)===e)))).some((e=>Na(e,t,r))),s=rt(e,N.noneOf).map((e=>n.rules.find((t=>_t(t)===e)))).some((e=>Na(e,t,r)));return i||o||s}function Na(e,t,r){const n=[];return Ia.forEach((i=>{const o=rt(e,i).filter((e=>e!==r||i!==t));n.push(...o)})),n.length>0}function Da(e,t,r,n,i){const o=u.v4(),s=La(rt(e,N.allOf),t,r,o,n,i),a=La(rt(e,N.anyOf),t,r,o,n,i),c=La(rt(e,N.noneOf),t,r,o,n,i);let l=ts(t,encodeURI(_t(e))+o);return rt(e,N.allow).forEach((e=>{l=Vt(l,N.allow,e)})),rt(e,N.deny).forEach((e=>{l=Vt(l,N.deny,e)})),s.forEach((e=>{l=Vt(l,N.allOf,e)})),a.forEach((e=>{l=Vt(l,N.anyOf,e)})),c.forEach((e=>{l=Vt(l,N.noneOf,e)})),[l,s.concat(a).concat(c)]}function La(e,t,r,n,i,o){return e.map((e=>{const s=r.rules.find((t=>_t(t)===e));if(void 0===s)return null;let a=so(t,encodeURI(_t(s))+n),c=!1;return Ia.forEach((e=>{rt(s,e).forEach((t=>{e===i&&t===o||(c=!0,a=Vt(a,e,t))}))})),c?a:null})).filter(Ua)}function Ua(e){return null!==e}async function ja(e,t=j){const r=ei(e),n=ci(e),i=Ba(r).concat(Ba(n)),o=await Ha(i,t),s=Wa(r,o).filter(Ua),a=Wa(n,o).filter(Ua),c=new Set;s.forEach((e=>{$a(e).forEach((e=>{c.add(e)}))})),a.forEach((e=>{$a(e).forEach((e=>{c.add(e)}))}));const l=Array.from(c),u=l.map((e=>Ma(e))).filter((e=>!i.includes(e))),d=await Ha(u,t),h={...o,...d},f=Wa(l,h).filter(Ua);return{inaccessibleUrls:Object.keys(h).filter((e=>null===h[e])),acrPolicies:s,policies:a,rules:f}}function Ma(e){const t=new URL(e);return t.hash="",t.href}function Ba(e){const t=[];return e.forEach((e=>{const r=Ma(e);t.includes(r)||t.push(r)})),t}async function Ha(e,t){const r=Array.from(new Set(e)),n={};return await Promise.all(r.map((async e=>{try{const r=await Ot(e,t);n[e]=r}catch(t){n[e]=null}}))),n}function Wa(e,t){return e.map((e=>{const r=Ma(e),n=t[r];return n?pt(n,e):null}))}function $a(e){return Yi(e).concat(eo(e)).concat(io(e))}function Va(e,t){var r,n,i,o;if(e.controlRead!==e.controlWrite)throw new Error("For Pods using Web Access Control, controlRead and controlWrite must be equal.");return{read:null!==(r=e.read)&&void 0!==r?r:t.read,append:null!==(n=e.append)&&void 0!==n?n:t.append,write:null!==(i=e.write)&&void 0!==i?i:t.write,control:null!==(o=e.controlRead)&&void 0!==o?o:t.control}}function Ka(e){return{read:e.read,write:e.write,append:e.append,controlRead:e.control,controlWrite:e.control}}async function Ja(e,t,r,n){const i=r(Gr(e,await Or(e,n)),t);return null===i?null:Ka(i)}async function Ga(e,t,r){const n=t(Gr(e,await Or(e,r)));if(null===n)return null;const i={};for(const[e,t]of Object.entries(n))i[e]=Ka(t);return i}function qa(e,t,r=j){return Ja(e,t,an,r)}function za(e,t,r=j){return Ja(e,t,vn,r)}function Ya(e,t=j){return async function(e,t,r){const n=t(Gr(e,await Or(e,r)));return null===n?null:Ka(n)}(e,Tn,t)}function Qa(e,t=j){return Ga(e,cn,t)}async function Xa(e,t){if(!sn(e))return null;const r=Gr(e,await Or(e,t));let n;if(Xr(r))n=function(e){return e.internal_acl.resourceAcl}(r);else{if(!en(r))return null;n=nn(r)}return Yr(r,n)}async function Za(e,t,r){let n=null;try{return n=await on(e,t,r),Yr(e,n)}catch(e){return null}}async function ec(e,t,r,n,i,o){const s=await Xa(e,o);if(null===s)return null;const a=n(s,t);return Za(s,i(Zr(s),t,Va(r,a)),o)}async function tc(e,t,r,n=j){return ec(e,t,r,an,dn,n)}async function rc(e,t,r=j){return async function(e,t,r,n,i){const o=await Xa(e,i);return null===o?null:Za(o,n(Zr(o),Va(t,r(o))),i)}(e,t,Tn,Cn,r)}var nc=Object.freeze({__proto__:null,getAccessFor:ic,getAccessForAll:oc,getAgentAccess:ac,getAgentAccessAll:lc,getGroupAccess:uc,getGroupAccessAll:dc,getPublicAccess:fc,setAccessFor:sc,setAgentAccess:cc,setGroupAccess:hc,setPublicAccess:pc});async function ic(e,t,r=j,n=j){if("agent"===t){if("string"!=typeof r)throw new Error("When reading Agent-specific access, the given agent cannot be left undefined.");return ac(e,r,n)}if("group"===t){if("string"!=typeof r)throw new Error("When reading Group-specific access, the given group cannot be left undefined.");return uc(e,r,n)}if("public"===t){if("string"==typeof r)throw new Error(`When reading public access, no actor type should be specified (here [${r}]).`);return fc(e,r)}return null}async function oc(e,t,r=j){return"agent"===t?lc(e,r):"group"===t?dc(e,r):null}async function sc(e,t,r,n=j,i=j){if("agent"===t){if("string"!=typeof n)throw new Error("When writing Agent-specific access, the given agent cannot be left undefined.");return cc(e,n,r,i)}if("group"===t){if("string"!=typeof n)throw new Error("When writing Group-specific access, the given group cannot be left undefined.");return hc(e,n,r,i)}if("public"===t){if("string"==typeof n)throw new Error(`When writing public access, no actor type should be specified (here [${n}]).`);return pc(e,r,n)}return null}async function ac(e,t,r=j){const n=await Li(e,r);return Hi(n)?function(e,t){return Ta(e,N.agent,t)}(await ja(n,r),t):sn(n)?qa(n,t,r):null}async function cc(e,t,r,n=j){const i=await Li(e,n);if(Hi(i)){const o=function(e,t,r,n){return Oa(e,t,N.agent,r,n)}(i,await ja(i,n),t,r);if(o)try{return await Bi(o,n),await ac(e,t,n)}catch(e){return null}return null}if(sn(i)){if(r.controlRead!==r.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(i)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=r;return await tc(i,t,e,n),qa(i,t,n)}return null}async function lc(e,t=j){const r=await Li(e,t);return Hi(r)?ka(await ja(r,t),N.agent):sn(r)?Qa(r,t):null}async function uc(e,t,r=j){const n=await Li(e,r);return Hi(n)?(i=await ja(n,r),o=t,Ta(i,N.group,o)):sn(n)?za(n,t,r):null;var i,o}async function dc(e,t=j){const r=await Li(e,t);return Hi(r)?ka(await ja(r,t),N.group):sn(r)?function(e,t=j){return Ga(e,bn,t)}(r,t):null}async function hc(e,t,r,n=j){const i=await Li(e,n);if(Hi(i)){const o=function(e,t,r,n){return Oa(e,t,N.group,r,n)}(i,await ja(i,n),t,r);if(o)try{return await Bi(o,n),await uc(e,t,n)}catch(e){return null}return null}if(sn(i)){if(r.controlRead!==r.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(i)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=r;return await async function(e,t,r,n=j){return ec(e,t,r,vn,In,n)}(i,t,e,n),za(i,t,n)}return null}async function fc(e,t=j){const r=await Li(e,t);return Hi(r)?Ta(await ja(r,t),N.agent,N.PublicAgent):sn(r)?Ya(r,t):null}async function pc(e,t,r=j){const n=await Li(e,r);if(Hi(n)){const i=function(e,t,r){return Oa(e,t,N.agent,N.PublicAgent,r)}(n,await ja(n,r),t);if(i)try{return await Bi(i,r),await fc(e,r)}catch(e){return null}return null}if(sn(n)){if(t.controlRead!==t.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(n)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=t;return await rc(n,e,r),Ya(n,r)}return null}var gc=Object.freeze({__proto__:null,getAccessFor:ic,getAccessForAll:oc,getAgentAccess:ac,getAgentAccessAll:lc,getGroupAccess:uc,getGroupAccessAll:dc,getPublicAccess:fc,setAccessFor:sc,setAgentAccess:cc,setGroupAccess:hc,setPublicAccess:pc});const yc=[N.agent];function mc(e,t,r){if(e.inaccessibleUrls.length>0)return null;const n=e.acrPolicies.filter((n=>vc(n,t,r,e))),i=e.policies.filter((n=>vc(n,t,r,e))),o=n.reduce(((e,t)=>{const r={...e},n=zo(t);return n.read&&(r.controlRead=!0),n.write&&(r.controlWrite=!0),r}),{read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1}),s=i.reduce(((e,t)=>{const r={...e},n=zo(t);return n.read&&(r.read=!0),n.append&&(r.append=!0),n.write&&(r.write=!0),r}),o),a=n.reduce(((e,t)=>{const r={...e},n=Zo(t);return!0===n.read&&(r.controlRead=!1),!0===n.write&&(r.controlWrite=!1),r}),s);return i.reduce(((e,t)=>{const r={...e},n=Zo(t);return!0===n.read&&(r.read=!1),!0===n.append&&(r.append=!1),!0===n.write&&(r.write=!1),r}),a)}function vc(e,t,r,n){const i=rt(e,N.allow),o=rt(e,N.deny);if(i.length+o.length===0)return!1;const s=Ws(e).map((e=>n.matchers.find((t=>_t(t)===e)))),a=Js(e).map((e=>n.matchers.find((t=>_t(t)===e)))),c=Ys(e).map((e=>n.matchers.find((t=>_t(t)===e))));return s.every((e=>wc(e,t,r)))&&(0===a.length||a.some((e=>wc(e,t,r))))&&s.length+a.length>0&&0===c.length}function bc(e,t){const r=rt(e,N.allow),n=rt(e,N.deny);return!0===t.read&&n.includes($r.read)||!1===t.read&&r.includes($r.read)&&!n.includes($r.read)||!0===t.append&&n.includes($r.append)||!1===t.append&&r.includes($r.append)&&!n.includes($r.append)||!0===t.write&&n.includes($r.write)||!1===t.write&&r.includes($r.write)&&!n.includes($r.write)}function wc(e,t,r){return rt(e,t).includes(r)}function _c(e,t,r,n,i){var o,s,a,c,l;if(!Hi(e)||t.inaccessibleUrls.length>0)return null;const d=mc(t,r,n);if(null===d)return null;const h=t.acrPolicies.filter((e=>vc(e,r,n,t))),f=t.policies.filter((e=>vc(e,r,n,t))),p=h.filter((e=>bc(e,{read:i.controlRead,write:i.controlWrite}))),g=f.filter((e=>bc(e,{read:i.read,append:i.append,write:i.write}))),y=p.filter((e=>Sc(e,r,n,t))),m=g.filter((e=>Sc(e,r,n,t))),v=mc({...t,acrPolicies:t.acrPolicies.filter((e=>!y.includes(e))),policies:t.policies.filter((e=>!m.includes(e)))},r,n);if(null===v)return null;let b=e;y.forEach((i=>{const[o,s]=Ac(i,e,t,r,n);b=ls(b,o),b=s.reduce(sa,b)})),m.forEach((i=>{const[o,s]=Ac(i,e,t,r,n);b=cs(b,o),b=s.reduce(sa,b)}));const w=`matcher_${encodeURIComponent(`${r}_${n}`)}`;let _=Xs(e,w);_=vr(_,r,n);const S=null!==(o=i.controlRead)&&void 0!==o?o:d.controlRead,E=null!==(s=i.controlWrite)&&void 0!==s?s:d.controlWrite;let A=y;if(S!==v.controlRead||E!==v.controlWrite){const t=u.v4();let r=ts(e,t);r=Go(r,{read:!0===S,append:!1,write:!0===E}),r=Vt(r,N.allOf,_),b=ls(b,r),b=sa(b,_),A=p}const R=null!==(a=i.read)&&void 0!==a?a:d.read,I=null!==(c=i.append)&&void 0!==c?c:d.append,T=null!==(l=i.write)&&void 0!==l?l:d.write;let x=m;if(R!==v.read||I!==v.append||T!==v.write){const t=u.v4();let r=ts(e,t);r=Go(r,{read:!0===R,append:!0===I,write:!0===T}),r=Vt(r,N.allOf,_),b=cs(b,r),b=sa(b,_),x=g}return A.forEach((e=>{b=ri(b,_t(e))})),x.forEach((e=>{b=ui(b,_t(e))})),b}function Sc(e,t,r,n){const i=rt(e,N.allOf).map((e=>n.matchers.find((t=>_t(t)===e)))).some((e=>Ec(e,t,r))),o=rt(e,N.anyOf).map((e=>n.matchers.find((t=>_t(t)===e)))).some((e=>Ec(e,t,r))),s=rt(e,N.noneOf).map((e=>n.matchers.find((t=>_t(t)===e)))).some((e=>Ec(e,t,r)));return i||o||s}function Ec(e,t,r){const n=[];return yc.forEach((i=>{const o=rt(e,i).filter((e=>e!==r||i!==t));n.push(...o)})),n.length>0}function Ac(e,t,r,n,i){const o=u.v4(),s=Rc(rt(e,N.allOf),t,r,o,n,i),a=Rc(rt(e,N.anyOf),t,r,o,n,i),c=Rc(rt(e,N.noneOf),t,r,o,n,i);let l=ts(t,encodeURI(_t(e))+o);return rt(e,N.allow).forEach((e=>{l=Vt(l,N.allow,e)})),rt(e,N.deny).forEach((e=>{l=Vt(l,N.deny,e)})),s.forEach((e=>{l=Vt(l,N.allOf,e)})),a.forEach((e=>{l=Vt(l,N.anyOf,e)})),c.forEach((e=>{l=Vt(l,N.noneOf,e)})),[l,s.concat(a).concat(c)]}function Rc(e,t,r,n,i,o){return e.map((e=>{const s=r.matchers.find((t=>_t(t)===e));if(void 0===s)return null;let a=Xs(t,encodeURI(_t(s))+n),c=!1;return yc.forEach((e=>{rt(s,e).forEach((t=>{e===i&&t===o||(c=!0,a=Vt(a,e,t))}))})),c?a:null})).filter(Ic)}function Ic(e){return null!==e}async function Tc(e,t=j){const r=ei(e),n=ci(e),i=Pc(r).concat(Pc(n)),o=await Cc(i,t),s=kc(r,o).filter(Ic),a=kc(n,o).filter(Ic),c=new Set;s.forEach((e=>{Oc(e).forEach((e=>{c.add(e)}))})),a.forEach((e=>{Oc(e).forEach((e=>{c.add(e)}))}));const l=Array.from(c),u=l.map((e=>xc(e))).filter((e=>!i.includes(e))),d=await Cc(u,t),h={...o,...d},f=kc(l,h).filter(Ic);return{inaccessibleUrls:Object.keys(h).filter((e=>null===h[e])),acrPolicies:s,policies:a,matchers:f}}function xc(e){const t=new URL(e);return t.hash="",t.href}function Pc(e){const t=[];return e.forEach((e=>{const r=xc(e);t.includes(r)||t.push(r)})),t}async function Cc(e,t){const r=Array.from(new Set(e)),n={};return await Promise.all(r.map((async e=>{try{const r=await Ot(e,t);n[e]=r}catch(t){n[e]=null}}))),n}function kc(e,t){return e.map((e=>{const r=xc(e),n=t[r];return n?pt(n,e):null}))}function Oc(e){return Ws(e).concat(Js(e)).concat(Ys(e))}async function Fc(e,t,r=j){const n=await Li(e,r);return Hi(n)?function(e,t){return mc(e,N.agent,t)}(await Tc(n,r),t):sn(n)?qa(n,t,r):null}async function Nc(e,t=j){const r=await Li(e,t);return Hi(r)?mc(await Tc(r,t),N.agent,N.PublicAgent):sn(r)?Ya(r,t):null}var Dc=Object.freeze({__proto__:null,getAccessFor:ic,getAccessForAll:oc,getAgentAccess:Fc,getAgentAccessAll:async function(e,t=j){const r=await Li(e,t);return Hi(r)?function(e,t){if(e.inaccessibleUrls.length>0)return null;const r={},n=function(e,t){const r=new Set;return e.matchers.forEach((e=>{rt(e,t).filter((e=>![N.PublicAgent,N.CreatorAgent,N.AuthenticatedAgent].includes(e)||t!==N.agent)).forEach((e=>r.add(e)))})),r}(e,t);return n.forEach((n=>{const i=mc(e,t,n);r[n]=i})),r}(await Tc(r,t),N.agent):sn(r)?Qa(r,t):null},getPublicAccess:Nc,setAccessFor:sc,setAgentAccess:async function(e,t,r,n=j){const i=await Li(e,n);if(Hi(i)){const o=function(e,t,r,n){return _c(e,t,N.agent,r,n)}(i,await Tc(i,n),t,r);if(o)try{return await Bi(o,n),await Fc(e,t,n)}catch(e){return null}return null}if(sn(i)){if(r.controlRead!==r.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(i)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=r;return await tc(i,t,e,n),qa(i,t,n)}return null},setPublicAccess:async function(e,t,r=j){const n=await Li(e,r);if(Hi(n)){const i=function(e,t,r){return _c(e,t,N.agent,N.PublicAgent,r)}(n,await Tc(n,r),t);if(i)try{return await Bi(i,r),await Nc(e,r)}catch(e){return null}return null}if(sn(n)){if(t.controlRead!==t.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(n)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=t;return await rc(n,e,r),Ya(n,r)}return null}});async function Lc(e,t){if("string"!=typeof e.internal_resourceInfo.aclUrl)return null;try{return await M(e.internal_resourceInfo.aclUrl,t)}catch(e){return null}}function Uc(e,t,r){const n=tt(t,yi.allOf).map((t=>pt(jn(e),t))).filter((e=>null!==e)),i=n.every((e=>tt(e,yi.agent).includes(r))),o=tt(t,yi.anyOf).map((t=>pt(jn(e),t))).filter((e=>null!==e)),s=o.some((e=>tt(e,yi.agent).includes(r))),a=tt(t,yi.noneOf).map((t=>pt(jn(e),t))).filter((e=>null!==e)),c=a.some((e=>tt(e,yi.agent).includes(r)));return n.length+o.length>0&&(0===n.length||i)&&(0===o.length||s)&&(0===a.length||!c)}function jc(e,t,r){const n=function(e){return Ii(e,yi.allow)}(e),i=function(e){return Ii(e,yi.deny)}(e);return"control"===r?{read:t.read,append:t.append,write:t.write,controlRead:(t.controlRead||n.read)&&!i.read,controlWrite:(t.controlWrite||n.write)&&!i.write}:{read:(t.read||n.read)&&!i.read,append:(t.append||n.append)&&!i.append,write:(t.write||n.write)&&!i.write,controlRead:t.controlRead,controlWrite:t.controlWrite}}async function Mc(e,t){let r={read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1};return Os(e).map((t=>pt(jn(e),t))).filter((e=>null!==e)).forEach((n=>{Uc(e,n,t)&&(r=jc(n,r,"resource"))})),xs(e).map((t=>pt(jn(e),t))).filter((e=>null!==e)).forEach((n=>{Uc(e,n,t)&&(r=jc(n,r,"control"))})),r}async function Bc(e,t){const r=await async function(e,t){const r=function(e){const t=e.internal_resourceInfo.linkedResources[yi.accessControl];return Array.isArray(t)&&1===t.length?t[0]:null}(e);if(null!==r)return r;const n=await Lc(e,t);if(null===n)return null;const i=J(n).type;return Array.isArray(i)&&i.includes(yi.AccessControlResource)?$(n):null}(e,t);if(null===r)return null;let n;try{n=await Ot(r,t)}catch(e){return null}return{...e,internal_acp:{acr:{...n,accessTo:$(e)}}}}async function Hc(e,t,r){const n=await M(e,r),i=await Bc(n,r);return null===i?qa(n,t,r):Mc(i,t)}async function Wc(e,t){const r=await M(e,t),n=await Bc(r,t);return null===n?Ya(r,t):async function(e){return Mc(e,yi.PublicAgent)}(n)}function $c(e,t,r){return Ai(e,t).concat("AgentMatcher").concat(r.charAt(0).toUpperCase()+r.slice(1)).concat("Policy")}function Vc(e,t,r){return $c(e,t,r).concat("Matcher")}const Kc=yi.anyOf;function Jc(e,t,r,n,i){var o;const s=Vc(e,r,n),a=function(e,t,r){const n=$c(e,t,r),i=Vc(e,t,r);let o=pt(jn(e),n);return o||(e=function(e,t,r){const n=$c(e,t,r);return n.includes("Acr")?Ss(e,n):Rs(e,n)}(e,t,r),o=vt({url:n}),o=Ti(o,{[r]:!0},yi.allow)),rt(o,Kc).includes(i)?e:(o=Cr(o).addUrl(Kc,i).build(),bs(e,o))}(e,r,n),c=null!==(o=pt(jn(a),s))&&void 0!==o?o:vt({url:s});return bs(a,"add"===i?la(c,t):ua(c,t))}async function Gc(e,t,r){const n=await Mc(e,t);return"boolean"==typeof r.read&&n.read!==r.read&&(e=Jc(e,t,wi,"read",r.read?"add":"remove")),"boolean"==typeof r.append&&n.append!==r.append&&(e=Jc(e,t,wi,"append",r.append?"add":"remove")),"boolean"==typeof r.write&&n.write!==r.write&&(e=Jc(e,t,wi,"write",r.write?"add":"remove")),"boolean"==typeof r.controlRead&&n.controlRead!==r.controlRead&&(e=Jc(e,t,_i,"controlRead",r.controlRead?"add":"remove")),"boolean"==typeof r.controlWrite&&n.controlWrite!==r.controlWrite&&(e=Jc(e,t,_i,"controlWrite",r.controlWrite?"add":"remove")),e}var qc=Object.freeze({__proto__:null,getAclServerResourceInfo:Lc,getAgentAccess:Hc,getAgentAccessAll:async function(e,t){const r=await M(e,t),n=await Bc(r,t);return null===n?Qa(r,t):async function(e){return(await Promise.all((t=e,Array.from(new Set(gt(jn(t)).map((e=>tt(e,yi.agent))).reduce(((e,t)=>e.concat(t)),[])))).map((async t=>({[t]:await Mc(e,t)}))))).reduce(((e,t)=>({...e,...t})),{});var t}(n)},getPublicAccess:Wc,setAgentAccess:async function(e,t,r,n){const i=await M(e,n),o=await Bc(i,n);if(null===o)return await tc(i,t,r,n),qa(i,t,n);try{return await Bi(await Gc(o,t,r),n),await Hc(e,t,n)}catch(e){return null}},setPublicAccess:async function(e,t,r){const n=await M(e,r),i=await Bc(n,r);if(null===i)return await rc(n,t,r),Ya(n,r);try{return await Bi(await async function(e,t){return Gc(e,yi.PublicAgent,t)}(i,t),r),await Wc(e,r)}catch(e){return null}}}),zc=Object.freeze({__proto__:null,acrAsMarkdown:pi,addAcrPolicyUrl:Xn,addAgent:vo,addAllOfRuleUrl:Gi,addAnyOfRuleUrl:Qi,addClient:Do,addGroup:So,addMemberAcrPolicyUrl:Zn,addMemberPolicyUrl:ai,addMockAcrTo:hs,addNoneOfRuleUrl:to,addPolicyUrl:si,createPolicy:Wo,createResourcePolicyFor:ts,createResourceRuleFor:so,createRule:oo,getAcrPolicyUrlAll:ei,getAgentAll:yo,getAllOfRuleUrlAll:Yi,getAllowModes:Yo,getAnyOfRuleUrlAll:eo,getClientAll:Fo,getDenyModes:es,getFileWithAccessDatasets:ji,getFileWithAcr:Di,getGroupAll:wo,getLinkedAcrUrl:Ki,getMemberAcrPolicyUrlAll:ti,getMemberPolicyUrlAll:li,getNoneOfRuleUrlAll:io,getPolicy:$o,getPolicyAll:Vo,getPolicyUrlAll:ci,getReferencedPolicyUrlAll:$i,getResourceAcrPolicy:ns,getResourceAcrPolicyAll:os,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getResourcePolicy:rs,getResourcePolicyAll:is,getResourceRule:co,getResourceRuleAll:uo,getRule:ao,getRuleAll:lo,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,hasAnyClient:Uo,hasAuthenticated:To,hasCreator:Co,hasLinkedAcr:Qn,hasPublic:Ao,isAcpControlled:Vi,mockAcrFor:ds,policyAsMarkdown:us,removeAcrPolicyUrl:ri,removeAcrPolicyUrlAll:ii,removeAgent:bo,removeAllOfRuleUrl:qi,removeAnyClient:Mo,removeAnyOfRuleUrl:Xi,removeAuthenticated:Po,removeClient:Lo,removeCreator:Oo,removeGroup:Eo,removeMemberAcrPolicyUrl:ni,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:di,removeMemberPolicyUrlAll:fi,removeNoneOfRuleUrl:ro,removePolicy:Ko,removePolicyUrl:ui,removePolicyUrlAll:hi,removePublic:Io,removeResourceAcrPolicy:as,removeResourcePolicy:ss,removeResourceRule:fo,removeRule:ho,ruleAsMarkdown:Bo,saveAcrFor:Bi,setAgent:mo,setAllOfRuleUrl:zi,setAllowModes:qo,setAnyClient:jo,setAnyOfRuleUrl:Zi,setAuthenticated:xo,setClient:No,setCreator:ko,setDenyModes:Xo,setGroup:_o,setNoneOfRuleUrl:no,setPolicy:Jo,setPublic:Ro,setResourceAcrPolicy:ls,setResourcePolicy:cs,setResourceRule:go,setRule:po}),Yc=Object.freeze({__proto__:null,addAcrPolicyUrl:Ss,addAgent:la,addAllOfMatcherUrl:Ms,addAnyOfMatcherUrl:$s,addClient:_a,addMemberAcrPolicyUrl:Es,addMemberPolicyUrl:As,addMockAcrTo:hs,addNoneOfMatcherUrl:Gs,addPolicyUrl:Rs,createMatcher:Qs,createPolicy:Wo,createResourceMatcherFor:Xs,createResourcePolicyFor:ts,getAcrPolicyUrlAll:xs,getAgentAll:aa,getAllOfMatcherUrlAll:Ws,getAllowModes:zo,getAnyOfMatcherUrlAll:Js,getClientAll:wa,getDenyModes:Zo,getFileWithAccessDatasets:ji,getFileWithAcr:Di,getLinkedAcrUrl:Ki,getMatcher:Zs,getMatcherAll:ta,getMemberAcrPolicyUrlAll:Cs,getMemberPolicyUrlAll:ks,getNoneOfMatcherUrlAll:Ys,getPolicy:$o,getPolicyAll:Vo,getPolicyUrlAll:Os,getReferencedPolicyUrlAll:$i,getResourceAcrPolicy:ns,getResourceAcrPolicyAll:os,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getResourceMatcher:ea,getResourceMatcherAll:ra,getResourcePolicy:rs,getResourcePolicyAll:is,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,getVcAccess:Fi,hasAccessibleAcr:Hi,hasAuthenticated:pa,hasCreator:ma,hasLinkedAcr:Qn,hasPublic:da,isAcpControlled:Vi,mockAcrFor:ds,removeAcrPolicyUrl:Fs,removeAcrPolicyUrlAll:ii,removeAgent:ua,removeAllOfMatcherUrl:Bs,removeAnyOfMatcherUrl:Vs,removeAuthenticated:ya,removeClient:Sa,removeCreator:ba,removeMatcher:na,removeMemberAcrPolicyUrl:Ns,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:Ds,removeMemberPolicyUrlAll:fi,removeNoneOfMatcherUrl:qs,removePolicy:Ko,removePolicyUrl:Ls,removePolicyUrlAll:hi,removePublic:fa,removeResourceAcrPolicy:as,removeResourceMatcher:ia,removeResourcePolicy:ss,saveAcrFor:Bi,setAgent:ca,setAllOfMatcherUrl:Hs,setAllowModes:Go,setAnyOfMatcherUrl:Ks,setAuthenticated:ga,setCreator:va,setDenyModes:Qo,setMatcher:oa,setNoneOfMatcherUrl:zs,setPolicy:Jo,setPublic:ha,setResourceMatcher:sa,setResourcePolicy:Us,setVcAccess:Ci});const{getJsonLdParser:Qc,getTurtleParser:Xc,solidDatasetAsTurtle:Zc}=We;t.FetchError=G,t.SolidClientError=p,t.ThingExpectedError=At,t.access=nc,t.access_v1=gc,t.access_v2=Dc,t.acp_ess_1=zc,t.acp_ess_2=Yc,t.acp_v1=ms,t.acp_v2=ys,t.acp_v3=vs,t.acp_v4=Ra,t.addBoolean=Kt,t.addDate=Gt,t.addDatetime=Jt,t.addDecimal=zt,t.addInteger=Yt,t.addIri=Vt,t.addJwkToJwks=Nn,t.addLiteral=er,t.addMockFallbackAclTo=function(e){const t=Dr(V(e)),r=`${t}.acl`,n=rn(function(e,t){return Object.assign(v(e),{internal_resourceInfo:{...e.internal_resourceInfo,aclUrl:t}})}(Wt(t),r));return Gr(v(e),{resourceAcl:null,fallbackAcl:n})},t.addMockResourceAclTo=function(e){var t;const r=null!==(t=e.internal_resourceInfo.aclUrl)&&void 0!==t?t:"https://your.pod/mock-acl.ttl",n=Object.assign(v(e),{internal_resourceInfo:{...e.internal_resourceInfo,aclUrl:r}});return Gr(n,{resourceAcl:rn(n),fallbackAcl:null})},t.addNamedNode=Zt,t.addPublicKeyToProfileJwks=async function(e,t,r=j){const n=await Ot(t,{fetch:r.fetch});if(null===n)throw new Error(`The profile document associated with WebID [${t}] could not be retrieved.`);const i=Fn(n,t);if(null===i)throw new Error(`No key set is declared for the property [${L}] in the profile of [${t}]`);const o=await Nn(e,i,r);return Je(i,new Blob([JSON.stringify(o)]),{contentType:"application/json",fetch:r.fetch})},t.addStringEnglish=function(e,t,r){return Qt(e,t,r,"en")},t.addStringNoLocale=Xt,t.addStringWithLocale=Qt,t.addTerm=tr,t.addTime=qt,t.addUrl=$t,t.asIri=_t,t.asUrl=wt,t.buildThing=Cr,t.changeLogAsMarkdown=Ut,t.createAcl=rn,t.createAclFromFallbackAcl=nn,t.createContainerAt=async function(e,t=j){var r;e=(e=g(e)).endsWith("/")?e:`${e}/`;const n={...j,...t},i=await n.fetch(e,{method:"PUT",body:n.initialContent?await je(Fe(n.initialContent).map(jt)):void 0,headers:{Accept:"text/turtle","Content-Type":"text/turtle","If-None-Match":"*",Link:`<${C}>; rel="type"`}});if(b(i)){const t=void 0===n.initialContent?"empty":"non-empty";throw new G(`Creating the ${t} Container at [${e}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i)}const o=m(i);return Y({...null!==(r=t.initialContent)&&void 0!==r?r:Ct(),internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:o})},t.createContainerInContainer=async function(e,t=j){e=g(e);const r={...j,...t},n={"Content-Type":"text/turtle",Link:`<${C}>; rel="type"`};t.slugSuggestion&&(n.slug=t.slugSuggestion);const i=await r.fetch(e,{method:"POST",headers:n});if(b(i))throw new G(`Creating an empty Container in the Container at [${e}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i);const o=m(i);if(!o.location)throw new Error("Could not determine the location of the newly created Container.");try{const e=new URL(o.location).toString();return Y({...Ct(),internal_resourceInfo:{...o,sourceIri:e}})}catch(e){}return Y({...Ct(),internal_resourceInfo:{...o,sourceIri:new URL(o.location,i.url).href}})},t.createSolidDataset=Ct,t.createThing=vt,t.deleteAclFor=async function(e,t=j){const r={...j,...t},n=await r.fetch(e.internal_resourceInfo.aclUrl,{method:"DELETE"});if(!n.ok)throw new Error(`Deleting the ACL of the Resource at [${$(e)}] failed: [${n.status}] [${n.statusText}].`);return Object.assign(v(e),{acl:{resourceAcl:null}})},t.deleteContainer=async function(e,t=j){const r=d(e)?g($(e)):g(e);if(!H(e))throw new Error(`You're trying to delete the Container at [${r}], but Container URLs should end in a \`/\`. Are you sure this is a Container?`);const n={...j,...t},i=await n.fetch(r,{method:"DELETE"});if(b(i))throw new G(`Deleting the Container at [${r}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i)},t.deleteFile=async function(e,t=$e){const r={...$e,...t},n=d(e)?g(V(e)):g(e),i=await r.fetch(n,{...r.init,method:"DELETE"});if(b(i))throw new G(`Deleting the file at [${n}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i)},t.deleteSolidDataset=async function(e,t=j){const r={...j,...t},n=d(e)?g($(e)):g(e),i=await r.fetch(n,{method:"DELETE"});if(b(i))throw new G(`Deleting the SolidDataset at [${n}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i)},t.fromRdfJsDataset=function(e){const t=Array.from(e),r=Oe(t);return t.filter((e=>r.every((t=>!t.equals(e.subject))))).reduce(((e,n)=>Ie(e,n,{otherQuads:t,chainBlankNodes:r})),{graphs:{default:{}},type:"Dataset"})},t.getAgentAccess=an,t.getAgentAccessAll=cn,t.getAgentDefaultAccess=hn,t.getAgentDefaultAccessAll=fn,t.getAgentResourceAccess=ln,t.getAgentResourceAccessAll=un,t.getAltProfileUrlAllFrom=Dn,t.getBoolean=function(e,t){Ye(e);const r=ht(e,t,re);return null===r?null:ue(r)},t.getBooleanAll=function(e,t){return Ye(e),ft(e,t,re).map(ue).filter((e=>null!==e))},t.getContainedResourceUrlAll=function(e){const t=$(e),r=pt(e,t);return null===r?[]:rt(r,O).filter((e=>Dt(e,t)))},t.getContentType=W,t.getDate=function(e,t){Ye(e);const r=ht(e,t,ie);return null===r?null:fe(r)},t.getDateAll=function(e,t){return Ye(e),ft(e,t,ie).map(fe).filter((e=>null!==e))},t.getDatetime=function(e,t){Ye(e);const r=ht(e,t,ne);return null===r?null:he(r)},t.getDatetimeAll=function(e,t){return Ye(e),ft(e,t,ne).map(he).filter((e=>null!==e))},t.getDecimal=function(e,t){Ye(e);const r=ht(e,t,se);return null===r?null:ye(r)},t.getDecimalAll=function(e,t){return Ye(e),ft(e,t,se).map((e=>ye(e))).filter((e=>null!==e))},t.getEffectiveAccess=function(e){var t,r,n,i,o,s,a;if("object"==typeof e.internal_resourceInfo.permissions)return{user:{read:e.internal_resourceInfo.permissions.user.read,append:e.internal_resourceInfo.permissions.user.append,write:e.internal_resourceInfo.permissions.user.write},public:{read:e.internal_resourceInfo.permissions.public.read,append:e.internal_resourceInfo.permissions.public.append,write:e.internal_resourceInfo.permissions.public.write}};const c=J(e);return{user:{read:null!==(r=null===(t=c[N.allow])||void 0===t?void 0:t.includes(N.Read))&&void 0!==r&&r,append:null!==(o=(null===(n=c[N.allow])||void 0===n?void 0:n.includes(N.Append))||(null===(i=c[N.allow])||void 0===i?void 0:i.includes(N.Write)))&&void 0!==o&&o,write:null!==(a=null===(s=c[N.allow])||void 0===s?void 0:s.includes(N.Write))&&void 0!==a&&a}}},t.getFallbackAcl=tn,t.getFile=Ke,t.getFileWithAcl=async function(e,t=j){const r=await Ke(e,t);return Gr(r,await Or(r,t))},t.getGroupAccess=vn,t.getGroupAccessAll=bn,t.getGroupDefaultAccess=Sn,t.getGroupDefaultAccessAll=En,t.getGroupResourceAccess=wn,t.getGroupResourceAccessAll=_n,t.getInteger=function(e,t){Ye(e);const r=ht(e,t,ae);return null===r?null:me(r)},t.getIntegerAll=function(e,t){return Ye(e),ft(e,t,ae).map((e=>me(e))).filter((e=>null!==e))},t.getIri=et,t.getIriAll=rt,t.getJsonLdParser=Qc,t.getLinkedResourceUrlAll=J,t.getLiteral=ct,t.getLiteralAll=lt,t.getNamedNode=st,t.getNamedNodeAll=at,t.getPodOwner=K,t.getPodUrlAll=async function(e,t=j){return Un(await Ln(e,t),e)},t.getPodUrlAllFrom=Un,t.getProfileAll=Ln,t.getProfileJwksIri=Fn,t.getPropertyAll=function(e){return Object.keys(e.predicates).filter((t=>null!==ut(e,t)))},t.getPublicAccess=Tn,t.getPublicDefaultAccess=Pn,t.getPublicResourceAccess=xn,t.getResourceAcl=Zr,t.getResourceInfo=M,t.getResourceInfoWithAcl=async function(e,t=j){const r=await M(e,t);return Gr(r,await Or(r,t))},t.getSolidDataset=Ot,t.getSolidDatasetWithAcl=async function(e,t=j){const r=await Ot(e,t);return Gr(r,await Or(r,t))},t.getSourceIri=V,t.getSourceUrl=$,t.getStringByLocaleAll=function(e,t){var r,n;if(Ye(e),!Se(t))throw new Rt(t);const i=g(t),o=null!==(n=null===(r=e.predicates[i])||void 0===r?void 0:r.langStrings)&&void 0!==n?n:{};return new Map(Object.entries(o).map((([e,t])=>[e,[...t]])))},t.getStringEnglish=function(e,t){return nt(e,t,"en")},t.getStringEnglishAll=function(e,t){return it(e,t,"en")},t.getStringNoLocale=function(e,t){return Ye(e),ht(e,t,ce)},t.getStringNoLocaleAll=ot,t.getStringWithLocale=nt,t.getStringWithLocaleAll=it,t.getTerm=ut,t.getTermAll=dt,t.getThing=pt,t.getThingAll=gt,t.getTime=function(e,t){Ye(e);const r=ht(e,t,oe);return null===r?null:de(r)},t.getTimeAll=function(e,t){return Ye(e),ft(e,t,oe).map(de).filter((e=>null!==e))},t.getTurtleParser=Xc,t.getUrl=Ze,t.getUrlAll=tt,t.getWebIdDataset=async function(e){return Ot(e,{fetch:y})},t.getWellKnownSolid=async function(e,t=j){const r=g(e);try{const e=new URL("/.well-known/solid",new URL(r).origin).href;return await Ot(e,{fetch:y})}catch(e){}const n=J(await M(r,{fetch:t.fetch,ignoreAuthenticationErrors:!0}))[U],i=1===(null==n?void 0:n.length)?n[0]:null;if(null!==i)return Ot(new URL(".well-known/solid",i.endsWith("/")?i:`${i}/`).href,{...t,parsers:{"application/ld+json":q()}});throw new Error("Could not determine storage root or well-known solid resource.")},t.hasAccessibleAcl=sn,t.hasAcl=function(e){return"object"==typeof e.internal_acl},t.hasFallbackAcl=en,t.hasResourceAcl=Xr,t.hasResourceInfo=d,t.hasServerResourceInfo=h,t.isContainer=H,t.isPodOwner=function(e,t){const r=K(t);return"string"!=typeof r?null:r===e},t.isRawData=function(e){return e.internal_resourceInfo.isRawData},t.isThing=bt,t.isThingLocal=Et,t.mockContainerFrom=Wt,t.mockFetchError=function(e,t=404,r="Not Found"){const n=new o.Response(void 0,{status:t,statusText:r});return new G(`Fetching the Resource at [${e}] failed: [${n.status}] [${n.statusText}].`,n)},t.mockFileFrom=function(e,t){const r=new Blob;return Object.assign(r,{internal_resourceInfo:{sourceIri:g(e),isRawData:!0,contentType:null==t?void 0:t.contentType,linkedResources:{}}})},t.mockSolidDatasetFrom=Ht,t.mockThingFrom=function(e){return{type:"Subject",predicates:{},url:g(e)}},t.overwriteFile=Je,t.removeAll=nr,t.removeBoolean=sr,t.removeDate=cr,t.removeDatetime=ar,t.removeDecimal=ur,t.removeInteger=dr,t.removeIri=or,t.removeLiteral=gr,t.removeNamedNode=pr,t.removeStringEnglish=function(e,t,r){return hr(e,t,r,"en")},t.removeStringNoLocale=fr,t.removeStringWithLocale=hr,t.removeThing=mt,t.removeTime=lr,t.removeUrl=ir,t.responseToResourceInfo=B,t.responseToSolidDataset=kt,t.saveAclFor=on,t.saveFileInContainer=async function(e,t,r=$e){const n=g(e),i=await Ge(n,t,"POST",r);if(b(i))throw new G(`Saving the file in [${e}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i);const o=i.headers.get("Location");if(null===o)throw new Error("Could not determine the location of the newly saved file.");const s=new URL(o,new URL(n).origin).href,a=v(t),c={internal_resourceInfo:{isRawData:!0,sourceIri:s,contentType:qe(t,r.contentType)}};return Object.assign(a,c)},t.saveSolidDatasetAt=Ft,t.saveSolidDatasetInContainer=async function(e,t,r=j){const n={...j,...r};e=g(e);const i=await je(Fe(t).map(jt)),o={"Content-Type":"text/turtle",Link:`<${k}>; rel="type"`};r.slugSuggestion&&(o.slug=r.slugSuggestion);const s=await n.fetch(e,{method:"POST",body:i,headers:o});if(b(s))throw new G(`Storing the Resource in the Container at [${e}] failed: [${s.status}] [${s.statusText}] ${await s.text()}.\n\nThe SolidDataset that was sent to the Pod is listed below.\n\n${Lt(t)}`,s);const a=m(s);if(!a.location)throw new Error("Could not determine the location of the newly saved SolidDataset.");let c;try{c=new URL(a.location).href}catch(e){c=new URL(a.location,s.url).href}const l={internal_resourceInfo:{isRawData:!1,sourceIri:c}};return Bt(Y({...t,...l}))},t.setAgentDefaultAccess=function(e,t,r){return zr(e,r,S,"default",t)},t.setAgentResourceAccess=dn,t.setBoolean=br,t.setDate=_r,t.setDatetime=wr,t.setDecimal=Er,t.setGroupDefaultAccess=function(e,t,r){return zr(e,r,E,"default",t)},t.setGroupResourceAccess=In,t.setInteger=Ar,t.setIri=vr,t.setLiteral=xr,t.setNamedNode=Tr,t.setProfileJwks=function(e,t,r){return yt(e,vr(On(e,t),L,r))},t.setPublicDefaultAccess=function(e,t){return zr(e,t,A,"default",F)},t.setPublicResourceAccess=Cn,t.setStringNoLocale=Ir,t.setStringWithLocale=Rr,t.setTerm=Pr,t.setThing=yt,t.setTime=Sr,t.setUrl=mr,t.solidDatasetAsMarkdown=Lt,t.solidDatasetAsTurtle=Zc,t.thingAsMarkdown=St,t.toRdfJsDataset=He,t.universalAccess=qc,t.validateContainedResourceAll=function(e){const t=$(e),r=pt(e,t);if(null===r)return{isValid:!0,invalidContainedResources:[]};const n=rt(r,O).filter((e=>!Dt(e,t)));return n.length>0?{isValid:!1,invalidContainedResources:n}:{isValid:!0,invalidContainedResources:[]}}},5914:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=globalThis.fetch;const{fetch:n,Response:i,Request:o,Headers:s}=globalThis;t.Headers=s,t.Request=o,t.Response=i,t.default=r,t.fetch=n},4727:function(e,t,r){const n=r(37);e.exports=n},377:function(e){class t{constructor(e){this.value=e||"b"+ ++t.nextId}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}t.prototype.termType="BlankNode",t.nextId=0,e.exports=t},37:function(e,t,r){const n=r(377),i=r(8144),o=r(3257),s=r(2704),a=r(9938),c=r(5304),l=r(7427),u={namedNode:function(e){return new a(e)},blankNode:function(e){return new n(e)},literal:function(e,t){return"string"==typeof t?-1===t.indexOf(":")?new s(e,t):new s(e,null,u.namedNode(t)):new s(e,null,t)},variable:function(e){return new l(e)},defaultGraph:function(){return u.defaultGraphInstance},triple:function(e,t,r){return u.quad(e,t,r)},quad:function(e,t,r,n){return new c(e,t,r,n||u.defaultGraphInstance)},fromTerm:function(e){return o.call(u,e)},fromQuad:function(e){return o.call(u,e)},defaultGraphInstance:new i};e.exports=u},8144:function(e){class t{equals(e){return!!e&&e.termType===this.termType}}t.prototype.termType="DefaultGraph",t.prototype.value="",e.exports=t},2704:function(e,t,r){const n=r(9938);class i{constructor(e,t,r){this.value=e,this.datatype=i.stringDatatype,this.language="",t?(this.language=t,this.datatype=i.langStringDatatype):r&&(this.datatype=r)}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value&&e.language===this.language&&e.datatype.equals(this.datatype)}}i.prototype.termType="Literal",i.langStringDatatype=new n("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),i.stringDatatype=new n("http://www.w3.org/2001/XMLSchema#string"),e.exports=i},9938:function(e){class t{constructor(e){this.value=e}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}t.prototype.termType="NamedNode",e.exports=t},5304:function(e,t,r){const n=r(8144);class i{constructor(e,t,r,i){this.subject=e,this.predicate=t,this.object=r,this.graph=i||new n}equals(e){return!!e&&("Quad"===e.termType||!e.termType)&&e.subject.equals(this.subject)&&e.predicate.equals(this.predicate)&&e.object.equals(this.object)&&e.graph.equals(this.graph)}}i.prototype.termType="Quad",i.prototype.value="",e.exports=i},7427:function(e){class t{constructor(e){this.value=e}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}t.prototype.termType="Variable",e.exports=t},3257:function(e){e.exports=function(e){if(!e)return null;if("BlankNode"===e.termType)return this.blankNode(e.value);if("DefaultGraph"===e.termType)return this.defaultGraph();if("Literal"===e.termType)return this.literal(e.value,e.language||this.namedNode(e.datatype.value));if("NamedNode"===e.termType)return this.namedNode(e.value);if("Quad"===e.termType){const t=this.fromTerm(e.subject),r=this.fromTerm(e.predicate),n=this.fromTerm(e.object),i=this.fromTerm(e.graph);return this.quad(t,r,n,i)}if("Variable"===e.termType)return this.variable(e.value);throw new Error(`unknown termType ${e.termType}`)}},2442:function(e){function t(e){return"string"==typeof e||e instanceof String}function r(e){if("string"==typeof e)return e;if(!e)return"";if(void 0!==e.id&&"Quad"!==e.termType)return e.id;let t,n,o,s;switch(e.termType){case"NamedNode":return e.value;case"BlankNode":return`_:${e.value}`;case"Variable":return`?${e.value}`;case"DefaultGraph":return"";case"Literal":return e.language?`"${e.value}"@${e.language}`:`"${e.value}"${e.datatype&&"http://www.w3.org/2001/XMLSchema#string"!==e.datatype.value?`^^${e.datatype.value}`:""}`;case"Quad":return t=i(r(e.subject)),n=i(r(e.predicate)),o=i(r(e.object)),s="DefaultGraph"===e.graph.termType?"":` ${r(e.graph)}`,`<<${t} ${n} ${o}${s}>>`;default:throw new Error(`Unexpected termType: ${e.termType}`)}}const n=/^"(.*".*)(?="[^"]*$)/;function i(e){return e.replace(n,((e,t)=>`"${t.replace(/"/g,'""')}`))}class o{constructor(e){if(this._size=0,this._graphs=Object.create(null),this._id=0,this._ids=Object.create(null),this._ids["><"]=0,this._entities=Object.create(null),this._quads=new Map,e)for(const t of e)this.add(t)}get size(){let e=this._size;if(null!==e)return e;e=0;const t=this._graphs;let r,n;for(const i in t)for(const o in r=t[i].subjects)for(const t in n=r[o])e+=Object.keys(n[t]).length;return this._size=e,this._size}add(e){let t=r(e.subject),n=r(e.predicate),i=r(e.object);const o=r(e.graph);let s=this._graphs[o];s||(s=this._graphs[o]={subjects:{},predicates:{},objects:{}},Object.freeze(s));const a=this._ids,c=this._entities;return t=a[t]||(a[c[++this._id]=t]=this._id),n=a[n]||(a[c[++this._id]=n]=this._id),i=a[i]||(a[c[++this._id]=i]=this._id),this._addToIndex(s.subjects,t,n,i),this._addToIndex(s.predicates,n,i,t),this._addToIndex(s.objects,i,t,n),this._setQuad(t,n,i,o,e),this._size=null,this}delete(e){let t=r(e.subject),n=r(e.predicate),i=r(e.object);const o=r(e.graph),s=this._ids,a=this._graphs;let c,l,u;if(!((t=s[t])&&(n=s[n])&&(i=s[i])&&(c=a[o])&&(l=c.subjects[t])&&(u=l[n])&&i in u))return this;for(t in this._removeFromIndex(c.subjects,t,n,i),this._removeFromIndex(c.predicates,n,i,t),this._removeFromIndex(c.objects,i,t,n),null!==this._size&&this._size--,this._deleteQuad(t,n,i,o),c.subjects)return this;return delete a[o],this}has(e){const n=r(e.subject),i=r(e.predicate),o=r(e.object),s=r(e.graph),a=this._graphs[s];if(!a)return!1;const c=this._ids;let l,u,d;return!(t(n)&&!(l=c[n])||t(i)&&!(u=c[i])||t(o)&&!(d=c[o]))&&1===this._countInIndex(a.objects,d,l,u)}match(e,t,r,n){return this._createDataset(this._match(e,t,r,n))}[Symbol.iterator](){return this._match()[Symbol.iterator]()}_addToIndex(e,t,r,n){const i=e[t]||(e[t]={}),o=i[r]||(i[r]={}),s=n in o;return s||(o[n]=null),!s}_removeFromIndex(e,t,r,n){const i=e[t],o=i[r];delete o[n];for(const e in o)return;delete i[r];for(const e in i)return;delete e[t]}_findInIndex(e,t,r,n,i,o,s,a,c,l){let u,d,h;t&&((u=e,e={})[t]=u[t]);for(const t in e)if(d=e[t],d){r&&((u=d,d={})[r]=u[r]);for(const e in d)if(h=d[e],h){const r=n?n in h?[n]:[]:Object.keys(h);for(let n=0;n0?s-4:s;for(r=0;r>16&255,l[u++]=t>>8&255,l[u++]=255&t;return 2===c&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,l[u++]=255&t),1===c&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t),l},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,o=[],s=16383,a=0,l=n-i;al?l:a+s));return 1===i?(t=e[n-1],o.push(r[t>>2]+r[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],o.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),o.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)r[s]=o[s],n[o.charCodeAt(s)]=s;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function c(e,t,n){for(var i,o,s=[],a=t;a>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return s.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},8849:function(e,t,r){"use strict";r.r(t);var n=void 0!==n?n:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,i=function(){try{return 2===new Blob(["hi"]).size}catch(e){return!1}}(),o=i&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(e){return!1}}(),s=n&&n.prototype.append&&n.prototype.getBlob;function a(e){return e.map((function(e){if(e.buffer instanceof ArrayBuffer){var t=e.buffer;if(e.byteLength!==t.byteLength){var r=new Uint8Array(e.byteLength);r.set(new Uint8Array(t,e.byteOffset,e.byteLength)),t=r.buffer}return t}return e}))}function c(e,t){t=t||{};var r=new n;return a(e).forEach((function(e){r.append(e)})),t.type?r.getBlob(t.type):r.getBlob()}function l(e,t){return new Blob(a(e),t||{})}"undefined"!=typeof Blob&&(c.prototype=Blob.prototype,l.prototype=Blob.prototype),t.default=i?o?Blob:l:s?c:void 0},8287:function(e,t,r){"use strict";const n=r(7526),i=r(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=c,t.SlowBuffer=function(e){return+e!=e&&(e=0),c.alloc(+e)},t.INSPECT_MAX_BYTES=50;const s=2147483647;function a(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,c.prototype),t}function c(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return d(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!c.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|g(e,t);let n=a(r);const i=n.write(e,t);return i!==r&&(n=n.slice(0,i)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(z(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(z(e,ArrayBuffer)||e&&z(e.buffer,ArrayBuffer))return f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(z(e,SharedArrayBuffer)||e&&z(e.buffer,SharedArrayBuffer)))return f(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return c.from(n,t,r);const i=function(e){if(c.isBuffer(e)){const t=0|p(e.length),r=a(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?a(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return c.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e){return u(e),a(e<0?0:0|p(e))}function h(e){const t=e.length<0?0:0|p(e.length),r=a(t);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function g(e,t){if(c.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||z(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return J(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(i)return n?-1:J(e).length;t=(""+t).toLowerCase(),i=!0}}function y(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,r);case"utf8":case"utf-8":return I(this,t,r);case"ascii":return x(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return R(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function m(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function v(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Y(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=c.from(t,n)),c.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,i){let o,s=1,a=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){let n=-1;for(o=r;oa&&(r=a-c),o=r;o>=0;o--){let r=!0;for(let n=0;ni&&(n=i):n=i;const o=t.length;let s;for(n>o/2&&(n=o/2),s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function R(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function I(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i239?4:t>223?3:t>191?2:1;if(i+s<=r){let r,n,a,c;switch(s){case 1:t<128&&(o=t);break;case 2:r=e[i+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(o=c));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(c=(15&t)<<12|(63&r)<<6|63&n,c>2047&&(c<55296||c>57343)&&(o=c));break;case 4:r=e[i+1],n=e[i+2],a=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(c=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&a,c>65535&&c<1114112&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(c.isBuffer(t)||(t=c.from(t)),t.copy(n,i)):Uint8Array.prototype.set.call(n,t,i);else{if(!c.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},c.byteLength=g,c.prototype._isBuffer=!0,c.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},o&&(c.prototype[o]=c.prototype.inspect),c.prototype.compare=function(e,t,r,n,i){if(z(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;let o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0);const a=Math.min(o,s),l=this.slice(n,i),u=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return _(this,e,t,r);case"ascii":case"latin1":case"binary":return S(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function x(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;in)&&(r=n);let i="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function F(e,t,r,n,i,o){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function N(e,t,r,n,i){W(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,r}function D(e,t,r,n,i){W(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o>>=8,e[r+6]=o,o>>=8,e[r+5]=o,o>>=8,e[r+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s>>=8,e[r+2]=s,s>>=8,e[r+1]=s,s>>=8,e[r]=s,r+8}function L(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,o){return t=+t,r>>>=0,o||L(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function j(e,t,r,n,o){return t=+t,r>>>=0,o||L(e,0,r,8),i.write(e,t,r,n,52,8),r+8}c.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||O(e,t,this.length);let n=this[e],i=1,o=0;for(;++o>>=0,t>>>=0,r||O(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},c.prototype.readUint8=c.prototype.readUInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),this[e]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readBigUInt64LE=X((function(e){$(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||O(e,t,this.length);let n=this[e],i=1,o=0;for(;++o=i&&(n-=Math.pow(2,8*t)),n},c.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||O(e,t,this.length);let n=t,i=1,o=this[e+--n];for(;n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},c.prototype.readInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||O(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){e>>>=0,t||O(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readBigInt64LE=X((function(e){$(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||O(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||O(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||O(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||O(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUintLE=c.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||F(this,e,t,r,Math.pow(2,8*r)-1,0);let i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n||F(this,e,t,r,Math.pow(2,8*r)-1,0);let i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},c.prototype.writeUint8=c.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigUInt64LE=X((function(e,t=0){return N(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeBigUInt64BE=X((function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);F(this,e,t,r,n-1,-n)}let i=0,o=1,s=0;for(this[t]=255&e;++i>>=0,!n){const n=Math.pow(2,8*r-1);F(this,e,t,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||F(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigInt64LE=X((function(e,t=0){return N(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeBigInt64BE=X((function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return j(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,n){if(!c.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function W(e,t,r,n,i,o){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new M.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){$(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(n,i,o)}function $(e,t){if("number"!=typeof e)throw new M.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,r){if(Math.floor(e)!==e)throw $(e,r),new M.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new M.ERR_BUFFER_OUT_OF_BOUNDS;throw new M.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}B("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),B("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),B("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=H(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=H(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n}),RangeError);const K=/[^+/0-9A-Za-z-_]/g;function J(e,t){let r;t=t||1/0;const n=e.length;let i=null;const o=[];for(let s=0;s55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,r,n){let i;for(i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function z(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}const Q=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)t[n+i]=e[r]+e[i]}return t}();function X(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},2341:function(e){"use strict";e.exports=function e(t){return null===t||"object"!=typeof t||null!=t.toJSON?JSON.stringify(t):Array.isArray(t)?"["+t.reduce(((t,r,n)=>t+(0===n?"":",")+e(void 0===r||"symbol"==typeof r?null:r)),"")+"]":"{"+Object.keys(t).sort().reduce(((r,n,i)=>void 0===t[n]||"symbol"==typeof t[n]?r:r+(0===r.length?"":",")+e(n)+":"+e(t[n])),"")+"}"}},6547:function(){!function(e){!function(t){var r="URLSearchParams"in e,n="Symbol"in e&&"iterator"in Symbol,i="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),o="FormData"in e,s="ArrayBuffer"in e;if(s)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function l(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function d(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return n&&(t[Symbol.iterator]=function(){return t}),t}function h(e){this.map={},e instanceof h?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function f(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function p(e){return new Promise((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function g(e){var t=new FileReader,r=p(t);return t.readAsArrayBuffer(e),r}function y(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:i&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():s&&i&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=y(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(e)||c(e))?this._bodyArrayBuffer=y(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var e=f(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?f(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(g)}),this.text=function(){var e,t,r,n=f(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,r=p(t=new FileReader),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?n:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function w(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}})),t}function _(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new h(t.headers),this.url=t.url||"",this._initBody(e)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})},m.call(b.prototype),m.call(_.prototype),_.prototype.clone=function(){return new _(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new h(this.headers),url:this.url})},_.error=function(){var e=new _(null,{status:0,statusText:""});return e.type="error",e};var S=[301,302,303,307,308];_.redirect=function(e,t){if(-1===S.indexOf(t))throw new RangeError("Invalid status code");return new _(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function E(e,r){return new Promise((function(n,o){var s=new b(e,r);if(s.signal&&s.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function c(){a.abort()}a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new h,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();t.append(n,i)}})),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;n(new _(i,r))},a.onerror=function(){o(new TypeError("Network request failed"))},a.ontimeout=function(){o(new TypeError("Network request failed"))},a.onabort=function(){o(new t.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&i&&(a.responseType="blob"),s.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),s.signal&&(s.signal.addEventListener("abort",c),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",c)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}E.polyfill=!0,e.fetch||(e.fetch=E,e.Headers=h,e.Request=b,e.Response=_),t.Headers=h,t.Request=b,t.Response=_,t.fetch=E,Object.defineProperty(t,"__esModule",{value:!0})}({})}("undefined"!=typeof self?self:this)},7007:function(e){"use strict";var t,r="object"==typeof Reflect?Reflect:null,n=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise((function(r,n){function i(r){e.removeListener(t,o),n(r)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}g(e,t,o,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&g(e,"error",t,{once:!0})}(e,i)}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function l(e,t,r,n){var i,o,s,l;if(a(r),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),s=o[t]),void 0===s)s=o[t]=r,++e._eventsCount;else if("function"==typeof s?s=o[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),(i=c(e))>0&&s.length>i&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,l=u,console&&console.warn&&console.warn(l)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=u.bind(n);return i.listener=r,n.wrapFn=i,i}function h(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var l=c.length,u=p(c,l);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){s=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},o.prototype.listeners=function(e){return h(this,e,!0)},o.prototype.rawListeners=function(e){return h(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},o.prototype.listenerCount=f,o.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},2384:function(e){"use strict";var t=/^utf-?8|ascii|utf-?16-?le|ucs-?2|base-?64|latin-?1$/i,r=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,n=/\s|\uFEFF|\xA0/,i=/\r?\n[\x20\x09]+/g,o=/[;,"]/,s=/[;,"]|\s/,a=/^[!#$%&'*+\-\.^_`|~\da-zA-Z]+$/;function c(e){return e.replace(r,"")}function l(e){return n.test(e)}function u(e,t){for(;l(e[t]);)t++;return t}function d(e){return s.test(e)||!a.test(e)}class h{constructor(e){this.refs=[],e&&this.parse(e)}rel(e){for(var t=[],r=e.toLowerCase(),n=0;n{return r=t,n=e,Object.keys(r).length===Object.keys(n).length&&Object.keys(r).every((e=>e in n&&r[e]===n[e]));var r,n}))||this.refs.push(e),this}has(e,t){e=e.toLowerCase(),t=t.toLowerCase();for(var r=0;r",t)))throw new Error("Expected end of URI delimiter at offset "+t);s={uri:e.slice(t+1,f)},t=f,r=2,t++}else if(2===r){if(l(e[t])){t++;continue}if(";"===e[t])r=4,t++;else{if(","!==e[t])throw new Error('Unexpected character "'+e[t]+'" at offset '+t);r=1,t++}}else{if(4!==r)throw new Error('Unknown parser state "'+r+'"');if(";"===e[t]||l(e[t])){t++;continue}-1===(f=e.indexOf("=",t))&&(f=e.indexOf(";",t)),-1===f&&(f=e.length);var a=c(e.slice(t,f)).toLowerCase(),d="";if('"'===e[t=u(e,t=f+1)])for(t++;t"),e.push(t);return e.join(", ")}}h.isCompatibleEncoding=function(e){return t.test(e)},h.parse=function(e,t){return(new h).parse(e,t)},h.isSingleOccurenceAttr=function(e){return"rel"===e||"type"===e||"media"===e||"title"===e||"title*"===e},h.isTokenAttr=function(e){return"rel"===e||"type"===e||"anchor"===e},h.escapeQuotes=function(e){return e.replace(/"/g,'\\"')},h.expandRelations=function(e){return e.rel.split(" ").map((function(t){var r=Object.assign({},e);return r.rel=t,r}))},h.parseExtendedValue=function(e){var t=/([^']+)?(?:'([^']*)')?(.+)/.exec(e);return{language:t[2].toLowerCase(),encoding:h.isCompatibleEncoding(t[1])?null:t[1].toLowerCase(),value:h.isCompatibleEncoding(t[1])?decodeURIComponent(t[3]):t[3]}},h.formatExtendedAttribute=function(e,t){var r=(t.encoding||"utf-8").toUpperCase();return e+"="+r+"'"+(t.language||"en")+"'"+(Buffer.isBuffer(t.value)&&h.isCompatibleEncoding(r)?t.value.toString(r):Buffer.isBuffer(t.value)?t.value.toString("hex").replace(/[0-9a-f]{2}/gi,"%$1"):encodeURIComponent(t.value))},h.formatAttribute=function(e,t){return Array.isArray(t)?t.map((t=>h.formatAttribute(e,t))).join("; "):"*"===e[e.length-1]||"string"!=typeof t?h.formatExtendedAttribute(e,t):(h.isTokenAttr(e)?t=d(t)?'"'+h.escapeQuotes(t)+'"':h.escapeQuotes(t):d(t)&&(t='"'+(t=(t=encodeURIComponent(t)).replace(/%20/g," ").replace(/%2C/g,",").replace(/%3B/g,";"))+'"'),e+"="+t)},e.exports=h},251:function(e,t){t.read=function(e,t,r,n,i){var o,s,a=8*i-n-1,c=(1<>1,u=-7,d=r?i-1:0,h=r?-1:1,f=e[t+d];for(d+=h,o=f&(1<<-u)-1,f>>=-u,u+=a;u>0;o=256*o+e[t+d],d+=h,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=n;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),o-=l}return(f?-1:1)*s*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var s,a,c,l=8*o-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(s++,c/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(t*c-1)*Math.pow(2,i),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),s=0));i>=8;e[r+f]=255&a,f+=p,a/=256,i-=8);for(s=s<0;e[r+f]=255&s,f+=p,s/=256,l-=8);e[r+f-p]|=128*g}},2395:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(2803),t),i(r(5094),t),i(r(585),t),i(r(9146),t),i(r(5086),t),i(r(5215),t),i(r(4931),t)},2803:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextParser=void 0,r(6547);const n=r(742),i=r(5094),o=r(585),s=r(5215),a=r(4931);class c{constructor(e){e=e||{},this.documentLoader=e.documentLoader||new o.FetchDocumentLoader,this.documentCache={},this.validateContext=!e.skipValidation,this.expandContentTypeToBase=!!e.expandContentTypeToBase,this.remoteContextsDepthLimit=e.remoteContextsDepthLimit||32,this.redirectSchemaOrgHttps=!("redirectSchemaOrgHttps"in e)||!!e.redirectSchemaOrgHttps}static validateLanguage(e,t,r){if("string"!=typeof e)throw new i.ErrorCoded(`The value of an '@language' must be a string, got '${JSON.stringify(e)}'`,r);if(!a.Util.REGEX_LANGUAGE_TAG.test(e)){if(t)throw new i.ErrorCoded(`The value of an '@language' must be a valid language tag, got '${JSON.stringify(e)}'`,r);return!1}return!0}static validateDirection(e,t){if("string"!=typeof e)throw new i.ErrorCoded(`The value of an '@direction' must be a string, got '${JSON.stringify(e)}'`,i.ERROR_CODES.INVALID_BASE_DIRECTION);if(!a.Util.REGEX_DIRECTION_TAG.test(e)){if(t)throw new i.ErrorCoded(`The value of an '@direction' must be 'ltr' or 'rtl', got '${JSON.stringify(e)}'`,i.ERROR_CODES.INVALID_BASE_DIRECTION);return!1}return!0}idifyReverseTerms(e){for(const t of Object.keys(e)){let r=e[t];if(r&&"object"==typeof r&&r["@reverse"]&&!r["@id"]){if("string"!=typeof r["@reverse"]||a.Util.isValidKeyword(r["@reverse"]))throw new i.ErrorCoded(`Invalid @reverse value, must be absolute IRI or blank node: '${r["@reverse"]}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);r=e[t]=Object.assign(Object.assign({},r),{"@id":r["@reverse"]}),r["@id"]=r["@reverse"],a.Util.isPotentialKeyword(r["@reverse"])?delete r["@reverse"]:r["@reverse"]=!0}}return e}expandPrefixedTerms(e,t,r){const n=e.getContextRaw();for(const o of r||Object.keys(n))if(a.Util.EXPAND_KEYS_BLACKLIST.indexOf(o)<0&&!a.Util.isReservedInternalKeyword(o)){const r=n[o];if(a.Util.isPotentialKeyword(o)&&a.Util.ALIAS_DOMAIN_BLACKLIST.indexOf(o)>=0&&("@type"!==o||"object"==typeof n[o]&&!n[o]["@protected"]&&"@set"!==n[o]["@container"]))throw new i.ErrorCoded(`Keywords can not be aliased to something else.\nTried mapping ${o} to ${JSON.stringify(r)}`,i.ERROR_CODES.KEYWORD_REDEFINITION);if(a.Util.ALIAS_RANGE_BLACKLIST.indexOf(a.Util.getContextValueId(r))>=0)throw new i.ErrorCoded(`Aliasing to certain keywords is not allowed.\nTried mapping ${o} to ${JSON.stringify(r)}`,i.ERROR_CODES.INVALID_KEYWORD_ALIAS);if(r&&a.Util.isPotentialKeyword(a.Util.getContextValueId(r))&&!0===r["@prefix"])throw new i.ErrorCoded(`Tried to use keyword aliases as prefix: '${o}': '${JSON.stringify(r)}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION);for(;a.Util.isPrefixValue(n[o]);){const r=n[o];let i=!1;if("string"==typeof r)n[o]=e.expandTerm(r,!0),i=i||r!==n[o];else{const s=r["@id"],c=r["@type"],l=!("@prefix"in r)||a.Util.isValidIri(o);if("@id"in r)null!=s&&"string"==typeof s&&(n[o]=Object.assign(Object.assign({},n[o]),{"@id":e.expandTerm(s,!0)}),i=i||s!==n[o]["@id"]);else if(!a.Util.isPotentialKeyword(o)&&l){const t=e.expandTerm(o,!0);t!==o&&(n[o]=Object.assign(Object.assign({},n[o]),{"@id":t}),i=!0)}if(c&&"string"==typeof c&&"@vocab"!==c&&(!r["@container"]||!r["@container"]["@type"])&&l){let r=e.expandTerm(c,!0);t&&c===r&&(r=e.expandTerm(c,!1)),r!==c&&(i=!0,n[o]=Object.assign(Object.assign({},n[o]),{"@type":r}))}}if(!i)break}}}normalize(e,{processingMode:t,normalizeLanguageTags:r}){if(r||1===t)for(const t of Object.keys(e))if("@language"===t&&"string"==typeof e[t])e[t]=e[t].toLowerCase();else{const r=e[t];if(r&&"object"==typeof r&&"string"==typeof r["@language"]){const n=r["@language"].toLowerCase();n!==r["@language"]&&(e[t]=Object.assign(Object.assign({},r),{"@language":n}))}}}containersToHash(e){for(const t of Object.keys(e)){const r=e[t];if(r&&"object"==typeof r)if("string"==typeof r["@container"])e[t]=Object.assign(Object.assign({},r),{"@container":{[r["@container"]]:!0}});else if(Array.isArray(r["@container"])){const n={};for(const e of r["@container"])n[e]=!0;e[t]=Object.assign(Object.assign({},r),{"@container":n})}}}applyScopedProtected(e,{processingMode:t},r){if(t&&t>=1.1&&e["@protected"]){for(const t of Object.keys(e))if(!a.Util.isReservedInternalKeyword(t)&&!a.Util.isPotentialKeyword(t)&&!a.Util.isTermProtected(e,t)){const n=e[t];n&&"object"==typeof n?"@protected"in e[t]||(e[t]=Object.assign(Object.assign({},e[t]),{"@protected":!0})):(e[t]={"@id":n,"@protected":!0},a.Util.isSimpleTermDefinitionPrefix(n,r)&&(e[t]=Object.assign(Object.assign({},e[t]),{"@prefix":!0})))}delete e["@protected"]}}validateKeywordRedefinitions(e,t,r,n){for(const r of null!=n?n:Object.keys(t))if(a.Util.isTermProtected(e,r)&&("string"==typeof t[r]?t[r]={"@id":t[r],"@protected":!0}:t[r]=Object.assign(Object.assign({},t[r]),{"@protected":!0}),!a.Util.deepEqual(e[r],t[r])))throw new i.ErrorCoded(`Attempted to override the protected keyword ${r} from ${JSON.stringify(a.Util.getContextValueId(e[r]))} to ${JSON.stringify(a.Util.getContextValueId(t[r]))}`,i.ERROR_CODES.PROTECTED_TERM_REDEFINITION)}validate(e,{processingMode:t}){for(const r of Object.keys(e)){if(a.Util.isReservedInternalKeyword(r))continue;if(""===r)throw new i.ErrorCoded(`The empty term is not allowed, got: '${r}': '${JSON.stringify(e[r])}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION);const n=e[r],o=typeof n;if(a.Util.isPotentialKeyword(r)){switch(r.substr(1)){case"vocab":if(null!==n&&"string"!==o)throw new i.ErrorCoded(`Found an invalid @vocab IRI: ${n}`,i.ERROR_CODES.INVALID_VOCAB_MAPPING);break;case"base":if(null!==n&&"string"!==o)throw new i.ErrorCoded(`Found an invalid @base IRI: ${e[r]}`,i.ERROR_CODES.INVALID_BASE_IRI);break;case"language":null!==n&&c.validateLanguage(n,!0,i.ERROR_CODES.INVALID_DEFAULT_LANGUAGE);break;case"version":if(null!==n&&"number"!==o)throw new i.ErrorCoded(`Found an invalid @version number: ${n}`,i.ERROR_CODES.INVALID_VERSION_VALUE);break;case"direction":null!==n&&c.validateDirection(n,!0);break;case"propagate":if(1===t)throw new i.ErrorCoded(`Found an illegal @propagate keyword: ${n}`,i.ERROR_CODES.INVALID_CONTEXT_ENTRY);if(null!==n&&"boolean"!==o)throw new i.ErrorCoded(`Found an invalid @propagate value: ${n}`,i.ERROR_CODES.INVALID_PROPAGATE_VALUE)}if(a.Util.isValidKeyword(r)&&a.Util.isValidKeyword(a.Util.getContextValueId(n)))throw new i.ErrorCoded(`Illegal keyword alias in term value, found: '${r}': '${a.Util.getContextValueId(n)}'`,i.ERROR_CODES.KEYWORD_REDEFINITION)}else if(null!==n)switch(o){case"string":if(a.Util.getPrefix(n,e)===r)throw new i.ErrorCoded(`Detected cyclical IRI mapping in context entry: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.CYCLIC_IRI_MAPPING);if(a.Util.isValidIriWeak(r)){if("@type"===n)throw new i.ErrorCoded(`IRIs can not be mapped to @type, found: '${r}': '${n}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);if(a.Util.isValidIri(n)&&n!==new s.JsonLdContextNormalized(e).expandTerm(r))throw new i.ErrorCoded(`IRIs can not be mapped to other IRIs, found: '${r}': '${n}'`,i.ERROR_CODES.INVALID_IRI_MAPPING)}break;case"object":if(!(a.Util.isCompactIri(r)||"@id"in n||("@id"===n["@type"]?e["@base"]:e["@vocab"])))throw new i.ErrorCoded(`Missing @id in context entry: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);for(const l of Object.keys(n)){const u=n[l];if(u)switch(l){case"@id":if(a.Util.isValidKeyword(u)&&"@type"!==u&&"@id"!==u&&"@graph"!==u&&"@nest"!==u)throw new i.ErrorCoded(`Illegal keyword alias in term value, found: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);if(a.Util.isValidIriWeak(r)){if("@type"===u)throw new i.ErrorCoded(`IRIs can not be mapped to @type, found: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);if(a.Util.isValidIri(u)&&u!==new s.JsonLdContextNormalized(e).expandTerm(r))throw new i.ErrorCoded(`IRIs can not be mapped to other IRIs, found: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING)}if("string"!=typeof u)throw new i.ErrorCoded(`Detected non-string @id in context entry: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);if(a.Util.getPrefix(u,e)===r)throw new i.ErrorCoded(`Detected cyclical IRI mapping in context entry: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.CYCLIC_IRI_MAPPING);break;case"@type":if("@type"===n["@container"]&&"@id"!==u&&"@vocab"!==u)throw new i.ErrorCoded(`@container: @type only allows @type: @id or @vocab, but got: '${r}': '${u}'`,i.ERROR_CODES.INVALID_TYPE_MAPPING);if("string"!=typeof u)throw new i.ErrorCoded(`The value of an '@type' must be a string, got '${JSON.stringify(o)}'`,i.ERROR_CODES.INVALID_TYPE_MAPPING);if(!("@id"===u||"@vocab"===u||1!==t&&"@json"===u||1!==t&&"@none"===u||"_"!==u[0]&&a.Util.isValidIri(u)))throw new i.ErrorCoded(`A context @type must be an absolute IRI, found: '${r}': '${u}'`,i.ERROR_CODES.INVALID_TYPE_MAPPING);break;case"@reverse":if("string"==typeof u&&n["@id"]&&n["@id"]!==u)throw new i.ErrorCoded(`Found non-matching @id and @reverse term values in '${r}':'${u}' and '${n["@id"]}'`,i.ERROR_CODES.INVALID_REVERSE_PROPERTY);if("@nest"in n)throw new i.ErrorCoded(`@nest is not allowed in the reverse property '${r}'`,i.ERROR_CODES.INVALID_REVERSE_PROPERTY);break;case"@container":if(1===t&&(Object.keys(u).length>1||a.Util.CONTAINERS_1_0.indexOf(Object.keys(u)[0])<0))throw new i.ErrorCoded(`Invalid term @container for '${r}' ('${Object.keys(u)}') in 1.0, must be only one of ${a.Util.CONTAINERS_1_0.join(", ")}`,i.ERROR_CODES.INVALID_CONTAINER_MAPPING);for(const e of Object.keys(u)){if("@list"===e&&n["@reverse"])throw new i.ErrorCoded(`Term value can not be @container: @list and @reverse at the same time on '${r}'`,i.ERROR_CODES.INVALID_REVERSE_PROPERTY);if(a.Util.CONTAINERS.indexOf(e)<0)throw new i.ErrorCoded(`Invalid term @container for '${r}' ('${e}'), must be one of ${a.Util.CONTAINERS.join(", ")}`,i.ERROR_CODES.INVALID_CONTAINER_MAPPING)}break;case"@language":c.validateLanguage(u,!0,i.ERROR_CODES.INVALID_LANGUAGE_MAPPING);break;case"@direction":c.validateDirection(u,!0);break;case"@prefix":if(null!==u&&"boolean"!=typeof u)throw new i.ErrorCoded(`Found an invalid term @prefix boolean in: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_PREFIX_VALUE);if(!("@id"in n)&&!a.Util.isValidIri(r))throw new i.ErrorCoded(`Invalid @prefix definition for '${r}' ('${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION);break;case"@index":if(1===t||!n["@container"]||!n["@container"]["@index"])throw new i.ErrorCoded(`Attempt to add illegal key to value object: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION);break;case"@nest":if(a.Util.isPotentialKeyword(u)&&"@nest"!==u)throw new i.ErrorCoded(`Found an invalid term @nest value in: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_NEST_VALUE)}}break;default:throw new i.ErrorCoded(`Found an invalid term value: '${r}': '${n}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION)}}}applyBaseEntry(e,t,r){return"string"==typeof e||(r&&!("@base"in e)&&t.parentContext&&"object"==typeof t.parentContext&&"@base"in t.parentContext&&(e["@base"]=t.parentContext["@base"],t.parentContext["@__baseDocument"]&&(e["@__baseDocument"]=!0)),t.baseIRI&&!t.external&&("@base"in e?null===e["@base"]||"string"!=typeof e["@base"]||a.Util.isValidIri(e["@base"])||(e["@base"]=(0,n.resolve)(e["@base"],t.parentContext&&t.parentContext["@base"]||t.baseIRI)):(e["@base"]=t.baseIRI,e["@__baseDocument"]=!0))),e}normalizeContextIri(e,t){if(!a.Util.isValidIri(e))try{e=(0,n.resolve)(e,t)}catch(t){throw new Error(`Invalid context IRI: ${e}`)}return this.redirectSchemaOrgHttps&&e.startsWith("http://schema.org")&&(e="https://schema.org/"),e}async parseInnerContexts(e,t,r){for(const n of null!=r?r:Object.keys(e)){const r=e[n];if(r&&"object"==typeof r&&"@context"in r&&null!==r["@context"]&&!t.ignoreScopedContexts){if(this.validateContext)try{const i=Object.assign(Object.assign({},e),{[n]:Object.assign({},e[n])});delete i[n]["@context"],await this.parse(r["@context"],Object.assign(Object.assign({},t),{external:!1,parentContext:i,ignoreProtection:!0,ignoreRemoteScopedContexts:!0,ignoreScopedContexts:!0}))}catch(e){throw new i.ErrorCoded(e.message,i.ERROR_CODES.INVALID_SCOPED_CONTEXT)}e[n]=Object.assign(Object.assign({},r),{"@context":(await this.parse(r["@context"],Object.assign(Object.assign({},t),{external:!1,minimalProcessing:!0,ignoreRemoteScopedContexts:!0,parentContext:e}))).getContextRaw()})}}return e}async parse(e,t={},r={}){const{baseIRI:n,parentContext:o,external:l,processingMode:u=c.DEFAULT_PROCESSING_MODE,normalizeLanguageTags:d,ignoreProtection:h,minimalProcessing:f}=t,p=t.remoteContexts||{};if(Object.keys(p).length>=this.remoteContextsDepthLimit)throw new i.ErrorCoded("Detected an overflow in remote context inclusions: "+Object.keys(p),i.ERROR_CODES.CONTEXT_OVERFLOW);if(null==e){if(!h&&o&&a.Util.hasProtectedTerms(o))throw new i.ErrorCoded("Illegal context nullification when terms are protected",i.ERROR_CODES.INVALID_CONTEXT_NULLIFICATION);return new s.JsonLdContextNormalized(this.applyBaseEntry({},t,!1))}if("string"==typeof e){const r=this.normalizeContextIri(e,n),i=this.getOverriddenLoad(r,t);if(i)return new s.JsonLdContextNormalized(i);const o=await this.parse(await this.load(r),Object.assign(Object.assign({},t),{baseIRI:r,external:!0,remoteContexts:Object.assign(Object.assign({},p),{[r]:!0})}));return this.applyBaseEntry(o.getContextRaw(),t,!0),o}if(Array.isArray(e)){const r=[],i=await Promise.all(e.map(((e,i)=>{if("string"==typeof e){const o=this.normalizeContextIri(e,n);r[i]=o;return this.getOverriddenLoad(o,t)||this.load(o)}return e})));if(f)return new s.JsonLdContextNormalized(i);const a=await i.reduce(((e,n,o)=>e.then((e=>this.parse(n,Object.assign(Object.assign({},t),{baseIRI:r[o]||t.baseIRI,external:!!r[o]||t.external,parentContext:e.getContextRaw(),remoteContexts:r[o]?Object.assign(Object.assign({},p),{[r[o]]:!0}):p}),{skipValidation:o=1.1))throw new i.ErrorCoded("Context importing is not supported in JSON-LD 1.0",i.ERROR_CODES.INVALID_CONTEXT_ENTRY);if("string"!=typeof e["@import"])throw new i.ErrorCoded("An @import value must be a string, but got "+typeof e["@import"],i.ERROR_CODES.INVALID_IMPORT_VALUE);p=await this.loadImportContext(this.normalizeContextIri(e["@import"],n)),delete e["@import"]}this.applyScopedProtected(p,{processingMode:u},s.defaultExpandOptions);const g=Object.assign(p,e);this.idifyReverseTerms(g),this.normalize(g,{processingMode:u,normalizeLanguageTags:d}),this.applyScopedProtected(g,{processingMode:u},s.defaultExpandOptions);const y=Object.keys(g),m=[];if("object"==typeof o)for(const e in o)e in g?m.push(e):g[e]=o[e];await this.parseInnerContexts(g,t,y);const v=new s.JsonLdContextNormalized(g);return(g&&g["@version"]||c.DEFAULT_PROCESSING_MODE)>=1.1&&(e["@vocab"]&&"string"==typeof e["@vocab"]||""===e["@vocab"])&&(o&&"@vocab"in o&&e["@vocab"].indexOf(":")<0?g["@vocab"]=o["@vocab"]+e["@vocab"]:(a.Util.isCompactIri(e["@vocab"])||e["@vocab"]in g)&&(g["@vocab"]=v.expandTerm(e["@vocab"],!0))),this.expandPrefixedTerms(v,this.expandContentTypeToBase,y),!h&&o&&u>=1.1&&this.validateKeywordRedefinitions(o,g,s.defaultExpandOptions,m),this.validateContext&&!r.skipValidation&&this.validate(g,{processingMode:u}),v}throw new i.ErrorCoded(`Tried parsing a context that is not a string, array or object, but got ${e}`,i.ERROR_CODES.INVALID_LOCAL_CONTEXT)}async load(e){const t=this.documentCache[e];if(t)return t;let r;try{r=await this.documentLoader.load(e)}catch(t){throw new i.ErrorCoded(`Failed to load remote context ${e}: ${t.message}`,i.ERROR_CODES.LOADING_REMOTE_CONTEXT_FAILED)}if(!("@context"in r))throw new i.ErrorCoded(`Missing @context in remote context at ${e}`,i.ERROR_CODES.INVALID_REMOTE_CONTEXT);return this.documentCache[e]=r["@context"]}getOverriddenLoad(e,t){if(e in(t.remoteContexts||{})){if(t.ignoreRemoteScopedContexts)return e;throw new i.ErrorCoded("Detected a cyclic context inclusion of "+e,i.ERROR_CODES.RECURSIVE_CONTEXT_INCLUSION)}return null}async loadImportContext(e){let t=await this.load(e);if("object"!=typeof t||Array.isArray(t))throw new i.ErrorCoded("An imported context must be a single object: "+e,i.ERROR_CODES.INVALID_REMOTE_CONTEXT);if("@import"in t)throw new i.ErrorCoded("An imported context can not import another context: "+e,i.ERROR_CODES.INVALID_CONTEXT_ENTRY);return t=Object.assign({},t),this.containersToHash(t),t}}c.DEFAULT_PROCESSING_MODE=1.1,t.ContextParser=c},5094:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ERROR_CODES=t.ErrorCoded=void 0;class r extends Error{constructor(e,t){super(e),this.code=t}}var n;t.ErrorCoded=r,(n=t.ERROR_CODES||(t.ERROR_CODES={})).COLLIDING_KEYWORDS="colliding keywords",n.CONFLICTING_INDEXES="conflicting indexes",n.CYCLIC_IRI_MAPPING="cyclic IRI mapping",n.INVALID_ID_VALUE="invalid @id value",n.INVALID_INDEX_VALUE="invalid @index value",n.INVALID_NEST_VALUE="invalid @nest value",n.INVALID_PREFIX_VALUE="invalid @prefix value",n.INVALID_PROPAGATE_VALUE="invalid @propagate value",n.INVALID_REVERSE_VALUE="invalid @reverse value",n.INVALID_IMPORT_VALUE="invalid @import value",n.INVALID_VERSION_VALUE="invalid @version value",n.INVALID_BASE_IRI="invalid base IRI",n.INVALID_CONTAINER_MAPPING="invalid container mapping",n.INVALID_CONTEXT_ENTRY="invalid context entry",n.INVALID_CONTEXT_NULLIFICATION="invalid context nullification",n.INVALID_DEFAULT_LANGUAGE="invalid default language",n.INVALID_INCLUDED_VALUE="invalid @included value",n.INVALID_IRI_MAPPING="invalid IRI mapping",n.INVALID_JSON_LITERAL="invalid JSON literal",n.INVALID_KEYWORD_ALIAS="invalid keyword alias",n.INVALID_LANGUAGE_MAP_VALUE="invalid language map value",n.INVALID_LANGUAGE_MAPPING="invalid language mapping",n.INVALID_LANGUAGE_TAGGED_STRING="invalid language-tagged string",n.INVALID_LANGUAGE_TAGGED_VALUE="invalid language-tagged value",n.INVALID_LOCAL_CONTEXT="invalid local context",n.INVALID_REMOTE_CONTEXT="invalid remote context",n.INVALID_REVERSE_PROPERTY="invalid reverse property",n.INVALID_REVERSE_PROPERTY_MAP="invalid reverse property map",n.INVALID_REVERSE_PROPERTY_VALUE="invalid reverse property value",n.INVALID_SCOPED_CONTEXT="invalid scoped context",n.INVALID_SCRIPT_ELEMENT="invalid script element",n.INVALID_SET_OR_LIST_OBJECT="invalid set or list object",n.INVALID_TERM_DEFINITION="invalid term definition",n.INVALID_TYPE_MAPPING="invalid type mapping",n.INVALID_TYPE_VALUE="invalid type value",n.INVALID_TYPED_VALUE="invalid typed value",n.INVALID_VALUE_OBJECT="invalid value object",n.INVALID_VALUE_OBJECT_VALUE="invalid value object value",n.INVALID_VOCAB_MAPPING="invalid vocab mapping",n.IRI_CONFUSED_WITH_PREFIX="IRI confused with prefix",n.KEYWORD_REDEFINITION="keyword redefinition",n.LOADING_DOCUMENT_FAILED="loading document failed",n.LOADING_REMOTE_CONTEXT_FAILED="loading remote context failed",n.MULTIPLE_CONTEXT_LINK_HEADERS="multiple context link headers",n.PROCESSING_MODE_CONFLICT="processing mode conflict",n.PROTECTED_TERM_REDEFINITION="protected term redefinition",n.CONTEXT_OVERFLOW="context overflow",n.INVALID_BASE_DIRECTION="invalid base direction",n.RECURSIVE_CONTEXT_INCLUSION="recursive context inclusion",n.INVALID_STREAMING_KEY_ORDER="invalid streaming key order",n.INVALID_EMBEDDED_NODE="invalid embedded node",n.INVALID_ANNOTATION="invalid annotation"},585:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FetchDocumentLoader=void 0,r(6547);const n=r(5094),i=r(2384),o=r(742);t.FetchDocumentLoader=class{constructor(e){this.fetcher=e}async load(e){const t=await(this.fetcher||fetch)(e,{headers:new Headers({accept:"application/ld+json"})});if(t.ok&&t.headers){let r=t.headers.get("Content-Type");if(r){const e=r.indexOf(";");e>0&&(r=r.substr(0,e))}if("application/ld+json"===r)return await t.json();if(t.headers.has("Link")){let r;if(t.headers.forEach(((t,n)=>{if("link"===n){const n=(0,i.parse)(t);for(const t of n.get("type","application/ld+json"))if("alternate"===t.rel){if(r)throw new Error("Multiple JSON-LD alternate links were found on "+e);r=(0,o.resolve)(t.uri,e)}}})),r)return this.load(r)}throw new n.ErrorCoded(`Unsupported JSON-LD media type ${r}`,n.ERROR_CODES.LOADING_DOCUMENT_FAILED)}throw new Error(t.statusText||`Status code: ${t.status}`)}}},9146:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},5086:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},5215:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultExpandOptions=t.JsonLdContextNormalized=void 0;const n=r(742),i=r(5094),o=r(4931);t.JsonLdContextNormalized=class{constructor(e){this.contextRaw=e}getContextRaw(){return this.contextRaw}expandTerm(e,r,s=t.defaultExpandOptions){const a=this.contextRaw[e];if(null===a||a&&null===a["@id"])return null;let c=!0;if(a&&r){const t=o.Util.getContextValueId(a);if(t&&t!==e){if("string"==typeof t&&(o.Util.isValidIri(t)||o.Util.isValidKeyword(t)))return t;o.Util.isPotentialKeyword(t)||(c=!1)}}const l=o.Util.getPrefix(e,this.contextRaw),u=this.contextRaw["@vocab"],d=(!!u||""===u)&&u.indexOf(":")<0,h=this.contextRaw["@base"],f=o.Util.isPotentialKeyword(e);if(l){const t=this.contextRaw[l],r=o.Util.getContextValueId(t);if(r){if("string"!=typeof t&&s.allowPrefixForcing){if("_"!==r[0]&&!f&&!t["@prefix"]&&!(e in this.contextRaw))return e}else if(!o.Util.isSimpleTermDefinitionPrefix(r,s))return e;return r+e.substr(l.length+1)}}else{if(r&&(u||""===u||s.allowVocabRelativeToBase&&h&&d)&&!f&&!o.Util.isCompactIri(e)){if(d){if(s.allowVocabRelativeToBase)return(u||h?(0,n.resolve)(u,h):"")+e;throw new i.ErrorCoded(`Relative vocab expansion for term '${e}' with vocab '${u}' is not allowed.`,i.ERROR_CODES.INVALID_VOCAB_MAPPING)}return u+e}if(!r&&h&&!f&&!o.Util.isCompactIri(e))return(0,n.resolve)(e,h)}if(c)return e;throw new i.ErrorCoded(`Invalid IRI mapping found for context entry '${e}': '${JSON.stringify(a)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING)}compactIri(e,t){if(t&&this.contextRaw["@vocab"]&&e.startsWith(this.contextRaw["@vocab"]))return e.substr(this.contextRaw["@vocab"].length);if(!t&&this.contextRaw["@base"]&&e.startsWith(this.contextRaw["@base"]))return e.substr(this.contextRaw["@base"].length);const r={prefix:"",suffix:e};for(const n in this.contextRaw){const i=this.contextRaw[n];if(i&&!o.Util.isPotentialKeyword(n)){const s=o.Util.getContextValueId(i);if(e.startsWith(s)){const i=e.substr(s.length);if(i)i.length0&&!(e&&"#"===e[0])}static getPrefix(e,t){if(e&&"#"===e[0])return null;const r=e.indexOf(":");if(r>=0){if(e.length>r+1&&"/"===e.charAt(r+1)&&"/"===e.charAt(r+2))return null;const n=e.substr(0,r);if("_"===n)return null;if(t[n])return n}return null}static getContextValueId(e){if(null===e||"string"==typeof e)return e;return e["@id"]||null}static isSimpleTermDefinitionPrefix(e,t){return!r.isPotentialKeyword(e)&&(t.allowPrefixNonGenDelims||"string"==typeof e&&("_"===e[0]||r.isPrefixIriEndingWithGenDelim(e)))}static isPotentialKeyword(e){return"string"==typeof e&&r.KEYWORD_REGEX.test(e)}static isPrefixIriEndingWithGenDelim(e){return r.ENDS_WITH_GEN_DELIM.test(e)}static isPrefixValue(e){return e&&("string"==typeof e||e&&"object"==typeof e)}static isValidIri(e){return Boolean(e&&r.IRI_REGEX.test(e))}static isValidIriWeak(e){return!!e&&":"!==e[0]&&r.IRI_REGEX_WEAK.test(e)}static isValidKeyword(e){return r.VALID_KEYWORDS[e]}static isTermProtected(e,t){const r=e[t];return!("string"==typeof r)&&r&&r["@protected"]}static hasProtectedTerms(e){for(const t of Object.keys(e))if(r.isTermProtected(e,t))return!0;return!1}static isReservedInternalKeyword(e){return e.startsWith("@__")}static deepEqual(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every((r=>{const n=e[r],i=t[r];return n===i||null!==n&&null!==i&&"object"==typeof n&&"object"==typeof i&&this.deepEqual(n,i)}))}}r.IRI_REGEX=/^([A-Za-z][A-Za-z0-9+-.]*|_):[^ "<>{}|\\\[\]`#]*(#[^#]*)?$/,r.IRI_REGEX_WEAK=/(?::[^:])|\//,r.KEYWORD_REGEX=/^@[a-z]+$/i,r.ENDS_WITH_GEN_DELIM=/[:/?#\[\]@]$/,r.REGEX_LANGUAGE_TAG=/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/,r.REGEX_DIRECTION_TAG=/^(ltr)|(rtl)$/,r.VALID_KEYWORDS={"@annotation":!0,"@base":!0,"@container":!0,"@context":!0,"@direction":!0,"@graph":!0,"@id":!0,"@import":!0,"@included":!0,"@index":!0,"@json":!0,"@language":!0,"@list":!0,"@nest":!0,"@none":!0,"@prefix":!0,"@propagate":!0,"@protected":!0,"@reverse":!0,"@set":!0,"@type":!0,"@value":!0,"@version":!0,"@vocab":!0},r.EXPAND_KEYS_BLACKLIST=["@base","@vocab","@language","@version","@direction"],r.ALIAS_DOMAIN_BLACKLIST=["@container","@graph","@id","@index","@list","@nest","@none","@prefix","@reverse","@set","@type","@value","@version"],r.ALIAS_RANGE_BLACKLIST=["@context","@preserve"],r.CONTAINERS=["@list","@set","@index","@language","@graph","@id","@type"],r.CONTAINERS_1_0=["@list","@set","@index"],t.Util=r},8690:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(2277),t)},4405:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextTree=void 0;class r{constructor(){this.subTrees={}}getContext(e){if(e.length>0){const[t,...r]=e,n=this.subTrees[t];if(n){const e=n.getContext(r);if(e)return e.then((({context:e,depth:t})=>({context:e,depth:t+1})))}}return this.context?this.context.then((e=>({context:e,depth:0}))):null}setContext(e,t){if(0===e.length)this.context=t;else{const[n,...i]=e;let o=this.subTrees[n];o||(o=this.subTrees[n]=new r),o.setContext(i,t)}}removeContext(e){this.setContext(e,null)}}t.ContextTree=r},2277:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonLdParser=void 0;const n=r(608),i=r(2395),o=r(2225),s=r(9693),a=r(4860),c=r(2386),l=r(6970),u=r(3809),d=r(5998),h=r(5517),f=r(736),p=r(4910),g=r(2036),y=r(6454),m=r(3283),v=r(3099),b=r(888),w=r(2384),_=r(6105);class S extends o.Transform{constructor(e){super({readableObjectMode:!0}),e=e||{},this.options=e,this.parsingContext=new v.ParsingContext(Object.assign({parser:this},e)),this.util=new b.Util({dataFactory:e.dataFactory,parsingContext:this.parsingContext}),this.jsonParser=new n,this.contextJobs=[],this.typeJobs=[],this.contextAwaitingJobs=[],this.lastDepth=0,this.lastKeys=[],this.lastOnValueJob=Promise.resolve(),this.attachJsonParserListeners(),this.on("end",(()=>{void 0!==this.jsonParser.mode&&this.emit("error",new Error("Unclosed document"))}))}static fromHttpResponse(e,t,r,n){let o,s,a=["application/activity+json"];if(n&&n.wellKnownMediaTypes&&(a=n.wellKnownMediaTypes),"application/ld+json"!==t&&!a.includes(t)){if("application/json"!==t&&!t.endsWith("+json"))throw new i.ErrorCoded(`Unsupported JSON-LD media type ${t}`,i.ERROR_CODES.LOADING_DOCUMENT_FAILED);if(r&&r.has("Link")&&r.forEach(((t,r)=>{if("link"===r){const r=(0,w.parse)(t);for(const t of r.get("rel","http://www.w3.org/ns/json-ld#context")){if(o)throw new i.ErrorCoded("Multiple JSON-LD context link headers were found on "+e,i.ERROR_CODES.MULTIPLE_CONTEXT_LINK_HEADERS);o=t.uri}}})),!o&&!(null==n?void 0:n.ignoreMissingContextLinkHeader))throw new i.ErrorCoded(`Missing context link header for media type ${t} on ${e}`,i.ERROR_CODES.LOADING_DOCUMENT_FAILED)}if(r&&r.has("Content-Type")){const e=r.get("Content-Type"),t=/; *profile=([^"]*)/.exec(e);t&&"http://www.w3.org/ns/json-ld#streaming"===t[1]&&(s=!0)}return new S(Object.assign({baseIRI:e,context:o,streamingProfile:s},n||{}))}import(e){if("pipe"in e){e.on("error",(e=>t.emit("error",e)));const t=e.pipe(new S(this.options));return t}{const t=new o.PassThrough({readableObjectMode:!0});e.on("error",(e=>r.emit("error",e))),e.on("data",(e=>t.push(e))),e.on("end",(()=>t.push(null)));const r=t.pipe(new S(this.options));return r}}_transform(e,t,r){this.jsonParser.write(e),this.lastOnValueJob.then((()=>r()),(e=>r(e)))}async newOnValueJob(e,t,r,n){let o=!0;if(n&&r1&&(u=this.parsingContext.validationStack[this.parsingContext.validationStack.length-1].property);for(let t=Math.max(1,this.parsingContext.validationStack.length-1);t=0?this.parsingContext.idStack[e-r-1]:[await this.util.getGraphContainerValue(t,e)];if(o)for(const t of o){this.parsingContext.emittedStack[e]=!0;for(const r of n)this.util.emitQuadChecked(e,i,r.predicate,r.object,t,r.reverse,r.isEmbedded)}else{const r=this.parsingContext.getUnidentifiedGraphBufferSafe(e-await this.util.getDepthOffsetGraph(e,t)-1);for(const e of n)e.reverse?r.push({object:i,predicate:e.predicate,subject:e.object,isEmbedded:e.isEmbedded}):r.push({object:e.object,predicate:e.predicate,subject:i,isEmbedded:e.isEmbedded})}}this.parsingContext.unidentifiedValuesBuffer.splice(e,1),this.parsingContext.literalStack.splice(e,1),this.parsingContext.jsonLiteralStack.splice(e,1)}const o=this.parsingContext.unidentifiedGraphsBuffer[e];if(o){for(const t of r){const r=1!==e||"BlankNode"!==t.termType||this.parsingContext.topLevelProperties?t:this.util.getDefaultGraph();this.parsingContext.emittedStack[e]=!0;for(const t of o)this.parsingContext.emitQuad(e,this.util.dataFactory.quad(t.subject,t.predicate,t.object,r))}this.parsingContext.unidentifiedGraphsBuffer.splice(e,1)}const s=this.parsingContext.annotationsBuffer[e];if(s){s.length>0&&1===e&&this.parsingContext.emitError(new i.ErrorCoded("Annotations can not be made on top-level nodes",i.ERROR_CODES.INVALID_ANNOTATION));const t=this.parsingContext.getAnnotationsBufferSafe(e-1);for(const e of s)t.push(e);delete this.parsingContext.annotationsBuffer[e]}}async validateKey(e,t,r){for(const n of S.ENTRY_HANDLERS)if(await n.validate(this.parsingContext,this.util,e,t,r))return{valid:!0,property:r||n.isPropertyHandler()};return{valid:!1,property:!1}}attachJsonParserListeners(){this.jsonParser.onValue=e=>{const t=this.jsonParser.stack.length,r=new Array(t+1).fill(0).map(((e,r)=>r===t?this.jsonParser.key:this.jsonParser.stack[r].key));if(!this.isParsingContextInner(t)){const n=()=>this.newOnValueJob(r,e,t,!0);if(this.parsingContext.streamingProfile||this.parsingContext.contextTree.getContext(r.slice(0,-1)))this.lastOnValueJob=this.lastOnValueJob.then(n);else if("@context"===r[t]){let e=this.contextJobs[t];e||(e=this.contextJobs[t]=[]),e.push(n)}else this.contextAwaitingJobs.push({job:n,keys:r,depth:t});this.parsingContext.streamingProfile||0!==t||(this.lastOnValueJob=this.lastOnValueJob.then((()=>this.executeBufferedJobs())))}},this.jsonParser.onError=e=>{this.emit("error",e)}}isParsingContextInner(e){for(let t=e;t>0;t--)if("@context"===this.jsonParser.stack[t-1].key)return!0;return!1}async executeBufferedJobs(){for(const e of this.contextJobs)if(e)for(const t of e)await t();this.parsingContext.unaliasedKeywordCacheStack.splice(0);const e=[];for(const t of this.contextAwaitingJobs)"@type"===await this.util.unaliasKeyword(t.keys[t.depth],t.keys,t.depth,!0)||"number"==typeof t.keys[t.depth]&&"@type"===await this.util.unaliasKeyword(t.keys[t.depth-1],t.keys,t.depth-1,!0)?this.typeJobs.push({job:t.job,keys:t.keys.slice(0,t.keys.length-1)}):e.push(t);for(const t of e){if(this.typeJobs.length>0){const e=[],r=[];for(let n=0;ne.keys.length-t.keys.length));for(const e of n)await e.job();const i=r.sort().reverse();for(const e of i)this.typeJobs.splice(e,1)}await t.job()}}}S.DEFAULT_PROCESSING_MODE="1.1",S.ENTRY_HANDLERS=[new s.EntryHandlerArrayValue,new u.EntryHandlerKeywordContext,new h.EntryHandlerKeywordId,new f.EntryHandlerKeywordIncluded,new d.EntryHandlerKeywordGraph,new p.EntryHandlerKeywordNest,new g.EntryHandlerKeywordType,new m.EntryHandlerKeywordValue,new _.EntryHandlerKeywordAnnotation,new a.EntryHandlerContainer,new y.EntryHandlerKeywordUnknownFallback,new l.EntryHandlerPredicate,new c.EntryHandlerInvalidFallback],t.JsonLdParser=S},3099:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ParsingContext=void 0;const n=r(2395),i=r(5094),o=r(4405),s=r(2277);class a{constructor(e){this.contextParser=new n.ContextParser({documentLoader:e.documentLoader,skipValidation:e.skipContextValidation}),this.streamingProfile=!!e.streamingProfile,this.baseIRI=e.baseIRI,this.produceGeneralizedRdf=!!e.produceGeneralizedRdf,this.allowSubjectList=!!e.allowSubjectList,this.processingMode=e.processingMode||s.JsonLdParser.DEFAULT_PROCESSING_MODE,this.strictValues=!!e.strictValues,this.validateValueIndexes=!!e.validateValueIndexes,this.defaultGraph=e.defaultGraph,this.rdfDirection=e.rdfDirection,this.normalizeLanguageTags=e.normalizeLanguageTags,this.streamingProfileAllowOutOfOrderPlainType=e.streamingProfileAllowOutOfOrderPlainType,this.rdfstar=!1!==e.rdfstar,this.rdfstarReverseInEmbedded=e.rdfstarReverseInEmbedded,this.topLevelProperties=!1,this.activeProcessingMode=parseFloat(this.processingMode),this.processingStack=[],this.processingType=[],this.emittedStack=[],this.idStack=[],this.graphStack=[],this.graphContainerTermStack=[],this.listPointerStack=[],this.contextTree=new o.ContextTree,this.literalStack=[],this.validationStack=[],this.unaliasedKeywordCacheStack=[],this.jsonLiteralStack=[],this.unidentifiedValuesBuffer=[],this.unidentifiedGraphsBuffer=[],this.annotationsBuffer=[],this.pendingContainerFlushBuffers=[],this.parser=e.parser,e.context?(this.rootContext=this.parseContext(e.context),this.rootContext.then((e=>this.validateContext(e)))):this.rootContext=Promise.resolve(new n.JsonLdContextNormalized(this.baseIRI?{"@base":this.baseIRI,"@__baseDocument":!0}:{}))}async parseContext(e,t,r){return this.contextParser.parse(e,{baseIRI:this.baseIRI,ignoreProtection:r,normalizeLanguageTags:this.normalizeLanguageTags,parentContext:t,processingMode:this.activeProcessingMode})}validateContext(e){const t=e.getContextRaw()["@version"];if(t){if(this.activeProcessingMode&&t>this.activeProcessingMode)throw new i.ErrorCoded(`Unsupported JSON-LD version '${t}' under active processing mode ${this.activeProcessingMode}.`,i.ERROR_CODES.PROCESSING_MODE_CONFLICT);if(this.activeProcessingMode&&t0&&!1===i.context.getContextRaw()["@propagate"]&&i.depth!==t&&!r);return 0===i.depth&&!1===i.context.getContextRaw()["@propagate"]&&i.depth!==t&&(i.context=new n.JsonLdContextNormalized({})),i}async newOnValueJob(e,t,r,n){await this.parser.newOnValueJob(e,t,r,n)}async handlePendingContainerFlushBuffers(){if(this.pendingContainerFlushBuffers.length>0){for(const e of this.pendingContainerFlushBuffers)await this.parser.flushBuffer(e.depth,e.keys),this.parser.flushStacks(e.depth);return this.pendingContainerFlushBuffers.splice(0,this.pendingContainerFlushBuffers.length),!0}return!1}emitQuad(e,t){1===e&&(this.topLevelProperties=!0),this.parser.push(t)}emitError(e){this.parser.emit("error",e)}emitContext(e){this.parser.emit("context",e)}getUnidentifiedValueBufferSafe(e){let t=this.unidentifiedValuesBuffer[e];return t||(t=[],this.unidentifiedValuesBuffer[e]=t),t}getUnidentifiedGraphBufferSafe(e){let t=this.unidentifiedGraphsBuffer[e];return t||(t=[],this.unidentifiedGraphsBuffer[e]=t),t}getAnnotationsBufferSafe(e){let t=this.annotationsBuffer[e];return t||(t=[],this.annotationsBuffer[e]=t),t}getExpandOptions(){return a.EXPAND_OPTIONS[this.activeProcessingMode]}shiftStack(e,t){const r=this.idStack[e+t];if(r&&(this.idStack[e]=r,this.emittedStack[e]=!0,delete this.idStack[e+t]),this.pendingContainerFlushBuffers.length)for(const r of this.pendingContainerFlushBuffers)r.depth>=e+t&&(r.depth-=t,r.keys.splice(e,t));this.unidentifiedValuesBuffer[e+t]&&(this.unidentifiedValuesBuffer[e]=this.unidentifiedValuesBuffer[e+t],delete this.unidentifiedValuesBuffer[e+t]),this.annotationsBuffer[e+t-1]&&(this.annotationsBuffer[e-1]||(this.annotationsBuffer[e-1]=[]),this.annotationsBuffer[e-1]=[...this.annotationsBuffer[e-1],...this.annotationsBuffer[e+t-1]],delete this.annotationsBuffer[e+t-1])}}a.EXPAND_OPTIONS={1:{allowPrefixForcing:!1,allowPrefixNonGenDelims:!1,allowVocabRelativeToBase:!1},1.1:{allowPrefixForcing:!0,allowPrefixNonGenDelims:!1,allowVocabRelativeToBase:!0}},t.ParsingContext=a},888:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Util=void 0;const n=r(2395),i=r(7793),o=r(4860),s=r(2341);class a{constructor(e){this.parsingContext=e.parsingContext,this.dataFactory=e.dataFactory||new i.DataFactory,this.rdfFirst=this.dataFactory.namedNode(a.RDF+"first"),this.rdfRest=this.dataFactory.namedNode(a.RDF+"rest"),this.rdfNil=this.dataFactory.namedNode(a.RDF+"nil"),this.rdfType=this.dataFactory.namedNode(a.RDF+"type"),this.rdfJson=this.dataFactory.namedNode(a.RDF+"JSON")}static getContextValue(e,t,r,n){const i=e.getContextRaw()[r];if(!i)return n;const o=i[t];return void 0===o?n:o}static getContextValueContainer(e,t){return a.getContextValue(e,"@container",t,{"@set":!0})}static getContextValueType(e,t){const r=a.getContextValue(e,"@type",t,null);return"@none"===r?null:r}static getContextValueLanguage(e,t){return a.getContextValue(e,"@language",t,e.getContextRaw()["@language"]||null)}static getContextValueDirection(e,t){return a.getContextValue(e,"@direction",t,e.getContextRaw()["@direction"]||null)}static isContextValueReverse(e,t){return!!a.getContextValue(e,"@reverse",t,null)}static getContextValueIndex(e,t){return a.getContextValue(e,"@index",t,e.getContextRaw()["@index"]||null)}static isPropertyReverse(e,t,r){return"@reverse"===r!==a.isContextValueReverse(e,t)}static isPropertyInEmbeddedNode(e){return"@id"===e}static isPropertyInAnnotationObject(e){return"@annotation"===e}static isValidIri(e){return null!==e&&n.Util.isValidIri(e)}static isPrefixArray(e,t){if(e.length>t.length)return!1;for(let r=0;r1)throw new n.ErrorCoded(`Found illegal neighbouring entries next to @set for key: '${t}'`,n.ERROR_CODES.INVALID_SET_OR_LIST_OBJECT);return[]}if("@list"in r){if(Object.keys(r).length>1)throw new n.ErrorCoded(`Found illegal neighbouring entries next to @list for key: '${t}'`,n.ERROR_CODES.INVALID_SET_OR_LIST_OBJECT);const e=r["@list"];return Array.isArray(e)?0===e.length?[this.rdfNil]:this.parsingContext.idStack[i+1]||[]:await this.valueToTerm(await this.parsingContext.getContext(o),t,e,i-1,o.slice(0,-1))}if("@reverse"in r&&"boolean"==typeof r["@reverse"])return[];if("@graph"in a.getContextValueContainer(await this.parsingContext.getContext(o),t)){const e=this.parsingContext.graphContainerTermStack[i+1];return e?Object.values(e):[this.dataFactory.blankNode()]}if("@id"in r){if(Object.keys(r).length>1&&(e=await this.parsingContext.getContext(o,0)),"@context"in r&&(e=await this.parsingContext.parseContext(r["@context"],e.getContextRaw())),"@vocab"===r["@type"])return this.nullableTermToArray(this.createVocabOrBaseTerm(e,r["@id"]));{const t=r["@id"];let o;if("object"==typeof t){if(!this.parsingContext.rdfstar)throw new n.ErrorCoded(`Found illegal @id '${r}'`,n.ERROR_CODES.INVALID_ID_VALUE);o=this.parsingContext.idStack[i+1][0]}else o=this.resourceToTerm(e,t);return this.nullableTermToArray(o)}}return this.parsingContext.emittedStack[i+1]||r&&"object"==typeof r&&0===Object.keys(r).length?this.parsingContext.idStack[i+1]||(this.parsingContext.idStack[i+1]=[this.dataFactory.blankNode()]):[];case"string":return this.nullableTermToArray(this.stringValueToTerm(i,await this.getContextSelfOrPropertyScoped(e,t),t,r,null));case"boolean":return this.nullableTermToArray(this.stringValueToTerm(i,await this.getContextSelfOrPropertyScoped(e,t),t,Boolean(r).toString(),this.dataFactory.namedNode(a.XSD_BOOLEAN)));case"number":return this.nullableTermToArray(this.stringValueToTerm(i,await this.getContextSelfOrPropertyScoped(e,t),t,r,this.dataFactory.namedNode(r%1==0&&r<1e21?a.XSD_INTEGER:a.XSD_DOUBLE)));default:return this.parsingContext.emitError(new Error(`Could not determine the RDF type of a ${s}`)),[]}}async getContextSelfOrPropertyScoped(e,t){const r=e.getContextRaw()[t];return r&&"object"==typeof r&&"@context"in r&&(e=await this.parsingContext.parseContext(r,e.getContextRaw(),!0)),e}nullableTermToArray(e){return e?[e]:[]}predicateToTerm(e,t){const r=e.expandTerm(t,!0,this.parsingContext.getExpandOptions());return r?"_"===r[0]&&":"===r[1]?this.parsingContext.produceGeneralizedRdf?this.dataFactory.blankNode(r.substr(2)):null:a.isValidIri(r)?this.dataFactory.namedNode(r):r&&this.parsingContext.strictValues?(this.parsingContext.emitError(new n.ErrorCoded(`Invalid predicate IRI: ${r}`,n.ERROR_CODES.INVALID_IRI_MAPPING)),null):null:null}resourceToTerm(e,t){if(t.startsWith("_:"))return this.dataFactory.blankNode(t.substr(2));const r=e.expandTerm(t,!1,this.parsingContext.getExpandOptions());if(!a.isValidIri(r)){if(!r||!this.parsingContext.strictValues)return null;this.parsingContext.emitError(new Error(`Invalid resource IRI: ${r}`))}return this.dataFactory.namedNode(r)}createVocabOrBaseTerm(e,t){if(t.startsWith("_:"))return this.dataFactory.blankNode(t.substr(2));const r=this.parsingContext.getExpandOptions();let n=e.expandTerm(t,!0,r);if(n===t&&(n=e.expandTerm(t,!1,r)),!a.isValidIri(n)){if(!n||!this.parsingContext.strictValues||n.startsWith("@"))return null;this.parsingContext.emitError(new Error(`Invalid term IRI: ${n}`))}return this.dataFactory.namedNode(n)}intToString(e,t){return"number"==typeof e?Number.isFinite(e)?e%1!=0||t&&t.value===a.XSD_DOUBLE?e.toExponential(15).replace(/(\d)0*e\+?/,"$1E"):Number(e).toString():e>0?"INF":"-INF":e}stringValueToTerm(e,t,r,n,i){const o=a.getContextValueType(t,r);if(o)if("@id"===o){if(!i)return this.resourceToTerm(t,this.intToString(n,i))}else if("@vocab"===o){if(!i)return this.createVocabOrBaseTerm(t,this.intToString(n,i))}else i=this.dataFactory.namedNode(o);if(!i){const o=a.getContextValueLanguage(t,r),s=a.getContextValueDirection(t,r);return s&&this.parsingContext.rdfDirection?this.createLanguageDirectionLiteral(e,this.intToString(n,i),o,s):this.dataFactory.literal(this.intToString(n,i),o)}return this.dataFactory.literal(this.intToString(n,i),i)}createLanguageDirectionLiteral(e,t,r,n){if("i18n-datatype"===this.parsingContext.rdfDirection)return r||(r=""),this.dataFactory.literal(t,this.dataFactory.namedNode(`https://www.w3.org/ns/i18n#${r}_${n}`));{const i=this.dataFactory.blankNode(),o=this.getDefaultGraph();return this.parsingContext.emitQuad(e,this.dataFactory.quad(i,this.dataFactory.namedNode(a.RDF+"value"),this.dataFactory.literal(t),o)),r&&this.parsingContext.emitQuad(e,this.dataFactory.quad(i,this.dataFactory.namedNode(a.RDF+"language"),this.dataFactory.literal(r),o)),this.parsingContext.emitQuad(e,this.dataFactory.quad(i,this.dataFactory.namedNode(a.RDF+"direction"),this.dataFactory.literal(n),o)),i}}valueToJsonString(e){return s(e)}async unaliasKeyword(e,t,r,i,o){if(Number.isInteger(e))return e;if(!i){const e=this.parsingContext.unaliasedKeywordCacheStack[r];if(e)return e}if(!n.Util.isPotentialKeyword(e)){let r=(o=o||await this.parsingContext.getContext(t)).getContextRaw()[e];r&&"object"==typeof r&&(r=r["@id"]),n.Util.isValidKeyword(r)&&(e=r)}return i?e:this.parsingContext.unaliasedKeywordCacheStack[r]=e}async unaliasKeywordParent(e,t){return await this.unaliasKeyword(t>0&&e[t-1],e,t-1)}async unaliasKeywords(e,t,r,n){const i={};for(const o in e)i[await this.unaliasKeyword(o,t,r+1,!0,n)]=e[o];return i}async isLiteral(e,t){for(let r=t;r>=0;r--){if("@annotation"===await this.unaliasKeyword(e[r],e,r))return!1;if(this.parsingContext.literalStack[r]||this.parsingContext.jsonLiteralStack[r])return!0}return!1}async getDepthOffsetGraph(e,t){for(let r=e-1;r>0;r--)if("@graph"===await this.unaliasKeyword(t[r],t,r)){const n=(await o.EntryHandlerContainer.getContainerHandler(this.parsingContext,t,r)).containers;return o.EntryHandlerContainer.isComplexGraphContainer(n)?-1:e-r-1}return-1}validateReverseSubject(e){if("Literal"===e.termType)throw new n.ErrorCoded(`Found illegal literal in subject position: ${e.value}`,n.ERROR_CODES.INVALID_REVERSE_PROPERTY_VALUE)}getDefaultGraph(){return this.parsingContext.defaultGraph||this.dataFactory.defaultGraph()}async getGraphContainerValue(e,t){let r=this.getDefaultGraph();const{containers:n,depth:i}=await o.EntryHandlerContainer.getContainerHandler(this.parsingContext,e,t);if("@graph"in n){const t=o.EntryHandlerContainer.getContainerGraphIndex(n,i,e),s=this.parsingContext.graphContainerTermStack[i];if(r=s?s[t]:null,!r){let o=null;if("@id"in n){const t=await this.getContainerKey(e[i],e,i);null!==t&&(o=await this.resourceToTerm(await this.parsingContext.getContext(e),t))}o||(o=this.dataFactory.blankNode()),this.parsingContext.graphContainerTermStack[i]||(this.parsingContext.graphContainerTermStack[i]={}),r=this.parsingContext.graphContainerTermStack[i][t]=o}}return r}async getPropertiesDepth(e,t){let r=t;for(let n=t-1;n>0;n--)if("number"!=typeof e[n]){const t=await this.unaliasKeyword(e[n],e,n);if("@reverse"===t)return n;if("@nest"!==t)return r;r=n}return r}async getContainerKey(e,t,r){const n=await this.unaliasKeyword(e,t,r);return"@none"===n?null:n}validateReverseInEmbeddedNode(e,t,r){if(r&&t&&!this.parsingContext.rdfstarReverseInEmbedded)throw new n.ErrorCoded(`Illegal reverse property in embedded node in ${e}`,n.ERROR_CODES.INVALID_EMBEDDED_NODE)}emitQuadChecked(e,t,r,i,o,s,a){let c;if(s?(this.validateReverseSubject(i),c=this.dataFactory.quad(i,r,t,o)):c=this.dataFactory.quad(t,r,i,o),a){if("DefaultGraph"!==c.graph.termType&&(c=this.dataFactory.quad(c.subject,c.predicate,c.object)),this.parsingContext.idStack[e-1])throw new n.ErrorCoded("Illegal multiple properties in an embedded node",n.ERROR_CODES.INVALID_EMBEDDED_NODE);this.parsingContext.idStack[e-1]=[c]}else this.parsingContext.emitQuad(e,c);const l=this.parsingContext.annotationsBuffer[e];if(l){for(const t of l)this.emitAnnotation(e,c,t);delete this.parsingContext.annotationsBuffer[e]}}emitAnnotation(e,t,r){let n;r.reverse?(this.validateReverseSubject(r.object),n=this.dataFactory.quad(r.object,r.predicate,t)):n=this.dataFactory.quad(t,r.predicate,r.object),this.parsingContext.emitQuad(e,n);for(const t of r.nestedAnnotations)this.emitAnnotation(e,n,t)}}a.XSD="http://www.w3.org/2001/XMLSchema#",a.XSD_BOOLEAN=a.XSD+"boolean",a.XSD_INTEGER=a.XSD+"integer",a.XSD_DOUBLE=a.XSD+"double",a.RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",t.Util=a},7986:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContainerHandlerIdentifier=void 0,t.ContainerHandlerIdentifier=class{canCombineWithGraph(){return!0}async handle(e,t,r,n,i,o){let s;if(t.emittedStack[o+1]&&t.idStack[o+1])s=t.idStack[o+1][0];else{const e=null!==await r.getContainerKey(n[o],n,o)?await r.resourceToTerm(await t.getContext(n),n[o]):r.dataFactory.blankNode();if(!e)return void(t.emittedStack[o]=!1);s=e,t.idStack[o+1]=[s]}let a=t.idStack[o];a||(a=t.idStack[o]=[]),a.some((e=>e.equals(s)))||a.push(s),await t.handlePendingContainerFlushBuffers()||(t.emittedStack[o]=!1)}}},1977:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContainerHandlerIndex=void 0;const n=r(2395),i=r(6970),o=r(888);t.ContainerHandlerIndex=class{canCombineWithGraph(){return!0}async handle(e,t,r,s,a,c){if(!Array.isArray(a)){const l="@graph"in e,u=await t.getContext(s),d=s[c-1],h=o.Util.getContextValueIndex(u,d);if(h){if(n.Util.isPotentialKeyword(h))throw new n.ErrorCoded(`Keywords can not be used as @index value, got: ${h}`,n.ERROR_CODES.INVALID_TERM_DEFINITION);if("string"!=typeof h)throw new n.ErrorCoded(`@index values must be strings, got: ${h}`,n.ERROR_CODES.INVALID_TERM_DEFINITION);if("object"!=typeof a){if("@id"!==o.Util.getContextValueType(u,d))throw new n.ErrorCoded(`Property-based index containers require nodes as values or strings with @type: @id, but got: ${a}`,n.ERROR_CODES.INVALID_VALUE_OBJECT);const e=r.resourceToTerm(u,a);e&&(t.idStack[c+1]=[e])}const e=r.createVocabOrBaseTerm(u,h);if(e){const n=await r.valueToTerm(u,h,await r.getContainerKey(s[c],s,c),c,s);if(l){const i=await r.getGraphContainerValue(s,c+1);for(const o of n)t.emitQuad(c,r.dataFactory.quad(i,e,o,r.getDefaultGraph()))}else for(const o of n)await i.EntryHandlerPredicate.handlePredicateObject(t,r,s,c+1,e,o,!1,!1,!1)}}const f=l?2:1;await t.newOnValueJob(s.slice(0,s.length-f),a,c-f,!0),await t.handlePendingContainerFlushBuffers()}t.emittedStack[c]=!1}}},3847:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContainerHandlerLanguage=void 0;const n=r(2395);t.ContainerHandlerLanguage=class{canCombineWithGraph(){return!1}async handle(e,t,r,i,o,s){const a=await r.getContainerKey(i[s],i,s);if(Array.isArray(o))o=o.map((e=>({"@value":e,"@language":a})));else{if("string"!=typeof o)throw new n.ErrorCoded(`Got invalid language map value, got '${JSON.stringify(o)}', but expected string`,n.ERROR_CODES.INVALID_LANGUAGE_MAP_VALUE);o={"@value":o,"@language":a}}await t.newOnValueJob(i.slice(0,i.length-1),o,s-1,!0),t.emittedStack[s]=!1}}},7229:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContainerHandlerType=void 0;const n=r(6970),i=r(888);t.ContainerHandlerType=class{canCombineWithGraph(){return!1}async handle(e,t,r,o,s,a){if(!Array.isArray(s)){if("string"==typeof s){const e=await t.getContext(o),n="@vocab"===i.Util.getContextValueType(e,o[a-1])?await r.createVocabOrBaseTerm(e,s):await r.resourceToTerm(e,s);if(n){const e={"@id":"NamedNode"===n.termType?n.value:s};await t.newOnValueJob(o.slice(0,o.length-1),e,a-1,!0),t.idStack[a+1]=[n]}}else{const e=!!t.idStack[a+1];e||delete t.idStack[a],await t.newOnValueJob(o.slice(0,o.length-1),s,a-1,!0),e||(t.idStack[a+1]=t.idStack[a])}const e=await r.getContainerKey(o[a],o,a),c=null!==e?r.createVocabOrBaseTerm(await t.getContext(o),e):null;c&&await n.EntryHandlerPredicate.handlePredicateObject(t,r,o,a+1,r.rdfType,c,!1,!1,!1),await t.handlePendingContainerFlushBuffers()}t.emittedStack[a]=!1}}},9693:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerArrayValue=void 0;const n=r(888),i=r(2395);t.EntryHandlerArrayValue=class{isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,n,i){return this.test(e,t,null,r,n)}async test(e,t,r,n,i){return"number"==typeof n[i]}async handle(e,t,r,i,o,s){let a=await t.unaliasKeywordParent(i,s);if("@list"===a){let r=null,n=0;for(let e=s-2;e>0;e--){const t=i[e];if("string"==typeof t||"number"==typeof t){n=e,r=t;break}}if(null!==r){const a=await t.valueToTerm(await e.getContext(i),r,o,s,i);for(const r of a)await this.handleListElement(e,t,r,o,s,i.slice(0,n),n);0===a.length&&await this.handleListElement(e,t,null,o,s,i.slice(0,n),n)}}else if("@set"===a)await e.newOnValueJob(i.slice(0,-2),o,s-2,!1);else if(void 0!==a&&"@type"!==a){for(let e=s-1;e>0;e--)if("number"!=typeof i[e]){a=await t.unaliasKeyword(i[e],i,e);break}const r=await e.getContext(i.slice(0,-1));if("@list"in n.Util.getContextValueContainer(r,a)){e.emittedStack[s+1]=!0;const r=await t.valueToTerm(await e.getContext(i),a,o,s,i);for(const n of r)await this.handleListElement(e,t,n,o,s,i.slice(0,-1),s-1);0===r.length&&await this.handleListElement(e,t,null,o,s,i.slice(0,-1),s-1)}else e.shiftStack(s,1),await e.newOnValueJob(i.slice(0,-1),o,s-1,!1),e.contextTree.removeContext(i.slice(0,-1))}}async handleListElement(e,t,r,n,o,s,a){let c=e.listPointerStack[o];if(null!==n&&null!==(await t.unaliasKeywords(n,s,o))["@value"]){if(c&&c.value){const r=t.dataFactory.blankNode();e.emitQuad(o,t.dataFactory.quad(c.value,t.rdfRest,r,t.getDefaultGraph())),c.value=r}else{const e=t.dataFactory.blankNode();c={value:e,listRootDepth:a,listId:e}}r&&e.emitQuad(o,t.dataFactory.quad(c.value,t.rdfFirst,r,t.getDefaultGraph()))}else c||(c={listRootDepth:a,listId:t.rdfNil});e.listPointerStack[o]=c,e.rdfstar&&e.annotationsBuffer[o]&&e.emitError(new i.ErrorCoded("Found an illegal annotation inside a list",i.ERROR_CODES.INVALID_ANNOTATION))}}},4860:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerContainer=void 0;const n=r(7986),i=r(1977),o=r(3847),s=r(7229),a=r(888);class c{static isSimpleGraphContainer(e){return"@graph"in e&&("@set"in e&&2===Object.keys(e).length||1===Object.keys(e).length)}static isComplexGraphContainer(e){return"@graph"in e&&("@set"in e&&Object.keys(e).length>2||!("@set"in e)&&Object.keys(e).length>1)}static getContainerGraphIndex(e,t,r){let n=c.isSimpleGraphContainer(e),i="";for(let e=t;e=0;e--)if("number"!=typeof t[e]){const r=a.Util.getContextValue(o,"@container",t[e],!1);if(r&&c.isSimpleGraphContainer(r))return{containers:r,depth:e+1,fallback:!1};const s=a.Util.getContextValue(o,"@container",t[e-1],!1);if(s){const t="@graph"in s;for(const r in c.CONTAINER_HANDLERS)if(s[r])return t?c.CONTAINER_HANDLERS[r].canCombineWithGraph()?{containers:s,depth:e,fallback:!1}:n:i?n:{containers:s,depth:e,fallback:!1};return n}if(i)return n;i=!0}return n}static async isBufferableContainerHandler(e,t,r){const n=await c.getContainerHandler(e,t,r);return!n.fallback&&!("@graph"in n.containers)}isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,n,i){return!!await this.test(e,t,null,r,n)}async test(e,t,r,n,i){const o=a.Util.getContextValueContainer(await e.getContext(n,2),n[i-1]);for(const e in c.CONTAINER_HANDLERS)if(o[e])return{containers:o,handler:c.CONTAINER_HANDLERS[e]};return null}async handle(e,t,r,n,i,o,s){return s.handler.handle(s.containers,e,t,n,i,o)}}c.CONTAINER_HANDLERS={"@id":new n.ContainerHandlerIdentifier,"@index":new i.ContainerHandlerIndex,"@language":new o.ContainerHandlerLanguage,"@type":new s.ContainerHandlerType},t.EntryHandlerContainer=c},2386:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerInvalidFallback=void 0,t.EntryHandlerInvalidFallback=class{isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,n,i){return!1}async test(e,t,r,n,i){return!0}async handle(e,t,r,n,i,o){e.emittedStack[o]=!1}}},6970:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerPredicate=void 0;const n=r(2395),i=r(888);class o{static async handlePredicateObject(e,t,r,i,o,s,a,c,l){const u=await t.getPropertiesDepth(r,i),d=await t.getDepthOffsetGraph(i,r),h=i-d,f=e.idStack[u];if(f&&!l)for(const n of f)if(d>=0){const r=e.idStack[h-1];if(r)for(const e of r)t.emitQuadChecked(i,n,o,s,e,a,c);else a?(t.validateReverseSubject(s),e.getUnidentifiedGraphBufferSafe(h-1).push({subject:s,predicate:o,object:n,isEmbedded:c})):e.getUnidentifiedGraphBufferSafe(h-1).push({subject:n,predicate:o,object:s,isEmbedded:c})}else{const e=await t.getGraphContainerValue(r,u);t.emitQuadChecked(i,n,o,s,e,a,c)}else if(a&&t.validateReverseSubject(s),l){if(e.rdfstar){e.idStack[i]&&e.emitError(new n.ErrorCoded(`Found an illegal @id inside an annotation: ${e.idStack[i][0].value}`,n.ERROR_CODES.INVALID_ANNOTATION));for(let o=0;o=0;e--){const t=c[e];t.depth>u&&(l.nestedAnnotations.push(t),c.splice(e,1))}}}else e.getUnidentifiedValueBufferSafe(u).push({predicate:o,object:s,reverse:a,isEmbedded:c})}isPropertyHandler(){return!0}isStackProcessor(){return!0}async validate(e,t,r,n,o){const s=r[n];if(s){const o=await e.getContext(r);if(!e.jsonLiteralStack[n]&&await t.predicateToTerm(o,r[n]))return"@json"===i.Util.getContextValueType(o,s)&&(e.jsonLiteralStack[n+1]=!0),!0}return!1}async test(e,t,r,n,i){return n[i]}async handle(e,t,r,s,a,c,l){const u=s[c],d=await e.getContext(s),h=await t.predicateToTerm(d,r);if(h){const l=await t.valueToTerm(d,r,a,c,s);if(l.length)for(let f of l){let l=await t.unaliasKeywordParent(s,c);const p=i.Util.isPropertyReverse(d,u,l);let g=0;for(;"@reverse"===l||"number"==typeof l;)"number"==typeof l?g++:c--,l=await t.unaliasKeywordParent(s,c-g);const y=i.Util.isPropertyInEmbeddedNode(l);t.validateReverseInEmbeddedNode(r,p,y);const m=i.Util.isPropertyInAnnotationObject(l);if(a){const o="@list"in i.Util.getContextValueContainer(d,r);if(o||a["@list"]){if((o&&!Array.isArray(a)&&!a["@list"]||a["@list"]&&!Array.isArray(a["@list"]))&&f!==t.rdfNil){const r=t.dataFactory.blankNode();e.emitQuad(c,t.dataFactory.quad(r,t.rdfRest,t.rdfNil,t.getDefaultGraph())),e.emitQuad(c,t.dataFactory.quad(r,t.rdfFirst,f,t.getDefaultGraph())),f=r}if(p&&!e.allowSubjectList)throw new n.ErrorCoded(`Found illegal list value in subject position at ${r}`,n.ERROR_CODES.INVALID_REVERSE_PROPERTY_VALUE)}}await o.handlePredicateObject(e,t,s,c,h,f,p,y,m)}}}}t.EntryHandlerPredicate=o},1548:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeyword=void 0,t.EntryHandlerKeyword=class{constructor(e){this.keyword=e}isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,n,i){return!1}async test(e,t,r,n,i){return r===this.keyword}}},6105:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordAnnotation=void 0;const n=r(1548),i=r(2395);class o extends n.EntryHandlerKeyword{constructor(){super("@annotation")}async handle(e,t,r,n,o,s){("string"==typeof o||"object"==typeof o&&o["@value"])&&e.emitError(new i.ErrorCoded(`Found illegal annotation value: ${JSON.stringify(o)}`,i.ERROR_CODES.INVALID_ANNOTATION))}}t.EntryHandlerKeywordAnnotation=o},3809:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordContext=void 0;const n=r(2395),i=r(1548);class o extends i.EntryHandlerKeyword{constructor(){super("@context")}isStackProcessor(){return!1}async handle(e,t,r,i,o,s){e.streamingProfile&&(e.processingStack[s]||e.processingType[s]||void 0!==e.idStack[s])&&e.emitError(new n.ErrorCoded("Found an out-of-order context, while streaming is enabled.(disable `streamingProfile`)",n.ERROR_CODES.INVALID_STREAMING_KEY_ORDER));const a=e.getContext(i),c=e.parseContext(o,(await a).getContextRaw());e.contextTree.setContext(i.slice(0,-1),c),e.emitContext(o),await e.validateContext(await c)}}t.EntryHandlerKeywordContext=o},5998:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordGraph=void 0;const n=r(1548);class i extends n.EntryHandlerKeyword{constructor(){super("@graph")}async handle(e,t,r,n,i,o){e.graphStack[o+1]=!0}}t.EntryHandlerKeywordGraph=i},5517:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordId=void 0;const n=r(2395),i=r(1548);class o extends i.EntryHandlerKeyword{constructor(){super("@id")}isStackProcessor(){return!1}async handle(e,t,r,i,o,s){if("string"!=typeof o){if(e.rdfstar&&"object"==typeof o){const t=Object.keys(o);1===t.length&&"@id"===t[0]&&e.emitError(new n.ErrorCoded(`Invalid embedded node without property with @id ${o["@id"]}`,n.ERROR_CODES.INVALID_EMBEDDED_NODE))}else e.emitError(new n.ErrorCoded(`Found illegal @id '${o}'`,n.ERROR_CODES.INVALID_ID_VALUE));return}const a=await t.getPropertiesDepth(i,s);if(void 0!==e.idStack[a]&&(e.idStack[a][0].listHead?e.emitError(new n.ErrorCoded(`Found illegal neighbouring entries next to @list for key: '${i[s-1]}'`,n.ERROR_CODES.INVALID_SET_OR_LIST_OBJECT)):e.emitError(new n.ErrorCoded(`Found duplicate @ids '${e.idStack[a][0].value}' and '${o}'`,n.ERROR_CODES.COLLIDING_KEYWORDS))),e.rdfstar&&e.annotationsBuffer[s])for(const t of e.annotationsBuffer[s])t.depth===s&&e.emitError(new n.ErrorCoded(`Found an illegal @id inside an annotation: ${o}`,n.ERROR_CODES.INVALID_ANNOTATION));e.idStack[a]=t.nullableTermToArray(await t.resourceToTerm(await e.getContext(i),o))}}t.EntryHandlerKeywordId=o},736:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordIncluded=void 0;const n=r(2395),i=r(1548);class o extends i.EntryHandlerKeyword{constructor(){super("@included")}async handle(e,t,r,i,o,s){"object"!=typeof o&&e.emitError(new n.ErrorCoded(`Found illegal @included '${o}'`,n.ERROR_CODES.INVALID_INCLUDED_VALUE));const a=await t.unaliasKeywords(o,i,s,await e.getContext(i));"@value"in a&&e.emitError(new n.ErrorCoded(`Found an illegal @included @value node '${JSON.stringify(o)}'`,n.ERROR_CODES.INVALID_INCLUDED_VALUE)),"@list"in a&&e.emitError(new n.ErrorCoded(`Found an illegal @included @list node '${JSON.stringify(o)}'`,n.ERROR_CODES.INVALID_INCLUDED_VALUE)),e.emittedStack[s]=!1}}t.EntryHandlerKeywordIncluded=o},4910:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordNest=void 0;const n=r(2395),i=r(1548);class o extends i.EntryHandlerKeyword{constructor(){super("@nest")}async handle(e,t,r,i,o,s){"object"!=typeof o&&e.emitError(new n.ErrorCoded(`Found invalid @nest entry for '${r}': '${o}'`,n.ERROR_CODES.INVALID_NEST_VALUE)),"@value"in await t.unaliasKeywords(o,i,s,await e.getContext(i))&&e.emitError(new n.ErrorCoded(`Found an invalid @value node for '${r}'`,n.ERROR_CODES.INVALID_NEST_VALUE)),e.emittedStack[s]=!1}}t.EntryHandlerKeywordNest=o},2036:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordType=void 0;const n=r(2395),i=r(888),o=r(6970),s=r(1548);class a extends s.EntryHandlerKeyword{constructor(){super("@type")}isStackProcessor(){return!1}async handle(e,t,r,s,a,c){const l=s[c],u=await e.getContext(s),d=t.rdfType,h=await t.unaliasKeywordParent(s,c),f=i.Util.isPropertyReverse(u,l,h),p=i.Util.isPropertyInEmbeddedNode(h);t.validateReverseInEmbeddedNode(r,f,p);const g=i.Util.isPropertyInAnnotationObject(h),y=Array.isArray(a)?a:[a];for(const r of y){"string"!=typeof r&&e.emitError(new n.ErrorCoded(`Found illegal @type '${r}'`,n.ERROR_CODES.INVALID_TYPE_VALUE));const i=t.createVocabOrBaseTerm(u,r);i&&await o.EntryHandlerPredicate.handlePredicateObject(e,t,s,c,d,i,f,p,g)}let m=Promise.resolve(u),v=!1;for(const t of y.sort()){const r=i.Util.getContextValue(u,"@context",t,null);r&&(v=!0,m=m.then((t=>e.parseContext(r,t.getContextRaw()))))}!e.streamingProfile||!v&&e.streamingProfileAllowOutOfOrderPlainType||!e.processingStack[c]&&!e.idStack[c]||e.emitError(new n.ErrorCoded("Found an out-of-order type-scoped context, while streaming is enabled.(disable `streamingProfile`)",n.ERROR_CODES.INVALID_STREAMING_KEY_ORDER)),v&&(m=m.then((e=>!0!==e.getContextRaw()["@propagate"]?new n.JsonLdContextNormalized(Object.assign(Object.assign({},e.getContextRaw()),{"@propagate":!1,"@__propagateFallback":u.getContextRaw()})):e)),e.contextTree.setContext(s.slice(0,s.length-1),m)),e.processingType[c]=!0}}t.EntryHandlerKeywordType=a},6454:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordUnknownFallback=void 0;const n=r(2395);class i{isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,i,o){const s=await t.unaliasKeyword(r[i],r,i);return!(!n.Util.isPotentialKeyword(s)||!o&&"@list"===s)}async test(e,t,r,i,o){return n.Util.isPotentialKeyword(r)}async handle(e,t,r,o,s,a){const c=i.VALID_KEYWORDS_TYPES[r];void 0!==c?c&&typeof s!==c.type&&e.emitError(new n.ErrorCoded(`Invalid value type for '${r}' with value '${s}'`,c.errorCode)):e.strictValues&&e.emitError(new Error(`Unknown keyword '${r}' with value '${s}'`)),e.emittedStack[a]=!1}}i.VALID_KEYWORDS_TYPES={"@index":{type:"string",errorCode:n.ERROR_CODES.INVALID_INDEX_VALUE},"@list":null,"@reverse":{type:"object",errorCode:n.ERROR_CODES.INVALID_REVERSE_VALUE},"@set":null,"@value":null},t.EntryHandlerKeywordUnknownFallback=i},3283:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordValue=void 0;const n=r(1548);class i extends n.EntryHandlerKeyword{constructor(){super("@value")}async validate(e,t,r,n,i){const o=r[n];return o&&!e.literalStack[n]&&await this.test(e,t,o,r,n)&&(e.literalStack[n]=!0),super.validate(e,t,r,n,i)}async test(e,t,r,n,i){return"@value"===await t.unaliasKeyword(n[i],n.slice(0,n.length-1),i-1,!0)}async handle(e,t,r,n,i,o){e.literalStack[o]=!0,delete e.unidentifiedValuesBuffer[o],delete e.unidentifiedGraphsBuffer[o],e.emittedStack[o]=!1}}t.EntryHandlerKeywordValue=i},2194:function(e,t,r){"use strict";const{SymbolDispose:n}=r(2057),{AbortError:i,codes:o}=r(54),{isNodeStream:s,isWebStream:a,kControllerErrorFunction:c}=r(9232),l=r(3789),{ERR_INVALID_ARG_TYPE:u}=o;let d;e.exports.addAbortSignal=function(t,r){if((e=>{if("object"!=typeof e||!("aborted"in e))throw new u("signal","AbortSignal",e)})(t),!s(r)&&!a(r))throw new u("stream",["ReadableStream","WritableStream","Stream"],r);return e.exports.addAbortSignalNoValidate(t,r)},e.exports.addAbortSignalNoValidate=function(e,t){if("object"!=typeof e||!("aborted"in e))return t;const o=s(t)?()=>{t.destroy(new i(void 0,{cause:e.reason}))}:()=>{t[c](new i(void 0,{cause:e.reason}))};if(e.aborted)o();else{d=d||r(6745).addAbortListener;const i=d(e,o);l(t,i[n])}return t}},6442:function(e,t,r){"use strict";const{StringPrototypeSlice:n,SymbolIterator:i,TypedArrayPrototypeSet:o,Uint8Array:s}=r(2057),{Buffer:a}=r(8287),{inspect:c}=r(6745);e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(e){const t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}unshift(e){const t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}shift(){if(0===this.length)return;const e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(0===this.length)return"";let t=this.head,r=""+t.data;for(;null!==(t=t.next);)r+=e+t.data;return r}concat(e){if(0===this.length)return a.alloc(0);const t=a.allocUnsafe(e>>>0);let r=this.head,n=0;for(;r;)o(t,r.data,n),n+=r.data.length,r=r.next;return t}consume(e,t){const r=this.head.data;if(eo.length)){e===o.length?(t+=o,++i,r.next?this.head=r.next:this.head=this.tail=null):(t+=n(o,0,e),this.head=r,r.data=n(o,e));break}t+=o,e-=o.length,++i}while(null!==(r=r.next));return this.length-=i,t}_getBuffer(e){const t=a.allocUnsafe(e),r=e;let n=this.head,i=0;do{const a=n.data;if(!(e>a.length)){e===a.length?(o(t,a,r-e),++i,n.next?this.head=n.next:this.head=this.tail=null):(o(t,new s(a.buffer,a.byteOffset,e),r-e),this.head=n,n.data=a.slice(e));break}o(t,a,r-e),e-=a.length,++i}while(null!==(n=n.next));return this.length-=i,t}[Symbol.for("nodejs.util.inspect.custom")](e,t){return c(this,{...t,depth:0,customInspect:!1})}}},769:function(e,t,r){"use strict";const{pipeline:n}=r(5783),i=r(399),{destroyer:o}=r(2295),{isNodeStream:s,isReadable:a,isWritable:c,isWebStream:l,isTransformStream:u,isWritableStream:d,isReadableStream:h}=r(9232),{AbortError:f,codes:{ERR_INVALID_ARG_VALUE:p,ERR_MISSING_ARGS:g}}=r(54),y=r(3789);e.exports=function(...e){if(0===e.length)throw new g("streams");if(1===e.length)return i.from(e[0]);const t=[...e];if("function"==typeof e[0]&&(e[0]=i.from(e[0])),"function"==typeof e[e.length-1]){const t=e.length-1;e[t]=i.from(e[t])}for(let r=0;r0&&!(c(e[r])||d(e[r])||u(e[r])))throw new p(`streams[${r}]`,t[r],"must be writable")}let r,m,v,b,w;const _=e[0],S=n(e,(function(e){const t=b;b=null,t?t(e):e?w.destroy(e):A||E||w.destroy()})),E=!!(c(_)||d(_)||u(_)),A=!!(a(S)||h(S)||u(S));if(w=new i({writableObjectMode:!(null==_||!_.writableObjectMode),readableObjectMode:!(null==S||!S.readableObjectMode),writable:E,readable:A}),E){if(s(_))w._write=function(e,t,n){_.write(e,t)?n():r=n},w._final=function(e){_.end(),m=e},_.on("drain",(function(){if(r){const e=r;r=null,e()}}));else if(l(_)){const e=(u(_)?_.writable:_).getWriter();w._write=async function(t,r,n){try{await e.ready,e.write(t).catch((()=>{})),n()}catch(e){n(e)}},w._final=async function(t){try{await e.ready,e.close().catch((()=>{})),m=t}catch(e){t(e)}}}const e=u(S)?S.readable:S;y(e,(()=>{if(m){const e=m;m=null,e()}}))}if(A)if(s(S))S.on("readable",(function(){if(v){const e=v;v=null,e()}})),S.on("end",(function(){w.push(null)})),w._read=function(){for(;;){const e=S.read();if(null===e)return void(v=w._read);if(!w.push(e))return}};else if(l(S)){const e=(u(S)?S.readable:S).getReader();w._read=async function(){for(;;)try{const{value:t,done:r}=await e.read();if(!w.push(t))return;if(r)return void w.push(null)}catch{return}}}return w._destroy=function(e,t){e||null===b||(e=new f),v=null,r=null,m=null,null===b?t(e):(b=t,s(S)&&o(S,e))},w}},2295:function(e,t,r){"use strict";const n=r(5606),{aggregateTwoErrors:i,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:s}=r(54),{Symbol:a}=r(2057),{kIsDestroyed:c,isDestroyed:l,isFinished:u,isServerRequest:d}=r(9232),h=a("kDestroy"),f=a("kConstruct");function p(e,t,r){e&&(e.stack,t&&!t.errored&&(t.errored=e),r&&!r.errored&&(r.errored=e))}function g(e,t,r){let i=!1;function o(t){if(i)return;i=!0;const o=e._readableState,s=e._writableState;p(t,s,o),s&&(s.closed=!0),o&&(o.closed=!0),"function"==typeof r&&r(t),t?n.nextTick(y,e,t):n.nextTick(m,e)}try{e._destroy(t||null,o)}catch(t){o(t)}}function y(e,t){v(e,t),m(e)}function m(e){const t=e._readableState,r=e._writableState;r&&(r.closeEmitted=!0),t&&(t.closeEmitted=!0),(null!=r&&r.emitClose||null!=t&&t.emitClose)&&e.emit("close")}function v(e,t){const r=e._readableState,n=e._writableState;null!=n&&n.errorEmitted||null!=r&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),e.emit("error",t))}function b(e,t,r){const i=e._readableState,o=e._writableState;if(null!=o&&o.destroyed||null!=i&&i.destroyed)return this;null!=i&&i.autoDestroy||null!=o&&o.autoDestroy?e.destroy(t):t&&(t.stack,o&&!o.errored&&(o.errored=t),i&&!i.errored&&(i.errored=t),r?n.nextTick(v,e,t):v(e,t))}function w(e){let t=!1;function r(r){if(t)return void b(e,null!=r?r:new o);t=!0;const i=e._readableState,s=e._writableState,a=s||i;i&&(i.constructed=!0),s&&(s.constructed=!0),a.destroyed?e.emit(h,r):r?b(e,r,!0):n.nextTick(_,e)}try{e._construct((e=>{n.nextTick(r,e)}))}catch(e){n.nextTick(r,e)}}function _(e){e.emit(f)}function S(e){return(null==e?void 0:e.setHeader)&&"function"==typeof e.abort}function E(e){e.emit("close")}function A(e,t){e.emit("error",t),n.nextTick(E,e)}e.exports={construct:function(e,t){if("function"!=typeof e._construct)return;const r=e._readableState,i=e._writableState;r&&(r.constructed=!1),i&&(i.constructed=!1),e.once(f,t),e.listenerCount(f)>1||n.nextTick(w,e)},destroyer:function(e,t){e&&!l(e)&&(t||u(e)||(t=new s),d(e)?(e.socket=null,e.destroy(t)):S(e)?e.abort():S(e.req)?e.req.abort():"function"==typeof e.destroy?e.destroy(t):"function"==typeof e.close?e.close():t?n.nextTick(A,e,t):n.nextTick(E,e),e.destroyed||(e[c]=!0))},destroy:function(e,t){const r=this._readableState,n=this._writableState,o=n||r;return null!=n&&n.destroyed||null!=r&&r.destroyed?("function"==typeof t&&t(),this):(p(e,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),o.constructed?g(this,e,t):this.once(h,(function(r){g(this,i(r,e),t)})),this)},undestroy:function(){const e=this._readableState,t=this._writableState;e&&(e.constructed=!0,e.closed=!1,e.closeEmitted=!1,e.destroyed=!1,e.errored=null,e.errorEmitted=!1,e.reading=!1,e.ended=!1===e.readable,e.endEmitted=!1===e.readable),t&&(t.constructed=!0,t.destroyed=!1,t.closed=!1,t.closeEmitted=!1,t.errored=null,t.errorEmitted=!1,t.finalCalled=!1,t.prefinished=!1,t.ended=!1===t.writable,t.ending=!1===t.writable,t.finished=!1===t.writable)},errorOrDestroy:b}},399:function(e,t,r){"use strict";const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:i,ObjectKeys:o,ObjectSetPrototypeOf:s}=r(2057);e.exports=l;const a=r(5277),c=r(4461);s(l.prototype,a.prototype),s(l,a);{const e=o(c.prototype);for(let t=0;t{d=!1,e&&v(t,e),h(e)})),l._write=function(e,t,i){r.write(e,t)?i():n=i},l._final=function(e){r.end(),i=e},r.on("drain",(function(){if(n){const e=n;n=null,e()}})),r.on("finish",(function(){if(i){const e=i;i=null,e()}}))),u&&(p(t,(e=>{u=!1,e&&v(t,e),h(e)})),t.on("readable",(function(){if(a){const e=a;a=null,e()}})),t.on("end",(function(){l.push(null)})),l._read=function(){for(;;){const e=t.read();if(null===e)return void(a=l._read);if(!l.push(e))return}}),l._destroy=function(e,o){e||null===c||(e=new g),a=null,n=null,i=null,null===c?o(e):(c=o,v(r,e),v(t,e))},l}e.exports=function e(t,r){if(d(t))return t;if(l(t))return P({readable:t});if(u(t))return P({writable:t});if(c(t))return P({writable:!1,readable:!1});if(h(t))return P({readable:w.fromWeb(t)});if(f(t))return P({writable:_.fromWeb(t)});if("function"==typeof t){const{value:e,write:i,final:o,destroy:s}=function(e){let{promise:t,resolve:r}=S();const i=new I,o=i.signal;return{value:e(async function*(){for(;;){const e=t;t=null;const{chunk:i,done:s,cb:a}=await e;if(n.nextTick(a),s)return;if(o.aborted)throw new g(void 0,{cause:o.reason});({promise:t,resolve:r}=S()),yield i}}(),{signal:o}),write(e,t,n){const i=r;r=null,i({chunk:e,done:!1,cb:n})},final(e){const t=r;r=null,t({done:!0,cb:e})},destroy(e,t){i.abort(),t(e)}}}(t);if(a(e))return E(x,e,{objectMode:!0,write:i,final:o,destroy:s});const c=null==e?void 0:e.then;if("function"==typeof c){let t;const r=T(c,e,(e=>{if(null!=e)throw new m("nully","body",e)}),(e=>{v(t,e)}));return t=new x({objectMode:!0,readable:!1,write:i,final(e){o((async()=>{try{await r,n.nextTick(e,null)}catch(t){n.nextTick(e,t)}}))},destroy:s})}throw new m("Iterable, AsyncIterable or AsyncFunction",r,e)}if(R(t))return e(t.arrayBuffer());if(a(t))return E(x,t,{objectMode:!0,writable:!1});if(h(null==t?void 0:t.readable)&&f(null==t?void 0:t.writable))return x.fromWeb(t);if("object"==typeof(null==t?void 0:t.writable)||"object"==typeof(null==t?void 0:t.readable))return P({readable:null!=t&&t.readable?l(null==t?void 0:t.readable)?null==t?void 0:t.readable:e(t.readable):void 0,writable:null!=t&&t.writable?u(null==t?void 0:t.writable)?null==t?void 0:t.writable:e(t.writable):void 0});const i=null==t?void 0:t.then;if("function"==typeof i){let e;return T(i,t,(t=>{null!=t&&e.push(t),e.push(null)}),(t=>{v(e,t)})),e=new x({objectMode:!0,writable:!1,read(){}})}throw new y(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],t)}},3789:function(e,t,r){const n=r(5606),{AbortError:i,codes:o}=r(54),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_PREMATURE_CLOSE:a}=o,{kEmptyObject:c,once:l}=r(6745),{validateAbortSignal:u,validateFunction:d,validateObject:h,validateBoolean:f}=r(5432),{Promise:p,PromisePrototypeThen:g,SymbolDispose:y}=r(2057),{isClosed:m,isReadable:v,isReadableNodeStream:b,isReadableStream:w,isReadableFinished:_,isReadableErrored:S,isWritable:E,isWritableNodeStream:A,isWritableStream:R,isWritableFinished:I,isWritableErrored:T,isNodeStream:x,willEmitClose:P,kIsClosedPromise:C}=r(9232);let k;const O=()=>{};function F(e,t,o){var f,p;if(2===arguments.length?(o=t,t=c):null==t?t=c:h(t,"options"),d(o,"callback"),u(t.signal,"options.signal"),o=l(o),w(e)||R(e))return function(e,t,o){let s=!1,a=O;if(t.signal)if(a=()=>{s=!0,o.call(e,new i(void 0,{cause:t.signal.reason}))},t.signal.aborted)n.nextTick(a);else{k=k||r(6745).addAbortListener;const n=k(t.signal,a),i=o;o=l(((...t)=>{n[y](),i.apply(e,t)}))}const c=(...t)=>{s||n.nextTick((()=>o.apply(e,t)))};return g(e[C].promise,c,c),O}(e,t,o);if(!x(e))throw new s("stream",["ReadableStream","WritableStream","Stream"],e);const F=null!==(f=t.readable)&&void 0!==f?f:b(e),N=null!==(p=t.writable)&&void 0!==p?p:A(e),D=e._writableState,L=e._readableState,U=()=>{e.writable||B()};let j=P(e)&&b(e)===F&&A(e)===N,M=I(e,!1);const B=()=>{M=!0,e.destroyed&&(j=!1),(!j||e.readable&&!F)&&(F&&!H||o.call(e))};let H=_(e,!1);const W=()=>{H=!0,e.destroyed&&(j=!1),(!j||e.writable&&!N)&&(N&&!M||o.call(e))},$=t=>{o.call(e,t)};let V=m(e);const K=()=>{V=!0;const t=T(e)||S(e);return t&&"boolean"!=typeof t?o.call(e,t):F&&!H&&b(e,!0)&&!_(e,!1)?o.call(e,new a):!N||M||I(e,!1)?void o.call(e):o.call(e,new a)},J=()=>{V=!0;const t=T(e)||S(e);if(t&&"boolean"!=typeof t)return o.call(e,t);o.call(e)},G=()=>{e.req.on("finish",B)};!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?N&&!D&&(e.on("end",U),e.on("close",U)):(e.on("complete",B),j||e.on("abort",K),e.req?G():e.on("request",G)),j||"boolean"!=typeof e.aborted||e.on("aborted",K),e.on("end",W),e.on("finish",B),!1!==t.error&&e.on("error",$),e.on("close",K),V?n.nextTick(K):null!=D&&D.errorEmitted||null!=L&&L.errorEmitted?j||n.nextTick(J):(F||j&&!v(e)||!M&&!1!==E(e))&&(N||j&&!E(e)||!H&&!1!==v(e))?L&&e.req&&e.aborted&&n.nextTick(J):n.nextTick(J);const q=()=>{o=O,e.removeListener("aborted",K),e.removeListener("complete",B),e.removeListener("abort",K),e.removeListener("request",G),e.req&&e.req.removeListener("finish",B),e.removeListener("end",U),e.removeListener("close",U),e.removeListener("finish",B),e.removeListener("end",W),e.removeListener("error",$),e.removeListener("close",K)};if(t.signal&&!V){const s=()=>{const r=o;q(),r.call(e,new i(void 0,{cause:t.signal.reason}))};if(t.signal.aborted)n.nextTick(s);else{k=k||r(6745).addAbortListener;const n=k(t.signal,s),i=o;o=l(((...t)=>{n[y](),i.apply(e,t)}))}}return q}e.exports=F,e.exports.finished=function(e,t){var r;let n=!1;return null===t&&(t=c),null!==(r=t)&&void 0!==r&&r.cleanup&&(f(t.cleanup,"cleanup"),n=t.cleanup),new p(((r,i)=>{const o=F(e,t,(e=>{n&&o(),e?i(e):r()}))}))}},4181:function(e,t,r){"use strict";const n=r(5606),{PromisePrototypeThen:i,SymbolAsyncIterator:o,SymbolIterator:s}=r(2057),{Buffer:a}=r(8287),{ERR_INVALID_ARG_TYPE:c,ERR_STREAM_NULL_VALUES:l}=r(54).codes;e.exports=function(e,t,r){let u,d;if("string"==typeof t||t instanceof a)return new e({objectMode:!0,...r,read(){this.push(t),this.push(null)}});if(t&&t[o])d=!0,u=t[o]();else{if(!t||!t[s])throw new c("iterable",["Iterable"],t);d=!1,u=t[s]()}const h=new e({objectMode:!0,highWaterMark:1,...r});let f=!1;return h._read=function(){f||(f=!0,async function(){for(;;){try{const{value:e,done:t}=d?await u.next():u.next();if(t)h.push(null);else{const t=e&&"function"==typeof e.then?await e:e;if(null===t)throw f=!1,new l;if(h.push(t))continue;f=!1}}catch(e){h.destroy(e)}break}}())},h._destroy=function(e,t){i(async function(e){const t=null!=e,r="function"==typeof u.throw;if(t&&r){const{value:t,done:r}=await u.throw(e);if(await t,r)return}if("function"==typeof u.return){const{value:e}=await u.return();await e}}(e),(()=>n.nextTick(t,e)),(r=>n.nextTick(t,r||e)))},h}},9526:function(e,t,r){"use strict";const{ArrayIsArray:n,ObjectSetPrototypeOf:i}=r(2057),{EventEmitter:o}=r(7007);function s(e){o.call(this,e)}function a(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?n(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}i(s.prototype,o.prototype),i(s,o),s.prototype.pipe=function(e,t){const r=this;function n(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function i(){r.readable&&r.resume&&r.resume()}r.on("data",n),e.on("drain",i),e._isStdio||t&&!1===t.end||(r.on("end",c),r.on("close",l));let s=!1;function c(){s||(s=!0,e.end())}function l(){s||(s=!0,"function"==typeof e.destroy&&e.destroy())}function u(e){d(),0===o.listenerCount(this,"error")&&this.emit("error",e)}function d(){r.removeListener("data",n),e.removeListener("drain",i),r.removeListener("end",c),r.removeListener("close",l),r.removeListener("error",u),e.removeListener("error",u),r.removeListener("end",d),r.removeListener("close",d),e.removeListener("close",d)}return a(r,"error",u),a(e,"error",u),r.on("end",d),r.on("close",d),e.on("close",d),e.emit("pipe",r),e},e.exports={Stream:s,prependListener:a}},2892:function(e,t,r){"use strict";const n=globalThis.AbortController||r(5568).AbortController,{codes:{ERR_INVALID_ARG_VALUE:i,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:s,ERR_OUT_OF_RANGE:a},AbortError:c}=r(54),{validateAbortSignal:l,validateInteger:u,validateObject:d}=r(5432),h=r(2057).Symbol("kWeak"),f=r(2057).Symbol("kResistStopPropagation"),{finished:p}=r(3789),g=r(769),{addAbortSignalNoValidate:y}=r(2194),{isWritable:m,isNodeStream:v}=r(9232),{deprecate:b}=r(6745),{ArrayPrototypePush:w,Boolean:_,MathFloor:S,Number:E,NumberIsNaN:A,Promise:R,PromiseReject:I,PromiseResolve:T,PromisePrototypeThen:x,Symbol:P}=r(2057),C=P("kEmpty"),k=P("kEof");function O(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal");let n=1;null!=(null==t?void 0:t.concurrency)&&(n=S(t.concurrency));let i=n-1;return null!=(null==t?void 0:t.highWaterMark)&&(i=S(t.highWaterMark)),u(n,"options.concurrency",1),u(i,"options.highWaterMark",0),i+=n,async function*(){const o=r(6745).AbortSignalAny([null==t?void 0:t.signal].filter(_)),s=this,a=[],l={signal:o};let u,d,h=!1,f=0;function p(){h=!0,g()}function g(){f-=1,y()}function y(){d&&!h&&f=i||f>=n)&&await new R((e=>{d=e}))}a.push(k)}catch(e){const t=I(e);x(t,g,p),a.push(t)}finally{h=!0,u&&(u(),u=null)}}();try{for(;;){for(;a.length>0;){const e=await a[0];if(e===k)return;if(o.aborted)throw new c;e!==C&&(yield e),a.shift(),y()}await new R((e=>{u=e}))}}finally{h=!0,d&&(d(),d=null)}}.call(this)}async function F(e,t=void 0){for await(const r of N.call(this,e,t))return!0;return!1}function N(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return O.call(this,(async function(t,r){return await e(t,r)?t:C}),t)}class D extends s{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}function L(e){if(e=E(e),A(e))return 0;if(e<0)throw new a("number",">= 0",e);return e}e.exports.streamReturningOperators={asIndexedPairs:b((function(e=void 0){return null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(e.signal,"options.signal"),async function*(){let t=0;for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new c({cause:e.signal.reason});yield[t++,n]}}.call(this)}),"readable.asIndexedPairs will be removed in a future version."),drop:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=L(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;e--<=0&&(yield r)}}.call(this)},filter:N,flatMap:function(e,t){const r=O.call(this,e,t);return async function*(){for await(const e of r)yield*e}.call(this)},map:O,take:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=L(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;if(e-- >0&&(yield r),e<=0)return}}.call(this)},compose:function(e,t){if(null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),v(e)&&!m(e))throw new i("stream",e,"must be writable");const r=g(this,e);return null!=t&&t.signal&&y(t.signal,r),r}},e.exports.promiseReturningOperators={every:async function(e,t=void 0){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return!await F.call(this,(async(...t)=>!await e(...t)),t)},forEach:async function(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);for await(const r of O.call(this,(async function(t,r){return await e(t,r),C}),t));},reduce:async function(e,t,r){var i;if("function"!=typeof e)throw new o("reducer",["Function","AsyncFunction"],e);null!=r&&d(r,"options"),null!=(null==r?void 0:r.signal)&&l(r.signal,"options.signal");let s=arguments.length>1;if(null!=r&&null!==(i=r.signal)&&void 0!==i&&i.aborted){const e=new c(void 0,{cause:r.signal.reason});throw this.once("error",(()=>{})),await p(this.destroy(e)),e}const a=new n,u=a.signal;if(null!=r&&r.signal){const e={once:!0,[h]:this,[f]:!0};r.signal.addEventListener("abort",(()=>a.abort()),e)}let g=!1;try{for await(const n of this){var y;if(g=!0,null!=r&&null!==(y=r.signal)&&void 0!==y&&y.aborted)throw new c;s?t=await e(t,n,{signal:u}):(t=n,s=!0)}if(!g&&!s)throw new D}finally{a.abort()}return t},toArray:async function(e){null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(e.signal,"options.signal");const t=[];for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new c(void 0,{cause:e.signal.reason});w(t,n)}return t},some:F,find:async function(e,t){for await(const r of N.call(this,e,t))return r}}},2163:function(e,t,r){"use strict";const{ObjectSetPrototypeOf:n}=r(2057);e.exports=o;const i=r(97);function o(e){if(!(this instanceof o))return new o(e);i.call(this,e)}n(o.prototype,i.prototype),n(o,i),o.prototype._transform=function(e,t,r){r(null,e)}},5783:function(e,t,r){const n=r(5606),{ArrayIsArray:i,Promise:o,SymbolAsyncIterator:s,SymbolDispose:a}=r(2057),c=r(3789),{once:l}=r(6745),u=r(2295),d=r(399),{aggregateTwoErrors:h,codes:{ERR_INVALID_ARG_TYPE:f,ERR_INVALID_RETURN_VALUE:p,ERR_MISSING_ARGS:g,ERR_STREAM_DESTROYED:y,ERR_STREAM_PREMATURE_CLOSE:m},AbortError:v}=r(54),{validateFunction:b,validateAbortSignal:w}=r(5432),{isIterable:_,isReadable:S,isReadableNodeStream:E,isNodeStream:A,isTransformStream:R,isWebStream:I,isReadableStream:T,isReadableFinished:x}=r(9232),P=globalThis.AbortController||r(5568).AbortController;let C,k,O;function F(e,t,r){let n=!1;return e.on("close",(()=>{n=!0})),{destroy:t=>{n||(n=!0,u.destroyer(e,t||new y("pipe")))},cleanup:c(e,{readable:t,writable:r},(e=>{n=!e}))}}function N(e){if(_(e))return e;if(E(e))return async function*(e){k||(k=r(5277)),yield*k.prototype[s].call(e)}(e);throw new f("val",["Readable","Iterable","AsyncIterable"],e)}async function D(e,t,r,{end:n}){let i,s=null;const a=e=>{if(e&&(i=e),s){const e=s;s=null,e()}},l=()=>new o(((e,t)=>{i?t(i):s=()=>{i?t(i):e()}}));t.on("drain",a);const u=c(t,{readable:!1},a);try{t.writableNeedDrain&&await l();for await(const r of e)t.write(r)||await l();n&&(t.end(),await l()),r()}catch(e){r(i!==e?h(i,e):e)}finally{u(),t.off("drain",a)}}async function L(e,t,r,{end:n}){R(t)&&(t=t.writable);const i=t.getWriter();try{for await(const t of e)await i.ready,i.write(t).catch((()=>{}));await i.ready,n&&await i.close(),r()}catch(e){try{await i.abort(e),r(e)}catch(e){r(e)}}}function U(e,t,o){if(1===e.length&&i(e[0])&&(e=e[0]),e.length<2)throw new g("streams");const s=new P,c=s.signal,l=null==o?void 0:o.signal,u=[];function h(){B(new v)}let y,m,b;w(l,"options.signal"),O=O||r(6745).addAbortListener,l&&(y=O(l,h));const x=[];let k,U=0;function M(e){B(e,0==--U)}function B(e,r){var i;if(!e||m&&"ERR_STREAM_PREMATURE_CLOSE"!==m.code||(m=e),m||r){for(;x.length;)x.shift()(m);null===(i=y)||void 0===i||i[a](),s.abort(),r&&(m||u.forEach((e=>e())),n.nextTick(t,m,b))}}for(let V=0;V0,q=J||!1!==(null==o?void 0:o.end),z=V===e.length-1;if(A(K)){if(q){const{destroy:Y,cleanup:Q}=F(K,J,G);x.push(Y),S(K)&&z&&u.push(Q)}function H(e){e&&"AbortError"!==e.name&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code&&M(e)}K.on("error",H),S(K)&&z&&u.push((()=>{K.removeListener("error",H)}))}if(0===V)if("function"==typeof K){if(k=K({signal:c}),!_(k))throw new p("Iterable, AsyncIterable or Stream","source",k)}else k=_(K)||E(K)||R(K)?K:d.from(K);else if("function"==typeof K){var W;if(k=R(k)?N(null===(W=k)||void 0===W?void 0:W.readable):N(k),k=K(k,{signal:c}),J){if(!_(k,!0))throw new p("AsyncIterable",`transform[${V-1}]`,k)}else{var $;C||(C=r(2163));const X=new C({objectMode:!0}),Z=null===($=k)||void 0===$?void 0:$.then;if("function"==typeof Z)U++,Z.call(k,(e=>{b=e,null!=e&&X.write(e),q&&X.end(),n.nextTick(M)}),(e=>{X.destroy(e),n.nextTick(M,e)}));else if(_(k,!0))U++,D(k,X,M,{end:q});else{if(!T(k)&&!R(k))throw new p("AsyncIterable or Promise","destination",k);{const re=k.readable||k;U++,D(re,X,M,{end:q})}}k=X;const{destroy:ee,cleanup:te}=F(k,!1,!0);x.push(ee),z&&u.push(te)}}else if(A(K)){if(E(k)){U+=2;const ne=j(k,K,M,{end:q});S(K)&&z&&u.push(ne)}else if(R(k)||T(k)){const ie=k.readable||k;U++,D(ie,K,M,{end:q})}else{if(!_(k))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],k);U++,D(k,K,M,{end:q})}k=K}else if(I(K)){if(E(k))U++,L(N(k),K,M,{end:q});else if(T(k)||_(k))U++,L(k,K,M,{end:q});else{if(!R(k))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],k);U++,L(k.readable,K,M,{end:q})}k=K}else k=d.from(K)}return(null!=c&&c.aborted||null!=l&&l.aborted)&&n.nextTick(h),k}function j(e,t,r,{end:i}){let o=!1;if(t.on("close",(()=>{o||r(new m)})),e.pipe(t,{end:!1}),i){function s(){o=!0,t.end()}x(e)?n.nextTick(s):e.once("end",s)}else r();return c(e,{readable:!0,writable:!1},(t=>{const n=e._readableState;t&&"ERR_STREAM_PREMATURE_CLOSE"===t.code&&n&&n.ended&&!n.errored&&!n.errorEmitted?e.once("end",r).once("error",r):r(t)})),c(t,{readable:!1,writable:!0},r)}e.exports={pipelineImpl:U,pipeline:function(...e){return U(e,l(function(e){return b(e[e.length-1],"streams[stream.length - 1]"),e.pop()}(e)))}}},5277:function(e,t,r){const n=r(5606),{ArrayPrototypeIndexOf:i,NumberIsInteger:o,NumberIsNaN:s,NumberParseInt:a,ObjectDefineProperties:c,ObjectKeys:l,ObjectSetPrototypeOf:u,Promise:d,SafeSet:h,SymbolAsyncDispose:f,SymbolAsyncIterator:p,Symbol:g}=r(2057);e.exports=G,G.ReadableState=J;const{EventEmitter:y}=r(7007),{Stream:m,prependListener:v}=r(9526),{Buffer:b}=r(8287),{addAbortSignal:w}=r(2194),_=r(3789);let S=r(6745).debuglog("stream",(e=>{S=e}));const E=r(6442),A=r(2295),{getHighWaterMark:R,getDefaultHighWaterMark:I}=r(936),{aggregateTwoErrors:T,codes:{ERR_INVALID_ARG_TYPE:x,ERR_METHOD_NOT_IMPLEMENTED:P,ERR_OUT_OF_RANGE:C,ERR_STREAM_PUSH_AFTER_EOF:k,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:O},AbortError:F}=r(54),{validateObject:N}=r(5432),D=g("kPaused"),{StringDecoder:L}=r(704),U=r(4181);u(G.prototype,m.prototype),u(G,m);const j=()=>{},{errorOrDestroy:M}=A,B=1,H=16,W=32,$=2048,V=4096;function K(e){return{enumerable:!1,get(){return!!(this.state&e)},set(t){t?this.state|=e:this.state&=~e}}}function J(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(399)),this.state=$|V|H|W,e&&e.objectMode&&(this.state|=B),n&&e&&e.readableObjectMode&&(this.state|=B),this.highWaterMark=e?R(this,e,"readableHighWaterMark",n):I(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[D]=null,e&&!1===e.emitClose&&(this.state&=~$),e&&!1===e.autoDestroy&&(this.state&=~V),this.errored=null,this.defaultEncoding=e&&e.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,e&&e.encoding&&(this.decoder=new L(e.encoding),this.encoding=e.encoding)}function G(e){if(!(this instanceof G))return new G(e);const t=this instanceof r(399);this._readableState=new J(e,this,t),e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.construct&&(this._construct=e.construct),e.signal&&!t&&w(e.signal,this)),m.call(this,e),A.construct(this,(()=>{this._readableState.needReadable&&Z(this,this._readableState)}))}function q(e,t,r,n){S("readableAddChunk",t);const i=e._readableState;let o;if(i.state&B||("string"==typeof t?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?t=b.from(t,r).toString(i.encoding):(t=b.from(t,r),r=""))):t instanceof b?r="":m._isUint8Array(t)?(t=m._uint8ArrayToBuffer(t),r=""):null!=t&&(o=new x("chunk",["string","Buffer","Uint8Array"],t))),o)M(e,o);else if(null===t)i.state&=-9,function(e,t){if(S("onEofChunk"),!t.ended){if(t.decoder){const e=t.decoder.end();e&&e.length&&(t.buffer.push(e),t.length+=t.objectMode?1:e.length)}t.ended=!0,t.sync?Q(e):(t.needReadable=!1,t.emittedReadable=!0,X(e))}}(e,i);else if(i.state&B||t&&t.length>0)if(n)if(4&i.state)M(e,new O);else{if(i.destroyed||i.errored)return!1;z(e,i,t,!0)}else if(i.ended)M(e,new k);else{if(i.destroyed||i.errored)return!1;i.state&=-9,i.decoder&&!r?(t=i.decoder.write(t),i.objectMode||0!==t.length?z(e,i,t,!1):Z(e,i)):z(e,i,t,!1)}else n||(i.state&=-9,Z(e,i));return!i.ended&&(i.length0?(65536&t.state?t.awaitDrainWriters.clear():t.awaitDrainWriters=null,t.dataEmitted=!0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),64&t.state&&Q(e)),Z(e,t)}function Y(e,t){return e<=0||0===t.length&&t.ended?0:t.state&B?1:s(e)?t.flowing&&t.length?t.buffer.first().length:t.length:e<=t.length?e:t.ended?t.length:0}function Q(e){const t=e._readableState;S("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(S("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(X,e))}function X(e){const t=e._readableState;S("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||t.errored||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,ie(e)}function Z(e,t){!t.readingMore&&t.constructed&&(t.readingMore=!0,n.nextTick(ee,e,t))}function ee(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!1===t[D]?t.flowing=!0:e.listenerCount("data")>0?e.resume():t.readableListening||(t.flowing=null)}function re(e){S("readable nexttick read 0"),e.read(0)}function ne(e,t){S("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),ie(e),t.flowing&&!t.reading&&e.read(0)}function ie(e){const t=e._readableState;for(S("flow",t.flowing);t.flowing&&null!==e.read(););}function oe(e,t){"function"!=typeof e.read&&(e=G.wrap(e,{objectMode:!0}));const r=async function*(e,t){let r,n=j;function i(t){this===e?(n(),n=j):n=t}e.on("readable",i);const o=_(e,{writable:!1},(e=>{r=e?T(r,e):null,n(),n=j}));try{for(;;){const t=e.destroyed?null:e.read();if(null!==t)yield t;else{if(r)throw r;if(null===r)return;await new d(i)}}}catch(e){throw r=T(r,e),r}finally{!r&&!1===(null==t?void 0:t.destroyOnReturn)||void 0!==r&&!e._readableState.autoDestroy?(e.off("readable",i),o()):A.destroyer(e,null)}}(e,t);return r.stream=e,r}function se(e,t){if(0===t.length)return null;let r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}function ae(e){const t=e._readableState;S("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(ce,t,e))}function ce(e,t){if(S("endReadableNT",e.endEmitted,e.length),!e.errored&&!e.closeEmitted&&!e.endEmitted&&0===e.length)if(e.endEmitted=!0,t.emit("end"),t.writable&&!1===t.allowHalfOpen)n.nextTick(le,t);else if(e.autoDestroy){const e=t._writableState;(!e||e.autoDestroy&&(e.finished||!1===e.writable))&&t.destroy()}}function le(e){e.writable&&!e.writableEnded&&!e.destroyed&&e.end()}let ue;function de(){return void 0===ue&&(ue={}),ue}c(J.prototype,{objectMode:K(B),ended:K(2),endEmitted:K(4),reading:K(8),constructed:K(H),sync:K(W),needReadable:K(64),emittedReadable:K(128),readableListening:K(256),resumeScheduled:K(512),errorEmitted:K(1024),emitClose:K($),autoDestroy:K(V),destroyed:K(8192),closed:K(16384),closeEmitted:K(32768),multiAwaitDrain:K(65536),readingMore:K(1<<17),dataEmitted:K(1<<18)}),G.prototype.destroy=A.destroy,G.prototype._undestroy=A.undestroy,G.prototype._destroy=function(e,t){t(e)},G.prototype[y.captureRejectionSymbol]=function(e){this.destroy(e)},G.prototype[f]=function(){let e;return this.destroyed||(e=this.readableEnded?null:new F,this.destroy(e)),new d(((t,r)=>_(this,(n=>n&&n!==e?r(n):t(null)))))},G.prototype.push=function(e,t){return q(this,e,t,!1)},G.prototype.unshift=function(e,t){return q(this,e,t,!0)},G.prototype.isPaused=function(){const e=this._readableState;return!0===e[D]||!1===e.flowing},G.prototype.setEncoding=function(e){const t=new L(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;const r=this._readableState.buffer;let n="";for(const e of r)n+=t.write(e);return r.clear(),""!==n&&r.push(n),this._readableState.length=n.length,this},G.prototype.read=function(e){S("read",e),void 0===e?e=NaN:o(e)||(e=a(e,10));const t=this._readableState,r=e;if(e>t.highWaterMark&&(t.highWaterMark=function(e){if(e>1073741824)throw new C("size","<= 1GiB",e);return e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,++e}(e)),0!==e&&(t.state&=-129),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return S("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?ae(this):Q(this),null;if(0===(e=Y(e,t))&&t.ended)return 0===t.length&&ae(this),null;let n,i=!!(64&t.state);if(S("need readable",i),(0===t.length||t.length-e0?se(e,t):null,null===n?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.multiAwaitDrain?t.awaitDrainWriters.clear():t.awaitDrainWriters=null),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&ae(this)),null===n||t.errorEmitted||t.closeEmitted||(t.dataEmitted=!0,this.emit("data",n)),n},G.prototype._read=function(e){throw new P("_read()")},G.prototype.pipe=function(e,t){const r=this,i=this._readableState;1===i.pipes.length&&(i.multiAwaitDrain||(i.multiAwaitDrain=!0,i.awaitDrainWriters=new h(i.awaitDrainWriters?[i.awaitDrainWriters]:[]))),i.pipes.push(e),S("pipe count=%d opts=%j",i.pipes.length,t);const o=t&&!1===t.end||e===n.stdout||e===n.stderr?g:s;function s(){S("onend"),e.end()}let a;i.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",(function t(n,o){S("onunpipe"),n===r&&o&&!1===o.hasUnpiped&&(o.hasUnpiped=!0,S("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),a&&e.removeListener("drain",a),e.removeListener("error",d),e.removeListener("unpipe",t),r.removeListener("end",s),r.removeListener("end",g),r.removeListener("data",u),c=!0,a&&i.awaitDrainWriters&&(!e._writableState||e._writableState.needDrain)&&a())}));let c=!1;function l(){c||(1===i.pipes.length&&i.pipes[0]===e?(S("false write response, pause",0),i.awaitDrainWriters=e,i.multiAwaitDrain=!1):i.pipes.length>1&&i.pipes.includes(e)&&(S("false write response, pause",i.awaitDrainWriters.size),i.awaitDrainWriters.add(e)),r.pause()),a||(a=function(e,t){return function(){const r=e._readableState;r.awaitDrainWriters===t?(S("pipeOnDrain",1),r.awaitDrainWriters=null):r.multiAwaitDrain&&(S("pipeOnDrain",r.awaitDrainWriters.size),r.awaitDrainWriters.delete(t)),r.awaitDrainWriters&&0!==r.awaitDrainWriters.size||!e.listenerCount("data")||e.resume()}}(r,e),e.on("drain",a))}function u(t){S("ondata");const r=e.write(t);S("dest.write",r),!1===r&&l()}function d(t){if(S("onerror",t),g(),e.removeListener("error",d),0===e.listenerCount("error")){const r=e._writableState||e._readableState;r&&!r.errorEmitted?M(e,t):e.emit("error",t)}}function f(){e.removeListener("finish",p),g()}function p(){S("onfinish"),e.removeListener("close",f),g()}function g(){S("unpipe"),r.unpipe(e)}return r.on("data",u),v(e,"error",d),e.once("close",f),e.once("finish",p),e.emit("pipe",r),!0===e.writableNeedDrain?l():i.flowing||(S("pipe resume"),r.resume()),e},G.prototype.unpipe=function(e){const t=this._readableState;if(0===t.pipes.length)return this;if(!e){const e=t.pipes;t.pipes=[],this.pause();for(let t=0;t0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,S("on readable",i.length,i.reading),i.length?Q(this):i.reading||n.nextTick(re,this))),r},G.prototype.addListener=G.prototype.on,G.prototype.removeListener=function(e,t){const r=m.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(te,this),r},G.prototype.off=G.prototype.removeListener,G.prototype.removeAllListeners=function(e){const t=m.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(te,this),t},G.prototype.resume=function(){const e=this._readableState;return e.flowing||(S("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(ne,e,t))}(this,e)),e[D]=!1,this},G.prototype.pause=function(){return S("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(S("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[D]=!0,this},G.prototype.wrap=function(e){let t=!1;e.on("data",(r=>{!this.push(r)&&e.pause&&(t=!0,e.pause())})),e.on("end",(()=>{this.push(null)})),e.on("error",(e=>{M(this,e)})),e.on("close",(()=>{this.destroy()})),e.on("destroy",(()=>{this.destroy()})),this._read=()=>{t&&e.resume&&(t=!1,e.resume())};const r=l(e);for(let t=1;t{t?e?e(t):this.destroy(t):(null!=r&&this.push(r),this.push(null),e&&e())}))}function d(){this._final!==u&&u.call(this)}l.prototype._final=u,l.prototype._transform=function(e,t,r){throw new o("_transform()")},l.prototype._write=function(e,t,r){const n=this._readableState,i=this._writableState,o=n.length;this._transform(e,t,((e,t)=>{e?r(e):(null!=t&&this.push(t),i.ended||o===n.length||n.length{const e=this._writableState;e.writing||W(this,e),V(this,e)}))}function D(e,t,r,i){const o=e._writableState;if("function"==typeof r)i=r,r=o.defaultEncoding;else{if(r){if("buffer"!==r&&!g.isEncoding(r))throw new x(r)}else r=o.defaultEncoding;"function"!=typeof i&&(i=C)}if(null===t)throw new I;if(!o.objectMode)if("string"==typeof t)!1!==o.decodeStrings&&(t=g.from(t,r),r="buffer");else if(t instanceof g)r="buffer";else{if(!p._isUint8Array(t))throw new w("chunk",["string","Buffer","Uint8Array"],t);t=p._uint8ArrayToBuffer(t),r="buffer"}let s;return o.ending?s=new T:o.destroyed&&(s=new A("write")),s?(n.nextTick(i,s),P(e,s,!0),s):(o.pendingcb++,function(e,t,r,n,i){const o=t.objectMode?1:r.length;t.length+=o;const s=t.lengthr.bufferedIndex&&W(e,r),i?null!==r.afterWriteTickInfo&&r.afterWriteTickInfo.cb===o?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:o,stream:e,state:r},n.nextTick(M,r.afterWriteTickInfo)):B(e,r,1,o))):P(e,new S)}function M({stream:e,state:t,count:r,cb:n}){return t.afterWriteTickInfo=null,B(e,t,r,n)}function B(e,t,r,n){for(!t.ending&&!e.destroyed&&0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"));r-- >0;)t.pendingcb--,n();t.destroyed&&H(t),V(e,t)}function H(e){if(e.writing)return;for(let r=e.bufferedIndex;r1&&e._writev){t.pendingcb-=s-1;const n=t.allNoop?C:e=>{for(let t=a;t256?(r.splice(0,a),t.bufferedIndex=0):t.bufferedIndex=a}t.bufferProcessing=!1}function $(e){return e.ending&&!e.destroyed&&e.constructed&&0===e.length&&!e.errored&&0===e.buffered.length&&!e.finished&&!e.writing&&!e.errorEmitted&&!e.closeEmitted}function V(e,t,r){$(t)&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.finalCalled=!0,function(e,t){let r=!1;function i(i){if(r)P(e,null!=i?i:S());else if(r=!0,t.pendingcb--,i){const r=t[k].splice(0);for(let e=0;e{$(t)?K(e,t):t.pendingcb--}),e,t)):$(t)&&(t.pendingcb++,K(e,t))))}function K(e,t){t.pendingcb--,t.finished=!0;const r=t[k].splice(0);for(let e=0;e{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);if(en)throw new _(t,`>= ${r} && <= ${n}`,e)})),P=m(((e,t,r=-2147483648,n=2147483647)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);if(en)throw new _(t,`>= ${r} && <= ${n}`,e)})),C=m(((e,t,r=!1)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);const n=r?1:0,i=4294967295;if(ei)throw new _(t,`>= ${n} && <= ${i}`,e)}));function k(e,t){if("string"!=typeof e)throw new b(t,"string",e)}const O=m(((e,t,r)=>{if(!i(r,e)){const n=o(s(r,(e=>"string"==typeof e?`'${e}'`:p(e))),", ");throw new w(t,e,"must be one of: "+n)}}));function F(e,t){if("boolean"!=typeof e)throw new b(t,"boolean",e)}function N(e,t,r){return null!=e&&h(e,t)?e[t]:r}const D=m(((e,t,r=null)=>{const i=N(r,"allowArray",!1),o=N(r,"allowFunction",!1);if(!N(r,"nullable",!1)&&null===e||!i&&n(e)||"object"!=typeof e&&(!o||"function"!=typeof e))throw new b(t,"Object",e)})),L=m(((e,t)=>{if(null!=e&&"object"!=typeof e&&"function"!=typeof e)throw new b(t,"a dictionary",e)})),U=m(((e,t,r=0)=>{if(!n(e))throw new b(t,"Array",e);if(e.length{if(!R(e))throw new b(t,["Buffer","TypedArray","DataView"],e)})),M=m(((e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new b(t,"AbortSignal",e)})),B=m(((e,t)=>{if("function"!=typeof e)throw new b(t,"Function",e)})),H=m(((e,t)=>{if("function"!=typeof e||A(e))throw new b(t,"Function",e)})),W=m(((e,t)=>{if(void 0!==e)throw new b(t,"undefined",e)})),$=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function V(e,t){if(void 0===e||!f($,e))throw new w(t,e,'must be an array or string of format "; rel=preload; as=style"')}e.exports={isInt32:function(e){return e===(0|e)},isUint32:function(e){return e===e>>>0},parseFileMode:function(e,t,r){if(void 0===e&&(e=r),"string"==typeof e){if(null===f(T,e))throw new w(t,e,"must be a 32-bit unsigned integer or an octal string");e=d(e,8)}return C(e,t),e},validateArray:U,validateStringArray:function(e,t){U(e,t);for(let r=0;rn||(null!=r||null!=n)&&c(e))throw new _(t,`${null!=r?`>= ${r}`:""}${null!=r&&null!=n?" && ":""}${null!=n?`<= ${n}`:""}`,e)},validateObject:D,validateOneOf:O,validatePlainFunction:H,validatePort:function(e,t="Port",r=!0){if("number"!=typeof e&&"string"!=typeof e||"string"==typeof e&&0===y(e).length||+e!=+e>>>0||e>65535||0===e&&!r)throw new v(t,e,r);return 0|e},validateSignalName:function(e,t="signal"){if(k(e,t),void 0===I[e]){if(void 0!==I[g(e)])throw new S(e+" (signals must use all capital letters)");throw new S(e)}},validateString:k,validateUint32:C,validateUndefined:W,validateUnion:function(e,t,r){if(!i(r,e))throw new b(t,`('${o(r,"|")}')`,e)},validateAbortSignal:M,validateLinkHeaderValue:function(e){if("string"==typeof e)return V(e,"hints"),e;if(n(e)){const t=e.length;let r="";if(0===t)return r;for(let n=0;n; rel=preload; as=style"')}}},2225:function(e,t,r){"use strict";const n=r(6897),i=r(7698),o=n.Readable.destroy;e.exports=n.Readable,e.exports._uint8ArrayToBuffer=n._uint8ArrayToBuffer,e.exports._isUint8Array=n._isUint8Array,e.exports.isDisturbed=n.isDisturbed,e.exports.isErrored=n.isErrored,e.exports.isReadable=n.isReadable,e.exports.Readable=n.Readable,e.exports.Writable=n.Writable,e.exports.Duplex=n.Duplex,e.exports.Transform=n.Transform,e.exports.PassThrough=n.PassThrough,e.exports.addAbortSignal=n.addAbortSignal,e.exports.finished=n.finished,e.exports.destroy=n.destroy,e.exports.destroy=o,e.exports.pipeline=n.pipeline,e.exports.compose=n.compose,Object.defineProperty(n,"promises",{configurable:!0,enumerable:!0,get(){return i}}),e.exports.Stream=n.Stream,e.exports.default=e.exports},54:function(e,t,r){"use strict";const{format:n,inspect:i,AggregateError:o}=r(6745),s=globalThis.AggregateError||o,a=Symbol("kIsNodeError"),c=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,u={};function d(e,t){if(!e)throw new u.ERR_INTERNAL_ASSERTION(t)}function h(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function f(e,t,r){r||(r=Error);class i extends r{constructor(...r){super(function(e,t,r){if("function"==typeof t)return d(t.length<=r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`),t(...r);const i=(t.match(/%[dfijoOs]/g)||[]).length;return d(i===r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${i}).`),0===r.length?t:n(t,...r)}(e,t,r))}toString(){return`${this.name} [${e}]: ${this.message}`}}Object.defineProperties(i.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${e}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),i.prototype.code=e,i.prototype[a]=!0,u[e]=i}function p(e){const t="__node_internal_"+e.name;return Object.defineProperty(e,"name",{value:t}),e}class g extends Error{constructor(e="The operation was aborted",t=void 0){if(void 0!==t&&"object"!=typeof t)throw new u.ERR_INVALID_ARG_TYPE("options","Object",t);super(e,t),this.code="ABORT_ERR",this.name="AbortError"}}f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",((e,t,r)=>{d("string"==typeof e,"'name' must be a string"),Array.isArray(t)||(t=[t]);let n="The ";e.endsWith(" argument")?n+=`${e} `:n+=`"${e}" ${e.includes(".")?"property":"argument"} `,n+="must be ";const o=[],s=[],a=[];for(const e of t)d("string"==typeof e,"All expected entries have to be of type string"),c.includes(e)?o.push(e.toLowerCase()):l.test(e)?s.push(e):(d("object"!==e,'The value "object" should be written as "Object"'),a.push(e));if(s.length>0){const e=o.indexOf("object");-1!==e&&(o.splice(o,e,1),s.push("Object"))}if(o.length>0){switch(o.length){case 1:n+=`of type ${o[0]}`;break;case 2:n+=`one of type ${o[0]} or ${o[1]}`;break;default:{const e=o.pop();n+=`one of type ${o.join(", ")}, or ${e}`}}(s.length>0||a.length>0)&&(n+=" or ")}if(s.length>0){switch(s.length){case 1:n+=`an instance of ${s[0]}`;break;case 2:n+=`an instance of ${s[0]} or ${s[1]}`;break;default:{const e=s.pop();n+=`an instance of ${s.join(", ")}, or ${e}`}}a.length>0&&(n+=" or ")}switch(a.length){case 0:break;case 1:a[0].toLowerCase()!==a[0]&&(n+="an "),n+=`${a[0]}`;break;case 2:n+=`one of ${a[0]} or ${a[1]}`;break;default:{const e=a.pop();n+=`one of ${a.join(", ")}, or ${e}`}}if(null==r)n+=`. Received ${r}`;else if("function"==typeof r&&r.name)n+=`. Received function ${r.name}`;else if("object"==typeof r){var u;null!==(u=r.constructor)&&void 0!==u&&u.name?n+=`. Received an instance of ${r.constructor.name}`:n+=`. Received ${i(r,{depth:-1})}`}else{let e=i(r,{colors:!1});e.length>25&&(e=`${e.slice(0,25)}...`),n+=`. Received type ${typeof r} (${e})`}return n}),TypeError),f("ERR_INVALID_ARG_VALUE",((e,t,r="is invalid")=>{let n=i(t);return n.length>128&&(n=n.slice(0,128)+"..."),`The ${e.includes(".")?"property":"argument"} '${e}' ${r}. Received ${n}`}),TypeError),f("ERR_INVALID_RETURN_VALUE",((e,t,r)=>{var n;return`Expected ${e} to be returned from the "${t}" function but got ${null!=r&&null!==(n=r.constructor)&&void 0!==n&&n.name?`instance of ${r.constructor.name}`:"type "+typeof r}.`}),TypeError),f("ERR_MISSING_ARGS",((...e)=>{let t;d(e.length>0,"At least one arg needs to be specified");const r=e.length;switch(e=(Array.isArray(e)?e:[e]).map((e=>`"${e}"`)).join(" or "),r){case 1:t+=`The ${e[0]} argument`;break;case 2:t+=`The ${e[0]} and ${e[1]} arguments`;break;default:{const r=e.pop();t+=`The ${e.join(", ")}, and ${r} arguments`}}return`${t} must be specified`}),TypeError),f("ERR_OUT_OF_RANGE",((e,t,r)=>{let n;return d(t,'Missing "range" argument'),Number.isInteger(r)&&Math.abs(r)>2**32?n=h(String(r)):"bigint"==typeof r?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=h(n)),n+="n"):n=i(r),`The value of "${e}" is out of range. It must be ${t}. Received ${n}`}),RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:g,aggregateTwoErrors:p((function(e,t){if(e&&t&&e!==t){if(Array.isArray(t.errors))return t.errors.push(e),t;const r=new s([t,e],t.message);return r.code=t.code,r}return e||t})),hideStackFrames:p,codes:u}},2057:function(e){"use strict";e.exports={ArrayIsArray(e){return Array.isArray(e)},ArrayPrototypeIncludes(e,t){return e.includes(t)},ArrayPrototypeIndexOf(e,t){return e.indexOf(t)},ArrayPrototypeJoin(e,t){return e.join(t)},ArrayPrototypeMap(e,t){return e.map(t)},ArrayPrototypePop(e,t){return e.pop(t)},ArrayPrototypePush(e,t){return e.push(t)},ArrayPrototypeSlice(e,t,r){return e.slice(t,r)},Error:Error,FunctionPrototypeCall(e,t,...r){return e.call(t,...r)},FunctionPrototypeSymbolHasInstance(e,t){return Function.prototype[Symbol.hasInstance].call(e,t)},MathFloor:Math.floor,Number:Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(e,t){return Object.defineProperties(e,t)},ObjectDefineProperty(e,t,r){return Object.defineProperty(e,t,r)},ObjectGetOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)},ObjectKeys(e){return Object.keys(e)},ObjectSetPrototypeOf(e,t){return Object.setPrototypeOf(e,t)},Promise:Promise,PromisePrototypeCatch(e,t){return e.catch(t)},PromisePrototypeThen(e,t,r){return e.then(t,r)},PromiseReject(e){return Promise.reject(e)},PromiseResolve(e){return Promise.resolve(e)},ReflectApply:Reflect.apply,RegExpPrototypeTest(e,t){return e.test(t)},SafeSet:Set,String:String,StringPrototypeSlice(e,t,r){return e.slice(t,r)},StringPrototypeToLowerCase(e){return e.toLowerCase()},StringPrototypeToUpperCase(e){return e.toUpperCase()},StringPrototypeTrim(e){return e.trim()},Symbol:Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(e,t,r){return e.set(t,r)},Boolean:Boolean,Uint8Array:Uint8Array}},6745:function(e,t,r){"use strict";const n=r(8287),{kResistStopPropagation:i,SymbolDispose:o}=r(2057),s=globalThis.AbortSignal||r(5568).AbortSignal,a=globalThis.AbortController||r(5568).AbortController,c=Object.getPrototypeOf((async function(){})).constructor,l=globalThis.Blob||n.Blob,u=void 0!==l?function(e){return e instanceof l}:function(e){return!1},d=(e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new ERR_INVALID_ARG_TYPE(t,"AbortSignal",e)};class h extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError("Expected input to be an Array, got "+typeof e);let t="";for(let r=0;r{e=r,t=n})),resolve:e,reject:t}},promisify(e){return new Promise(((t,r)=>{e(((e,...n)=>e?r(e):t(...n)))}))},debuglog(){return function(){}},format(e,...t){return e.replace(/%([sdifj])/g,(function(...[e,r]){const n=t.shift();return"f"===r?n.toFixed(6):"j"===r?JSON.stringify(n):"s"===r&&"object"==typeof n?`${n.constructor!==Object?n.constructor.name:""} {}`.trim():n.toString()}))},inspect(e){switch(typeof e){case"string":if(e.includes("'")){if(!e.includes('"'))return`"${e}"`;if(!e.includes("`")&&!e.includes("${"))return`\`${e}\``}return`'${e}'`;case"number":return isNaN(e)?"NaN":Object.is(e,-0)?String(e):e;case"bigint":return`${String(e)}n`;case"boolean":case"undefined":return String(e);case"object":return"{}"}},types:{isAsyncFunction(e){return e instanceof c},isArrayBufferView(e){return ArrayBuffer.isView(e)}},isBlob:u,deprecate(e,t){return e},addAbortListener:r(7007).addAbortListener||function(e,t){if(void 0===e)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);let r;return d(e,"signal"),(e=>{if("function"!=typeof e)throw new ERR_INVALID_ARG_TYPE("listener","Function",e)})(t),e.aborted?queueMicrotask((()=>t())):(e.addEventListener("abort",t,{__proto__:null,once:!0,[i]:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,[o](){var e;null===(e=r)||void 0===e||e()}}},AbortSignalAny:s.any||function(e){if(1===e.length)return e[0];const t=new a,r=()=>t.abort();return e.forEach((e=>{d(e,"signals"),e.addEventListener("abort",r,{once:!0})})),t.signal.addEventListener("abort",(()=>{e.forEach((e=>e.removeEventListener("abort",r)))}),{once:!0}),t.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")},6897:function(e,t,r){const{Buffer:n}=r(8287),{ObjectDefineProperty:i,ObjectKeys:o,ReflectApply:s}=r(2057),{promisify:{custom:a}}=r(6745),{streamReturningOperators:c,promiseReturningOperators:l}=r(2892),{codes:{ERR_ILLEGAL_CONSTRUCTOR:u}}=r(54),d=r(769),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:f}=r(936),{pipeline:p}=r(5783),{destroyer:g}=r(2295),y=r(3789),m=r(7698),v=r(9232),b=e.exports=r(9526).Stream;b.isDestroyed=v.isDestroyed,b.isDisturbed=v.isDisturbed,b.isErrored=v.isErrored,b.isReadable=v.isReadable,b.isWritable=v.isWritable,b.Readable=r(5277);for(const S of o(c)){const E=c[S];function w(...e){if(new.target)throw u();return b.Readable.from(s(E,this,e))}i(w,"name",{__proto__:null,value:E.name}),i(w,"length",{__proto__:null,value:E.length}),i(b.Readable.prototype,S,{__proto__:null,value:w,enumerable:!1,configurable:!0,writable:!0})}for(const A of o(l)){const R=l[A];function w(...e){if(new.target)throw u();return s(R,this,e)}i(w,"name",{__proto__:null,value:R.name}),i(w,"length",{__proto__:null,value:R.length}),i(b.Readable.prototype,A,{__proto__:null,value:w,enumerable:!1,configurable:!0,writable:!0})}b.Writable=r(4461),b.Duplex=r(399),b.Transform=r(97),b.PassThrough=r(2163),b.pipeline=p;const{addAbortSignal:_}=r(2194);b.addAbortSignal=_,b.finished=y,b.destroy=g,b.compose=d,b.setDefaultHighWaterMark=h,b.getDefaultHighWaterMark=f,i(b,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return m}}),i(p,a,{__proto__:null,enumerable:!0,get(){return m.pipeline}}),i(y,a,{__proto__:null,enumerable:!0,get(){return m.finished}}),b.Stream=b,b._isUint8Array=function(e){return e instanceof Uint8Array},b._uint8ArrayToBuffer=function(e){return n.from(e.buffer,e.byteOffset,e.byteLength)}},7698:function(e,t,r){"use strict";const{ArrayPrototypePop:n,Promise:i}=r(2057),{isIterable:o,isNodeStream:s,isWebStream:a}=r(9232),{pipelineImpl:c}=r(5783),{finished:l}=r(3789);r(6897),e.exports={finished:l,pipeline:function(...e){return new i(((t,r)=>{let i,l;const u=e[e.length-1];if(u&&"object"==typeof u&&!s(u)&&!o(u)&&!a(u)){const t=n(e);i=t.signal,l=t.end}c(e,((e,n)=>{e?r(e):t(n)}),{signal:i,end:l})}))}}},8572:function(e,t,r){var n=r(8287),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(o(n,t),t.Buffer=s),s.prototype=Object.create(i.prototype),o(i,s),s.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},s.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},704:function(e,t,r){"use strict";var n=r(8572).Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=l,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=u,this.end=d,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,r=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function l(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function u(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function d(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0?(i>0&&(e.lastNeed=i-1),i):--n=0?(i>0&&(e.lastNeed=i-2),i):--n=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},810:function(e,t,r){"use strict";const{SymbolDispose:n}=r(4641),{AbortError:i,codes:o}=r(8526),{isNodeStream:s,isWebStream:a,kControllerErrorFunction:c}=r(136),l=r(9365),{ERR_INVALID_ARG_TYPE:u}=o;let d;e.exports.addAbortSignal=function(t,r){if((e=>{if("object"!=typeof e||!("aborted"in e))throw new u("signal","AbortSignal",e)})(t),!s(r)&&!a(r))throw new u("stream",["ReadableStream","WritableStream","Stream"],r);return e.exports.addAbortSignalNoValidate(t,r)},e.exports.addAbortSignalNoValidate=function(e,t){if("object"!=typeof e||!("aborted"in e))return t;const o=s(t)?()=>{t.destroy(new i(void 0,{cause:e.reason}))}:()=>{t[c](new i(void 0,{cause:e.reason}))};if(e.aborted)o();else{d=d||r(6017).addAbortListener;const i=d(e,o);l(t,i[n])}return t}},5586:function(e,t,r){"use strict";const{StringPrototypeSlice:n,SymbolIterator:i,TypedArrayPrototypeSet:o,Uint8Array:s}=r(4641),{Buffer:a}=r(8287),{inspect:c}=r(6017);e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(e){const t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}unshift(e){const t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}shift(){if(0===this.length)return;const e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(0===this.length)return"";let t=this.head,r=""+t.data;for(;null!==(t=t.next);)r+=e+t.data;return r}concat(e){if(0===this.length)return a.alloc(0);const t=a.allocUnsafe(e>>>0);let r=this.head,n=0;for(;r;)o(t,r.data,n),n+=r.data.length,r=r.next;return t}consume(e,t){const r=this.head.data;if(eo.length)){e===o.length?(t+=o,++i,r.next?this.head=r.next:this.head=this.tail=null):(t+=n(o,0,e),this.head=r,r.data=n(o,e));break}t+=o,e-=o.length,++i}while(null!==(r=r.next));return this.length-=i,t}_getBuffer(e){const t=a.allocUnsafe(e),r=e;let n=this.head,i=0;do{const a=n.data;if(!(e>a.length)){e===a.length?(o(t,a,r-e),++i,n.next?this.head=n.next:this.head=this.tail=null):(o(t,new s(a.buffer,a.byteOffset,e),r-e),this.head=n,n.data=a.slice(e));break}o(t,a,r-e),e-=a.length,++i}while(null!==(n=n.next));return this.length-=i,t}[Symbol.for("nodejs.util.inspect.custom")](e,t){return c(this,{...t,depth:0,customInspect:!1})}}},8489:function(e,t,r){"use strict";const{pipeline:n}=r(8431),i=r(3559),{destroyer:o}=r(7647),{isNodeStream:s,isReadable:a,isWritable:c,isWebStream:l,isTransformStream:u,isWritableStream:d,isReadableStream:h}=r(136),{AbortError:f,codes:{ERR_INVALID_ARG_VALUE:p,ERR_MISSING_ARGS:g}}=r(8526),y=r(9365);e.exports=function(...e){if(0===e.length)throw new g("streams");if(1===e.length)return i.from(e[0]);const t=[...e];if("function"==typeof e[0]&&(e[0]=i.from(e[0])),"function"==typeof e[e.length-1]){const t=e.length-1;e[t]=i.from(e[t])}for(let r=0;r0&&!(c(e[r])||d(e[r])||u(e[r])))throw new p(`streams[${r}]`,t[r],"must be writable")}let r,m,v,b,w;const _=e[0],S=n(e,(function(e){const t=b;b=null,t?t(e):e?w.destroy(e):A||E||w.destroy()})),E=!!(c(_)||d(_)||u(_)),A=!!(a(S)||h(S)||u(S));if(w=new i({writableObjectMode:!(null==_||!_.writableObjectMode),readableObjectMode:!(null==S||!S.readableObjectMode),writable:E,readable:A}),E){if(s(_))w._write=function(e,t,n){_.write(e,t)?n():r=n},w._final=function(e){_.end(),m=e},_.on("drain",(function(){if(r){const e=r;r=null,e()}}));else if(l(_)){const e=(u(_)?_.writable:_).getWriter();w._write=async function(t,r,n){try{await e.ready,e.write(t).catch((()=>{})),n()}catch(e){n(e)}},w._final=async function(t){try{await e.ready,e.close().catch((()=>{})),m=t}catch(e){t(e)}}}const e=u(S)?S.readable:S;y(e,(()=>{if(m){const e=m;m=null,e()}}))}if(A)if(s(S))S.on("readable",(function(){if(v){const e=v;v=null,e()}})),S.on("end",(function(){w.push(null)})),w._read=function(){for(;;){const e=S.read();if(null===e)return void(v=w._read);if(!w.push(e))return}};else if(l(S)){const e=(u(S)?S.readable:S).getReader();w._read=async function(){for(;;)try{const{value:t,done:r}=await e.read();if(!w.push(t))return;if(r)return void w.push(null)}catch{return}}}return w._destroy=function(e,t){e||null===b||(e=new f),v=null,r=null,m=null,null===b?t(e):(b=t,s(S)&&o(S,e))},w}},7647:function(e,t,r){"use strict";const n=r(5606),{aggregateTwoErrors:i,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:s}=r(8526),{Symbol:a}=r(4641),{kIsDestroyed:c,isDestroyed:l,isFinished:u,isServerRequest:d}=r(136),h=a("kDestroy"),f=a("kConstruct");function p(e,t,r){e&&(e.stack,t&&!t.errored&&(t.errored=e),r&&!r.errored&&(r.errored=e))}function g(e,t,r){let i=!1;function o(t){if(i)return;i=!0;const o=e._readableState,s=e._writableState;p(t,s,o),s&&(s.closed=!0),o&&(o.closed=!0),"function"==typeof r&&r(t),t?n.nextTick(y,e,t):n.nextTick(m,e)}try{e._destroy(t||null,o)}catch(t){o(t)}}function y(e,t){v(e,t),m(e)}function m(e){const t=e._readableState,r=e._writableState;r&&(r.closeEmitted=!0),t&&(t.closeEmitted=!0),(null!=r&&r.emitClose||null!=t&&t.emitClose)&&e.emit("close")}function v(e,t){const r=e._readableState,n=e._writableState;null!=n&&n.errorEmitted||null!=r&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),e.emit("error",t))}function b(e,t,r){const i=e._readableState,o=e._writableState;if(null!=o&&o.destroyed||null!=i&&i.destroyed)return this;null!=i&&i.autoDestroy||null!=o&&o.autoDestroy?e.destroy(t):t&&(t.stack,o&&!o.errored&&(o.errored=t),i&&!i.errored&&(i.errored=t),r?n.nextTick(v,e,t):v(e,t))}function w(e){let t=!1;function r(r){if(t)return void b(e,null!=r?r:new o);t=!0;const i=e._readableState,s=e._writableState,a=s||i;i&&(i.constructed=!0),s&&(s.constructed=!0),a.destroyed?e.emit(h,r):r?b(e,r,!0):n.nextTick(_,e)}try{e._construct((e=>{n.nextTick(r,e)}))}catch(e){n.nextTick(r,e)}}function _(e){e.emit(f)}function S(e){return(null==e?void 0:e.setHeader)&&"function"==typeof e.abort}function E(e){e.emit("close")}function A(e,t){e.emit("error",t),n.nextTick(E,e)}e.exports={construct:function(e,t){if("function"!=typeof e._construct)return;const r=e._readableState,i=e._writableState;r&&(r.constructed=!1),i&&(i.constructed=!1),e.once(f,t),e.listenerCount(f)>1||n.nextTick(w,e)},destroyer:function(e,t){e&&!l(e)&&(t||u(e)||(t=new s),d(e)?(e.socket=null,e.destroy(t)):S(e)?e.abort():S(e.req)?e.req.abort():"function"==typeof e.destroy?e.destroy(t):"function"==typeof e.close?e.close():t?n.nextTick(A,e,t):n.nextTick(E,e),e.destroyed||(e[c]=!0))},destroy:function(e,t){const r=this._readableState,n=this._writableState,o=n||r;return null!=n&&n.destroyed||null!=r&&r.destroyed?("function"==typeof t&&t(),this):(p(e,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),o.constructed?g(this,e,t):this.once(h,(function(r){g(this,i(r,e),t)})),this)},undestroy:function(){const e=this._readableState,t=this._writableState;e&&(e.constructed=!0,e.closed=!1,e.closeEmitted=!1,e.destroyed=!1,e.errored=null,e.errorEmitted=!1,e.reading=!1,e.ended=!1===e.readable,e.endEmitted=!1===e.readable),t&&(t.constructed=!0,t.destroyed=!1,t.closed=!1,t.closeEmitted=!1,t.errored=null,t.errorEmitted=!1,t.finalCalled=!1,t.prefinished=!1,t.ended=!1===t.writable,t.ending=!1===t.writable,t.finished=!1===t.writable)},errorOrDestroy:b}},3559:function(e,t,r){"use strict";const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:i,ObjectKeys:o,ObjectSetPrototypeOf:s}=r(4641);e.exports=l;const a=r(3125),c=r(7221);s(l.prototype,a.prototype),s(l,a);{const e=o(c.prototype);for(let t=0;t{d=!1,e&&v(t,e),h(e)})),l._write=function(e,t,i){r.write(e,t)?i():n=i},l._final=function(e){r.end(),i=e},r.on("drain",(function(){if(n){const e=n;n=null,e()}})),r.on("finish",(function(){if(i){const e=i;i=null,e()}}))),u&&(p(t,(e=>{u=!1,e&&v(t,e),h(e)})),t.on("readable",(function(){if(a){const e=a;a=null,e()}})),t.on("end",(function(){l.push(null)})),l._read=function(){for(;;){const e=t.read();if(null===e)return void(a=l._read);if(!l.push(e))return}}),l._destroy=function(e,o){e||null===c||(e=new g),a=null,n=null,i=null,null===c?o(e):(c=o,v(r,e),v(t,e))},l}e.exports=function e(t,r){if(d(t))return t;if(l(t))return P({readable:t});if(u(t))return P({writable:t});if(c(t))return P({writable:!1,readable:!1});if(h(t))return P({readable:w.fromWeb(t)});if(f(t))return P({writable:_.fromWeb(t)});if("function"==typeof t){const{value:e,write:i,final:o,destroy:s}=function(e){let{promise:t,resolve:r}=S();const i=new I,o=i.signal;return{value:e(async function*(){for(;;){const e=t;t=null;const{chunk:i,done:s,cb:a}=await e;if(n.nextTick(a),s)return;if(o.aborted)throw new g(void 0,{cause:o.reason});({promise:t,resolve:r}=S()),yield i}}(),{signal:o}),write(e,t,n){const i=r;r=null,i({chunk:e,done:!1,cb:n})},final(e){const t=r;r=null,t({done:!0,cb:e})},destroy(e,t){i.abort(),t(e)}}}(t);if(a(e))return E(x,e,{objectMode:!0,write:i,final:o,destroy:s});const c=null==e?void 0:e.then;if("function"==typeof c){let t;const r=T(c,e,(e=>{if(null!=e)throw new m("nully","body",e)}),(e=>{v(t,e)}));return t=new x({objectMode:!0,readable:!1,write:i,final(e){o((async()=>{try{await r,n.nextTick(e,null)}catch(t){n.nextTick(e,t)}}))},destroy:s})}throw new m("Iterable, AsyncIterable or AsyncFunction",r,e)}if(R(t))return e(t.arrayBuffer());if(a(t))return E(x,t,{objectMode:!0,writable:!1});if(h(null==t?void 0:t.readable)&&f(null==t?void 0:t.writable))return x.fromWeb(t);if("object"==typeof(null==t?void 0:t.writable)||"object"==typeof(null==t?void 0:t.readable))return P({readable:null!=t&&t.readable?l(null==t?void 0:t.readable)?null==t?void 0:t.readable:e(t.readable):void 0,writable:null!=t&&t.writable?u(null==t?void 0:t.writable)?null==t?void 0:t.writable:e(t.writable):void 0});const i=null==t?void 0:t.then;if("function"==typeof i){let e;return T(i,t,(t=>{null!=t&&e.push(t),e.push(null)}),(t=>{v(e,t)})),e=new x({objectMode:!0,writable:!1,read(){}})}throw new y(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],t)}},9365:function(e,t,r){const n=r(5606),{AbortError:i,codes:o}=r(8526),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_PREMATURE_CLOSE:a}=o,{kEmptyObject:c,once:l}=r(6017),{validateAbortSignal:u,validateFunction:d,validateObject:h,validateBoolean:f}=r(2224),{Promise:p,PromisePrototypeThen:g,SymbolDispose:y}=r(4641),{isClosed:m,isReadable:v,isReadableNodeStream:b,isReadableStream:w,isReadableFinished:_,isReadableErrored:S,isWritable:E,isWritableNodeStream:A,isWritableStream:R,isWritableFinished:I,isWritableErrored:T,isNodeStream:x,willEmitClose:P,kIsClosedPromise:C}=r(136);let k;const O=()=>{};function F(e,t,o){var f,p;if(2===arguments.length?(o=t,t=c):null==t?t=c:h(t,"options"),d(o,"callback"),u(t.signal,"options.signal"),o=l(o),w(e)||R(e))return function(e,t,o){let s=!1,a=O;if(t.signal)if(a=()=>{s=!0,o.call(e,new i(void 0,{cause:t.signal.reason}))},t.signal.aborted)n.nextTick(a);else{k=k||r(6017).addAbortListener;const n=k(t.signal,a),i=o;o=l(((...t)=>{n[y](),i.apply(e,t)}))}const c=(...t)=>{s||n.nextTick((()=>o.apply(e,t)))};return g(e[C].promise,c,c),O}(e,t,o);if(!x(e))throw new s("stream",["ReadableStream","WritableStream","Stream"],e);const F=null!==(f=t.readable)&&void 0!==f?f:b(e),N=null!==(p=t.writable)&&void 0!==p?p:A(e),D=e._writableState,L=e._readableState,U=()=>{e.writable||B()};let j=P(e)&&b(e)===F&&A(e)===N,M=I(e,!1);const B=()=>{M=!0,e.destroyed&&(j=!1),(!j||e.readable&&!F)&&(F&&!H||o.call(e))};let H=_(e,!1);const W=()=>{H=!0,e.destroyed&&(j=!1),(!j||e.writable&&!N)&&(N&&!M||o.call(e))},$=t=>{o.call(e,t)};let V=m(e);const K=()=>{V=!0;const t=T(e)||S(e);return t&&"boolean"!=typeof t?o.call(e,t):F&&!H&&b(e,!0)&&!_(e,!1)?o.call(e,new a):!N||M||I(e,!1)?void o.call(e):o.call(e,new a)},J=()=>{V=!0;const t=T(e)||S(e);if(t&&"boolean"!=typeof t)return o.call(e,t);o.call(e)},G=()=>{e.req.on("finish",B)};!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?N&&!D&&(e.on("end",U),e.on("close",U)):(e.on("complete",B),j||e.on("abort",K),e.req?G():e.on("request",G)),j||"boolean"!=typeof e.aborted||e.on("aborted",K),e.on("end",W),e.on("finish",B),!1!==t.error&&e.on("error",$),e.on("close",K),V?n.nextTick(K):null!=D&&D.errorEmitted||null!=L&&L.errorEmitted?j||n.nextTick(J):(F||j&&!v(e)||!M&&!1!==E(e))&&(N||j&&!E(e)||!H&&!1!==v(e))?L&&e.req&&e.aborted&&n.nextTick(J):n.nextTick(J);const q=()=>{o=O,e.removeListener("aborted",K),e.removeListener("complete",B),e.removeListener("abort",K),e.removeListener("request",G),e.req&&e.req.removeListener("finish",B),e.removeListener("end",U),e.removeListener("close",U),e.removeListener("finish",B),e.removeListener("end",W),e.removeListener("error",$),e.removeListener("close",K)};if(t.signal&&!V){const s=()=>{const r=o;q(),r.call(e,new i(void 0,{cause:t.signal.reason}))};if(t.signal.aborted)n.nextTick(s);else{k=k||r(6017).addAbortListener;const n=k(t.signal,s),i=o;o=l(((...t)=>{n[y](),i.apply(e,t)}))}}return q}e.exports=F,e.exports.finished=function(e,t){var r;let n=!1;return null===t&&(t=c),null!==(r=t)&&void 0!==r&&r.cleanup&&(f(t.cleanup,"cleanup"),n=t.cleanup),new p(((r,i)=>{const o=F(e,t,(e=>{n&&o(),e?i(e):r()}))}))}},333:function(e,t,r){"use strict";const n=r(5606),{PromisePrototypeThen:i,SymbolAsyncIterator:o,SymbolIterator:s}=r(4641),{Buffer:a}=r(8287),{ERR_INVALID_ARG_TYPE:c,ERR_STREAM_NULL_VALUES:l}=r(8526).codes;e.exports=function(e,t,r){let u,d;if("string"==typeof t||t instanceof a)return new e({objectMode:!0,...r,read(){this.push(t),this.push(null)}});if(t&&t[o])d=!0,u=t[o]();else{if(!t||!t[s])throw new c("iterable",["Iterable"],t);d=!1,u=t[s]()}const h=new e({objectMode:!0,highWaterMark:1,...r});let f=!1;return h._read=function(){f||(f=!0,async function(){for(;;){try{const{value:e,done:t}=d?await u.next():u.next();if(t)h.push(null);else{const t=e&&"function"==typeof e.then?await e:e;if(null===t)throw f=!1,new l;if(h.push(t))continue;f=!1}}catch(e){h.destroy(e)}break}}())},h._destroy=function(e,t){i(async function(e){const t=null!=e,r="function"==typeof u.throw;if(t&&r){const{value:t,done:r}=await u.throw(e);if(await t,r)return}if("function"==typeof u.return){const{value:e}=await u.return();await e}}(e),(()=>n.nextTick(t,e)),(r=>n.nextTick(t,r||e)))},h}},334:function(e,t,r){"use strict";const{ArrayIsArray:n,ObjectSetPrototypeOf:i}=r(4641),{EventEmitter:o}=r(7007);function s(e){o.call(this,e)}function a(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?n(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}i(s.prototype,o.prototype),i(s,o),s.prototype.pipe=function(e,t){const r=this;function n(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function i(){r.readable&&r.resume&&r.resume()}r.on("data",n),e.on("drain",i),e._isStdio||t&&!1===t.end||(r.on("end",c),r.on("close",l));let s=!1;function c(){s||(s=!0,e.end())}function l(){s||(s=!0,"function"==typeof e.destroy&&e.destroy())}function u(e){d(),0===o.listenerCount(this,"error")&&this.emit("error",e)}function d(){r.removeListener("data",n),e.removeListener("drain",i),r.removeListener("end",c),r.removeListener("close",l),r.removeListener("error",u),e.removeListener("error",u),r.removeListener("end",d),r.removeListener("close",d),e.removeListener("close",d)}return a(r,"error",u),a(e,"error",u),r.on("end",d),r.on("close",d),e.on("close",d),e.emit("pipe",r),e},e.exports={Stream:s,prependListener:a}},1284:function(e,t,r){"use strict";const n=globalThis.AbortController||r(5568).AbortController,{codes:{ERR_INVALID_ARG_VALUE:i,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:s,ERR_OUT_OF_RANGE:a},AbortError:c}=r(8526),{validateAbortSignal:l,validateInteger:u,validateObject:d}=r(2224),h=r(4641).Symbol("kWeak"),f=r(4641).Symbol("kResistStopPropagation"),{finished:p}=r(9365),g=r(8489),{addAbortSignalNoValidate:y}=r(810),{isWritable:m,isNodeStream:v}=r(136),{deprecate:b}=r(6017),{ArrayPrototypePush:w,Boolean:_,MathFloor:S,Number:E,NumberIsNaN:A,Promise:R,PromiseReject:I,PromiseResolve:T,PromisePrototypeThen:x,Symbol:P}=r(4641),C=P("kEmpty"),k=P("kEof");function O(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal");let n=1;null!=(null==t?void 0:t.concurrency)&&(n=S(t.concurrency));let i=n-1;return null!=(null==t?void 0:t.highWaterMark)&&(i=S(t.highWaterMark)),u(n,"options.concurrency",1),u(i,"options.highWaterMark",0),i+=n,async function*(){const o=r(6017).AbortSignalAny([null==t?void 0:t.signal].filter(_)),s=this,a=[],l={signal:o};let u,d,h=!1,f=0;function p(){h=!0,g()}function g(){f-=1,y()}function y(){d&&!h&&f=i||f>=n)&&await new R((e=>{d=e}))}a.push(k)}catch(e){const t=I(e);x(t,g,p),a.push(t)}finally{h=!0,u&&(u(),u=null)}}();try{for(;;){for(;a.length>0;){const e=await a[0];if(e===k)return;if(o.aborted)throw new c;e!==C&&(yield e),a.shift(),y()}await new R((e=>{u=e}))}}finally{h=!0,d&&(d(),d=null)}}.call(this)}async function F(e,t=void 0){for await(const r of N.call(this,e,t))return!0;return!1}function N(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return O.call(this,(async function(t,r){return await e(t,r)?t:C}),t)}class D extends s{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}function L(e){if(e=E(e),A(e))return 0;if(e<0)throw new a("number",">= 0",e);return e}e.exports.streamReturningOperators={asIndexedPairs:b((function(e=void 0){return null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(e.signal,"options.signal"),async function*(){let t=0;for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new c({cause:e.signal.reason});yield[t++,n]}}.call(this)}),"readable.asIndexedPairs will be removed in a future version."),drop:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=L(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;e--<=0&&(yield r)}}.call(this)},filter:N,flatMap:function(e,t){const r=O.call(this,e,t);return async function*(){for await(const e of r)yield*e}.call(this)},map:O,take:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=L(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;if(e-- >0&&(yield r),e<=0)return}}.call(this)},compose:function(e,t){if(null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),v(e)&&!m(e))throw new i("stream",e,"must be writable");const r=g(this,e);return null!=t&&t.signal&&y(t.signal,r),r}},e.exports.promiseReturningOperators={every:async function(e,t=void 0){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return!await F.call(this,(async(...t)=>!await e(...t)),t)},forEach:async function(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);for await(const r of O.call(this,(async function(t,r){return await e(t,r),C}),t));},reduce:async function(e,t,r){var i;if("function"!=typeof e)throw new o("reducer",["Function","AsyncFunction"],e);null!=r&&d(r,"options"),null!=(null==r?void 0:r.signal)&&l(r.signal,"options.signal");let s=arguments.length>1;if(null!=r&&null!==(i=r.signal)&&void 0!==i&&i.aborted){const e=new c(void 0,{cause:r.signal.reason});throw this.once("error",(()=>{})),await p(this.destroy(e)),e}const a=new n,u=a.signal;if(null!=r&&r.signal){const e={once:!0,[h]:this,[f]:!0};r.signal.addEventListener("abort",(()=>a.abort()),e)}let g=!1;try{for await(const n of this){var y;if(g=!0,null!=r&&null!==(y=r.signal)&&void 0!==y&&y.aborted)throw new c;s?t=await e(t,n,{signal:u}):(t=n,s=!0)}if(!g&&!s)throw new D}finally{a.abort()}return t},toArray:async function(e){null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(e.signal,"options.signal");const t=[];for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new c(void 0,{cause:e.signal.reason});w(t,n)}return t},some:F,find:async function(e,t){for await(const r of N.call(this,e,t))return r}}},2091:function(e,t,r){"use strict";const{ObjectSetPrototypeOf:n}=r(4641);e.exports=o;const i=r(8649);function o(e){if(!(this instanceof o))return new o(e);i.call(this,e)}n(o.prototype,i.prototype),n(o,i),o.prototype._transform=function(e,t,r){r(null,e)}},8431:function(e,t,r){const n=r(5606),{ArrayIsArray:i,Promise:o,SymbolAsyncIterator:s,SymbolDispose:a}=r(4641),c=r(9365),{once:l}=r(6017),u=r(7647),d=r(3559),{aggregateTwoErrors:h,codes:{ERR_INVALID_ARG_TYPE:f,ERR_INVALID_RETURN_VALUE:p,ERR_MISSING_ARGS:g,ERR_STREAM_DESTROYED:y,ERR_STREAM_PREMATURE_CLOSE:m},AbortError:v}=r(8526),{validateFunction:b,validateAbortSignal:w}=r(2224),{isIterable:_,isReadable:S,isReadableNodeStream:E,isNodeStream:A,isTransformStream:R,isWebStream:I,isReadableStream:T,isReadableFinished:x}=r(136),P=globalThis.AbortController||r(5568).AbortController;let C,k,O;function F(e,t,r){let n=!1;return e.on("close",(()=>{n=!0})),{destroy:t=>{n||(n=!0,u.destroyer(e,t||new y("pipe")))},cleanup:c(e,{readable:t,writable:r},(e=>{n=!e}))}}function N(e){if(_(e))return e;if(E(e))return async function*(e){k||(k=r(3125)),yield*k.prototype[s].call(e)}(e);throw new f("val",["Readable","Iterable","AsyncIterable"],e)}async function D(e,t,r,{end:n}){let i,s=null;const a=e=>{if(e&&(i=e),s){const e=s;s=null,e()}},l=()=>new o(((e,t)=>{i?t(i):s=()=>{i?t(i):e()}}));t.on("drain",a);const u=c(t,{readable:!1},a);try{t.writableNeedDrain&&await l();for await(const r of e)t.write(r)||await l();n&&(t.end(),await l()),r()}catch(e){r(i!==e?h(i,e):e)}finally{u(),t.off("drain",a)}}async function L(e,t,r,{end:n}){R(t)&&(t=t.writable);const i=t.getWriter();try{for await(const t of e)await i.ready,i.write(t).catch((()=>{}));await i.ready,n&&await i.close(),r()}catch(e){try{await i.abort(e),r(e)}catch(e){r(e)}}}function U(e,t,o){if(1===e.length&&i(e[0])&&(e=e[0]),e.length<2)throw new g("streams");const s=new P,c=s.signal,l=null==o?void 0:o.signal,u=[];function h(){B(new v)}let y,m,b;w(l,"options.signal"),O=O||r(6017).addAbortListener,l&&(y=O(l,h));const x=[];let k,U=0;function M(e){B(e,0==--U)}function B(e,r){var i;if(!e||m&&"ERR_STREAM_PREMATURE_CLOSE"!==m.code||(m=e),m||r){for(;x.length;)x.shift()(m);null===(i=y)||void 0===i||i[a](),s.abort(),r&&(m||u.forEach((e=>e())),n.nextTick(t,m,b))}}for(let V=0;V0,q=J||!1!==(null==o?void 0:o.end),z=V===e.length-1;if(A(K)){if(q){const{destroy:Y,cleanup:Q}=F(K,J,G);x.push(Y),S(K)&&z&&u.push(Q)}function H(e){e&&"AbortError"!==e.name&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code&&M(e)}K.on("error",H),S(K)&&z&&u.push((()=>{K.removeListener("error",H)}))}if(0===V)if("function"==typeof K){if(k=K({signal:c}),!_(k))throw new p("Iterable, AsyncIterable or Stream","source",k)}else k=_(K)||E(K)||R(K)?K:d.from(K);else if("function"==typeof K){var W;if(k=R(k)?N(null===(W=k)||void 0===W?void 0:W.readable):N(k),k=K(k,{signal:c}),J){if(!_(k,!0))throw new p("AsyncIterable",`transform[${V-1}]`,k)}else{var $;C||(C=r(2091));const X=new C({objectMode:!0}),Z=null===($=k)||void 0===$?void 0:$.then;if("function"==typeof Z)U++,Z.call(k,(e=>{b=e,null!=e&&X.write(e),q&&X.end(),n.nextTick(M)}),(e=>{X.destroy(e),n.nextTick(M,e)}));else if(_(k,!0))U++,D(k,X,M,{end:q});else{if(!T(k)&&!R(k))throw new p("AsyncIterable or Promise","destination",k);{const re=k.readable||k;U++,D(re,X,M,{end:q})}}k=X;const{destroy:ee,cleanup:te}=F(k,!1,!0);x.push(ee),z&&u.push(te)}}else if(A(K)){if(E(k)){U+=2;const ne=j(k,K,M,{end:q});S(K)&&z&&u.push(ne)}else if(R(k)||T(k)){const ie=k.readable||k;U++,D(ie,K,M,{end:q})}else{if(!_(k))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],k);U++,D(k,K,M,{end:q})}k=K}else if(I(K)){if(E(k))U++,L(N(k),K,M,{end:q});else if(T(k)||_(k))U++,L(k,K,M,{end:q});else{if(!R(k))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],k);U++,L(k.readable,K,M,{end:q})}k=K}else k=d.from(K)}return(null!=c&&c.aborted||null!=l&&l.aborted)&&n.nextTick(h),k}function j(e,t,r,{end:i}){let o=!1;if(t.on("close",(()=>{o||r(new m)})),e.pipe(t,{end:!1}),i){function s(){o=!0,t.end()}x(e)?n.nextTick(s):e.once("end",s)}else r();return c(e,{readable:!0,writable:!1},(t=>{const n=e._readableState;t&&"ERR_STREAM_PREMATURE_CLOSE"===t.code&&n&&n.ended&&!n.errored&&!n.errorEmitted?e.once("end",r).once("error",r):r(t)})),c(t,{readable:!1,writable:!0},r)}e.exports={pipelineImpl:U,pipeline:function(...e){return U(e,l(function(e){return b(e[e.length-1],"streams[stream.length - 1]"),e.pop()}(e)))}}},3125:function(e,t,r){const n=r(5606),{ArrayPrototypeIndexOf:i,NumberIsInteger:o,NumberIsNaN:s,NumberParseInt:a,ObjectDefineProperties:c,ObjectKeys:l,ObjectSetPrototypeOf:u,Promise:d,SafeSet:h,SymbolAsyncDispose:f,SymbolAsyncIterator:p,Symbol:g}=r(4641);e.exports=G,G.ReadableState=J;const{EventEmitter:y}=r(7007),{Stream:m,prependListener:v}=r(334),{Buffer:b}=r(8287),{addAbortSignal:w}=r(810),_=r(9365);let S=r(6017).debuglog("stream",(e=>{S=e}));const E=r(5586),A=r(7647),{getHighWaterMark:R,getDefaultHighWaterMark:I}=r(3920),{aggregateTwoErrors:T,codes:{ERR_INVALID_ARG_TYPE:x,ERR_METHOD_NOT_IMPLEMENTED:P,ERR_OUT_OF_RANGE:C,ERR_STREAM_PUSH_AFTER_EOF:k,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:O},AbortError:F}=r(8526),{validateObject:N}=r(2224),D=g("kPaused"),{StringDecoder:L}=r(6600),U=r(333);u(G.prototype,m.prototype),u(G,m);const j=()=>{},{errorOrDestroy:M}=A,B=1,H=16,W=32,$=2048,V=4096;function K(e){return{enumerable:!1,get(){return!!(this.state&e)},set(t){t?this.state|=e:this.state&=~e}}}function J(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(3559)),this.state=$|V|H|W,e&&e.objectMode&&(this.state|=B),n&&e&&e.readableObjectMode&&(this.state|=B),this.highWaterMark=e?R(this,e,"readableHighWaterMark",n):I(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[D]=null,e&&!1===e.emitClose&&(this.state&=~$),e&&!1===e.autoDestroy&&(this.state&=~V),this.errored=null,this.defaultEncoding=e&&e.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,e&&e.encoding&&(this.decoder=new L(e.encoding),this.encoding=e.encoding)}function G(e){if(!(this instanceof G))return new G(e);const t=this instanceof r(3559);this._readableState=new J(e,this,t),e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.construct&&(this._construct=e.construct),e.signal&&!t&&w(e.signal,this)),m.call(this,e),A.construct(this,(()=>{this._readableState.needReadable&&Z(this,this._readableState)}))}function q(e,t,r,n){S("readableAddChunk",t);const i=e._readableState;let o;if(i.state&B||("string"==typeof t?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?t=b.from(t,r).toString(i.encoding):(t=b.from(t,r),r=""))):t instanceof b?r="":m._isUint8Array(t)?(t=m._uint8ArrayToBuffer(t),r=""):null!=t&&(o=new x("chunk",["string","Buffer","Uint8Array"],t))),o)M(e,o);else if(null===t)i.state&=-9,function(e,t){if(S("onEofChunk"),!t.ended){if(t.decoder){const e=t.decoder.end();e&&e.length&&(t.buffer.push(e),t.length+=t.objectMode?1:e.length)}t.ended=!0,t.sync?Q(e):(t.needReadable=!1,t.emittedReadable=!0,X(e))}}(e,i);else if(i.state&B||t&&t.length>0)if(n)if(4&i.state)M(e,new O);else{if(i.destroyed||i.errored)return!1;z(e,i,t,!0)}else if(i.ended)M(e,new k);else{if(i.destroyed||i.errored)return!1;i.state&=-9,i.decoder&&!r?(t=i.decoder.write(t),i.objectMode||0!==t.length?z(e,i,t,!1):Z(e,i)):z(e,i,t,!1)}else n||(i.state&=-9,Z(e,i));return!i.ended&&(i.length0?(65536&t.state?t.awaitDrainWriters.clear():t.awaitDrainWriters=null,t.dataEmitted=!0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),64&t.state&&Q(e)),Z(e,t)}function Y(e,t){return e<=0||0===t.length&&t.ended?0:t.state&B?1:s(e)?t.flowing&&t.length?t.buffer.first().length:t.length:e<=t.length?e:t.ended?t.length:0}function Q(e){const t=e._readableState;S("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(S("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(X,e))}function X(e){const t=e._readableState;S("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||t.errored||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,ie(e)}function Z(e,t){!t.readingMore&&t.constructed&&(t.readingMore=!0,n.nextTick(ee,e,t))}function ee(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!1===t[D]?t.flowing=!0:e.listenerCount("data")>0?e.resume():t.readableListening||(t.flowing=null)}function re(e){S("readable nexttick read 0"),e.read(0)}function ne(e,t){S("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),ie(e),t.flowing&&!t.reading&&e.read(0)}function ie(e){const t=e._readableState;for(S("flow",t.flowing);t.flowing&&null!==e.read(););}function oe(e,t){"function"!=typeof e.read&&(e=G.wrap(e,{objectMode:!0}));const r=async function*(e,t){let r,n=j;function i(t){this===e?(n(),n=j):n=t}e.on("readable",i);const o=_(e,{writable:!1},(e=>{r=e?T(r,e):null,n(),n=j}));try{for(;;){const t=e.destroyed?null:e.read();if(null!==t)yield t;else{if(r)throw r;if(null===r)return;await new d(i)}}}catch(e){throw r=T(r,e),r}finally{!r&&!1===(null==t?void 0:t.destroyOnReturn)||void 0!==r&&!e._readableState.autoDestroy?(e.off("readable",i),o()):A.destroyer(e,null)}}(e,t);return r.stream=e,r}function se(e,t){if(0===t.length)return null;let r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}function ae(e){const t=e._readableState;S("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(ce,t,e))}function ce(e,t){if(S("endReadableNT",e.endEmitted,e.length),!e.errored&&!e.closeEmitted&&!e.endEmitted&&0===e.length)if(e.endEmitted=!0,t.emit("end"),t.writable&&!1===t.allowHalfOpen)n.nextTick(le,t);else if(e.autoDestroy){const e=t._writableState;(!e||e.autoDestroy&&(e.finished||!1===e.writable))&&t.destroy()}}function le(e){e.writable&&!e.writableEnded&&!e.destroyed&&e.end()}let ue;function de(){return void 0===ue&&(ue={}),ue}c(J.prototype,{objectMode:K(B),ended:K(2),endEmitted:K(4),reading:K(8),constructed:K(H),sync:K(W),needReadable:K(64),emittedReadable:K(128),readableListening:K(256),resumeScheduled:K(512),errorEmitted:K(1024),emitClose:K($),autoDestroy:K(V),destroyed:K(8192),closed:K(16384),closeEmitted:K(32768),multiAwaitDrain:K(65536),readingMore:K(1<<17),dataEmitted:K(1<<18)}),G.prototype.destroy=A.destroy,G.prototype._undestroy=A.undestroy,G.prototype._destroy=function(e,t){t(e)},G.prototype[y.captureRejectionSymbol]=function(e){this.destroy(e)},G.prototype[f]=function(){let e;return this.destroyed||(e=this.readableEnded?null:new F,this.destroy(e)),new d(((t,r)=>_(this,(n=>n&&n!==e?r(n):t(null)))))},G.prototype.push=function(e,t){return q(this,e,t,!1)},G.prototype.unshift=function(e,t){return q(this,e,t,!0)},G.prototype.isPaused=function(){const e=this._readableState;return!0===e[D]||!1===e.flowing},G.prototype.setEncoding=function(e){const t=new L(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;const r=this._readableState.buffer;let n="";for(const e of r)n+=t.write(e);return r.clear(),""!==n&&r.push(n),this._readableState.length=n.length,this},G.prototype.read=function(e){S("read",e),void 0===e?e=NaN:o(e)||(e=a(e,10));const t=this._readableState,r=e;if(e>t.highWaterMark&&(t.highWaterMark=function(e){if(e>1073741824)throw new C("size","<= 1GiB",e);return e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,++e}(e)),0!==e&&(t.state&=-129),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return S("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?ae(this):Q(this),null;if(0===(e=Y(e,t))&&t.ended)return 0===t.length&&ae(this),null;let n,i=!!(64&t.state);if(S("need readable",i),(0===t.length||t.length-e0?se(e,t):null,null===n?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.multiAwaitDrain?t.awaitDrainWriters.clear():t.awaitDrainWriters=null),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&ae(this)),null===n||t.errorEmitted||t.closeEmitted||(t.dataEmitted=!0,this.emit("data",n)),n},G.prototype._read=function(e){throw new P("_read()")},G.prototype.pipe=function(e,t){const r=this,i=this._readableState;1===i.pipes.length&&(i.multiAwaitDrain||(i.multiAwaitDrain=!0,i.awaitDrainWriters=new h(i.awaitDrainWriters?[i.awaitDrainWriters]:[]))),i.pipes.push(e),S("pipe count=%d opts=%j",i.pipes.length,t);const o=t&&!1===t.end||e===n.stdout||e===n.stderr?g:s;function s(){S("onend"),e.end()}let a;i.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",(function t(n,o){S("onunpipe"),n===r&&o&&!1===o.hasUnpiped&&(o.hasUnpiped=!0,S("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),a&&e.removeListener("drain",a),e.removeListener("error",d),e.removeListener("unpipe",t),r.removeListener("end",s),r.removeListener("end",g),r.removeListener("data",u),c=!0,a&&i.awaitDrainWriters&&(!e._writableState||e._writableState.needDrain)&&a())}));let c=!1;function l(){c||(1===i.pipes.length&&i.pipes[0]===e?(S("false write response, pause",0),i.awaitDrainWriters=e,i.multiAwaitDrain=!1):i.pipes.length>1&&i.pipes.includes(e)&&(S("false write response, pause",i.awaitDrainWriters.size),i.awaitDrainWriters.add(e)),r.pause()),a||(a=function(e,t){return function(){const r=e._readableState;r.awaitDrainWriters===t?(S("pipeOnDrain",1),r.awaitDrainWriters=null):r.multiAwaitDrain&&(S("pipeOnDrain",r.awaitDrainWriters.size),r.awaitDrainWriters.delete(t)),r.awaitDrainWriters&&0!==r.awaitDrainWriters.size||!e.listenerCount("data")||e.resume()}}(r,e),e.on("drain",a))}function u(t){S("ondata");const r=e.write(t);S("dest.write",r),!1===r&&l()}function d(t){if(S("onerror",t),g(),e.removeListener("error",d),0===e.listenerCount("error")){const r=e._writableState||e._readableState;r&&!r.errorEmitted?M(e,t):e.emit("error",t)}}function f(){e.removeListener("finish",p),g()}function p(){S("onfinish"),e.removeListener("close",f),g()}function g(){S("unpipe"),r.unpipe(e)}return r.on("data",u),v(e,"error",d),e.once("close",f),e.once("finish",p),e.emit("pipe",r),!0===e.writableNeedDrain?l():i.flowing||(S("pipe resume"),r.resume()),e},G.prototype.unpipe=function(e){const t=this._readableState;if(0===t.pipes.length)return this;if(!e){const e=t.pipes;t.pipes=[],this.pause();for(let t=0;t0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,S("on readable",i.length,i.reading),i.length?Q(this):i.reading||n.nextTick(re,this))),r},G.prototype.addListener=G.prototype.on,G.prototype.removeListener=function(e,t){const r=m.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(te,this),r},G.prototype.off=G.prototype.removeListener,G.prototype.removeAllListeners=function(e){const t=m.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(te,this),t},G.prototype.resume=function(){const e=this._readableState;return e.flowing||(S("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(ne,e,t))}(this,e)),e[D]=!1,this},G.prototype.pause=function(){return S("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(S("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[D]=!0,this},G.prototype.wrap=function(e){let t=!1;e.on("data",(r=>{!this.push(r)&&e.pause&&(t=!0,e.pause())})),e.on("end",(()=>{this.push(null)})),e.on("error",(e=>{M(this,e)})),e.on("close",(()=>{this.destroy()})),e.on("destroy",(()=>{this.destroy()})),this._read=()=>{t&&e.resume&&(t=!1,e.resume())};const r=l(e);for(let t=1;t{t?e?e(t):this.destroy(t):(null!=r&&this.push(r),this.push(null),e&&e())}))}function d(){this._final!==u&&u.call(this)}l.prototype._final=u,l.prototype._transform=function(e,t,r){throw new o("_transform()")},l.prototype._write=function(e,t,r){const n=this._readableState,i=this._writableState,o=n.length;this._transform(e,t,((e,t)=>{e?r(e):(null!=t&&this.push(t),i.ended||o===n.length||n.length{const e=this._writableState;e.writing||W(this,e),V(this,e)}))}function D(e,t,r,i){const o=e._writableState;if("function"==typeof r)i=r,r=o.defaultEncoding;else{if(r){if("buffer"!==r&&!g.isEncoding(r))throw new x(r)}else r=o.defaultEncoding;"function"!=typeof i&&(i=C)}if(null===t)throw new I;if(!o.objectMode)if("string"==typeof t)!1!==o.decodeStrings&&(t=g.from(t,r),r="buffer");else if(t instanceof g)r="buffer";else{if(!p._isUint8Array(t))throw new w("chunk",["string","Buffer","Uint8Array"],t);t=p._uint8ArrayToBuffer(t),r="buffer"}let s;return o.ending?s=new T:o.destroyed&&(s=new A("write")),s?(n.nextTick(i,s),P(e,s,!0),s):(o.pendingcb++,function(e,t,r,n,i){const o=t.objectMode?1:r.length;t.length+=o;const s=t.lengthr.bufferedIndex&&W(e,r),i?null!==r.afterWriteTickInfo&&r.afterWriteTickInfo.cb===o?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:o,stream:e,state:r},n.nextTick(M,r.afterWriteTickInfo)):B(e,r,1,o))):P(e,new S)}function M({stream:e,state:t,count:r,cb:n}){return t.afterWriteTickInfo=null,B(e,t,r,n)}function B(e,t,r,n){for(!t.ending&&!e.destroyed&&0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"));r-- >0;)t.pendingcb--,n();t.destroyed&&H(t),V(e,t)}function H(e){if(e.writing)return;for(let r=e.bufferedIndex;r1&&e._writev){t.pendingcb-=s-1;const n=t.allNoop?C:e=>{for(let t=a;t256?(r.splice(0,a),t.bufferedIndex=0):t.bufferedIndex=a}t.bufferProcessing=!1}function $(e){return e.ending&&!e.destroyed&&e.constructed&&0===e.length&&!e.errored&&0===e.buffered.length&&!e.finished&&!e.writing&&!e.errorEmitted&&!e.closeEmitted}function V(e,t,r){$(t)&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.finalCalled=!0,function(e,t){let r=!1;function i(i){if(r)P(e,null!=i?i:S());else if(r=!0,t.pendingcb--,i){const r=t[k].splice(0);for(let e=0;e{$(t)?K(e,t):t.pendingcb--}),e,t)):$(t)&&(t.pendingcb++,K(e,t))))}function K(e,t){t.pendingcb--,t.finished=!0;const r=t[k].splice(0);for(let e=0;e{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);if(en)throw new _(t,`>= ${r} && <= ${n}`,e)})),P=m(((e,t,r=-2147483648,n=2147483647)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);if(en)throw new _(t,`>= ${r} && <= ${n}`,e)})),C=m(((e,t,r=!1)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);const n=r?1:0,i=4294967295;if(ei)throw new _(t,`>= ${n} && <= ${i}`,e)}));function k(e,t){if("string"!=typeof e)throw new b(t,"string",e)}const O=m(((e,t,r)=>{if(!i(r,e)){const n=o(s(r,(e=>"string"==typeof e?`'${e}'`:p(e))),", ");throw new w(t,e,"must be one of: "+n)}}));function F(e,t){if("boolean"!=typeof e)throw new b(t,"boolean",e)}function N(e,t,r){return null!=e&&h(e,t)?e[t]:r}const D=m(((e,t,r=null)=>{const i=N(r,"allowArray",!1),o=N(r,"allowFunction",!1);if(!N(r,"nullable",!1)&&null===e||!i&&n(e)||"object"!=typeof e&&(!o||"function"!=typeof e))throw new b(t,"Object",e)})),L=m(((e,t)=>{if(null!=e&&"object"!=typeof e&&"function"!=typeof e)throw new b(t,"a dictionary",e)})),U=m(((e,t,r=0)=>{if(!n(e))throw new b(t,"Array",e);if(e.length{if(!R(e))throw new b(t,["Buffer","TypedArray","DataView"],e)})),M=m(((e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new b(t,"AbortSignal",e)})),B=m(((e,t)=>{if("function"!=typeof e)throw new b(t,"Function",e)})),H=m(((e,t)=>{if("function"!=typeof e||A(e))throw new b(t,"Function",e)})),W=m(((e,t)=>{if(void 0!==e)throw new b(t,"undefined",e)})),$=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function V(e,t){if(void 0===e||!f($,e))throw new w(t,e,'must be an array or string of format "; rel=preload; as=style"')}e.exports={isInt32:function(e){return e===(0|e)},isUint32:function(e){return e===e>>>0},parseFileMode:function(e,t,r){if(void 0===e&&(e=r),"string"==typeof e){if(null===f(T,e))throw new w(t,e,"must be a 32-bit unsigned integer or an octal string");e=d(e,8)}return C(e,t),e},validateArray:U,validateStringArray:function(e,t){U(e,t);for(let r=0;rn||(null!=r||null!=n)&&c(e))throw new _(t,`${null!=r?`>= ${r}`:""}${null!=r&&null!=n?" && ":""}${null!=n?`<= ${n}`:""}`,e)},validateObject:D,validateOneOf:O,validatePlainFunction:H,validatePort:function(e,t="Port",r=!0){if("number"!=typeof e&&"string"!=typeof e||"string"==typeof e&&0===y(e).length||+e!=+e>>>0||e>65535||0===e&&!r)throw new v(t,e,r);return 0|e},validateSignalName:function(e,t="signal"){if(k(e,t),void 0===I[e]){if(void 0!==I[g(e)])throw new S(e+" (signals must use all capital letters)");throw new S(e)}},validateString:k,validateUint32:C,validateUndefined:W,validateUnion:function(e,t,r){if(!i(r,e))throw new b(t,`('${o(r,"|")}')`,e)},validateAbortSignal:M,validateLinkHeaderValue:function(e){if("string"==typeof e)return V(e,"hints"),e;if(n(e)){const t=e.length;let r="";if(0===t)return r;for(let n=0;n; rel=preload; as=style"')}}},5721:function(e,t,r){"use strict";const n=r(2825),i=r(5018),o=n.Readable.destroy;e.exports=n.Readable,e.exports._uint8ArrayToBuffer=n._uint8ArrayToBuffer,e.exports._isUint8Array=n._isUint8Array,e.exports.isDisturbed=n.isDisturbed,e.exports.isErrored=n.isErrored,e.exports.isReadable=n.isReadable,e.exports.Readable=n.Readable,e.exports.Writable=n.Writable,e.exports.Duplex=n.Duplex,e.exports.Transform=n.Transform,e.exports.PassThrough=n.PassThrough,e.exports.addAbortSignal=n.addAbortSignal,e.exports.finished=n.finished,e.exports.destroy=n.destroy,e.exports.destroy=o,e.exports.pipeline=n.pipeline,e.exports.compose=n.compose,Object.defineProperty(n,"promises",{configurable:!0,enumerable:!0,get(){return i}}),e.exports.Stream=n.Stream,e.exports.default=e.exports},8526:function(e,t,r){"use strict";const{format:n,inspect:i,AggregateError:o}=r(6017),s=globalThis.AggregateError||o,a=Symbol("kIsNodeError"),c=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,u={};function d(e,t){if(!e)throw new u.ERR_INTERNAL_ASSERTION(t)}function h(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function f(e,t,r){r||(r=Error);class i extends r{constructor(...r){super(function(e,t,r){if("function"==typeof t)return d(t.length<=r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`),t(...r);const i=(t.match(/%[dfijoOs]/g)||[]).length;return d(i===r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${i}).`),0===r.length?t:n(t,...r)}(e,t,r))}toString(){return`${this.name} [${e}]: ${this.message}`}}Object.defineProperties(i.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${e}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),i.prototype.code=e,i.prototype[a]=!0,u[e]=i}function p(e){const t="__node_internal_"+e.name;return Object.defineProperty(e,"name",{value:t}),e}class g extends Error{constructor(e="The operation was aborted",t=void 0){if(void 0!==t&&"object"!=typeof t)throw new u.ERR_INVALID_ARG_TYPE("options","Object",t);super(e,t),this.code="ABORT_ERR",this.name="AbortError"}}f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",((e,t,r)=>{d("string"==typeof e,"'name' must be a string"),Array.isArray(t)||(t=[t]);let n="The ";e.endsWith(" argument")?n+=`${e} `:n+=`"${e}" ${e.includes(".")?"property":"argument"} `,n+="must be ";const o=[],s=[],a=[];for(const e of t)d("string"==typeof e,"All expected entries have to be of type string"),c.includes(e)?o.push(e.toLowerCase()):l.test(e)?s.push(e):(d("object"!==e,'The value "object" should be written as "Object"'),a.push(e));if(s.length>0){const e=o.indexOf("object");-1!==e&&(o.splice(o,e,1),s.push("Object"))}if(o.length>0){switch(o.length){case 1:n+=`of type ${o[0]}`;break;case 2:n+=`one of type ${o[0]} or ${o[1]}`;break;default:{const e=o.pop();n+=`one of type ${o.join(", ")}, or ${e}`}}(s.length>0||a.length>0)&&(n+=" or ")}if(s.length>0){switch(s.length){case 1:n+=`an instance of ${s[0]}`;break;case 2:n+=`an instance of ${s[0]} or ${s[1]}`;break;default:{const e=s.pop();n+=`an instance of ${s.join(", ")}, or ${e}`}}a.length>0&&(n+=" or ")}switch(a.length){case 0:break;case 1:a[0].toLowerCase()!==a[0]&&(n+="an "),n+=`${a[0]}`;break;case 2:n+=`one of ${a[0]} or ${a[1]}`;break;default:{const e=a.pop();n+=`one of ${a.join(", ")}, or ${e}`}}if(null==r)n+=`. Received ${r}`;else if("function"==typeof r&&r.name)n+=`. Received function ${r.name}`;else if("object"==typeof r){var u;null!==(u=r.constructor)&&void 0!==u&&u.name?n+=`. Received an instance of ${r.constructor.name}`:n+=`. Received ${i(r,{depth:-1})}`}else{let e=i(r,{colors:!1});e.length>25&&(e=`${e.slice(0,25)}...`),n+=`. Received type ${typeof r} (${e})`}return n}),TypeError),f("ERR_INVALID_ARG_VALUE",((e,t,r="is invalid")=>{let n=i(t);return n.length>128&&(n=n.slice(0,128)+"..."),`The ${e.includes(".")?"property":"argument"} '${e}' ${r}. Received ${n}`}),TypeError),f("ERR_INVALID_RETURN_VALUE",((e,t,r)=>{var n;return`Expected ${e} to be returned from the "${t}" function but got ${null!=r&&null!==(n=r.constructor)&&void 0!==n&&n.name?`instance of ${r.constructor.name}`:"type "+typeof r}.`}),TypeError),f("ERR_MISSING_ARGS",((...e)=>{let t;d(e.length>0,"At least one arg needs to be specified");const r=e.length;switch(e=(Array.isArray(e)?e:[e]).map((e=>`"${e}"`)).join(" or "),r){case 1:t+=`The ${e[0]} argument`;break;case 2:t+=`The ${e[0]} and ${e[1]} arguments`;break;default:{const r=e.pop();t+=`The ${e.join(", ")}, and ${r} arguments`}}return`${t} must be specified`}),TypeError),f("ERR_OUT_OF_RANGE",((e,t,r)=>{let n;return d(t,'Missing "range" argument'),Number.isInteger(r)&&Math.abs(r)>2**32?n=h(String(r)):"bigint"==typeof r?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=h(n)),n+="n"):n=i(r),`The value of "${e}" is out of range. It must be ${t}. Received ${n}`}),RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:g,aggregateTwoErrors:p((function(e,t){if(e&&t&&e!==t){if(Array.isArray(t.errors))return t.errors.push(e),t;const r=new s([t,e],t.message);return r.code=t.code,r}return e||t})),hideStackFrames:p,codes:u}},4641:function(e){"use strict";e.exports={ArrayIsArray(e){return Array.isArray(e)},ArrayPrototypeIncludes(e,t){return e.includes(t)},ArrayPrototypeIndexOf(e,t){return e.indexOf(t)},ArrayPrototypeJoin(e,t){return e.join(t)},ArrayPrototypeMap(e,t){return e.map(t)},ArrayPrototypePop(e,t){return e.pop(t)},ArrayPrototypePush(e,t){return e.push(t)},ArrayPrototypeSlice(e,t,r){return e.slice(t,r)},Error:Error,FunctionPrototypeCall(e,t,...r){return e.call(t,...r)},FunctionPrototypeSymbolHasInstance(e,t){return Function.prototype[Symbol.hasInstance].call(e,t)},MathFloor:Math.floor,Number:Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(e,t){return Object.defineProperties(e,t)},ObjectDefineProperty(e,t,r){return Object.defineProperty(e,t,r)},ObjectGetOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)},ObjectKeys(e){return Object.keys(e)},ObjectSetPrototypeOf(e,t){return Object.setPrototypeOf(e,t)},Promise:Promise,PromisePrototypeCatch(e,t){return e.catch(t)},PromisePrototypeThen(e,t,r){return e.then(t,r)},PromiseReject(e){return Promise.reject(e)},PromiseResolve(e){return Promise.resolve(e)},ReflectApply:Reflect.apply,RegExpPrototypeTest(e,t){return e.test(t)},SafeSet:Set,String:String,StringPrototypeSlice(e,t,r){return e.slice(t,r)},StringPrototypeToLowerCase(e){return e.toLowerCase()},StringPrototypeToUpperCase(e){return e.toUpperCase()},StringPrototypeTrim(e){return e.trim()},Symbol:Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(e,t,r){return e.set(t,r)},Boolean:Boolean,Uint8Array:Uint8Array}},6017:function(e,t,r){"use strict";const n=r(8287),{kResistStopPropagation:i,SymbolDispose:o}=r(4641),s=globalThis.AbortSignal||r(5568).AbortSignal,a=globalThis.AbortController||r(5568).AbortController,c=Object.getPrototypeOf((async function(){})).constructor,l=globalThis.Blob||n.Blob,u=void 0!==l?function(e){return e instanceof l}:function(e){return!1},d=(e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new ERR_INVALID_ARG_TYPE(t,"AbortSignal",e)};class h extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError("Expected input to be an Array, got "+typeof e);let t="";for(let r=0;r{e=r,t=n})),resolve:e,reject:t}},promisify(e){return new Promise(((t,r)=>{e(((e,...n)=>e?r(e):t(...n)))}))},debuglog(){return function(){}},format(e,...t){return e.replace(/%([sdifj])/g,(function(...[e,r]){const n=t.shift();return"f"===r?n.toFixed(6):"j"===r?JSON.stringify(n):"s"===r&&"object"==typeof n?`${n.constructor!==Object?n.constructor.name:""} {}`.trim():n.toString()}))},inspect(e){switch(typeof e){case"string":if(e.includes("'")){if(!e.includes('"'))return`"${e}"`;if(!e.includes("`")&&!e.includes("${"))return`\`${e}\``}return`'${e}'`;case"number":return isNaN(e)?"NaN":Object.is(e,-0)?String(e):e;case"bigint":return`${String(e)}n`;case"boolean":case"undefined":return String(e);case"object":return"{}"}},types:{isAsyncFunction(e){return e instanceof c},isArrayBufferView(e){return ArrayBuffer.isView(e)}},isBlob:u,deprecate(e,t){return e},addAbortListener:r(7007).addAbortListener||function(e,t){if(void 0===e)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);let r;return d(e,"signal"),(e=>{if("function"!=typeof e)throw new ERR_INVALID_ARG_TYPE("listener","Function",e)})(t),e.aborted?queueMicrotask((()=>t())):(e.addEventListener("abort",t,{__proto__:null,once:!0,[i]:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,[o](){var e;null===(e=r)||void 0===e||e()}}},AbortSignalAny:s.any||function(e){if(1===e.length)return e[0];const t=new a,r=()=>t.abort();return e.forEach((e=>{d(e,"signals"),e.addEventListener("abort",r,{once:!0})})),t.signal.addEventListener("abort",(()=>{e.forEach((e=>e.removeEventListener("abort",r)))}),{once:!0}),t.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")},2825:function(e,t,r){const{Buffer:n}=r(8287),{ObjectDefineProperty:i,ObjectKeys:o,ReflectApply:s}=r(4641),{promisify:{custom:a}}=r(6017),{streamReturningOperators:c,promiseReturningOperators:l}=r(1284),{codes:{ERR_ILLEGAL_CONSTRUCTOR:u}}=r(8526),d=r(8489),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:f}=r(3920),{pipeline:p}=r(8431),{destroyer:g}=r(7647),y=r(9365),m=r(5018),v=r(136),b=e.exports=r(334).Stream;b.isDestroyed=v.isDestroyed,b.isDisturbed=v.isDisturbed,b.isErrored=v.isErrored,b.isReadable=v.isReadable,b.isWritable=v.isWritable,b.Readable=r(3125);for(const S of o(c)){const E=c[S];function w(...e){if(new.target)throw u();return b.Readable.from(s(E,this,e))}i(w,"name",{__proto__:null,value:E.name}),i(w,"length",{__proto__:null,value:E.length}),i(b.Readable.prototype,S,{__proto__:null,value:w,enumerable:!1,configurable:!0,writable:!0})}for(const A of o(l)){const R=l[A];function w(...e){if(new.target)throw u();return s(R,this,e)}i(w,"name",{__proto__:null,value:R.name}),i(w,"length",{__proto__:null,value:R.length}),i(b.Readable.prototype,A,{__proto__:null,value:w,enumerable:!1,configurable:!0,writable:!0})}b.Writable=r(7221),b.Duplex=r(3559),b.Transform=r(8649),b.PassThrough=r(2091),b.pipeline=p;const{addAbortSignal:_}=r(810);b.addAbortSignal=_,b.finished=y,b.destroy=g,b.compose=d,b.setDefaultHighWaterMark=h,b.getDefaultHighWaterMark=f,i(b,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return m}}),i(p,a,{__proto__:null,enumerable:!0,get(){return m.pipeline}}),i(y,a,{__proto__:null,enumerable:!0,get(){return m.finished}}),b.Stream=b,b._isUint8Array=function(e){return e instanceof Uint8Array},b._uint8ArrayToBuffer=function(e){return n.from(e.buffer,e.byteOffset,e.byteLength)}},5018:function(e,t,r){"use strict";const{ArrayPrototypePop:n,Promise:i}=r(4641),{isIterable:o,isNodeStream:s,isWebStream:a}=r(136),{pipelineImpl:c}=r(8431),{finished:l}=r(9365);r(2825),e.exports={finished:l,pipeline:function(...e){return new i(((t,r)=>{let i,l;const u=e[e.length-1];if(u&&"object"==typeof u&&!s(u)&&!o(u)&&!a(u)){const t=n(e);i=t.signal,l=t.end}c(e,((e,n)=>{e?r(e):t(n)}),{signal:i,end:l})}))}}},2692:function(e,t,r){var n=r(8287),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(o(n,t),t.Buffer=s),s.prototype=Object.create(i.prototype),o(i,s),s.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},s.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},6600:function(e,t,r){"use strict";var n=r(2692).Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=l,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=u,this.end=d,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,r=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function l(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function u(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function d(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0?(i>0&&(e.lastNeed=i-1),i):--n=0?(i>0&&(e.lastNeed=i-2),i):--n=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},8518:function(e,t,r){"use strict";r.r(t),r.d(t,{BlankNode:function(){return T},DataFactory:function(){return E},DefaultGraph:function(){return P},EntityIndex:function(){return fe},Lexer:function(){return m},Literal:function(){return I},NamedNode:function(){return R},Parser:function(){return H},Quad:function(){return O},Reasoner:function(){return be},Store:function(){return pe},StoreFactory:function(){return me},StreamParser:function(){return Se},StreamWriter:function(){return Ee},Term:function(){return A},Triple:function(){return O},Util:function(){return n},Variable:function(){return x},Writer:function(){return oe},default:function(){return Ae},getRulesFromDataset:function(){return ve},termFromId:function(){return C},termToId:function(){return k}});var n={};r.r(n),r.d(n,{inDefaultGraph:function(){return z},isBlankNode:function(){return K},isDefaultGraph:function(){return q},isLiteral:function(){return J},isNamedNode:function(){return V},isVariable:function(){return G},prefix:function(){return Y},prefixes:function(){return Q}});var i=r(8287),o=r(9596),s=r.n(o);const a="http://www.w3.org/1999/02/22-rdf-syntax-ns#",c="http://www.w3.org/2001/XMLSchema#",l="http://www.w3.org/2000/10/swap/";var u={xsd:{decimal:`${c}decimal`,boolean:`${c}boolean`,double:`${c}double`,integer:`${c}integer`,string:`${c}string`},rdf:{type:`${a}type`,nil:`${a}nil`,first:`${a}first`,rest:`${a}rest`,langString:`${a}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${l}reify#forSome`,forAll:`${l}reify#forAll`},log:{implies:`${l}log#implies`}};const{xsd:d}=u,h=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,f={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},p=/[\x00-\x20<>\\"\{\}\|\^\`]/,g={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},y=/$0^/;class m{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const e in this)!(e in g)&&this[e]instanceof RegExp&&(this[e]=y)}else this._n3Mode=!1!==e.n3;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let r=this._input,n=r.length;for(;;){let e,s;for(;e=this._newline.exec(r);)this.comments&&(s=this._comment.exec(e[0]))&&i("comment",s[1],"",this._line,e[0].length),r=r.substr(e[0].length,r.length),n=r.length,this._line++;if(!e&&(e=this._whitespace.exec(r))&&(r=r.substr(e[0].length,r.length)),this._endOfFile.test(r))return t&&(this.comments&&(s=this._comment.exec(r))&&i("comment",s[1],"",this._line,r.length),r=null,i("eof","","",this._line,0)),this._input=r;const a=this._line,c=r[0];let l="",u="",h="",f=null,g=0,y=!1;switch(c){case"^":if(r.length<3)break;if("^"!==r[1]){this._n3Mode&&(g=1,l="^");break}if(this._previousMarker="^^",r=r.substr(2),"<"!==r[0]){y=!0;break}case"<":if(f=this._unescapedIri.exec(r))l="IRI",u=f[1];else if(f=this._iri.exec(r)){if(u=this._unescape(f[1]),null===u||p.test(u))return o(this);l="IRI"}else r.length>1&&"<"===r[1]?(l="<<",g=2):this._n3Mode&&r.length>1&&"="===r[1]&&(l="inverse",g=2,u=">");break;case">":r.length>1&&">"===r[1]&&(l=">>",g=2);break;case"_":((f=this._blank.exec(r))||t&&(f=this._blank.exec(`${r} `)))&&(l="blank",h="_",u=f[1]);break;case'"':if(f=this._simpleQuotedString.exec(r))u=f[1];else if(({value:u,matchLength:g}=this._parseLiteral(r)),null===u)return o(this);null===f&&0===g||(l="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(f=this._simpleApostropheString.exec(r))u=f[1];else if(({value:u,matchLength:g}=this._parseLiteral(r)),null===u)return o(this);null===f&&0===g||(l="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(f=this._variable.exec(r))&&(l="var",u=f[0]);break;case"@":"literal"===this._previousMarker&&(f=this._langcode.exec(r))?(l="langcode",u=f[1]):(f=this._keyword.exec(r))&&(l=f[0]);break;case".":if(1===r.length?t:r[1]<"0"||r[1]>"9"){l=".",g=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(f=this._number.exec(r)||t&&(f=this._number.exec(`${r} `)))&&(l="literal",u=f[0],h="string"==typeof f[1]?d.double:"string"==typeof f[2]?d.decimal:d.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(f=this._sparqlKeyword.exec(r))?l=f[0].toUpperCase():y=!0;break;case"f":case"t":(f=this._boolean.exec(r))?(l="literal",u=f[0],h=d.boolean):y=!0;break;case"a":(f=this._shortPredicates.exec(r))?(l="abbreviation",u="a"):y=!0;break;case"=":this._n3Mode&&r.length>1&&(l="abbreviation",">"!==r[1]?(g=1,u="="):(g=2,u=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(g=1,l=c);break;case"{":!this._lineMode&&r.length>=2&&("|"===r[1]?(l="{|",g=2):(l=c,g=1));break;case"|":r.length>=2&&"}"===r[1]&&(l="|}",g=2);break;default:y=!0}if(y&&("@prefix"!==this._previousMarker&&"PREFIX"!==this._previousMarker||!(f=this._prefix.exec(r))?((f=this._prefixed.exec(r))||t&&(f=this._prefixed.exec(`${r} `)))&&(l="prefixed",h=f[1]||"",u=this._unescape(f[2])):(l="prefix",u=f[1]||"")),"^^"===this._previousMarker)switch(l){case"prefixed":l="type";break;case"IRI":l="typeIRI";break;default:l=""}if(!l)return t||!/^'''|^"""/.test(r)&&/\n|\r/.test(r)?o(this):this._input=r;const m=g||f[0].length,v=i(l,u,h,a,m);this.previousToken=v,this._previousMarker=l,r=r.substr(m,r.length)}function i(t,i,o,s,a){const c=r?n-r.length:n,l={type:t,value:i,prefix:o,line:s,start:c,end:c+a};return e(null,l),l}function o(t){e(t._syntaxError(/^\S*/.exec(r)[0]))}}_unescape(e){let t=!1;const r=e.replace(h,((e,r,n,i)=>{if("string"==typeof r)return String.fromCharCode(Number.parseInt(r,16));if("string"==typeof n){let e=Number.parseInt(n,16);return e<=65535?String.fromCharCode(Number.parseInt(n,16)):String.fromCharCode(55296+((e-=65536)>>10),56320+(1023&e))}return i in f?f[i]:(t=!0,"")}));return t?null:r}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],r=t.length;let n=Math.max(this._literalClosingPos,r);for(;(n=e.indexOf(t,n))>0;){let t=0;for(;"\\"===e[n-t-1];)t++;if(t%2==0){const t=e.substring(r,n),i=t.split(/\r\n|\r|\n/).length-1,o=n+r;if(1===r&&0!==i||3===r&&this._lineMode)break;return this._line+=i,{value:this._unescape(t),matchLength:o}}n++}this._literalClosingPos=e.length-r+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\ufeff")?e.substr(1):e}tokenize(e,t){if(this._line=1,"string"==typeof e){if(this._input=this._readStartingBom(e),"function"!=typeof t){const e=[];let t;if(this._tokenizeToEnd(((r,n)=>r?t=r:e.push(n)),!0),t)throw t;return e}s()((()=>this._tokenizeToEnd(t,!0)))}else this._pendingBuffer=null,"function"==typeof e.setEncoding&&e.setEncoding("utf8"),e.on("data",(e=>{null!==this._input&&0!==e.length&&(this._pendingBuffer&&(e=i.Buffer.concat([this._pendingBuffer,e]),this._pendingBuffer=null),128&e[e.length-1]?this._pendingBuffer=e:(void 0===this._input?this._input=this._readStartingBom("string"==typeof e?e:e.toString()):this._input+=e,this._tokenizeToEnd(t,!1)))})),e.on("end",(()=>{"string"==typeof this._input&&this._tokenizeToEnd(t,!0)})),e.on("error",t)}}const{rdf:v,xsd:b}=u;let w,_=0;const S={namedNode:F,blankNode:N,variable:L,literal:D,defaultGraph:function(){return w},quad:U,triple:U,fromTerm:j,fromQuad:M};var E=S;class A{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof A?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}class R extends A{get termType(){return"NamedNode"}}class I extends A{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let t=e.lastIndexOf('"')+1;return t0?"INF":"-INF")))),""===r||r===b.string?new I(`"${e}"`):new I(`"${e}"^^${r}`)}function L(e){return new x(e)}function U(e,t,r,n){return new O(e,t,r,n)}function j(e){if(e instanceof A)return e;switch(e.termType){case"NamedNode":return F(e.value);case"BlankNode":return N(e.value);case"Variable":return L(e.value);case"DefaultGraph":return w;case"Literal":return D(e.value,e.language||e.datatype);case"Quad":return M(e);default:throw new Error(`Unexpected termType: ${e.termType}`)}}function M(e){if(e instanceof O)return e;if("Quad"!==e.termType)throw new Error(`Unexpected termType: ${e.termType}`);return U(j(e.subject),j(e.predicate),j(e.object),j(e.graph))}let B=0;class H{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&$(this,e.factory);const t="string"==typeof e.format?e.format.match(/\w*$/)[0].toLowerCase():"",r=/turtle/.test(t),n=/trig/.test(t),i=/triple/.test(t),o=/quad/.test(t),s=this._n3Mode=/n3/.test(t),a=i||o;(this._supportsNamedGraphs=!(r||s))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||n||i||s),this._supportsRDFStar=""===t||/star|\*$/.test(t),a&&(this._resolveRelativeIRI=e=>null),this._blankNodePrefix="string"!=typeof e.blankNodePrefix?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new m({lineMode:a,n3:s}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){B=0}_setBase(e){if(e){const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}else this._base="",this._basePath=""}_saveContext(e,t,r,n,i){const o=this._n3Mode;this._contextStack.push({type:e,subject:r,predicate:n,object:i,graph:t,inverse:!!o&&this._inversePredicate,blankPrefix:o?this._prefixes._:"",quantified:o?this._quantified:null}),o&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const r=this._contextStack.pop();if(!r||r.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=r.subject,this._predicate=r.predicate,this._object=r.object,this._graph=r.graph,this._n3Mode&&(this._inversePredicate=r.inverse,this._prefixes._=r.blankPrefix,this._quantified=r.quantified)}_readInTopContext(e){switch(e.type){case"eof":return null!==this._graph?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let r;switch(e.type){case"IRI":case"typeIRI":const t=this._resolveIRI(e.value);if(null===t)return this._error("Invalid IRI",e);r=this._factory.namedNode(t);break;case"type":case"prefixed":const n=this._prefixes[e.prefix];if(void 0===n)return this._error(`Undefined prefix "${e.prefix}:"`,e);r=this._factory.namedNode(n+e.value);break;case"blank":r=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":r=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&r.id in this._quantified&&(r=this._quantified[r.id]),r}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(0===e.prefix.length)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if(void 0===(this._subject=this._readEntity(e)))return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return null===this._predicate?this._error(`Unexpected ${t}`,e):(this._subject=null,"]"===t?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return null!==this._predicate?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if(void 0===(this._predicate=this._readEntity(e)))return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(0===e.prefix.length)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if(void 0===(this._object=this._readEntity(e)))return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return"{"===e.type?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return"{"!==e.type?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return"]"===e.type?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if("]"!==e.type)return this._readBlankNodePunctuation(e);null!==this._subject&&this._emit(this._subject,this._predicate,this._object,this._graph);const t=null===this._predicate;return this._restoreContext("blank",e),null!==this._object?this._getContextEndReader():null!==this._predicate?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,r=null,n=this._readListItem;const i=this._subject,o=this._contextStack,s=o[o.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),n=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),0!==o.length&&"list"===o[o.length-1].type&&this._emit(this._subject,this._predicate,this._object,this._graph),null===this._predicate){if(n=this._readPredicate,this._subject===this.RDF_NIL)return n}else if(n=this._getContextEndReader(),this._object===this.RDF_NIL)return n;r=this.RDF_NIL;break;case"literal":0===e.prefix.length?(this._literalValue=e.value,n=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),n=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if(void 0===(t=this._readEntity(e)))return}if(null===r&&(this._subject=r=this._factory.blankNode()),null===i?null===s.predicate?s.subject=r:s.object=r:this._emit(i,this.RDF_REST,r,this._graph),null!==t){if(this._n3Mode&&("IRI"===e.type||"prefixed"===e.type))return this._saveContext("item",this._graph,r,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(r,this.RDF_FIRST,t,this._graph)}return n}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const r=this._readEntity(e);if(void 0===r)return;t=this._factory.literal(this._literalValue,r),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){const r=this._completeLiteral(e);if(r)return this._object=r.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),null===r.token?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(r.token))}_readFormulaTail(e){return"}"!==e.type?this._readPunctuation(e):(null!==this._subject&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),null===this._object?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,r=this._graph;const n=this._subject,i=this._inversePredicate;switch(e.type){case"}":if(null===this._graph)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,t=this._contextStack.length?this._readSubject:this._readInTopContext,i&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const o=this._predicate,s=this._object;this._subject=this._factory.quad(n,o,s,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if("Quad"!==this._subject.termType)return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&null===this._graph&&void 0!==(r=this._readEntity(e))){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(null!==n){const e=this._predicate,t=this._object;i?this._emit(t,e,n,r):this._emit(n,e,t,r)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return"."!==e.type?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return"prefix"!==e.type?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if("IRI"!==e.type)return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){const t="IRI"===e.type&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return"]"!==e.type?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):"."!==e.type?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if(void 0!==(t=this._readEntity(e,!0)))break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(null===this._subject?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return","===e.type?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._contextStack,r=t.length&&t[t.length-1];if(r&&"item"===r.type){const t=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,t,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,r;const n=this._factory.blankNode();if(void 0!==(r=this._readEntity(e)))return null===this._predicate?(t=this._subject,this._subject=n):(t=this._object,this._object=n),this._emit(t,r,n,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let r,n;if(void 0!==(r=this._readEntity(e)))return null===this._predicate?(n=this._subject,this._subject=t):(n=this._object,this._object=t),this._emit(t,r,n,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return">>"!==e.type?this._supportsQuads&&null===this._graph&&void 0!==(this._graph=this._readEntity(e))?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(">>"!==e.type)return this._error(`Expected >> but got ${e.type}`,e);const t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),null===this._subject?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,r,n){this._callback(null,this._factory.quad(e,t,r,n||this.DEFAULTGRAPH))}_error(e,t){const r=new Error(`${e} on line ${t.line}.`);r.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(r),this._callback=W}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return("/"===e[1]?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const t=e.length;let r="",n=-1,i=-1,o=0,s="/";for(;n=i&&(r=r.substr(0,o)),"/"!==s)return`${r}/${e.substr(n+1)}`;o=n+1}}}s=e[++n]}return r+e.substring(o)}parse(e,t,r){let n,i,o;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(n=t.onQuad,i=t.onPrefix,o=t.onComment):(n=t,i=r),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${B++}_`,this._prefixCallback=i||W,this._inversePredicate=!1,this._quantified=Object.create(null),!n){const t=[];let r;if(this._callback=(e,n)=>{e?r=e:n&&t.push(n)},this._lexer.tokenize(e).every((e=>this._readCallback=this._readCallback(e))),r)throw r;return t}let s=(e,t)=>{null!==e?(this._callback(e),this._callback=W):this._readCallback&&(this._readCallback=this._readCallback(t))};o&&(this._lexer.comments=!0,s=(e,t)=>{null!==e?(this._callback(e),this._callback=W):this._readCallback&&("comment"===t.type?o(t.value):this._readCallback=this._readCallback(t))}),this._callback=n,this._lexer.tokenize(e,s)}}function W(){}function $(e,t){e._factory=t,e.DEFAULTGRAPH=t.defaultGraph(),e.RDF_FIRST=t.namedNode(u.rdf.first),e.RDF_REST=t.namedNode(u.rdf.rest),e.RDF_NIL=t.namedNode(u.rdf.nil),e.N3_FORALL=t.namedNode(u.r.forAll),e.N3_FORSOME=t.namedNode(u.r.forSome),e.ABBREVIATIONS={a:t.namedNode(u.rdf.type),"=":t.namedNode(u.owl.sameAs),">":t.namedNode(u.log.implies)},e.QUANTIFIERS_GRAPH=t.namedNode("urn:n3:quantifiers")}function V(e){return!!e&&"NamedNode"===e.termType}function K(e){return!!e&&"BlankNode"===e.termType}function J(e){return!!e&&"Literal"===e.termType}function G(e){return!!e&&"Variable"===e.termType}function q(e){return!!e&&"DefaultGraph"===e.termType}function z(e){return q(e.graph)}function Y(e,t){return Q({"":e.value||e},t)("")}function Q(e,t){const r=Object.create(null);for(const t in e)n(t,e[t]);function n(e,n){if("string"==typeof n){const i=Object.create(null);r[e]=e=>i[e]||(i[e]=t.namedNode(n+e))}else if(!(e in r))throw new Error(`Unknown prefix: ${e}`);return r[e]}return t=t||E,n}$(H.prototype,E);const X=E.defaultGraph(),{rdf:Z,xsd:ee}=u,te=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,re=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,ne={"\\":"\\\\",'"':'\\"',"\t":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class ie extends A{equals(e){return e===this}}class oe{constructor(e,t){if(this._prefixRegex=/$0^/,e&&"function"!=typeof e.write&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=void 0===t.end||!!t.end;else{let e="";this._outputStream={write(t,r,n){e+=t,n&&n()},end:t=>{t&&t(null,e)}},this._endStream=!0}this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine):(this._lineMode=!1,this._graph=X,this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes),t.baseIRI&&(this._baseMatcher=new RegExp(`^${ae(t.baseIRI)}${t.baseIRI.endsWith("/")?"":"[#?]"}`),this._baseLength=t.baseIRI.length))}get _inDefaultGraph(){return X.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_writeQuad(e,t,r,n,i){try{n.equals(this._graph)||(this._write((null===this._subject?"":this._inDefaultGraph?".\n":"\n}\n")+(X.equals(n)?"":`${this._encodeIriOrBlank(n)} {\n`)),this._graph=n,this._subject=null),e.equals(this._subject)?t.equals(this._predicate)?this._write(`, ${this._encodeObject(r)}`,i):this._write(`;\n ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,i):this._write(`${(null===this._subject?"":".\n")+this._encodeSubject(this._subject=e)} ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,i)}catch(e){i&&i(e)}}_writeQuadLine(e,t,r,n,i){delete this._prefixMatch,this._write(this.quadToString(e,t,r,n),i)}quadToString(e,t,r,n){return`${this._encodeSubject(e)} ${this._encodeIriOrBlank(t)} ${this._encodeObject(r)}${n&&n.value?` ${this._encodeIriOrBlank(n)} .\n`:" .\n"}`}quadsToString(e){let t="";for(const r of e)t+=this.quadToString(r.subject,r.predicate,r.object,r.graph);return t}_encodeSubject(e){return"Quad"===e.termType?this._encodeQuad(e):this._encodeIriOrBlank(e)}_encodeIriOrBlank(e){if("NamedNode"!==e.termType)return this._lists&&e.value in this._lists&&(e=this.list(this._lists[e.value])),"id"in e?e.id:`_:${e.value}`;let t=e.value;this._baseMatcher&&this._baseMatcher.test(t)&&(t=t.substr(this._baseLength)),te.test(t)&&(t=t.replace(re,se));const r=this._prefixRegex.exec(t);return r?r[1]?this._prefixIRIs[r[1]]+r[2]:t:`<${t}>`}_encodeLiteral(e){let t=e.value;if(te.test(t)&&(t=t.replace(re,se)),e.language)return`"${t}"@${e.language}`;if(this._lineMode){if(e.datatype.value===ee.string)return`"${t}"`}else switch(e.datatype.value){case ee.string:return`"${t}"`;case ee.boolean:if("true"===t||"false"===t)return t;break;case ee.integer:if(/^[+-]?\d+$/.test(t))return t;break;case ee.decimal:if(/^[+-]?\d*\.\d+$/.test(t))return t;break;case ee.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(t))return t}return`"${t}"^^${this._encodeIriOrBlank(e.datatype)}`}_encodePredicate(e){return e.value===Z.type?"a":this._encodeIriOrBlank(e)}_encodeObject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeQuad({subject:e,predicate:t,object:r,graph:n}){return`<<${this._encodeSubject(e)} ${this._encodePredicate(t)} ${this._encodeObject(r)}${q(n)?"":` ${this._encodeIriOrBlank(n)}`}>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(e,t,r,n,i){void 0===r?this._writeQuad(e.subject,e.predicate,e.object,e.graph,t):"function"==typeof n?this._writeQuad(e,t,r,X,n):this._writeQuad(e,t,r,n||X,i)}addQuads(e){for(let t=0;t.\n`)}if(r){let e="",t="";for(const r in this._prefixIRIs)e+=e?`|${r}`:r,t+=(t?"|":"")+this._prefixIRIs[r];e=ae(e),this._prefixRegex=new RegExp(`^(?:${t})[^/]*$|^(${e})([_a-zA-Z0-9][\\-_a-zA-Z0-9]*)$`)}this._write(r?"\n":"",t)}blank(e,t){let r,n,i=e;switch(void 0===e?i=[]:e.termType?i=[{predicate:e,object:t}]:"length"in e||(i=[e]),n=i.length){case 0:return new ie("[]");case 1:if(r=i[0],!(r.object instanceof ie))return new ie(`[ ${this._encodePredicate(r.predicate)} ${this._encodeObject(r.object)} ]`);default:let t="[";for(let o=0;o{t=null,e(r,n)});if(this._endStream)try{return this._outputStream.end(t)}catch(e){}t&&t()}}function se(e){let t=ne[e];return void 0===t&&(1===e.length?(t=e.charCodeAt(0).toString(16),t="\\u0000".substr(0,6-t.length)+t):(t=(1024*(e.charCodeAt(0)-55296)+e.charCodeAt(1)+9216).toString(16),t="\\U00000000".substr(0,10-t.length)+t)),t}function ae(e){return e.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}var ce=r(5721);const le=Symbol("iter");function ue(e,t,r=4){if(0===r)return Object.assign(e,t);for(const n in t)e[n]=ue(e[n]||Object.create(null),t[n],r-1);return e}function de(e,t,r=4){let n=!1;for(const i in e)if(i in t){const o=0===r?null:de(e[i],t[i],r-1);if(!1!==o)n=n||Object.create(null),n[i]=o;else if(3===r)return!1}return n}function he(e,t,r=4){let n=!1;for(const i in e)if(i in t){if(0!==r){const o=he(e[i],t[i],r-1);if(!1!==o)n=n||Object.create(null),n[i]=o;else if(3===r)return!1}}else n=n||Object.create(null),n[i]=0===r?null:ue({},e[i],r-1);return n}class fe{constructor(e={}){this._id=1,this._ids=Object.create(null),this._ids[""]=1,this._entities=Object.create(null),this._entities[1]="",this._blankNodeIndex=0,this._factory=e.factory||E}_termFromId(e){if("."===e[0]){const t=this._entities,r=e.split(".");return this._factory.quad(this._termFromId(t[r[1]]),this._termFromId(t[r[2]]),this._termFromId(t[r[3]]),r[4]&&this._termFromId(t[r[4]]))}return C(e,this._factory)}_termToNumericId(e){if("Quad"===e.termType){const t=this._termToNumericId(e.subject),r=this._termToNumericId(e.predicate),n=this._termToNumericId(e.object);let i;return t&&r&&n&&(q(e.graph)||(i=this._termToNumericId(e.graph)))&&this._ids[i?`.${t}.${r}.${n}.${i}`:`.${t}.${r}.${n}`]}return this._ids[k(e)]}_termToNewNumericId(e){const t=e&&"Quad"===e.termType?`.${this._termToNewNumericId(e.subject)}.${this._termToNewNumericId(e.predicate)}.${this._termToNewNumericId(e.object)}${q(e.graph)?"":`.${this._termToNewNumericId(e.graph)}`}`:k(e);return this._ids[t]||(this._ids[this._entities[++this._id]=t]=this._id)}createBlankNode(e){let t,r;if(e)for(t=e=`_:${e}`,r=1;this._ids[t];)t=e+r++;else do{t="_:b"+this._blankNodeIndex++}while(this._ids[t]);return this._ids[t]=++this._id,this._entities[this._id]=t,this._factory.blankNode(t.substr(2))}}class pe{constructor(e,t){this._size=0,this._graphs=Object.create(null),t||!e||e[0]||(t=e,e=null),t=t||{},this._factory=t.factory||E,this._entityIndex=t.entityIndex||new fe({factory:this._factory}),this._entities=this._entityIndex._entities,this._termFromId=this._entityIndex._termFromId.bind(this._entityIndex),this._termToNumericId=this._entityIndex._termToNumericId.bind(this._entityIndex),this._termToNewNumericId=this._entityIndex._termToNewNumericId.bind(this._entityIndex),e&&this.addQuads(e)}get size(){let e=this._size;if(null!==e)return e;e=0;const t=this._graphs;let r,n;for(const i in t)for(const o in r=t[i].subjects)for(const t in n=r[o])e+=Object.keys(n[t]).length;return this._size=e}_addToIndex(e,t,r,n){const i=e[t]||(e[t]={}),o=i[r]||(i[r]={}),s=n in o;return s||(o[n]=null),!s}_removeFromIndex(e,t,r,n){const i=e[t],o=i[r];delete o[n];for(const e in o)return;delete i[r];for(const e in i)return;delete e[t]}*_findInIndex(e,t,r,n,i,o,s,a){let c,l,u;const d=this._entities,h=this._termFromId(d[a]),f={subject:null,predicate:null,object:null};t&&((c=e,e={})[t]=c[t]);for(const t in e)if(l=e[t]){f[i]=this._termFromId(d[t]),r&&((c=l,l={})[r]=c[r]);for(const e in l)if(u=l[e]){f[o]=this._termFromId(d[e]);const t=n?n in u?[n]:[]:Object.keys(u);for(let e=0;e{r in t||(t[r]=!0,e(this._termFromId(this._entities[r],this._factory)))}}add(e){return this.addQuad(e),this}addQuad(e,t,r,n){t||(n=e.graph,r=e.object,t=e.predicate,e=e.subject),n=n?this._termToNewNumericId(n):1;let i=this._graphs[n];return i||(i=this._graphs[n]={subjects:{},predicates:{},objects:{}},Object.freeze(i)),e=this._termToNewNumericId(e),t=this._termToNewNumericId(t),r=this._termToNewNumericId(r),!!this._addToIndex(i.subjects,e,t,r)&&(this._addToIndex(i.predicates,t,r,e),this._addToIndex(i.objects,r,e,t),this._size=null,!0)}addQuads(e){for(let t=0;t{this.addQuad(e)})),e}removeQuad(e,t,r,n){t||({subject:e,predicate:t,object:r,graph:n}=e),n=n?this._termToNumericId(n):1;const i=this._graphs;let o,s,a;if(!((e=e&&this._termToNumericId(e))&&(t=t&&this._termToNumericId(t))&&(r=r&&this._termToNumericId(r))&&(o=i[n])&&(s=o.subjects[e])&&(a=s[t])&&r in a))return!1;for(e in this._removeFromIndex(o.subjects,e,t,r),this._removeFromIndex(o.predicates,t,r,e),this._removeFromIndex(o.objects,r,e,t),null!==this._size&&this._size--,o.subjects)return!0;return delete i[n],!0}removeQuads(e){for(let t=0;t{this.removeQuad(e)})),e}removeMatches(e,t,r,n){const i=new ce.Readable({objectMode:!0}),o=this.readQuads(e,t,r,n);return i._read=e=>{for(;--e>=0;){const{done:e,value:t}=o.next();if(e)return void i.push(null);i.push(t)}},this.remove(i)}deleteGraph(e){return this.removeMatches(null,null,null,e)}getQuads(e,t,r,n){return[...this.readQuads(e,t,r,n)]}*readQuads(e,t,r,n){const i=this._getGraphs(n);let o,s,a,c;if(!(e&&!(s=this._termToNumericId(e))||t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r))))for(const e in i)(o=i[e])&&(s?c?yield*this._findInIndex(o.objects,c,s,a,"object","subject","predicate",e):yield*this._findInIndex(o.subjects,s,a,null,"subject","predicate","object",e):a?yield*this._findInIndex(o.predicates,a,c,null,"predicate","object","subject",e):c?yield*this._findInIndex(o.objects,c,null,null,"object","subject","predicate",e):yield*this._findInIndex(o.subjects,null,null,null,"subject","predicate","object",e))}match(e,t,r,n){return new ye(this,e,t,r,n,{entityIndex:this._entityIndex})}countQuads(e,t,r,n){const i=this._getGraphs(n);let o,s,a,c,l=0;if(e&&!(s=this._termToNumericId(e))||t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r)))return 0;for(const n in i)(o=i[n])&&(l+=e?r?this._countInIndex(o.objects,c,s,a):this._countInIndex(o.subjects,s,a,c):t?this._countInIndex(o.predicates,a,c,s):this._countInIndex(o.objects,c,s,a));return l}forEach(e,t,r,n,i){this.some((t=>(e(t,this),!1)),t,r,n,i)}every(e,t,r,n,i){return!this.some((t=>!e(t,this)),t,r,n,i)}some(e,t,r,n,i){for(const o of this.readQuads(t,r,n,i))if(e(o))return!0;return!1}getSubjects(e,t,r){const n=[];return this.forSubjects((e=>{n.push(e)}),e,t,r),n}forSubjects(e,t,r,n){const i=this._getGraphs(n);let o,s,a;if(e=this._uniqueEntities(e),!(t&&!(s=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(o=i[n])&&(s?a?this._loopBy2Keys(o.predicates,s,a,e):this._loopByKey1(o.subjects,s,e):a?this._loopByKey0(o.objects,a,e):this._loop(o.subjects,e))}getPredicates(e,t,r){const n=[];return this.forPredicates((e=>{n.push(e)}),e,t,r),n}forPredicates(e,t,r,n){const i=this._getGraphs(n);let o,s,a;if(e=this._uniqueEntities(e),!(t&&!(s=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(o=i[n])&&(s?a?this._loopBy2Keys(o.objects,a,s,e):this._loopByKey0(o.subjects,s,e):a?this._loopByKey1(o.predicates,a,e):this._loop(o.predicates,e))}getObjects(e,t,r){const n=[];return this.forObjects((e=>{n.push(e)}),e,t,r),n}forObjects(e,t,r,n){const i=this._getGraphs(n);let o,s,a;if(e=this._uniqueEntities(e),!(t&&!(s=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(o=i[n])&&(s?a?this._loopBy2Keys(o.subjects,s,a,e):this._loopByKey1(o.objects,s,e):a?this._loopByKey0(o.predicates,a,e):this._loop(o.objects,e))}getGraphs(e,t,r){const n=[];return this.forGraphs((e=>{n.push(e)}),e,t,r),n}forGraphs(e,t,r,n){for(const i in this._graphs)this.some((t=>(e(t.graph),!0)),t,r,n,this._termFromId(this._entities[i]))}createBlankNode(e){return this._entityIndex.createBlankNode(e)}extractLists({remove:e=!1,ignoreErrors:t=!1}={}){const r={},n=t?()=>!0:(e,t)=>{throw new Error(`${e.value} ${t}`)},i=this.getQuads(null,u.rdf.rest,u.rdf.nil,null),o=e?[...i]:[];return i.forEach((t=>{const i=[];let s,a,c=!1;const l=t.graph;let d=t.subject;for(;d&&!c;){const e=this.getQuads(null,null,d,null),t=this.getQuads(d,null,null,null);let r,h=null,f=null,p=null;for(let i=0;ithis.has(e)));const t=this._graphs,r=e._graphs;let n,i,o,s,a;for(const e in r){if(!(n=t[e]))return!1;n=n.subjects;for(const t in i=r[e].subjects){if(!(o=n[t]))return!1;for(const e in s=i[t]){if(!(a=o[e]))return!1;for(const t in s[e])if(!(t in a))return!1}}}return!0}deleteMatches(e,t,r,n){for(const i of this.match(e,t,r,n))this.removeQuad(i);return this}difference(e){if(e&&e instanceof ye&&(e=e.filtered),e===this)return new pe({entityIndex:this._entityIndex});if(e instanceof pe&&e._entityIndex===this._entityIndex){const t=new pe({entityIndex:this._entityIndex}),r=he(this._graphs,e._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter((t=>!e.has(t)))}equals(e){return e instanceof ye&&(e=e.filtered),e===this||this.size===e.size&&this.contains(e)}filter(e){const t=new pe({entityIndex:this._entityIndex});for(const r of this)e(r,this)&&t.add(r);return t}intersection(e){if(e instanceof ye&&(e=e.filtered),e===this){const e=new pe({entityIndex:this._entityIndex});return e._graphs=ue(Object.create(null),this._graphs),e._size=this._size,e}if(e instanceof pe&&this._entityIndex===e._entityIndex){const t=new pe({entityIndex:this._entityIndex}),r=de(e._graphs,this._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter((t=>e.has(t)))}map(e){const t=new pe({entityIndex:this._entityIndex});for(const r of this)t.add(e(r,this));return t}reduce(e,t){const r=this.readQuads();let n=void 0===t?r.next().value:t;for(const t of r)n=e(n,t,this);return n}toArray(){return this.getQuads()}toCanonical(){throw new Error("not implemented")}toStream(){return this.match()}toString(){return(new oe).quadsToString(this)}union(e){const t=new pe({entityIndex:this._entityIndex});return t._graphs=ue(Object.create(null),this._graphs),t._size=this._size,t.addAll(e),t}*[Symbol.iterator](){yield*this.readQuads()}}function ge(e,t,r=0){const n=t[r];if(n&&!(n in e))return!1;let i=!1;for(const o in n?{[n]:e[n]}:e){const n=2===r?null:ge(e[o],t,r+1);!1!==n&&(i=i||Object.create(null),i[o]=n)}return i}class ye extends ce.Readable{constructor(e,t,r,n,i,o){super({objectMode:!0}),Object.assign(this,{n3Store:e,subject:t,predicate:r,object:n,graph:i,options:o})}get filtered(){if(!this._filtered){const{n3Store:e,graph:t,object:r,predicate:n,subject:i}=this,o=this._filtered=new pe({factory:e._factory,entityIndex:this.options.entityIndex});let s,a,c;if(i&&!(s=o._termToNumericId(i))||n&&!(a=o._termToNumericId(n))||r&&!(c=o._termToNumericId(r)))return o;const l=e._getGraphs(t);for(const e in l){let t,r,n;!s&&a?(r=ge(l[e].predicates,[a,c,s]))&&(t=ge(l[e].subjects,[s,a,c]),n=ge(l[e].objects,[c,s,a])):c?(n=ge(l[e].objects,[c,s,a]))&&(t=ge(l[e].subjects,[s,a,c]),r=ge(l[e].predicates,[a,c,s])):(t=ge(l[e].subjects,[s,a,c]))&&(r=ge(l[e].predicates,[a,c,s]),n=ge(l[e].objects,[c,s,a])),t&&(o._graphs[e]={subjects:t,predicates:r,objects:n})}o._size=null}return this._filtered}get size(){return this.filtered.size}_read(e){e>0&&!this[le]&&(this[le]=this[Symbol.iterator]());const t=this[le];for(;--e>=0;){const{done:e,value:r}=t.next();if(e)return void this.push(null);this.push(r)}}addAll(e){return this.filtered.addAll(e)}contains(e){return this.filtered.contains(e)}deleteMatches(e,t,r,n){return this.filtered.deleteMatches(e,t,r,n)}difference(e){return this.filtered.difference(e)}equals(e){return this.filtered.equals(e)}every(e,t,r,n,i){return this.filtered.every(e,t,r,n,i)}filter(e){return this.filtered.filter(e)}forEach(e,t,r,n,i){return this.filtered.forEach(e,t,r,n,i)}import(e){return this.filtered.import(e)}intersection(e){return this.filtered.intersection(e)}map(e){return this.filtered.map(e)}some(e,t,r,n,i){return this.filtered.some(e,t,r,n,i)}toCanonical(){return this.filtered.toCanonical()}toStream(){return this._filtered?this._filtered.toStream():this.n3Store.match(this.subject,this.predicate,this.object,this.graph)}union(e){return this._filtered?this._filtered.union(e):this.n3Store.match(this.subject,this.predicate,this.object,this.graph).addAll(e)}toArray(){return this._filtered?this._filtered.toArray():this.n3Store.getQuads(this.subject,this.predicate,this.object,this.graph)}reduce(e,t){return this.filtered.reduce(e,t)}toString(){return(new oe).quadsToString(this)}add(e){return this.filtered.add(e)}delete(e){return this.filtered.delete(e)}has(e){return this.filtered.has(e)}match(e,t,r,n){return new ye(this.filtered,e,t,r,n,this.options)}*[Symbol.iterator](){yield*this._filtered||this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}}class me{dataset(e){return new pe(e)}}function ve(e){const t=[];for(const{subject:r,object:n}of e.match(null,E.namedNode("http://www.w3.org/2000/10/swap/log#implies"),null,E.defaultGraph())){const i=[...e.match(null,null,null,r)],o=[...e.match(null,null,null,n)];t.push({premise:i,conclusion:o})}return t}class be{constructor(e){this._store=e}_add(e,t,r,n,i){this._store._addToIndex(n.subjects,e,t,r)&&(this._store._addToIndex(n.predicates,t,r,e),this._store._addToIndex(n.objects,r,e,t),i())}_evaluatePremise(e,t,r,n=0){let i,o,s,a,c;const[l,u,d]=e.premise[n].value,h=t[e.premise[n].content],f=!(s=l.value);for(s in f?h:{[s]:h[s]})if(a=h[s]){for(s in f&&(l.value=Number(s)),i=!(s=u.value),i?a:{[s]:a[s]})if(c=a[s]){for(s in i&&(u.value=Number(s)),o=!(s=d.value),o?c:{[s]:c[s]})o&&(d.value=Number(s)),n===e.premise.length-1?e.conclusion.forEach((e=>{this._add(e.subject.value,e.predicate.value,e.object.value,t,(()=>{r(e)}))})):this._evaluatePremise(e,t,r,n+1);o&&(d.value=null)}i&&(u.value=null)}f&&(l.value=null)}_evaluateRules(e,t,r){for(let n=0;n{r.push([e.subject.value,e.predicate.value,e.object.value,t])}))}const i=e=>{e.forEach((e=>{this._add(e.subject.value,e.predicate.value,e.object.value,t,(()=>{n(e)}))}))};let o;for(this._evaluateRules(e,t,n);void 0!==(o=r.pop());){const[e,r,s,a]=o,c=a.basePremise.subject.value;c||(a.basePremise.subject.value=e);const l=a.basePremise.predicate.value;l||(a.basePremise.predicate.value=r);const u=a.basePremise.object.value;u||(a.basePremise.object.value=s),0===a.premise.length?i(a.conclusion):this._evaluatePremise(a,t,n),c||(a.basePremise.subject.value=null),l||(a.basePremise.predicate.value=null),u||(a.basePremise.object.value=null)}}_createRule({premise:e,conclusion:t}){const r={},n=e=>"Variable"===e.termType?r[e.value]=r[e.value]||{}:{value:this._store._termToNewNumericId(e)},i=e=>({subject:n(e.subject),predicate:n(e.predicate),object:n(e.object)});return{premise:e.map((e=>i(e))),conclusion:t.map((e=>i(e))),variables:Object.values(r)}}reason(e){Array.isArray(e)||(e=ve(e)),e=e.map((e=>this._createRule(e)));for(const t of e)for(const r of e)for(let e=0;e{e.value=null}))}}for(const t of e){const e=new Set;t.premise=t.premise.map((t=>we(t,e)))}const t=this._store._getGraphs();for(const r in t)this._reasonGraphNaive(e,t[r]);this._store._size=null}}function we({subject:e,predicate:t,object:r},n){const i=e.value||n.has(e)||(n.add(e),!1),o=t.value||n.has(t)||(n.add(t),!1),s=r.value||n.has(r)||(n.add(r),!1);return!i&&o?{content:"predicates",value:[t,r,e]}:s?{content:"objects",value:[r,e,t]}:{content:"subjects",value:[e,t,r]}}function _e(e,t){return null===e.value&&(e.value=t.value),e.value===t.value}class Se extends ce.Transform{constructor(e){super({decodeStrings:!0}),this._readableState.objectMode=!0;const t=new H(e);let r,n;const i={onQuad:(e,t)=>{e&&this.emit("error",e)||t&&this.push(t)},onPrefix:(e,t)=>{this.emit("prefix",e,t)}};e&&e.comments&&(i.onComment=e=>{this.emit("comment",e)}),t.parse({on:(e,t)=>{switch(e){case"data":r=t;break;case"end":n=t}}},i),this._transform=(e,t,n)=>{r(e),n()},this._flush=e=>{n(),e()}}import(e){return e.on("data",(e=>{this.write(e)})),e.on("end",(()=>{this.end()})),e.on("error",(e=>{this.emit("error",e)})),this}}class Ee extends ce.Transform{constructor(e){super({encoding:"utf8",writableObjectMode:!0});const t=this._writer=new oe({write:(e,t,r)=>{this.push(e),r&&r()},end:e=>{this.push(null),e&&e()}},e);this._transform=(e,r,n)=>{t.addQuad(e,n)},this._flush=e=>{t.end(e)}}import(e){return e.on("data",(e=>{this.write(e)})),e.on("end",(()=>{this.end()})),e.on("error",(e=>{this.emit("error",e)})),e.on("prefix",((e,t)=>{this._writer.addPrefix(e,t)})),this}}var Ae={Lexer:m,Parser:H,Writer:oe,Store:pe,StoreFactory:me,EntityIndex:fe,StreamParser:Se,StreamWriter:Ee,Util:n,Reasoner:be,DataFactory:E,Term:A,NamedNode:R,Literal:I,BlankNode:T,Variable:x,DefaultGraph:P,Quad:O,Triple:O,termFromId:C,termToId:k}},5606:function(e){var t,r,n=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function s(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:i}catch(e){t=i}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var a,c=[],l=!1,u=-1;function d(){l&&a&&(l=!1,a.length?c=a.concat(c):u=-1,c.length&&h())}function h(){if(!l){var e=s(d);l=!0;for(var t=c.length;t;){for(a=c,c=[];++u1)for(var r=1;r(n||(n=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0)))},7793:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(9931),t),i(r(8483),t),i(r(2142),t),i(r(2426),t),i(r(3988),t),i(r(6754),t),i(r(8401),t)},9931:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BlankNode=void 0,t.BlankNode=class{constructor(e){this.termType="BlankNode",this.value=e}equals(e){return!!e&&"BlankNode"===e.termType&&e.value===this.value}}},8483:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DataFactory=void 0;const n=r(9931),i=r(2142),o=r(2426),s=r(3988),a=r(6754),c=r(8401);let l=0;t.DataFactory=class{constructor(e){this.blankNodeCounter=0,e=e||{},this.blankNodePrefix=e.blankNodePrefix||`df_${l++}_`}namedNode(e){return new s.NamedNode(e)}blankNode(e){return new n.BlankNode(e||`${this.blankNodePrefix}${this.blankNodeCounter++}`)}literal(e,t){return new o.Literal(e,t)}variable(e){return new c.Variable(e)}defaultGraph(){return i.DefaultGraph.INSTANCE}quad(e,t,r,n){return new a.Quad(e,t,r,n||this.defaultGraph())}fromTerm(e){switch(e.termType){case"NamedNode":return this.namedNode(e.value);case"BlankNode":return this.blankNode(e.value);case"Literal":return e.language?this.literal(e.value,e.language):e.datatype.equals(o.Literal.XSD_STRING)?this.literal(e.value):this.literal(e.value,this.fromTerm(e.datatype));case"Variable":return this.variable(e.value);case"DefaultGraph":return this.defaultGraph();case"Quad":return this.quad(this.fromTerm(e.subject),this.fromTerm(e.predicate),this.fromTerm(e.object),this.fromTerm(e.graph))}}fromQuad(e){return this.fromTerm(e)}resetBlankNodeCounter(){this.blankNodeCounter=0}}},2142:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultGraph=void 0;class r{constructor(){this.termType="DefaultGraph",this.value=""}equals(e){return!!e&&"DefaultGraph"===e.termType}}t.DefaultGraph=r,r.INSTANCE=new r},2426:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Literal=void 0;const n=r(3988);class i{constructor(e,t){this.termType="Literal",this.value=e,"string"==typeof t?(this.language=t,this.datatype=i.RDF_LANGUAGE_STRING):t?(this.language="",this.datatype=t):(this.language="",this.datatype=i.XSD_STRING)}equals(e){return!!e&&"Literal"===e.termType&&e.value===this.value&&e.language===this.language&&this.datatype.equals(e.datatype)}}t.Literal=i,i.RDF_LANGUAGE_STRING=new n.NamedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),i.XSD_STRING=new n.NamedNode("http://www.w3.org/2001/XMLSchema#string")},3988:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NamedNode=void 0,t.NamedNode=class{constructor(e){this.termType="NamedNode",this.value=e}equals(e){return!!e&&"NamedNode"===e.termType&&e.value===this.value}}},6754:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Quad=void 0,t.Quad=class{constructor(e,t,r,n){this.termType="Quad",this.value="",this.subject=e,this.predicate=t,this.object=r,this.graph=n}equals(e){return!!e&&("Quad"===e.termType||!e.termType)&&this.subject.equals(e.subject)&&this.predicate.equals(e.predicate)&&this.object.equals(e.object)&&this.graph.equals(e.graph)}}},8401:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Variable=void 0,t.Variable=class{constructor(e){this.termType="Variable",this.value=e}equals(e){return!!e&&"Variable"===e.termType&&e.value===this.value}}},742:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(4806),t)},4806:function(e,t){"use strict";function r(e){const t=[];let r=0;for(;re.join(""))).join("/")}function n(e,t){let n=t+1;t>=0?"/"===e[t+1]&&"/"===e[t+2]&&(n=t+3):"/"===e[0]&&"/"===e[1]&&(n=2);const i=e.indexOf("/",n);return i<0?e:e.substr(0,i)+r(e.substr(i))}function i(e){return!e||"#"===e||"?"===e||"/"===e}Object.defineProperty(t,"__esModule",{value:!0}),t.removeDotSegmentsOfPath=t.removeDotSegments=t.resolve=void 0,t.resolve=function(e,t){const i=(t=t||"").indexOf("#");if(i>0&&(t=t.substr(0,i)),!e.length){if(t.indexOf(":")<0)throw new Error(`Found invalid baseIRI '${t}' for value '${e}'`);return t}if(e.startsWith("?")){const r=t.indexOf("?");return r>0&&(t=t.substr(0,r)),t+e}if(e.startsWith("#"))return t+e;if(!t.length){const t=e.indexOf(":");if(t<0)throw new Error(`Found invalid relative IRI '${e}' for a missing baseIRI`);return n(e,t)}const o=e.indexOf(":");if(o>=0)return n(e,o);const s=t.indexOf(":");if(s<0)throw new Error(`Found invalid baseIRI '${t}' for value '${e}'`);const a=t.substr(0,s+1);if(0===e.indexOf("//"))return a+n(e,o);let c;if(t.indexOf("//",s)===s+1){if(c=t.indexOf("/",s+3),c<0)return t.length>s+3?t+"/"+n(e,o):a+n(e,o)}else if(c=t.indexOf("/",s+1),c<0)return a+n(e,o);if(0===e.indexOf("/"))return t.substr(0,c)+r(e);let l=t.substr(c);const u=l.lastIndexOf("/");return u>=0&&u({name:e,mode:this.scopeModeMap[e]})))}get scopeParameter(){return this.scopes.map((e=>`${this._scopeNameForParameter(e)}:${e.mode}`)).join(" ")}claim(e,t){if("string"!=typeof e||-1!==e.indexOf("/")||0===e.length)throw new Error("Scope should be a non-empty string without forward slashes");if(!t.match(/^rw?$/))throw new Error("Mode should be either 'r' or 'rw'");this._adjustRootPaths(e),this.scopeModeMap[e]=t}get(e){return this.scopeModeMap[e]}remove(e){const t={};for(const e in this.scopeModeMap)t[e]=this.scopeModeMap[e];this.reset(),delete t[e];for(const e in t)this.claim(e,t[e])}checkPermission(e,t){const r=this.get(e);return r&&("r"===t||"rw"===r)}checkPathPermission(e,t){if(this.checkPermission("*",t))return!0;const r=this._getModuleName(e);return!!this.checkPermission(r,t)}reset(){this.rootPaths=[],this.scopeModeMap={}}_getModuleName(e){if("/"!==e[0])throw new Error("Path should start with a slash");const t=e.replace(/^\/public/,"").match(/^\/([^/]*)\//);return t?t[1]:"*"}_adjustRootPaths(e){"*"in this.scopeModeMap||"*"===e?this.rootPaths=["/"]:e in this.scopeModeMap||(this.rootPaths.push("/"+e+"/"),this.rootPaths.push("/public/"+e+"/"))}_scopeNameForParameter(e){if("*"===e.name&&this.storageType){if("2012.04"===this.storageType)return"";if(this.storageType.match(/remotestorage-0[01]/))return"root"}return e.name}setStorageType(e){this.storageType=e}}t.Access=r,t.default=r},3275:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Authorize=void 0;const o=i(r(3334)),s=r(7746),a=i(r(5503)),c=r(368);let l;function u(e){const t=e||d.getLocation().href,r={};for(const[e,n]of new URL(t).searchParams)r[e]=n;const n=t.indexOf("#");if(-1===n)return r;const i=t.substring(n+1);return i.includes("=")?i.split("&").reduce((function(e,t){const r=t.split("=");if("state"===r[0]&&r[1].match(/rsDiscovery/)){let t=decodeURIComponent(r[1]);const n=t.substr(t.indexOf("rsDiscovery=")).split("&")[0].split("=")[1];e.rsDiscovery=JSON.parse(atob(n)),t=t.replace(new RegExp("&?rsDiscovery="+n),""),t.length>0&&(e.state=t)}else e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]);return e}),r):r}class d{static authorize(e,t){if((0,o.default)("[Authorize] authURL = ",t.authURL,"scope = ",t.scope,"redirectUri = ",t.redirectUri,"clientId = ",t.clientId,"response_type =",t.response_type),!t.scope)throw new Error("Cannot authorize due to undefined or empty scope; did you forget to access.claim()?");if(!(0,s.localStorageAvailable)()&&"remotestorage"===e.backend){t.redirectUri+=t.redirectUri.indexOf("#")>0?"&":"#";const r={userAddress:e.remote.userAddress,href:e.remote.href,storageApi:e.remote.storageApi,properties:e.remote.properties};t.redirectUri+="rsDiscovery="+(0,s.toBase64)(JSON.stringify(r))}const r=function(e){const t=new URL(e.redirectUri);e.state||(e.state=t.hash?t.hash.substring(1):""),e.response_type||(e.response_type="token");const r=new URL(e.authURL);r.searchParams.set("redirect_uri",e.redirectUri.replace(/#.*$/,"")),r.searchParams.set("scope",e.scope),r.searchParams.set("client_id",e.clientId);for(const t of["state","response_type","code_challenge","code_challenge_method","token_access_type"]){const n=e[t];n&&r.searchParams.set(t,n)}return r.href}(t);s.globalContext.cordova?d.openWindow(r,t.redirectUri,"location=yes,clearsessioncache=yes,clearcache=yes").then((t=>{e.remote.configure({token:t.access_token})})):d.setLocation(r)}static refreshAccessToken(e,t,r){return n(this,void 0,void 0,(function*(){var e,n,i;yield t.configure({token:null,tokenType:null});const s=new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:r}),l=yield(0,c.requestWithTimeout)("POST",t.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString(),responseType:"json"});if(200!==(null==l?void 0:l.status))throw yield t.configure({refreshToken:null}),new a.default("refresh token rejected:"+JSON.stringify(l.response));{(0,o.default)(`[Authorize] access token good for ${null===(e=null==l?void 0:l.response)||void 0===e?void 0:e.expires_in} seconds`);const r={token:null===(n=null==l?void 0:l.response)||void 0===n?void 0:n.access_token,tokenType:null===(i=null==l?void 0:l.response)||void 0===i?void 0:i.token_type};if(!r.token)throw new Error(`no access_token in "successful" refresh: ${l.response}`);yield t.configure(r)}}))}static setLocation(e){if("string"==typeof e)document.location.href=e;else{if("object"!=typeof e)throw"Invalid location "+e;document.location=e}}static _rs_supported(){return"undefined"!=typeof document}static _rs_cleanup(e){e.removeEventListener("features-loaded",l)}}t.Authorize=d,d.IMPLIED_FAKE_TOKEN=!1,d.getLocation=function(){return document.location},d.openWindow=function(e,t,r){return new Promise(((n,i)=>{const o=open(e,"_blank",r);function s(){i("Authorization was canceled")}o&&!o.closed?(o.addEventListener("loadstart",(function(e){if(0!==e.url.indexOf(t))return;o.removeEventListener("exit",s),o.close();const r=u(e.url);r?n(r):i("Authorization error")})),o.addEventListener("exit",s)):i("Authorization popup was blocked")}))},d._rs_init=function(e){const t=u();let r;t&&(r=d.getLocation(),r.hash=""),l=function(){let i=!1;if(t){if(t.error)throw"access_denied"===t.error?new a.default("Authorization failed: access denied",{code:"access_denied"}):new a.default(`Authorization failed: ${t.error}`);t.rsDiscovery&&e.remote.configure(t.rsDiscovery),t.access_token&&(e.remote.configure({token:t.access_token}),i=!0),t.remotestorage&&(e.connect(t.remotestorage),i=!0),t.state&&(r=d.getLocation(),d.setLocation(r.href.split("#")[0]+"#"+t.state)),t.code&&(function(t){n(this,void 0,void 0,(function*(){var n,i,s,a;const l=sessionStorage.getItem("remotestorage:codeVerifier");if(!l)return void(0,o.default)("[Authorize] Ignoring OAuth code parameter, because no PKCE code verifier found in sessionStorage");r=d.getLocation();let u=r.origin;"/"!==r.pathname&&(u+=r.pathname);const h=new URLSearchParams({code:t,grant_type:"authorization_code",client_id:e.remote.clientId,redirect_uri:u,code_verifier:l}),f=yield(0,c.requestWithTimeout)("POST",e.remote.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:h.toString(),responseType:"json"});if(200===f.status){(0,o.default)(`[Authorize] access token good for ${null===(n=null==f?void 0:f.response)||void 0===n?void 0:n.expires_in} seconds`);const t={token:null===(i=null==f?void 0:f.response)||void 0===i?void 0:i.access_token,refreshToken:null===(s=null==f?void 0:f.response)||void 0===s?void 0:s.refresh_token,tokenType:null===(a=null==f?void 0:f.response)||void 0===a?void 0:a.token_type};t.token?e.remote.configure(t):e._emit("error",new Error(`no access_token in "successful" response: ${f.response}`)),sessionStorage.removeItem("remotestorage:codeVerifier")}else e._emit("error",new Error(`${f.statusText}: ${f.response}`))}))}(t.code),i=!0),i||e.remote.stopWaitingForToken()}else e.remote.stopWaitingForToken()},e.on("features-loaded",l)},t.default=d},6424:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClient=void 0;const o=i(r(439)),s=i(r(1613)),a=i(r(6491)),c=i(r(93)),l=i(r(7028)),u=r(7746);class d{constructor(e,t){if(this.schemas={configurable:!0,get(){return d.Types.inScope(this.moduleName)}},"/"!==t[t.length-1])throw"Not a folder: "+t;"/"===t&&(this.makePath=e=>("/"===e[0]?"":"/")+e),this.storage=e,this.base=t,this.moduleName=function(e){const t=e.split("/");return e.length>2?t[1]:"root"}(this.base),this.addEvents(["change"]),this.on=this.on.bind(this),e.onChange(this.base,this._fireChange.bind(this))}scope(e){return new d(this.storage,this.makePath(e))}getListing(e,t){return n(this,void 0,void 0,(function*(){if("string"!=typeof e)e="";else if(e.length>0&&!(0,u.isFolder)(e))return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then((e=>404===e.statusCode?{}:e.body))}))}getAll(e,t){return n(this,void 0,void 0,(function*(){if("string"!=typeof e)e="";else if(e.length>0&&!(0,u.isFolder)(e))return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then((r=>{if(404===r.statusCode)return{};if("object"==typeof r.body){const n=Object.keys(r.body);if(0===n.length)return{};const i=n.map((n=>this.storage.get(this.makePath(e+n),t).then((e=>{if("string"==typeof e.body)try{e.body=JSON.parse(e.body)}catch(e){}"object"==typeof e.body&&(r.body[n]=e.body)}))));return Promise.all(i).then((()=>r.body))}}))}))}getFile(e,t){return n(this,void 0,void 0,(function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getFile must be a string"):this.storage.get(this.makePath(e),t).then((e=>({data:e.body,contentType:e.contentType,revision:e.revision})))}))}storeFile(e,t,r){return n(this,void 0,void 0,(function*(){return"string"!=typeof e?Promise.reject("Argument 'mimeType' of baseClient.storeFile must be a string"):"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.storeFile must be a string"):"string"!=typeof r&&"object"!=typeof r?Promise.reject("Argument 'body' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView"):(this.storage.access.checkPathPermission(this.makePath(t),"rw")||console.warn("WARNING: Editing a document to which only read access ('r') was claimed"),this.storage.put(this.makePath(t),r,e).then((e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode))))}))}getObject(e,t){return n(this,void 0,void 0,(function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getObject must be a string"):this.storage.get(this.makePath(e),t).then((t=>{if("object"==typeof t.body)return t.body;if("string"==typeof t.body)try{return JSON.parse(t.body)}catch(t){throw new Error("Not valid JSON: "+this.makePath(e))}else if(void 0!==t.body&&200===t.statusCode)return Promise.reject("Not an object: "+this.makePath(e))}))}))}storeObject(e,t,r){return n(this,void 0,void 0,(function*(){if("string"!=typeof e)return Promise.reject("Argument 'typeAlias' of baseClient.storeObject must be a string");if("string"!=typeof t)return Promise.reject("Argument 'path' of baseClient.storeObject must be a string");if("object"!=typeof r)return Promise.reject("Argument 'object' of baseClient.storeObject must be an object");this._attachType(r,e);try{const e=this.validate(r);if(!e.valid)return Promise.reject(e)}catch(e){return Promise.reject(e)}return this.storage.put(this.makePath(t),JSON.stringify(r),"application/json; charset=UTF-8").then((e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode)))}))}remove(e){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.remove must be a string"):(this.storage.access.checkPathPermission(this.makePath(e),"rw")||console.warn("WARNING: Removing a document to which only read access ('r') was claimed"),this.storage.delete(this.makePath(e)))}getItemURL(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(e=(0,u.cleanPath)(this.makePath(e)),this.storage.remote.href+e):void 0}cache(e,t="ALL"){if("string"!=typeof e)throw"Argument 'path' of baseClient.cache must be a string";if("string"!=typeof t)throw"Argument 'strategy' of baseClient.cache must be a string or undefined";if("FLUSH"!==t&&"SEEN"!==t&&"ALL"!==t)throw'Argument \'strategy\' of baseclient.cache must be one of ["FLUSH", "SEEN", "ALL"]';return this.storage.caching.set(this.makePath(e),t),this}declareType(e,t,r){let n;if(r&&"string"==typeof t)n=t;else if(r||"string"==typeof t){if(!r&&"string"==typeof t)throw new Error("declareType() requires a JSON Schema object to be passed, in order to validate object types/formats")}else r=t,n=this._defaultTypeURI(e);d.Types.declare(this.moduleName,e,n,r)}validate(e){const t=d.Types.getSchema(e["@context"]);if(t)return o.default.validateResult(e,t);throw new a.default(e["@context"])}_defaultTypeURI(e){return"http://remotestorage.io/spec/modules/"+encodeURIComponent(this.moduleName)+"/"+encodeURIComponent(e)}_attachType(e,t){e["@context"]=d.Types.resolveAlias(this.moduleName+"/"+t)||this._defaultTypeURI(t)}makePath(e){return this.base+(e||"")}_fireChange(e){l.default.changeEvents[e.origin]&&(["new","old","lastCommon"].forEach((function(t){if((!e[t+"ContentType"]||/^application\/(.*)json(.*)/.exec(e[t+"ContentType"]))&&"string"==typeof e[t+"Value"])try{e[t+"Value"]=JSON.parse(e[t+"Value"])}catch(e){}})),this._emit("change",e))}static _rs_init(){}}t.BaseClient=d,d.Types=s.default,(0,u.applyMixins)(d,[c.default]),t.default=d},7285:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Caching=void 0;const i=r(7746),o=n(r(3334));class s{constructor(){this.pendingActivations=[],this.reset()}set(e,t){if("string"!=typeof e)throw new Error("path should be a string");if(!(0,i.isFolder)(e))throw new Error("path should be a folder");if(!t.match(/^(FLUSH|SEEN|ALL)$/))throw new Error("strategy should be 'FLUSH', 'SEEN', or 'ALL'");this._rootPaths[e]=t,"ALL"===t&&(this.activateHandler?this.activateHandler(e):this.pendingActivations.push(e))}enable(e){this.set(e,"ALL")}disable(e){this.set(e,"FLUSH")}onActivate(e){(0,o.default)("[Caching] Setting activate handler",e,this.pendingActivations),this.activateHandler=e;for(let t=0;t{const i=l(n[e]);return u(n,t)?r(e):i?{statusCode:200,body:i.body||i.itemsMap,contentType:i.contentType}:{statusCode:404}})):this.getNodes([e]).then((t=>{const r=l(t[e]);if(r){if((0,c.isFolder)(e))for(const e in r.itemsMap)r.itemsMap.hasOwnProperty(e)&&!1===r.itemsMap[e]&&delete r.itemsMap[e];return{statusCode:200,body:r.body||r.itemsMap,contentType:r.contentType}}return{statusCode:404}}))}))}put(e,t,r){return n(this,void 0,void 0,(function*(){const n=(0,c.pathsFromRoot)(e);return this._updateNodes(n,(function(e,n){try{for(let i=0,o=e.length;i0)break}else console.error("Cannot delete non-existing node "+n)}return t}))}flush(e){return this._getAllDescendentPaths(e).then((e=>this.getNodes(e))).then((e=>{for(const t in e){const r=e[t];r&&r.common&&r.local&&this._emitChange({path:r.path,origin:"local",oldValue:!1===r.local.body?void 0:r.local.body,newValue:!1===r.common.body?void 0:r.common.body}),e[t]=void 0}return this.setNodes(e)}))}_emitChange(e){s.default.changeEvents[e.origin]&&this._emit("change",e)}fireInitial(){s.default.changeEvents.local&&this.forAllNodes((e=>{if((0,c.isDocument)(e.path)){const t=l(e);t&&this._emitChange({path:e.path,origin:"local",oldValue:void 0,oldContentType:void 0,newValue:t.body,newContentType:t.contentType})}})).then((()=>{this._emit("local-events-done")}))}onDiff(e){this.diffHandler=e}migrate(e){return"object"!=typeof e||e.common||(e.common={},"string"==typeof e.path?"/"===e.path.substr(-1)&&"object"==typeof e.body&&(e.common.itemsMap=e.body):(e.local||(e.local={}),e.local.body=e.body,e.local.contentType=e.contentType)),e}_updateNodes(e,t){return new Promise(((r,n)=>{this._doUpdateNodes(e,t,{resolve:r,reject:n})}))}_doUpdateNodes(e,t,r){this._updateNodesRunning?this._updateNodesQueued.push({paths:e,cb:t,promise:r}):(this._updateNodesRunning=!0,this.getNodes(e).then((n=>{const i=(0,c.deepClone)(n),o=[];n=t(e,n);for(const e in n){const t=n[e];(0,c.equal)(t,i[e])?delete n[e]:(0,c.isDocument)(e)&&((0,c.equal)(t.local.body,t.local.previousBody)&&t.local.contentType===t.local.previousContentType||o.push({path:e,origin:"window",oldValue:t.local.previousBody,newValue:!1===t.local.body?void 0:t.local.body,oldContentType:t.local.previousContentType,newContentType:t.local.contentType}),delete t.local.previousBody,delete t.local.previousContentType)}this.setNodes(n).then((()=>{this._emitChangeEvents(o),r.resolve({statusCode:200})}))})).then((()=>Promise.resolve()),(e=>{r.reject(e)})).then((()=>{this._updateNodesRunning=!1;const e=this._updateNodesQueued.shift();e&&this._doUpdateNodes(e.paths,e.cb,e.promise)})))}_emitChangeEvents(e){for(let t=0,r=e.length;t{const r=[e],n=l(t[e]),i=Object.keys(n.itemsMap).map((t=>this._getAllDescendentPaths(e+t).then((e=>{for(let t=0,n=e.length;tr))})):Promise.resolve([e])}_getInternals(){return{getLatest:l,makeNode:d,isOutdated:u}}}(0,c.applyMixins)(f,[o.default]),e.exports=f},7028:function(e){"use strict";e.exports={cache:!0,changeEvents:{local:!0,window:!1,remote:!0,conflict:!0},cordovaRedirectUri:void 0,logging:!1,modules:[],backgroundSyncInterval:6e4,disableFeatures:[],discoveryTimeout:5e3,isBackground:!1,requestTimeout:3e4,syncInterval:1e4}},5373:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(4199)),o=n(r(7028)),s=n(r(3334)),a=r(7746);let c;const l="remotestorage:discover";let u={};const d=function(e){return new Promise(((t,r)=>{if(e in u)return t(u[e]);const n=new i.default({tls_only:!1,uri_fallback:!0,request_timeout:o.default.discoveryTimeout});return setTimeout((()=>r(new Error("timed out"))),o.default.discoveryTimeout),n.lookup(e,(function(n,i){if(n)return r(n);if("object"!=typeof i.idx.links.remotestorage||"number"!=typeof i.idx.links.remotestorage.length||i.idx.links.remotestorage.length<=0)return(0,s.default)("[Discover] WebFinger record for "+e+" does not have remotestorage defined in the links section ",JSON.stringify(i.json)),r("WebFinger record for "+e+" does not have remotestorage defined in the links section.");const o=i.idx.links.remotestorage[0],a=o.properties["http://tools.ietf.org/html/rfc6749#section-4.2"]||o.properties["auth-endpoint"],d=o.properties["http://remotestorage.io/spec/version"]||o.type;return u[e]={href:o.href,storageApi:d,authURL:a,properties:o.properties},c&&localStorage.setItem(l,JSON.stringify({cache:u})),t(u[e])}))}))};(d.DiscoveryError=function(e){this.name="DiscoveryError",this.message=e,this.stack=(new Error).stack}).prototype=Object.create(Error.prototype),d.DiscoveryError.prototype.constructor=d.DiscoveryError,d._rs_init=function(){if(c=(0,a.localStorageAvailable)(),c)try{const e=JSON.parse(localStorage[l]);u=e.cache}catch(e){}},d._rs_supported=function(){return Object.prototype.hasOwnProperty.call(a.globalContext,"fetch")||Object.prototype.hasOwnProperty.call(a.globalContext,"XMLHttpRequest")},d._rs_cleanup=function(){c&&delete localStorage[l]},e.exports=d},5706:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(93)),s=i(r(6424)),a=i(r(6941)),c=i(r(6982)),l=i(r(5503)),u=r(7746),d=r(368),h=r(3684),f=i(r(3275));let p;const g="remotestorage:dropbox",y="https://api.dropboxapi.com/2/files/list_folder",m="https://api.dropboxapi.com/2/files/list_folder/continue",v="/remotestorage";function b(e){return(v+"/"+e).replace(/\/+$/,"").replace(/\/+/g,"/")}const w=/[\u007f-\uffff]/g;function _(e){return JSON.stringify(e).replace(w,(function(e){return"\\u"+("000"+e.charCodeAt(0).toString(16)).slice(-4)}))}function S(e,t){return new RegExp("^"+t.join("\\/")+"(\\/|$)").test(e.error_summary)}function E(e){return e instanceof ArrayBuffer||(0,d.isArrayBufferView)(e)}class A extends h.RemoteBase{constructor(e){if(super(e),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this._initialFetchDone=!1,this.addEvents(["connected","not-connected"]),this.clientId=e.apiKeys.dropbox.appKey,this.TOKEN_URL="https://api.dropboxapi.com/oauth2/token",this._revCache=new a.default("rev"),this._fetchDeltaCursor=null,this._fetchDeltaPromise=null,this._itemRefs={},p=(0,u.localStorageAvailable)(),p){const e=(0,u.getJSONFromLocalStorage)(g);e&&this.configure(e),this._itemRefs=(0,u.getJSONFromLocalStorage)(`${g}:shares`)||{}}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}connect(){return n(this,void 0,void 0,(function*(){try{if(this.rs.setBackend("dropbox"),this.token)T(this.rs);else{const{codeVerifier:e,codeChallenge:t,state:r}=yield(0,u.generateCodeVerifier)();sessionStorage.setItem("remotestorage:codeVerifier",e),sessionStorage.setItem("remotestorage:state",r),this.rs.authorize({authURL:"https://www.dropbox.com/oauth2/authorize",scope:"account_info.read files.content.read files.content.write files.metadata.read files.metadata.write",clientId:this.clientId,response_type:"code",state:r,code_challenge:t,code_challenge_method:"S256",token_access_type:"offline"})}}catch(e){throw this.rs._emit("error",e),this.rs.setBackend(void 0),e}}))}configure(e){return n(this,void 0,void 0,(function*(){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token),void 0!==e.refreshToken&&(this.refreshToken=e.refreshToken),void 0!==e.tokenType&&(this.tokenType=e.tokenType);const t=()=>{p&&localStorage.setItem(g,JSON.stringify({userAddress:this.userAddress,token:this.token,refreshToken:this.refreshToken,tokenType:this.tokenType}))};if(this.refreshToken||this.token)if(this.connected=!0,this.userAddress)this._emit("connected"),t();else try{const e=yield this.info();this.userAddress=e.email,this._emit("connected"),t()}catch(e){this.connected=!1,this.rs._emit("error",new Error("Could not fetch user info.")),t.apply(this)}else(()=>{this.connected=!1,p&&localStorage.removeItem(g),this.rs.setBackend(void 0)})()}))}_getFolder(e){const t=this._revCache,r=r=>{let i;if(200!==r.status&&409!==r.status)return Promise.reject("Unexpected response status: "+r.status);try{i=JSON.parse(r.responseText)}catch(e){return Promise.reject(e)}if(409===r.status)return S(i,["path","not_found"])?Promise.resolve({}):Promise.reject(new Error("API returned an error: "+i.error_summary));const o=i.entries.reduce(((r,n)=>{try{const i="folder"===n[".tag"],o=n.path_display.split("/").slice(-1)[0]+(i?"/":"");if(i)r[o]={ETag:t.get(e+o)};else{const t=new Date(n.server_modified);r[o]={ETag:n.rev,"Content-Length":n.size,"Last-Modified":t.toUTCString()},this._revCache.set(e+o,n.rev)}}catch(t){console.error(`[Dropbox] folder “${e}” has entry ${JSON.stringify(n)}:`,t)}return r}),{});return i.has_more?n(i.cursor).then((function(e){return Object.assign(o,e)})):Promise.resolve(o)},n=e=>{const t={body:{cursor:e}};return this._request("POST",m,t).then(r)};return this._request("POST",y,{body:{path:b(e)}}).then(r).then((function(r){return Promise.resolve({statusCode:200,body:r,contentType:"application/json; charset=UTF-8",revision:t.get(e)})}))}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const r=this._revCache.get(e);if(null===r)return Promise.resolve({statusCode:404});if(t&&t.ifNoneMatch){if(!this._initialFetchDone)return this.fetchDelta().then((()=>this.get(e,t)));if(r&&r===t.ifNoneMatch)return Promise.resolve({statusCode:304})}if("/"===e.slice(-1))return this._getFolder(e);const n={headers:{"Dropbox-API-Arg":_({path:b(e)})},responseType:"arraybuffer"};return t&&t.ifNoneMatch&&(n.headers["If-None-Match"]=t.ifNoneMatch),this._request("GET","https://content.dropboxapi.com/2/files/download",n).then((t=>{const r=t.status;let n,i,o,s;return 200!==r&&409!==r?Promise.resolve({statusCode:r}):(n=t.getResponseHeader("Dropbox-API-Result"),(0,u.getTextFromArrayBuffer)(t.response,"UTF-8").then((a=>{i=a,409===r&&(n=i);try{n=JSON.parse(n)}catch(e){return Promise.reject(e)}if(409===r)return S(n,["path","not_found"])?{statusCode:404}:Promise.reject(new Error('API error while downloading file ("'+e+'"): '+n.error_summary));if(o=t.getResponseHeader("Content-Type"),s=n.rev,this._revCache.set(e,s),this._shareIfNeeded(e),(0,u.shouldBeTreatedAsBinary)(a,o))i=t.response;else try{i=JSON.parse(i),o="application/json; charset=UTF-8"}catch(e){}return{statusCode:r,body:i,contentType:o,revision:s}})))}))}put(e,t,r){return n(this,arguments,void 0,(function*(e,t,r,n={}){if(!this.connected)throw new Error("not connected (path: "+e+")");const i=this._revCache.get(e);if(n&&n.ifMatch&&i&&i!==n.ifMatch)return{statusCode:412,revision:i};if(n&&"*"===n.ifNoneMatch&&i&&"rev"!==i)return{statusCode:412,revision:i};if(!r.match(/charset=/)&&E(t)&&(r+="; charset=binary"),t.length>157286400)throw new Error("Cannot upload file larger than 150MB");const o={body:t,contentType:r,path:e};if(n&&(n.ifMatch||"*"===n.ifNoneMatch)){const t=yield this._getMetadata(e);if(n&&"*"===n.ifNoneMatch&&t)return{statusCode:412,revision:t.rev};if(n&&n.ifMatch&&t&&t.rev!==n.ifMatch)return{statusCode:412,revision:t.rev}}const s=yield this._uploadSimple(o);return this._shareIfNeeded(e),s}))}delete(e){return n(this,arguments,void 0,(function*(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");const r=this._revCache.get(e);if((null==t?void 0:t.ifMatch)&&r&&t.ifMatch!==r)return{statusCode:412,revision:r};if(null==t?void 0:t.ifMatch){const r=yield this._getMetadata(e);if((null==t?void 0:t.ifMatch)&&r&&r.rev!==t.ifMatch)return{statusCode:412,revision:r.rev}}return this._deleteSimple(e)}))}_shareIfNeeded(e){if(e.match(/^\/public\/.*[^/]$/)&&void 0===this._itemRefs[e])return this.share(e)}share(e){const t={body:{path:b(e)}};return this._request("POST","https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings",t).then((t=>{if(200!==t.status&&409!==t.status)return Promise.reject(new Error("Invalid response status:"+t.status));let r;try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+t.responseText))}return 409===t.status?S(r,["shared_link_already_exists"])?this._getSharedLink(e):Promise.reject(new Error("API error: "+r.error_summary)):Promise.resolve(r.url)})).then((t=>(this._itemRefs[e]=t,p&&localStorage.setItem(g+":shares",JSON.stringify(this._itemRefs)),Promise.resolve(t))),(t=>(t.message='Sharing Dropbox file or folder ("'+e+'") failed: '+t.message,Promise.reject(t))))}info(){return this._request("POST","https://api.dropboxapi.com/2/users/get_current_account",{}).then((function(e){let t;try{const r=JSON.parse(e.responseText);t=null==r?void 0:r.email}catch(t){return Promise.reject(new Error("Could not query current account info: Invalid API response: "+e.responseText))}return Promise.resolve({email:t})}))}_request(e,t,r){return n(this,arguments,void 0,(function*(e,t,r,n=1){if(this.isForbiddenRequestMethod(e,t))throw`Don't use ${e} on directories!`;if(!this.token)throw new l.default("No access token");r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,"object"!=typeof r.body||E(r.body)||(r.body=JSON.stringify(r.body),r.headers["Content-Type"]="application/json; charset=UTF-8"),this.rs._emit("wire-busy",{method:e,isFolder:(0,u.isFolder)(t)});try{const i=yield(0,d.requestWithTimeout)(e,t,r);return this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!0}),401===(null==i?void 0:i.status)&&this.refreshToken?n>=3?(console.error(`Abandoned after ${n} attempts: ${e} ${t}`),i):(this.rs._emit("wire-busy",{method:e,isFolder:(0,u.isFolder)(t)}),yield f.default.refreshAccessToken(this.rs,this,this.refreshToken),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!0}),this._request(e,t,r,n+1)):[503,429].includes(null==i?void 0:i.status)?(this.online&&(this.online=!1,this.rs._emit("network-offline")),n>=3?(console.warn(`Abandoned after ${n} attempts: ${e} ${t}`),i):(yield new Promise((e=>setTimeout(e,(0,d.retryAfterMs)(i)))),this._request(e,t,r,n+1))):i}catch(r){throw this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!1}),r}}))}fetchDelta(...e){if(this._fetchDeltaPromise)return this._fetchDeltaPromise;const t=e=>n(this,void 0,void 0,(function*(){let r,n;"string"==typeof e?(r=m,n={cursor:e}):(r=y,n={path:v,recursive:!0,include_deleted:!0});try{const i=yield this._request("POST",r,{body:n});if(401===i.status)throw new l.default;if(200!==i.status&&409!==i.status)throw new Error("Invalid response status: "+i.status);let o;try{o=JSON.parse(i.responseText)}catch(e){throw new Error("Invalid response body: "+i.responseText)}if(409===i.status){if(!S(o,["path","not_found"]))throw new Error("API returned an error: "+o.error_summary);o={cursor:null,entries:[],has_more:!1}}if(e||this._revCache.deactivatePropagation(),o.entries.forEach((e=>{const t=e.path_display.slice(14);"deleted"===e[".tag"]?(this._revCache.delete(t),this._revCache.delete(t+"/")):"file"===e[".tag"]&&this._revCache.set(t,e.rev)})),this._fetchDeltaCursor=o.cursor,o.has_more)return t(o.cursor);this._revCache.activatePropagation(),this._initialFetchDone=!0}catch(e){if("timeout"===e)return;throw e}}));return this._fetchDeltaPromise=t(this._fetchDeltaCursor).catch((e=>("object"==typeof e&&"message"in e?e.message="Dropbox: fetchDelta: "+e.message:e=`Dropbox: fetchDelta: ${e}`,this.rs._emit("error",e),this._fetchDeltaPromise=null,Promise.reject(e)))).then((()=>(this._fetchDeltaPromise=null,Promise.resolve(e)))),this._fetchDeltaPromise}_getMetadata(e){const t={path:b(e)};return this._request("POST","https://api.dropboxapi.com/2/files/get_metadata",{body:t}).then((e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status:"+e.status));let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?S(t,["path","not_found"])?Promise.resolve():Promise.reject(new Error("API error: "+t.error_summary)):Promise.resolve(t)})).then(void 0,(t=>(t.message='Could not load metadata for file or folder ("'+e+'"): '+t.message,Promise.reject(t))))}_uploadSimple(e){const t={path:b(e.path),mode:{".tag":"overwrite",update:void 0},mute:!0};return e.ifMatch&&(t.mode={".tag":"update",update:e.ifMatch}),this._request("POST","https://content.dropboxapi.com/2/files/upload",{body:e.body,headers:{"Content-Type":"application/octet-stream","Dropbox-API-Arg":_(t)}}).then((t=>{if(200!==t.status&&409!==t.status)return Promise.resolve({statusCode:t.status});let r;try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid API result: "+t.responseText))}return 409===t.status?S(r,["path","conflict"])?this._getMetadata(e.path).then((function(e){return Promise.resolve({statusCode:412,revision:e.rev})})):(this.rs._emit("error",new Error(r.error_summary)),Promise.resolve({statusCode:t.status})):(this._revCache.set(e.path,r.rev),Promise.resolve({statusCode:t.status,revision:r.rev}))}))}_deleteSimple(e){const t={path:b(e)};return this._request("POST","https://api.dropboxapi.com/2/files/delete",{body:t}).then((e=>{if(200!==e.status&&409!==e.status)return Promise.resolve({statusCode:e.status});let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}if(409===e.status){if(S(t,["path_lookup","not_found"]))return Promise.resolve({statusCode:404});this.rs._emit("error",new Error(t.error_summary))}return Promise.resolve({statusCode:e.status})})).then((t=>(200!==t.statusCode&&404!==t.statusCode||(this._revCache.delete(e),delete this._itemRefs[e]),Promise.resolve(t))),(t=>(t.message='Could not delete Dropbox file or folder ("'+e+'"): '+t.message,Promise.reject(t))))}_getSharedLink(e){return n(this,void 0,void 0,(function*(){const t={body:{path:b(e),direct_only:!0}};return this._request("POST","https://api.dropbox.com/2/sharing/list_shared_links",t).then((e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status: "+e.status));let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?Promise.reject(new Error("API error: "+(null==t?void 0:t.error_summary)||0)):t.links.length?Promise.resolve(t.links[0].url):Promise.reject(new Error("No links returned"))}),(t=>(t.message='Could not get link to a shared file or folder ("'+e+'"): '+t.message,Promise.reject(t))))}))}static _rs_init(e){p=(0,u.localStorageAvailable)(),e.apiKeys.dropbox&&(e.dropbox=new A(e)),"dropbox"===e.backend&&T(e)}static _rs_supported(){return!0}static _rs_cleanup(e){!function(e){(function(e){e._origRemote&&(e.remote=e._origRemote,delete e._origRemote)})(e),function(e){e._dropboxOrigSync&&(e.sync.sync=e._dropboxOrigSync,delete e._dropboxOrigSync)}(e),function(e){e._origBaseClientGetItemURL&&(s.default.prototype.getItemURL=e._origBaseClientGetItemURL,delete e._origBaseClientGetItemURL)}(e),I(e)}(e),p&&localStorage.removeItem(g),e.setBackend(void 0)}}function R(e,...t){e._dropboxOrigSync||(e._dropboxOrigSync=e.sync.sync.bind(e.sync),e.sync.sync=function(){return this.dropbox.fetchDelta(e,...t).then(e._dropboxOrigSync,(function(t){e._emit("error",new c.default(t)),e._emit("sync-done")}))}.bind(e))}function I(e){e._dropboxOrigSyncCycle&&(e.syncCycle=e._dropboxOrigSyncCycle,delete e._dropboxOrigSyncCycle)}function T(e){!function(e){e._origRemote||(e._origRemote=e.remote,e.remote=e.dropbox)}(e),e.sync?R(e):function(e,...t){e._dropboxOrigSyncCycle||(e._dropboxOrigSyncCycle=e.syncCycle,e.syncCycle=()=>{if(!e.sync)throw new Error("expected sync to be initialized by now");R(e),e._dropboxOrigSyncCycle(e,...t),I(e)})}(e),function(e){e._origBaseClientGetItemURL||(e._origBaseClientGetItemURL=s.default.prototype.getItemURL,s.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Dropbox yet")})}(e)}(0,u.applyMixins)(A,[o.default]),e.exports=A},9451:function(e,t,r){"use strict";const n=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(93)),i=r(7746);class o{constructor(){this.addEvents(["background","foreground"]),this.mode="undefined"!=typeof window?"browser":"node","browser"===this.mode&&(this.setBrowserPrefixedNames(),document.addEventListener(this.visibilityChangeEvent,this.setVisibility.bind(this),!1),this.setVisibility())}setBrowserPrefixedNames(){"browser"===this.mode&&(void 0!==document.hidden?(this.hiddenProperty="hidden",this.visibilityChangeEvent="visibilitychange"):void 0!==document.mozHidden?(this.hiddenProperty="mozHidden",this.visibilityChangeEvent="mozvisibilitychange"):void 0!==document.msHidden?(this.hiddenProperty="msHidden",this.visibilityChangeEvent="msvisibilitychange"):void 0!==document.webkitHidden&&(this.hiddenProperty="webkitHidden",this.visibilityChangeEvent="webkitvisibilitychange"))}setVisibility(){document[this.hiddenProperty]?this.goBackground():this.goForeground()}isBrowser(){return"browser"===this.mode}isNode(){return"node"===this.mode}goBackground(){this._emit("background")}goForeground(){this._emit("foreground")}static _rs_init(){}static _rs_cleanup(){}}(0,i.applyMixins)(o,[n.default]),e.exports=o},93:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.EventHandling=void 0;const i=n(r(3334));class o{addEvents(e){e.forEach((e=>this._addEvent(e)))}addEventListener(e,t){if("string"!=typeof e)throw new Error("Argument eventName should be a string");if("function"!=typeof t)throw new Error("Argument handler should be a function");(0,i.default)("[EventHandling] Adding event listener",e),this._validateEvent(e),this._handlers[e].push(t)}on(e,t){return this.addEventListener(e,t)}removeEventListener(e,t){this._validateEvent(e);const r=this._handlers[e].length;for(let n=0;n{e.apply(this,t)}))}_validateEvent(e){if(!(e in this._handlers))throw new Error("Unknown event: "+e)}_delegateEvent(e,t){t.on(e,(t=>{this._emit(e,t)}))}_addEvent(e){void 0===this._handlers&&(this._handlers={}),this._handlers[e]=[]}}t.EventHandling=o,t.default=o},6545:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(7028)),o=n(r(9451)),s=n(r(3334)),a=r(7746),c=n(r(1370)),l=n(r(2548)),u=n(r(3275)),d=n(r(5373)),h=n(r(6424)),f=n(r(1801)),p=n(r(5706)),g=n(r(6467)),y=n(r(600)),m=n(r(313)),v=n(r(7285)),b=n(r(8567)),w=n(r(7794)),_=n(r(8365)),S={features:[],featuresDone:0,readyFired:!1,loadFeatures(){this.features=[],this.featuresDone=0,this.readyFired=!1,this.featureModules={WireClient:y.default,Dropbox:p.default,GoogleDrive:f.default,Solid:g.default,Access:l.default,Discover:d.default,Authorize:u.default,BaseClient:h.default,Env:o.default},i.default.cache&&(0,a.extend)(this.featureModules,{Caching:v.default,IndexedDB:b.default,LocalStorage:w.default,InMemoryStorage:_.default,Sync:m.default}),i.default.disableFeatures.forEach((e=>{this.featureModules[e]&&delete this.featureModules[e]})),this._allLoaded=!1;for(const e in this.featureModules)this.loadFeature(e)},hasFeature(e){for(let t=this.features.length-1;t>=0;t--)if(this.features[t].name===e)return this.features[t].supported;return!1},loadFeature(e){const t=this.featureModules[e],r=!t._rs_supported||t._rs_supported();(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initializing ...`),"object"==typeof r?r.then((()=>{this.featureSupported(e,!0),this.initFeature(e)}),(()=>{this.featureSupported(e,!1)})):"boolean"==typeof r?(this.featureSupported(e,r),r&&this.initFeature(e)):this.featureSupported(e,!1)},initFeature(e){const t=this.featureModules[e];let r;try{r=t._rs_init(this)}catch(t){return void this.featureFailed(e,t)}"object"==typeof r&&"function"==typeof r.then?r.then((()=>{this.featureInitialized(e)}),(t=>{this.featureFailed(e,t)})):this.featureInitialized(e)},featureFailed(e,t){(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initialization failed (${t})`),this.featureDone()},featureSupported(e,t){(0,s.default)(`[RemoteStorage] [FEATURE ${e}]${t?"":"not "} supported`),t||this.featureDone()},featureInitialized(e){(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initialized`),this.features.push({name:e,init:this.featureModules[e]._rs_init,supported:!0,cleanup:this.featureModules[e]._rs_cleanup}),this.featureDone()},featureDone(){this.featuresDone++,this.featuresDone===Object.keys(this.featureModules).length&&setTimeout(this.featuresLoaded.bind(this),0)},_setCachingModule(){["IndexedDB","LocalStorage","InMemoryStorage"].some((e=>{if(this.features.some((t=>t.name===e)))return this.features.local=this.featureModules[e],!0}))},_fireReady(){try{this.readyFired||(this._emit("ready"),this.readyFired=!0)}catch(e){console.error("'ready' failed: ",e,e.stack),this._emit("error",e)}},featuresLoaded(){(0,s.default)("[RemoteStorage] All features loaded"),this._setCachingModule(),this.local=i.default.cache&&this.features.local&&new this.features.local,this.local&&this.remote?(this._setGPD(c.default,this),this._bindChange(this.local)):this.remote&&this._setGPD(this.remote,this.remote),this.remote&&(this.remote.on("connected",(()=>{this._fireReady(),this._emit("connected")})),this.remote.on("not-connected",(()=>{this._fireReady(),this._emit("not-connected")})),this.remote.connected&&(this._fireReady(),this._emit("connected")),this.hasFeature("Authorize")||this.remote.stopWaitingForToken()),this._collectCleanupFunctions();try{this._allLoaded=!0,this._emit("features-loaded")}catch(e){(0,a.logError)(e),this._emit("error",e)}this._processPending()},_collectCleanupFunctions(){this._cleanups=[];for(let e=0;e=r-this.maxAge?t.v:void 0}set(e,t){this._items[e]={v:t,t:(new Date).getTime()}}}class v extends c.RemoteBase{constructor(e,t){if(super(e),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this.addEvents(["connected","not-connected"]),this.clientId=t,this._fileIdCache=new m(300),h=(0,s.localStorageAvailable)(),h){const e=(0,s.getJSONFromLocalStorage)(u);e&&this.configure(e)}}configure(e){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token);const t=function(){h&&localStorage.setItem(u,JSON.stringify({userAddress:this.userAddress,token:this.token}))},r=function(){this.connected=!1,delete this.token,h&&localStorage.removeItem(u)};this.token?(this.connected=!0,this.userAddress?(this._emit("connected"),t.apply(this)):this.info().then((e=>{this.userAddress=e.user.emailAddress,this._emit("connected"),t.apply(this)})).catch((()=>{r.apply(this),this.rs._emit("error",new Error("Could not fetch user info."))}))):r.apply(this)}connect(){this.rs.setBackend("googledrive"),this.rs.authorize({authURL:"https://accounts.google.com/o/oauth2/auth",scope:"https://www.googleapis.com/auth/drive",clientId:this.clientId})}get(e,t={}){return(0,s.isFolder)(e)?this._getFolder(y(e)):this._getFile(y(e),t)}put(e,t,r,n={}){const i=y(e);function o(e){if(e.status>=200&&e.status<300){const t=JSON.parse(e.responseText),r=this.stripQuotes(t.etag);return Promise.resolve({statusCode:200,contentType:t.mimeType,revision:r})}return 412===e.status?Promise.resolve({statusCode:412,revision:"conflict"}):Promise.reject("PUT failed with status "+e.status+" ("+e.responseText+")")}return this._getFileId(i).then((e=>e?n&&"*"===n.ifNoneMatch?o({status:412}):this._updateFile(e,i,t,r,n).then(o):this._createFile(i,t,r).then(o)))}delete(e,t={}){const r=y(e);return this._getFileId(r).then((e=>e?this._getMeta(e).then((r=>{let n;return"object"==typeof r&&"string"==typeof r.etag&&(n=this.stripQuotes(r.etag)),t&&t.ifMatch&&t.ifMatch!==n?{statusCode:412,revision:n}:this._request("DELETE",l+"/drive/v2/files/"+e,{}).then((e=>200===e.status||204===e.status?{statusCode:200}:Promise.reject("Delete failed: "+e.status+" ("+e.responseText+")")))})):Promise.resolve({statusCode:200})))}info(){const e=l+"/drive/v2/about?fields=user";return this._request("GET",e,{}).then((function(e){try{const t=JSON.parse(e.responseText);return Promise.resolve(t)}catch(e){return Promise.reject(e)}}))}_updateFile(e,t,r,n,i){const o={mimeType:n},s={"Content-Type":"application/json; charset=UTF-8"};return i&&i.ifMatch&&(s["If-Match"]=this.addQuotes(i.ifMatch)),this._request("PUT",l+"/upload/drive/v2/files/"+e+"?uploadType=resumable",{body:JSON.stringify(o),headers:s}).then((e=>412===e.status?e:this._request("PUT",e.getResponseHeader("Location"),{body:n.match(/^application\/json/)?JSON.stringify(r):r})))}_createFile(e,t,r){return this._getParentId(e).then((n=>{const i={title:f(g(e)),mimeType:r,parents:[{kind:"drive#fileLink",id:n}]};return this._request("POST",l+"/upload/drive/v2/files?uploadType=resumable",{body:JSON.stringify(i),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then((e=>this._request("POST",e.getResponseHeader("Location"),{body:r.match(/^application\/json/)?JSON.stringify(t):t})))}))}_getFile(e,t){return this._getFileId(e).then((e=>this._getMeta(e).then((e=>{let r;if("object"==typeof e&&"string"==typeof e.etag&&(r=this.stripQuotes(e.etag)),t&&t.ifNoneMatch&&r===t.ifNoneMatch)return Promise.resolve({statusCode:304});if(!e.downloadUrl){if(!e.exportLinks||!e.exportLinks["text/html"])return Promise.resolve({statusCode:200,body:"",contentType:e.mimeType,revision:r});e.mimeType+=";export=text/html",e.downloadUrl=e.exportLinks["text/html"]}return this._request("GET",e.downloadUrl,{responseType:"arraybuffer"}).then((t=>(0,s.getTextFromArrayBuffer)(t.response,"UTF-8").then((function(n){let i=n;if(e.mimeType.match(/^application\/json/))try{i=JSON.parse(i)}catch(e){}else(0,s.shouldBeTreatedAsBinary)(n,e.mimeType)&&(i=t.response);return{statusCode:200,body:i,contentType:e.mimeType,revision:r}}))))}))))}_getFolder(e){return this._getFileId(e).then((t=>{let r,n,i;if(!t)return Promise.resolve({statusCode:404});const o="'"+t+"' in parents";return this._request("GET",l+"/drive/v2/files?q="+encodeURIComponent(o)+"&fields="+encodeURIComponent("items(downloadUrl,etag,fileSize,id,mimeType,title,labels)")+"&maxResults=1000&trashed=false",{}).then((t=>{var o;if(200!==t.status)return Promise.reject("request failed or something: "+t.status);try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject("non-JSON response from GoogleDrive")}i={};for(const t of r.items)(null===(o=t.labels)||void 0===o?void 0:o.trashed)||(n=this.stripQuotes(t.etag),t.mimeType===d?(this._fileIdCache.set(e+(0,s.cleanPath)(t.title)+"/",t.id),i[t.title+"/"]={ETag:n}):(this._fileIdCache.set(e+(0,s.cleanPath)(t.title),t.id),i[t.title]={ETag:n,"Content-Type":t.mimeType,"Content-Length":t.fileSize}));return Promise.resolve({statusCode:200,body:i,contentType:"application/json; charset=UTF-8",revision:void 0})}))}))}_getParentId(e){const t=p(e);return this._getFileId(t).then((e=>e?Promise.resolve(e):this._createFolder(t)))}_createFolder(e){return this._getParentId(e).then((t=>this._request("POST",l+"/drive/v2/files",{body:JSON.stringify({title:f(g(e)),mimeType:d,parents:[{id:t}]}),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then((e=>{const t=JSON.parse(e.responseText);return Promise.resolve(t.id)}))))}_getFileId(e){let t;return"/"===e?Promise.resolve("root"):(t=this._fileIdCache.get(e))?Promise.resolve(t):this._getFolder(p(e)).then((()=>(t=this._fileIdCache.get(e),t?Promise.resolve(t):"/"===e.substr(-1)?this._createFolder(e).then((()=>this._getFileId(e))):Promise.resolve())))}_getMeta(e){return this._request("GET",l+"/drive/v2/files/"+e,{}).then((function(t){return 200===t.status?Promise.resolve(JSON.parse(t.responseText)):Promise.reject("request (getting metadata for "+e+") failed with status: "+t.status)}))}_request(e,t,r){return this.isForbiddenRequestMethod(e,t)?Promise.reject(`Don't use ${e} on directories!`):(r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,this.rs._emit("wire-busy",{method:e,isFolder:(0,s.isFolder)(t)}),(0,a.requestWithTimeout)(e,t,r).then((r=>r&&401===r.status?void this.connect():(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!0}),Promise.resolve(r))),(r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!1}),Promise.reject(r)))))}static _rs_init(e){const t=e.apiKeys.googledrive;var r;t&&(e.googledrive=new v(e,t.clientId),"googledrive"===e.backend&&(e._origRemote=e.remote,e.remote=e.googledrive,(r=e)._origBaseClientGetItemURL||(r._origBaseClientGetItemURL=i.default.prototype.getItemURL,i.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Google Drive yet")})))}static _rs_supported(){return!0}static _rs_cleanup(e){var t;e.setBackend(void 0),e._origRemote&&(e.remote=e._origRemote,delete e._origRemote),(t=e)._origBaseClientGetItemURL&&(i.default.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)}}(0,s.applyMixins)(v,[o.default]),e.exports=v},8567:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(93)),s=i(r(3496)),a=i(r(3334)),c=r(7746),l="remotestorage";let u;class d extends s.default{constructor(e){super(),this.addEvents(["change","local-events-done"]),this.db=e||u,this.db?(this.getsRunning=0,this.putsRunning=0,this.changesQueued={},this.changesRunning={},this.commitSlownessWarning=null):(0,a.default)("[IndexedDB] Failed to open DB")}getNodes(e){return n(this,void 0,void 0,(function*(){const t=[],r={};for(let n=0,i=e.length;n0?this.getNodesFromDb(t).then((function(e){for(const t in r)e[t]=r[t];return e})):Promise.resolve(r)}))}setNodes(e){return n(this,void 0,void 0,(function*(){for(const t in e)this.changesQueued[t]=e[t]||!1;return this.maybeFlush(),Promise.resolve()}))}maybeFlush(){0===this.putsRunning?this.flushChangesQueued():this.commitSlownessWarning||(this.commitSlownessWarning=r.g.setInterval((function(){console.warn("WARNING: waited more than 10 seconds for previous commit to finish")}),1e4))}flushChangesQueued(){this.commitSlownessWarning&&(clearInterval(this.commitSlownessWarning),this.commitSlownessWarning=null),Object.keys(this.changesQueued).length>0&&(this.changesRunning=this.changesQueued,this.changesQueued={},this.setNodesInDb(this.changesRunning).then(this.flushChangesQueued.bind(this)))}getNodesFromDb(e){return new Promise(((t,r)=>{const n=this.db.transaction(["nodes"],"readonly"),i=n.objectStore("nodes"),o={};this.getsRunning++,e.map((e=>{i.get(e).onsuccess=t=>{o[e]=t.target.result}})),n.oncomplete=()=>{t(o),this.getsRunning--},n.onerror=n.onabort=()=>{r("get transaction error/abort"),this.getsRunning--}}))}setNodesInDb(e){return n(this,void 0,void 0,(function*(){return new Promise(((t,r)=>{const n=this.db.transaction(["nodes"],"readwrite"),i=n.objectStore("nodes"),o=(new Date).getTime();this.putsRunning++,(0,a.default)("[IndexedDB] Starting put",e,this.putsRunning);for(const t in e){const r=e[t];if("object"==typeof r)try{i.put(r)}catch(e){throw(0,a.default)("[IndexedDB] Error while putting",r,e),e}else try{i.delete(t)}catch(e){throw(0,a.default)("[IndexedDB] Error while removing",i,r,e),e}}n.oncomplete=()=>{this.putsRunning--,(0,a.default)("[IndexedDB] Finished put",e,this.putsRunning,(new Date).getTime()-o+"ms"),t()},n.onerror=()=>{this.putsRunning--,r("transaction error")},n.onabort=()=>{r("transaction abort"),this.putsRunning--}}))}))}reset(e){const t=this.db.name;this.db.close(),d.clean(this.db.name,(()=>{d.open(t,((t,r)=>{t?(0,a.default)("[IndexedDB] Error while resetting local storage",t):this.db=r,"function"==typeof e&&e(self)}))}))}forAllNodes(e){return n(this,void 0,void 0,(function*(){return new Promise((t=>{this.db.transaction(["nodes"],"readonly").objectStore("nodes").openCursor().onsuccess=r=>{const n=r.target.result;n?(e(this.migrate(n.value)),n.continue()):t()}}))}))}closeDB(){0===this.putsRunning?this.db.close():setTimeout(this.closeDB.bind(this),100)}static open(e,t){const r=setTimeout((function(){t("timeout trying to open db")}),1e4);try{const n=indexedDB.open(e,2);n.onerror=function(){(0,a.default)("[IndexedDB] Opening DB failed",n),clearTimeout(r),t(n.error)},n.onupgradeneeded=function(e){const t=n.result;(0,a.default)("[IndexedDB] Upgrade: from ",e.oldVersion," to ",e.newVersion),1!==e.oldVersion&&((0,a.default)("[IndexedDB] Creating object store: nodes"),t.createObjectStore("nodes",{keyPath:"path"})),(0,a.default)("[IndexedDB] Creating object store: changes"),t.createObjectStore("changes",{keyPath:"path"})},n.onsuccess=function(){clearTimeout(r);const i=n.result;if(!i.objectStoreNames.contains("nodes")||!i.objectStoreNames.contains("changes"))return(0,a.default)("[IndexedDB] Missing object store. Resetting the database."),void d.clean(e,(function(){d.open(e,t)}));t(null,n.result)}}catch(n){(0,a.default)("[IndexedDB] Failed to open database: "+n),(0,a.default)("[IndexedDB] Resetting database and trying again."),clearTimeout(r),d.clean(e,(function(){d.open(e,t)}))}}static clean(e,t){const r=indexedDB.deleteDatabase(e);r.onsuccess=function(){(0,a.default)("[IndexedDB] Done removing DB"),t()},r.onerror=r.onabort=function(t){console.error('Failed to remove database "'+e+'"',t)}}static _rs_init(e){return new Promise(((t,r)=>{d.open(l,(function(n,i){n?r(n):(u=i,i.onerror=()=>{e._emit("error",n)},t())}))}))}static _rs_supported(){return new Promise(((e,t)=>{const r=(0,c.getGlobalContext)();let n=!1;if("undefined"!=typeof navigator&&navigator.userAgent.match(/Android (2|3|4\.[0-3])/)&&(navigator.userAgent.match(/Chrome|Firefox/)||(n=!0)),"indexedDB"in r&&!n)try{const r=indexedDB.open("rs-check");r.onerror=function(){t()},r.onsuccess=function(){r.result.close(),indexedDB.deleteDatabase("rs-check"),e()}}catch(e){t()}else t()}))}static _rs_cleanup(e){return new Promise((t=>{e.local&&e.local.closeDB(),d.clean(l,t)}))}diffHandler(){}}(0,c.applyMixins)(d,[o.default]),e.exports=d},8365:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(93)),o=n(r(3496)),s=r(7746);class a extends o.default{constructor(){super(),this._storage={},this.addEvents(["change","local-events-done"])}getNodes(e){const t={};for(let r=0,n=e.length;r{(0,s.default)("[LocalStorage] Removing",e),delete localStorage[e]}))}}(0,a.applyMixins)(u,[o.default]),e.exports=u},3334:function(e,t,r){"use strict";const n=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(7028));e.exports=function(...e){n.default.logging&&console.log(...e)}},3684:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteBase=void 0;const i=n(r(93)),o=r(7746);class s extends i.default{constructor(e){super(),this.rs=e,this.connected=!1}stopWaitingForToken(){this.connected||this._emit("not-connected")}addQuotes(e){return"string"!=typeof e?e:"*"===e?"*":'"'+e+'"'}stripQuotes(e){return"string"!=typeof e?e:e.replace(/^["']|["']$/g,"")}isForbiddenRequestMethod(e,t){return("PUT"===e||"DELETE"===e)&&(0,o.isFolder)(t)}}t.RemoteBase=s},423:function(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s=2e3&&e<=36e5}var x;!function(e){e.GOOGLE="googledrive",e.DROPBOX="dropbox"}(x||(x={}));class P{constructor(e){if(this._pending=[],this._cleanups=[],this._pathHandlers={change:{}},this.apiKeys={},this._init=S.default.loadFeatures,this.features=S.default.features,this.loadFeature=S.default.loadFeature,this.featureSupported=S.default.featureSupported,this.featureDone=S.default.featureDone,this.featuresDone=S.default.featuresDone,this.featuresLoaded=S.default.featuresLoaded,this.featureInitialized=S.default.featureInitialized,this.featureFailed=S.default.featureFailed,this.hasFeature=S.default.hasFeature,this._setCachingModule=S.default._setCachingModule,this._collectCleanupFunctions=S.default._collectCleanupFunctions,this._fireReady=S.default._fireReady,this.initFeature=S.default.initFeature,"object"==typeof e&&(0,u.extend)(c.default,e),this.addEvents(["ready","authing","connecting","pod-not-selected","connected","disconnected","not-connected","conflict","error","features-loaded","sync-interval-change","sync-req-done","sync-done","wire-busy","wire-done","network-offline","network-online"]),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")}),R=(0,u.localStorageAvailable)(),R){this.apiKeys=(0,u.getJSONFromLocalStorage)("remotestorage:api-keys")||{};const e=localStorage.getItem("remotestorage:backend");"dropbox"===e||"googledrive"===e||"solid"===e?this.setBackend(e):this.setBackend("remotestorage")}const t=this.on;this.on=function(e,r){if(this._allLoaded)switch(e){case"features-loaded":setTimeout(r,0);break;case"ready":this.remote&&setTimeout(r,0);break;case"connected":this.remote&&this.remote.connected&&setTimeout(r,0);break;case"not-connected":this.remote&&!this.remote.connected&&setTimeout(r,0);break;case"pod-not-selected":this.remote instanceof v.default&&Array.isArray(this.remote.getPodURLs())&&this.remote.getPodURLs().length>0&&null===this.remote.getPodURL()&&setTimeout(r,0)}return t.call(this,e,r)},this._init(),this.fireInitial=function(){this.local&&setTimeout(this.local.fireInitial.bind(this.local),0)}.bind(this),this.on("ready",this.fireInitial.bind(this)),this.loadModules()}get connected(){return this.remote.connected}loadModules(){c.default.modules.forEach(this.addModule.bind(this))}authorize(e){if(this.access.setStorageType(this.remote.storageApi),void 0===e.scope&&(e.scope=this.access.scopeParameter),A.cordova)e.redirectUri=c.default.cordovaRedirectUri;else{const t=h.default.getLocation();let r=t.origin;"/"!==t.pathname&&(r+=t.pathname),e.redirectUri=r}void 0===e.clientId&&(e.clientId=e.redirectUri.match(/^(https?:\/\/[^/]+)/)[0]),h.default.authorize(this,e)}impliedauth(e,t){e=e||this.remote.storageApi,t=t||String(document.location),(0,l.default)("ImpliedAuth proceeding due to absent authURL; storageApi = "+e+" redirectUri = "+t),this.remote.configure({token:h.default.IMPLIED_FAKE_TOKEN}),document.location.href=t}connect(e,t){if(this.setBackend("remotestorage"),e.indexOf("@")<0&&!e.match(/^(https?:\/\/)?[^\s\/$\.?#]+\.[^\s]*$/))this._emit("error",new P.DiscoveryError("Not a valid user address or URL."));else{if(e.indexOf("@")<0&&!e.match(/^https?:\/\//)&&(e=`https://${e}`),A.cordova){if("string"!=typeof c.default.cordovaRedirectUri)return void this._emit("error",new P.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));if(!A.cordova.InAppBrowser)return void this._emit("error",new P.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"))}this.remote.configure({userAddress:e}),this._emit("connecting"),(0,b.default)(e).then((r=>{if(this._emit("authing"),r.userAddress=e,this.remote.configure(r),!this.remote.connected)if(r.authURL)if(void 0===t)this.authorize({authURL:r.authURL});else{if("string"!=typeof t)throw new Error("Supplied bearer token must be a string");(0,l.default)("Skipping authorization sequence and connecting with known token"),this.remote.configure({token:t})}else this.impliedauth()}),(()=>{this._emit("error",new P.DiscoveryError("No storage information found for this user address."))}))}}reconnect(){this.remote.configure({token:null}),"remotestorage"===this.backend?this.connect(this.remote.userAddress):this.remote.connect()}disconnect(){this.remote&&this.remote.configure({userAddress:null,href:null,storageApi:null,token:null,properties:null}),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")});const e=this._cleanups.length;let t=0;const r=()=>{t++,t>=e&&(this._init(),this._emit("disconnected"))};e>0?this._cleanups.forEach((e=>{const t=e(this);"object"==typeof t&&"function"==typeof t.then?t.then(r):r()})):r()}setBackend(e){this.backend=e,R&&(void 0!==e?localStorage.setItem("remotestorage:backend",e):localStorage.removeItem("remotestorage:backend"))}onChange(e,t){this._pathHandlers.change[e]||(this._pathHandlers.change[e]=[]),this._pathHandlers.change[e].push(t)}enableLog(){c.default.logging=!0}disableLog(){c.default.logging=!1}log(...e){l.default.apply(P,e)}setApiKeys(e){const t=[x.GOOGLE,x.DROPBOX];if("object"!=typeof e||!Object.keys(e).every((e=>t.includes(e))))return console.error("setApiKeys() was called with invalid arguments"),!1;Object.keys(e).forEach((t=>{const r=e[t];if(r){switch(t){case x.DROPBOX:this.apiKeys[x.DROPBOX]={appKey:r},void 0!==this.dropbox&&this.dropbox.clientId===r||m.default._rs_init(this);break;case x.GOOGLE:this.apiKeys[x.GOOGLE]={clientId:r},void 0!==this.googledrive&&this.googledrive.clientId===r||y.default._rs_init(this)}return!0}delete this.apiKeys[t]})),R&&localStorage.setItem("remotestorage:api-keys",JSON.stringify(this.apiKeys))}setCordovaRedirectUri(e){if("string"!=typeof e||!e.match(/http(s)?:\/\//))throw new Error("Cordova redirect URI must be a URI string");c.default.cordovaRedirectUri=e}_setGPD(e,t){function r(e){return function(...r){return e.apply(t,r).then(I.bind(this))}}this.get=r(e.get),this.put=r(e.put),this.delete=r(e.delete)}_pendingGPD(e){return(...t)=>{const r=Array.prototype.slice.call(t);return new Promise(((t,n)=>{this._pending.push({method:e,args:r,promise:{resolve:t,reject:n}})}))}}_processPending(){this._pending.forEach((e=>{try{this[e.method](...e.args).then(e.promise.resolve,e.promise.reject)}catch(t){e.promise.reject(t)}})),this._pending=[]}_bindChange(e){e.on("change",this._dispatchEvent.bind(this,"change"))}_dispatchEvent(e,t){Object.keys(this._pathHandlers[e]).forEach((r=>{const n=r.length;t.path.substr(0,n)===r&&this._pathHandlers[e][r].forEach((e=>{const n={};for(const e in t)n[e]=t[e];n.relativePath=t.path.replace(new RegExp("^"+r),"");try{e(n)}catch(e){console.error("'change' handler failed: ",e,e.stack),this._emit("error",e)}}))}))}scope(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.scope must be a string";return this.access.checkPathPermission(e,"r")||console.warn("WARNING: Please use remoteStorage.access.claim() to ask for access permissions first: https://remotestoragejs.readthedocs.io/en/latest/js-api/access.html#claim"),new f.default(this,e)}getSyncInterval(){return c.default.syncInterval}setSyncInterval(e){if(!T(e))throw e+" is not a valid sync interval";const t=c.default.syncInterval;c.default.syncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getBackgroundSyncInterval(){return c.default.backgroundSyncInterval}setBackgroundSyncInterval(e){if(!T(e))throw e+" is not a valid sync interval";const t=c.default.backgroundSyncInterval;c.default.backgroundSyncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getCurrentSyncInterval(){return c.default.isBackground?c.default.backgroundSyncInterval:c.default.syncInterval}getRequestTimeout(){return c.default.requestTimeout}setRequestTimeout(e){if("number"!=typeof e)throw e+" is not a valid request timeout";c.default.requestTimeout=e}syncCycle(){this.sync&&!this.sync.stopped&&(this.on("sync-done",(()=>{this.sync&&!this.sync.stopped&&(this._syncTimer&&(clearTimeout(this._syncTimer),this._syncTimer=void 0),this._syncTimer=setTimeout(this.sync.sync.bind(this.sync),this.getCurrentSyncInterval()))})),this.sync.sync())}startSync(){return c.default.cache?(this.sync.stopped=!1,this.syncStopped=!1,this.sync.sync()):(console.warn("Nothing to sync, because caching is disabled."),Promise.resolve())}stopSync(){clearTimeout(this._syncTimer),this._syncTimer=void 0,this.sync?this.sync.stopped=!0:this.syncStopped=!0}addModule(e){const t=e.name,r=e.builder;if(Object.defineProperty(this,t,{configurable:!0,get:function(){const e=this._loadModule(t,r);return Object.defineProperty(this,t,{value:e}),e}}),-1!==t.indexOf("-")){const e=t.replace(/\-[a-z]/g,(function(e){return e[1].toUpperCase()}));Object.defineProperty(this,e,{get:function(){return this[t]}})}}_loadModule(e,t){if(t)return t(new f.default(this,"/"+e+"/"),new f.default(this,"/public/"+e+"/")).exports;throw"Unknown module: "+e}}t.RemoteStorage=P,P.Authorize=h.default,P.SyncError=w.default,P.Unauthorized=_.default,P.DiscoveryError=b.default.DiscoveryError,P.util=E,Object.defineProperty(P.prototype,"access",{get:function(){const e=new d.default;return Object.defineProperty(this,"access",{value:e}),e},configurable:!0}),Object.defineProperty(P.prototype,"caching",{configurable:!0,get:function(){const e=new p.default;return Object.defineProperty(this,"caching",{value:e}),e}}),(0,u.applyMixins)(P,[g.EventHandling]),t.default=P},368:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isArrayBufferView=void 0,t.retryAfterMs=function(e){const t=1e3*parseInt(e.getResponseHeader("Retry-After"));return t>=1e3?t:Math.max(1500,Math.min(6e4,Math.round(s.default.syncInterval/(2.9+.2*Math.random()))))},t.requestWithTimeout=function(e,r,i){return n(this,void 0,void 0,(function*(){return"function"==typeof fetch?function(e,t,r){return n(this,void 0,void 0,(function*(){const n="function"==typeof AbortController?new AbortController:null;let i;const a=new Promise(((e,t)=>{i=setTimeout((()=>{n&&n.abort(),t("timeout")}),s.default.requestTimeout)}));let c;const l={},u=fetch(t,{method:e,headers:r.headers,body:r.body,signal:n?n.signal:void 0}).then((e=>{switch((0,o.default)("[requests fetch]",e),e.headers.forEach(((e,t)=>{l[t.toUpperCase()]=e})),c={readyState:4,status:e.status,statusText:e.statusText,response:void 0,getResponseHeader:e=>l[e.toUpperCase()]||null,responseType:r.responseType,responseURL:t},r.responseType){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json();case void 0:case"":case"text":return e.text();default:throw new Error("responseType 'document' is not currently supported using fetch")}})).then((e=>(c.response=e,r.responseType&&"text"!==r.responseType||(c.responseText=e),c))).finally((()=>{clearTimeout(i)}));return Promise.race([u,a])}))}(e,r,i):"function"==typeof XMLHttpRequest?function(e,r,i){return n(this,void 0,void 0,(function*(){return new Promise(((n,a)=>{(0,o.default)("[requests XHR]",e,r);let c=!1;const l=setTimeout((()=>{c=!0,a("timeout")}),s.default.requestTimeout),u=new XMLHttpRequest;if(u.open(e,r,!0),i.responseType&&(u.responseType=i.responseType),i.headers)for(const e in i.headers)u.setRequestHeader(e,i.headers[e]);u.onload=()=>{c||(clearTimeout(l),n(u))},u.onerror=e=>{c||(clearTimeout(l),a(e))};let d=i.body;"object"==typeof d&&!(0,t.isArrayBufferView)(d)&&d instanceof ArrayBuffer&&(d=new Uint8Array(d)),u.send(d)}))}))}(e,r,i):Promise.reject("[Requests] You need to add a polyfill for fetch or XMLHttpRequest")}))};const o=i(r(3334)),s=i(r(7028));if("function"==typeof(r.g||window).ArrayBufferView)t.isArrayBufferView=function(e){return e&&e instanceof(r.g||window).ArrayBufferView};else{const e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];t.isArrayBufferView=function(t){for(let r=0;r<8;r++)if(t instanceof e[r])return!0;return!1}}},6941:function(e){"use strict";e.exports=class{constructor(e){this._itemsRev={},this._storage={},this._canPropagate=!1,this.defaultValue=e,this.activatePropagation()}get(e){e=e.toLowerCase();let t=this._storage[e];return void 0===t&&(t=this.defaultValue,this._storage[e]=t),t}set(e,t){return e=e.toLowerCase(),this._storage[e]===t||(this._storage[e]=t,t||delete this._itemsRev[e],this._updateParentFolderItemRev(e,t),this._canPropagate&&this._propagate(e)),t}delete(e){return this.set(e,null)}deactivatePropagation(){return this._canPropagate=!1,!0}activatePropagation(){return this._canPropagate||(this._generateFolderRev("/"),this._canPropagate=!0),!0}_hashCode(e){let t=0;if(0===e.length)return t;for(let r=0;r0&&(r=this._generateHash(e))}return this.set(e,r),r}}},6491:function(e){"use strict";class t extends Error{constructor(e){super();const t=new Error("Schema not found: "+e);return t.name="SchemaNotFound",t}}e.exports=t},6467:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=r(2452),s=r(4848),a=i(r(6424)),c=i(r(93)),l=r(7746),u=r(3684),d=i(r(7398)),h=i(r(8849)),f="remotestorage:solid";let p;class g extends u.RemoteBase{constructor(e){if(super(e),this.podURLs=null,this.online=!0,this.addEvents(["connected","not-connected","pod-not-selected"]),this.configStorage=new d.default(this),this.session=new o.Session({secureStorage:new o.InMemoryStorage,insecureStorage:this.configStorage},"any"),p=(0,l.localStorageAvailable)(),p){const e=(0,l.getJSONFromLocalStorage)(f);e&&this.configure(e)}}onConfigChanged(e){if(e){const t=JSON.parse(e);if(void 0!==t.clientSecret){let e=(0,l.getJSONFromLocalStorage)(f);return e||(e={}),e.href=this.authURL,e.properties={sessionProperties:t,podURL:this.selectedPodURL},this.sessionProperties=t,void localStorage.setItem(f,JSON.stringify(e))}}this.podURLs=null,localStorage.removeItem(f)}configure(e){if(void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.href&&(this.authURL=e.href),void 0!==e.properties){const t=e.properties;t?(void 0!==t.sessionProperties?this.sessionProperties=t.sessionProperties:this.sessionProperties=null,void 0!==t.podURL?this.selectedPodURL=t.podURL:this.selectedPodURL=null):(this.sessionProperties=null,this.selectedPodURL=null)}this.sessionProperties?(this.configStorage.setConfig(JSON.stringify(this.sessionProperties)),this.connected=this.session.info&&this.session.info.isLoggedIn,function(){p&&localStorage.setItem(f,JSON.stringify({userAddress:this.userAddress,href:this.authURL,properties:{sessionProperties:this.sessionProperties,podURL:this.selectedPodURL}}))}.apply(this)):function(){this.connected=!1,this.sessionProperties=null,this.podURLs=null,p&&localStorage.removeItem(f)}.apply(this)}setAuthURL(e){this.authURL=e}getPodURLs(){return this.podURLs}setPodURL(e){if(this.selectedPodURL!==e&&(this.selectedPodURL=e,this.session.info&&this.session.info.isLoggedIn))if(this.selectedPodURL){let e=(0,l.getJSONFromLocalStorage)(f);e||(e={}),e.userAddress=this.session.info.webId,e.href=this.authURL,e.properties={sessionProperties:this.sessionProperties,podURL:this.selectedPodURL},localStorage.setItem(f,JSON.stringify(e)),this.connected=!0,this._emit("connected")}else this.connected=!1,this.rs._emit("pod-not-selected")}getPodURL(){return this.selectedPodURL}connect(){this.rs.setBackend("solid"),this.authURL?this.session.login({oidcIssuer:this.authURL,redirectUrl:new URL("/",window.location.href).toString(),clientName:"Remote Storage"}):this.rs._emit("error",new Error("No authURL is configured."))}getSession(){return this.session.info&&this.session.info.isLoggedIn?this.session:null}getFileURL(e){return e.startsWith("/")&&(e=e.substring(1)),0===e.length&&(e="/"),this.selectedPodURL+e}get(e,t={}){const r=this.getFileURL(e);return"/"===e.slice(-1)?(0,s.getSolidDataset)(r,{fetch:this.session.fetch}).then((e=>{const t=(0,s.getContainedResourceUrlAll)(e).reduce(((t,n)=>{const i=n.substring(r.length),o=(0,s.getThing)(e,n);return t[i]={ETag:(0,s.getDecimal)(o,"http://www.w3.org/ns/posix/stat#mtime").toString(),"Last-Modified":(0,s.getDatetime)(o,"http://purl.org/dc/terms/modified").toUTCString()},"/"===i.slice(-1)||(t[i]["Content-Length"]=(0,s.getInteger)(o,"http://www.w3.org/ns/posix/stat#size")),t}),{});return Promise.resolve({statusCode:200,body:t,contentType:"application/json; charset=UTF-8"})})).catch((e=>e instanceof s.FetchError&&404===e.statusCode?Promise.resolve({statusCode:200,body:{},contentType:"application/json; charset=UTF-8"}):Promise.reject("Failed to get container: "+e.message))):(0,s.getFile)(r,{fetch:this.session.fetch}).then((e=>n(this,void 0,void 0,(function*(){return{statusCode:200,body:yield e.text(),contentType:(0,s.getContentType)(e)}})))).catch((e=>{const t=e.statusCode;return 401===t||403===t||404===t?{statusCode:t}:Promise.reject("Failed to get the file: "+e.message)}))}put(e,t,r,n={}){const i=this.getFileURL(e),o=this.session.fetch,a=function(){const e=function(e){if("object"==typeof e){if(e instanceof h.default)return e;if(e instanceof DataView)return new h.default([e],{type:"application/octet-stream"});if(e instanceof ArrayBuffer)return new h.default([new DataView(e)]);if(ArrayBuffer.isView(e))return new h.default([e],{type:"application/octet-stream"});if(e instanceof FormData)return new h.default([new URLSearchParams([JSON.parse(JSON.stringify(e.entries()))]).toString()],{type:"application/x-www-form-urlencoded"});if(e instanceof URLSearchParams)return new h.default([e.toString()],{type:"application/x-www-form-urlencoded"})}return"string"==typeof e?new h.default([e],{type:"plain/text"}):new h.default([JSON.stringify(e)],{type:"application/json"})}(t);return(0,s.overwriteFile)(i,e,{contentType:r,fetch:o}).then((e=>({statusCode:201}))).catch((e=>Promise.reject("PUT failed with status "+e.statusCode+" ("+e.message+")")))};return(0,s.getFile)(i,{fetch:o}).then((e=>n&&"*"===n.ifNoneMatch?{statusCode:412,revision:"conflict"}:a())).catch((e=>{const t=e.statusCode;return 404===t?a():Promise.reject("PUT failed with status "+t+" ("+e.message+")")}))}delete(e,t={}){const r=this.getFileURL(e);return(0,s.deleteFile)(r,{fetch:this.session.fetch}).then((()=>({statusCode:200}))).catch((e=>{const t=e.statusCode;return 404===t?{statusCode:200}:Promise.reject("DELETE failed with status "+t+" ("+e.message+")")}))}static _rs_init(e){const t=new g(e);var r;e.solid=t,"solid"===e.backend&&(e._origRemote=e.remote,e.remote=e.solid,(r=e)._origBaseClientGetItemURL||(r._origBaseClientGetItemURL=a.default.prototype.getItemURL,a.default.prototype.getItemURL=function(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(e.startsWith("/")&&(e=e.substring(1)),this.selectedPodURL+(0,l.cleanPath)(e)):void 0}),(()=>{n(this,void 0,void 0,(function*(){const r=t.session;if(yield r.handleIncomingRedirect(),r.info.isLoggedIn){const n=r.info.webId;t.userAddress=n,t.selectedPodURL?t._emit("connected"):(t.podURLs=yield(0,s.getPodUrlAll)(n,{fetch:fetch}),e._emit("pod-not-selected"))}else t.sessionProperties&&t.connect()}))})())}static _rs_supported(){return!0}static _rs_cleanup(e){var t;e.setBackend(void 0),e._origRemote&&(e.remote=e._origRemote,delete e._origRemote),(t=e)._origBaseClientGetItemURL&&(a.default.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)}}(0,l.applyMixins)(g,[c.default]),e.exports=g},7398:function(e,t){"use strict";var r=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});class n{get storage(){return window.localStorage}get(e){return r(this,void 0,void 0,(function*(){return this.storage.getItem(e)||void 0}))}set(e,t){return r(this,void 0,void 0,(function*(){this.storage.setItem(e,t)}))}delete(e){return r(this,void 0,void 0,(function*(){this.storage.removeItem(e)}))}}t.default=class{constructor(e){this.browserStorage=new n,this.observer=e}isConfigKey(e){return e.startsWith("solidClientAuthenticationUser")}setConfig(e){this.config=e}get(e){return r(this,void 0,void 0,(function*(){if(this.isConfigKey(e))return this.config;this.browserStorage.get(e)}))}set(e,t){return r(this,void 0,void 0,(function*(){if(this.isConfigKey(e)){if(this.config){const e=JSON.parse(this.config),r=JSON.parse(t),n=Object.assign(Object.assign({},e),r);this.config=JSON.stringify(n)}else this.config=t;this.observer.onConfigChanged(this.config)}else this.browserStorage.set(e,t)}))}delete(e){return r(this,void 0,void 0,(function*(){this.isConfigKey(e)?(this.config=void 0,this.observer.onConfigChanged(this.config)):this.browserStorage.delete(e)}))}}},6982:function(e){"use strict";class t extends Error{constructor(e){super(),this.name="SyncError",this.message="Sync failed: ","string"==typeof e?this.message+=e:(this.message+=e.message,this.stack=e.stack,this.originalError=e)}}e.exports=t},313:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Sync=void 0;const o=i(r(7028)),s=i(r(9451)),a=i(r(93)),c=i(r(3334)),l=i(r(3275)),u=i(r(6982)),d=i(r(5503)),h=r(7746);let f,p;function g(e,t,r){return{action:e,path:t,promise:r}}function y(e,t){return e.common.revision!==t&&(!e.remote||e.remote.revision!==t)}function m(e){return e.common&&e.common.revision}class v{constructor(e){this._finishedTasks=[],this.rs=e,this._tasks={},this._running={},this._timeStarted={},this.numThreads=10,this.rs.local.onDiff((e=>{this.addTask(e),this.doTasks()})),this.rs.caching.onActivate((e=>{this.addTask(e),this.doTasks()})),this.addEvents(["done","req-done"])}now(){return(new Date).getTime()}queueGetRequest(e){return new Promise(((t,r)=>{this.rs.remote.connected?this.rs.remote.online?(this.addTask(e,function(){this.rs.local.get(e).then((e=>t(e)))}.bind(this)),this.doTasks()):r("cannot fulfill maxAge requirement - remote is not online"):r("cannot fulfill maxAge requirement - remote is not connected")}))}corruptServerItemsMap(e,t){if("object"!=typeof e||Array.isArray(e))return!0;for(const r in e){const n=e[r];if("object"!=typeof n)return!0;if("string"!=typeof n.ETag)return!0;if((0,h.isFolder)(r)){if(-1!==r.substring(0,r.length-1).indexOf("/"))return!0}else{if(-1!==r.indexOf("/"))return!0;if(t){if("string"!=typeof n["Content-Type"])return!0;if("number"!=typeof n["Content-Length"])return!0}}}return!1}corruptItemsMap(e){if("object"!=typeof e||Array.isArray(e))return!0;for(const t in e)if("boolean"!=typeof e[t])return!0;return!1}corruptRevision(e){return"object"!=typeof e||Array.isArray(e)||e.revision&&"string"!=typeof e.revision||e.body&&"string"!=typeof e.body&&"object"!=typeof e.body||e.contentType&&"string"!=typeof e.contentType||e.contentLength&&"number"!=typeof e.contentLength||e.timestamp&&"number"!=typeof e.timestamp||e.itemsMap&&this.corruptItemsMap(e.itemsMap)}isCorrupt(e){return"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.path||this.corruptRevision(e.common)||e.local&&this.corruptRevision(e.local)||e.remote&&this.corruptRevision(e.remote)||e.push&&this.corruptRevision(e.push)}hasTasks(){return Object.getOwnPropertyNames(this._tasks).length>0}collectDiffTasks(){return n(this,void 0,void 0,(function*(){let e=0;return this.rs.local.forAllNodes((t=>{e>100||(this.isCorrupt(t)?((0,c.default)("[Sync] WARNING: corrupt node in local cache",t),"object"==typeof t&&t.path&&(this.addTask(t.path),e++)):(this.needsFetch(t)&&this.rs.access.checkPathPermission(t.path,"r")||(0,h.isDocument)(t.path)&&this.needsPush(t)&&this.rs.access.checkPathPermission(t.path,"rw"))&&(this.addTask(t.path),e++))})).then((()=>e)).catch((e=>{throw e}))}))}inConflict(e){return e.local&&e.remote&&(void 0!==e.remote.body||e.remote.itemsMap)}needsRefresh(e){return!!e.common&&(!e.common.timestamp||this.now()-e.common.timestamp>o.default.syncInterval)}needsFetch(e){return!!this.inConflict(e)||!(!e.common||void 0!==e.common.itemsMap||void 0!==e.common.body)||!(!e.remote||void 0!==e.remote.itemsMap||void 0!==e.remote.body)}needsPush(e){return!this.inConflict(e)&&(!(!e.local||e.push)||void 0)}needsRemotePut(e){return e.local&&e.local.body}needsRemoteDelete(e){return e.local&&!1===e.local.body}getParentPath(e){const t=e.match(/^(.*\/)([^\/]+\/?)$/);if(t)return t[1];throw new Error('Not a valid path: "'+e+'"')}deleteChildPathsFromTasks(){for(const e in this._tasks){const t=(0,h.pathsFromRoot)(e);for(let r=1;r{let t;if(this.needsRefresh(e)){try{t=this.getParentPath(e.path)}catch(e){}t&&this.rs.access.checkPathPermission(t,"r")?this.addTask(t):this.rs.access.checkPathPermission(e.path,"r")&&this.addTask(e.path)}})).then((()=>this.deleteChildPathsFromTasks())).catch((e=>{throw e}))}))}flush(e){for(const t in e)"FLUSH"===this.rs.caching.checkPath(t)&&e[t]&&!e[t].local&&((0,c.default)("[Sync] Flushing",t),e[t]=void 0);return e}doTask(e){return this.rs.local.getNodes([e]).then((t=>{const r=t[e];return void 0===r||function(e){return e.remote&&e.remote.revision&&!e.remote.itemsMap&&!e.remote.body}(r)?g("get",e,this.rs.remote.get(e)):this.needsRemotePut(r)?(r.push=(0,h.deepClone)(r.local),r.push.timestamp=this.now(),this.rs.local.setNodes(this.flush(t)).then((()=>{let t;return t=m(r)?{ifMatch:r.common.revision}:{ifNoneMatch:"*"},g("put",e,this.rs.remote.put(e,r.push.body,r.push.contentType,t))}))):this.needsRemoteDelete(r)?(r.push={body:!1,timestamp:this.now()},this.rs.local.setNodes(this.flush(t)).then((()=>m(r)?g("delete",e,this.rs.remote.delete(e,{ifMatch:r.common.revision})):g("get",e,this.rs.remote.get(e))))):m(r)?g("get",e,this.rs.remote.get(e,{ifNoneMatch:r.common.revision})):g("get",e,this.rs.remote.get(e))}))}autoMergeFolder(e){if(e.remote.itemsMap&&(e.common=e.remote,delete e.remote,e.common.itemsMap)){for(const t in e.common.itemsMap)e.local.itemsMap[t]||(e.local.itemsMap[t]=!1);(0,h.equal)(e.local.itemsMap,e.common.itemsMap)&&delete e.local}return e}autoMergeDocument(e){return function(e){return(!e.remote||!e.remote.revision||e.remote.revision===e.common.revision)&&(void 0===e.common.body&&!1===e.remote.body||e.remote.body===e.common.body&&e.remote.contentType===e.common.contentType)}(e)?delete(e=function(e){return e.remote&&!1===e.remote.body&&e.local&&!1===e.local.body&&delete e.local,e}(e)).remote:void 0!==e.remote.body&&((0,c.default)("[Sync] Emitting keep/revert"),this.rs.local._emitChange({origin:"conflict",path:e.path,oldValue:e.local.body,newValue:e.remote.body,lastCommonValue:e.common.body,oldContentType:e.local.contentType,newContentType:e.remote.contentType,lastCommonContentType:e.common.contentType}),e.remote.body?e.common=e.remote:e.common={},delete e.remote,delete e.local),e}autoMerge(e){if(e.remote){if(e.local)return(0,h.isFolder)(e.path)?this.autoMergeFolder(e):this.autoMergeDocument(e);if((0,h.isFolder)(e.path))void 0!==e.remote.itemsMap&&(e.common=e.remote,delete e.remote);else if(void 0!==e.remote.body){const t={origin:"remote",path:e.path,oldValue:!1===e.common.body?void 0:e.common.body,newValue:!1===e.remote.body?void 0:e.remote.body,oldContentType:e.common.contentType,newContentType:e.remote.contentType};if((t.oldValue||t.newValue)&&this.rs.local._emitChange(t),!e.remote.body)return;e.common=e.remote,delete e.remote}return e}e.common.body&&this.rs.local._emitChange({origin:"remote",path:e.path,oldValue:e.common.body,newValue:void 0,oldContentType:e.common.contentType,newContentType:void 0})}updateCommonTimestamp(e,t){return n(this,void 0,void 0,(function*(){return this.rs.local.getNodes([e]).then((r=>(r[e]&&r[e].common&&r[e].common.revision===t&&(r[e].common.timestamp=this.now()),this.rs.local.setNodes(this.flush(r)))))}))}markChildren(e,t,r,i){return n(this,void 0,void 0,(function*(){const n=[],o={},s={};for(const r in t)n.push(e+r),o[e+r]=t[r];for(const t in i)n.push(e+t);return this.rs.local.getNodes(n).then((t=>{let n,a;for(const c in t)if(a=t[c],o[c])a&&a.common?y(a,o[c].ETag)&&(r[c]=(0,h.deepClone)(a),r[c].remote={revision:o[c].ETag,timestamp:this.now()},r[c]=this.autoMerge(r[c])):(n=this.rs.caching.checkPath(c),"ALL"===n&&(r[c]={path:c,common:{timestamp:this.now()},remote:{revision:o[c].ETag,timestamp:this.now()}})),r[c]&&o[c]["Content-Type"]&&(r[c].remote.contentType=o[c]["Content-Type"]),r[c]&&o[c]["Content-Length"]&&(r[c].remote.contentLength=o[c]["Content-Length"]);else if(i[c.substring(e.length)]&&a&&a.common){if(a.common.itemsMap)for(const e in a.common.itemsMap)s[c+e]=!0;if(a.local&&a.local.itemsMap)for(const e in a.local.itemsMap)s[c+e]=!0;if(a.remote||(0,h.isFolder)(c))r[c]=void 0;else if(r[c]=this.autoMerge(a),void 0===r[c]){const t=this.getParentPath(c),n=r[t],i=c.substring(e.length);n&&n.local&&(delete n.local.itemsMap[i],(0,h.equal)(n.local.itemsMap,n.common.itemsMap)&&delete n.local)}}return this.deleteRemoteTrees(Object.keys(s),r).then((e=>this.rs.local.setNodes(this.flush(e))))}))}))}deleteRemoteTrees(e,t){return n(this,void 0,void 0,(function*(){return 0===e.length?Promise.resolve(t):this.rs.local.getNodes(e).then((e=>n(this,void 0,void 0,(function*(){const r={};function n(e,t){if(e&&e.itemsMap)for(const n in e.itemsMap)r[t+n]=!0}for(const r in e){const i=e[r];i&&((0,h.isFolder)(r)?(n(i.common,r),n(i.local,r)):i.common&&void 0!==typeof i.common.body&&(t[r]=(0,h.deepClone)(i),t[r].remote={body:!1,timestamp:this.now()},t[r]=this.autoMerge(t[r])))}return this.deleteRemoteTrees(Object.keys(r),t).then((e=>this.rs.local.setNodes(this.flush(e))))}))))}))}completeFetch(e,t,r,i){return n(this,void 0,void 0,(function*(){let n,o;const s=(0,h.pathsFromRoot)(e);return(0,h.isFolder)(e)?n=[e]:(o=s[1],n=[e,o]),this.rs.local.getNodes(n).then((n=>{let s,a,c=n[e];const l={};function u(e){if(e&&e.itemsMap)for(s in e.itemsMap)t[s]||(l[s]=!0)}if("object"==typeof c&&c.path===e&&"object"==typeof c.common||(c={path:e,common:{}},n[e]=c),c.remote={revision:i,timestamp:this.now()},(0,h.isFolder)(e))for(s in u(c.common),u(c.remote),c.remote.itemsMap={},t)c.remote.itemsMap[s]=!0;else c.remote.body=t,c.remote.contentType=r,a=n[o],a&&a.local&&a.local.itemsMap&&(s=e.substring(o.length),a.local.itemsMap[s]=!0,(0,h.equal)(a.local.itemsMap,a.common.itemsMap)&&delete a.local);return n[e]=this.autoMerge(c),{toBeSaved:n,missingChildren:l}}))}))}completePush(e,t,r,i){return n(this,void 0,void 0,(function*(){return this.rs.local.getNodes([e]).then((n=>{const o=n[e];if(!o.push)throw this.stopped=!0,new Error("completePush called but no push version!");return r?((0,c.default)("[Sync] We have a conflict"),o.remote&&o.remote.revision===i||(o.remote={revision:i||"conflict",timestamp:this.now()},delete o.push),n[e]=this.autoMerge(o)):(o.common={revision:i,timestamp:this.now()},"put"===t?(o.common.body=o.push.body,o.common.contentType=o.push.contentType,(0,h.equal)(o.local.body,o.push.body)&&o.local.contentType===o.push.contentType&&delete o.local,delete o.push):"delete"===t&&(!1===o.local.body?n[e]=void 0:delete o.push)),this.rs.local.setNodes(this.flush(n))}))}))}dealWithFailure(e){return n(this,void 0,void 0,(function*(){return this.rs.local.getNodes([e]).then((t=>{if(t[e])return delete t[e].push,this.rs.local.setNodes(this.flush(t))}))}))}interpretStatus(e){const t={statusCode:e,successful:void 0,conflict:void 0,unAuth:void 0,notFound:void 0,changed:void 0,networkProblems:void 0};if("string"==typeof e&&("offline"===e||"timeout"===e))return t.successful=!1,t.networkProblems=!0,t;if("number"==typeof e){const r=Math.floor(e/100);return t.successful=2===r||304===e||412===e||404===e,t.conflict=412===e,t.unAuth=401===e&&this.rs.remote.token!==l.default.IMPLIED_FAKE_TOKEN||402===e||403===e,t.notFound=404===e,t.changed=304!==e,t}}handleGetResponse(e,t,r,i,o){return n(this,void 0,void 0,(function*(){return t.notFound&&(r=!!(0,h.isFolder)(e)&&{}),t.changed?this.completeFetch(e,r,i,o).then((t=>(0,h.isFolder)(e)?this.corruptServerItemsMap(r)?((0,c.default)("[Sync] WARNING: Discarding corrupt folder description from server for "+e),!1):this.markChildren(e,r,t.toBeSaved,t.missingChildren).then((()=>!0)):this.rs.local.setNodes(this.flush(t.toBeSaved)).then((()=>!0)))):this.updateCommonTimestamp(e,o).then((()=>!0))}))}handleResponse(e,t,r){const n=this.interpretStatus(r.statusCode);if(n.successful){if("get"===t)return this.handleGetResponse(e,n,r.body,r.contentType,r.revision);if("put"===t||"delete"===t)return this.completePush(e,t,n.conflict,r.revision).then((function(){return!0}));throw new Error(`cannot handle response for unknown action ${t}`)}{let t;return t=n.unAuth?new d.default:n.networkProblems?new u.default("Network request failed."):new Error("HTTP response code "+n.statusCode+" received."),this.dealWithFailure(e).then((()=>{throw this.rs._emit("error",t),t}))}}finishTask(e,t=!0){if(void 0!==e.action){if(!(t&&((0,c.default)("[Sync] queue finished task:",e.path),this._finishedTasks.push(e),this._finishedTasks.length>1)))return(0,c.default)("[Sync] run task:",e.path),e.promise.then((t=>this.handleResponse(e.path,e.action,t)),(t=>((0,c.default)("[Sync] wireclient rejects its promise!",e.path,e.action,t),this.handleResponse(e.path,e.action,{statusCode:"offline"})))).then((t=>n(this,void 0,void 0,(function*(){if(this._finishedTasks.shift(),delete this._timeStarted[e.path],delete this._running[e.path],t&&this._tasks[e.path]){for(let t=0;t0?this.finishTask(this._finishedTasks[0],!1):yield this.collectTasks(!1).then((()=>{!this.hasTasks()||this.stopped?((0,c.default)("[Sync] Sync is done! Reschedule?",Object.getOwnPropertyNames(this._tasks).length,this.stopped),this.done||(this.done=!0,this.rs._emit("sync-done",{completed:!0}))):setTimeout((()=>{this.doTasks()}),10)}))}))),(t=>{(0,c.default)("[Sync] Error",t),this._finishedTasks.shift(),delete this._timeStarted[e.path],delete this._running[e.path],this.rs._emit("sync-req-done",{tasksRemaining:Object.keys(this._tasks).length}),this._finishedTasks.length>0?this.finishTask(this._finishedTasks[0],!1):this.done||(this.done=!0,this.rs._emit("sync-done",{completed:!1}))}));(0,c.default)("[Sync] delaying finished task:",e.path)}else delete this._running[e.path]}doTasks(){let e,t,r=0;e=this.rs.remote.connected?this.rs.remote.online?this.numThreads:1:0;const n=e-Object.getOwnPropertyNames(this._running).length;if(n<=0)return!0;for(t in this._tasks)if(!this._running[t]&&(this._timeStarted[t]=this.now(),this._running[t]=this.doTask(t),this._running[t].then(this.finishTask.bind(this)),r++,r>=n))return!0;return r>=n}collectTasks(e){return n(this,void 0,void 0,(function*(){return this.hasTasks()||this.stopped?Promise.resolve():this.collectDiffTasks().then((t=>t||!1===e?Promise.resolve():this.collectRefreshTasks()),(function(e){throw e}))}))}addTask(e,t){this._tasks[e]||(this._tasks[e]=[]),"function"==typeof t&&this._tasks[e].push(t)}sync(){return this.done=!1,this.doTasks()?Promise.resolve():this.collectTasks().then((()=>{try{this.doTasks()}catch(e){(0,c.default)("[Sync] doTasks error",e)}}),(function(e){throw(0,c.default)("[Sync] Sync error",e),new Error("Local cache unavailable")}))}static _rs_init(e){f=function(){(0,c.default)("[Sync] syncCycleCb calling syncCycle");const t=new s.default;t.isBrowser()&&function(e,t){function r(e){const r=t.getCurrentSyncInterval();o.default.isBackground=!e;const n=t.getCurrentSyncInterval();t._emit("sync-interval-change",{oldValue:r,newValue:n})}e.on("background",(()=>r(!1))),e.on("foreground",(()=>r(!0)))}(t,e),e.sync||(e.sync=new v(e),e.syncStopped&&((0,c.default)("[Sync] Instantiating sync stopped"),e.sync.stopped=!0,delete e.syncStopped)),(0,c.default)("[Sync] syncCycleCb calling syncCycle"),e.syncCycle()},p=function(){e.removeEventListener("connected",p),e.startSync()},e.on("ready",f),e.on("connected",p)}static _rs_cleanup(e){e.stopSync(),e.removeEventListener("ready",f),e.removeEventListener("connected",p),e.sync=void 0,delete e.sync}}t.Sync=v,(0,h.applyMixins)(v,[a.default]),t.default=v},1370:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};const i=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(3334));function o(e){return"dropbox"===this.backend&&!!e.match(/^\/public\/.*[^\/]$/)}const s={get:function(e,t){if(this.local){if(void 0===t)t="object"==typeof(r=this).remote&&r.remote.connected&&r.remote.online?2*r.getSyncInterval():((0,i.default)("Not setting default maxAge, because remote is offline or not connected"),!1);else if("number"!=typeof t&&!1!==t)return Promise.reject("Argument 'maxAge' must be 'false' or a number");return this.local.get(e,t,this.sync.queueGetRequest.bind(this.sync))}return this.remote.get(e);var r},put:function(e,t,r){return o.bind(this)(e)?s._wrapBusyDone.call(this,this.remote.put(e,t,r)):this.local?this.local.put(e,t,r):s._wrapBusyDone.call(this,this.remote.put(e,t,r))},delete:function(e){return this.local?this.local.delete(e):s._wrapBusyDone.call(this,this.remote.delete(e))},_wrapBusyDone:function(e){return n(this,void 0,void 0,(function*(){return this._emit("wire-busy"),e.then((e=>(this._emit("wire-done",{success:!0}),Promise.resolve(e))),(e=>(this._emit("wire-done",{success:!1}),Promise.reject(e))))}))}};e.exports=s},1613:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClientTypes=void 0;class r{constructor(){this.uris={},this.schemas={},this.aliases={}}declare(e,t,r,n){const i=e+"/"+t;if(n.extends){const t=n.extends.split("/"),r=1===t.length?e+"/"+t.shift():t.join("/"),o=this.uris[r];if(!o)throw"Type '"+i+"' tries to extend unknown schema '"+r+"'";n.extends=this.schemas[o]}this.uris[i]=r,this.aliases[r]=i,this.schemas[r]=n}resolveAlias(e){return this.uris[e]}getSchema(e){return this.schemas[e]}inScope(e){const t=e.length,r={};for(const n in this.uris)if(n.substr(0,t+1)===e+"/"){const e=this.uris[n];r[e]=this.schemas[e]}return r}}t.BaseClientTypes=r;const n=new r;t.default=n},5503:function(e){"use strict";class t extends Error{constructor(e,t={}){super(),this.name="Unauthorized",this.message=void 0===e?"App authorization expired or revoked.":e,void 0!==t.code&&(this.code=t.code),this.stack=(new Error).stack}}e.exports=t},7746:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};function i(e,t){if("object"==typeof e&&!Array.isArray(e)&&null!==e)for(const r in e)if("object"==typeof e[r]&&null!==e[r])if("[object ArrayBuffer]"===e[r].toString()){t[r]=new ArrayBuffer(e[r].byteLength);const n=new Int8Array(e[r]);new Int8Array(t[r]).set(n)}else i(e[r],t[r])}Object.defineProperty(t,"__esModule",{value:!0}),t.toBase64=t.getTextFromArrayBuffer=t.shouldBeTreatedAsBinary=t.getJSONFromLocalStorage=t.localStorageAvailable=t.pathsFromRoot=t.deepClone=t.equal=t.bindAll=t.cleanPath=t.baseName=t.isDocument=t.isFolder=t.containingFolder=t.extend=t.getGlobalContext=t.globalContext=t.logError=void 0,t.generateCodeVerifier=function(){return n(this,arguments,void 0,(function*(e=128){const t=new Uint8Array(e);crypto.getRandomValues(t);const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=Array.from(t).map((e=>r[e%66])),i=n.join(""),o=Uint8Array.from(n.map((e=>e.charCodeAt(0)))),s=(a=yield crypto.subtle.digest("SHA-256",o),btoa(String.fromCharCode.apply(null,new Uint8Array(a))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""));var a;return crypto.getRandomValues(t),{codeVerifier:i,codeChallenge:s,state:Array.from(t).map((e=>r[e%66])).join("")}}))},t.applyMixins=function(e,t){t.forEach((t=>{Object.getOwnPropertyNames(t.prototype).forEach((r=>{Object.defineProperty(e.prototype,r,Object.getOwnPropertyDescriptor(t.prototype,r))}))}))},t.logError=e=>{"string"==typeof e?console.error(e):console.error(e.message,e.stack)},t.globalContext="undefined"!=typeof window?window:"object"==typeof self?self:r.g,t.getGlobalContext=()=>"undefined"!=typeof window?window:"object"==typeof self?self:r.g,t.extend=(...e)=>{const t=e[0];return Array.prototype.slice.call(e,1).forEach((function(e){for(const r in e)t[r]=e[r]})),t},t.containingFolder=e=>{if(""===e)return"/";if(!e)throw"Path not given!";return e.replace(/\/+/g,"/").replace(/[^\/]+\/?$/,"")},t.isFolder=e=>"/"===e.slice(-1),t.isDocument=e=>!(0,t.isFolder)(e),t.baseName=e=>{const r=e.split("/");return(0,t.isFolder)(e)?r[r.length-2]+"/":r[r.length-1]},t.cleanPath=e=>e.replace(/\/+/g,"/").split("/").map(encodeURIComponent).join("/").replace(/'/g,"%27"),t.bindAll=e=>{for(const t in this)"function"==typeof e[t]&&(e[t]=e[t].bind(e))},t.equal=(e,r,n=[])=>{let i;if(typeof e!=typeof r)return!1;if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return e===r;if("function"==typeof e)return e.toString()===r.toString();if(e instanceof ArrayBuffer&&r instanceof ArrayBuffer&&(e=new Uint8Array(e),r=new Uint8Array(r)),e instanceof Array){if(e.length!==r.length)return!1;for(let i=0,o=e.length;i=0)continue;o=n.slice(),o.push(r[i])}if(!(0,t.equal)(e[i],r[i],o))return!1}}return!0},t.deepClone=e=>{if(void 0!==e){const t=JSON.parse(JSON.stringify(e));return i(e,t),t}},t.pathsFromRoot=e=>{const t=[e],r=e.replace(/\/$/,"").split("/");for(;r.length>1;)r.pop(),t.push(r.join("/")+"/");return t},t.localStorageAvailable=()=>{const e=(0,t.getGlobalContext)();if(!("localStorage"in e))return!1;try{return e.localStorage.setItem("rs-check","1"),e.localStorage.removeItem("rs-check"),!0}catch(e){return!1}},t.getJSONFromLocalStorage=e=>{const r=(0,t.getGlobalContext)();try{return JSON.parse(r.localStorage.getItem(e))}catch(e){}},t.shouldBeTreatedAsBinary=(e,t)=>!!(t&&t.match(/charset=binary/)||/[\x00-\x08\x0E-\x1F\uFFFD]/.test(e)),t.getTextFromArrayBuffer=(e,r)=>new Promise((n=>{if("undefined"==typeof Blob||"undefined"==typeof FileReader){const t=Buffer.from(e);n(t.toString(r))}else{let i;const o=t.globalContext;if(o.BlobBuilder=o.BlobBuilder||o.WebKitBlobBuilder,void 0!==o.BlobBuilder){const t=new o.BlobBuilder;t.append(e),i=t.getBlob()}else i=new Blob([e]);const s=new FileReader;"function"==typeof s.addEventListener?s.addEventListener("loadend",(function(e){n(e.target.result)})):s.onloadend=function(e){n(e.target.result)},s.readAsText(i,r)}})),t.toBase64=e=>{const r=(0,t.getGlobalContext)();return"btoa"in r?r.btoa(e):Buffer.from(e).toString("base64")}},600:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(3275)),s=i(r(93)),a=i(r(5503)),c=i(r(3334)),l=r(7746),u=r(368),d=r(3684);let h;const f="remotestorage:wireclient",p={"draft-dejong-remotestorage-00":2,"draft-dejong-remotestorage-01":3,"draft-dejong-remotestorage-02":4,"https://www.w3.org/community/rww/wiki/read-write-web-00#simple":1};class g extends d.RemoteBase{constructor(e){if(super(e),this._revisionCache={},h=(0,l.localStorageAvailable)(),this.addEvents(["connected","not-connected"]),h){const e=function(){const e=(0,l.getJSONFromLocalStorage)(f)||{},{userAddress:t,href:r,storageApi:n,token:i,properties:o}=e;return{userAddress:t,href:r,storageApi:n,token:i,properties:o}}();e&&setTimeout((()=>{this.configure(e)}),0)}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}get storageType(){if(this.storageApi){const e=this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/);return e?e[1]:"2012.04"}}_request(e,t,r,i,s,d,h){return n(this,void 0,void 0,(function*(){if(this.isForbiddenRequestMethod(e,t))return Promise.reject(`Don't use ${e} on directories!`);let n;return r!==o.default.IMPLIED_FAKE_TOKEN&&(i.Authorization="Bearer "+r),this.rs._emit("wire-busy",{method:e,isFolder:(0,l.isFolder)(t)}),(0,u.requestWithTimeout)(e,t,{body:s,headers:i,responseType:"arraybuffer"}).then((r=>{if(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,l.isFolder)(t),success:!0}),i=r.status,[401,403,404,412].indexOf(i)>=0)return(0,c.default)("[WireClient] Error response status",r.status),n=d?this.stripQuotes(r.getResponseHeader("ETag")):void 0,401===r.status&&this.rs._emit("error",new a.default),Promise.resolve({statusCode:r.status,revision:n});if(function(e){return[201,204,304].indexOf(e)>=0}(r.status)||200===r.status&&"GET"!==e)return n=this.stripQuotes(r.getResponseHeader("ETag")),(0,c.default)("[WireClient] Successful request",n),Promise.resolve({statusCode:r.status,revision:n});{const e=r.getResponseHeader("Content-Type");n=d?this.stripQuotes(r.getResponseHeader("ETag")):200===r.status?h:void 0;const t=function(e){let t,r="utf-8";return e&&(t=e.match(/charset=(.+)$/),t&&(r=t[1])),r}(e);return(0,l.shouldBeTreatedAsBinary)(r.response,e)?((0,c.default)("[WireClient] Successful request with unknown or binary mime-type",n),Promise.resolve({statusCode:r.status,body:r.response,contentType:e,revision:n})):(0,l.getTextFromArrayBuffer)(r.response,t).then((t=>((0,c.default)("[WireClient] Successful request",n),Promise.resolve({statusCode:r.status,body:t,contentType:e,revision:n}))))}var i}),(r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,l.isFolder)(t),success:!1}),Promise.reject(r))))}))}configure(e){if("object"!=typeof e)throw new Error("WireClient configure settings parameter should be an object");if(void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.href&&(this.href=e.href),void 0!==e.storageApi&&(this.storageApi=e.storageApi),void 0!==e.token&&(this.token=e.token),void 0!==e.properties&&(this.properties=e.properties),"string"==typeof this.storageApi){const e=p[this.storageApi]||5;this.supportsRevs=e>=2}this.href&&this.token?(this.connected=!0,this.online=!0,this._emit("connected")):this.connected=!1,h&&(localStorage[f]=JSON.stringify({userAddress:this.userAddress,href:this.href,storageApi:this.storageApi,token:this.token,properties:this.properties}))}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const r={};return this.supportsRevs&&t.ifNoneMatch&&(r["If-None-Match"]=this.addQuotes(t.ifNoneMatch)),this._request("GET",this.href+(0,l.cleanPath)(e),this.token,r,void 0,this.supportsRevs,this._revisionCache[e]).then((t=>{if(!(0,l.isFolder)(e))return Promise.resolve(t);let r={};if(void 0!==t.body)try{t.body=JSON.parse(t.body)}catch(t){return Promise.reject("Folder description at "+this.href+(0,l.cleanPath)(e)+" is not JSON")}if(200===t.statusCode&&"object"==typeof t.body){if(0===Object.keys(t.body).length)t.statusCode=404;else if("http://remotestorage.io/spec/folder-description"===(n=t.body)["@context"]&&"object"==typeof n.items){for(const r in t.body.items)this._revisionCache[e+r]=t.body.items[r].ETag;r=t.body.items}else Object.keys(t.body).forEach((n=>{this._revisionCache[e+n]=t.body[n],r[n]={ETag:t.body[n]}}));return t.body=r,Promise.resolve(t)}return Promise.resolve(t);var n}))}put(e,t,r,n={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");!r.match(/charset=/)&&(t instanceof ArrayBuffer||(0,u.isArrayBufferView)(t))&&(r+="; charset=binary");const i={"Content-Type":r};return this.supportsRevs&&(n.ifMatch&&(i["If-Match"]=this.addQuotes(n.ifMatch)),n.ifNoneMatch&&(i["If-None-Match"]=this.addQuotes(n.ifNoneMatch))),this._request("PUT",this.href+(0,l.cleanPath)(e),this.token,i,t,this.supportsRevs)}delete(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");t||(t={});const r={};return this.supportsRevs&&t.ifMatch&&(r["If-Match"]=this.addQuotes(t.ifMatch)),this._request("DELETE",this.href+(0,l.cleanPath)(e),this.token,r,void 0,this.supportsRevs)}static _rs_init(e){e.remote=new g(e),e.remote.online=!0}static _rs_supported(){return"function"==typeof fetch||"function"==typeof XMLHttpRequest}static _rs_cleanup(){h&&delete localStorage[f]}}(0,l.applyMixins)(g,[s.default]),e.exports=g},439:function(e,t){var r,n;r=function(){var e,t,r,n;Object.keys||(Object.keys=(e=Object.prototype.hasOwnProperty,t=!{toString:null}.propertyIsEnumerable("toString"),n=(r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length,function(i){if("object"!=typeof i&&"function"!=typeof i||null===i)throw new TypeError("Object.keys called on non-object");var o=[];for(var s in i)e.call(i,s)&&o.push(s);if(t)for(var a=0;a>>0;if(0===r)return-1;var n=0;if(arguments.length>1&&((n=Number(arguments[1]))!=n?n=0:0!==n&&n!==1/0&&n!==-1/0&&(n=(n>0||-1)*Math.floor(Math.abs(n)))),n>=r)return-1;for(var i=n>=0?n:Math.max(r-Math.abs(n),0);i0&&(t+=u.suffices["*"]&&r||",",u.suffices["*"]&&c&&(t+=u.name+"=")),t+=a?encodeURIComponent(d[f]).replace(/!/g,"%21"):s(d[f])}else if("object"==typeof d){c&&!u.suffices["*"]&&(t+=u.name+"=");var p=!0;for(var g in d)p||(t+=u.suffices["*"]&&r||","),p=!1,t+=a?encodeURIComponent(g).replace(/!/g,"%21"):s(g),t+=u.suffices["*"]?"=":",",t+=a?encodeURIComponent(d[g]).replace(/!/g,"%21"):s(d[g])}else c&&(t+=u.name,l&&""===d||(t+="=")),null!=u.truncate&&(d=d.substring(0,u.truncate)),t+=a?encodeURIComponent(d).replace(/!/g,"%21"):s(d)}return t};return w.varNames=u,{prefix:n,substitution:w}}function c(e){if(!(this instanceof c))return new c(e);for(var t=e.split("{"),r=[t.shift()],n=[],i=[],o=[];t.length>0;){var s=t.shift(),l=s.split("}")[0],u=s.substring(l.length+1),d=a(l);i.push(d.substitution),n.push(d.prefix),r.push(u),o=o.concat(d.substitution.varNames)}this.fill=function(e){for(var t=r[0],n=0;n0&&"/"===t.charAt(e.length-1)||"#"===r.charAt(0)||"?"===r.charAt(0))return!0}return!1}(t,e.id)&&void 0===this.schemas[e.id]&&(this.schemas[e.id]=e),e)if("enum"!==n)if("object"==typeof e[n])this.searchSchemas(e[n],t);else if("$ref"===n){var i=g(e[n]);i&&void 0===this.schemas[i]&&void 0===this.missingMap[i]&&(this.missingMap[i]=i)}},l.prototype.addSchema=function(e,t){if("string"!=typeof e||void 0===t){if("object"!=typeof e||"string"!=typeof e.id)return;e=(t=e).id}e===g(e)+"#"&&(e=g(e)),this.schemas[e]=t,delete this.missingMap[e],y(t,e),this.searchSchemas(t,e)},l.prototype.getSchemaMap=function(){var e={};for(var t in this.schemas)e[t]=this.schemas[t];return e},l.prototype.getSchemaUris=function(e){var t=[];for(var r in this.schemas)e&&!e.test(r)||t.push(r);return t},l.prototype.getMissingUris=function(e){var t=[];for(var r in this.missingMap)e&&!e.test(r)||t.push(r);return t},l.prototype.dropSchemas=function(){this.schemas={},this.reset()},l.prototype.reset=function(){this.missing=[],this.missingMap={},this.errors=[]},l.prototype.validateAll=function(e,t,r,n,i){var o;if(!(t=this.resolveRefs(t)))return null;if(t instanceof S)return this.errors.push(t),t;var s,a=this.errors.length,c=null,l=null;if(this.checkRecursive&&e&&"object"==typeof e){if(o=!this.scanned.length,e[this.validatedSchemasKey]){var u=e[this.validatedSchemasKey].indexOf(t);if(-1!==u)return this.errors=this.errors.concat(e[this.validationErrorsKey][u]),null}if(Object.isFrozen(e)&&-1!==(s=this.scannedFrozen.indexOf(e))){var d=this.scannedFrozenSchemas[s].indexOf(t);if(-1!==d)return this.errors=this.errors.concat(this.scannedFrozenValidationErrors[s][d]),null}if(this.scanned.push(e),Object.isFrozen(e))-1===s&&(s=this.scannedFrozen.length,this.scannedFrozen.push(e),this.scannedFrozenSchemas.push([])),c=this.scannedFrozenSchemas[s].length,this.scannedFrozenSchemas[s][c]=t,this.scannedFrozenValidationErrors[s][c]=[];else{if(!e[this.validatedSchemasKey])try{Object.defineProperty(e,this.validatedSchemasKey,{value:[],configurable:!0}),Object.defineProperty(e,this.validationErrorsKey,{value:[],configurable:!0})}catch(t){e[this.validatedSchemasKey]=[],e[this.validationErrorsKey]=[]}l=e[this.validatedSchemasKey].length,e[this.validatedSchemasKey][l]=t,e[this.validationErrorsKey][l]=[]}}var h=this.errors.length,f=this.validateBasic(e,t,i)||this.validateNumeric(e,t,i)||this.validateString(e,t,i)||this.validateArray(e,t,i)||this.validateObject(e,t,i)||this.validateCombinations(e,t,i)||this.validateHypermedia(e,t,i)||this.validateFormat(e,t,i)||this.validateDefinedKeywords(e,t,i)||null;if(o){for(;this.scanned.length;)delete this.scanned.pop()[this.validatedSchemasKey];this.scannedFrozen=[],this.scannedFrozenSchemas=[]}if(f||h!==this.errors.length)for(;r&&r.length||n&&n.length;){var p=r&&r.length?""+r.pop():null,g=n&&n.length?""+n.pop():null;f&&(f=f.prefixWith(p,g)),this.prefixErrors(h,p,g)}return null!==c?this.scannedFrozenValidationErrors[s][c]=this.errors.slice(a):null!==l&&(e[this.validationErrorsKey][l]=this.errors.slice(a)),this.handleError(f)},l.prototype.validateFormat=function(e,t){if("string"!=typeof t.format||!this.formatValidators[t.format])return null;var r=this.formatValidators[t.format].call(null,e,t);return"string"==typeof r||"number"==typeof r?this.createError(v.FORMAT_CUSTOM,{message:r},"","/format",null,e,t):r&&"object"==typeof r?this.createError(v.FORMAT_CUSTOM,{message:r.message||"?"},r.dataPath||"",r.schemaPath||"/format",null,e,t):null},l.prototype.validateDefinedKeywords=function(e,t,r){for(var n in this.definedKeywords)if(void 0!==t[n])for(var i=this.definedKeywords[n],o=0;o=d&&nt.maximum)return this.createError(v.NUMBER_MAXIMUM,{value:e,maximum:t.maximum},"","/maximum",null,e,t);if(t.exclusiveMaximum&&e===t.maximum)return this.createError(v.NUMBER_MAXIMUM_EXCLUSIVE,{value:e,maximum:t.maximum},"","/exclusiveMaximum",null,e,t)}return null},l.prototype.validateNaN=function(e,t){return"number"!=typeof e?null:!0===isNaN(e)||e===1/0||e===-1/0?this.createError(v.NUMBER_NOT_A_NUMBER,{value:e},"","/type",null,e,t):null},l.prototype.validateString=function(e,t,r){return this.validateStringLength(e,t,r)||this.validateStringPattern(e,t,r)||null},l.prototype.validateStringLength=function(e,t){return"string"!=typeof e?null:void 0!==t.minLength&&e.lengtht.maxLength?this.createError(v.STRING_LENGTH_LONG,{length:e.length,maximum:t.maxLength},"","/maxLength",null,e,t):null},l.prototype.validateStringPattern=function(e,t){if("string"!=typeof e||"string"!=typeof t.pattern&&!(t.pattern instanceof RegExp))return null;var r;if(t.pattern instanceof RegExp)r=t.pattern;else{var n,i="",o=t.pattern.match(/^\/(.+)\/([img]*)$/);o?(n=o[1],i=o[2]):n=t.pattern,r=new RegExp(n,i)}return r.test(e)?null:this.createError(v.STRING_PATTERN,{pattern:t.pattern},"","/pattern",null,e,t)},l.prototype.validateArray=function(e,t,r){return Array.isArray(e)&&(this.validateArrayLength(e,t,r)||this.validateArrayUniqueItems(e,t,r)||this.validateArrayItems(e,t,r))||null},l.prototype.validateArrayLength=function(e,t){var r;return void 0!==t.minItems&&e.lengtht.maxItems&&(r=this.createError(v.ARRAY_LENGTH_LONG,{length:e.length,maximum:t.maxItems},"","/maxItems",null,e,t),this.handleError(r))?r:null},l.prototype.validateArrayUniqueItems=function(e,t){if(t.uniqueItems)for(var r=0;rt.maxProperties&&(r=this.createError(v.OBJECT_PROPERTIES_MAXIMUM,{propertyCount:n.length,maximum:t.maxProperties},"","/maxProperties",null,e,t),this.handleError(r))?r:null},l.prototype.validateObjectRequiredProperties=function(e,t){if(void 0!==t.required)for(var r=0;r 10000");if(void 0!==v[e])throw new Error("Error already defined: "+e+" as "+v[e]);if(void 0!==b[t])throw new Error("Error code already used: "+b[t]+" as "+t);for(var n in v[e]=t,b[t]=e,_[e]=_[t]=r,E){var i=E[n];i[e]&&(i[t]=i[t]||i[e])}},reset:function(){i.reset(),this.error=null,this.missing=[],this.valid=!0},missing:[],error:null,valid:!0,normSchema:y,resolveUrl:p,getDocumentUri:g,errorCodes:v};return o.language(t||"en"),o}();return A.addLanguage("en-gb",_),A.tv4=A,A},void 0===(n=r.apply(t,[]))||(e.exports=n)},2831:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NIL",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(t,"parse",{enumerable:!0,get:function(){return d.default}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(t,"v1",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(t,"v3",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(t,"v4",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(t,"v5",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(t,"validate",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(t,"version",{enumerable:!0,get:function(){return c.default}});var n=h(r(3518)),i=h(r(4948)),o=h(r(5073)),s=h(r(7186)),a=h(r(4808)),c=h(r(7775)),l=h(r(7037)),u=h(r(9910)),d=h(r(6792));function h(e){return e&&e.__esModule?e:{default:e}}},2311:function(e,t){"use strict";function r(e){return 14+(e+64>>>9<<4)+1}function n(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function i(e,t,r,i,o,s){return n((a=n(n(t,e),n(i,s)))<<(c=o)|a>>>32-c,r);var a,c}function o(e,t,r,n,o,s,a){return i(t&r|~t&n,e,t,o,s,a)}function s(e,t,r,n,o,s,a){return i(t&n|r&~n,e,t,o,s,a)}function a(e,t,r,n,o,s,a){return i(t^r^n,e,t,o,s,a)}function c(e,t,r,n,o,s,a){return i(r^(t|~n),e,t,o,s,a)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;t.default=function(e){if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(let r=0;r>5]>>>i%32&255,o=parseInt(n.charAt(r>>>4&15)+n.charAt(15&r),16);t.push(o)}return t}(function(e,t){e[t>>5]|=128<>5]|=(255&e[r/8])<>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}},7656:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i},2858:function(e,t){"use strict";let r;Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){if(!r&&(r="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!r))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return r(n)};const n=new Uint8Array(16)},9042:function(e,t){"use strict";function r(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:case 3:return t^r^n;case 2:return t&r^t&n^r&n}}function n(e,t){return e<>>32-t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;t.default=function(e){const t=[1518500249,1859775393,2400959708,3395469782],i=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=[];for(let r=0;r>>0;d=u,u=l,l=n(c,30)>>>0,c=s,s=a}i[0]=i[0]+s>>>0,i[1]=i[1]+c>>>0,i[2]=i[2]+l>>>0,i[3]=i[3]+u>>>0,i[4]=i[4]+d>>>0}return[i[0]>>24&255,i[0]>>16&255,i[0]>>8&255,255&i[0],i[1]>>24&255,i[1]>>16&255,i[1]>>8&255,255&i[1],i[2]>>24&255,i[2]>>16&255,i[2]>>8&255,255&i[2],i[3]>>24&255,i[3]>>16&255,i[3]>>8&255,255&i[3],i[4]>>24&255,i[4]>>16&255,i[4]>>8&255,255&i[4]]}},9910:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.unsafeStringify=s;var n,i=(n=r(7037))&&n.__esModule?n:{default:n};const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));function s(e,t=0){return o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]}t.default=function(e,t=0){const r=s(e,t);if(!(0,i.default)(r))throw TypeError("Stringified UUID is invalid");return r}},3518:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,i=(n=r(2858))&&n.__esModule?n:{default:n},o=r(9910);let s,a,c=0,l=0;t.default=function(e,t,r){let n=t&&r||0;const u=t||new Array(16);let d=(e=e||{}).node||s,h=void 0!==e.clockseq?e.clockseq:a;if(null==d||null==h){const t=e.random||(e.rng||i.default)();null==d&&(d=s=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==h&&(h=a=16383&(t[6]<<8|t[7]))}let f=void 0!==e.msecs?e.msecs:Date.now(),p=void 0!==e.nsecs?e.nsecs:l+1;const g=f-c+(p-l)/1e4;if(g<0&&void 0===e.clockseq&&(h=h+1&16383),(g<0||f>c)&&void 0===e.nsecs&&(p=0),p>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");c=f,l=p,a=h,f+=122192928e5;const y=(1e4*(268435455&f)+p)%4294967296;u[n++]=y>>>24&255,u[n++]=y>>>16&255,u[n++]=y>>>8&255,u[n++]=255&y;const m=f/4294967296*1e4&268435455;u[n++]=m>>>8&255,u[n++]=255&m,u[n++]=m>>>24&15|16,u[n++]=m>>>16&255,u[n++]=h>>>8|128,u[n++]=255&h;for(let e=0;e<6;++e)u[n+e]=d[e];return t||(0,o.unsafeStringify)(u)}},4948:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=o(r(9025)),i=o(r(2311));function o(e){return e&&e.__esModule?e:{default:e}}var s=(0,n.default)("v3",48,i.default);t.default=s},9025:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.URL=t.DNS=void 0,t.default=function(e,t,r){function n(e,n,s,a){var c;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));const t=[];for(let r=0;r=301&&o.status<=302?function(e){return"string"==typeof e&&"https"===e.split("://")[0]}(o.getResponseHeader("Location"))?c():t(s({message:"no redirect URL found",url:e,status:o.status})):t(s({message:"error during request",url:e,status:o.status}))}function c(){o.onreadystatechange=function(){4===o.readyState&&a()},o.onload=function(){a()},o.ontimeout=function(){return t(s({message:"request timed out",url:e,status:o.status}))},o.open("GET",e,!0),o.timeout=n.config.request_timeout,o.setRequestHeader("Accept","application/jrd+json, application/json"),o.send()}return c()},a.prototype.__isValidJSON=function(e){try{JSON.parse(e)}catch(e){return!1}return!0},a.prototype.__isLocalhost=function(e){return/^localhost(\.localdomain)?(\:[0-9]+)?$/.test(e)},a.prototype.__processJRD=function(e,t,n,o){var a=JSON.parse(t);if("object"!=typeof a||"object"!=typeof a.links)return void 0!==a.error?n(s({message:a.error,request:e})):n(s({message:"unknown response from server",request:e}));var c=a.links;Array.isArray(c)||(c=[]);var l={object:a,json:t,idx:{}};l.idx.properties={name:void 0},l.idx.links=JSON.parse(JSON.stringify(i)),c.map((function(e,t){if(r.hasOwnProperty(e.rel)&&l.idx.links[r[e.rel]]){var n={};Object.keys(e).map((function(t,r){n[t]=e[t]})),l.idx.links[r[e.rel]].push(n)}}));var u=JSON.parse(t).properties;for(var d in u)u.hasOwnProperty(d)&&"http://packetizer.com/ns/name"===d&&(l.idx.properties.name=u[d]);return o(l)},a.prototype.lookup=function(e,t){if("string"!=typeof e)throw new Error("first parameter must be a user address");if("function"!=typeof t)throw new Error("second parameter must be a callback");var r=this,n="";n=e.indexOf("://")>-1?e.replace(/ /g,"").split("/")[2]:e.replace(/ /g,"").split("@")[1];var i=0,s="https";function a(){var t="";return e.split("://")[1]||(t="acct:"),s+"://"+n+"/.well-known/"+o[i]+"?resource="+t+e}function c(e){if(r.config.uri_fallback&&"webfist.org"!==n&&i!==o.length-1)return i+=1,l();if(!r.config.tls_only&&"https"===s)return i=0,s="http",l();if(!r.config.webfist_fallback||"webfist.org"===n)return t(e);i=0,s="http",n="webfist.org";var c=a();r.__fetchJRD(c,t,(function(e){r.__processJRD(c,e,t,(function(e){"object"==typeof e.idx.links.webfist&&"string"==typeof e.idx.links.webfist[0].href&&r.__fetchJRD(e.idx.links.webfist[0].href,t,(function(e){r.__processJRD(c,e,t,(function(e){return t(null,t)}))}))}))}))}function l(){var e=a();r.__fetchJRD(e,c,(function(n){r.__processJRD(e,n,t,(function(e){t(null,e)}))}))}return r.__isLocalhost(n)&&(s="http"),setTimeout(l,0)},a.prototype.lookupLink=function(e,t,r){if(!i.hasOwnProperty(t))return r("unsupported rel "+t);this.lookup(e,(function(e,n){var i=n.idx.links[t];return e?r(e):0===i.length?r('no links found with rel="'+t+'"'):r(null,i[0])}))},void 0===(n=function(){return a}.apply(t,[]))||(e.exports=n)}()},4317:function(e){e.exports=XMLHttpRequest},6438:function(e,t,r){"use strict";r.r(t),r.d(t,{CompactEncrypt:function(){return ee},CompactSign:function(){return te.T},EmbeddedJWK:function(){return he},EncryptJWT:function(){return ae},FlattenedEncrypt:function(){return K},FlattenedSign:function(){return re.n},GeneralEncrypt:function(){return G},GeneralSign:function(){return ie},SignJWT:function(){return oe.P},UnsecuredJWT:function(){return we},base64url:function(){return n},calculateJwkThumbprint:function(){return ue},calculateJwkThumbprintUri:function(){return de},compactDecrypt:function(){return B},compactVerify:function(){return q.B},createLocalJWKSet:function(){return me},createRemoteJWKSet:function(){return be},cryptoRuntime:function(){return xe},decodeJwt:function(){return Ae},decodeProtectedHeader:function(){return Ee},errors:function(){return s},exportJWK:function(){return W.JU},exportPKCS8:function(){return W.Yp},exportSPKI:function(){return W.Y5},flattenedDecrypt:function(){return M},flattenedVerify:function(){return z.Z},generalDecrypt:function(){return H},generalVerify:function(){return Y},generateKeyPair:function(){return Re.T},generateSecret:function(){return Te},importJWK:function(){return F.Og},importPKCS8:function(){return F.Lf},importSPKI:function(){return F.jU},importX509:function(){return F.Mh},jwtDecrypt:function(){return Z},jwtVerify:function(){return Q.V}});var n={};r.r(n),r.d(n,{decode:function(){return Se},encode:function(){return _e}});var i=r(1436),o=r(9095),s=r(7493),a=r(8057);function c(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new s.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}var l=e=>(0,a.A)(new Uint8Array(c(e)>>3)),u=(e,t)=>{if(t.length<<3!==c(e))throw new s.JWEInvalid("Invalid Initialization Vector length")},d=(e,t)=>{const r=e.byteLength<<3;if(r!==t)throw new s.JWEInvalid(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},h=r(7991),f=r(2698),p=r(1575),g=r(5994),y=async(e,t,r,n,i,a)=>{if(!((0,h.R)(t)||t instanceof Uint8Array))throw new TypeError((0,p.A)(t,...g.g,"Uint8Array"));switch(u(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&d(t,parseInt(e.slice(-3),10)),async function(e,t,r,n,i,a){if(!(t instanceof Uint8Array))throw new TypeError((0,p.A)(t,"Uint8Array"));const c=parseInt(e.slice(1,4),10),l=await h.A.subtle.importKey("raw",t.subarray(c>>3),"AES-CBC",!1,["decrypt"]),u=await h.A.subtle.importKey("raw",t.subarray(0,c>>3),{hash:"SHA-"+(c<<1),name:"HMAC"},!1,["sign"]),d=(0,o.xW)(a,n,r,(0,o.mx)(a.length<<3)),f=new Uint8Array((await h.A.subtle.sign("HMAC",u,d)).slice(0,c>>3));let g,y;try{g=((e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");const r=e.length;let n=0,i=-1;for(;++i{throw new s.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.')},v=async()=>{throw new s.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.')};var b=r(9874),w=r(149),_=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]];function S(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function E(e,t,r){if((0,h.R)(e))return(0,f.$)(e,t,r),e;if(e instanceof Uint8Array)return h.A.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError((0,p.A)(e,...g.g,"Uint8Array"))}const A=async(e,t,r)=>{const n=await E(t,e,"wrapKey");S(n,e);const i=await h.A.subtle.importKey("raw",r,..._);return new Uint8Array(await h.A.subtle.wrapKey("raw",i,n,"AES-KW"))},R=async(e,t,r)=>{const n=await E(t,e,"unwrapKey");S(n,e);const i=await h.A.subtle.unwrapKey("raw",r,n,"AES-KW",..._);return new Uint8Array(await h.A.subtle.exportKey("raw",i))};async function I(e,t,r,n,i=new Uint8Array(0),s=new Uint8Array(0)){if(!(0,h.R)(e))throw new TypeError((0,p.A)(e,...g.g));if((0,f.$)(e,"ECDH"),!(0,h.R)(t))throw new TypeError((0,p.A)(t,...g.g));(0,f.$)(t,"ECDH","deriveBits");const a=(0,o.xW)((0,o.Kp)(o.Rd.encode(r)),(0,o.Kp)(i),(0,o.Kp)(s),(0,o.VS)(n));let c;c="X25519"===e.algorithm.name?256:"X448"===e.algorithm.name?448:Math.ceil(parseInt(e.algorithm.namedCurve.substr(-3),10)/8)<<3;const l=new Uint8Array(await h.A.subtle.deriveBits({name:e.algorithm.name,public:e},t,c));return(0,o.yI)(l,n,a)}function T(e){if(!(0,h.R)(e))throw new TypeError((0,p.A)(e,...g.g));return["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||"X25519"===e.algorithm.name||"X448"===e.algorithm.name}async function x(e,t,r,n){!function(e){if(!(e instanceof Uint8Array)||e.length<8)throw new s.JWEInvalid("PBES2 Salt Input must be 8 or more octets")}(e);const i=(0,o.MT)(t,e),a=parseInt(t.slice(13,16),10),c={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},l={length:a,name:"AES-KW"},u=await function(e,t){if(e instanceof Uint8Array)return h.A.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if((0,h.R)(e))return(0,f.$)(e,t,"deriveBits","deriveKey"),e;throw new TypeError((0,p.A)(e,...g.g,"Uint8Array"))}(n,t);if(u.usages.includes("deriveBits"))return new Uint8Array(await h.A.subtle.deriveBits(c,u,a));if(u.usages.includes("deriveKey"))return h.A.subtle.deriveKey(c,u,l,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}function P(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new s.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var C=r(4495);function k(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new s.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}var O=e=>(0,a.A)(new Uint8Array(k(e)>>3)),F=r(8136),N=r(8858),D=async(e,t,r,n,i)=>{if(!((0,h.R)(r)||r instanceof Uint8Array))throw new TypeError((0,p.A)(r,...g.g,"Uint8Array"));switch(u(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&d(r,parseInt(e.slice(-3),10)),async function(e,t,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError((0,p.A)(r,"Uint8Array"));const s=parseInt(e.slice(1,4),10),a=await h.A.subtle.importKey("raw",r.subarray(s>>3),"AES-CBC",!1,["encrypt"]),c=await h.A.subtle.importKey("raw",r.subarray(0,s>>3),{hash:"SHA-"+(s<<1),name:"HMAC"},!1,["sign"]),l=new Uint8Array(await h.A.subtle.encrypt({iv:n,name:"AES-CBC"},a,t)),u=(0,o.xW)(i,n,l,(0,o.mx)(i.length<<3));return{ciphertext:l,tag:new Uint8Array((await h.A.subtle.sign("HMAC",c,u)).slice(0,s>>3))}}(e,t,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&d(r,parseInt(e.slice(1,4),10)),async function(e,t,r,n,i){let o;r instanceof Uint8Array?o=await h.A.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):((0,f.$)(r,e,"encrypt"),o=r);const s=new Uint8Array(await h.A.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},o,t)),a=s.slice(-16);return{ciphertext:s.slice(0,-16),tag:a}}(e,t,r,n,i);default:throw new s.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}},L=async function(e,t,r,n,o){switch((0,N.A)(e,t,"decrypt"),e){case"dir":if(void 0!==r)throw new s.JWEInvalid("Encountered unexpected JWE Encrypted Key");return t;case"ECDH-ES":if(void 0!==r)throw new s.JWEInvalid("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!(0,w.A)(n.epk))throw new s.JWEInvalid('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!T(t))throw new s.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");const o=await(0,F.Og)(n.epk,e);let a,c;if(void 0!==n.apu){if("string"!=typeof n.apu)throw new s.JWEInvalid('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{a=(0,i.D4)(n.apu)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the apu")}}if(void 0!==n.apv){if("string"!=typeof n.apv)throw new s.JWEInvalid('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{c=(0,i.D4)(n.apv)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the apv")}}const l=await I(o,t,"ECDH-ES"===e?n.enc:e,"ECDH-ES"===e?k(n.enc):parseInt(e.slice(-5,-2),10),a,c);if("ECDH-ES"===e)return l;if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");return R(e.slice(-6),l,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");return(async(e,t,r)=>{if(!(0,h.R)(t))throw new TypeError((0,p.A)(t,...g.g));if((0,f.$)(t,e,"decrypt","unwrapKey"),(0,C.A)(e,t),t.usages.includes("decrypt"))return new Uint8Array(await h.A.subtle.decrypt(P(e),t,r));if(t.usages.includes("unwrapKey")){const n=await h.A.subtle.unwrapKey("raw",r,t,P(e),..._);return new Uint8Array(await h.A.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')})(e,t,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");if("number"!=typeof n.p2c)throw new s.JWEInvalid('JOSE Header "p2c" (PBES2 Count) missing or invalid');const a=(null==o?void 0:o.maxPBES2Count)||1e4;if(n.p2c>a)throw new s.JWEInvalid('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof n.p2s)throw new s.JWEInvalid('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let c;try{c=(0,i.D4)(n.p2s)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the p2s")}return(async(e,t,r,n,i)=>{const o=await x(i,e,n,t);return R(e.slice(-6),o,r)})(e,t,r,n.p2c,c)}case"A128KW":case"A192KW":case"A256KW":if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");return R(e,t,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");if("string"!=typeof n.iv)throw new s.JWEInvalid('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof n.tag)throw new s.JWEInvalid('JOSE Header "tag" (Authentication Tag) missing or invalid');let o,a;try{o=(0,i.D4)(n.iv)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the iv")}try{a=(0,i.D4)(n.tag)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the tag")}return async function(e,t,r,n,i){const o=e.slice(0,7);return y(o,t,r,n,i,new Uint8Array(0))}(e,t,r,o,a)}default:throw new s.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}},U=r(2168),j=r(4618);async function M(e,t,r){var n;if(!(0,w.A)(e))throw new s.JWEInvalid("Flattened JWE must be an object");if(void 0===e.protected&&void 0===e.header&&void 0===e.unprotected)throw new s.JWEInvalid("JOSE Header missing");if("string"!=typeof e.iv)throw new s.JWEInvalid("JWE Initialization Vector missing or incorrect type");if("string"!=typeof e.ciphertext)throw new s.JWEInvalid("JWE Ciphertext missing or incorrect type");if("string"!=typeof e.tag)throw new s.JWEInvalid("JWE Authentication Tag missing or incorrect type");if(void 0!==e.protected&&"string"!=typeof e.protected)throw new s.JWEInvalid("JWE Protected Header incorrect type");if(void 0!==e.encrypted_key&&"string"!=typeof e.encrypted_key)throw new s.JWEInvalid("JWE Encrypted Key incorrect type");if(void 0!==e.aad&&"string"!=typeof e.aad)throw new s.JWEInvalid("JWE AAD incorrect type");if(void 0!==e.header&&!(0,w.A)(e.header))throw new s.JWEInvalid("JWE Shared Unprotected Header incorrect type");if(void 0!==e.unprotected&&!(0,w.A)(e.unprotected))throw new s.JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");let a;if(e.protected)try{const t=(0,i.D4)(e.protected);a=JSON.parse(o.D0.decode(t))}catch(e){throw new s.JWEInvalid("JWE Protected Header is invalid")}if(!(0,b.A)(a,e.header,e.unprotected))throw new s.JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");const c={...a,...e.header,...e.unprotected};if((0,U.A)(s.JWEInvalid,new Map,null==r?void 0:r.crit,a,c),void 0!==c.zip){if(!a||!a.zip)throw new s.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if("DEF"!==c.zip)throw new s.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}const{alg:l,enc:u}=c;if("string"!=typeof l||!l)throw new s.JWEInvalid("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof u||!u)throw new s.JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");const d=r&&(0,j.A)("keyManagementAlgorithms",r.keyManagementAlgorithms),h=r&&(0,j.A)("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(d&&!d.has(l))throw new s.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');if(h&&!h.has(u))throw new s.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed');let f;if(void 0!==e.encrypted_key)try{f=(0,i.D4)(e.encrypted_key)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the encrypted_key")}let p,g,v,_=!1;"function"==typeof t&&(t=await t(a,e),_=!0);try{p=await L(l,t,f,c,r)}catch(e){if(e instanceof TypeError||e instanceof s.JWEInvalid||e instanceof s.JOSENotSupported)throw e;p=O(u)}try{g=(0,i.D4)(e.iv)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the iv")}try{v=(0,i.D4)(e.tag)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the tag")}const S=o.Rd.encode(null!==(n=e.protected)&&void 0!==n?n:"");let E,A;E=void 0!==e.aad?(0,o.xW)(S,o.Rd.encode("."),o.Rd.encode(e.aad)):S;try{A=(0,i.D4)(e.ciphertext)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the ciphertext")}let R=await y(u,p,A,g,v,E);"DEF"===c.zip&&(R=await((null==r?void 0:r.inflateRaw)||m)(R));const I={plaintext:R};if(void 0!==e.protected&&(I.protectedHeader=a),void 0!==e.aad)try{I.additionalAuthenticatedData=(0,i.D4)(e.aad)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the aad")}return void 0!==e.unprotected&&(I.sharedUnprotectedHeader=e.unprotected),void 0!==e.header&&(I.unprotectedHeader=e.header),_?{...I,key:t}:I}async function B(e,t,r){if(e instanceof Uint8Array&&(e=o.D0.decode(e)),"string"!=typeof e)throw new s.JWEInvalid("Compact JWE must be a string or Uint8Array");const{0:n,1:i,2:a,3:c,4:l,length:u}=e.split(".");if(5!==u)throw new s.JWEInvalid("Invalid Compact JWE");const d=await M({ciphertext:c,iv:a||void 0,protected:n||void 0,tag:l||void 0,encrypted_key:i||void 0},t,r),h={plaintext:d.plaintext,protectedHeader:d.protectedHeader};return"function"==typeof t?{...h,key:d.key}:h}async function H(e,t,r){if(!(0,w.A)(e))throw new s.JWEInvalid("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(w.A))throw new s.JWEInvalid("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new s.JWEInvalid("JWE Recipients has no members");for(const n of e.recipients)try{return await M({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch(e){}throw new s.JWEDecryptionFailed}var W=r(5130),$=async function(e,t,r,n,o={}){let c,u,d;switch((0,N.A)(e,r,"encrypt"),e){case"dir":d=r;break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!T(r))throw new s.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");const{apu:a,apv:l}=o;let{epk:f}=o;f||(f=(await async function(e){if(!(0,h.R)(e))throw new TypeError((0,p.A)(e,...g.g));return h.A.subtle.generateKey(e.algorithm,!0,["deriveBits"])}(r)).privateKey);const{x:y,y:m,crv:v,kty:b}=await(0,W.JU)(f),w=await I(r,f,"ECDH-ES"===e?t:e,"ECDH-ES"===e?k(t):parseInt(e.slice(-5,-2),10),a,l);if(u={epk:{x:y,crv:v,kty:b}},"EC"===b&&(u.epk.y=m),a&&(u.apu=(0,i.lF)(a)),l&&(u.apv=(0,i.lF)(l)),"ECDH-ES"===e){d=w;break}d=n||O(t);const _=e.slice(-6);c=await A(_,w,d);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":d=n||O(t),c=await(async(e,t,r)=>{if(!(0,h.R)(t))throw new TypeError((0,p.A)(t,...g.g));if((0,f.$)(t,e,"encrypt","wrapKey"),(0,C.A)(e,t),t.usages.includes("encrypt"))return new Uint8Array(await h.A.subtle.encrypt(P(e),t,r));if(t.usages.includes("wrapKey")){const n=await h.A.subtle.importKey("raw",r,..._);return new Uint8Array(await h.A.subtle.wrapKey("raw",n,t,P(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')})(e,r,d);break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{d=n||O(t);const{p2c:s,p2s:l}=o;({encryptedKey:c,...u}=await(async(e,t,r,n=2048,o=(0,a.A)(new Uint8Array(16)))=>{const s=await x(o,e,n,t);return{encryptedKey:await A(e.slice(-6),s,r),p2c:n,p2s:(0,i.lF)(o)}})(e,r,d,s,l));break}case"A128KW":case"A192KW":case"A256KW":d=n||O(t),c=await A(e,r,d);break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{d=n||O(t);const{iv:s}=o;({encryptedKey:c,...u}=await async function(e,t,r,n){const o=e.slice(0,7);n||(n=l(o));const{ciphertext:s,tag:a}=await D(o,r,t,n,new Uint8Array(0));return{encryptedKey:s,iv:(0,i.lF)(n),tag:(0,i.lF)(a)}}(e,r,d,s));break}default:throw new s.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:d,encryptedKey:c,parameters:u}};const V=Symbol();class K{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=e}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}async encrypt(e,t){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new s.JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!(0,b.A)(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new s.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if((0,U.A)(s.JWEInvalid,new Map,null==t?void 0:t.crit,this._protectedHeader,r),void 0!==r.zip){if(!this._protectedHeader||!this._protectedHeader.zip)throw new s.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if("DEF"!==r.zip)throw new s.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}const{alg:n,enc:a}=r;if("string"!=typeof n||!n)throw new s.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof a||!a)throw new s.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let c,u,d,h,f,p,g;if("dir"===n){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if("ECDH-ES"===n&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");{let r;({cek:u,encryptedKey:c,parameters:r}=await $(n,a,e,this._cek,this._keyManagementParameters)),r&&(t&&V in t?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...r}:this.setUnprotectedHeader(r):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...r}:this.setProtectedHeader(r))}if(this._iv||(this._iv=l(a)),h=this._protectedHeader?o.Rd.encode((0,i.lF)(JSON.stringify(this._protectedHeader))):o.Rd.encode(""),this._aad?(f=(0,i.lF)(this._aad),d=(0,o.xW)(h,o.Rd.encode("."),o.Rd.encode(f))):d=h,"DEF"===r.zip){const e=await((null==t?void 0:t.deflateRaw)||v)(this._plaintext);({ciphertext:p,tag:g}=await D(a,e,u,this._iv,d))}else({ciphertext:p,tag:g}=await D(a,this._plaintext,u,this._iv,d));const y={ciphertext:(0,i.lF)(p),iv:(0,i.lF)(this._iv),tag:(0,i.lF)(g)};return c&&(y.encrypted_key=(0,i.lF)(c)),f&&(y.aad=f),this._protectedHeader&&(y.protected=o.D0.decode(h)),this._sharedUnprotectedHeader&&(y.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(y.header=this._unprotectedHeader),y}}class J{constructor(e,t,r){this.parent=e,this.key=t,this.options=r}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addRecipient(...e){return this.parent.addRecipient(...e)}encrypt(...e){return this.parent.encrypt(...e)}done(){return this.parent}}class G{constructor(e){this._recipients=[],this._plaintext=e}addRecipient(e,t){const r=new J(this,e,{crit:null==t?void 0:t.crit});return this._recipients.push(r),r}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}async encrypt(e){var t,r,n;if(!this._recipients.length)throw new s.JWEInvalid("at least one recipient must be added");if(e={deflateRaw:null==e?void 0:e.deflateRaw},1===this._recipients.length){const[t]=this._recipients,r=await new K(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(t.unprotectedHeader).encrypt(t.key,{...t.options,...e});let n={ciphertext:r.ciphertext,iv:r.iv,recipients:[{}],tag:r.tag};return r.aad&&(n.aad=r.aad),r.protected&&(n.protected=r.protected),r.unprotected&&(n.unprotected=r.unprotected),r.encrypted_key&&(n.recipients[0].encrypted_key=r.encrypted_key),r.header&&(n.recipients[0].header=r.header),n}let o;for(let e=0;e{if("string"!=typeof e||!e)throw new s.JWKInvalid(`${t} missing or invalid`)};async function ue(e,t){if(!(0,w.A)(e))throw new TypeError("JWK must be an object");if(null!=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":le(e.crv,'"crv" (Curve) Parameter'),le(e.x,'"x" (X Coordinate) Parameter'),le(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":le(e.crv,'"crv" (Subtype of Key Pair) Parameter'),le(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":le(e.e,'"e" (Exponent) Parameter'),le(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":le(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new s.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported')}const n=o.Rd.encode(JSON.stringify(r));return(0,i.lF)(await(0,ce.A)(t,n))}async function de(e,t){null!=t||(t="sha256");const r=await ue(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function he(e,t){const r={...e,...null==t?void 0:t.header};if(!(0,w.A)(r.jwk))throw new s.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');const n=await(0,F.Og)({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||"public"!==n.type)throw new s.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}function fe(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(pe)}function pe(e){return(0,w.A)(e)}class ge{constructor(e){if(this._cached=new WeakMap,!fe(e))throw new s.JWKSInvalid("JSON Web Key Set malformed");var t;this._jwks=(t=e,"function"==typeof structuredClone?structuredClone(t):JSON.parse(JSON.stringify(t)))}async getKey(e,t){const{alg:r,kid:n}={...e,...null==t?void 0:t.header},i=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 s.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set')}}(r),o=this._jwks.keys.filter((e=>{let t=i===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&&"EdDSA"===r&&(t="Ed25519"===e.crv||"Ed448"===e.crv),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}return t})),{0:a,length:c}=o;if(0===c)throw new s.JWKSNoMatchingKey;if(1!==c){const e=new s.JWKSMultipleMatchingKeys,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of o)try{yield await ye(t,e,r)}catch(e){continue}},e}return ye(this._cached,a,r)}}async function ye(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await(0,F.Og)({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new s.JWKSInvalid("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function me(e){const t=new ge(e);return async function(e,r){return t.getKey(e,r)}}class ve extends ge{constructor(e,t){if(super({keys:[]}),this._jwks=void 0,!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:null==t?void 0:t.agent,headers:null==t?void 0:t.headers},this._timeoutDuration="number"==typeof(null==t?void 0:t.timeoutDuration)?null==t?void 0:t.timeoutDuration:5e3,this._cooldownDuration="number"==typeof(null==t?void 0:t.cooldownDuration)?null==t?void 0:t.cooldownDuration:3e4,this._cacheMaxAge="number"==typeof(null==t?void 0:t.cacheMaxAge)?null==t?void 0:t.cacheMaxAge:6e5}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now(){let n,i,o=!1;"function"==typeof AbortController&&(n=new AbortController,i=setTimeout((()=>{o=!0,n.abort()}),t));const a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch((e=>{if(o)throw new s.JWKSTimeout;throw e}));if(void 0!==i&&clearTimeout(i),200!==a.status)throw new s.JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch(e){throw new s.JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON")}})(this._url,this._timeoutDuration,this._options).then((e=>{if(!fe(e))throw new s.JWKSInvalid("JSON Web Key Set malformed");this._jwks={keys:e.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0})).catch((e=>{throw this._pendingFetch=void 0,e}))),await this._pendingFetch}}function be(e,t){const r=new ve(e,t);return async function(e,t){return r.getKey(e,t)}}class we extends se.G{encode(){return`${i.lF(JSON.stringify({alg:"none"}))}.${i.lF(JSON.stringify(this._payload))}.`}static decode(e,t){if("string"!=typeof e)throw new s.JWTInvalid("Unsecured JWT must be a string");const{0:r,1:n,2:a,length:c}=e.split(".");if(3!==c||""!==a)throw new s.JWTInvalid("Invalid Unsecured JWT");let l;try{if(l=JSON.parse(o.D0.decode(i.D4(r))),"none"!==l.alg)throw new Error}catch(e){throw new s.JWTInvalid("Invalid Unsecured JWT")}return{payload:(0,X.A)(l,i.D4(n),t),header:l}}}const _e=i.lF,Se=i.D4;function Ee(e){let t;if("string"==typeof e){const r=e.split(".");3!==r.length&&5!==r.length||([t]=r)}else if("object"==typeof e&&e){if(!("protected"in e))throw new TypeError("Token does not contain a Protected Header");t=e.protected}try{if("string"!=typeof t||!t)throw new Error;const e=JSON.parse(o.D0.decode(Se(t)));if(!(0,w.A)(e))throw new Error;return e}catch(e){throw new TypeError("Invalid Token or Protected Header formatting")}}function Ae(e){if("string"!=typeof e)throw new s.JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new s.JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new s.JWTInvalid("Invalid JWT");if(!t)throw new s.JWTInvalid("JWTs must contain a payload");let n,i;try{n=Se(t)}catch(e){throw new s.JWTInvalid("Failed to base64url decode the payload")}try{i=JSON.parse(o.D0.decode(n))}catch(e){throw new s.JWTInvalid("Failed to parse the decoded payload as JSON")}if(!(0,w.A)(i))throw new s.JWTInvalid("Invalid JWT Claims Set");return i}var Re=r(7307),Ie=r(8793);async function Te(e,t){return(0,Ie.K)(e,t)}var xe="WebCryptoAPI"},2609:function(e,t,r){"use strict";r.d(t,{T:function(){return i}});var n=r(5550);class i{constructor(e){this._flattened=new n.n(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}`}}},5609:function(e,t,r){"use strict";r.d(t,{B:function(){return s}});var n=r(6711),i=r(7493),o=r(9095);async function s(e,t,r){if(e instanceof Uint8Array&&(e=o.D0.decode(e)),"string"!=typeof e)throw new i.JWSInvalid("Compact JWS must be a string or Uint8Array");const{0:s,1:a,2:c,length:l}=e.split(".");if(3!==l)throw new i.JWSInvalid("Invalid Compact JWS");const u=await(0,n.Z)({payload:a,protected:s,signature:c},t,r),d={payload:u.payload,protectedHeader:u.protectedHeader};return"function"==typeof t?{...d,key:u.key}:d}},5550:function(e,t,r){"use strict";r.d(t,{n:function(){return f}});var n=r(1436),i=r(1020),o=r(7991),s=r(4495),a=r(676),c=r(9874),l=r(7493),u=r(9095),d=r(8858),h=r(2168);class f{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 l.JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!(0,c.A)(this._protectedHeader,this._unprotectedHeader))throw new l.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let f=!0;if((0,h.A)(l.JWSInvalid,new Map([["b64",!0]]),null==t?void 0:t.crit,this._protectedHeader,r).has("b64")&&(f=this._protectedHeader.b64,"boolean"!=typeof f))throw new l.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:p}=r;if("string"!=typeof p||!p)throw new l.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');(0,d.A)(p,e,"sign");let g,y=this._payload;f&&(y=u.Rd.encode((0,n.lF)(y))),g=this._protectedHeader?u.Rd.encode((0,n.lF)(JSON.stringify(this._protectedHeader))):u.Rd.encode("");const m=(0,u.xW)(g,u.Rd.encode("."),y),v=await(async(e,t,r)=>{const n=await(0,a.A)(e,t,"sign");(0,s.A)(e,n);const c=await o.A.subtle.sign((0,i.A)(e,n.algorithm),n,r);return new Uint8Array(c)})(p,e,m),b={signature:(0,n.lF)(v),payload:""};return f&&(b.payload=u.D0.decode(y)),this._unprotectedHeader&&(b.header=this._unprotectedHeader),this._protectedHeader&&(b.protected=u.D0.decode(g)),b}}},6711:function(e,t,r){"use strict";r.d(t,{Z:function(){return y}});var n=r(1436),i=r(1020),o=r(7991),s=r(4495),a=r(676),c=async(e,t,r,n)=>{const c=await(0,a.A)(e,t,"verify");(0,s.A)(e,c);const l=(0,i.A)(e,c.algorithm);try{return await o.A.subtle.verify(l,c,r,n)}catch(e){return!1}},l=r(7493),u=r(9095),d=r(9874),h=r(149),f=r(8858),p=r(2168),g=r(4618);async function y(e,t,r){var i;if(!(0,h.A)(e))throw new l.JWSInvalid("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new l.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new l.JWSInvalid("JWS Protected Header incorrect type");if(void 0===e.payload)throw new l.JWSInvalid("JWS Payload missing");if("string"!=typeof e.signature)throw new l.JWSInvalid("JWS Signature missing or incorrect type");if(void 0!==e.header&&!(0,h.A)(e.header))throw new l.JWSInvalid("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{const t=(0,n.D4)(e.protected);o=JSON.parse(u.D0.decode(t))}catch(e){throw new l.JWSInvalid("JWS Protected Header is invalid")}if(!(0,d.A)(o,e.header))throw new l.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...o,...e.header};let a=!0;if((0,p.A)(l.JWSInvalid,new Map([["b64",!0]]),null==r?void 0:r.crit,o,s).has("b64")&&(a=o.b64,"boolean"!=typeof a))throw new l.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:y}=s;if("string"!=typeof y||!y)throw new l.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');const m=r&&(0,g.A)("algorithms",r.algorithms);if(m&&!m.has(y))throw new l.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');if(a){if("string"!=typeof e.payload)throw new l.JWSInvalid("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new l.JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let v=!1;"function"==typeof t&&(t=await t(o,e),v=!0),(0,f.A)(y,t,"verify");const b=(0,u.xW)(u.Rd.encode(null!==(i=e.protected)&&void 0!==i?i:""),u.Rd.encode("."),"string"==typeof e.payload?u.Rd.encode(e.payload):e.payload);let w,_;try{w=(0,n.D4)(e.signature)}catch(e){throw new l.JWSInvalid("Failed to base64url decode the signature")}if(!await c(y,t,w,b))throw new l.JWSSignatureVerificationFailed;if(a)try{_=(0,n.D4)(e.payload)}catch(e){throw new l.JWSInvalid("Failed to base64url decode the payload")}else _="string"==typeof e.payload?u.Rd.encode(e.payload):e.payload;const S={payload:_};return void 0!==e.protected&&(S.protectedHeader=o),void 0!==e.header&&(S.unprotectedHeader=e.header),v?{...S,key:t}:S}},3085:function(e,t,r){"use strict";r.d(t,{G:function(){return s}});var n=r(2222),i=r(149),o=r(6957);class s{constructor(e){if(!(0,i.A)(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 this._payload="number"==typeof e?{...this._payload,nbf:e}:{...this._payload,nbf:(0,n.A)(new Date)+(0,o.A)(e)},this}setExpirationTime(e){return this._payload="number"==typeof e?{...this._payload,exp:e}:{...this._payload,exp:(0,n.A)(new Date)+(0,o.A)(e)},this}setIssuedAt(e){return this._payload=void 0===e?{...this._payload,iat:(0,n.A)(new Date)}:{...this._payload,iat:e},this}}},7248:function(e,t,r){"use strict";r.d(t,{P:function(){return a}});var n=r(2609),i=r(7493),o=r(9095),s=r(3085);class a extends s.G{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){var r;const s=new n.T(o.Rd.encode(JSON.stringify(this._payload)));if(s.setProtectedHeader(this._protectedHeader),Array.isArray(null===(r=this._protectedHeader)||void 0===r?void 0:r.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new i.JWTInvalid("JWTs MUST NOT use unencoded payload");return s.sign(e,t)}}},9380:function(e,t,r){"use strict";r.d(t,{V:function(){return s}});var n=r(5609),i=r(9803),o=r(7493);async function s(e,t,r){var s;const a=await(0,n.B)(e,t,r);if((null===(s=a.protectedHeader.crit)||void 0===s?void 0:s.includes("b64"))&&!1===a.protectedHeader.b64)throw new o.JWTInvalid("JWTs MUST NOT use unencoded payload");const c={payload:(0,i.A)(a.protectedHeader,a.payload,r),protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}},5130:function(e,t,r){"use strict";r.d(t,{JU:function(){return d},Yp:function(){return u},Y5:function(){return l}});var n=r(5141),i=r(7991),o=r(1575),s=r(1436),a=r(5994),c=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:(0,s.lF)(e)};if(!(0,i.R)(e))throw new TypeError((0,o.A)(e,...a.g,"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:c,...l}=await i.A.subtle.exportKey("jwk",e);return l};async function l(e){return(0,n.Nj)(e)}async function u(e){return(0,n.Jq)(e)}async function d(e){return c(e)}},7307:function(e,t,r){"use strict";r.d(t,{T:function(){return i}});var n=r(8793);async function i(e,t){return(0,n.T)(e,t)}},8136:function(e,t,r){"use strict";r.d(t,{Og:function(){return h},Lf:function(){return d},jU:function(){return l},Mh:function(){return u}});var n=r(1436),i=r(5141),o=r(7991),s=r(7493),a=async e=>{var t,r;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:i,keyUsages:a}=function(e){let t,r;switch(e.kty){case"oct":switch(e.alg){case"HS256":case"HS384":case"HS512":t={name:"HMAC",hash:`SHA-${e.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new s.JOSENotSupported(`${e.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":t={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":t={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":t={name:"PBKDF2"},r=["deriveBits"];break;default:throw new s.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new s.JOSENotSupported('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 s.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){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 s.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new s.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),c=[i,null!==(t=e.ext)&&void 0!==t&&t,null!==(r=e.key_ops)&&void 0!==r?r:a];if("PBKDF2"===i.name)return o.A.subtle.importKey("raw",(0,n.D4)(e.k),...c);const l={...e};return delete l.alg,delete l.use,o.A.subtle.importKey("jwk",l,...c)},c=r(149);async function l(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw new TypeError('"spki" must be SPKI formatted string');return(0,i.sc)(e,t,r)}async function u(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN CERTIFICATE-----"))throw new TypeError('"x509" must be X.509 formatted string');return(0,i.zp)(e,t,r)}async function d(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return(0,i.IG)(e,t,r)}async function h(e,t,r){var i;if(!(0,c.A)(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 null!=r||(r=!0!==e.ext),r?a({...e,alg:t,ext:null!==(i=e.ext)&&void 0!==i&&i}):(0,n.D4)(e.k);case"RSA":if(void 0!==e.oth)throw new s.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return a({...e,alg:t});default:throw new s.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value')}}},9095:function(e,t,r){"use strict";r.d(t,{D0:function(){return o},Kp:function(){return h},MT:function(){return c},Rd:function(){return i},VS:function(){return d},mx:function(){return u},xW:function(){return a},yI:function(){return f}});var n=r(610);const i=new TextEncoder,o=new TextDecoder,s=2**32;function a(...e){const t=e.reduce(((e,{length:t})=>e+t),0),r=new Uint8Array(t);let n=0;return e.forEach((e=>{r.set(e,n),n+=e.length})),r}function c(e,t){return a(i.encode(e),new Uint8Array([0]),t)}function l(e,t,r){if(t<0||t>=s)throw new RangeError(`value must be >= 0 and <= ${s-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,255&t],r)}function u(e){const t=Math.floor(e/s),r=e%s,n=new Uint8Array(8);return l(n,t,0),l(n,r,4),n}function d(e){const t=new Uint8Array(4);return l(t,e),t}function h(e){return a(d(e.length),e)}async function f(e,t,r){const i=Math.ceil((t>>3)/32),o=new Uint8Array(32*i);for(let t=0;t>3)}},8858:function(e,t,r){"use strict";var n=r(1575),i=r(5994);t.A=(e,t,r)=>{e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?((e,t)=>{if(!(t instanceof Uint8Array)){if(!(0,i.A)(t))throw new TypeError((0,n.t)(e,t,...i.g,"Uint8Array"));if("secret"!==t.type)throw new TypeError(`${i.g.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}})(e,t):((e,t,r)=>{if(!(0,i.A)(t))throw new TypeError((0,n.t)(e,t,...i.g));if("secret"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)})(e,t,r)}},2698:function(e,t,r){"use strict";function n(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 o(e){return parseInt(e.name.slice(4),10)}function s(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)}}function a(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!i(e.algorithm,"HMAC"))throw n("HMAC");const r=parseInt(t.slice(2),10);if(o(e.algorithm.hash)!==r)throw n(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!i(e.algorithm,"RSASSA-PKCS1-v1_5"))throw n("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(o(e.algorithm.hash)!==r)throw n(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!i(e.algorithm,"RSA-PSS"))throw n("RSA-PSS");const r=parseInt(t.slice(2),10);if(o(e.algorithm.hash)!==r)throw n(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw n("Ed25519 or Ed448");break;case"ES256":case"ES384":case"ES512":{if(!i(e.algorithm,"ECDSA"))throw n("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 n(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}s(e,r)}function c(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!i(e.algorithm,"AES-GCM"))throw n("AES-GCM");const r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw n(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!i(e.algorithm,"AES-KW"))throw n("AES-KW");const r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw n(r,"algorithm.length");break}case"ECDH":switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw n("ECDH, X25519, or X448")}break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!i(e.algorithm,"PBKDF2"))throw n("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!i(e.algorithm,"RSA-OAEP"))throw n("RSA-OAEP");const r=parseInt(t.slice(9),10)||1;if(o(e.algorithm.hash)!==r)throw n(`SHA-${r}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}s(e,r)}r.d(t,{$:function(){return c},Y:function(){return a}})},2222:function(e,t){"use strict";t.A=e=>Math.floor(e.getTime()/1e3)},1575:function(e,t,r){"use strict";function n(e,t,...r){if(r.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&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function i(e,t,...r){return n(`Key for the ${e} algorithm must be `,t,...r)}r.d(t,{t:function(){return i}}),t.A=(e,...t)=>n("Key must be ",e,...t)},9874:function(e,t){"use strict";t.A=(...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}},149:function(e,t,r){"use strict";function n(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}r.d(t,{A:function(){return n}})},9803:function(e,t,r){"use strict";var n=r(7493),i=r(9095),o=r(2222),s=r(6957),a=r(149);const c=e=>e.toLowerCase().replace(/^application\//,"");t.A=(e,t,r={})=>{const{typ:l}=r;if(l&&("string"!=typeof e.typ||c(e.typ)!==c(l)))throw new n.JWTClaimValidationFailed('unexpected "typ" JWT header value',"typ","check_failed");let u;try{u=JSON.parse(i.D0.decode(t))}catch(e){}if(!(0,a.A)(u))throw new n.JWTInvalid("JWT Claims Set must be a top-level JSON object");const{requiredClaims:d=[],issuer:h,subject:f,audience:p,maxTokenAge:g}=r;void 0!==g&&d.push("iat"),void 0!==p&&d.push("aud"),void 0!==f&&d.push("sub"),void 0!==h&&d.push("iss");for(const e of new Set(d.reverse()))if(!(e in u))throw new n.JWTClaimValidationFailed(`missing required "${e}" claim`,e,"missing");if(h&&!(Array.isArray(h)?h:[h]).includes(u.iss))throw new n.JWTClaimValidationFailed('unexpected "iss" claim value',"iss","check_failed");if(f&&u.sub!==f)throw new n.JWTClaimValidationFailed('unexpected "sub" claim value',"sub","check_failed");if(p&&(m="string"==typeof p?[p]:p,!("string"==typeof(y=u.aud)?m.includes(y):Array.isArray(y)&&m.some(Set.prototype.has.bind(new Set(y))))))throw new n.JWTClaimValidationFailed('unexpected "aud" claim value',"aud","check_failed");var y,m;let v;switch(typeof r.clockTolerance){case"string":v=(0,s.A)(r.clockTolerance);break;case"number":v=r.clockTolerance;break;case"undefined":v=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:b}=r,w=(0,o.A)(b||new Date);if((void 0!==u.iat||g)&&"number"!=typeof u.iat)throw new n.JWTClaimValidationFailed('"iat" claim must be a number',"iat","invalid");if(void 0!==u.nbf){if("number"!=typeof u.nbf)throw new n.JWTClaimValidationFailed('"nbf" claim must be a number',"nbf","invalid");if(u.nbf>w+v)throw new n.JWTClaimValidationFailed('"nbf" claim timestamp check failed',"nbf","check_failed")}if(void 0!==u.exp){if("number"!=typeof u.exp)throw new n.JWTClaimValidationFailed('"exp" claim must be a number',"exp","invalid");if(u.exp<=w-v)throw new n.JWTExpired('"exp" claim timestamp check failed',"exp","check_failed")}if(g){const e=w-u.iat;if(e-v>("number"==typeof g?g:(0,s.A)(g)))throw new n.JWTExpired('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(e<0-v)throw new n.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return u}},6957:function(e,t){"use strict";const r=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;t.A=e=>{const t=r.exec(e);if(!t)throw new TypeError("Invalid time period format");const n=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(n);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(60*n);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(3600*n);case"day":case"days":case"d":return Math.round(86400*n);case"week":case"weeks":case"w":return Math.round(604800*n);default:return Math.round(31557600*n)}}},4618:function(e,t){"use strict";t.A=(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)}},2168:function(e,t,r){"use strict";var n=r(7493);t.A=function(e,t,r,i,o){if(void 0!==o.crit&&void 0===i.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||void 0===i.crit)return new Set;if(!Array.isArray(i.crit)||0===i.crit.length||i.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 s;s=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of i.crit){if(!s.has(t))throw new n.JOSENotSupported(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(s.get(t)&&void 0===i[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(i.crit)}},5141:function(e,t,r){"use strict";r.d(t,{IG:function(){return g},sc:function(){return y},zp:function(){return b},Jq:function(){return d},Nj:function(){return u}});var n=r(7991),i=r(1575),o=r(1436),s=(e,t)=>`-----BEGIN ${t}-----\n${(e.match(/.{1,64}/g)||[]).join("\n")}\n-----END ${t}-----`,a=r(7493),c=r(5994);const l=async(e,t,r)=>{if(!(0,n.R)(r))throw new TypeError((0,i.A)(r,...c.g));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return s((0,o.WG)(new Uint8Array(await n.A.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},u=e=>l("public","spki",e),d=e=>l("private","pkcs8",e),h=(e,t,r=0)=>{0===r&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(-1===n)return!1;const i=e.subarray(n,n+t.length);return i.length===t.length&&(i.every(((e,r)=>e===t[r]))||h(e,t,n+1))},f=e=>{switch(!0){case h(e,[42,134,72,206,61,3,1,7]):return"P-256";case h(e,[43,129,4,0,34]):return"P-384";case h(e,[43,129,4,0,35]):return"P-521";case h(e,[43,101,110]):return"X25519";case h(e,[43,101,111]):return"X448";case h(e,[43,101,112]):return"Ed25519";case h(e,[43,101,113]):return"Ed448";default:throw new a.JOSENotSupported("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},p=async(e,t,r,i,o)=>{var s;let c,l;const u=new Uint8Array(atob(r.replace(e,"")).split("").map((e=>e.charCodeAt(0)))),d="spki"===t;switch(i){case"PS256":case"PS384":case"PS512":c={name:"RSA-PSS",hash:`SHA-${i.slice(-3)}`},l=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":c={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${i.slice(-3)}`},l=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":c={name:"RSA-OAEP",hash:`SHA-${parseInt(i.slice(-3),10)||1}`},l=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":c={name:"ECDSA",namedCurve:"P-256"},l=d?["verify"]:["sign"];break;case"ES384":c={name:"ECDSA",namedCurve:"P-384"},l=d?["verify"]:["sign"];break;case"ES512":c={name:"ECDSA",namedCurve:"P-521"},l=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=f(u);c=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},l=d?[]:["deriveBits"];break}case"EdDSA":c={name:f(u)},l=d?["verify"]:["sign"];break;default:throw new a.JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value')}return n.A.subtle.importKey(t,u,c,null!==(s=null==o?void 0:o.extractable)&&void 0!==s&&s,l)},g=(e,t,r)=>p(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),y=(e,t,r)=>p(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function m(e){let t=[],r=0;for(;r=128;)r=128*r+e[t]-128,t++;r=128*r+e[t]-128,t++}let n=0;if(e[t]<128)n=e[t],t++;else{if(128===n){for(n=0;0!==e[t+n]||0!==e[t+n+1];){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++}const r=t+n+2;return{byteLength:r,contents:e.subarray(t,t+n),raw:e.subarray(0,r)}}{let r=127&e[t];t++,n=0;for(let i=0;i{let n;try{n=function(e){const t=e.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=(0,o.y4)(t);return s(function(e){const t=m(m(v(e).contents)[0].contents);return(0,o.WG)(t[160===t[0].raw[0]?6:5].raw)}(r),"PUBLIC KEY")}(e)}catch(e){throw new TypeError("Failed to parse the X.509 certificate",{cause:e})}return y(n,t,r)}},1436:function(e,t,r){"use strict";r.d(t,{D4:function(){return a},WG:function(){return i},lF:function(){return o},y4:function(){return s}});var n=r(9095);const i=e=>{let t=e;"string"==typeof t&&(t=n.Rd.encode(t));const r=[];for(let e=0;ei(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),s=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e{let t=e;t instanceof Uint8Array&&(t=n.D0.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return s(t)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.")}}},4495:function(e,t){"use strict";t.A=(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`)}}},610:function(e,t,r){"use strict";var n=r(7991);t.A=async(e,t)=>{const r=`SHA-${e.slice(-3)}`;return new Uint8Array(await n.A.subtle.digest(r,t))}},8793:function(e,t,r){"use strict";r.d(t,{K:function(){return s},T:function(){return c}});var n=r(7991),i=r(7493),o=r(8057);async function s(e,t){var r;let s,a,c;switch(e){case"HS256":case"HS384":case"HS512":s=parseInt(e.slice(-3),10),a={name:"HMAC",hash:`SHA-${s}`,length:s},c=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return s=parseInt(e.slice(-3),10),(0,o.A)(new Uint8Array(s>>3));case"A128KW":case"A192KW":case"A256KW":s=parseInt(e.slice(1,4),10),a={name:"AES-KW",length:s},c=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":s=parseInt(e.slice(1,4),10),a={name:"AES-GCM",length:s},c=["encrypt","decrypt"];break;default:throw new i.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return n.A.subtle.generateKey(a,null!==(r=null==t?void 0:t.extractable)&&void 0!==r&&r,c)}function a(e){var t;const r=null!==(t=null==e?void 0:e.modulusLength)&&void 0!==t?t:2048;if("number"!=typeof r||r<2048)throw new i.JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function c(e,t){var r,o,s;let c,l;switch(e){case"PS256":case"PS384":case"PS512":c={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:a(t)},l=["sign","verify"];break;case"RS256":case"RS384":case"RS512":c={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:a(t)},l=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":c={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:a(t)},l=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":c={name:"ECDSA",namedCurve:"P-256"},l=["sign","verify"];break;case"ES384":c={name:"ECDSA",namedCurve:"P-384"},l=["sign","verify"];break;case"ES512":c={name:"ECDSA",namedCurve:"P-521"},l=["sign","verify"];break;case"EdDSA":l=["sign","verify"];const n=null!==(r=null==t?void 0:t.crv)&&void 0!==r?r:"Ed25519";switch(n){case"Ed25519":case"Ed448":c={name:n};break;default:throw new i.JOSENotSupported("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{l=["deriveKey","deriveBits"];const e=null!==(o=null==t?void 0:t.crv)&&void 0!==o?o:"P-256";switch(e){case"P-256":case"P-384":case"P-521":c={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":c={name:e};break;default:throw new i.JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new i.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return n.A.subtle.generateKey(c,null!==(s=null==t?void 0:t.extractable)&&void 0!==s&&s,l)}},676:function(e,t,r){"use strict";r.d(t,{A:function(){return a}});var n=r(7991),i=r(2698),o=r(1575),s=r(5994);function a(e,t,r){if((0,n.R)(t))return(0,i.Y)(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError((0,o.A)(t,...s.g));return n.A.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError((0,o.A)(t,...s.g,"Uint8Array"))}},5994:function(e,t,r){"use strict";r.d(t,{g:function(){return i}});var n=r(7991);t.A=e=>(0,n.R)(e);const i=["CryptoKey"]},8057:function(e,t,r){"use strict";var n=r(7991);t.A=n.A.getRandomValues.bind(n.A)},1020:function(e,t,r){"use strict";r.d(t,{A:function(){return i}});var n=r(7493);function i(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"EdDSA":return{name:t.name};default:throw new n.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}},7991:function(e,t,r){"use strict";r.d(t,{R:function(){return n}}),t.A=crypto;const n=e=>e instanceof CryptoKey},7493:function(e,t,r){"use strict";r.r(t),r.d(t,{JOSEAlgNotAllowed:function(){return s},JOSEError:function(){return n},JOSENotSupported:function(){return a},JWEDecompressionFailed:function(){return l},JWEDecryptionFailed:function(){return c},JWEInvalid:function(){return u},JWKInvalid:function(){return f},JWKSInvalid:function(){return p},JWKSMultipleMatchingKeys:function(){return y},JWKSNoMatchingKey:function(){return g},JWKSTimeout:function(){return m},JWSInvalid:function(){return d},JWSSignatureVerificationFailed:function(){return v},JWTClaimValidationFailed:function(){return i},JWTExpired:function(){return o},JWTInvalid:function(){return h}});class n extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(e){var t;super(e),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor)}}class i extends n{static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(e,t="unspecified",r="unspecified"){super(e),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=r}}class o extends n{static get code(){return"ERR_JWT_EXPIRED"}constructor(e,t="unspecified",r="unspecified"){super(e),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=r}}class s extends n{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}}class a extends n{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class c extends n{constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}}class l extends n{constructor(){super(...arguments),this.code="ERR_JWE_DECOMPRESSION_FAILED",this.message="decompression operation failed"}static get code(){return"ERR_JWE_DECOMPRESSION_FAILED"}}class u extends n{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}}class d extends n{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class h extends n{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}class f extends n{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}}class p extends n{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}}class g extends n{constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_NO_MATCHING_KEY"}}class y extends n{constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Symbol.asyncIterator;class m extends n{constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}}class v extends n{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}}},t={};function r(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,r),o.exports}r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n=r(423);return n.default}()})); //# sourceMappingURL=remotestorage.js.map \ No newline at end of file diff --git a/release/remotestorage.js.map b/release/remotestorage.js.map index 4a45e5f95..201acdadc 100644 --- a/release/remotestorage.js.map +++ b/release/remotestorage.js.map @@ -1 +1 @@ -{"version":3,"file":"remotestorage.js","mappings":";CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,gBAAiB,GAAIH,GACF,iBAAZC,QACdA,QAAuB,cAAID,IAE3BD,EAAoB,cAAIC,GACzB,CATD,CASGK,MAAM,WACT,6CCVA,IAAI,OAAEC,GAAW,EAAQ,MAErBC,EAAI,CAAC,EAELC,EAAgBD,EAAEC,WAAgB,EAClCC,EAAgBF,EAAEE,YAA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ClB,OAAOlE,GAAOkE,EAASpd,EAAI5xD,OAAQozD,EACvC,CAqCA,MAwGM+4B,GAAS,CAvGXtN,6BACAH,kBACAQ,6BACAJ,qCACAH,0BACAC,qCACAL,0BACA1F,oBACAkG,cACAK,mBACAd,eACAZ,eAGAqI,mBACAC,yBACAC,sBACAC,gBACAC,sBACAC,4BACAC,yBACAC,mBACAjM,gBACAkM,sBACAzL,yBACA0L,4BACAzL,+BACA0L,yBACA5K,4BACA6K,mBACA9K,sBAGAuH,gBACAwD,cAAe/C,GACfgD,aAAc3C,GACdZ,aACAE,gBACAC,gBACAqD,cAAenD,GACfoD,aAAc/C,GACdN,aACAW,2BACAE,wBACAE,2BACAH,qBACAE,wBACAK,2BACAH,wBACAoE,qBAGA9B,YACAqE,iBACAjE,eACAoE,cACAG,iBACAhE,eACAkE,iBACA9D,YACAmE,cACAnD,aACAC,gBACAC,gBACAC,gBACAC,gBACAC,UArLJ,SAAmBna,EAAShvE,GAGxB,MAAMuiF,EAAmByG,GAAaha,GACtC,IAAI72E,EAAS+2E,GAAOF,EAASpd,EAAI5xD,OAAQA,GAKzC,OAHIuiF,IACApqF,EAAS+wF,GAAa/wF,IAEnBA,CACX,EA4KIixF,gBA5FJ,SAAyBpa,GACrB,OAAOxB,GAAUwB,EAASpd,EAAI5xD,OAAQozD,EAC1C,EA2FIm0B,oBACAC,cACAC,aACAU,oBACAC,cACA/gE,aACAgiE,uBACAC,iBACAC,gBACAwB,yBACAH,sBACAC,yBACAC,sBACAH,yBACAH,sBACAC,yBACAC,sBACAS,0BACAH,uBACAC,0BACAC,uBACAI,4BACAG,sBACAE,yBACAE,yBACAK,sBAGA3G,gBACAD,eAkCE8G,GAAwB,CAACx6B,EAAImB,MAAOnB,EAAIoB,OAmB9C,SAASq5B,GAA0BC,EAASC,EAAezY,GACvD,GAAIwY,EAAQE,iBAAiB32F,OAAS,EAGlC,OAAO,KAEX,MAAM42F,EAAwBH,EAAQI,YAAYz7E,QAAQksE,GAAWwP,G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rsM,KAAOqsM,EACXL,EAAoB98L,EAAEm9L,EAAYrsM,KAASgsM,EAAoB98L,EAAEhT,EAAS8D,IAC5EW,OAAOwO,eAAejT,EAAS8D,EAAK,CAAEoP,YAAY,EAAMC,IAAKg9L,EAAWrsM,IAG3E,ECPAgsM,EAAoB5wL,EAAI,WACvB,GAA0B,iBAAf5X,WAAyB,OAAOA,WAC3C,IACC,OAAOlH,MAAQ,IAAI+jD,SAAS,cAAb,EAChB,CAAE,MAAO96C,GACR,GAAsB,iBAAXiJ,OAAqB,OAAOA,MACxC,CACA,CAPuB,GCAxBw9L,EAAoB98L,EAAI,SAAS2nB,EAAKshC,GAAQ,OAAOx3D,OAAOM,UAAU0O,eAAexK,KAAK0xB,EAAKshC,EAAO,ECCtG6zI,EAAoBn9L,EAAI,SAAS3S,GACX,oBAAXoT,QAA0BA,OAAOC,aAC1C5O,OAAOwO,eAAejT,EAASoT,OAAOC,YAAa,CAAE9P,MAAO,WAE7DkB,OAAOwO,eAAejT,EAAS,aAAc,CAAEuD,OAAO,GACvD,ECHA,IAAI6sM,EAAsBN,EAAoB,sBjRO9C","sources":["webpack://RemoteStorage/webpack/universalModuleDefinition","webpack://RemoteStorage/./node_modules/@bergos/jsonparse/jsonparse.js","webpack://RemoteStorage/./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs","webpack://RemoteStorage/./node_modules/uuid/dist/esm-browser/native.js","webpack://RemoteStorage/./node_modules/uuid/dist/esm-browser/rng.js","webpack://RemoteStorage/./node_modules/uuid/dist/esm-browser/stringify.js","webpack://RemoteStorage/./node_modules/uuid/dist/esm-browser/v4.js","webpack://RemoteStorage/./node_modules/@inrupt/solid-client-authn-core/dist/index.mjs","webpack://RemoteStorage/./node_modules/@inrupt/oidc-client-ext/dist/index.es.js","webpack://RemoteStorage/./node_modules/@inrupt/oidc-client/lib/oidc-client.min.js","webpack://RemoteStorage/./node_modules/@inrupt/solid-client-authn-browser/dist/index.js","webpack://RemoteStorage/./node_modules/@inrupt/solid-client-authn-core/dist/index.js","webpack://RemoteStorage/./node_modules/@inrupt/solid-client/dist/index.js","webpack://RemoteStorage/./node_modules/@inrupt/universal-fetch/dist/index-browser.js","webpack://RemoteStorage/./node_modules/@rdfjs/data-model/index.js","webpack://RemoteStorage/./node_modules/@rdfjs/data-model/lib/BlankNode.js","webpack://RemoteStorage/./node_modules/@rdfjs/data-model/lib/DataFactory.js","webpack://RemoteStorage/./node_modules/@rdfjs/data-model/lib/DefaultGraph.js","webpack://RemoteStorage/./node_modules/@rdfjs/data-model/lib/Literal.js","webpack://RemoteStorage/./node_modules/@rdfjs/data-model/lib/NamedNode.js","webpack://RemoteStorage/./node_modules/@rdfjs/data-model/lib/Quad.js","webpack://RemoteStorage/./node_modules/@rdfjs/data-model/lib/Variable.js","webpack://RemoteStorage/./node_modules/@rdfjs/data-model/lib/fromTerm.js","webpack://RemoteStorage/./node_modules/@rdfjs/dataset/DatasetCore.js","webpack://RemoteStorage/./node_modules/@rdfjs/dataset/index.js","webpack://RemoteStorage/./node_modules/abort-controller/browser.js","webpack://RemoteStorage/./node_modules/base64-js/index.js","webpack://RemoteStorage/./node_modules/blob/main.js","webpack://RemoteStorage/./node_modules/buffer/index.js","webpack://RemoteStorage/./node_modules/canonicalize/lib/canonicalize.js","webpack://RemoteStorage/./node_modules/cross-fetch/dist/browser-polyfill.js","webpack://RemoteStorage/./node_modules/events/events.js","webpack://RemoteStorage/./node_modules/http-link-header/lib/link.js","webpack://RemoteStorage/./node_modules/ieee754/index.js","webpack://RemoteStorage/./node_modules/jsonld-context-parser/index.js","webpack://RemoteStorage/./node_modules/jsonld-context-parser/lib/ContextParser.js","webpack://RemoteStorage/./node_modules/jsonld-context-parser/lib/ErrorCoded.js","webpack://RemoteStorage/./node_modules/jsonld-context-parser/lib/FetchDocumentLoader.js","webpack://RemoteStorage/./node_modules/jsonld-context-parser/lib/IDocumentLoader.js","webpack://RemoteStorage/./node_modules/jsonld-context-parser/lib/JsonLdContext.js","webpack://RemoteStorage/./node_modules/jsonld-context-parser/lib/JsonLdContextNormalized.js","webpack://RemoteStorage/./node_modules/jsonld-context-parser/lib/Util.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/index.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/ContextTree.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/JsonLdParser.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/ParsingContext.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/Util.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/containerhandler/ContainerHandlerIdentifier.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/containerhandler/ContainerHandlerIndex.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/containerhandler/ContainerHandlerLanguage.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/containerhandler/ContainerHandlerType.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/EntryHandlerArrayValue.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/EntryHandlerContainer.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/EntryHandlerInvalidFallback.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/EntryHandlerPredicate.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/keyword/EntryHandlerKeyword.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/keyword/EntryHandlerKeywordAnnotation.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/keyword/EntryHandlerKeywordContext.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/keyword/EntryHandlerKeywordGraph.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/keyword/EntryHandlerKeywordId.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/keyword/EntryHandlerKeywordIncluded.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/keyword/EntryHandlerKeywordNest.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/keyword/EntryHandlerKeywordType.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/keyword/EntryHandlerKeywordUnknownFallback.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/lib/entryhandler/keyword/EntryHandlerKeywordValue.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/add-abort-signal.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/buffer_list.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/compose.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/destroy.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/duplex.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/duplexify.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/from.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/legacy.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/operators.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/passthrough.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/pipeline.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/readable.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/state.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/transform.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/utils.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/streams/writable.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/internal/validators.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/ours/browser.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/ours/errors.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/ours/primordials.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/ours/util.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/stream.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/readable-stream/lib/stream/promises.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/safe-buffer/index.js","webpack://RemoteStorage/./node_modules/jsonld-streaming-parser/node_modules/string_decoder/lib/string_decoder.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/add-abort-signal.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/buffer_list.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/compose.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/destroy.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/duplex.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/duplexify.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/from.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/legacy.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/operators.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/passthrough.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/pipeline.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/readable.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/state.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/transform.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/utils.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/streams/writable.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/internal/validators.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/ours/browser.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/ours/errors.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/ours/primordials.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/ours/util.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/stream.js","webpack://RemoteStorage/./node_modules/n3/node_modules/readable-stream/lib/stream/promises.js","webpack://RemoteStorage/./node_modules/n3/node_modules/safe-buffer/index.js","webpack://RemoteStorage/./node_modules/n3/node_modules/string_decoder/lib/string_decoder.js","webpack://RemoteStorage/./node_modules/n3/src/IRIs.js","webpack://RemoteStorage/./node_modules/n3/src/N3Lexer.js","webpack://RemoteStorage/./node_modules/n3/src/N3DataFactory.js","webpack://RemoteStorage/./node_modules/n3/src/N3Parser.js","webpack://RemoteStorage/./node_modules/n3/src/N3Util.js","webpack://RemoteStorage/./node_modules/n3/src/N3Writer.js","webpack://RemoteStorage/./node_modules/n3/src/N3Store.js","webpack://RemoteStorage/./node_modules/n3/src/N3StoreFactory.js","webpack://RemoteStorage/./node_modules/n3/src/N3Reasoner.js","webpack://RemoteStorage/./node_modules/n3/src/N3StreamParser.js","webpack://RemoteStorage/./node_modules/n3/src/N3StreamWriter.js","webpack://RemoteStorage/./node_modules/n3/src/index.js","webpack://RemoteStorage/./node_modules/process/browser.js","webpack://RemoteStorage/./node_modules/queue-microtask/index.js","webpack://RemoteStorage/./node_modules/rdf-data-factory/index.js","webpack://RemoteStorage/./node_modules/rdf-data-factory/lib/BlankNode.js","webpack://RemoteStorage/./node_modules/rdf-data-factory/lib/DataFactory.js","webpack://RemoteStorage/./node_modules/rdf-data-factory/lib/DefaultGraph.js","webpack://RemoteStorage/./node_modules/rdf-data-factory/lib/Literal.js","webpack://RemoteStorage/./node_modules/rdf-data-factory/lib/NamedNode.js","webpack://RemoteStorage/./node_modules/rdf-data-factory/lib/Quad.js","webpack://RemoteStorage/./node_modules/rdf-data-factory/lib/Variable.js","webpack://RemoteStorage/./node_modules/relative-to-absolute-iri/index.js","webpack://RemoteStorage/./node_modules/relative-to-absolute-iri/lib/Resolve.js","webpack://RemoteStorage/./src/access.ts","webpack://RemoteStorage/./src/authorize.ts","webpack://RemoteStorage/./src/baseclient.ts","webpack://RemoteStorage/./src/caching.ts","webpack://RemoteStorage/./src/cachinglayer.ts","webpack://RemoteStorage/./src/config.ts","webpack://RemoteStorage/./src/discover.ts","webpack://RemoteStorage/./src/dropbox.ts","webpack://RemoteStorage/./src/env.ts","webpack://RemoteStorage/./src/eventhandling.ts","webpack://RemoteStorage/./src/features.ts","webpack://RemoteStorage/./src/googledrive.ts","webpack://RemoteStorage/./src/indexeddb.ts","webpack://RemoteStorage/./src/inmemorystorage.ts","webpack://RemoteStorage/./src/localstorage.ts","webpack://RemoteStorage/./src/log.ts","webpack://RemoteStorage/./src/remote.ts","webpack://RemoteStorage/./src/remotestorage.ts","webpack://RemoteStorage/./src/requests.ts","webpack://RemoteStorage/./src/revisioncache.ts","webpack://RemoteStorage/./src/schema-not-found-error.ts","webpack://RemoteStorage/./src/solid.ts","webpack://RemoteStorage/./src/solidStorage.ts","webpack://RemoteStorage/./src/sync-error.ts","webpack://RemoteStorage/./src/sync.ts","webpack://RemoteStorage/./src/syncedgetputdelete.ts","webpack://RemoteStorage/./src/types.ts","webpack://RemoteStorage/./src/unauthorized-error.ts","webpack://RemoteStorage/./src/util.ts","webpack://RemoteStorage/./src/wireclient.ts","webpack://RemoteStorage/./node_modules/tv4/tv4.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/index.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/md5.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/native.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/nil.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/parse.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/regex.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/rng.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/sha1.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/stringify.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/v1.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/v3.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/v35.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/v4.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/v5.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/validate.js","webpack://RemoteStorage/./node_modules/uuid/dist/commonjs-browser/version.js","webpack://RemoteStorage/./node_modules/webfinger.js/src/webfinger.js","webpack://RemoteStorage/./node_modules/xhr2/lib/browser.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/iv.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/check_iv_length.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/check_cek_length.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/decrypt.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/timing_safe_equal.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/zlib.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/bogus.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/aeskw.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/ecdhes.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/pbes2kw.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/check_p2s.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/subtle_rsaes.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/cek.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/encrypt.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/decrypt_key_management.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/rsaes.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/aesgcmkw.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwe/flattened/decrypt.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwe/compact/decrypt.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwe/general/decrypt.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/encrypt_key_management.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwe/flattened/encrypt.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwe/general/encrypt.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jws/general/verify.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwt/decrypt.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwe/compact/encrypt.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jws/general/sign.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwt/encrypt.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwk/thumbprint.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwk/embedded.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwks/local.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwks/remote.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/fetch_jwks.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwt/unsecured.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/util/base64url.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/util/decode_protected_header.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/util/decode_jwt.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/key/generate_secret.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/runtime.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/util/runtime.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jws/compact/sign.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jws/compact/verify.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jws/flattened/sign.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/sign.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/verify.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jws/flattened/verify.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwt/produce.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwt/sign.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/jwt/verify.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/key_to_jwk.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/key/export.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/key/generate_key_pair.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/jwk_to_key.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/key/import.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/buffer_utils.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/check_key_type.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/crypto_key.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/epoch.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/invalid_key_input.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/is_disjoint.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/is_object.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/jwt_claims_set.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/secs.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/validate_algorithms.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/validate_crit.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/lib/format_pem.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/asn1.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/base64url.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/check_key_length.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/digest.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/generate.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/get_sign_verify_key.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/is_key_like.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/random.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/subtle_dsa.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/runtime/webcrypto.js","webpack://RemoteStorage/./node_modules/jose/dist/browser/util/errors.js","webpack://RemoteStorage/webpack/bootstrap","webpack://RemoteStorage/webpack/runtime/compat get default export","webpack://RemoteStorage/webpack/runtime/define property getters","webpack://RemoteStorage/webpack/runtime/global","webpack://RemoteStorage/webpack/runtime/hasOwnProperty shorthand","webpack://RemoteStorage/webpack/runtime/make namespace object","webpack://RemoteStorage/webpack/startup"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"RemoteStorage\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"RemoteStorage\"] = factory();\n\telse\n\t\troot[\"RemoteStorage\"] = factory();\n})(this, function() {\nreturn ","var { Buffer } = require('buffer')\n// Named constants with unique integer values\nvar C = {};\n// Tokens\nvar LEFT_BRACE = C.LEFT_BRACE = 0x1;\nvar RIGHT_BRACE = C.RIGHT_BRACE = 0x2;\nvar LEFT_BRACKET = C.LEFT_BRACKET = 0x3;\nvar RIGHT_BRACKET = C.RIGHT_BRACKET = 0x4;\nvar COLON = C.COLON = 0x5;\nvar COMMA = C.COMMA = 0x6;\nvar TRUE = C.TRUE = 0x7;\nvar FALSE = C.FALSE = 0x8;\nvar NULL = C.NULL = 0x9;\nvar STRING = C.STRING = 0xa;\nvar NUMBER = C.NUMBER = 0xb;\n// Tokenizer States\nvar START = C.START = 0x11;\nvar STOP = C.STOP = 0x12;\nvar TRUE1 = C.TRUE1 = 0x21;\nvar TRUE2 = C.TRUE2 = 0x22;\nvar TRUE3 = C.TRUE3 = 0x23;\nvar FALSE1 = C.FALSE1 = 0x31;\nvar FALSE2 = C.FALSE2 = 0x32;\nvar FALSE3 = C.FALSE3 = 0x33;\nvar FALSE4 = C.FALSE4 = 0x34;\nvar NULL1 = C.NULL1 = 0x41;\nvar NULL2 = C.NULL2 = 0x42;\nvar NULL3 = C.NULL3 = 0x43;\nvar NUMBER1 = C.NUMBER1 = 0x51;\nvar NUMBER3 = C.NUMBER3 = 0x53;\nvar STRING1 = C.STRING1 = 0x61;\nvar STRING2 = C.STRING2 = 0x62;\nvar STRING3 = C.STRING3 = 0x63;\nvar STRING4 = C.STRING4 = 0x64;\nvar STRING5 = C.STRING5 = 0x65;\nvar STRING6 = C.STRING6 = 0x66;\n// Parser States\nvar VALUE = C.VALUE = 0x71;\nvar KEY = C.KEY = 0x72;\n// Parser Modes\nvar OBJECT = C.OBJECT = 0x81;\nvar ARRAY = C.ARRAY = 0x82;\n// Character constants\nvar BACK_SLASH = \"\\\\\".charCodeAt(0);\nvar FORWARD_SLASH = \"\\/\".charCodeAt(0);\nvar BACKSPACE = \"\\b\".charCodeAt(0);\nvar FORM_FEED = \"\\f\".charCodeAt(0);\nvar NEWLINE = \"\\n\".charCodeAt(0);\nvar CARRIAGE_RETURN = \"\\r\".charCodeAt(0);\nvar TAB = \"\\t\".charCodeAt(0);\n\nvar STRING_BUFFER_SIZE = 64 * 1024;\n\nfunction alloc(size) {\n return Buffer.alloc ? Buffer.alloc(size) : new Buffer(size);\n}\n\nfunction Parser() {\n this.tState = START;\n this.value = undefined;\n\n this.string = undefined; // string data\n this.stringBuffer = alloc(STRING_BUFFER_SIZE);\n this.stringBufferOffset = 0;\n this.unicode = undefined; // unicode escapes\n this.highSurrogate = undefined;\n\n this.key = undefined;\n this.mode = undefined;\n this.stack = [];\n this.state = VALUE;\n this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary\n this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read\n this.temp_buffs = { \"2\": alloc(2), \"3\": alloc(3), \"4\": alloc(4) }; // for rebuilding chars split before boundary is reached\n\n // Stream offset\n this.offset = -1;\n}\n\n// Slow code to string converter (only used when throwing syntax errors)\nParser.toknam = function (code) {\n var keys = Object.keys(C);\n for (var i = 0, l = keys.length; i < l; i++) {\n var key = keys[i];\n if (C[key] === code) { return key; }\n }\n return code && (\"0x\" + code.toString(16));\n};\n\nvar proto = Parser.prototype;\nproto.onError = function (err) { throw err; };\nproto.charError = function (buffer, i) {\n this.tState = STOP;\n this.onError(new Error(\"Unexpected \" + JSON.stringify(String.fromCharCode(buffer[i])) + \" at position \" + i + \" in state \" + Parser.toknam(this.tState)));\n};\nproto.appendStringChar = function (char) {\n if (this.stringBufferOffset >= STRING_BUFFER_SIZE) {\n this.string += this.stringBuffer.toString('utf8');\n this.stringBufferOffset = 0;\n }\n\n this.stringBuffer[this.stringBufferOffset++] = char;\n};\nproto.appendStringBuf = function (buf, start, end) {\n var size = buf.length;\n if (typeof start === 'number') {\n if (typeof end === 'number') {\n if (end < 0) {\n // adding a negative end decreeses the size\n size = buf.length - start + end;\n } else {\n size = end - start;\n }\n } else {\n size = buf.length - start;\n }\n }\n\n if (size < 0) {\n size = 0;\n }\n\n if (this.stringBufferOffset + size > STRING_BUFFER_SIZE) {\n this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset);\n this.stringBufferOffset = 0;\n }\n\n buf.copy(this.stringBuffer, this.stringBufferOffset, start, end);\n this.stringBufferOffset += size;\n};\nproto.write = function (buffer) {\n if (typeof buffer === \"string\") buffer = new Buffer(buffer);\n var n;\n for (var i = 0, l = buffer.length; i < l; i++) {\n if (this.tState === START){\n n = buffer[i];\n this.offset++;\n if(n === 0x7b){ this.onToken(LEFT_BRACE, \"{\"); // {\n }else if(n === 0x7d){ this.onToken(RIGHT_BRACE, \"}\"); // }\n }else if(n === 0x5b){ this.onToken(LEFT_BRACKET, \"[\"); // [\n }else if(n === 0x5d){ this.onToken(RIGHT_BRACKET, \"]\"); // ]\n }else if(n === 0x3a){ this.onToken(COLON, \":\"); // :\n }else if(n === 0x2c){ this.onToken(COMMA, \",\"); // ,\n }else if(n === 0x74){ this.tState = TRUE1; // t\n }else if(n === 0x66){ this.tState = FALSE1; // f\n }else if(n === 0x6e){ this.tState = NULL1; // n\n }else if(n === 0x22){ // \"\n this.string = \"\";\n this.stringBufferOffset = 0;\n this.tState = STRING1;\n }else if(n === 0x2d){ this.string = \"-\"; this.tState = NUMBER1; // -\n }else{\n if (n >= 0x30 && n < 0x40) { // 1-9\n this.string = String.fromCharCode(n); this.tState = NUMBER3;\n } else if (n === 0x20 || n === 0x09 || n === 0x0a || n === 0x0d) {\n // whitespace\n } else {\n return this.charError(buffer, i);\n }\n }\n }else if (this.tState === STRING1){ // After open quote\n n = buffer[i]; // get current byte from buffer\n // check for carry over of a multi byte char split between data chunks\n // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration\n if (this.bytes_remaining > 0) {\n for (var j = 0; j < this.bytes_remaining; j++) {\n this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = buffer[j];\n }\n\n this.appendStringBuf(this.temp_buffs[this.bytes_in_sequence]);\n this.bytes_in_sequence = this.bytes_remaining = 0;\n i = i + j - 1;\n } else if (this.bytes_remaining === 0 && n >= 128) { // else if no remainder bytes carried over, parse multi byte (>=128) chars one at a time\n if (n <= 193 || n > 244) {\n return this.onError(new Error(\"Invalid UTF-8 character at position \" + i + \" in state \" + Parser.toknam(this.tState)));\n }\n if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2;\n if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3;\n if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4;\n if ((this.bytes_in_sequence + i) > buffer.length) { // if bytes needed to complete char fall outside buffer length, we have a boundary split\n for (var k = 0; k <= (buffer.length - 1 - i); k++) {\n this.temp_buffs[this.bytes_in_sequence][k] = buffer[i + k]; // fill temp buffer of correct size with bytes available in this chunk\n }\n this.bytes_remaining = (i + this.bytes_in_sequence) - buffer.length;\n i = buffer.length - 1;\n } else {\n this.appendStringBuf(buffer, i, i + this.bytes_in_sequence);\n i = i + this.bytes_in_sequence - 1;\n }\n } else if (n === 0x22) {\n this.tState = START;\n this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset);\n this.stringBufferOffset = 0;\n this.onToken(STRING, this.string);\n this.offset += Buffer.byteLength(this.string, 'utf8') + 1;\n this.string = undefined;\n }\n else if (n === 0x5c) {\n this.tState = STRING2;\n }\n else if (n >= 0x20) { this.appendStringChar(n); }\n else {\n return this.charError(buffer, i);\n }\n }else if (this.tState === STRING2){ // After backslash\n n = buffer[i];\n if(n === 0x22){ this.appendStringChar(n); this.tState = STRING1;\n }else if(n === 0x5c){ this.appendStringChar(BACK_SLASH); this.tState = STRING1;\n }else if(n === 0x2f){ this.appendStringChar(FORWARD_SLASH); this.tState = STRING1;\n }else if(n === 0x62){ this.appendStringChar(BACKSPACE); this.tState = STRING1;\n }else if(n === 0x66){ this.appendStringChar(FORM_FEED); this.tState = STRING1;\n }else if(n === 0x6e){ this.appendStringChar(NEWLINE); this.tState = STRING1;\n }else if(n === 0x72){ this.appendStringChar(CARRIAGE_RETURN); this.tState = STRING1;\n }else if(n === 0x74){ this.appendStringChar(TAB); this.tState = STRING1;\n }else if(n === 0x75){ this.unicode = \"\"; this.tState = STRING3;\n }else{\n return this.charError(buffer, i);\n }\n }else if (this.tState === STRING3 || this.tState === STRING4 || this.tState === STRING5 || this.tState === STRING6){ // unicode hex codes\n n = buffer[i];\n // 0-9 A-F a-f\n if ((n >= 0x30 && n < 0x40) || (n > 0x40 && n <= 0x46) || (n > 0x60 && n <= 0x66)) {\n this.unicode += String.fromCharCode(n);\n if (this.tState++ === STRING6) {\n var intVal = parseInt(this.unicode, 16);\n this.unicode = undefined;\n if (this.highSurrogate !== undefined && intVal >= 0xDC00 && intVal < (0xDFFF + 1)) { //<56320,57343> - lowSurrogate\n this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate, intVal)));\n this.highSurrogate = undefined;\n } else if (this.highSurrogate === undefined && intVal >= 0xD800 && intVal < (0xDBFF + 1)) { //<55296,56319> - highSurrogate\n this.highSurrogate = intVal;\n } else {\n if (this.highSurrogate !== undefined) {\n this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate)));\n this.highSurrogate = undefined;\n }\n this.appendStringBuf(new Buffer(String.fromCharCode(intVal)));\n }\n this.tState = STRING1;\n }\n } else {\n return this.charError(buffer, i);\n }\n } else if (this.tState === NUMBER1 || this.tState === NUMBER3) {\n n = buffer[i];\n\n switch (n) {\n case 0x30: // 0\n case 0x31: // 1\n case 0x32: // 2\n case 0x33: // 3\n case 0x34: // 4\n case 0x35: // 5\n case 0x36: // 6\n case 0x37: // 7\n case 0x38: // 8\n case 0x39: // 9\n case 0x2e: // .\n case 0x65: // e\n case 0x45: // E\n case 0x2b: // +\n case 0x2d: // -\n this.string += String.fromCharCode(n);\n this.tState = NUMBER3;\n break;\n default:\n this.tState = START;\n var error = this.numberReviver(this.string, buffer, i);\n if (error){\n return error;\n }\n\n this.offset += this.string.length - 1;\n this.string = undefined;\n i--;\n break;\n }\n }else if (this.tState === TRUE1){ // r\n if (buffer[i] === 0x72) { this.tState = TRUE2; }\n else { return this.charError(buffer, i); }\n }else if (this.tState === TRUE2){ // u\n if (buffer[i] === 0x75) { this.tState = TRUE3; }\n else { return this.charError(buffer, i); }\n }else if (this.tState === TRUE3){ // e\n if (buffer[i] === 0x65) { this.tState = START; this.onToken(TRUE, true); this.offset+= 3; }\n else { return this.charError(buffer, i); }\n }else if (this.tState === FALSE1){ // a\n if (buffer[i] === 0x61) { this.tState = FALSE2; }\n else { return this.charError(buffer, i); }\n }else if (this.tState === FALSE2){ // l\n if (buffer[i] === 0x6c) { this.tState = FALSE3; }\n else { return this.charError(buffer, i); }\n }else if (this.tState === FALSE3){ // s\n if (buffer[i] === 0x73) { this.tState = FALSE4; }\n else { return this.charError(buffer, i); }\n }else if (this.tState === FALSE4){ // e\n if (buffer[i] === 0x65) { this.tState = START; this.onToken(FALSE, false); this.offset+= 4; }\n else { return this.charError(buffer, i); }\n }else if (this.tState === NULL1){ // u\n if (buffer[i] === 0x75) { this.tState = NULL2; }\n else { return this.charError(buffer, i); }\n }else if (this.tState === NULL2){ // l\n if (buffer[i] === 0x6c) { this.tState = NULL3; }\n else { return this.charError(buffer, i); }\n }else if (this.tState === NULL3){ // l\n if (buffer[i] === 0x6c) { this.tState = START; this.onToken(NULL, null); this.offset += 3; }\n else { return this.charError(buffer, i); }\n }\n }\n};\nproto.onToken = function (token, value) {\n // Override this to get events\n};\n\nproto.parseError = function (token, value) {\n this.tState = STOP;\n this.onError(new Error(\"Unexpected \" + Parser.toknam(token) + (value ? (\"(\" + JSON.stringify(value) + \")\") : \"\") + \" in state \" + Parser.toknam(this.state)));\n};\nproto.push = function () {\n this.stack.push({value: this.value, key: this.key, mode: this.mode});\n};\nproto.pop = function () {\n var value = this.value;\n var parent = this.stack.pop();\n this.value = parent.value;\n this.key = parent.key;\n this.mode = parent.mode;\n this.emit(value);\n if (!this.mode) { this.state = VALUE; }\n};\nproto.emit = function (value) {\n if (this.mode) { this.state = COMMA; }\n this.onValue(value);\n};\nproto.onValue = function (value) {\n // Override me\n};\nproto.onToken = function (token, value) {\n if(this.state === VALUE){\n if(token === STRING || token === NUMBER || token === TRUE || token === FALSE || token === NULL){\n if (this.value) {\n this.value[this.key] = value;\n }\n this.emit(value);\n }else if(token === LEFT_BRACE){\n this.push();\n if (this.value) {\n this.value = this.value[this.key] = {};\n } else {\n this.value = {};\n }\n this.key = undefined;\n this.state = KEY;\n this.mode = OBJECT;\n }else if(token === LEFT_BRACKET){\n this.push();\n if (this.value) {\n this.value = this.value[this.key] = [];\n } else {\n this.value = [];\n }\n this.key = 0;\n this.mode = ARRAY;\n this.state = VALUE;\n }else if(token === RIGHT_BRACE){\n if (this.mode === OBJECT) {\n this.pop();\n } else {\n return this.parseError(token, value);\n }\n }else if(token === RIGHT_BRACKET){\n if (this.mode === ARRAY) {\n this.pop();\n } else {\n return this.parseError(token, value);\n }\n }else{\n return this.parseError(token, value);\n }\n }else if(this.state === KEY){\n if (token === STRING) {\n this.key = value;\n this.state = COLON;\n } else if (token === RIGHT_BRACE) {\n this.pop();\n } else {\n return this.parseError(token, value);\n }\n }else if(this.state === COLON){\n if (token === COLON) { this.state = VALUE; }\n else { return this.parseError(token, value); }\n }else if(this.state === COMMA){\n if (token === COMMA) {\n if (this.mode === ARRAY) { this.key++; this.state = VALUE; }\n else if (this.mode === OBJECT) { this.state = KEY; }\n\n } else if (token === RIGHT_BRACKET && this.mode === ARRAY || token === RIGHT_BRACE && this.mode === OBJECT) {\n this.pop();\n } else {\n return this.parseError(token, value);\n }\n }else{\n return this.parseError(token, value);\n }\n};\n\n// Override to implement your own number reviver.\n// Any value returned is treated as error and will interrupt parsing.\nproto.numberReviver = function (text, buffer, i) {\n var result = Number(text);\n\n if (isNaN(result)) {\n return this.charError(buffer, i);\n }\n\n if ((text.match(/[0-9]+/) == text) && (result.toString() != text)) {\n // Long string of digits which is an ID string and not valid and/or safe JavaScript integer Number\n this.onToken(STRING, text);\n } else {\n this.onToken(NUMBER, result);\n }\n}\n\nParser.C = C;\n\nmodule.exports = Parser;\n","var indexBrowser = globalThis.fetch;\nconst { fetch, Response, Request, Headers } = globalThis;\n\nexport { Headers, Request, Response, indexBrowser as default, fetch };\n","const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default {\n randomUUID\n};","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nlet getRandomValues;\nconst rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\n\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(rnds);\n}\n\nexport default v4;","import { EventEmitter } from 'events';\nimport { fetch, Headers } from '@inrupt/universal-fetch';\nimport { jwtVerify, importJWK, exportJWK, SignJWT, generateKeyPair } from 'jose';\nimport { v4 } from 'uuid';\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Intended to be used by dependent packages as a common prefix for keys into\n * storage mechanisms (so as to group all keys related to Solid Client Authn\n * within those storage mechanisms, e.g., window.localStorage).\n */\nconst SOLID_CLIENT_AUTHN_KEY_PREFIX = \"solidClientAuthn:\";\n/**\n * Ordered list of signature algorithms, from most preferred to least preferred.\n */\nconst PREFERRED_SIGNING_ALG = [\"ES256\", \"RS256\"];\nconst EVENTS = {\n // Note that an `error` events MUST be listened to: https://nodejs.org/dist/latest-v16.x/docs/api/events.html#error-events.\n ERROR: \"error\",\n LOGIN: \"login\",\n LOGOUT: \"logout\",\n NEW_REFRESH_TOKEN: \"newRefreshToken\",\n SESSION_EXPIRED: \"sessionExpired\",\n SESSION_EXTENDED: \"sessionExtended\",\n SESSION_RESTORED: \"sessionRestore\",\n TIMEOUT_SET: \"timeoutSet\",\n};\n/**\n * We want to refresh a token 5 seconds before it expires.\n */\nconst REFRESH_BEFORE_EXPIRATION_SECONDS = 5;\n// The openid scope requests an OIDC ID token token to be returned.\nconst SCOPE_OPENID = \"openid\";\n// The offline_access scope requests a refresh token to be returned.\nconst SCOPE_OFFLINE = \"offline_access\";\n// The webid scope is required as per https://solid.github.io/solid-oidc/#webid-scope\nconst SCOPE_WEBID = \"webid\";\n// The scopes are expected as a space-separated list.\nconst DEFAULT_SCOPES = [SCOPE_OPENID, SCOPE_OFFLINE, SCOPE_WEBID].join(\" \");\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Temporary internal builder for safe proxying.\n */\nconst buildProxyHandler = (\n// The class to be excluded needs to be injected, because it is defined in a\n// dependency.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntoExclude, errorMessage) => ({\n // This proxy is only a temporary measure until Session no longer extends\n // SessionEventEmitter, and the proxying is no longer necessary.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(target, prop, receiver) {\n // Reject any calls to the proxy that isn't specific to the EventEmitter API\n if (!Object.getOwnPropertyNames(EventEmitter).includes(prop) &&\n Object.getOwnPropertyNames(toExclude).includes(prop)) {\n throw new Error(`${errorMessage}: [${prop}] is not supported`);\n }\n return Reflect.get(target, prop, receiver);\n },\n});\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n */\nclass AggregateHandler {\n constructor(handleables) {\n this.handleables = handleables;\n this.handleables = handleables;\n }\n /**\n * Helper function that will asynchronously determine the proper handler to use. If multiple\n * handlers can handle, it will choose the first one in the list\n * @param params Paramerters to feed to the handler\n */\n async getProperHandler(params) {\n // TODO : This function doesn't currently operate as described. Tests need to be written\n // return new Promise | null>((resolve, reject) => {\n // const resolvedValues: Array = Array(this.handleables.length).map(() => null)\n // let numberResolved = 0\n // this.handleables.forEach(async (handleable: IHandleable, index: number) => {\n // resolvedValues[index] = await handleable.canHandle(...params)\n // numberResolved++\n // let curResolvedValueIndex = 0\n // while (\n // resolvedValues[curResolvedValueIndex] !== null ||\n // resolvedValues[curResolvedValueIndex] !== undefined\n // ) {\n // if (resolvedValues[curResolvedValueIndex]) {\n // resolve(this.handleables[curResolvedValueIndex])\n // }\n // curResolvedValueIndex++\n // }\n // })\n // })\n const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));\n for (let i = 0; i < canHandleList.length; i += 1) {\n if (canHandleList[i]) {\n return this.handleables[i];\n }\n }\n return null;\n }\n async canHandle(...params) {\n return (await this.getProperHandler(params)) !== null;\n }\n async handle(...params) {\n const handler = await this.getProperHandler(params);\n if (handler) {\n return handler.handle(...params);\n }\n throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params\n .map((param) => {\n try {\n return JSON.stringify(param);\n }\n catch (err) {\n /* eslint-disable @typescript-eslint/no-explicit-any */\n return param.toString();\n }\n })\n .join(\", \")}`);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// eslint-disable-next-line no-shadow\nasync function fetchJwks(jwksIri, issuerIri) {\n // FIXME: the following line works, but the underlying network calls don't seem\n // to be mocked properly by our test code. It would be nicer to replace calls to this\n // function by the following line and to fix the mocks.\n // const jwks = createRemoteJWKSet(new URL(jwksIri));\n const jwksResponse = await fetch.call(globalThis, jwksIri);\n if (jwksResponse.status !== 200) {\n throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);\n }\n // The JWKS should only contain the current key for the issuer.\n let jwk;\n try {\n jwk = (await jwksResponse.json()).keys[0];\n }\n catch (e) {\n throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);\n }\n return jwk;\n}\n/**\n * Extract a WebID from an ID token payload based on https://github.com/solid/webid-oidc-spec.\n * Note that this does not yet implement the user endpoint lookup, and only checks\n * for `webid` or IRI-like `sub` claims.\n *\n * @param idToken the payload of the ID token from which the WebID can be extracted.\n * @returns a WebID extracted from the ID token.\n * @internal\n */\nasync function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {\n const jwk = await fetchJwks(jwksIri, issuerIri);\n let payload;\n try {\n const { payload: verifiedPayload } = await jwtVerify(idToken, await importJWK(jwk), {\n issuer: issuerIri,\n audience: clientId,\n });\n payload = verifiedPayload;\n }\n catch (e) {\n throw new Error(`Token verification failed: ${e.stack}`);\n }\n if (typeof payload.webid === \"string\") {\n return payload.webid;\n }\n if (typeof payload.sub !== \"string\") {\n throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);\n }\n try {\n // This parses the 'sub' claim to check if it is a well-formed IRI.\n // However, the normalized value isn't returned to make sure the WebID is returned\n // as specified by the Identity Provider.\n // eslint-disable-next-line no-new\n new URL(payload.sub);\n return payload.sub;\n }\n catch (e) {\n throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction isValidRedirectUrl(redirectUrl) {\n // If the redirect URL is not a valid URL, an error will be thrown.\n try {\n const urlObject = new URL(redirectUrl);\n const noReservedQuery = !urlObject.searchParams.has(\"code\") &&\n !urlObject.searchParams.has(\"state\");\n // As per https://tools.ietf.org/html/rfc6749#section-3.1.2, the redirect URL\n // must not include a hash fragment.\n const noHash = urlObject.hash === \"\";\n return noReservedQuery && noHash;\n }\n catch (e) {\n return false;\n }\n}\nfunction removeOpenIdParams(redirectUrl) {\n const cleanedUpUrl = new URL(redirectUrl);\n // For auth code flow\n cleanedUpUrl.searchParams.delete(\"state\");\n cleanedUpUrl.searchParams.delete(\"code\");\n // For login error\n cleanedUpUrl.searchParams.delete(\"error\");\n cleanedUpUrl.searchParams.delete(\"error_description\");\n // For RFC9207\n cleanedUpUrl.searchParams.delete(\"iss\");\n return cleanedUpUrl;\n}\n\n/**\n * @hidden\n * @packageDocumentation\n */\n/**\n * @hidden\n * Authorization code flow spec: https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth\n * PKCE: https://tools.ietf.org/html/rfc7636\n */\nclass AuthorizationCodeWithPkceOidcHandlerBase {\n constructor(storageUtility, redirector) {\n this.storageUtility = storageUtility;\n this.redirector = redirector;\n this.storageUtility = storageUtility;\n this.redirector = redirector;\n }\n async canHandle(oidcLoginOptions) {\n return !!(oidcLoginOptions.issuerConfiguration.grantTypesSupported &&\n oidcLoginOptions.issuerConfiguration.grantTypesSupported.indexOf(\"authorization_code\") > -1);\n }\n async handleRedirect({ oidcLoginOptions, state, codeVerifier, targetUrl, }) {\n await Promise.all([\n // We use the OAuth 'state' value (which should be crypto-random) as\n // the key in our storage to store our actual SessionID. We do this\n // 'cos we'll need to lookup our session information again when the\n // browser is redirected back to us (i.e. the OAuth client\n // application) from the Authorization Server.\n // We don't want to use our session ID as the OAuth 'state' value, as\n // that session ID can be any developer-specified value, and therefore\n // may not be appropriate (since the OAuth 'state' value should really\n // be an unguessable crypto-random value).\n // eslint-disable-next-line no-underscore-dangle\n this.storageUtility.setForUser(state, {\n sessionId: oidcLoginOptions.sessionId,\n }),\n // Store our login-process state using the session ID as the key.\n // Strictly speaking, this indirection from our OAuth state value to\n // our session ID is unnecessary, but it provides a slightly cleaner\n // separation of concerns.\n this.storageUtility.setForUser(oidcLoginOptions.sessionId, {\n // eslint-disable-next-line no-underscore-dangle\n codeVerifier,\n issuer: oidcLoginOptions.issuer.toString(),\n // The redirect URL is read after redirect, so it must be stored now.\n redirectUrl: oidcLoginOptions.redirectUrl,\n dpop: oidcLoginOptions.dpop ? \"true\" : \"false\",\n }),\n ]);\n this.redirector.redirect(targetUrl, {\n handleRedirect: oidcLoginOptions.handleRedirect,\n });\n return undefined;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n */\nclass GeneralLogoutHandler {\n constructor(sessionInfoManager) {\n this.sessionInfoManager = sessionInfoManager;\n this.sessionInfoManager = sessionInfoManager;\n }\n async canHandle() {\n return true;\n }\n async handle(userId) {\n await this.sessionInfoManager.clear(userId);\n }\n}\n\nclass IRpLogoutHandler {\n constructor(redirector) {\n this.redirector = redirector;\n this.redirector = redirector;\n }\n async canHandle(userId, options) {\n return (options === null || options === void 0 ? void 0 : options.logoutType) === \"idp\";\n }\n async handle(userId, options) {\n if ((options === null || options === void 0 ? void 0 : options.logoutType) !== \"idp\") {\n throw new Error(\"Attempting to call idp logout handler to perform app logout\");\n }\n if (options.toLogoutUrl === undefined) {\n throw new Error(\"Cannot perform IDP logout. Did you log in using the OIDC authentication flow?\");\n }\n this.redirector.redirect(options.toLogoutUrl(options), {\n handleRedirect: options.handleRedirect,\n });\n }\n}\n\nclass IWaterfallLogoutHandler {\n constructor(sessionInfoManager, redirector) {\n this.handlers = [\n new GeneralLogoutHandler(sessionInfoManager),\n new IRpLogoutHandler(redirector),\n ];\n }\n async canHandle() {\n return true;\n }\n async handle(userId, options) {\n for (const handler of this.handlers) {\n /* eslint-disable no-await-in-loop */\n if (await handler.canHandle(userId, options))\n await handler.handle(userId, options);\n /* eslint-enable no-await-in-loop */\n }\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\nfunction getUnauthenticatedSession() {\n return {\n isLoggedIn: false,\n sessionId: v4(),\n fetch: (...args) => fetch.call(globalThis, ...args),\n };\n}\n/**\n * @param sessionId\n * @param storage\n * @hidden\n */\nasync function clear(sessionId, storage) {\n await Promise.all([\n storage.deleteAllUserData(sessionId, { secure: false }),\n storage.deleteAllUserData(sessionId, { secure: true }),\n ]);\n}\n/**\n * @hidden\n */\nclass SessionInfoManagerBase {\n constructor(storageUtility) {\n this.storageUtility = storageUtility;\n this.storageUtility = storageUtility;\n }\n update(_sessionId, _options) {\n throw new Error(\"Not Implemented\");\n }\n get(_) {\n throw new Error(\"Not implemented\");\n }\n // eslint-disable-next-line class-methods-use-this\n async getAll() {\n throw new Error(\"Not implemented\");\n }\n /**\n * This function removes all session-related information from storage.\n * @param sessionId the session identifier\n * @param storage the storage where session info is stored\n * @hidden\n */\n async clear(sessionId) {\n return clear(sessionId, this.storageUtility);\n }\n /**\n * Registers a new session, so that its ID can be retrieved.\n * @param sessionId\n */\n async register(_sessionId) {\n throw new Error(\"Not implemented\");\n }\n /**\n * Returns all the registered session IDs. Differs from getAll, which also\n * returns additional session information.\n */\n async getRegisteredSessionIdAll() {\n throw new Error(\"Not implemented\");\n }\n /**\n * Deletes all information about all sessions, including their registrations.\n */\n async clearAll() {\n throw new Error(\"Not implemented\");\n }\n}\n\n/**\n * This function is designed to isomorphically capture the behavior in oidc-client-js and node-oidc-provider\n * - https://github.com/IdentityModel/oidc-client-js/blob/edec8f59897bdeedcb0b4167586d49626203c2c1/src/OidcClient.js#L138\n * - https://github.com/panva/node-openid-client/blob/35758419489ff751a71f5b66f5020087a63e1e88/lib/client.js#L284\n *\n * @param options IEndSessionOptions\n * @returns The URL to redirect to in order to perform RP Initiated Logout\n * @hidden\n */\nfunction getEndSessionUrl({ endSessionEndpoint, idTokenHint, postLogoutRedirectUri, state, }) {\n const url = new URL(endSessionEndpoint);\n if (idTokenHint !== undefined)\n url.searchParams.append(\"id_token_hint\", idTokenHint);\n if (postLogoutRedirectUri !== undefined) {\n url.searchParams.append(\"post_logout_redirect_uri\", postLogoutRedirectUri);\n if (state !== undefined)\n url.searchParams.append(\"state\", state);\n }\n return url.toString();\n}\n/**\n * @param options.endSessionEndpoint The end_session_endpoint advertised by the server\n * @param options.idTokenHint The idToken supplied by the server after logging in\n * Redirects the window to the location required to perform RP initiated logout\n *\n * @hidden\n */\nfunction maybeBuildRpInitiatedLogout({ endSessionEndpoint, idTokenHint, }) {\n if (endSessionEndpoint === undefined)\n return undefined;\n return function logout({ state, postLogoutUrl }) {\n return getEndSessionUrl({\n endSessionEndpoint,\n idTokenHint,\n state,\n postLogoutRedirectUri: postLogoutUrl,\n });\n };\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction isSupportedTokenType(token) {\n return typeof token === \"string\" && [\"DPoP\", \"Bearer\"].includes(token);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst USER_SESSION_PREFIX = \"solidClientAuthenticationUser\";\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction isValidUrl(url) {\n try {\n // Here, the URL constructor is just called to parse the given string and\n // verify if it is a well-formed IRI.\n // eslint-disable-next-line no-new\n new URL(url);\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction determineSigningAlg(supported, preferred) {\n var _a;\n return ((_a = preferred.find((signingAlg) => {\n return supported.includes(signingAlg);\n })) !== null && _a !== void 0 ? _a : null);\n}\nfunction determineClientType(options, issuerConfig) {\n if (options.clientId !== undefined && !isValidUrl(options.clientId)) {\n return \"static\";\n }\n if (issuerConfig.scopesSupported.includes(\"webid\") &&\n options.clientId !== undefined &&\n isValidUrl(options.clientId)) {\n return \"solid-oidc\";\n }\n // If no client_id is provided, the client must go through Dynamic Client Registration.\n // If a client_id is provided and it looks like a URI, yet the Identity Provider\n // does *not* support Solid-OIDC, then we also perform DCR (and discard the\n // provided client_id).\n return \"dynamic\";\n}\nasync function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {\n const clientType = determineClientType(options, issuerConfig);\n if (clientType === \"dynamic\") {\n return clientRegistrar.getClient({\n sessionId: options.sessionId,\n clientName: options.clientName,\n redirectUrl: options.redirectUrl,\n }, issuerConfig);\n }\n // If a client_id was provided, and the Identity Provider is Solid-OIDC compliant,\n // or it is not compliant but the client_id isn't an IRI (we assume it has already\n // been registered with the IdP), then the client registration information needs\n // to be stored so that it can be retrieved later after redirect.\n await storageUtility.setForUser(options.sessionId, {\n // If the client is either static or solid-oidc compliant, its client ID cannot be undefined.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n clientId: options.clientId,\n });\n if (options.clientSecret) {\n await storageUtility.setForUser(options.sessionId, {\n clientSecret: options.clientSecret,\n });\n }\n if (options.clientName) {\n await storageUtility.setForUser(options.sessionId, {\n clientName: options.clientName,\n });\n }\n return {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n clientName: options.clientName,\n clientType,\n };\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n// By only referring to `window` at runtime, apps that do server-side rendering\n// won't run into errors when rendering code that instantiates a\n// ClientAuthentication:\nconst globalFetch = (request, init) => fetch.call(globalThis, request, init);\n/**\n * @hidden\n */\nclass ClientAuthentication {\n constructor(loginHandler, redirectHandler, logoutHandler, sessionInfoManager, issuerConfigFetcher) {\n this.loginHandler = loginHandler;\n this.redirectHandler = redirectHandler;\n this.logoutHandler = logoutHandler;\n this.sessionInfoManager = sessionInfoManager;\n this.issuerConfigFetcher = issuerConfigFetcher;\n // By default, our fetch() resolves to the environment fetch() function.\n this.fetch = globalFetch;\n this.logout = async (sessionId, options) => {\n // When doing IDP logout this will redirect away from the current page, so we should not expect\n // code after this condition to be run if it is true.\n // We also need to make sure that any other cleanup that we want to do for\n // our session takes place before this condition is run\n await this.logoutHandler.handle(sessionId, (options === null || options === void 0 ? void 0 : options.logoutType) === \"idp\"\n ? {\n ...options,\n toLogoutUrl: this.boundLogout,\n }\n : options);\n // Restore our fetch() function back to the environment fetch(), effectively\n // leaving us with un-authenticated fetches from now on.\n this.fetch = globalFetch;\n // Delete the bound logout function, so that it can't be called after this.\n delete this.boundLogout;\n };\n this.getSessionInfo = async (sessionId) => {\n // TODO complete\n return this.sessionInfoManager.get(sessionId);\n };\n this.getAllSessionInfo = async () => {\n return this.sessionInfoManager.getAll();\n };\n this.loginHandler = loginHandler;\n this.redirectHandler = redirectHandler;\n this.logoutHandler = logoutHandler;\n this.sessionInfoManager = sessionInfoManager;\n this.issuerConfigFetcher = issuerConfigFetcher;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n/**\n * A helper class that will validate items taken from local storage\n */\nasync function getSessionIdFromOauthState(storageUtility, oauthState) {\n return storageUtility.getForUser(oauthState, \"sessionId\");\n}\n/**\n * Based on the provided state, this looks up contextual information stored\n * before redirecting the user to the OIDC issuer.\n * @param sessionId The state (~ correlation ID) of the OIDC request\n * @param storageUtility\n * @param configFetcher\n * @returns Information stored about the client issuing the request\n */\nasync function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {\n try {\n const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([\n storageUtility.getForUser(sessionId, \"issuer\", {\n errorIfNull: true,\n }),\n storageUtility.getForUser(sessionId, \"codeVerifier\"),\n storageUtility.getForUser(sessionId, \"redirectUrl\"),\n storageUtility.getForUser(sessionId, \"dpop\", { errorIfNull: true }),\n ]);\n // Clear the code verifier, which is one-time use.\n await storageUtility.deleteForUser(sessionId, \"codeVerifier\");\n // Unlike openid-client, this looks up the configuration from storage\n const issuerConfig = await configFetcher.fetchConfig(issuerIri);\n return {\n codeVerifier,\n redirectUrl: storedRedirectIri,\n issuerConfig,\n dpop: dpop === \"true\",\n };\n }\n catch (e) {\n throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);\n }\n}\n/**\n * Stores information about the session in the provided storage. Note that not\n * all storage are equally secure, and it is strongly advised not to store either\n * the refresh token or the DPoP key in the browser's local storage.\n *\n * @param storageUtility\n * @param sessionId\n * @param webId\n * @param isLoggedIn\n * @param refreshToken\n * @param secure\n * @param dpopKey\n */\nasync function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {\n // TODO: Investigate why this does not work with a Promise.all\n if (refreshToken !== undefined) {\n await storageUtility.setForUser(sessionId, { refreshToken }, { secure });\n }\n if (webId !== undefined) {\n await storageUtility.setForUser(sessionId, { webId }, { secure });\n }\n if (isLoggedIn !== undefined) {\n await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });\n }\n if (dpopKey !== undefined) {\n await storageUtility.setForUser(sessionId, {\n publicKey: JSON.stringify(dpopKey.publicKey),\n privateKey: JSON.stringify(await exportJWK(dpopKey.privateKey)),\n }, { secure });\n }\n}\n// TOTEST: this does not handle all possible bad inputs for example what if it's not proper JSON\n/**\n * @hidden\n */\nclass StorageUtility {\n constructor(secureStorage, insecureStorage) {\n this.secureStorage = secureStorage;\n this.insecureStorage = insecureStorage;\n this.secureStorage = secureStorage;\n this.insecureStorage = insecureStorage;\n }\n getKey(userId) {\n return `solidClientAuthenticationUser:${userId}`;\n }\n async getUserData(userId, secure) {\n const stored = await (secure\n ? this.secureStorage\n : this.insecureStorage).get(this.getKey(userId));\n if (stored === undefined) {\n return {};\n }\n try {\n return JSON.parse(stored);\n }\n catch (err) {\n throw new Error(`Data for user [${userId}] in [${secure ? \"secure\" : \"unsecure\"}] storage is corrupted - expected valid JSON, but got: ${stored}`);\n }\n }\n async setUserData(userId, data, secure) {\n await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));\n }\n async get(key, options) {\n const value = await ((options === null || options === void 0 ? void 0 : options.secure)\n ? this.secureStorage\n : this.insecureStorage).get(key);\n if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {\n throw new Error(`[${key}] is not stored`);\n }\n return value;\n }\n async set(key, value, options) {\n return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);\n }\n async delete(key, options) {\n return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);\n }\n async getForUser(userId, key, options) {\n const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);\n let value;\n if (!userData || !userData[key]) {\n value = undefined;\n }\n value = userData[key];\n if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {\n throw new Error(`Field [${key}] for user [${userId}] is not stored`);\n }\n return value || undefined;\n }\n async setForUser(userId, values, options) {\n let userData;\n try {\n userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);\n }\n catch (_a) {\n // if reading the user data throws, the data is corrupted, and we want to write over it\n userData = {};\n }\n await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);\n }\n async deleteForUser(userId, key, options) {\n const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);\n delete userData[key];\n await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);\n }\n async deleteAllUserData(userId, options) {\n await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n */\nclass InMemoryStorage {\n constructor() {\n this.map = {};\n }\n async get(key) {\n return this.map[key] || undefined;\n }\n async set(key, value) {\n this.map[key] = value;\n }\n async delete(key) {\n delete this.map[key];\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n/**\n * Error to be triggered when a poor configuration is received\n */\n// NOTE: There's a bug with istanbul and typescript that prevents full branch coverages\n// https://github.com/gotwarlost/istanbul/issues/690\n// The workaround is to put istanbul ignore on the constructor\n/**\n * @hidden\n */\nclass ConfigurationError extends Error {\n /* istanbul ignore next */\n constructor(message) {\n super(message);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n/**\n * Error to be triggered if a method is not implemented\n * @hidden\n */\nclass NotImplementedError extends Error {\n /* istanbul ignore next */\n constructor(methodName) {\n super(`[${methodName}] is not implemented`);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n/**\n * Error to be triggered when receiving a response missing mandatory elements\n */\n// NOTE: There's a bug with istanbul and typescript that prevents full branch coverages\n// https://github.com/gotwarlost/istanbul/issues/690\n// The workaround is to put istanbul ignore on the constructor\n/**\n * @hidden\n */\nclass InvalidResponseError extends Error {\n /* istanbul ignore next */\n constructor(missingFields) {\n super(`Invalid response from OIDC provider: missing fields ${missingFields}`);\n this.missingFields = missingFields;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n/**\n * Error to be triggered when receiving a response missing mandatory elements\n */\n// NOTE: There's a bug with istanbul and typescript that prevents full branch coverages\n// https://github.com/gotwarlost/istanbul/issues/690\n// The workaround is to put istanbul ignore on the constructor\n/**\n * @hidden\n */\nclass OidcProviderError extends Error {\n /* istanbul ignore next */\n constructor(message, error, errorDescription) {\n super(message);\n this.error = error;\n this.errorDescription = errorDescription;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Normalizes a URL in order to generate the DPoP token based on a consistent scheme.\n *\n * @param audience The URL to normalize.\n * @returns The normalized URL as a string.\n * @hidden\n */\nfunction normalizeHTU(audience) {\n const audienceUrl = new URL(audience);\n return new URL(audienceUrl.pathname, audienceUrl.origin).toString();\n}\n/**\n * Creates a DPoP header according to https://tools.ietf.org/html/draft-fett-oauth-dpop-04,\n * based on the target URL and method, using the provided key.\n *\n * @param audience Target URL.\n * @param method HTTP method allowed.\n * @param key Key used to sign the token.\n * @returns A JWT that can be used as a DPoP Authorization header.\n */\nasync function createDpopHeader(audience, method, dpopKey) {\n return new SignJWT({\n htu: normalizeHTU(audience),\n htm: method.toUpperCase(),\n jti: v4(),\n })\n .setProtectedHeader({\n alg: PREFERRED_SIGNING_ALG[0],\n jwk: dpopKey.publicKey,\n typ: \"dpop+jwt\",\n })\n .setIssuedAt()\n .sign(dpopKey.privateKey, {});\n}\nasync function generateDpopKeyPair() {\n const { privateKey, publicKey } = await generateKeyPair(PREFERRED_SIGNING_ALG[0]);\n const dpopKeyPair = {\n privateKey,\n publicKey: await exportJWK(publicKey),\n };\n // The alg property isn't set by exportJWK, so set it manually.\n [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;\n return dpopKeyPair;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * If expires_in isn't specified for the access token, we assume its lifetime is\n * 10 minutes.\n */\nconst DEFAULT_EXPIRATION_TIME_SECONDS = 600;\nfunction isExpectedAuthError(statusCode) {\n // As per https://tools.ietf.org/html/rfc7235#section-3.1 and https://tools.ietf.org/html/rfc7235#section-3.1,\n // a response failing because the provided credentials aren't accepted by the\n // server can get a 401 or a 403 response.\n return [401, 403].includes(statusCode);\n}\nasync function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {\n var _a;\n const headers = new Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);\n // Any pre-existing Authorization header should be overriden.\n headers.set(\"Authorization\", `DPoP ${authToken}`);\n headers.set(\"DPoP\", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : \"get\", dpopKey));\n return {\n ...defaultOptions,\n headers,\n };\n}\nasync function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {\n if (dpopKey !== undefined) {\n return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);\n }\n const headers = new Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);\n // Any pre-existing Authorization header should be overriden.\n headers.set(\"Authorization\", `Bearer ${authToken}`);\n return {\n ...defaultOptions,\n headers,\n };\n}\nasync function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {\n return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));\n}\nasync function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {\n var _a;\n const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);\n eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);\n if (typeof tokenSet.refreshToken === \"string\") {\n eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);\n }\n return {\n accessToken: tokenSet.accessToken,\n refreshToken: tokenSet.refreshToken,\n expiresIn: tokenSet.expiresIn,\n };\n}\n/**\n *\n * @param expiresIn Delay until the access token expires.\n * @returns a delay until the access token should be refreshed.\n */\nconst computeRefreshDelay = (expiresIn) => {\n if (expiresIn !== undefined) {\n return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0\n ? // We want to refresh the token 5 seconds before they actually expire.\n expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS\n : expiresIn;\n }\n return DEFAULT_EXPIRATION_TIME_SECONDS;\n};\n/**\n * @param unauthFetch a regular fetch function, compliant with the WHATWG spec.\n * @param authToken an access token, either a Bearer token or a DPoP one.\n * @param options The option object may contain two objects: the DPoP key token\n * is bound to if applicable, and options to customise token renewal behaviour.\n *\n * @returns A fetch function that adds an appropriate Authorization header with\n * the provided token, and adds a DPoP header if applicable.\n */\nasync function buildAuthenticatedFetch(unauthFetch, accessToken, options) {\n var _a;\n let currentAccessToken = accessToken;\n let latestTimeout;\n const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;\n // Setup the refresh timeout outside of the authenticated fetch, so that\n // an idle app will not get logged out if it doesn't issue a fetch before\n // the first expiration date.\n if (currentRefreshOptions !== undefined) {\n const proactivelyRefreshToken = async () => {\n var _a, _b, _c, _d;\n try {\n const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, \n // If currentRefreshOptions is defined, options is necessarily defined too.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n options.dpopKey, \n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n options.eventEmitter);\n // Update the tokens in the closure if appropriate.\n currentAccessToken = refreshedAccessToken;\n if (refreshToken !== undefined) {\n currentRefreshOptions.refreshToken = refreshToken;\n }\n // Each time the access token is refreshed, we must plan fo the next\n // refresh iteration.\n clearTimeout(latestTimeout);\n latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);\n // If currentRefreshOptions is defined, options is necessarily defined too.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);\n }\n catch (e) {\n // It is possible that an underlying library throws an error on refresh flow failure.\n // If we used a log framework, the error could be logged at the `debug` level,\n // but otherwise the failure of the refresh flow should not blow up in the user's\n // face, so we just swallow the error.\n if (e instanceof OidcProviderError) {\n // The OIDC provider refused to refresh the access token and returned an error instead.\n /* istanbul ignore next 100% coverage would require testing that nothing\n happens here if the emitter is undefined, which is more cumbersome\n than what it's worth. */\n (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);\n /* istanbul ignore next 100% coverage would require testing that nothing\n happens here if the emitter is undefined, which is more cumbersome\n than what it's worth. */\n (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);\n }\n if (e instanceof InvalidResponseError &&\n e.missingFields.includes(\"access_token\")) {\n // In this case, the OIDC provider returned a non-standard response, but\n // did not specify that it was an error. We cannot refresh nonetheless.\n /* istanbul ignore next 100% coverage would require testing that nothing\n happens here if the emitter is undefined, which is more cumbersome\n than what it's worth. */\n (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);\n }\n }\n };\n latestTimeout = setTimeout(proactivelyRefreshToken, \n // If currentRefreshOptions is defined, options is necessarily defined too.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n computeRefreshDelay(options.expiresIn) * 1000);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);\n }\n else if (options !== undefined && options.eventEmitter !== undefined) {\n // If no refresh options are provided, the session expires when the access token does.\n const expirationTimeout = setTimeout(() => {\n // The event emitter is always defined in our code, and it would be tedious\n // to test for conditions when it is not.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);\n }, computeRefreshDelay(options.expiresIn) * 1000);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);\n }\n return async (url, requestInit) => {\n let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);\n const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);\n if (response.ok || failedButNotExpectedAuthError) {\n // If there hasn't been a redirection, or if there has been a non-auth related\n // issue, it should be handled at the application level\n return response;\n }\n const hasBeenRedirected = response.url !== url;\n if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {\n // If the request failed for auth reasons, and has been redirected, we should\n // replay it generating a DPoP header for the rediration target IRI. This\n // doesn't apply to Bearer tokens, as the Bearer tokens aren't specific\n // to a given resource and method, while the DPoP header (associated to a\n // DPoP token) is.\n response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, \n // Replace the original target IRI (`url`) by the redirection target\n response.url, requestInit, options.dpopKey);\n }\n return response;\n };\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst StorageUtilityGetResponse = \"getResponse\";\nconst StorageUtilityMock = {\n /* eslint-disable @typescript-eslint/no-unused-vars */\n get: async (key, options) => StorageUtilityGetResponse,\n set: async (key, value) => {\n /* do nothing */\n },\n delete: async (key) => {\n /* do nothing */\n },\n getForUser: async (userId, key, options) => StorageUtilityGetResponse,\n setForUser: async (userId, values, options) => {\n /* do nothing */\n },\n deleteForUser: async (userId, key, options) => {\n /* do nothing */\n },\n deleteAllUserData: async (userId, options) => {\n /* do nothing */\n },\n};\nconst mockStorage = (stored) => {\n const store = stored;\n return {\n get: async (key) => {\n if (store[key] === undefined) {\n return undefined;\n }\n if (typeof store[key] === \"string\") {\n return store[key];\n }\n return JSON.stringify(store[key]);\n },\n set: async (key, value) => {\n store[key] = value;\n },\n delete: async (key) => {\n delete store[key];\n },\n };\n};\nconst mockStorageUtility = (stored, isSecure = false) => {\n if (isSecure) {\n return new StorageUtility(mockStorage(stored), mockStorage({}));\n }\n return new StorageUtility(mockStorage({}), mockStorage(stored));\n};\n\nexport { AggregateHandler, AuthorizationCodeWithPkceOidcHandlerBase, ClientAuthentication, ConfigurationError, DEFAULT_SCOPES, EVENTS, GeneralLogoutHandler, IRpLogoutHandler, IWaterfallLogoutHandler, InMemoryStorage, InvalidResponseError, NotImplementedError, OidcProviderError, PREFERRED_SIGNING_ALG, REFRESH_BEFORE_EXPIRATION_SECONDS, SOLID_CLIENT_AUTHN_KEY_PREFIX, SessionInfoManagerBase, StorageUtility, StorageUtilityGetResponse, StorageUtilityMock, USER_SESSION_PREFIX, buildAuthenticatedFetch, buildProxyHandler, clear, createDpopHeader, determineSigningAlg, fetchJwks, generateDpopKeyPair, getEndSessionUrl, getSessionIdFromOauthState, getUnauthenticatedSession, getWebidFromTokenPayload, handleRegistration, isSupportedTokenType, isValidRedirectUrl, loadOidcContextFromStorage, maybeBuildRpInitiatedLogout, mockStorage, mockStorageUtility, removeOpenIdParams, saveSessionInfoToStorage };\n//# sourceMappingURL=index.mjs.map\n","import { OidcClient, WebStorageStateStore } from '@inrupt/oidc-client';\nexport { CordovaIFrameNavigator, CordovaPopupNavigator, InMemoryWebStorage, Log, OidcClient, SessionMonitor, User, UserManager, Version, WebStorageStateStore } from '@inrupt/oidc-client';\nimport { determineSigningAlg, PREFERRED_SIGNING_ALG, getWebidFromTokenPayload, OidcProviderError, InvalidResponseError, generateDpopKeyPair, createDpopHeader, DEFAULT_SCOPES, removeOpenIdParams } from '@inrupt/solid-client-authn-core';\nimport { fetch as fetch$1 } from '@inrupt/universal-fetch';\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction processErrorResponse(\n// The type is any here because the object is parsed from a JSON response\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nresponseBody, options) {\n var _a, _b, _c, _d;\n // The following errors are defined by the spec, and allow providing some context.\n // See https://tools.ietf.org/html/rfc7591#section-3.2.2 for more information\n if (responseBody.error === \"invalid_redirect_uri\") {\n throw new Error(`Dynamic client registration failed: the provided redirect uri [${(_a = options.redirectUrl) === null || _a === void 0 ? void 0 : _a.toString()}] is invalid - ${(_b = responseBody.error_description) !== null && _b !== void 0 ? _b : \"\"}`);\n }\n if (responseBody.error === \"invalid_client_metadata\") {\n throw new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(options)} is invalid - ${(_c = responseBody.error_description) !== null && _c !== void 0 ? _c : \"\"}`);\n }\n // We currently don't support software statements, so no related error should happen.\n // If an error outside of the spec happens, no additional context can be provided\n throw new Error(`Dynamic client registration failed: ${responseBody.error} - ${(_d = responseBody.error_description) !== null && _d !== void 0 ? _d : \"\"}`);\n}\nfunction validateRegistrationResponse(\n// The type is any here because the object is parsed from a JSON response\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nresponseBody, options) {\n if (responseBody.client_id === undefined) {\n throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(responseBody)}`);\n }\n if (options.redirectUrl &&\n (responseBody.redirect_uris === undefined ||\n responseBody.redirect_uris[0] !== options.redirectUrl.toString())) {\n throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(responseBody.redirect_uris)} don't match the provided ${JSON.stringify([\n options.redirectUrl.toString(),\n ])}`);\n }\n}\nasync function registerClient(options, issuerConfig) {\n var _a;\n if (!issuerConfig.registrationEndpoint) {\n throw new Error(\"Dynamic Registration could not be completed because the issuer has no registration endpoint.\");\n }\n if (!Array.isArray(issuerConfig.idTokenSigningAlgValuesSupported)) {\n throw new Error(\"The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.\");\n }\n const signingAlg = determineSigningAlg(issuerConfig.idTokenSigningAlgValuesSupported, PREFERRED_SIGNING_ALG);\n const config = {\n /* eslint-disable camelcase */\n client_name: options.clientName,\n application_type: \"web\",\n redirect_uris: [(_a = options.redirectUrl) === null || _a === void 0 ? void 0 : _a.toString()],\n subject_type: \"public\",\n token_endpoint_auth_method: \"client_secret_basic\",\n id_token_signed_response_alg: signingAlg,\n grant_types: [\"authorization_code\", \"refresh_token\"],\n /* eslint-enable camelcase */\n };\n const headers = {\n \"Content-Type\": \"application/json\",\n };\n const registerResponse = await fetch(issuerConfig.registrationEndpoint.toString(), {\n method: \"POST\",\n headers,\n body: JSON.stringify(config),\n });\n if (registerResponse.ok) {\n const responseBody = await registerResponse.json();\n validateRegistrationResponse(responseBody, options);\n return {\n clientId: responseBody.client_id,\n clientSecret: responseBody.client_secret,\n idTokenSignedResponseAlg: responseBody.id_token_signed_response_alg,\n clientType: \"dynamic\",\n };\n }\n if (registerResponse.status === 400) {\n processErrorResponse(await registerResponse.json(), options);\n }\n throw new Error(`Dynamic client registration failed: the server returned ${registerResponse.status} ${registerResponse.statusText} - ${await registerResponse.text()}`);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// Identifiers in camelcase are mandated by the OAuth spec.\n/* eslint-disable camelcase */\nfunction hasError(value) {\n return value.error !== undefined && typeof value.error === \"string\";\n}\nfunction hasErrorDescription(value) {\n return (value.error_description !== undefined &&\n typeof value.error_description === \"string\");\n}\nfunction hasErrorUri(value) {\n return value.error_uri !== undefined && typeof value.error_uri === \"string\";\n}\nfunction hasAccessToken(value) {\n return (value.access_token !== undefined && typeof value.access_token === \"string\");\n}\nfunction hasIdToken(value) {\n return value.id_token !== undefined && typeof value.id_token === \"string\";\n}\nfunction hasRefreshToken(value) {\n return (value.refresh_token !== undefined && typeof value.refresh_token === \"string\");\n}\nfunction hasTokenType(value) {\n return value.token_type !== undefined && typeof value.token_type === \"string\";\n}\nfunction hasExpiresIn(value) {\n return value.expires_in === undefined || typeof value.expires_in === \"number\";\n}\nfunction validatePreconditions(issuer, data) {\n if (data.grantType &&\n (!issuer.grantTypesSupported ||\n !issuer.grantTypesSupported.includes(data.grantType))) {\n throw new Error(`The issuer [${issuer.issuer}] does not support the [${data.grantType}] grant`);\n }\n if (!issuer.tokenEndpoint) {\n throw new Error(`This issuer [${issuer.issuer}] does not have a token endpoint`);\n }\n}\nfunction validateTokenEndpointResponse(tokenResponse, dpop) {\n if (hasError(tokenResponse)) {\n throw new OidcProviderError(`Token endpoint returned error [${tokenResponse.error}]${hasErrorDescription(tokenResponse)\n ? `: ${tokenResponse.error_description}`\n : \"\"}${hasErrorUri(tokenResponse) ? ` (see ${tokenResponse.error_uri})` : \"\"}`, tokenResponse.error, hasErrorDescription(tokenResponse)\n ? tokenResponse.error_description\n : undefined);\n }\n if (!hasAccessToken(tokenResponse)) {\n throw new InvalidResponseError([\"access_token\"]);\n }\n if (!hasIdToken(tokenResponse)) {\n throw new InvalidResponseError([\"id_token\"]);\n }\n if (!hasTokenType(tokenResponse)) {\n throw new InvalidResponseError([\"token_type\"]);\n }\n if (!hasExpiresIn(tokenResponse)) {\n throw new InvalidResponseError([\"expires_in\"]);\n }\n // TODO: Due to a bug in both the ESS ID broker AND NSS (what were the odds), a DPoP token is returned\n // with a token_type 'Bearer'. To work around this, this test is currently disabled.\n // https://github.com/solid/oidc-op/issues/26\n // Fixed, but unreleased for the ESS (current version: inrupt-oidc-server-0.5.2)\n // if (dpop && tokenResponse.token_type.toLowerCase() !== \"dpop\") {\n // throw new Error(\n // `Invalid token endpoint response: requested a [DPoP] token, but got a 'token_type' value of [${tokenResponse.token_type}].`\n // );\n // }\n if (!dpop && tokenResponse.token_type.toLowerCase() !== \"bearer\") {\n throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${tokenResponse.token_type}].`);\n }\n return tokenResponse;\n}\nasync function getTokens(issuer, client, data, dpop) {\n validatePreconditions(issuer, data);\n const headers = {\n \"content-type\": \"application/x-www-form-urlencoded\",\n };\n let dpopKey;\n if (dpop) {\n dpopKey = await generateDpopKeyPair();\n headers.DPoP = await createDpopHeader(issuer.tokenEndpoint, \"POST\", dpopKey);\n }\n // TODO: Find out where this is specified.\n if (client.clientSecret) {\n headers.Authorization = `Basic ${btoa(`${client.clientId}:${client.clientSecret}`)}`;\n }\n const requestBody = {\n /* eslint-disable camelcase */\n grant_type: data.grantType,\n redirect_uri: data.redirectUrl,\n code: data.code,\n code_verifier: data.codeVerifier,\n client_id: client.clientId,\n /* eslint-enable camelcase */\n };\n const tokenRequestInit = {\n method: \"POST\",\n headers,\n body: new URLSearchParams(requestBody).toString(),\n };\n const rawTokenResponse = await fetch$1(issuer.tokenEndpoint, tokenRequestInit);\n const jsonTokenResponse = (await rawTokenResponse.json());\n const tokenResponse = validateTokenEndpointResponse(jsonTokenResponse, dpop);\n const webId = await getWebidFromTokenPayload(tokenResponse.id_token, issuer.jwksUri, issuer.issuer, client.clientId);\n return {\n accessToken: tokenResponse.access_token,\n idToken: tokenResponse.id_token,\n refreshToken: hasRefreshToken(tokenResponse)\n ? tokenResponse.refresh_token\n : undefined,\n webId,\n dpopKey,\n expiresIn: tokenResponse.expires_in,\n };\n}\n/**\n * This function exchanges an authorization code for a bearer token.\n * Note that it is based on oidc-client-js, and assumes that the same client has\n * been used to issue the initial redirect.\n * @param redirectUrl The URL to which the user has been redirected\n */\nasync function getBearerToken(redirectUrl) {\n let signinResponse;\n try {\n const client = new OidcClient({\n // TODO: We should look at the various interfaces being used for storage,\n // i.e. between oidc-client-js (WebStorageStoreState), localStorage\n // (which has an interface Storage), and our own proprietary interface\n // IStorage - i.e. we should really just be using the browser Web Storage\n // API, e.g. \"stateStore: window.localStorage,\".\n // We are instantiating a new instance here, so the only value we need to\n // explicitly provide is the response mode (default otherwise will look\n // for a hash '#' fragment!).\n // eslint-disable-next-line camelcase\n response_mode: \"query\",\n // The userinfo endpoint on NSS fails, so disable this for now\n // Note that in Solid, information should be retrieved from the\n // profile referenced by the WebId.\n // TODO: Note that this is heavy-handed, and that this userinfo check\n // verifies that the `sub` claim in the id token you get along with the\n // access token matches the sub claim associated with the access token at\n // the userinfo endpoint.\n // That is a useful check, and in the future it should be only disabled\n // against NSS, and not in general.\n // Issue tracker: https://github.com/solid/node-solid-server/issues/1490\n loadUserInfo: false,\n });\n signinResponse = await client.processSigninResponse(redirectUrl);\n if (client.settings.metadata === undefined) {\n throw new Error(\"Cannot retrieve issuer metadata from client information in storage.\");\n }\n if (client.settings.metadata.jwks_uri === undefined) {\n throw new Error(\"Missing some issuer metadata from client information in storage: 'jwks_uri' is undefined\");\n }\n if (client.settings.metadata.issuer === undefined) {\n throw new Error(\"Missing some issuer metadata from client information in storage: 'issuer' is undefined\");\n }\n if (client.settings.client_id === undefined) {\n throw new Error(\"Missing some client information in storage: 'client_id' is undefined\");\n }\n const webId = await getWebidFromTokenPayload(signinResponse.id_token, client.settings.metadata.jwks_uri, client.settings.metadata.issuer, client.settings.client_id);\n return {\n accessToken: signinResponse.access_token,\n idToken: signinResponse.id_token,\n webId,\n // Although not a field in the TypeScript response interface, the refresh\n // token (which can optionally come back with the access token (if, as per\n // the OAuth2 spec, we requested one using the scope of 'offline_access')\n // will be included in the signin response object.\n // eslint-disable-next-line camelcase\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n refreshToken: signinResponse.refresh_token,\n };\n }\n catch (err) {\n throw new Error(`Problem handling Auth Code Grant (Flow) redirect - URL [${redirectUrl}]: ${err}`);\n }\n}\nasync function getDpopToken(issuer, client, data) {\n return getTokens(issuer, client, data, true);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst isValidUrl = (url) => {\n try {\n // Here, the URL constructor is just called to parse the given string and\n // verify if it is a well-formed IRI.\n // eslint-disable-next-line no-new\n new URL(url);\n return true;\n }\n catch (_a) {\n return false;\n }\n};\n// Identifiers in snake_case are mandated by the OAuth spec.\n/* eslint-disable camelcase */\nasync function refresh(refreshToken, issuer, client, dpopKey) {\n if (client.clientId === undefined) {\n throw new Error(\"No client ID available when trying to refresh the access token.\");\n }\n const requestBody = {\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n scope: DEFAULT_SCOPES,\n };\n let dpopHeader = {};\n if (dpopKey !== undefined) {\n dpopHeader = {\n DPoP: await createDpopHeader(issuer.tokenEndpoint, \"POST\", dpopKey),\n };\n }\n let authHeader = {};\n if (client.clientSecret !== undefined) {\n authHeader = {\n // We assume that client_secret_basic is the client authentication method.\n // TODO: Get the authentication method from the IClient configuration object.\n Authorization: `Basic ${btoa(`${client.clientId}:${client.clientSecret}`)}`,\n };\n }\n else if (isValidUrl(client.clientId)) {\n // If the client ID is an URL, and there is no client secret, the client\n // has a Solid-OIDC Client Identifier, and it should be present in the\n // request body.\n requestBody.client_id = client.clientId;\n }\n const rawResponse = await fetch$1(issuer.tokenEndpoint, {\n method: \"POST\",\n body: new URLSearchParams(requestBody).toString(),\n headers: {\n ...dpopHeader,\n ...authHeader,\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n });\n let response;\n try {\n response = await rawResponse.json();\n }\n catch (e) {\n // The response is left out of the error on purpose not to leak any sensitive information.\n throw new Error(`The token endpoint of issuer ${issuer.issuer} returned a malformed response.`);\n }\n const validatedResponse = validateTokenEndpointResponse(response, dpopKey !== undefined);\n const webId = await getWebidFromTokenPayload(validatedResponse.id_token, issuer.jwksUri, issuer.issuer, client.clientId);\n return {\n accessToken: validatedResponse.access_token,\n idToken: validatedResponse.id_token,\n refreshToken: typeof validatedResponse.refresh_token === \"string\"\n ? validatedResponse.refresh_token\n : undefined,\n webId,\n dpopKey,\n expiresIn: validatedResponse.expires_in,\n };\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Removes OIDC-specific query parameters from a given URL (state, code...), and\n * sanitizes the URL (e.g. removes the hash fragment).\n * @param redirectUrl The URL to clean up.\n * @returns A copy of the URL, without OIDC-specific query params.\n */\nfunction normalizeCallbackUrl(redirectUrl) {\n const cleanedUrl = removeOpenIdParams(redirectUrl);\n // As per https://tools.ietf.org/html/rfc6749#section-3.1.2, the redirect URL\n // must not include a hash fragment.\n cleanedUrl.hash = \"\";\n // Do not normalize the trailing slash, and respect the original redirect URL.\n if (\n // The trailing slash is present in the original redirect URL\n redirectUrl.includes(`${cleanedUrl.origin}/`)) {\n return cleanedUrl.href;\n }\n // Calling cleanedUrl.href appends a trailing slash to the origin, which may\n // create a redirect URL mismatch if it wasn't originally present.\n return `${cleanedUrl.origin}${cleanedUrl.href.substring(\n // Adds 1 to the origin length to remove the trailing slash\n cleanedUrl.origin.length + 1)}`;\n}\n/**\n * Clears any OIDC-related data lingering in the local storage.\n */\nasync function clearOidcPersistentStorage() {\n const client = new OidcClient({\n // TODO: We should look at the various interfaces being used for storage,\n // i.e. between oidc-client-js (WebStorageStoreState), localStorage\n // (which has an interface Storage), and our own proprietary interface\n // IStorage - i.e. we should really just be using the browser Web Storage\n // API, e.g. \"stateStore: window.localStorage,\".\n // We are instantiating a new instance here, so the only value we need to\n // explicitly provide is the response mode (default otherwise will look\n // for a hash '#' fragment!).\n // eslint-disable-next-line camelcase\n response_mode: \"query\",\n });\n await client.clearStaleState(new WebStorageStateStore({}));\n const myStorage = window.localStorage;\n const itemsToRemove = [];\n for (let i = 0; i <= myStorage.length; i += 1) {\n const key = myStorage.key(i);\n if (key &&\n (key.match(/^oidc\\..+$/) ||\n key.match(/^solidClientAuthenticationUser:.+$/))) {\n itemsToRemove.push(key);\n }\n }\n itemsToRemove.forEach((key) => myStorage.removeItem(key));\n}\n\nexport { clearOidcPersistentStorage, getBearerToken, getDpopToken, normalizeCallbackUrl, refresh, registerClient };\n","!function t(e,r){if(\"object\"==typeof exports&&\"object\"==typeof module)module.exports=r();else if(\"function\"==typeof define&&define.amd)define([],r);else{var n=r();for(var i in n)(\"object\"==typeof exports?exports:e)[i]=n[i]}}(this,(function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(t,\"__esModule\",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&\"object\"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,\"default\",{enumerable:!0,value:t}),2&e&&\"string\"!=typeof t)for(var i in t)r.d(n,i,function(e){return t[e]}.bind(null,i));return n},r.n=function(t){var e=t&&t.__esModule?function e(){return t.default}:function e(){return t};return r.d(e,\"a\",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p=\"\",r(r.s=22)}([function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0});var n=function(){function t(t,e){for(var r=0;r=4){for(var e=arguments.length,r=Array(e),n=0;n=3){for(var e=arguments.length,r=Array(e),n=0;n=2){for(var e=arguments.length,r=Array(e),n=0;n=1){for(var e=arguments.length,r=Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:o.JsonService;if(s(this,t),!e)throw i.Log.error(\"MetadataService: No settings passed to MetadataService\"),new Error(\"settings\");this._settings=e,this._jsonService=new r([\"application/jwk-set+json\"])}return t.prototype.resetSigningKeys=function t(){this._settings=this._settings||{},this._settings.signingKeys=void 0},t.prototype.getMetadata=function t(){var e=this;return this._settings.metadata?(i.Log.debug(\"MetadataService.getMetadata: Returning metadata from settings\"),Promise.resolve(this._settings.metadata)):this.metadataUrl?(i.Log.debug(\"MetadataService.getMetadata: getting metadata from\",this.metadataUrl),this._jsonService.getJson(this.metadataUrl).then((function(t){i.Log.debug(\"MetadataService.getMetadata: json received\");var r=e._settings.metadataSeed||{};return e._settings.metadata=Object.assign({},r,t),e._settings.metadata}))):(i.Log.error(\"MetadataService.getMetadata: No authority or metadataUrl configured on settings\"),Promise.reject(new Error(\"No authority or metadataUrl configured on settings\")))},t.prototype.getIssuer=function t(){return this._getMetadataProperty(\"issuer\")},t.prototype.getAuthorizationEndpoint=function t(){return this._getMetadataProperty(\"authorization_endpoint\")},t.prototype.getUserInfoEndpoint=function t(){return this._getMetadataProperty(\"userinfo_endpoint\")},t.prototype.getTokenEndpoint=function t(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._getMetadataProperty(\"token_endpoint\",e)},t.prototype.getCheckSessionIframe=function t(){return this._getMetadataProperty(\"check_session_iframe\",!0)},t.prototype.getEndSessionEndpoint=function t(){return this._getMetadataProperty(\"end_session_endpoint\",!0)},t.prototype.getRevocationEndpoint=function t(){return this._getMetadataProperty(\"revocation_endpoint\",!0)},t.prototype.getKeysEndpoint=function t(){return this._getMetadataProperty(\"jwks_uri\",!0)},t.prototype._getMetadataProperty=function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return i.Log.debug(\"MetadataService.getMetadataProperty for: \"+e),this.getMetadata().then((function(t){if(i.Log.debug(\"MetadataService.getMetadataProperty: metadata recieved\"),void 0===t[e]){if(!0===r)return void i.Log.warn(\"MetadataService.getMetadataProperty: Metadata does not contain optional property \"+e);throw i.Log.error(\"MetadataService.getMetadataProperty: Metadata does not contain property \"+e),new Error(\"Metadata does not contain property \"+e)}return t[e]}))},t.prototype.getSigningKeys=function t(){var e=this;return this._settings.signingKeys?(i.Log.debug(\"MetadataService.getSigningKeys: Returning signingKeys from settings\"),Promise.resolve(this._settings.signingKeys)):this._getMetadataProperty(\"jwks_uri\").then((function(t){return i.Log.debug(\"MetadataService.getSigningKeys: jwks_uri received\",t),e._jsonService.getJson(t).then((function(t){if(i.Log.debug(\"MetadataService.getSigningKeys: key set received\",t),!t.keys)throw i.Log.error(\"MetadataService.getSigningKeys: Missing keys on keyset\"),new Error(\"Missing keys on keyset\");return e._settings.signingKeys=t.keys,e._settings.signingKeys}))}))},n(t,[{key:\"metadataUrl\",get:function t(){return this._metadataUrl||(this._settings.metadataUrl?this._metadataUrl=this._settings.metadataUrl:(this._metadataUrl=this._settings.authority,this._metadataUrl&&this._metadataUrl.indexOf(a)<0&&(\"/\"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+=\"/\"),this._metadataUrl+=a))),this._metadataUrl}}]),t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.UrlUtility=void 0;var n=r(0),i=r(1);e.UrlUtility=function(){function t(){!function e(t,r){if(!(t instanceof r))throw new TypeError(\"Cannot call a class as a function\")}(this,t)}return t.addQueryParam=function t(e,r,n){return e.indexOf(\"?\")<0&&(e+=\"?\"),\"?\"!==e[e.length-1]&&(e+=\"&\"),e+=encodeURIComponent(r),e+=\"=\",e+=encodeURIComponent(n)},t.parseUrlFragment=function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"#\",o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.Global;\"string\"!=typeof e&&(e=o.location.href);var s=e.lastIndexOf(r);s>=0&&(e=e.substr(s+1)),\"?\"===r&&(s=e.indexOf(\"#\"))>=0&&(e=e.substr(0,s));for(var a,u={},c=/([^&=]+)=([^&]*)/g,h=0;a=c.exec(e);)if(u[decodeURIComponent(a[1])]=decodeURIComponent(a[2].replace(/\\+/g,\" \")),h++>50)return n.Log.error(\"UrlUtility.parseUrlFragment: response exceeded expected number of parameters\",e),{error:\"Response exceeded expected number of parameters\"};for(var l in u)return u;return{}},t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.JoseUtil=void 0;var n=r(26),i=function o(t){return t&&t.__esModule?t:{default:t}}(r(33));e.JoseUtil=(0,i.default)({jws:n.jws,KeyUtil:n.KeyUtil,X509:n.X509,crypto:n.crypto,hextob64u:n.hextob64u,b64tohex:n.b64tohex,AllowedSigningAlgs:n.AllowedSigningAlgs})},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.OidcClientSettings=void 0;var n=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t},i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},r=e.authority,i=e.metadataUrl,o=e.metadata,l=e.signingKeys,p=e.metadataSeed,v=e.client_id,y=e.client_secret,m=e.response_type,_=void 0===m?f:m,S=e.scope,b=void 0===S?g:S,w=e.redirect_uri,F=e.post_logout_redirect_uri,E=e.client_authentication,x=void 0===E?d:E,A=e.prompt,k=e.display,P=e.max_age,C=e.ui_locales,T=e.acr_values,R=e.resource,I=e.response_mode,D=e.filterProtocolClaims,L=void 0===D||D,N=e.loadUserInfo,U=void 0===N||N,B=e.staleStateAge,O=void 0===B?900:B,j=e.clockSkew,M=void 0===j?300:j,H=e.clockService,V=void 0===H?new s.ClockService:H,K=e.userInfoJwtIssuer,q=void 0===K?\"OP\":K,J=e.mergeClaims,W=void 0!==J&&J,z=e.stateStore,Y=void 0===z?new a.WebStorageStateStore:z,G=e.ResponseValidatorCtor,X=void 0===G?u.ResponseValidator:G,$=e.MetadataServiceCtor,Q=void 0===$?c.MetadataService:$,Z=e.extraQueryParams,tt=void 0===Z?{}:Z,et=e.extraTokenParams,rt=void 0===et?{}:et;h(this,t),this._authority=r,this._metadataUrl=i,this._metadata=o,this._metadataSeed=p,this._signingKeys=l,this._client_id=v,this._client_secret=y,this._response_type=_,this._scope=b,this._redirect_uri=w,this._post_logout_redirect_uri=F,this._client_authentication=x,this._prompt=A,this._display=k,this._max_age=P,this._ui_locales=C,this._acr_values=T,this._resource=R,this._response_mode=I,this._filterProtocolClaims=!!L,this._loadUserInfo=!!U,this._staleStateAge=O,this._clockSkew=M,this._clockService=V,this._userInfoJwtIssuer=q,this._mergeClaims=!!W,this._stateStore=Y,this._validator=new X(this),this._metadataService=new Q(this),this._extraQueryParams=\"object\"===(void 0===tt?\"undefined\":n(tt))?tt:{},this._extraTokenParams=\"object\"===(void 0===rt?\"undefined\":n(rt))?rt:{}}return t.prototype.getEpochTime=function t(){return this._clockService.getEpochTime()},i(t,[{key:\"client_id\",get:function t(){return this._client_id},set:function t(e){if(this._client_id)throw o.Log.error(\"OidcClientSettings.set_client_id: client_id has already been assigned.\"),new Error(\"client_id has already been assigned.\");this._client_id=e}},{key:\"client_secret\",get:function t(){return this._client_secret}},{key:\"response_type\",get:function t(){return this._response_type}},{key:\"scope\",get:function t(){return this._scope}},{key:\"redirect_uri\",get:function t(){return this._redirect_uri}},{key:\"post_logout_redirect_uri\",get:function t(){return this._post_logout_redirect_uri}},{key:\"client_authentication\",get:function t(){return this._client_authentication}},{key:\"prompt\",get:function t(){return this._prompt}},{key:\"display\",get:function t(){return this._display}},{key:\"max_age\",get:function t(){return this._max_age}},{key:\"ui_locales\",get:function t(){return this._ui_locales}},{key:\"acr_values\",get:function t(){return this._acr_values}},{key:\"resource\",get:function t(){return this._resource}},{key:\"response_mode\",get:function t(){return this._response_mode}},{key:\"authority\",get:function t(){return this._authority},set:function t(e){if(this._authority)throw o.Log.error(\"OidcClientSettings.set_authority: authority has already been assigned.\"),new Error(\"authority has already been assigned.\");this._authority=e}},{key:\"metadataUrl\",get:function t(){return this._metadataUrl||(this._metadataUrl=this.authority,this._metadataUrl&&this._metadataUrl.indexOf(l)<0&&(\"/\"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+=\"/\"),this._metadataUrl+=l)),this._metadataUrl}},{key:\"metadata\",get:function t(){return this._metadata},set:function t(e){this._metadata=e}},{key:\"metadataSeed\",get:function t(){return this._metadataSeed},set:function t(e){this._metadataSeed=e}},{key:\"signingKeys\",get:function t(){return this._signingKeys},set:function t(e){this._signingKeys=e}},{key:\"filterProtocolClaims\",get:function t(){return this._filterProtocolClaims}},{key:\"loadUserInfo\",get:function t(){return this._loadUserInfo}},{key:\"staleStateAge\",get:function t(){return this._staleStateAge}},{key:\"clockSkew\",get:function t(){return this._clockSkew}},{key:\"userInfoJwtIssuer\",get:function t(){return this._userInfoJwtIssuer}},{key:\"mergeClaims\",get:function t(){return this._mergeClaims}},{key:\"stateStore\",get:function t(){return this._stateStore}},{key:\"validator\",get:function t(){return this._validator}},{key:\"metadataService\",get:function t(){return this._metadataService}},{key:\"extraQueryParams\",get:function t(){return this._extraQueryParams},set:function t(e){\"object\"===(void 0===e?\"undefined\":n(e))?this._extraQueryParams=e:this._extraQueryParams={}}},{key:\"extraTokenParams\",get:function t(){return this._extraTokenParams},set:function t(e){\"object\"===(void 0===e?\"undefined\":n(e))?this._extraTokenParams=e:this._extraTokenParams={}}}]),t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.WebStorageStateStore=void 0;var n=r(0),i=r(1);function o(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}e.WebStorageStateStore=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.prefix,n=void 0===r?\"oidc.\":r,s=e.store,a=void 0===s?i.Global.localStorage:s;o(this,t),this._store=a,this._prefix=n}return t.prototype.set=function t(e,r){return n.Log.debug(\"WebStorageStateStore.set\",e),e=this._prefix+e,this._store.setItem(e,r),Promise.resolve()},t.prototype.get=function t(e){n.Log.debug(\"WebStorageStateStore.get\",e),e=this._prefix+e;var r=this._store.getItem(e);return Promise.resolve(r)},t.prototype.remove=function t(e){n.Log.debug(\"WebStorageStateStore.remove\",e),e=this._prefix+e;var r=this._store.getItem(e);return this._store.removeItem(e),Promise.resolve(r)},t.prototype.getAllKeys=function t(){n.Log.debug(\"WebStorageStateStore.getAllKeys\");for(var e=[],r=0;r0&&void 0!==arguments[0]?arguments[0]:null,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i.Global.XMLHttpRequest,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;o(this,t),e&&Array.isArray(e)?this._contentTypes=e.slice():this._contentTypes=[],this._contentTypes.push(\"application/json\"),n&&this._contentTypes.push(\"application/jwt\"),this._XMLHttpRequest=r,this._jwtHandler=n}return t.prototype.getJson=function t(e,r){var i=this;if(!e)throw n.Log.error(\"JsonService.getJson: No url passed\"),new Error(\"url\");return n.Log.debug(\"JsonService.getJson, url: \",e),new Promise((function(t,o){var s=new i._XMLHttpRequest;s.open(\"GET\",e);var a=i._contentTypes,u=i._jwtHandler;s.onload=function(){if(n.Log.debug(\"JsonService.getJson: HTTP response received, status\",s.status),200===s.status){var r=s.getResponseHeader(\"Content-Type\");if(r){var i=a.find((function(t){if(r.startsWith(t))return!0}));if(\"application/jwt\"==i)return void u(s).then(t,o);if(i)try{return void t(JSON.parse(s.responseText))}catch(t){return n.Log.error(\"JsonService.getJson: Error parsing JSON response\",t.message),void o(t)}}o(Error(\"Invalid response Content-Type: \"+r+\", from URL: \"+e))}else o(Error(s.statusText+\" (\"+s.status+\")\"))},s.onerror=function(){n.Log.error(\"JsonService.getJson: network error\"),o(Error(\"Network Error\"))},r&&(n.Log.debug(\"JsonService.getJson: token passed, setting Authorization header\"),s.setRequestHeader(\"Authorization\",\"Bearer \"+r)),s.send()}))},t.prototype.postForm=function t(e,r,i){var o=this;if(!e)throw n.Log.error(\"JsonService.postForm: No url passed\"),new Error(\"url\");return n.Log.debug(\"JsonService.postForm, url: \",e),new Promise((function(t,s){var a=new o._XMLHttpRequest;a.open(\"POST\",e);var u=o._contentTypes;a.onload=function(){if(n.Log.debug(\"JsonService.postForm: HTTP response received, status\",a.status),200!==a.status){if(400===a.status)if(i=a.getResponseHeader(\"Content-Type\"))if(u.find((function(t){if(i.startsWith(t))return!0})))try{var r=JSON.parse(a.responseText);if(r&&r.error)return n.Log.error(\"JsonService.postForm: Error from server: \",r.error),void s(new Error(r.error))}catch(t){return n.Log.error(\"JsonService.postForm: Error parsing JSON response\",t.message),void s(t)}s(Error(a.statusText+\" (\"+a.status+\")\"))}else{var i;if((i=a.getResponseHeader(\"Content-Type\"))&&u.find((function(t){if(i.startsWith(t))return!0})))try{return void t(JSON.parse(a.responseText))}catch(t){return n.Log.error(\"JsonService.postForm: Error parsing JSON response\",t.message),void s(t)}s(Error(\"Invalid response Content-Type: \"+i+\", from URL: \"+e))}},a.onerror=function(){n.Log.error(\"JsonService.postForm: network error\"),s(Error(\"Network Error\"))};var c=\"\";for(var h in r){var l=r[h];l&&(c.length>0&&(c+=\"&\"),c+=encodeURIComponent(h),c+=\"=\",c+=encodeURIComponent(l))}a.setRequestHeader(\"Content-Type\",\"application/x-www-form-urlencoded\"),void 0!==i&&a.setRequestHeader(\"Authorization\",\"Basic \"+btoa(i)),a.send(c)}))},t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.SigninRequest=void 0;var n=r(0),i=r(3),o=r(13);e.SigninRequest=function(){function t(e){var r=e.url,s=e.client_id,a=e.redirect_uri,u=e.response_type,c=e.scope,h=e.authority,l=e.data,f=e.prompt,g=e.display,d=e.max_age,p=e.ui_locales,v=e.id_token_hint,y=e.login_hint,m=e.acr_values,_=e.resource,S=e.response_mode,b=e.request,w=e.request_uri,F=e.extraQueryParams,E=e.request_type,x=e.client_secret,A=e.extraTokenParams,k=e.skipUserInfo;if(function P(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}(this,t),!r)throw n.Log.error(\"SigninRequest.ctor: No url passed\"),new Error(\"url\");if(!s)throw n.Log.error(\"SigninRequest.ctor: No client_id passed\"),new Error(\"client_id\");if(!a)throw n.Log.error(\"SigninRequest.ctor: No redirect_uri passed\"),new Error(\"redirect_uri\");if(!u)throw n.Log.error(\"SigninRequest.ctor: No response_type passed\"),new Error(\"response_type\");if(!c)throw n.Log.error(\"SigninRequest.ctor: No scope passed\"),new Error(\"scope\");if(!h)throw n.Log.error(\"SigninRequest.ctor: No authority passed\"),new Error(\"authority\");var C=t.isOidc(u),T=t.isCode(u);S||(S=t.isCode(u)?\"query\":null),this.state=new o.SigninState({nonce:C,data:l,client_id:s,authority:h,redirect_uri:a,code_verifier:T,request_type:E,response_mode:S,client_secret:x,scope:c,extraTokenParams:A,skipUserInfo:k}),r=i.UrlUtility.addQueryParam(r,\"client_id\",s),r=i.UrlUtility.addQueryParam(r,\"redirect_uri\",a),r=i.UrlUtility.addQueryParam(r,\"response_type\",u),r=i.UrlUtility.addQueryParam(r,\"scope\",c),r=i.UrlUtility.addQueryParam(r,\"state\",this.state.id),C&&(r=i.UrlUtility.addQueryParam(r,\"nonce\",this.state.nonce)),T&&(r=i.UrlUtility.addQueryParam(r,\"code_challenge\",this.state.code_challenge),r=i.UrlUtility.addQueryParam(r,\"code_challenge_method\",\"S256\"));var R={prompt:f,display:g,max_age:d,ui_locales:p,id_token_hint:v,login_hint:y,acr_values:m,resource:_,request:b,request_uri:w,response_mode:S};for(var I in R)R[I]&&(r=i.UrlUtility.addQueryParam(r,I,R[I]));for(var D in F)r=i.UrlUtility.addQueryParam(r,D,F[D]);this.url=r}return t.isOidc=function t(e){return!!e.split(/\\s+/g).filter((function(t){return\"id_token\"===t}))[0]},t.isOAuth=function t(e){return!!e.split(/\\s+/g).filter((function(t){return\"token\"===t}))[0]},t.isCode=function t(e){return!!e.split(/\\s+/g).filter((function(t){return\"code\"===t}))[0]},t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.State=void 0;var n=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},r=e.id,n=e.data,i=e.created,s=e.request_type;a(this,t),this._id=r||(0,o.default)(),this._data=n,this._created=\"number\"==typeof i&&i>0?i:parseInt(Date.now()/1e3),this._request_type=s}return t.prototype.toStorageString=function t(){return i.Log.debug(\"State.toStorageString\"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type})},t.fromStorageString=function e(r){return i.Log.debug(\"State.fromStorageString\"),new t(JSON.parse(r))},t.clearStaleState=function e(r,n){var o=Date.now()/1e3-n;return r.getAllKeys().then((function(e){i.Log.debug(\"State.clearStaleState: got keys\",e);for(var n=[],s=function s(a){var c=e[a];u=r.get(c).then((function(e){var n=!1;if(e)try{var s=t.fromStorageString(e);i.Log.debug(\"State.clearStaleState: got item from key: \",c,s.created),s.created<=o&&(n=!0)}catch(t){i.Log.error(\"State.clearStaleState: Error parsing state for key\",c,t.message),n=!0}else i.Log.debug(\"State.clearStaleState: no item in storage for key: \",c),n=!0;if(n)return i.Log.debug(\"State.clearStaleState: removed item for key: \",c),r.remove(c)})),n.push(u)},a=0;a0&&void 0!==arguments[0]?arguments[0]:{};g(this,t),e instanceof o.OidcClientSettings?this._settings=e:this._settings=new o.OidcClientSettings(e)}return t.prototype.createSigninRequest=function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=r.response_type,o=r.scope,s=r.redirect_uri,u=r.data,c=r.state,h=r.prompt,l=r.display,f=r.max_age,g=r.ui_locales,d=r.id_token_hint,p=r.login_hint,v=r.acr_values,y=r.resource,m=r.request,_=r.request_uri,S=r.response_mode,b=r.extraQueryParams,w=r.extraTokenParams,F=r.request_type,E=r.skipUserInfo,x=arguments[1];i.Log.debug(\"OidcClient.createSigninRequest\");var A=this._settings.client_id;n=n||this._settings.response_type,o=o||this._settings.scope,s=s||this._settings.redirect_uri,h=h||this._settings.prompt,l=l||this._settings.display,f=f||this._settings.max_age,g=g||this._settings.ui_locales,v=v||this._settings.acr_values,y=y||this._settings.resource,S=S||this._settings.response_mode,b=b||this._settings.extraQueryParams,w=w||this._settings.extraTokenParams;var k=this._settings.authority;return a.SigninRequest.isCode(n)&&\"code\"!==n?Promise.reject(new Error(\"OpenID Connect hybrid flow is not supported\")):this._metadataService.getAuthorizationEndpoint().then((function(t){i.Log.debug(\"OidcClient.createSigninRequest: Received authorization endpoint\",t);var r=new a.SigninRequest({url:t,client_id:A,redirect_uri:s,response_type:n,scope:o,data:u||c,authority:k,prompt:h,display:l,max_age:f,ui_locales:g,id_token_hint:d,login_hint:p,acr_values:v,resource:y,request:m,request_uri:_,extraQueryParams:b,extraTokenParams:w,request_type:F,response_mode:S,client_secret:e._settings.client_secret,skipUserInfo:E}),P=r.state;return(x=x||e._stateStore).set(P.id,P.toStorageString()).then((function(){return r}))}))},t.prototype.readSigninResponseState=function t(e,r){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];i.Log.debug(\"OidcClient.readSigninResponseState\");var o=\"query\"===this._settings.response_mode||!this._settings.response_mode&&a.SigninRequest.isCode(this._settings.response_type),s=o?\"?\":\"#\",c=new u.SigninResponse(e,s);if(!c.state)return i.Log.error(\"OidcClient.readSigninResponseState: No state in response\"),Promise.reject(new Error(\"No state in response\"));r=r||this._stateStore;var h=n?r.remove.bind(r):r.get.bind(r);return h(c.state).then((function(t){if(!t)throw i.Log.error(\"OidcClient.readSigninResponseState: No matching state found in storage\"),new Error(\"No matching state found in storage\");return{state:l.SigninState.fromStorageString(t),response:c}}))},t.prototype.processSigninResponse=function t(e,r){var n=this;return i.Log.debug(\"OidcClient.processSigninResponse\"),this.readSigninResponseState(e,r,!0).then((function(t){var e=t.state,r=t.response;return i.Log.debug(\"OidcClient.processSigninResponse: Received state from storage; validating response\"),n._validator.validateSigninResponse(e,r)}))},t.prototype.createSignoutRequest=function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=r.id_token_hint,o=r.data,s=r.state,a=r.post_logout_redirect_uri,u=r.extraQueryParams,h=r.request_type,l=arguments[1];return i.Log.debug(\"OidcClient.createSignoutRequest\"),a=a||this._settings.post_logout_redirect_uri,u=u||this._settings.extraQueryParams,this._metadataService.getEndSessionEndpoint().then((function(t){if(!t)throw i.Log.error(\"OidcClient.createSignoutRequest: No end session endpoint url returned\"),new Error(\"no end session endpoint\");i.Log.debug(\"OidcClient.createSignoutRequest: Received end session endpoint\",t);var r=new c.SignoutRequest({url:t,id_token_hint:n,post_logout_redirect_uri:a,data:o||s,extraQueryParams:u,request_type:h}),f=r.state;return f&&(i.Log.debug(\"OidcClient.createSignoutRequest: Signout request has state to persist\"),(l=l||e._stateStore).set(f.id,f.toStorageString())),r}))},t.prototype.readSignoutResponseState=function t(e,r){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];i.Log.debug(\"OidcClient.readSignoutResponseState\");var o=new h.SignoutResponse(e);if(!o.state)return i.Log.debug(\"OidcClient.readSignoutResponseState: No state in response\"),o.error?(i.Log.warn(\"OidcClient.readSignoutResponseState: Response was error: \",o.error),Promise.reject(new s.ErrorResponse(o))):Promise.resolve({state:void 0,response:o});var a=o.state;r=r||this._stateStore;var u=n?r.remove.bind(r):r.get.bind(r);return u(a).then((function(t){if(!t)throw i.Log.error(\"OidcClient.readSignoutResponseState: No matching state found in storage\"),new Error(\"No matching state found in storage\");return{state:f.State.fromStorageString(t),response:o}}))},t.prototype.processSignoutResponse=function t(e,r){var n=this;return i.Log.debug(\"OidcClient.processSignoutResponse\"),this.readSignoutResponseState(e,r,!0).then((function(t){var e=t.state,r=t.response;return e?(i.Log.debug(\"OidcClient.processSignoutResponse: Received state from storage; validating response\"),n._validator.validateSignoutResponse(e,r)):(i.Log.debug(\"OidcClient.processSignoutResponse: No state from storage; skipping validating response\"),r)}))},t.prototype.clearStaleState=function t(e){return i.Log.debug(\"OidcClient.clearStaleState\"),e=e||this._stateStore,f.State.clearStaleState(e,this.settings.staleStateAge)},n(t,[{key:\"_stateStore\",get:function t(){return this.settings.stateStore}},{key:\"_validator\",get:function t(){return this.settings.validator}},{key:\"_metadataService\",get:function t(){return this.settings.metadataService}},{key:\"settings\",get:function t(){return this._settings}},{key:\"metadataService\",get:function t(){return this._metadataService}}]),t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.TokenClient=void 0;var n=r(7),i=r(2),o=r(0);function s(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}e.TokenClient=function(){function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.JsonService,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.MetadataService;if(s(this,t),!e)throw o.Log.error(\"TokenClient.ctor: No settings passed\"),new Error(\"settings\");this._settings=e,this._jsonService=new r,this._metadataService=new a(this._settings)}return t.prototype.exchangeCode=function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(r=Object.assign({},r)).grant_type=r.grant_type||\"authorization_code\",r.client_id=r.client_id||this._settings.client_id,r.client_secret=r.client_secret||this._settings.client_secret,r.redirect_uri=r.redirect_uri||this._settings.redirect_uri;var n=void 0,i=r._client_authentication||this._settings._client_authentication;return delete r._client_authentication,r.code?r.redirect_uri?r.code_verifier?r.client_id?r.client_secret||\"client_secret_basic\"!=i?(\"client_secret_basic\"==i&&(n=r.client_id+\":\"+r.client_secret,delete r.client_id,delete r.client_secret),this._metadataService.getTokenEndpoint(!1).then((function(t){return o.Log.debug(\"TokenClient.exchangeCode: Received token endpoint\"),e._jsonService.postForm(t,r,n).then((function(t){return o.Log.debug(\"TokenClient.exchangeCode: response received\"),t}))}))):(o.Log.error(\"TokenClient.exchangeCode: No client_secret passed\"),Promise.reject(new Error(\"A client_secret is required\"))):(o.Log.error(\"TokenClient.exchangeCode: No client_id passed\"),Promise.reject(new Error(\"A client_id is required\"))):(o.Log.error(\"TokenClient.exchangeCode: No code_verifier passed\"),Promise.reject(new Error(\"A code_verifier is required\"))):(o.Log.error(\"TokenClient.exchangeCode: No redirect_uri passed\"),Promise.reject(new Error(\"A redirect_uri is required\"))):(o.Log.error(\"TokenClient.exchangeCode: No code passed\"),Promise.reject(new Error(\"A code is required\")))},t.prototype.exchangeRefreshToken=function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(r=Object.assign({},r)).grant_type=r.grant_type||\"refresh_token\",r.client_id=r.client_id||this._settings.client_id,r.client_secret=r.client_secret||this._settings.client_secret;var n=void 0,i=r._client_authentication||this._settings._client_authentication;return delete r._client_authentication,r.refresh_token?r.client_id?(\"client_secret_basic\"==i&&(n=r.client_id+\":\"+r.client_secret,delete r.client_id,delete r.client_secret),this._metadataService.getTokenEndpoint(!1).then((function(t){return o.Log.debug(\"TokenClient.exchangeRefreshToken: Received token endpoint\"),e._jsonService.postForm(t,r,n).then((function(t){return o.Log.debug(\"TokenClient.exchangeRefreshToken: response received\"),t}))}))):(o.Log.error(\"TokenClient.exchangeRefreshToken: No client_id passed\"),Promise.reject(new Error(\"A client_id is required\"))):(o.Log.error(\"TokenClient.exchangeRefreshToken: No refresh_token passed\"),Promise.reject(new Error(\"A refresh_token is required\")))},t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.ErrorResponse=void 0;var n=r(0);function i(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}function o(t,e){if(!t)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return!e||\"object\"!=typeof e&&\"function\"!=typeof e?t:e}e.ErrorResponse=function(t){function e(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=r.error,a=r.error_description,u=r.error_uri,c=r.state,h=r.session_state;if(i(this,e),!s)throw n.Log.error(\"No error passed to ErrorResponse\"),new Error(\"error\");var l=o(this,t.call(this,a||s));return l.name=\"ErrorResponse\",l.error=s,l.error_description=a,l.error_uri=u,l.state=c,l.session_state=h,l}return function r(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,t),e}(Error)},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.SigninState=void 0;var n=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=r.nonce,i=r.authority,o=r.client_id,u=r.redirect_uri,l=r.code_verifier,f=r.response_mode,g=r.client_secret,d=r.scope,p=r.extraTokenParams,v=r.skipUserInfo;c(this,e);var y=h(this,t.call(this,arguments[0]));if(!0===n?y._nonce=(0,a.default)():n&&(y._nonce=n),!0===l?y._code_verifier=(0,a.default)()+(0,a.default)()+(0,a.default)():l&&(y._code_verifier=l),y.code_verifier){var m=s.JoseUtil.hashString(y.code_verifier,\"SHA256\");y._code_challenge=s.JoseUtil.hexToBase64Url(m)}return y._redirect_uri=u,y._authority=i,y._client_id=o,y._response_mode=f,y._client_secret=g,y._scope=d,y._extraTokenParams=p,y._skipUserInfo=v,y}return function r(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,t),e.prototype.toStorageString=function t(){return i.Log.debug(\"SigninState.toStorageString\"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,nonce:this.nonce,code_verifier:this.code_verifier,redirect_uri:this.redirect_uri,authority:this.authority,client_id:this.client_id,response_mode:this.response_mode,client_secret:this.client_secret,scope:this.scope,extraTokenParams:this.extraTokenParams,skipUserInfo:this.skipUserInfo})},e.fromStorageString=function t(r){return i.Log.debug(\"SigninState.fromStorageString\"),new e(JSON.parse(r))},n(e,[{key:\"nonce\",get:function t(){return this._nonce}},{key:\"authority\",get:function t(){return this._authority}},{key:\"client_id\",get:function t(){return this._client_id}},{key:\"redirect_uri\",get:function t(){return this._redirect_uri}},{key:\"code_verifier\",get:function t(){return this._code_verifier}},{key:\"code_challenge\",get:function t(){return this._code_challenge}},{key:\"response_mode\",get:function t(){return this._response_mode}},{key:\"client_secret\",get:function t(){return this._client_secret}},{key:\"scope\",get:function t(){return this._scope}},{key:\"extraTokenParams\",get:function t(){return this._extraTokenParams}},{key:\"skipUserInfo\",get:function t(){return this._skipUserInfo}}]),e}(o.State)},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.default=function n(){return(\"undefined\"!=i&&null!==i&&void 0!==i.getRandomValues?o:s)().replace(/-/g,\"\")};var i=\"undefined\"!=typeof window?window.crypto||window.msCrypto:null;function o(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(function(t){return(t^i.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}))}function s(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(function(t){return(t^16*Math.random()>>t/4).toString(16)}))}t.exports=e.default},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.User=void 0;var n=function(){function t(t,e){for(var r=0;r0){var n=parseInt(Date.now()/1e3);this.expires_at=n+r}}},{key:\"expired\",get:function t(){var e=this.expires_in;if(void 0!==e)return e<=0}},{key:\"scopes\",get:function t(){return(this.scope||\"\").split(\" \")}}]),t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.AccessTokenEvents=void 0;var n=r(0),i=r(46);function o(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}e.AccessTokenEvents=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.accessTokenExpiringNotificationTime,n=void 0===r?60:r,s=e.accessTokenExpiringTimer,a=void 0===s?new i.Timer(\"Access token expiring\"):s,u=e.accessTokenExpiredTimer,c=void 0===u?new i.Timer(\"Access token expired\"):u;o(this,t),this._accessTokenExpiringNotificationTime=n,this._accessTokenExpiring=a,this._accessTokenExpired=c}return t.prototype.load=function t(e){if(e.access_token&&void 0!==e.expires_in){var r=e.expires_in;if(n.Log.debug(\"AccessTokenEvents.load: access token present, remaining duration:\",r),r>0){var i=r-this._accessTokenExpiringNotificationTime;i<=0&&(i=1),n.Log.debug(\"AccessTokenEvents.load: registering expiring timer in:\",i),this._accessTokenExpiring.init(i)}else n.Log.debug(\"AccessTokenEvents.load: canceling existing expiring timer becase we're past expiration.\"),this._accessTokenExpiring.cancel();var o=r+1;n.Log.debug(\"AccessTokenEvents.load: registering expired timer in:\",o),this._accessTokenExpired.init(o)}else this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},t.prototype.unload=function t(){n.Log.debug(\"AccessTokenEvents.unload: canceling existing access token timers\"),this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},t.prototype.addAccessTokenExpiring=function t(e){this._accessTokenExpiring.addHandler(e)},t.prototype.removeAccessTokenExpiring=function t(e){this._accessTokenExpiring.removeHandler(e)},t.prototype.addAccessTokenExpired=function t(e){this._accessTokenExpired.addHandler(e)},t.prototype.removeAccessTokenExpired=function t(e){this._accessTokenExpired.removeHandler(e)},t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.Event=void 0;var n=r(0);e.Event=function(){function t(e){!function r(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}(this,t),this._name=e,this._callbacks=[]}return t.prototype.addHandler=function t(e){this._callbacks.push(e)},t.prototype.removeHandler=function t(e){var r=this._callbacks.findIndex((function(t){return t===e}));r>=0&&this._callbacks.splice(r,1)},t.prototype.raise=function t(){n.Log.debug(\"Event: Raising event: \"+this._name);for(var e=0;e1&&void 0!==arguments[1]?arguments[1]:o.CheckSessionIFrame,u=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.Global.timer;if(a(this,t),!e)throw i.Log.error(\"SessionMonitor.ctor: No user manager passed to SessionMonitor\"),new Error(\"userManager\");this._userManager=e,this._CheckSessionIFrameCtor=n,this._timer=u,this._userManager.events.addUserLoaded(this._start.bind(this)),this._userManager.events.addUserUnloaded(this._stop.bind(this)),Promise.resolve(this._userManager.getUser().then((function(t){t?r._start(t):r._settings.monitorAnonymousSession&&r._userManager.querySessionStatus().then((function(t){var e={session_state:t.session_state};t.sub&&t.sid&&(e.profile={sub:t.sub,sid:t.sid}),r._start(e)})).catch((function(t){i.Log.error(\"SessionMonitor ctor: error from querySessionStatus:\",t.message)}))})).catch((function(t){i.Log.error(\"SessionMonitor ctor: error from getUser:\",t.message)})))}return t.prototype._start=function t(e){var r=this,n=e.session_state;n&&(e.profile?(this._sub=e.profile.sub,this._sid=e.profile.sid,i.Log.debug(\"SessionMonitor._start: session_state:\",n,\", sub:\",this._sub)):(this._sub=void 0,this._sid=void 0,i.Log.debug(\"SessionMonitor._start: session_state:\",n,\", anonymous user\")),this._checkSessionIFrame?this._checkSessionIFrame.start(n):this._metadataService.getCheckSessionIframe().then((function(t){if(t){i.Log.debug(\"SessionMonitor._start: Initializing check session iframe\");var e=r._client_id,o=r._checkSessionInterval,s=r._stopCheckSessionOnError;r._checkSessionIFrame=new r._CheckSessionIFrameCtor(r._callback.bind(r),e,t,o,s),r._checkSessionIFrame.load().then((function(){r._checkSessionIFrame.start(n)}))}else i.Log.warn(\"SessionMonitor._start: No check session iframe found in the metadata\")})).catch((function(t){i.Log.error(\"SessionMonitor._start: Error from getCheckSessionIframe:\",t.message)})))},t.prototype._stop=function t(){var e=this;if(this._sub=void 0,this._sid=void 0,this._checkSessionIFrame&&(i.Log.debug(\"SessionMonitor._stop\"),this._checkSessionIFrame.stop()),this._settings.monitorAnonymousSession)var r=this._timer.setInterval((function(){e._timer.clearInterval(r),e._userManager.querySessionStatus().then((function(t){var r={session_state:t.session_state};t.sub&&t.sid&&(r.profile={sub:t.sub,sid:t.sid}),e._start(r)})).catch((function(t){i.Log.error(\"SessionMonitor: error from querySessionStatus:\",t.message)}))}),1e3)},t.prototype._callback=function t(){var e=this;this._userManager.querySessionStatus().then((function(t){var r=!0;t?t.sub===e._sub?(r=!1,e._checkSessionIFrame.start(t.session_state),t.sid===e._sid?i.Log.debug(\"SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:\",t.session_state):(i.Log.debug(\"SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:\",t.session_state),e._userManager.events._raiseUserSessionChanged())):i.Log.debug(\"SessionMonitor._callback: Different subject signed into OP:\",t.sub):i.Log.debug(\"SessionMonitor._callback: Subject no longer signed into OP\"),r&&(e._sub?(i.Log.debug(\"SessionMonitor._callback: SessionMonitor._callback; raising signed out event\"),e._userManager.events._raiseUserSignedOut()):(i.Log.debug(\"SessionMonitor._callback: SessionMonitor._callback; raising signed in event\"),e._userManager.events._raiseUserSignedIn()))})).catch((function(t){e._sub&&(i.Log.debug(\"SessionMonitor._callback: Error calling queryCurrentSigninSession; raising signed out event\",t.message),e._userManager.events._raiseUserSignedOut())}))},n(t,[{key:\"_settings\",get:function t(){return this._userManager.settings}},{key:\"_metadataService\",get:function t(){return this._userManager.metadataService}},{key:\"_client_id\",get:function t(){return this._settings.client_id}},{key:\"_checkSessionInterval\",get:function t(){return this._settings.checkSessionInterval}},{key:\"_stopCheckSessionOnError\",get:function t(){return this._settings.stopCheckSessionOnError}}]),t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.CheckSessionIFrame=void 0;var n=r(0);function i(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}e.CheckSessionIFrame=function(){function t(e,r,n,o){var s=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];i(this,t),this._callback=e,this._client_id=r,this._url=n,this._interval=o||2e3,this._stopOnError=s;var a=n.indexOf(\"/\",n.indexOf(\"//\")+2);this._frame_origin=n.substr(0,a),this._frame=window.document.createElement(\"iframe\"),this._frame.style.visibility=\"hidden\",this._frame.style.position=\"absolute\",this._frame.style.display=\"none\",this._frame.width=0,this._frame.height=0,this._frame.src=n}return t.prototype.load=function t(){var e=this;return new Promise((function(t){e._frame.onload=function(){t()},window.document.body.appendChild(e._frame),e._boundMessageEvent=e._message.bind(e),window.addEventListener(\"message\",e._boundMessageEvent,!1)}))},t.prototype._message=function t(e){e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(\"error\"===e.data?(n.Log.error(\"CheckSessionIFrame: error message from check session op iframe\"),this._stopOnError&&this.stop()):\"changed\"===e.data?(n.Log.debug(\"CheckSessionIFrame: changed message from check session op iframe\"),this.stop(),this._callback()):n.Log.debug(\"CheckSessionIFrame: \"+e.data+\" message from check session op iframe\"))},t.prototype.start=function t(e){var r=this;if(this._session_state!==e){n.Log.debug(\"CheckSessionIFrame.start\"),this.stop(),this._session_state=e;var i=function t(){r._frame.contentWindow.postMessage(r._client_id+\" \"+r._session_state,r._frame_origin)};i(),this._timer=window.setInterval(i,this._interval)}},t.prototype.stop=function t(){this._session_state=null,this._timer&&(n.Log.debug(\"CheckSessionIFrame.stop\"),window.clearInterval(this._timer),this._timer=null)},t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.TokenRevocationClient=void 0;var n=r(0),i=r(2),o=r(1);function s(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}var a=\"access_token\",u=\"refresh_token\";e.TokenRevocationClient=function(){function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o.Global.XMLHttpRequest,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.MetadataService;if(s(this,t),!e)throw n.Log.error(\"TokenRevocationClient.ctor: No settings provided\"),new Error(\"No settings provided.\");this._settings=e,this._XMLHttpRequestCtor=r,this._metadataService=new a(this._settings)}return t.prototype.revoke=function t(e,r){var i=this,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:\"access_token\";if(!e)throw n.Log.error(\"TokenRevocationClient.revoke: No token provided\"),new Error(\"No token provided.\");if(o!==a&&o!=u)throw n.Log.error(\"TokenRevocationClient.revoke: Invalid token type\"),new Error(\"Invalid token type.\");return this._metadataService.getRevocationEndpoint().then((function(t){if(t){n.Log.debug(\"TokenRevocationClient.revoke: Revoking \"+o);var s=i._settings.client_id,a=i._settings.client_secret;return i._revoke(t,s,a,e,o)}if(r)throw n.Log.error(\"TokenRevocationClient.revoke: Revocation not supported\"),new Error(\"Revocation not supported\")}))},t.prototype._revoke=function t(e,r,i,o,s){var a=this;return new Promise((function(t,u){var c=new a._XMLHttpRequestCtor;c.open(\"POST\",e),c.onload=function(){n.Log.debug(\"TokenRevocationClient.revoke: HTTP response received, status\",c.status),200===c.status?t():u(Error(c.statusText+\" (\"+c.status+\")\"))},c.onerror=function(){n.Log.debug(\"TokenRevocationClient.revoke: Network Error.\"),u(\"Network Error\")};var h=\"client_id=\"+encodeURIComponent(r);i&&(h+=\"&client_secret=\"+encodeURIComponent(i)),h+=\"&token_type_hint=\"+encodeURIComponent(s),h+=\"&token=\"+encodeURIComponent(o),c.setRequestHeader(\"Content-Type\",\"application/x-www-form-urlencoded\"),c.send(h)}))},t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.CordovaPopupWindow=void 0;var n=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:o.MetadataService,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.UserInfoService,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:c.JoseUtil,l=arguments.length>4&&void 0!==arguments[4]?arguments[4]:a.TokenClient;if(h(this,t),!e)throw i.Log.error(\"ResponseValidator.ctor: No settings passed to ResponseValidator\"),new Error(\"settings\");this._settings=e,this._metadataService=new r(this._settings),this._userInfoService=new n(this._settings),this._joseUtil=u,this._tokenClient=new l(this._settings)}return t.prototype.validateSigninResponse=function t(e,r){var n=this;return i.Log.debug(\"ResponseValidator.validateSigninResponse\"),this._processSigninParams(e,r).then((function(t){return i.Log.debug(\"ResponseValidator.validateSigninResponse: state processed\"),n._validateTokens(e,t).then((function(t){return i.Log.debug(\"ResponseValidator.validateSigninResponse: tokens validated\"),n._processClaims(e,t).then((function(t){return i.Log.debug(\"ResponseValidator.validateSigninResponse: claims processed\"),t}))}))}))},t.prototype.validateSignoutResponse=function t(e,r){return e.id!==r.state?(i.Log.error(\"ResponseValidator.validateSignoutResponse: State does not match\"),Promise.reject(new Error(\"State does not match\"))):(i.Log.debug(\"ResponseValidator.validateSignoutResponse: state validated\"),r.state=e.data,r.error?(i.Log.warn(\"ResponseValidator.validateSignoutResponse: Response was error\",r.error),Promise.reject(new u.ErrorResponse(r))):Promise.resolve(r))},t.prototype._processSigninParams=function t(e,r){if(e.id!==r.state)return i.Log.error(\"ResponseValidator._processSigninParams: State does not match\"),Promise.reject(new Error(\"State does not match\"));if(!e.client_id)return i.Log.error(\"ResponseValidator._processSigninParams: No client_id on state\"),Promise.reject(new Error(\"No client_id on state\"));if(!e.authority)return i.Log.error(\"ResponseValidator._processSigninParams: No authority on state\"),Promise.reject(new Error(\"No authority on state\"));if(this._settings.authority){if(this._settings.authority&&this._settings.authority!==e.authority)return i.Log.error(\"ResponseValidator._processSigninParams: authority mismatch on settings vs. signin state\"),Promise.reject(new Error(\"authority mismatch on settings vs. signin state\"))}else this._settings.authority=e.authority;if(this._settings.client_id){if(this._settings.client_id&&this._settings.client_id!==e.client_id)return i.Log.error(\"ResponseValidator._processSigninParams: client_id mismatch on settings vs. signin state\"),Promise.reject(new Error(\"client_id mismatch on settings vs. signin state\"))}else this._settings.client_id=e.client_id;return i.Log.debug(\"ResponseValidator._processSigninParams: state validated\"),r.state=e.data,r.error?(i.Log.warn(\"ResponseValidator._processSigninParams: Response was error\",r.error),Promise.reject(new u.ErrorResponse(r))):e.nonce&&!r.id_token?(i.Log.error(\"ResponseValidator._processSigninParams: Expecting id_token in response\"),Promise.reject(new Error(\"No id_token in response\"))):!e.nonce&&r.id_token?(i.Log.error(\"ResponseValidator._processSigninParams: Not expecting id_token in response\"),Promise.reject(new Error(\"Unexpected id_token in response\"))):e.code_verifier&&!r.code?(i.Log.error(\"ResponseValidator._processSigninParams: Expecting code in response\"),Promise.reject(new Error(\"No code in response\"))):!e.code_verifier&&r.code?(i.Log.error(\"ResponseValidator._processSigninParams: Not expecting code in response\"),Promise.reject(new Error(\"Unexpected code in response\"))):(r.scope||(r.scope=e.scope),Promise.resolve(r))},t.prototype._processClaims=function t(e,r){var n=this;if(r.isOpenIdConnect){if(i.Log.debug(\"ResponseValidator._processClaims: response is OIDC, processing claims\"),r.profile=this._filterProtocolClaims(r.profile),!0!==e.skipUserInfo&&this._settings.loadUserInfo&&r.access_token)return i.Log.debug(\"ResponseValidator._processClaims: loading user info\"),this._userInfoService.getClaims(r.access_token).then((function(t){return i.Log.debug(\"ResponseValidator._processClaims: user info claims received from user info endpoint\"),t.sub!==r.profile.sub?(i.Log.error(\"ResponseValidator._processClaims: sub from user info endpoint does not match sub in id_token\"),Promise.reject(new Error(\"sub from user info endpoint does not match sub in id_token\"))):(r.profile=n._mergeClaims(r.profile,t),i.Log.debug(\"ResponseValidator._processClaims: user info claims received, updated profile:\",r.profile),r)}));i.Log.debug(\"ResponseValidator._processClaims: not loading user info\")}else i.Log.debug(\"ResponseValidator._processClaims: response is not OIDC, not processing claims\");return Promise.resolve(r)},t.prototype._mergeClaims=function t(e,r){var i=Object.assign({},e);for(var o in r){var s=r[o];Array.isArray(s)||(s=[s]);for(var a=0;a1)return i.Log.error(\"ResponseValidator._validateIdToken: No kid found in id_token and more than one key found in metadata\"),Promise.reject(new Error(\"No kid found in id_token and more than one key found in metadata\"));o=t[0]}return Promise.resolve(o)}))},t.prototype._getSigningKeyForJwtWithSingleRetry=function t(e){var r=this;return this._getSigningKeyForJwt(e).then((function(t){return t?Promise.resolve(t):(r._metadataService.resetSigningKeys(),r._getSigningKeyForJwt(e))}))},t.prototype._validateIdToken=function t(e,r){var n=this;if(!e.nonce)return i.Log.error(\"ResponseValidator._validateIdToken: No nonce on state\"),Promise.reject(new Error(\"No nonce on state\"));var o=this._joseUtil.parseJwt(r.id_token);return o&&o.header&&o.payload?e.nonce!==o.payload.nonce?(i.Log.error(\"ResponseValidator._validateIdToken: Invalid nonce in id_token\"),Promise.reject(new Error(\"Invalid nonce in id_token\"))):this._metadataService.getIssuer().then((function(t){return i.Log.debug(\"ResponseValidator._validateIdToken: Received issuer\"),n._getSigningKeyForJwtWithSingleRetry(o).then((function(s){if(!s)return i.Log.error(\"ResponseValidator._validateIdToken: No key matching kid or alg found in signing keys\"),Promise.reject(new Error(\"No key matching kid or alg found in signing keys\"));var a=e.client_id,u=n._settings.clockSkew;return i.Log.debug(\"ResponseValidator._validateIdToken: Validaing JWT; using clock skew (in seconds) of: \",u),n._joseUtil.validateJwt(r.id_token,s,t,a,u).then((function(){return i.Log.debug(\"ResponseValidator._validateIdToken: JWT validation successful\"),o.payload.sub?(r.profile=o.payload,r):(i.Log.error(\"ResponseValidator._validateIdToken: No sub present in id_token\"),Promise.reject(new Error(\"No sub present in id_token\")))}))}))})):(i.Log.error(\"ResponseValidator._validateIdToken: Failed to parse id_token\",o),Promise.reject(new Error(\"Failed to parse id_token\")))},t.prototype._filterByAlg=function t(e,r){var n=null;if(r.startsWith(\"RS\"))n=\"RSA\";else if(r.startsWith(\"PS\"))n=\"PS\";else{if(!r.startsWith(\"ES\"))return i.Log.debug(\"ResponseValidator._filterByAlg: alg not supported: \",r),[];n=\"EC\"}return i.Log.debug(\"ResponseValidator._filterByAlg: Looking for keys that match kty: \",n),e=e.filter((function(t){return t.kty===n})),i.Log.debug(\"ResponseValidator._filterByAlg: Number of keys that match kty: \",n,e.length),e},t.prototype._validateAccessToken=function t(e){if(!e.profile)return i.Log.error(\"ResponseValidator._validateAccessToken: No profile loaded from id_token\"),Promise.reject(new Error(\"No profile loaded from id_token\"));if(!e.profile.at_hash)return i.Log.error(\"ResponseValidator._validateAccessToken: No at_hash in id_token\"),Promise.reject(new Error(\"No at_hash in id_token\"));if(!e.id_token)return i.Log.error(\"ResponseValidator._validateAccessToken: No id_token\"),Promise.reject(new Error(\"No id_token\"));var r=this._joseUtil.parseJwt(e.id_token);if(!r||!r.header)return i.Log.error(\"ResponseValidator._validateAccessToken: Failed to parse id_token\",r),Promise.reject(new Error(\"Failed to parse id_token\"));var n=r.header.alg;if(!n||5!==n.length)return i.Log.error(\"ResponseValidator._validateAccessToken: Unsupported alg:\",n),Promise.reject(new Error(\"Unsupported alg: \"+n));var o=n.substr(2,3);if(!o)return i.Log.error(\"ResponseValidator._validateAccessToken: Unsupported alg:\",n,o),Promise.reject(new Error(\"Unsupported alg: \"+n));if(256!==(o=parseInt(o))&&384!==o&&512!==o)return i.Log.error(\"ResponseValidator._validateAccessToken: Unsupported alg:\",n,o),Promise.reject(new Error(\"Unsupported alg: \"+n));var s=\"sha\"+o,a=this._joseUtil.hashString(e.access_token,s);if(!a)return i.Log.error(\"ResponseValidator._validateAccessToken: access_token hash failed:\",s),Promise.reject(new Error(\"Failed to validate at_hash\"));var u=a.substr(0,a.length/2),c=this._joseUtil.hexToBase64Url(u);return c!==e.profile.at_hash?(i.Log.error(\"ResponseValidator._validateAccessToken: Failed to validate at_hash\",c,e.profile.at_hash),Promise.reject(new Error(\"Failed to validate at_hash\"))):(i.Log.debug(\"ResponseValidator._validateAccessToken: success\"),Promise.resolve(e))},t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.UserInfoService=void 0;var n=r(7),i=r(2),o=r(0),s=r(4);function a(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}e.UserInfoService=function(){function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.JsonService,u=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.MetadataService,c=arguments.length>3&&void 0!==arguments[3]?arguments[3]:s.JoseUtil;if(a(this,t),!e)throw o.Log.error(\"UserInfoService.ctor: No settings passed\"),new Error(\"settings\");this._settings=e,this._jsonService=new r(void 0,void 0,this._getClaimsFromJwt.bind(this)),this._metadataService=new u(this._settings),this._joseUtil=c}return t.prototype.getClaims=function t(e){var r=this;return e?this._metadataService.getUserInfoEndpoint().then((function(t){return o.Log.debug(\"UserInfoService.getClaims: received userinfo url\",t),r._jsonService.getJson(t,e).then((function(t){return o.Log.debug(\"UserInfoService.getClaims: claims received\",t),t}))})):(o.Log.error(\"UserInfoService.getClaims: No token passed\"),Promise.reject(new Error(\"A token is required\")))},t.prototype._getClaimsFromJwt=function t(e){var r=this;try{var n=this._joseUtil.parseJwt(e.responseText);if(!n||!n.header||!n.payload)return o.Log.error(\"UserInfoService._getClaimsFromJwt: Failed to parse JWT\",n),Promise.reject(new Error(\"Failed to parse id_token\"));var i=n.header.kid,s=void 0;switch(this._settings.userInfoJwtIssuer){case\"OP\":s=this._metadataService.getIssuer();break;case\"ANY\":s=Promise.resolve(n.payload.iss);break;default:s=Promise.resolve(this._settings.userInfoJwtIssuer)}return s.then((function(t){return o.Log.debug(\"UserInfoService._getClaimsFromJwt: Received issuer:\"+t),r._metadataService.getSigningKeys().then((function(s){if(!s)return o.Log.error(\"UserInfoService._getClaimsFromJwt: No signing keys from metadata\"),Promise.reject(new Error(\"No signing keys from metadata\"));o.Log.debug(\"UserInfoService._getClaimsFromJwt: Received signing keys\");var a=void 0;if(i)a=s.filter((function(t){return t.kid===i}))[0];else{if((s=r._filterByAlg(s,n.header.alg)).length>1)return o.Log.error(\"UserInfoService._getClaimsFromJwt: No kid found in id_token and more than one key found in metadata\"),Promise.reject(new Error(\"No kid found in id_token and more than one key found in metadata\"));a=s[0]}if(!a)return o.Log.error(\"UserInfoService._getClaimsFromJwt: No key matching kid or alg found in signing keys\"),Promise.reject(new Error(\"No key matching kid or alg found in signing keys\"));var u=r._settings.client_id,c=r._settings.clockSkew;return o.Log.debug(\"UserInfoService._getClaimsFromJwt: Validaing JWT; using clock skew (in seconds) of: \",c),r._joseUtil.validateJwt(e.responseText,a,t,u,c,void 0,!0).then((function(){return o.Log.debug(\"UserInfoService._getClaimsFromJwt: JWT validation successful\"),n.payload}))}))}))}catch(t){return o.Log.error(\"UserInfoService._getClaimsFromJwt: Error parsing JWT response\",t.message),void reject(t)}},t.prototype._filterByAlg=function t(e,r){var n=null;if(r.startsWith(\"RS\"))n=\"RSA\";else if(r.startsWith(\"PS\"))n=\"PS\";else{if(!r.startsWith(\"ES\"))return o.Log.debug(\"UserInfoService._filterByAlg: alg not supported: \",r),[];n=\"EC\"}return o.Log.debug(\"UserInfoService._filterByAlg: Looking for keys that match kty: \",n),e=e.filter((function(t){return t.kty===n})),o.Log.debug(\"UserInfoService._filterByAlg: Number of keys that match kty: \",n,e.length),e},t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.AllowedSigningAlgs=e.b64tohex=e.hextob64u=e.crypto=e.X509=e.KeyUtil=e.jws=void 0;var n=r(27);e.jws=n.jws,e.KeyUtil=n.KEYUTIL,e.X509=n.X509,e.crypto=n.crypto,e.hextob64u=n.hextob64u,e.b64tohex=n.b64tohex,e.AllowedSigningAlgs=[\"RS256\",\"RS384\",\"RS512\",\"PS256\",\"PS384\",\"PS512\",\"ES256\",\"ES384\",\"ES512\"]},function(t,e,r){\"use strict\";(function(t){Object.defineProperty(e,\"__esModule\",{value:!0});var r,n,i,o,s,a,u,c,h,l,f,g=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t},d={userAgent:!1},p={},v=v||(r=Math,i=(n={}).lib={},o=i.Base=function(){function t(){}return{extend:function e(r){t.prototype=this;var n=new t;return r&&n.mixIn(r),n.hasOwnProperty(\"init\")||(n.init=function(){n.$super.init.apply(this,arguments)}),n.init.prototype=n,n.$super=this,n},create:function t(){var e=this.extend();return e.init.apply(e,arguments),e},init:function t(){},mixIn:function t(e){for(var r in e)e.hasOwnProperty(r)&&(this[r]=e[r]);e.hasOwnProperty(\"toString\")&&(this.toString=e.toString)},clone:function t(){return this.init.prototype.extend(this)}}}(),s=i.WordArray=o.extend({init:function t(e,r){e=this.words=e||[],this.sigBytes=null!=r?r:4*e.length},toString:function t(e){return(e||u).stringify(this)},concat:function t(e){var r=this.words,n=e.words,i=this.sigBytes,o=e.sigBytes;if(this.clamp(),i%4)for(var s=0;s>>2]>>>24-s%4*8&255;r[i+s>>>2]|=a<<24-(i+s)%4*8}else for(s=0;s>>2]=n[s>>>2];return this.sigBytes+=o,this},clamp:function t(){var e=this.words,n=this.sigBytes;e[n>>>2]&=4294967295<<32-n%4*8,e.length=r.ceil(n/4)},clone:function t(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function t(e){for(var n=[],i=0;i>>2]>>>24-o%4*8&255;i.push((s>>>4).toString(16)),i.push((15&s).toString(16))}return i.join(\"\")},parse:function t(e){for(var r=e.length,n=[],i=0;i>>3]|=parseInt(e.substr(i,2),16)<<24-i%8*4;return new s.init(n,r/2)}},c=a.Latin1={stringify:function t(e){for(var r=e.words,n=e.sigBytes,i=[],o=0;o>>2]>>>24-o%4*8&255;i.push(String.fromCharCode(s))}return i.join(\"\")},parse:function t(e){for(var r=e.length,n=[],i=0;i>>2]|=(255&e.charCodeAt(i))<<24-i%4*8;return new s.init(n,r)}},h=a.Utf8={stringify:function t(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(t){throw new Error(\"Malformed UTF-8 data\")}},parse:function t(e){return c.parse(unescape(encodeURIComponent(e)))}},l=i.BufferedBlockAlgorithm=o.extend({reset:function t(){this._data=new s.init,this._nDataBytes=0},_append:function t(e){\"string\"==typeof e&&(e=h.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function t(e){var n=this._data,i=n.words,o=n.sigBytes,a=this.blockSize,u=o/(4*a),c=(u=e?r.ceil(u):r.max((0|u)-this._minBufferSize,0))*a,h=r.min(4*c,o);if(c){for(var l=0;l>>2]>>>24-o%4*8&255)<<16|(r[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|r[o+2>>>2]>>>24-(o+2)%4*8&255,a=0;4>a&&o+.75*a>>6*(3-a)&63));if(r=i.charAt(64))for(;e.length%4;)e.push(r);return e.join(\"\")},parse:function t(r){var n=r.length,i=this._map;(o=i.charAt(64))&&(-1!=(o=r.indexOf(o))&&(n=o));for(var o=[],s=0,a=0;a>>6-a%4*2;o[s>>>2]|=(u|c)<<24-s%4*8,s++}return e.create(o,s)},_map:\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\"}}(),function(t){for(var e=v,r=(i=e.lib).WordArray,n=i.Hasher,i=e.algo,o=[],s=[],a=function t(e){return 4294967296*(e-(0|e))|0},u=2,c=0;64>c;){var h;t:{h=u;for(var l=t.sqrt(h),f=2;f<=l;f++)if(!(h%f)){h=!1;break t}h=!0}h&&(8>c&&(o[c]=a(t.pow(u,.5))),s[c]=a(t.pow(u,1/3)),c++),u++}var g=[];i=i.SHA256=n.extend({_doReset:function t(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function t(e,r){for(var n=this._hash.words,i=n[0],o=n[1],a=n[2],u=n[3],c=n[4],h=n[5],l=n[6],f=n[7],d=0;64>d;d++){if(16>d)g[d]=0|e[r+d];else{var p=g[d-15],v=g[d-2];g[d]=((p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3)+g[d-7]+((v<<15|v>>>17)^(v<<13|v>>>19)^v>>>10)+g[d-16]}p=f+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&h^~c&l)+s[d]+g[d],v=((i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22))+(i&o^i&a^o&a),f=l,l=h,h=c,c=u+p|0,u=a,a=o,o=i,i=p+v|0}n[0]=n[0]+i|0,n[1]=n[1]+o|0,n[2]=n[2]+a|0,n[3]=n[3]+u|0,n[4]=n[4]+c|0,n[5]=n[5]+h|0,n[6]=n[6]+l|0,n[7]=n[7]+f|0},_doFinalize:function e(){var r=this._data,n=r.words,i=8*this._nDataBytes,o=8*r.sigBytes;return n[o>>>5]|=128<<24-o%32,n[14+(o+64>>>9<<4)]=t.floor(i/4294967296),n[15+(o+64>>>9<<4)]=i,r.sigBytes=4*n.length,this._process(),this._hash},clone:function t(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA256=n._createHelper(i),e.HmacSHA256=n._createHmacHelper(i)}(Math),function(){function t(){return n.create.apply(n,arguments)}for(var e=v,r=e.lib.Hasher,n=(o=e.x64).Word,i=o.WordArray,o=e.algo,s=[t(1116352408,3609767458),t(1899447441,602891725),t(3049323471,3964484399),t(3921009573,2173295548),t(961987163,4081628472),t(1508970993,3053834265),t(2453635748,2937671579),t(2870763221,3664609560),t(3624381080,2734883394),t(310598401,1164996542),t(607225278,1323610764),t(1426881987,3590304994),t(1925078388,4068182383),t(2162078206,991336113),t(2614888103,633803317),t(3248222580,3479774868),t(3835390401,2666613458),t(4022224774,944711139),t(264347078,2341262773),t(604807628,2007800933),t(770255983,1495990901),t(1249150122,1856431235),t(1555081692,3175218132),t(1996064986,2198950837),t(2554220882,3999719339),t(2821834349,766784016),t(2952996808,2566594879),t(3210313671,3203337956),t(3336571891,1034457026),t(3584528711,2466948901),t(113926993,3758326383),t(338241895,168717936),t(666307205,1188179964),t(773529912,1546045734),t(1294757372,1522805485),t(1396182291,2643833823),t(1695183700,2343527390),t(1986661051,1014477480),t(2177026350,1206759142),t(2456956037,344077627),t(2730485921,1290863460),t(2820302411,3158454273),t(3259730800,3505952657),t(3345764771,106217008),t(3516065817,3606008344),t(3600352804,1432725776),t(4094571909,1467031594),t(275423344,851169720),t(430227734,3100823752),t(506948616,1363258195),t(659060556,3750685593),t(883997877,3785050280),t(958139571,3318307427),t(1322822218,3812723403),t(1537002063,2003034995),t(1747873779,3602036899),t(1955562222,1575990012),t(2024104815,1125592928),t(2227730452,2716904306),t(2361852424,442776044),t(2428436474,593698344),t(2756734187,3733110249),t(3204031479,2999351573),t(3329325298,3815920427),t(3391569614,3928383900),t(3515267271,566280711),t(3940187606,3454069534),t(4118630271,4000239992),t(116418474,1914138554),t(174292421,2731055270),t(289380356,3203993006),t(460393269,320620315),t(685471733,587496836),t(852142971,1086792851),t(1017036298,365543100),t(1126000580,2618297676),t(1288033470,3409855158),t(1501505948,4234509866),t(1607167915,987167468),t(1816402316,1246189591)],a=[],u=0;80>u;u++)a[u]=t();o=o.SHA512=r.extend({_doReset:function t(){this._hash=new i.init([new n.init(1779033703,4089235720),new n.init(3144134277,2227873595),new n.init(1013904242,4271175723),new n.init(2773480762,1595750129),new n.init(1359893119,2917565137),new n.init(2600822924,725511199),new n.init(528734635,4215389547),new n.init(1541459225,327033209)])},_doProcessBlock:function t(e,r){for(var n=(f=this._hash.words)[0],i=f[1],o=f[2],u=f[3],c=f[4],h=f[5],l=f[6],f=f[7],g=n.high,d=n.low,p=i.high,v=i.low,y=o.high,m=o.low,_=u.high,S=u.low,b=c.high,w=c.low,F=h.high,E=h.low,x=l.high,A=l.low,k=f.high,P=f.low,C=g,T=d,R=p,I=v,D=y,L=m,N=_,U=S,B=b,O=w,j=F,M=E,H=x,V=A,K=k,q=P,J=0;80>J;J++){var W=a[J];if(16>J)var z=W.high=0|e[r+2*J],Y=W.low=0|e[r+2*J+1];else{z=((Y=(z=a[J-15]).high)>>>1|(G=z.low)<<31)^(Y>>>8|G<<24)^Y>>>7;var G=(G>>>1|Y<<31)^(G>>>8|Y<<24)^(G>>>7|Y<<25),X=((Y=(X=a[J-2]).high)>>>19|($=X.low)<<13)^(Y<<3|$>>>29)^Y>>>6,$=($>>>19|Y<<13)^($<<3|Y>>>29)^($>>>6|Y<<26),Q=(Y=a[J-7]).high,Z=(tt=a[J-16]).high,tt=tt.low;z=(z=(z=z+Q+((Y=G+Y.low)>>>0>>0?1:0))+X+((Y=Y+$)>>>0<$>>>0?1:0))+Z+((Y=Y+tt)>>>0>>0?1:0);W.high=z,W.low=Y}Q=B&j^~B&H,tt=O&M^~O&V,W=C&R^C&D^R&D;var et=T&I^T&L^I&L,rt=(G=(C>>>28|T<<4)^(C<<30|T>>>2)^(C<<25|T>>>7),X=(T>>>28|C<<4)^(T<<30|C>>>2)^(T<<25|C>>>7),($=s[J]).high),nt=$.low;Z=K+((B>>>14|O<<18)^(B>>>18|O<<14)^(B<<23|O>>>9))+(($=q+((O>>>14|B<<18)^(O>>>18|B<<14)^(O<<23|B>>>9)))>>>0>>0?1:0),K=H,q=V,H=j,V=M,j=B,M=O,B=N+(Z=(Z=(Z=Z+Q+(($=$+tt)>>>0>>0?1:0))+rt+(($=$+nt)>>>0>>0?1:0))+z+(($=$+Y)>>>0>>0?1:0))+((O=U+$|0)>>>0>>0?1:0)|0,N=D,U=L,D=R,L=I,R=C,I=T,C=Z+(W=G+W+((Y=X+et)>>>0>>0?1:0))+((T=$+Y|0)>>>0<$>>>0?1:0)|0}d=n.low=d+T,n.high=g+C+(d>>>0>>0?1:0),v=i.low=v+I,i.high=p+R+(v>>>0>>0?1:0),m=o.low=m+L,o.high=y+D+(m>>>0>>0?1:0),S=u.low=S+U,u.high=_+N+(S>>>0>>0?1:0),w=c.low=w+O,c.high=b+B+(w>>>0>>0?1:0),E=h.low=E+M,h.high=F+j+(E>>>0>>0?1:0),A=l.low=A+V,l.high=x+H+(A>>>0>>0?1:0),P=f.low=P+q,f.high=k+K+(P>>>0>>0?1:0)},_doFinalize:function t(){var e=this._data,r=e.words,n=8*this._nDataBytes,i=8*e.sigBytes;return r[i>>>5]|=128<<24-i%32,r[30+(i+128>>>10<<5)]=Math.floor(n/4294967296),r[31+(i+128>>>10<<5)]=n,e.sigBytes=4*r.length,this._process(),this._hash.toX32()},clone:function t(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32}),e.SHA512=r._createHelper(o),e.HmacSHA512=r._createHmacHelper(o)}(),function(){var t=v,e=(i=t.x64).Word,r=i.WordArray,n=(i=t.algo).SHA512,i=i.SHA384=n.extend({_doReset:function t(){this._hash=new r.init([new e.init(3418070365,3238371032),new e.init(1654270250,914150663),new e.init(2438529370,812702999),new e.init(355462360,4144912697),new e.init(1731405415,4290775857),new e.init(2394180231,1750603025),new e.init(3675008525,1694076839),new e.init(1203062813,3204075428)])},_doFinalize:function t(){var e=n._doFinalize.call(this);return e.sigBytes-=16,e}});t.SHA384=n._createHelper(i),t.HmacSHA384=n._createHmacHelper(i)}();\n/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\nvar y,m=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";function _(t){var e,r,n=\"\";for(e=0;e+3<=t.length;e+=3)r=parseInt(t.substring(e,e+3),16),n+=m.charAt(r>>6)+m.charAt(63&r);for(e+1==t.length?(r=parseInt(t.substring(e,e+1),16),n+=m.charAt(r<<2)):e+2==t.length&&(r=parseInt(t.substring(e,e+2),16),n+=m.charAt(r>>2)+m.charAt((3&r)<<4)),\"=\";(3&n.length)>0;)n+=\"=\";return n}function S(t){var e,r,n,i=\"\",o=0;for(e=0;e>2),r=3&n,o=1):1==o?(i+=T(r<<2|n>>4),r=15&n,o=2):2==o?(i+=T(r),i+=T(n>>2),r=3&n,o=3):(i+=T(r<<2|n>>4),i+=T(15&n),o=0));return 1==o&&(i+=T(r<<2)),i}function b(t){var e,r=S(t),n=new Array;for(e=0;2*e>15;--o>=0;){var u=32767&this[t],c=this[t++]>>15,h=a*u+c*s;i=((u=s*u+((32767&h)<<15)+r[n]+(1073741823&i))>>>30)+(h>>>15)+a*c+(i>>>30),r[n++]=1073741823&u}return i},y=30):\"Netscape\"!=d.appName?(w.prototype.am=function x(t,e,r,n,i,o){for(;--o>=0;){var s=e*this[t++]+r[n]+i;i=Math.floor(s/67108864),r[n++]=67108863&s}return i},y=26):(w.prototype.am=function A(t,e,r,n,i,o){for(var s=16383&e,a=e>>14;--o>=0;){var u=16383&this[t],c=this[t++]>>14,h=a*u+c*s;i=((u=s*u+((16383&h)<<14)+r[n]+i)>>28)+(h>>14)+a*c,r[n++]=268435455&u}return i},y=28),w.prototype.DB=y,w.prototype.DM=(1<>>16)&&(t=e,r+=16),0!=(e=t>>8)&&(t=e,r+=8),0!=(e=t>>4)&&(t=e,r+=4),0!=(e=t>>2)&&(t=e,r+=2),0!=(e=t>>1)&&(t=e,r+=1),r}function L(t){this.m=t}function N(t){this.m=t,this.mp=t.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,e+=16),0==(255&t)&&(t>>=8,e+=8),0==(15&t)&&(t>>=4,e+=4),0==(3&t)&&(t>>=2,e+=2),0==(1&t)&&++e,e}function H(t){for(var e=0;0!=t;)t&=t-1,++e;return e}function V(){}function K(t){return t}function q(t){this.r2=F(),this.q3=F(),w.ONE.dlShiftTo(2*t.t,this.r2),this.mu=this.r2.divide(t),this.m=t}L.prototype.convert=function J(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t},L.prototype.revert=function W(t){return t},L.prototype.reduce=function z(t){t.divRemTo(this.m,null,t)},L.prototype.mulTo=function Y(t,e,r){t.multiplyTo(e,r),this.reduce(r)},L.prototype.sqrTo=function G(t,e){t.squareTo(e),this.reduce(e)},N.prototype.convert=function X(t){var e=F();return t.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),t.s<0&&e.compareTo(w.ZERO)>0&&this.m.subTo(e,e),e},N.prototype.revert=function $(t){var e=F();return t.copyTo(e),this.reduce(e),e},N.prototype.reduce=function Q(t){for(;t.t<=this.mt2;)t[t.t++]=0;for(var e=0;e>15)*this.mpl&this.um)<<15)&t.DM;for(t[r=e+this.m.t]+=this.m.am(0,n,t,e,0,this.m.t);t[r]>=t.DV;)t[r]-=t.DV,t[++r]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)},N.prototype.mulTo=function Z(t,e,r){t.multiplyTo(e,r),this.reduce(r)},N.prototype.sqrTo=function tt(t,e){t.squareTo(e),this.reduce(e)},w.prototype.copyTo=function et(t){for(var e=this.t-1;e>=0;--e)t[e]=this[e];t.t=this.t,t.s=this.s},w.prototype.fromInt=function rt(t){this.t=1,this.s=t<0?-1:0,t>0?this[0]=t:t<-1?this[0]=t+this.DV:this.t=0},w.prototype.fromString=function nt(t,e){var r;if(16==e)r=4;else if(8==e)r=3;else if(256==e)r=8;else if(2==e)r=1;else if(32==e)r=5;else{if(4!=e)return void this.fromRadix(t,e);r=2}this.t=0,this.s=0;for(var n=t.length,i=!1,o=0;--n>=0;){var s=8==r?255&t[n]:R(t,n);s<0?\"-\"==t.charAt(n)&&(i=!0):(i=!1,0==o?this[this.t++]=s:o+r>this.DB?(this[this.t-1]|=(s&(1<>this.DB-o):this[this.t-1]|=s<=this.DB&&(o-=this.DB))}8==r&&0!=(128&t[0])&&(this.s=-1,o>0&&(this[this.t-1]|=(1<0&&this[this.t-1]==t;)--this.t},w.prototype.dlShiftTo=function ot(t,e){var r;for(r=this.t-1;r>=0;--r)e[r+t]=this[r];for(r=t-1;r>=0;--r)e[r]=0;e.t=this.t+t,e.s=this.s},w.prototype.drShiftTo=function st(t,e){for(var r=t;r=0;--r)e[r+s+1]=this[r]>>i|a,a=(this[r]&o)<=0;--r)e[r]=0;e[s]=a,e.t=this.t+s+1,e.s=this.s,e.clamp()},w.prototype.rShiftTo=function ut(t,e){e.s=this.s;var r=Math.floor(t/this.DB);if(r>=this.t)e.t=0;else{var n=t%this.DB,i=this.DB-n,o=(1<>n;for(var s=r+1;s>n;n>0&&(e[this.t-r-1]|=(this.s&o)<>=this.DB;if(t.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=t.s}e.s=n<0?-1:0,n<-1?e[r++]=this.DV+n:n>0&&(e[r++]=n),e.t=r,e.clamp()},w.prototype.multiplyTo=function ht(t,e){var r=this.abs(),n=t.abs(),i=r.t;for(e.t=i+n.t;--i>=0;)e[i]=0;for(i=0;i=0;)t[r]=0;for(r=0;r=e.DV&&(t[r+e.t]-=e.DV,t[r+e.t+1]=1)}t.t>0&&(t[t.t-1]+=e.am(r,e[r],t,2*r,0,1)),t.s=0,t.clamp()},w.prototype.divRemTo=function ft(t,e,r){var n=t.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(u,o),i.lShiftTo(u,r)):(n.copyTo(o),i.copyTo(r));var c=o.t,h=o[c-1];if(0!=h){var l=h*(1<1?o[c-2]>>this.F2:0),f=this.FV/l,g=(1<=0&&(r[r.t++]=1,r.subTo(y,r)),w.ONE.dlShiftTo(c,y),y.subTo(o,o);o.t=0;){var m=r[--p]==h?this.DM:Math.floor(r[p]*f+(r[p-1]+d)*g);if((r[p]+=o.am(0,m,r,v,0,c))0&&r.rShiftTo(u,r),s<0&&w.ZERO.subTo(r,r)}}},w.prototype.invDigit=function gt(){if(this.t<1)return 0;var t=this[0];if(0==(1&t))return 0;var e=3&t;return(e=(e=(e=(e=e*(2-(15&t)*e)&15)*(2-(255&t)*e)&255)*(2-((65535&t)*e&65535))&65535)*(2-t*e%this.DV)%this.DV)>0?this.DV-e:-e},w.prototype.isEven=function dt(){return 0==(this.t>0?1&this[0]:this.s)},w.prototype.exp=function pt(t,e){if(t>4294967295||t<1)return w.ONE;var r=F(),n=F(),i=e.convert(this),o=D(t)-1;for(i.copyTo(r);--o>=0;)if(e.sqrTo(r,n),(t&1<0)e.mulTo(n,i,r);else{var s=r;r=n,n=s}return e.revert(r)},w.prototype.toString=function vt(t){if(this.s<0)return\"-\"+this.negate().toString(t);var e;if(16==t)e=4;else if(8==t)e=3;else if(2==t)e=1;else if(32==t)e=5;else{if(4!=t)return this.toRadix(t);e=2}var r,n=(1<0)for(a>a)>0&&(i=!0,o=T(r));s>=0;)a>(a+=this.DB-e)):(r=this[s]>>(a-=e)&n,a<=0&&(a+=this.DB,--s)),r>0&&(i=!0),i&&(o+=T(r));return i?o:\"0\"},w.prototype.negate=function yt(){var t=F();return w.ZERO.subTo(this,t),t},w.prototype.abs=function mt(){return this.s<0?this.negate():this},w.prototype.compareTo=function _t(t){var e=this.s-t.s;if(0!=e)return e;var r=this.t;if(0!=(e=r-t.t))return this.s<0?-e:e;for(;--r>=0;)if(0!=(e=this[r]-t[r]))return e;return 0},w.prototype.bitLength=function St(){return this.t<=0?0:this.DB*(this.t-1)+D(this[this.t-1]^this.s&this.DM)},w.prototype.mod=function bt(t){var e=F();return this.abs().divRemTo(t,null,e),this.s<0&&e.compareTo(w.ZERO)>0&&t.subTo(e,e),e},w.prototype.modPowInt=function wt(t,e){var r;return r=t<256||e.isEven()?new L(e):new N(e),this.exp(t,r)},w.ZERO=I(0),w.ONE=I(1),V.prototype.convert=K,V.prototype.revert=K,V.prototype.mulTo=function Ft(t,e,r){t.multiplyTo(e,r)},V.prototype.sqrTo=function Et(t,e){t.squareTo(e)},q.prototype.convert=function xt(t){if(t.s<0||t.t>2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;var e=F();return t.copyTo(e),this.reduce(e),e},q.prototype.revert=function At(t){return t},q.prototype.reduce=function kt(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)},q.prototype.mulTo=function Pt(t,e,r){t.multiplyTo(e,r),this.reduce(r)},q.prototype.sqrTo=function Ct(t,e){t.squareTo(e),this.reduce(e)};var Tt=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],Rt=(1<<26)/Tt[Tt.length-1];\n/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\nfunction It(){this.i=0,this.j=0,this.S=new Array}w.prototype.chunkSize=function Dt(t){return Math.floor(Math.LN2*this.DB/Math.log(t))},w.prototype.toRadix=function Lt(t){if(null==t&&(t=10),0==this.signum()||t<2||t>36)return\"0\";var e=this.chunkSize(t),r=Math.pow(t,e),n=I(r),i=F(),o=F(),s=\"\";for(this.divRemTo(n,i,o);i.signum()>0;)s=(r+o.intValue()).toString(t).substr(1)+s,i.divRemTo(n,i,o);return o.intValue().toString(t)+s},w.prototype.fromRadix=function Nt(t,e){this.fromInt(0),null==e&&(e=10);for(var r=this.chunkSize(e),n=Math.pow(e,r),i=!1,o=0,s=0,a=0;a=r&&(this.dMultiply(n),this.dAddOffset(s,0),o=0,s=0))}o>0&&(this.dMultiply(Math.pow(e,o)),this.dAddOffset(s,0)),i&&w.ZERO.subTo(this,this)},w.prototype.fromNumber=function Ut(t,e,r){if(\"number\"==typeof e)if(t<2)this.fromInt(1);else for(this.fromNumber(t,r),this.testBit(t-1)||this.bitwiseTo(w.ONE.shiftLeft(t-1),B,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(e);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(w.ONE.shiftLeft(t-1),this);else{var n=new Array,i=7&t;n.length=1+(t>>3),e.nextBytes(n),i>0?n[0]&=(1<>=this.DB;if(t.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=t.s}e.s=n<0?-1:0,n>0?e[r++]=n:n<-1&&(e[r++]=this.DV+n),e.t=r,e.clamp()},w.prototype.dMultiply=function Mt(t){this[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()},w.prototype.dAddOffset=function Ht(t,e){if(0!=t){for(;this.t<=e;)this[this.t++]=0;for(this[e]+=t;this[e]>=this.DV;)this[e]-=this.DV,++e>=this.t&&(this[this.t++]=0),++this[e]}},w.prototype.multiplyLowerTo=function Vt(t,e,r){var n,i=Math.min(this.t+t.t,e);for(r.s=0,r.t=i;i>0;)r[--i]=0;for(n=r.t-this.t;i=0;)r[n]=0;for(n=Math.max(e-this.t,0);n0)if(0==e)r=this[0]%t;else for(var n=this.t-1;n>=0;--n)r=(e*r+this[n])%t;return r},w.prototype.millerRabin=function Jt(t){var e=this.subtract(w.ONE),r=e.getLowestSetBit();if(r<=0)return!1;var n=e.shiftRight(r);(t=t+1>>1)>Tt.length&&(t=Tt.length);for(var i=F(),o=0;o>24},w.prototype.shortValue=function Gt(){return 0==this.t?this.s:this[0]<<16>>16},w.prototype.signum=function Xt(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},w.prototype.toByteArray=function $t(){var t=this.t,e=new Array;e[0]=this.s;var r,n=this.DB-t*this.DB%8,i=0;if(t-- >0)for(n>n)!=(this.s&this.DM)>>n&&(e[i++]=r|this.s<=0;)n<8?(r=(this[t]&(1<>(n+=this.DB-8)):(r=this[t]>>(n-=8)&255,n<=0&&(n+=this.DB,--t)),0!=(128&r)&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(e[i++]=r);return e},w.prototype.equals=function Qt(t){return 0==this.compareTo(t)},w.prototype.min=function Zt(t){return this.compareTo(t)<0?this:t},w.prototype.max=function te(t){return this.compareTo(t)>0?this:t},w.prototype.and=function ee(t){var e=F();return this.bitwiseTo(t,U,e),e},w.prototype.or=function re(t){var e=F();return this.bitwiseTo(t,B,e),e},w.prototype.xor=function ne(t){var e=F();return this.bitwiseTo(t,O,e),e},w.prototype.andNot=function ie(t){var e=F();return this.bitwiseTo(t,j,e),e},w.prototype.not=function oe(){for(var t=F(),e=0;e=this.t?0!=this.s:0!=(this[e]&1<1){var h=F();for(n.sqrTo(s[1],h);a<=c;)s[a]=F(),n.mulTo(h,s[a-2],s[a]),a+=2}var l,f,g=t.t-1,d=!0,p=F();for(i=D(t[g])-1;g>=0;){for(i>=u?l=t[g]>>i-u&c:(l=(t[g]&(1<0&&(l|=t[g-1]>>this.DB+i-u)),a=r;0==(1&l);)l>>=1,--a;if((i-=a)<0&&(i+=this.DB,--g),d)s[l].copyTo(o),d=!1;else{for(;a>1;)n.sqrTo(o,p),n.sqrTo(p,o),a-=2;a>0?n.sqrTo(o,p):(f=o,o=p,p=f),n.mulTo(p,s[l],o)}for(;g>=0&&0==(t[g]&1<=0?(r.subTo(n,r),e&&i.subTo(s,i),o.subTo(a,o)):(n.subTo(r,n),e&&s.subTo(i,s),a.subTo(o,a))}return 0!=n.compareTo(w.ONE)?w.ZERO:a.compareTo(t)>=0?a.subtract(t):a.signum()<0?(a.addTo(t,a),a.signum()<0?a.add(t):a):a},w.prototype.pow=function we(t){return this.exp(t,new V)},w.prototype.gcd=function Fe(t){var e=this.s<0?this.negate():this.clone(),r=t.s<0?t.negate():t.clone();if(e.compareTo(r)<0){var n=e;e=r,r=n}var i=e.getLowestSetBit(),o=r.getLowestSetBit();if(o<0)return e;for(i0&&(e.rShiftTo(o,e),r.rShiftTo(o,r));e.signum()>0;)(i=e.getLowestSetBit())>0&&e.rShiftTo(i,e),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),e.compareTo(r)>=0?(e.subTo(r,e),e.rShiftTo(1,e)):(r.subTo(e,r),r.rShiftTo(1,r));return o>0&&r.lShiftTo(o,r),r},w.prototype.isProbablePrime=function Ee(t){var e,r=this.abs();if(1==r.t&&r[0]<=Tt[Tt.length-1]){for(e=0;e>8&255,Ce[Te++]^=e>>16&255,Ce[Te++]^=e>>24&255,Te>=256&&(Te-=256)}((new Date).getTime())}if(null==Ce){var Ie;if(Ce=new Array,Te=0,void 0!==p&&(void 0!==p.crypto||void 0!==p.msCrypto)){var De=p.crypto||p.msCrypto;if(De.getRandomValues){var Le=new Uint8Array(32);for(De.getRandomValues(Le),Ie=0;Ie<32;++Ie)Ce[Te++]=Le[Ie]}else if(\"Netscape\"==d.appName&&d.appVersion<\"5\"){var Ne=p.crypto.random(32);for(Ie=0;Ie>>8,Ce[Te++]=255&Ie;Te=0,Re()}function Ue(){if(null==Pe){for(Re(),(Pe=function t(){return new It}()).init(Ce),Te=0;Te>24,(16711680&i)>>16,(65280&i)>>8,255&i]))),i+=1;return n}function Me(){this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null}\n/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\nfunction He(t,e){this.x=e,this.q=t}function Ve(t,e,r,n){this.curve=t,this.x=e,this.y=r,this.z=null==n?w.ONE:n,this.zinv=null}function Ke(t,e,r){this.q=t,this.a=this.fromBigInteger(e),this.b=this.fromBigInteger(r),this.infinity=new Ve(this,null,null)}Be.prototype.nextBytes=function qe(t){var e;for(e=0;e0&&e.length>0))throw\"Invalid RSA public key\";this.n=Oe(t,16),this.e=parseInt(e,16)}},Me.prototype.encrypt=function ze(t){var e=function r(t,e){if(e=0&&e>0;){var i=t.charCodeAt(n--);i<128?r[--e]=i:i>127&&i<2048?(r[--e]=63&i|128,r[--e]=i>>6|192):(r[--e]=63&i|128,r[--e]=i>>6&63|128,r[--e]=i>>12|224)}r[--e]=0;for(var o=new Be,s=new Array;e>2;){for(s[0]=0;0==s[0];)o.nextBytes(s);r[--e]=s[0]}return r[--e]=2,r[--e]=0,new w(r)}(t,this.n.bitLength()+7>>3);if(null==e)return null;var n=this.doPublic(e);if(null==n)return null;var i=n.toString(16);return 0==(1&i.length)?i:\"0\"+i},Me.prototype.encryptOAEP=function Ye(t,e,r){var n=function i(t,e,r,n){var i=Sr.crypto.MessageDigest,o=Sr.crypto.Util,s=null;if(r||(r=\"sha1\"),\"string\"==typeof r&&(s=i.getCanonicalAlgName(r),n=i.getHashLength(s),r=function t(e){return Lr(o.hashHex(Nr(e),s))}),t.length+2*n+2>e)throw\"Message too long for RSA\";var a,u=\"\";for(a=0;a>3,e,r);if(null==n)return null;var o=this.doPublic(n);if(null==o)return null;var s=o.toString(16);return 0==(1&s.length)?s:\"0\"+s},Me.prototype.type=\"RSA\",He.prototype.equals=function Ge(t){return t==this||this.q.equals(t.q)&&this.x.equals(t.x)},He.prototype.toBigInteger=function Xe(){return this.x},He.prototype.negate=function $e(){return new He(this.q,this.x.negate().mod(this.q))},He.prototype.add=function Qe(t){return new He(this.q,this.x.add(t.toBigInteger()).mod(this.q))},He.prototype.subtract=function Ze(t){return new He(this.q,this.x.subtract(t.toBigInteger()).mod(this.q))},He.prototype.multiply=function tr(t){return new He(this.q,this.x.multiply(t.toBigInteger()).mod(this.q))},He.prototype.square=function er(){return new He(this.q,this.x.square().mod(this.q))},He.prototype.divide=function rr(t){return new He(this.q,this.x.multiply(t.toBigInteger().modInverse(this.q)).mod(this.q))},Ve.prototype.getX=function nr(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))},Ve.prototype.getY=function ir(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))},Ve.prototype.equals=function or(t){return t==this||(this.isInfinity()?t.isInfinity():t.isInfinity()?this.isInfinity():!!t.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(t.z)).mod(this.curve.q).equals(w.ZERO)&&t.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(t.z)).mod(this.curve.q).equals(w.ZERO))},Ve.prototype.isInfinity=function sr(){return null==this.x&&null==this.y||this.z.equals(w.ZERO)&&!this.y.toBigInteger().equals(w.ZERO)},Ve.prototype.negate=function ar(){return new Ve(this.curve,this.x,this.y.negate(),this.z)},Ve.prototype.add=function ur(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(t.z)).mod(this.curve.q),r=t.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(t.z)).mod(this.curve.q);if(w.ZERO.equals(r))return w.ZERO.equals(e)?this.twice():this.curve.getInfinity();var n=new w(\"3\"),i=this.x.toBigInteger(),o=this.y.toBigInteger(),s=(t.x.toBigInteger(),t.y.toBigInteger(),r.square()),a=s.multiply(r),u=i.multiply(s),c=e.square().multiply(this.z),h=c.subtract(u.shiftLeft(1)).multiply(t.z).subtract(a).multiply(r).mod(this.curve.q),l=u.multiply(n).multiply(e).subtract(o.multiply(a)).subtract(c.multiply(e)).multiply(t.z).add(e.multiply(a)).mod(this.curve.q),f=a.multiply(this.z).multiply(t.z).mod(this.curve.q);return new Ve(this.curve,this.curve.fromBigInteger(h),this.curve.fromBigInteger(l),f)},Ve.prototype.twice=function cr(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var t=new w(\"3\"),e=this.x.toBigInteger(),r=this.y.toBigInteger(),n=r.multiply(this.z),i=n.multiply(r).mod(this.curve.q),o=this.curve.a.toBigInteger(),s=e.square().multiply(t);w.ZERO.equals(o)||(s=s.add(this.z.square().multiply(o)));var a=(s=s.mod(this.curve.q)).square().subtract(e.shiftLeft(3).multiply(i)).shiftLeft(1).multiply(n).mod(this.curve.q),u=s.multiply(t).multiply(e).subtract(i.shiftLeft(1)).shiftLeft(2).multiply(i).subtract(s.square().multiply(s)).mod(this.curve.q),c=n.square().multiply(n).shiftLeft(3).mod(this.curve.q);return new Ve(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(u),c)},Ve.prototype.multiply=function hr(t){if(this.isInfinity())return this;if(0==t.signum())return this.curve.getInfinity();var e,r=t,n=r.multiply(new w(\"3\")),i=this.negate(),o=this,s=this.curve.q.subtract(t),a=s.multiply(new w(\"3\")),u=new Ve(this.curve,this.x,this.y),c=u.negate();for(e=n.bitLength()-2;e>0;--e){o=o.twice();var h=n.testBit(e);h!=r.testBit(e)&&(o=o.add(h?this:i))}for(e=a.bitLength()-2;e>0;--e){u=u.twice();var l=a.testBit(e);l!=s.testBit(e)&&(u=u.add(l?u:c))}return o},Ve.prototype.multiplyTwo=function lr(t,e,r){var n;n=t.bitLength()>r.bitLength()?t.bitLength()-1:r.bitLength()-1;for(var i=this.curve.getInfinity(),o=this.add(e);n>=0;)i=i.twice(),t.testBit(n)?i=r.testBit(n)?i.add(o):i.add(this):r.testBit(n)&&(i=i.add(e)),--n;return i},Ke.prototype.getQ=function fr(){return this.q},Ke.prototype.getA=function gr(){return this.a},Ke.prototype.getB=function dr(){return this.b},Ke.prototype.equals=function pr(t){return t==this||this.q.equals(t.q)&&this.a.equals(t.a)&&this.b.equals(t.b)},Ke.prototype.getInfinity=function vr(){return this.infinity},Ke.prototype.fromBigInteger=function yr(t){return new He(this.q,t)},Ke.prototype.decodePointHex=function mr(t){switch(parseInt(t.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:return null;case 4:case 6:case 7:var e=(t.length-2)/2,r=t.substr(2,e),n=t.substr(e+2,e);return new Ve(this,this.fromBigInteger(new w(r,16)),this.fromBigInteger(new w(n,16)));default:return null}},\n/*! (c) Stefan Thomas | https://github.com/bitcoinjs/bitcoinjs-lib\n */\nHe.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)},Ve.prototype.getEncoded=function(t){var e=function t(e,r){var n=e.toByteArrayUnsigned();if(rn.length;)n.unshift(0);return n},r=this.getX().toBigInteger(),n=this.getY().toBigInteger(),i=e(r,32);return t?n.isEven()?i.unshift(2):i.unshift(3):(i.unshift(4),i=i.concat(e(n,32))),i},Ve.decodeFrom=function(t,e){e[0];var r=e.length-1,n=e.slice(1,1+r/2),i=e.slice(1+r/2,1+r);n.unshift(0),i.unshift(0);var o=new w(n),s=new w(i);return new Ve(t,t.fromBigInteger(o),t.fromBigInteger(s))},Ve.decodeFromHex=function(t,e){e.substr(0,2);var r=e.length-2,n=e.substr(2,r/2),i=e.substr(2+r/2,r/2),o=new w(n,16),s=new w(i,16);return new Ve(t,t.fromBigInteger(o),t.fromBigInteger(s))},Ve.prototype.add2D=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;if(this.x.equals(t.x))return this.y.equals(t.y)?this.twice():this.curve.getInfinity();var e=t.x.subtract(this.x),r=t.y.subtract(this.y).divide(e),n=r.square().subtract(this.x).subtract(t.x),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new Ve(this.curve,n,i)},Ve.prototype.twice2D=function(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var t=this.curve.fromBigInteger(w.valueOf(2)),e=this.curve.fromBigInteger(w.valueOf(3)),r=this.x.square().multiply(e).add(this.curve.a).divide(this.y.multiply(t)),n=r.square().subtract(this.x.multiply(t)),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new Ve(this.curve,n,i)},Ve.prototype.multiply2D=function(t){if(this.isInfinity())return this;if(0==t.signum())return this.curve.getInfinity();var e,r=t,n=r.multiply(new w(\"3\")),i=this.negate(),o=this;for(e=n.bitLength()-2;e>0;--e){o=o.twice();var s=n.testBit(e);s!=r.testBit(e)&&(o=o.add2D(s?this:i))}return o},Ve.prototype.isOnCurve=function(){var t=this.getX().toBigInteger(),e=this.getY().toBigInteger(),r=this.curve.getA().toBigInteger(),n=this.curve.getB().toBigInteger(),i=this.curve.getQ(),o=e.multiply(e).mod(i),s=t.multiply(t).multiply(t).add(r.multiply(t)).add(n).mod(i);return o.equals(s)},Ve.prototype.toString=function(){return\"(\"+this.getX().toBigInteger().toString()+\",\"+this.getY().toBigInteger().toString()+\")\"},Ve.prototype.validate=function(){var t=this.curve.getQ();if(this.isInfinity())throw new Error(\"Point is at infinity.\");var e=this.getX().toBigInteger(),r=this.getY().toBigInteger();if(e.compareTo(w.ONE)<0||e.compareTo(t.subtract(w.ONE))>0)throw new Error(\"x coordinate out of bounds\");if(r.compareTo(w.ONE)<0||r.compareTo(t.subtract(w.ONE))>0)throw new Error(\"y coordinate out of bounds\");if(!this.isOnCurve())throw new Error(\"Point is not on the curve.\");if(this.multiply(t).isInfinity())throw new Error(\"Point is not a scalar multiple of G.\");return!0};\n/*! Mike Samuel (c) 2009 | code.google.com/p/json-sans-eval\n */\nvar _r=function(){var t=new RegExp('(?:false|true|null|[\\\\{\\\\}\\\\[\\\\]]|(?:-?\\\\b(?:0|[1-9][0-9]*)(?:\\\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\\\b)|(?:\"(?:[^\\\\0-\\\\x08\\\\x0a-\\\\x1f\"\\\\\\\\]|\\\\\\\\(?:[\"/\\\\\\\\bfnrt]|u[0-9A-Fa-f]{4}))*\"))',\"g\"),e=new RegExp(\"\\\\\\\\(?:([^u])|u(.{4}))\",\"g\"),r={'\"':'\"',\"/\":\"/\",\"\\\\\":\"\\\\\",b:\"\\b\",f:\"\\f\",n:\"\\n\",r:\"\\r\",t:\"\\t\"};function n(t,e,n){return e?r[e]:String.fromCharCode(parseInt(n,16))}var i=new String(\"\"),o=Object.hasOwnProperty;return function(r,s){var a,u,c=r.match(t),h=c[0],l=!1;\"{\"===h?a={}:\"[\"===h?a=[]:(a=[],l=!0);for(var f=[a],d=1-l,p=c.length;d=0;)delete n[i[c]]}return s.call(e,r,n)}({\"\":a},\"\")}return a}}();void 0!==Sr&&Sr||(e.KJUR=Sr={}),void 0!==Sr.asn1&&Sr.asn1||(Sr.asn1={}),Sr.asn1.ASN1Util=new function(){this.integerToByteHex=function(t){var e=t.toString(16);return e.length%2==1&&(e=\"0\"+e),e},this.bigIntToMinTwosComplementsHex=function(t){var e=t.toString(16);if(\"-\"!=e.substr(0,1))e.length%2==1?e=\"0\"+e:e.match(/^[0-7]/)||(e=\"00\"+e);else{var r=e.substr(1).length;r%2==1?r+=1:e.match(/^[0-7]/)||(r+=2);for(var n=\"\",i=0;i15)throw\"ASN.1 length too long to represent by 8x: n = \"+t.toString(16);return(128+r).toString(16)+e},this.getEncodedHex=function(){return(null==this.hTLV||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getValueHex=function(){return this.getEncodedHex(),this.hV},this.getFreshValueHex=function(){return\"\"},this.setByParam=function(t){this.params=t},null!=t&&null!=t.tlv&&(this.hTLV=t.tlv,this.isModified=!1)},Sr.asn1.DERAbstractString=function(t){Sr.asn1.DERAbstractString.superclass.constructor.call(this);this.getString=function(){return this.s},this.setString=function(t){this.hTLV=null,this.isModified=!0,this.s=t,this.hV=Ir(this.s).toLowerCase()},this.setStringHex=function(t){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=t},this.getFreshValueHex=function(){return this.hV},void 0!==t&&(\"string\"==typeof t?this.setString(t):void 0!==t.str?this.setString(t.str):void 0!==t.hex&&this.setStringHex(t.hex))},Zr(Sr.asn1.DERAbstractString,Sr.asn1.ASN1Object),Sr.asn1.DERAbstractTime=function(t){Sr.asn1.DERAbstractTime.superclass.constructor.call(this);this.localDateToUTC=function(t){var e=t.getTime()+6e4*t.getTimezoneOffset();return new Date(e)},this.formatDate=function(t,e,r){var n=this.zeroPadding,i=this.localDateToUTC(t),o=String(i.getFullYear());\"utc\"==e&&(o=o.substr(2,2));var s=o+n(String(i.getMonth()+1),2)+n(String(i.getDate()),2)+n(String(i.getHours()),2)+n(String(i.getMinutes()),2)+n(String(i.getSeconds()),2);if(!0===r){var a=i.getMilliseconds();if(0!=a){var u=n(String(a),3);s=s+\".\"+(u=u.replace(/[0]+$/,\"\"))}}return s+\"Z\"},this.zeroPadding=function(t,e){return t.length>=e?t:new Array(e-t.length+1).join(\"0\")+t},this.getString=function(){return this.s},this.setString=function(t){this.hTLV=null,this.isModified=!0,this.s=t,this.hV=kr(t)},this.setByDateValue=function(t,e,r,n,i,o){var s=new Date(Date.UTC(t,e-1,r,n,i,o,0));this.setByDate(s)},this.getFreshValueHex=function(){return this.hV}},Zr(Sr.asn1.DERAbstractTime,Sr.asn1.ASN1Object),Sr.asn1.DERAbstractStructured=function(t){Sr.asn1.DERAbstractString.superclass.constructor.call(this);this.setByASN1ObjectArray=function(t){this.hTLV=null,this.isModified=!0,this.asn1Array=t},this.appendASN1Object=function(t){this.hTLV=null,this.isModified=!0,this.asn1Array.push(t)},this.asn1Array=new Array,void 0!==t&&void 0!==t.array&&(this.asn1Array=t.array)},Zr(Sr.asn1.DERAbstractStructured,Sr.asn1.ASN1Object),Sr.asn1.DERBoolean=function(t){Sr.asn1.DERBoolean.superclass.constructor.call(this),this.hT=\"01\",this.hTLV=0==t?\"010100\":\"0101ff\"},Zr(Sr.asn1.DERBoolean,Sr.asn1.ASN1Object),Sr.asn1.DERInteger=function(t){Sr.asn1.DERInteger.superclass.constructor.call(this),this.hT=\"02\",this.setByBigInteger=function(t){this.hTLV=null,this.isModified=!0,this.hV=Sr.asn1.ASN1Util.bigIntToMinTwosComplementsHex(t)},this.setByInteger=function(t){var e=new w(String(t),10);this.setByBigInteger(e)},this.setValueHex=function(t){this.hV=t},this.getFreshValueHex=function(){return this.hV},void 0!==t&&(void 0!==t.bigint?this.setByBigInteger(t.bigint):void 0!==t.int?this.setByInteger(t.int):\"number\"==typeof t?this.setByInteger(t):void 0!==t.hex&&this.setValueHex(t.hex))},Zr(Sr.asn1.DERInteger,Sr.asn1.ASN1Object),Sr.asn1.DERBitString=function(t){if(void 0!==t&&void 0!==t.obj){var e=Sr.asn1.ASN1Util.newObject(t.obj);t.hex=\"00\"+e.getEncodedHex()}Sr.asn1.DERBitString.superclass.constructor.call(this),this.hT=\"03\",this.setHexValueIncludingUnusedBits=function(t){this.hTLV=null,this.isModified=!0,this.hV=t},this.setUnusedBitsAndHexValue=function(t,e){if(t<0||7i.length&&(i=n[r]);return(t=t.replace(i,\"::\")).slice(1,-1)}function zr(t){var e=\"malformed hex value\";if(!t.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/))throw e;if(8!=t.length)return 32==t.length?Wr(t):t;try{return parseInt(t.substr(0,2),16)+\".\"+parseInt(t.substr(2,2),16)+\".\"+parseInt(t.substr(4,2),16)+\".\"+parseInt(t.substr(6,2),16)}catch(t){throw e}}function Yr(t){return t.match(/.{4}/g).map((function e(t){var e=parseInt(t.substr(0,2),16),r=parseInt(t.substr(2),16);if(0==e&r<128)return String.fromCharCode(r);if(e<8){var n=128|63&r;return Dr((192|(7&e)<<3|(192&r)>>6).toString(16)+n.toString(16))}n=128|(15&e)<<2|(192&r)>>6;var i=128|63&r;return Dr((224|(240&e)>>4).toString(16)+n.toString(16)+i.toString(16))})).join(\"\")}function Gr(t){for(var e=encodeURIComponent(t),r=\"\",n=0;n\"7\"?\"00\"+t:t}Fr.getLblen=function(t,e){if(\"8\"!=t.substr(e+2,1))return 1;var r=parseInt(t.substr(e+3,1));return 0==r?-1:0=n)break}return s},Fr.getNthChildIdx=function(t,e,r){return Fr.getChildIdx(t,e)[r]},Fr.getIdxbyList=function(t,e,r,n){var i,o,s=Fr;return 0==r.length?void 0!==n&&t.substr(e,2)!==n?-1:e:(i=r.shift())>=(o=s.getChildIdx(t,e)).length?-1:s.getIdxbyList(t,o[i],r,n)},Fr.getIdxbyListEx=function(t,e,r,n){var i,o,s=Fr;if(0==r.length)return void 0!==n&&t.substr(e,2)!==n?-1:e;i=r.shift(),o=s.getChildIdx(t,e);for(var a=0,u=0;u=t.length?null:i.getTLV(t,o)},Fr.getTLVbyListEx=function(t,e,r,n){var i=Fr,o=i.getIdxbyListEx(t,e,r,n);return-1==o?null:i.getTLV(t,o)},Fr.getVbyList=function(t,e,r,n,i){var o,s,a=Fr;return-1==(o=a.getIdxbyList(t,e,r,n))||o>=t.length?null:(s=a.getV(t,o),!0===i&&(s=s.substr(2)),s)},Fr.getVbyListEx=function(t,e,r,n,i){var o,s,a=Fr;return-1==(o=a.getIdxbyListEx(t,e,r,n))?null:(s=a.getV(t,o),\"03\"==t.substr(o,2)&&!1!==i&&(s=s.substr(2)),s)},Fr.getInt=function(t,e,r){null==r&&(r=-1);try{var n=t.substr(e,2);if(\"02\"!=n&&\"03\"!=n)return r;var i=Fr.getV(t,e);return\"02\"==n?parseInt(i,16):function o(t){try{var e=t.substr(0,2);if(\"00\"==e)return parseInt(t.substr(2),16);var r=parseInt(e,16),n=t.substr(2),i=parseInt(n,16).toString(2);return\"0\"==i&&(i=\"00000000\"),i=i.slice(0,0-r),parseInt(i,2)}catch(t){return-1}}(i)}catch(t){return r}},Fr.getOID=function(t,e,r){null==r&&(r=null);try{return\"06\"!=t.substr(e,2)?r:function n(t){if(!Xr(t))return null;try{var e=[],r=t.substr(0,2),n=parseInt(r,16);e[0]=new String(Math.floor(n/40)),e[1]=new String(n%40);for(var i=t.substr(2),o=[],s=0;s0&&(c=c+\".\"+a.join(\".\")),c}catch(t){return null}}(Fr.getV(t,e))}catch(t){return r}},Fr.getOIDName=function(t,e,r){null==r&&(r=null);try{var n=Fr.getOID(t,e,r);if(n==r)return r;var i=Sr.asn1.x509.OID.oid2name(n);return\"\"==i?n:i}catch(t){return r}},Fr.getString=function(t,e,r){null==r&&(r=null);try{return Lr(Fr.getV(t,e))}catch(t){return r}},Fr.hextooidstr=function(t){var e=function t(e,r){return e.length>=r?e:new Array(r-e.length+1).join(\"0\")+e},r=[],n=t.substr(0,2),i=parseInt(n,16);r[0]=new String(Math.floor(i/40)),r[1]=new String(i%40);for(var o=t.substr(2),s=[],a=0;a0&&(h=h+\".\"+u.join(\".\")),h},Fr.dump=function(t,e,r,n){var i=Fr,o=i.getV,s=i.dump,a=i.getChildIdx,u=t;t instanceof Sr.asn1.ASN1Object&&(u=t.getEncodedHex());var c=function t(e,r){return e.length<=2*r?e:e.substr(0,r)+\"..(total \"+e.length/2+\"bytes)..\"+e.substr(e.length-r,r)};void 0===e&&(e={ommit_long_octet:32}),void 0===r&&(r=0),void 0===n&&(n=\"\");var h,l=e.ommit_long_octet;if(\"01\"==(h=u.substr(r,2)))return\"00\"==(f=o(u,r))?n+\"BOOLEAN FALSE\\n\":n+\"BOOLEAN TRUE\\n\";if(\"02\"==h)return n+\"INTEGER \"+c(f=o(u,r),l)+\"\\n\";if(\"03\"==h){var f=o(u,r);if(i.isASN1HEX(f.substr(2))){var g=n+\"BITSTRING, encapsulates\\n\";return g+=s(f.substr(2),e,0,n+\" \")}return n+\"BITSTRING \"+c(f,l)+\"\\n\"}if(\"04\"==h){f=o(u,r);if(i.isASN1HEX(f)){g=n+\"OCTETSTRING, encapsulates\\n\";return g+=s(f,e,0,n+\" \")}return n+\"OCTETSTRING \"+c(f,l)+\"\\n\"}if(\"05\"==h)return n+\"NULL\\n\";if(\"06\"==h){var d=o(u,r),p=Sr.asn1.ASN1Util.oidHexToInt(d),v=Sr.asn1.x509.OID.oid2name(p),y=p.replace(/\\./g,\" \");return\"\"!=v?n+\"ObjectIdentifier \"+v+\" (\"+y+\")\\n\":n+\"ObjectIdentifier (\"+y+\")\\n\"}if(\"0a\"==h)return n+\"ENUMERATED \"+parseInt(o(u,r))+\"\\n\";if(\"0c\"==h)return n+\"UTF8String '\"+Dr(o(u,r))+\"'\\n\";if(\"13\"==h)return n+\"PrintableString '\"+Dr(o(u,r))+\"'\\n\";if(\"14\"==h)return n+\"TeletexString '\"+Dr(o(u,r))+\"'\\n\";if(\"16\"==h)return n+\"IA5String '\"+Dr(o(u,r))+\"'\\n\";if(\"17\"==h)return n+\"UTCTime \"+Dr(o(u,r))+\"\\n\";if(\"18\"==h)return n+\"GeneralizedTime \"+Dr(o(u,r))+\"\\n\";if(\"1a\"==h)return n+\"VisualString '\"+Dr(o(u,r))+\"'\\n\";if(\"1e\"==h)return n+\"BMPString '\"+Yr(o(u,r))+\"'\\n\";if(\"30\"==h){if(\"3000\"==u.substr(r,4))return n+\"SEQUENCE {}\\n\";g=n+\"SEQUENCE\\n\";var m=e;if((2==(b=a(u,r)).length||3==b.length)&&\"06\"==u.substr(b[0],2)&&\"04\"==u.substr(b[b.length-1],2)){v=i.oidname(o(u,b[0]));var _=JSON.parse(JSON.stringify(e));_.x509ExtName=v,m=_}for(var S=0;S31)&&(128==(192&r)&&(31&r)==n))}catch(t){return!1}},Fr.isASN1HEX=function(t){var e=Fr;if(t.length%2==1)return!1;var r=e.getVblen(t,0),n=t.substr(0,2),i=e.getL(t,0);return t.length-n.length-i.length==2*r},Fr.checkStrictDER=function(t,e,r,n,i){var o=Fr;if(void 0===r){if(\"string\"!=typeof t)throw new Error(\"not hex string\");if(t=t.toLowerCase(),!Sr.lang.String.isHex(t))throw new Error(\"not hex string\");r=t.length,i=(n=t.length/2)<128?1:Math.ceil(n.toString(16))+1}if(o.getL(t,e).length>2*i)throw new Error(\"L of TLV too long: idx=\"+e);var s=o.getVblen(t,e);if(s>n)throw new Error(\"value of L too long than hex: idx=\"+e);var a=o.getTLV(t,e),u=a.length-2-o.getL(t,e).length;if(u!==2*s)throw new Error(\"V string length and L's value not the same:\"+u+\"/\"+2*s);if(0===e&&t.length!=a.length)throw new Error(\"total length and TLV length unmatch:\"+t.length+\"!=\"+a.length);var c=t.substr(e,2);if(\"02\"===c){var h=o.getVidx(t,e);if(\"00\"==t.substr(h,2)&&t.charCodeAt(h+2)<56)throw new Error(\"not least zeros for DER INTEGER\")}if(32&parseInt(c,16)){for(var l=o.getVblen(t,e),f=0,g=o.getChildIdx(t,e),d=0;d=r?e:new Array(r-e.length+1).join(n)+e};function Zr(t,e){var r=function t(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t,t.superclass=e.prototype,e.prototype.constructor==Object.prototype.constructor&&(e.prototype.constructor=e)}void 0!==Sr&&Sr||(e.KJUR=Sr={}),void 0!==Sr.crypto&&Sr.crypto||(Sr.crypto={}),Sr.crypto.Util=new function(){this.DIGESTINFOHEAD={sha1:\"3021300906052b0e03021a05000414\",sha224:\"302d300d06096086480165030402040500041c\",sha256:\"3031300d060960864801650304020105000420\",sha384:\"3041300d060960864801650304020205000430\",sha512:\"3051300d060960864801650304020305000440\",md2:\"3020300c06082a864886f70d020205000410\",md5:\"3020300c06082a864886f70d020505000410\",ripemd160:\"3021300906052b2403020105000414\"},this.DEFAULTPROVIDER={md5:\"cryptojs\",sha1:\"cryptojs\",sha224:\"cryptojs\",sha256:\"cryptojs\",sha384:\"cryptojs\",sha512:\"cryptojs\",ripemd160:\"cryptojs\",hmacmd5:\"cryptojs\",hmacsha1:\"cryptojs\",hmacsha224:\"cryptojs\",hmacsha256:\"cryptojs\",hmacsha384:\"cryptojs\",hmacsha512:\"cryptojs\",hmacripemd160:\"cryptojs\",MD5withRSA:\"cryptojs/jsrsa\",SHA1withRSA:\"cryptojs/jsrsa\",SHA224withRSA:\"cryptojs/jsrsa\",SHA256withRSA:\"cryptojs/jsrsa\",SHA384withRSA:\"cryptojs/jsrsa\",SHA512withRSA:\"cryptojs/jsrsa\",RIPEMD160withRSA:\"cryptojs/jsrsa\",MD5withECDSA:\"cryptojs/jsrsa\",SHA1withECDSA:\"cryptojs/jsrsa\",SHA224withECDSA:\"cryptojs/jsrsa\",SHA256withECDSA:\"cryptojs/jsrsa\",SHA384withECDSA:\"cryptojs/jsrsa\",SHA512withECDSA:\"cryptojs/jsrsa\",RIPEMD160withECDSA:\"cryptojs/jsrsa\",SHA1withDSA:\"cryptojs/jsrsa\",SHA224withDSA:\"cryptojs/jsrsa\",SHA256withDSA:\"cryptojs/jsrsa\",MD5withRSAandMGF1:\"cryptojs/jsrsa\",SHAwithRSAandMGF1:\"cryptojs/jsrsa\",SHA1withRSAandMGF1:\"cryptojs/jsrsa\",SHA224withRSAandMGF1:\"cryptojs/jsrsa\",SHA256withRSAandMGF1:\"cryptojs/jsrsa\",SHA384withRSAandMGF1:\"cryptojs/jsrsa\",SHA512withRSAandMGF1:\"cryptojs/jsrsa\",RIPEMD160withRSAandMGF1:\"cryptojs/jsrsa\"},this.CRYPTOJSMESSAGEDIGESTNAME={md5:v.algo.MD5,sha1:v.algo.SHA1,sha224:v.algo.SHA224,sha256:v.algo.SHA256,sha384:v.algo.SHA384,sha512:v.algo.SHA512,ripemd160:v.algo.RIPEMD160},this.getDigestInfoHex=function(t,e){if(void 0===this.DIGESTINFOHEAD[e])throw\"alg not supported in Util.DIGESTINFOHEAD: \"+e;return this.DIGESTINFOHEAD[e]+t},this.getPaddedDigestInfoHex=function(t,e,r){var n=this.getDigestInfoHex(t,e),i=r/4;if(n.length+22>i)throw\"key is too short for SigAlg: keylen=\"+r+\",\"+e;for(var o=\"0001\",s=\"00\"+n,a=\"\",u=i-o.length-s.length,c=0;c=0)return!1;if(n.compareTo(r.ONE)<0||n.compareTo(o)>=0)return!1;var a=n.modInverse(o),u=t.multiply(a).mod(o),c=e.multiply(a).mod(o);return s.multiply(u).add(i.multiply(c)).getX().toBigInteger().mod(o).equals(e)},this.serializeSig=function(t,e){var r=t.toByteArraySigned(),n=e.toByteArraySigned(),i=[];return i.push(2),i.push(r.length),(i=i.concat(r)).push(2),i.push(n.length),(i=i.concat(n)).unshift(i.length),i.unshift(48),i},this.parseSig=function(t){var e;if(48!=t[0])throw new Error(\"Signature not a valid DERSequence\");if(2!=t[e=2])throw new Error(\"First element in signature must be a DERInteger\");var n=t.slice(e+2,e+2+t[e+1]);if(2!=t[e+=2+t[e+1]])throw new Error(\"Second element in signature must be a DERInteger\");var i=t.slice(e+2,e+2+t[e+1]);return e+=2+t[e+1],{r:r.fromByteArrayUnsigned(n),s:r.fromByteArrayUnsigned(i)}},this.parseSigCompact=function(t){if(65!==t.length)throw\"Signature has the wrong length\";var e=t[0]-27;if(e<0||e>7)throw\"Invalid signature type\";var n=this.ecparams.n;return{r:r.fromByteArrayUnsigned(t.slice(1,33)).mod(n),s:r.fromByteArrayUnsigned(t.slice(33,65)).mod(n),i:e}},this.readPKCS5PrvKeyHex=function(t){if(!1===c(t))throw new Error(\"not ASN.1 hex string\");var e,r,n;try{e=u(t,0,[\"[0]\",0],\"06\"),r=u(t,0,[1],\"04\");try{n=u(t,0,[\"[1]\",0],\"03\")}catch(t){}}catch(t){throw new Error(\"malformed PKCS#1/5 plain ECC private key\")}if(this.curveName=s(e),void 0===this.curveName)throw\"unsupported curve name\";this.setNamedCurve(this.curveName),this.setPublicKeyHex(n),this.setPrivateKeyHex(r),this.isPublic=!1},this.readPKCS8PrvKeyHex=function(t){if(!1===c(t))throw new e(\"not ASN.1 hex string\");var r,n,i;try{u(t,0,[1,0],\"06\"),r=u(t,0,[1,1],\"06\"),n=u(t,0,[2,0,1],\"04\");try{i=u(t,0,[2,0,\"[1]\",0],\"03\")}catch(t){}}catch(t){throw new e(\"malformed PKCS#8 plain ECC private key\")}if(this.curveName=s(r),void 0===this.curveName)throw new e(\"unsupported curve name\");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i),this.setPrivateKeyHex(n),this.isPublic=!1},this.readPKCS8PubKeyHex=function(t){if(!1===c(t))throw new e(\"not ASN.1 hex string\");var r,n;try{u(t,0,[0,0],\"06\"),r=u(t,0,[0,1],\"06\"),n=u(t,0,[1],\"03\")}catch(t){throw new e(\"malformed PKCS#8 ECC public key\")}if(this.curveName=s(r),null===this.curveName)throw new e(\"unsupported curve name\");this.setNamedCurve(this.curveName),this.setPublicKeyHex(n)},this.readCertPubKeyHex=function(t,r){if(!1===c(t))throw new e(\"not ASN.1 hex string\");var n,i;try{n=u(t,0,[0,5,0,1],\"06\"),i=u(t,0,[0,5,1],\"03\")}catch(t){throw new e(\"malformed X.509 certificate ECC public key\")}if(this.curveName=s(n),null===this.curveName)throw new e(\"unsupported curve name\");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i)},void 0!==t&&void 0!==t.curve&&(this.curveName=t.curve),void 0===this.curveName&&(this.curveName=\"secp256r1\"),this.setNamedCurve(this.curveName),void 0!==t&&(void 0!==t.prv&&this.setPrivateKeyHex(t.prv),void 0!==t.pub&&this.setPublicKeyHex(t.pub))},Sr.crypto.ECDSA.parseSigHex=function(t){var e=Sr.crypto.ECDSA.parseSigHexInHexRS(t);return{r:new w(e.r,16),s:new w(e.s,16)}},Sr.crypto.ECDSA.parseSigHexInHexRS=function(t){var e=Fr,r=e.getChildIdx,n=e.getV;if(e.checkStrictDER(t,0),\"30\"!=t.substr(0,2))throw new Error(\"signature is not a ASN.1 sequence\");var i=r(t,0);if(2!=i.length)throw new Error(\"signature shall have two elements\");var o=i[0],s=i[1];if(\"02\"!=t.substr(o,2))throw new Error(\"1st item not ASN.1 integer\");if(\"02\"!=t.substr(s,2))throw new Error(\"2nd item not ASN.1 integer\");return{r:n(t,o),s:n(t,s)}},Sr.crypto.ECDSA.asn1SigToConcatSig=function(t){var e=Sr.crypto.ECDSA.parseSigHexInHexRS(t),r=e.r,n=e.s;if(\"00\"==r.substr(0,2)&&r.length%32==2&&(r=r.substr(2)),\"00\"==n.substr(0,2)&&n.length%32==2&&(n=n.substr(2)),r.length%32==30&&(r=\"00\"+r),n.length%32==30&&(n=\"00\"+n),r.length%32!=0)throw\"unknown ECDSA sig r length error\";if(n.length%32!=0)throw\"unknown ECDSA sig s length error\";return r+n},Sr.crypto.ECDSA.concatSigToASN1Sig=function(t){if(t.length/2*8%128!=0)throw\"unknown ECDSA concatinated r-s sig length error\";var e=t.substr(0,t.length/2),r=t.substr(t.length/2);return Sr.crypto.ECDSA.hexRSSigToASN1Sig(e,r)},Sr.crypto.ECDSA.hexRSSigToASN1Sig=function(t,e){var r=new w(t,16),n=new w(e,16);return Sr.crypto.ECDSA.biRSSigToASN1Sig(r,n)},Sr.crypto.ECDSA.biRSSigToASN1Sig=function(t,e){var r=Sr.asn1,n=new r.DERInteger({bigint:t}),i=new r.DERInteger({bigint:e});return new r.DERSequence({array:[n,i]}).getEncodedHex()},Sr.crypto.ECDSA.getName=function(t){return\"2b8104001f\"===t?\"secp192k1\":\"2a8648ce3d030107\"===t?\"secp256r1\":\"2b8104000a\"===t?\"secp256k1\":\"2b81040021\"===t?\"secp224r1\":\"2b81040022\"===t?\"secp384r1\":-1!==\"|secp256r1|NIST P-256|P-256|prime256v1|\".indexOf(t)?\"secp256r1\":-1!==\"|secp256k1|\".indexOf(t)?\"secp256k1\":-1!==\"|secp224r1|NIST P-224|P-224|\".indexOf(t)?\"secp224r1\":-1!==\"|secp384r1|NIST P-384|P-384|\".indexOf(t)?\"secp384r1\":null},void 0!==Sr&&Sr||(e.KJUR=Sr={}),void 0!==Sr.crypto&&Sr.crypto||(Sr.crypto={}),Sr.crypto.ECParameterDB=new function(){var t={},e={};function r(t){return new w(t,16)}this.getByName=function(r){var n=r;if(void 0!==e[n]&&(n=e[r]),void 0!==t[n])return t[n];throw\"unregistered EC curve name: \"+n},this.regist=function(n,i,o,s,a,u,c,h,l,f,g,d){t[n]={};var p=r(o),v=r(s),y=r(a),m=r(u),_=r(c),S=new Ke(p,v,y),b=S.decodePointHex(\"04\"+h+l);t[n].name=n,t[n].keylen=i,t[n].curve=S,t[n].G=b,t[n].n=m,t[n].h=_,t[n].oid=g,t[n].info=d;for(var w=0;w=2*u)break}var f={};return f.keyhex=c.substr(0,2*i[e].keylen),f.ivhex=c.substr(2*i[e].keylen,2*i[e].ivlen),f},a=function t(e,r,n,o){var s=v.enc.Base64.parse(e),a=v.enc.Hex.stringify(s);return(0,i[r].proc)(a,n,o)};return{version:\"1.0.0\",parsePKCS5PEM:function t(e){return o(e)},getKeyAndUnusedIvByPasscodeAndIvsalt:function t(e,r,n){return s(e,r,n)},decryptKeyB64:function t(e,r,n,i){return a(e,r,n,i)},getDecryptedKeyHex:function t(e,r){var n=o(e),i=(n.type,n.cipher),u=n.ivsalt,c=n.data,h=s(i,r,u).keyhex;return a(c,i,h,u)},getEncryptedPKCS5PEMFromPrvKeyHex:function t(e,r,n,o,a){var u=\"\";if(void 0!==o&&null!=o||(o=\"AES-256-CBC\"),void 0===i[o])throw new Error(\"KEYUTIL unsupported algorithm: \"+o);void 0!==a&&null!=a||(a=function t(e){var r=v.lib.WordArray.random(e);return v.enc.Hex.stringify(r)}(i[o].ivlen).toUpperCase());var c=function t(e,r,n,o){return(0,i[r].eproc)(e,n,o)}(r,o,s(o,n,a).keyhex,a);u=\"-----BEGIN \"+e+\" PRIVATE KEY-----\\r\\n\";return u+=\"Proc-Type: 4,ENCRYPTED\\r\\n\",u+=\"DEK-Info: \"+o+\",\"+a+\"\\r\\n\",u+=\"\\r\\n\",u+=c.replace(/(.{64})/g,\"$1\\r\\n\"),u+=\"\\r\\n-----END \"+e+\" PRIVATE KEY-----\\r\\n\"},parseHexOfEncryptedPKCS8:function t(e){var r=Fr,n=r.getChildIdx,i=r.getV,o={},s=n(e,0);if(2!=s.length)throw new Error(\"malformed format: SEQUENCE(0).items != 2: \"+s.length);o.ciphertext=i(e,s[1]);var a=n(e,s[0]);if(2!=a.length)throw new Error(\"malformed format: SEQUENCE(0.0).items != 2: \"+a.length);if(\"2a864886f70d01050d\"!=i(e,a[0]))throw new Error(\"this only supports pkcs5PBES2\");var u=n(e,a[1]);if(2!=a.length)throw new Error(\"malformed format: SEQUENCE(0.0.1).items != 2: \"+u.length);var c=n(e,u[1]);if(2!=c.length)throw new Error(\"malformed format: SEQUENCE(0.0.1.1).items != 2: \"+c.length);if(\"2a864886f70d0307\"!=i(e,c[0]))throw\"this only supports TripleDES\";o.encryptionSchemeAlg=\"TripleDES\",o.encryptionSchemeIV=i(e,c[1]);var h=n(e,u[0]);if(2!=h.length)throw new Error(\"malformed format: SEQUENCE(0.0.1.0).items != 2: \"+h.length);if(\"2a864886f70d01050c\"!=i(e,h[0]))throw new Error(\"this only supports pkcs5PBKDF2\");var l=n(e,h[1]);if(l.length<2)throw new Error(\"malformed format: SEQUENCE(0.0.1.0.1).items < 2: \"+l.length);o.pbkdf2Salt=i(e,l[0]);var f=i(e,l[1]);try{o.pbkdf2Iter=parseInt(f,16)}catch(t){throw new Error(\"malformed format pbkdf2Iter: \"+f)}return o},getPBKDF2KeyHexFromParam:function t(e,r){var n=v.enc.Hex.parse(e.pbkdf2Salt),i=e.pbkdf2Iter,o=v.PBKDF2(r,n,{keySize:6,iterations:i});return v.enc.Hex.stringify(o)},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function t(e,r){var n=Mr(e,\"ENCRYPTED PRIVATE KEY\"),i=this.parseHexOfEncryptedPKCS8(n),o=tn.getPBKDF2KeyHexFromParam(i,r),s={};s.ciphertext=v.enc.Hex.parse(i.ciphertext);var a=v.enc.Hex.parse(o),u=v.enc.Hex.parse(i.encryptionSchemeIV),c=v.TripleDES.decrypt(s,a,{iv:u});return v.enc.Hex.stringify(c)},getKeyFromEncryptedPKCS8PEM:function t(e,r){var n=this._getPlainPKCS8HexFromEncryptedPKCS8PEM(e,r);return this.getKeyFromPlainPrivatePKCS8Hex(n)},parsePlainPrivatePKCS8Hex:function t(e){var r=Fr,n=r.getChildIdx,i=r.getV,o={algparam:null};if(\"30\"!=e.substr(0,2))throw new Error(\"malformed plain PKCS8 private key(code:001)\");var s=n(e,0);if(s.length<3)throw new Error(\"malformed plain PKCS8 private key(code:002)\");if(\"30\"!=e.substr(s[1],2))throw new Error(\"malformed PKCS8 private key(code:003)\");var a=n(e,s[1]);if(2!=a.length)throw new Error(\"malformed PKCS8 private key(code:004)\");if(\"06\"!=e.substr(a[0],2))throw new Error(\"malformed PKCS8 private key(code:005)\");if(o.algoid=i(e,a[0]),\"06\"==e.substr(a[1],2)&&(o.algparam=i(e,a[1])),\"04\"!=e.substr(s[2],2))throw new Error(\"malformed PKCS8 private key(code:006)\");return o.keyidx=r.getVidx(e,s[2]),o},getKeyFromPlainPrivatePKCS8PEM:function t(e){var r=Mr(e,\"PRIVATE KEY\");return this.getKeyFromPlainPrivatePKCS8Hex(r)},getKeyFromPlainPrivatePKCS8Hex:function t(e){var r,n=this.parsePlainPrivatePKCS8Hex(e);if(\"2a864886f70d010101\"==n.algoid)r=new Me;else if(\"2a8648ce380401\"==n.algoid)r=new Sr.crypto.DSA;else{if(\"2a8648ce3d0201\"!=n.algoid)throw new Error(\"unsupported private key algorithm\");r=new Sr.crypto.ECDSA}return r.readPKCS8PrvKeyHex(e),r},_getKeyFromPublicPKCS8Hex:function t(e){var r,n=Fr.getVbyList(e,0,[0,0],\"06\");if(\"2a864886f70d010101\"===n)r=new Me;else if(\"2a8648ce380401\"===n)r=new Sr.crypto.DSA;else{if(\"2a8648ce3d0201\"!==n)throw new Error(\"unsupported PKCS#8 public key hex\");r=new Sr.crypto.ECDSA}return r.readPKCS8PubKeyHex(e),r},parsePublicRawRSAKeyHex:function t(e){var r=Fr,n=r.getChildIdx,i=r.getV,o={};if(\"30\"!=e.substr(0,2))throw new Error(\"malformed RSA key(code:001)\");var s=n(e,0);if(2!=s.length)throw new Error(\"malformed RSA key(code:002)\");if(\"02\"!=e.substr(s[0],2))throw new Error(\"malformed RSA key(code:003)\");if(o.n=i(e,s[0]),\"02\"!=e.substr(s[1],2))throw new Error(\"malformed RSA key(code:004)\");return o.e=i(e,s[1]),o},parsePublicPKCS8Hex:function t(e){var r=Fr,n=r.getChildIdx,i=r.getV,o={algparam:null},s=n(e,0);if(2!=s.length)throw new Error(\"outer DERSequence shall have 2 elements: \"+s.length);var a=s[0];if(\"30\"!=e.substr(a,2))throw new Error(\"malformed PKCS8 public key(code:001)\");var u=n(e,a);if(2!=u.length)throw new Error(\"malformed PKCS8 public key(code:002)\");if(\"06\"!=e.substr(u[0],2))throw new Error(\"malformed PKCS8 public key(code:003)\");if(o.algoid=i(e,u[0]),\"06\"==e.substr(u[1],2)?o.algparam=i(e,u[1]):\"30\"==e.substr(u[1],2)&&(o.algparam={},o.algparam.p=r.getVbyList(e,u[1],[0],\"02\"),o.algparam.q=r.getVbyList(e,u[1],[1],\"02\"),o.algparam.g=r.getVbyList(e,u[1],[2],\"02\")),\"03\"!=e.substr(s[1],2))throw new Error(\"malformed PKCS8 public key(code:004)\");return o.key=i(e,s[1]).substr(2),o}}}();tn.getKey=function(t,e,r){var n=(v=Fr).getChildIdx,i=(v.getV,v.getVbyList),o=Sr.crypto,s=o.ECDSA,a=o.DSA,u=Me,c=Mr,h=tn;if(void 0!==u&&t instanceof u)return t;if(void 0!==s&&t instanceof s)return t;if(void 0!==a&&t instanceof a)return t;if(void 0!==t.curve&&void 0!==t.xy&&void 0===t.d)return new s({pub:t.xy,curve:t.curve});if(void 0!==t.curve&&void 0!==t.d)return new s({prv:t.d,curve:t.curve});if(void 0===t.kty&&void 0!==t.n&&void 0!==t.e&&void 0===t.d)return(P=new u).setPublic(t.n,t.e),P;if(void 0===t.kty&&void 0!==t.n&&void 0!==t.e&&void 0!==t.d&&void 0!==t.p&&void 0!==t.q&&void 0!==t.dp&&void 0!==t.dq&&void 0!==t.co&&void 0===t.qi)return(P=new u).setPrivateEx(t.n,t.e,t.d,t.p,t.q,t.dp,t.dq,t.co),P;if(void 0===t.kty&&void 0!==t.n&&void 0!==t.e&&void 0!==t.d&&void 0===t.p)return(P=new u).setPrivate(t.n,t.e,t.d),P;if(void 0!==t.p&&void 0!==t.q&&void 0!==t.g&&void 0!==t.y&&void 0===t.x)return(P=new a).setPublic(t.p,t.q,t.g,t.y),P;if(void 0!==t.p&&void 0!==t.q&&void 0!==t.g&&void 0!==t.y&&void 0!==t.x)return(P=new a).setPrivate(t.p,t.q,t.g,t.y,t.x),P;if(\"RSA\"===t.kty&&void 0!==t.n&&void 0!==t.e&&void 0===t.d)return(P=new u).setPublic(Rr(t.n),Rr(t.e)),P;if(\"RSA\"===t.kty&&void 0!==t.n&&void 0!==t.e&&void 0!==t.d&&void 0!==t.p&&void 0!==t.q&&void 0!==t.dp&&void 0!==t.dq&&void 0!==t.qi)return(P=new u).setPrivateEx(Rr(t.n),Rr(t.e),Rr(t.d),Rr(t.p),Rr(t.q),Rr(t.dp),Rr(t.dq),Rr(t.qi)),P;if(\"RSA\"===t.kty&&void 0!==t.n&&void 0!==t.e&&void 0!==t.d)return(P=new u).setPrivate(Rr(t.n),Rr(t.e),Rr(t.d)),P;if(\"EC\"===t.kty&&void 0!==t.crv&&void 0!==t.x&&void 0!==t.y&&void 0===t.d){var l=(k=new s({curve:t.crv})).ecparams.keylen/4,f=\"04\"+(\"0000000000\"+Rr(t.x)).slice(-l)+(\"0000000000\"+Rr(t.y)).slice(-l);return k.setPublicKeyHex(f),k}if(\"EC\"===t.kty&&void 0!==t.crv&&void 0!==t.x&&void 0!==t.y&&void 0!==t.d){l=(k=new s({curve:t.crv})).ecparams.keylen/4,f=\"04\"+(\"0000000000\"+Rr(t.x)).slice(-l)+(\"0000000000\"+Rr(t.y)).slice(-l);var g=(\"0000000000\"+Rr(t.d)).slice(-l);return k.setPublicKeyHex(f),k.setPrivateKeyHex(g),k}if(\"pkcs5prv\"===r){var d,p=t,v=Fr;if(9===(d=n(p,0)).length)(P=new u).readPKCS5PrvKeyHex(p);else if(6===d.length)(P=new a).readPKCS5PrvKeyHex(p);else{if(!(d.length>2&&\"04\"===p.substr(d[1],2)))throw new Error(\"unsupported PKCS#1/5 hexadecimal key\");(P=new s).readPKCS5PrvKeyHex(p)}return P}if(\"pkcs8prv\"===r)return P=h.getKeyFromPlainPrivatePKCS8Hex(t);if(\"pkcs8pub\"===r)return h._getKeyFromPublicPKCS8Hex(t);if(\"x509pub\"===r)return on.getPublicKeyFromCertHex(t);if(-1!=t.indexOf(\"-END CERTIFICATE-\",0)||-1!=t.indexOf(\"-END X509 CERTIFICATE-\",0)||-1!=t.indexOf(\"-END TRUSTED CERTIFICATE-\",0))return on.getPublicKeyFromCertPEM(t);if(-1!=t.indexOf(\"-END PUBLIC KEY-\")){var y=Mr(t,\"PUBLIC KEY\");return h._getKeyFromPublicPKCS8Hex(y)}if(-1!=t.indexOf(\"-END RSA PRIVATE KEY-\")&&-1==t.indexOf(\"4,ENCRYPTED\")){var m=c(t,\"RSA PRIVATE KEY\");return h.getKey(m,null,\"pkcs5prv\")}if(-1!=t.indexOf(\"-END DSA PRIVATE KEY-\")&&-1==t.indexOf(\"4,ENCRYPTED\")){var _=i(R=c(t,\"DSA PRIVATE KEY\"),0,[1],\"02\"),S=i(R,0,[2],\"02\"),b=i(R,0,[3],\"02\"),F=i(R,0,[4],\"02\"),E=i(R,0,[5],\"02\");return(P=new a).setPrivate(new w(_,16),new w(S,16),new w(b,16),new w(F,16),new w(E,16)),P}if(-1!=t.indexOf(\"-END EC PRIVATE KEY-\")&&-1==t.indexOf(\"4,ENCRYPTED\")){m=c(t,\"EC PRIVATE KEY\");return h.getKey(m,null,\"pkcs5prv\")}if(-1!=t.indexOf(\"-END PRIVATE KEY-\"))return h.getKeyFromPlainPrivatePKCS8PEM(t);if(-1!=t.indexOf(\"-END RSA PRIVATE KEY-\")&&-1!=t.indexOf(\"4,ENCRYPTED\")){var x=h.getDecryptedKeyHex(t,e),A=new Me;return A.readPKCS5PrvKeyHex(x),A}if(-1!=t.indexOf(\"-END EC PRIVATE KEY-\")&&-1!=t.indexOf(\"4,ENCRYPTED\")){var k,P=i(R=h.getDecryptedKeyHex(t,e),0,[1],\"04\"),C=i(R,0,[2,0],\"06\"),T=i(R,0,[3,0],\"03\").substr(2);if(void 0===Sr.crypto.OID.oidhex2name[C])throw new Error(\"undefined OID(hex) in KJUR.crypto.OID: \"+C);return(k=new s({curve:Sr.crypto.OID.oidhex2name[C]})).setPublicKeyHex(T),k.setPrivateKeyHex(P),k.isPublic=!1,k}if(-1!=t.indexOf(\"-END DSA PRIVATE KEY-\")&&-1!=t.indexOf(\"4,ENCRYPTED\")){var R;_=i(R=h.getDecryptedKeyHex(t,e),0,[1],\"02\"),S=i(R,0,[2],\"02\"),b=i(R,0,[3],\"02\"),F=i(R,0,[4],\"02\"),E=i(R,0,[5],\"02\");return(P=new a).setPrivate(new w(_,16),new w(S,16),new w(b,16),new w(F,16),new w(E,16)),P}if(-1!=t.indexOf(\"-END ENCRYPTED PRIVATE KEY-\"))return h.getKeyFromEncryptedPKCS8PEM(t,e);throw new Error(\"not supported argument\")},tn.generateKeypair=function(t,e){if(\"RSA\"==t){var r=e;(s=new Me).generate(r,\"10001\"),s.isPrivate=!0,s.isPublic=!0;var n=new Me,i=s.n.toString(16),o=s.e.toString(16);return n.setPublic(i,o),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=s,a.pubKeyObj=n,a}if(\"EC\"==t){var s,a,u=e,c=new Sr.crypto.ECDSA({curve:u}).generateKeyPairHex();return(s=new Sr.crypto.ECDSA({curve:u})).setPublicKeyHex(c.ecpubhex),s.setPrivateKeyHex(c.ecprvhex),s.isPrivate=!0,s.isPublic=!1,(n=new Sr.crypto.ECDSA({curve:u})).setPublicKeyHex(c.ecpubhex),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=s,a.pubKeyObj=n,a}throw new Error(\"unknown algorithm: \"+t)},tn.getPEM=function(t,e,r,n,i,o){var s=Sr,a=s.asn1,u=a.DERObjectIdentifier,c=a.DERInteger,h=a.ASN1Util.newObject,l=a.x509.SubjectPublicKeyInfo,f=s.crypto,g=f.DSA,d=f.ECDSA,p=Me;function y(t){return h({seq:[{int:0},{int:{bigint:t.n}},{int:t.e},{int:{bigint:t.d}},{int:{bigint:t.p}},{int:{bigint:t.q}},{int:{bigint:t.dmp1}},{int:{bigint:t.dmq1}},{int:{bigint:t.coeff}}]})}function m(t){return h({seq:[{int:1},{octstr:{hex:t.prvKeyHex}},{tag:[\"a0\",!0,{oid:{name:t.curveName}}]},{tag:[\"a1\",!0,{bitstr:{hex:\"00\"+t.pubKeyHex}}]}]})}function _(t){return h({seq:[{int:0},{int:{bigint:t.p}},{int:{bigint:t.q}},{int:{bigint:t.g}},{int:{bigint:t.y}},{int:{bigint:t.x}}]})}if((void 0!==p&&t instanceof p||void 0!==g&&t instanceof g||void 0!==d&&t instanceof d)&&1==t.isPublic&&(void 0===e||\"PKCS8PUB\"==e))return jr(F=new l(t).getEncodedHex(),\"PUBLIC KEY\");if(\"PKCS1PRV\"==e&&void 0!==p&&t instanceof p&&(void 0===r||null==r)&&1==t.isPrivate)return jr(F=y(t).getEncodedHex(),\"RSA PRIVATE KEY\");if(\"PKCS1PRV\"==e&&void 0!==d&&t instanceof d&&(void 0===r||null==r)&&1==t.isPrivate){var S=new u({name:t.curveName}).getEncodedHex(),b=m(t).getEncodedHex(),w=\"\";return w+=jr(S,\"EC PARAMETERS\"),w+=jr(b,\"EC PRIVATE KEY\")}if(\"PKCS1PRV\"==e&&void 0!==g&&t instanceof g&&(void 0===r||null==r)&&1==t.isPrivate)return jr(F=_(t).getEncodedHex(),\"DSA PRIVATE KEY\");if(\"PKCS5PRV\"==e&&void 0!==p&&t instanceof p&&void 0!==r&&null!=r&&1==t.isPrivate){var F=y(t).getEncodedHex();return void 0===n&&(n=\"DES-EDE3-CBC\"),this.getEncryptedPKCS5PEMFromPrvKeyHex(\"RSA\",F,r,n,o)}if(\"PKCS5PRV\"==e&&void 0!==d&&t instanceof d&&void 0!==r&&null!=r&&1==t.isPrivate){F=m(t).getEncodedHex();return void 0===n&&(n=\"DES-EDE3-CBC\"),this.getEncryptedPKCS5PEMFromPrvKeyHex(\"EC\",F,r,n,o)}if(\"PKCS5PRV\"==e&&void 0!==g&&t instanceof g&&void 0!==r&&null!=r&&1==t.isPrivate){F=_(t).getEncodedHex();return void 0===n&&(n=\"DES-EDE3-CBC\"),this.getEncryptedPKCS5PEMFromPrvKeyHex(\"DSA\",F,r,n,o)}var E=function t(e,r){var n=x(e,r);return new h({seq:[{seq:[{oid:{name:\"pkcs5PBES2\"}},{seq:[{seq:[{oid:{name:\"pkcs5PBKDF2\"}},{seq:[{octstr:{hex:n.pbkdf2Salt}},{int:n.pbkdf2Iter}]}]},{seq:[{oid:{name:\"des-EDE3-CBC\"}},{octstr:{hex:n.encryptionSchemeIV}}]}]}]},{octstr:{hex:n.ciphertext}}]}).getEncodedHex()},x=function t(e,r){var n=v.lib.WordArray.random(8),i=v.lib.WordArray.random(8),o=v.PBKDF2(r,n,{keySize:6,iterations:100}),s=v.enc.Hex.parse(e),a=v.TripleDES.encrypt(s,o,{iv:i})+\"\",u={};return u.ciphertext=a,u.pbkdf2Salt=v.enc.Hex.stringify(n),u.pbkdf2Iter=100,u.encryptionSchemeAlg=\"DES-EDE3-CBC\",u.encryptionSchemeIV=v.enc.Hex.stringify(i),u};if(\"PKCS8PRV\"==e&&null!=p&&t instanceof p&&1==t.isPrivate){var A=y(t).getEncodedHex();F=h({seq:[{int:0},{seq:[{oid:{name:\"rsaEncryption\"}},{null:!0}]},{octstr:{hex:A}}]}).getEncodedHex();return void 0===r||null==r?jr(F,\"PRIVATE KEY\"):jr(b=E(F,r),\"ENCRYPTED PRIVATE KEY\")}if(\"PKCS8PRV\"==e&&void 0!==d&&t instanceof d&&1==t.isPrivate){A=new h({seq:[{int:1},{octstr:{hex:t.prvKeyHex}},{tag:[\"a1\",!0,{bitstr:{hex:\"00\"+t.pubKeyHex}}]}]}).getEncodedHex(),F=h({seq:[{int:0},{seq:[{oid:{name:\"ecPublicKey\"}},{oid:{name:t.curveName}}]},{octstr:{hex:A}}]}).getEncodedHex();return void 0===r||null==r?jr(F,\"PRIVATE KEY\"):jr(b=E(F,r),\"ENCRYPTED PRIVATE KEY\")}if(\"PKCS8PRV\"==e&&void 0!==g&&t instanceof g&&1==t.isPrivate){A=new c({bigint:t.x}).getEncodedHex(),F=h({seq:[{int:0},{seq:[{oid:{name:\"dsa\"}},{seq:[{int:{bigint:t.p}},{int:{bigint:t.q}},{int:{bigint:t.g}}]}]},{octstr:{hex:A}}]}).getEncodedHex();return void 0===r||null==r?jr(F,\"PRIVATE KEY\"):jr(b=E(F,r),\"ENCRYPTED PRIVATE KEY\")}throw new Error(\"unsupported object nor format\")},tn.getKeyFromCSRPEM=function(t){var e=Mr(t,\"CERTIFICATE REQUEST\");return tn.getKeyFromCSRHex(e)},tn.getKeyFromCSRHex=function(t){var e=tn.parseCSRHex(t);return tn.getKey(e.p8pubkeyhex,null,\"pkcs8pub\")},tn.parseCSRHex=function(t){var e=Fr,r=e.getChildIdx,n=e.getTLV,i={},o=t;if(\"30\"!=o.substr(0,2))throw new Error(\"malformed CSR(code:001)\");var s=r(o,0);if(s.length<1)throw new Error(\"malformed CSR(code:002)\");if(\"30\"!=o.substr(s[0],2))throw new Error(\"malformed CSR(code:003)\");var a=r(o,s[0]);if(a.length<3)throw new Error(\"malformed CSR(code:004)\");return i.p8pubkeyhex=n(o,a[2]),i},tn.getKeyID=function(t){var e=tn,r=Fr;\"string\"==typeof t&&-1!=t.indexOf(\"BEGIN \")&&(t=e.getKey(t));var n=Mr(e.getPEM(t)),i=r.getIdxbyList(n,0,[1]),o=r.getV(n,i).substring(2);return Sr.crypto.Util.hashHex(o,\"sha1\")},tn.getJWKFromKey=function(t){var e={};if(t instanceof Me&&t.isPrivate)return e.kty=\"RSA\",e.n=Tr(t.n.toString(16)),e.e=Tr(t.e.toString(16)),e.d=Tr(t.d.toString(16)),e.p=Tr(t.p.toString(16)),e.q=Tr(t.q.toString(16)),e.dp=Tr(t.dmp1.toString(16)),e.dq=Tr(t.dmq1.toString(16)),e.qi=Tr(t.coeff.toString(16)),e;if(t instanceof Me&&t.isPublic)return e.kty=\"RSA\",e.n=Tr(t.n.toString(16)),e.e=Tr(t.e.toString(16)),e;if(t instanceof Sr.crypto.ECDSA&&t.isPrivate){if(\"P-256\"!==(n=t.getShortNISTPCurveName())&&\"P-384\"!==n)throw new Error(\"unsupported curve name for JWT: \"+n);var r=t.getPublicKeyXYHex();return e.kty=\"EC\",e.crv=n,e.x=Tr(r.x),e.y=Tr(r.y),e.d=Tr(t.prvKeyHex),e}if(t instanceof Sr.crypto.ECDSA&&t.isPublic){var n;if(\"P-256\"!==(n=t.getShortNISTPCurveName())&&\"P-384\"!==n)throw new Error(\"unsupported curve name for JWT: \"+n);r=t.getPublicKeyXYHex();return e.kty=\"EC\",e.crv=n,e.x=Tr(r.x),e.y=Tr(r.y),e}throw new Error(\"not supported key object\")},Me.getPosArrayOfChildrenFromHex=function(t){return Fr.getChildIdx(t,0)},Me.getHexValueArrayOfChildrenFromHex=function(t){var e,r=Fr.getV,n=r(t,(e=Me.getPosArrayOfChildrenFromHex(t))[0]),i=r(t,e[1]),o=r(t,e[2]),s=r(t,e[3]),a=r(t,e[4]),u=r(t,e[5]),c=r(t,e[6]),h=r(t,e[7]),l=r(t,e[8]);return(e=new Array).push(n,i,o,s,a,u,c,h,l),e},Me.prototype.readPrivateKeyFromPEMString=function(t){var e=Mr(t),r=Me.getHexValueArrayOfChildrenFromHex(e);this.setPrivateEx(r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8])},Me.prototype.readPKCS5PrvKeyHex=function(t){var e=Me.getHexValueArrayOfChildrenFromHex(t);this.setPrivateEx(e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8])},Me.prototype.readPKCS8PrvKeyHex=function(t){var e,r,n,i,o,s,a,u,c=Fr,h=c.getVbyListEx;if(!1===c.isASN1HEX(t))throw new Error(\"not ASN.1 hex string\");try{e=h(t,0,[2,0,1],\"02\"),r=h(t,0,[2,0,2],\"02\"),n=h(t,0,[2,0,3],\"02\"),i=h(t,0,[2,0,4],\"02\"),o=h(t,0,[2,0,5],\"02\"),s=h(t,0,[2,0,6],\"02\"),a=h(t,0,[2,0,7],\"02\"),u=h(t,0,[2,0,8],\"02\")}catch(t){throw new Error(\"malformed PKCS#8 plain RSA private key\")}this.setPrivateEx(e,r,n,i,o,s,a,u)},Me.prototype.readPKCS5PubKeyHex=function(t){var e=Fr,r=e.getV;if(!1===e.isASN1HEX(t))throw new Error(\"keyHex is not ASN.1 hex string\");var n=e.getChildIdx(t,0);if(2!==n.length||\"02\"!==t.substr(n[0],2)||\"02\"!==t.substr(n[1],2))throw new Error(\"wrong hex for PKCS#5 public key\");var i=r(t,n[0]),o=r(t,n[1]);this.setPublic(i,o)},Me.prototype.readPKCS8PubKeyHex=function(t){var e=Fr;if(!1===e.isASN1HEX(t))throw new Error(\"not ASN.1 hex string\");if(\"06092a864886f70d010101\"!==e.getTLVbyListEx(t,0,[0,0]))throw new Error(\"not PKCS8 RSA public key\");var r=e.getTLVbyListEx(t,0,[1,0]);this.readPKCS5PubKeyHex(r)},Me.prototype.readCertPubKeyHex=function(t,e){var r,n;(r=new on).readCertHex(t),n=r.getPublicKeyHex(),this.readPKCS8PubKeyHex(n)};new RegExp(\"[^0-9a-f]\",\"gi\");function en(t,e){for(var r=\"\",n=e/4-t.length,i=0;i>24,(16711680&i)>>16,(65280&i)>>8,255&i])))),i+=1;return n}function nn(t){for(var e in Sr.crypto.Util.DIGESTINFOHEAD){var r=Sr.crypto.Util.DIGESTINFOHEAD[e],n=r.length;if(t.substring(0,n)==r)return[e,t.substring(n)]}return[]}function on(t){var e,r=Fr,n=r.getChildIdx,i=r.getV,o=r.getTLV,s=r.getVbyList,a=r.getVbyListEx,u=r.getTLVbyList,c=r.getTLVbyListEx,h=r.getIdxbyList,l=r.getIdxbyListEx,f=r.getVidx,g=r.getInt,d=r.oidname,p=r.hextooidstr,v=Mr;try{e=Sr.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV}catch(t){}this.HEX2STAG={\"0c\":\"utf8\",13:\"prn\",16:\"ia5\",\"1a\":\"vis\",\"1e\":\"bmp\"},this.hex=null,this.version=0,this.foffset=0,this.aExtInfo=null,this.getVersion=function(){if(null===this.hex||0!==this.version)return this.version;var t=u(this.hex,0,[0,0]);if(\"a0\"==t.substr(0,2)){var e=u(t,0,[0]),r=g(e,0);if(r<0||21){var a=o(t,s[1]),u=this.getGeneralName(a);null!=u.uri&&(i.uri=u.uri)}if(s.length>2){var c=o(t,s[2]);\"0101ff\"==c&&(i.reqauth=!0),\"010100\"==c&&(i.reqauth=!1)}return i},this.getX500NameRule=function(t){for(var e=null,r=[],n=0;n0&&(t.ext=this.getExtParamArray()),t.sighex=this.getSignatureValueHex(),t},this.getExtParamArray=function(t){null==t&&(-1!=l(this.hex,0,[0,\"[3]\"])&&(t=c(this.hex,0,[0,\"[3]\",0],\"30\")));for(var e=[],r=n(t,0),i=0;i0&&(c=new Array(r),(new Be).nextBytes(c),c=String.fromCharCode.apply(String,c));var h=Lr(u(Nr(\"\\0\\0\\0\\0\\0\\0\\0\\0\"+i+c))),l=[];for(n=0;n>8*a-s&255;for(d[0]&=~p,n=0;nn)return!1;var i=this.doPublic(r).toString(16);if(i.length+3!=n/4)return!1;var o=nn(i.replace(/^1f+00/,\"\"));if(0==o.length)return!1;var s=o[0];return o[1]==function t(e){return Sr.crypto.Util.hashString(e,s)}(t)},Me.prototype.verifyWithMessageHash=function(t,e){if(e.length!=Math.ceil(this.n.bitLength()/4))return!1;var r=Oe(e,16);if(r.bitLength()>this.n.bitLength())return 0;var n=nn(this.doPublic(r).toString(16).replace(/^1f+00/,\"\"));if(0==n.length)return!1;n[0];return n[1]==t},Me.prototype.verifyPSS=function(t,e,r,n){var i=function t(e){return Sr.crypto.Util.hashHex(e,r)}(Nr(t));return void 0===n&&(n=-1),this.verifyWithMessageHashPSS(i,e,r,n)},Me.prototype.verifyWithMessageHashPSS=function(t,e,r,n){if(e.length!=Math.ceil(this.n.bitLength()/4))return!1;var i,o=new w(e,16),s=function t(e){return Sr.crypto.Util.hashHex(e,r)},a=Lr(t),u=a.length,c=this.n.bitLength()-1,h=Math.ceil(c/8);if(-1===n||void 0===n)n=u;else if(-2===n)n=h-u-2;else if(n<-2)throw new Error(\"invalid salt length\");if(h>8*h-c&255;if(0!=(f.charCodeAt(0)&d))throw new Error(\"bits beyond keysize not zero\");var p=rn(g,f.length,s),v=[];for(i=0;i0)&&-1==(\":\"+r.join(\":\")+\":\").indexOf(\":\"+v+\":\"))throw\"algorithm '\"+v+\"' not accepted in the list\";if(\"none\"!=v&&null===e)throw\"key shall be specified to verify.\";if(\"string\"==typeof e&&-1!=e.indexOf(\"-----BEGIN \")&&(e=tn.getKey(e)),!(\"RS\"!=y&&\"PS\"!=y||e instanceof n))throw\"key shall be a RSAKey obj for RS* and PS* algs\";if(\"ES\"==y&&!(e instanceof u))throw\"key shall be a ECDSA obj for ES* algs\";var m=null;if(void 0===o.jwsalg2sigalg[p.alg])throw\"unsupported alg name: \"+v;if(\"none\"==(m=o.jwsalg2sigalg[v]))throw\"not supported\";if(\"Hmac\"==m.substr(0,4)){if(void 0===e)throw\"hexadecimal key shall be specified for HMAC\";var _=new c({alg:m,pass:e});return _.updateString(f),d==_.doFinal()}if(-1!=m.indexOf(\"withECDSA\")){var S,b=null;try{b=u.concatSigToASN1Sig(d)}catch(t){return!1}return(S=new h({alg:m})).init(e),S.updateString(f),S.verify(b)}return(S=new h({alg:m})).init(e),S.updateString(f),S.verify(d)},Sr.jws.JWS.parse=function(t){var e,r,n,i=t.split(\".\"),o={};if(2!=i.length&&3!=i.length)throw\"malformed sJWS: wrong number of '.' splitted elements\";return e=i[0],r=i[1],3==i.length&&(n=i[2]),o.headerObj=Sr.jws.JWS.readSafeJSONString(wr(e)),o.payloadObj=Sr.jws.JWS.readSafeJSONString(wr(r)),o.headerPP=JSON.stringify(o.headerObj,null,\" \"),null==o.payloadObj?o.payloadPP=wr(r):o.payloadPP=JSON.stringify(o.payloadObj,null,\" \"),void 0!==n&&(o.sigHex=Rr(n)),o},Sr.jws.JWS.verifyJWT=function(t,e,r){var n=Sr.jws,i=n.JWS,o=i.readSafeJSONString,s=i.inArray,a=i.includedArray,u=t.split(\".\"),c=u[0],h=u[1],l=(Rr(u[2]),o(wr(c))),f=o(wr(h));if(void 0===l.alg)return!1;if(void 0===r.alg)throw\"acceptField.alg shall be specified\";if(!s(l.alg,r.alg))return!1;if(void 0!==f.iss&&\"object\"===g(r.iss)&&!s(f.iss,r.iss))return!1;if(void 0!==f.sub&&\"object\"===g(r.sub)&&!s(f.sub,r.sub))return!1;if(void 0!==f.aud&&\"object\"===g(r.aud))if(\"string\"==typeof f.aud){if(!s(f.aud,r.aud))return!1}else if(\"object\"==g(f.aud)&&!a(f.aud,r.aud))return!1;var d=n.IntDate.getNow();return void 0!==r.verifyAt&&\"number\"==typeof r.verifyAt&&(d=r.verifyAt),void 0!==r.gracePeriod&&\"number\"==typeof r.gracePeriod||(r.gracePeriod=0),!(void 0!==f.exp&&\"number\"==typeof f.exp&&f.exp+r.gracePeriodr.length&&(n=r.length);for(var i=0;i\n * @license MIT\n */\nvar n=r(30),i=r(31),o=r(32);function s(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(t,e){if(s()=s())throw new RangeError(\"Attempt to allocate Buffer larger than maximum size: 0x\"+s().toString(16)+\" bytes\");return 0|t}function d(t,e){if(u.isBuffer(t))return t.length;if(\"undefined\"!=typeof ArrayBuffer&&\"function\"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;\"string\"!=typeof t&&(t=\"\"+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case\"ascii\":case\"latin1\":case\"binary\":return r;case\"utf8\":case\"utf-8\":case void 0:return K(t).length;case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return 2*r;case\"hex\":return r>>>1;case\"base64\":return q(t).length;default:if(n)return K(t).length;e=(\"\"+e).toLowerCase(),n=!0}}function p(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return\"\";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return\"\";if((r>>>=0)<=(e>>>=0))return\"\";for(t||(t=\"utf8\");;)switch(t){case\"hex\":return I(this,e,r);case\"utf8\":case\"utf-8\":return A(this,e,r);case\"ascii\":return T(this,e,r);case\"latin1\":case\"binary\":return R(this,e,r);case\"base64\":return x(this,e,r);case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return D(this,e,r);default:if(n)throw new TypeError(\"Unknown encoding: \"+t);t=(t+\"\").toLowerCase(),n=!0}}function v(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function y(t,e,r,n,i){if(0===t.length)return-1;if(\"string\"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if(\"string\"==typeof e&&(e=u.from(e,n)),u.isBuffer(e))return 0===e.length?-1:m(t,e,r,n,i);if(\"number\"==typeof e)return e&=255,u.TYPED_ARRAY_SUPPORT&&\"function\"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):m(t,[e],r,n,i);throw new TypeError(\"val must be string, number or Buffer\")}function m(t,e,r,n,i){var o,s=1,a=t.length,u=e.length;if(void 0!==n&&(\"ucs2\"===(n=String(n).toLowerCase())||\"ucs-2\"===n||\"utf16le\"===n||\"utf-16le\"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,u/=2,r/=2}function c(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var h=-1;for(o=r;oa&&(r=a-u),o=r;o>=0;o--){for(var l=!0,f=0;fi&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError(\"Invalid hex string\");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function x(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function A(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:c>223?3:c>191?2:1;if(i+l<=r)switch(l){case 1:c<128&&(h=c);break;case 2:128==(192&(o=t[i+1]))&&(u=(31&c)<<6|63&o)>127&&(h=u);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(u=(15&c)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(h=u);break;case 4:o=t[i+1],s=t[i+2],a=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(u=(15&c)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(h=u)}null===h?(h=65533,l=1):h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|1023&h),n.push(h),i+=l}return function f(t){var e=t.length;if(e<=C)return String.fromCharCode.apply(String,t);var r=\"\",n=0;for(;n0&&(r=this.toString(\"hex\",0,n).match(/.{2}/g).join(\" \"),this.length>n&&(r+=\" ... \")),\"\"},u.prototype.compare=function t(e,r,n,i,o){if(!u.isBuffer(e))throw new TypeError(\"Argument must be a Buffer\");if(void 0===r&&(r=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===o&&(o=this.length),r<0||n>e.length||i<0||o>this.length)throw new RangeError(\"out of range index\");if(i>=o&&r>=n)return 0;if(i>=o)return-1;if(r>=n)return 1;if(this===e)return 0;for(var s=(o>>>=0)-(i>>>=0),a=(n>>>=0)-(r>>>=0),c=Math.min(s,a),h=this.slice(i,o),l=e.slice(r,n),f=0;fo)&&(n=o),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError(\"Attempt to write outside buffer bounds\");i||(i=\"utf8\");for(var s=!1;;)switch(i){case\"hex\":return _(this,e,r,n);case\"utf8\":case\"utf-8\":return S(this,e,r,n);case\"ascii\":return b(this,e,r,n);case\"latin1\":case\"binary\":return w(this,e,r,n);case\"base64\":return F(this,e,r,n);case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return E(this,e,r,n);default:if(s)throw new TypeError(\"Unknown encoding: \"+i);i=(\"\"+i).toLowerCase(),s=!0}},u.prototype.toJSON=function t(){return{type:\"Buffer\",data:Array.prototype.slice.call(this._arr||this,0)}};var C=4096;function T(t,e,r){var n=\"\";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i=\"\",o=e;or)throw new RangeError(\"Trying to access beyond buffer length\")}function N(t,e,r,n,i,o){if(!u.isBuffer(t))throw new TypeError('\"buffer\" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError(\"Index out of range\")}function U(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function B(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function O(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError(\"Index out of range\");if(r<0)throw new RangeError(\"Index out of range\")}function j(t,e,r,n,o){return o||O(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function M(t,e,r,n,o){return o||O(t,0,r,8),i.write(t,e,r,n,52,8),r+8}u.prototype.slice=function t(e,r){var n,i=this.length;if((e=~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),(r=void 0===r?i:~~r)<0?(r+=i)<0&&(r=0):r>i&&(r=i),r0&&(o*=256);)i+=this[e+--r]*o;return i},u.prototype.readUInt8=function t(e,r){return r||L(e,1,this.length),this[e]},u.prototype.readUInt16LE=function t(e,r){return r||L(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function t(e,r){return r||L(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function t(e,r){return r||L(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function t(e,r){return r||L(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function t(e,r,n){e|=0,r|=0,n||L(e,r,this.length);for(var i=this[e],o=1,s=0;++s=(o*=128)&&(i-=Math.pow(2,8*r)),i},u.prototype.readIntBE=function t(e,r,n){e|=0,r|=0,n||L(e,r,this.length);for(var i=r,o=1,s=this[e+--i];i>0&&(o*=256);)s+=this[e+--i]*o;return s>=(o*=128)&&(s-=Math.pow(2,8*r)),s},u.prototype.readInt8=function t(e,r){return r||L(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function t(e,r){r||L(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt16BE=function t(e,r){r||L(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt32LE=function t(e,r){return r||L(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function t(e,r){return r||L(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function t(e,r){return r||L(e,4,this.length),i.read(this,e,!0,23,4)},u.prototype.readFloatBE=function t(e,r){return r||L(e,4,this.length),i.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function t(e,r){return r||L(e,8,this.length),i.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function t(e,r){return r||L(e,8,this.length),i.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function t(e,r,n,i){(e=+e,r|=0,n|=0,i)||N(this,e,r,n,Math.pow(2,8*n)-1,0);var o=1,s=0;for(this[r]=255&e;++s=0&&(s*=256);)this[r+o]=e/s&255;return r+n},u.prototype.writeUInt8=function t(e,r,n){return e=+e,r|=0,n||N(this,e,r,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[r]=255&e,r+1},u.prototype.writeUInt16LE=function t(e,r,n){return e=+e,r|=0,n||N(this,e,r,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8):U(this,e,r,!0),r+2},u.prototype.writeUInt16BE=function t(e,r,n){return e=+e,r|=0,n||N(this,e,r,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=255&e):U(this,e,r,!1),r+2},u.prototype.writeUInt32LE=function t(e,r,n){return e=+e,r|=0,n||N(this,e,r,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=255&e):B(this,e,r,!0),r+4},u.prototype.writeUInt32BE=function t(e,r,n){return e=+e,r|=0,n||N(this,e,r,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=255&e):B(this,e,r,!1),r+4},u.prototype.writeIntLE=function t(e,r,n,i){if(e=+e,r|=0,!i){var o=Math.pow(2,8*n-1);N(this,e,r,n,o-1,-o)}var s=0,a=1,u=0;for(this[r]=255&e;++s>0)-u&255;return r+n},u.prototype.writeIntBE=function t(e,r,n,i){if(e=+e,r|=0,!i){var o=Math.pow(2,8*n-1);N(this,e,r,n,o-1,-o)}var s=n-1,a=1,u=0;for(this[r+s]=255&e;--s>=0&&(a*=256);)e<0&&0===u&&0!==this[r+s+1]&&(u=1),this[r+s]=(e/a>>0)-u&255;return r+n},u.prototype.writeInt8=function t(e,r,n){return e=+e,r|=0,n||N(this,e,r,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[r]=255&e,r+1},u.prototype.writeInt16LE=function t(e,r,n){return e=+e,r|=0,n||N(this,e,r,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8):U(this,e,r,!0),r+2},u.prototype.writeInt16BE=function t(e,r,n){return e=+e,r|=0,n||N(this,e,r,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=255&e):U(this,e,r,!1),r+2},u.prototype.writeInt32LE=function t(e,r,n){return e=+e,r|=0,n||N(this,e,r,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24):B(this,e,r,!0),r+4},u.prototype.writeInt32BE=function t(e,r,n){return e=+e,r|=0,n||N(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=255&e):B(this,e,r,!1),r+4},u.prototype.writeFloatLE=function t(e,r,n){return j(this,e,r,!0,n)},u.prototype.writeFloatBE=function t(e,r,n){return j(this,e,r,!1,n)},u.prototype.writeDoubleLE=function t(e,r,n){return M(this,e,r,!0,n)},u.prototype.writeDoubleBE=function t(e,r,n){return M(this,e,r,!1,n)},u.prototype.copy=function t(e,r,n,i){if(n||(n=0),i||0===i||(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=this.length)throw new RangeError(\"sourceStart out of bounds\");if(i<0)throw new RangeError(\"sourceEnd out of bounds\");i>this.length&&(i=this.length),e.length-r=0;--o)e[o+r]=this[o+n];else if(s<1e3||!u.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),\"number\"==typeof e)for(s=r;s55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error(\"Invalid code point\");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function q(t){return n.toByteArray(function e(t){if((t=function e(t){return t.trim?t.trim():t.replace(/^\\s+|\\s+$/g,\"\")}(t).replace(H,\"\")).length<2)return\"\";for(;t.length%4!=0;)t+=\"=\";return t}(t))}function J(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}}).call(this,r(29))},function(t,e){var r;r=function(){return this}();try{r=r||new Function(\"return this\")()}catch(t){\"object\"==typeof window&&(r=window)}t.exports=r},function(t,e,r){\"use strict\";e.byteLength=function n(t){var e=f(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function i(t){var e,r,n=f(t),i=n[0],o=n[1],s=new u(function c(t,e,r){return 3*(e+r)/4-r}(0,i,o)),h=0,l=o>0?i-4:i;for(r=0;r>16&255,s[h++]=e>>8&255,s[h++]=255&e;2===o&&(e=a[t.charCodeAt(r)]<<2|a[t.charCodeAt(r+1)]>>4,s[h++]=255&e);1===o&&(e=a[t.charCodeAt(r)]<<10|a[t.charCodeAt(r+1)]<<4|a[t.charCodeAt(r+2)]>>2,s[h++]=e>>8&255,s[h++]=255&e);return s},e.fromByteArray=function o(t){for(var e,r=t.length,n=r%3,i=[],o=16383,a=0,u=r-n;au?u:a+o));1===n?(e=t[r-1],i.push(s[e>>2]+s[e<<4&63]+\"==\")):2===n&&(e=(t[r-2]<<8)+t[r-1],i.push(s[e>>10]+s[e>>4&63]+s[e<<2&63]+\"=\"));return i.join(\"\")};for(var s=[],a=[],u=\"undefined\"!=typeof Uint8Array?Uint8Array:Array,c=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\",h=0,l=c.length;h0)throw new Error(\"Invalid string. Length must be a multiple of 4\");var r=t.indexOf(\"=\");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function g(t,e,r){for(var n,i,o=[],a=e;a>18&63]+s[i>>12&63]+s[i>>6&63]+s[63&i]);return o.join(\"\")}a[\"-\".charCodeAt(0)]=62,a[\"_\".charCodeAt(0)]=63},function(t,e){\n/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\ne.read=function(t,e,r,n,i){var o,s,a=8*i-n-1,u=(1<>1,h=-7,l=r?i-1:0,f=r?-1:1,g=t[e+l];for(l+=f,o=g&(1<<-h)-1,g>>=-h,h+=a;h>0;o=256*o+t[e+l],l+=f,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=n;h>0;s=256*s+t[e+l],l+=f,h-=8);if(0===o)o=1-c;else{if(o===u)return s?NaN:1/0*(g?-1:1);s+=Math.pow(2,n),o-=c}return(g?-1:1)*s*Math.pow(2,o-n)},e.write=function(t,e,r,n,i,o){var s,a,u,c=8*o-i-1,h=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,g=n?0:o-1,d=n?1:-1,p=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+l>=1?f/u:f*Math.pow(2,1-l))*u>=2&&(s++,u/=2),s+l>=h?(a=0,s=h):s+l>=1?(a=(e*u-1)*Math.pow(2,i),s+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),s=0));i>=8;t[r+g]=255&a,g+=d,a/=256,i-=8);for(s=s<0;t[r+g]=255&s,g+=d,s/=256,c-=8);t[r+g-d]|=128*p}},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return\"[object Array]\"==r.call(t)}},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.default=function n(t){var e=t.jws,r=t.KeyUtil,n=t.X509,o=t.crypto,s=t.hextob64u,a=t.b64tohex,u=t.AllowedSigningAlgs;return function(){function t(){!function e(t,r){if(!(t instanceof r))throw new TypeError(\"Cannot call a class as a function\")}(this,t)}return t.parseJwt=function t(r){i.Log.debug(\"JoseUtil.parseJwt\");try{var n=e.JWS.parse(r);return{header:n.headerObj,payload:n.payloadObj}}catch(t){i.Log.error(t)}},t.validateJwt=function e(o,s,u,c,h,l,f){i.Log.debug(\"JoseUtil.validateJwt\");try{if(\"RSA\"===s.kty)if(s.e&&s.n)s=r.getKey(s);else{if(!s.x5c||!s.x5c.length)return i.Log.error(\"JoseUtil.validateJwt: RSA key missing key material\",s),Promise.reject(new Error(\"RSA key missing key material\"));var g=a(s.x5c[0]);s=n.getPublicKeyFromCertHex(g)}else{if(\"EC\"!==s.kty)return i.Log.error(\"JoseUtil.validateJwt: Unsupported key type\",s&&s.kty),Promise.reject(new Error(s.kty));if(!(s.crv&&s.x&&s.y))return i.Log.error(\"JoseUtil.validateJwt: EC key missing key material\",s),Promise.reject(new Error(\"EC key missing key material\"));s=r.getKey(s)}return t._validateJwt(o,s,u,c,h,l,f)}catch(t){return i.Log.error(t&&t.message||t),Promise.reject(\"JWT validation failed\")}},t.validateJwtAttributes=function e(r,n,o,s,a,u){s||(s=0),a||(a=parseInt(Date.now()/1e3));var c=t.parseJwt(r).payload;if(!c.iss)return i.Log.error(\"JoseUtil._validateJwt: issuer was not provided\"),Promise.reject(new Error(\"issuer was not provided\"));if(c.iss!==n)return i.Log.error(\"JoseUtil._validateJwt: Invalid issuer in token\",c.iss),Promise.reject(new Error(\"Invalid issuer in token: \"+c.iss));if(!c.aud)return i.Log.error(\"JoseUtil._validateJwt: aud was not provided\"),Promise.reject(new Error(\"aud was not provided\"));if(!(c.aud===o||Array.isArray(c.aud)&&c.aud.indexOf(o)>=0))return i.Log.error(\"JoseUtil._validateJwt: Invalid audience in token\",c.aud),Promise.reject(new Error(\"Invalid audience in token: \"+c.aud));if(c.azp&&c.azp!==o)return i.Log.error(\"JoseUtil._validateJwt: Invalid azp in token\",c.azp),Promise.reject(new Error(\"Invalid azp in token: \"+c.azp));if(!u){var h=a+s,l=a-s;if(!c.iat)return i.Log.error(\"JoseUtil._validateJwt: iat was not provided\"),Promise.reject(new Error(\"iat was not provided\"));if(h1&&void 0!==arguments[1]?arguments[1]:\"#\";o(this,t);var n=i.UrlUtility.parseUrlFragment(e,r);this.error=n.error,this.error_description=n.error_description,this.error_uri=n.error_uri,this.code=n.code,this.state=n.state,this.id_token=n.id_token,this.session_state=n.session_state,this.access_token=n.access_token,this.token_type=n.token_type,this.scope=n.scope,this.profile=void 0,this.expires_in=n.expires_in}return n(t,[{key:\"expires_in\",get:function t(){if(this.expires_at){var e=parseInt(Date.now()/1e3);return this.expires_at-e}},set:function t(e){var r=parseInt(e);if(\"number\"==typeof r&&r>0){var n=parseInt(Date.now()/1e3);this.expires_at=n+r}}},{key:\"expired\",get:function t(){var e=this.expires_in;if(void 0!==e)return e<=0}},{key:\"scopes\",get:function t(){return(this.scope||\"\").split(\" \")}},{key:\"isOpenIdConnect\",get:function t(){return this.scopes.indexOf(\"openid\")>=0||!!this.id_token}}]),t}()},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.SignoutRequest=void 0;var n=r(0),i=r(3),o=r(9);e.SignoutRequest=function t(e){var r=e.url,s=e.id_token_hint,a=e.post_logout_redirect_uri,u=e.data,c=e.extraQueryParams,h=e.request_type;if(function l(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}(this,t),!r)throw n.Log.error(\"SignoutRequest.ctor: No url passed\"),new Error(\"url\");for(var f in s&&(r=i.UrlUtility.addQueryParam(r,\"id_token_hint\",s)),a&&(r=i.UrlUtility.addQueryParam(r,\"post_logout_redirect_uri\",a),u&&(this.state=new o.State({data:u,request_type:h}),r=i.UrlUtility.addQueryParam(r,\"state\",this.state.id))),c)r=i.UrlUtility.addQueryParam(r,f,c[f]);this.url=r}},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.SignoutResponse=void 0;var n=r(3);e.SignoutResponse=function t(e){!function r(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}(this,t);var i=n.UrlUtility.parseUrlFragment(e,\"?\");this.error=i.error,this.error_description=i.error_description,this.error_uri=i.error_uri,this.state=i.state}},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.InMemoryWebStorage=void 0;var n=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:c.SilentRenewService,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:h.SessionMonitor,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:f.TokenRevocationClient,l=arguments.length>4&&void 0!==arguments[4]?arguments[4]:g.TokenClient,y=arguments.length>5&&void 0!==arguments[5]?arguments[5]:d.JoseUtil;p(this,e),r instanceof s.UserManagerSettings||(r=new s.UserManagerSettings(r));var m=v(this,t.call(this,r));return m._events=new u.UserManagerEvents(r),m._silentRenewService=new n(m),m.settings.automaticSilentRenew&&(i.Log.debug(\"UserManager.ctor: automaticSilentRenew is configured, setting up silent renew\"),m.startSilentRenew()),m.settings.monitorSession&&(i.Log.debug(\"UserManager.ctor: monitorSession is configured, setting up session monitor\"),m._sessionMonitor=new o(m)),m._tokenRevocationClient=new a(m._settings),m._tokenClient=new l(m._settings),m._joseUtil=y,m}return function r(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,t),e.prototype.getUser=function t(){var e=this;return this._loadUser().then((function(t){return t?(i.Log.info(\"UserManager.getUser: user loaded\"),e._events.load(t,!1),t):(i.Log.info(\"UserManager.getUser: user not found in storage\"),null)}))},e.prototype.removeUser=function t(){var e=this;return this.storeUser(null).then((function(){i.Log.info(\"UserManager.removeUser: user removed from storage\"),e._events.unload()}))},e.prototype.signinRedirect=function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type=\"si:r\";var r={useReplaceToNavigate:e.useReplaceToNavigate};return this._signinStart(e,this._redirectNavigator,r).then((function(){i.Log.info(\"UserManager.signinRedirect: successful\")}))},e.prototype.signinRedirectCallback=function t(e){return this._signinEnd(e||this._redirectNavigator.url).then((function(t){return t.profile&&t.profile.sub?i.Log.info(\"UserManager.signinRedirectCallback: successful, signed in sub: \",t.profile.sub):i.Log.info(\"UserManager.signinRedirectCallback: no sub\"),t}))},e.prototype.signinPopup=function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type=\"si:p\";var r=e.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return r?(e.redirect_uri=r,e.display=\"popup\",this._signin(e,this._popupNavigator,{startUrl:r,popupWindowFeatures:e.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:e.popupWindowTarget||this.settings.popupWindowTarget}).then((function(t){return t&&(t.profile&&t.profile.sub?i.Log.info(\"UserManager.signinPopup: signinPopup successful, signed in sub: \",t.profile.sub):i.Log.info(\"UserManager.signinPopup: no sub\")),t}))):(i.Log.error(\"UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured\"),Promise.reject(new Error(\"No popup_redirect_uri or redirect_uri configured\")))},e.prototype.signinPopupCallback=function t(e){return this._signinCallback(e,this._popupNavigator).then((function(t){return t&&(t.profile&&t.profile.sub?i.Log.info(\"UserManager.signinPopupCallback: successful, signed in sub: \",t.profile.sub):i.Log.info(\"UserManager.signinPopupCallback: no sub\")),t})).catch((function(t){i.Log.error(t.message)}))},e.prototype.signinSilent=function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return r=Object.assign({},r),this._loadUser().then((function(t){return t&&t.refresh_token?(r.refresh_token=t.refresh_token,e._useRefreshToken(r)):(r.request_type=\"si:s\",r.id_token_hint=r.id_token_hint||e.settings.includeIdTokenInSilentRenew&&t&&t.id_token,t&&e._settings.validateSubOnSilentRenew&&(i.Log.debug(\"UserManager.signinSilent, subject prior to silent renew: \",t.profile.sub),r.current_sub=t.profile.sub),e._signinSilentIframe(r))}))},e.prototype._useRefreshToken=function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this._tokenClient.exchangeRefreshToken(r).then((function(t){return t?t.access_token?e._loadUser().then((function(r){if(r){var n=Promise.resolve();return t.id_token&&(n=e._validateIdTokenFromTokenRefreshToken(r.profile,t.id_token)),n.then((function(){return i.Log.debug(\"UserManager._useRefreshToken: refresh token response success\"),r.id_token=t.id_token||r.id_token,r.access_token=t.access_token,r.refresh_token=t.refresh_token||r.refresh_token,r.expires_in=t.expires_in,e.storeUser(r).then((function(){return e._events.load(r),r}))}))}return null})):(i.Log.error(\"UserManager._useRefreshToken: No access token returned from token endpoint\"),Promise.reject(\"No access token returned from token endpoint\")):(i.Log.error(\"UserManager._useRefreshToken: No response returned from token endpoint\"),Promise.reject(\"No response returned from token endpoint\"))}))},e.prototype._validateIdTokenFromTokenRefreshToken=function t(e,r){var n=this;return this._metadataService.getIssuer().then((function(t){return n.settings.getEpochTime().then((function(o){return n._joseUtil.validateJwtAttributes(r,t,n._settings.client_id,n._settings.clockSkew,o).then((function(t){return t?t.sub!==e.sub?(i.Log.error(\"UserManager._validateIdTokenFromTokenRefreshToken: sub in id_token does not match current sub\"),Promise.reject(new Error(\"sub in id_token does not match current sub\"))):t.auth_time&&t.auth_time!==e.auth_time?(i.Log.error(\"UserManager._validateIdTokenFromTokenRefreshToken: auth_time in id_token does not match original auth_time\"),Promise.reject(new Error(\"auth_time in id_token does not match original auth_time\"))):t.azp&&t.azp!==e.azp?(i.Log.error(\"UserManager._validateIdTokenFromTokenRefreshToken: azp in id_token does not match original azp\"),Promise.reject(new Error(\"azp in id_token does not match original azp\"))):!t.azp&&e.azp?(i.Log.error(\"UserManager._validateIdTokenFromTokenRefreshToken: azp not in id_token, but present in original id_token\"),Promise.reject(new Error(\"azp not in id_token, but present in original id_token\"))):void 0:(i.Log.error(\"UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token\"),Promise.reject(new Error(\"Failed to validate id_token\")))}))}))}))},e.prototype._signinSilentIframe=function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return r?(e.redirect_uri=r,e.prompt=e.prompt||\"none\",this._signin(e,this._iframeNavigator,{startUrl:r,silentRequestTimeout:e.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(t){return t&&(t.profile&&t.profile.sub?i.Log.info(\"UserManager.signinSilent: successful, signed in sub: \",t.profile.sub):i.Log.info(\"UserManager.signinSilent: no sub\")),t}))):(i.Log.error(\"UserManager.signinSilent: No silent_redirect_uri configured\"),Promise.reject(new Error(\"No silent_redirect_uri configured\")))},e.prototype.signinSilentCallback=function t(e){return this._signinCallback(e,this._iframeNavigator).then((function(t){return t&&(t.profile&&t.profile.sub?i.Log.info(\"UserManager.signinSilentCallback: successful, signed in sub: \",t.profile.sub):i.Log.info(\"UserManager.signinSilentCallback: no sub\")),t}))},e.prototype.signinCallback=function t(e){var r=this;return this.readSigninResponseState(e).then((function(t){var n=t.state;t.response;return\"si:r\"===n.request_type?r.signinRedirectCallback(e):\"si:p\"===n.request_type?r.signinPopupCallback(e):\"si:s\"===n.request_type?r.signinSilentCallback(e):Promise.reject(new Error(\"invalid response_type in state\"))}))},e.prototype.signoutCallback=function t(e,r){var n=this;return this.readSignoutResponseState(e).then((function(t){var i=t.state,o=t.response;return i?\"so:r\"===i.request_type?n.signoutRedirectCallback(e):\"so:p\"===i.request_type?n.signoutPopupCallback(e,r):Promise.reject(new Error(\"invalid response_type in state\")):o}))},e.prototype.querySessionStatus=function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(r=Object.assign({},r)).request_type=\"si:s\";var n=r.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return n?(r.redirect_uri=n,r.prompt=\"none\",r.response_type=r.response_type||this.settings.query_status_response_type,r.scope=r.scope||\"openid\",r.skipUserInfo=!0,this._signinStart(r,this._iframeNavigator,{startUrl:n,silentRequestTimeout:r.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(t){return e.processSigninResponse(t.url).then((function(t){if(i.Log.debug(\"UserManager.querySessionStatus: got signin response\"),t.session_state&&t.profile.sub)return i.Log.info(\"UserManager.querySessionStatus: querySessionStatus success for sub: \",t.profile.sub),{session_state:t.session_state,sub:t.profile.sub,sid:t.profile.sid};i.Log.info(\"querySessionStatus successful, user not authenticated\")})).catch((function(t){if(t.session_state&&e.settings.monitorAnonymousSession&&(\"login_required\"==t.message||\"consent_required\"==t.message||\"interaction_required\"==t.message||\"account_selection_required\"==t.message))return i.Log.info(\"UserManager.querySessionStatus: querySessionStatus success for anonymous user\"),{session_state:t.session_state};throw t}))}))):(i.Log.error(\"UserManager.querySessionStatus: No silent_redirect_uri configured\"),Promise.reject(new Error(\"No silent_redirect_uri configured\")))},e.prototype._signin=function t(e,r){var n=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this._signinStart(e,r,i).then((function(t){return n._signinEnd(t.url,e)}))},e.prototype._signinStart=function t(e,r){var n=this,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.prepare(o).then((function(t){return i.Log.debug(\"UserManager._signinStart: got navigator window handle\"),n.createSigninRequest(e).then((function(e){return i.Log.debug(\"UserManager._signinStart: got signin request\"),o.url=e.url,o.id=e.state.id,t.navigate(o)})).catch((function(e){throw t.close&&(i.Log.debug(\"UserManager._signinStart: Error after preparing navigator, closing navigator window\"),t.close()),e}))}))},e.prototype._signinEnd=function t(e){var r=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.processSigninResponse(e).then((function(t){i.Log.debug(\"UserManager._signinEnd: got signin response\");var e=new a.User(t);if(n.current_sub){if(n.current_sub!==e.profile.sub)return i.Log.debug(\"UserManager._signinEnd: current user does not match user returned from signin. sub from signin: \",e.profile.sub),Promise.reject(new Error(\"login_required\"));i.Log.debug(\"UserManager._signinEnd: current user matches user returned from signin\")}return r.storeUser(e).then((function(){return i.Log.debug(\"UserManager._signinEnd: user stored\"),r._events.load(e),e}))}))},e.prototype._signinCallback=function t(e,r){i.Log.debug(\"UserManager._signinCallback\");var n=\"query\"===this._settings.response_mode||!this._settings.response_mode&&l.SigninRequest.isCode(this._settings.response_type)?\"?\":\"#\";return r.callback(e,void 0,n)},e.prototype.signoutRedirect=function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type=\"so:r\";var r=e.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;r&&(e.post_logout_redirect_uri=r);var n={useReplaceToNavigate:e.useReplaceToNavigate};return this._signoutStart(e,this._redirectNavigator,n).then((function(){i.Log.info(\"UserManager.signoutRedirect: successful\")}))},e.prototype.signoutRedirectCallback=function t(e){return this._signoutEnd(e||this._redirectNavigator.url).then((function(t){return i.Log.info(\"UserManager.signoutRedirectCallback: successful\"),t}))},e.prototype.signoutPopup=function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type=\"so:p\";var r=e.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return e.post_logout_redirect_uri=r,e.display=\"popup\",e.post_logout_redirect_uri&&(e.state=e.state||{}),this._signout(e,this._popupNavigator,{startUrl:r,popupWindowFeatures:e.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:e.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){i.Log.info(\"UserManager.signoutPopup: successful\")}))},e.prototype.signoutPopupCallback=function t(e,r){void 0===r&&\"boolean\"==typeof e&&(r=e,e=null);return this._popupNavigator.callback(e,r,\"?\").then((function(){i.Log.info(\"UserManager.signoutPopupCallback: successful\")}))},e.prototype._signout=function t(e,r){var n=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this._signoutStart(e,r,i).then((function(t){return n._signoutEnd(t.url)}))},e.prototype._signoutStart=function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=this,n=arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.prepare(o).then((function(t){return i.Log.debug(\"UserManager._signoutStart: got navigator window handle\"),r._loadUser().then((function(n){return i.Log.debug(\"UserManager._signoutStart: loaded current user from storage\"),(r._settings.revokeAccessTokenOnSignout?r._revokeInternal(n):Promise.resolve()).then((function(){var s=e.id_token_hint||n&&n.id_token;return s&&(i.Log.debug(\"UserManager._signoutStart: Setting id_token into signout request\"),e.id_token_hint=s),r.removeUser().then((function(){return i.Log.debug(\"UserManager._signoutStart: user removed, creating signout request\"),r.createSignoutRequest(e).then((function(e){return i.Log.debug(\"UserManager._signoutStart: got signout request\"),o.url=e.url,e.state&&(o.id=e.state.id),t.navigate(o)}))}))}))})).catch((function(e){throw t.close&&(i.Log.debug(\"UserManager._signoutStart: Error after preparing navigator, closing navigator window\"),t.close()),e}))}))},e.prototype._signoutEnd=function t(e){return this.processSignoutResponse(e).then((function(t){return i.Log.debug(\"UserManager._signoutEnd: got signout response\"),t}))},e.prototype.revokeAccessToken=function t(){var e=this;return this._loadUser().then((function(t){return e._revokeInternal(t,!0).then((function(r){if(r)return i.Log.debug(\"UserManager.revokeAccessToken: removing token properties from user and re-storing\"),t.access_token=null,t.refresh_token=null,t.expires_at=null,t.token_type=null,e.storeUser(t).then((function(){i.Log.debug(\"UserManager.revokeAccessToken: user stored\"),e._events.load(t)}))}))})).then((function(){i.Log.info(\"UserManager.revokeAccessToken: access token revoked successfully\")}))},e.prototype._revokeInternal=function t(e,r){var n=this;if(e){var o=e.access_token,s=e.refresh_token;return this._revokeAccessTokenInternal(o,r).then((function(t){return n._revokeRefreshTokenInternal(s,r).then((function(e){return t||e||i.Log.debug(\"UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format\"),t||e}))}))}return Promise.resolve(!1)},e.prototype._revokeAccessTokenInternal=function t(e,r){return!e||e.indexOf(\".\")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(e,r).then((function(){return!0}))},e.prototype._revokeRefreshTokenInternal=function t(e,r){return e?this._tokenRevocationClient.revoke(e,r,\"refresh_token\").then((function(){return!0})):Promise.resolve(!1)},e.prototype.startSilentRenew=function t(){this._silentRenewService.start()},e.prototype.stopSilentRenew=function t(){this._silentRenewService.stop()},e.prototype._loadUser=function t(){return this._userStore.get(this._userStoreKey).then((function(t){return t?(i.Log.debug(\"UserManager._loadUser: user storageString loaded\"),a.User.fromStorageString(t)):(i.Log.debug(\"UserManager._loadUser: no user storageString\"),null)}))},e.prototype.storeUser=function t(e){if(e){i.Log.debug(\"UserManager.storeUser: storing user\");var r=e.toStorageString();return this._userStore.set(this._userStoreKey,r)}return i.Log.debug(\"storeUser.storeUser: removing user\"),this._userStore.remove(this._userStoreKey)},n(e,[{key:\"_redirectNavigator\",get:function t(){return this.settings.redirectNavigator}},{key:\"_popupNavigator\",get:function t(){return this.settings.popupNavigator}},{key:\"_iframeNavigator\",get:function t(){return this.settings.iframeNavigator}},{key:\"_userStore\",get:function t(){return this.settings.userStore}},{key:\"events\",get:function t(){return this._events}},{key:\"_userStoreKey\",get:function t(){return\"user:\"+this.settings.authority+\":\"+this.settings.client_id}}]),e}(o.OidcClient)},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.UserManagerSettings=void 0;var n=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=r.popup_redirect_uri,i=r.popup_post_logout_redirect_uri,g=r.popupWindowFeatures,d=r.popupWindowTarget,p=r.silent_redirect_uri,v=r.silentRequestTimeout,y=r.automaticSilentRenew,m=void 0!==y&&y,_=r.validateSubOnSilentRenew,S=void 0!==_&&_,b=r.includeIdTokenInSilentRenew,w=void 0===b||b,F=r.monitorSession,E=void 0===F||F,x=r.monitorAnonymousSession,A=void 0!==x&&x,k=r.checkSessionInterval,P=void 0===k?2e3:k,C=r.stopCheckSessionOnError,T=void 0===C||C,R=r.query_status_response_type,I=r.revokeAccessTokenOnSignout,D=void 0!==I&&I,L=r.accessTokenExpiringNotificationTime,N=void 0===L?60:L,U=r.redirectNavigator,B=void 0===U?new o.RedirectNavigator:U,O=r.popupNavigator,j=void 0===O?new s.PopupNavigator:O,M=r.iframeNavigator,H=void 0===M?new a.IFrameNavigator:M,V=r.userStore,K=void 0===V?new u.WebStorageStateStore({store:c.Global.sessionStorage}):V;l(this,e);var q=f(this,t.call(this,arguments[0]));return q._popup_redirect_uri=n,q._popup_post_logout_redirect_uri=i,q._popupWindowFeatures=g,q._popupWindowTarget=d,q._silent_redirect_uri=p,q._silentRequestTimeout=v,q._automaticSilentRenew=m,q._validateSubOnSilentRenew=S,q._includeIdTokenInSilentRenew=w,q._accessTokenExpiringNotificationTime=N,q._monitorSession=E,q._monitorAnonymousSession=A,q._checkSessionInterval=P,q._stopCheckSessionOnError=T,R?q._query_status_response_type=R:arguments[0]&&arguments[0].response_type?q._query_status_response_type=h.SigninRequest.isOidc(arguments[0].response_type)?\"id_token\":\"code\":q._query_status_response_type=\"id_token\",q._revokeAccessTokenOnSignout=D,q._redirectNavigator=B,q._popupNavigator=j,q._iframeNavigator=H,q._userStore=K,q}return function r(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,t),n(e,[{key:\"popup_redirect_uri\",get:function t(){return this._popup_redirect_uri}},{key:\"popup_post_logout_redirect_uri\",get:function t(){return this._popup_post_logout_redirect_uri}},{key:\"popupWindowFeatures\",get:function t(){return this._popupWindowFeatures}},{key:\"popupWindowTarget\",get:function t(){return this._popupWindowTarget}},{key:\"silent_redirect_uri\",get:function t(){return this._silent_redirect_uri}},{key:\"silentRequestTimeout\",get:function t(){return this._silentRequestTimeout}},{key:\"automaticSilentRenew\",get:function t(){return this._automaticSilentRenew}},{key:\"validateSubOnSilentRenew\",get:function t(){return this._validateSubOnSilentRenew}},{key:\"includeIdTokenInSilentRenew\",get:function t(){return this._includeIdTokenInSilentRenew}},{key:\"accessTokenExpiringNotificationTime\",get:function t(){return this._accessTokenExpiringNotificationTime}},{key:\"monitorSession\",get:function t(){return this._monitorSession}},{key:\"monitorAnonymousSession\",get:function t(){return this._monitorAnonymousSession}},{key:\"checkSessionInterval\",get:function t(){return this._checkSessionInterval}},{key:\"stopCheckSessionOnError\",get:function t(){return this._stopCheckSessionOnError}},{key:\"query_status_response_type\",get:function t(){return this._query_status_response_type}},{key:\"revokeAccessTokenOnSignout\",get:function t(){return this._revokeAccessTokenOnSignout}},{key:\"redirectNavigator\",get:function t(){return this._redirectNavigator}},{key:\"popupNavigator\",get:function t(){return this._popupNavigator}},{key:\"iframeNavigator\",get:function t(){return this._iframeNavigator}},{key:\"userStore\",get:function t(){return this._userStore}}]),e}(i.OidcClientSettings)},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.RedirectNavigator=void 0;var n=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1])||arguments[1];n.Log.debug(\"UserManagerEvents.load\"),t.prototype.load.call(this,r),i&&this._userLoaded.raise(r)},e.prototype.unload=function e(){n.Log.debug(\"UserManagerEvents.unload\"),t.prototype.unload.call(this),this._userUnloaded.raise()},e.prototype.addUserLoaded=function t(e){this._userLoaded.addHandler(e)},e.prototype.removeUserLoaded=function t(e){this._userLoaded.removeHandler(e)},e.prototype.addUserUnloaded=function t(e){this._userUnloaded.addHandler(e)},e.prototype.removeUserUnloaded=function t(e){this._userUnloaded.removeHandler(e)},e.prototype.addSilentRenewError=function t(e){this._silentRenewError.addHandler(e)},e.prototype.removeSilentRenewError=function t(e){this._silentRenewError.removeHandler(e)},e.prototype._raiseSilentRenewError=function t(e){n.Log.debug(\"UserManagerEvents._raiseSilentRenewError\",e.message),this._silentRenewError.raise(e)},e.prototype.addUserSignedIn=function t(e){this._userSignedIn.addHandler(e)},e.prototype.removeUserSignedIn=function t(e){this._userSignedIn.removeHandler(e)},e.prototype._raiseUserSignedIn=function t(){n.Log.debug(\"UserManagerEvents._raiseUserSignedIn\"),this._userSignedIn.raise()},e.prototype.addUserSignedOut=function t(e){this._userSignedOut.addHandler(e)},e.prototype.removeUserSignedOut=function t(e){this._userSignedOut.removeHandler(e)},e.prototype._raiseUserSignedOut=function t(){n.Log.debug(\"UserManagerEvents._raiseUserSignedOut\"),this._userSignedOut.raise()},e.prototype.addUserSessionChanged=function t(e){this._userSessionChanged.addHandler(e)},e.prototype.removeUserSessionChanged=function t(e){this._userSessionChanged.removeHandler(e)},e.prototype._raiseUserSessionChanged=function t(){n.Log.debug(\"UserManagerEvents._raiseUserSessionChanged\"),this._userSessionChanged.raise()},e}(i.AccessTokenEvents)},function(t,e,r){\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0}),e.Timer=void 0;var n=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:o.Global.timer,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;a(this,e);var s=u(this,t.call(this,r));return s._timer=n,s._nowFunc=i||function(){return Date.now()/1e3},s}return function r(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,t),e.prototype.init=function t(e){e<=0&&(e=1),e=parseInt(e);var r=this.now+e;if(this.expiration===r&&this._timerHandle)i.Log.debug(\"Timer.init timer \"+this._name+\" skipping initialization since already initialized for expiration:\",this.expiration);else{this.cancel(),i.Log.debug(\"Timer.init timer \"+this._name+\" for duration:\",e),this._expiration=r;var n=5;e {\n var _a, _b;\n // In order to get a clean start, make sure that the session is logged out\n // on login.\n // But we may want to preserve our client application info, particularly if\n // we used Dynamic Client Registration to register (since we don't\n // necessarily want the user to have to register this app each time they\n // login).\n await this.sessionInfoManager.clear(options.sessionId);\n // In the case of the user hitting the 'back' button in their browser, they\n // could return to a previous redirect URL that contains OIDC params that\n // are now longer valid. To be safe, strip relevant params now.\n // If the user is providing a redirect IRI, it should not be modified, so\n // normalization only applies if we default to the current location (which is\n // a bad practice and should be discouraged).\n const redirectUrl = (_a = options.redirectUrl) !== null && _a !== void 0 ? _a : oidcClientExt.normalizeCallbackUrl(window.location.href);\n if (!solidClientAuthnCore.isValidRedirectUrl(redirectUrl)) {\n throw new Error(`${redirectUrl} is not a valid redirect URL, it is either a malformed IRI, includes a hash fragment, or reserved query parameters ('code' or 'state').`);\n }\n await this.loginHandler.handle({\n ...options,\n redirectUrl,\n // If no clientName is provided, the clientId may be used instead.\n clientName: (_b = options.clientName) !== null && _b !== void 0 ? _b : options.clientId,\n eventEmitter,\n });\n };\n // Collects session information from storage, and returns them. Returns null\n // if the expected information cannot be found.\n // Note that the ID token is not stored, which means the session information\n // cannot be validated at this point.\n this.validateCurrentSession = async (currentSessionId) => {\n const sessionInfo = await this.sessionInfoManager.get(currentSessionId);\n if (sessionInfo === undefined ||\n sessionInfo.clientAppId === undefined ||\n sessionInfo.issuer === undefined) {\n return null;\n }\n return sessionInfo;\n };\n this.handleIncomingRedirect = async (url, eventEmitter) => {\n try {\n const redirectInfo = await this.redirectHandler.handle(url, eventEmitter);\n // The `FallbackRedirectHandler` directly returns the global `fetch` for\n // his value, so we should ensure it's bound to `window` rather than to\n // ClientAuthentication, to avoid the following error:\n // > 'fetch' called on an object that does not implement interface Window.\n this.fetch = redirectInfo.fetch.bind(window);\n this.boundLogout = redirectInfo.getLogoutUrl;\n // Strip the oauth params:\n await this.cleanUrlAfterRedirect(url);\n return {\n isLoggedIn: redirectInfo.isLoggedIn,\n webId: redirectInfo.webId,\n sessionId: redirectInfo.sessionId,\n expirationDate: redirectInfo.expirationDate,\n };\n }\n catch (err) {\n // Strip the oauth params:\n await this.cleanUrlAfterRedirect(url);\n // FIXME: EVENTS.ERROR should be errorCode, errorDescription\n //\n // I'm not sure if \"redirect\" is a good error code, and in theory `err`\n // maybe an Error object and not a string; Maybe we want to just hardcode\n // a description instead?\n eventEmitter.emit(solidClientAuthnCore.EVENTS.ERROR, \"redirect\", err);\n return undefined;\n }\n };\n }\n async cleanUrlAfterRedirect(url) {\n const cleanedUpUrl = solidClientAuthnCore.removeOpenIdParams(url).href;\n // Remove OAuth-specific query params (since the login flow finishes with\n // the browser being redirected back with OAuth2 query params (e.g. for\n // 'code' and 'state'), and so if the user simply refreshes this page our\n // authentication library will be called again with what are now invalid\n // query parameters!).\n window.history.replaceState(null, \"\", cleanedUpUrl);\n while (window.location.href !== cleanedUpUrl) {\n // Poll the current URL every ms. Active polling is required because\n // window.history.replaceState is asynchronous, but the associated\n // 'popstate' event which should be listened to is only sent on active\n // navigation, which we will not have here.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event#when_popstate_is_sent\n // eslint-disable-next-line no-await-in-loop\n await new Promise((resolve) => {\n setTimeout(() => resolve(), 1);\n });\n }\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction hasIssuer(options) {\n return typeof options.oidcIssuer === \"string\";\n}\nfunction hasRedirectUrl(options) {\n return typeof options.redirectUrl === \"string\";\n}\n/**\n * @hidden\n */\nclass OidcLoginHandler {\n constructor(storageUtility, oidcHandler, issuerConfigFetcher, clientRegistrar) {\n this.storageUtility = storageUtility;\n this.oidcHandler = oidcHandler;\n this.issuerConfigFetcher = issuerConfigFetcher;\n this.clientRegistrar = clientRegistrar;\n this.storageUtility = storageUtility;\n this.oidcHandler = oidcHandler;\n this.issuerConfigFetcher = issuerConfigFetcher;\n this.clientRegistrar = clientRegistrar;\n }\n async canHandle(options) {\n return hasIssuer(options) && hasRedirectUrl(options);\n }\n async handle(options) {\n if (!hasIssuer(options)) {\n throw new solidClientAuthnCore.ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(options)}`);\n }\n if (!hasRedirectUrl(options)) {\n throw new solidClientAuthnCore.ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(options)}`);\n }\n // Fetch issuer config.\n const issuerConfig = await this.issuerConfigFetcher.fetchConfig(options.oidcIssuer);\n const clientRegistration = await solidClientAuthnCore.handleRegistration(options, issuerConfig, this.storageUtility, this.clientRegistrar);\n // Construct OIDC Options\n const OidcOptions = {\n // Note that here, the issuer is not the one from the received options, but\n // from the issuer's config. This enforces the canonical URL is used and stored,\n // which is also the one present in the ID token, so storing a technically\n // valid, but different issuer URL (e.g. using a trailing slash or not) now\n // could prevent from validating the ID token later.\n issuer: issuerConfig.issuer,\n // TODO: differentiate if DPoP should be true\n dpop: options.tokenType.toLowerCase() === \"dpop\",\n ...options,\n issuerConfiguration: issuerConfig,\n client: clientRegistration,\n };\n // Call proper OIDC Handler\n return this.oidcHandler.handle(OidcOptions);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * Authorization code flow spec: https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth\n * PKCE: https://tools.ietf.org/html/rfc7636\n */\nclass AuthorizationCodeWithPkceOidcHandler extends solidClientAuthnCore.AuthorizationCodeWithPkceOidcHandlerBase {\n async handle(oidcLoginOptions) {\n var _a;\n /* eslint-disable camelcase */\n const oidcOptions = {\n authority: oidcLoginOptions.issuer.toString(),\n client_id: oidcLoginOptions.client.clientId,\n client_secret: oidcLoginOptions.client.clientSecret,\n redirect_uri: oidcLoginOptions.redirectUrl.toString(),\n post_logout_redirect_uri: oidcLoginOptions.redirectUrl.toString(),\n response_type: \"code\",\n scope: solidClientAuthnCore.DEFAULT_SCOPES,\n filterProtocolClaims: true,\n // The userinfo endpoint on NSS fails, so disable this for now\n // Note that in Solid, information should be retrieved from the\n // profile referenced by the WebId.\n loadUserInfo: false,\n code_verifier: true,\n prompt: (_a = oidcLoginOptions.prompt) !== null && _a !== void 0 ? _a : \"consent\",\n };\n /* eslint-enable camelcase */\n const oidcClientLibrary = new oidcClientExt.OidcClient(oidcOptions);\n try {\n const signingRequest = await oidcClientLibrary.createSigninRequest();\n // Make sure to await the promise before returning so that the error is caught.\n return await this.handleRedirect({\n oidcLoginOptions,\n // eslint-disable-next-line no-underscore-dangle\n state: signingRequest.state._id,\n // eslint-disable-next-line no-underscore-dangle\n codeVerifier: signingRequest.state._code_verifier,\n targetUrl: signingRequest.url.toString(),\n });\n }\n catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n // The login is only completed AFTER redirect, so nothing to return here.\n return undefined;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst WELL_KNOWN_OPENID_CONFIG = \".well-known/openid-configuration\";\n/* eslint-disable camelcase */\nconst issuerConfigKeyMap = {\n issuer: {\n toKey: \"issuer\",\n convertToUrl: true,\n },\n authorization_endpoint: {\n toKey: \"authorizationEndpoint\",\n convertToUrl: true,\n },\n token_endpoint: {\n toKey: \"tokenEndpoint\",\n convertToUrl: true,\n },\n userinfo_endpoint: {\n toKey: \"userinfoEndpoint\",\n convertToUrl: true,\n },\n jwks_uri: {\n toKey: \"jwksUri\",\n convertToUrl: true,\n },\n registration_endpoint: {\n toKey: \"registrationEndpoint\",\n convertToUrl: true,\n },\n end_session_endpoint: {\n toKey: \"endSessionEndpoint\",\n convertToUrl: true,\n },\n scopes_supported: { toKey: \"scopesSupported\" },\n response_types_supported: { toKey: \"responseTypesSupported\" },\n response_modes_supported: { toKey: \"responseModesSupported\" },\n grant_types_supported: { toKey: \"grantTypesSupported\" },\n acr_values_supported: { toKey: \"acrValuesSupported\" },\n subject_types_supported: { toKey: \"subjectTypesSupported\" },\n id_token_signing_alg_values_supported: {\n toKey: \"idTokenSigningAlgValuesSupported\",\n },\n id_token_encryption_alg_values_supported: {\n toKey: \"idTokenEncryptionAlgValuesSupported\",\n },\n id_token_encryption_enc_values_supported: {\n toKey: \"idTokenEncryptionEncValuesSupported\",\n },\n userinfo_signing_alg_values_supported: {\n toKey: \"userinfoSigningAlgValuesSupported\",\n },\n userinfo_encryption_alg_values_supported: {\n toKey: \"userinfoEncryptionAlgValuesSupported\",\n },\n userinfo_encryption_enc_values_supported: {\n toKey: \"userinfoEncryptionEncValuesSupported\",\n },\n request_object_signing_alg_values_supported: {\n toKey: \"requestObjectSigningAlgValuesSupported\",\n },\n request_object_encryption_alg_values_supported: {\n toKey: \"requestObjectEncryptionAlgValuesSupported\",\n },\n request_object_encryption_enc_values_supported: {\n toKey: \"requestObjectEncryptionEncValuesSupported\",\n },\n token_endpoint_auth_methods_supported: {\n toKey: \"tokenEndpointAuthMethodsSupported\",\n },\n token_endpoint_auth_signing_alg_values_supported: {\n toKey: \"tokenEndpointAuthSigningAlgValuesSupported\",\n },\n display_values_supported: { toKey: \"displayValuesSupported\" },\n claim_types_supported: { toKey: \"claimTypesSupported\" },\n claims_supported: { toKey: \"claimsSupported\" },\n service_documentation: { toKey: \"serviceDocumentation\" },\n claims_locales_supported: { toKey: \"claimsLocalesSupported\" },\n ui_locales_supported: { toKey: \"uiLocalesSupported\" },\n claims_parameter_supported: { toKey: \"claimsParameterSupported\" },\n request_parameter_supported: { toKey: \"requestParameterSupported\" },\n request_uri_parameter_supported: { toKey: \"requestUriParameterSupported\" },\n require_request_uri_registration: { toKey: \"requireRequestUriRegistration\" },\n op_policy_uri: {\n toKey: \"opPolicyUri\",\n convertToUrl: true,\n },\n op_tos_uri: {\n toKey: \"opTosUri\",\n convertToUrl: true,\n },\n};\n/* eslint-enable camelcase */\nfunction processConfig(config) {\n const parsedConfig = {};\n Object.keys(config).forEach((key) => {\n if (issuerConfigKeyMap[key]) {\n // TODO: PMcB55: Validate URL if \"issuerConfigKeyMap[key].convertToUrl\"\n // if (issuerConfigKeyMap[key].convertToUrl) {\n // validateUrl(config[key]);\n // }\n parsedConfig[issuerConfigKeyMap[key].toKey] = config[key];\n }\n });\n if (!Array.isArray(parsedConfig.scopesSupported)) {\n parsedConfig.scopesSupported = [\"openid\"];\n }\n return parsedConfig;\n}\n/**\n * @hidden\n */\nclass IssuerConfigFetcher {\n constructor(storageUtility) {\n this.storageUtility = storageUtility;\n this.storageUtility = storageUtility;\n }\n // This method needs no state (so can be static), and can be exposed to allow\n // callers to know where this implementation puts state it needs.\n static getLocalStorageKey(issuer) {\n return `issuerConfig:${issuer}`;\n }\n async fetchConfig(issuer) {\n let issuerConfig;\n const openIdConfigUrl = new URL(WELL_KNOWN_OPENID_CONFIG, \n // Make sure to append a slash at issuer URL, so that the .well-known URL\n // includes the full issuer path. See https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig.\n issuer.endsWith(\"/\") ? issuer : `${issuer}/`).href;\n const issuerConfigRequestBody = await universalFetch.fetch.call(globalThis, openIdConfigUrl);\n // Check the validity of the fetched config\n try {\n issuerConfig = processConfig(await issuerConfigRequestBody.json());\n }\n catch (err) {\n throw new solidClientAuthnCore.ConfigurationError(`[${issuer.toString()}] has an invalid configuration: ${err.message}`);\n }\n // Update store with fetched config\n await this.storageUtility.set(IssuerConfigFetcher.getLocalStorageKey(issuer), JSON.stringify(issuerConfig));\n return issuerConfig;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @param sessionId\n * @param storage\n * @hidden\n */\nasync function clear(sessionId, storage) {\n await solidClientAuthnCore.clear(sessionId, storage);\n await oidcClientExt.clearOidcPersistentStorage();\n}\n/**\n * @hidden\n */\nclass SessionInfoManager extends solidClientAuthnCore.SessionInfoManagerBase {\n async get(sessionId) {\n const [isLoggedIn, webId, clientId, clientSecret, redirectUrl, refreshToken, issuer, tokenType,] = await Promise.all([\n this.storageUtility.getForUser(sessionId, \"isLoggedIn\", {\n secure: true,\n }),\n this.storageUtility.getForUser(sessionId, \"webId\", {\n secure: true,\n }),\n this.storageUtility.getForUser(sessionId, \"clientId\", {\n secure: false,\n }),\n this.storageUtility.getForUser(sessionId, \"clientSecret\", {\n secure: false,\n }),\n this.storageUtility.getForUser(sessionId, \"redirectUrl\", {\n secure: false,\n }),\n this.storageUtility.getForUser(sessionId, \"refreshToken\", {\n secure: true,\n }),\n this.storageUtility.getForUser(sessionId, \"issuer\", {\n secure: false,\n }),\n this.storageUtility.getForUser(sessionId, \"tokenType\", {\n secure: false,\n }),\n ]);\n if (typeof redirectUrl === \"string\" && !solidClientAuthnCore.isValidRedirectUrl(redirectUrl)) {\n // This resolves the issue for people experiencing https://github.com/inrupt/solid-client-authn-js/issues/2891.\n // An invalid redirect URL is present in the storage, and the session should\n // be cleared to get a fresh start. This will require the user to log back in.\n await Promise.all([\n this.storageUtility.deleteAllUserData(sessionId, { secure: false }),\n this.storageUtility.deleteAllUserData(sessionId, { secure: true }),\n ]);\n return undefined;\n }\n if (tokenType !== undefined && !solidClientAuthnCore.isSupportedTokenType(tokenType)) {\n throw new Error(`Tokens of type [${tokenType}] are not supported.`);\n }\n if (clientId === undefined &&\n isLoggedIn === undefined &&\n webId === undefined &&\n refreshToken === undefined) {\n return undefined;\n }\n return {\n sessionId,\n webId,\n isLoggedIn: isLoggedIn === \"true\",\n redirectUrl,\n refreshToken,\n issuer,\n clientAppId: clientId,\n clientAppSecret: clientSecret,\n // Default the token type to DPoP if unspecified.\n tokenType: tokenType !== null && tokenType !== void 0 ? tokenType : \"DPoP\",\n };\n }\n /**\n * This function removes all session-related information from storage.\n * @param sessionId the session identifier\n * @param storage the storage where session info is stored\n * @hidden\n */\n async clear(sessionId) {\n return clear(sessionId, this.storageUtility);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * This class handles redirect IRIs without any query params, and returns an unauthenticated\n * session. It serves as a fallback so that consuming libraries don't have to test\n * for the query params themselves, and can always try to use them as a redirect IRI.\n * @hidden\n */\nclass FallbackRedirectHandler {\n async canHandle(redirectUrl) {\n try {\n // The next URL object is built for validating it.\n // eslint-disable-next-line no-new\n new URL(redirectUrl);\n return true;\n }\n catch (e) {\n throw new Error(`[${redirectUrl}] is not a valid URL, and cannot be used as a redirect URL: ${e}`);\n }\n }\n async handle(\n // The argument is ignored, but must be present to implement the interface\n _redirectUrl) {\n return solidClientAuthnCore.getUnauthenticatedSession();\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n// FIXME: The following doesn't work in the browser, it results in all the fetches\n// being unauthenticated. This should be looked into when migrating to universal-fetch.\n// import { fetch } from \"cross-fetch\";\nconst globalFetch = (...args) => universalFetch.fetch.call(globalThis, ...args);\n/**\n * @hidden\n */\nclass AuthCodeRedirectHandler {\n constructor(storageUtility, sessionInfoManager, issuerConfigFetcher, clientRegistrar, tokerRefresher) {\n this.storageUtility = storageUtility;\n this.sessionInfoManager = sessionInfoManager;\n this.issuerConfigFetcher = issuerConfigFetcher;\n this.clientRegistrar = clientRegistrar;\n this.tokerRefresher = tokerRefresher;\n this.storageUtility = storageUtility;\n this.sessionInfoManager = sessionInfoManager;\n this.issuerConfigFetcher = issuerConfigFetcher;\n this.clientRegistrar = clientRegistrar;\n this.tokerRefresher = tokerRefresher;\n }\n async canHandle(redirectUrl) {\n try {\n const myUrl = new URL(redirectUrl);\n return (myUrl.searchParams.get(\"code\") !== null &&\n myUrl.searchParams.get(\"state\") !== null);\n }\n catch (e) {\n throw new Error(`[${redirectUrl}] is not a valid URL, and cannot be used as a redirect URL: ${e}`);\n }\n }\n async handle(redirectUrl, eventEmitter) {\n if (!(await this.canHandle(redirectUrl))) {\n throw new Error(`AuthCodeRedirectHandler cannot handle [${redirectUrl}]: it is missing one of [code, state].`);\n }\n const url = new URL(redirectUrl);\n const oauthState = url.searchParams.get(\"state\");\n const storedSessionId = (await this.storageUtility.getForUser(oauthState, \"sessionId\", {\n errorIfNull: true,\n }));\n const { issuerConfig, codeVerifier, redirectUrl: storedRedirectIri, dpop: isDpop, } = await solidClientAuthnCore.loadOidcContextFromStorage(storedSessionId, this.storageUtility, this.issuerConfigFetcher);\n const iss = url.searchParams.get(\"iss\");\n if (typeof iss === \"string\" && iss !== issuerConfig.issuer) {\n throw new Error(`The value of the iss parameter (${iss}) does not match the issuer identifier of the authorization server (${issuerConfig.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);\n }\n if (codeVerifier === undefined) {\n throw new Error(`The code verifier for session ${storedSessionId} is missing from storage.`);\n }\n if (storedRedirectIri === undefined) {\n throw new Error(`The redirect URL for session ${storedSessionId} is missing from storage.`);\n }\n const client = await this.clientRegistrar.getClient({ sessionId: storedSessionId }, issuerConfig);\n let tokens;\n const tokenCreatedAt = Date.now();\n if (isDpop) {\n tokens = await oidcClientExt.getDpopToken(issuerConfig, client, {\n grantType: \"authorization_code\",\n // We rely on our 'canHandle' function checking that the OAuth 'code'\n // parameter is present in our query string.\n code: url.searchParams.get(\"code\"),\n codeVerifier,\n redirectUrl: storedRedirectIri,\n });\n // Delete oidc-client-specific session information from storage. This is\n // done automatically when retrieving a bearer token, but since the DPoP\n // binding uses our custom code, this needs to be done manually.\n window.localStorage.removeItem(`oidc.${oauthState}`);\n }\n else {\n tokens = await oidcClientExt.getBearerToken(url.toString());\n }\n let refreshOptions;\n if (tokens.refreshToken !== undefined) {\n refreshOptions = {\n sessionId: storedSessionId,\n refreshToken: tokens.refreshToken,\n tokenRefresher: this.tokerRefresher,\n };\n }\n const authFetch = await solidClientAuthnCore.buildAuthenticatedFetch(globalFetch, tokens.accessToken, {\n dpopKey: tokens.dpopKey,\n refreshOptions,\n eventEmitter,\n expiresIn: tokens.expiresIn,\n });\n await this.storageUtility.setForUser(storedSessionId, {\n webId: tokens.webId,\n isLoggedIn: \"true\",\n }, { secure: true });\n const sessionInfo = await this.sessionInfoManager.get(storedSessionId);\n if (!sessionInfo) {\n throw new Error(`Could not retrieve session: [${storedSessionId}].`);\n }\n return Object.assign(sessionInfo, {\n fetch: authFetch,\n getLogoutUrl: solidClientAuthnCore.maybeBuildRpInitiatedLogout({\n idTokenHint: tokens.idToken,\n endSessionEndpoint: issuerConfig.endSessionEndpoint,\n }),\n expirationDate: typeof tokens.expiresIn === \"number\"\n ? tokenCreatedAt + tokens.expiresIn * 1000\n : undefined,\n });\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n */\nclass AggregateRedirectHandler extends solidClientAuthnCore.AggregateHandler {\n constructor(redirectHandlers) {\n super(redirectHandlers);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n */\nclass BrowserStorage {\n get storage() {\n return window.localStorage;\n }\n async get(key) {\n return this.storage.getItem(key) || undefined;\n }\n async set(key, value) {\n this.storage.setItem(key, value);\n }\n async delete(key) {\n this.storage.removeItem(key);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n */\nclass Redirector {\n redirect(redirectUrl, options) {\n if (options && options.handleRedirect) {\n options.handleRedirect(redirectUrl);\n }\n else if (options && options.redirectByReplacingState) {\n window.history.replaceState({}, \"\", redirectUrl);\n }\n else {\n window.location.href = redirectUrl;\n }\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n */\nclass ClientRegistrar {\n constructor(storageUtility) {\n this.storageUtility = storageUtility;\n this.storageUtility = storageUtility;\n }\n async getClient(options, issuerConfig) {\n // If client secret and/or client id are stored in storage, use those.\n const [storedClientId, storedClientSecret,\n // storedClientName,\n ] = await Promise.all([\n this.storageUtility.getForUser(options.sessionId, \"clientId\", {\n secure: false,\n }),\n this.storageUtility.getForUser(options.sessionId, \"clientSecret\", {\n secure: false,\n }),\n // this.storageUtility.getForUser(options.sessionId, \"clientName\", {\n // // FIXME: figure out how to persist secure storage at reload\n // secure: false,\n // }),\n ]);\n if (storedClientId) {\n return {\n clientId: storedClientId,\n clientSecret: storedClientSecret,\n clientType: \"dynamic\",\n };\n }\n try {\n const registeredClient = await oidcClientExt.registerClient(options, issuerConfig);\n // Save info\n const infoToSave = {\n clientId: registeredClient.clientId,\n };\n if (registeredClient.clientSecret) {\n infoToSave.clientSecret = registeredClient.clientSecret;\n }\n if (registeredClient.idTokenSignedResponseAlg) {\n infoToSave.idTokenSignedResponseAlg =\n registeredClient.idTokenSignedResponseAlg;\n }\n await this.storageUtility.setForUser(options.sessionId, infoToSave, {\n // FIXME: figure out how to persist secure storage at reload\n // Otherwise, the client info cannot be retrieved from storage, and\n // the lib tries to re-register the client on each fetch\n secure: false,\n });\n return registeredClient;\n }\n catch (error) {\n throw new Error(`Client registration failed: [${error}]`);\n }\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * This class handles redirect IRIs without any query params, and returns an unauthenticated\n * session. It serves as a fallback so that consuming libraries don't have to test\n * for the query params themselves, and can always try to use them as a redirect IRI.\n * @hidden\n */\nclass ErrorOidcHandler {\n async canHandle(redirectUrl) {\n try {\n // eslint-disable-next-line no-new\n return new URL(redirectUrl).searchParams.has(\"error\");\n }\n catch (e) {\n throw new Error(`[${redirectUrl}] is not a valid URL, and cannot be used as a redirect URL: ${e}`);\n }\n }\n async handle(redirectUrl, eventEmitter) {\n if (eventEmitter !== undefined) {\n const url = new URL(redirectUrl);\n const errorUrl = url.searchParams.get(\"error\");\n const errorDescriptionUrl = url.searchParams.get(\"error_description\");\n eventEmitter.emit(solidClientAuthnCore.EVENTS.ERROR, errorUrl, errorDescriptionUrl);\n }\n return solidClientAuthnCore.getUnauthenticatedSession();\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// Some identifiers are not in camelcase on purpose, as they are named using the\n// official names from the OIDC/OAuth2 specifications.\n/* eslint-disable camelcase */\n/**\n * @hidden\n */\nclass TokenRefresher {\n constructor(storageUtility, issuerConfigFetcher, clientRegistrar) {\n this.storageUtility = storageUtility;\n this.issuerConfigFetcher = issuerConfigFetcher;\n this.clientRegistrar = clientRegistrar;\n this.storageUtility = storageUtility;\n this.issuerConfigFetcher = issuerConfigFetcher;\n this.clientRegistrar = clientRegistrar;\n }\n async refresh(sessionId, refreshToken, dpopKey, eventEmitter) {\n const oidcContext = await solidClientAuthnCore.loadOidcContextFromStorage(sessionId, this.storageUtility, this.issuerConfigFetcher);\n // This should also retrieve the client from storage\n const clientInfo = await this.clientRegistrar.getClient({ sessionId }, oidcContext.issuerConfig);\n if (refreshToken === undefined) {\n // TODO: in a next PR, look up storage for a refresh token\n throw new Error(`Session [${sessionId}] has no refresh token to allow it to refresh its access token.`);\n }\n if (oidcContext.dpop && dpopKey === undefined) {\n throw new Error(`For session [${sessionId}], the key bound to the DPoP access token must be provided to refresh said access token.`);\n }\n const tokenSet = await oidcClientExt.refresh(refreshToken, oidcContext.issuerConfig, clientInfo, dpopKey);\n if (tokenSet.refreshToken !== undefined) {\n eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(solidClientAuthnCore.EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);\n await this.storageUtility.setForUser(sessionId, {\n refreshToken: tokenSet.refreshToken,\n });\n }\n return tokenSet;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n *\n * @param dependencies\n * @deprecated This function will be removed from the external API in an upcoming release.\n */\nfunction getClientAuthenticationWithDependencies(dependencies) {\n const inMemoryStorage = new solidClientAuthnCore.InMemoryStorage();\n const secureStorage = dependencies.secureStorage || inMemoryStorage;\n const insecureStorage = dependencies.insecureStorage || new BrowserStorage();\n const storageUtility = new StorageUtilityBrowser(secureStorage, insecureStorage);\n const issuerConfigFetcher = new IssuerConfigFetcher(storageUtility);\n const clientRegistrar = new ClientRegistrar(storageUtility);\n const sessionInfoManager = new SessionInfoManager(storageUtility);\n const tokenRefresher = new TokenRefresher(storageUtility, issuerConfigFetcher, clientRegistrar);\n const redirector = new Redirector();\n // make new handler for redirect and login\n const loginHandler = new OidcLoginHandler(storageUtility, new AuthorizationCodeWithPkceOidcHandler(storageUtility, redirector), issuerConfigFetcher, clientRegistrar);\n const redirectHandler = new AggregateRedirectHandler([\n new ErrorOidcHandler(),\n new AuthCodeRedirectHandler(storageUtility, sessionInfoManager, issuerConfigFetcher, clientRegistrar, tokenRefresher),\n // This catch-all class will always be able to handle the\n // redirect IRI, so it must be registered last.\n new FallbackRedirectHandler(),\n ]);\n return new ClientAuthentication(loginHandler, redirectHandler, new solidClientAuthnCore.IWaterfallLogoutHandler(sessionInfoManager, redirector), sessionInfoManager, issuerConfigFetcher);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst KEY_CURRENT_SESSION = `${solidClientAuthnCore.SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`;\nconst KEY_CURRENT_URL = `${solidClientAuthnCore.SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nasync function silentlyAuthenticate(sessionId, clientAuthn, session) {\n var _a;\n const storedSessionInfo = await clientAuthn.validateCurrentSession(sessionId);\n if (storedSessionInfo !== null) {\n // It can be really useful to save the user's current browser location,\n // so that we can restore it after completing the silent authentication\n // on incoming redirect. This way, the user is eventually redirected back\n // to the page they were on and not to the app's redirect page.\n window.localStorage.setItem(KEY_CURRENT_URL, window.location.href);\n await clientAuthn.login({\n sessionId,\n prompt: \"none\",\n oidcIssuer: storedSessionInfo.issuer,\n redirectUrl: storedSessionInfo.redirectUrl,\n clientId: storedSessionInfo.clientAppId,\n clientSecret: storedSessionInfo.clientAppSecret,\n tokenType: (_a = storedSessionInfo.tokenType) !== null && _a !== void 0 ? _a : \"DPoP\",\n }, session.events);\n return true;\n }\n return false;\n}\nfunction isLoggedIn(sessionInfo) {\n return !!(sessionInfo === null || sessionInfo === void 0 ? void 0 : sessionInfo.isLoggedIn);\n}\n/**\n * A {@link Session} object represents a user's session on an application. The session holds state, as it stores information enabling acces to private resources after login for instance.\n */\nclass Session extends EventEmitter {\n /**\n * Session object constructor. Typically called as follows:\n *\n * ```typescript\n * const session = new Session();\n * ```\n *\n * See also [getDefaultSession](https://docs.inrupt.com/developer-tools/api/javascript/solid-client-authn-browser/functions.html#getdefaultsession).\n *\n * @param sessionOptions The options enabling the correct instantiation of\n * the session. Either both storages or clientAuthentication are required. For\n * more information, see {@link ISessionOptions}.\n * @param sessionId A string uniquely identifying the session.\n *\n */\n constructor(sessionOptions = {}, sessionId = undefined) {\n super();\n this.tokenRequestInProgress = false;\n /**\n * Triggers the login process. Note that this method will redirect the user away from your app.\n *\n * @param options Parameter to customize the login behaviour. In particular, two options are mandatory: `options.oidcIssuer`, the user's identity provider, and `options.redirectUrl`, the URL to which the user will be redirected after logging in their identity provider.\n * @returns This method should redirect the user away from the app: it does not return anything. The login process is completed by {@linkcode handleIncomingRedirect}.\n */\n // Define these functions as properties so that they don't get accidentally re-bound.\n // Isn't Javascript fun?\n this.login = async (options) => {\n var _a;\n await this.clientAuthentication.login({\n sessionId: this.info.sessionId,\n ...options,\n // Defaults the token type to DPoP\n tokenType: (_a = options.tokenType) !== null && _a !== void 0 ? _a : \"DPoP\",\n }, this.events);\n // `login` redirects the user away from the app,\n // so unless it throws an error, there is no code that should run afterwards\n // (since there is no \"after\" in the lifetime of the script).\n // Hence, this Promise never resolves:\n return new Promise(() => { });\n };\n /**\n * Fetches data using available login information. If the user is not logged in, this will behave as a regular `fetch`. The signature of this method is identical to the [canonical `fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n *\n * @param url The URL from which data should be fetched.\n * @param init Optional parameters customizing the request, by specifying an HTTP method, headers, a body, etc. Follows the [WHATWG Fetch Standard](https://fetch.spec.whatwg.org/).\n */\n this.fetch = (url, init) => this.clientAuthentication.fetch(url, init);\n /**\n * An internal logout function, to control whether or not the logout signal\n * should be sent, i.e. if the logout was user-initiated or is the result of\n * an external event.\n *\n * @hidden\n */\n this.internalLogout = async (emitSignal, options) => {\n // Clearing this value means that silent refresh will no longer be attempted.\n // In particular, in the case of a silent authentication error it prevents\n // from getting stuck in an authentication retries loop.\n window.localStorage.removeItem(KEY_CURRENT_SESSION);\n await this.clientAuthentication.logout(this.info.sessionId, options);\n this.info.isLoggedIn = false;\n if (emitSignal) {\n this.events.emit(solidClientAuthnCore.EVENTS.LOGOUT);\n }\n };\n /**\n * Logs the user out of the application.\n *\n * There are 2 types of logout supported by this library,\n * `app` logout and `idp` logout.\n *\n * App logout will log the user out within the application\n * by clearing any session data from the browser. It does\n * not log the user out of their Solid identity provider,\n * and should not redirect the user away.\n * App logout can be performed as follows:\n * ```typescript\n * await session.logout({ logoutType: 'app' });\n * ```\n *\n * IDP logout will log the user out of their Solid identity provider,\n * and will redirect the user away from the application to do so. In order\n * for users to be redirected back to `postLogoutUrl` you MUST include the\n * `postLogoutUrl` value in the `post_logout_redirect_uris` field in the\n * [Client ID Document](https://docs.inrupt.com/ess/latest/security/authentication/#client-identifier-client-id).\n * IDP logout can be performed as follows:\n * ```typescript\n * await session.logout({\n * logoutType: 'idp',\n * // An optional URL to redirect to after logout has completed;\n * // this MUST match a logout URL listed in the Client ID Document\n * // of the application that is logged in.\n * // If the application is logged in with a Client ID that is not\n * // a URI dereferencing to a Client ID Document then users will\n * // not be redirected back to the `postLogoutUrl` after logout.\n * postLogoutUrl: 'https://example.com/logout',\n * // An optional value to be included in the query parameters\n * // when the IDP provider redirects the user to the postLogoutRedirectUrl.\n * state: \"my-state\"\n * });\n * ```\n */\n this.logout = async (options) => this.internalLogout(true, options);\n /**\n * Completes the login process by processing the information provided by the\n * Solid identity provider through redirect.\n *\n * @param options See {@see IHandleIncomingRedirectOptions}.\n */\n this.handleIncomingRedirect = async (inputOptions = {}) => {\n var _a;\n if (this.info.isLoggedIn) {\n return this.info;\n }\n if (this.tokenRequestInProgress) {\n return undefined;\n }\n const options = typeof inputOptions === \"string\" ? { url: inputOptions } : inputOptions;\n const url = (_a = options.url) !== null && _a !== void 0 ? _a : window.location.href;\n this.tokenRequestInProgress = true;\n const sessionInfo = await this.clientAuthentication.handleIncomingRedirect(url, this.events);\n if (isLoggedIn(sessionInfo)) {\n this.setSessionInfo(sessionInfo);\n const currentUrl = window.localStorage.getItem(KEY_CURRENT_URL);\n if (currentUrl === null) {\n // The login event can only be triggered **after** the user has been\n // redirected from the IdP with access and ID tokens.\n this.events.emit(solidClientAuthnCore.EVENTS.LOGIN);\n }\n else {\n // If an URL is stored in local storage, we are being logged in after a\n // silent authentication, so remove our currently stored URL location\n // to clean up our state now that we are completing the re-login process.\n window.localStorage.removeItem(KEY_CURRENT_URL);\n this.events.emit(solidClientAuthnCore.EVENTS.SESSION_RESTORED, currentUrl);\n }\n }\n else if (options.restorePreviousSession === true) {\n // Silent authentication happens after a refresh, which means there are no\n // OAuth params in the current location IRI. It can only succeed if a session\n // was previously logged in, in which case its ID will be present with a known\n // identifier in local storage.\n // Check if we have a locally stored session ID...\n const storedSessionId = window.localStorage.getItem(KEY_CURRENT_SESSION);\n // ...if not, then there is no ID token, and so silent authentication cannot happen, but\n // if we do have a stored session ID, attempt to re-authenticate now silently.\n if (storedSessionId !== null) {\n const attemptedSilentAuthentication = await silentlyAuthenticate(storedSessionId, this.clientAuthentication, this);\n // At this point, we know that the main window will imminently be redirected.\n // However, this redirect is asynchronous and there is no way to halt execution\n // until it happens precisely. That's why the current Promise simply does not\n // resolve.\n if (attemptedSilentAuthentication) {\n return new Promise(() => { });\n }\n }\n }\n this.tokenRequestInProgress = false;\n return sessionInfo;\n };\n // Until Session no longer implements EventEmitter, this.events is just a proxy\n // to this (with some interface filtering). When we make the breaking change,\n // this.events will be a regular EventEmitter (implementing ISessionEventEmitter):\n // this.events = new EventEmitter();\n this.events = new Proxy(this, solidClientAuthnCore.buildProxyHandler(Session.prototype, \"events only implements ISessionEventListener\"));\n if (sessionOptions.clientAuthentication) {\n this.clientAuthentication = sessionOptions.clientAuthentication;\n }\n else if (sessionOptions.secureStorage && sessionOptions.insecureStorage) {\n this.clientAuthentication = getClientAuthenticationWithDependencies({\n secureStorage: sessionOptions.secureStorage,\n insecureStorage: sessionOptions.insecureStorage,\n });\n }\n else {\n this.clientAuthentication = getClientAuthenticationWithDependencies({});\n }\n if (sessionOptions.sessionInfo) {\n this.info = {\n sessionId: sessionOptions.sessionInfo.sessionId,\n isLoggedIn: false,\n webId: sessionOptions.sessionInfo.webId,\n };\n }\n else {\n this.info = {\n sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : uuid.v4(),\n isLoggedIn: false,\n };\n }\n // When a session is logged in, we want to track its ID in local storage to\n // enable silent refresh. The current session ID specifically stored in 'localStorage'\n // (as opposed to using our storage abstraction layer) because it is only\n // used in a browser-specific mechanism.\n this.events.on(solidClientAuthnCore.EVENTS.LOGIN, () => window.localStorage.setItem(KEY_CURRENT_SESSION, this.info.sessionId));\n this.events.on(solidClientAuthnCore.EVENTS.SESSION_EXPIRED, () => this.internalLogout(false));\n this.events.on(solidClientAuthnCore.EVENTS.ERROR, () => this.internalLogout(false));\n }\n /**\n * Register a callback function to be called when a user completes login.\n *\n * The callback is called when {@link handleIncomingRedirect} completes successfully.\n *\n * @param callback The function called when a user completes login.\n * @deprecated Prefer session.events.on(EVENTS.LOGIN, callback)\n */\n onLogin(callback) {\n this.events.on(solidClientAuthnCore.EVENTS.LOGIN, callback);\n }\n /**\n * Register a callback function to be called when a user logs out:\n *\n * @param callback The function called when a user completes logout.\n * @deprecated Prefer session.events.on(EVENTS.LOGOUT, callback)\n */\n onLogout(callback) {\n this.events.on(solidClientAuthnCore.EVENTS.LOGOUT, callback);\n }\n /**\n * Register a callback function to be called when a user logs out:\n *\n * @param callback The function called when an error occurs.\n * @since 1.11.0\n * @deprecated Prefer session.events.on(EVENTS.ERROR, callback)\n */\n onError(callback) {\n this.events.on(solidClientAuthnCore.EVENTS.ERROR, callback);\n }\n /**\n * Register a callback function to be called when a session is restored.\n *\n * Note: the callback will be called with the saved value of the 'current URL'\n * at the time the session was restored.\n *\n * @param callback The function called when a user's already logged-in session is restored, e.g., after a silent authentication is completed after a page refresh.\n * @deprecated Prefer session.events.on(EVENTS.SESSION_RESTORED, callback)\n */\n onSessionRestore(callback) {\n this.events.on(solidClientAuthnCore.EVENTS.SESSION_RESTORED, callback);\n }\n /**\n * Register a callback that runs when the session expires and can no longer\n * make authenticated requests, but following a user logout.\n * @param callback The function that runs on session expiration.\n * @since 1.11.0\n * @deprecated Prefer session.events.on(EVENTS.SESSION_EXPIRED, callback)\n */\n onSessionExpiration(callback) {\n this.events.on(solidClientAuthnCore.EVENTS.SESSION_EXPIRED, callback);\n }\n setSessionInfo(sessionInfo) {\n this.info.isLoggedIn = sessionInfo.isLoggedIn;\n this.info.webId = sessionInfo.webId;\n this.info.sessionId = sessionInfo.sessionId;\n this.info.expirationDate = sessionInfo.expirationDate;\n this.events.on(solidClientAuthnCore.EVENTS.SESSION_EXTENDED, (expiresIn) => {\n this.info.expirationDate = Date.now() + expiresIn * 1000;\n });\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nlet defaultSession;\n/**\n * Obtain the {@link Session} used when not explicitly instantiating one yourself.\n *\n * When using the top-level exports {@link fetch}, {@link login}, {@link logout},\n * {@link handleIncomingRedirect}, {@link onLogin} and {@link onLogout}, these apply to an\n * implicitly-instantiated {@link Session}.\n * This function returns a reference to that Session in order to obtain e.g. the current user's\n * WebID.\n * @since 1.3.0\n */\nfunction getDefaultSession() {\n if (typeof defaultSession === \"undefined\") {\n defaultSession = new Session();\n }\n return defaultSession;\n}\n/**\n * This function's signature is equal to `window.fetch`, but if the current user is authenticated\n * (see [[login]] and [[handleIncomingRedirect]]), requests made using it will include that user's\n * credentials. If not, this will behave just like the regular `window.fetch`.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch}\n * @since 1.3.0\n */\n/* eslint-disable-next-line no-shadow */\nconst fetch = (...args) => {\n const session = getDefaultSession();\n return session.fetch(...args);\n};\n/**\n * Triggers the login process. Note that this method will redirect the user away from your app.\n *\n * @param options Parameter to customize the login behaviour. In particular, two options are mandatory: `options.oidcIssuer`, the user's identity provider, and `options.redirectUrl`, the URL to which the user will be redirected after logging in their identity provider.\n * @returns This method should redirect the user away from the app: it does not return anything. The login process is completed by [[handleIncomingRedirect]].\n * @since 1.3.0\n */\nconst login = (...args) => {\n const session = getDefaultSession();\n return session.login(...args);\n};\n/**\n * Logs the user out of the application.\n *\n * By default this does not log the user out of their Solid identity provider.\n * In order to do so, you must set the logoutType to `idp`. For usage details\n * see {@link Session.logout}.\n *\n * @since 1.3.0\n */\nconst logout = (...args) => {\n const session = getDefaultSession();\n return session.logout(...args);\n};\n/**\n * Completes the login process by processing the information provided by the Solid identity provider through redirect.\n *\n * @param url The URL of the page handling the redirect, including the query parameters — these contain the information to process the login.\n * @since 1.3.0\n */\nconst handleIncomingRedirect = (...args) => {\n const session = getDefaultSession();\n return session.handleIncomingRedirect(...args);\n};\n/**\n * Register a callback function to be called when a user completes login.\n *\n * The callback is called when {@link handleIncomingRedirect} completes successfully.\n * @since 1.3.0\n *\n * @param callback The function called when a user completes login.\n * @deprecated Prefer events.on(EVENTS.LOGIN, callback)\n\n */\nconst onLogin = (...args) => {\n const session = getDefaultSession();\n return session.onLogin(...args);\n};\n/**\n * Register a callback function to be called when a user logs out:\n *\n * @param callback The function called when a user completes logout.\n * @since 1.3.0\n * @deprecated Prefer events.on(EVENTS.LOGOUT, callback)\n *\n */\nconst onLogout = (...args) => {\n const session = getDefaultSession();\n return session.onLogout(...args);\n};\n/**\n * Register a callback function to be called when a session is restored:\n *\n * @param callback The function called when a session is restored.\n * @since 1.3.0\n * @deprecated Prefer events.on(EVENTS.SESSION_RESTORED, callback)\n */\nconst onSessionRestore = (...args) => {\n const session = getDefaultSession();\n return session.onSessionRestore(...args);\n};\n/**\n * {@link SessionEventEmitter} instance to subscribe to events by the default session.\n *\n * @since 1.14.0\n */\nconst events = () => {\n return getDefaultSession().events;\n};\n\nObject.defineProperty(exports, 'ConfigurationError', {\n enumerable: true,\n get: function () { return solidClientAuthnCore.ConfigurationError; }\n});\nObject.defineProperty(exports, 'EVENTS', {\n enumerable: true,\n get: function () { return solidClientAuthnCore.EVENTS; }\n});\nObject.defineProperty(exports, 'InMemoryStorage', {\n enumerable: true,\n get: function () { return solidClientAuthnCore.InMemoryStorage; }\n});\nObject.defineProperty(exports, 'NotImplementedError', {\n enumerable: true,\n get: function () { return solidClientAuthnCore.NotImplementedError; }\n});\nexports.Session = Session;\nexports.events = events;\nexports.fetch = fetch;\nexports.getClientAuthenticationWithDependencies = getClientAuthenticationWithDependencies;\nexports.getDefaultSession = getDefaultSession;\nexports.handleIncomingRedirect = handleIncomingRedirect;\nexports.login = login;\nexports.logout = logout;\nexports.onLogin = onLogin;\nexports.onLogout = onLogout;\nexports.onSessionRestore = onSessionRestore;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nvar events = require('events');\nvar universalFetch = require('@inrupt/universal-fetch');\nvar jose = require('jose');\nvar uuid = require('uuid');\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Intended to be used by dependent packages as a common prefix for keys into\n * storage mechanisms (so as to group all keys related to Solid Client Authn\n * within those storage mechanisms, e.g., window.localStorage).\n */\nconst SOLID_CLIENT_AUTHN_KEY_PREFIX = \"solidClientAuthn:\";\n/**\n * Ordered list of signature algorithms, from most preferred to least preferred.\n */\nconst PREFERRED_SIGNING_ALG = [\"ES256\", \"RS256\"];\nconst EVENTS = {\n // Note that an `error` events MUST be listened to: https://nodejs.org/dist/latest-v16.x/docs/api/events.html#error-events.\n ERROR: \"error\",\n LOGIN: \"login\",\n LOGOUT: \"logout\",\n NEW_REFRESH_TOKEN: \"newRefreshToken\",\n SESSION_EXPIRED: \"sessionExpired\",\n SESSION_EXTENDED: \"sessionExtended\",\n SESSION_RESTORED: \"sessionRestore\",\n TIMEOUT_SET: \"timeoutSet\",\n};\n/**\n * We want to refresh a token 5 seconds before it expires.\n */\nconst REFRESH_BEFORE_EXPIRATION_SECONDS = 5;\n// The openid scope requests an OIDC ID token token to be returned.\nconst SCOPE_OPENID = \"openid\";\n// The offline_access scope requests a refresh token to be returned.\nconst SCOPE_OFFLINE = \"offline_access\";\n// The webid scope is required as per https://solid.github.io/solid-oidc/#webid-scope\nconst SCOPE_WEBID = \"webid\";\n// The scopes are expected as a space-separated list.\nconst DEFAULT_SCOPES = [SCOPE_OPENID, SCOPE_OFFLINE, SCOPE_WEBID].join(\" \");\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Temporary internal builder for safe proxying.\n */\nconst buildProxyHandler = (\n// The class to be excluded needs to be injected, because it is defined in a\n// dependency.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntoExclude, errorMessage) => ({\n // This proxy is only a temporary measure until Session no longer extends\n // SessionEventEmitter, and the proxying is no longer necessary.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(target, prop, receiver) {\n // Reject any calls to the proxy that isn't specific to the EventEmitter API\n if (!Object.getOwnPropertyNames(events.EventEmitter).includes(prop) &&\n Object.getOwnPropertyNames(toExclude).includes(prop)) {\n throw new Error(`${errorMessage}: [${prop}] is not supported`);\n }\n return Reflect.get(target, prop, receiver);\n },\n});\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n */\nclass AggregateHandler {\n constructor(handleables) {\n this.handleables = handleables;\n this.handleables = handleables;\n }\n /**\n * Helper function that will asynchronously determine the proper handler to use. If multiple\n * handlers can handle, it will choose the first one in the list\n * @param params Paramerters to feed to the handler\n */\n async getProperHandler(params) {\n // TODO : This function doesn't currently operate as described. Tests need to be written\n // return new Promise | null>((resolve, reject) => {\n // const resolvedValues: Array = Array(this.handleables.length).map(() => null)\n // let numberResolved = 0\n // this.handleables.forEach(async (handleable: IHandleable, index: number) => {\n // resolvedValues[index] = await handleable.canHandle(...params)\n // numberResolved++\n // let curResolvedValueIndex = 0\n // while (\n // resolvedValues[curResolvedValueIndex] !== null ||\n // resolvedValues[curResolvedValueIndex] !== undefined\n // ) {\n // if (resolvedValues[curResolvedValueIndex]) {\n // resolve(this.handleables[curResolvedValueIndex])\n // }\n // curResolvedValueIndex++\n // }\n // })\n // })\n const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));\n for (let i = 0; i < canHandleList.length; i += 1) {\n if (canHandleList[i]) {\n return this.handleables[i];\n }\n }\n return null;\n }\n async canHandle(...params) {\n return (await this.getProperHandler(params)) !== null;\n }\n async handle(...params) {\n const handler = await this.getProperHandler(params);\n if (handler) {\n return handler.handle(...params);\n }\n throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params\n .map((param) => {\n try {\n return JSON.stringify(param);\n }\n catch (err) {\n /* eslint-disable @typescript-eslint/no-explicit-any */\n return param.toString();\n }\n })\n .join(\", \")}`);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// eslint-disable-next-line no-shadow\nasync function fetchJwks(jwksIri, issuerIri) {\n // FIXME: the following line works, but the underlying network calls don't seem\n // to be mocked properly by our test code. It would be nicer to replace calls to this\n // function by the following line and to fix the mocks.\n // const jwks = createRemoteJWKSet(new URL(jwksIri));\n const jwksResponse = await universalFetch.fetch.call(globalThis, jwksIri);\n if (jwksResponse.status !== 200) {\n throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);\n }\n // The JWKS should only contain the current key for the issuer.\n let jwk;\n try {\n jwk = (await jwksResponse.json()).keys[0];\n }\n catch (e) {\n throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);\n }\n return jwk;\n}\n/**\n * Extract a WebID from an ID token payload based on https://github.com/solid/webid-oidc-spec.\n * Note that this does not yet implement the user endpoint lookup, and only checks\n * for `webid` or IRI-like `sub` claims.\n *\n * @param idToken the payload of the ID token from which the WebID can be extracted.\n * @returns a WebID extracted from the ID token.\n * @internal\n */\nasync function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {\n const jwk = await fetchJwks(jwksIri, issuerIri);\n let payload;\n try {\n const { payload: verifiedPayload } = await jose.jwtVerify(idToken, await jose.importJWK(jwk), {\n issuer: issuerIri,\n audience: clientId,\n });\n payload = verifiedPayload;\n }\n catch (e) {\n throw new Error(`Token verification failed: ${e.stack}`);\n }\n if (typeof payload.webid === \"string\") {\n return payload.webid;\n }\n if (typeof payload.sub !== \"string\") {\n throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);\n }\n try {\n // This parses the 'sub' claim to check if it is a well-formed IRI.\n // However, the normalized value isn't returned to make sure the WebID is returned\n // as specified by the Identity Provider.\n // eslint-disable-next-line no-new\n new URL(payload.sub);\n return payload.sub;\n }\n catch (e) {\n throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction isValidRedirectUrl(redirectUrl) {\n // If the redirect URL is not a valid URL, an error will be thrown.\n try {\n const urlObject = new URL(redirectUrl);\n const noReservedQuery = !urlObject.searchParams.has(\"code\") &&\n !urlObject.searchParams.has(\"state\");\n // As per https://tools.ietf.org/html/rfc6749#section-3.1.2, the redirect URL\n // must not include a hash fragment.\n const noHash = urlObject.hash === \"\";\n return noReservedQuery && noHash;\n }\n catch (e) {\n return false;\n }\n}\nfunction removeOpenIdParams(redirectUrl) {\n const cleanedUpUrl = new URL(redirectUrl);\n // For auth code flow\n cleanedUpUrl.searchParams.delete(\"state\");\n cleanedUpUrl.searchParams.delete(\"code\");\n // For login error\n cleanedUpUrl.searchParams.delete(\"error\");\n cleanedUpUrl.searchParams.delete(\"error_description\");\n // For RFC9207\n cleanedUpUrl.searchParams.delete(\"iss\");\n return cleanedUpUrl;\n}\n\n/**\n * @hidden\n * @packageDocumentation\n */\n/**\n * @hidden\n * Authorization code flow spec: https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth\n * PKCE: https://tools.ietf.org/html/rfc7636\n */\nclass AuthorizationCodeWithPkceOidcHandlerBase {\n constructor(storageUtility, redirector) {\n this.storageUtility = storageUtility;\n this.redirector = redirector;\n this.storageUtility = storageUtility;\n this.redirector = redirector;\n }\n async canHandle(oidcLoginOptions) {\n return !!(oidcLoginOptions.issuerConfiguration.grantTypesSupported &&\n oidcLoginOptions.issuerConfiguration.grantTypesSupported.indexOf(\"authorization_code\") > -1);\n }\n async handleRedirect({ oidcLoginOptions, state, codeVerifier, targetUrl, }) {\n await Promise.all([\n // We use the OAuth 'state' value (which should be crypto-random) as\n // the key in our storage to store our actual SessionID. We do this\n // 'cos we'll need to lookup our session information again when the\n // browser is redirected back to us (i.e. the OAuth client\n // application) from the Authorization Server.\n // We don't want to use our session ID as the OAuth 'state' value, as\n // that session ID can be any developer-specified value, and therefore\n // may not be appropriate (since the OAuth 'state' value should really\n // be an unguessable crypto-random value).\n // eslint-disable-next-line no-underscore-dangle\n this.storageUtility.setForUser(state, {\n sessionId: oidcLoginOptions.sessionId,\n }),\n // Store our login-process state using the session ID as the key.\n // Strictly speaking, this indirection from our OAuth state value to\n // our session ID is unnecessary, but it provides a slightly cleaner\n // separation of concerns.\n this.storageUtility.setForUser(oidcLoginOptions.sessionId, {\n // eslint-disable-next-line no-underscore-dangle\n codeVerifier,\n issuer: oidcLoginOptions.issuer.toString(),\n // The redirect URL is read after redirect, so it must be stored now.\n redirectUrl: oidcLoginOptions.redirectUrl,\n dpop: oidcLoginOptions.dpop ? \"true\" : \"false\",\n }),\n ]);\n this.redirector.redirect(targetUrl, {\n handleRedirect: oidcLoginOptions.handleRedirect,\n });\n return undefined;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n */\nclass GeneralLogoutHandler {\n constructor(sessionInfoManager) {\n this.sessionInfoManager = sessionInfoManager;\n this.sessionInfoManager = sessionInfoManager;\n }\n async canHandle() {\n return true;\n }\n async handle(userId) {\n await this.sessionInfoManager.clear(userId);\n }\n}\n\nclass IRpLogoutHandler {\n constructor(redirector) {\n this.redirector = redirector;\n this.redirector = redirector;\n }\n async canHandle(userId, options) {\n return (options === null || options === void 0 ? void 0 : options.logoutType) === \"idp\";\n }\n async handle(userId, options) {\n if ((options === null || options === void 0 ? void 0 : options.logoutType) !== \"idp\") {\n throw new Error(\"Attempting to call idp logout handler to perform app logout\");\n }\n if (options.toLogoutUrl === undefined) {\n throw new Error(\"Cannot perform IDP logout. Did you log in using the OIDC authentication flow?\");\n }\n this.redirector.redirect(options.toLogoutUrl(options), {\n handleRedirect: options.handleRedirect,\n });\n }\n}\n\nclass IWaterfallLogoutHandler {\n constructor(sessionInfoManager, redirector) {\n this.handlers = [\n new GeneralLogoutHandler(sessionInfoManager),\n new IRpLogoutHandler(redirector),\n ];\n }\n async canHandle() {\n return true;\n }\n async handle(userId, options) {\n for (const handler of this.handlers) {\n /* eslint-disable no-await-in-loop */\n if (await handler.canHandle(userId, options))\n await handler.handle(userId, options);\n /* eslint-enable no-await-in-loop */\n }\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\nfunction getUnauthenticatedSession() {\n return {\n isLoggedIn: false,\n sessionId: uuid.v4(),\n fetch: (...args) => universalFetch.fetch.call(globalThis, ...args),\n };\n}\n/**\n * @param sessionId\n * @param storage\n * @hidden\n */\nasync function clear(sessionId, storage) {\n await Promise.all([\n storage.deleteAllUserData(sessionId, { secure: false }),\n storage.deleteAllUserData(sessionId, { secure: true }),\n ]);\n}\n/**\n * @hidden\n */\nclass SessionInfoManagerBase {\n constructor(storageUtility) {\n this.storageUtility = storageUtility;\n this.storageUtility = storageUtility;\n }\n update(_sessionId, _options) {\n throw new Error(\"Not Implemented\");\n }\n get(_) {\n throw new Error(\"Not implemented\");\n }\n // eslint-disable-next-line class-methods-use-this\n async getAll() {\n throw new Error(\"Not implemented\");\n }\n /**\n * This function removes all session-related information from storage.\n * @param sessionId the session identifier\n * @param storage the storage where session info is stored\n * @hidden\n */\n async clear(sessionId) {\n return clear(sessionId, this.storageUtility);\n }\n /**\n * Registers a new session, so that its ID can be retrieved.\n * @param sessionId\n */\n async register(_sessionId) {\n throw new Error(\"Not implemented\");\n }\n /**\n * Returns all the registered session IDs. Differs from getAll, which also\n * returns additional session information.\n */\n async getRegisteredSessionIdAll() {\n throw new Error(\"Not implemented\");\n }\n /**\n * Deletes all information about all sessions, including their registrations.\n */\n async clearAll() {\n throw new Error(\"Not implemented\");\n }\n}\n\n/**\n * This function is designed to isomorphically capture the behavior in oidc-client-js and node-oidc-provider\n * - https://github.com/IdentityModel/oidc-client-js/blob/edec8f59897bdeedcb0b4167586d49626203c2c1/src/OidcClient.js#L138\n * - https://github.com/panva/node-openid-client/blob/35758419489ff751a71f5b66f5020087a63e1e88/lib/client.js#L284\n *\n * @param options IEndSessionOptions\n * @returns The URL to redirect to in order to perform RP Initiated Logout\n * @hidden\n */\nfunction getEndSessionUrl({ endSessionEndpoint, idTokenHint, postLogoutRedirectUri, state, }) {\n const url = new URL(endSessionEndpoint);\n if (idTokenHint !== undefined)\n url.searchParams.append(\"id_token_hint\", idTokenHint);\n if (postLogoutRedirectUri !== undefined) {\n url.searchParams.append(\"post_logout_redirect_uri\", postLogoutRedirectUri);\n if (state !== undefined)\n url.searchParams.append(\"state\", state);\n }\n return url.toString();\n}\n/**\n * @param options.endSessionEndpoint The end_session_endpoint advertised by the server\n * @param options.idTokenHint The idToken supplied by the server after logging in\n * Redirects the window to the location required to perform RP initiated logout\n *\n * @hidden\n */\nfunction maybeBuildRpInitiatedLogout({ endSessionEndpoint, idTokenHint, }) {\n if (endSessionEndpoint === undefined)\n return undefined;\n return function logout({ state, postLogoutUrl }) {\n return getEndSessionUrl({\n endSessionEndpoint,\n idTokenHint,\n state,\n postLogoutRedirectUri: postLogoutUrl,\n });\n };\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction isSupportedTokenType(token) {\n return typeof token === \"string\" && [\"DPoP\", \"Bearer\"].includes(token);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst USER_SESSION_PREFIX = \"solidClientAuthenticationUser\";\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction isValidUrl(url) {\n try {\n // Here, the URL constructor is just called to parse the given string and\n // verify if it is a well-formed IRI.\n // eslint-disable-next-line no-new\n new URL(url);\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction determineSigningAlg(supported, preferred) {\n var _a;\n return ((_a = preferred.find((signingAlg) => {\n return supported.includes(signingAlg);\n })) !== null && _a !== void 0 ? _a : null);\n}\nfunction determineClientType(options, issuerConfig) {\n if (options.clientId !== undefined && !isValidUrl(options.clientId)) {\n return \"static\";\n }\n if (issuerConfig.scopesSupported.includes(\"webid\") &&\n options.clientId !== undefined &&\n isValidUrl(options.clientId)) {\n return \"solid-oidc\";\n }\n // If no client_id is provided, the client must go through Dynamic Client Registration.\n // If a client_id is provided and it looks like a URI, yet the Identity Provider\n // does *not* support Solid-OIDC, then we also perform DCR (and discard the\n // provided client_id).\n return \"dynamic\";\n}\nasync function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {\n const clientType = determineClientType(options, issuerConfig);\n if (clientType === \"dynamic\") {\n return clientRegistrar.getClient({\n sessionId: options.sessionId,\n clientName: options.clientName,\n redirectUrl: options.redirectUrl,\n }, issuerConfig);\n }\n // If a client_id was provided, and the Identity Provider is Solid-OIDC compliant,\n // or it is not compliant but the client_id isn't an IRI (we assume it has already\n // been registered with the IdP), then the client registration information needs\n // to be stored so that it can be retrieved later after redirect.\n await storageUtility.setForUser(options.sessionId, {\n // If the client is either static or solid-oidc compliant, its client ID cannot be undefined.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n clientId: options.clientId,\n });\n if (options.clientSecret) {\n await storageUtility.setForUser(options.sessionId, {\n clientSecret: options.clientSecret,\n });\n }\n if (options.clientName) {\n await storageUtility.setForUser(options.sessionId, {\n clientName: options.clientName,\n });\n }\n return {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n clientName: options.clientName,\n clientType,\n };\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n// By only referring to `window` at runtime, apps that do server-side rendering\n// won't run into errors when rendering code that instantiates a\n// ClientAuthentication:\nconst globalFetch = (request, init) => universalFetch.fetch.call(globalThis, request, init);\n/**\n * @hidden\n */\nclass ClientAuthentication {\n constructor(loginHandler, redirectHandler, logoutHandler, sessionInfoManager, issuerConfigFetcher) {\n this.loginHandler = loginHandler;\n this.redirectHandler = redirectHandler;\n this.logoutHandler = logoutHandler;\n this.sessionInfoManager = sessionInfoManager;\n this.issuerConfigFetcher = issuerConfigFetcher;\n // By default, our fetch() resolves to the environment fetch() function.\n this.fetch = globalFetch;\n this.logout = async (sessionId, options) => {\n // When doing IDP logout this will redirect away from the current page, so we should not expect\n // code after this condition to be run if it is true.\n // We also need to make sure that any other cleanup that we want to do for\n // our session takes place before this condition is run\n await this.logoutHandler.handle(sessionId, (options === null || options === void 0 ? void 0 : options.logoutType) === \"idp\"\n ? {\n ...options,\n toLogoutUrl: this.boundLogout,\n }\n : options);\n // Restore our fetch() function back to the environment fetch(), effectively\n // leaving us with un-authenticated fetches from now on.\n this.fetch = globalFetch;\n // Delete the bound logout function, so that it can't be called after this.\n delete this.boundLogout;\n };\n this.getSessionInfo = async (sessionId) => {\n // TODO complete\n return this.sessionInfoManager.get(sessionId);\n };\n this.getAllSessionInfo = async () => {\n return this.sessionInfoManager.getAll();\n };\n this.loginHandler = loginHandler;\n this.redirectHandler = redirectHandler;\n this.logoutHandler = logoutHandler;\n this.sessionInfoManager = sessionInfoManager;\n this.issuerConfigFetcher = issuerConfigFetcher;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n/**\n * A helper class that will validate items taken from local storage\n */\nasync function getSessionIdFromOauthState(storageUtility, oauthState) {\n return storageUtility.getForUser(oauthState, \"sessionId\");\n}\n/**\n * Based on the provided state, this looks up contextual information stored\n * before redirecting the user to the OIDC issuer.\n * @param sessionId The state (~ correlation ID) of the OIDC request\n * @param storageUtility\n * @param configFetcher\n * @returns Information stored about the client issuing the request\n */\nasync function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {\n try {\n const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([\n storageUtility.getForUser(sessionId, \"issuer\", {\n errorIfNull: true,\n }),\n storageUtility.getForUser(sessionId, \"codeVerifier\"),\n storageUtility.getForUser(sessionId, \"redirectUrl\"),\n storageUtility.getForUser(sessionId, \"dpop\", { errorIfNull: true }),\n ]);\n // Clear the code verifier, which is one-time use.\n await storageUtility.deleteForUser(sessionId, \"codeVerifier\");\n // Unlike openid-client, this looks up the configuration from storage\n const issuerConfig = await configFetcher.fetchConfig(issuerIri);\n return {\n codeVerifier,\n redirectUrl: storedRedirectIri,\n issuerConfig,\n dpop: dpop === \"true\",\n };\n }\n catch (e) {\n throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);\n }\n}\n/**\n * Stores information about the session in the provided storage. Note that not\n * all storage are equally secure, and it is strongly advised not to store either\n * the refresh token or the DPoP key in the browser's local storage.\n *\n * @param storageUtility\n * @param sessionId\n * @param webId\n * @param isLoggedIn\n * @param refreshToken\n * @param secure\n * @param dpopKey\n */\nasync function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {\n // TODO: Investigate why this does not work with a Promise.all\n if (refreshToken !== undefined) {\n await storageUtility.setForUser(sessionId, { refreshToken }, { secure });\n }\n if (webId !== undefined) {\n await storageUtility.setForUser(sessionId, { webId }, { secure });\n }\n if (isLoggedIn !== undefined) {\n await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });\n }\n if (dpopKey !== undefined) {\n await storageUtility.setForUser(sessionId, {\n publicKey: JSON.stringify(dpopKey.publicKey),\n privateKey: JSON.stringify(await jose.exportJWK(dpopKey.privateKey)),\n }, { secure });\n }\n}\n// TOTEST: this does not handle all possible bad inputs for example what if it's not proper JSON\n/**\n * @hidden\n */\nclass StorageUtility {\n constructor(secureStorage, insecureStorage) {\n this.secureStorage = secureStorage;\n this.insecureStorage = insecureStorage;\n this.secureStorage = secureStorage;\n this.insecureStorage = insecureStorage;\n }\n getKey(userId) {\n return `solidClientAuthenticationUser:${userId}`;\n }\n async getUserData(userId, secure) {\n const stored = await (secure\n ? this.secureStorage\n : this.insecureStorage).get(this.getKey(userId));\n if (stored === undefined) {\n return {};\n }\n try {\n return JSON.parse(stored);\n }\n catch (err) {\n throw new Error(`Data for user [${userId}] in [${secure ? \"secure\" : \"unsecure\"}] storage is corrupted - expected valid JSON, but got: ${stored}`);\n }\n }\n async setUserData(userId, data, secure) {\n await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));\n }\n async get(key, options) {\n const value = await ((options === null || options === void 0 ? void 0 : options.secure)\n ? this.secureStorage\n : this.insecureStorage).get(key);\n if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {\n throw new Error(`[${key}] is not stored`);\n }\n return value;\n }\n async set(key, value, options) {\n return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);\n }\n async delete(key, options) {\n return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);\n }\n async getForUser(userId, key, options) {\n const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);\n let value;\n if (!userData || !userData[key]) {\n value = undefined;\n }\n value = userData[key];\n if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {\n throw new Error(`Field [${key}] for user [${userId}] is not stored`);\n }\n return value || undefined;\n }\n async setForUser(userId, values, options) {\n let userData;\n try {\n userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);\n }\n catch (_a) {\n // if reading the user data throws, the data is corrupted, and we want to write over it\n userData = {};\n }\n await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);\n }\n async deleteForUser(userId, key, options) {\n const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);\n delete userData[key];\n await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);\n }\n async deleteAllUserData(userId, options) {\n await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n */\nclass InMemoryStorage {\n constructor() {\n this.map = {};\n }\n async get(key) {\n return this.map[key] || undefined;\n }\n async set(key, value) {\n this.map[key] = value;\n }\n async delete(key) {\n delete this.map[key];\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n/**\n * Error to be triggered when a poor configuration is received\n */\n// NOTE: There's a bug with istanbul and typescript that prevents full branch coverages\n// https://github.com/gotwarlost/istanbul/issues/690\n// The workaround is to put istanbul ignore on the constructor\n/**\n * @hidden\n */\nclass ConfigurationError extends Error {\n /* istanbul ignore next */\n constructor(message) {\n super(message);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n/**\n * Error to be triggered if a method is not implemented\n * @hidden\n */\nclass NotImplementedError extends Error {\n /* istanbul ignore next */\n constructor(methodName) {\n super(`[${methodName}] is not implemented`);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n/**\n * Error to be triggered when receiving a response missing mandatory elements\n */\n// NOTE: There's a bug with istanbul and typescript that prevents full branch coverages\n// https://github.com/gotwarlost/istanbul/issues/690\n// The workaround is to put istanbul ignore on the constructor\n/**\n * @hidden\n */\nclass InvalidResponseError extends Error {\n /* istanbul ignore next */\n constructor(missingFields) {\n super(`Invalid response from OIDC provider: missing fields ${missingFields}`);\n this.missingFields = missingFields;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n * @packageDocumentation\n */\n/**\n * Error to be triggered when receiving a response missing mandatory elements\n */\n// NOTE: There's a bug with istanbul and typescript that prevents full branch coverages\n// https://github.com/gotwarlost/istanbul/issues/690\n// The workaround is to put istanbul ignore on the constructor\n/**\n * @hidden\n */\nclass OidcProviderError extends Error {\n /* istanbul ignore next */\n constructor(message, error, errorDescription) {\n super(message);\n this.error = error;\n this.errorDescription = errorDescription;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Normalizes a URL in order to generate the DPoP token based on a consistent scheme.\n *\n * @param audience The URL to normalize.\n * @returns The normalized URL as a string.\n * @hidden\n */\nfunction normalizeHTU(audience) {\n const audienceUrl = new URL(audience);\n return new URL(audienceUrl.pathname, audienceUrl.origin).toString();\n}\n/**\n * Creates a DPoP header according to https://tools.ietf.org/html/draft-fett-oauth-dpop-04,\n * based on the target URL and method, using the provided key.\n *\n * @param audience Target URL.\n * @param method HTTP method allowed.\n * @param key Key used to sign the token.\n * @returns A JWT that can be used as a DPoP Authorization header.\n */\nasync function createDpopHeader(audience, method, dpopKey) {\n return new jose.SignJWT({\n htu: normalizeHTU(audience),\n htm: method.toUpperCase(),\n jti: uuid.v4(),\n })\n .setProtectedHeader({\n alg: PREFERRED_SIGNING_ALG[0],\n jwk: dpopKey.publicKey,\n typ: \"dpop+jwt\",\n })\n .setIssuedAt()\n .sign(dpopKey.privateKey, {});\n}\nasync function generateDpopKeyPair() {\n const { privateKey, publicKey } = await jose.generateKeyPair(PREFERRED_SIGNING_ALG[0]);\n const dpopKeyPair = {\n privateKey,\n publicKey: await jose.exportJWK(publicKey),\n };\n // The alg property isn't set by exportJWK, so set it manually.\n [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;\n return dpopKeyPair;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * If expires_in isn't specified for the access token, we assume its lifetime is\n * 10 minutes.\n */\nconst DEFAULT_EXPIRATION_TIME_SECONDS = 600;\nfunction isExpectedAuthError(statusCode) {\n // As per https://tools.ietf.org/html/rfc7235#section-3.1 and https://tools.ietf.org/html/rfc7235#section-3.1,\n // a response failing because the provided credentials aren't accepted by the\n // server can get a 401 or a 403 response.\n return [401, 403].includes(statusCode);\n}\nasync function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {\n var _a;\n const headers = new universalFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);\n // Any pre-existing Authorization header should be overriden.\n headers.set(\"Authorization\", `DPoP ${authToken}`);\n headers.set(\"DPoP\", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : \"get\", dpopKey));\n return {\n ...defaultOptions,\n headers,\n };\n}\nasync function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {\n if (dpopKey !== undefined) {\n return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);\n }\n const headers = new universalFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);\n // Any pre-existing Authorization header should be overriden.\n headers.set(\"Authorization\", `Bearer ${authToken}`);\n return {\n ...defaultOptions,\n headers,\n };\n}\nasync function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {\n return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));\n}\nasync function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {\n var _a;\n const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);\n eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);\n if (typeof tokenSet.refreshToken === \"string\") {\n eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);\n }\n return {\n accessToken: tokenSet.accessToken,\n refreshToken: tokenSet.refreshToken,\n expiresIn: tokenSet.expiresIn,\n };\n}\n/**\n *\n * @param expiresIn Delay until the access token expires.\n * @returns a delay until the access token should be refreshed.\n */\nconst computeRefreshDelay = (expiresIn) => {\n if (expiresIn !== undefined) {\n return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0\n ? // We want to refresh the token 5 seconds before they actually expire.\n expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS\n : expiresIn;\n }\n return DEFAULT_EXPIRATION_TIME_SECONDS;\n};\n/**\n * @param unauthFetch a regular fetch function, compliant with the WHATWG spec.\n * @param authToken an access token, either a Bearer token or a DPoP one.\n * @param options The option object may contain two objects: the DPoP key token\n * is bound to if applicable, and options to customise token renewal behaviour.\n *\n * @returns A fetch function that adds an appropriate Authorization header with\n * the provided token, and adds a DPoP header if applicable.\n */\nasync function buildAuthenticatedFetch(unauthFetch, accessToken, options) {\n var _a;\n let currentAccessToken = accessToken;\n let latestTimeout;\n const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;\n // Setup the refresh timeout outside of the authenticated fetch, so that\n // an idle app will not get logged out if it doesn't issue a fetch before\n // the first expiration date.\n if (currentRefreshOptions !== undefined) {\n const proactivelyRefreshToken = async () => {\n var _a, _b, _c, _d;\n try {\n const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, \n // If currentRefreshOptions is defined, options is necessarily defined too.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n options.dpopKey, \n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n options.eventEmitter);\n // Update the tokens in the closure if appropriate.\n currentAccessToken = refreshedAccessToken;\n if (refreshToken !== undefined) {\n currentRefreshOptions.refreshToken = refreshToken;\n }\n // Each time the access token is refreshed, we must plan fo the next\n // refresh iteration.\n clearTimeout(latestTimeout);\n latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);\n // If currentRefreshOptions is defined, options is necessarily defined too.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);\n }\n catch (e) {\n // It is possible that an underlying library throws an error on refresh flow failure.\n // If we used a log framework, the error could be logged at the `debug` level,\n // but otherwise the failure of the refresh flow should not blow up in the user's\n // face, so we just swallow the error.\n if (e instanceof OidcProviderError) {\n // The OIDC provider refused to refresh the access token and returned an error instead.\n /* istanbul ignore next 100% coverage would require testing that nothing\n happens here if the emitter is undefined, which is more cumbersome\n than what it's worth. */\n (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);\n /* istanbul ignore next 100% coverage would require testing that nothing\n happens here if the emitter is undefined, which is more cumbersome\n than what it's worth. */\n (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);\n }\n if (e instanceof InvalidResponseError &&\n e.missingFields.includes(\"access_token\")) {\n // In this case, the OIDC provider returned a non-standard response, but\n // did not specify that it was an error. We cannot refresh nonetheless.\n /* istanbul ignore next 100% coverage would require testing that nothing\n happens here if the emitter is undefined, which is more cumbersome\n than what it's worth. */\n (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);\n }\n }\n };\n latestTimeout = setTimeout(proactivelyRefreshToken, \n // If currentRefreshOptions is defined, options is necessarily defined too.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n computeRefreshDelay(options.expiresIn) * 1000);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);\n }\n else if (options !== undefined && options.eventEmitter !== undefined) {\n // If no refresh options are provided, the session expires when the access token does.\n const expirationTimeout = setTimeout(() => {\n // The event emitter is always defined in our code, and it would be tedious\n // to test for conditions when it is not.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);\n }, computeRefreshDelay(options.expiresIn) * 1000);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);\n }\n return async (url, requestInit) => {\n let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);\n const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);\n if (response.ok || failedButNotExpectedAuthError) {\n // If there hasn't been a redirection, or if there has been a non-auth related\n // issue, it should be handled at the application level\n return response;\n }\n const hasBeenRedirected = response.url !== url;\n if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {\n // If the request failed for auth reasons, and has been redirected, we should\n // replay it generating a DPoP header for the rediration target IRI. This\n // doesn't apply to Bearer tokens, as the Bearer tokens aren't specific\n // to a given resource and method, while the DPoP header (associated to a\n // DPoP token) is.\n response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, \n // Replace the original target IRI (`url`) by the redirection target\n response.url, requestInit, options.dpopKey);\n }\n return response;\n };\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst StorageUtilityGetResponse = \"getResponse\";\nconst StorageUtilityMock = {\n /* eslint-disable @typescript-eslint/no-unused-vars */\n get: async (key, options) => StorageUtilityGetResponse,\n set: async (key, value) => {\n /* do nothing */\n },\n delete: async (key) => {\n /* do nothing */\n },\n getForUser: async (userId, key, options) => StorageUtilityGetResponse,\n setForUser: async (userId, values, options) => {\n /* do nothing */\n },\n deleteForUser: async (userId, key, options) => {\n /* do nothing */\n },\n deleteAllUserData: async (userId, options) => {\n /* do nothing */\n },\n};\nconst mockStorage = (stored) => {\n const store = stored;\n return {\n get: async (key) => {\n if (store[key] === undefined) {\n return undefined;\n }\n if (typeof store[key] === \"string\") {\n return store[key];\n }\n return JSON.stringify(store[key]);\n },\n set: async (key, value) => {\n store[key] = value;\n },\n delete: async (key) => {\n delete store[key];\n },\n };\n};\nconst mockStorageUtility = (stored, isSecure = false) => {\n if (isSecure) {\n return new StorageUtility(mockStorage(stored), mockStorage({}));\n }\n return new StorageUtility(mockStorage({}), mockStorage(stored));\n};\n\nexports.AggregateHandler = AggregateHandler;\nexports.AuthorizationCodeWithPkceOidcHandlerBase = AuthorizationCodeWithPkceOidcHandlerBase;\nexports.ClientAuthentication = ClientAuthentication;\nexports.ConfigurationError = ConfigurationError;\nexports.DEFAULT_SCOPES = DEFAULT_SCOPES;\nexports.EVENTS = EVENTS;\nexports.GeneralLogoutHandler = GeneralLogoutHandler;\nexports.IRpLogoutHandler = IRpLogoutHandler;\nexports.IWaterfallLogoutHandler = IWaterfallLogoutHandler;\nexports.InMemoryStorage = InMemoryStorage;\nexports.InvalidResponseError = InvalidResponseError;\nexports.NotImplementedError = NotImplementedError;\nexports.OidcProviderError = OidcProviderError;\nexports.PREFERRED_SIGNING_ALG = PREFERRED_SIGNING_ALG;\nexports.REFRESH_BEFORE_EXPIRATION_SECONDS = REFRESH_BEFORE_EXPIRATION_SECONDS;\nexports.SOLID_CLIENT_AUTHN_KEY_PREFIX = SOLID_CLIENT_AUTHN_KEY_PREFIX;\nexports.SessionInfoManagerBase = SessionInfoManagerBase;\nexports.StorageUtility = StorageUtility;\nexports.StorageUtilityGetResponse = StorageUtilityGetResponse;\nexports.StorageUtilityMock = StorageUtilityMock;\nexports.USER_SESSION_PREFIX = USER_SESSION_PREFIX;\nexports.buildAuthenticatedFetch = buildAuthenticatedFetch;\nexports.buildProxyHandler = buildProxyHandler;\nexports.clear = clear;\nexports.createDpopHeader = createDpopHeader;\nexports.determineSigningAlg = determineSigningAlg;\nexports.fetchJwks = fetchJwks;\nexports.generateDpopKeyPair = generateDpopKeyPair;\nexports.getEndSessionUrl = getEndSessionUrl;\nexports.getSessionIdFromOauthState = getSessionIdFromOauthState;\nexports.getUnauthenticatedSession = getUnauthenticatedSession;\nexports.getWebidFromTokenPayload = getWebidFromTokenPayload;\nexports.handleRegistration = handleRegistration;\nexports.isSupportedTokenType = isSupportedTokenType;\nexports.isValidRedirectUrl = isValidRedirectUrl;\nexports.loadOidcContextFromStorage = loadOidcContextFromStorage;\nexports.maybeBuildRpInitiatedLogout = maybeBuildRpInitiatedLogout;\nexports.mockStorage = mockStorage;\nexports.mockStorageUtility = mockStorageUtility;\nexports.removeOpenIdParams = removeOpenIdParams;\nexports.saveSessionInfoToStorage = saveSessionInfoToStorage;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nvar jsonldStreamingParser = require('jsonld-streaming-parser');\nvar jsonldContextParser = require('jsonld-context-parser');\nvar universalFetch = require('@inrupt/universal-fetch');\nvar LinkHeader = require('http-link-header');\nvar n3 = require('n3');\nvar RdfJsDataFactory = require('@rdfjs/data-model');\nvar rdfJsDatasetModule = require('@rdfjs/dataset');\nvar uuid = require('uuid');\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Verify whether a given SolidDataset includes metadata about where it was sent to.\n *\n * @param dataset A [[SolidDataset]] that may have metadata attached about the Resource it was retrieved from.\n * @returns True if `dataset` includes metadata about the Resource it was sent to, false if not.\n * @since 0.2.0\n */\nfunction hasResourceInfo(resource) {\n const potentialResourceInfo = resource;\n return (typeof potentialResourceInfo === \"object\" &&\n typeof potentialResourceInfo.internal_resourceInfo === \"object\");\n}\n/**\n * Verify whether a given SolidDataset includes metadata about where it was retrieved from.\n *\n * @param dataset A [[SolidDataset]] that may have metadata attached about the Resource it was retrieved from.\n * @returns True if `dataset` includes metadata about the Resource it was retrieved from, false if not.\n * @since 0.6.0\n */\nfunction hasServerResourceInfo(resource) {\n const potentialResourceInfo = resource;\n return (typeof potentialResourceInfo === \"object\" &&\n typeof potentialResourceInfo.internal_resourceInfo === \"object\" &&\n typeof potentialResourceInfo.internal_resourceInfo.linkedResources ===\n \"object\");\n}\n/** @internal */\nfunction hasChangelog(dataset) {\n const potentialChangeLog = dataset;\n return (typeof potentialChangeLog.internal_changeLog === \"object\" &&\n Array.isArray(potentialChangeLog.internal_changeLog.additions) &&\n Array.isArray(potentialChangeLog.internal_changeLog.deletions));\n}\n/**\n * Errors thrown by solid-client extend this class, and can thereby be distinguished from errors\n * thrown in lower-level libraries.\n * @since 1.2.0\n */\nclass SolidClientError extends Error {\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @internal */\nfunction internal_toIriString(iri) {\n return typeof iri === \"string\" ? iri : iri.value;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// Make sure fetch can't be rebound, because it can cause errors in the browser.\n// Namely, it causes the issue discussed in https://stackoverflow.com/questions/71822422/uncaught-in-promise-typeerror-fetch-called-on-an-object-that-does-not-imple.\n// @see https://github.com/inrupt/solid-client-js/pull/1884#discussion_r1153872418\nconst fetch = universalFetch.fetch.bind(globalThis);\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @internal\n */\nfunction internal_parseResourceInfo(response) {\n var _a, _b, _c, _d, _e;\n const contentTypeParts = (_b = (_a = response.headers.get(\"Content-Type\")) === null || _a === void 0 ? void 0 : _a.split(\";\")) !== null && _b !== void 0 ? _b : [];\n // If the server offers a Turtle or JSON-LD serialisation on its own accord,\n // that tells us whether it is RDF data that the server can understand\n // (and hence can be updated with a PATCH request with SPARQL INSERT and DELETE statements),\n // in which case our SolidDataset-related functions should handle it.\n // For more context, see https://github.com/inrupt/solid-client-js/pull/214.\n const isSolidDataset = contentTypeParts.length > 0 &&\n [\"text/turtle\", \"application/ld+json\"].includes(contentTypeParts[0]);\n const resourceInfo = {\n sourceIri: response.url,\n isRawData: !isSolidDataset,\n contentLocation: (_c = response.headers.get(\"Content-Location\")) !== null && _c !== void 0 ? _c : undefined,\n contentType: (_d = response.headers.get(\"Content-Type\")) !== null && _d !== void 0 ? _d : undefined,\n linkedResources: {},\n location: (_e = response.headers.get(\"Location\")) !== null && _e !== void 0 ? _e : undefined,\n };\n const linkHeader = response.headers.get(\"Link\");\n if (linkHeader) {\n const parsedLinks = LinkHeader.parse(linkHeader);\n // Set ACL link\n const aclLinks = parsedLinks.get(\"rel\", \"acl\");\n if (aclLinks.length === 1) {\n resourceInfo.aclUrl = new URL(aclLinks[0].uri, resourceInfo.sourceIri).href;\n }\n // Parse all link headers and expose them in a standard way\n // (this can replace the parsing of the ACL link above):\n resourceInfo.linkedResources = parsedLinks.refs.reduce((rels, ref) => {\n var _a;\n var _b;\n (_a = rels[_b = ref.rel]) !== null && _a !== void 0 ? _a : (rels[_b] = []);\n rels[ref.rel].push(new URL(ref.uri, resourceInfo.sourceIri).href);\n return rels;\n }, resourceInfo.linkedResources);\n }\n const wacAllowHeader = response.headers.get(\"WAC-Allow\");\n if (wacAllowHeader) {\n resourceInfo.permissions = parseWacAllowHeader(wacAllowHeader);\n }\n return resourceInfo;\n}\n/**\n * Parse a WAC-Allow header into user and public access booleans.\n *\n * @param wacAllowHeader A WAC-Allow header in the format `user=\"read append write control\",public=\"read\"`\n * @see https://github.com/solid/solid-spec/blob/cb1373a369398d561b909009bd0e5a8c3fec953b/api-rest.md#wac-allow-headers\n */\nfunction parseWacAllowHeader(wacAllowHeader) {\n function parsePermissionStatement(permissionStatement) {\n const permissions = permissionStatement.split(\" \");\n const writePermission = permissions.includes(\"write\");\n return writePermission\n ? {\n read: permissions.includes(\"read\"),\n append: true,\n write: true,\n control: permissions.includes(\"control\"),\n }\n : {\n read: permissions.includes(\"read\"),\n append: permissions.includes(\"append\"),\n write: false,\n control: permissions.includes(\"control\"),\n };\n }\n function getStatementFor(header, scope) {\n const relevantEntries = header\n .split(\",\")\n .map((rawEntry) => rawEntry.split(\"=\"))\n .filter((parts) => parts.length === 2 && parts[0].trim() === scope);\n // There should only be one statement with the given scope:\n if (relevantEntries.length !== 1) {\n return \"\";\n }\n const relevantStatement = relevantEntries[0][1].trim();\n // The given statement should be wrapped in double quotes to be valid:\n if (relevantStatement.charAt(0) !== '\"' ||\n relevantStatement.charAt(relevantStatement.length - 1) !== '\"') {\n return \"\";\n }\n // Return the statment without the wrapping quotes, e.g.: read append write control\n return relevantStatement.substring(1, relevantStatement.length - 1);\n }\n return {\n user: parsePermissionStatement(getStatementFor(wacAllowHeader, \"user\")),\n public: parsePermissionStatement(getStatementFor(wacAllowHeader, \"public\")),\n };\n}\n/** @hidden Used to instantiate a separate instance from input parameters */\nfunction internal_cloneResource(resource) {\n let clonedResource;\n if (typeof resource.slice === \"function\") {\n // If given Resource is a File:\n clonedResource = Object.assign(resource.slice(), { ...resource });\n }\n else {\n // If it is just a plain object containing metadata:\n clonedResource = { ...resource };\n }\n return clonedResource;\n}\n/** @internal */\nfunction internal_isUnsuccessfulResponse(response) {\n return !response.ok;\n}\nfunction internal_isAuthenticationFailureResponse(response) {\n return response.status === 401 || response.status === 403;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// TODO: These should be replaced by auto-generated constants,\n// if we can ensure that unused constants will be excluded from bundles.\n/** @hidden */\nconst acl = {\n Authorization: \"http://www.w3.org/ns/auth/acl#Authorization\",\n AuthenticatedAgent: \"http://www.w3.org/ns/auth/acl#AuthenticatedAgent\",\n accessTo: \"http://www.w3.org/ns/auth/acl#accessTo\",\n agent: \"http://www.w3.org/ns/auth/acl#agent\",\n agentGroup: \"http://www.w3.org/ns/auth/acl#agentGroup\",\n agentClass: \"http://www.w3.org/ns/auth/acl#agentClass\",\n default: \"http://www.w3.org/ns/auth/acl#default\",\n defaultForNew: \"http://www.w3.org/ns/auth/acl#defaultForNew\",\n mode: \"http://www.w3.org/ns/auth/acl#mode\",\n origin: \"http://www.w3.org/ns/auth/acl#origin\",\n};\n/** @hidden */\nconst rdf = {\n type: \"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\",\n};\n/** @hidden */\nconst rdfs = {\n seeAlso: \"http://www.w3.org/2000/01/rdf-schema#seeAlso\",\n};\n/** @hidden */\nconst ldp = {\n BasicContainer: \"http://www.w3.org/ns/ldp#BasicContainer\",\n Container: \"http://www.w3.org/ns/ldp#Container\",\n Resource: \"http://www.w3.org/ns/ldp#Resource\",\n contains: \"http://www.w3.org/ns/ldp#contains\",\n};\n/** @hidden */\nconst foaf = {\n Agent: \"http://xmlns.com/foaf/0.1/Agent\",\n primaryTopic: \"http://xmlns.com/foaf/0.1/primaryTopic\",\n isPrimaryTopicOf: \"http://xmlns.com/foaf/0.1/isPrimaryTopicOf\",\n};\n/** @hidden */\nconst acp = {\n AccessControlResource: \"http://www.w3.org/ns/solid/acp#AccessControlResource\",\n Policy: \"http://www.w3.org/ns/solid/acp#Policy\",\n AccessControl: \"http://www.w3.org/ns/solid/acp#AccessControl\",\n Read: \"http://www.w3.org/ns/solid/acp#Read\",\n Append: \"http://www.w3.org/ns/solid/acp#Append\",\n Write: \"http://www.w3.org/ns/solid/acp#Write\",\n /** @deprecated Removed from the ACP proposal, to be replaced by Matchers. */\n Rule: \"http://www.w3.org/ns/solid/acp#Rule\",\n Matcher: \"http://www.w3.org/ns/solid/acp#Matcher\",\n accessControl: \"http://www.w3.org/ns/solid/acp#accessControl\",\n memberAccessControl: \"http://www.w3.org/ns/solid/acp#memberAccessControl\",\n apply: \"http://www.w3.org/ns/solid/acp#apply\",\n /** @deprecated Removed from the ACP proposal, to be replaced by memberAccessControls. */\n applyMembers: \"http://www.w3.org/ns/solid/acp#applyMembers\",\n allow: \"http://www.w3.org/ns/solid/acp#allow\",\n deny: \"http://www.w3.org/ns/solid/acp#deny\",\n allOf: \"http://www.w3.org/ns/solid/acp#allOf\",\n anyOf: \"http://www.w3.org/ns/solid/acp#anyOf\",\n noneOf: \"http://www.w3.org/ns/solid/acp#noneOf\",\n access: \"http://www.w3.org/ns/solid/acp#access\",\n /** @deprecated Removed from the ACP proposal, to be replaced by memberAccessControls. */\n accessMembers: \"http://www.w3.org/ns/solid/acp#accessMembers\",\n agent: \"http://www.w3.org/ns/solid/acp#agent\",\n group: \"http://www.w3.org/ns/solid/acp#group\",\n client: \"http://www.w3.org/ns/solid/acp#client\",\n PublicAgent: \"http://www.w3.org/ns/solid/acp#PublicAgent\",\n AuthenticatedAgent: \"http://www.w3.org/ns/solid/acp#AuthenticatedAgent\",\n CreatorAgent: \"http://www.w3.org/ns/solid/acp#CreatorAgent\",\n};\n/** @hidden */\nconst solid = {\n PublicOidcClient: \"http://www.w3.org/ns/solid/terms#PublicOidcClient\",\n};\n/** @hidden */\nconst security = {\n publicKey: \"https://w3id.org/security#publicKey\",\n};\n/** @hidden */\nconst pim = {\n storage: \"http://www.w3.org/ns/pim/space#storage\",\n};\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @ignore For internal use only. */\nconst internal_defaultFetchOptions = {\n fetch,\n};\n/**\n * Retrieve the information about a resource (e.g. access permissions) without\n * fetching the resource itself.\n *\n * @param url URL to fetch Resource metadata from.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters).\n * @returns Promise resolving to the metadata describing the given Resource, or rejecting if fetching it failed.\n * @since 0.4.0\n */\nasync function getResourceInfo(url, options = { ...internal_defaultFetchOptions, ignoreAuthenticationErrors: false }) {\n var _a;\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const response = await config.fetch(url, { method: \"HEAD\" });\n return responseToResourceInfo(response, {\n ignoreAuthenticationErrors: (_a = options.ignoreAuthenticationErrors) !== null && _a !== void 0 ? _a : false,\n });\n}\n/**\n * Parse Solid metadata from a Response obtained by fetching a Resource from a Solid Pod,\n *\n * @param response A Fetch API Response. See {@link https://developer.mozilla.org/en-US/docs/Web/API/Response MDN}.\n * @returns Resource metadata readable by functions such as [[getSourceUrl]].\n * @hidden This interface is not exposed yet until we've tried it out in practice.\n */\nfunction responseToResourceInfo(response, options = { ignoreAuthenticationErrors: false }) {\n if (internal_isUnsuccessfulResponse(response) &&\n (!internal_isAuthenticationFailureResponse(response) ||\n !options.ignoreAuthenticationErrors)) {\n throw new FetchError(`Fetching the metadata of the Resource at [${response.url}] failed: [${response.status}] [${response.statusText}].`, response);\n }\n const resourceInfo = internal_parseResourceInfo(response);\n return { internal_resourceInfo: resourceInfo };\n}\n/**\n * @param resource Resource for which to check whether it is a Container.\n * @returns Whether `resource` is a Container.\n */\nfunction isContainer(resource) {\n const containerUrl = hasResourceInfo(resource)\n ? getSourceUrl(resource)\n : internal_toIriString(resource);\n return containerUrl.endsWith(\"/\");\n}\n/**\n * This function will tell you whether a given Resource contains raw data, or a SolidDataset.\n *\n * @param resource Resource for which to check whether it contains raw data.\n * @return Whether `resource` contains raw data.\n */\nfunction isRawData(resource) {\n return resource.internal_resourceInfo.isRawData;\n}\n/**\n * @param resource Resource for which to determine the Content Type.\n * @returns The Content Type, if known, or null if not known.\n */\nfunction getContentType$1(resource) {\n var _a;\n return (_a = resource.internal_resourceInfo.contentType) !== null && _a !== void 0 ? _a : null;\n}\nfunction getSourceUrl(resource) {\n if (hasResourceInfo(resource)) {\n return resource.internal_resourceInfo.sourceIri;\n }\n return null;\n}\n/** @hidden Alias of getSourceUrl for those who prefer to use IRI terminology. */\nconst getSourceIri = getSourceUrl;\n/**\n * Given a Resource that exposes information about the owner of the Pod it is in, returns the WebID of that owner.\n *\n * Data about the owner of the Pod is exposed when the following conditions hold:\n * - The Pod server supports exposing the Pod owner\n * - The current user is allowed to see who the Pod owner is.\n *\n * If one or more of those conditions are false, this function will return `null`.\n *\n * @param resource A Resource that contains information about the owner of the Pod it is in.\n * @returns The WebID of the owner of the Pod the Resource is in, if provided, or `null` if not.\n * @since 0.6.0\n */\nfunction getPodOwner(resource) {\n var _a;\n if (!hasServerResourceInfo(resource)) {\n return null;\n }\n const podOwners = (_a = getLinkedResourceUrlAll(resource)[\"http://www.w3.org/ns/solid/terms#podOwner\"]) !== null && _a !== void 0 ? _a : [];\n return podOwners.length === 1 ? podOwners[0] : null;\n}\n/**\n * Given a WebID and a Resource that exposes information about the owner of the Pod it is in, returns whether the given WebID is the owner of the Pod.\n *\n * Data about the owner of the Pod is exposed when the following conditions hold:\n * - The Pod server supports exposing the Pod owner\n * - The current user is allowed to see who the Pod owner is.\n *\n * If one or more of those conditions are false, this function will return `null`.\n *\n * @param webId The WebID of which to check whether it is the Pod Owner's.\n * @param resource A Resource that contains information about the owner of the Pod it is in.\n * @returns Whether the given WebID is the Pod Owner's, if the Pod Owner is exposed, or `null` if it is not exposed.\n * @since 0.6.0\n */\nfunction isPodOwner(webId, resource) {\n const podOwner = getPodOwner(resource);\n if (typeof podOwner !== \"string\") {\n return null;\n }\n return podOwner === webId;\n}\n/**\n * Get the URLs of Resources linked to the given Resource.\n *\n * Solid servers can link Resources to each other. For example, in servers\n * implementing Web Access Control, Resources can have an Access Control List\n * Resource linked to it via the `acl` relation.\n *\n * @param resource A Resource fetched from a Solid Pod.\n * @returns The URLs of Resources linked to the given Resource, indexed by the key that links them.\n * @since 1.7.0\n */\nfunction getLinkedResourceUrlAll(resource) {\n return resource.internal_resourceInfo.linkedResources;\n}\n/**\n * Get what access the current user has to the given Resource.\n *\n * This function can tell you what access the current user has for the given\n * Resource, allowing you to e.g. determine that changes to it will be rejected\n * before attempting to do so.\n * Additionally, for servers adhering to the Web Access Control specification,\n * it will tell you what access unauthenticated users have to the given Resource.\n *\n * @param resource A Resource fetched from a Solid Pod.\n * @returns What access the current user and, if supported by the server, unauthenticated users have to the given Resource.\n * @since 1.7.0\n */\nfunction getEffectiveAccess(resource) {\n var _a, _b, _c, _d, _e, _f, _g;\n if (typeof resource.internal_resourceInfo.permissions === \"object\") {\n return {\n user: {\n read: resource.internal_resourceInfo.permissions.user.read,\n append: resource.internal_resourceInfo.permissions.user.append,\n write: resource.internal_resourceInfo.permissions.user.write,\n },\n public: {\n read: resource.internal_resourceInfo.permissions.public.read,\n append: resource.internal_resourceInfo.permissions.public.append,\n write: resource.internal_resourceInfo.permissions.public.write,\n },\n };\n }\n const linkedResourceUrls = getLinkedResourceUrlAll(resource);\n return {\n user: {\n read: (_b = (_a = linkedResourceUrls[acp.allow]) === null || _a === void 0 ? void 0 : _a.includes(acp.Read)) !== null && _b !== void 0 ? _b : false,\n append: (_e = (((_c = linkedResourceUrls[acp.allow]) === null || _c === void 0 ? void 0 : _c.includes(acp.Append)) ||\n ((_d = linkedResourceUrls[acp.allow]) === null || _d === void 0 ? void 0 : _d.includes(acp.Write)))) !== null && _e !== void 0 ? _e : false,\n write: (_g = (_f = linkedResourceUrls[acp.allow]) === null || _f === void 0 ? void 0 : _f.includes(acp.Write)) !== null && _g !== void 0 ? _g : false,\n },\n };\n}\n/**\n * Extends the regular JavaScript error object with access to the status code and status message.\n * @since 1.2.0\n */\nclass FetchError extends SolidClientError {\n get statusCode() {\n return this.response.status;\n }\n get statusText() {\n return this.response.statusText;\n }\n constructor(message, errorResponse) {\n super(message);\n this.response = errorResponse;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note} This function is still experimental and subject to change, even\n * in a non-major release.\n * ```\n * This returns a parser that transforms a JSON-LD string into a set of RDFJS quads.\n *\n * @returns A Parser object.\n * @since 1.15.0\n */\nconst getJsonLdParser$1 = () => {\n const onQuadCallbacks = [];\n const onCompleteCallbacks = [];\n const onErrorCallbacks = [];\n return {\n onQuad: (callback) => {\n onQuadCallbacks.push(callback);\n },\n onError: (callback) => {\n onErrorCallbacks.push(callback);\n },\n onComplete: (callback) => {\n onCompleteCallbacks.push(callback);\n },\n // The following returns a Promise that can be awaited, which is undocumented\n // behavior that doesn't match the type signature. It prevents a potentially\n // breaking change, and will be updated on the next major release.\n parse: async (source, resourceInfo) => new Promise((res) => {\n const parser = new jsonldStreamingParser.JsonLdParser({\n baseIRI: getSourceUrl(resourceInfo),\n documentLoader: new jsonldContextParser.FetchDocumentLoader(fetch),\n });\n let endCalled = false;\n function end() {\n if (!endCalled) {\n endCalled = true;\n onCompleteCallbacks.forEach((callback) => callback());\n res();\n }\n }\n parser.on(\"end\", end);\n parser.on(\"error\", (err) => {\n onErrorCallbacks.forEach((callback) => callback(err));\n end();\n });\n onQuadCallbacks.forEach((callback) => parser.on(\"data\", callback));\n parser.write(source);\n parser.end();\n }),\n };\n};\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// @rdfjs/dataset is a CommonJS module, so named imports break in Node.\n// Thus, import the default export, then obtain the `dataset` property from there.\nrdfJsDatasetModule.dataset;\nconst localNodeSkolemPrefix = \"https://inrupt.com/.well-known/sdk-local-node/\";\n/**\n * Runtime freezing might be too much overhead;\n * if so, this function allows us to replace it by a function\n * that merely marks its input as Readonly<> for static analysis.\n */\nconst { freeze } = Object;\nfunction isLocalNodeIri(iri) {\n return (iri.substring(0, localNodeSkolemPrefix.length) === localNodeSkolemPrefix);\n}\nfunction getLocalNodeName(localNodeIri) {\n return localNodeIri.substring(localNodeSkolemPrefix.length);\n}\nfunction getLocalNodeIri(localNodeName) {\n return `${localNodeSkolemPrefix}${localNodeName}`;\n}\nfunction isBlankNodeId(value) {\n return typeof value === \"string\" && value.substring(0, 2) === \"_:\";\n}\nfunction getBlankNodeValue(blankNodeId) {\n return blankNodeId.substring(2);\n}\nfunction getBlankNodeId(blankNode) {\n return `_:${blankNode.value}`;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * IRIs of the XML Schema data types we support\n */\nconst xmlSchemaTypes = {\n boolean: \"http://www.w3.org/2001/XMLSchema#boolean\",\n dateTime: \"http://www.w3.org/2001/XMLSchema#dateTime\",\n date: \"http://www.w3.org/2001/XMLSchema#date\",\n time: \"http://www.w3.org/2001/XMLSchema#time\",\n decimal: \"http://www.w3.org/2001/XMLSchema#decimal\",\n integer: \"http://www.w3.org/2001/XMLSchema#integer\",\n string: \"http://www.w3.org/2001/XMLSchema#string\",\n langString: \"http://www.w3.org/1999/02/22-rdf-syntax-ns#langString\",\n};\n/**\n * @internal\n * @param value Value to serialise.\n * @returns String representation of `value`.\n * @see https://www.w3.org/TR/xmlschema-2/#boolean-lexical-representation\n */\nfunction serializeBoolean(value) {\n return value ? \"true\" : \"false\";\n}\n/**\n * @internal\n * @param value Value to deserialise.\n * @returns Deserialized boolean, or null if the given value is not a valid serialised boolean.\n * @see https://www.w3.org/TR/xmlschema-2/#boolean-lexical-representation\n */\nfunction deserializeBoolean(value) {\n if (value === \"true\" || value === \"1\") {\n return true;\n }\n if (value === \"false\" || value === \"0\") {\n return false;\n }\n return null;\n}\n/**\n * @internal\n * @param value Value to serialise.\n * @returns String representation of `value` in UTC.\n * @see https://www.w3.org/TR/xmlschema-2/#time-lexical-repr\n */\nfunction serializeTime(value) {\n let millisecondString;\n let timezoneString;\n if (value.millisecond) {\n if (value.millisecond < 10) {\n millisecondString = `00${value.millisecond}`;\n }\n else if (value.millisecond < 100) {\n millisecondString = `0${value.millisecond}`;\n }\n else {\n millisecondString = value.millisecond;\n }\n }\n if (typeof value.timezoneHourOffset === \"number\") {\n const timezoneFormatted = Math.abs(value.timezoneHourOffset) < 10\n ? `0${Math.abs(value.timezoneHourOffset)}`\n : Math.abs(value.timezoneHourOffset);\n timezoneString =\n value.timezoneHourOffset >= 0\n ? `+${timezoneFormatted}`\n : `-${timezoneFormatted}`;\n if (value.timezoneMinuteOffset) {\n timezoneString = `${timezoneString}:${value.timezoneMinuteOffset < 10\n ? `0${value.timezoneMinuteOffset}`\n : value.timezoneMinuteOffset}`;\n }\n else {\n timezoneString += \":00\";\n }\n }\n return `${value.hour < 10 ? `0${value.hour}` : value.hour}:${value.minute < 10 ? `0${value.minute}` : value.minute}:${value.second < 10 ? `0${value.second}` : value.second}${value.millisecond ? `.${millisecondString}` : \"\"}${timezoneString || \"\"}`;\n}\n/**\n * @internal\n * @param literalString Value to deserialise.\n * @returns Deserialized time, or null if the given value is not a valid serialised datetime.\n * @see https://www.w3.org/TR/xmlschema-2/#time-lexical-repr\n */\nfunction deserializeTime(literalString) {\n // Time in the format described at\n // https://www.w3.org/TR/xmlschema-2/#time-lexical-repr\n // \\d\\d:\\d\\d:\\d\\d - Two digits for the hour, minute and second, respectively, separated by a `:`.\n // Example: \"13:37:42\".\n // (\\.\\d+)? - Optionally a `.` followed by one or more digits representing milliseconds.\n // Example: \".1337\".\n // (Z|(\\+|-)\\d\\d:\\d\\d) - The letter Z indicating UTC, or a `+` or `-` followed by two digits for\n // the hour offset and two for the minute offset, separated by a `:`.\n // Example: \"+13:37\".\n const timeRegEx = /\\d\\d:\\d\\d:\\d\\d(\\.\\d+)?(Z|(\\+|-)\\d\\d:\\d\\d)?/;\n if (!timeRegEx.test(literalString)) {\n return null;\n }\n const [timeString, timezoneString] = splitTimeFromTimezone(literalString);\n const [hourString, minuteString, timeRest] = timeString.split(\":\");\n let utcHours = Number.parseInt(hourString, 10);\n let utcMinutes = Number.parseInt(minuteString, 10);\n const [secondString, optionalMillisecondString] = timeRest.split(\".\");\n const utcSeconds = Number.parseInt(secondString, 10);\n const utcMilliseconds = optionalMillisecondString\n ? Number.parseInt(optionalMillisecondString, 10)\n : undefined;\n if (utcMinutes >= 60) {\n utcHours += 1;\n utcMinutes -= 60;\n }\n const deserializedTime = {\n hour: utcHours,\n minute: utcMinutes,\n second: utcSeconds,\n };\n if (typeof utcMilliseconds === \"number\") {\n deserializedTime.millisecond = utcMilliseconds;\n }\n if (typeof timezoneString === \"string\") {\n const [hourOffset, minuteOffset] = getTimezoneOffsets(timezoneString);\n if (typeof hourOffset !== \"number\" ||\n hourOffset > 24 ||\n typeof minuteOffset !== \"number\" ||\n minuteOffset > 59) {\n return null;\n }\n deserializedTime.timezoneHourOffset = hourOffset;\n deserializedTime.timezoneMinuteOffset = minuteOffset;\n }\n return deserializedTime;\n}\n/**\n * @internal\n * @param value Value to serialise.\n * @returns String representation of `value`.\n * @see https://www.w3.org/TR/xmlschema-2/#dateTime-lexical-representation\n */\nfunction serializeDatetime(value) {\n // Although the XML Schema DateTime is not _exactly_ an ISO 8601 string\n // (see https://www.w3.org/TR/xmlschema-2/#deviantformats),\n // the deviations only affect the parsing, not the serialisation.\n // Therefore, we can just use .toISOString():\n return value.toISOString();\n}\n/**\n * @internal\n * @param value Value to deserialise.\n * @returns Deserialized datetime, or null if the given value is not a valid serialised datetime.\n * @see https://www.w3.org/TR/xmlschema-2/#dateTime-lexical-representation\n */\nfunction deserializeDatetime(literalString) {\n // DateTime in the format described at\n // https://www.w3.org/TR/xmlschema-2/#dateTime-lexical-representation\n // (without constraints on the value).\n // -? - An optional leading `-`.\n // \\d{4,}- - Four or more digits followed by a `-` representing the year. Example: \"3000-\".\n // \\d\\d-\\d\\d - Two digits representing the month and two representing the day of the month,\n // separated by a `-`. Example: \"11-03\".\n // T - The letter T, separating the date from the time.\n // \\d\\d:\\d\\d:\\d\\d - Two digits for the hour, minute and second, respectively, separated by a `:`.\n // Example: \"13:37:42\".\n // (\\.\\d+)? - Optionally a `.` followed by one or more digits representing milliseconds.\n // Example: \".1337\".\n // (Z|(\\+|-)\\d\\d:\\d\\d) - The letter Z indicating UTC, or a `+` or `-` followed by two digits for\n // the hour offset and two for the minute offset, separated by a `:`.\n // Example: \"+13:37\".\n const datetimeRegEx = /-?\\d{4,}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(\\.\\d+)?(Z|(\\+|-)\\d\\d:\\d\\d)?/;\n if (!datetimeRegEx.test(literalString)) {\n return null;\n }\n const [signedDateString, rest] = literalString.split(\"T\");\n // The date string can optionally be prefixed with `-`,\n // in which case the year is negative:\n const [yearMultiplier, dateString] = signedDateString.charAt(0) === \"-\"\n ? [-1, signedDateString.substring(1)]\n : [1, signedDateString];\n const [yearString, monthString, dayString] = dateString.split(\"-\");\n const utcFullYear = Number.parseInt(yearString, 10) * yearMultiplier;\n const utcMonth = Number.parseInt(monthString, 10) - 1;\n const utcDate = Number.parseInt(dayString, 10);\n const [timeString, timezoneString] = splitTimeFromTimezone(rest);\n const [hourOffset, minuteOffset] = typeof timezoneString === \"string\"\n ? getTimezoneOffsets(timezoneString)\n : [0, 0];\n const [hourString, minuteString, timeRest] = timeString.split(\":\");\n const utcHours = Number.parseInt(hourString, 10) + hourOffset;\n const utcMinutes = Number.parseInt(minuteString, 10) + minuteOffset;\n const [secondString, optionalMillisecondString] = timeRest.split(\".\");\n const utcSeconds = Number.parseInt(secondString, 10);\n const utcMilliseconds = optionalMillisecondString\n ? Number.parseInt(optionalMillisecondString, 10)\n : 0;\n const date = new Date(Date.UTC(utcFullYear, utcMonth, utcDate, utcHours, utcMinutes, utcSeconds, utcMilliseconds));\n // For the year, values from 0 to 99 map to the years 1900 to 1999. Since the serialisation\n // always writes out the years fully, we should correct this to actually map to the years 0 to 99.\n // See\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#Individual_date_and_time_component_values\n if (utcFullYear >= 0 && utcFullYear < 100) {\n // Note that we base it on the calculated year, rather than the year that was actually read.\n // This is because the year might actually differ from the value listed in the serialisation,\n // i.e. when moving the timezone offset to UTC pushes it into a different year:\n date.setUTCFullYear(date.getUTCFullYear() - 1900);\n }\n return date;\n}\n/**\n * @internal\n * @param value Value to serialise.\n * @returns String representation of `value`.\n * @see https://www.w3.org/TR/xmlschema-2/#date-lexical-representation\n */\nfunction serializeDate(value) {\n const year = value.getFullYear();\n const month = value.getMonth() + 1;\n const day = value.getDate();\n const [, timezone] = splitTimeFromTimezone(value.toISOString());\n return `${year}-${String(month).padStart(2, \"0\")}-${String(day).padStart(2, \"0\")}${timezone}`;\n}\n/**\n * @internal\n * @param value Value to deserialise.\n * @returns Deserialized datetime, or null if the given value is not a valid serialised datetime.\n * @see https://www.w3.org/TR/xmlschema-2/#date-lexical-representation\n */\nfunction deserializeDate(literalString) {\n // Date in the format described at\n // https://www.w3.org/TR/xmlschema-2/#date-lexical-representation\n // (without constraints on the value).\n // -? - An optional leading `-`.\n // \\d{4,}- - Four or more digits followed by a `-` representing the year. Example: \"3000-\".\n // \\d\\d-\\d\\d - Two digits representing the month and two representing the day of the month,\n // separated by a `-`. Example: \"11-03\".\n // (Z|(\\+|-)\\d\\d:\\d\\d) - Optionally, the letter Z indicating UTC, or a `+` or `-` followed by two digits for\n // the hour offset and two for the minute offset, separated by a `:`.\n // Example: \"+13:37\".\n const dateRegEx = /-?\\d{4,}-\\d\\d-\\d\\d(Z|(\\+|-)\\d\\d:\\d\\d)?/;\n if (!dateRegEx.test(literalString)) {\n return null;\n }\n const signedDateString = literalString;\n // The date string can optionally be prefixed with `-`,\n // in which case the year is negative:\n const [yearMultiplier, dateString] = signedDateString.charAt(0) === \"-\"\n ? [-1, signedDateString.substring(1)]\n : [1, signedDateString];\n const [yearString, monthString, dayAndTimezoneString] = dateString.split(\"-\");\n const dayString = dayAndTimezoneString.length > 2\n ? dayAndTimezoneString.substring(0, 2)\n : dayAndTimezoneString;\n const utcFullYear = Number.parseInt(yearString, 10) * yearMultiplier;\n const utcMonth = Number.parseInt(monthString, 10) - 1;\n const utcDate = Number.parseInt(dayString, 10);\n const hour = 12;\n // setting at 12:00 avoids all timezones\n const date = new Date(Date.UTC(utcFullYear, utcMonth, utcDate, hour));\n // For the year, values from 0 to 99 map to the years 1900 to 1999. Since the serialisation\n // always writes out the years fully, we should correct this to actually map to the years 0 to 99.\n // See\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#Individual_date_and_time_component_values\n if (utcFullYear >= 0 && utcFullYear < 100) {\n date.setUTCFullYear(date.getUTCFullYear() - 1900);\n }\n return date;\n}\n/**\n * @param timeString An XML Schema time string.\n * @returns A tuple [timeString, timezoneString].\n * @see https://www.w3.org/TR/xmlschema-2/#time-lexical-repr\n */\nfunction splitTimeFromTimezone(timeString) {\n if (timeString.endsWith(\"Z\")) {\n return [timeString.substring(0, timeString.length - 1), \"Z\"];\n }\n const splitOnPlus = timeString.split(\"+\");\n const splitOnMinus = timeString.split(\"-\");\n if (splitOnPlus.length === 1 && splitOnMinus.length === 1) {\n return [splitOnPlus[0], undefined];\n }\n return splitOnPlus.length > splitOnMinus.length\n ? [splitOnPlus[0], `+${splitOnPlus[1]}`]\n : [splitOnMinus[0], `-${splitOnMinus[1]}`];\n}\n/**\n * @param timezoneString Lexical representation of a time zone in XML Schema.\n * @returns A tuple of the hour and minute offset of the time zone.\n * @see https://www.w3.org/TR/xmlschema-2/#dateTime-timezones\n */\nfunction getTimezoneOffsets(timezoneString) {\n if (timezoneString === \"Z\") {\n return [0, 0];\n }\n const multiplier = timezoneString.charAt(0) === \"+\" ? 1 : -1;\n const [hourString, minuteString] = timezoneString.substring(1).split(\":\");\n const hours = Number.parseInt(hourString, 10);\n const minutes = Number.parseInt(minuteString, 10);\n return [hours * multiplier, minutes * multiplier];\n}\n/**\n * @internal\n * @param value Value to serialise.\n * @returns String representation of `value`.\n * @see https://www.w3.org/TR/xmlschema-2/#decimal-lexical-representation\n */\nfunction serializeDecimal(value) {\n return value.toString();\n}\n/**\n * @internal\n * @param value Value to deserialise.\n * @returns Deserialized decimal, or null if the given value is not a valid serialised decimal.\n * @see https://www.w3.org/TR/xmlschema-2/#decimal-lexical-representation\n */\nfunction deserializeDecimal(literalString) {\n const deserialized = Number.parseFloat(literalString);\n if (Number.isNaN(deserialized)) {\n return null;\n }\n return deserialized;\n}\n/**\n * @internal\n * @param value Value to serialise.\n * @returns String representation of `value`.\n */\nfunction serializeInteger(value) {\n return value.toString();\n}\n/**\n * @internal\n * @param value Value to deserialise.\n * @returns Deserialized integer, or null if the given value is not a valid serialised integer.\n */\nfunction deserializeInteger(literalString) {\n const deserialized = Number.parseInt(literalString, 10);\n if (Number.isNaN(deserialized)) {\n return null;\n }\n return deserialized;\n}\n/**\n * @internal\n * @param locale Locale to transform into a consistent format.\n */\nfunction normalizeLocale(locale) {\n return locale.toLowerCase();\n}\n/**\n * @internal Library users shouldn't need to be exposed to raw NamedNodes.\n * @param value The value that might or might not be a Named Node.\n * @returns Whether `value` is a Named Node.\n */\nfunction isNamedNode(value) {\n return isTerm(value) && value.termType === \"NamedNode\";\n}\n/**\n * @internal Library users shouldn't need to be exposed to raw Literals.\n * @param value The value that might or might not be a Literal.\n * @returns Whether `value` is a Literal.\n */\nfunction isLiteral(value) {\n return isTerm(value) && value.termType === \"Literal\";\n}\n/**\n * @internal Library users shouldn't need to be exposed to raw Terms.\n * @param value The value that might or might not be a Term.\n * @returns Whether `value` is a Term.\n */\nfunction isTerm(value) {\n return (value !== null &&\n typeof value === \"object\" &&\n typeof value.termType === \"string\" &&\n typeof value.value === \"string\" &&\n typeof value.equals === \"function\");\n}\n/**\n * @internal Library users shouldn't need to be exposed to LocalNodes.\n * @param value The value that might or might not be a Node with no known IRI yet.\n * @returns Whether `value` is a Node with no known IRI yet.\n */\nfunction isLocalNode(value) {\n return isNamedNode(value) && isLocalNodeIri(value.value);\n}\n/**\n * Ensure that a given value is a valid URL.\n *\n * @internal Library users shouldn't need to be exposed to raw URLs.\n * @param iri The value of which to verify that it is a valid URL.\n */\nfunction internal_isValidUrl(iri) {\n const iriString = internal_toIriString(iri);\n // If the runtime environment supports URL, instantiate one.\n // If the given IRI is not a valid URL, it will throw an error.\n // See: https://developer.mozilla.org/en-US/docs/Web/API/URL\n /* istanbul ignore if [URL is available in our testing environment, so we cannot test the alternative] */\n if (typeof URL !== \"function\") {\n // If we can't validate the URL, do not throw an error:\n return true;\n }\n try {\n // eslint-disable-next-line no-new\n new URL(iriString);\n return true;\n }\n catch (_a) {\n return false;\n }\n}\n/**\n * @internal Utility method; library users should not need to interact with LocalNodes directly.\n * @param localNode The LocalNode to resolve to a NamedNode.\n * @param resourceIri The Resource in which the Node will be saved.\n */\nfunction resolveIriForLocalNode(localNode, resourceIri) {\n return DataFactory.namedNode(resolveLocalIri(getLocalNodeName(localNode.value), resourceIri));\n}\n/**\n * @internal API for internal use only.\n * @param name The name identifying a Thing.\n * @param resourceIri The Resource in which the Thing can be found.\n */\nfunction resolveLocalIri(name, resourceIri) {\n /* istanbul ignore if [The URL interface is available in the testing environment, so we cannot test this] */\n if (typeof URL !== \"function\") {\n throw new Error(\"The URL interface is not available, so an IRI cannot be determined.\");\n }\n const thingIri = new URL(resourceIri);\n thingIri.hash = name;\n return thingIri.href;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst DataFactory = RdfJsDataFactory;\nfunction addRdfJsQuadToDataset(dataset, quad, quadParseOptions = {}) {\n var _a;\n const supportedGraphTypes = [\n \"NamedNode\",\n \"DefaultGraph\",\n ];\n if (!supportedGraphTypes.includes(quad.graph.termType)) {\n throw new Error(`Cannot parse Quads with nodes of type [${quad.graph.termType}] as their Graph node.`);\n }\n const graphId = quad.graph.termType === \"DefaultGraph\" ? \"default\" : quad.graph.value;\n const graph = (_a = dataset.graphs[graphId]) !== null && _a !== void 0 ? _a : {};\n return freeze({\n ...dataset,\n graphs: freeze({\n ...dataset.graphs,\n [graphId]: addRdfJsQuadToGraph(graph, quad, quadParseOptions),\n }),\n });\n}\nfunction addRdfJsQuadToGraph(graph, quad, quadParseOptions) {\n var _a;\n const supportedSubjectTypes = [\n \"NamedNode\",\n \"BlankNode\",\n ];\n if (!supportedSubjectTypes.includes(quad.subject.termType)) {\n throw new Error(`Cannot parse Quads with nodes of type [${quad.subject.termType}] as their Subject node.`);\n }\n const subjectIri = quad.subject.termType === \"BlankNode\"\n ? `_:${quad.subject.value}`\n : quad.subject.value;\n const subject = (_a = graph[subjectIri]) !== null && _a !== void 0 ? _a : {\n type: \"Subject\",\n url: subjectIri,\n predicates: {},\n };\n return freeze({\n ...graph,\n [subjectIri]: addRdfJsQuadToSubject(subject, quad, quadParseOptions),\n });\n}\nfunction addRdfJsQuadToSubject(subject, quad, quadParseOptions) {\n return freeze({\n ...subject,\n predicates: addRdfJsQuadToPredicates(subject.predicates, quad, quadParseOptions),\n });\n}\nfunction addRdfJsQuadToPredicates(predicates, quad, quadParseOptions) {\n var _a;\n const supportedPredicateTypes = [\n \"NamedNode\",\n ];\n if (!supportedPredicateTypes.includes(quad.predicate.termType)) {\n throw new Error(`Cannot parse Quads with nodes of type [${quad.predicate.termType}] as their Predicate node.`);\n }\n const predicateIri = quad.predicate.value;\n const objects = (_a = predicates[predicateIri]) !== null && _a !== void 0 ? _a : {};\n return freeze({\n ...predicates,\n [predicateIri]: addRdfJsQuadToObjects(objects, quad, quadParseOptions),\n });\n}\nfunction addRdfJsQuadToObjects(objects, quad, quadParseOptions) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n if (quad.object.termType === \"NamedNode\") {\n const namedNodes = freeze([\n ...((_a = objects.namedNodes) !== null && _a !== void 0 ? _a : []),\n quad.object.value,\n ]);\n return freeze({\n ...objects,\n namedNodes,\n });\n }\n if (quad.object.termType === \"Literal\") {\n if (quad.object.datatype.value === xmlSchemaTypes.langString) {\n const locale = quad.object.language.toLowerCase();\n const thisLocaleStrings = freeze([\n ...((_c = (_b = objects.langStrings) === null || _b === void 0 ? void 0 : _b[locale]) !== null && _c !== void 0 ? _c : []),\n quad.object.value,\n ]);\n const langStrings = freeze({\n ...((_d = objects.langStrings) !== null && _d !== void 0 ? _d : {}),\n [locale]: thisLocaleStrings,\n });\n return freeze({\n ...objects,\n langStrings,\n });\n }\n // If the Object is a non-langString Literal\n const thisTypeValues = freeze([\n ...((_f = (_e = objects.literals) === null || _e === void 0 ? void 0 : _e[quad.object.datatype.value]) !== null && _f !== void 0 ? _f : []),\n quad.object.value,\n ]);\n const literals = freeze({\n ...((_g = objects.literals) !== null && _g !== void 0 ? _g : {}),\n [quad.object.datatype.value]: thisTypeValues,\n });\n return freeze({\n ...objects,\n literals,\n });\n }\n if (quad.object.termType === \"BlankNode\") {\n const blankNodePredicates = getPredicatesForBlankNode(quad.object, quadParseOptions);\n const blankNodes = freeze([\n ...((_h = objects.blankNodes) !== null && _h !== void 0 ? _h : []),\n blankNodePredicates,\n ]);\n return freeze({\n ...objects,\n blankNodes,\n });\n }\n throw new Error(`Objects of type [${quad.object.termType}] are not supported.`);\n}\nfunction getPredicatesForBlankNode(node, quadParseOptions) {\n var _a, _b;\n const chainBlankNodes = (_a = quadParseOptions.chainBlankNodes) !== null && _a !== void 0 ? _a : [];\n if (chainBlankNodes.find((chainBlankNode) => chainBlankNode.equals(node)) ===\n undefined) {\n // If this Blank Node is not used to provide nested values for another Subject,\n // just return its identifier.\n // That identifier will also be listed among the Subjects in the Graph.\n return getBlankNodeId(node);\n }\n /* istanbul ignore next: If there are chain nodes, there will always be other Quads, so the `?? []` can't be reached: */\n const quads = (_b = quadParseOptions.otherQuads) !== null && _b !== void 0 ? _b : [];\n const quadsWithNodeAsSubject = quads.filter((quad) => quad.subject.equals(node));\n // First add the Quads with regular Objects\n const predicates = quadsWithNodeAsSubject\n .filter((quad) => !isBlankNode(quad.object))\n .reduce((predicatesAcc, quad) => {\n var _a;\n const supportedPredicateTypes = [\n \"NamedNode\",\n ];\n if (!supportedPredicateTypes.includes(quad.predicate.termType)) {\n throw new Error(`Cannot parse Quads with nodes of type [${quad.predicate.termType}] as their Predicate node.`);\n }\n const objects = (_a = predicatesAcc[quad.predicate.value]) !== null && _a !== void 0 ? _a : {};\n return freeze({\n ...predicatesAcc,\n [quad.predicate.value]: addRdfJsQuadToObjects(objects, quad, quadParseOptions),\n });\n }, {});\n // And then also add the Quads that have another Blank Node as the Object\n // in addition to the Blank Node `node` as the Subject:\n const blankNodeObjectQuads = quadsWithNodeAsSubject.filter((quad) => isBlankNode(quad.object));\n return blankNodeObjectQuads.reduce((predicatesAcc, quad) => {\n var _a, _b;\n const supportedPredicateTypes = [\n \"NamedNode\",\n ];\n if (!supportedPredicateTypes.includes(quad.predicate.termType)) {\n throw new Error(`Cannot parse Quads with nodes of type [${quad.predicate.termType}] as their Predicate node.`);\n }\n /* istanbul ignore next: The `?? {}` doesn't get hit; presumably it's initialised above. */\n const objects = (_a = predicatesAcc[quad.predicate.value]) !== null && _a !== void 0 ? _a : {};\n /* istanbul ignore next: The `?? []` doesn't get hit; presumably it's initialised above. */\n const blankNodes = (_b = objects.blankNodes) !== null && _b !== void 0 ? _b : [];\n return freeze({\n ...predicatesAcc,\n // The BlankNode assertions are valid because we filtered on BlankNodes above:\n [quad.predicate.value]: {\n ...objects,\n blankNodes: [\n ...blankNodes,\n getPredicatesForBlankNode(quad.object, quadParseOptions),\n ],\n },\n });\n }, predicates);\n}\n/**\n * Given an array of Quads, returns all Blank Nodes that are used in a single chain of Nodes.\n *\n * This allows you to obtain which Blank Nodes are involved in e.g. RDF lists.\n * This is useful because those can be represented as nested data that will have\n * a deterministic structure, whereas a representation of Blank Nodes that\n * create a cycle or are re-used will need ad-hoc, non-deterministic identifiers\n * to allow for representation without inifinite nesting.\n */\nfunction getChainBlankNodes(quads) {\n // All Blank Nodes that occur in Subject position:\n const blankNodeSubjects = quads\n .map((quad) => quad.subject)\n .filter(isBlankNode);\n // All Blank Nodes that occur in Object position:\n const blankNodeObjects = quads.map((quad) => quad.object).filter(isBlankNode);\n // Makes sure that all given Nodes are the same,\n // which will be used to verify that a set of Quads all have the same Subject:\n function everyNodeTheSame(nodes) {\n // This could potentially be made more performant by mapping every term\n // to their value and using native JS comparisons, assuming every node is\n // either a Blank or a Named Node.\n return nodes.every((otherNode) => nodes.every((anotherNode) => otherNode.equals(anotherNode)));\n }\n // Get all Blank Nodes that are part of a cycle in the graph:\n const cycleBlankNodes = [];\n blankNodeObjects.forEach((blankNodeObject) => {\n cycleBlankNodes.push(...getCycleBlankNodes(blankNodeObject, quads));\n });\n // Get Blank Nodes that are used to provide nested values for a single Subject,\n // which we'll represent as nested values as well\n // (this allows us to avoid generating a non-deterministic, ad-hoc identifier\n // for those Blank Nodes).\n // We'll do this by taking all Blank Nodes in the given Quads...\n const chainBlankNodes = blankNodeSubjects\n .concat(blankNodeObjects)\n .filter((blankNode) => {\n // ....removing those Blank Nodes that are part of a cycle...\n if (cycleBlankNodes.some((cycleBlankNode) => cycleBlankNode.equals(blankNode))) {\n return false;\n }\n // ...and then returning only those Blank Nodes that only occur in the\n // Object position for a single Subject, i.e. that are part of a single\n // chain:\n const subjectsWithThisNodeAsObject = quads\n .filter((quad) => quad.object.equals(blankNode))\n .map((quad) => quad.subject);\n return (subjectsWithThisNodeAsObject.length > 0 &&\n everyNodeTheSame(subjectsWithThisNodeAsObject));\n });\n return chainBlankNodes;\n}\nfunction toRdfJsQuads(dataset, options = {}) {\n var _a;\n const quads = [];\n const dataFactory = (_a = options.dataFactory) !== null && _a !== void 0 ? _a : RdfJsDataFactory;\n Object.keys(dataset.graphs).forEach((graphIri) => {\n const graph = dataset.graphs[graphIri];\n const graphNode = graphIri === \"default\"\n ? dataFactory.defaultGraph()\n : dataFactory.namedNode(graphIri);\n Object.keys(graph).forEach((subjectIri) => {\n const { predicates } = graph[subjectIri];\n const subjectNode = isBlankNodeId(subjectIri)\n ? dataFactory.blankNode(getBlankNodeValue(subjectIri))\n : dataFactory.namedNode(subjectIri);\n quads.push(...subjectToRdfJsQuads(predicates, subjectNode, graphNode, options));\n });\n });\n return quads;\n}\nfunction subjectToRdfJsQuads(predicates, subjectNode, graphNode, options = {}) {\n var _a;\n const quads = [];\n const dataFactory = (_a = options.dataFactory) !== null && _a !== void 0 ? _a : RdfJsDataFactory;\n Object.keys(predicates).forEach((predicateIri) => {\n var _a, _b, _c, _d;\n const predicateNode = dataFactory.namedNode(predicateIri);\n const langStrings = (_a = predicates[predicateIri].langStrings) !== null && _a !== void 0 ? _a : {};\n const namedNodes = (_b = predicates[predicateIri].namedNodes) !== null && _b !== void 0 ? _b : [];\n const literals = (_c = predicates[predicateIri].literals) !== null && _c !== void 0 ? _c : {};\n const blankNodes = (_d = predicates[predicateIri].blankNodes) !== null && _d !== void 0 ? _d : [];\n const literalTypes = Object.keys(literals);\n literalTypes.forEach((typeIri) => {\n const typeNode = dataFactory.namedNode(typeIri);\n const literalValues = literals[typeIri];\n literalValues.forEach((value) => {\n const literalNode = dataFactory.literal(value, typeNode);\n quads.push(dataFactory.quad(subjectNode, predicateNode, literalNode, graphNode));\n });\n });\n const locales = Object.keys(langStrings);\n locales.forEach((locale) => {\n const localeValues = langStrings[locale];\n localeValues.forEach((value) => {\n const langStringNode = dataFactory.literal(value, locale);\n quads.push(dataFactory.quad(subjectNode, predicateNode, langStringNode, graphNode));\n });\n });\n namedNodes.forEach((namedNodeIri) => {\n const node = dataFactory.namedNode(namedNodeIri);\n quads.push(dataFactory.quad(subjectNode, predicateNode, node, graphNode));\n });\n blankNodes.forEach((blankNodeIdOrPredicates) => {\n if (isBlankNodeId(blankNodeIdOrPredicates)) {\n const blankNode = dataFactory.blankNode(getBlankNodeValue(blankNodeIdOrPredicates));\n quads.push(dataFactory.quad(subjectNode, predicateNode, blankNode, graphNode));\n }\n else {\n const node = dataFactory.blankNode();\n const blankNodeObjectQuad = dataFactory.quad(subjectNode, predicateNode, node, graphNode);\n const blankNodeSubjectQuads = subjectToRdfJsQuads(blankNodeIdOrPredicates, node, graphNode);\n quads.push(blankNodeObjectQuad);\n quads.push(...blankNodeSubjectQuads);\n }\n });\n });\n return quads;\n}\n/**\n * A recursive function that finds all Blank Nodes in an array of Quads that create a cycle in the graph.\n *\n * This function will traverse the graph starting from `currentNode`, keeping\n * track of all the Blank Nodes it encounters twice while doing so, and\n * returning those.\n */\nfunction getCycleBlankNodes(currentNode, quads, traversedBlankNodes = []) {\n // If we've encountered `currentNode` before, all the Blank Nodes we've\n // encountered so far are part of a cycle. Return those.\n if (traversedBlankNodes.find((traversedBlankNode) => traversedBlankNode.equals(currentNode)) !== undefined) {\n return traversedBlankNodes;\n }\n // Find all Blank Nodes that are connected to `currentNode`:\n const blankNodeObjects = quads\n .filter((quad) => quad.subject.equals(currentNode) && isBlankNode(quad.object))\n .map((quad) => quad.object);\n // If no Blank Nodes are connected to `currentNode`, and `currentNode` is not\n // part of a cycle, we're done; the currently traversed Nodes do not form a\n // cycle:\n if (blankNodeObjects.length === 0) {\n return [];\n }\n // Store that we've traversed `currentNode`, then move on to all the Blank\n // Nodes connected to it, which will then take up the role of `currentNode`:\n const nextTraversedNodes = [...traversedBlankNodes, currentNode];\n const cycleBlankNodeArrays = blankNodeObjects.map((nextNode) => getCycleBlankNodes(nextNode, quads, nextTraversedNodes));\n // Collect all the cycle Blank Nodes found in those traverals,\n // then return them:\n const allCycleBlankNodes = [];\n for (const cycleBlankNodes of cycleBlankNodeArrays) {\n allCycleBlankNodes.push(...cycleBlankNodes);\n }\n return allCycleBlankNodes;\n}\nfunction isBlankNode(term) {\n return term.termType === \"BlankNode\";\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note} This function is still experimental and subject to change, even\n * in a non-major release.\n * ```\n * This returns a parser that transforms a JSON-LD string into a set of RDFJS quads.\n *\n * @returns A Parser object.\n * @since 1.15.0\n */\nconst getTurtleParser$1 = () => {\n const onQuadCallbacks = [];\n const onCompleteCallbacks = [];\n const onErrorCallbacks = [];\n return {\n onQuad: (callback) => {\n onQuadCallbacks.push(callback);\n },\n onError: (callback) => {\n onErrorCallbacks.push(callback);\n },\n onComplete: (callback) => {\n onCompleteCallbacks.push(callback);\n },\n parse: async (source, resourceInfo) => {\n const parser = await getParser(getSourceUrl(resourceInfo));\n parser.parse(source, (error, quad) => {\n if (error) {\n onErrorCallbacks.forEach((callback) => callback(error));\n }\n else if (quad) {\n onQuadCallbacks.forEach((callback) => callback(quad));\n }\n else {\n onCompleteCallbacks.forEach((callback) => callback());\n }\n });\n },\n };\n};\nasync function getParser(baseIri) {\n return new n3.Parser({ format: \"text/turtle\", baseIRI: baseIri });\n}\n/**\n * @param quads Triples that should be serialised to Turtle\n * @internal Utility method for internal use; not part of the public API.\n */\nasync function triplesToTurtle(quads, options) {\n const format = \"text/turtle\";\n const writer = new n3.Writer({ format, prefixes: options === null || options === void 0 ? void 0 : options.prefixes });\n // Remove any potentially lingering references to Named Graphs in Quads;\n // they'll be determined by the URL the Turtle will be sent to:\n const triples = quads.map((quad) => DataFactory.quad(quad.subject, quad.predicate, quad.object, undefined));\n writer.addQuads(triples);\n const writePromise = new Promise((resolve, reject) => {\n writer.end((error, result) => {\n /* istanbul ignore if [n3.js doesn't actually pass an error nor a result, apparently: https://github.com/rdfjs/N3.js/blob/62682e48c02d8965b4d728cb5f2cbec6b5d1b1b8/src/N3Writer.js#L290] */\n if (error) {\n reject(error);\n }\n else {\n resolve(result);\n }\n });\n });\n const rawTurtle = await writePromise;\n return rawTurtle;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst prefixes = {\n acl: \"http://www.w3.org/ns/auth/acl#\",\n acp: \"http://www.w3.org/ns/solid/acp#\",\n cc: \"http://creativecommons.org/ns#\",\n cert: \"http://www.w3.org/ns/auth/cert#\",\n csvw: \"http://www.w3.org/ns/csvw#\",\n current: \"#\",\n dc: \"http://purl.org/dc/terms/\",\n dcam: \"http://purl.org/dc/dcam/\",\n dcat: \"http://www.w3.org/ns/dcat#\",\n dctype: \"http://purl.org/dc/dcmitype/\",\n foaf: \"http://xmlns.com/foaf/0.1/\",\n ldp: \"http://www.w3.org/ns/ldp#\",\n owl: \"http://www.w3.org/2002/07/owl#\",\n posixstat: \"http://www.w3.org/ns/posix/stat#\",\n rdf: \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\",\n rdfs: \"http://www.w3.org/2000/01/rdf-schema#\",\n schema: \"https://schema.org/\",\n shacl: \"http://www.w3.org/ns/shacl#\",\n skos: \"http://www.w3.org/2004/02/skos/core#\",\n skosxl: \"http://www.w3.org/2008/05/skos-xl#\",\n solid: \"http://www.w3.org/ns/solid/terms#\",\n swapdoc: \"http://www.w3.org/2000/10/swap/pim/doc#\",\n ui: \"http://www.w3.org/ns/ui#\",\n vann: \"http://purl.org/vocab/vann/\",\n vcard: \"http://www.w3.org/2006/vcard/ns#\",\n ws: \"http://www.w3.org/ns/pim/space#\",\n xsd: \"http://www.w3.org/2001/XMLSchema#\",\n};\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst rdfJsDataset = rdfJsDatasetModule.dataset;\n/**\n * Convert an RDF/JS Dataset into a [[SolidDataset]]\n *\n * Parse an RDF/JS\n * {@link https://rdf.js.org/dataset-spec/#datasetcore-interface DatasetCore},\n * into a [[SolidDataset]]. Note that, when saving the returned SolidDataset to\n * a Solid Pod, only Quads in the Default Graph will be stored.\n *\n * @param rdfJsDataset The source RDF/JS Dataset.\n * @returns A [[SolidDataset]] containing the same data as the given RDF/JS Dataset.\n * @since 1.9.0\n */\nfunction fromRdfJsDataset(rdfJsDataset) {\n const dataset = {\n graphs: { default: {} },\n type: \"Dataset\",\n };\n const quads = Array.from(rdfJsDataset);\n const chainBlankNodes = getChainBlankNodes(quads);\n // Quads with chain Blank Nodes as their Subject will be parsed when those\n // Blank Nodes are referred to in an Object. See `addRdfJsQuadToObjects`.\n const quadsWithoutChainBlankNodeSubjects = quads.filter((quad) => chainBlankNodes.every((chainBlankNode) => !chainBlankNode.equals(quad.subject)));\n return quadsWithoutChainBlankNodeSubjects.reduce((datasetAcc, quad) => addRdfJsQuadToDataset(datasetAcc, quad, {\n otherQuads: quads,\n chainBlankNodes,\n }), dataset);\n}\n/**\n * Convert a [[SolidDataset]] into an RDF/JS Dataset\n *\n * Export a [[SolidDataset]] into an RDF/JS\n * {@link https://rdf.js.org/dataset-spec/#datasetcore-interface DatasetCore}.\n *\n * @param set A [[SolidDataset]] to export into an RDF/JS Dataset.\n * @param options Optional parameter that allows you to pass in your own RDF/JS DataFactory or DatasetCoreFactory.\n * @returns An RDF/JS Dataset containing the data from the given SolidDataset.\n * @since 1.9.0\n */\nfunction toRdfJsDataset(set, options = {}) {\n var _a, _b;\n const datasetFactory = (_b = (_a = options.datasetFactory) === null || _a === void 0 ? void 0 : _a.dataset) !== null && _b !== void 0 ? _b : rdfJsDataset;\n return datasetFactory(toRdfJsQuads(set, options));\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * A function to serialise a Solid Dataset as Turtle\n *\n * @param dataset The Dataset to serialize as Turtle\n * @param options.prefixes The Prefixes to use for Turtle serialisation (defaulting to a set of well known prefixes)\n * @param options.thing Restricts serialisation to the part of a dataset related to the thing\n * @returns RDF serialised as Turtle\n * @since 1.20.0\n */\nasync function solidDatasetAsTurtle$1(dataset, options) {\n const { prefixes: prefixes$1 = prefixes, thing } = { ...options };\n const writer = new n3.Writer({ format: \"application/turtle\", prefixes: prefixes$1 });\n const subject = thing ? new n3.NamedNode(thing) : undefined;\n // If the subject is undefined, all the triples match.\n for (const quad of toRdfJsDataset(dataset).match(subject)) {\n writer.addQuad(quad);\n }\n return new Promise((resolve, reject) => {\n writer.end((error, result) => {\n /* istanbul ignore next */\n if (error) {\n reject(error);\n }\n else {\n resolve(result);\n }\n });\n });\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nvar formats = /*#__PURE__*/Object.freeze({\n __proto__: null,\n getJsonLdParser: getJsonLdParser$1,\n getTurtleParser: getTurtleParser$1,\n solidDatasetAsTurtle: solidDatasetAsTurtle$1\n});\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst defaultGetFileOptions = {\n fetch,\n};\nconst RESERVED_HEADERS = [\"Slug\", \"If-None-Match\", \"Content-Type\"];\n/**\n * Some of the headers must be set by the library, rather than directly.\n */\nfunction containsReserved(header) {\n return RESERVED_HEADERS.some((reserved) => header[reserved] !== undefined);\n}\n/**\n * Retrieves a file from a URL and returns the file as a blob.\n *\n * For example:\n *\n * ```\n * const fileBlob = await getFile(\"https://pod.example.com/some/file\", { fetch: fetch });\n * ```\n *\n * For additional examples, see\n * [Read/Write Files](https://docs.inrupt.com/developer-tools/javascript/client-libraries/tutorial/read-write-files/#retrieve-a-file).\n *\n * @param fileUrl The URL of the file to return\n * @param options Fetching options: a custom fetcher and/or headers.\n * @returns The file as a blob.\n */\nasync function getFile(fileUrl, options = defaultGetFileOptions) {\n const config = {\n ...defaultGetFileOptions,\n ...options,\n };\n const url = internal_toIriString(fileUrl);\n const response = await config.fetch(url, config.init);\n if (internal_isUnsuccessfulResponse(response)) {\n throw new FetchError(`Fetching the File failed: [${response.status}] [${response.statusText}] ${await response.text()}.`, response);\n }\n const resourceInfo = internal_parseResourceInfo(response);\n const data = await response.blob();\n const fileWithResourceInfo = Object.assign(data, {\n internal_resourceInfo: resourceInfo,\n });\n return fileWithResourceInfo;\n}\n/**\n * Deletes a file at a given URL.\n *\n * For example:\n *\n * ```\n * await deleteFile( \"https://pod.example.com/some/file\", { fetch: fetch });\n * ```\n *\n * For additional examples, see\n * [Read/Write Files](https://docs.inrupt.com/developer-tools/javascript/client-libraries/tutorial/read-write-files/#delete-a-file).\n *\n * @param file The URL of the file to delete or the file itself (if it has ResourceInfo).\n */\nasync function deleteFile(file, options = defaultGetFileOptions) {\n const config = {\n ...defaultGetFileOptions,\n ...options,\n };\n const url = hasResourceInfo(file)\n ? internal_toIriString(getSourceIri(file))\n : internal_toIriString(file);\n const response = await config.fetch(url, {\n ...config.init,\n method: \"DELETE\",\n });\n if (internal_isUnsuccessfulResponse(response)) {\n throw new FetchError(`Deleting the file at [${url}] failed: [${response.status}] [${response.statusText}] ${await response.text()}.`, response);\n }\n}\nasync function saveFileInContainer(folderUrl, file, options = defaultGetFileOptions) {\n const folderUrlString = internal_toIriString(folderUrl);\n const response = await writeFile(folderUrlString, file, \"POST\", options);\n if (internal_isUnsuccessfulResponse(response)) {\n throw new FetchError(`Saving the file in [${folderUrl}] failed: [${response.status}] [${response.statusText}] ${await response.text()}.`, response);\n }\n const locationHeader = response.headers.get(\"Location\");\n if (locationHeader === null) {\n throw new Error(\"Could not determine the location of the newly saved file.\");\n }\n const fileIri = new URL(locationHeader, new URL(folderUrlString).origin).href;\n const blobClone = internal_cloneResource(file);\n const resourceInfo = {\n internal_resourceInfo: {\n isRawData: true,\n sourceIri: fileIri,\n contentType: getContentType(file, options.contentType),\n },\n };\n return Object.assign(blobClone, resourceInfo);\n}\nasync function overwriteFile(fileUrl, file, options = defaultGetFileOptions) {\n const fileUrlString = internal_toIriString(fileUrl);\n const response = await writeFile(fileUrlString, file, \"PUT\", options);\n if (internal_isUnsuccessfulResponse(response)) {\n throw new FetchError(`Overwriting the file at [${fileUrlString}] failed: [${response.status}] [${response.statusText}] ${await response.text()}.`, response);\n }\n const blobClone = internal_cloneResource(file);\n const resourceInfo = internal_parseResourceInfo(response);\n resourceInfo.sourceIri = fileUrlString;\n resourceInfo.isRawData = true;\n return Object.assign(blobClone, { internal_resourceInfo: resourceInfo });\n}\nfunction isHeadersArray(headers) {\n return Array.isArray(headers);\n}\n/**\n * The return type of this function is misleading: it should ONLY be used to check\n * whether an object has a forEach method that returns pairs.\n *\n * @param headers A headers object that might have a forEach\n */\nfunction hasHeadersObjectForEach(headers) {\n return typeof headers.forEach === \"function\";\n}\n/**\n * @hidden\n * This function feels unnecessarily complicated, but is required in order to\n * have Headers according to type definitions in both Node and browser environments.\n * This might require a fix upstream to be cleaned up.\n *\n * @param headersToFlatten A structure containing headers potentially in several formats\n */\nfunction flattenHeaders(headersToFlatten) {\n if (typeof headersToFlatten === \"undefined\") {\n return {};\n }\n let flatHeaders = {};\n if (isHeadersArray(headersToFlatten)) {\n headersToFlatten.forEach(([key, value]) => {\n flatHeaders[key] = value;\n });\n // Note that the following line must be a elsif, because string[][] has a forEach,\n // but it returns string[] instead of \n }\n else if (hasHeadersObjectForEach(headersToFlatten)) {\n headersToFlatten.forEach((value, key) => {\n flatHeaders[key] = value;\n });\n }\n else {\n // If the headers are already a Record,\n // they can directly be returned.\n flatHeaders = headersToFlatten;\n }\n return flatHeaders;\n}\nasync function writeFile(targetUrl, file, method, options) {\n var _a, _b;\n const config = {\n ...defaultGetFileOptions,\n ...options,\n };\n const headers = flattenHeaders((_b = (_a = config.init) === null || _a === void 0 ? void 0 : _a.headers) !== null && _b !== void 0 ? _b : {});\n if (containsReserved(headers)) {\n throw new Error(`No reserved header (${RESERVED_HEADERS.join(\", \")}) should be set in the optional RequestInit.`);\n }\n // If a slug is in the parameters, set the request headers accordingly\n if (config.slug !== undefined) {\n headers.Slug = config.slug;\n }\n headers[\"Content-Type\"] = getContentType(file, options.contentType);\n const targetUrlString = internal_toIriString(targetUrl);\n return config.fetch(targetUrlString, {\n ...config.init,\n headers,\n method,\n body: file,\n });\n}\nfunction getContentType(file, contentTypeOverride) {\n if (typeof contentTypeOverride === \"string\") {\n return contentTypeOverride;\n }\n const fileType = typeof file === \"object\" &&\n file !== null &&\n \"type\" in file &&\n typeof file.type === \"string\" &&\n file.type.length > 0\n ? file.type\n : undefined;\n return fileType !== null && fileType !== void 0 ? fileType : \"application/octet-stream\";\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden For internal use only. */\nfunction internal_getReadableValue(value) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n if (isNamedNode(value)) {\n return `<${value.value}> (URL)`;\n }\n if (isLiteral(value)) {\n /* istanbul ignore if: thingAsMarkdown always instantiates a NamedNode, so we can't hit this code path in tests. */\n if (!isNamedNode(value.datatype)) {\n return `[${value.value}] (RDF/JS Literal of unknown type)`;\n }\n let val;\n switch (value.datatype.value) {\n case xmlSchemaTypes.boolean:\n val =\n (_b = (_a = deserializeBoolean(value.value)) === null || _a === void 0 ? void 0 : _a.valueOf()) !== null && _b !== void 0 ? _b : `Invalid data: \\`${value.value}\\``;\n return `${val} (boolean)`;\n case xmlSchemaTypes.dateTime:\n val =\n (_d = (_c = deserializeDatetime(value.value)) === null || _c === void 0 ? void 0 : _c.toUTCString()) !== null && _d !== void 0 ? _d : `Invalid data: \\`${value.value}\\``;\n return `${val} (datetime)`;\n case xmlSchemaTypes.decimal:\n val =\n (_f = (_e = deserializeDecimal(value.value)) === null || _e === void 0 ? void 0 : _e.toString()) !== null && _f !== void 0 ? _f : `Invalid data: \\`${value.value}\\``;\n return `${val} (decimal)`;\n case xmlSchemaTypes.integer:\n val =\n (_h = (_g = deserializeInteger(value.value)) === null || _g === void 0 ? void 0 : _g.toString()) !== null && _h !== void 0 ? _h : `Invalid data: \\`${value.value}\\``;\n return `${val} (integer)`;\n case xmlSchemaTypes.langString:\n return `\"${value.value}\" (${value.language} string)`;\n case xmlSchemaTypes.string:\n return `\"${value.value}\" (string)`;\n default:\n return `[${value.value}] (RDF/JS Literal of type: \\`${value.datatype.value}\\`)`;\n }\n }\n /* istanbul ignore else: thingAsMarkdown doesn't generate other Nodes, so we can't hit this path in tests. */\n if (value.termType === \"BlankNode\") {\n return `[${value.value}] (RDF/JS BlankNode)`;\n }\n /* istanbul ignore next: thingAsMarkdown doesn't generate Quad Nodes, so we can't hit this path in tests. */\n if (value.termType === \"Quad\") {\n return `??? (nested RDF* Quad)`;\n }\n /* istanbul ignore else: The if statements are exhaustive; if not, TypeScript will complain. */\n /* istanbul ignore next: thingAsMarkdown doesn't generate Variable Nodes, so we can't hit this path in tests. */\n if (value.termType === \"Variable\") {\n return `?${value.value} (RDF/JS Variable)`;\n }\n /* istanbul ignore next: The if statements are exhaustive; if not, TypeScript will complain. */\n return value;\n}\n/**\n * @hidden\n */\nfunction internal_throwIfNotThing(thing) {\n if (!isThing(thing)) {\n throw new ThingExpectedError(thing);\n }\n}\n/**\n * @hidden\n * @param solidDataset\n */\nfunction internal_addAdditionsToChangeLog(solidDataset, additions) {\n const changeLog = hasChangelog(solidDataset)\n ? solidDataset.internal_changeLog\n : /* istanbul ignore next: This function always gets called after addDeletionsToChangeLog, so the ChangeLog always already exists in tests: */\n { additions: [], deletions: [] };\n const [newAdditions, newDeletions] = additions\n .filter((addition) => !containsBlankNode(addition))\n .reduce(([additionsAcc, deletionsAcc], addition) => {\n const existingDeletion = deletionsAcc.find((deletion) => deletion.equals(addition));\n if (typeof existingDeletion !== \"undefined\") {\n return [\n additionsAcc,\n deletionsAcc.filter((deletion) => !deletion.equals(addition)),\n ];\n }\n return [additionsAcc.concat(addition), deletionsAcc];\n }, [changeLog.additions, changeLog.deletions]);\n return freeze({\n ...solidDataset,\n internal_changeLog: {\n additions: newAdditions,\n deletions: newDeletions,\n },\n });\n}\n/**\n * @hidden\n * @param solidDataset\n */\nfunction internal_addDeletionsToChangeLog(solidDataset, deletions) {\n const changeLog = hasChangelog(solidDataset)\n ? solidDataset.internal_changeLog\n : { additions: [], deletions: [] };\n const [newAdditions, newDeletions] = deletions\n .filter((deletion) => !containsBlankNode(deletion))\n .reduce(([additionsAcc, deletionsAcc], deletion) => {\n const existingAddition = additionsAcc.find((addition) => addition.equals(deletion));\n if (typeof existingAddition !== \"undefined\") {\n return [\n additionsAcc.filter((addition) => !addition.equals(deletion)),\n deletionsAcc,\n ];\n }\n return [additionsAcc, deletionsAcc.concat(deletion)];\n }, [changeLog.additions, changeLog.deletions]);\n return freeze({\n ...solidDataset,\n internal_changeLog: {\n additions: newAdditions,\n deletions: newDeletions,\n },\n });\n}\n/**\n * Enforces the presence of a Changelog for a given dataset. If a changelog is\n * already present, it is unchanged. Otherwise, an empty changelog is created.\n * @hidden\n * @param solidDataset\n */\nfunction internal_withChangeLog(solidDataset) {\n const newSolidDataset = hasChangelog(solidDataset)\n ? solidDataset\n : freeze({\n ...solidDataset,\n internal_changeLog: { additions: [], deletions: [] },\n });\n return newSolidDataset;\n}\n/**\n * We don't currently support reading and writing Blank Nodes, so this function can be used to skip those Quads.\n *\n * This is needed because we cannot reconcile Blank Nodes in additions and\n * deletions. Down the road, we should do a diff before saving a SolidDataset\n * against a saved copy of the originally-fetched one, based on our own data\n * structures, which should make it easier to reconcile.\n */\nfunction containsBlankNode(quad) {\n return (quad.subject.termType === \"BlankNode\" ||\n quad.object.termType === \"BlankNode\");\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Returns the URLs of all Properties that the given [[Thing ]]has values for.b\n *\n * @param thing The [[Thing]] of which to get that Property URLs that have a value.\n * @returns The URLs of the Properties for which values are defined for the given Thing.\n * @hidden This is an advanced API that should not be needed for most Solid use cases. If you do find yourself needing this, please file a feature request sharing your use case.\n */\nfunction getPropertyAll(thing) {\n return Object.keys(thing.predicates).filter((predicate) => getTerm(thing, predicate) !== null);\n}\n/**\n * Returns the URL value of the specified Property from a [[Thing]].\n * If the Property is not present or its value is not of type URL, returns null.\n * If the Property has multiple URL values, returns one of its URL values.\n *\n * @param thing The [[Thing]] to read a URL value from.\n * @param property The Property whose URL value to return.\n * @returns A URL value for the given Property if present, or null if the Property is not present or the value is not of type URL.\n */\nfunction getUrl(thing, property) {\n var _a, _b, _c;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateUrl = internal_toIriString(property);\n const firstUrl = (_c = (_b = (_a = thing.predicates[predicateUrl]) === null || _a === void 0 ? void 0 : _a.namedNodes) === null || _b === void 0 ? void 0 : _b[0]) !== null && _c !== void 0 ? _c : null;\n if (firstUrl === null) {\n return null;\n }\n return isLocalNodeIri(firstUrl) ? `#${getLocalNodeName(firstUrl)}` : firstUrl;\n}\n/** @hidden Alias of [[getUrl]] for those who prefer IRI terminology. */\nconst getIri = getUrl;\n/**\n * Returns the URL values of the specified Property from a [[Thing]].\n * If the Property is not present, returns an empty array.\n * If the Property's value is not of type URL, omits that value in the array.\n *\n * @param thing The [[Thing]] to read the URL values from.\n * @param property The Property whose URL values to return.\n * @returns An array of URL values for the given Property.\n */\nfunction getUrlAll(thing, property) {\n var _a, _b, _c;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateUrl = internal_toIriString(property);\n return ((_c = (_b = (_a = thing.predicates[predicateUrl]) === null || _a === void 0 ? void 0 : _a.namedNodes) === null || _b === void 0 ? void 0 : _b.map((iri) => isLocalNodeIri(iri) ? `#${getLocalNodeName(iri)}` : iri)) !== null && _c !== void 0 ? _c : []);\n}\n/** @hidden Alias of [[getUrlAll]] for those who prefer IRI terminology. */\nconst getIriAll = getUrlAll;\n/**\n * Returns the boolean value of the specified Property from a [[Thing]].\n * If the Property is not present or its value is not of type boolean, returns null.\n * If the Property has multiple boolean values, returns one of its values.\n *\n * @param thing The [[Thing]] to read a boolean value from.\n * @param property The Property whose boolean value to return.\n * @returns A boolean value for the given Property if present, or null if the Property is not present or the value is not of type boolean.\n */\nfunction getBoolean(thing, property) {\n internal_throwIfNotThing(thing);\n const literalString = getLiteralOfType(thing, property, xmlSchemaTypes.boolean);\n if (literalString === null) {\n return null;\n }\n return deserializeBoolean(literalString);\n}\n/**\n * Returns the boolean values of the specified Property from a [[Thing]].\n * If the Property is not present, returns an empty array.\n * If the Property's value is not of type boolean, omits that value in the array.\n *\n * @param thing The [[Thing]] to read the boolean values from.\n * @param property The Property whose boolean values to return.\n * @returns An array of boolean values for the given Property.\n */\nfunction getBooleanAll(thing, property) {\n internal_throwIfNotThing(thing);\n const literalStrings = getLiteralAllOfType(thing, property, xmlSchemaTypes.boolean);\n return literalStrings\n .map(deserializeBoolean)\n .filter((possibleBoolean) => possibleBoolean !== null);\n}\n/**\n * Returns the datetime value of the specified Property from a [[Thing]].\n * If the Property is not present or its value is not of type datetime, returns null.\n * If the Property has multiple datetime values, returns one of its values.\n *\n * @param thing The [[Thing]] to read a datetime value from.\n * @param property The Property whose datetime value to return.\n * @returns A datetime value for the given Property if present, or null if the Property is not present or the value is not of type datetime.\n */\nfunction getDatetime(thing, property) {\n internal_throwIfNotThing(thing);\n const literalString = getLiteralOfType(thing, property, xmlSchemaTypes.dateTime);\n if (literalString === null) {\n return null;\n }\n return deserializeDatetime(literalString);\n}\n/**\n * Returns the datetime values of the specified Property from a [[Thing]].\n * If the Property is not present, returns an empty array.\n * If the Property's value is not of type datetime, omits that value in the array.\n *\n * @param thing The [[Thing]] to read the datetime values from.\n * @param property The Property whose datetime values to return.\n * @returns An array of datetime values for the given Property.\n */\nfunction getDatetimeAll(thing, property) {\n internal_throwIfNotThing(thing);\n const literalStrings = getLiteralAllOfType(thing, property, xmlSchemaTypes.dateTime);\n return literalStrings\n .map(deserializeDatetime)\n .filter((potentialDatetime) => potentialDatetime !== null);\n}\n/**\n * Returns the date value of the specified Property from a [[Thing]].\n * If the Property is not present or its value is not of type date, returns null.\n * If the Property has multiple date values, returns one of its values.\n *\n * @param thing The [[Thing]] to read a date value from.\n * @param property The Property whose date value to return.\n * @returns A date value for the given Property if present, or null if the Property is not present or the value is not of type date.\n * @since 1.10.0\n */\nfunction getDate(thing, property) {\n internal_throwIfNotThing(thing);\n const literalString = getLiteralOfType(thing, property, xmlSchemaTypes.date);\n if (literalString === null) {\n return null;\n }\n return deserializeDate(literalString);\n}\n/**\n * Returns the date values of the specified Property from a [[Thing]].\n * If the Property is not present, returns an empty array.\n * If the Property's value is not of type date, omits that value in the array.\n *\n * @param thing The [[Thing]] to read the date values from.\n * @param property The Property whose date values to return.\n * @returns An array of date values for the given Property.\n * @since 1.10.0\n */\nfunction getDateAll(thing, property) {\n internal_throwIfNotThing(thing);\n const literalStrings = getLiteralAllOfType(thing, property, xmlSchemaTypes.date);\n return literalStrings\n .map(deserializeDate)\n .filter((potentialDate) => potentialDate !== null);\n}\n/**\n * Returns the time value of the specified Property from a [[Thing]].\n * If the Property is not present or its value is not of type time, returns null.\n * If the Property has multiple time values, returns one of its values.\n *\n * @param thing The [[Thing]] to read a time value from.\n * @param property The Property whose time value to return.\n * @returns A time value for the given Property if present, or null if the Property is not present or the value is not of type time.\n * @since 1.10.0\n */\nfunction getTime(thing, property) {\n internal_throwIfNotThing(thing);\n const literalString = getLiteralOfType(thing, property, xmlSchemaTypes.time);\n if (literalString === null) {\n return null;\n }\n return deserializeTime(literalString);\n}\n/**\n * Returns the time values of the specified Property from a [[Thing]].\n * If the Property is not present, returns an empty array.\n * If the Property's value is not of type time, omits that value in the array.\n *\n * @param thing The [[Thing]] to read the time values from.\n * @param property The Property whose time values to return.\n * @returns An array of time values for the given Property.\n * @since 1.10.0\n */\nfunction getTimeAll(thing, property) {\n internal_throwIfNotThing(thing);\n const literalStrings = getLiteralAllOfType(thing, property, xmlSchemaTypes.time);\n return literalStrings\n .map(deserializeTime)\n .filter((potentialTime) => potentialTime !== null);\n}\n/**\n * Returns the decimal value of the specified Property from a [[Thing]].\n * If the Property is not present or its value is not of type decimal, returns null.\n * If the Property has multiple decimal values, returns one of its values.\n *\n * @param thing The [[Thing]] to read a decimal value from.\n * @param property The Property whose decimal value to return.\n * @returns A decimal value for the given Property if present, or null if the Property is not present or the value is not of type decimal.\n */\nfunction getDecimal(thing, property) {\n internal_throwIfNotThing(thing);\n const literalString = getLiteralOfType(thing, property, xmlSchemaTypes.decimal);\n if (literalString === null) {\n return null;\n }\n return deserializeDecimal(literalString);\n}\n/**\n * Returns the decimal values of the specified Property from a [[Thing]].\n * If the Property is not present, returns an empty array.\n * If the Property's value is not of type decimal, omits that value in the array.\n *\n * @param thing The [[Thing]] to read the decimal values from.\n * @param property The Property whose decimal values to return.\n * @returns An array of decimal values for the given Property.\n */\nfunction getDecimalAll(thing, property) {\n internal_throwIfNotThing(thing);\n const literalStrings = getLiteralAllOfType(thing, property, xmlSchemaTypes.decimal);\n return literalStrings\n .map((literalString) => deserializeDecimal(literalString))\n .filter((potentialDecimal) => potentialDecimal !== null);\n}\n/**\n * Returns the integer value of the specified Property from a [[Thing]].\n * If the Property is not present or its value is not of type integer, returns null.\n * If the Property has multiple integer values, returns one of its values.\n *\n * @param thing The [[Thing]] to read an integer value from.\n * @param property The Property whose integer value to return.\n * @returns A integer value for the given Property if present, or null if the Property is not present or the value is not of type datetime.\n */\nfunction getInteger(thing, property) {\n internal_throwIfNotThing(thing);\n const literalString = getLiteralOfType(thing, property, xmlSchemaTypes.integer);\n if (literalString === null) {\n return null;\n }\n return deserializeInteger(literalString);\n}\n/**\n * Returns the integer values of the specified Property from a [[Thing]].\n * If the Property is not present, returns an empty array.\n * If the Property's value is not of type integer, omits that value in the array.\n *\n * @param thing The [[Thing]] to read the integer values from.\n * @param property The Property whose integer values to return.\n * @returns An array of integer values for the given Property.\n */\nfunction getIntegerAll(thing, property) {\n internal_throwIfNotThing(thing);\n const literalStrings = getLiteralAllOfType(thing, property, xmlSchemaTypes.integer);\n return literalStrings\n .map((literalString) => deserializeInteger(literalString))\n .filter((potentialInteger) => potentialInteger !== null);\n}\n/**\n * Returns the English (language tag \"en\") string value of the specified Property from a [[Thing]].\n * If the Property is not present as a string in English, returns null.\n * If the Property has multiple English string values, returns one of its values.\n *\n * @param thing The [[Thing]] to read a localised string value from.\n * @param property The Property whose localised string value to return.\n * @returns An English string value for the given Property if present, or null otherwise.\n * @since 1.13.0\n */\nfunction getStringEnglish(thing, property) {\n return getStringWithLocale(thing, property, \"en\");\n}\n/**\n * Returns the localized string value of the specified Property from a [[Thing]].\n * If the Property is not present as a string in the specified locale, returns null.\n * If the Property has multiple string values for the specified locale, returns one of its values.\n *\n * @param thing The [[Thing]] to read a localised string value from.\n * @param property The Property whose localised string value to return.\n * @param locale The desired locale for the string value.\n * @returns A localised string value for the given Property if present in the specified `locale`, or null otherwise.\n */\nfunction getStringWithLocale(thing, property, locale) {\n var _a, _b;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n const langStrings = (_b = (_a = thing.predicates[predicateIri]) === null || _a === void 0 ? void 0 : _a.langStrings) !== null && _b !== void 0 ? _b : {};\n const existingLocales = Object.keys(langStrings);\n const matchingLocale = existingLocales.find((existingLocale) => existingLocale.toLowerCase() === locale.toLowerCase() &&\n Array.isArray(langStrings[existingLocale]) &&\n langStrings[existingLocale].length > 0);\n return typeof matchingLocale === \"string\"\n ? langStrings[matchingLocale][0]\n : null;\n}\n/**\n * Returns the English (language tag \"en\") string values of the specified Property from a [[Thing]].\n * If the Property is not present, returns an empty array.\n * If the Property's value is not an English string, omits that value in the array.\n *\n * @param thing The [[Thing]] to read a localised string value from.\n * @param property The Property whose localised string value to return.\n * @returns An array of English string values for the given Property.\n */\nfunction getStringEnglishAll(thing, property) {\n return getStringWithLocaleAll(thing, property, \"en\");\n}\n/**\n * Returns the localized string values of the specified Property from a [[Thing]].\n * If the Property is not present, returns an empty array.\n * If the Property's value is not a string of the specified locale, omits that value in the array.\n *\n * @param thing The [[Thing]] to read the localised string values from.\n * @param property The Property whose localised string values to return.\n * @param locale The desired locale for the string values.\n * @returns An array of localised string values for the given Property.\n */\nfunction getStringWithLocaleAll(thing, property, locale) {\n var _a, _b;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n const langStrings = (_b = (_a = thing.predicates[predicateIri]) === null || _a === void 0 ? void 0 : _a.langStrings) !== null && _b !== void 0 ? _b : {};\n const existingLocales = Object.keys(langStrings);\n const matchingLocale = existingLocales.find((existingLocale) => existingLocale.toLowerCase() === locale.toLowerCase() &&\n Array.isArray(langStrings[existingLocale]) &&\n langStrings[existingLocale].length > 0);\n return typeof matchingLocale === \"string\"\n ? [...langStrings[matchingLocale]]\n : [];\n}\n/**\n * Returns all localized string values mapped by the locales for the specified property from the\n * specified [[Thing]] (explicitly filters out non-language string literals).\n *\n * @param thing The [[Thing]] to read the localised string values from.\n * @param property The Property whose localised string values to return.\n * @returns A Map of objects, keyed on locale with the value an array of string values (for that locale).\n */\nfunction getStringByLocaleAll(thing, property) {\n var _a, _b;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n const stringsByLocale = (_b = (_a = thing.predicates[predicateIri]) === null || _a === void 0 ? void 0 : _a.langStrings) !== null && _b !== void 0 ? _b : {};\n return new Map(Object.entries(stringsByLocale).map(([locale, values]) => [\n locale,\n [...values],\n ]));\n}\n/**\n * Returns the string value of the specified Property from a [[Thing]].\n * If the Property is not present or its value is not of type string, returns null.\n * If the Property has multiple string values, returns one of its values.\n *\n * @param thing The [[Thing]] to read a string value from.\n * @param property The Property whose string value to return.\n * @returns A string value for the given Property if present, or null if the Property is not present or the value is not of type string.\n */\nfunction getStringNoLocale(thing, property) {\n internal_throwIfNotThing(thing);\n const literalString = getLiteralOfType(thing, property, xmlSchemaTypes.string);\n return literalString;\n}\n/**\n * Returns the string values of the specified Property from a [[Thing]].\n * If the Property is not present, returns an empty array.\n * If the Property's value is not of type string, omits that value in the array.\n *\n * @param thing The [[Thing]] to read the string values from.\n * @param property The Property whose string values to return.\n * @returns An array of string values for the given Property.\n */\nfunction getStringNoLocaleAll(thing, property) {\n internal_throwIfNotThing(thing);\n const literalStrings = getLiteralAllOfType(thing, property, xmlSchemaTypes.string);\n return literalStrings;\n}\n/**\n * @param thing The [[Thing]] to read a NamedNode value from.\n * @param property The given Property for which you want the NamedNode value.\n * @returns A NamedNode value for the given Property, if present, or null otherwise.\n * @ignore This should not be needed due to the other get*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @see https://rdf.js.org/data-model-spec/#namednode-interface\n */\nfunction getNamedNode(thing, property) {\n const iriString = getIri(thing, property);\n if (iriString === null) {\n return null;\n }\n return DataFactory.namedNode(iriString);\n}\n/**\n * @param thing The [[Thing]] to read the NamedNode values from.\n * @param property The given Property for which you want the NamedNode values.\n * @returns The NamedNode values for the given Property.\n * @ignore This should not be needed due to the other get*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @see https://rdf.js.org/data-model-spec/#namednode-interface\n */\nfunction getNamedNodeAll(thing, property) {\n const iriStrings = getIriAll(thing, property);\n return iriStrings.map((iriString) => DataFactory.namedNode(iriString));\n}\n/**\n * @param thing The [[Thing]] to read a Literal value from.\n * @param property The given Property for which you want the Literal value.\n * @returns A Literal value for the given Property, if present, or null otherwise.\n * @ignore This should not be needed due to the other get*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @see https://rdf.js.org/data-model-spec/#literal-interface\n */\nfunction getLiteral(thing, property) {\n var _a, _b, _c, _d;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n const langStrings = (_b = (_a = thing.predicates[predicateIri]) === null || _a === void 0 ? void 0 : _a.langStrings) !== null && _b !== void 0 ? _b : {};\n const locales = Object.keys(langStrings);\n if (locales.length > 0) {\n const nonEmptyLocale = locales.find((locale) => Array.isArray(langStrings[locale]) && langStrings[locale].length > 0);\n if (typeof nonEmptyLocale === \"string\") {\n return DataFactory.literal(langStrings[nonEmptyLocale][0], nonEmptyLocale);\n }\n }\n const otherLiterals = (_d = (_c = thing.predicates[predicateIri]) === null || _c === void 0 ? void 0 : _c.literals) !== null && _d !== void 0 ? _d : {};\n const dataTypes = Object.keys(otherLiterals);\n if (dataTypes.length > 0) {\n const nonEmptyDataType = dataTypes.find((dataType) => Array.isArray(otherLiterals[dataType]) &&\n otherLiterals[dataType].length > 0);\n if (typeof nonEmptyDataType === \"string\") {\n return DataFactory.literal(otherLiterals[nonEmptyDataType][0], DataFactory.namedNode(nonEmptyDataType));\n }\n }\n return null;\n}\n/**\n * @param thing The [[Thing]] to read the Literal values from.\n * @param property The given Property for which you want the Literal values.\n * @returns The Literal values for the given Property.\n * @ignore This should not be needed due to the other get*All() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @see https://rdf.js.org/data-model-spec/#literal-interface\n */\nfunction getLiteralAll(thing, property) {\n var _a, _b, _c, _d;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n let literals = [];\n const langStrings = (_b = (_a = thing.predicates[predicateIri]) === null || _a === void 0 ? void 0 : _a.langStrings) !== null && _b !== void 0 ? _b : {};\n const locales = Object.keys(langStrings);\n for (const locale of locales) {\n const stringsInLocale = langStrings[locale];\n const localeLiterals = stringsInLocale.map((langString) => DataFactory.literal(langString, locale));\n literals = literals.concat(localeLiterals);\n }\n const otherLiterals = (_d = (_c = thing.predicates[predicateIri]) === null || _c === void 0 ? void 0 : _c.literals) !== null && _d !== void 0 ? _d : {};\n const dataTypes = Object.keys(otherLiterals);\n for (const dataType of dataTypes) {\n const values = otherLiterals[dataType];\n const typeNode = DataFactory.namedNode(dataType);\n const dataTypeLiterals = values.map((value) => DataFactory.literal(value, typeNode));\n literals = literals.concat(dataTypeLiterals);\n }\n return literals;\n}\n/**\n * @param thing The [[Thing]] to read a raw RDF/JS value from.\n * @param property The given Property for which you want the raw value.\n * @returns A Term for the given Property, if present, or null otherwise.\n * @ignore This should not be needed due to the other get*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @see https://rdf.js.org/data-model-spec/\n * @since 0.3.0\n */\nfunction getTerm(thing, property) {\n var _a, _b;\n internal_throwIfNotThing(thing);\n const namedNode = getNamedNode(thing, property);\n if (namedNode !== null) {\n return namedNode;\n }\n const literal = getLiteral(thing, property);\n if (literal !== null) {\n return literal;\n }\n const predicateIri = internal_toIriString(property);\n const blankNodes = (_b = (_a = thing.predicates[predicateIri]) === null || _a === void 0 ? void 0 : _a.blankNodes) !== null && _b !== void 0 ? _b : [];\n if (blankNodes.length > 0) {\n const blankNodeValue = isBlankNodeId(blankNodes[0])\n ? getBlankNodeValue(blankNodes[0])\n : undefined;\n return DataFactory.blankNode(blankNodeValue);\n }\n return null;\n}\n/**\n * @param thing The [[Thing]] to read the raw RDF/JS values from.\n * @param property The given Property for which you want the raw values.\n * @returns The Terms for the given Property.\n * @ignore This should not be needed due to the other get*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @see https://rdf.js.org/data-model-spec/\n * @since 0.3.0\n */\nfunction getTermAll(thing, property) {\n var _a, _b;\n internal_throwIfNotThing(thing);\n const namedNodes = getNamedNodeAll(thing, property);\n const literals = getLiteralAll(thing, property);\n const predicateIri = internal_toIriString(property);\n const blankNodeValues = (_b = (_a = thing.predicates[predicateIri]) === null || _a === void 0 ? void 0 : _a.blankNodes) !== null && _b !== void 0 ? _b : [];\n const blankNodes = blankNodeValues.map((rawBlankNode) => {\n const blankNodeName = isBlankNodeId(rawBlankNode)\n ? getBlankNodeValue(rawBlankNode)\n : undefined;\n return DataFactory.blankNode(blankNodeName);\n });\n const terms = namedNodes\n .concat(literals)\n .concat(blankNodes);\n return terms;\n}\n/**\n * @param thing The [Thing]] to read a Literal of the given type from.\n * @param property The given Property for which you want the Literal value.\n * @param literalType Set type of the Literal data.\n * @returns The stringified value for the given Property and type, if present, or null otherwise.\n */\nfunction getLiteralOfType(thing, property, literalType) {\n var _a, _b, _c, _d;\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n return (_d = (_c = (_b = (_a = thing.predicates[predicateIri]) === null || _a === void 0 ? void 0 : _a.literals) === null || _b === void 0 ? void 0 : _b[literalType]) === null || _c === void 0 ? void 0 : _c[0]) !== null && _d !== void 0 ? _d : null;\n}\n/**\n * @param thing The [Thing]] to read the Literals of the given type from.\n * @param property The given Property for which you want the Literal values.\n * @param literalType Set type of the Literal data.\n * @returns The stringified values for the given Property and type.\n */\nfunction getLiteralAllOfType(thing, property, literalType) {\n var _a, _b, _c;\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n const literalsOfType = (_c = (_b = (_a = thing.predicates[predicateIri]) === null || _a === void 0 ? void 0 : _a.literals) === null || _b === void 0 ? void 0 : _b[literalType]) !== null && _c !== void 0 ? _c : [];\n return [...literalsOfType];\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Extract Quads with a given Subject from a [[SolidDataset]] into a [[Thing]].\n *\n * @param solidDataset The [[SolidDataset]] to extract the [[Thing]] from.\n * @param thingUrl The URL of the desired [[Thing]].\n * @param options Not yet implemented.\n */\nfunction getThing(solidDataset, thingUrl, options = {}) {\n var _a;\n if (!internal_isValidUrl(thingUrl)) {\n throw new ValidThingUrlExpectedError(thingUrl);\n }\n const graph = typeof options.scope !== \"undefined\"\n ? internal_toIriString(options.scope)\n : \"default\";\n const thingsByIri = (_a = solidDataset.graphs[graph]) !== null && _a !== void 0 ? _a : {};\n const thingIri = internal_toIriString(thingUrl);\n const resolvedThingIri = isLocalNodeIri(thingIri) && hasServerResourceInfo(solidDataset)\n ? resolveLocalIri(getLocalNodeName(thingIri), getSourceUrl(solidDataset))\n : thingIri;\n const thing = thingsByIri[resolvedThingIri];\n if (typeof thing === \"undefined\") {\n return null;\n }\n return thing;\n}\n/**\n * Get all [[Thing]]s in a [[SolidDataset]].\n *\n * @param solidDataset The [[SolidDataset]] to extract the [[Thing]]s from.\n * @param options Not yet implemented.\n */\nfunction getThingAll(solidDataset, options = { acceptBlankNodes: false }) {\n var _a;\n const graph = typeof options.scope !== \"undefined\"\n ? internal_toIriString(options.scope)\n : \"default\";\n const thingsByIri = (_a = solidDataset.graphs[graph]) !== null && _a !== void 0 ? _a : {};\n return Object.values(thingsByIri).filter((thing) => !isBlankNodeId(thing.url) || options.acceptBlankNodes);\n}\n/**\n * Insert a [[Thing]] into a [[SolidDataset]], replacing previous instances of that Thing.\n *\n * @param solidDataset The SolidDataset to insert a Thing into.\n * @param thing The Thing to insert into the given SolidDataset.\n * @returns A new SolidDataset equal to the given SolidDataset, but with the given Thing.\n */\nfunction setThing(solidDataset, thing) {\n var _a;\n const thingIri = isThingLocal(thing) && hasServerResourceInfo(solidDataset)\n ? resolveLocalIri(getLocalNodeName(thing.url), getSourceUrl(solidDataset))\n : thing.url;\n const defaultGraph = solidDataset.graphs.default;\n const updatedDefaultGraph = freeze({\n ...defaultGraph,\n [thingIri]: freeze({ ...thing, url: thingIri }),\n });\n const updatedGraphs = freeze({\n ...solidDataset.graphs,\n default: updatedDefaultGraph,\n });\n const subjectNode = DataFactory.namedNode(thingIri);\n const deletedThingPredicates = (_a = solidDataset.graphs.default[thingIri]) === null || _a === void 0 ? void 0 : _a.predicates;\n const deletions = typeof deletedThingPredicates !== \"undefined\"\n ? subjectToRdfJsQuads(deletedThingPredicates, subjectNode, DataFactory.defaultGraph())\n : [];\n const additions = subjectToRdfJsQuads(thing.predicates, subjectNode, DataFactory.defaultGraph());\n return internal_addAdditionsToChangeLog(internal_addDeletionsToChangeLog(freeze({\n ...solidDataset,\n graphs: updatedGraphs,\n }), deletions), additions);\n}\n/**\n * Remove a Thing from a SolidDataset.\n *\n * @param solidDataset The SolidDataset to remove a Thing from.\n * @param thing The Thing to remove from `solidDataset`.\n * @returns A new [[SolidDataset]] equal to the input SolidDataset, excluding the given Thing.\n */\nfunction removeThing(solidDataset, thing) {\n var _a;\n let thingIri;\n if (isNamedNode(thing)) {\n thingIri = thing.value;\n }\n else if (typeof thing === \"string\") {\n thingIri =\n isLocalNodeIri(thing) && hasServerResourceInfo(solidDataset)\n ? resolveLocalIri(getLocalNodeName(thing), getSourceUrl(solidDataset))\n : thing;\n }\n else if (isThingLocal(thing)) {\n thingIri = thing.url;\n }\n else {\n thingIri = asIri(thing);\n }\n const defaultGraph = solidDataset.graphs.default;\n const updatedDefaultGraph = { ...defaultGraph };\n delete updatedDefaultGraph[thingIri];\n const updatedGraphs = freeze({\n ...solidDataset.graphs,\n default: freeze(updatedDefaultGraph),\n });\n const subjectNode = DataFactory.namedNode(thingIri);\n const deletedThingPredicates = (_a = solidDataset.graphs.default[thingIri]) === null || _a === void 0 ? void 0 : _a.predicates;\n const deletions = typeof deletedThingPredicates !== \"undefined\"\n ? subjectToRdfJsQuads(deletedThingPredicates, subjectNode, DataFactory.defaultGraph())\n : [];\n return internal_addDeletionsToChangeLog(freeze({\n ...solidDataset,\n graphs: updatedGraphs,\n }), deletions);\n}\nfunction createThing(options = {}) {\n var _a;\n if (typeof options.url !== \"undefined\") {\n const { url } = options;\n if (!internal_isValidUrl(url)) {\n throw new ValidThingUrlExpectedError(url);\n }\n const thing = freeze({\n type: \"Subject\",\n predicates: freeze({}),\n url,\n });\n return thing;\n }\n const name = (_a = options.name) !== null && _a !== void 0 ? _a : generateName();\n const localNodeIri = getLocalNodeIri(name);\n const thing = freeze({\n type: \"Subject\",\n predicates: freeze({}),\n url: localNodeIri,\n });\n return thing;\n}\n/**\n * @param input An value that might be a [[Thing]].\n * @returns Whether `input` is a Thing.\n * @since 0.2.0\n */\nfunction isThing(input) {\n return (typeof input === \"object\" &&\n input !== null &&\n typeof input.type === \"string\" &&\n input.type === \"Subject\");\n}\nfunction asUrl(thing, baseUrl) {\n if (isThingLocal(thing)) {\n if (typeof baseUrl === \"undefined\") {\n throw new Error(\"The URL of a Thing that has not been persisted cannot be determined without a base URL.\");\n }\n return resolveLocalIri(getLocalNodeName(thing.url), baseUrl);\n }\n return thing.url;\n}\n/** @hidden Alias of [[asUrl]] for those who prefer IRI terminology. */\nconst asIri = asUrl;\n/**\n * Gets a human-readable representation of the given Thing to aid debugging.\n *\n * Note that changes to the exact format of the return value are not considered a breaking change;\n * it is intended to aid in debugging, not as a serialisation method that can be reliably parsed.\n *\n * @param thing The Thing to get a human-readable representation of.\n * @since 0.3.0\n */\nfunction thingAsMarkdown(thing) {\n let thingAsMarkdown = \"\";\n if (isThingLocal(thing)) {\n thingAsMarkdown += `## Thing (no URL yet — identifier: \\`#${getLocalNodeName(thing.url)}\\`)\\n`;\n }\n else {\n thingAsMarkdown += `## Thing: ${thing.url}\\n`;\n }\n const predicateIris = Object.keys(thing.predicates);\n if (predicateIris.length === 0) {\n thingAsMarkdown += \"\\n\\n\";\n }\n else {\n for (const predicate of predicateIris) {\n thingAsMarkdown += `\\nProperty: ${predicate}\\n`;\n const values = getTermAll(thing, predicate);\n thingAsMarkdown += values.reduce((acc, value) => {\n return `${acc}- ${internal_getReadableValue(value)}\\n`;\n }, \"\");\n }\n }\n return thingAsMarkdown;\n}\n/**\n * @param thing The [[Thing]] of which a URL might or might not be known.\n * @return `true` if `thing` has no known URL yet.\n * @since 1.7.0\n */\nfunction isThingLocal(thing) {\n return isLocalNodeIri(thing.url);\n}\n/**\n * This error is thrown when a function expected to receive a [[Thing]] but received something else.\n * @since 1.2.0\n */\nclass ThingExpectedError extends SolidClientError {\n constructor(receivedValue) {\n const message = `Expected a Thing, but received: [${receivedValue}].`;\n super(message);\n this.receivedValue = receivedValue;\n }\n}\n/**\n * This error is thrown when a function expected to receive a valid URL to identify a property but received something else.\n */\nclass ValidPropertyUrlExpectedError extends SolidClientError {\n constructor(receivedValue) {\n const value = isNamedNode(receivedValue)\n ? receivedValue.value\n : receivedValue;\n const message = `Expected a valid URL to identify a property, but received: [${value}].`;\n super(message);\n this.receivedProperty = value;\n }\n}\n/**\n * This error is thrown when a function expected to receive a valid URL value but received something else.\n */\nclass ValidValueUrlExpectedError extends SolidClientError {\n constructor(receivedValue) {\n const value = isNamedNode(receivedValue)\n ? receivedValue.value\n : receivedValue;\n const message = `Expected a valid URL value, but received: [${value}].`;\n super(message);\n this.receivedValue = value;\n }\n}\n/**\n * This error is thrown when a function expected to receive a valid URL to identify a [[Thing]] but received something else.\n */\nclass ValidThingUrlExpectedError extends SolidClientError {\n constructor(receivedValue) {\n const value = isNamedNode(receivedValue)\n ? receivedValue.value\n : receivedValue;\n const message = `Expected a valid URL to identify a Thing, but received: [${value}].`;\n super(message);\n this.receivedValue = value;\n }\n}\n/**\n * Generate a string that can be used as the unique identifier for a Thing\n *\n * This function works by starting with a date string (so that Things can be\n * sorted chronologically), followed by a random number generated by taking a\n * random number between 0 and 1, and cutting off the `0.`.\n *\n * @internal\n * @returns An string that's likely to be unique\n */\nconst generateName = () => {\n return uuid.v4();\n};\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * This function normalizes IRIs as managed by the server to ease accurate comparison.\n * @param iri\n * @hidden\n */\nfunction normalizeServerSideIri(iri) {\n const iriObj = new URL(iri);\n iriObj.hash = \"\";\n return iriObj.href;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Initialise a new [[SolidDataset]] in memory.\n *\n * @returns An empty [[SolidDataset]].\n */\nfunction createSolidDataset() {\n return freeze({\n type: \"Dataset\",\n graphs: {\n default: {},\n },\n });\n}\n/**\n * @hidden This interface is not exposed yet until we've tried it out in practice.\n */\nasync function responseToSolidDataset(response, parseOptions = {}) {\n if (internal_isUnsuccessfulResponse(response)) {\n throw new FetchError(`Fetching the SolidDataset at [${response.url}] failed: [${response.status}] [${response.statusText}] ${await response.text()}.`, response);\n }\n const resourceInfo = responseToResourceInfo(response);\n const parsers = {\n \"text/turtle\": getTurtleParser$1(),\n ...parseOptions.parsers,\n };\n const contentType = getContentType$1(resourceInfo);\n if (contentType === null) {\n throw new Error(`Could not determine the content type of the Resource at [${getSourceUrl(resourceInfo)}].`);\n }\n const mimeType = contentType.split(\";\")[0];\n const parser = parsers[mimeType];\n if (typeof parser === \"undefined\") {\n throw new Error(`The Resource at [${getSourceUrl(resourceInfo)}] has a MIME type of [${mimeType}], but the only parsers available are for the following MIME types: [${Object.keys(parsers).join(\", \")}].`);\n }\n const data = await response.text();\n const parsingPromise = new Promise((resolve, reject) => {\n let solidDataset = freeze({\n graphs: freeze({ default: freeze({}) }),\n type: \"Dataset\",\n });\n // While Quads without Blank Nodes can be added to the SolidDataset as we\n // encounter them, to parse Quads with Blank Nodes, we'll have to wait until\n // we've seen all the Quads, so that we can reconcile equal Blank Nodes.\n const quadsWithBlankNodes = [];\n const allQuads = [];\n parser.onError((error) => {\n reject(new Error(`Encountered an error parsing the Resource at [${getSourceUrl(resourceInfo)}] with content type [${contentType}]: ${error}`));\n });\n parser.onQuad((quad) => {\n allQuads.push(quad);\n if (quad.subject.termType === \"BlankNode\" ||\n quad.object.termType === \"BlankNode\") {\n // Quads with Blank Nodes will be parsed when all Quads are known,\n // so that equal Blank Nodes can be reconciled:\n quadsWithBlankNodes.push(quad);\n }\n else {\n solidDataset = addRdfJsQuadToDataset(solidDataset, quad);\n }\n });\n parser.onComplete(async () => {\n // If a Resource contains more than this number of Blank Nodes,\n // we consider the detection of chains (O(n^2), I think) to be too\n // expensive, and just incorporate them as regular Blank Nodes with\n // non-deterministic, ad-hoc identifiers into the SolidDataset:\n const maxBlankNodesToDetectChainsFor = 20;\n // Some Blank Nodes only serve to use a set of Quads as the Object for a\n // single Subject. Those Quads will be added to the SolidDataset when\n // their Subject's Blank Node is encountered in the Object position.\n const chainBlankNodes = quadsWithBlankNodes.length <= maxBlankNodesToDetectChainsFor\n ? getChainBlankNodes(quadsWithBlankNodes)\n : [];\n const quadsWithoutChainBlankNodeSubjects = quadsWithBlankNodes.filter((quad) => chainBlankNodes.every((chainBlankNode) => !chainBlankNode.equals(quad.subject)));\n solidDataset = quadsWithoutChainBlankNodeSubjects.reduce((datasetAcc, quad) => addRdfJsQuadToDataset(datasetAcc, quad, {\n otherQuads: allQuads,\n chainBlankNodes,\n }), solidDataset);\n const solidDatasetWithResourceInfo = freeze({\n ...solidDataset,\n ...resourceInfo,\n });\n resolve(solidDatasetWithResourceInfo);\n });\n parser.parse(data, resourceInfo);\n });\n return parsingPromise;\n}\n/**\n * Fetch a SolidDataset from the given URL. Currently requires the SolidDataset to be available as [Turtle](https://www.w3.org/TR/turtle/).\n *\n * Note that the URL of a container ends with a [trailing slash \"/\"](https://solidproject.org/TR/protocol#uri).\n * If it is missing, some libraries will add it automatically, which may result in additional round-trips, possibly including\n * authentication errors ([more information](https://github.com/inrupt/solid-client-js/issues/1216#issuecomment-904703695)).\n *\n * @param url URL to fetch a [[SolidDataset]] from.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns Promise resolving to a [[SolidDataset]] containing the data at the given Resource, or rejecting if fetching it failed.\n */\nasync function getSolidDataset(url, options = internal_defaultFetchOptions) {\n var _a;\n url = internal_toIriString(url);\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const parserContentTypes = Object.keys((_a = options.parsers) !== null && _a !== void 0 ? _a : {});\n const acceptedContentTypes = parserContentTypes.length > 0\n ? parserContentTypes.join(\", \")\n : \"text/turtle\";\n const response = await config.fetch(url, {\n headers: {\n Accept: acceptedContentTypes,\n },\n });\n if (internal_isUnsuccessfulResponse(response)) {\n throw new FetchError(`Fetching the Resource at [${url}] failed: [${response.status}] [${response.statusText}] ${await response.text()}.`, response);\n }\n const solidDataset = await responseToSolidDataset(response, options);\n return solidDataset;\n}\n/**\n * Create a SPARQL UPDATE Patch request from a [[SolidDataset]] with a changelog.\n * @param solidDataset the [[SolidDataset]] that has been locally updated, and that should be persisted.\n * @returns an HTTP PATCH request configuration object, aligned with the [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters), containing a SPARQL UPDATE.\n * @hidden\n */\nasync function prepareSolidDatasetUpdate(solidDataset) {\n const deleteStatement = solidDataset.internal_changeLog.deletions.length > 0\n ? `DELETE DATA {${(await triplesToTurtle(solidDataset.internal_changeLog.deletions.map(getNamedNodesForLocalNodes))).trim()}};`\n : \"\";\n const insertStatement = solidDataset.internal_changeLog.additions.length > 0\n ? `INSERT DATA {${(await triplesToTurtle(solidDataset.internal_changeLog.additions.map(getNamedNodesForLocalNodes))).trim()}};`\n : \"\";\n return {\n method: \"PATCH\",\n body: `${deleteStatement} ${insertStatement}`,\n headers: {\n \"Content-Type\": \"application/sparql-update\",\n },\n };\n}\n/**\n * Create a Put request to write a locally created [[SolidDataset]] to a Pod.\n * @param solidDataset the [[SolidDataset]] that has been locally updated, and that should be persisted.\n * @returns an HTTP PUT request configuration object, aligned with the [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters), containing a serialization of the [[SolidDataset]].\n * @hidden\n */\nasync function prepareSolidDatasetCreation(solidDataset, options) {\n return {\n method: \"PUT\",\n body: await triplesToTurtle(toRdfJsQuads(solidDataset).map(getNamedNodesForLocalNodes), options),\n headers: {\n \"Content-Type\": \"text/turtle\",\n \"If-None-Match\": \"*\",\n Link: `<${ldp.Resource}>; rel=\"type\"`,\n },\n };\n}\n/**\n * Given a SolidDataset, store it in a Solid Pod (overwriting the existing data at the given URL).\n *\n * A SolidDataset keeps track of the data changes compared to the data in the Pod; i.e.,\n * the changelog tracks both the old value and new values of the property being modified. This\n * function applies the changes to the current SolidDataset. If the old value specified in the\n * changelog does not correspond to the value currently in the Pod, this function will throw an\n * error (common issues are listed in [the documentation](https://docs.inrupt.com/developer-tools/javascript/client-libraries/reference/error-codes/)).\n *\n * The SolidDataset returned by this function will contain the data sent to the Pod, and a ChangeLog\n * up-to-date with the saved data. Note that if the data on the server was modified in between the\n * first fetch and saving it, the updated data will not be reflected in the returned SolidDataset.\n * To make sure you have the latest data, call [[getSolidDataset]] again after saving the data.\n *\n * The Solid server will create any intermediary Containers that do not exist yet, so they do not\n * need to be created in advance. For example, if the target URL is\n * https://example.pod/container/resource and https://example.pod/container/ does not exist yet,\n * it will exist after this function resolves successfully.\n *\n * @param url URL to save `solidDataset` to.\n * @param solidDataset The [[SolidDataset]] to save.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * `options.prefixes`: A prefix map to customize the serialization. Only applied on resource creation if the serialization allows it.\n * @returns A Promise resolving to a [[SolidDataset]] containing the stored data, or rejecting if saving it failed.\n */\nasync function saveSolidDatasetAt(url, solidDataset, options = internal_defaultFetchOptions) {\n url = internal_toIriString(url);\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const datasetWithChangelog = internal_withChangeLog(solidDataset);\n const requestInit = isUpdate(datasetWithChangelog, url)\n ? await prepareSolidDatasetUpdate(datasetWithChangelog)\n : await prepareSolidDatasetCreation(datasetWithChangelog, options);\n const response = await config.fetch(url, requestInit);\n if (internal_isUnsuccessfulResponse(response)) {\n const diagnostics = isUpdate(datasetWithChangelog, url)\n ? `The changes that were sent to the Pod are listed below.\\n\\n${changeLogAsMarkdown(datasetWithChangelog)}`\n : `The SolidDataset that was sent to the Pod is listed below.\\n\\n${solidDatasetAsMarkdown(datasetWithChangelog)}`;\n throw new FetchError(`Storing the Resource at [${url}] failed: [${response.status}] [${response.statusText}] ${await response.text()}.\\n\\n${diagnostics}`, response);\n }\n const resourceInfo = {\n ...internal_parseResourceInfo(response),\n isRawData: false,\n };\n const storedDataset = freeze({\n ...solidDataset,\n internal_changeLog: { additions: [], deletions: [] },\n internal_resourceInfo: resourceInfo,\n });\n const storedDatasetWithResolvedIris = resolveLocalIrisInSolidDataset(storedDataset);\n return storedDatasetWithResolvedIris;\n}\n/**\n * Deletes the SolidDataset at a given URL.\n *\n * If operating on a container, the container must be empty otherwise a 409 CONFLICT will be raised.\n *\n * @param solidDataset The URL of the SolidDataset to delete or the SolidDataset itself (if it has ResourceInfo).\n * @since 0.6.0\n */\nasync function deleteSolidDataset(solidDataset, options = internal_defaultFetchOptions) {\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const url = hasResourceInfo(solidDataset)\n ? internal_toIriString(getSourceUrl(solidDataset))\n : internal_toIriString(solidDataset);\n const response = await config.fetch(url, { method: \"DELETE\" });\n if (internal_isUnsuccessfulResponse(response)) {\n throw new FetchError(`Deleting the SolidDataset at [${url}] failed: [${response.status}] [${response.statusText}] ${await response.text()}.`, response);\n }\n}\n/**\n * Create a Container at the given URL. Some content may optionally be specified,\n * e.g. to add metadata describing the container.\n *\n * Throws an error if creating the Container failed, e.g. because the current user does not have\n * permissions to, or because the Container already exists.\n *\n * Note that a Solid server will automatically create the necessary Containers when storing a\n * Resource; i.e. there is no need to call this function if it is immediately followed by\n * [[saveSolidDatasetAt]] or [[overwriteFile]].\n *\n * @param url URL of the empty Container that is to be created.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @param solidDataset Optional parameter - if provided we use this dataset as the body of the HTT request, meaning it's data is included in the Container resource.\n * @since 0.2.0\n */\nasync function createContainerAt(url, options = internal_defaultFetchOptions) {\n var _a;\n url = internal_toIriString(url);\n url = url.endsWith(\"/\") ? url : `${url}/`;\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const response = await config.fetch(url, {\n method: \"PUT\",\n body: config.initialContent\n ? await triplesToTurtle(toRdfJsQuads(config.initialContent).map(getNamedNodesForLocalNodes))\n : undefined,\n headers: {\n Accept: \"text/turtle\",\n \"Content-Type\": \"text/turtle\",\n \"If-None-Match\": \"*\",\n // This header should not be required to create a Container,\n // but ESS currently expects it:\n Link: `<${ldp.BasicContainer}>; rel=\"type\"`,\n },\n });\n if (internal_isUnsuccessfulResponse(response)) {\n const containerType = config.initialContent === undefined ? \"empty\" : \"non-empty\";\n throw new FetchError(`Creating the ${containerType} Container at [${url}] failed: [${response.status}] [${response.statusText}] ${await response.text()}.`, response);\n }\n const resourceInfo = internal_parseResourceInfo(response);\n const containerDataset = freeze({\n ...((_a = options.initialContent) !== null && _a !== void 0 ? _a : createSolidDataset()),\n internal_changeLog: { additions: [], deletions: [] },\n internal_resourceInfo: resourceInfo,\n });\n return containerDataset;\n}\nfunction isSourceIriEqualTo(dataset, iri) {\n return (normalizeServerSideIri(dataset.internal_resourceInfo.sourceIri) ===\n normalizeServerSideIri(iri));\n}\nfunction isUpdate(solidDataset, url) {\n return (hasChangelog(solidDataset) &&\n hasResourceInfo(solidDataset) &&\n typeof solidDataset.internal_resourceInfo.sourceIri === \"string\" &&\n isSourceIriEqualTo(solidDataset, url));\n}\n/**\n * Given a SolidDataset, store it in a Solid Pod in a new Resource inside a Container.\n *\n * The Container at the given URL should already exist; if it does not, you can initialise it first\n * using [[createContainerAt]], or directly save the SolidDataset at the desired location using\n * [[saveSolidDatasetAt]].\n *\n * This function is primarily useful if the current user does not have access to change existing files in\n * a Container, but is allowed to add new files; in other words, they have Append, but not Write\n * access to a Container. This is useful in situations where someone wants to allow others to,\n * for example, send notifications to their Pod, but not to view or delete existing notifications.\n * You can pass a suggestion for the new Resource's name, but the server may decide to give it\n * another name — for example, if a Resource with that name already exists inside the given\n * Container.\n * If the user does have access to write directly to a given location, [[saveSolidDatasetAt]]\n * will do the job just fine, and does not require the parent Container to exist in advance.\n *\n * @param containerUrl URL of the Container in which to create a new Resource.\n * @param solidDataset The [[SolidDataset]] to save to a new Resource in the given Container.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns A Promise resolving to a [[SolidDataset]] containing the saved data. The Promise rejects if the save failed.\n */\nasync function saveSolidDatasetInContainer(containerUrl, solidDataset, options = internal_defaultFetchOptions) {\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n containerUrl = internal_toIriString(containerUrl);\n const rawTurtle = await triplesToTurtle(toRdfJsQuads(solidDataset).map(getNamedNodesForLocalNodes));\n const headers = {\n \"Content-Type\": \"text/turtle\",\n Link: `<${ldp.Resource}>; rel=\"type\"`,\n };\n if (options.slugSuggestion) {\n headers.slug = options.slugSuggestion;\n }\n const response = await config.fetch(containerUrl, {\n method: \"POST\",\n body: rawTurtle,\n headers,\n });\n if (internal_isUnsuccessfulResponse(response)) {\n throw new FetchError(`Storing the Resource in the Container at [${containerUrl}] failed: [${response.status}] [${response.statusText}] ${await response.text()}.\\n\\n` +\n `The SolidDataset that was sent to the Pod is listed below.\\n\\n${solidDatasetAsMarkdown(solidDataset)}`, response);\n }\n const internalResourceInfo = internal_parseResourceInfo(response);\n if (!internalResourceInfo.location) {\n throw new Error(\"Could not determine the location of the newly saved SolidDataset.\");\n }\n let resourceIri;\n try {\n // Try to parse the location header as a URL (safe if it's an absolute URL)``\n // This should help determine the container URL if normalisation happened on the server side.\n resourceIri = new URL(internalResourceInfo.location).href;\n }\n catch (e) {\n // If it's a relative URL then, rely on the response.url to construct the sourceIri\n resourceIri = new URL(internalResourceInfo.location, response.url).href;\n }\n const resourceInfo = {\n internal_resourceInfo: {\n isRawData: false,\n sourceIri: resourceIri,\n },\n };\n const resourceWithResourceInfo = freeze({\n ...solidDataset,\n ...resourceInfo,\n });\n const resourceWithResolvedIris = resolveLocalIrisInSolidDataset(resourceWithResourceInfo);\n return resourceWithResolvedIris;\n}\n/**\n * Create an empty Container inside the Container at the given URL.\n *\n * Throws an error if creating the Container failed, e.g. because the current user does not have\n * permissions to.\n *\n * The Container in which to create the new Container should itself already exist.\n *\n * This function is primarily useful if the current user does not have access to change existing files in\n * a Container, but is allowed to add new files; in other words, they have Append, but not Write\n * access to a Container. This is useful in situations where someone wants to allow others to,\n * for example, send notifications to their Pod, but not to view or delete existing notifications.\n * You can pass a suggestion for the new Resource's name, but the server may decide to give it\n * another name — for example, if a Resource with that name already exists inside the given\n * Container.\n * If the user does have access to write directly to a given location, [[createContainerAt]]\n * will do the job just fine, and does not require the parent Container to exist in advance.\n *\n * @param containerUrl URL of the Container in which the empty Container is to\n * be created.\n * @param options Optional parameter `options.fetch`: An alternative `fetch`\n * function to make the HTTP request, compatible with the browser-native [fetch\n * API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).`options.slugSuggestion`\n * accepts a string for your new Container's name.\n * @returns A promise that resolves to a SolidDataset with ResourceInfo if\n * successful, and that rejects otherwise.\n * @since 0.2.0\n */\nasync function createContainerInContainer(containerUrl, options = internal_defaultFetchOptions) {\n containerUrl = internal_toIriString(containerUrl);\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const headers = {\n \"Content-Type\": \"text/turtle\",\n Link: `<${ldp.BasicContainer}>; rel=\"type\"`,\n };\n if (options.slugSuggestion) {\n headers.slug = options.slugSuggestion;\n }\n const response = await config.fetch(containerUrl, {\n method: \"POST\",\n headers,\n });\n if (internal_isUnsuccessfulResponse(response)) {\n throw new FetchError(`Creating an empty Container in the Container at [${containerUrl}] failed: [${response.status}] [${response.statusText}] ${await response.text()}.`, response);\n }\n const internalResourceInfo = internal_parseResourceInfo(response);\n if (!internalResourceInfo.location) {\n throw new Error(\"Could not determine the location of the newly created Container.\");\n }\n try {\n // Try to parse the location header as a URL (safe if it's an absolute URL)``\n // This should help determine the container URL if normalisation happened on the server side.\n const sourceIri = new URL(internalResourceInfo.location).toString();\n return freeze({\n ...createSolidDataset(),\n internal_resourceInfo: {\n ...internalResourceInfo,\n sourceIri,\n },\n });\n }\n catch (e) {\n // If it's a relative URL then, rely on the response.url to construct the sourceIri\n }\n return freeze({\n ...createSolidDataset(),\n internal_resourceInfo: {\n ...internalResourceInfo,\n sourceIri: new URL(internalResourceInfo.location, response.url).href,\n },\n });\n}\n/**\n * Deletes the Container at a given URL.\n *\n * @param container The URL of the Container to delete or the Container Dataset itself (if it has ResourceInfo).\n * @since 0.6.0\n */\nasync function deleteContainer(container, options = internal_defaultFetchOptions) {\n const url = hasResourceInfo(container)\n ? internal_toIriString(getSourceUrl(container))\n : internal_toIriString(container);\n if (!isContainer(container)) {\n throw new Error(`You're trying to delete the Container at [${url}], but Container URLs should end in a \\`/\\`. Are you sure this is a Container?`);\n }\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const response = await config.fetch(url, { method: \"DELETE\" });\n if (internal_isUnsuccessfulResponse(response)) {\n throw new FetchError(`Deleting the Container at [${url}] failed: [${response.status}] [${response.statusText}] ${await response.text()}.`, response);\n }\n}\nfunction isChildResource(a, b) {\n const parent = new URL(b);\n const child = new URL(a);\n // Explicitly test on the whole URL to enforce similar origins.\n const isAncestor = child.href.startsWith(parent.href);\n const relativePath = child.pathname\n .substring(parent.pathname.length, child.pathname.length)\n .replace(/(^\\/)|(\\/$)/g, \"\");\n // The child path component that isn't present in the parent should only\n // potentially include slashes at the end (if it is a container).\n return isAncestor && relativePath.length >= 1 && !relativePath.includes(\"/\");\n}\n/**\n * Given a [[SolidDataset]] representing a Container (see [[isContainer]]), fetch the URLs of all\n * contained resources that respect [slash semantics](https://solidproject.org/TR/protocol#uri-slash-semantics)\n * (see {@link validateContainedResourceAll}).\n * If the solidDataset given is not a container, or is missing resourceInfo, throw an error.\n *\n * @param solidDataset The container from which to fetch all contained Resource URLs.\n * @returns A list of URLs, each of which points to a contained Resource of the given SolidDataset.\n * @since 1.3.0\n */\nfunction getContainedResourceUrlAll(solidDataset) {\n const containerUrl = getSourceUrl(solidDataset);\n const container = getThing(solidDataset, containerUrl);\n if (container === null) {\n return [];\n }\n // See https://www.w3.org/TR/2015/REC-ldp-20150226/#h-ldpc-http_post:\n // > a containment triple MUST be added to the state of the LDPC whose subject is the LDPC URI,\n // > whose predicate is ldp:contains and whose object is the URI for the newly created document\n return (getIriAll(container, ldp.contains)\n // See https://solidproject.org/TR/protocol#resource-containment\n .filter((childUrl) => isChildResource(childUrl, containerUrl)));\n}\n/**\n * Given a {@link SolidDataset} representing a [Container](https://solidproject.org/TR/protocol#resource-containment)\n * (see {@link isContainer}), verify that all its containment claims are valid. Containment of a resource is valid if\n * it respects [slash semantics](https://solidproject.org/TR/protocol#uri-slash-semantics).\n *\n * For the example, given a container at https://example.org/container/:\n * - The following resources are valid:\n * - https://example.org/container/resource\n * - https://example.org/container/subcontainer/\n * - The following resources are invalid:\n * - https://example.org/container/resource/invalid (not a direct child resource)\n * - https://example.org/container2 (not a child resource)\n * - https://domain2.example.org/container/resource (not a direct child resource)\n *\n * If a component claim is invalid, {@link validateContainedResourceAll} returns the invalid component's URL\n * as part of its return object.\n *\n * Note: It is recommended that this function always be used before calling\n * {@link getContainedResourceUrlAll} since {@link getContainedResourceUrlAll} does not\n * return Resources for which containment is invalid. Using the function in conjunction\n * with {@link getContainedResourceUrlAll} allows for the detection of unexpected behaviour from servers,\n * including malicious containment triples that could appear. Because ESS conforms to the Solid Protocol,\n * i.e., respects slash semantics for its containment triples, validateContainedResourceAll returns true for\n * containers fetched from ESS.\n *\n * @param solidDataset The container from which containment claims are validated.\n * @returns A validation report, including the offending contained resources URL if any.\n * @since unreleased\n */\nfunction validateContainedResourceAll(solidDataset) {\n const containerUrl = getSourceUrl(solidDataset);\n const container = getThing(solidDataset, containerUrl);\n if (container === null) {\n return { isValid: true, invalidContainedResources: [] };\n }\n // See https://www.w3.org/TR/2015/REC-ldp-20150226/#h-ldpc-http_post:\n // > a containment triple MUST be added to the state of the LDPC whose subject is the LDPC URI,\n // > whose predicate is ldp:contains and whose object is the URI for the newly created document\n const invalidChildren = getIriAll(container, ldp.contains)\n // See https://solidproject.org/TR/protocol#resource-containment\n .filter((childUrl) => !isChildResource(childUrl, containerUrl));\n if (invalidChildren.length > 0) {\n return { isValid: false, invalidContainedResources: invalidChildren };\n }\n return { isValid: true, invalidContainedResources: [] };\n}\n/**\n * Gets a human-readable representation of the given SolidDataset to aid debugging.\n *\n * Note that changes to the exact format of the return value are not considered a breaking change;\n * it is intended to aid in debugging, not as a serialisation method that can be reliably parsed.\n *\n * @param solidDataset The [[SolidDataset]] to get a human-readable representation of.\n * @since 0.3.0\n */\nfunction solidDatasetAsMarkdown(solidDataset) {\n let readableSolidDataset = \"\";\n if (hasResourceInfo(solidDataset)) {\n readableSolidDataset += `# SolidDataset: ${getSourceUrl(solidDataset)}\\n`;\n }\n else {\n readableSolidDataset += `# SolidDataset (no URL yet)\\n`;\n }\n const things = getThingAll(solidDataset);\n if (things.length === 0) {\n readableSolidDataset += \"\\n\\n\";\n }\n else {\n things.forEach((thing) => {\n readableSolidDataset += `\\n${thingAsMarkdown(thing)}`;\n if (hasChangelog(solidDataset)) {\n readableSolidDataset += `\\n${getReadableChangeLogSummary(solidDataset, thing)}\\n`;\n }\n });\n }\n return readableSolidDataset;\n}\n/**\n * Gets a human-readable representation of the local changes to a Resource to aid debugging.\n *\n * Note that changes to the exact format of the return value are not considered a breaking change;\n * it is intended to aid in debugging, not as a serialisation method that can be reliably parsed.\n *\n * @param solidDataset The Resource of which to get a human-readable representation of the changes applied to it locally.\n * @since 0.3.0\n */\nfunction changeLogAsMarkdown(solidDataset) {\n if (!hasResourceInfo(solidDataset)) {\n return \"This is a newly initialized SolidDataset, so there is no source to compare it to.\";\n }\n if (!hasChangelog(solidDataset) ||\n (solidDataset.internal_changeLog.additions.length === 0 &&\n solidDataset.internal_changeLog.deletions.length === 0)) {\n return (`## Changes compared to ${getSourceUrl(solidDataset)}\\n\\n` +\n `This SolidDataset has not been modified since it was fetched from ${getSourceUrl(solidDataset)}.\\n`);\n }\n let readableChangeLog = `## Changes compared to ${getSourceUrl(solidDataset)}\\n`;\n const changeLogsByThingAndProperty = sortChangeLogByThingAndProperty(solidDataset);\n Object.keys(changeLogsByThingAndProperty).forEach((thingUrl) => {\n readableChangeLog += `\\n### Thing: ${thingUrl}\\n`;\n const changeLogByProperty = changeLogsByThingAndProperty[thingUrl];\n Object.keys(changeLogByProperty).forEach((propertyUrl) => {\n readableChangeLog += `\\nProperty: ${propertyUrl}\\n`;\n const { deleted } = changeLogByProperty[propertyUrl];\n const { added } = changeLogByProperty[propertyUrl];\n if (deleted.length > 0) {\n readableChangeLog += \"- Removed:\\n\";\n readableChangeLog += deleted.reduce((acc, deletedValue) => {\n return `${acc} - ${internal_getReadableValue(deletedValue)}\\n`;\n }, \"\");\n }\n if (added.length > 0) {\n readableChangeLog += \"- Added:\\n\";\n readableChangeLog += added.reduce((acc, addedValue) => {\n return `${acc} - ${internal_getReadableValue(addedValue)}\\n`;\n }, \"\");\n }\n });\n });\n return readableChangeLog;\n}\nfunction sortChangeLogByThingAndProperty(solidDataset) {\n const changeLogsByThingAndProperty = Object.create(null);\n solidDataset.internal_changeLog.deletions.forEach((deletion) => {\n var _a, _b;\n var _c;\n const subjectNode = isLocalNode(deletion.subject)\n ? /* istanbul ignore next: Unsaved deletions should be removed from the additions list instead, so this code path shouldn't be hit: */\n resolveIriForLocalNode(deletion.subject, getSourceUrl(solidDataset))\n : deletion.subject;\n if (!isNamedNode(subjectNode) || !isNamedNode(deletion.predicate)) {\n return;\n }\n const thingUrl = internal_toIriString(subjectNode);\n const propertyUrl = internal_toIriString(deletion.predicate);\n (_a = changeLogsByThingAndProperty[thingUrl]) !== null && _a !== void 0 ? _a : (changeLogsByThingAndProperty[thingUrl] = Object.create(null));\n (_b = (_c = changeLogsByThingAndProperty[thingUrl])[propertyUrl]) !== null && _b !== void 0 ? _b : (_c[propertyUrl] = {\n added: [],\n deleted: [],\n });\n changeLogsByThingAndProperty[thingUrl][propertyUrl].deleted.push(deletion.object);\n });\n solidDataset.internal_changeLog.additions.forEach((addition) => {\n var _a, _b;\n var _c;\n const subjectNode = isLocalNode(addition.subject)\n ? /* istanbul ignore next: setThing already resolves local Subjects when adding them, so this code path should never be hit. */\n resolveIriForLocalNode(addition.subject, getSourceUrl(solidDataset))\n : addition.subject;\n if (!isNamedNode(subjectNode) || !isNamedNode(addition.predicate)) {\n return;\n }\n const thingUrl = internal_toIriString(subjectNode);\n const propertyUrl = internal_toIriString(addition.predicate);\n (_a = changeLogsByThingAndProperty[thingUrl]) !== null && _a !== void 0 ? _a : (changeLogsByThingAndProperty[thingUrl] = Object.create(null));\n (_b = (_c = changeLogsByThingAndProperty[thingUrl])[propertyUrl]) !== null && _b !== void 0 ? _b : (_c[propertyUrl] = {\n added: [],\n deleted: [],\n });\n changeLogsByThingAndProperty[thingUrl][propertyUrl].added.push(addition.object);\n });\n return changeLogsByThingAndProperty;\n}\nfunction getReadableChangeLogSummary(solidDataset, thing) {\n const subject = DataFactory.namedNode(thing.url);\n const nrOfAdditions = solidDataset.internal_changeLog.additions.reduce((count, addition) => (addition.subject.equals(subject) ? count + 1 : count), 0);\n const nrOfDeletions = solidDataset.internal_changeLog.deletions.reduce((count, deletion) => (deletion.subject.equals(subject) ? count + 1 : count), 0);\n const additionString = nrOfAdditions === 1\n ? \"1 new value added\"\n : `${nrOfAdditions} new values added`;\n const deletionString = nrOfDeletions === 1 ? \"1 value removed\" : `${nrOfDeletions} values removed`;\n return `(${additionString} / ${deletionString})`;\n}\nfunction getNamedNodesForLocalNodes(quad) {\n const subject = isNamedNode(quad.subject)\n ? getNamedNodeFromLocalNode(quad.subject)\n : /* istanbul ignore next: We don't allow non-NamedNodes as the Subject, so this code path should never be hit: */\n quad.subject;\n const object = isNamedNode(quad.object)\n ? getNamedNodeFromLocalNode(quad.object)\n : quad.object;\n return DataFactory.quad(subject, quad.predicate, object, quad.graph);\n}\nfunction getNamedNodeFromLocalNode(node) {\n if (isLocalNodeIri(node.value)) {\n return DataFactory.namedNode(`#${getLocalNodeName(node.value)}`);\n }\n return node;\n}\nfunction resolveLocalIrisInSolidDataset(solidDataset) {\n const resourceIri = getSourceUrl(solidDataset);\n const defaultGraph = solidDataset.graphs.default;\n const thingIris = Object.keys(defaultGraph);\n const updatedDefaultGraph = thingIris.reduce((graphAcc, thingIri) => {\n const resolvedThing = resolveLocalIrisInThing(graphAcc[thingIri], resourceIri);\n const resolvedThingIri = isLocalNodeIri(thingIri)\n ? `${resourceIri}#${getLocalNodeName(thingIri)}`\n : thingIri;\n const updatedGraph = { ...graphAcc };\n delete updatedGraph[thingIri];\n updatedGraph[resolvedThingIri] = resolvedThing;\n return freeze(updatedGraph);\n }, defaultGraph);\n const updatedGraphs = freeze({\n ...solidDataset.graphs,\n default: updatedDefaultGraph,\n });\n return freeze({\n ...solidDataset,\n graphs: updatedGraphs,\n });\n}\nfunction resolveLocalIrisInThing(thing, baseIri) {\n const predicateIris = Object.keys(thing.predicates);\n const updatedPredicates = predicateIris.reduce((predicatesAcc, predicateIri) => {\n var _a;\n const namedNodes = (_a = predicatesAcc[predicateIri].namedNodes) !== null && _a !== void 0 ? _a : [];\n if (namedNodes.every((namedNode) => !isLocalNodeIri(namedNode))) {\n // This Predicate has no local node Objects, so return it unmodified:\n return predicatesAcc;\n }\n const updatedNamedNodes = freeze(namedNodes.map((namedNode) => isLocalNodeIri(namedNode)\n ? `${baseIri}#${getLocalNodeName(namedNode)}`\n : namedNode));\n const updatedPredicate = freeze({\n ...predicatesAcc[predicateIri],\n namedNodes: updatedNamedNodes,\n });\n return freeze({\n ...predicatesAcc,\n [predicateIri]: updatedPredicate,\n });\n }, thing.predicates);\n return freeze({\n ...thing,\n predicates: updatedPredicates,\n url: isLocalNodeIri(thing.url)\n ? `${baseIri}#${getLocalNodeName(thing.url)}`\n : thing.url,\n });\n}\n/**\n * @hidden\n *\n * Fetch a SolidDataset containing information about the capabilities of the\n * storage server that hosts the given resource URL. For more information,\n * please see the [ESS\n * Documentation](https://docs.inrupt.com/ess/latest/services/discovery-endpoint/#well-known-solid).\n *\n * **Note:** The data contained in this dataset has changed between ESS 1.1 and\n * ESS 2.0, as such you will need to check for multiple predicates to support\n * both versions.\n *\n * ```typescript\n * const wellKnown = await getWellKnownSolid(resource);\n *\n * // The wellKnown dataset uses a blank node for the subject all of it’s predicates,\n * // such that we need to call getThingAll with acceptBlankNodes set to true to\n * // retrieve back predicates contained within the dataset\n * const wellKnownSubjects = getThingAll(wellKnown, {\n * acceptBlankNodes: true,\n * });\n * const wellKnownSubject = wellKnownSubjects[0];\n *\n * // Retrieve a value from the wellKnown dataset:\n * let notificationGateway = getIri(\n * wellKnownSubject,\n * \"http://www.w3.org/ns/solid/terms#notificationGateway\"\n * );\n * ```\n *\n *\n * @param url URL of a Resource.\n * @param options Optional parameter `options.fetch`: An alternative `fetch`\n * function to make the HTTP request, compatible with the browser-native [fetch\n * API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns Promise resolving to a [[SolidDataset]] containing the data at\n * '.well-known/solid' for the given Resource, or rejecting if fetching it\n * failed.\n * @since 1.12.0\n */\nasync function getWellKnownSolid(url, options = internal_defaultFetchOptions) {\n const urlString = internal_toIriString(url);\n // Try to fetch the well-known solid dataset from the server's root\n try {\n const wellKnownSolidUrl = new URL(\"/.well-known/solid\", new URL(urlString).origin).href;\n return await getSolidDataset(wellKnownSolidUrl, {\n fetch: fetch,\n });\n }\n catch (e) {\n // In case of error, do nothing and try to discover the .well-known\n // at the pod's root.\n }\n // 1.1s implementation:\n const resourceMetadata = await getResourceInfo(urlString, {\n fetch: options.fetch,\n // Discovering the .well-known/solid document is useful even for resources\n // we don't have access to.\n ignoreAuthenticationErrors: true,\n });\n const linkedResources = getLinkedResourceUrlAll(resourceMetadata);\n const rootResources = linkedResources[pim.storage];\n const rootResource = (rootResources === null || rootResources === void 0 ? void 0 : rootResources.length) === 1 ? rootResources[0] : null;\n // If pod root (storage) was advertised, retrieve well known solid from pod's root\n if (rootResource !== null) {\n const wellKnownSolidUrl = new URL(\".well-known/solid\", rootResource.endsWith(\"/\") ? rootResource : `${rootResource}/`).href;\n return getSolidDataset(wellKnownSolidUrl, {\n ...options,\n parsers: {\n \"application/ld+json\": getJsonLdParser$1(),\n },\n });\n }\n throw new Error(\"Could not determine storage root or well-known solid resource.\");\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{warning}\n * Do not use this function in production code. For use in **unit tests**.\n * ```\n *\n * This function initialises a new [[SolidDataset]] with metadata as though the\n * SolidDataset has been retrieved from the given URL. The mock SolidDataset can be used in\n * unit tests that require persisted SolidDatasets; e.g., unit tests that call [[getSourceUrl]].\n *\n * @param url The URL from which the returned SolidDataset appears to be retrieved.\n * @returns A mock SolidDataset that appears to be retrieved from the `url`.\n * @since 0.2.0\n */\nfunction mockSolidDatasetFrom(url) {\n const solidDataset = createSolidDataset();\n const solidDatasetWithResourceInfo = {\n ...solidDataset,\n internal_resourceInfo: {\n sourceIri: internal_toIriString(url),\n isRawData: false,\n contentType: \"text/turtle\",\n linkedResources: {},\n },\n };\n return solidDatasetWithResourceInfo;\n}\n/**\n * ```{warning}\n * Do not use this function in production code. For use in **unit tests**.\n * ```\n *\n * This function initialises a new Container [[SolidDataset]] with metadata as though the\n * Container has been retrieved from the given URL. The mock SolidDataset can be used in\n * unit tests that require persisted Containers; e.g., unit tests that call [[isContainer]].\n *\n * @param url The URL from which the returned Container appears to be retrieved. The `url` must end in a slash.\n * @returns A mock SolidDataset that appears to be retrieved from the `url`.\n * @since 0.2.0\n */\nfunction mockContainerFrom(url) {\n const sourceIri = internal_toIriString(url);\n if (!sourceIri.endsWith(\"/\")) {\n throw new Error(\"A Container's URL should end in a slash. Please update your tests.\");\n }\n return mockSolidDatasetFrom(sourceIri);\n}\n/**\n * ```{warning}\n * Do not use this function in production code. For use in **unit tests**.\n * ```\n *\n * This function initialises a new File with metadata as though the\n * File has been retrieved from the given URL. The mock File can be used in\n * unit tests that require persisted Files; e.g. unit tests that call [[getSourceUrl]].\n *\n * @param url The URL from which the returned File appears to be retrieved.\n * @returns A mock File that appears to be retrieved from the `url`.\n * @since 0.2.0\n */\nfunction mockFileFrom(url, options) {\n const file = new Blob();\n const fileWithResourceInfo = Object.assign(file, {\n internal_resourceInfo: {\n sourceIri: internal_toIriString(url),\n isRawData: true,\n contentType: options === null || options === void 0 ? void 0 : options.contentType,\n linkedResources: {},\n },\n });\n return fileWithResourceInfo;\n}\n/**\n * ```{warning}\n * Do not use this function in production code. For use in **unit tests**.\n * ```\n *\n * This function initialises a new Error object with metadata as though the\n * it was the result of getting a 404 when trying to fetch the Resource at the\n * given URL. The mock Error can be used in unit tests that require functions\n * that fetch Resources (like [[getSolidDataset]]) to fail.\n *\n * @param url The URL of the Resource that could not be fetched according to the error.\n * @param statusCode Optional status code (defaults to 404) that caused the error.\n * @returns A mock Error that represents not having been able to fetch the Resource at `url` due to a 404 Response.\n * @since 1.1.0\n */\nfunction mockFetchError(fetchedUrl, statusCode = 404, statusText = \"Not Found\") {\n // The Response constructor in Node 14 makes an empty status text undefined.\n const failedResponse = new universalFetch.Response(undefined, {\n status: statusCode,\n statusText,\n });\n return new FetchError(`Fetching the Resource at [${fetchedUrl}] failed: [${failedResponse.status}] [${failedResponse.statusText}].`, failedResponse);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Create a new Thing with a URL added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setUrl]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to add a URL value to.\n * @param property Property for which to add the given URL value.\n * @param url URL to add to `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n */\nconst addUrl = (thing, property, url) => {\n var _a, _b;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n if (!isThing(url) && !internal_isValidUrl(url)) {\n throw new ValidValueUrlExpectedError(url);\n }\n const predicateIri = internal_toIriString(property);\n const existingPredicate = (_a = thing.predicates[predicateIri]) !== null && _a !== void 0 ? _a : {};\n const existingNamedNodes = (_b = existingPredicate.namedNodes) !== null && _b !== void 0 ? _b : [];\n let iriToAdd;\n if (isNamedNode(url)) {\n iriToAdd = url.value;\n }\n else if (typeof url === \"string\") {\n iriToAdd = url;\n }\n else if (isThingLocal(url)) {\n iriToAdd = url.url;\n }\n else {\n iriToAdd = asIri(url);\n }\n const updatedNamedNodes = freeze(existingNamedNodes.concat(internal_toIriString(iriToAdd)));\n const updatedPredicate = freeze({\n ...existingPredicate,\n namedNodes: updatedNamedNodes,\n });\n const updatedPredicates = freeze({\n ...thing.predicates,\n [predicateIri]: updatedPredicate,\n });\n const updatedThing = freeze({\n ...thing,\n predicates: updatedPredicates,\n });\n return updatedThing;\n};\n/** @hidden Alias for [[addUrl]] for those who prefer IRI terminology. */\nconst addIri = addUrl;\n/**\n * Create a new Thing with a boolean added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setBoolean]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to add a boolean value to.\n * @param property Property for which to add the given boolean value.\n * @param value Boolean to add to `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n */\nconst addBoolean = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addLiteralOfType(thing, property, serializeBoolean(value), xmlSchemaTypes.boolean);\n};\n/**\n * Create a new Thing with a datetime added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setDatetime]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to add a datetime value to.\n * @param property Property for which to add the given datetime value.\n * @param value Datetime to add to `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n */\nconst addDatetime = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addLiteralOfType(thing, property, serializeDatetime(value), xmlSchemaTypes.dateTime);\n};\n/**\n * Create a new Thing with a date added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setDate]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to add a date value to.\n * @param property Property for which to add the given date value.\n * @param value Date to add to `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n * @since 1.10.0\n */\nconst addDate = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addLiteralOfType(thing, property, serializeDate(value), xmlSchemaTypes.date);\n};\n/**\n * Create a new Thing with a time added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setDatetime]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to add a datetime value to.\n * @param property Property for which to add the given datetime value.\n * @param value time to add to `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n * @since 1.10.0\n */\nconst addTime = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addLiteralOfType(thing, property, serializeTime(value), xmlSchemaTypes.time);\n};\n/**\n * Create a new Thing with a decimal added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setDecimal]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to add a decimal value to.\n * @param property Property for which to add the given decimal value.\n * @param value Decimal to add to `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n */\nconst addDecimal = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addLiteralOfType(thing, property, serializeDecimal(value), xmlSchemaTypes.decimal);\n};\n/**\n * Create a new Thing with an integer added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setInteger]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to add an integer value to.\n * @param property Property for which to add the given integer value.\n * @param value Integer to add to `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n */\nconst addInteger = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addLiteralOfType(thing, property, serializeInteger(value), xmlSchemaTypes.integer);\n};\n/**\n * Create a new Thing with an English string added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setStringEnglish]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to add a localised string value to.\n * @param property Property for which to add the given string value.\n * @param value String to add to `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n * @since 1.13.0\n */\nfunction addStringEnglish(thing, property, value) {\n return addStringWithLocale(thing, property, value, \"en\");\n}\n/**\n * Create a new Thing with a localised string added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setStringWithLocale]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to add a localised string value to.\n * @param property Property for which to add the given string value.\n * @param value String to add to `thing` for the given `property`.\n * @param locale Locale of the added string.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n */\nfunction addStringWithLocale(thing, property, value, locale) {\n var _a, _b, _c;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n const normalizedLocale = normalizeLocale(locale);\n const existingPredicate = (_a = thing.predicates[predicateIri]) !== null && _a !== void 0 ? _a : {};\n const existingLangStrings = (_b = existingPredicate.langStrings) !== null && _b !== void 0 ? _b : {};\n const existingStringsInLocale = (_c = existingLangStrings[normalizedLocale]) !== null && _c !== void 0 ? _c : [];\n const updatedStringsInLocale = freeze(existingStringsInLocale.concat(value));\n const updatedLangStrings = freeze({\n ...existingLangStrings,\n [normalizedLocale]: updatedStringsInLocale,\n });\n const updatedPredicate = freeze({\n ...existingPredicate,\n langStrings: updatedLangStrings,\n });\n const updatedPredicates = freeze({\n ...thing.predicates,\n [predicateIri]: updatedPredicate,\n });\n const updatedThing = freeze({\n ...thing,\n predicates: updatedPredicates,\n });\n return updatedThing;\n}\n/**\n * Create a new Thing with an unlocalised string added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setStringNoLocale]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to add an unlocalised string value to.\n * @param property Property for which to add the given string value.\n * @param value String to add to `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n */\nconst addStringNoLocale = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addLiteralOfType(thing, property, value, xmlSchemaTypes.string);\n};\n/**\n * Create a new Thing with a Named Node added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setNamedNode]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @ignore This should not be needed due to the other add*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @param thing The [[Thing]] to add a Named Node to.\n * @param property Property for which to add a value.\n * @param value The Named Node to add.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n */\nfunction addNamedNode(thing, property, value) {\n return addUrl(thing, property, value.value);\n}\n/**\n * Create a new Thing with a Literal added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setLiteral]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @ignore This should not be needed due to the other add*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @param thing The [[Thing]] to add a Literal to.\n * @param property Property for which to add a value.\n * @param value The Literal to add.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n */\nfunction addLiteral(thing, property, value) {\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const typeIri = value.datatype.value;\n if (typeIri === xmlSchemaTypes.langString) {\n return addStringWithLocale(thing, property, value.value, value.language);\n }\n return addLiteralOfType(thing, property, value.value, value.datatype.value);\n}\n/**\n * Creates a new Thing with a Term added for a Property.\n *\n * This preserves existing values for the given Property. To replace them, see [[setTerm]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @ignore This should not be needed due to the other add*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @param thing The [[Thing]] to add a Term to.\n * @param property Property for which to add a value.\n * @param value The Term to add.\n * @returns A new Thing equal to the input Thing with the given value added for the given Property.\n * @since 0.3.0\n */\nfunction addTerm(thing, property, value) {\n var _a, _b;\n if (value.termType === \"NamedNode\") {\n return addNamedNode(thing, property, value);\n }\n if (value.termType === \"Literal\") {\n return addLiteral(thing, property, value);\n }\n if (value.termType === \"BlankNode\") {\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n const existingPredicate = (_a = thing.predicates[predicateIri]) !== null && _a !== void 0 ? _a : {};\n const existingBlankNodes = (_b = existingPredicate.blankNodes) !== null && _b !== void 0 ? _b : [];\n const updatedBlankNodes = freeze(existingBlankNodes.concat(getBlankNodeId(value)));\n const updatedPredicate = freeze({\n ...existingPredicate,\n blankNodes: updatedBlankNodes,\n });\n const updatedPredicates = freeze({\n ...thing.predicates,\n [predicateIri]: updatedPredicate,\n });\n const updatedThing = freeze({\n ...thing,\n predicates: updatedPredicates,\n });\n return updatedThing;\n }\n throw new Error(`Term type [${value.termType}] is not supported by @inrupt/solid-client.`);\n}\nfunction addLiteralOfType(thing, property, value, type) {\n var _a, _b, _c;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n const existingPredicate = (_a = thing.predicates[predicateIri]) !== null && _a !== void 0 ? _a : {};\n const existingLiterals = (_b = existingPredicate.literals) !== null && _b !== void 0 ? _b : {};\n const existingValuesOfType = (_c = existingLiterals[type]) !== null && _c !== void 0 ? _c : [];\n const updatedValuesOfType = freeze(existingValuesOfType.concat(value));\n const updatedLiterals = freeze({\n ...existingLiterals,\n [type]: updatedValuesOfType,\n });\n const updatedPredicate = freeze({\n ...existingPredicate,\n literals: updatedLiterals,\n });\n const updatedPredicates = freeze({\n ...thing.predicates,\n [predicateIri]: updatedPredicate,\n });\n const updatedThing = freeze({\n ...thing,\n predicates: updatedPredicates,\n });\n return updatedThing;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction removeAll(thing, property) {\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n const newPredicates = { ...thing.predicates };\n delete newPredicates[predicateIri];\n return freeze({\n ...thing,\n predicates: freeze(newPredicates),\n });\n}\n/**\n * Create a new Thing with the given URL removed for the given Property.\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to remove a URL value from.\n * @param property Property for which to remove the given URL value.\n * @param value URL to remove from `thing` for the given `Property`.\n * @returns A new Thing equal to the input Thing with the given value removed for the given Property.\n */\nconst removeUrl = (thing, property, value) => {\n var _a, _b, _c;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n if (!isThing(value) && !internal_isValidUrl(value)) {\n throw new ValidValueUrlExpectedError(value);\n }\n const iriToRemove = isThing(value)\n ? asIri(value)\n : internal_toIriString(value);\n const updatedNamedNodes = freeze((_c = (_b = (_a = thing.predicates[predicateIri]) === null || _a === void 0 ? void 0 : _a.namedNodes) === null || _b === void 0 ? void 0 : _b.filter((namedNode) => namedNode.toLowerCase() !== iriToRemove.toLowerCase())) !== null && _c !== void 0 ? _c : []);\n const updatedPredicate = freeze({\n ...thing.predicates[predicateIri],\n namedNodes: updatedNamedNodes,\n });\n const updatedPredicates = freeze({\n ...thing.predicates,\n [predicateIri]: updatedPredicate,\n });\n return freeze({\n ...thing,\n predicates: updatedPredicates,\n });\n};\n/** @hidden Alias of [[removeUrl]] for those who prefer IRI terminology. */\nconst removeIri = removeUrl;\n/**\n * Create a new Thing with the given boolean removed for the given Property.\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to remove a boolean value from.\n * @param property Property for which to remove the given boolean value.\n * @param value Boolean to remove from `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value removed for the given Property.\n */\nconst removeBoolean = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return removeLiteralMatching(thing, property, xmlSchemaTypes.boolean, (foundBoolean) => deserializeBoolean(foundBoolean) === value);\n};\n/**\n * Create a new Thing with the given datetime removed for the given Property.\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to remove a datetime value from.\n * @param property Property for which to remove the given datetime value.\n * @param value Datetime to remove from `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value removed for the given Property.\n */\nconst removeDatetime = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return removeLiteralMatching(thing, property, xmlSchemaTypes.dateTime, (foundDatetime) => { var _a; return ((_a = deserializeDatetime(foundDatetime)) === null || _a === void 0 ? void 0 : _a.getTime()) === value.getTime(); });\n};\n/**\n * Create a new Thing with the given date removed for the given Property.\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to remove a date value from.\n * @param property Property for which to remove the given date value.\n * @param value Date to remove from `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value removed for the given Property.\n * @since 1.10.0\n */\nconst removeDate = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return removeLiteralMatching(thing, property, xmlSchemaTypes.date, function (foundDate) {\n const deserializedDate = deserializeDate(foundDate);\n if (deserializedDate) {\n return (deserializedDate.getFullYear() === value.getFullYear() &&\n deserializedDate.getMonth() === value.getMonth() &&\n deserializedDate.getUTCDate() === value.getUTCDate());\n }\n return false;\n });\n};\n/**\n * Create a new Thing with the given datetime removed for the given Property.\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to remove a datetime value from.\n * @param property Property for which to remove the given datetime value.\n * @param value Time to remove from `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value removed for the given Property.\n * @since 1.10.0\n */\nconst removeTime = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return removeLiteralMatching(thing, property, xmlSchemaTypes.time, function (foundTime) {\n const deserializedTime = deserializeTime(foundTime);\n if (deserializedTime) {\n return (deserializedTime.hour === value.hour &&\n deserializedTime.minute === value.minute &&\n deserializedTime.second === value.second &&\n deserializedTime.millisecond === value.millisecond &&\n deserializedTime.timezoneHourOffset === value.timezoneHourOffset &&\n deserializedTime.timezoneMinuteOffset === value.timezoneMinuteOffset);\n }\n return false;\n });\n};\n/**\n * Create a new Thing with the given decimal removed for the given Property.\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to remove a decimal value from.\n * @param property Property for which to remove the given decimal value.\n * @param value Decimal to remove from `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value removed for the given Property.\n */\nconst removeDecimal = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return removeLiteralMatching(thing, property, xmlSchemaTypes.decimal, (foundDecimal) => deserializeDecimal(foundDecimal) === value);\n};\n/**\n * Create a new Thing with the given integer removed for the given Property.\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to remove an integer value from.\n * @param property Property for which to remove the given integer value.\n * @param value Integer to remove from `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value removed for the given Property.\n */\nconst removeInteger = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return removeLiteralMatching(thing, property, xmlSchemaTypes.integer, (foundInteger) => deserializeInteger(foundInteger) === value);\n};\n/**\n * Create a new Thing with the given English string removed for the given Property.\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to remove a localised string value from.\n * @param property Property for which to remove the given localised string value.\n * @param value String to remove from `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value removed for the given Property.\n * @since 1.13.0\n */\nfunction removeStringEnglish(thing, property, value) {\n return removeStringWithLocale(thing, property, value, \"en\");\n}\n/**\n * Create a new Thing with the given localised string removed for the given Property.\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to remove a localised string value from.\n * @param property Property for which to remove the given localised string value.\n * @param value String to remove from `thing` for the given `property`.\n * @param locale Locale of the string to remove.\n * @returns A new Thing equal to the input Thing with the given value removed for the given Property.\n */\nfunction removeStringWithLocale(thing, property, value, locale) {\n var _a, _b;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n const existingLangStrings = (_b = (_a = thing.predicates[predicateIri]) === null || _a === void 0 ? void 0 : _a.langStrings) !== null && _b !== void 0 ? _b : {};\n const matchingLocale = Object.keys(existingLangStrings).find((existingLocale) => normalizeLocale(existingLocale) === normalizeLocale(locale) &&\n Array.isArray(existingLangStrings[existingLocale]) &&\n existingLangStrings[existingLocale].length > 0);\n if (typeof matchingLocale !== \"string\") {\n // Nothing to remove.\n return thing;\n }\n const existingStringsInLocale = existingLangStrings[matchingLocale];\n const updatedStringsInLocale = freeze(existingStringsInLocale.filter((existingString) => existingString !== value));\n const updatedLangStrings = freeze({\n ...existingLangStrings,\n [matchingLocale]: updatedStringsInLocale,\n });\n const updatedPredicate = freeze({\n ...thing.predicates[predicateIri],\n langStrings: updatedLangStrings,\n });\n const updatedPredicates = freeze({\n ...thing.predicates,\n [predicateIri]: updatedPredicate,\n });\n return freeze({\n ...thing,\n predicates: updatedPredicates,\n });\n}\n/**\n * Create a new Thing with the given unlocalised string removed for the given Property.\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to remove an unlocalised string value from.\n * @param property Property for which to remove the given string value.\n * @param value String to remove from `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value removed for the given Property.\n */\nconst removeStringNoLocale = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return removeLiteralMatching(thing, property, xmlSchemaTypes.string, (foundString) => foundString === value);\n};\n/**\n * @ignore This should not be needed due to the other remove*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @param thing Thing to remove a NamedNode value from.\n * @param property Property for which to remove the given NamedNode value.\n * @param value NamedNode to remove from `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value removed for the given Property.\n */\nfunction removeNamedNode(thing, property, value) {\n return removeUrl(thing, property, value.value);\n}\n/**\n * @ignore This should not be needed due to the other remove*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @param thing Thing to remove a Literal value from.\n * @param property Property for which to remove the given Literal value.\n * @param value Literal to remove from `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with the given value removed for the given Property.\n */\nfunction removeLiteral(thing, property, value) {\n var _a, _b, _c;\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const typeIri = value.datatype.value;\n if (typeIri === xmlSchemaTypes.langString) {\n return removeStringWithLocale(thing, property, value.value, value.language);\n }\n const predicateIri = internal_toIriString(property);\n const existingPredicateValues = (_a = thing.predicates[predicateIri]) !== null && _a !== void 0 ? _a : {};\n const existingLiterals = (_b = existingPredicateValues.literals) !== null && _b !== void 0 ? _b : {};\n const existingValuesOfType = (_c = existingLiterals[typeIri]) !== null && _c !== void 0 ? _c : [];\n const updatedValues = freeze(existingValuesOfType.filter((existingValue) => existingValue !== value.value));\n const updatedLiterals = freeze({\n ...existingLiterals,\n [typeIri]: updatedValues,\n });\n const updatedPredicate = freeze({\n ...existingPredicateValues,\n literals: updatedLiterals,\n });\n const updatedPredicates = freeze({\n ...thing.predicates,\n [predicateIri]: updatedPredicate,\n });\n const updatedThing = freeze({\n ...thing,\n predicates: updatedPredicates,\n });\n return updatedThing;\n}\n/**\n * @param thing Thing to remove a Literal value from.\n * @param property Property for which to remove the given Literal value.\n * @param type Data type that the Literal should be stored as.\n * @param matcher Function that returns true if the given value is an equivalent serialisation of the value to remove. For example, when removing a `false` boolean, the matcher should return true for both \"0\" and \"false\".\n */\nfunction removeLiteralMatching(thing, property, type, matcher) {\n var _a, _b, _c;\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n const predicateIri = internal_toIriString(property);\n const existingPredicateValues = (_a = thing.predicates[predicateIri]) !== null && _a !== void 0 ? _a : {};\n const existingLiterals = (_b = existingPredicateValues.literals) !== null && _b !== void 0 ? _b : {};\n const existingValuesOfType = (_c = existingLiterals[type]) !== null && _c !== void 0 ? _c : [];\n const updatedValues = freeze(existingValuesOfType.filter((existingValue) => !matcher(existingValue)));\n const updatedLiterals = freeze({\n ...existingLiterals,\n [type]: updatedValues,\n });\n const updatedPredicate = freeze({\n ...existingPredicateValues,\n literals: updatedLiterals,\n });\n const updatedPredicates = freeze({\n ...thing.predicates,\n [predicateIri]: updatedPredicate,\n });\n const updatedThing = freeze({\n ...thing,\n predicates: updatedPredicates,\n });\n return updatedThing;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Create a new Thing with existing values replaced by the given URL for the given Property.\n *\n * To preserve existing values, see [[addUrl]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to set a URL value on.\n * @param property Property for which to set the given URL value.\n * @param url URL to set on `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property.\n */\nconst setUrl = (thing, property, url) => {\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n if (!isThing(url) && !internal_isValidUrl(url)) {\n throw new ValidValueUrlExpectedError(url);\n }\n return addUrl(removeAll(thing, property), property, url);\n};\n/** @hidden Alias of [[setUrl]] for those who prefer IRI terminology. */\nconst setIri = setUrl;\n/**\n * Create a new Thing with existing values replaced by the given boolean for the given Property.\n *\n * To preserve existing values, see [[addBoolean]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to set a boolean value on.\n * @param property Property for which to set the given boolean value.\n * @param value Boolean to set on `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property.\n */\nconst setBoolean = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addBoolean(removeAll(thing, property), property, value);\n};\n/**\n * Create a new Thing with existing values replaced by the given datetime for the given Property.\n *\n * To preserve existing values, see [[addDatetime]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to set an datetime value on.\n * @param property Property for which to set the given datetime value.\n * @param value Datetime to set on `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property.\n */\nconst setDatetime = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addDatetime(removeAll(thing, property), property, value);\n};\n/**\n * Create a new Thing with existing values replaced by the given date for the given Property.\n *\n * To preserve existing values, see [[addDate]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to set an date value on.\n * @param property Property for which to set the given date value.\n * @param value Date to set on `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property.\n * @since 1.10.0\n */\nconst setDate = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addDate(removeAll(thing, property), property, value);\n};\n/**\n * Create a new Thing with existing values replaced by the given time for the given Property.\n *\n * To preserve existing values, see [[addTime]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to set an time value on.\n * @param property Property for which to set the given time value.\n * @param value time to set on `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property.\n * @since 1.10.0\n */\nconst setTime = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addTime(removeAll(thing, property), property, value);\n};\n/**\n * Create a new Thing with existing values replaced by the given decimal for the given Property.\n *\n * To preserve existing values, see [[addDecimal]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to set a decimal value on.\n * @param property Property for which to set the given decimal value.\n * @param value Decimal to set on `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property.\n */\nconst setDecimal = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addDecimal(removeAll(thing, property), property, value);\n};\n/**\n * Create a new Thing with existing values replaced by the given integer for the given Property.\n *\n * To preserve existing values, see [[addInteger]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to set an integer value on.\n * @param property Property for which to set the given integer value.\n * @param value Integer to set on `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property.\n */\nconst setInteger = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addInteger(removeAll(thing, property), property, value);\n};\n/**\n * Create a new Thing with existing values replaced by the given localised string for the given Property.\n *\n * To preserve existing values, see [[addStringWithLocale]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to set a localised string value on.\n * @param property Property for which to set the given localised string value.\n * @param value Localised string to set on `thing` for the given `property`.\n * @param locale Locale of the added string.\n * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property.\n */\nfunction setStringWithLocale(thing, property, value, locale) {\n internal_throwIfNotThing(thing);\n return addStringWithLocale(removeAll(thing, property), property, value, locale);\n}\n/**\n * Create a new Thing with existing values replaced by the given unlocalised string for the given Property.\n *\n * To preserve existing values, see [[addStringNoLocale]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @param thing Thing to set an unlocalised string value on.\n * @param property Property for which to set the given unlocalised string value.\n * @param value Unlocalised string to set on `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property.\n */\nconst setStringNoLocale = (thing, property, value) => {\n internal_throwIfNotThing(thing);\n return addStringNoLocale(removeAll(thing, property), property, value);\n};\n/**\n * Create a new Thing with existing values replaced by the given Named Node for the given Property.\n *\n * This replaces existing values for the given Property. To preserve them, see [[addNamedNode]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @ignore This should not be needed due to the other set*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @param thing The [[Thing]] to set a NamedNode on.\n * @param property Property for which to set the value.\n * @param value The NamedNode to set on `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property.\n */\nfunction setNamedNode(thing, property, value) {\n internal_throwIfNotThing(thing);\n return addNamedNode(removeAll(thing, property), property, value);\n}\n/**\n * Create a new Thing with existing values replaced by the given Literal for the given Property.\n *\n * This replaces existing values for the given Property. To preserve them, see [[addLiteral]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @ignore This should not be needed due to the other set*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @param thing The [[Thing]] to set a Literal on.\n * @param property Property for which to set the value.\n * @param value The Literal to set on `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property.\n */\nfunction setLiteral(thing, property, value) {\n internal_throwIfNotThing(thing);\n return addLiteral(removeAll(thing, property), property, value);\n}\n/**\n * Creates a new Thing with existing values replaced by the given Term for the given Property.\n *\n * This replaces existing values for the given Property. To preserve them, see [[addTerm]].\n *\n * The original `thing` is not modified; this function returns a cloned Thing with updated values.\n *\n * @ignore This should not be needed due to the other set*() functions. If you do find yourself needing it, please file a feature request for your use case.\n * @param thing The [[Thing]] to set a Term on.\n * @param property Property for which to set the value.\n * @param value The raw RDF/JS value to set on `thing` for the given `property`.\n * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property.\n * @since 0.3.0\n */\nfunction setTerm(thing, property, value) {\n internal_throwIfNotThing(thing);\n if (!internal_isValidUrl(property)) {\n throw new ValidPropertyUrlExpectedError(property);\n }\n return addTerm(removeAll(thing, property), property, value);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Create or modify a [[Thing]], setting multiple properties in a single expresssion.\n *\n * For example, you can create a new Thing and initialise several properties as follows:\n *\n * const me = buildThing()\n * .addUrl(rdf.type, schema.Person)\n * .addStringNoLocale(schema.givenName, \"Vincent\")\n * .build();\n *\n * Take note of the final call to `.build()` to obtain the actual Thing.\n *\n * @param init Optionally pass an existing [[Thing]] to modify the properties of. If left empty, `buildThing` will initialise a new Thing.\n * @returns a [[ThingBuilder]], a Fluent API that allows you to set multiple properties in a single expression.\n * @since 1.9.0\n */\nfunction buildThing(init = createThing()) {\n let thing = isThing(init) ? init : createThing(init);\n function getAdder(adder) {\n return (property, value) => {\n thing = adder(thing, property, value);\n return builder;\n };\n }\n function getSetter(setter) {\n return (property, value) => {\n thing = setter(thing, property, value);\n return builder;\n };\n }\n function getRemover(remover) {\n return (property, value) => {\n thing = remover(thing, property, value);\n return builder;\n };\n }\n const builder = {\n build: () => thing,\n addUrl: getAdder(addUrl),\n addIri: getAdder(addIri),\n addBoolean: getAdder(addBoolean),\n addDatetime: getAdder(addDatetime),\n addDate: getAdder(addDate),\n addTime: getAdder(addTime),\n addDecimal: getAdder(addDecimal),\n addInteger: getAdder(addInteger),\n addStringNoLocale: getAdder(addStringNoLocale),\n addStringEnglish: (property, value) => {\n thing = addStringWithLocale(thing, property, value, \"en\");\n return builder;\n },\n addStringWithLocale: (property, value, locale) => {\n thing = addStringWithLocale(thing, property, value, locale);\n return builder;\n },\n addNamedNode: getAdder(addNamedNode),\n addLiteral: getAdder(addLiteral),\n addTerm: getAdder(addTerm),\n setUrl: getSetter(setUrl),\n setIri: getSetter(setIri),\n setBoolean: getSetter(setBoolean),\n setDatetime: getSetter(setDatetime),\n setDate: getSetter(setDate),\n setTime: getSetter(setTime),\n setDecimal: getSetter(setDecimal),\n setInteger: getSetter(setInteger),\n setStringNoLocale: getSetter(setStringNoLocale),\n setStringEnglish: (property, value) => {\n thing = setStringWithLocale(thing, property, value, \"en\");\n return builder;\n },\n setStringWithLocale: (property, value, locale) => {\n thing = setStringWithLocale(thing, property, value, locale);\n return builder;\n },\n setNamedNode: getSetter(setNamedNode),\n setLiteral: getSetter(setLiteral),\n setTerm: getSetter(setTerm),\n removeAll: (property) => {\n thing = removeAll(thing, property);\n return builder;\n },\n removeUrl: getRemover(removeUrl),\n removeIri: getRemover(removeIri),\n removeBoolean: getRemover(removeBoolean),\n removeDatetime: getRemover(removeDatetime),\n removeDate: getRemover(removeDate),\n removeTime: getRemover(removeTime),\n removeDecimal: getRemover(removeDecimal),\n removeInteger: getRemover(removeInteger),\n removeStringNoLocale: getRemover(removeStringNoLocale),\n removeStringEnglish: (property, value) => buildThing(removeStringWithLocale(thing, property, value, \"en\")),\n removeStringWithLocale: (property, value, locale) => buildThing(removeStringWithLocale(thing, property, value, locale)),\n removeNamedNode: getRemover(removeNamedNode),\n removeLiteral: getRemover(removeLiteral),\n };\n return builder;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Function for use in unit tests to mock a [[Thing]] with a given URL.\n *\n * Warning: do not use this function in actual production code.\n * This function initialises a new empty Thing and sets its URL to a given URL.\n * This is useful to mock a Thing in tests of code that call e.g.\n * [[asUrl]].\n *\n * @param url The URL that the mocked Thing pretends identifies it.\n * @returns A new Thing, pretending to be identified by the given URL.\n * @since 0.2.0\n */\nfunction mockThingFrom(url) {\n const iri = internal_toIriString(url);\n const thing = {\n type: \"Subject\",\n predicates: {},\n url: iri,\n };\n return thing;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @param linkedAccessResource A Resource exposed via the Link header of another Resource with rel=\"acl\".\n * @returns Whether that Resource is an ACP ACR or not (in which case it's likely a WAC ACL).\n */\nfunction isAcr(linkedAccessResource) {\n const relTypeLinks = getLinkedResourceUrlAll(linkedAccessResource).type;\n return (Array.isArray(relTypeLinks) &&\n relTypeLinks.includes(acp.AccessControlResource));\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * This (currently internal) function fetches the ACL indicated in the [[WithServerResourceInfo]]\n * attached to a resource.\n *\n * @internal\n * @param resourceInfo The Resource info with the ACL URL\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters).\n */\nasync function internal_fetchAcl(resourceInfo, options = internal_defaultFetchOptions) {\n if (!hasAccessibleAcl(resourceInfo)) {\n return {\n resourceAcl: null,\n fallbackAcl: null,\n };\n }\n try {\n const resourceAcl = await internal_fetchResourceAcl(resourceInfo, options);\n const acl = resourceAcl === null\n ? {\n resourceAcl: null,\n fallbackAcl: await internal_fetchFallbackAcl(resourceInfo, options),\n }\n : { resourceAcl, fallbackAcl: null };\n return acl;\n }\n catch (e) {\n /* istanbul ignore else: fetchResourceAcl swallows all non-AclIsAcrErrors */\n if (e instanceof AclIsAcrError) {\n return {\n resourceAcl: null,\n fallbackAcl: null,\n };\n }\n /* istanbul ignore next: fetchResourceAcl swallows all non-AclIsAcrErrors */\n throw e;\n }\n}\n/** @internal */\nasync function internal_fetchResourceAcl(dataset, options = internal_defaultFetchOptions) {\n if (!hasAccessibleAcl(dataset)) {\n return null;\n }\n try {\n const aclSolidDataset = await getSolidDataset(dataset.internal_resourceInfo.aclUrl, options);\n if (isAcr(aclSolidDataset)) {\n throw new AclIsAcrError(dataset, aclSolidDataset);\n }\n return freeze({\n ...aclSolidDataset,\n internal_accessTo: getSourceUrl(dataset),\n });\n }\n catch (e) {\n if (e instanceof AclIsAcrError) {\n throw e;\n }\n // Since a Solid server adds a `Link` header to an ACL even if that ACL does not exist,\n // failure to fetch the ACL is expected to happen - we just return `null` and let callers deal\n // with it.\n return null;\n }\n}\n/** @internal */\nasync function internal_fetchFallbackAcl(resource, options = internal_defaultFetchOptions) {\n const resourceUrl = new URL(getSourceUrl(resource));\n const resourcePath = resourceUrl.pathname;\n // Note: we're currently assuming that the Origin is the root of the Pod. However, it is not yet\n // set in stone that that will always be the case. We might need to check the Container's\n // metadata at some point in time to check whether it is actually the root of the Pod.\n // See: https://github.com/solid/specification/issues/153#issuecomment-624630022\n if (resourcePath === \"/\") {\n // We're already at the root, so there's no Container we can retrieve:\n return null;\n }\n const containerPath = internal_getContainerPath(resourcePath);\n const containerIri = new URL(containerPath, resourceUrl.origin).href;\n const containerInfo = await getResourceInfo(containerIri, options);\n if (!hasAccessibleAcl(containerInfo)) {\n // If the current user does not have access to this Container's ACL,\n // we cannot determine whether its ACL is the one that applies. Thus, return null:\n return null;\n }\n const containerAcl = await internal_fetchResourceAcl(containerInfo, options);\n if (containerAcl === null) {\n return internal_fetchFallbackAcl(containerInfo, options);\n }\n return containerAcl;\n}\n/**\n * Given the path to a Resource, get the URL of the Container one level up in the hierarchy.\n * @param resourcePath The path of the Resource of which we need to determine the Container's path.\n * @hidden For internal use only.\n */\nfunction internal_getContainerPath(resourcePath) {\n const resourcePathWithoutTrailingSlash = resourcePath.substring(resourcePath.length - 1) === \"/\"\n ? resourcePath.substring(0, resourcePath.length - 1)\n : resourcePath;\n const containerPath = `${resourcePath.substring(0, resourcePathWithoutTrailingSlash.lastIndexOf(\"/\"))}/`;\n return containerPath;\n}\n/** @internal */\nfunction internal_getAclRules(aclDataset) {\n const things = getThingAll(aclDataset);\n return things.filter(isAclRule);\n}\nfunction isAclRule(thing) {\n return getIriAll(thing, rdf.type).includes(acl.Authorization);\n}\n/** @internal */\nfunction internal_getResourceAclRulesForResource(aclRules, resource) {\n return aclRules.filter((rule) => appliesToResource(rule, resource));\n}\nfunction appliesToResource(aclRule, resource) {\n return getIriAll(aclRule, acl.accessTo).includes(resource);\n}\n/** @internal */\nfunction internal_getDefaultAclRulesForResource(aclRules, resource) {\n return aclRules.filter((rule) => isDefaultForResource(rule, resource));\n}\nfunction isDefaultForResource(aclRule, resource) {\n return (getIriAll(aclRule, acl.default).includes(resource) ||\n getIriAll(aclRule, acl.defaultForNew).includes(resource));\n}\n/** @internal */\nfunction internal_getAccess(rule) {\n const ruleAccessModes = getIriAll(rule, acl.mode);\n const writeAccess = ruleAccessModes.includes(internal_accessModeIriStrings.write);\n return writeAccess\n ? {\n read: ruleAccessModes.includes(internal_accessModeIriStrings.read),\n append: true,\n write: true,\n control: ruleAccessModes.includes(internal_accessModeIriStrings.control),\n }\n : {\n read: ruleAccessModes.includes(internal_accessModeIriStrings.read),\n append: ruleAccessModes.includes(internal_accessModeIriStrings.append),\n write: false,\n control: ruleAccessModes.includes(internal_accessModeIriStrings.control),\n };\n}\n/** @internal */\nfunction internal_combineAccessModes(modes) {\n return modes.reduce((accumulator, current) => {\n const writeAccess = accumulator.write || current.write;\n return writeAccess\n ? {\n read: accumulator.read || current.read,\n append: true,\n write: true,\n control: accumulator.control || current.control,\n }\n : {\n read: accumulator.read || current.read,\n append: accumulator.append || current.append,\n write: false,\n control: accumulator.control || current.control,\n };\n }, { read: false, append: false, write: false, control: false });\n}\n/** @internal */\nfunction internal_removeEmptyAclRules(aclDataset) {\n const aclRules = internal_getAclRules(aclDataset);\n const aclRulesToRemove = aclRules.filter(isEmptyAclRule);\n // Is this too clever? It iterates over aclRulesToRemove, one by one removing them from aclDataset.\n const updatedAclDataset = aclRulesToRemove.reduce(removeThing, aclDataset);\n return updatedAclDataset;\n}\nfunction isEmptyAclRule(aclRule) {\n // If there are Quads in there unrelated to Access Control,\n // this is not an empty ACL rule that can be deleted:\n if (subjectToRdfJsQuads(aclRule.predicates, DataFactory.namedNode(aclRule.url), DataFactory.defaultGraph()).some((quad) => !isAclQuad(quad))) {\n return false;\n }\n // If the rule does not apply to any Resource, it is no longer working:\n if (getIri(aclRule, acl.accessTo) === null &&\n getIri(aclRule, acl.default) === null &&\n getIri(aclRule, acl.defaultForNew) === null) {\n return true;\n }\n // If the rule does not specify Access Modes, it is no longer working:\n if (getIri(aclRule, acl.mode) === null) {\n return true;\n }\n // If the rule does not specify whom it applies to, it is no longer working:\n if (getIri(aclRule, acl.agent) === null &&\n getIri(aclRule, acl.agentGroup) === null &&\n getIri(aclRule, acl.agentClass) === null) {\n return true;\n }\n return false;\n}\nfunction isAclQuad(quad) {\n const { predicate } = quad;\n const { object } = quad;\n if (predicate.equals(DataFactory.namedNode(rdf.type)) &&\n object.equals(DataFactory.namedNode(acl.Authorization))) {\n return true;\n }\n if (predicate.equals(DataFactory.namedNode(acl.accessTo)) ||\n predicate.equals(DataFactory.namedNode(acl.default)) ||\n predicate.equals(DataFactory.namedNode(acl.defaultForNew))) {\n return true;\n }\n if (predicate.equals(DataFactory.namedNode(acl.mode)) &&\n Object.values(internal_accessModeIriStrings).some((mode) => object.equals(DataFactory.namedNode(mode)))) {\n return true;\n }\n if (predicate.equals(DataFactory.namedNode(acl.agent)) ||\n predicate.equals(DataFactory.namedNode(acl.agentGroup)) ||\n predicate.equals(DataFactory.namedNode(acl.agentClass))) {\n return true;\n }\n if (predicate.equals(DataFactory.namedNode(acl.origin))) {\n return true;\n }\n return false;\n}\n/**\n * IRIs of potential Access Modes\n * @internal\n */\nconst internal_accessModeIriStrings = {\n read: \"http://www.w3.org/ns/auth/acl#Read\",\n append: \"http://www.w3.org/ns/auth/acl#Append\",\n write: \"http://www.w3.org/ns/auth/acl#Write\",\n control: \"http://www.w3.org/ns/auth/acl#Control\",\n};\n/** @internal\n * This function finds, among a set of ACL rules, the ones granting access to a given entity (the target)\n * and identifying it with a specific property (`acl:agent` or `acl:agentGroup`).\n * @param aclRules The set of rules to filter\n * @param targetIri The IRI of the target\n * @param targetType The property linking the rule to the target\n */\nfunction internal_getAclRulesForIri(aclRules, targetIri, targetType) {\n return aclRules.filter((rule) => getIriAll(rule, targetType).includes(targetIri));\n}\n/** @internal\n * This function transforms a given set of rules into a map associating the IRIs\n * of the entities to which permissions are granted by these rules, and the permissions\n * granted to them. Additionally, it filters these entities based on the predicate\n * that refers to them in the rule.\n */\nfunction internal_getAccessByIri(aclRules, targetType) {\n const targetIriAccess = {};\n aclRules.forEach((rule) => {\n const ruleTargetIri = getIriAll(rule, targetType);\n const access = internal_getAccess(rule);\n // A rule might apply to multiple agents. If multiple rules apply to the same agent, the Access\n // Modes granted by those rules should be combined:\n ruleTargetIri.forEach((targetIri) => {\n targetIriAccess[targetIri] =\n typeof targetIriAccess[targetIri] === \"undefined\"\n ? access\n : internal_combineAccessModes([targetIriAccess[targetIri], access]);\n });\n });\n return targetIriAccess;\n}\n/**\n * Initialises a new ACL Rule that grants some access - but does not yet specify to whom.\n *\n * @hidden This is an internal utility function that should not be used directly by downstreams.\n * @param access Access mode that this Rule will grant\n */\nfunction internal_initialiseAclRule(access) {\n let newRule = createThing();\n newRule = setIri(newRule, rdf.type, acl.Authorization);\n if (access.read) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.read);\n }\n if (access.append && !access.write) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.append);\n }\n if (access.write) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.write);\n }\n if (access.control) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.control);\n }\n return newRule;\n}\n/**\n * Creates a new ACL Rule with the same ACL values as the input ACL Rule, but having a different IRI.\n *\n * Note that non-ACL values will not be copied over.\n *\n * @hidden This is an internal utility function that should not be used directly by downstreams.\n * @param sourceRule ACL rule to duplicate.\n */\nfunction internal_duplicateAclRule(sourceRule) {\n let targetRule = createThing();\n targetRule = setIri(targetRule, rdf.type, acl.Authorization);\n function copyIris(inputRule, outputRule, predicate) {\n return getIriAll(inputRule, predicate).reduce((outputRule, iriTarget) => addIri(outputRule, predicate, iriTarget), outputRule);\n }\n targetRule = copyIris(sourceRule, targetRule, acl.accessTo);\n targetRule = copyIris(sourceRule, targetRule, acl.default);\n targetRule = copyIris(sourceRule, targetRule, acl.defaultForNew);\n targetRule = copyIris(sourceRule, targetRule, acl.agent);\n targetRule = copyIris(sourceRule, targetRule, acl.agentGroup);\n targetRule = copyIris(sourceRule, targetRule, acl.agentClass);\n targetRule = copyIris(sourceRule, targetRule, acl.origin);\n targetRule = copyIris(sourceRule, targetRule, acl.mode);\n return targetRule;\n}\nfunction internal_setAcl(resource, acl) {\n return Object.assign(internal_cloneResource(resource), { internal_acl: acl });\n}\nconst supportedActorPredicates = [\n acl.agent,\n acl.agentClass,\n acl.agentGroup,\n acl.origin,\n];\n/**\n * Given an ACL Rule, returns two new ACL Rules that cover all the input Rule's use cases,\n * except for giving the given Actor access to the given Resource.\n *\n * @param rule The ACL Rule that should no longer apply for a given Actor to a given Resource.\n * @param actor The Actor that should be removed from the Rule for the given Resource.\n * @param resourceIri The Resource to which the Rule should no longer apply for the given Actor.\n * @returns A tuple with the original ACL Rule without the given Actor, and a new ACL Rule for the given Actor for the remaining Resources, respectively.\n */\nfunction internal_removeActorFromRule(rule, actor, actorPredicate, resourceIri, ruleType) {\n // If the existing Rule does not apply to the given Actor, we don't need to split up.\n // Without this check, we'd be creating a new rule for the given Actor (ruleForOtherTargets)\n // that would give it access it does not currently have:\n if (!getIriAll(rule, actorPredicate).includes(actor)) {\n const emptyRule = internal_initialiseAclRule({\n read: false,\n append: false,\n write: false,\n control: false,\n });\n return [rule, emptyRule];\n }\n // The existing rule will keep applying to Actors other than the given one:\n const ruleWithoutActor = removeIri(rule, actorPredicate, actor);\n // The actor might have been given other access in the existing rule, so duplicate it...\n let ruleForOtherTargets = internal_duplicateAclRule(rule);\n // ...but remove access to the original Resource...\n ruleForOtherTargets = removeIri(ruleForOtherTargets, ruleType === \"resource\" ? acl.accessTo : acl.default, resourceIri);\n // Prevents the legacy predicate 'acl:defaultForNew' to lead to privilege escalation\n if (ruleType === \"default\") {\n ruleForOtherTargets = removeIri(ruleForOtherTargets, acl.defaultForNew, resourceIri);\n }\n // ...and only apply the new Rule to the given Actor (because the existing Rule covers the others):\n ruleForOtherTargets = setIri(ruleForOtherTargets, actorPredicate, actor);\n supportedActorPredicates\n .filter((predicate) => predicate !== actorPredicate)\n .forEach((predicate) => {\n ruleForOtherTargets = removeAll(ruleForOtherTargets, predicate);\n });\n return [ruleWithoutActor, ruleForOtherTargets];\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n * Modifies the resource ACL (Access Control List) to set the Access Modes for the given Agent.\n * Specifically, the function returns a new resource ACL initialised with the given ACL and\n * new rules for the Actor's access.\n *\n * If rules for Actor's access already exist in the given ACL, in the returned ACL,\n * they are replaced by the new rules.\n *\n * This function does not modify:\n *\n * - Access Modes granted indirectly to Actors through other ACL rules, e.g., public or group-specific permissions.\n * - Access Modes granted to Actors for the child Resources if the associated Resource is a Container.\n * - The original ACL.\n *\n * @param aclDataset The SolidDataset that contains Access-Control List rules.\n * @param actor The Actor to grant specific Access Modes.\n * @param access The Access Modes to grant to the Actor for the Resource.\n * @returns A new resource ACL initialised with the given `aclDataset` and `access` for the `agent`.\n */\nfunction internal_setActorAccess$2(aclDataset, access, actorPredicate, accessType, actor) {\n // First make sure that none of the pre-existing rules in the given ACL SolidDataset\n // give the Agent access to the Resource:\n let filteredAcl = aclDataset;\n getThingAll(aclDataset).forEach((aclRule) => {\n // Obtain both the Rule that no longer includes the given Actor,\n // and a new Rule that includes all ACL Quads\n // that do not pertain to the given Actor-Resource combination.\n // Note that usually, the latter will no longer include any meaningful statements;\n // we'll clean them up afterwards.\n const [filteredRule, remainingRule] = internal_removeActorFromRule(aclRule, actor, actorPredicate, aclDataset.internal_accessTo, accessType);\n filteredAcl = setThing(filteredAcl, filteredRule);\n filteredAcl = setThing(filteredAcl, remainingRule);\n });\n // Create a new Rule that only grants the given Actor the given Access Modes:\n let newRule = internal_initialiseAclRule(access);\n newRule = setIri(newRule, accessType === \"resource\" ? acl.accessTo : acl.default, aclDataset.internal_accessTo);\n newRule = setIri(newRule, actorPredicate, actor);\n const updatedAcl = setThing(filteredAcl, newRule);\n // Remove any remaining Rules that do not contain any meaningful statements:\n return internal_removeEmptyAclRules(updatedAcl);\n}\nfunction internal_setResourceAcl(resource, acl) {\n const newAcl = {\n resourceAcl: acl,\n fallbackAcl: null,\n };\n return internal_setAcl(resource, newAcl);\n}\nfunction internal_getResourceAcl(resource) {\n return resource.internal_acl.resourceAcl;\n}\n/**\n * This error indicates that, if we're following a Link with rel=\"acl\",\n * it does not result in a WAC ACL, but in an ACP ACR.\n */\nclass AclIsAcrError extends Error {\n constructor(sourceResource, aclResource) {\n super(`[${getSourceIri(sourceResource)}] is governed by Access Control Policies in [${getSourceIri(aclResource)}] rather than by Web Access Control.`);\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Verify whether a given SolidDataset was fetched together with its Access Control List.\n *\n * @param dataset A [[SolidDataset]] that may have its ACLs attached.\n * @returns True if `dataset` was fetched together with its ACLs.\n */\nfunction hasAcl(dataset) {\n const potentialAcl = dataset;\n return typeof potentialAcl.internal_acl === \"object\";\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Verifies whether the given Resource has a resource ACL (Access Control List) attached.\n *\n * The [[hasResourceAcl]] function checks that:\n * - a given Resource has a resource ACL attached, and\n * - the user calling [[hasResourceAcl]] has Control access to the Resource.\n *\n * To retrieve a Resource with its ACLs, see [[getSolidDatasetWithAcl]].\n *\n * @param resource A Resource that might have an ACL attached.\n * @returns `true` if the Resource has a resource ACL attached that is accessible by the user.\n */\nfunction hasResourceAcl(resource) {\n return (resource.internal_acl.resourceAcl !== null &&\n getSourceUrl(resource) ===\n resource.internal_acl.resourceAcl.internal_accessTo &&\n resource.internal_resourceInfo.aclUrl ===\n getSourceUrl(resource.internal_acl.resourceAcl));\n}\n/**\n * Experimental: fetch a SolidDataset and its associated Access Control List.\n *\n * This is an experimental function that fetches both a Resource, the linked ACL Resource (if\n * available), and the ACL that applies to it if the linked ACL Resource is not available. This can\n * result in many HTTP requests being executed, in lieu of the Solid spec mandating servers to\n * provide this info in a single request. Therefore, and because this function is still\n * experimental, prefer [[getSolidDataset]] instead.\n *\n * If the Resource does not advertise the ACL Resource (because the authenticated user does not have\n * access to it), the `acl` property in the returned value will be null. `acl.resourceAcl` will be\n * undefined if the Resource's linked ACL Resource could not be fetched (because it does not exist),\n * and `acl.fallbackAcl` will be null if the applicable Container's ACL is not accessible to the\n * authenticated user.\n *\n * @param url URL of the SolidDataset to fetch.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns A SolidDataset and the ACLs that apply to it, if available to the authenticated user.\n */\nasync function getSolidDatasetWithAcl(url, options = internal_defaultFetchOptions) {\n const solidDataset = await getSolidDataset(url, options);\n const acl = await internal_fetchAcl(solidDataset, options);\n return internal_setAcl(solidDataset, acl);\n}\n/**\n * ```{note} This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Retrieves a file, its resource ACL (Access Control List) if available,\n * and its fallback ACL from a URL and returns them as a blob.\n *\n * If the user calling the function does not have access to the file's resource ACL,\n * [[hasAccessibleAcl]] on the returned blob returns false.\n * If the user has access to the file's resource ACL but the resource ACL does not exist,\n * [[getResourceAcl]] on the returned blob returns null.\n * If the fallback ACL is inaccessible by the user,\n * [[getFallbackAcl]] on the returned blob returns null.\n *\n * ```{tip}\n * To retrieve the ACLs, the function results in multiple HTTP requests rather than a single\n * request as mandated by the Solid spec. As such, prefer [[getFile]] instead if you do not need the ACL.\n * ```\n *\n * @param url The URL of the fetched file\n * @param options Fetching options: a custom fetcher and/or headers.\n * @returns A file and its ACLs, if available to the authenticated user, as a blob.\n * @since 0.2.0\n */\nasync function getFileWithAcl(input, options = internal_defaultFetchOptions) {\n const file = await getFile(input, options);\n const acl = await internal_fetchAcl(file, options);\n return internal_setAcl(file, acl);\n}\n/**\n * Experimental: fetch a Resource's metadata and its associated Access Control List.\n *\n * This is an experimental function that fetches both a Resource's metadata, the linked ACL Resource (if\n * available), and the ACL that applies to it if the linked ACL Resource is not available (if accessible). This can\n * result in many HTTP requests being executed, in lieu of the Solid spec mandating servers to\n * provide this info in a single request.\n *\n * If the Resource's linked ACL Resource could not be fetched (because it does not exist, or because\n * the authenticated user does not have access to it), `acl.resourceAcl` will be `null`. If the\n * applicable Container's ACL is not accessible to the authenticated user, `acl.fallbackAcl` will be\n * `null`.\n *\n * @param url URL of the SolidDataset to fetch.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns A Resource's metadata and the ACLs that apply to the Resource, if available to the authenticated user.\n */\nasync function getResourceInfoWithAcl(url, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfo(url, options);\n const acl = await internal_fetchAcl(resourceInfo, options);\n return internal_setAcl(resourceInfo, acl);\n}\nfunction getResourceAcl(resource) {\n if (!hasResourceAcl(resource)) {\n return null;\n }\n return resource.internal_acl.resourceAcl;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Verifies whether the given Resource has a fallback ACL (Access Control List) attached.\n *\n * A fallback ACL for a Resource is inherited from the Resource's parent Container\n * (or another of its ancestor Containers) and applies if the Resource does\n * not have its own resource ACL.\n *\n * The [[hasFallbackAcl]] function checks that:\n * - a given Resource has a fallback ACL attached, and\n * - the user calling [[hasFallbackAcl]] has Control access to the Container\n * from which the Resource inherits its ACL.\n *\n * To retrieve a Resource with its ACLs, see [[getSolidDatasetWithAcl]].\n *\n * @param resource A [[SolidDataset]] that might have a fallback ACL attached.\n *\n * @returns `true` if the Resource has a fallback ACL attached that is accessible to the user.\n */\nfunction hasFallbackAcl(resource) {\n return resource.internal_acl.fallbackAcl !== null;\n}\nfunction getFallbackAcl(dataset) {\n if (!hasFallbackAcl(dataset)) {\n return null;\n }\n return dataset.internal_acl.fallbackAcl;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Creates an empty resource ACL (Access Control List) for a given Resource.\n *\n * @param targetResource A Resource that does not have its own ACL yet (see [[hasResourceAcl]]).\n * @returns An empty resource ACL for the given Resource.\n */\nfunction createAcl(targetResource) {\n const emptyResourceAcl = freeze({\n ...createSolidDataset(),\n internal_accessTo: getSourceUrl(targetResource),\n internal_resourceInfo: {\n sourceIri: targetResource.internal_resourceInfo.aclUrl,\n isRawData: false,\n linkedResources: {},\n },\n });\n return emptyResourceAcl;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Creates a resource ACL (Access Control List), initialised from the fallback ACL\n * inherited from the given Resource's Container (or another of its ancestor Containers).\n * That is, the new ACL has the same rules/entries as the fallback ACL that currently\n * applies to the Resource.\n *\n * @param resource A Resource without its own resource ACL (see [[hasResourceAcl]]) but with an accessible fallback ACL (see [[hasFallbackAcl]]).\n * @returns A resource ACL initialised with the rules/entries from the Resource's fallback ACL.\n */\nfunction createAclFromFallbackAcl(resource) {\n const emptyResourceAcl = createAcl(resource);\n const fallbackAclRules = internal_getAclRules(resource.internal_acl.fallbackAcl);\n const defaultAclRules = internal_getDefaultAclRulesForResource(fallbackAclRules, resource.internal_acl.fallbackAcl.internal_accessTo);\n const newAclRules = defaultAclRules.map((rule) => {\n rule = removeAll(rule, acl.default);\n rule = removeAll(rule, acl.defaultForNew);\n rule = setIri(rule, acl.accessTo, getSourceUrl(resource));\n rule = setIri(rule, acl.default, getSourceUrl(resource));\n return rule;\n });\n // Iterate over every ACL Rule we want to import, inserting them into `emptyResourceAcl` one by one:\n const initialisedResourceAcl = newAclRules.reduce(setThing, emptyResourceAcl);\n return initialisedResourceAcl;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Saves the resource ACL for a Resource.\n *\n * @param resource The Resource to which the given resource ACL applies.\n * @param resourceAcl An [[AclDataset]] whose ACL Rules will apply to `resource`.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n */\nasync function saveAclFor(resource, resourceAcl, options = internal_defaultFetchOptions) {\n if (!hasAccessibleAcl(resource)) {\n throw new Error(`Could not determine the location of the ACL for the Resource at [${getSourceUrl(resource)}]; possibly the current user does not have Control access to that Resource. Try calling \\`hasAccessibleAcl()\\` before calling \\`saveAclFor()\\`.`);\n }\n const savedDataset = await saveSolidDatasetAt(resource.internal_resourceInfo.aclUrl, resourceAcl, options);\n const savedAclDataset = {\n ...savedDataset,\n internal_accessTo: getSourceUrl(resource),\n };\n return savedAclDataset;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Removes the resource ACL (Access Control List) from a Resource.\n *\n * Once the resource ACL is removed from the Resource, the Resource relies on the\n * fallback ACL inherited from the Resource's parent Container (or another of its ancestor Containers).\n *\n * @param resource The Resource for which you want to delete the ACL.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n */\nasync function deleteAclFor(resource, options = internal_defaultFetchOptions) {\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const response = await config.fetch(resource.internal_resourceInfo.aclUrl, {\n method: \"DELETE\",\n });\n if (!response.ok) {\n throw new Error(`Deleting the ACL of the Resource at [${getSourceUrl(resource)}] failed: [${response.status}] [${response.statusText}].`);\n }\n const storedResource = Object.assign(internal_cloneResource(resource), {\n acl: {\n resourceAcl: null,\n },\n });\n return storedResource;\n}\n/**\n * Given a [[SolidDataset]], verify whether its Access Control List is accessible to the current user.\n *\n * This should generally only be true for SolidDatasets fetched by\n * [[getSolidDatasetWithAcl]].\n *\n * Please note that the Web Access Control specification is not yet finalised, and hence, this\n * function is still experimental and can change in a non-major release.\n *\n * @param dataset A [[SolidDataset]].\n * @returns Whether the given `dataset` has a an ACL that is accessible to the current user.\n */\nfunction hasAccessibleAcl(dataset) {\n return typeof dataset.internal_resourceInfo.aclUrl === \"string\";\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns an Agent's explicitly-granted Access Modes for the given Resource.\n *\n * The function does not return Access Modes granted indirectly to the Agent through other\n * ACL rules, e.g., public or group-specific permissions.\n *\n * @param resourceInfo Information about the Resource to which the given Agent may have been granted access.\n * @param agent WebID of the Agent for which to retrieve what access it has to the Resource.\n * @returns Access Modes that have been explicitly granted to the Agent for the given Resource, or `null` if it could not be determined (e.g. because the current user does not have Control access to a given Resource or its Container).\n */\nfunction getAgentAccess$5(resourceInfo, agent) {\n if (hasResourceAcl(resourceInfo)) {\n return getAgentResourceAccess(resourceInfo.internal_acl.resourceAcl, agent);\n }\n if (hasFallbackAcl(resourceInfo)) {\n return getAgentDefaultAccess(resourceInfo.internal_acl.fallbackAcl, agent);\n }\n return null;\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n * Returns all explicitly-granted Access Modes per Agent for the given Resource.\n *\n * The function does not return Access Modes granted indirectly to Agents through other\n * ACL rules, e.g., public or group-specific permissions.\n *\n * @param resourceInfo Information about the Resource to which Agents may have been granted access.\n * @returns Access Modes per Agent that have been explicitly granted for the given Resource, or `null` if it could not be determined (e.g. because the current user does not have Control access to a given Resource or its Container).\n */\nfunction getAgentAccessAll$5(resourceInfo) {\n if (hasResourceAcl(resourceInfo)) {\n const resourceAcl = getResourceAcl(resourceInfo);\n return getAgentResourceAccessAll(resourceAcl);\n }\n if (hasFallbackAcl(resourceInfo)) {\n const fallbackAcl = getFallbackAcl(resourceInfo);\n return getAgentDefaultAccessAll(fallbackAcl);\n }\n return null;\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns the Access Modes explicitly granted to an Agent for the Resource\n * associated with an ACL (Access ControlList).\n *\n * The function does not return:\n *\n * - Access Modes granted indirectly to the Agent through other ACL rules, e.g., public or group-specific permissions.\n * - Access Modes granted to the Agent for the child Resources if the associated Resource is a Container (see [[getAgentDefaultAccess]] instead).\n *\n * @param aclDataset The SolidDataset that contains ACL rules.\n * @param agent WebID of the Agent for which to retrieve what access it has to the Resource.\n * @returns Access Modes that have been explicitly granted to an Agent for the Resource associated with an ACL SolidDataset.\n */\nfunction getAgentResourceAccess(aclDataset, agent) {\n const allRules = internal_getAclRules(aclDataset);\n const resourceRules = internal_getResourceAclRulesForResource(allRules, aclDataset.internal_accessTo);\n const agentResourceRules = getAgentAclRulesForAgent(resourceRules, agent);\n const agentAccessModes = agentResourceRules.map(internal_getAccess);\n return internal_combineAccessModes(agentAccessModes);\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns the explicitly granted Access Modes per Agent for the Resource associated\n * with an ACL (Access Control List).\n *\n * The function does not return:\n *\n * - Access Modes granted indirectly to Agents through other ACL rules, e.g., public or group-specific permissions.\n * - Access Modes granted to Agents for the child Resources if the associated Resource is a Container.\n *\n * @param aclDataset The SolidDataset that contains ACL rules.\n * @returns Access Modes per Agent that have been explicitly granted for the Resource associated with an ACL SolidDataset.\n */\nfunction getAgentResourceAccessAll(aclDataset) {\n const allRules = internal_getAclRules(aclDataset);\n const resourceRules = internal_getResourceAclRulesForResource(allRules, aclDataset.internal_accessTo);\n const agentResourceRules = getAgentAclRules(resourceRules);\n return getAccessByAgent(agentResourceRules);\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n * Modifies the resource ACL (Access Control List) to set the Access Modes for the given Agent.\n * Specifically, the function returns a new resource ACL initialised with the given ACL and\n * new rules for the Agent's access.\n *\n * If rules for Agent's access already exist in the given ACL, in the returned ACL,\n * they are replaced by the new rules.\n *\n * This function does not modify:\n *\n * - Access Modes granted indirectly to Agents through other ACL rules, e.g., public or group-specific permissions.\n * - Access Modes granted to Agents for the child Resources if the associated Resource is a Container.\n * - The original ACL.\n *\n * @param aclDataset The SolidDataset that contains Access-Control List rules.\n * @param agent The Agent to grant specific Access Modes.\n * @param access The Access Modes to grant to the Agent for the Resource.\n * @returns A new resource ACL initialised with the given `aclDataset` and `access` for the `agent`.\n */\nfunction setAgentResourceAccess$1(aclDataset, agent, access) {\n return internal_setActorAccess$2(aclDataset, access, acl.agent, \"resource\", agent);\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns an Agent's Access Modes explicitly granted for the children of the\n * Container associated with the given ACL (Access Control List).\n *\n * The function does not return:\n * - Access Modes granted indirectly to the Agent through other ACL rules, e.g. public or group-specific permissions.\n * - Access Modes granted to the Agent for the Container Resource itself (see [[getAgentResourceAccess]] instead).\n *\n * @param aclDataset The SolidDataset that contains Access-Control List rules for a certain Container.\n * @param agent WebID of the Agent for which to retrieve what access it has to the Container's children.\n * @returns Access Modes that have been explicitly granted to an Agent for the children of the Container associated with the given ACL.\n */\nfunction getAgentDefaultAccess(aclDataset, agent) {\n const allRules = internal_getAclRules(aclDataset);\n const resourceRules = internal_getDefaultAclRulesForResource(allRules, aclDataset.internal_accessTo);\n const agentResourceRules = getAgentAclRulesForAgent(resourceRules, agent);\n const agentAccessModes = agentResourceRules.map(internal_getAccess);\n return internal_combineAccessModes(agentAccessModes);\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns the Access Modes, per Agent, that have been explicitly granted for the children\n * of the Container associated with the given ACL (Access Control List).\n *\n * The function does not return:\n *\n * - Access Modes granted indirectly to the Agents through other ACL rules, e.g. public or group-specific permissions.\n * - Access Modes granted to the Agents for the Container Resource itself (see [[getAgentResourceAccessAll]] instead).\n *\n * @param aclDataset The SolidDataset that contains Access-Control List rules.\n * @returns Access Modes, per Agent, that have been explicitly granted for the children of the Container associated with the given ACL.\n */\nfunction getAgentDefaultAccessAll(aclDataset) {\n const allRules = internal_getAclRules(aclDataset);\n const resourceRules = internal_getDefaultAclRulesForResource(allRules, aclDataset.internal_accessTo);\n const agentResourceRules = getAgentAclRules(resourceRules);\n return getAccessByAgent(agentResourceRules);\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Modifies the default ACL (Access Control List) to set an Agent's Access Modes for the Container's children.\n * Specifically, the function returns a new default ACL initialised with the given ACL and\n * new rules for the Agent's access.\n *\n * If rules already exist for the Agent in the given ACL, in the returned ACL, they are replaced by the new rules.\n *\n * This function does not modify:\n * - Access Modes granted indirectly to the Agent through other ACL rules, e.g., public or group-specific permissions.\n * - Access Modes granted to the Agent for the Container Resource itself.\n * - The original ACL.\n *\n * @param aclDataset The SolidDataset that contains Access-Control List rules.\n * @param agent The Agent to grant specific Access Modes.\n * @param access The Access Modes to grant to the Agent.\n * @returns A new default ACL initialised with the given `aclDataset` and `access` for the `agent`.\n */\nfunction setAgentDefaultAccess(aclDataset, agent, access) {\n return internal_setActorAccess$2(aclDataset, access, acl.agent, \"default\", agent);\n}\nfunction getAgentAclRulesForAgent(aclRules, agent) {\n return internal_getAclRulesForIri(aclRules, agent, acl.agent);\n}\nfunction getAgentAclRules(aclRules) {\n return aclRules.filter(isAgentAclRule);\n}\nfunction isAgentAclRule(aclRule) {\n return getIri(aclRule, acl.agent) !== null;\n}\nfunction getAccessByAgent(aclRules) {\n return internal_getAccessByIri(aclRules, acl.agent);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note} This function is still experimental and subject to change, even in a non-major release.\n * ```\n * Returns a Group's explicity-granted Access Modes for a given Resource.\n *\n * The function does not return Access Modes granted indirectly to the Group through other\n * ACL rules, e.g., public permissions.\n *\n * @param resourceInfo Information about the Resource to which the given Group may have been granted access.\n * @param group URL of the Group for which to retrieve what access it has to the Resource.\n * @returns Access Modes that have been explicitly granted to the `group` for the given Resource, or `null` if it could not be determined (e.g. because the current user does not have Control Access to a given Resource or its Container).\n */\nfunction getGroupAccess$2(resourceInfo, group) {\n if (hasResourceAcl(resourceInfo)) {\n return getGroupResourceAccess(resourceInfo.internal_acl.resourceAcl, group);\n }\n if (hasFallbackAcl(resourceInfo)) {\n return getGroupDefaultAccess(resourceInfo.internal_acl.fallbackAcl, group);\n }\n return null;\n}\n/**\n * ```{note} This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns all explicitly-granted Access Modes per Group for the given Resource.\n *\n * The function does not return Access Modes granted indirectly to the Group through other\n * ACL rules, e.g., public permissions.\n *\n * @param resourceInfo Information about the Resource to which the given Group may have been granted access.\n * @returns Access Modes per Group that have been explicitly granted for the given Resource, or `null` if it could not be determined (e.g. because the current user does not have Control Access to a given Resource or its Container).\n */\nfunction getGroupAccessAll$2(resourceInfo) {\n if (hasResourceAcl(resourceInfo)) {\n const resourceAcl = getResourceAcl(resourceInfo);\n return getGroupResourceAccessAll(resourceAcl);\n }\n if (hasFallbackAcl(resourceInfo)) {\n const fallbackAcl = getFallbackAcl(resourceInfo);\n return getGroupDefaultAccessAll(fallbackAcl);\n }\n return null;\n}\n/**\n * ```{note} This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns the Access Modes explicitly granted to a Group for the Resource\n * associated with an ACL (Access Control List).\n *\n * The function does not return:\n * - Access Modes granted indirectly to the Group through other ACL rules, e.g., public permissions.\n * - Access Modes granted to the Group for the child Resources if the associated Resource is a Container\n * (see [[getGroupDefaultAccess]] instead).\n *\n * @param aclDataset The SolidDataset that contains Access Control List rules.\n * @param group URL of the Group for which to retrieve what access it has to the Resource.\n * @returns Access Modes explicitly granted to a Group for the Resource associated with an ACL.\n */\nfunction getGroupResourceAccess(aclDataset, group) {\n const allRules = internal_getAclRules(aclDataset);\n const resourceRules = internal_getResourceAclRulesForResource(allRules, aclDataset.internal_accessTo);\n const groupResourceRules = getGroupAclRuleForGroup(resourceRules, group);\n const groupAccessModes = groupResourceRules.map(internal_getAccess);\n return internal_combineAccessModes(groupAccessModes);\n}\n/**\n * ```{note} This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns the explicitly granted Access Modes per Group for the Resource associated\n * with an ACL (Access Control List).\n *\n * The function does not return:\n * - Access Modes granted indirectly to the Group through other ACL rules, e.g., public permissions.\n * - Access Modes granted to Groups for the child Resources if the associated Resource is a Container.\n *\n * @param aclDataset The SolidDataset that contains Access Control List rules.\n * @returns Access Modes per Group that have been explicitly granted for the Resource associated with an ACL.\n */\nfunction getGroupResourceAccessAll(aclDataset) {\n const allRules = internal_getAclRules(aclDataset);\n const resourceRules = internal_getResourceAclRulesForResource(allRules, aclDataset.internal_accessTo);\n return getAccessByGroup(resourceRules);\n}\n/**\n * ```{note} This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns a Group's Access Modes explicitly granted for the children of the\n * Container associated with an ACL (Access ControlList).\n *\n * The function does not return:\n * - Access Modes granted indirectly to the Group through other ACL rules, e.g. public permissions.\n * - Access Modes granted to the Group for the Container Resource itself (see [[getGroupResourceAccess]] instead).\n *\n * @param aclDataset The SolidDataset that contains ACL rules for a certain Container.\n * @param group URL of the Group for which to retrieve what access it has to the child Resources of the given Container.\n * @returns Access Modes that have been explicitly granted to the Group for the children of the Container associated with the given ACL.\n */\nfunction getGroupDefaultAccess(aclDataset, group) {\n const allRules = internal_getAclRules(aclDataset);\n const defaultRules = internal_getDefaultAclRulesForResource(allRules, aclDataset.internal_accessTo);\n const groupDefaultRules = getGroupAclRuleForGroup(defaultRules, group);\n const groupAccessModes = groupDefaultRules.map(internal_getAccess);\n return internal_combineAccessModes(groupAccessModes);\n}\n/**\n * ```{note} This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns the Access Modes, per Group, that have been explicitly granted for the children\n * of the Container associated with the given ACL (Access Control List).\n *\n * The function does not return:\n * - Access Modes granted indirectly to the Groups through other ACL rules, e.g. public permissions.\n * - Access Modes granted to the Groups for the Container Resource itself (see [[getGroupResourceAccessAll]] instead).\n *\n * @param aclDataset The SolidDataset that contains Access Control List rules for a certain Container.\n * @returns Access Modes per Group that have been explicitly granted for the children of the Container associated with the given ACL SolidDataset.\n */\nfunction getGroupDefaultAccessAll(aclDataset) {\n const allRules = internal_getAclRules(aclDataset);\n const defaultRules = internal_getDefaultAclRulesForResource(allRules, aclDataset.internal_accessTo);\n return getAccessByGroup(defaultRules);\n}\nfunction getGroupAclRuleForGroup(rules, group) {\n return internal_getAclRulesForIri(rules, group, acl.agentGroup);\n}\nfunction getAccessByGroup(aclRules) {\n return internal_getAccessByIri(aclRules, acl.agentGroup);\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n * Modifies the resource ACL (Access Control List) to set the Access Modes for the given Group.\n * Specifically, the function returns a new resource ACL initialised with the given ACL and\n * new rules for the Group's access.\n *\n * If rules for Groups's access already exist in the given ACL, in the returned ACL,\n * they are replaced by the new rules.\n *\n * This function does not modify:\n *\n * - Access Modes granted indirectly to Groups through other ACL rules, e.g., public or Agent-specific permissions.\n * - Access Modes granted to Groups for the child Resources if the associated Resource is a Container.\n * - The original ACL.\n *\n * @param aclDataset The SolidDataset that contains Access-Control List rules.\n * @param group The Group to grant specific Access Modes.\n * @param access The Access Modes to grant to the Group for the Resource.\n * @returns A new resource ACL initialised with the given `aclDataset` and `access` for the `group`.\n * @since 1.4.0\n */\nfunction setGroupResourceAccess$1(aclDataset, group, access) {\n return internal_setActorAccess$2(aclDataset, access, acl.agentGroup, \"resource\", group);\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Modifies the default ACL (Access Control List) to set a Group's Access Modes for the Container's children.\n * Specifically, the function returns a new default ACL initialised with the given ACL and\n * new rules for the Group's access.\n *\n * If rules already exist for the Group in the given ACL, in the returned ACL, they are replaced by the new rules.\n *\n * This function does not modify:\n * - Access Modes granted indirectly to the Group through other ACL rules, e.g., public or Agent-specific permissions.\n * - Access Modes granted to the Group for the Container Resource itself.\n * - The original ACL.\n *\n * @param aclDataset The SolidDataset that contains Access-Control List rules.\n * @param group The Group to grant specific Access Modes.\n * @param access The Access Modes to grant to the Group.\n * @returns A new default ACL initialised with the given `aclDataset` and `access` for the `group`.\n * @since 1.4.0\n */\nfunction setGroupDefaultAccess(aclDataset, group, access) {\n return internal_setActorAccess$2(aclDataset, access, acl.agentGroup, \"default\", group);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns the Access Modes granted to the public in general for a Resource.\n *\n * This function does not return Access Modes granted to specific Agents\n * through other ACL (Access Control List) rules, e.g., agent- or group-specific permissions.\n *\n * @param resourceInfo Information about the Resource to which the given Agent may have been granted access.\n * @returns Access Modes granted to the public in general for the Resource, or `null` if it could not be determined (e.g. because the current user does not have Control Access to a given Resource or its Container).\n */\nfunction getPublicAccess$5(resourceInfo) {\n if (hasResourceAcl(resourceInfo)) {\n return getPublicResourceAccess(resourceInfo.internal_acl.resourceAcl);\n }\n if (hasFallbackAcl(resourceInfo)) {\n return getPublicDefaultAccess(resourceInfo.internal_acl.fallbackAcl);\n }\n return null;\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns the Access Modes granted to the public in general for the Resource\n * associated with an ACL (Access Control List).\n *\n * This function does not return:\n * - Access Modes granted to specific Agents through other ACL rules, e.g., agent- or group-specific permissions.\n * - Access Modes to child Resources if the associated Resource is a Container (see [[getPublicDefaultAccess]] instead).\n *\n * @param aclDataset The SolidDataset that contains Access Control List rules.\n * @returns Access Modes granted to the public in general for the Resource associated with the `aclDataset`.\n */\nfunction getPublicResourceAccess(aclDataset) {\n const allRules = internal_getAclRules(aclDataset);\n const resourceRules = internal_getResourceAclRulesForResource(allRules, aclDataset.internal_accessTo);\n const publicResourceRules = getClassAclRulesForClass(resourceRules, foaf.Agent);\n const publicAccessModes = publicResourceRules.map(internal_getAccess);\n return internal_combineAccessModes(publicAccessModes);\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Returns the Access Modes granted to the public in general for the child Resources\n * of the Container associated with an ACL (Access Control List).\n *\n * This function does not return:\n * - Access Modes granted to Agents through other ACL rules, e.g., agent- or group-specific permissions.\n * - Access Modes to the Container Resource itself (see [[getPublicResourceAccess]] instead).\n *\n * @param aclDataset The SolidDataset that contains Access Control List rules for a certain Container.\n * @returns Access Modes granted to the public in general for the children of the Container associated with the given `aclDataset`.\n */\nfunction getPublicDefaultAccess(aclDataset) {\n const allRules = internal_getAclRules(aclDataset);\n const resourceRules = internal_getDefaultAclRulesForResource(allRules, aclDataset.internal_accessTo);\n const publicResourceRules = getClassAclRulesForClass(resourceRules, foaf.Agent);\n const publicAccessModes = publicResourceRules.map(internal_getAccess);\n return internal_combineAccessModes(publicAccessModes);\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Modifies the resource ACL (Access Control List) to set the Access Modes for the public.\n * Specifically, the function returns a new resource ACL (Access Control List) initialised\n * with the given resource ACL and new rules for the given public access.\n *\n * If rules for public access already exist in the given ACL, in the *returned* ACL,\n * they are replaced by the new rules.\n *\n * This function does not modify:\n * - Access Modes granted to Agents through other ACL rules, e.g., agent- or group-specific permissions.\n * - Access Modes to child Resources if the associated Resource is a Container.\n * - The original ACL.\n *\n * @param aclDataset The SolidDataset that contains Access Control List rules.\n * @param access The Access Modes to grant to the public.\n * @returns A new resource ACL initialised with the given `aclDataset` and public `access`.\n */\nfunction setPublicResourceAccess$1(aclDataset, access) {\n return internal_setActorAccess$2(aclDataset, access, acl.agentClass, \"resource\", foaf.Agent);\n}\n/**\n * ```{note}\n * This function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Modifies the default ACL (Access Control List) to set the public's default Access Modes\n * to child resources. Specifically, the function returns a new default ACL initialised\n * with the given default ACL and new rules for the given public access.\n *\n * If rules for public access already exist in the given ACL, in the *returned* ACL,\n * they are replaced by the new rules.\n *\n * This function does not modify:\n * - Access Modes granted to Agents through other ACL rules, e.g., agent- or group-specific permissions.\n * - Access Modes to Container Resource itself.\n * - The original ACL.\n *\n * @param aclDataset The SolidDataset that contains Access Control List rules.\n * @param access The Access Modes to grant to the public.\n * @returns A new default ACL initialised with the given `aclDataset` and public `access`.\n */\nfunction setPublicDefaultAccess(aclDataset, access) {\n return internal_setActorAccess$2(aclDataset, access, acl.agentClass, \"default\", foaf.Agent);\n}\nfunction getClassAclRulesForClass(aclRules, agentClass) {\n return aclRules.filter((rule) => appliesToClass(rule, agentClass));\n}\nfunction appliesToClass(aclRule, agentClass) {\n return getIriAll(aclRule, acl.agentClass).includes(agentClass);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction setMockAclUrl(resource, aclUrl) {\n const resourceWithAclUrl = Object.assign(internal_cloneResource(resource), {\n internal_resourceInfo: {\n ...resource.internal_resourceInfo,\n aclUrl,\n },\n });\n return resourceWithAclUrl;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{warning}\n * Do not use this function in production code. For use in **unit tests** that\n * require a [[SolidDataset]] with a resource ACL (Access Control List).\n * ```\n *\n * Initialises a new empty ACL and attaches it to a given [[SolidDataset]] for use\n * in **unit tests**; e.g., unit tests that call [[getResourceAcl]].\n *\n * @param resource The Resource to mock up with a new resource ACL.\n * @returns The input Resource with an empty resource ACL attached.\n * @since 0.2.0\n */\nfunction addMockResourceAclTo(resource) {\n var _a;\n const aclUrl = (_a = resource.internal_resourceInfo.aclUrl) !== null && _a !== void 0 ? _a : \"https://your.pod/mock-acl.ttl\";\n const resourceWithAclUrl = Object.assign(internal_cloneResource(resource), {\n internal_resourceInfo: {\n ...resource.internal_resourceInfo,\n aclUrl,\n },\n });\n const aclDataset = createAcl(resourceWithAclUrl);\n const resourceWithResourceAcl = internal_setAcl(resourceWithAclUrl, {\n resourceAcl: aclDataset,\n fallbackAcl: null,\n });\n return resourceWithResourceAcl;\n}\n/**\n *\n * ```{warning}\n * Do not use this function in production code. For use in **unit tests** that require a\n * [[SolidDataset]] with a fallback ACL (Access Control List).\n * ```\n *\n * Initialises a new empty fallback ACL and attaches it to a given [[SolidDataset]] for use\n * in **unit tests**; e.g., unit tests that call [[getFallbackAcl]].\n *\n * @param resource The Resource to mock up with new fallback ACL.\n * @returns The input Resource with an empty fallback ACL attached.\n * @since 0.2.0\n */\nfunction addMockFallbackAclTo(resource) {\n const containerUrl = internal_getContainerPath(getSourceIri(resource));\n const aclUrl = `${containerUrl}.acl`;\n const mockContainer = setMockAclUrl(mockContainerFrom(containerUrl), aclUrl);\n const aclDataset = createAcl(mockContainer);\n const resourceWithFallbackAcl = internal_setAcl(internal_cloneResource(resource), {\n resourceAcl: null,\n fallbackAcl: aclDataset,\n });\n return resourceWithFallbackAcl;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction getProfileFromProfileDoc(profileDataset, webId) {\n const profile = getThing(profileDataset, webId);\n if (profile === null) {\n throw new Error(`Profile document [${getSourceUrl(profileDataset)}] does not include WebID [${webId}]`);\n }\n return profile;\n}\n/**\n * Set a JWKS IRI associated with a WebID in a profile document.\n *\n * @param profileDocument The profile document dataset.\n * @param webId The WebID associated with the profile document.\n * @param jwksIri The JWKS IRI to be set.\n * @returns A modified copy of the profile document, with the JWKS IRI set.\n * @since 1.12.0\n */\nfunction setProfileJwks(profileDocument, webId, jwksIri) {\n return setThing(profileDocument, setIri(getProfileFromProfileDoc(profileDocument, webId), security.publicKey, jwksIri));\n}\n/**\n * Look for a JWKS IRI optionally advertized from a profile document.\n *\n * @param profileDocument The profile document.\n * @param webId The WebID featured in the profile document.\n * @returns The JWKS IRI associated with the WebID, if any.\n * @since 1.12.0\n */\nfunction getProfileJwksIri(profileDocument, webId) {\n return getUrl(getProfileFromProfileDoc(profileDocument, webId), security.publicKey);\n}\nconst isJwks = (jwksDocument) => {\n return typeof jwksDocument.keys !== \"undefined\";\n};\n/**\n * Fetch a JWKS at a given IRI, and add the given JWK to the obtained key set.\n *\n * @param jwk The JWK to add to the set.\n * @param jwksIri The IRI where the key set should be looked up.\n * @param options @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns Promise resolving to a JWKS where the given key has been added.\n * @since 1.12.0\n */\nasync function addJwkToJwks(jwk, jwksIri, options = internal_defaultFetchOptions) {\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const jwksResponse = await config.fetch(jwksIri);\n if (!jwksResponse.ok) {\n throw new Error(`Fetching [${jwksIri}] returned an error: ${jwksResponse.status} ${jwksResponse.statusText}`);\n }\n try {\n const jwksDocument = await jwksResponse.json();\n if (!isJwks(jwksDocument)) {\n throw new Error(`[${jwksIri}] does not dereference to a valid JWKS: ${JSON.stringify(jwksDocument)}`);\n }\n return {\n keys: [...jwksDocument.keys, jwk],\n };\n }\n catch (e) {\n throw new Error(`Parsing the document at [${jwksIri}] failed: ${e}`);\n }\n}\n/**\n * Adds a public key to the JWKS listed in the profile associated to the given WebID.\n * Retrieves the profile document for the specified WebID and looks up the associated\n * JWKS. Having added the given key to the JWKS, this function overwrites the\n * previous JWKS so that the new version is saved. This assumes the JWKS is hosted\n * at a read-write IRI, such as in a Solid Pod.\n *\n * @param publicKey The public key value to set.\n * @param webId The WebID whose profile document references the key set to which we wish to add the specified public key.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @since 1.12.0\n */\nasync function addPublicKeyToProfileJwks(publicKey, webId, options = internal_defaultFetchOptions) {\n const profileDataset = await getSolidDataset(webId, {\n fetch: options.fetch,\n });\n if (profileDataset === null) {\n throw new Error(`The profile document associated with WebID [${webId}] could not be retrieved.`);\n }\n const jwksIri = getProfileJwksIri(profileDataset, webId);\n if (jwksIri === null) {\n throw new Error(`No key set is declared for the property [${security.publicKey}] in the profile of [${webId}]`);\n }\n const updatedJwks = await addJwkToJwks(publicKey, jwksIri, options);\n return overwriteFile(jwksIri, new Blob([JSON.stringify(updatedJwks)]), {\n contentType: \"application/json\",\n fetch: options.fetch,\n });\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * List all the alternative profiles IRI found in a given WebID profile.\n *\n * Note that some of these profiles may be private, and you may not have access to\n * the resulting resource.\n *\n * @param webId The WebID of the user's whose alternative profiles you are discovering.\n * @param webIdProfile The WebID profile obtained dereferencing the provided WebID.\n * @returns A list of URLs of the user's alternative profiles.\n * @since 1.20.0\n */\nfunction getAltProfileUrlAllFrom(webId, webIdProfile) {\n const webIdThing = getThing(webIdProfile, webId);\n const altProfileUrlAll = getThingAll(webIdProfile)\n .filter((thing) => getIriAll(thing, foaf.primaryTopic).length > 0)\n .map(asIri)\n .concat(webIdThing ? getIriAll(webIdThing, rdfs.seeAlso) : [])\n .concat(webIdThing ? getIriAll(webIdThing, foaf.isPrimaryTopicOf) : [])\n .filter((profileIri) => profileIri !== getSourceIri(webIdProfile));\n // Deduplicate the results.\n return Array.from(new Set(altProfileUrlAll));\n}\nasync function getProfileAll(webId, options = internal_defaultFetchOptions) {\n var _a, _b;\n const authFetch = (_a = options.fetch) !== null && _a !== void 0 ? _a : fetch;\n const webIdProfile = (_b = options.webIdProfile) !== null && _b !== void 0 ? _b : (await getSolidDataset(webId, {\n // This should always use an unauthenticated fetch.\n fetch: fetch,\n }));\n const altProfileAll = (await Promise.allSettled(getAltProfileUrlAllFrom(webId, webIdProfile).map((uniqueProfileIri) => getSolidDataset(uniqueProfileIri, { fetch: authFetch }))))\n // Ignore the alternative profiles lookup which failed.\n .filter((result) => result.status === \"fulfilled\")\n .map((successfulResult) => successfulResult.value);\n return {\n webIdProfile,\n altProfileAll,\n };\n}\n/**\n * Discover the Pods an agent advertises for in their profile resources. Both the\n * agent's WebID and alternative profiles are fetched. Note that this function will\n * only return URLs of Pods linked to using the `pim:storage`, i.e. a triple\n * looking like should appear in the profile\n * resources.\n *\n * @param webId The WebID of the agent whose Pods should be discovered\n * @param options Optional parameter\n * - `options.fetch`: An alternative `fetch` function to make the HTTP request,\n * compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns a Promise resolving to an array containing the URLs of all the Pods\n * linked from the agent's profile resource using the `pim:storage` predicate.\n * @since 1.18.0\n */\nasync function getPodUrlAll(webId, options = internal_defaultFetchOptions) {\n const profiles = await getProfileAll(webId, options);\n return getPodUrlAllFrom(profiles, webId);\n}\n/**\n * Discover the Pods advertised for in the provided profile resources. Note that\n * this function will only return URLs of Pods linked to using the `pim:storage`\n * predicate, i.e. a triple looking like \n * should appear in the profile resources.\n *\n * @param profiles The profile resources in which the Pods should be discovered\n * @param webId The WebID of the agent whose Pods should be discovered\n * @returns An array containing the URLs of all the Pods linked from the agent's\n * profile resource using the `pim:storage` predicate.\n * @since 1.18.0\n */\nfunction getPodUrlAllFrom(profiles, webId) {\n const result = new Set();\n [profiles.webIdProfile, ...profiles.altProfileAll].forEach((profileResource) => {\n const webIdThing = getThing(profileResource, webId);\n if (webIdThing !== null) {\n getIriAll(webIdThing, pim.storage).forEach((podIri) => result.add(podIri));\n }\n });\n return Array.from(result);\n}\n/**\n * Get the WebID Profile document dataset.\n *\n * @example\n * ```\n * const webId = \"https://example.org/people/me\";\n * const profile = await getWebIdDataset(webId);\n * const podRoot = getPodUrlAllFrom({ webIdProfile: profile, altProfileAll: [] }, webId);\n * const profileThing = getThing(profile, webId);\n * const name = getStringNoLocale(profileThing, FOAF.name);\n * ```\n *\n * @param webId The WebID of the agent whose WebID Profile dataset is to be fetched.\n * @returns a SolidDataset for the WebID Profile document.\n * @since 1.24.0\n */\nasync function getWebIdDataset(webId) {\n return getSolidDataset(webId, { fetch: fetch });\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction internal_getAcr(resource) {\n if (!hasAccessibleAcr(resource)) {\n throw new Error(`An Access Control Resource for [${getSourceUrl(resource)}] is not available. This could be because the current user is not allowed to see it, or because their Pod Server does not support Access Control Resources.`);\n }\n return resource.internal_acp.acr;\n}\n/** @hidden */\nfunction internal_setAcr(resource, acr) {\n return Object.assign(internal_cloneResource(resource), {\n internal_acp: {\n ...resource.internal_acp,\n acr,\n },\n });\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Initialise a new [[Control]].\n * @hidden Developers don't need to care about initialising Controls - they can just add Policies directly.\n * @deprecated\n */\nfunction internal_createControl(options) {\n let control = createThing(options);\n control = setIri(control, rdf.type, acp.AccessControl);\n return control;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Find an [[Control]] with a given URL in a given Resource with an Access Control Resource.\n *\n * @returns The requested Access Control, or `null` if it could not be found.\n * @hidden Developers don't need to care about initialising Controls - they can just add Policies directly.\n * @deprecated\n */\nfunction internal_getControl(withAccessControlResource, url, options) {\n const acr = internal_getAcr(withAccessControlResource);\n const foundThing = getThing(acr, url, options);\n if (foundThing === null ||\n !getIriAll(foundThing, rdf.type).includes(acp.AccessControl)) {\n return null;\n }\n return foundThing;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get all [[Control]]s in the Access Control Resource of a given Resource.\n * @hidden Developers don't need to care about initialising Controls - they can just add Policies directly.\n * @deprecated\n */\nfunction internal_getControlAll(withAccessControlResource, options) {\n const acr = internal_getAcr(withAccessControlResource);\n const foundThings = getThingAll(acr, options);\n const explicitAccessControl = foundThings.filter((foundThing) => getIriAll(foundThing, rdf.type).includes(acp.AccessControl));\n const implicitAccessControl = foundThings\n .filter((foundThing) => getIriAll(foundThing, acp.accessControl).length > 0)\n .map((thingWithAccessControl) => {\n // The initial filter ensures that at least one AccessControl will be found.\n const controlIri = getIriAll(thingWithAccessControl, acp.accessControl)[0];\n // The found control is only an object in the current dataset, so we create the\n // associated thing in order to possibly make it a subject.\n return createThing({ url: controlIri });\n });\n return explicitAccessControl.concat(implicitAccessControl);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Insert an [[Control]] into the [[AccessControlResource]] of a Resource, replacing previous\n * instances of that Access Control.\n *\n * @param withAccessControlResource A Resource with the Access Control Resource into which to insert an Access Control.\n * @param control The Control to insert into the Access Control Resource.\n * @returns The given Resource with a new Access Control Resource equal to the original Access Control Resource, but with the given Access Control.\n * @hidden Developers don't need to care about initialising Controls - they can just add Policies directly.\n * @deprecated\n */\nfunction internal_setControl(withAccessControlResource, control) {\n const acr = internal_getAcr(withAccessControlResource);\n const updatedAcr = setThing(acr, control);\n const updatedResource = internal_setAcr(withAccessControlResource, updatedAcr);\n return updatedResource;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Add a [[Policy]] to an [[Control]] such that that Policy applies to the Resource to which\n * the [[Control]] is linked.\n *\n * @param accessControl The [[Control]] to which the Policy should be added.\n * @param policyUrl URL of the Policy that should apply to the Resource to which the [[Control]] is linked.\n * @returns A new [[Control]] equal to the given [[Control]], but with the given policy added to it.\n * @hidden Developers don't need to care about working with Controls - they can just add Policies to the Resource directly.\n * @deprecated\n */\nfunction internal_addPolicyUrl(accessControl, policyUrl) {\n return addIri(accessControl, acp.apply, policyUrl);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get all Policies that apply to the Resource to which the given [[Control]] is linked, and\n * which can be removed by anyone with Write access to the Access Control Resource that contains the\n * [[Control]].\n *\n * @param accessControl The [[Control]] of which to get the Policies.\n * @returns The Policies that are listed in this [[Control]] as applying to the Resource it is linked to, and as removable by anyone with Write access to the Access Control Resource.\n * @hidden Developers don't need to care about working with Controls - they can just add Policies to the Resource directly.\n * @deprecated\n */\nfunction internal_getPolicyUrlAll(accessControl) {\n return getIriAll(accessControl, acp.apply);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Remove a given Policy that applies to the Resource to which the given [[Control]] is linked,\n * and which can be removed by anyone with Write access to the Access Control Resource that contains\n * the Access Control.\n *\n * @param accessControl The [[Control]] of which to remove the Policies.\n * @param policyUrl URL of the Policy that should no longer apply to the Resource to which the [[Control]] is linked.\n * @returns A new [[Control]] equal to the given [[Control]], but with the given Policy removed from it.\n * @hidden Developers don't need to care about working with Controls - they can just add Policies to the Resource directly.\n * @deprecated\n */\nfunction internal_removePolicyUrl(accessControl, policyUrl) {\n return removeIri(accessControl, acp.apply, policyUrl);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Remove all Policies that apply to the Resource to which the given [[Control]] is linked, and\n * which can be removed by anyone with Write access to the Access Control Resource that contains the\n * [[Control]].\n *\n * @param accessControl The [[Control]] of which to remove the Policies.\n * @returns A new [[Control]] equal to the given [[Control]], but with all Policies removed from it.\n * @hidden Developers don't need to care about working with Controls - they can just add Policies to the Resource directly.\n * @deprecated\n */\nfunction internal_removePolicyUrlAll(accessControl) {\n return removeAll(accessControl, acp.apply);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Add a [[Policy]] to an [[Control]] such that that Policy applies to the children of the\n * Resource to which the [[Control]] is linked.\n *\n * @param accessControl The [[Control]] to which the Policy should be added.\n * @param policyUrl URL of the Policy that should apply to the children of the Resource to which the [[Control]] is linked.\n * @returns A new [[Control]] equal to the given [[Control]], but with the given policy added to it as a Member Policy.\n * @hidden Developers don't need to care about working with Controls - they can just add Policies to the Resource directly.\n * @deprecated\n */\nfunction internal_addMemberPolicyUrl(accessControl, policyUrl) {\n return addIri(accessControl, acp.applyMembers, policyUrl);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get all Policies that apply to the children of the Resource to which the given [[Control]] is\n * linked, and which can be removed by anyone with Write access to the Access Control Resource that\n * contains the [[Control]].\n *\n * @param accessControl The [[Control]] of which to get the Policies.\n * @returns The Policies that are listed in this [[Control]] as applying to the children of the Resource it is linked to, and as removable by anyone with Write access to the Access Control Resource.\n * @hidden Developers don't need to care about working with Controls - they can just add Policies to the Resource directly.\n * @deprecated\n */\nfunction internal_getMemberPolicyUrlAll(accessControl) {\n return getIriAll(accessControl, acp.applyMembers);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Remove a given Policy that applies to the children of the Resource to which the given Access\n * Control is linked, and which can be removed by anyone with Write access to the Access Control\n * Resource that contains the Access Control.\n *\n * @param accessControl The [[Control]] of which to remove the Member Policy.\n * @param policyUrl URL of the Member Policy that should no longer apply to the Resource to which the [[Control]] is linked.\n * @returns A new [[Control]] equal to the given [[Control]], but with the given Member Policy removed from it.\n * @hidden Developers don't need to care about working with Controls - they can just add Policies to the Resource directly.\n * @deprecated\n */\nfunction internal_removeMemberPolicyUrl(accessControl, policyUrl) {\n return removeIri(accessControl, acp.applyMembers, policyUrl);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Remove all Policies that apply to the children of the Resource to which the given Access Control\n * is linked, and which can be removed by anyone with Write access to the Access Control Resource\n * that contains the Access Control.\n *\n * @param accessControl The [[Control]] of which to remove the Member Policies.\n * @returns A new [[Control]] equal to the given [[Control]], but with all Member Policies removed from it.\n * @hidden Developers don't need to care about working with Controls - they can just add Policies to the Resource directly.\n * @deprecated\n */\nfunction internal_removeMemberPolicyUrlAll(accessControl) {\n return removeAll(accessControl, acp.applyMembers);\n}\nfunction internal_getInitialisedControl(resourceWithAcr) {\n const allControls = internal_getControlAll(resourceWithAcr);\n return allControls.length === 0 ? internal_createControl() : allControls[0];\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Given a Resource, check whether it is governed by Access Policies.\n * (Specifically, a Resource that is governed by Access Policies will refer to exactly one Access\n * Control Resource, and expose that to users who are allowed to see or modify access to the given\n * Resource.)\n *\n * @param resource Resource which may or may not be governed by Access Policies.\n * @returns True if the Resource refers to an Access Control Resource and is hence governed by Access Policies, or false if it does not.\n * @since 1.6.0\n */\nfunction hasLinkedAcr(resource) {\n return (hasServerResourceInfo(resource) &&\n Array.isArray(resource.internal_resourceInfo.linkedResources[acp.accessControl]) &&\n resource.internal_resourceInfo.linkedResources[acp.accessControl].length ===\n 1);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Add a [[Policy]] to an Access Control Resource such that that [[Policy]] applies to the Access\n * Control Resource itself, rather than the Resource it governs.\n *\n * @param resourceWithAcr The Resource with an Access Control Resource to which the ACR Policy should be added.\n * @param policyUrl URL of the Policy that should apply to the given Access Control Resource.\n * @returns A Resource with a new Access Control Resource equal to the original ACR, but with the given ACR Policy added to it.\n * @since 1.6.0\n */\nfunction addAcrPolicyUrl$1(resourceWithAcr, policyUrl) {\n var _a;\n const acr = internal_getAcr(resourceWithAcr);\n const acrUrl = getSourceUrl(acr);\n let acrThing = (_a = getThing(acr, acrUrl)) !== null && _a !== void 0 ? _a : createThing({ url: acrUrl });\n acrThing = addIri(acrThing, acp.access, policyUrl);\n const updatedAcr = setThing(acr, acrThing);\n const updatedResource = internal_setAcr(resourceWithAcr, updatedAcr);\n return updatedResource;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Add a [[Policy]] to a Resource's Access Control Resource such that that\n * Policy applies to the Access Control Resources of child Resources.\n *\n * @param resourceWithAcr The Resource with an Access Control Resource to which the ACR Policy should be added.\n * @param policyUrl URL of the Policy that should apply to the given Access Control Resources of children of the Resource.\n * @returns A Resource with a new Access Control Resource equal to the original ACR, but with the given ACR Policy added to it.\n * @since 1.6.0\n */\nfunction addMemberAcrPolicyUrl$1(resourceWithAcr, policyUrl) {\n var _a;\n const acr = internal_getAcr(resourceWithAcr);\n const acrUrl = getSourceUrl(acr);\n let acrThing = (_a = getThing(acr, acrUrl)) !== null && _a !== void 0 ? _a : createThing({ url: acrUrl });\n acrThing = addIri(acrThing, acp.accessMembers, policyUrl);\n const updatedAcr = setThing(acr, acrThing);\n const updatedResource = internal_setAcr(resourceWithAcr, updatedAcr);\n return updatedResource;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the URLs of the Access Policies that apply to an Access Control Resource itself, rather than\n * to the Resource it governs.\n *\n * @param resourceWithAcr The Resource with the Access Control Resource of which to get the URLs of the Policies that govern access to it.\n * @returns URLs of the Policies that govern access to the given Access Control Resource.\n * @since 1.6.0\n */\nfunction getAcrPolicyUrlAll$1(resourceWithAcr) {\n const acr = internal_getAcr(resourceWithAcr);\n const acrUrl = getSourceUrl(acr);\n const acrThing = getThing(acr, acrUrl);\n if (acrThing === null) {\n return [];\n }\n return getIriAll(acrThing, acp.access);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the URLs of the Access Policies that apply to the Access Control Resources of the Resource's\n * children.\n *\n * @param resourceWithAcr The Resource with the Access Control Resource of which to get the URLs of the Policies that govern access to its children.\n * @returns URLs of the Policies that govern access to the Access Control Resources of the given Resource's children.\n * @since 1.6.0\n */\nfunction getMemberAcrPolicyUrlAll$1(resourceWithAcr) {\n const acr = internal_getAcr(resourceWithAcr);\n const acrUrl = getSourceUrl(acr);\n const acrThing = getThing(acr, acrUrl);\n if (acrThing === null) {\n return [];\n }\n return getIriAll(acrThing, acp.accessMembers);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Stop the URL of a given [[Policy]] from applying to an Access Control Resource itself.\n *\n * @param resourceWithAcr The Resource with the Access Control Resource to which the given URL of a Policy should no longer apply.\n * @param policyUrl The URL of the Policy that should no longer apply.\n * @returns A Resource with a new Access Control Resource equal to the original ACR, but with the given ACR Policy removed from it.\n * @since 1.6.0\n */\nfunction removeAcrPolicyUrl$1(resourceWithAcr, policyUrl) {\n const acr = internal_getAcr(resourceWithAcr);\n const acrUrl = getSourceUrl(acr);\n const acrThing = getThing(acr, acrUrl);\n if (acrThing === null) {\n return resourceWithAcr;\n }\n const updatedAcrThing = removeIri(acrThing, acp.access, policyUrl);\n const updatedAcr = setThing(acr, updatedAcrThing);\n return internal_setAcr(resourceWithAcr, updatedAcr);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Stop the URL of a given [[Policy]] from applying to the Access Control Resources of the\n * Resource's children.\n *\n * @param resourceWithAcr The Resource with the Access Control Resource to whose children's ACRs the given URL of a Policy should no longer apply.\n * @param policyUrl The URL of the Policy that should no longer apply.\n * @returns A Resource with a new Access Control Resource equal to the original ACR, but with the given member ACR Policy removed from it.\n * @since 1.6.0\n */\nfunction removeMemberAcrPolicyUrl$1(resourceWithAcr, policyUrl) {\n const acr = internal_getAcr(resourceWithAcr);\n const acrUrl = getSourceUrl(acr);\n const acrThing = getThing(acr, acrUrl);\n if (acrThing === null) {\n return resourceWithAcr;\n }\n const updatedAcrThing = removeIri(acrThing, acp.accessMembers, policyUrl);\n const updatedAcr = setThing(acr, updatedAcrThing);\n return internal_setAcr(resourceWithAcr, updatedAcr);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Stop all URL of Access Policies from applying to an Access Control Resource itself.\n *\n * @param resourceWithAcr The Resource with the Access Control Resource to which no more Policies should apply.\n * @returns A Resource with a new Access Control Resource equal to the original ACR, but without any Policy applying to it.\n * @since 1.6.0\n */\nfunction removeAcrPolicyUrlAll(resourceWithAcr) {\n const acr = internal_getAcr(resourceWithAcr);\n const acrUrl = getSourceUrl(acr);\n const acrThing = getThing(acr, acrUrl);\n if (acrThing === null) {\n return resourceWithAcr;\n }\n const updatedAcrThing = removeAll(acrThing, acp.access);\n const updatedAcr = setThing(acr, updatedAcrThing);\n return internal_setAcr(resourceWithAcr, updatedAcr);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Stop all URL of Access Policies from applying to the Access Control Resources of the Resource's\n * children.\n *\n * @param resourceWithAcr The Resource with the Access Control Resource that should no longer apply Policies to its children's ACRs.\n * @returns A Resource with a new Access Control Resource equal to the original ACR, but without any Policy applying to its children's ACRs.\n * @since 1.6.0\n */\nfunction removeMemberAcrPolicyUrlAll(resourceWithAcr) {\n const acr = internal_getAcr(resourceWithAcr);\n const acrUrl = getSourceUrl(acr);\n const acrThing = getThing(acr, acrUrl);\n if (acrThing === null) {\n return resourceWithAcr;\n }\n const updatedAcrThing = removeAll(acrThing, acp.accessMembers);\n const updatedAcr = setThing(acr, updatedAcrThing);\n return internal_setAcr(resourceWithAcr, updatedAcr);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Add a [[Policy]] to an Access Control Resource such that that [[Policy]] applies to that Resource.\n *\n * @param resourceWithAcr The Resource to which the ACR Policy should be added.\n * @param policyUrl URL of the Policy that should apply to the given Resource.\n * @returns A Resource with a new Access Control Resource equal to the original ACR, but with the given Policy added to it.\n * @since 1.6.0\n */\nfunction addPolicyUrl$1(resourceWithAcr, policyUrl) {\n const control = internal_getInitialisedControl(resourceWithAcr);\n const updatedControl = internal_addPolicyUrl(control, policyUrl);\n const updatedResource = internal_setControl(resourceWithAcr, updatedControl);\n return updatedResource;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Add a [[Policy]] to a Resource's Access Control Resource such that that\n * Policy applies to that Resource's children.\n *\n * @param resourceWithAcr The Resource to whose Access Control Resource the Policy should be added.\n * @param policyUrl URL of the Policy that should apply to the given Resource's children.\n * @returns A new Resource equal to the given Resource, but with the given Member Policy added to its Access Control Resource.\n * @since 1.6.0\n */\nfunction addMemberPolicyUrl$1(resourceWithAcr, policyUrl) {\n const control = internal_getInitialisedControl(resourceWithAcr);\n const updatedControl = internal_addMemberPolicyUrl(control, policyUrl);\n const updatedResource = internal_setControl(resourceWithAcr, updatedControl);\n return updatedResource;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the URLs of the Access Policies that apply to a Resource.\n *\n * @param resourceWithAcr The Resource with the Access Control Resource of which to get the URLs of the Policies that govern access to it.\n * @returns URLs of the Policies that govern access to the given Resource.\n * @since 1.6.0\n */\nfunction getPolicyUrlAll$1(resourceWithAcr) {\n const controls = internal_getControlAll(resourceWithAcr);\n const policyUrlsByControl = controls.map((control) => internal_getPolicyUrlAll(control));\n const uniquePolicyUrls = new Set();\n policyUrlsByControl.forEach((policyUrls) => {\n policyUrls.forEach((url) => uniquePolicyUrls.add(url));\n });\n return Array.from(uniquePolicyUrls);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the URLs of the Access Policies that apply to a Resource's children.\n *\n * @param resourceWithAcr The Resource with the Access Control Resource of which to get the URLs of the Policies that govern access to its children.\n * @returns URLs of the Policies that govern access to the given Resource's children.\n * @since 1.6.0\n */\nfunction getMemberPolicyUrlAll$1(resourceWithAcr) {\n const controls = internal_getControlAll(resourceWithAcr);\n const memberPolicyUrlsByControl = controls.map((control) => internal_getMemberPolicyUrlAll(control));\n const uniquePolicyUrls = new Set();\n memberPolicyUrlsByControl.forEach((policyUrls) => {\n policyUrls.forEach((url) => uniquePolicyUrls.add(url));\n });\n return Array.from(uniquePolicyUrls);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Stop the URL of a given [[Policy]] from applying to a Resource.\n *\n * @param resourceWithAcr The Resource, with its Access Control Resource, to which the given URL of a Policy should no longer apply.\n * @param policyUrl The URL of the Policy that should no longer apply.\n * @returns A Resource with a new Access Control Resource equal to the original ACR, but with the given Policy removed from it.\n * @since 1.6.0\n */\nfunction removePolicyUrl$1(resourceWithAcr, policyUrl) {\n const controls = internal_getControlAll(resourceWithAcr);\n const updatedControls = controls.map((control) => internal_removePolicyUrl(control, policyUrl));\n const updatedResource = updatedControls.reduce(internal_setControl, resourceWithAcr);\n return updatedResource;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Stop the URL of a given [[Policy]] from applying to the Resource's children.\n *\n * @param resourceWithAcr The Resource with the Access Control Resource to whose children the given URL of a Policy should no longer apply.\n * @param policyUrl The URL of the Policy that should no longer apply.\n * @returns A Resource with a new Access Control Resource equal to the original ACR, but with the given Member Policy removed from it.\n * @since 1.6.0\n */\nfunction removeMemberPolicyUrl$1(resourceWithAcr, policyUrl) {\n const controls = internal_getControlAll(resourceWithAcr);\n const updatedControls = controls.map((control) => internal_removeMemberPolicyUrl(control, policyUrl));\n const updatedResource = updatedControls.reduce(internal_setControl, resourceWithAcr);\n return updatedResource;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Stop all URL of Access Policies from applying to a Resource.\n *\n * @param resourceWithAcr The Resource, with its Access Control Resource, to which no more Policies should apply.\n * @returns A Resource with a new Access Control Resource equal to the original ACR, but without any Policy applying to the Resource.\n * @since 1.6.0\n */\nfunction removePolicyUrlAll(resourceWithAcr) {\n const controls = internal_getControlAll(resourceWithAcr);\n const updatedControls = controls.map((control) => internal_removePolicyUrlAll(control));\n const updatedResource = updatedControls.reduce(internal_setControl, resourceWithAcr);\n return updatedResource;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Stop all URL of Access Policies from applying to the Resource's children.\n *\n * @param resourceWithAcr The Resource with the Access Control Resource that should no longer apply Policies to its children.\n * @returns A Resource with a new Access Control Resource equal to the original ACR, but without any Policy applying to the Resource's children.\n * @since 1.6.0\n */\nfunction removeMemberPolicyUrlAll(resourceWithAcr) {\n const controls = internal_getControlAll(resourceWithAcr);\n const updatedControls = controls.map((control) => internal_removeMemberPolicyUrlAll(control));\n const updatedResource = updatedControls.reduce(internal_setControl, resourceWithAcr);\n return updatedResource;\n}\n/**\n * Gets a human-readable representation of the given [[Control]] to aid debugging.\n *\n * Note that changes to the exact format of the return value are not considered a breaking change;\n * it is intended to aid in debugging, not as a serialisation method that can be reliably parsed.\n *\n * @param resourceWithAcr The Resource with an attached Access Control Resource of which you want to get a human-readable representation.\n * @since 1.6.0\n * @deprecated\n */\nfunction acrAsMarkdown(resourceWithAcr) {\n let markdown = `# Access controls for ${getSourceUrl(resourceWithAcr)}\\n`;\n const policyUrls = getPolicyUrlAll$1(resourceWithAcr);\n const memberPolicyUrls = getMemberPolicyUrlAll$1(resourceWithAcr);\n const acrPolicyUrls = getAcrPolicyUrlAll$1(resourceWithAcr);\n const memberAcrPolicyUrls = getMemberAcrPolicyUrlAll$1(resourceWithAcr);\n if (policyUrls.length === 0 &&\n memberPolicyUrls.length === 0 &&\n acrPolicyUrls.length === 0 &&\n memberAcrPolicyUrls.length === 0) {\n markdown += \"\\n\\n\";\n }\n if (policyUrls.length > 0) {\n markdown += \"\\nThe following policies apply to this resource:\\n- \";\n markdown += `${policyUrls.join(\"\\n- \")}\\n`;\n }\n if (acrPolicyUrls.length > 0) {\n markdown +=\n \"\\nThe following policies apply to the access control resource for this resource:\\n- \";\n markdown += `${acrPolicyUrls.join(\"\\n- \")}\\n`;\n }\n if (memberPolicyUrls.length > 0) {\n markdown +=\n \"\\nThe following policies apply to the children of this resource:\\n- \";\n markdown += `${memberPolicyUrls.join(\"\\n- \")}\\n`;\n }\n if (memberAcrPolicyUrls.length > 0) {\n markdown +=\n \"\\nThe following policies apply to the access control resources for children of this resource:\\n- \";\n markdown += `${memberAcrPolicyUrls.join(\"\\n- \")}\\n`;\n }\n return markdown;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nconst ACP_NAMESPACE = \"http://www.w3.org/ns/solid/acp#\";\n/** @hidden */\nconst ACP = {\n AccessControl: ACP_NAMESPACE.concat(\"AccessControl\"),\n AccessControlResource: ACP_NAMESPACE.concat(\"AccessControlResource\"),\n AuthenticatedAgent: ACP_NAMESPACE.concat(\"AuthenticatedAgent\"),\n CreatorAgent: ACP_NAMESPACE.concat(\"CreatorAgent\"),\n Matcher: ACP_NAMESPACE.concat(\"Matcher\"),\n Policy: ACP_NAMESPACE.concat(\"Policy\"),\n PublicAgent: ACP_NAMESPACE.concat(\"PublicAgent\"),\n access: ACP_NAMESPACE.concat(\"access\"),\n accessControl: ACP_NAMESPACE.concat(\"accessControl\"),\n agent: ACP_NAMESPACE.concat(\"agent\"),\n allOf: ACP_NAMESPACE.concat(\"allOf\"),\n allow: ACP_NAMESPACE.concat(\"allow\"),\n anyOf: ACP_NAMESPACE.concat(\"anyOf\"),\n apply: ACP_NAMESPACE.concat(\"apply\"),\n client: ACP_NAMESPACE.concat(\"client\"),\n deny: ACP_NAMESPACE.concat(\"deny\"),\n memberAccessControl: ACP_NAMESPACE.concat(\"memberAccessControl\"),\n noneOf: ACP_NAMESPACE.concat(\"noneOf\"),\n vc: ACP_NAMESPACE.concat(\"vc\"),\n};\n/** @hidden */\nconst ACL_NAMESPACE = \"http://www.w3.org/ns/auth/acl#\";\n/** @hidden */\nconst ACL = {\n Append: ACL_NAMESPACE.concat(\"Append\"),\n Control: ACL_NAMESPACE.concat(\"Control\"),\n Read: ACL_NAMESPACE.concat(\"Read\"),\n Write: ACL_NAMESPACE.concat(\"Write\"),\n};\n/** @hidden */\nconst VC_ACCESS_GRANT = \"http://www.w3.org/ns/solid/vc#SolidAccessGrant\";\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction getAccessControlResourceThing(resource) {\n const acr = internal_getAcr(resource);\n const acrUrl = getSourceUrl(acr);\n return getThing(acr, acrUrl);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nconst DEFAULT_ACCESS_CONTROL = \"defaultAccessControl\";\n/** @hidden */\nconst DEFAULT_ACR_ACCESS_CONTROL = \"defaultAcrAccessControl\";\n/** @hidden */\nconst DEFAULT_MEMBER_ACCESS_CONTROL = \"defaultMemberAccessControl\";\n/** @hidden */\nconst DEFAULT_MEMBER_ACR_ACCESS_CONTROL = \"defaultMemberAcrAccessControl\";\n/** @hidden */\nfunction getDefaultAccessControlUrl(resource, name) {\n const acr = internal_getAcr(resource);\n const acrUrl = getSourceUrl(acr);\n return acrUrl.concat(\"#\").concat(name);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction getDefaultAccessControlThing(resource, name) {\n const acr = internal_getAcr(resource);\n const defaultAccessControlUrl = getDefaultAccessControlUrl(resource, name);\n const accessControlThing = getThing(acr, defaultAccessControlUrl);\n if (accessControlThing === null ||\n typeof accessControlThing === \"undefined\") {\n return createThing({ url: defaultAccessControlUrl });\n }\n return accessControlThing;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction getModes(policy, type) {\n const modes = getIriAll(policy, type);\n return {\n read: modes.includes(ACL.Read),\n append: modes.includes(ACL.Append),\n write: modes.includes(ACL.Write),\n controlRead: false,\n controlWrite: false,\n };\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @hidden\n *\n * Internal function that attaches an ACR to a Resource. Prefer using this than\n * setting the internal values manually (easier to refactor when changing the internals).\n */\nfunction setAcr(resource, acr) {\n return Object.assign(internal_cloneResource(resource), {\n internal_acp: {\n acr,\n },\n });\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction setModes(policy, modes, type) {\n let newPolicy = removeAll(policy, type);\n if (modes.read || modes.controlRead) {\n newPolicy = addIri(newPolicy, type, ACL.Read);\n }\n if (modes.append) {\n newPolicy = addIri(newPolicy, type, ACL.Append);\n }\n if (modes.write || modes.controlWrite) {\n newPolicy = addIri(newPolicy, type, ACL.Write);\n }\n return newPolicy;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst DEFAULT_VC_POLICY_NAME = \"defaultVcPolicy\";\nconst DEFAULT_VC_MATCHER_NAME = \"defaultVcMatcher\";\nfunction createVcPolicy(acr, policyIri, matcherIri, access) {\n var _a;\n let vcPolicy = getThing(acr, policyIri);\n if (vcPolicy === null) {\n // If the policy does not exist, create it and link the default Access Control to it.\n vcPolicy = buildThing({ url: policyIri })\n .addIri(rdf.type, ACP.Policy)\n .addIri(ACP.anyOf, matcherIri)\n .build();\n }\n const vcMatcher = (_a = getThing(acr, matcherIri)) !== null && _a !== void 0 ? _a : buildThing({ url: matcherIri })\n .addIri(rdf.type, ACP.Matcher)\n .addIri(ACP.vc, VC_ACCESS_GRANT)\n .build();\n const currentModes = getModes(vcPolicy, ACP.allow);\n // Only change the modes which are set in `access`, and preserve the others.\n vcPolicy = setModes(vcPolicy, { ...currentModes, ...access }, ACP.allow);\n return {\n matcher: vcMatcher,\n policy: vcPolicy,\n };\n}\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Set the maximum access modes that are allowed for a VC holder for a given resource.\n * If the resource owner issued an Access Grant for the resource, the agent that\n * has been granted access will have at most the permissions set by this function.\n * The Access Grant may be more restrictive.\n *\n * Note that additional access may have been set if the ACR has been manipulated\n * not using this library, which is currently out of scope. In this case, the access\n * set by this function may not apply.\n *\n * @param resourceWithAcr The resource for which the access modes are being set for VC holders.\n * @param access The access modes to set. Setting a mode to `true` will enable it, to `false`\n * will disable it, and to `undefined` will leave it unchanged compared to what was previously\n * set.\n * @param options An option object to customize the function behavior:\n * - inherit: if set to `true`, the access set to the target resource cascades\n * to its contained resources.\n * @returns A copy of the resource and its attached ACR, updated to the new access modes.\n * @since 1.17.0\n */\nfunction setVcAccess(resourceWithAcr, access, options = { inherit: false }) {\n var _a;\n let acr = internal_getAcr(resourceWithAcr);\n const defaultVcPolicyIri = `${getSourceIri(acr)}#${DEFAULT_VC_POLICY_NAME}`;\n const defaultVcMatcherIri = `${getSourceIri(acr)}#${DEFAULT_VC_MATCHER_NAME}`;\n const { policy, matcher } = createVcPolicy(acr, defaultVcPolicyIri, defaultVcMatcherIri, access);\n let accessControl = getDefaultAccessControlThing(resourceWithAcr, \"defaultAccessControl\");\n if (!getIriAll(accessControl, ACP.apply).includes(asIri(policy))) {\n // Case when the ACR Thing existed, but did not include a link to the default Access Control.\n accessControl = addIri(accessControl, ACP.apply, policy);\n }\n let memberAccessControl = getDefaultAccessControlThing(resourceWithAcr, \"defaultMemberAccessControl\");\n let acrThing = (_a = getAccessControlResourceThing(resourceWithAcr)) !== null && _a !== void 0 ? _a : createThing({ url: getSourceIri(acr) });\n if (!getIriAll(acrThing, ACP.accessControl).includes(asIri(accessControl))) {\n // Case when the ACR Thing existed, but did not include a link to the default Access Control.\n acrThing = addIri(acrThing, ACP.accessControl, accessControl);\n }\n // Write the changed access control, policy and matchers in the ACR\n acr = [acrThing, accessControl, policy, matcher].reduce(setThing, acr);\n if (options.inherit) {\n // Add triples to the member access control and link it to the ACR only\n // if the VC access is recursive if they don't exist already.\n if (!getIriAll(memberAccessControl, ACP.apply).includes(asIri(policy))) {\n memberAccessControl = addIri(memberAccessControl, ACP.apply, policy);\n }\n if (!getIriAll(acrThing, ACP.memberAccessControl).includes(asIri(memberAccessControl))) {\n acrThing = addIri(acrThing, ACP.memberAccessControl, memberAccessControl);\n }\n acr = [acrThing, memberAccessControl].reduce(setThing, acr);\n }\n return setAcr(resourceWithAcr, acr);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst DEFAULT_NO_ACCESS = {\n read: false,\n append: false,\n write: false,\n controlRead: false,\n controlWrite: false,\n};\nconst linkExists = (subject, predicate, object) => getIriAll(subject, predicate).includes(asIri(object));\n// TODO: It should be possible to write a `chainExists` function, taking in a chain\n// of Thing, predicate, Thing, predicate... and checks whether such chain exists\n// in a given dataset. It would make the following function much easier to read,\n// instead of checking at each link that it isn't null and it is connected to the\n// next link.\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Get the maximum access modes that are allowed for a VC holder for a given resource.\n * If the resource owner issued an Access Grant for the resource, the agent that\n * has been granted access will have at most the permissions returned by this function.\n * The Access Grant may be more restrictive.\n *\n * Note that only the modes set using [[setVcAccess]] will be returned by this function.\n * Additional access may have been set if the ACR has been manipulated not using this\n * library, which is currently out of scope.\n *\n * @param resourceWithAcr The resource for which the VC access modes are looked up.\n * @returns The access modes available to a VC holder.\n * @since 1.17.0\n */\nfunction getVcAccess(resourceWithAcr) {\n const acr = internal_getAcr(resourceWithAcr);\n const accessControl = getDefaultAccessControlThing(resourceWithAcr, \"defaultAccessControl\");\n const acrThing = getAccessControlResourceThing(resourceWithAcr);\n if (acrThing === null ||\n !linkExists(acrThing, ACP.accessControl, accessControl)) {\n return DEFAULT_NO_ACCESS;\n }\n const defaultVcPolicyIri = `${getSourceIri(acr)}#${DEFAULT_VC_POLICY_NAME}`;\n const vcPolicy = getThing(acr, defaultVcPolicyIri);\n if (vcPolicy === null || !linkExists(accessControl, ACP.apply, vcPolicy)) {\n return DEFAULT_NO_ACCESS;\n }\n const defaultVcMatcherIri = `${getSourceIri(acr)}#${DEFAULT_VC_MATCHER_NAME}`;\n const vcMatcher = getThing(acr, defaultVcMatcherIri);\n if (vcMatcher === null || !linkExists(vcPolicy, ACP.anyOf, vcMatcher)) {\n return DEFAULT_NO_ACCESS;\n }\n return getModes(vcPolicy, ACP.allow);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Fetch a SolidDataset and its associated Access Control Resource (if available to the current user).\n *\n * @param url URL of the SolidDataset to fetch.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns A SolidDataset and the ACR that applies to it, if available to the authenticated user.\n * @since 1.6.0\n */\nasync function getSolidDatasetWithAcr(url, options = internal_defaultFetchOptions) {\n const urlString = internal_toIriString(url);\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const solidDataset = await getSolidDataset(urlString, config);\n const acp = await fetchAcr(solidDataset, config);\n return { ...solidDataset, ...acp };\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Fetch a file and its associated Access Control Resource (if available to the current user).\n *\n * @param url URL of the file to fetch.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns A file and the ACR that applies to it, if available to the authenticated user.\n * @since 1.6.0\n */\nasync function getFileWithAcr(url, options = internal_defaultFetchOptions) {\n const urlString = internal_toIriString(url);\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const file = await getFile(urlString, config);\n const acp = await fetchAcr(file, config);\n return Object.assign(file, acp);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Retrieve information about a Resource and its associated Access Control Resource (if available to\n * the current user), without fetching the Resource itself.\n *\n * @param url URL of the Resource about which to fetch its information.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns Metadata describing a Resource, and the ACR that applies to it, if available to the authenticated user.\n * @since 1.6.0\n */\nasync function getResourceInfoWithAcr(url, options = internal_defaultFetchOptions) {\n const urlString = internal_toIriString(url);\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const resourceInfo = await getResourceInfo(urlString, config);\n const acp = await fetchAcr(resourceInfo, config);\n return { ...resourceInfo, ...acp };\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Fetch a SolidDataset, and:\n * - if the Resource is governed by an ACR: its associated Access Control Resource (if available to\n * the current user), and all the Access Control Policies\n * referred to therein, if available to the current user.\n * - if the Resource is governed by an ACL: its associated Resource ACL (if available to the current\n * user), or its Fallback ACL if it does not exist.\n *\n * @param url URL of the SolidDataset to fetch.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns A SolidDataset and either the ACL access data or the ACR access data, if available to the current user.\n * @since 1.6.0\n */\nasync function getSolidDatasetWithAccessDatasets(url, options = internal_defaultFetchOptions) {\n const urlString = internal_toIriString(url);\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const solidDataset = await getSolidDataset(urlString, config);\n if (hasAccessibleAcl(solidDataset)) {\n const acl = await internal_fetchAcl(solidDataset, config);\n return internal_setAcl(solidDataset, acl);\n }\n const acr = await fetchAcr(solidDataset, config);\n return { ...solidDataset, ...acr };\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Fetch a File, and:\n * - if the Resource is governed by an ACR: its associated Access Control Resource (if available to\n * the current user), and all the Access Control Policies\n * referred to therein, if available to the current user.\n * - if the Resource is governed by an ACL: its associated Resource ACL (if available to the current\n * user), or its Fallback ACL if it does not exist.\n *\n * @param url URL of the File to fetch.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns A File and either the ACL access data or the ACR access data, if available to the current user.\n * @since 1.6.0\n */\nasync function getFileWithAccessDatasets(url, options = internal_defaultFetchOptions) {\n const urlString = internal_toIriString(url);\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const file = await getFile(urlString, config);\n if (hasAccessibleAcl(file)) {\n const acl = await internal_fetchAcl(file, config);\n return internal_setAcl(file, acl);\n }\n const acr = await fetchAcr(file, config);\n return Object.assign(file, acr);\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Fetch information about a Resource, and:\n * - if the Resource is governed by an ACR: its associated Access Control Resource (if available to\n * the current user), and all the Access Control Policies\n * referred to therein, if available to the current user.\n * - if the Resource is governed by an ACL: its associated Resource ACL (if available to the current\n * user), or its Fallback ACL if it does not exist.\n *\n * @param url URL of the Resource information about which to fetch.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns Information about a Resource and either the ACL access data or the ACR access data, if available to the current user.\n * @since 1.6.0\n */\nasync function getResourceInfoWithAccessDatasets(url, options = internal_defaultFetchOptions) {\n const urlString = internal_toIriString(url);\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const resourceInfo = await getResourceInfo(urlString, config);\n if (hasAccessibleAcl(resourceInfo)) {\n const acl = await internal_fetchAcl(resourceInfo, config);\n return internal_setAcl(resourceInfo, acl);\n }\n const acr = await fetchAcr(resourceInfo, config);\n return { ...resourceInfo, ...acr };\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Save a Resource's Access Control Resource.\n *\n * @param resource Resource with an Access Control Resource that should be saved.\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @since 1.6.0\n */\nasync function saveAcrFor(resource, options = internal_defaultFetchOptions) {\n const acr = internal_getAcr(resource);\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const savedAcr = await saveSolidDatasetAt(getSourceUrl(acr), acr, config);\n return internal_setAcr(resource, savedAcr);\n}\n/**\n * @param resource Resource of which to check whether it has an Access Control Resource attached.\n * @returns Boolean representing whether the given Resource has an Access Control Resource attached for use in e.g. [[getPolicyUrlAll]].\n * @since 1.6.0\n */\nfunction hasAccessibleAcr(resource) {\n return (typeof resource.internal_acp === \"object\" &&\n resource.internal_acp !== null &&\n typeof resource.internal_acp.acr === \"object\" &&\n resource.internal_acp.acr !== null);\n}\nasync function fetchAcr(resource, options) {\n let acrUrl;\n if (hasLinkedAcr(resource)) {\n // Whereas a Resource can generally have multiple linked Resources for the same relation,\n // it can only have one Access Control Resource for that ACR to be valid.\n // Hence the accessing of [0] directly:\n const { linkedResources } = resource.internal_resourceInfo;\n [acrUrl] = linkedResources[acp.accessControl];\n }\n else if (hasAccessibleAcl(resource)) {\n // The ACP proposal will be updated to expose the Access Control Resource\n // via a Link header with rel=\"acl\", just like WAC. That means that if\n // an ACL is advertised, we can still fetch its metadata — if that indicates\n // that it's actually an ACP Access Control Resource, then we can fetch that\n // instead.\n let aclResourceInfo;\n try {\n aclResourceInfo = await getResourceInfo(resource.internal_resourceInfo.aclUrl, options);\n }\n catch (e) {\n // Since both ACL and ACR will be discovered through the same header, we\n // need to ignore errors here so that in the case of ACL not found, the\n // code can resume and a new ACL can be initialized. The case for ACR is\n // covered in the code below, since in this case the ACR is always present\n }\n if (aclResourceInfo && isAcr(aclResourceInfo)) {\n acrUrl = getSourceUrl(aclResourceInfo);\n }\n }\n // If the Resource doesn't advertise an ACR via the old Link header,\n // nor via a rel=\"acl\" header, then return, indicating that no ACR could be\n // fetched:\n if (typeof acrUrl !== \"string\") {\n return {\n internal_acp: {\n acr: null,\n },\n };\n }\n let acr;\n try {\n acr = await getSolidDataset(acrUrl, options);\n }\n catch (e) {\n return {\n internal_acp: {\n acr: null,\n },\n };\n }\n const acrDataset = {\n ...acr,\n accessTo: getSourceUrl(resource),\n };\n const acpInfo = {\n internal_acp: {\n acr: acrDataset,\n },\n };\n return acpInfo;\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * To make it easy to fetch all the relevant Access Policy Resources,\n * this function returns all referenced Access Policy Resources referenced in an\n * Access Control Resource.\n * In other words, if Access Controls refer to different Policies in the same\n * Access Policy Resource, this function will only return that Access Policy\n * Resource's URL once.\n *\n * @param withAcr A Resource with an Access Control Resource attached.\n * @returns List of all unique Access Policy Resources that are referenced in the given Access Control Resource.\n * @since 1.6.0\n */\nfunction getReferencedPolicyUrlAll(withAcr) {\n const policyUrls = getPolicyUrlAll$1(withAcr)\n .map(normalizeServerSideIri)\n .concat(getMemberPolicyUrlAll$1(withAcr).map(normalizeServerSideIri))\n .concat(getAcrPolicyUrlAll$1(withAcr).map(normalizeServerSideIri))\n .concat(getMemberAcrPolicyUrlAll$1(withAcr).map(normalizeServerSideIri));\n const uniqueUrls = Array.from(new Set(policyUrls));\n return uniqueUrls;\n}\n/**\n * Verify whether the access to the given resource is controlled using the ACP\n * system.\n * @param resource The target resource\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns True if the access to the resource is controlled using ACP, false otherwise.\n * @since 1.14.0.\n */\nasync function isAcpControlled(resource, options = internal_defaultFetchOptions) {\n const urlString = internal_toIriString(resource);\n const config = {\n ...internal_defaultFetchOptions,\n ...options,\n };\n const resourceInfo = await getResourceInfo(urlString, config);\n return hasAccessibleAcr(await fetchAcr(resourceInfo, config));\n}\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Given a Resource, find out the URL of its governing Access Control Resource.\n *\n * @param resource Resource which should be governed by Access Policies.\n * @returns The URL of the Access Control Resource, or undefined if not ACR is found.\n * @since 1.15.0\n */\nfunction getLinkedAcrUrl(resource) {\n if (!hasServerResourceInfo(resource)) {\n return undefined;\n }\n // Two rels types are acceptable to indicate a link to an ACR.\n const acrLinks = [acp.accessControl, \"acl\"].map((rel) => {\n if (Array.isArray(resource.internal_resourceInfo.linkedResources[rel]) &&\n resource.internal_resourceInfo.linkedResources[rel].length === 1) {\n return resource.internal_resourceInfo.linkedResources[rel][0];\n }\n return undefined;\n });\n return acrLinks.find((x) => x !== undefined);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * NOTE: Don't export for now (i.e. if exported, should this be `isAcpRule()` so\n * as not to clash with `isAclRule()`.\n *\n * @param thing the [[Thing]] to check to see if it's an ACP rule or not\n */\nfunction isRule(thing) {\n return getIriAll(thing, rdf.type).includes(acp.Rule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Add a rule that refines the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is **not** present in **any** of the \"All Of\" rules,\n * they will not be granted access.\n *\n * Also see [[addAnyOfRuleUrl]] and [[addNoneOfRuleUrl]].\n *\n * @param policy The [[Policy]] to which the rule should be added.\n * @param rule The rule to add to the policy.\n * @returns A new [[Policy]] clone of the original one, with the new rule added.\n * @since 1.6.0\n */\nfunction addAllOfRuleUrl(policy, rule) {\n return addIri(policy, acp.allOf, rule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Removes a rule that refines the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is **not** present in **any** of the \"All Of\" rules,\n * they will not be granted access.\n * @param policy The [[Policy]] from which the rule should be removed.\n * @param rule The rule to remove from the policy.\n * @returns A new [[Policy]] clone of the original one, with the rule removed.\n * @since 1.6.0\n */\nfunction removeAllOfRuleUrl(policy, rule) {\n return removeIri(policy, acp.allOf, rule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Overwrites the rule refining the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is **not** present in **any** of the \"All Of\" rules,\n * they will not be granted access.\n * @param policy The [[Policy]] to which the rule should be added.\n * @param rules The rules the policy requires.\n * @returns A new [[Policy]] clone of the original one, with the \"All Of\" rules replaced.\n * @since 1.6.0\n */\nfunction setAllOfRuleUrl(policy, rule) {\n return setIri(policy, acp.allOf, rule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the \"All Of\" [[Rule]]s for the given [[Policy]]\n * @param policy The [[policy]] from which the rules should be read.\n * @returns A list of the \"All Of\" [[Rule]]s\n * @since 1.6.0\n */\nfunction getAllOfRuleUrlAll(policy) {\n return getIriAll(policy, acp.allOf);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Add a rule that extends the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is present in **any** of the \"Any Of\" rules,\n * they will be granted access.\n *\n * Also see [[addAllOfRuleUrl]] and [[addNoneOfRuleUrl]].\n *\n * @param policy The [[Policy]] to which the rule should be added.\n * @param rule The rule to add to the policy.\n * @returns A new [[Policy]] clone of the original one, with the new rule added.\n * @since 1.6.0\n */\nfunction addAnyOfRuleUrl(policy, rule) {\n return addIri(policy, acp.anyOf, rule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Removes a rule that extends the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is present in **any** of the \"Any Of\" rules,\n * they will be granted access.\n * @param policy The [[Policy]] from which the rule should be removed.\n * @param rule The rule to remove from the policy.\n * @returns A new [[Policy]] clone of the original one, with the rule removed.\n * @since 1.6.0\n */\nfunction removeAnyOfRuleUrl(policy, rule) {\n return removeIri(policy, acp.anyOf, rule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Overwrite the rule extending the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is present in **any** of the \"Any Of\" rules,\n * they will be granted access.\n * @param policy The [[Policy]] to which the rule should be added.\n * @param rules The rules the policy accepts.\n * @returns A new [[Policy]] clone of the original one, with the \"Any Of\" rules replaced.\n * @since 1.6.0\n */\nfunction setAnyOfRuleUrl(policy, rule) {\n return setIri(policy, acp.anyOf, rule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the \"Any Of\" [[Rule]]s for the given [[Policy]]\n * @param policy The [[policy]] from which the rules should be read.\n * @returns A list of the \"Any Of\" [[Rule]]s\n * @since 1.6.0\n */\nfunction getAnyOfRuleUrlAll(policy) {\n return getIriAll(policy, acp.anyOf);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Add a rule that restricts the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is present in **any** of the forbidden rules,\n * they will **not** be granted access.\n *\n * Also see [[addAllOfRuleUrl]] and [[addAnyOfRuleUrl]].\n *\n * @param policy The [[Policy]] to which the rule should be added.\n * @param rule The rule to add to the policy.\n * @returns A new [[Policy]] clone of the original one, with the new rule added.\n * @since 1.6.0\n */\nfunction addNoneOfRuleUrl(policy, rule) {\n return addIri(policy, acp.noneOf, rule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Removes a rule that restricts the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is present in **any** of the forbidden rules,\n * they will **not** be granted access.\n * @param policy The [[Policy]] from which the rule should be removed.\n * @param rule The rule to remove from the policy.\n * @returns A new [[Policy]] clone of the original one, with the rule removed.\n * @since 1.6.0\n */\nfunction removeNoneOfRuleUrl(policy, rule) {\n return removeIri(policy, acp.noneOf, rule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set the rules restrincting the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is present in **any** of the \"None Of\" rules,\n * they will not be granted access.\n * @param policy The [[Policy]] to which the rule should be added.\n * @param rules The rules the policy accepts.\n * @returns A new [[Policy]] clone of the original one, with the \"Any Of\" rules replaced.\n * @since 1.6.0\n */\nfunction setNoneOfRuleUrl(policy, rule) {\n return setIri(policy, acp.noneOf, rule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the \"None Of\" [[Rule]]s for the given [[Policy]]\n * @param policy The [[policy]] from which the rules should be read.\n * @returns A list of the forbidden [[Rule]]s\n * @since 1.6.0\n */\nfunction getNoneOfRuleUrlAll(policy) {\n return getIriAll(policy, acp.noneOf);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Initialise a new, empty [[Rule]].\n *\n * @param url URL that identifies this [[Rule]].\n * @since 1.6.0\n */\nfunction createRule(url) {\n const stringUrl = internal_toIriString(url);\n let ruleThing = createThing({ url: stringUrl });\n ruleThing = setUrl(ruleThing, rdf.type, acp.Rule);\n return ruleThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Initialise a new, empty [[ResourceRule]] for the given Resource.\n *\n * @param resourceWithAcr The Resource to which the new Rule is to apply.\n * @param name Name that identifies this [[Rule]].\n * @since 1.6.0\n */\nfunction createResourceRuleFor(resourceWithAcr, name) {\n const acr = internal_getAcr(resourceWithAcr);\n const url = new URL(getSourceUrl(acr));\n url.hash = `#${name}`;\n let ruleThing = createThing({ url: url.href });\n ruleThing = setUrl(ruleThing, rdf.type, acp.Rule);\n return ruleThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the [[Rule]] with the given URL from an [[SolidDataset]].\n *\n * @param ruleResource The Resource that contains the given [[Rule]].\n * @param url URL that identifies this [[Rule]].\n * @returns The requested [[Rule]], if it exists, or `null` if it does not.\n * @since 1.6.0\n */\nfunction getRule(ruleResource, url) {\n const foundThing = getThing(ruleResource, url);\n if (foundThing === null || getUrl(foundThing, rdf.type) !== acp.Rule) {\n return null;\n }\n return foundThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the [[ResourceRule]] with the given name from an Resource's Access Control\n * Resource.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains the given [[ResourceRule]].\n * @param name Name that identifies this [[ResourceRule]].\n * @returns The requested [[ResourceRule]], if it exists, or `null` if it does not.\n * @since 1.6.0\n */\nfunction getResourceRule(resourceWithAcr, name) {\n const acr = internal_getAcr(resourceWithAcr);\n const acrUrl = getSourceUrl(acr);\n const url = new URL(acrUrl);\n url.hash = `#${name}`;\n const foundThing = getThing(acr, url.href);\n if (foundThing === null || !isRule(foundThing)) {\n return null;\n }\n return foundThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Gets the [[Rule]]s from a [[SolidDataset]].\n *\n * @param ruleResource The Resource that contains (zero or more) [[Rule]]s.\n * @returns The [[Rule]]s contained in this resource.\n * @since 1.6.0\n */\nfunction getRuleAll(ruleResource) {\n const things = getThingAll(ruleResource);\n return things.filter(isRule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Gets the [[ResourceRule]]s from a Resource's Access Control Resource.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains (zero or more) [[ResourceRule]]s.\n * @returns The [[ResourceRule]]s contained in this Resource's Access Control Resource.\n * @since 1.6.0\n */\nfunction getResourceRuleAll(resourceWithAcr) {\n const acr = internal_getAcr(resourceWithAcr);\n const things = getThingAll(acr);\n return things.filter(isRule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Removes the given [[Rule]] from the given [[SolidDataset]].\n *\n * @param ruleResource The Resource that contains (zero or more) [[Rule]]s.\n * @returns A new SolidDataset equal to the given Rule Resource, but without the given Rule.\n * @since 1.6.0\n */\nfunction removeRule(ruleResource, rule) {\n return removeThing(ruleResource, rule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Removes the given [[ResourceRule]] from the given Resource's Access Control Resource.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains (zero or more) [[ResourceRule]]s.\n * @returns A new Resource equal to the given Resource, but without the given Rule in its ACR.\n * @since 1.6.0\n */\nfunction removeResourceRule(resourceWithAcr, rule) {\n const acr = internal_getAcr(resourceWithAcr);\n let ruleToRemove;\n if (typeof rule === \"string\") {\n if (internal_isValidUrl(rule)) {\n ruleToRemove = rule;\n }\n else {\n // If the given Rule to remove is the name of the Rule,\n // resolve it to its full URL — developers usually refer to either the\n // Rule itself, or by its name, as they do not have access to the ACR\n // directly.\n const ruleUrl = new URL(getSourceUrl(acr));\n ruleUrl.hash = `#${rule}`;\n ruleToRemove = ruleUrl.href;\n }\n }\n else if (isNamedNode(rule)) {\n ruleToRemove = internal_toIriString(rule);\n }\n else {\n ruleToRemove = asUrl(rule);\n }\n // Check whether the actual Rule (i.e. with the Rule type) exists:\n const matchingRule = getResourceRule(resourceWithAcr, new URL(ruleToRemove).hash.substring(1));\n if (matchingRule === null) {\n // No such Rule exists yet, so return the Resource+ACR unchanged:\n return resourceWithAcr;\n }\n const updatedAcr = removeThing(acr, matchingRule);\n const updatedResource = internal_setAcr(resourceWithAcr, updatedAcr);\n return updatedResource;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Insert the given [[Rule]] into the given [[SolidDataset]], replacing previous\n * instances of that Rule.\n *\n * @param ruleResource The Resource that contains (zero or more) [[Rule]]s.\n * @returns A new SolidDataset equal to the given Rule Resource, but with the given Rule.\n * @since 1.6.0\n */\nfunction setRule(ruleResource, rule) {\n return setThing(ruleResource, rule);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Insert the given [[ResourceRule]] into the given Resource's Access Control Resource,\n * replacing previous instances of that Rule.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains (zero or more) [[ResourceRule]]s.\n * @returns A new Resource equal to the given Resource, but with the given Rule in its ACR.\n * @since 1.6.0\n */\nfunction setResourceRule(resourceWithAcr, rule) {\n const acr = internal_getAcr(resourceWithAcr);\n const updatedAcr = setThing(acr, rule);\n const updatedResource = internal_setAcr(resourceWithAcr, updatedAcr);\n return updatedResource;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * List all the agents a [[Rule]] applies **directly** to. This will not include agents\n * that are part of a group the [[Rule]] applies to, nor will it include specific agent\n * classes, such as authenticated or public agents.\n *\n * @param rule The rule from which agents are read.\n * @returns A list of the WebIDs of agents included in the rule.\n * @since 1.6.0\n */\nfunction getAgentAll$1(rule) {\n return getIriAll(rule, acp.agent).filter((agent) => agent !== acp.PublicAgent &&\n agent !== acp.AuthenticatedAgent &&\n agent !== acp.CreatorAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Overwrite the agents the [[Rule]] applies to with the provided agents.\n *\n * @param rule The rule for which agents are set.\n * @param agent The agent the rule should apply to.\n * @returns A copy of the input rule, applying to a different set of agents.\n * @since 1.6.0\n */\nfunction setAgent$1(rule, agent) {\n // Preserve the special agent classes authenticated and public, which we\n // don't want to overwrite with this function.\n const isPublic = hasPublic$1(rule);\n const isAuthenticated = hasAuthenticated$1(rule);\n const isCreator = hasCreator$1(rule);\n let result = setIri(rule, acp.agent, agent);\n // Restore public and authenticated\n if (isPublic) {\n result = setPublic$1(result);\n }\n if (isAuthenticated) {\n result = setAuthenticated$1(result);\n }\n if (isCreator) {\n result = setCreator$1(result);\n }\n return result;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Apply the [[Rule]] to an additional agent.\n *\n * @param rule The [[Rule]] to be applied to an additional agent.\n * @param agent The agent the [[Rule]] should apply to.\n * @returns A copy of the [[Rule]], applying to an additional agent.\n * @since 1.6.0\n */\nfunction addAgent$1(rule, agent) {\n return addIri(rule, acp.agent, agent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Prevent the [[Rule]] from applying to a given agent directly. This will not\n * remove the agent from any groups the rule applies to.\n *\n * @param rule The [[Rule]] that should no longer apply to a given agent.\n * @param agent The agent the rule should no longer apply to.\n * @returns A copy of the rule, not applying to the given agent.\n * @since 1.6.0\n */\nfunction removeAgent$1(rule, agent) {\n return removeIri(rule, acp.agent, agent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Lists all the groups a [[Rule]] applies to.\n *\n * @param rule The rule from which groups are read.\n * @returns A list of the [[URL]]'s of groups included in the rule.\n * @since 1.6.0\n * @deprecated Access Control Policies will no longer support vcard:Group. You can re-use a Rule listing multiple Agents to get the same functionality.\n */\nfunction getGroupAll(rule) {\n return getIriAll(rule, acp.group);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Overwrite the groups the [[Rule]] applies to with the provided groups.\n *\n * @param rule The rule for which groups are set.\n * @param group The group the rule should apply to.\n * @returns A copy of the input rule, applying to a different set of groups.\n * @since 1.6.0\n * @deprecated Access Control Policies will no longer support vcard:Group. You can re-use a Rule listing multiple Agents to get the same functionality.\n */\nfunction setGroup(rule, group) {\n return setIri(rule, acp.group, group);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Apply the [[Rule]] to an additional group.\n *\n * @param rule The [[Rule]] to be applied to an additional group.\n * @param agent The group the [[Rule]] should apply to.\n * @returns A copy of the [[Rule]], applying to an additional group.\n * @since 1.6.0\n * @deprecated Access Control Policies will no longer support vcard:Group. You can re-use a Rule listing multiple Agents to get the same functionality.\n */\nfunction addGroup(rule, group) {\n return addIri(rule, acp.group, group);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Prevent the [[Rule]] from applying to a given group.\n *\n * @param rule The [[Rule]] that should no longer apply to a given group.\n * @param agent The group the rule should no longer apply to.\n * @returns A copy of the rule, not applying to the given group.\n * @since 1.6.0\n * @deprecated Access Control Policies will no longer support vcard:Group. You can re-use a Rule listing multiple Agents to get the same functionality.\n */\nfunction removeGroup(rule, group) {\n return removeIri(rule, acp.group, group);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Check if the rule applies to any agent.\n *\n * @param rule The rule checked for public access.\n * @returns Whether the rule applies to any agent or not.\n * @since 1.6.0\n */\nfunction hasPublic$1(rule) {\n return (getIriAll(rule, acp.agent).filter((agent) => agent === acp.PublicAgent)\n .length > 0);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set a Rule to apply to any Agent.\n *\n * @param rule The rule being modified.\n * @returns A copy of the rule, updated to apply to any agent.\n * @since 1.6.0\n */\nfunction setPublic$1(rule) {\n // The second argument should not be part of the function signature,\n // so it's not in the parameter list:\n // eslint-disable-next-line prefer-rest-params\n if (typeof arguments === \"object\" && typeof arguments[1] === \"boolean\") {\n throw new Error(\"The function `setPublic` no longer takes a second parameter. It is now used together with `removePublic` instead.\");\n }\n return addIri(rule, acp.agent, acp.PublicAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set a Rule to no longer apply to any Agent.\n *\n * @param rule The rule being modified.\n * @returns A copy of the rule, updated to no longer apply to any agent.\n * @since 1.6.0\n */\nfunction removePublic$1(rule) {\n return removeIri(rule, acp.agent, acp.PublicAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Check if the rule applies to any authenticated agent.\n *\n * @param rule The rule checked for authenticated access.\n * @returns Whether the rule applies to any authenticated agent or not.\n * @since 1.6.0\n */\nfunction hasAuthenticated$1(rule) {\n return (getIriAll(rule, acp.agent).filter((agent) => agent === acp.AuthenticatedAgent).length > 0);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set a Rule to apply to any authenticated Agent.\n *\n * @param rule The rule being modified.\n * @returns A copy of the rule, updated to apply to any authenticated Agent.\n * @since 1.6.0\n */\nfunction setAuthenticated$1(rule) {\n // The second argument should not be part of the function signature,\n // so it's not in the parameter list:\n // eslint-disable-next-line prefer-rest-params\n if (typeof arguments === \"object\" && typeof arguments[1] === \"boolean\") {\n throw new Error(\"The function `setAuthenticated` no longer takes a second parameter. It is now used together with `removeAuthenticated` instead.\");\n }\n return addIri(rule, acp.agent, acp.AuthenticatedAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set a Rule to no longer apply to any authenticated Agent.\n *\n * @param rule The rule being modified.\n * @returns A copy of the rule, updated to apply/not apply to any authenticated agent.\n * @since 1.6.0\n */\nfunction removeAuthenticated$1(rule) {\n return removeIri(rule, acp.agent, acp.AuthenticatedAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Check if the rule applies to the creator of the Resource.\n *\n * @param rule The rule checked for authenticated access.\n * @returns Whether the rule applies to the creator of the Resource or not.\n * @since 1.6.0\n */\nfunction hasCreator$1(rule) {\n return (getIriAll(rule, acp.agent).filter((agent) => agent === acp.CreatorAgent)\n .length > 0);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set a Rule to apply to the creator of a Resource.\n *\n * @param rule The rule being modified.\n * @returns A copy of the rule, updated to apply to the creator of a Resource.\n * @since 1.6.0\n */\nfunction setCreator$1(rule) {\n // The second argument should not be part of the function signature,\n // so it's not in the parameter list:\n // eslint-disable-next-line prefer-rest-params\n if (typeof arguments === \"object\" && typeof arguments[1] === \"boolean\") {\n throw new Error(\"The function `setCreator` no longer takes a second parameter. It is now used together with `removeCreator` instead.\");\n }\n return addIri(rule, acp.agent, acp.CreatorAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set a Rule to no longer apply to the creator of a Resource.\n *\n * @param rule The rule being modified.\n * @returns A copy of the rule, updated to apply/not apply to the creator of a Resource.\n * @since 1.6.0\n */\nfunction removeCreator$1(rule) {\n return removeIri(rule, acp.agent, acp.CreatorAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * List all the clients a [[Rule]] applies **directly** to. This will not include\n * specific client classes, such as public clients.\n *\n * @param rule The rule from which clients are read.\n * @returns A list of the WebIDs of clients included in the rule.\n * @since 1.6.0\n */\nfunction getClientAll$1(rule) {\n return getIriAll(rule, acp.client).filter((client) => client !== solid.PublicOidcClient);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Overwrite the clients the [[Rule]] applies to with the provided Client.\n *\n * @param rule The rule for which clients are set.\n * @param client The Client the rule should apply to.\n * @returns A copy of the input rule, applying to a different set of Clients.\n * @since 1.6.0\n */\nfunction setClient$1(rule, client) {\n // Preserve the special \"any client\" class, which we\n // don't want to overwrite with this function.\n const anyClientEnabled = hasAnyClient$1(rule);\n let result = setIri(rule, acp.client, client);\n // Restore the \"any client\" class\n if (anyClientEnabled) {\n result = setAnyClient$1(result);\n }\n return result;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Apply the [[Rule]] to an additional Client.\n *\n * @param rule The [[Rule]] to be applied to an additional Client.\n * @param client The Client the [[Rule]] should apply to.\n * @returns A copy of the [[Rule]], applying to an additional Client.\n * @since 1.6.0\n */\nfunction addClient$1(rule, client) {\n return addIri(rule, acp.client, client);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Prevent the [[Rule]] from applying to a given Client directly.\n *\n * @param rule The [[Rule]] that should no longer apply to a given Client.\n * @param client The Client the rule should no longer apply to.\n * @returns A copy of the rule, not applying to the given Client.\n * @since 1.6.0\n */\nfunction removeClient$1(rule, client) {\n return removeIri(rule, acp.client, client);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Check if the rule applies to any client, i.e. all the applications\n * regardless of their identifier.\n *\n * @param rule The rule checked for authenticated access.\n * @returns Whether the rule applies to public clients.\n * @since 1.6.0\n */\nfunction hasAnyClient$1(rule) {\n return (getIriAll(rule, acp.client).filter((client) => client === solid.PublicOidcClient).length > 0);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Make the [[Rule]] apply to any client application.\n *\n * @param rule The rule for which clients are set.\n * @returns A copy of the rule, updated to apply to any client\n * @since 1.6.0\n */\nfunction setAnyClient$1(rule) {\n return addIri(rule, acp.client, solid.PublicOidcClient);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Make the [[Rule]] no longer apply to any client application.\n *\n * @param rule The rule for which clients are set.\n * @returns A copy of the rule, updated to no longer apply to any client\n * @since 1.6.0\n */\nfunction removeAnyClient$1(rule) {\n return removeIri(rule, acp.client, solid.PublicOidcClient);\n}\n/**\n * Gets a human-readable representation of the given [[Rule]] to aid debugging.\n *\n * Note that changes to the exact format of the return value are not considered a breaking change;\n * it is intended to aid in debugging, not as a serialisation method that can be reliably parsed.\n *\n * @param rule The Rule to get a human-readable representation of.\n * @since 1.6.0\n */\nfunction ruleAsMarkdown(rule) {\n let markdown = `## Rule: ${asUrl(rule)}\\n\\n`;\n let targetEnumeration = \"\";\n if (hasPublic$1(rule)) {\n targetEnumeration += \"- Everyone\\n\";\n }\n if (hasAuthenticated$1(rule)) {\n targetEnumeration += \"- All authenticated agents\\n\";\n }\n if (hasCreator$1(rule)) {\n targetEnumeration += \"- The creator of this resource\\n\";\n }\n if (hasAnyClient$1(rule)) {\n targetEnumeration += \"- Users of any client application\\n\";\n }\n const targetAgents = getAgentAll$1(rule);\n if (targetAgents.length > 0) {\n targetEnumeration += \"- The following agents:\\n - \";\n targetEnumeration += `${targetAgents.join(\"\\n - \")}\\n`;\n }\n const targetGroups = getGroupAll(rule);\n if (targetGroups.length > 0) {\n targetEnumeration += \"- Members of the following groups:\\n - \";\n targetEnumeration += `${targetGroups.join(\"\\n - \")}\\n`;\n }\n const targetClients = getClientAll$1(rule);\n if (targetClients.length > 0) {\n targetEnumeration += \"- Users of the following client applications:\\n - \";\n targetEnumeration += `${targetClients.join(\"\\n - \")}\\n`;\n }\n markdown +=\n targetEnumeration.length > 0\n ? `This rule applies to:\\n${targetEnumeration}`\n : \"\\n\";\n return markdown;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @param thing the [[Thing]] to check to see if it's an ACP Policy or not\n */\nfunction isPolicy(thing) {\n return getIriAll(thing, rdf.type).includes(acp.Policy);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Initialise a new, empty [[Policy]].\n *\n * @param url URL that identifies this Policy.\n * @since 1.6.0\n */\nfunction createPolicy(url) {\n const stringUrl = internal_toIriString(url);\n let policyThing = createThing({ url: stringUrl });\n policyThing = setUrl(policyThing, rdf.type, acp.Policy);\n return policyThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the [[Policy]] with the given URL from an [[SolidDataset]].\n *\n * @param policyResource The Resource that contains the given Policy.\n * @param url URL that identifies this Policy.\n * @returns The requested Policy, if it exists, or `null` if it does not.\n * @since 1.6.0\n */\nfunction getPolicy(policyResource, url) {\n const foundThing = getThing(policyResource, url);\n if (foundThing === null || !isPolicy(foundThing)) {\n return null;\n }\n return foundThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get all [[Policy]]'s in a given [[SolidDataset]].\n *\n * @param policyResource The Resource that contains Access Policies.\n * @since 1.6.0\n */\nfunction getPolicyAll(policyResource) {\n const foundThings = getThingAll(policyResource);\n const foundPolicies = foundThings.filter((thing) => !isThingLocal(thing) && isPolicy(thing));\n return foundPolicies;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Remove the given [[Policy]] from the given [[SolidDataset]].\n *\n * @param policyResource The Resource that contains Access Policies.\n * @param policy The Policy to remove from the resource.\n * @since 1.6.0\n */\nfunction removePolicy(policyResource, policy) {\n return removeThing(policyResource, policy);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Insert the given [[Policy]] into the given [[SolidDataset]], replacing previous instances of that Policy.\n *\n * @param policyResource The Resource that contains Access Policies.\n * @param policy The Policy to insert into the Resource.\n * @returns A new dataset equal to the given resource, but with the given Policy.\n * @since 1.6.0\n */\nfunction setPolicy(policyResource, policy) {\n return setThing(policyResource, policy);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Given a [[Policy]] and a set of [[AccessModes]], return a new Policy based on the given\n * Policy, but with the given Access Modes allowed on it.\n *\n * @param policy The Policy on which to set the modes to allow.\n * @param modes Modes to allow for this Policy.\n * @since Not released yet.\n */\nfunction setAllowModesV2(policy, modes) {\n let newPolicy = removeAll(policy, acp.allow);\n if (modes.read === true) {\n newPolicy = addIri(newPolicy, acp.allow, internal_accessModeIriStrings.read);\n }\n if (modes.append === true) {\n newPolicy = addIri(newPolicy, acp.allow, internal_accessModeIriStrings.append);\n }\n if (modes.write === true) {\n newPolicy = addIri(newPolicy, acp.allow, internal_accessModeIriStrings.write);\n }\n return newPolicy;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Given a [[Policy]] and a set of [[AccessModes]], return a new Policy based on the given\n * Policy, but with the given Access Modes allowed on it.\n *\n * @param policy The Policy on which to set the modes to allow.\n * @param modes Modes to allow for this Policy.\n * @since 1.6.0\n * @deprecated The Access Control Policies proposal will be updated to use a different vocabulary for allow- and deny-modes. To be compatible with servers that implement that, use [[setAllowModesV2]].\n */\nfunction setAllowModesV1(policy, modes) {\n let newPolicy = removeAll(policy, acp.allow);\n if (modes.read === true) {\n newPolicy = addIri(newPolicy, acp.allow, acp.Read);\n }\n if (modes.append === true) {\n newPolicy = addIri(newPolicy, acp.allow, acp.Append);\n }\n if (modes.write === true) {\n newPolicy = addIri(newPolicy, acp.allow, acp.Write);\n }\n return newPolicy;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Given a [[Policy]], return which [[AccessModes]] it allows.\n *\n * @param policy The Policy for which you want to know the Access Modes it allows.\n * @since Not released yet.\n */\nfunction getAllowModesV2(policy) {\n const allowedModes = getIriAll(policy, acp.allow);\n return {\n read: allowedModes.includes(internal_accessModeIriStrings.read),\n append: allowedModes.includes(internal_accessModeIriStrings.append),\n write: allowedModes.includes(internal_accessModeIriStrings.write),\n };\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Given a [[Policy]], return which [[AccessModes]] it allows.\n *\n * @param policy The Policy for which you want to know the Access Modes it allows.\n * @since 1.6.0\n * @deprecated The Access Control Policies proposal will be updated to use a different vocabulary for allow- and deny-modes. To be compatible with servers that implement that, use [[getAllowModesV2]].\n */\nfunction getAllowModesV1(policy) {\n const allowedModes = getIriAll(policy, acp.allow);\n return {\n read: allowedModes.includes(acp.Read),\n append: allowedModes.includes(acp.Append),\n write: allowedModes.includes(acp.Write),\n };\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Given a [[Policy]] and a set of [[AccessModes]], return a new Policy based on the given\n * Policy, but with the given Access Modes disallowed on it.\n *\n * @param policy The Policy on which to set the modes to disallow.\n * @param modes Modes to disallow for this Policy.\n * @since Not released yet.\n */\nfunction setDenyModesV2(policy, modes) {\n let newPolicy = removeAll(policy, acp.deny);\n if (modes.read === true) {\n newPolicy = addIri(newPolicy, acp.deny, internal_accessModeIriStrings.read);\n }\n if (modes.append === true) {\n newPolicy = addIri(newPolicy, acp.deny, internal_accessModeIriStrings.append);\n }\n if (modes.write === true) {\n newPolicy = addIri(newPolicy, acp.deny, internal_accessModeIriStrings.write);\n }\n return newPolicy;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Given a [[Policy]] and a set of [[AccessModes]], return a new Policy based on the given\n * Policy, but with the given Access Modes disallowed on it.\n *\n * @param policy The Policy on which to set the modes to disallow.\n * @param modes Modes to disallow for this Policy.\n * @since 1.6.0\n * @deprecated The Access Control Policies proposal will be updated to use a different vocabulary for allow- and deny-modes. To be compatible with servers that implement that, use [[setDenyModesV2]].\n */\nfunction setDenyModesV1(policy, modes) {\n let newPolicy = removeAll(policy, acp.deny);\n if (modes.read === true) {\n newPolicy = addIri(newPolicy, acp.deny, acp.Read);\n }\n if (modes.append === true) {\n newPolicy = addIri(newPolicy, acp.deny, acp.Append);\n }\n if (modes.write === true) {\n newPolicy = addIri(newPolicy, acp.deny, acp.Write);\n }\n return newPolicy;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Given a [[Policy]], return which [[AccessModes]] it disallows.\n *\n * @param policy The Policy on which you want to know the Access Modes it disallows.\n * @since Not released yet.\n */\nfunction getDenyModesV2(policy) {\n const deniedModes = getIriAll(policy, acp.deny);\n return {\n read: deniedModes.includes(internal_accessModeIriStrings.read),\n append: deniedModes.includes(internal_accessModeIriStrings.append),\n write: deniedModes.includes(internal_accessModeIriStrings.write),\n };\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Given a [[Policy]], return which [[AccessModes]] it disallows.\n *\n * @param policy The Policy on which you want to know the Access Modes it disallows.\n * @since 1.6.0\n * @deprecated The Access Control Policies proposal will be updated to use a different vocabulary for allow- and deny-modes. To be compatible with servers that implement that, use [[getDenyModesV2]].\n */\nfunction getDenyModesV1(policy) {\n const deniedModes = getIriAll(policy, acp.deny);\n return {\n read: deniedModes.includes(acp.Read),\n append: deniedModes.includes(acp.Append),\n write: deniedModes.includes(acp.Write),\n };\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Initialise a new, empty [[ResourcePolicy]] for the given Resource.\n *\n * @param resourceWithAcr The Resource to which the Policy is to apply.\n * @param name The name that identifies this Policy.\n * @since 1.6.0\n */\nfunction createResourcePolicyFor(resourceWithAcr, name) {\n const acr = internal_getAcr(resourceWithAcr);\n const url = new URL(getSourceUrl(acr));\n url.hash = `#${name}`;\n let policyThing = createThing({ url: url.href });\n policyThing = setUrl(policyThing, rdf.type, acp.Policy);\n return policyThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the [[ResourcePolicy]] with the given name that applies to a Resource\n * from its Access Control Resource.\n *\n * @param resourceWithAcr The Resource whose ACR contains the given Policy.\n * @param name The name that identifies this Policy.\n * @returns The requested Policy, if it exists and applies to the given Resource, or `null` if it does not.\n * @since 1.6.0\n */\nfunction getResourcePolicy(resourceWithAcr, name) {\n const acr = internal_getAcr(resourceWithAcr);\n const acrUrl = getSourceUrl(acr);\n const url = new URL(acrUrl);\n url.hash = `#${name}`;\n const foundThing = getThing(acr, url.href);\n if (!getPolicyUrlAll$1(resourceWithAcr).includes(url.href) ||\n foundThing === null ||\n !isPolicy(foundThing)) {\n return null;\n }\n return foundThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the [[ResourcePolicy]] with the given name that applies to a Resource's\n * Access Control Resource from that Access Control Resource.\n *\n * @param resourceWithAcr The Resource whose ACR contains the given Policy.\n * @param name The name that identifies this Policy.\n * @returns The requested Policy, if it exists and applies to the Resource's ACR, or `null` if it does not.\n * @since 1.6.0\n */\nfunction getResourceAcrPolicy(resourceWithAcr, name) {\n const acr = internal_getAcr(resourceWithAcr);\n const acrUrl = getSourceUrl(acr);\n const url = new URL(acrUrl);\n url.hash = `#${name}`;\n const foundThing = getThing(acr, url.href);\n if (!getAcrPolicyUrlAll$1(resourceWithAcr).includes(url.href) ||\n foundThing === null ||\n !isPolicy(foundThing)) {\n return null;\n }\n return foundThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get all [[ResourcePolicy]]'s that apply to a Resource in its Access Control\n * Resource.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains Access Policies applying to it.\n * @since 1.6.0\n */\nfunction getResourcePolicyAll(resourceWithAcr) {\n const acr = internal_getAcr(resourceWithAcr);\n const policyUrls = getPolicyUrlAll$1(resourceWithAcr);\n const foundThings = policyUrls.map((policyUrl) => getThing(acr, policyUrl));\n const foundPolicies = foundThings.filter((thing) => thing !== null && isPolicy(thing));\n return foundPolicies;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get all [[ResourcePolicy]]'s that apply to a given Resource's Access Control\n * Resource from that Access Control Resource.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains Access Policies.\n * @since 1.6.0\n */\nfunction getResourceAcrPolicyAll(resourceWithAcr) {\n const acr = internal_getAcr(resourceWithAcr);\n const policyUrls = getAcrPolicyUrlAll$1(resourceWithAcr);\n const foundThings = policyUrls.map((policyUrl) => getThing(acr, policyUrl));\n const foundPolicies = foundThings.filter((thing) => thing !== null && isPolicy(thing));\n return foundPolicies;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Remove the given [[ResourcePolicy]] from the given Resource's Access Control\n * Resource.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains Access Policies.\n * @param policy The Policy to remove from the Resource's Access Control Resource.\n * @since 1.6.0\n */\nfunction removeResourcePolicy(resourceWithAcr, policy) {\n const acr = internal_getAcr(resourceWithAcr);\n let policyToRemove = policy;\n if (typeof policyToRemove === \"string\") {\n if (internal_isValidUrl(policyToRemove) === false) {\n // If the given Policy to remove is the name of the Policy,\n // resolve it to its full URL — developers usually refer to either the\n // Policy itself, or by its name, as they do not have access to the ACR\n // directly.\n const policyUrl = new URL(getSourceUrl(acr));\n policyUrl.hash = `#${policy}`;\n policyToRemove = policyUrl.href;\n }\n }\n let policyUrlString;\n if (typeof policyToRemove === \"string\") {\n policyUrlString = policyToRemove;\n }\n else if (isNamedNode(policyToRemove)) {\n policyUrlString = internal_toIriString(policyToRemove);\n }\n else {\n policyUrlString = asUrl(policyToRemove, getSourceUrl(acr));\n }\n // Check whether the actual Policy (i.e. with the Policy type) exists:\n const matchingRule = getResourcePolicy(resourceWithAcr, new URL(policyUrlString).hash.substring(1));\n if (matchingRule === null) {\n // No such Policy exists yet, so return the Resource+ACR unchanged:\n return resourceWithAcr;\n }\n const updatedAcr = removeThing(acr, policyToRemove);\n const updatedResource = internal_setAcr(resourceWithAcr, updatedAcr);\n return removePolicyUrl$1(updatedResource, policyUrlString);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Remove the given [[ResourcePolicy]] that applies to a given Resource's Access\n * Control Resource from that Access Control Resource.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains Access Policies.\n * @param policy The ACR Policy to remove from the Resource's Access Control Resource.\n * @since 1.6.0\n */\nfunction removeResourceAcrPolicy(resourceWithAcr, policy) {\n const acr = internal_getAcr(resourceWithAcr);\n let policyToRemove = policy;\n if (typeof policyToRemove === \"string\") {\n if (internal_isValidUrl(policyToRemove) === false) {\n // If the given Policy to remove is the name of the Policy,\n // resolve it to its full URL — developers usually refer to either the\n // Policy itself, or by its name, as they do not have access to the ACR\n // directly.\n const policyUrl = new URL(getSourceUrl(acr));\n policyUrl.hash = `#${policy}`;\n policyToRemove = policyUrl.href;\n }\n }\n let policyUrlString;\n if (typeof policyToRemove === \"string\") {\n policyUrlString = policyToRemove;\n }\n else if (isNamedNode(policyToRemove)) {\n policyUrlString = internal_toIriString(policyToRemove);\n }\n else {\n policyUrlString = asUrl(policyToRemove, getSourceUrl(acr));\n }\n // Check whether the actual Policy (i.e. with the Policy type) exists:\n const matchingRule = getResourceAcrPolicy(resourceWithAcr, new URL(policyUrlString).hash.substring(1));\n if (matchingRule === null) {\n // No such Policy exists yet, so return the Resource+ACR unchanged:\n return resourceWithAcr;\n }\n const updatedAcr = removeThing(acr, policyToRemove);\n const updatedResource = internal_setAcr(resourceWithAcr, updatedAcr);\n return removeAcrPolicyUrl$1(updatedResource, policyUrlString);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Insert the given [[ResourcePolicy]] into the given Resource's Acccess Control\n * Resource, replacing previous instances of that Policy.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains Access Policies.\n * @param policy The Policy to insert into the Resource's Access Control Resource.\n * @returns A new Resource equal to the given Resource, but with the given Policy in its Access Control Resource.\n * @since 1.6.0\n */\nfunction setResourcePolicy$1(resourceWithAcr, policy) {\n const acr = internal_getAcr(resourceWithAcr);\n const updatedAcr = setThing(acr, policy);\n const updatedResource = internal_setAcr(resourceWithAcr, updatedAcr);\n const policyUrl = asUrl(policy, getSourceUrl(acr));\n return addPolicyUrl$1(updatedResource, policyUrl);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Insert the given [[ResourcePolicy]] into the given Resource's Acccess Control\n * Resource, replacing previous instances of that Policy, to apply to the Access\n * Control Resource itself.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains Access Policies.\n * @param policy The Policy to insert into the Resource's Access Control Resource.\n * @returns A new Resource equal to the given Resource, but with the given Policy in its Access Control Resource, applying to that Access Control Resource.\n * @since 1.6.0\n */\nfunction setResourceAcrPolicy(resourceWithAcr, policy) {\n const acr = internal_getAcr(resourceWithAcr);\n const updatedAcr = setThing(acr, policy);\n const updatedResource = internal_setAcr(resourceWithAcr, updatedAcr);\n const policyUrl = asUrl(policy, getSourceUrl(acr));\n return addAcrPolicyUrl$1(updatedResource, policyUrl);\n}\n/**\n * Gets a human-readable representation of the given [[Policy]] to aid debugging.\n *\n * Note that changes to the exact format of the return value are not considered a breaking change;\n * it is intended to aid in debugging, not as a serialisation method that can be reliably parsed.\n *\n * @param policy The Policy to get a human-readable representation of.\n * @since 1.6.0\n * @deprecated\n */\nfunction policyAsMarkdown(policy) {\n function getStatus(allow, deny) {\n if (deny) {\n return \"denied\";\n }\n if (allow) {\n return \"allowed\";\n }\n return \"unspecified\";\n }\n const allowModes = getAllowModesV1(policy);\n const denyModes = getDenyModesV1(policy);\n let markdown = `## Policy: ${asUrl(policy)}\\n\\n`;\n markdown += `- Read: ${getStatus(allowModes.read, denyModes.read)}\\n`;\n markdown += `- Append: ${getStatus(allowModes.append, denyModes.append)}\\n`;\n markdown += `- Write: ${getStatus(allowModes.write, denyModes.write)}\\n`;\n const allOfRules = getAllOfRuleUrlAll(policy);\n const anyOfRules = getAnyOfRuleUrlAll(policy);\n const noneOfRules = getNoneOfRuleUrlAll(policy);\n if (allOfRules.length === 0 &&\n anyOfRules.length === 0 &&\n noneOfRules.length === 0) {\n markdown += \"\\n\\n\";\n }\n if (allOfRules.length > 0) {\n markdown += \"\\nAll of these rules should match:\\n\";\n markdown += `- ${allOfRules.join(\"\\n- \")}\\n`;\n }\n if (anyOfRules.length > 0) {\n markdown += \"\\nAt least one of these rules should match:\\n\";\n markdown += `- ${anyOfRules.join(\"\\n- \")}\\n`;\n }\n if (noneOfRules.length > 0) {\n markdown += \"\\nNone of these rules should match:\\n\";\n markdown += `- ${noneOfRules.join(\"\\n- \")}\\n`;\n }\n return markdown;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n *\n * ```{warning}\n * Do not use this function in production code. For use in **unit tests** that require a\n * [[AccessControlResource]].\n * ```\n *\n * Initialises a new empty Access Control Resource for a given Resource for use\n * in **unit tests**.\n *\n * @param resourceUrl The URL of the Resource to which the mocked ACR should apply.\n * @returns The mocked empty Access Control Resource for the given Resource.\n * @since 1.6.0\n */\nfunction mockAcrFor(resourceUrl) {\n const acrUrl = new URL(\"access-control-resource\", resourceUrl).href;\n const acr = {\n ...mockSolidDatasetFrom(acrUrl),\n accessTo: resourceUrl,\n };\n return acr;\n}\n/**\n * ```{warning}\n * Do not use this function in production code. For use in **unit tests** that require a\n * Resource with an [[AccessControlResource]].\n * ```\n *\n * Attaches an Access Control Resource to a given [[SolidDataset]] for use\n * in **unit tests**; e.g., unit tests that call [[getPolicyUrlAll]].\n *\n * @param resource The Resource to mock up with a new resource ACL.\n * @param accessControlResource The Access Control Resource to attach to the given Resource.\n * @returns The input Resource with an empty resource ACL attached.\n * @since 1.6.0\n */\nfunction addMockAcrTo(resource, accessControlResource = mockAcrFor(getSourceUrl(resource))) {\n const resourceWithAcr = Object.assign(internal_cloneResource(resource), {\n internal_acp: {\n acr: accessControlResource,\n aprs: {},\n },\n });\n return resourceWithAcr;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst v2AcpFunctions = {\n getFileWithAccessDatasets,\n getFileWithAcr,\n getReferencedPolicyUrlAll,\n getResourceInfoWithAccessDatasets,\n getResourceInfoWithAcr,\n getSolidDatasetWithAccessDatasets,\n getSolidDatasetWithAcr,\n hasAccessibleAcr,\n saveAcrFor,\n};\nconst v2ControlFunctions = {\n acrAsMarkdown,\n addAcrPolicyUrl: addAcrPolicyUrl$1,\n addMemberAcrPolicyUrl: addMemberAcrPolicyUrl$1,\n addMemberPolicyUrl: addMemberPolicyUrl$1,\n addPolicyUrl: addPolicyUrl$1,\n getAcrPolicyUrlAll: getAcrPolicyUrlAll$1,\n getMemberAcrPolicyUrlAll: getMemberAcrPolicyUrlAll$1,\n getMemberPolicyUrlAll: getMemberPolicyUrlAll$1,\n getPolicyUrlAll: getPolicyUrlAll$1,\n hasLinkedAcr,\n removeAcrPolicyUrl: removeAcrPolicyUrl$1,\n removeAcrPolicyUrlAll,\n removeMemberAcrPolicyUrl: removeMemberAcrPolicyUrl$1,\n removeMemberAcrPolicyUrlAll,\n removeMemberPolicyUrl: removeMemberPolicyUrl$1,\n removeMemberPolicyUrlAll,\n removePolicyUrl: removePolicyUrl$1,\n removePolicyUrlAll,\n};\nconst v2PolicyFunctions = {\n createPolicy,\n getAllowModes: getAllowModesV1,\n getDenyModes: getDenyModesV1,\n getPolicy,\n getPolicyAll,\n policyAsMarkdown,\n removePolicy,\n setAllowModes: setAllowModesV1,\n setDenyModes: setDenyModesV1,\n setPolicy,\n};\nconst v2RuleFunctions = {\n addAgent: addAgent$1,\n addForbiddenRuleUrl: addNoneOfRuleUrl,\n addGroup,\n addOptionalRuleUrl: addAnyOfRuleUrl,\n addRequiredRuleUrl: addAllOfRuleUrl,\n createRule,\n getAgentAll: getAgentAll$1,\n getForbiddenRuleUrlAll: getNoneOfRuleUrlAll,\n getGroupAll,\n getOptionalRuleUrlAll: getAnyOfRuleUrlAll,\n getRequiredRuleUrlAll: getAllOfRuleUrlAll,\n getRule,\n getRuleAll,\n hasAuthenticated: hasAuthenticated$1,\n hasCreator: hasCreator$1,\n hasPublic: hasPublic$1,\n removeAgent: removeAgent$1,\n removeForbiddenRuleUrl: removeNoneOfRuleUrl,\n removeGroup,\n removeOptionalRuleUrl: removeAnyOfRuleUrl,\n removeRequiredRuleUrl: removeAllOfRuleUrl,\n removeRule,\n ruleAsMarkdown,\n setAgent: setAgent$1,\n setForbiddenRuleUrl: setNoneOfRuleUrl,\n setGroup,\n setOptionalRuleUrl: setAnyOfRuleUrl,\n setRequiredRuleUrl: setAllOfRuleUrl,\n setRule,\n};\nconst v2MockFunctions = {\n addMockAcrTo,\n mockAcrFor,\n};\n/* istanbul ignore next Not a supported public API: */\n/** @deprecated Replaced by [[setPublic]] */\nfunction previousSetPublicSignature(rule, enable) {\n return enable ? setPublic$1(rule) : removePublic$1(rule);\n}\n/* istanbul ignore next Not a supported public API: */\n/** @deprecated Replaced by [[setAuthenticated]] */\nfunction previousSetAuthenticatedSignature(rule, enable) {\n return enable ? setAuthenticated$1(rule) : removeAuthenticated$1(rule);\n}\n/* istanbul ignore next Not a supported public API: */\n/** @deprecated Replaced by [[setCreator]] */\nfunction previousSetCreatorSignature(rule, enable) {\n return enable ? setCreator$1(rule) : removeCreator$1(rule);\n}\nconst deprecatedFunctions$1 = {\n /** @deprecated This misspelling was included accidentally. The correct function is [[getForbiddenRuleUrlAll]]. */\n getForbiddenRuleurlAll: getNoneOfRuleUrlAll,\n setPublic: previousSetPublicSignature,\n setAuthenticated: previousSetAuthenticatedSignature,\n setCreator: previousSetCreatorSignature,\n};\n/**\n * @hidden\n * @deprecated Replaced by [[acp_v3]].\n */\nconst acp_v2 = {\n ...v2AcpFunctions,\n ...v2ControlFunctions,\n ...v2PolicyFunctions,\n ...v2RuleFunctions,\n ...v2MockFunctions,\n ...deprecatedFunctions$1,\n};\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst v1AcpFunctions = {\n getFileWithAccessDatasets,\n getFileWithAcr,\n getReferencedPolicyUrlAll,\n getResourceInfoWithAccessDatasets,\n getResourceInfoWithAcr,\n getSolidDatasetWithAccessDatasets,\n getSolidDatasetWithAcr,\n hasAccessibleAcr,\n saveAcrFor,\n};\nconst v1PolicyFunctions = {\n createPolicy,\n getAllowModes: getAllowModesV1,\n getDenyModes: getDenyModesV1,\n getPolicy,\n getPolicyAll,\n policyAsMarkdown,\n removePolicy,\n setAllowModes: setAllowModesV1,\n setDenyModes: setDenyModesV1,\n setPolicy,\n};\nconst v1RuleFunctions = {\n addAgent: addAgent$1,\n addForbiddenRuleUrl: addNoneOfRuleUrl,\n addGroup,\n addOptionalRuleUrl: addAnyOfRuleUrl,\n addRequiredRuleUrl: addAllOfRuleUrl,\n createRule,\n getAgentAll: getAgentAll$1,\n getForbiddenRuleUrlAll: getNoneOfRuleUrlAll,\n getGroupAll,\n getOptionalRuleUrlAll: getAnyOfRuleUrlAll,\n getRequiredRuleUrlAll: getAllOfRuleUrlAll,\n getRule,\n getRuleAll,\n hasAuthenticated: hasAuthenticated$1,\n hasCreator: hasCreator$1,\n hasPublic: hasPublic$1,\n removeAgent: removeAgent$1,\n removeForbiddenRuleUrl: removeNoneOfRuleUrl,\n removeGroup,\n removeOptionalRuleUrl: removeAnyOfRuleUrl,\n removeRequiredRuleUrl: removeAllOfRuleUrl,\n removeRule,\n ruleAsMarkdown,\n setAgent: setAgent$1,\n setForbiddenRuleUrl: setNoneOfRuleUrl,\n setGroup,\n setOptionalRuleUrl: setAnyOfRuleUrl,\n setRequiredRuleUrl: setAllOfRuleUrl,\n setRule,\n};\nconst v1MockFunctions = {\n addMockAcrTo,\n mockAcrFor,\n};\nconst v1ControlFunctions = {\n hasLinkedAcr,\n addAcrPolicyUrl: addAcrPolicyUrl$1,\n addMemberAcrPolicyUrl: addMemberAcrPolicyUrl$1,\n getAcrPolicyUrlAll: getAcrPolicyUrlAll$1,\n getMemberAcrPolicyUrlAll: getMemberAcrPolicyUrlAll$1,\n removeAcrPolicyUrl: removeAcrPolicyUrl$1,\n removeAcrPolicyUrlAll,\n removeMemberAcrPolicyUrl: removeMemberAcrPolicyUrl$1,\n removeMemberAcrPolicyUrlAll,\n};\nconst deprecatedFunctions = {\n createControl: internal_createControl,\n getControl: internal_getControl,\n getAllControl: internal_getControlAll,\n getControlAll: internal_getControlAll,\n setControl: internal_setControl,\n removeControl,\n addPolicyUrl: internal_addPolicyUrl,\n getPolicyUrlAll: internal_getPolicyUrlAll,\n removePolicyUrl: internal_removePolicyUrl,\n removePolicyUrlAll: internal_removePolicyUrlAll,\n addMemberPolicyUrl: internal_addMemberPolicyUrl,\n getMemberPolicyUrlAll: internal_getMemberPolicyUrlAll,\n removeMemberPolicyUrl: internal_getMemberPolicyUrlAll,\n removeMemberPolicyUrlAll: internal_removeMemberPolicyUrlAll,\n /** @deprecated This misspelling was included accidentally. The correct function is [[getForbiddenRuleUrlAll]]. */\n getForbiddenRuleurlAll: getNoneOfRuleUrlAll,\n setPublic: previousSetPublicSignature,\n setAuthenticated: previousSetAuthenticatedSignature,\n setCreator: previousSetCreatorSignature,\n};\n/**\n * @hidden\n * @deprecated Replaced by [[acp_v2]].\n */\nconst acp_v1 = {\n ...v1AcpFunctions,\n ...v1PolicyFunctions,\n ...v1RuleFunctions,\n ...v1MockFunctions,\n ...v1ControlFunctions,\n ...deprecatedFunctions,\n};\n/**\n * ```{note} The Web Access Control specification is not yet finalised. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Remove an [[Control]] from the [[AccessControlResource]] of a Resource.\n *\n * @param withAccessControlResource A Resource with the Access Control Resource from which to remove an Access Control.\n * @param control The [[Control]] to remove from the given Access Control Resource.\n * @returns The given Resource with a new Access Control Resource equal to the original Access Control Resource, excluding the given Access Control.\n * @hidden Developers don't need to care about initialising Controls - they can just add Policies directly.\n * @deprecated\n */\nfunction removeControl(withAccessControlResource, control) {\n const acr = internal_getAcr(withAccessControlResource);\n const updatedAcr = removeThing(acr, control);\n const updatedResource = internal_setAcr(withAccessControlResource, updatedAcr);\n return updatedResource;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst v3AcpFunctions = {\n getFileWithAccessDatasets,\n getFileWithAcr,\n getLinkedAcrUrl,\n getReferencedPolicyUrlAll,\n getResourceInfoWithAccessDatasets,\n getResourceInfoWithAcr,\n getSolidDatasetWithAccessDatasets,\n getSolidDatasetWithAcr,\n hasAccessibleAcr,\n saveAcrFor,\n isAcpControlled,\n};\nconst v3ControlFunctions = {\n acrAsMarkdown,\n addAcrPolicyUrl: addAcrPolicyUrl$1,\n addMemberAcrPolicyUrl: addMemberAcrPolicyUrl$1,\n addMemberPolicyUrl: addMemberPolicyUrl$1,\n addPolicyUrl: addPolicyUrl$1,\n getAcrPolicyUrlAll: getAcrPolicyUrlAll$1,\n getMemberAcrPolicyUrlAll: getMemberAcrPolicyUrlAll$1,\n getMemberPolicyUrlAll: getMemberPolicyUrlAll$1,\n getPolicyUrlAll: getPolicyUrlAll$1,\n hasLinkedAcr,\n removeAcrPolicyUrl: removeAcrPolicyUrl$1,\n removeAcrPolicyUrlAll,\n removeMemberAcrPolicyUrl: removeMemberAcrPolicyUrl$1,\n removeMemberAcrPolicyUrlAll,\n removeMemberPolicyUrl: removeMemberPolicyUrl$1,\n removeMemberPolicyUrlAll,\n removePolicyUrl: removePolicyUrl$1,\n removePolicyUrlAll,\n};\nconst v3PolicyFunctions = {\n createPolicy,\n getAllowModes: getAllowModesV1,\n getDenyModes: getDenyModesV1,\n getPolicy,\n getPolicyAll,\n policyAsMarkdown,\n removePolicy,\n setAllowModes: setAllowModesV1,\n setDenyModes: setDenyModesV1,\n setPolicy,\n createResourcePolicyFor,\n getResourceAcrPolicy,\n getResourceAcrPolicyAll,\n getResourcePolicy,\n getResourcePolicyAll,\n removeResourceAcrPolicy,\n removeResourcePolicy,\n setResourceAcrPolicy,\n setResourcePolicy: setResourcePolicy$1,\n};\nconst v3RuleFunctions = {\n addAgent: addAgent$1,\n addGroup,\n createRule,\n getAgentAll: getAgentAll$1,\n getGroupAll,\n getRule,\n getRuleAll,\n removeAgent: removeAgent$1,\n removeGroup,\n removeRule,\n ruleAsMarkdown,\n setAgent: setAgent$1,\n setGroup,\n setRule,\n addClient: addClient$1,\n getClientAll: getClientAll$1,\n hasAnyClient: hasAnyClient$1,\n removeClient: removeClient$1,\n setAnyClient: setAnyClient$1,\n setClient: setClient$1,\n removeAnyClient: removeAnyClient$1,\n hasAuthenticated: hasAuthenticated$1,\n hasCreator: hasCreator$1,\n hasPublic: hasPublic$1,\n setAuthenticated: setAuthenticated$1,\n setCreator: setCreator$1,\n setPublic: setPublic$1,\n removeAuthenticated: removeAuthenticated$1,\n removeCreator: removeCreator$1,\n removePublic: removePublic$1,\n getAnyOfRuleUrlAll,\n addAnyOfRuleUrl,\n removeAnyOfRuleUrl,\n setAnyOfRuleUrl,\n getAllOfRuleUrlAll,\n addAllOfRuleUrl,\n removeAllOfRuleUrl,\n setAllOfRuleUrl,\n getNoneOfRuleUrlAll,\n addNoneOfRuleUrl,\n removeNoneOfRuleUrl,\n setNoneOfRuleUrl,\n createResourceRuleFor,\n getResourceRule,\n getResourceRuleAll,\n removeResourceRule,\n setResourceRule,\n};\nconst v3MockFunctions = {\n addMockAcrTo,\n mockAcrFor,\n};\n/**\n * @hidden\n * @deprecated Please import \"acp_ess_1\" directly.\n */\nconst acp_v3 = {\n ...v3AcpFunctions,\n ...v3ControlFunctions,\n ...v3PolicyFunctions,\n ...v3RuleFunctions,\n ...v3MockFunctions,\n};\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction setAccessControlResourceThing(resource, thing) {\n return Object.assign(internal_cloneResource(resource), {\n internal_acp: {\n ...resource.internal_acp,\n acr: setThing(resource.internal_acp.acr, thing),\n },\n });\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction getAccessControlTypeFromDefaultAccessControlName(name) {\n if (name.includes(\"Member\")) {\n return ACP.memberAccessControl;\n }\n return ACP.accessControl;\n}\n/** @hidden */\nfunction setDefaultAccessControlThingIfNotExist(resource, name) {\n const defaultAccessControlThingUrl = getDefaultAccessControlUrl(resource, name);\n const acr = internal_getAcr(resource);\n // Get the Access Control Resource Thing or create it\n let accessControlResourceThing = getAccessControlResourceThing(resource);\n if (accessControlResourceThing === null ||\n typeof accessControlResourceThing === \"undefined\") {\n accessControlResourceThing = createThing({ url: getSourceUrl(acr) });\n }\n // Get the Default Access Control Thing or create it and return\n const accessControlUrlAll = getIriAll(accessControlResourceThing, getAccessControlTypeFromDefaultAccessControlName(name));\n if (!accessControlUrlAll.includes(defaultAccessControlThingUrl)) {\n accessControlResourceThing = buildThing(accessControlResourceThing)\n .addUrl(getAccessControlTypeFromDefaultAccessControlName(name), defaultAccessControlThingUrl)\n .build();\n return setAccessControlResourceThing(resource, accessControlResourceThing);\n }\n // Return the original resource if the ACR and Default AC exist\n return resource;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Add a policy applying to the ACR of the given resource.\n *\n * @param resourceWithAcr The resource for which to add the URL of a policy\n * applying to its access control resource.\n * @param policyUrl A Policy URL.\n * @returns The resource with its ammended access control resource.\n * @since 1.16.1\n */\nfunction addAcrPolicyUrl(resourceWithAcr, policyUrl) {\n const resourceWithAcrContainingDefaultAccessControl = setDefaultAccessControlThingIfNotExist(resourceWithAcr, DEFAULT_ACR_ACCESS_CONTROL);\n const defaultAccessControlThing = getDefaultAccessControlThing(resourceWithAcrContainingDefaultAccessControl, DEFAULT_ACR_ACCESS_CONTROL);\n return setAccessControlResourceThing(resourceWithAcrContainingDefaultAccessControl, buildThing(defaultAccessControlThing).addUrl(ACP.access, policyUrl).build());\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Add a policy applying to the ACRs of the given resource's children.\n *\n * @param resourceWithAcr The resource for which to add the URL of a policy\n * applying to its children's access control resources.\n * @param policyUrl A Policy URL.\n * @returns The resource with its ammended access control resource.\n * @since 1.16.1\n */\nfunction addMemberAcrPolicyUrl(resourceWithAcr, policyUrl) {\n const resourceWithAcrContainingDefaultAccessControl = setDefaultAccessControlThingIfNotExist(resourceWithAcr, DEFAULT_MEMBER_ACR_ACCESS_CONTROL);\n const defaultAccessControlThing = getDefaultAccessControlThing(resourceWithAcrContainingDefaultAccessControl, DEFAULT_MEMBER_ACR_ACCESS_CONTROL);\n return setAccessControlResourceThing(resourceWithAcrContainingDefaultAccessControl, buildThing(defaultAccessControlThing).addUrl(ACP.access, policyUrl).build());\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Add a policy applying to the given resource's children.\n *\n * @param resourceWithAcr The resource for which to add the URL of a policy\n * applying to its children.\n * @param policyUrl A Policy URL.\n * @returns The resource with its ammended access control resource.\n * @since 1.16.1\n */\nfunction addMemberPolicyUrl(resourceWithAcr, policyUrl) {\n const resourceWithAcrContainingDefaultMemberAccessControl = setDefaultAccessControlThingIfNotExist(resourceWithAcr, DEFAULT_MEMBER_ACCESS_CONTROL);\n const defaultMemberAccessControlThing = getDefaultAccessControlThing(resourceWithAcrContainingDefaultMemberAccessControl, DEFAULT_MEMBER_ACCESS_CONTROL);\n return setAccessControlResourceThing(resourceWithAcrContainingDefaultMemberAccessControl, buildThing(defaultMemberAccessControlThing)\n .addUrl(ACP.apply, policyUrl)\n .build());\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Add a policy applying to the given resource.\n *\n * @param resourceWithAcr The resource for which to add the URL of a policy\n * applying to it.\n * @param policyUrl A Policy URL.\n * @returns The resource with its ammended access control resource.\n * @since 1.16.1\n */\nfunction addPolicyUrl(resourceWithAcr, policyUrl) {\n const resourceWithAcrContainingDefaultAccessControl = setDefaultAccessControlThingIfNotExist(resourceWithAcr, DEFAULT_ACCESS_CONTROL);\n const defaultAccessControlThing = getDefaultAccessControlThing(resourceWithAcrContainingDefaultAccessControl, DEFAULT_ACCESS_CONTROL);\n return setAccessControlResourceThing(resourceWithAcrContainingDefaultAccessControl, buildThing(defaultAccessControlThing).addUrl(ACP.apply, policyUrl).build());\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Get the URL of all access controls linked to the given resource's ACR.\n *\n * @param resourceWithAcr The resource for which to retrieve URLs of access\n * controls applying to it.\n * @returns Access Control URL array\n * @since 1.6.0\n */\nfunction getAccessControlUrlAll(resourceWithAcr) {\n const acrThing = getAccessControlResourceThing(resourceWithAcr);\n if (acrThing === null) {\n return [];\n }\n return getIriAll(acrThing, ACP.accessControl);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction getPolicyUrls(resource, accessControlUrls, type) {\n const acr = internal_getAcr(resource);\n return Array.from(new Set(accessControlUrls\n .map((accessControlUrl) => {\n const accessControlThing = getThing(acr, accessControlUrl);\n // istanbul ignore next\n if (accessControlThing !== null) {\n return getIriAll(accessControlThing, type);\n }\n // istanbul ignore next\n return [];\n })\n .reduce((previousValue, currentValue) => previousValue.concat(currentValue), [])));\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Get the URLs of policies applying to the ACR of the given resource.\n *\n * @param resourceWithAcr The resource for which to retrieve URLs of policies\n * applying to its access control resource.\n * @returns Policy URL array.\n * @since 1.16.1\n */\nfunction getAcrPolicyUrlAll(resourceWithAcr) {\n return getPolicyUrls(resourceWithAcr, getAccessControlUrlAll(resourceWithAcr), ACP.access);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Get the URL of all member access controls linked to the given resource's ACR.\n *\n * @param resourceWithAcr The resource for which to retrieve URLs of access\n * controls inherited by its children.\n * @returns Access Control URL array\n * @since 1.6.0\n */\nfunction getMemberAccessControlUrlAll(resourceWithAcr) {\n const acrThing = getAccessControlResourceThing(resourceWithAcr);\n if (acrThing === null) {\n return [];\n }\n return getIriAll(acrThing, ACP.memberAccessControl);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Get the URLs of policies applying to the ACRs of the given resource's\n * children.\n *\n * @param resourceWithAcr The resource for which to retrieve URLs of policies\n * applying to its children's access control resources.\n * @returns Policy URL array.\n * @since 1.16.1\n */\nfunction getMemberAcrPolicyUrlAll(resourceWithAcr) {\n return getPolicyUrls(resourceWithAcr, getMemberAccessControlUrlAll(resourceWithAcr), ACP.access);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Get the URLs of policies applying to the given resource's children.\n *\n * @param resourceWithAcr The resource for which to retrieve URLs policies\n * applying to its children.\n * @returns Policy URL array.\n * @since 1.16.1\n */\nfunction getMemberPolicyUrlAll(resourceWithAcr) {\n return getPolicyUrls(resourceWithAcr, getMemberAccessControlUrlAll(resourceWithAcr), ACP.apply);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Get the URLs of policies applying to the given resource.\n *\n * @param resourceWithAcr The resource for which to retrieve URLs of policies\n * applying to it.\n * @returns Policy URL array.\n * @since 1.16.1\n */\nfunction getPolicyUrlAll(resourceWithAcr) {\n return getPolicyUrls(resourceWithAcr, getAccessControlUrlAll(resourceWithAcr), ACP.apply);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Remove a policy applying to the ACR of the given resource.\n *\n * @param resourceWithAcr The resource for which to remove the URL of a policy\n * applying to its access control resource.\n * @param policyUrl A Policy URL.\n * @returns The resource with its ammended access control resource.\n * @since 1.16.1\n */\nfunction removeAcrPolicyUrl(resourceWithAcr, policyUrl) {\n const defaultAccessControlThing = getDefaultAccessControlThing(resourceWithAcr, DEFAULT_ACR_ACCESS_CONTROL);\n return setAccessControlResourceThing(resourceWithAcr, removeIri(defaultAccessControlThing, ACP.access, policyUrl));\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Remove a policy applying to the ACRs of the given resource's children.\n *\n * @param resourceWithAcr The resource for which to remove the URL of a policy\n * applying to its children's access control resources.\n * @param policyUrl A Policy URL.\n * @returns The resource with its ammended access control resource.\n * @since 1.16.1\n */\nfunction removeMemberAcrPolicyUrl(resourceWithAcr, policyUrl) {\n const defaultAccessControlThing = getDefaultAccessControlThing(resourceWithAcr, DEFAULT_MEMBER_ACR_ACCESS_CONTROL);\n return setAccessControlResourceThing(resourceWithAcr, removeIri(defaultAccessControlThing, ACP.access, policyUrl));\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Remove a policy applying to the given resource's children.\n *\n * @param resourceWithAcr The resource for which to remove the URL of a policy\n * applying to its children.\n * @param policyUrl A Policy URL.\n * @returns The resource with its ammended access control resource.\n * @since 1.16.1\n */\nfunction removeMemberPolicyUrl(resourceWithAcr, policyUrl) {\n const defaultAccessControlThing = getDefaultAccessControlThing(resourceWithAcr, DEFAULT_MEMBER_ACCESS_CONTROL);\n return setAccessControlResourceThing(resourceWithAcr, removeIri(defaultAccessControlThing, ACP.apply, policyUrl));\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Remove a policy applying to the given resource.\n *\n * @param resourceWithAcr The resource for which to remove the URL of a policy\n * applying to it.\n * @param policyUrl A Policy URL.\n * @returns The resource with its ammended access control resource.\n * @since 1.16.1\n */\nfunction removePolicyUrl(resourceWithAcr, policyUrl) {\n const defaultAccessControlThing = getDefaultAccessControlThing(resourceWithAcr, DEFAULT_ACCESS_CONTROL);\n return setAccessControlResourceThing(resourceWithAcr, removeIri(defaultAccessControlThing, ACP.apply, policyUrl));\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Insert the given [[ResourcePolicy]] into the given Resource's Acccess Control\n * Resource, replacing previous instances of that Policy.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains Access Policies.\n * @param policy The Policy to insert into the Resource's Access Control Resource.\n * @returns A new Resource equal to the given Resource, but with the given Policy in its Access Control Resource.\n * @since 1.18.0\n */\nfunction setResourcePolicy(resourceWithAcr, policy) {\n return setAccessControlResourceThing(resourceWithAcr, policy);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * @param thing the [[Thing]] to check to see if it's an ACP Matcher or not\n */\nfunction isMatcher(thing) {\n return getIriAll(thing, rdf.type).includes(acp.Matcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Add a Matcher that refines the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is **not** present in **any** of the \"All Of\" Matchers,\n * they will not be granted access.\n *\n * Also see [[addAnyOfMatcherUrl]] and [[addNoneOfMatcherUrl]].\n *\n * @param policy The [[Policy]] to which the Matcher should be added.\n * @param matcher The Matcher to add to the policy.\n * @returns A new [[Policy]] clone of the original one, with the new Matcher added.\n * @since Not released yet.\n */\nfunction addAllOfMatcherUrl(policy, matcher) {\n return addIri(policy, acp.allOf, matcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Removes a Matcher that refines the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is **not** present in **any** of the \"All Of\" Matchers,\n * they will not be granted access.\n * @param policy The [[Policy]] from which the Matcher should be removed.\n * @param matcher The Matcher to remove from the policy.\n * @returns A new [[Policy]] clone of the original one, with the Matcher removed.\n * @since Not released yet.\n */\nfunction removeAllOfMatcherUrl(policy, matcher) {\n return removeIri(policy, acp.allOf, matcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Overwrites the Matcher refining the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is **not** present in **any** of the \"All Of\" Matchers,\n * they will not be granted access.\n * @param policy The [[Policy]] to which the Matcher should be added.\n * @param matcher The Matcher to set for the Policy.\n * @returns A new [[Policy]] clone of the original one, with the \"All Of\" Matchers replaced.\n * @since Not released yet.\n */\nfunction setAllOfMatcherUrl(policy, matcher) {\n return setIri(policy, acp.allOf, matcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the \"All Of\" [[Matcher]]s for the given [[Policy]]\n * @param policy The [[policy]] from which the Matchers should be read.\n * @returns A list of the \"All Of\" [[Matcher]]s\n * @since Not released yet.\n */\nfunction getAllOfMatcherUrlAll(policy) {\n return getIriAll(policy, acp.allOf);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Add a Matcher that extends the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is present in **any** of the \"Any Of\" Matchers,\n * they will be granted access.\n *\n * Also see [[addAllOfMatcherUrl]] and [[addNoneOfMatcherUrl]].\n *\n * @param policy The [[Policy]] to which the Matcher should be added.\n * @param matcher The Matcher to add to the policy.\n * @returns A new [[Policy]] clone of the original one, with the new Matcher added.\n * @since Not released yet.\n */\nfunction addAnyOfMatcherUrl(policy, matcher) {\n return addIri(policy, acp.anyOf, matcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Removes a Matcher that extends the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is present in **any** of the \"Any Of\" Matchers,\n * they will be granted access.\n * @param policy The [[Policy]] from which the Matcher should be removed.\n * @param matcher The Matcher to remove from the policy.\n * @returns A new [[Policy]] clone of the original one, with the Matcher removed.\n * @since Not released yet.\n */\nfunction removeAnyOfMatcherUrl(policy, matcher) {\n return removeIri(policy, acp.anyOf, matcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Overwrite the Matcher extending the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is present in **any** of the \"Any Of\" Matchers,\n * they will be granted access.\n * @param policy The [[Policy]] to which the Matcher should be added.\n * @param matcher The Matcher to set for the Policy.\n * @returns A new [[Policy]] clone of the original one, with the \"Any Of\" Matchers replaced.\n * @since Not released yet.\n */\nfunction setAnyOfMatcherUrl(policy, matcher) {\n return setIri(policy, acp.anyOf, matcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the \"Any Of\" [[Matcher]]s for the given [[Policy]]\n * @param policy The [[policy]] from which the Matchers should be read.\n * @returns A list of the \"Any Of\" [[Matcher]]s\n * @since Not released yet.\n */\nfunction getAnyOfMatcherUrlAll(policy) {\n return getIriAll(policy, acp.anyOf);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Add a Matcher that restricts the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is matched by another Matcher, but **also**\n * by the given Matcher, they will **not** be granted access.\n *\n * Also see [[addAllOfMatcherUrl]] and [[addAnyOfMatcherUrl]].\n *\n * @param policy The [[Policy]] to which the Matcher should be added.\n * @param matcher The Matcher to add to the policy.\n * @returns A new [[Policy]] clone of the original one, with the new Matcher added.\n * @since Not released yet.\n */\nfunction addNoneOfMatcherUrl(policy, matcher) {\n return addIri(policy, acp.noneOf, matcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Removes a Matcher that restricts the scope of a given the [[Policy]]. If an agent\n * requesting access to a resource is matched by another Matcher, but **also**\n * in any of the \"None Of\" Matchers, they will **not** be granted access.\n *\n * @param policy The [[Policy]] from which the Matcher should be removed.\n * @param matcher The Matcher to remove from the policy.\n * @returns A new [[Policy]] clone of the original one, with the Matcher removed.\n * @since Not released yet.\n */\nfunction removeNoneOfMatcherUrl(policy, matcher) {\n return removeIri(policy, acp.noneOf, matcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set the Matchers restricting the scope of a given [[Policy]]. If an agent\n * requesting access to a resource is matched by another Matcher, but **also**\n * by any of the \"None Of\" Matchers, they will not be granted access.\n *\n * @param policy The [[Policy]] to which the Matcher should be added.\n * @param matcher The Matcher to set for the Policy.\n * @returns A new [[Policy]] clone of the original one, with the \"None Of\" Matchers replaced.\n * @since Not released yet.\n */\nfunction setNoneOfMatcherUrl(policy, matcher) {\n return setIri(policy, acp.noneOf, matcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the \"None Of\" [[Matcher]]s for the given [[Policy]]\n * @param policy The [[policy]] from which the Matchers should be read.\n * @returns A list of the forbidden [[Matcher]]s\n * @since Not released yet.\n */\nfunction getNoneOfMatcherUrlAll(policy) {\n return getIriAll(policy, acp.noneOf);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Initialise a new, empty [[Matcher]].\n *\n * @param url URL that identifies this [[Matcher]].\n * @since Not released yet.\n */\nfunction createMatcher(url) {\n const stringUrl = internal_toIriString(url);\n let matcherThing = createThing({ url: stringUrl });\n matcherThing = setUrl(matcherThing, rdf.type, acp.Matcher);\n return matcherThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Initialise a new, empty [[ResourceMatcher]] for the given Resource.\n *\n * @param resourceWithAcr The Resource to which the new Matcher is to apply.\n * @param name Name that identifies this [[Matcher]].\n * @since Not released yet.\n */\nfunction createResourceMatcherFor(resourceWithAcr, name) {\n const acr = internal_getAcr(resourceWithAcr);\n const url = new URL(getSourceUrl(acr));\n url.hash = `#${name}`;\n let matcherThing = createThing({ url: url.href });\n matcherThing = setUrl(matcherThing, rdf.type, acp.Matcher);\n return matcherThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the [[Matcher]] with the given URL from an [[SolidDataset]].\n *\n * @param matcherResource The Resource that contains the given [[Matcher]].\n * @param url URL that identifies this [[Matcher]].\n * @returns The requested [[Matcher]], if it exists, or `null` if it does not.\n * @since Not released yet.\n */\nfunction getMatcher(matcherResource, url) {\n const foundThing = getThing(matcherResource, url);\n if (foundThing === null || !isMatcher(foundThing)) {\n return null;\n }\n return foundThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Get the [[ResourceMatcher]] with the given name from an Resource's Access Control\n * Resource.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains the given [[ResourceMatcher]].\n * @param name Name that identifies this [[ResourceMatcher]].\n * @returns The requested [[ResourceMatcher]], if it exists, or `null` if it does not.\n * @since Not released yet.\n */\nfunction getResourceMatcher(resourceWithAcr, name) {\n const acr = internal_getAcr(resourceWithAcr);\n const acrUrl = getSourceUrl(acr);\n const url = new URL(acrUrl);\n url.hash = `#${name}`;\n const foundThing = getThing(acr, url.href);\n if (foundThing === null || !isMatcher(foundThing)) {\n return null;\n }\n return foundThing;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Gets the [[Matcher]]s from a [[SolidDataset]].\n *\n * @param matcherResource The Resource that contains (zero or more) [[Matcher]]s.\n * @returns The [[Matcher]]s contained in this resource.\n * @since Not released yet.\n */\nfunction getMatcherAll(matcherResource) {\n const things = getThingAll(matcherResource);\n return things.filter(isMatcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Gets the [[ResourceMatcher]]s from a Resource's Access Control Resource.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains (zero or more) [[ResourceMatcher]]s.\n * @returns The [[ResourceMatcher]]s contained in this Resource's Access Control Resource.\n * @since Not released yet.\n */\nfunction getResourceMatcherAll(resourceWithAcr) {\n const acr = internal_getAcr(resourceWithAcr);\n const things = getThingAll(acr);\n return things.filter(isMatcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Removes the given [[Matcher]] from the given [[SolidDataset]].\n *\n * @param matcherResource The Resource that contains (zero or more) [[Matcher]]s.\n * @returns A new SolidDataset equal to the given Matcher Resource, but without the given Matcher.\n * @since Not released yet.\n */\nfunction removeMatcher(matcherResource, matcher) {\n return removeThing(matcherResource, matcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Removes the given [[ResourceMatcher]] from the given Resource's Access Control Resource.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains (zero or more) [[ResourceMatcher]]s.\n * @returns A new Resource equal to the given Resource, but without the given Matcher in its ACR.\n * @since Not released yet.\n */\nfunction removeResourceMatcher(resourceWithAcr, matcher) {\n const acr = internal_getAcr(resourceWithAcr);\n let matcherToRemove;\n if (typeof matcher === \"string\") {\n if (internal_isValidUrl(matcher)) {\n matcherToRemove = matcher;\n }\n else {\n // If the given Matcher to remove is the name of the Matcher,\n // resolve it to its full URL — developers usually refer to either the\n // Matcher itself, or by its name, as they do not have access to the ACR\n // directly.\n const matcherUrl = new URL(getSourceUrl(acr));\n matcherUrl.hash = `#${matcher}`;\n matcherToRemove = matcherUrl.href;\n }\n }\n else if (isNamedNode(matcher)) {\n matcherToRemove = internal_toIriString(matcher);\n }\n else {\n matcherToRemove = asUrl(matcher);\n }\n // Check whether the actual Matcher (i.e. with the Matcher type) exists:\n const matchingMatcher = getResourceMatcher(resourceWithAcr, new URL(matcherToRemove).hash.substring(1));\n if (matchingMatcher === null) {\n // No such Matcher exists yet, so return the Resource+ACR unchanged:\n return resourceWithAcr;\n }\n const updatedAcr = removeThing(acr, matchingMatcher);\n const updatedResource = internal_setAcr(resourceWithAcr, updatedAcr);\n return updatedResource;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Insert the given [[Matcher]] into the given [[SolidDataset]], replacing previous\n * instances of that Matcher.\n *\n * @param matcherResource The Resource that contains (zero or more) [[Matcher]]s.\n * @returns A new SolidDataset equal to the given Matcher Resource, but with the given Matcher.\n * @since Not released yet.\n */\nfunction setMatcher(matcherResource, matcher) {\n return setThing(matcherResource, matcher);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Insert the given [[ResourceMatcher]] into the given Resource's Access Control Resource,\n * replacing previous instances of that Matcher.\n *\n * @param resourceWithAcr The Resource whose Access Control Resource contains (zero or more) [[ResourceMatcher]]s.\n * @returns A new Resource equal to the given Resource, but with the given Matcher in its ACR.\n * @since Not released yet.\n */\nfunction setResourceMatcher(resourceWithAcr, matcher) {\n const acr = internal_getAcr(resourceWithAcr);\n const updatedAcr = setThing(acr, matcher);\n const updatedResource = internal_setAcr(resourceWithAcr, updatedAcr);\n return updatedResource;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * List all the agents a [[Matcher]] applies **directly** to. This will not include agents\n * that are matched on a property other than their WebID.\n *\n * @param matcher The matcher from which agents are read.\n * @returns A list of the WebIDs of agents included in the matcher.\n * @since Not released yet.\n */\nfunction getAgentAll(matcher) {\n return getIriAll(matcher, acp.agent).filter((agent) => agent !== acp.PublicAgent &&\n agent !== acp.AuthenticatedAgent &&\n agent !== acp.CreatorAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Overwrite the agents the [[Matcher]] applies to with the provided agents.\n *\n * @param matcher The matcher for which agents are set.\n * @param agent The agent the matcher should apply to.\n * @returns A copy of the input matcher, applying to a different set of agents.\n * @since Not released yet.\n */\nfunction setAgent(matcher, agent) {\n // Preserve the special agent classes authenticated and public, which we\n // don't want to overwrite with this function.\n const isPublic = hasPublic(matcher);\n const isAuthenticated = hasAuthenticated(matcher);\n const isCreator = hasCreator(matcher);\n let result = setIri(matcher, acp.agent, agent);\n // Restore public and authenticated\n if (isPublic) {\n result = setPublic(result);\n }\n if (isAuthenticated) {\n result = setAuthenticated(result);\n }\n if (isCreator) {\n result = setCreator(result);\n }\n return result;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Apply the [[Matcher]] to an additional agent.\n *\n * @param matcher The [[Matcher]] to be applied to an additional agent.\n * @param agent The agent the [[Matcher]] should apply to.\n * @returns A copy of the [[Matcher]], applying to an additional agent.\n * @since Not released yet.\n */\nfunction addAgent(matcher, agent) {\n return addIri(matcher, acp.agent, agent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Prevent the [[Matcher]] from applying to a given agent directly. This will not\n * prevent the agent from matching on other properties than its WebID.\n *\n * @param matcher The [[Matcher]] that should no longer apply to a given agent.\n * @param agent The agent the Matcher should no longer apply to.\n * @returns A copy of the Matcher, not applying to the given agent.\n * @since Not released yet.\n */\nfunction removeAgent(matcher, agent) {\n return removeIri(matcher, acp.agent, agent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Check if the Matcher applies to any agent.\n *\n * @param matcher The Matcher checked for public access.\n * @returns Whether the Matcher applies to any agent or not.\n * @since Not released yet.\n */\nfunction hasPublic(matcher) {\n return (getIriAll(matcher, acp.agent).filter((agent) => agent === acp.PublicAgent)\n .length > 0);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set a Matcher to apply to any Agent.\n *\n * @param matcher The Matcher being modified.\n * @returns A copy of the Matcher, updated to apply to any agent.\n * @since Not released yet.\n */\nfunction setPublic(matcher) {\n // The second argument should not be part of the function signature,\n // so it's not in the parameter list:\n // eslint-disable-next-line prefer-rest-params\n if (typeof arguments === \"object\" && typeof arguments[1] === \"boolean\") {\n throw new Error(\"The function `setPublic` no longer takes a second parameter. It is now used together with `removePublic` instead.\");\n }\n return addIri(matcher, acp.agent, acp.PublicAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set a Matcher to no longer apply to any Agent.\n *\n * @param matcher The Matcher being modified.\n * @returns A copy of the Matcher, updated to no longer apply to any agent.\n * @since Not released yet.\n */\nfunction removePublic(matcher) {\n return removeIri(matcher, acp.agent, acp.PublicAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Check if the Matcher applies to any authenticated agent.\n *\n * @param matcher The Matcher checked for authenticated access.\n * @returns Whether the Matcher applies to any authenticated agent or not.\n * @since Not released yet.\n */\nfunction hasAuthenticated(matcher) {\n return (getIriAll(matcher, acp.agent).filter((agent) => agent === acp.AuthenticatedAgent).length > 0);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set a Matcher to apply to any authenticated Agent.\n *\n * @param matcher The Matcher being modified.\n * @returns A copy of the Matcher, updated to apply to any authenticated Agent.\n * @since Not released yet.\n */\nfunction setAuthenticated(matcher) {\n // The second argument should not be part of the function signature,\n // so it's not in the parameter list:\n // eslint-disable-next-line prefer-rest-params\n if (typeof arguments === \"object\" && typeof arguments[1] === \"boolean\") {\n throw new Error(\"The function `setAuthenticated` no longer takes a second parameter. It is now used together with `removeAuthenticated` instead.\");\n }\n return addIri(matcher, acp.agent, acp.AuthenticatedAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set a Matcher to no longer apply to any authenticated Agent.\n *\n * @param matcher The Matcher being modified.\n * @returns A copy of the Matcher, updated to apply/not apply to any authenticated agent.\n * @since Not released yet.\n */\nfunction removeAuthenticated(matcher) {\n return removeIri(matcher, acp.agent, acp.AuthenticatedAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Check if the Matcher applies to the creator of the Resource.\n *\n * @param matcher The Matcher checked for authenticated access.\n * @returns Whether the Matcher applies to the creator of the Resource or not.\n * @since Not released yet.\n */\nfunction hasCreator(matcher) {\n return (getIriAll(matcher, acp.agent).filter((agent) => agent === acp.CreatorAgent)\n .length > 0);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set a Matcher to apply to the creator of a Resource.\n *\n * @param matcher The Matcher being modified.\n * @returns A copy of the Matcher, updated to apply to the creator of a Resource.\n * @since Not released yet.\n */\nfunction setCreator(matcher) {\n // The second argument should not be part of the function signature,\n // so it's not in the parameter list:\n // eslint-disable-next-line prefer-rest-params\n if (typeof arguments === \"object\" && typeof arguments[1] === \"boolean\") {\n throw new Error(\"The function `setCreator` no longer takes a second parameter. It is now used together with `removeCreator` instead.\");\n }\n return addIri(matcher, acp.agent, acp.CreatorAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Set a Matcher to no longer apply to the creator of a Resource.\n *\n * @param matcher The Matcher being modified.\n * @returns A copy of the Matcher, updated to apply/not apply to the creator of a Resource.\n * @since Not released yet.\n */\nfunction removeCreator(matcher) {\n return removeIri(matcher, acp.agent, acp.CreatorAgent);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * List all the clients a [[Matcher]] applies **directly** to. This will not include\n * specific client classes, such as public clients.\n *\n * @param matcher The Matcher from which clients are read.\n * @returns A list of the WebIDs of clients included in the Matcher.\n * @since Not released yet.\n */\nfunction getClientAll(matcher) {\n return getIriAll(matcher, acp.client)\n .filter((client) => client !== solid.PublicOidcClient)\n .concat(getStringNoLocaleAll(matcher, acp.client));\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Overwrite the clients the [[Matcher]] applies to with the provided Client.\n *\n * @param matcher The Matcher for which clients are set.\n * @param client The Client the Matcher should apply to.\n * @returns A copy of the input Matcher, applying to a different set of Clients.\n */\nfunction setClient(matcher, client) {\n // Preserve the special \"any client\" class, which we\n // don't want to overwrite with this function.\n const anyClientEnabled = hasAnyClient(matcher);\n let result = setIri(matcher, acp.client, client);\n // Restore the \"any client\" class\n if (anyClientEnabled) {\n result = setAnyClient(result);\n }\n return result;\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Apply the [[Matcher]] to an additional Client.\n *\n * @param matcher The [[Matcher]] to be applied to an additional Client.\n * @param client The Client the [[Matcher]] should apply to.\n * @returns A copy of the [[Matcher]], applying to an additional Client.\n * @since Not released yet.\n */\nfunction addClient(matcher, client) {\n if (!internal_isValidUrl(client)) {\n return addStringNoLocale(matcher, acp.client, client);\n }\n return addIri(matcher, acp.client, client);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Prevent the [[Matcher]] from applying to a given Client directly.\n *\n * @param matcher The [[Matcher]] that should no longer apply to a given Client.\n * @param client The Client the Matcher should no longer apply to.\n * @returns A copy of the Matcher, not applying to the given Client.\n * @since Not released yet.\n */\nfunction removeClient(matcher, client) {\n if (!internal_isValidUrl(client)) {\n return removeStringNoLocale(matcher, acp.client, client);\n }\n return removeIri(matcher, acp.client, client);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Check if the Matcher applies to any client, i.e. all the applications\n * regardless of their identifier.\n *\n * @param matcher The Matcher checked for authenticated access.\n * @returns Whether the Matcher applies to public clients.\n * @since Not released yet.\n * @deprecated\n */\nfunction hasAnyClient(matcher) {\n return (getIriAll(matcher, acp.client).filter((client) => client === solid.PublicOidcClient).length > 0);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Make the [[Matcher]] apply to any client application.\n *\n * @param matcher The Matcher for which clients are set.\n * @returns A copy of the Matcher, updated to apply to any client\n * @since Not released yet.\n * @deprecated\n */\nfunction setAnyClient(matcher) {\n return addIri(matcher, acp.client, solid.PublicOidcClient);\n}\n/**\n * ```{note} There is no Access Control Policies specification yet. As such, this\n * function is still experimental and subject to change, even in a non-major release.\n * ```\n *\n * Make the [[Matcher]] no longer apply to any client application.\n *\n * @param matcher The Matcher for which clients are set.\n * @returns A copy of the Matcher, updated to no longer apply to any client\n * @since Not released yet.\n * @deprecated\n */\nfunction removeAnyClient(matcher) {\n return removeIri(matcher, acp.client, solid.PublicOidcClient);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst v4AcpFunctions = {\n getFileWithAccessDatasets,\n getFileWithAcr,\n getReferencedPolicyUrlAll,\n getResourceInfoWithAccessDatasets,\n getResourceInfoWithAcr,\n getSolidDatasetWithAccessDatasets,\n getSolidDatasetWithAcr,\n hasAccessibleAcr,\n saveAcrFor,\n isAcpControlled,\n getVcAccess,\n setVcAccess,\n};\nconst v4ControlFunctions = {\n addAcrPolicyUrl,\n addMemberAcrPolicyUrl,\n addMemberPolicyUrl,\n addPolicyUrl,\n getAcrPolicyUrlAll,\n getMemberAcrPolicyUrlAll,\n getMemberPolicyUrlAll,\n getPolicyUrlAll,\n hasLinkedAcr,\n removeAcrPolicyUrl,\n removeAcrPolicyUrlAll,\n removeMemberAcrPolicyUrl,\n removeMemberAcrPolicyUrlAll,\n removeMemberPolicyUrl,\n removeMemberPolicyUrlAll,\n removePolicyUrl,\n removePolicyUrlAll,\n};\nconst v4PolicyFunctions = {\n createPolicy,\n getAllowModes: getAllowModesV2,\n getDenyModes: getDenyModesV2,\n getPolicy,\n getPolicyAll,\n removePolicy,\n setAllowModes: setAllowModesV2,\n setDenyModes: setDenyModesV2,\n setPolicy,\n createResourcePolicyFor,\n getResourceAcrPolicy,\n getResourceAcrPolicyAll,\n getResourcePolicy,\n getResourcePolicyAll,\n removeResourceAcrPolicy,\n removeResourcePolicy,\n setResourcePolicy,\n};\nconst v4MatcherFunctions = {\n addAgent,\n createMatcher,\n getAgentAll,\n getMatcher,\n getMatcherAll,\n removeAgent,\n removeMatcher,\n setAgent,\n setMatcher,\n addClient,\n getClientAll,\n hasAnyClient,\n removeClient,\n setAnyClient,\n setClient,\n removeAnyClient,\n hasAuthenticated,\n hasCreator,\n hasPublic,\n setAuthenticated,\n setCreator,\n setPublic,\n removeAuthenticated,\n removeCreator,\n removePublic,\n getAnyOfMatcherUrlAll,\n addAnyOfMatcherUrl,\n removeAnyOfMatcherUrl,\n setAnyOfMatcherUrl,\n getAllOfMatcherUrlAll,\n addAllOfMatcherUrl,\n removeAllOfMatcherUrl,\n setAllOfMatcherUrl,\n getNoneOfMatcherUrlAll,\n addNoneOfMatcherUrl,\n removeNoneOfMatcherUrl,\n setNoneOfMatcherUrl,\n createResourceMatcherFor,\n getResourceMatcher,\n getResourceMatcherAll,\n removeResourceMatcher,\n setResourceMatcher,\n};\nconst v4MockFunctions = {\n addMockAcrTo,\n mockAcrFor,\n};\n/**\n * @hidden\n * @deprecated Please import \"acp_ess_2\" directly.\n */\nconst acp_v4 = {\n ...v4AcpFunctions,\n ...v4ControlFunctions,\n ...v4PolicyFunctions,\n ...v4MatcherFunctions,\n ...v4MockFunctions,\n};\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst knownActorRelations$1 = [acp.agent, acp.group];\n/**\n * Get an overview of what access is defined for a given actor in a Resource's Access Control Resource.\n *\n * This will only return a value if all relevant access is defined in just the Resource's Access\n * Control Resource; in other words, if an Access Policy or Access Rule applies that is re-used for\n * other Resources, this function will not be able to determine the access relevant to this actor.\n *\n * Additionally, this only considers access given _explicitly_ to the given actor, i.e. without\n * additional conditions.\n *\n * In other words, this function will generally understand and return the access as set by\n * [[internal_setActorAccess]], but not understand more convoluted Policies.\n *\n * @param acpData All Access Control Policies and Rules that apply to a particular Resource.\n * @param actorRelation What type of actor (e.g. acp:agent or acp:group) you want to get the access for.\n * @param actor Which instance of the given actor type you want to get the access for.\n * @returns What Access modes are granted to the given actor explicitly, or null if it could not be determined.\n */\nfunction internal_getActorAccess$1(acpData, actorRelation, actor) {\n if (acpData.inaccessibleUrls.length > 0) {\n // If we can't see all access data,\n // we can't reliably determine what access the given actor has:\n return null;\n }\n const applicableAcrPolicies = acpData.acrPolicies.filter((policy) => policyAppliesTo$1(policy, actorRelation, actor, acpData));\n const applicablePolicies = acpData.policies.filter((policy) => policyAppliesTo$1(policy, actorRelation, actor, acpData));\n const initialAccess = {\n read: false,\n append: false,\n write: false,\n controlRead: false,\n controlWrite: false,\n };\n // All allowed reading and writing defined in ACR policies\n // determines whether the `controlRead` and `controlWrite` statuses are `true`.\n const allowedAcrAccess = applicableAcrPolicies.reduce((acc, policy) => {\n const allAllowedAccess = { ...acc };\n const allowModes = getAllowModesV1(policy);\n if (allowModes.read) {\n allAllowedAccess.controlRead = true;\n }\n if (allowModes.write) {\n allAllowedAccess.controlWrite = true;\n }\n return allAllowedAccess;\n }, initialAccess);\n // Then allowed reading, appending and writing in regular policies\n // determines whether the respective status is `true`.\n const withAllowedAccess = applicablePolicies.reduce((acc, policy) => {\n const allAllowedAccess = { ...acc };\n const allowModes = getAllowModesV1(policy);\n if (allowModes.read) {\n allAllowedAccess.read = true;\n }\n if (allowModes.append) {\n allAllowedAccess.append = true;\n }\n if (allowModes.write) {\n allAllowedAccess.write = true;\n }\n return allAllowedAccess;\n }, allowedAcrAccess);\n // At this point, everything that has been explicitly allowed is true.\n // However, it could still be overridden by access that is explicitly denied.\n // Starting with `controlRead` and `controlWrite`,\n // by inspecting denied reading and writing defined in the ACR policies.\n const withAcrDeniedAccess = applicableAcrPolicies.reduce((acc, policy) => {\n const allDeniedAccess = { ...acc };\n const denyModes = getDenyModesV1(policy);\n if (denyModes.read === true) {\n allDeniedAccess.controlRead = false;\n }\n if (denyModes.write === true) {\n allDeniedAccess.controlWrite = false;\n }\n return allDeniedAccess;\n }, withAllowedAccess);\n // And finally, we set to `false` those access modes that are explicitly denied\n // in the regular policies:\n const withDeniedAccess = applicablePolicies.reduce((acc, policy) => {\n const allDeniedAccess = { ...acc };\n const denyModes = getDenyModesV1(policy);\n if (denyModes.read === true) {\n allDeniedAccess.read = false;\n }\n if (denyModes.append === true) {\n allDeniedAccess.append = false;\n }\n if (denyModes.write === true) {\n allDeniedAccess.write = false;\n }\n return allDeniedAccess;\n }, withAcrDeniedAccess);\n return withDeniedAccess;\n}\n/**\n * Get an overview of what access is defined for a given Agent in a Resource's Access Control Resource.\n *\n * This will only return a value if all relevant access is defined in just the Resource's Access\n * Control Resource; in other words, if an Access Policy or Access Rule applies that is re-used for\n * other Resources, this function will not be able to determine the access relevant to this Agent.\n *\n * Additionally, this only considers access given _explicitly_ to the given Agent, i.e. without\n * additional conditions.\n *\n * In other words, this function will generally understand and return the access as set by\n * [[internal_setAgentAccess]], but not understand more convoluted Policies.\n *\n * @param acpData All Access Control Policies and Rules that apply to a particular Resource.\n * @param webId WebID of the Agent you want to get the access for.\n * @returns What Access modes are granted to the given Agent explicitly, or null if it could not be determined.\n */\nfunction internal_getAgentAccess$1(acpData, webId) {\n return internal_getActorAccess$1(acpData, acp.agent, webId);\n}\n/**\n * Get an overview of what access is defined for a given Group in a Resource's Access Control Resource.\n *\n * This will only return a value if all relevant access is defined in just the Resource's Access\n * Control Resource; in other words, if an Access Policy or Access Rule applies that is re-used for\n * other Resources, this function will not be able to determine the access relevant to this Group.\n *\n * Additionally, this only considers access given _explicitly_ to the given Group, i.e. without\n * additional conditions.\n *\n * In other words, this function will generally understand and return the access as set by\n * [[internal_setGroupAccess]], but not understand more convoluted Policies.\n *\n * @param acpData All Access Control Policies and Rules that apply to a particular Resource.\n * @param groupUrl URL of the Group you want to get the access for.\n * @returns What Access modes are granted to the given Group explicitly, or null if it could not be determined.\n */\nfunction internal_getGroupAccess(acpData, groupUrl) {\n return internal_getActorAccess$1(acpData, acp.group, groupUrl);\n}\n/**\n * Get an overview of what access is defined for everybody in a Resource's Access Control Resource.\n *\n * This will only return a value if all relevant access is defined in just the Resource's Access\n * Control Resource; in other words, if an Access Policy or Access Rule applies that is re-used for\n * other Resources, this function will not be able to determine the access relevant to everybody.\n *\n * Additionally, this only considers access given _explicitly_ to everybody, i.e. without\n * additional conditions.\n *\n * In other words, this function will generally understand and return the access as set by\n * [[internal_setPublicAccess]], but not understand more convoluted Policies.\n *\n * @param acpData All Access Control Policies and Rules that apply to a particular Resource.\n * @returns What Access modes are granted to everyone explicitly, or null if it could not be determined.\n */\nfunction internal_getPublicAccess$1(acpData) {\n return internal_getActorAccess$1(acpData, acp.agent, acp.PublicAgent);\n}\nfunction policyAppliesTo$1(policy, actorRelation, actor, acpData) {\n const allowModes = getIriAll(policy, acp.allow);\n const denyModes = getIriAll(policy, acp.deny);\n if (allowModes.length + denyModes.length === 0) {\n // A Policy that does not specify access modes does not do anything:\n return false;\n }\n // Note: the non-null assertions (`!`) here should be valid because\n // the caller of `policyAppliesTo` should already have validated that\n // the return value of internal_getPoliciesAndRules() did not have any\n // inaccessible URLs, so we should be able to find every Rule.\n const allOfRules = getAllOfRuleUrlAll(policy).map((ruleUrl) => acpData.rules.find((rule) => asIri(rule) === ruleUrl));\n const anyOfRules = getAnyOfRuleUrlAll(policy).map((ruleUrl) => acpData.rules.find((rule) => asIri(rule) === ruleUrl));\n const noneOfRules = getNoneOfRuleUrlAll(policy).map((ruleUrl) => acpData.rules.find((rule) => asIri(rule) === ruleUrl));\n // We assume that this Policy applies if this specific actor is mentioned\n // and no further restrictions are in place.\n // (In other words, the Policy may apply to others *in addition to* this\n // actor, but if it applies to this actor *unless* some other condition holds,\n // we cannot be sure whether it will apply to this actor.)\n // This means that:\n return (\n // Every existing allOf Rule explicitly applies explicitly to this given actor:\n allOfRules.every((rule) => ruleAppliesTo(rule, actorRelation, actor)) &&\n // If there are anyOf Rules, at least one applies explicitly to this actor:\n (anyOfRules.length === 0 ||\n anyOfRules.some((rule) => ruleAppliesTo(rule, actorRelation, actor))) &&\n // No further restrictions are in place that make this sometimes not apply\n // to the given actor:\n noneOfRules.length === 0);\n}\nfunction policyConflictsWith$1(policy, otherAccess) {\n const allowModes = getIriAll(policy, acp.allow);\n const denyModes = getIriAll(policy, acp.deny);\n return ((otherAccess.read === true && denyModes.includes(acp.Read)) ||\n (otherAccess.read === false &&\n allowModes.includes(acp.Read) &&\n !denyModes.includes(acp.Read)) ||\n (otherAccess.append === true && denyModes.includes(acp.Append)) ||\n (otherAccess.append === false &&\n allowModes.includes(acp.Append) &&\n !denyModes.includes(acp.Append)) ||\n (otherAccess.write === true && denyModes.includes(acp.Write)) ||\n (otherAccess.write === false &&\n allowModes.includes(acp.Write) &&\n !denyModes.includes(acp.Write)));\n}\nfunction ruleAppliesTo(rule, actorRelation, actor) {\n // A Rule that does not list *any* actor matches for everyone:\n let isEmpty = true;\n knownActorRelations$1.forEach((knownActorRelation) => {\n isEmpty && (isEmpty = getIri(rule, knownActorRelation) === null);\n });\n return isEmpty || getIriAll(rule, actorRelation).includes(actor);\n}\n/**\n * Get a set of all actors mentioned in an ACR by active Rules (i.e. that are\n * referenced by Policies referenced by the ACR Control, and therefore that\n * effectively apply).\n *\n * @param acpData All Access Control Policies and Rules that apply to a particular Resource.\n * @param actorRelation\n */\nfunction internal_findActorAll$1(acpData, actorRelation) {\n const actors = new Set();\n // This code could be prettier using flat(), which isn't supported by nodeJS 10.\n // If you read this comment after April 2021, feel free to refactor.\n acpData.rules.forEach((rule) => {\n getIriAll(rule, actorRelation)\n .filter((iri) => ![\n acp.PublicAgent,\n acp.CreatorAgent,\n acp.AuthenticatedAgent,\n ].includes(iri) || actorRelation !== acp.agent)\n .forEach((iri) => actors.add(iri));\n });\n return actors;\n}\n/**\n * Iterate through all the actors active for an ACR, and list all of their access.\n * @param acpData All Access Control Policies and Rules that apply to a particular Resource.\n * @param actorRelation The type of actor we want to list access for\n * @returns A map with each actor access indexed by their URL, or null if some\n * external policies are referenced.\n */\nfunction internal_getActorAccessAll$1(acpData, actorRelation) {\n if (acpData.inaccessibleUrls.length > 0) {\n // If we can't see all access data,\n // we can't reliably determine what access actors of the given type have:\n return null;\n }\n const result = {};\n const actors = internal_findActorAll$1(acpData, actorRelation);\n actors.forEach((iri) => {\n // The type assertion holds, because if internal_getActorAccess were null,\n // we would have returned {} already.\n const access = internal_getActorAccess$1(acpData, actorRelation, iri);\n result[iri] = access;\n });\n return result;\n}\n/**\n * Get an overview of what access are defined for all Groups in a Resource's Access Control Resource.\n *\n * This will only return a value if all relevant access is defined in just the Resource's Access\n * Control Resource; in other words, if an Access Policy or Access Rule applies that is re-used for\n * other Resources, this function will not be able to determine the access relevant to the mentionned\n * Groups.\n *\n * Additionally, this only considers access given _explicitly_ to individual Groups, i.e. without\n * additional conditions.\n *\n * In other words, this function will generally understand and return the access as set by\n * [[internal_setAgentAccess]], but not understand more convoluted Policies.\n *\n * @param acpData All Access Control Policies and Rules that apply to a particular Resource.\n * @returns A map with each Group's access indexed by their URL, or null if some\n * external policies are referenced.\n */\nfunction internal_getGroupAccessAll(acpData) {\n return internal_getActorAccessAll$1(acpData, acp.group);\n}\n/**\n * Get an overview of what access are defined for all Agents in a Resource's Access Control Resource.\n *\n * This will only return a value if all relevant access is defined in just the Resource's Access\n * Control Resource; in other words, if an Access Policy or Access Rule applies that is re-used for\n * other Resources, this function will not be able to determine the access relevant to the mentionned\n * Agents.\n *\n * Additionally, this only considers access given _explicitly_ to individual Agents, i.e. without\n * additional conditions.\n *\n * In other words, this function will generally understand and return the access as set by\n * [[internal_setAgentAccess]], but not understand more convoluted Policies.\n *\n * @param acpData All Access Control Policies and Rules that apply to a particular Resource.\n * @returns A map with each Agent's access indexed by their WebID, or null if some\n * external policies are referenced.\n */\nfunction internal_getAgentAccessAll$1(acpData) {\n return internal_getActorAccessAll$1(acpData, acp.agent);\n}\n/**\n * Set access to a Resource for a specific actor.\n *\n * This function adds the relevant Access Control Policies and Rules to a\n * Resource's Access Control Resource to define the given access for the given\n * actor specifically. In other words, it can, for example, add Policies that\n * give a particular Group Read access to the Resource. However, if other\n * Policies specify that everyone in that Group is *denied* Read access *except*\n * for a particular Agent, then that will be left intact.\n * This means that, unless *only* this module's functions are used to manipulate\n * access to this Resource, the set access might not be equal to the effective\n * access for an agent matching the given actor.\n *\n * There are a number of preconditions that have to be fulfilled for this\n * function to work:\n * - Access to the Resource is determined via an Access Control Resource.\n * - The Resource's Access Control Resource does not refer to (Policies or Rules\n * in) other Resources.\n * - The current user has access to the Resource's Access Control Resource.\n *\n * If those conditions do not hold, this function will return `null`.\n *\n * Additionally, take note that the given access will only be applied to the\n * given Resource; if that Resource is a Container, access will have to be set\n * for its contained Resources independently.\n *\n * @param resource Resource that was fetched together with its linked Access Control Resource.\n * @param acpData All Access Control Policies and Rules that apply to a particular Resource.\n * @param actorRelation What type of actor (e.g. acp:agent or acp:group) you want to set the access for.\n * @param actor Which instance of the given actor type you want to set the access for.\n * @param access What access (read, append, write, controlRead, controlWrite) to set for the given actor. `true` to allow, `false` to deny, and `undefined` to leave unchanged.\n * @returns The Resource with the updated Access Control Resource attached, if updated successfully, or `null` if not.\n */\nfunction internal_setActorAccess$1(resource, acpData, actorRelation, actor, access) {\n var _a, _b, _c, _d, _e;\n if (!hasAccessibleAcr(resource) || acpData.inaccessibleUrls.length > 0) {\n return null;\n }\n // Get the access that currently applies to the given actor\n const existingAccess = internal_getActorAccess$1(acpData, actorRelation, actor);\n /* istanbul ignore if: It returns null if the ACR has inaccessible Policies, which should happen since we already check for that above. */\n if (existingAccess === null) {\n return null;\n }\n // Get all Policies that apply specifically to the given actor\n const applicableAcrPolicies = acpData.acrPolicies.filter((policy) => policyAppliesTo$1(policy, actorRelation, actor, acpData));\n const applicablePolicies = acpData.policies.filter((policy) => policyAppliesTo$1(policy, actorRelation, actor, acpData));\n // We only need to override Policies that define access other than what we want:\n const conflictingAcrPolicies = applicableAcrPolicies.filter((policy) => policyConflictsWith$1(policy, {\n read: access.controlRead,\n write: access.controlWrite,\n }));\n const conflictingPolicies = applicablePolicies.filter((policy) => policyConflictsWith$1(policy, {\n read: access.read,\n append: access.append,\n write: access.write,\n }));\n // For every Policy that applies specifically to the given Actor, but _also_\n // to another actor (i.e. that applies using an anyOf Rule, or a Rule that\n // mentions both the given and another actor)...\n const otherActorAcrPolicies = conflictingAcrPolicies.filter((acrPolicy) => policyHasOtherActors$1(acrPolicy, actorRelation, actor, acpData));\n const otherActorPolicies = conflictingPolicies.filter((policy) => policyHasOtherActors$1(policy, actorRelation, actor, acpData));\n // ...check what access the current actor would have if we removed them...\n const acpDataWithPoliciesExcluded = {\n ...acpData,\n acrPolicies: acpData.acrPolicies.filter((acrPolicy) => !otherActorAcrPolicies.includes(acrPolicy)),\n policies: acpData.policies.filter((policy) => !otherActorPolicies.includes(policy)),\n };\n const remainingAccess = internal_getActorAccess$1(acpDataWithPoliciesExcluded, actorRelation, actor);\n /* istanbul ignore if: It returns null if the ACR has inaccessible Policies, which should happen since we already check for that at the start. */\n if (remainingAccess === null) {\n return null;\n }\n // ...add copies of those Policies and their Rules, but excluding the given actor...\n let updatedResource = resource;\n otherActorAcrPolicies.forEach((acrPolicy) => {\n const [policyCopy, ruleCopies] = copyPolicyExcludingActor$1(acrPolicy, resource, acpData, actorRelation, actor);\n updatedResource = setResourceAcrPolicy(updatedResource, policyCopy);\n updatedResource = ruleCopies.reduce(setResourceRule, updatedResource);\n });\n otherActorPolicies.forEach((policy) => {\n const [policyCopy, ruleCopies] = copyPolicyExcludingActor$1(policy, resource, acpData, actorRelation, actor);\n updatedResource = setResourcePolicy$1(updatedResource, policyCopy);\n updatedResource = ruleCopies.reduce(setResourceRule, updatedResource);\n });\n // ...add a new Policy that applies the given access,\n // and the previously applying access for access modes that were undefined...\n const newRuleName = `rule_${encodeURIComponent(`${actorRelation}_${actor}`)}`;\n let newRule = createResourceRuleFor(resource, newRuleName);\n newRule = setIri(newRule, actorRelation, actor);\n const newControlReadAccess = (_a = access.controlRead) !== null && _a !== void 0 ? _a : existingAccess.controlRead;\n const newControlWriteAccess = (_b = access.controlWrite) !== null && _b !== void 0 ? _b : existingAccess.controlWrite;\n let acrPoliciesToUnapply = otherActorAcrPolicies;\n // Only replace existing Policies if the defined access actually changes:\n if (newControlReadAccess !== remainingAccess.controlRead ||\n newControlWriteAccess !== remainingAccess.controlWrite) {\n const newAcrPolicyName = uuid.v4();\n let newAcrPolicy = createResourcePolicyFor(resource, newAcrPolicyName);\n newAcrPolicy = setAllowModesV1(newAcrPolicy, {\n read: newControlReadAccess === true,\n append: false,\n write: newControlWriteAccess === true,\n });\n newAcrPolicy = addIri(newAcrPolicy, acp.allOf, newRule);\n updatedResource = setResourceAcrPolicy(updatedResource, newAcrPolicy);\n updatedResource = setResourceRule(updatedResource, newRule);\n // If we don't have to set new access, we only need to unapply the\n // ACR Policies that applied to both the given actor and other actors\n // (because they have been replaced by clones not mentioning the given\n // actor). Hence `policiesToUnApply` is initialised to `otherActorPolicies`.\n // However, if we're in this if branch, that means we also had to replace\n // Policies that defined access for just this actor, so we'll have to remove\n // all Policies mentioning this actor:\n acrPoliciesToUnapply = conflictingAcrPolicies;\n }\n const newReadAccess = (_c = access.read) !== null && _c !== void 0 ? _c : existingAccess.read;\n const newAppendAccess = (_d = access.append) !== null && _d !== void 0 ? _d : existingAccess.append;\n const newWriteAccess = (_e = access.write) !== null && _e !== void 0 ? _e : existingAccess.write;\n let policiesToUnapply = otherActorPolicies;\n // Only replace existing Policies if the defined access actually changes:\n if (newReadAccess !== remainingAccess.read ||\n newAppendAccess !== remainingAccess.append ||\n newWriteAccess !== remainingAccess.write) {\n const newPolicyName = uuid.v4();\n let newPolicy = createResourcePolicyFor(resource, newPolicyName);\n newPolicy = setAllowModesV1(newPolicy, {\n read: newReadAccess === true,\n append: newAppendAccess === true,\n write: newWriteAccess === true,\n });\n newPolicy = addIri(newPolicy, acp.allOf, newRule);\n updatedResource = setResourcePolicy$1(updatedResource, newPolicy);\n updatedResource = setResourceRule(updatedResource, newRule);\n // If we don't have to set new access, we only need to unapply the\n // Policies that applied to both the given actor and other actors (because\n // they have been replaced by clones not mentioning the given actor). Hence\n // `policiesToUnApply` is initialised to `otherActorPolicies`.\n // However, if we're in this if branch, that means we also had to replace\n // Policies that defined access for just this actor, so we'll have to remove\n // all Policies mentioning this actor:\n policiesToUnapply = conflictingPolicies;\n }\n // ...then remove existing Policy URLs that mentioned both the given actor\n // and other actors from the given Resource and apply the new ones (but do not\n // remove the actual old Policies - they might still apply to other Resources!).\n acrPoliciesToUnapply.forEach((previouslyApplicableAcrPolicy) => {\n updatedResource = removeAcrPolicyUrl$1(updatedResource, asIri(previouslyApplicableAcrPolicy));\n });\n policiesToUnapply.forEach((previouslyApplicablePolicy) => {\n updatedResource = removePolicyUrl$1(updatedResource, asIri(previouslyApplicablePolicy));\n });\n return updatedResource;\n}\n/**\n * Set access to a Resource for a specific Agent.\n *\n * This function adds the relevant Access Control Policies and Rules to a\n * Resource's Access Control Resource to define the given access for the given\n * Agent specifically. In other words, it can, for example, add Policies that\n * give a particular Agent Read access to the Resource. However, if other\n * Policies specify that that Agent is *denied* Read access *except* if they're\n * in a particular Group, then that will be left intact.\n * This means that, unless *only* this function is used to manipulate access to\n * this Resource, the set access might not be equal to the effective access for\n * the given Agent.\n *\n * There are a number of preconditions that have to be fulfilled for this\n * function to work:\n * - Access to the Resource is determined via an Access Control Resource.\n * - The Resource's Access Control Resource does not refer to (Policies or Rules\n * in) other Resources.\n * - The current user has access to the Resource's Access Control Resource.\n *\n * If those conditions do not hold, this function will return `null`.\n *\n * Additionally, take note that the given access will only be applied to the\n * given Resource; if that Resource is a Container, access will have to be set\n * for its contained Resources independently.\n *\n * @param resource Resource that was fetched together with its linked Access Control Resource.\n * @param acpData All Access Control Policies and Rules that apply to a particular Resource.\n * @param webId Which Agent you want to set the access for.\n * @param access What access (read, append, write, controlRead, controlWrite) to set for the given Agent. `true` to allow, `false` to deny, and `undefined` to leave unchanged.\n * @returns The Resource with the updated Access Control Resource attached, if updated successfully, or `null` if not.\n */\nfunction internal_setAgentAccess$1(resource, acpData, webId, access) {\n return internal_setActorAccess$1(resource, acpData, acp.agent, webId, access);\n}\n/**\n * Set access to a Resource for a specific Group.\n *\n * This function adds the relevant Access Control Policies and Rules to a\n * Resource's Access Control Resource to define the given access for the given\n * Group specifically. In other words, it can, for example, add Policies that\n * give a particular Group Read access to the Resource. However, if other\n * Policies specify that it is *denied* Read access *except* if they're a\n * particular Agent, then that will be left intact.\n * This means that, unless *only* this module's functions are used to manipulate\n * access to this Resource, the set access might not be equal to the effective\n * access for Agents in the given Group.\n *\n * There are a number of preconditions that have to be fulfilled for this\n * function to work:\n * - Access to the Resource is determined via an Access Control Resource.\n * - The Resource's Access Control Resource does not refer to (Policies or Rules\n * in) other Resources.\n * - The current user has access to the Resource's Access Control Resource.\n *\n * If those conditions do not hold, this function will return `null`.\n *\n * Additionally, take note that the given access will only be applied to the\n * given Resource; if that Resource is a Container, access will have to be set\n * for its contained Resources independently.\n *\n * @param resource Resource that was fetched together with its linked Access Control Resource.\n * @param acpData All Access Control Policies and Rules that apply to a particular Resource.\n * @param groupUrl Which Group you want to set the access for.\n * @param access What access (read, append, write, controlRead, controlWrite) to set for the given Group. `true` to allow, `false` to deny, and `undefined` to leave unchanged.\n * @returns The Resource with the updated Access Control Resource attached, if updated successfully, or `null` if not.\n */\nfunction internal_setGroupAccess(resource, acpData, groupUrl, access) {\n return internal_setActorAccess$1(resource, acpData, acp.group, groupUrl, access);\n}\n/**\n * Set access to a Resource for everybody.\n *\n * This function adds the relevant Access Control Policies and Rules to a\n * Resource's Access Control Resource to define the given access for everybody\n * specifically. In other words, it can, for example, add Policies that\n * give everybody Read access to the Resource. However, if other\n * Policies specify that everybody is *denied* Read access *except* if they're\n * in a particular Group, then that will be left intact.\n * This means that, unless *only* this module's functions are used to manipulate\n * access to this Resource, the set access might not be equal to the effective\n * access for a particular Agent.\n *\n * There are a number of preconditions that have to be fulfilled for this\n * function to work:\n * - Access to the Resource is determined via an Access Control Resource.\n * - The Resource's Access Control Resource does not refer to (Policies or Rules\n * in) other Resources.\n * - The current user has access to the Resource's Access Control Resource.\n *\n * If those conditions do not hold, this function will return `null`.\n *\n * Additionally, take note that the given access will only be applied to the\n * given Resource; if that Resource is a Container, access will have to be set\n * for its contained Resources independently.\n *\n * @param resource Resource that was fetched together with its linked Access Control Resource.\n * @param acpData All Access Control Policies and Rules that apply to a particular Resource.\n * @param access What access (read, append, write, controlRead, controlWrite) to set for everybody. `true` to allow, `false` to deny, and `undefined` to leave unchanged.\n * @returns The Resource with the updated Access Control Resource attached, if updated successfully, or `null` if not.\n */\nfunction internal_setPublicAccess$1(resource, acpData, access) {\n return internal_setActorAccess$1(resource, acpData, acp.agent, acp.PublicAgent, access);\n}\nfunction policyHasOtherActors$1(policy, actorRelation, actor, acpData) {\n // Note: the non-null assertions (`!`) here should be valid because\n // the caller of `policyHasOtherActors` should already have validated\n // that the return value of internal_getPoliciesAndRules() did not have\n // any inaccessible URLs, so we should be able to find every Rule.\n const allOfRules = getIriAll(policy, acp.allOf).map((ruleUrl) => acpData.rules.find((rule) => asIri(rule) === ruleUrl));\n const allOfRulesHaveOtherActors = allOfRules.some((rule) => {\n return ruleHasOtherActors(rule, actorRelation, actor);\n });\n const anyOfRules = getIriAll(policy, acp.anyOf).map((ruleUrl) => acpData.rules.find((rule) => asIri(rule) === ruleUrl));\n const anyOfRulesHaveOtherActors = anyOfRules.some((rule) => {\n return ruleHasOtherActors(rule, actorRelation, actor);\n });\n /* istanbul ignore next This function only gets called after policyAppliesTo, which already filters out all noneOf Rules */\n const noneOfRules = getIriAll(policy, acp.noneOf).map((ruleUrl) => acpData.rules.find((rule) => asIri(rule) === ruleUrl));\n /* istanbul ignore next This function only gets called after policyAppliesTo, which already filters out all noneOf Rules */\n const noneOfRulesHaveOtherActors = noneOfRules.some((rule) => {\n return ruleHasOtherActors(rule, actorRelation, actor);\n });\n return (allOfRulesHaveOtherActors ||\n anyOfRulesHaveOtherActors ||\n noneOfRulesHaveOtherActors);\n}\nfunction ruleHasOtherActors(rule, actorRelation, actor) {\n const otherActors = [];\n knownActorRelations$1.forEach((knownActorRelation) => {\n const otherActorsWithThisRelation = getIriAll(rule, knownActorRelation).filter((applicableActor) => applicableActor !== actor || knownActorRelation !== actorRelation);\n // Unfortunately Node 10 does not support `.flat()` yet, hence the use of `push`:\n otherActors.push(...otherActorsWithThisRelation);\n });\n return otherActors.length > 0;\n}\nfunction copyPolicyExcludingActor$1(inputPolicy, resourceWithAcr, acpData, actorRelationToExclude, actorToExclude) {\n const newIriSuffix = uuid.v4();\n // Create new Rules for the Policy, excluding the given Actor\n const newAllOfRules = copyRulesExcludingActor(getIriAll(inputPolicy, acp.allOf), resourceWithAcr, acpData, newIriSuffix, actorRelationToExclude, actorToExclude);\n const newAnyOfRules = copyRulesExcludingActor(getIriAll(inputPolicy, acp.anyOf), resourceWithAcr, acpData, newIriSuffix, actorRelationToExclude, actorToExclude);\n const newNoneOfRules = copyRulesExcludingActor(getIriAll(inputPolicy, acp.noneOf), resourceWithAcr, acpData, newIriSuffix, actorRelationToExclude, actorToExclude);\n // Create a new Policy with the new Rules\n let newPolicy = createResourcePolicyFor(resourceWithAcr, encodeURI(asIri(inputPolicy)) + newIriSuffix);\n getIriAll(inputPolicy, acp.allow).forEach((allowMode) => {\n newPolicy = addIri(newPolicy, acp.allow, allowMode);\n });\n getIriAll(inputPolicy, acp.deny).forEach((denyMode) => {\n newPolicy = addIri(newPolicy, acp.deny, denyMode);\n });\n newAllOfRules.forEach((newRule) => {\n newPolicy = addIri(newPolicy, acp.allOf, newRule);\n });\n newAnyOfRules.forEach((newRule) => {\n newPolicy = addIri(newPolicy, acp.anyOf, newRule);\n });\n /* istanbul ignore next Policies listing noneOf Rules are left alone (because they do not unambiguously apply to the given actor always), so there will usually not be any noneOf Rules to copy. */\n newNoneOfRules.forEach((newRule) => {\n newPolicy = addIri(newPolicy, acp.noneOf, newRule);\n });\n return [\n newPolicy,\n newAllOfRules.concat(newAnyOfRules).concat(newNoneOfRules),\n ];\n}\n/** Creates clones of all the Rules identified by `ruleIris` in `acpData`, excluding the given Actor */\nfunction copyRulesExcludingActor(ruleIris, resourceWithAcr, acpData, iriSuffix, actorRelationToExclude, actorToExclude) {\n return ruleIris\n .map((ruleIri) => {\n const rule = acpData.rules.find((rule) => asIri(rule) === ruleIri);\n /* istanbul ignore if: getPoliciesAndRules should already have fetched all referenced Rules, so this should never be true: */\n if (typeof rule === \"undefined\") {\n return null;\n }\n let newRule = createResourceRuleFor(resourceWithAcr, encodeURI(asIri(rule)) + iriSuffix);\n let listsOtherActors = false;\n knownActorRelations$1.forEach((knownActorRelation) => {\n getIriAll(rule, knownActorRelation).forEach((targetActor) => {\n if (knownActorRelation === actorRelationToExclude &&\n targetActor === actorToExclude) {\n return;\n }\n listsOtherActors = true;\n newRule = addIri(newRule, knownActorRelation, targetActor);\n });\n });\n return listsOtherActors ? newRule : null;\n })\n .filter(isNotNull$1);\n}\nfunction isNotNull$1(value) {\n return value !== null;\n}\nasync function internal_getPoliciesAndRules(resource, options = internal_defaultFetchOptions) {\n const acrPolicyUrls = getAcrPolicyUrlAll$1(resource);\n const policyUrls = getPolicyUrlAll$1(resource);\n const allPolicyResourceUrls = getResourceUrls$1(acrPolicyUrls).concat(getResourceUrls$1(policyUrls));\n const policyResources = await getResources$1(allPolicyResourceUrls, options);\n const acrPolicies = getThingsFromResources$1(acrPolicyUrls, policyResources).filter(isNotNull$1);\n const policies = getThingsFromResources$1(policyUrls, policyResources).filter(isNotNull$1);\n const ruleUrlSet = new Set();\n acrPolicies.forEach((acrPolicy) => {\n const referencedRuleUrls = getReferencedRuleUrls(acrPolicy);\n referencedRuleUrls.forEach((ruleUrl) => {\n ruleUrlSet.add(ruleUrl);\n });\n });\n policies.forEach((policy) => {\n const referencedRuleUrls = getReferencedRuleUrls(policy);\n referencedRuleUrls.forEach((ruleUrl) => {\n ruleUrlSet.add(ruleUrl);\n });\n });\n const ruleUrls = Array.from(ruleUrlSet);\n const ruleResourceUrls = ruleUrls.map((ruleUrl) => getResourceUrl$1(ruleUrl));\n const unfetchedRuleResourceUrls = ruleResourceUrls.filter((ruleResourceUrl) => !allPolicyResourceUrls.includes(ruleResourceUrl));\n const ruleResources = await getResources$1(unfetchedRuleResourceUrls, options);\n const allResources = {\n ...policyResources,\n ...ruleResources,\n };\n const rules = getThingsFromResources$1(ruleUrls, allResources).filter(isNotNull$1);\n const inaccessibleUrls = Object.keys(allResources).filter((resourceUrl) => allResources[resourceUrl] === null);\n return {\n inaccessibleUrls,\n acrPolicies,\n policies,\n rules,\n };\n}\nfunction getResourceUrl$1(thingUrl) {\n const thingUrlObject = new URL(thingUrl);\n thingUrlObject.hash = \"\";\n return thingUrlObject.href;\n}\nfunction getResourceUrls$1(thingUrls) {\n const resourceUrls = [];\n thingUrls.forEach((thingUrl) => {\n const resourceUrl = getResourceUrl$1(thingUrl);\n if (!resourceUrls.includes(resourceUrl)) {\n resourceUrls.push(resourceUrl);\n }\n });\n return resourceUrls;\n}\nasync function getResources$1(resourceUrls, options) {\n const uniqueResourceUrls = Array.from(new Set(resourceUrls));\n const resources = {};\n await Promise.all(uniqueResourceUrls.map(async (resourceUrl) => {\n try {\n const resource = await getSolidDataset(resourceUrl, options);\n resources[resourceUrl] = resource;\n }\n catch (e) {\n resources[resourceUrl] = null;\n }\n }));\n return resources;\n}\nfunction getThingsFromResources$1(thingUrls, resources) {\n return thingUrls.map((thingUrl) => {\n const resourceUrl = getResourceUrl$1(thingUrl);\n const resource = resources[resourceUrl];\n if (!resource) {\n return null;\n }\n return getThing(resource, thingUrl);\n });\n}\nfunction getReferencedRuleUrls(policy) {\n return getAllOfRuleUrlAll(policy)\n .concat(getAnyOfRuleUrlAll(policy))\n .concat(getNoneOfRuleUrlAll(policy));\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nfunction universalAccessToAcl(newAccess, previousAccess) {\n var _a, _b, _c, _d;\n // Universal access is aligned on ACP, which means there is a distinction between\n // controlRead and controlWrite. This split doesn't exist in WAC, which is why\n // the type for the input variable of this function is a restriction on the\n // universal Access type.\n if (newAccess.controlRead !== newAccess.controlWrite) {\n throw new Error(\"For Pods using Web Access Control, controlRead and controlWrite must be equal.\");\n }\n return {\n read: (_a = newAccess.read) !== null && _a !== void 0 ? _a : previousAccess.read,\n append: (_b = newAccess.append) !== null && _b !== void 0 ? _b : previousAccess.append,\n write: (_c = newAccess.write) !== null && _c !== void 0 ? _c : previousAccess.write,\n control: (_d = newAccess.controlRead) !== null && _d !== void 0 ? _d : previousAccess.control,\n };\n}\nfunction aclAccessToUniversal(access) {\n // In ACL, denying access to an actor is a notion that doesn't exist, so an\n // access is either granted or not for a given mode.\n // This creates a misalignment with the ACP notion of an access being granted,\n // denied, or simply not mentioned. Here, we convert the boolean vision of\n // ACL into the boolean or undefined vision of ACP.\n return {\n read: access.read,\n write: access.write,\n append: access.append,\n controlRead: access.control,\n controlWrite: access.control,\n };\n}\nasync function getActorAccess(resource, actor, accessEvaluationCallback, options) {\n const resourceAcl = await internal_fetchAcl(resource, options);\n const wacAccess = accessEvaluationCallback(internal_setAcl(resource, resourceAcl), actor);\n if (wacAccess === null) {\n return null;\n }\n return aclAccessToUniversal(wacAccess);\n}\nasync function getActorClassAccess(resource, accessEvaluationCallback, options) {\n const resourceAcl = await internal_fetchAcl(resource, options);\n const wacAccess = accessEvaluationCallback(internal_setAcl(resource, resourceAcl));\n if (wacAccess === null) {\n return null;\n }\n return aclAccessToUniversal(wacAccess);\n}\nasync function getActorAccessAll(resource, accessEvaluationCallback, options) {\n const resourceAcl = await internal_fetchAcl(resource, options);\n const wacAgentAccess = accessEvaluationCallback(internal_setAcl(resource, resourceAcl));\n if (wacAgentAccess === null) {\n return null;\n }\n const result = {};\n for (const [webId, wacAccess] of Object.entries(wacAgentAccess)) {\n result[webId] = aclAccessToUniversal(wacAccess);\n }\n return result;\n}\n/**\n * For a given Resource, look up its metadata, and read the Access permissions\n * granted to the given Agent.\n *\n * Note that this only lists permissions granted to the given Agent individually,\n * and will not exhaustively list modes the given Agent may have access to because\n * they apply to everyone, or because they apply to the Agent through a group for\n * instance.\n *\n * @param resource The URL of the Resource for which we want to list Access\n * @param agent The Agent for which the Access is granted\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns What Access modes are granted to the given Agent explicitly, or null if it could not be determined.\n */\nfunction getAgentAccess$4(resource, agent, options = internal_defaultFetchOptions) {\n return getActorAccess(resource, agent, getAgentAccess$5, options);\n}\n/**\n * For a given Resource, look up its metadata, and read the Access permissions\n * granted to the given Group.\n *\n * Note that this only lists permissions granted to the given Group individually,\n * and will not exhaustively list modes the given Group may have access to because\n * they apply to everyone, or because they apply to the Group through another\n * Group that may contain it for instance.\n *\n * @param resource The URL of the Resource for which we want to list Access\n * @param group The Group for which the Access is granted\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns What Access modes are granted to the given Group explicitly, or null if it could not be determined.\n */\nfunction getGroupAccess$1(resource, group, options = internal_defaultFetchOptions) {\n return getActorAccess(resource, group, getGroupAccess$2, options);\n}\n/**\n * For a given Resource, look up its metadata, and read the Access permissions\n * granted to everyone.\n *\n * Note that this only lists permissions explicitly granted to everyone as a whole,\n * and will not exhaustively list modes any individual Agent or Group may have\n * access to because they specifically apply to them only.\n *\n * @param resource The URL of the Resource for which we want to list public Access\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns What Access modes are granted to the everyone explicitly, or null if it could not be determined.\n */\nfunction getPublicAccess$4(resource, options = internal_defaultFetchOptions) {\n return getActorClassAccess(resource, getPublicAccess$5, options);\n}\n/**\n * For a given Resource, look up its metadata, and read the Access permissions\n * granted explicitly to each individual Agent.\n *\n * Note that this only lists permissions granted to each Agent individually,\n * and will not exhaustively list modes any Agent may have access to because\n * they apply to everyone, or because they apply to an Agent through a group for\n * instance.\n *\n * @param resource The URL of the Resource for which we want to list Agents Access\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns A map of Agent WebIDs and the access granted to them, or null if it could not be determined.\n */\nfunction getAgentAccessAll$4(resource, options = internal_defaultFetchOptions) {\n return getActorAccessAll(resource, getAgentAccessAll$5, options);\n}\n/**\n * For a given Resource, look up its metadata, and read the Access permissions\n * granted explicitly to each individual Group.\n *\n * Note that this only lists permissions granted to each Group individually,\n * and will not exhaustively list modes any Group may have access to because\n * they apply individually to all of the Agents in the Group, or to everyone\n * for instance.\n *\n * @param resource The URL of the Resource for which we want to list Agents Access\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns A map of Group URLs and the access granted to them, or null if it could not be determined.\n */\nfunction getGroupAccessAll$1(resource, options = internal_defaultFetchOptions) {\n return getActorAccessAll(resource, getGroupAccessAll$2, options);\n}\nasync function prepareResourceAcl(resource, options) {\n if (!hasAccessibleAcl(resource)) {\n return null;\n }\n const acl = await internal_fetchAcl(resource, options);\n const resourceWithAcl = internal_setAcl(resource, acl);\n let resourceAcl;\n if (hasResourceAcl(resourceWithAcl)) {\n // This is the simple case, where the Resource ACL we need to update already\n // exists.\n resourceAcl = internal_getResourceAcl(resourceWithAcl);\n }\n else if (hasFallbackAcl(resourceWithAcl)) {\n // In this case, the Resource ACL needs to be created first, and then updated.\n resourceAcl = createAclFromFallbackAcl(resourceWithAcl);\n }\n else {\n return null;\n }\n return internal_setResourceAcl(resourceWithAcl, resourceAcl);\n}\nasync function saveUpdatedAcl(resource, acl, options) {\n let savedAcl = null;\n try {\n savedAcl = await saveAclFor(resource, acl, options);\n return internal_setResourceAcl(resource, savedAcl);\n }\n catch (e) {\n return null;\n }\n}\nasync function setActorClassAccess(resource, access, getAccess, setAccess, options) {\n const resourceWithOldAcl = await prepareResourceAcl(resource, options);\n if (resourceWithOldAcl === null) {\n return null;\n }\n const resourceAcl = getResourceAcl(resourceWithOldAcl);\n const currentAccess = getAccess(resourceWithOldAcl);\n const wacAccess = universalAccessToAcl(access, currentAccess);\n const updatedResourceAcl = setAccess(resourceAcl, wacAccess);\n return saveUpdatedAcl(resourceWithOldAcl, updatedResourceAcl, options);\n}\nasync function setActorAccess(resource, actor, access, getAccess, setAccess, options) {\n const resourceWithOldAcl = await prepareResourceAcl(resource, options);\n if (resourceWithOldAcl === null) {\n return null;\n }\n const currentAccess = getAccess(resourceWithOldAcl, actor);\n const resourceAcl = getResourceAcl(resourceWithOldAcl);\n const wacAccess = universalAccessToAcl(access, currentAccess);\n const updatedResourceAcl = setAccess(resourceAcl, actor, wacAccess);\n return saveUpdatedAcl(resourceWithOldAcl, updatedResourceAcl, options);\n}\n/**\n * Set the Access modes for a given Agent to a given Resource.\n *\n * Important note: if the target resource did not have a Resource ACL, and its\n * Access was regulated by its Fallback ACL, said Fallback ACL is copied to create\n * a new Resource ACL. This has the side effect that the next time the Fallback\n * ACL is updated, the changes _will not impact_ the target resource.\n *\n * If the target Resource's Access mode cannot be determined, e.g. the user does\n * not have Read and Write access to the target Resource's ACL, or to its\n * fallback ACL if it does not have a Resource ACL, then `null` is returned.\n *\n * @param resource The Resource for which Access is being set\n * @param agent The Agent for whom Access is being set\n * @param access The Access being set\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns The Resource, with its ACL updated, or null if the new Access could not\n * be set.\n */\nasync function setAgentResourceAccess(resource, agent, access, options = internal_defaultFetchOptions) {\n return setActorAccess(resource, agent, access, getAgentAccess$5, setAgentResourceAccess$1, options);\n}\n/**\n * Set the Access modes for a given Group to a given Resource.\n *\n * Important note: if the target resource did not have a Resource ACL, and its\n * Access was regulated by its Fallback ACL, said Fallback ACL is copied to create\n * a new Resource ACL. This has the side effect that the next time the Fallback\n * ACL is updated, the changes _will not impact_ the target resource.\n *\n * If the target Resource's Access mode cannot be determined, e.g. the user does\n * not have Read and Write access to the target Resource's ACL, or to its\n * fallback ACL if it does not have a Resource ACL, then `null` is returned.\n *\n * @param resource The Resource for which Access is being set\n * @param agent The Group for which Access is being set\n * @param access The Access being set\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns The Resource, with its ACL updated, or null if the new Access could not\n * be set.\n */\nasync function setGroupResourceAccess(resource, group, access, options = internal_defaultFetchOptions) {\n return setActorAccess(resource, group, access, getGroupAccess$2, setGroupResourceAccess$1, options);\n}\n/**\n * Set the Access modes for everyone to a given Resource.\n *\n * Important note: if the target resource did not have a Resource ACL, and its\n * Access was regulated by its Fallback ACL, said Fallback ACL is copied to create\n * a new Resource ACL. This has the side effect that the next time the Fallback\n * ACL is updated, the changes _will not impact_ the target resource.\n *\n * If the target Resource's Access mode cannot be determined, e.g. the user does\n * not have Read and Write access to the target Resource's ACL, or to its\n * fallback ACL if it does not have a Resource ACL, then `null` is returned.\n *\n * @param resource The Resource for which Access is being set\n * @param access The Access being set\n * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).\n * @returns The Resource, with its ACL updated, or null if the new Access could not\n * be set.\n */\nasync function setPublicResourceAccess(resource, access, options = internal_defaultFetchOptions) {\n return setActorClassAccess(resource, access, getPublicAccess$5, setPublicResourceAccess$1, options);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// This file exists to maintain backwards compatibility with the old API as long\n// as possible. Once pod.inrupt.com implements the breaking changes to Access\n// Control Policies, this will be updated to point to _v2.\n/**\n * @hidden\n * @deprecated Please import from the \"universal\" modules.\n */\n\nvar universal = /*#__PURE__*/Object.freeze({\n __proto__: null,\n getAccessFor: getAccessFor,\n getAccessForAll: getAccessForAll,\n getAgentAccess: getAgentAccess$3,\n getAgentAccessAll: getAgentAccessAll$3,\n getGroupAccess: getGroupAccess,\n getGroupAccessAll: getGroupAccessAll,\n getPublicAccess: getPublicAccess$3,\n setAccessFor: setAccessFor,\n setAgentAccess: setAgentAccess$3,\n setGroupAccess: setGroupAccess,\n setPublicAccess: setPublicAccess$3\n});\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nasync function getAccessFor(resourceUrl, actorType, actor = internal_defaultFetchOptions, options = internal_defaultFetchOptions) {\n if (actorType === \"agent\") {\n if (typeof actor !== \"string\") {\n throw new Error(\"When reading Agent-specific access, the given agent cannot be left undefined.\");\n }\n return getAgentAccess$3(resourceUrl, actor, options);\n }\n if (actorType === \"group\") {\n if (typeof actor !== \"string\") {\n throw new Error(\"When reading Group-specific access, the given group cannot be left undefined.\");\n }\n return getGroupAccess(resourceUrl, actor, options);\n }\n if (actorType === \"public\") {\n if (typeof actor === \"string\") {\n throw new Error(`When reading public access, no actor type should be specified (here [${actor}]).`);\n }\n return getPublicAccess$3(resourceUrl, actor);\n }\n return null;\n}\n/**\n * Get an overview of what access is defined for a given set of actors: all Agents\n * or all Groups.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access, in which case it will\n * resolve to `null`.\n * - It will only return access specified explicitly for the given actor (Agent\n * or Group). If additional restrictions are set up to apply to the given Agent\n * in a particular situation, those will not be reflected in the return value\n * of this function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @param actorType type of actor whose access is being read.\n * @returns What access is set for the given resource, grouped by resp. Agent or Group.\n * @since 1.5.0\n *\n * @hidden\n * @deprecated Access Control Policies will no longer support vcard:Group. Use the mechanism-specific access API's if you want to define access for groups of people.\n */\nasync function getAccessForAll(resourceUrl, actorType, options = internal_defaultFetchOptions) {\n if (actorType === \"agent\") {\n return getAgentAccessAll$3(resourceUrl, options);\n }\n if (actorType === \"group\") {\n return getGroupAccessAll(resourceUrl, options);\n }\n return null;\n}\nasync function setAccessFor(resourceUrl, actorType, access, actor = internal_defaultFetchOptions, options = internal_defaultFetchOptions) {\n if (actorType === \"agent\") {\n if (typeof actor !== \"string\") {\n throw new Error(\"When writing Agent-specific access, the given agent cannot be left undefined.\");\n }\n return setAgentAccess$3(resourceUrl, actor, access, options);\n }\n if (actorType === \"group\") {\n if (typeof actor !== \"string\") {\n throw new Error(\"When writing Group-specific access, the given group cannot be left undefined.\");\n }\n return setGroupAccess(resourceUrl, actor, access, options);\n }\n if (actorType === \"public\") {\n if (typeof actor === \"string\") {\n throw new Error(`When writing public access, no actor type should be specified (here [${actor}]).`);\n }\n return setPublicAccess$3(resourceUrl, access, actor);\n }\n return null;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Get an overview of what access is defined for a given Agent.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access, in which case it will\n * resolve to `null`.\n * - It will only return access specified explicitly for the given Agent. If\n * additional restrictions are set up to apply to the given Agent in a\n * particular situation, those will not be reflected in the return value of\n * this function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @param webId WebID of the Agent you want to get the access for.\n * @since 1.5.0\n * @hidden\n * @deprecated Please import from the \"universal\" modules.\n */\nasync function getAgentAccess$3(resourceUrl, webId, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndRules(resourceInfo, options);\n return internal_getAgentAccess$1(acpData, webId);\n }\n if (hasAccessibleAcl(resourceInfo)) {\n return getAgentAccess$4(resourceInfo, webId, options);\n }\n return null;\n}\n/**\n * Set access to a Resource for a specific Agent.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably setting access, in which case it will\n * resolve to `null`.\n * - It will only set access explicitly for the given Agent. In other words,\n * additional restrictions could be present that further restrict or loosen\n * what access the given Agent has in particular circumstances.\n * - The provided access will only apply to the given Resource. In other words,\n * if the Resource is a Container, the configured Access may not apply to\n * contained Resources.\n * - If the current user does not have permission to view or change access for\n * the given Resource, this function will resolve to `null`.\n *\n * Additionally, two caveats apply to users with a Pod server that uses WAC:\n * - If the Resource did not have an ACL yet, a new one will be initialised.\n * This means that changes to the ACL of a parent Container can no longer\n * affect access people have to this Resource, although existing access will\n * be preserved.\n * - Setting different values for `controlRead` and `controlWrite` is not\n * supported, and **will throw an error**. If you expect (some of) your users\n * to have Pods implementing WAC, be sure to pass the same value for both.\n *\n * @param resourceUrl URL of the Resource you want to change the Agent's access to.\n * @param webId WebID of the Agent you want to set access for.\n * @param access What access permissions you want to set for the given Agent to the given Resource. Possible properties are `read`, `append`, `write`, `controlRead` and `controlWrite`: set to `true` to allow, to `false` to stop allowing, or `undefined` to leave unchanged. Take note that `controlRead` and `controlWrite` can not have distinct values for a Pod server implementing Web Access Control; trying this will throw an error.\n * @returns What access has been set for the given Agent explicitly.\n * @since 1.5.0\n * @hidden\n * @deprecated Please import from the \"universal\" modules.\n */\nasync function setAgentAccess$3(resourceUrl, webId, access, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndRules(resourceInfo, options);\n const updatedResource = internal_setAgentAccess$1(resourceInfo, acpData, webId, access);\n if (updatedResource) {\n try {\n await saveAcrFor(updatedResource, options);\n return await getAgentAccess$3(resourceUrl, webId, options);\n }\n catch (e) {\n return null;\n }\n }\n return null;\n }\n if (hasAccessibleAcl(resourceInfo)) {\n if (access.controlRead !== access.controlWrite) {\n throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${getSourceIri(resourceInfo)}]), \\`controlRead\\` and \\`controlWrite\\` should have the same value.`);\n }\n const wacAccess = access;\n await setAgentResourceAccess(resourceInfo, webId, wacAccess, options);\n return getAgentAccess$4(resourceInfo, webId, options);\n }\n return null;\n}\n/**\n * Get an overview of what access is defined for all Agents with respect to a given\n * Resource.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access, in which case it will\n * resolve to `null`.\n * - It will only return access specified explicitly for the returned Agents. If\n * additional restrictions are set up to apply to the listed Agents in a\n * particular situation, those will not be reflected in the return value of\n * this function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @returns The access information to the Resource, grouped by Agent.\n * @since 1.5.0\n * @hidden\n * @deprecated Please import from the \"universal\" modules.\n */\nasync function getAgentAccessAll$3(resourceUrl, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndRules(resourceInfo, options);\n return internal_getAgentAccessAll$1(acpData);\n }\n if (hasAccessibleAcl(resourceInfo)) {\n return getAgentAccessAll$4(resourceInfo, options);\n }\n return null;\n}\n/**\n * Get an overview of what access is defined for a given Group.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access, in which case it will\n * resolve to `null`.\n * - It will only return access specified explicitly for the given Group. If\n * additional restrictions are set up to apply to the given Group in a\n * particular situation, those will not be reflected in the return value of\n * this function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @param webId WebID of the Group you want to get the access for.\n * @since 1.5.0\n * @hidden\n * @deprecated Access Control Policies will no longer support vcard:Group. Use the mechanism-specific access API's if you want to define access for groups of people.\n */\nasync function getGroupAccess(resourceUrl, webId, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndRules(resourceInfo, options);\n return internal_getGroupAccess(acpData, webId);\n }\n if (hasAccessibleAcl(resourceInfo)) {\n return getGroupAccess$1(resourceInfo, webId, options);\n }\n return null;\n}\n/**\n * Get an overview of what access is defined for all Groups with respect to a given\n * Resource.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access, in which case it will\n * resolve to `null`.\n * - It will only return access specified explicitly for the returned Groups. If\n * additional restrictions are set up to apply to the listed Groups in a\n * particular situation, those will not be reflected in the return value of\n * this function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @returns The access information to the Resource, sorted by Group.\n * @since 1.5.0\n * @hidden\n * @deprecated Access Control Policies will no longer support vcard:Group. Use the mechanism-specific access API's if you want to define access for groups of people.\n */\nasync function getGroupAccessAll(resourceUrl, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndRules(resourceInfo, options);\n return internal_getGroupAccessAll(acpData);\n }\n if (hasAccessibleAcl(resourceInfo)) {\n return getGroupAccessAll$1(resourceInfo, options);\n }\n return null;\n}\n/**\n * Set access to a Resource for a specific Group.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably setting access, in which case it will\n * resolve to `null`.\n * - It will only set access explicitly for the given Group. In other words,\n * additional restrictions could be present that further restrict or loosen\n * what access the given Group has in particular circumstances.\n * - The provided access will only apply to the given Resource. In other words,\n * if the Resource is a Container, the configured Access may not apply to\n * contained Resources.\n * - If the current user does not have permission to view or change access for\n * the given Resource, this function will resolve to `null`.\n *\n * Additionally, two caveats apply to users with a Pod server that uses WAC:\n * - If the Resource did not have an ACL yet, a new one will be initialised.\n * This means that changes to the ACL of a parent Container can no longer\n * affect access people have to this Resource, although existing access will\n * be preserved.\n * - Setting different values for `controlRead` and `controlWrite` is not\n * supported, and **will throw an error**. If you expect (some of) your users\n * to have Pods implementing WAC, be sure to pass the same value for both.\n *\n * @param resourceUrl URL of the Resource you want to change the Group's access to.\n * @param groupUrl URL of the Group you want to set access for.\n * @param access What access permissions you want to set for the given Group to the given Resource. Possible properties are `read`, `append`, `write`, `controlRead` and `controlWrite`: set to `true` to allow, to `false` to stop allowing, or `undefined` to leave unchanged. Take note that `controlRead` and `controlWrite` can not have distinct values for a Pod server implementing Web Access Control; trying this will throw an error.\n * @returns What access has been set for the given Group explicitly.\n * @since 1.5.0\n * @hidden\n * @deprecated Access Control Policies will no longer support vcard:Group. Use the mechanism-specific access API's if you want to define access for groups of people.\n */\nasync function setGroupAccess(resourceUrl, groupUrl, access, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndRules(resourceInfo, options);\n const updatedResource = internal_setGroupAccess(resourceInfo, acpData, groupUrl, access);\n if (updatedResource) {\n try {\n await saveAcrFor(updatedResource, options);\n return await getGroupAccess(resourceUrl, groupUrl, options);\n }\n catch (e) {\n return null;\n }\n }\n return null;\n }\n if (hasAccessibleAcl(resourceInfo)) {\n if (access.controlRead !== access.controlWrite) {\n throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${getSourceIri(resourceInfo)}]), \\`controlRead\\` and \\`controlWrite\\` should have the same value.`);\n }\n const wacAccess = access;\n await setGroupResourceAccess(resourceInfo, groupUrl, wacAccess, options);\n return getGroupAccess$1(resourceInfo, groupUrl, options);\n }\n return null;\n}\n/**\n * Get an overview of what access is defined for everyone.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access, in which case it will\n * resolve to `null`.\n * - It will only return access specified explicitly for everyone. If\n * additional restrictions are set up to apply to users in a particular\n * situation, those will not be reflected in the return value of this\n * function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @since 1.5.0\n *\n * @hidden\n * @deprecated Please import from the \"universal\" modules.\n */\nasync function getPublicAccess$3(resourceUrl, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndRules(resourceInfo, options);\n return internal_getPublicAccess$1(acpData);\n }\n if (hasAccessibleAcl(resourceInfo)) {\n return getPublicAccess$4(resourceInfo, options);\n }\n return null;\n}\n/**\n * Set access to a Resource for everybody.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably setting access, in which case it will\n * resolve to `null`.\n * - It will only set access explicitly for everybody. In other words,\n * additional restrictions could be present that further restrict or loosen\n * what access a user has in particular circumstances.\n * - The provided access will only apply to the given Resource. In other words,\n * if the Resource is a Container, the configured Access may not apply to\n * contained Resources.\n * - If the current user does not have permission to view or change access for\n * the given Resource, this function will resolve to `null`.\n *\n * Additionally, two caveats apply to users with a Pod server that uses WAC:\n * - If the Resource did not have an ACL yet, a new one will be initialised.\n * This means that changes to the ACL of a parent Container can no longer\n * affect access people have to this Resource, although existing access will\n * be preserved.\n * - Setting different values for `controlRead` and `controlWrite` is not\n * supported, and **will throw an error**. If you expect (some of) your users\n * to have Pods implementing WAC, be sure to pass the same value for both.\n *\n * @param resourceUrl URL of the Resource you want to change public access to.\n * @param access What access permissions you want to set for everybody to the given Resource. Possible properties are `read`, `append`, `write`, `controlRead` and `controlWrite`: set to `true` to allow, to `false` to stop allowing, or `undefined` to leave unchanged. Take note that `controlRead` and `controlWrite` can not have distinct values for a Pod server implementing Web Access Control; trying this will throw an error.\n * @returns What access has been set for everybody explicitly.\n * @since 1.5.0\n *\n * @hidden\n * @deprecated Please import from the \"universal\" modules.\n */\nasync function setPublicAccess$3(resourceUrl, access, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndRules(resourceInfo, options);\n const updatedResource = internal_setPublicAccess$1(resourceInfo, acpData, access);\n if (updatedResource) {\n try {\n await saveAcrFor(updatedResource, options);\n return await getPublicAccess$3(resourceUrl, options);\n }\n catch (e) {\n return null;\n }\n }\n return null;\n }\n if (hasAccessibleAcl(resourceInfo)) {\n if (access.controlRead !== access.controlWrite) {\n throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${getSourceIri(resourceInfo)}]), \\`controlRead\\` and \\`controlWrite\\` should have the same value.`);\n }\n const wacAccess = access;\n await setPublicResourceAccess(resourceInfo, wacAccess, options);\n return getPublicAccess$4(resourceInfo, options);\n }\n return null;\n}\n\nvar universal_v1 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n getAccessFor: getAccessFor,\n getAccessForAll: getAccessForAll,\n getAgentAccess: getAgentAccess$3,\n getAgentAccessAll: getAgentAccessAll$3,\n getGroupAccess: getGroupAccess,\n getGroupAccessAll: getGroupAccessAll,\n getPublicAccess: getPublicAccess$3,\n setAccessFor: setAccessFor,\n setAgentAccess: setAgentAccess$3,\n setGroupAccess: setGroupAccess,\n setPublicAccess: setPublicAccess$3\n});\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\nconst knownActorRelations = [acp.agent];\n/**\n * Get an overview of what access is defined for a given actor in a Resource's Access Control Resource.\n *\n * This will only return a value if all relevant access is defined in just the Resource's Access\n * Control Resource; in other words, if an Access Policy or Access Matcher applies that is re-used for\n * other Resources, this function will not be able to determine the access relevant to this actor.\n *\n * Additionally, this only considers access given _explicitly_ to the given actor, i.e. without\n * additional conditions.\n *\n * In other words, this function will generally understand and return the access as set by\n * [[internal_setActorAccess]], but not understand more convoluted Policies.\n *\n * @param acpData All Access Control Policies and Matchers that apply to a particular Resource.\n * @param actorRelation What type of actor (e.g. acp:agent) you want to get the access for.\n * @param actor Which instance of the given actor type you want to get the access for.\n * @returns What Access modes are granted to the given actor explicitly, or null if it could not be determined.\n */\nfunction internal_getActorAccess(acpData, actorRelation, actor) {\n if (acpData.inaccessibleUrls.length > 0) {\n // If we can't see all access data,\n // we can't reliably determine what access the given actor has:\n return null;\n }\n const applicableAcrPolicies = acpData.acrPolicies.filter((policy) => policyAppliesTo(policy, actorRelation, actor, acpData));\n const applicablePolicies = acpData.policies.filter((policy) => policyAppliesTo(policy, actorRelation, actor, acpData));\n const initialAccess = {\n read: false,\n append: false,\n write: false,\n controlRead: false,\n controlWrite: false,\n };\n // All allowed reading and writing defined in ACR policies\n // determines whether the `controlRead` and `controlWrite` statuses are `true`.\n const allowedAcrAccess = applicableAcrPolicies.reduce((acc, policy) => {\n const allAllowedAccess = { ...acc };\n const allowModes = getAllowModesV2(policy);\n if (allowModes.read) {\n allAllowedAccess.controlRead = true;\n }\n if (allowModes.write) {\n allAllowedAccess.controlWrite = true;\n }\n return allAllowedAccess;\n }, initialAccess);\n // Then allowed reading, appending and writing in regular policies\n // determines whether the respective status is `true`.\n const withAllowedAccess = applicablePolicies.reduce((acc, policy) => {\n const allAllowedAccess = { ...acc };\n const allowModes = getAllowModesV2(policy);\n if (allowModes.read) {\n allAllowedAccess.read = true;\n }\n if (allowModes.append) {\n allAllowedAccess.append = true;\n }\n if (allowModes.write) {\n allAllowedAccess.write = true;\n }\n return allAllowedAccess;\n }, allowedAcrAccess);\n // At this point, everything that has been explicitly allowed is true.\n // However, it could still be overridden by access that is explicitly denied.\n // Starting with `controlRead` and `controlWrite`,\n // by inspecting denied reading and writing defined in the ACR policies.\n const withAcrDeniedAccess = applicableAcrPolicies.reduce((acc, policy) => {\n const allDeniedAccess = { ...acc };\n const denyModes = getDenyModesV2(policy);\n if (denyModes.read === true) {\n allDeniedAccess.controlRead = false;\n }\n if (denyModes.write === true) {\n allDeniedAccess.controlWrite = false;\n }\n return allDeniedAccess;\n }, withAllowedAccess);\n // And finally, we set to `false` those access modes that are explicitly denied\n // in the regular policies:\n const withDeniedAccess = applicablePolicies.reduce((acc, policy) => {\n const allDeniedAccess = { ...acc };\n const denyModes = getDenyModesV2(policy);\n if (denyModes.read === true) {\n allDeniedAccess.read = false;\n }\n if (denyModes.append === true) {\n allDeniedAccess.append = false;\n }\n if (denyModes.write === true) {\n allDeniedAccess.write = false;\n }\n return allDeniedAccess;\n }, withAcrDeniedAccess);\n return withDeniedAccess;\n}\n/**\n * Get an overview of what access is defined for a given Agent in a Resource's Access Control Resource.\n *\n * This will only return a value if all relevant access is defined in just the Resource's Access\n * Control Resource; in other words, if an Access Policy or Access Matcher applies that is re-used for\n * other Resources, this function will not be able to determine the access relevant to this Agent.\n *\n * Additionally, this only considers access given _explicitly_ to the given Agent, i.e. without\n * additional conditions.\n *\n * In other words, this function will generally understand and return the access as set by\n * [[internal_setAgentAccess]], but not understand more convoluted Policies.\n *\n * @param acpData All Access Control Policies and Matchers that apply to a particular Resource.\n * @param webId WebID of the Agent you want to get the access for.\n * @returns What Access modes are granted to the given Agent explicitly, or null if it could not be determined.\n */\nfunction internal_getAgentAccess(acpData, webId) {\n return internal_getActorAccess(acpData, acp.agent, webId);\n}\n/**\n * Get an overview of what access is defined for everybody in a Resource's Access Control Resource.\n *\n * This will only return a value if all relevant access is defined in just the Resource's Access\n * Control Resource; in other words, if an Access Policy or Access Matcher applies that is re-used for\n * other Resources, this function will not be able to determine the access relevant to everybody.\n *\n * Additionally, this only considers access given _explicitly_ to everybody, i.e. without\n * additional conditions.\n *\n * In other words, this function will generally understand and return the access as set by\n * [[internal_setPublicAccess]], but not understand more convoluted Policies.\n *\n * @param acpData All Access Control Policies and Matchers that apply to a particular Resource.\n * @returns What Access modes are granted to everyone explicitly, or null if it could not be determined.\n */\nfunction internal_getPublicAccess(acpData) {\n return internal_getActorAccess(acpData, acp.agent, acp.PublicAgent);\n}\nfunction policyAppliesTo(policy, actorRelation, actor, acpData) {\n const allowModes = getIriAll(policy, acp.allow);\n const denyModes = getIriAll(policy, acp.deny);\n if (allowModes.length + denyModes.length === 0) {\n // A Policy that does not specify access modes does not do anything:\n return false;\n }\n // Note: the non-null assertions (`!`) here should be valid because\n // the caller of `policyAppliesTo` should already have validated that\n // the return value of internal_getPoliciesAndMatchers() did not have any\n // inaccessible URLs, so we should be able to find every Matcher.\n const allOfMatchers = getAllOfMatcherUrlAll(policy).map((matcherUrl) => acpData.matchers.find((matcher) => asIri(matcher) === matcherUrl));\n const anyOfMatchers = getAnyOfMatcherUrlAll(policy).map((matcherUrl) => acpData.matchers.find((matcher) => asIri(matcher) === matcherUrl));\n const noneOfMatchers = getNoneOfMatcherUrlAll(policy).map((matcherUrl) => acpData.matchers.find((matcher) => asIri(matcher) === matcherUrl));\n // We assume that this Policy applies if this specific actor is mentioned\n // and no further restrictions are in place.\n // (In other words, the Policy may apply to others *in addition to* this\n // actor, but if it applies to this actor *unless* some other condition holds,\n // we cannot be sure whether it will apply to this actor.)\n // This means that:\n return (\n // Every existing allOf Matcher explicitly applies explicitly to this given actor:\n allOfMatchers.every((matcher) => matcherAppliesTo(matcher, actorRelation, actor)) &&\n // If there are anyOf Matchers, at least one applies explicitly to this actor:\n (anyOfMatchers.length === 0 ||\n anyOfMatchers.some((matcher) => matcherAppliesTo(matcher, actorRelation, actor))) &&\n // There is at least one allOf or anyOf Matcher:\n allOfMatchers.length + anyOfMatchers.length > 0 &&\n // No further restrictions are in place that make this sometimes not apply\n // to the given actor:\n noneOfMatchers.length === 0);\n}\nfunction policyConflictsWith(policy, otherAccess) {\n const allowModes = getIriAll(policy, acp.allow);\n const denyModes = getIriAll(policy, acp.deny);\n return ((otherAccess.read === true &&\n denyModes.includes(internal_accessModeIriStrings.read)) ||\n (otherAccess.read === false &&\n allowModes.includes(internal_accessModeIriStrings.read) &&\n !denyModes.includes(internal_accessModeIriStrings.read)) ||\n (otherAccess.append === true &&\n denyModes.includes(internal_accessModeIriStrings.append)) ||\n (otherAccess.append === false &&\n allowModes.includes(internal_accessModeIriStrings.append) &&\n !denyModes.includes(internal_accessModeIriStrings.append)) ||\n (otherAccess.write === true &&\n denyModes.includes(internal_accessModeIriStrings.write)) ||\n (otherAccess.write === false &&\n allowModes.includes(internal_accessModeIriStrings.write) &&\n !denyModes.includes(internal_accessModeIriStrings.write)));\n}\nfunction matcherAppliesTo(matcher, actorRelation, actor) {\n return getIriAll(matcher, actorRelation).includes(actor);\n}\n/**\n * Get a set of all actors mentioned in an ACR by active Matchers (i.e. that are\n * referenced by Policies referenced by the ACR Control, and therefore that\n * effectively apply).\n *\n * @param acpData All Access Control Policies and Matchers that apply to a particular Resource.\n * @param actorRelation\n */\nfunction internal_findActorAll(acpData, actorRelation) {\n const actors = new Set();\n // This code could be prettier using flat(), which isn't supported by nodeJS 10.\n // If you read this comment after April 2021, feel free to refactor.\n acpData.matchers.forEach((matcher) => {\n getIriAll(matcher, actorRelation)\n .filter((iri) => ![\n acp.PublicAgent,\n acp.CreatorAgent,\n acp.AuthenticatedAgent,\n ].includes(iri) || actorRelation !== acp.agent)\n .forEach((iri) => actors.add(iri));\n });\n return actors;\n}\n/**\n * Iterate through all the actors active for an ACR, and list all of their access.\n * @param acpData All Access Control Policies and Matchers that apply to a particular Resource.\n * @param actorRelation The type of actor we want to list access for\n * @returns A map with each actor access indexed by their URL, or null if some\n * external policies are referenced.\n */\nfunction internal_getActorAccessAll(acpData, actorRelation) {\n if (acpData.inaccessibleUrls.length > 0) {\n // If we can't see all access data,\n // we can't reliably determine what access actors of the given type have:\n return null;\n }\n const result = {};\n const actors = internal_findActorAll(acpData, actorRelation);\n actors.forEach((iri) => {\n // The type assertion holds, because if internal_getActorAccess were null,\n // we would have returned {} already.\n const access = internal_getActorAccess(acpData, actorRelation, iri);\n result[iri] = access;\n });\n return result;\n}\n/**\n * Get an overview of what access are defined for all Agents in a Resource's Access Control Resource.\n *\n * This will only return a value if all relevant access is defined in just the Resource's Access\n * Control Resource; in other words, if an Access Policy or Access Matcher applies that is re-used for\n * other Resources, this function will not be able to determine the access relevant to the mentionned\n * Agents.\n *\n * Additionally, this only considers access given _explicitly_ to individual Agents, i.e. without\n * additional conditions.\n *\n * In other words, this function will generally understand and return the access as set by\n * [[internal_setAgentAccess]], but not understand more convoluted Policies.\n *\n * @param acpData All Access Control Policies and Matchers that apply to a particular Resource.\n * @returns A map with each Agent's access indexed by their WebID, or null if some\n * external policies are referenced.\n */\nfunction internal_getAgentAccessAll(acpData) {\n return internal_getActorAccessAll(acpData, acp.agent);\n}\n/**\n * Set access to a Resource for a specific actor.\n *\n * This function adds the relevant Access Control Policies and Matchers to a\n * Resource's Access Control Resource to define the given access for the given\n * actor specifically. In other words, it can, for example, add Policies that\n * give the general Public Read access to the Resource. However, if other\n * Policies specify that everyone is *denied* Read access *except* for a\n * particular Agent, then that will be left intact.\n * This means that, unless *only* this module's functions are used to manipulate\n * access to this Resource, the set access might not be equal to the effective\n * access for an agent matching the given actor.\n *\n * There are a number of preconditions that have to be fulfilled for this\n * function to work:\n * - Access to the Resource is determined via an Access Control Resource.\n * - The Resource's Access Control Resource does not refer to (Policies or Matchers\n * in) other Resources.\n * - The current user has access to the Resource's Access Control Resource.\n *\n * If those conditions do not hold, this function will return `null`.\n *\n * Additionally, take note that the given access will only be applied to the\n * given Resource; if that Resource is a Container, access will have to be set\n * for its contained Resources independently.\n *\n * @param resource Resource that was fetched together with its linked Access Control Resource.\n * @param acpData All Access Control Policies and Matchers that apply to a particular Resource.\n * @param actorRelation What type of actor (e.g. acp:agent) you want to set the access for.\n * @param actor Which instance of the given actor type you want to set the access for.\n * @param access What access (read, append, write, controlRead, controlWrite) to set for the given actor. `true` to allow, `false` to deny, and `undefined` to leave unchanged.\n * @returns The Resource with the updated Access Control Resource attached, if updated successfully, or `null` if not.\n */\nfunction internal_setActorAccess(resource, acpData, actorRelation, actor, access) {\n var _a, _b, _c, _d, _e;\n if (!hasAccessibleAcr(resource) || acpData.inaccessibleUrls.length > 0) {\n return null;\n }\n // Get the access that currently applies to the given actor\n const existingAccess = internal_getActorAccess(acpData, actorRelation, actor);\n /* istanbul ignore if: It returns null if the ACR has inaccessible Policies, which should happen since we already check for that above. */\n if (existingAccess === null) {\n return null;\n }\n // Get all Policies that apply specifically to the given actor\n const applicableAcrPolicies = acpData.acrPolicies.filter((policy) => policyAppliesTo(policy, actorRelation, actor, acpData));\n const applicablePolicies = acpData.policies.filter((policy) => policyAppliesTo(policy, actorRelation, actor, acpData));\n // We only need to override Policies that define access other than what we want:\n const conflictingAcrPolicies = applicableAcrPolicies.filter((policy) => policyConflictsWith(policy, {\n read: access.controlRead,\n write: access.controlWrite,\n }));\n const conflictingPolicies = applicablePolicies.filter((policy) => policyConflictsWith(policy, {\n read: access.read,\n append: access.append,\n write: access.write,\n }));\n // For every Policy that applies specifically to the given Actor, but _also_\n // to another actor (i.e. that applies using an anyOf Matcher, or a Matcher that\n // mentions both the given and another actor)...\n const otherActorAcrPolicies = conflictingAcrPolicies.filter((acrPolicy) => policyHasOtherActors(acrPolicy, actorRelation, actor, acpData));\n const otherActorPolicies = conflictingPolicies.filter((policy) => policyHasOtherActors(policy, actorRelation, actor, acpData));\n // ...check what access the current actor would have if we removed them...\n const acpDataWithPoliciesExcluded = {\n ...acpData,\n acrPolicies: acpData.acrPolicies.filter((acrPolicy) => !otherActorAcrPolicies.includes(acrPolicy)),\n policies: acpData.policies.filter((policy) => !otherActorPolicies.includes(policy)),\n };\n const remainingAccess = internal_getActorAccess(acpDataWithPoliciesExcluded, actorRelation, actor);\n /* istanbul ignore if: It returns null if the ACR has inaccessible Policies, which should happen since we already check for that at the start. */\n if (remainingAccess === null) {\n return null;\n }\n // ...add copies of those Policies and their Matchers, but excluding the given actor...\n let updatedResource = resource;\n otherActorAcrPolicies.forEach((acrPolicy) => {\n const [policyCopy, matcherCopies] = copyPolicyExcludingActor(acrPolicy, resource, acpData, actorRelation, actor);\n updatedResource = setResourceAcrPolicy(updatedResource, policyCopy);\n updatedResource = matcherCopies.reduce(setResourceMatcher, updatedResource);\n });\n otherActorPolicies.forEach((policy) => {\n const [policyCopy, matcherCopies] = copyPolicyExcludingActor(policy, resource, acpData, actorRelation, actor);\n updatedResource = setResourcePolicy$1(updatedResource, policyCopy);\n updatedResource = matcherCopies.reduce(setResourceMatcher, updatedResource);\n });\n // ...add a new Policy that applies the given access,\n // and the previously applying access for access modes that were undefined...\n const newMatcherName = `matcher_${encodeURIComponent(`${actorRelation}_${actor}`)}`;\n let newMatcher = createResourceMatcherFor(resource, newMatcherName);\n newMatcher = setIri(newMatcher, actorRelation, actor);\n const newControlReadAccess = (_a = access.controlRead) !== null && _a !== void 0 ? _a : existingAccess.controlRead;\n const newControlWriteAccess = (_b = access.controlWrite) !== null && _b !== void 0 ? _b : existingAccess.controlWrite;\n let acrPoliciesToUnapply = otherActorAcrPolicies;\n // Only replace existing Policies if the defined access actually changes:\n if (newControlReadAccess !== remainingAccess.controlRead ||\n newControlWriteAccess !== remainingAccess.controlWrite) {\n const newAcrPolicyName = uuid.v4();\n let newAcrPolicy = createResourcePolicyFor(resource, newAcrPolicyName);\n newAcrPolicy = setAllowModesV2(newAcrPolicy, {\n read: newControlReadAccess === true,\n append: false,\n write: newControlWriteAccess === true,\n });\n newAcrPolicy = addIri(newAcrPolicy, acp.allOf, newMatcher);\n updatedResource = setResourceAcrPolicy(updatedResource, newAcrPolicy);\n updatedResource = setResourceMatcher(updatedResource, newMatcher);\n // If we don't have to set new access, we only need to unapply the\n // ACR Policies that applied to both the given actor and other actors\n // (because they have been replaced by clones not mentioning the given\n // actor). Hence `policiesToUnApply` is initialised to `otherActorPolicies`.\n // However, if we're in this if branch, that means we also had to replace\n // Policies that defined access for just this actor, so we'll have to remove\n // all Policies mentioning this actor:\n acrPoliciesToUnapply = conflictingAcrPolicies;\n }\n const newReadAccess = (_c = access.read) !== null && _c !== void 0 ? _c : existingAccess.read;\n const newAppendAccess = (_d = access.append) !== null && _d !== void 0 ? _d : existingAccess.append;\n const newWriteAccess = (_e = access.write) !== null && _e !== void 0 ? _e : existingAccess.write;\n let policiesToUnapply = otherActorPolicies;\n // Only replace existing Policies if the defined access actually changes:\n if (newReadAccess !== remainingAccess.read ||\n newAppendAccess !== remainingAccess.append ||\n newWriteAccess !== remainingAccess.write) {\n const newPolicyName = uuid.v4();\n let newPolicy = createResourcePolicyFor(resource, newPolicyName);\n newPolicy = setAllowModesV2(newPolicy, {\n read: newReadAccess === true,\n append: newAppendAccess === true,\n write: newWriteAccess === true,\n });\n newPolicy = addIri(newPolicy, acp.allOf, newMatcher);\n updatedResource = setResourcePolicy$1(updatedResource, newPolicy);\n updatedResource = setResourceMatcher(updatedResource, newMatcher);\n // If we don't have to set new access, we only need to unapply the\n // Policies that applied to both the given actor and other actors (because\n // they have been replaced by clones not mentioning the given actor). Hence\n // `policiesToUnApply` is initialised to `otherActorPolicies`.\n // However, if we're in this if branch, that means we also had to replace\n // Policies that defined access for just this actor, so we'll have to remove\n // all Policies mentioning this actor:\n policiesToUnapply = conflictingPolicies;\n }\n // ...then remove existing Policy URLs that mentioned both the given actor\n // and other actors from the given Resource and apply the new ones (but do not\n // remove the actual old Policies - they might still apply to other Resources!).\n acrPoliciesToUnapply.forEach((previouslyApplicableAcrPolicy) => {\n updatedResource = removeAcrPolicyUrl$1(updatedResource, asIri(previouslyApplicableAcrPolicy));\n });\n policiesToUnapply.forEach((previouslyApplicablePolicy) => {\n updatedResource = removePolicyUrl$1(updatedResource, asIri(previouslyApplicablePolicy));\n });\n return updatedResource;\n}\n/**\n * Set access to a Resource for a specific Agent.\n *\n * This function adds the relevant Access Control Policies and Matchers to a\n * Resource's Access Control Resource to define the given access for the given\n * Agent specifically. In other words, it can, for example, add Policies that\n * give a particular Agent Read access to the Resource. However, if other\n * Policies specify that that Agent is *denied* Read access *except* if they\n * match on some other characteristic, then that will be left intact.\n * This means that, unless *only* this function is used to manipulate access to\n * this Resource, the set access might not be equal to the effective access for\n * the given Agent.\n *\n * There are a number of preconditions that have to be fulfilled for this\n * function to work:\n * - Access to the Resource is determined via an Access Control Resource.\n * - The Resource's Access Control Resource does not refer to (Policies or Matchers\n * in) other Resources.\n * - The current user has access to the Resource's Access Control Resource.\n *\n * If those conditions do not hold, this function will return `null`.\n *\n * Additionally, take note that the given access will only be applied to the\n * given Resource; if that Resource is a Container, access will have to be set\n * for its contained Resources independently.\n *\n * @param resource Resource that was fetched together with its linked Access Control Resource.\n * @param acpData All Access Control Policies and Matchers that apply to a particular Resource.\n * @param webId Which Agent you want to set the access for.\n * @param access What access (read, append, write, controlRead, controlWrite) to set for the given Agent. `true` to allow, `false` to deny, and `undefined` to leave unchanged.\n * @returns The Resource with the updated Access Control Resource attached, if updated successfully, or `null` if not.\n */\nfunction internal_setAgentAccess(resource, acpData, webId, access) {\n return internal_setActorAccess(resource, acpData, acp.agent, webId, access);\n}\n/**\n * Set access to a Resource for everybody.\n *\n * This function adds the relevant Access Control Policies and Matchers to a\n * Resource's Access Control Resource to define the given access for everybody\n * specifically. In other words, it can, for example, add Policies that\n * give everybody Read access to the Resource. However, if other\n * Policies specify that everybody is *denied* Read access *except* if they're\n * a particular Agent, then that will be left intact.\n * This means that, unless *only* this module's functions are used to manipulate\n * access to this Resource, the set access might not be equal to the effective\n * access for a particular Agent.\n *\n * There are a number of preconditions that have to be fulfilled for this\n * function to work:\n * - Access to the Resource is determined via an Access Control Resource.\n * - The Resource's Access Control Resource does not refer to (Policies or Matchers\n * in) other Resources.\n * - The current user has access to the Resource's Access Control Resource.\n *\n * If those conditions do not hold, this function will return `null`.\n *\n * Additionally, take note that the given access will only be applied to the\n * given Resource; if that Resource is a Container, access will have to be set\n * for its contained Resources independently.\n *\n * @param resource Resource that was fetched together with its linked Access Control Resource.\n * @param acpData All Access Control Policies and Matchers that apply to a particular Resource.\n * @param access What access (read, append, write, controlRead, controlWrite) to set for everybody. `true` to allow, `false` to deny, and `undefined` to leave unchanged.\n * @returns The Resource with the updated Access Control Resource attached, if updated successfully, or `null` if not.\n */\nfunction internal_setPublicAccess(resource, acpData, access) {\n return internal_setActorAccess(resource, acpData, acp.agent, acp.PublicAgent, access);\n}\nfunction policyHasOtherActors(policy, actorRelation, actor, acpData) {\n // Note: the non-null assertions (`!`) here should be valid because\n // the caller of `policyHasOtherActors` should already have validated\n // that the return value of internal_getPoliciesAndMatchers() did not have\n // any inaccessible URLs, so we should be able to find every Matcher.\n const allOfMatchers = getIriAll(policy, acp.allOf).map((matcherUrl) => acpData.matchers.find((matcher) => asIri(matcher) === matcherUrl));\n const allOfMatchersHaveOtherActors = allOfMatchers.some((matcher) => {\n return matcherHasOtherActors(matcher, actorRelation, actor);\n });\n const anyOfMatchers = getIriAll(policy, acp.anyOf).map((matcherUrl) => acpData.matchers.find((matcher) => asIri(matcher) === matcherUrl));\n const anyOfMatchersHaveOtherActors = anyOfMatchers.some((matcher) => {\n return matcherHasOtherActors(matcher, actorRelation, actor);\n });\n /* istanbul ignore next This function only gets called after policyAppliesTo, which already filters out all noneOf Matchers */\n const noneOfMatchers = getIriAll(policy, acp.noneOf).map((matcherUrl) => acpData.matchers.find((matcher) => asIri(matcher) === matcherUrl));\n /* istanbul ignore next This function only gets called after policyAppliesTo, which already filters out all noneOf Matchers */\n const noneOfMatchersHaveOtherActors = noneOfMatchers.some((matcher) => {\n return matcherHasOtherActors(matcher, actorRelation, actor);\n });\n return (allOfMatchersHaveOtherActors ||\n anyOfMatchersHaveOtherActors ||\n noneOfMatchersHaveOtherActors);\n}\nfunction matcherHasOtherActors(matcher, actorRelation, actor) {\n const otherActors = [];\n knownActorRelations.forEach((knownActorRelation) => {\n const otherActorsWithThisRelation = getIriAll(matcher, knownActorRelation).filter((applicableActor) => applicableActor !== actor || knownActorRelation !== actorRelation);\n // Unfortunately Node 10 does not support `.flat()` yet, hence the use of `push`:\n otherActors.push(...otherActorsWithThisRelation);\n });\n return otherActors.length > 0;\n}\nfunction copyPolicyExcludingActor(inputPolicy, resourceWithAcr, acpData, actorRelationToExclude, actorToExclude) {\n const newIriSuffix = uuid.v4();\n // Create new Matchers for the Policy, excluding the given Actor\n const newAllOfMatchers = copyMatchersExcludingActor(getIriAll(inputPolicy, acp.allOf), resourceWithAcr, acpData, newIriSuffix, actorRelationToExclude, actorToExclude);\n const newAnyOfMatchers = copyMatchersExcludingActor(getIriAll(inputPolicy, acp.anyOf), resourceWithAcr, acpData, newIriSuffix, actorRelationToExclude, actorToExclude);\n const newNoneOfMatchers = copyMatchersExcludingActor(getIriAll(inputPolicy, acp.noneOf), resourceWithAcr, acpData, newIriSuffix, actorRelationToExclude, actorToExclude);\n // Create a new Policy with the new Matchers\n let newPolicy = createResourcePolicyFor(resourceWithAcr, encodeURI(asIri(inputPolicy)) + newIriSuffix);\n getIriAll(inputPolicy, acp.allow).forEach((allowMode) => {\n newPolicy = addIri(newPolicy, acp.allow, allowMode);\n });\n getIriAll(inputPolicy, acp.deny).forEach((denyMode) => {\n newPolicy = addIri(newPolicy, acp.deny, denyMode);\n });\n newAllOfMatchers.forEach((newMatcher) => {\n newPolicy = addIri(newPolicy, acp.allOf, newMatcher);\n });\n newAnyOfMatchers.forEach((newMatcher) => {\n newPolicy = addIri(newPolicy, acp.anyOf, newMatcher);\n });\n /* istanbul ignore next Policies listing noneOf Matchers are left alone (because they do not unambiguously apply to the given actor always), so there will usually not be any noneOf Matchers to copy. */\n newNoneOfMatchers.forEach((newMatcher) => {\n newPolicy = addIri(newPolicy, acp.noneOf, newMatcher);\n });\n return [\n newPolicy,\n newAllOfMatchers.concat(newAnyOfMatchers).concat(newNoneOfMatchers),\n ];\n}\n/** Creates clones of all the Matchers identified by `matcherIris` in `acpData`, excluding the given Actor */\nfunction copyMatchersExcludingActor(matcherIris, resourceWithAcr, acpData, iriSuffix, actorRelationToExclude, actorToExclude) {\n return matcherIris\n .map((matcherIri) => {\n const matcher = acpData.matchers.find((matcher) => asIri(matcher) === matcherIri);\n /* istanbul ignore if: getPoliciesAndMatchers should already have fetched all referenced Matchers, so this should never be true: */\n if (typeof matcher === \"undefined\") {\n return null;\n }\n let newMatcher = createResourceMatcherFor(resourceWithAcr, encodeURI(asIri(matcher)) + iriSuffix);\n let listsOtherActors = false;\n knownActorRelations.forEach((knownActorRelation) => {\n getIriAll(matcher, knownActorRelation).forEach((targetActor) => {\n if (knownActorRelation === actorRelationToExclude &&\n targetActor === actorToExclude) {\n return;\n }\n listsOtherActors = true;\n newMatcher = addIri(newMatcher, knownActorRelation, targetActor);\n });\n });\n return listsOtherActors ? newMatcher : null;\n })\n .filter(isNotNull);\n}\nfunction isNotNull(value) {\n return value !== null;\n}\nasync function internal_getPoliciesAndMatchers(resource, options = internal_defaultFetchOptions) {\n const acrPolicyUrls = getAcrPolicyUrlAll$1(resource);\n const policyUrls = getPolicyUrlAll$1(resource);\n const allPolicyResourceUrls = getResourceUrls(acrPolicyUrls).concat(getResourceUrls(policyUrls));\n const policyResources = await getResources(allPolicyResourceUrls, options);\n const acrPolicies = getThingsFromResources(acrPolicyUrls, policyResources).filter(isNotNull);\n const policies = getThingsFromResources(policyUrls, policyResources).filter(isNotNull);\n const matcherUrlSet = new Set();\n acrPolicies.forEach((acrPolicy) => {\n const referencedMatcherUrls = getReferencedMatcherUrls(acrPolicy);\n referencedMatcherUrls.forEach((matcherUrl) => {\n matcherUrlSet.add(matcherUrl);\n });\n });\n policies.forEach((policy) => {\n const referencedMatcherUrls = getReferencedMatcherUrls(policy);\n referencedMatcherUrls.forEach((matcherUrl) => {\n matcherUrlSet.add(matcherUrl);\n });\n });\n const matcherUrls = Array.from(matcherUrlSet);\n const matcherResourceUrls = matcherUrls.map((matcherUrl) => getResourceUrl(matcherUrl));\n const unfetchedMatcherResourceUrls = matcherResourceUrls.filter((matcherResourceUrl) => !allPolicyResourceUrls.includes(matcherResourceUrl));\n const matcherResources = await getResources(unfetchedMatcherResourceUrls, options);\n const allResources = {\n ...policyResources,\n ...matcherResources,\n };\n const matchers = getThingsFromResources(matcherUrls, allResources).filter(isNotNull);\n const inaccessibleUrls = Object.keys(allResources).filter((resourceUrl) => allResources[resourceUrl] === null);\n return {\n inaccessibleUrls,\n acrPolicies,\n policies,\n matchers,\n };\n}\nfunction getResourceUrl(thingUrl) {\n const thingUrlObject = new URL(thingUrl);\n thingUrlObject.hash = \"\";\n return thingUrlObject.href;\n}\nfunction getResourceUrls(thingUrls) {\n const resourceUrls = [];\n thingUrls.forEach((thingUrl) => {\n const resourceUrl = getResourceUrl(thingUrl);\n if (!resourceUrls.includes(resourceUrl)) {\n resourceUrls.push(resourceUrl);\n }\n });\n return resourceUrls;\n}\nasync function getResources(resourceUrls, options) {\n const uniqueResourceUrls = Array.from(new Set(resourceUrls));\n const resources = {};\n await Promise.all(uniqueResourceUrls.map(async (resourceUrl) => {\n try {\n const resource = await getSolidDataset(resourceUrl, options);\n resources[resourceUrl] = resource;\n }\n catch (e) {\n resources[resourceUrl] = null;\n }\n }));\n return resources;\n}\nfunction getThingsFromResources(thingUrls, resources) {\n return thingUrls.map((thingUrl) => {\n const resourceUrl = getResourceUrl(thingUrl);\n const resource = resources[resourceUrl];\n if (!resource) {\n return null;\n }\n return getThing(resource, thingUrl);\n });\n}\nfunction getReferencedMatcherUrls(policy) {\n return getAllOfMatcherUrlAll(policy)\n .concat(getAnyOfMatcherUrlAll(policy))\n .concat(getNoneOfMatcherUrlAll(policy));\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Get an overview of what access is defined for a given Agent.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access, in which case it will\n * resolve to `null`.\n * - It will only return access specified explicitly for the given Agent. If\n * additional restrictions are set up to apply to the given Agent in a\n * particular situation, those will not be reflected in the return value of\n * this function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @param webId WebID of the Agent you want to get the access for.\n * @since 1.5.0\n * @hidden\n * @deprecated Please import from the \"universal\" modules.\n */\nasync function getAgentAccess$2(resourceUrl, webId, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndMatchers(resourceInfo, options);\n return internal_getAgentAccess(acpData, webId);\n }\n if (hasAccessibleAcl(resourceInfo)) {\n return getAgentAccess$4(resourceInfo, webId, options);\n }\n return null;\n}\n/**\n * Set access to a Resource for a specific Agent.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably setting access, in which case it will\n * resolve to `null`.\n * - It will only set access explicitly for the given Agent. In other words,\n * additional restrictions could be present that further restrict or loosen\n * what access the given Agent has in particular circumstances.\n * - The provided access will only apply to the given Resource. In other words,\n * if the Resource is a Container, the configured Access may not apply to\n * contained Resources.\n * - If the current user does not have permission to view or change access for\n * the given Resource, this function will resolve to `null`.\n *\n * Additionally, two caveats apply to users with a Pod server that uses WAC:\n * - If the Resource did not have an ACL yet, a new one will be initialised.\n * This means that changes to the ACL of a parent Container can no longer\n * affect access people have to this Resource, although existing access will\n * be preserved.\n * - Setting different values for `controlRead` and `controlWrite` is not\n * supported, and **will throw an error**. If you expect (some of) your users\n * to have Pods implementing WAC, be sure to pass the same value for both.\n *\n * @param resourceUrl URL of the Resource you want to change the Agent's access to.\n * @param webId WebID of the Agent you want to set access for.\n * @param access What access permissions you want to set for the given Agent to the given Resource. Possible properties are `read`, `append`, `write`, `controlRead` and `controlWrite`: set to `true` to allow, to `false` to stop allowing, or `undefined` to leave unchanged. Take note that `controlRead` and `controlWrite` can not have distinct values for a Pod server implementing Web Access Control; trying this will throw an error.\n * @returns What access has been set for the given Agent explicitly.\n * @since 1.5.0\n * @hidden\n * @deprecated Please import from the \"universal\" modules.\n */\nasync function setAgentAccess$2(resourceUrl, webId, access, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndMatchers(resourceInfo, options);\n const updatedResource = internal_setAgentAccess(resourceInfo, acpData, webId, access);\n if (updatedResource) {\n try {\n await saveAcrFor(updatedResource, options);\n return await getAgentAccess$2(resourceUrl, webId, options);\n }\n catch (e) {\n return null;\n }\n }\n return null;\n }\n if (hasAccessibleAcl(resourceInfo)) {\n if (access.controlRead !== access.controlWrite) {\n throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${getSourceIri(resourceInfo)}]), \\`controlRead\\` and \\`controlWrite\\` should have the same value.`);\n }\n const wacAccess = access;\n await setAgentResourceAccess(resourceInfo, webId, wacAccess, options);\n return getAgentAccess$4(resourceInfo, webId, options);\n }\n return null;\n}\n/**\n * Get an overview of what access is defined for all Agents with respect to a given\n * Resource.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access, in which case it will\n * resolve to `null`.\n * - It will only return access specified explicitly for the returned Agents. If\n * additional restrictions are set up to apply to the listed Agents in a\n * particular situation, those will not be reflected in the return value of\n * this function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @returns The access information to the Resource, grouped by Agent.\n * @since 1.5.0\n * @hidden\n * @deprecated Please import from the \"universal\" modules.\n */\nasync function getAgentAccessAll$2(resourceUrl, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndMatchers(resourceInfo, options);\n return internal_getAgentAccessAll(acpData);\n }\n if (hasAccessibleAcl(resourceInfo)) {\n return getAgentAccessAll$4(resourceInfo, options);\n }\n return null;\n}\n/**\n * Get an overview of what access is defined for everyone.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access, in which case it will\n * resolve to `null`.\n * - It will only return access specified explicitly for everyone. If\n * additional restrictions are set up to apply to users in a particular\n * situation, those will not be reflected in the return value of this\n * function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @since 1.5.0\n * @hidden\n * @deprecated Please import from the \"universal\" modules.\n */\nasync function getPublicAccess$2(resourceUrl, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndMatchers(resourceInfo, options);\n return internal_getPublicAccess(acpData);\n }\n if (hasAccessibleAcl(resourceInfo)) {\n return getPublicAccess$4(resourceInfo, options);\n }\n return null;\n}\n/**\n * Set access to a Resource for everybody.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably setting access, in which case it will\n * resolve to `null`.\n * - It will only set access explicitly for everybody. In other words,\n * additional restrictions could be present that further restrict or loosen\n * what access a user has in particular circumstances.\n * - The provided access will only apply to the given Resource. In other words,\n * if the Resource is a Container, the configured Access may not apply to\n * contained Resources.\n * - If the current user does not have permission to view or change access for\n * the given Resource, this function will resolve to `null`.\n *\n * Additionally, two caveats apply to users with a Pod server that uses WAC:\n * - If the Resource did not have an ACL yet, a new one will be initialised.\n * This means that changes to the ACL of a parent Container can no longer\n * affect access people have to this Resource, although existing access will\n * be preserved.\n * - Setting different values for `controlRead` and `controlWrite` is not\n * supported, and **will throw an error**. If you expect (some of) your users\n * to have Pods implementing WAC, be sure to pass the same value for both.\n *\n * @param resourceUrl URL of the Resource you want to change public access to.\n * @param access What access permissions you want to set for everybody to the given Resource. Possible properties are `read`, `append`, `write`, `controlRead` and `controlWrite`: set to `true` to allow, to `false` to stop allowing, or `undefined` to leave unchanged. Take note that `controlRead` and `controlWrite` can not have distinct values for a Pod server implementing Web Access Control; trying this will throw an error.\n * @returns What access has been set for everybody explicitly.\n * @since 1.5.0\n * @hidden\n * @deprecated Please import from the \"universal\" modules.\n */\nasync function setPublicAccess$2(resourceUrl, access, options = internal_defaultFetchOptions) {\n const resourceInfo = await getResourceInfoWithAcr(resourceUrl, options);\n if (hasAccessibleAcr(resourceInfo)) {\n const acpData = await internal_getPoliciesAndMatchers(resourceInfo, options);\n const updatedResource = internal_setPublicAccess(resourceInfo, acpData, access);\n if (updatedResource) {\n try {\n await saveAcrFor(updatedResource, options);\n return await getPublicAccess$2(resourceUrl, options);\n }\n catch (e) {\n return null;\n }\n }\n return null;\n }\n if (hasAccessibleAcl(resourceInfo)) {\n if (access.controlRead !== access.controlWrite) {\n throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${getSourceIri(resourceInfo)}]), \\`controlRead\\` and \\`controlWrite\\` should have the same value.`);\n }\n const wacAccess = access;\n await setPublicResourceAccess(resourceInfo, wacAccess, options);\n return getPublicAccess$4(resourceInfo, options);\n }\n return null;\n}\n\nvar universal_v2 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n getAccessFor: getAccessFor,\n getAccessForAll: getAccessForAll,\n getAgentAccess: getAgentAccess$2,\n getAgentAccessAll: getAgentAccessAll$2,\n getPublicAccess: getPublicAccess$2,\n setAccessFor: setAccessFor,\n setAgentAccess: setAgentAccess$2,\n setPublicAccess: setPublicAccess$2\n});\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Retrieve the Server Resource Info of Resource expressing access control over\n * another resource it is linked to. It applies in both ACP and WAC contexts:\n * the Access Control Resource is discovered consistently using a Link header\n * with `rel=acl`.\n *\n * @param {WithServerResourceInfo} resource The Resource for which ACL we want\n * to retrieve the Server Resource Info.\n * @param {DefaultOptions} options\n * @returns The Server Resource Info if available, null otherwise.\n * @since 1.19.0\n */\nasync function getAclServerResourceInfo(resource, options) {\n if (typeof resource.internal_resourceInfo.aclUrl !== \"string\") {\n return null;\n }\n try {\n return await getResourceInfo(resource.internal_resourceInfo.aclUrl, options);\n }\n catch (_a) {\n // A WAC-governed resource may have a link to a non-existant ACL (by design).\n // The absence of an ACL at the target URL is a useful information that is\n // used by the universal API to pick between ACR and WAC.\n return null;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Policies allow or deny access modes over resources and their associated\n * access control resource.\n *\n * @param policy The Policy Thing which allows retrieved access modes.\n * @returns Policy URL array.\n * @since 1.16.1\n */\nfunction getAllowModes(policy) {\n return getModes(policy, ACP.allow);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * ```{note}\n * The ACP specification is a draft. As such, this function is experimental and\n * subject to change, even in a non-major release.\n * See also: https://solid.github.io/authorization-panel/acp-specification/\n * ```\n *\n * Policies allow or deny access modes over resources and their associated\n * access control resource.\n *\n * @param policy The Policy Thing which denies retrieved access modes.\n * @returns Policy URL array.\n * @since 1.16.1\n */\nfunction getDenyModes(policy) {\n return getModes(policy, ACP.deny);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction isAgentMatched(acr, policy, webId) {\n // TODO: Proper solution\n // Finalise, release and use the TypeScript ACP Solid library\n // internal_getActorAccess in acp_v2:96 doesn't reduce the policies properly\n // policyAppliesTo in acp_v2:256 assumes that every matcher is an agent matcher\n //\n // TODO: Stopgap solution\n // Implement a simplistic reduce function that\n // matches policies where the agent is present in the matchers\n const allOfMatchers = getUrlAll(policy, ACP.allOf)\n .map((url) => getThing(internal_getAcr(acr), url))\n .filter((thing) => thing !== null);\n const allOfMatched = allOfMatchers.every((thing) => {\n return getUrlAll(thing, ACP.agent).includes(webId);\n });\n const anyOfMatchers = getUrlAll(policy, ACP.anyOf)\n .map((url) => getThing(internal_getAcr(acr), url))\n .filter((thing) => thing !== null);\n const anyOfMatched = anyOfMatchers.some((thing) => {\n return getUrlAll(thing, ACP.agent).includes(webId);\n });\n const noneOfMatchers = getUrlAll(policy, ACP.noneOf)\n .map((url) => getThing(internal_getAcr(acr), url))\n .filter((thing) => thing !== null);\n const noneOfMatched = noneOfMatchers.some((thing) => {\n return getUrlAll(thing, ACP.agent).includes(webId);\n });\n return (allOfMatchers.length + anyOfMatchers.length > 0 &&\n (allOfMatchers.length === 0 || allOfMatched) &&\n (anyOfMatchers.length === 0 || anyOfMatched) &&\n (noneOfMatchers.length === 0 || !noneOfMatched));\n}\n/** @hidden */\nfunction reduceModes(policy, modes, type) {\n const allowed = getAllowModes(policy);\n const denied = getDenyModes(policy);\n if (type === \"control\") {\n return {\n read: modes.read,\n append: modes.append,\n write: modes.write,\n controlRead: (modes.controlRead || allowed.read) && !denied.read,\n controlWrite: (modes.controlWrite || allowed.write) && !denied.write,\n };\n }\n return {\n read: (modes.read || allowed.read) && !denied.read,\n append: (modes.append || allowed.append) && !denied.append,\n write: (modes.write || allowed.write) && !denied.write,\n controlRead: modes.controlRead,\n controlWrite: modes.controlWrite,\n };\n}\n/**\n * Get an overview of what access is defined for a given Agent.\n *\n * @param resourceWithAcr URL of the Resource you want to read the access for.\n * @param webId WebID of the Agent you want to get the access for.\n * @since 1.16.0\n */\nasync function getAgentAccess$1(resourceWithAcr, webId) {\n // TODO: add support for external resources\n let resourceAccess = {\n read: false,\n append: false,\n write: false,\n controlRead: false,\n controlWrite: false,\n };\n const policyAll = getPolicyUrlAll(resourceWithAcr)\n .map((url) => getThing(internal_getAcr(resourceWithAcr), url))\n .filter((policy) => policy !== null);\n policyAll.forEach((policy) => {\n if (isAgentMatched(resourceWithAcr, policy, webId)) {\n resourceAccess = reduceModes(policy, resourceAccess, \"resource\");\n }\n });\n const acrPolicyAll = getAcrPolicyUrlAll(resourceWithAcr)\n .map((url) => getThing(internal_getAcr(resourceWithAcr), url))\n .filter((policy) => policy !== null);\n acrPolicyAll.forEach((policy) => {\n if (isAgentMatched(resourceWithAcr, policy, webId)) {\n resourceAccess = reduceModes(policy, resourceAccess, \"control\");\n }\n });\n return resourceAccess;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Retrieve the URL of an Access Control Resource as per pre-draft versions of\n * the ACP specification.\n *\n * @param resource The Resource for which to retrieve the URL of the Access\n * Control Resource if it is accessible.\n * @returns The URL of the ACR or null.\n * @deprecated\n */\nfunction getAcrUrl$1(resource) {\n const linkedAccessControlResource = resource.internal_resourceInfo.linkedResources[ACP.accessControl];\n if (Array.isArray(linkedAccessControlResource) &&\n linkedAccessControlResource.length === 1) {\n return linkedAccessControlResource[0];\n }\n return null;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Retrieve the URL of an Access Control Resource as per the ACP Draft\n * specification.\n *\n * @param resource The Resource for which to retrieve the URL of the Access\n * Control Resource if it is accessible.\n * @returns The URL of the ACR or null.\n */\nasync function getAcrUrl(resource, options) {\n // TODO: Remove as soon as ESS 1.1 is phased out\n const legacyAcrUrl = getAcrUrl$1(resource);\n if (legacyAcrUrl !== null) {\n return legacyAcrUrl;\n }\n // The ACP Draft mandates a link rel=\"type\" header identifies Access Control Resources\n const aclServerResourceInfo = await getAclServerResourceInfo(resource, options);\n if (aclServerResourceInfo === null) {\n return null;\n }\n const relTypeLinks = getLinkedResourceUrlAll(aclServerResourceInfo).type;\n if (Array.isArray(relTypeLinks) &&\n relTypeLinks.includes(ACP.AccessControlResource)) {\n return getSourceUrl(aclServerResourceInfo);\n }\n return null;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Retrieve the Access Control Resource of a Resource as per the ACP Draft\n * specification.\n *\n * @param resource The Resource for which to retrieve the URL of the Access\n * Control Resource if it is accessible.\n * @param options Default Options such as a fetch function.\n * @returns The URL of the ACR or null.\n */\nasync function getResourceAcr(resource, options) {\n const acrUrl = await getAcrUrl(resource, options);\n if (acrUrl === null) {\n return null;\n }\n let acr;\n try {\n acr = await getSolidDataset(acrUrl, options);\n }\n catch (e) {\n return null;\n }\n return {\n ...resource,\n internal_acp: {\n acr: {\n ...acr,\n accessTo: getSourceUrl(resource),\n },\n },\n };\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Get an overview of what access is defined for a given Agent.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access.\n * - It will only return access specified explicitly for the given Agent within\n * the ACL linked to the resource. If additional restrictions or external\n * resources are used, those will not be reflected in the return value of this\n * function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @param webId WebID of the Agent you want to get the access for.\n * @param options Default Options such as a fetch function.\n * @since 1.19.0\n */\nasync function getAgentAccess(resourceUrl, webId, options) {\n const resourceInfo = await getResourceInfo(resourceUrl, options);\n const acr = await getResourceAcr(resourceInfo, options);\n if (acr === null) {\n return getAgentAccess$4(resourceInfo, webId, options);\n }\n return getAgentAccess$1(acr, webId);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction getAgentUrlAll(acr) {\n return Array.from(new Set(getThingAll(internal_getAcr(acr))\n .map((thing) => {\n return getUrlAll(thing, ACP.agent);\n })\n .reduce((flatArray, agentArray) => {\n return flatArray.concat(agentArray);\n }, [])));\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Get an overview of what access is defined for agents.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access.\n * - It will only return access specified explicitly for the given Agent within\n * the ACL linked to the resource. If additional restrictions or external\n * resources are used, those will not be reflected in the return value of this\n * function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @param options Default Options such as a fetch function.\n * @since 1.21.0\n */\nasync function getAgentAccessAll$1(resourceWithAcr) {\n return (await Promise.all(getAgentUrlAll(resourceWithAcr).map(async (agent) => ({\n [agent]: await getAgentAccess$1(resourceWithAcr, agent),\n })))).reduce((agentAccessAll, currentAgentAccess) => ({\n ...agentAccessAll,\n ...currentAgentAccess,\n }), {});\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Get an overview of what access is defined for agents.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access.\n * - It will only return access specified explicitly for the given Agent within\n * the ACL linked to the resource. If additional restrictions or external\n * resources are used, those will not be reflected in the return value of this\n * function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @param options Default Options such as a fetch function.\n * @since 1.21.0\n */\nasync function getAgentAccessAll(resourceUrl, options) {\n const resourceInfo = await getResourceInfo(resourceUrl, options);\n const acr = await getResourceAcr(resourceInfo, options);\n if (acr === null) {\n return getAgentAccessAll$4(resourceInfo, options);\n }\n return getAgentAccessAll$1(acr);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Get an overview of what access is given to the public.\n *\n * @param resourceWithAcr URL of the Resource you want to read the access for.\n * @since 1.16.0\n */\nasync function getPublicAccess$1(resourceWithAcr) {\n return getAgentAccess$1(resourceWithAcr, ACP.PublicAgent);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Get an overview of what access is defined for the Public.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably reading access.\n * - It will only return access specified explicitly for the given Agent within\n * the ACL linked to the resource. If additional restrictions or external\n * resources are used, those will not be reflected in the return value of this\n * function.\n * - It will only return access specified explicitly for the given Resource.\n * In other words, if the Resource is a Container, the returned Access may not\n * apply to contained Resources.\n * - If the current user does not have permission to view access for the given\n * Resource, this function will resolve to `null`.\n *\n * @param resourceUrl URL of the Resource you want to read the access for.\n * @param options Default Options such as a fetch function.\n * @since 1.19.0\n */\nasync function getPublicAccess(resourceUrl, options) {\n const resourceInfo = await getResourceInfo(resourceUrl, options);\n const acr = await getResourceAcr(resourceInfo, options);\n if (acr === null) {\n return getPublicAccess$4(resourceInfo, options);\n }\n return getPublicAccess$1(acr);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction getDefaultAgentMatcherPolicyUrl(resource, name, mode) {\n return getDefaultAccessControlUrl(resource, name)\n .concat(\"AgentMatcher\")\n .concat(mode.charAt(0).toUpperCase() + mode.slice(1))\n .concat(\"Policy\");\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction setDefaultAgentMatcherPolicyThingIfNotExist(resource, name, mode) {\n const policyUrl = getDefaultAgentMatcherPolicyUrl(resource, name, mode);\n // TODO: Re-enable when we support setting agent access on member resources\n // if (policyUrl.includes(\"Member\") && policyUrl.includes(\"Acr\")) {\n // return addMemberAcrPolicyUrl(resource, policyUrl);\n // }\n // if (policyUrl.includes(\"Member\")) {\n // return addMemberPolicyUrl(resource, policyUrl);\n // }\n if (policyUrl.includes(\"Acr\")) {\n return addAcrPolicyUrl(resource, policyUrl);\n }\n return addPolicyUrl(resource, policyUrl);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction getDefaultAgentMatcherPolicyMatcherUrl(resource, name, mode) {\n return getDefaultAgentMatcherPolicyUrl(resource, name, mode).concat(\"Matcher\");\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nconst DEFAULT_POLICY_MATCHER_PREDICATE = ACP.anyOf;\n/**\n * This functions scaffolds the default elements required for giving access to\n * an agent:\n * 1. If the Access Control Resource is empty, create the AccessControlResource\n * element;\n * 2. If the current default Access Control doesn't exist (the one applying to\n * one of: the Resource, the ACR, the Member Resources or the ACR of members)\n * create it;\n * 3. If the default Policy for allowing the Access Modes for the current\n * default Access Control doesn't exist, create it;\n * 4. If the default \"anyOf\" Agent Matcher for the current Policy creates it;\n * 5. Returns an ACR with a Matcher ready to add to.\n * @hidden\n * */\nfunction setDefaultAgentMatcherPolicyMatcherThingIfNotExist(resource, name, mode) {\n const policyUrl = getDefaultAgentMatcherPolicyUrl(resource, name, mode);\n const matcherUrl = getDefaultAgentMatcherPolicyMatcherUrl(resource, name, mode);\n let defaultAgentMatcherPolicyThing = getThing(internal_getAcr(resource), policyUrl);\n if (!defaultAgentMatcherPolicyThing) {\n resource = setDefaultAgentMatcherPolicyThingIfNotExist(resource, name, mode);\n defaultAgentMatcherPolicyThing = createThing({ url: policyUrl });\n defaultAgentMatcherPolicyThing = setModes(defaultAgentMatcherPolicyThing, { [mode]: true }, ACP.allow);\n }\n // Get the Default Access Control Agent Matcher Policy Matcher Thing or create it and return\n const agentMatcherPolicyUrlAll = getIriAll(defaultAgentMatcherPolicyThing, DEFAULT_POLICY_MATCHER_PREDICATE);\n if (!agentMatcherPolicyUrlAll.includes(matcherUrl)) {\n defaultAgentMatcherPolicyThing = buildThing(defaultAgentMatcherPolicyThing)\n .addUrl(DEFAULT_POLICY_MATCHER_PREDICATE, matcherUrl)\n .build();\n return setAccessControlResourceThing(resource, defaultAgentMatcherPolicyThing);\n }\n return resource;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/** @hidden */\nfunction setAgentAccessMode(resourceWithAcr, webId, name, mode, operation) {\n var _a;\n const matcherUrl = getDefaultAgentMatcherPolicyMatcherUrl(resourceWithAcr, name, mode);\n // Set default Matcher if not exists\n const resourceWithDefaultAgentMatcher = setDefaultAgentMatcherPolicyMatcherThingIfNotExist(resourceWithAcr, name, mode);\n const defaultAgentMatcherThing = (_a = getThing(internal_getAcr(resourceWithDefaultAgentMatcher), matcherUrl)) !== null && _a !== void 0 ? _a : createThing({ url: matcherUrl });\n return setAccessControlResourceThing(resourceWithDefaultAgentMatcher, operation === \"add\"\n ? addAgent(defaultAgentMatcherThing, webId)\n : removeAgent(defaultAgentMatcherThing, webId));\n}\n/**\n * Set access for a given Agent.\n *\n * @param resourceWithAcr URL of the Resource you want to set the access for.\n * @param webId WebID of the Agent you want to set the access for.\n * @param access Access Modes you want to set for the agent.\n * @since 1.16.0\n */\nasync function setAgentAccess$1(resourceWithAcr, webId, access) {\n const agentAccessModes = await getAgentAccess$1(resourceWithAcr, webId);\n // Add Agent to Default Matchers (including member) if access mode is different from what exists\n if (typeof access.read === \"boolean\" &&\n agentAccessModes.read !== access.read) {\n resourceWithAcr = setAgentAccessMode(resourceWithAcr, webId, DEFAULT_ACCESS_CONTROL, \"read\", access.read ? \"add\" : \"remove\");\n }\n if (typeof access.append === \"boolean\" &&\n agentAccessModes.append !== access.append) {\n resourceWithAcr = setAgentAccessMode(resourceWithAcr, webId, DEFAULT_ACCESS_CONTROL, \"append\", access.append ? \"add\" : \"remove\");\n }\n if (typeof access.write === \"boolean\" &&\n agentAccessModes.write !== access.write) {\n resourceWithAcr = setAgentAccessMode(resourceWithAcr, webId, DEFAULT_ACCESS_CONTROL, \"write\", access.write ? \"add\" : \"remove\");\n }\n if (typeof access.controlRead === \"boolean\" &&\n agentAccessModes.controlRead !== access.controlRead) {\n resourceWithAcr = setAgentAccessMode(resourceWithAcr, webId, DEFAULT_ACR_ACCESS_CONTROL, \"controlRead\", access.controlRead ? \"add\" : \"remove\");\n }\n if (typeof access.controlWrite === \"boolean\" &&\n agentAccessModes.controlWrite !== access.controlWrite) {\n resourceWithAcr = setAgentAccessMode(resourceWithAcr, webId, DEFAULT_ACR_ACCESS_CONTROL, \"controlWrite\", access.controlWrite ? \"add\" : \"remove\");\n }\n return resourceWithAcr;\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Set access to a resource for a given Agent.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably setting access.\n * - It will only set access explicitly for the given Agent. In other words,\n * additional restrictions could be present that further restrict or loosen\n * what access the given Agent has in particular circumstances.\n * - The provided access will only apply to the given Resource. In other words,\n * if the Resource is a Container, the configured Access will not apply to\n * contained Resources.\n * - If the current user does not have permission to view or change access for\n * the given Resource, this function will resolve to `null`.\n *\n * Additionally, two caveats apply to users with a Pod server that uses WAC:\n * - If the Resource did not have an ACL yet, a new one will be initialised.\n * This means that changes to the ACL of a parent Container can no longer\n * affect access people have to this Resource, although existing access will\n * be preserved.\n * - Setting different values for `controlRead` and `controlWrite` is not\n * supported, and **will throw an error**. If you expect (some of) your users\n * to have Pods implementing WAC, be sure to pass the same value for both.\n *\n * @param resourceUrl URL of the Resource you want to set access for.\n * @param webId WebID of the Agent you want to set access for.\n * @param access The Access Modes to add (true) or remove (false).\n * @param options Default Options such as a fetch function.\n * @since 1.19.0\n */\nasync function setAgentAccess(resourceUrl, webId, access, options) {\n // TODO: Change the standard getAgentAccess signatures to all take a T extends WithAcl\n const resourceInfo = await getResourceInfo(resourceUrl, options);\n const acr = await getResourceAcr(resourceInfo, options);\n if (acr === null) {\n await setAgentResourceAccess(resourceInfo, webId, access, options);\n return getAgentAccess$4(resourceInfo, webId, options);\n }\n // TODO: Make sure both setAgentAccessWac and setAgentAccessAcp don't save within the function, expose one standard saveAclFor function that is universal.\n try {\n await saveAcrFor(await setAgentAccess$1(acr, webId, access), options);\n return await getAgentAccess(resourceUrl, webId, options);\n }\n catch (e) {\n return null;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Set access for the public.\n *\n * @param resourceWithAcr URL of the Resource you want to read the access for.\n * @param access Access Modes you want to set for the agent.\n * @since 1.16.0\n */\nasync function setPublicAccess$1(resourceWithAcr, access) {\n return setAgentAccess$1(resourceWithAcr, ACP.PublicAgent, access);\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * Set access to a resource for the public.\n *\n * This function works with Solid Pods that implement either the Web Access\n * Control spec or the Access Control Policies proposal, with some caveats:\n *\n * - If access to the given Resource has been set using anything other than the\n * functions in this module, it is possible that it has been set in a way that\n * prevents this function from reliably setting access.\n * - It will only set access explicitly for the given Agent. In other words,\n * additional restrictions could be present that further restrict or loosen\n * what access the given Agent has in particular circumstances.\n * - The provided access will only apply to the given Resource. In other words,\n * if the Resource is a Container, the configured Access will not apply to\n * contained Resources.\n * - If the current user does not have permission to view or change access for\n * the given Resource, this function will resolve to `null`.\n *\n * Additionally, two caveats apply to users with a Pod server that uses WAC:\n * - If the Resource did not have an ACL yet, a new one will be initialised.\n * This means that changes to the ACL of a parent Container can no longer\n * affect access people have to this Resource, although existing access will\n * be preserved.\n * - Setting different values for `controlRead` and `controlWrite` is not\n * supported, and **will throw an error**. If you expect (some of) your users\n * to have Pods implementing WAC, be sure to pass the same value for both.\n *\n * @param resourceUrl URL of the Resource you want to set access for.\n * @param access The Access Modes to add (true) or remove (false).\n * @param options Default Options such as a fetch function.\n * @since 1.19.0\n */\nasync function setPublicAccess(resourceUrl, access, options) {\n const resourceInfo = await getResourceInfo(resourceUrl, options);\n const acr = await getResourceAcr(resourceInfo, options);\n if (acr === null) {\n await setPublicResourceAccess(resourceInfo, access, options);\n return getPublicAccess$4(resourceInfo, options);\n }\n try {\n await saveAcrFor(await setPublicAccess$1(acr, access), options);\n return await getPublicAccess(resourceUrl, options);\n }\n catch (e) {\n return null;\n }\n}\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * :::{admonition} Experimental API\n * :class: important\n *\n * This API is still experimental, and subject to change. It builds on top of\n * both ACP and WAC, aiming at being adaptable to any Access Control system that\n * may be implemented in Solid. That is why it is purely Resource-centric: the\n * library discovers metadata associated with the Resource itself, and calls the\n * appropriate underlying API to deal with the Access Control in place for the\n * target Resource.\n *\n * As it is still under development, the following export is *only* intended for\n * experimentation by early adopters, and is not recommended for production\n * applications.\n *\n * For more information see: [Tutorial: Managing\n * Access](https://docs.inrupt.com/developer-tools/javascript/client-libraries/tutorial/manage-access/)\n * :::\n *\n * This module can be imported as an object from the main package, which results\n * in tree-shaking not being supported (so all the exported APIs will likely end\n * up in your bundle). This import style is used for environments such as nextjs\n * or create-react-app.\n *\n * ```typescript\n * import { universalAccess } from \"@inrupt/solid-client\";\n * ```\n *\n * Alternatively, if your environment supports [export\n * maps](https://nodejs.org/dist/latest-v16.x/docs/api/packages.html#exports),\n * then you can import directly:\n *\n * ```typescript\n * import * as universalAccess from \"@inrupt/solid-client/universal\";\n * ```\n *\n * If you're using Typescript, and receive errors about type definitions not\n * being found, please see this\n * [documentation](https://www.typescriptlang.org/docs/handbook/esm-node.html)\n *\n * @packageDocumentation\n * @module universalAccess\n */\n\nvar index = /*#__PURE__*/Object.freeze({\n __proto__: null,\n getAclServerResourceInfo: getAclServerResourceInfo,\n getAgentAccess: getAgentAccess,\n getAgentAccessAll: getAgentAccessAll,\n getPublicAccess: getPublicAccess,\n setAgentAccess: setAgentAccess,\n setPublicAccess: setPublicAccess\n});\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * :::{admonition} Experimental API\n * :class: important\n *\n * The Access Control Policies proposal has not yet been reviewed for inclusion in the Solid spec.\n * To enable early experimentation, solid-client exposes a low-level API. However, this API can and\n * will include breaking changes in non-major releases. Additionally, for most applications, a\n * higher-level API that is planned will be more applicable.\n *\n * Thus, the following export is *only* intended for experimentation by early adopters, and is not\n * recommended for production applications. Because of this, all ACP-related API's are exported on a\n * single object, which does not facilitate tree-shaking: if you use one ACP-related API, all of\n * them will be included in your bundle.\n *\n * For more information see: [Tutorial: Managing\n * Access](https://docs.inrupt.com/developer-tools/javascript/client-libraries/tutorial/manage-access/)\n * :::\n *\n * This module supports Inrupt's ESS 1.1 ACP implementation.\n *\n * This module can be imported as an object from the main package, which results\n * in tree-shaking not being supported (so all the exported APIs will likely end\n * up in your bundle). This import style is used for environments such as nextjs\n * or create-react-app.\n *\n * ```typescript\n * import { acp_ess_1 } from \"@inrupt/solid-client\";\n * ```\n *\n * @packageDocumentation\n * @module acp_ess_1\n */\n\nvar ess1 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n acrAsMarkdown: acrAsMarkdown,\n addAcrPolicyUrl: addAcrPolicyUrl$1,\n addAgent: addAgent$1,\n addAllOfRuleUrl: addAllOfRuleUrl,\n addAnyOfRuleUrl: addAnyOfRuleUrl,\n addClient: addClient$1,\n addGroup: addGroup,\n addMemberAcrPolicyUrl: addMemberAcrPolicyUrl$1,\n addMemberPolicyUrl: addMemberPolicyUrl$1,\n addMockAcrTo: addMockAcrTo,\n addNoneOfRuleUrl: addNoneOfRuleUrl,\n addPolicyUrl: addPolicyUrl$1,\n createPolicy: createPolicy,\n createResourcePolicyFor: createResourcePolicyFor,\n createResourceRuleFor: createResourceRuleFor,\n createRule: createRule,\n getAcrPolicyUrlAll: getAcrPolicyUrlAll$1,\n getAgentAll: getAgentAll$1,\n getAllOfRuleUrlAll: getAllOfRuleUrlAll,\n getAllowModes: getAllowModesV1,\n getAnyOfRuleUrlAll: getAnyOfRuleUrlAll,\n getClientAll: getClientAll$1,\n getDenyModes: getDenyModesV1,\n getFileWithAccessDatasets: getFileWithAccessDatasets,\n getFileWithAcr: getFileWithAcr,\n getGroupAll: getGroupAll,\n getLinkedAcrUrl: getLinkedAcrUrl,\n getMemberAcrPolicyUrlAll: getMemberAcrPolicyUrlAll$1,\n getMemberPolicyUrlAll: getMemberPolicyUrlAll$1,\n getNoneOfRuleUrlAll: getNoneOfRuleUrlAll,\n getPolicy: getPolicy,\n getPolicyAll: getPolicyAll,\n getPolicyUrlAll: getPolicyUrlAll$1,\n getReferencedPolicyUrlAll: getReferencedPolicyUrlAll,\n getResourceAcrPolicy: getResourceAcrPolicy,\n getResourceAcrPolicyAll: getResourceAcrPolicyAll,\n getResourceInfoWithAccessDatasets: getResourceInfoWithAccessDatasets,\n getResourceInfoWithAcr: getResourceInfoWithAcr,\n getResourcePolicy: getResourcePolicy,\n getResourcePolicyAll: getResourcePolicyAll,\n getResourceRule: getResourceRule,\n getResourceRuleAll: getResourceRuleAll,\n getRule: getRule,\n getRuleAll: getRuleAll,\n getSolidDatasetWithAccessDatasets: getSolidDatasetWithAccessDatasets,\n getSolidDatasetWithAcr: getSolidDatasetWithAcr,\n hasAccessibleAcr: hasAccessibleAcr,\n hasAnyClient: hasAnyClient$1,\n hasAuthenticated: hasAuthenticated$1,\n hasCreator: hasCreator$1,\n hasLinkedAcr: hasLinkedAcr,\n hasPublic: hasPublic$1,\n isAcpControlled: isAcpControlled,\n mockAcrFor: mockAcrFor,\n policyAsMarkdown: policyAsMarkdown,\n removeAcrPolicyUrl: removeAcrPolicyUrl$1,\n removeAcrPolicyUrlAll: removeAcrPolicyUrlAll,\n removeAgent: removeAgent$1,\n removeAllOfRuleUrl: removeAllOfRuleUrl,\n removeAnyClient: removeAnyClient$1,\n removeAnyOfRuleUrl: removeAnyOfRuleUrl,\n removeAuthenticated: removeAuthenticated$1,\n removeClient: removeClient$1,\n removeCreator: removeCreator$1,\n removeGroup: removeGroup,\n removeMemberAcrPolicyUrl: removeMemberAcrPolicyUrl$1,\n removeMemberAcrPolicyUrlAll: removeMemberAcrPolicyUrlAll,\n removeMemberPolicyUrl: removeMemberPolicyUrl$1,\n removeMemberPolicyUrlAll: removeMemberPolicyUrlAll,\n removeNoneOfRuleUrl: removeNoneOfRuleUrl,\n removePolicy: removePolicy,\n removePolicyUrl: removePolicyUrl$1,\n removePolicyUrlAll: removePolicyUrlAll,\n removePublic: removePublic$1,\n removeResourceAcrPolicy: removeResourceAcrPolicy,\n removeResourcePolicy: removeResourcePolicy,\n removeResourceRule: removeResourceRule,\n removeRule: removeRule,\n ruleAsMarkdown: ruleAsMarkdown,\n saveAcrFor: saveAcrFor,\n setAgent: setAgent$1,\n setAllOfRuleUrl: setAllOfRuleUrl,\n setAllowModes: setAllowModesV1,\n setAnyClient: setAnyClient$1,\n setAnyOfRuleUrl: setAnyOfRuleUrl,\n setAuthenticated: setAuthenticated$1,\n setClient: setClient$1,\n setCreator: setCreator$1,\n setDenyModes: setDenyModesV1,\n setGroup: setGroup,\n setNoneOfRuleUrl: setNoneOfRuleUrl,\n setPolicy: setPolicy,\n setPublic: setPublic$1,\n setResourceAcrPolicy: setResourceAcrPolicy,\n setResourcePolicy: setResourcePolicy$1,\n setResourceRule: setResourceRule,\n setRule: setRule\n});\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n/**\n * :::{admonition} Experimental API\n * :class: important\n *\n * The Access Control Policies proposal has not yet been reviewed for inclusion in the Solid spec.\n * To enable early experimentation, solid-client exposes a low-level API. However, this API can and\n * will include breaking changes in non-major releases. Additionally, for most applications, a\n * higher-level API that is planned will be more applicable.\n *\n * Thus, the following export is *only* intended for experimentation by early adopters, and is not\n * recommended for production applications. Because of this, all ACP-related API's are exported on a\n * single object, which does not facilitate tree-shaking: if you use one ACP-related API, all of\n * them will be included in your bundle.\n *\n * For more information see: [Tutorial: Managing\n * Access](https://docs.inrupt.com/developer-tools/javascript/client-libraries/tutorial/manage-access/)\n * :::\n *\n * This module supports Inrupt's ESS 2.0 ACP implementation.\n *\n * This module can be imported as an object from the main package, which results\n * in tree-shaking not being supported (so all the exported APIs will likely end\n * up in your bundle). This import style is used for environments such as nextjs\n * or create-react-app.\n *\n * ```typescript\n * import { acp_ess_2 } from \"@inrupt/solid-client\";\n * ```\n *\n * @packageDocumentation\n * @module acp_ess_2\n */\n\nvar ess2 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n addAcrPolicyUrl: addAcrPolicyUrl,\n addAgent: addAgent,\n addAllOfMatcherUrl: addAllOfMatcherUrl,\n addAnyOfMatcherUrl: addAnyOfMatcherUrl,\n addClient: addClient,\n addMemberAcrPolicyUrl: addMemberAcrPolicyUrl,\n addMemberPolicyUrl: addMemberPolicyUrl,\n addMockAcrTo: addMockAcrTo,\n addNoneOfMatcherUrl: addNoneOfMatcherUrl,\n addPolicyUrl: addPolicyUrl,\n createMatcher: createMatcher,\n createPolicy: createPolicy,\n createResourceMatcherFor: createResourceMatcherFor,\n createResourcePolicyFor: createResourcePolicyFor,\n getAcrPolicyUrlAll: getAcrPolicyUrlAll,\n getAgentAll: getAgentAll,\n getAllOfMatcherUrlAll: getAllOfMatcherUrlAll,\n getAllowModes: getAllowModesV2,\n getAnyOfMatcherUrlAll: getAnyOfMatcherUrlAll,\n getClientAll: getClientAll,\n getDenyModes: getDenyModesV2,\n getFileWithAccessDatasets: getFileWithAccessDatasets,\n getFileWithAcr: getFileWithAcr,\n getLinkedAcrUrl: getLinkedAcrUrl,\n getMatcher: getMatcher,\n getMatcherAll: getMatcherAll,\n getMemberAcrPolicyUrlAll: getMemberAcrPolicyUrlAll,\n getMemberPolicyUrlAll: getMemberPolicyUrlAll,\n getNoneOfMatcherUrlAll: getNoneOfMatcherUrlAll,\n getPolicy: getPolicy,\n getPolicyAll: getPolicyAll,\n getPolicyUrlAll: getPolicyUrlAll,\n getReferencedPolicyUrlAll: getReferencedPolicyUrlAll,\n getResourceAcrPolicy: getResourceAcrPolicy,\n getResourceAcrPolicyAll: getResourceAcrPolicyAll,\n getResourceInfoWithAccessDatasets: getResourceInfoWithAccessDatasets,\n getResourceInfoWithAcr: getResourceInfoWithAcr,\n getResourceMatcher: getResourceMatcher,\n getResourceMatcherAll: getResourceMatcherAll,\n getResourcePolicy: getResourcePolicy,\n getResourcePolicyAll: getResourcePolicyAll,\n getSolidDatasetWithAccessDatasets: getSolidDatasetWithAccessDatasets,\n getSolidDatasetWithAcr: getSolidDatasetWithAcr,\n getVcAccess: getVcAccess,\n hasAccessibleAcr: hasAccessibleAcr,\n hasAuthenticated: hasAuthenticated,\n hasCreator: hasCreator,\n hasLinkedAcr: hasLinkedAcr,\n hasPublic: hasPublic,\n isAcpControlled: isAcpControlled,\n mockAcrFor: mockAcrFor,\n removeAcrPolicyUrl: removeAcrPolicyUrl,\n removeAcrPolicyUrlAll: removeAcrPolicyUrlAll,\n removeAgent: removeAgent,\n removeAllOfMatcherUrl: removeAllOfMatcherUrl,\n removeAnyOfMatcherUrl: removeAnyOfMatcherUrl,\n removeAuthenticated: removeAuthenticated,\n removeClient: removeClient,\n removeCreator: removeCreator,\n removeMatcher: removeMatcher,\n removeMemberAcrPolicyUrl: removeMemberAcrPolicyUrl,\n removeMemberAcrPolicyUrlAll: removeMemberAcrPolicyUrlAll,\n removeMemberPolicyUrl: removeMemberPolicyUrl,\n removeMemberPolicyUrlAll: removeMemberPolicyUrlAll,\n removeNoneOfMatcherUrl: removeNoneOfMatcherUrl,\n removePolicy: removePolicy,\n removePolicyUrl: removePolicyUrl,\n removePolicyUrlAll: removePolicyUrlAll,\n removePublic: removePublic,\n removeResourceAcrPolicy: removeResourceAcrPolicy,\n removeResourceMatcher: removeResourceMatcher,\n removeResourcePolicy: removeResourcePolicy,\n saveAcrFor: saveAcrFor,\n setAgent: setAgent,\n setAllOfMatcherUrl: setAllOfMatcherUrl,\n setAllowModes: setAllowModesV2,\n setAnyOfMatcherUrl: setAnyOfMatcherUrl,\n setAuthenticated: setAuthenticated,\n setCreator: setCreator,\n setDenyModes: setDenyModesV2,\n setMatcher: setMatcher,\n setNoneOfMatcherUrl: setNoneOfMatcherUrl,\n setPolicy: setPolicy,\n setPublic: setPublic,\n setResourceMatcher: setResourceMatcher,\n setResourcePolicy: setResourcePolicy,\n setVcAccess: setVcAccess\n});\n\n//\n// Copyright Inrupt Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the\n// Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// Export the different formats methods from @inrupt/solid-client import, these\n// are not part of our Public API, but are needed to be exported for usage from\n// our other packages.\n//\n// NOTE: We have to export like this, otherwise rollup does some sort of\n// tree-shaking and breaks the build where `dist/formats/index.mjs` is no longer\n// built, and this causes the `@inrupt/solid-client/formats` subpath export to\n// no longer work.\nconst { getJsonLdParser, getTurtleParser, solidDatasetAsTurtle } = formats;\n\nexports.FetchError = FetchError;\nexports.SolidClientError = SolidClientError;\nexports.ThingExpectedError = ThingExpectedError;\nexports.access = universal;\nexports.access_v1 = universal_v1;\nexports.access_v2 = universal_v2;\nexports.acp_ess_1 = ess1;\nexports.acp_ess_2 = ess2;\nexports.acp_v1 = acp_v1;\nexports.acp_v2 = acp_v2;\nexports.acp_v3 = acp_v3;\nexports.acp_v4 = acp_v4;\nexports.addBoolean = addBoolean;\nexports.addDate = addDate;\nexports.addDatetime = addDatetime;\nexports.addDecimal = addDecimal;\nexports.addInteger = addInteger;\nexports.addIri = addIri;\nexports.addJwkToJwks = addJwkToJwks;\nexports.addLiteral = addLiteral;\nexports.addMockFallbackAclTo = addMockFallbackAclTo;\nexports.addMockResourceAclTo = addMockResourceAclTo;\nexports.addNamedNode = addNamedNode;\nexports.addPublicKeyToProfileJwks = addPublicKeyToProfileJwks;\nexports.addStringEnglish = addStringEnglish;\nexports.addStringNoLocale = addStringNoLocale;\nexports.addStringWithLocale = addStringWithLocale;\nexports.addTerm = addTerm;\nexports.addTime = addTime;\nexports.addUrl = addUrl;\nexports.asIri = asIri;\nexports.asUrl = asUrl;\nexports.buildThing = buildThing;\nexports.changeLogAsMarkdown = changeLogAsMarkdown;\nexports.createAcl = createAcl;\nexports.createAclFromFallbackAcl = createAclFromFallbackAcl;\nexports.createContainerAt = createContainerAt;\nexports.createContainerInContainer = createContainerInContainer;\nexports.createSolidDataset = createSolidDataset;\nexports.createThing = createThing;\nexports.deleteAclFor = deleteAclFor;\nexports.deleteContainer = deleteContainer;\nexports.deleteFile = deleteFile;\nexports.deleteSolidDataset = deleteSolidDataset;\nexports.fromRdfJsDataset = fromRdfJsDataset;\nexports.getAgentAccess = getAgentAccess$5;\nexports.getAgentAccessAll = getAgentAccessAll$5;\nexports.getAgentDefaultAccess = getAgentDefaultAccess;\nexports.getAgentDefaultAccessAll = getAgentDefaultAccessAll;\nexports.getAgentResourceAccess = getAgentResourceAccess;\nexports.getAgentResourceAccessAll = getAgentResourceAccessAll;\nexports.getAltProfileUrlAllFrom = getAltProfileUrlAllFrom;\nexports.getBoolean = getBoolean;\nexports.getBooleanAll = getBooleanAll;\nexports.getContainedResourceUrlAll = getContainedResourceUrlAll;\nexports.getContentType = getContentType$1;\nexports.getDate = getDate;\nexports.getDateAll = getDateAll;\nexports.getDatetime = getDatetime;\nexports.getDatetimeAll = getDatetimeAll;\nexports.getDecimal = getDecimal;\nexports.getDecimalAll = getDecimalAll;\nexports.getEffectiveAccess = getEffectiveAccess;\nexports.getFallbackAcl = getFallbackAcl;\nexports.getFile = getFile;\nexports.getFileWithAcl = getFileWithAcl;\nexports.getGroupAccess = getGroupAccess$2;\nexports.getGroupAccessAll = getGroupAccessAll$2;\nexports.getGroupDefaultAccess = getGroupDefaultAccess;\nexports.getGroupDefaultAccessAll = getGroupDefaultAccessAll;\nexports.getGroupResourceAccess = getGroupResourceAccess;\nexports.getGroupResourceAccessAll = getGroupResourceAccessAll;\nexports.getInteger = getInteger;\nexports.getIntegerAll = getIntegerAll;\nexports.getIri = getIri;\nexports.getIriAll = getIriAll;\nexports.getJsonLdParser = getJsonLdParser;\nexports.getLinkedResourceUrlAll = getLinkedResourceUrlAll;\nexports.getLiteral = getLiteral;\nexports.getLiteralAll = getLiteralAll;\nexports.getNamedNode = getNamedNode;\nexports.getNamedNodeAll = getNamedNodeAll;\nexports.getPodOwner = getPodOwner;\nexports.getPodUrlAll = getPodUrlAll;\nexports.getPodUrlAllFrom = getPodUrlAllFrom;\nexports.getProfileAll = getProfileAll;\nexports.getProfileJwksIri = getProfileJwksIri;\nexports.getPropertyAll = getPropertyAll;\nexports.getPublicAccess = getPublicAccess$5;\nexports.getPublicDefaultAccess = getPublicDefaultAccess;\nexports.getPublicResourceAccess = getPublicResourceAccess;\nexports.getResourceAcl = getResourceAcl;\nexports.getResourceInfo = getResourceInfo;\nexports.getResourceInfoWithAcl = getResourceInfoWithAcl;\nexports.getSolidDataset = getSolidDataset;\nexports.getSolidDatasetWithAcl = getSolidDatasetWithAcl;\nexports.getSourceIri = getSourceIri;\nexports.getSourceUrl = getSourceUrl;\nexports.getStringByLocaleAll = getStringByLocaleAll;\nexports.getStringEnglish = getStringEnglish;\nexports.getStringEnglishAll = getStringEnglishAll;\nexports.getStringNoLocale = getStringNoLocale;\nexports.getStringNoLocaleAll = getStringNoLocaleAll;\nexports.getStringWithLocale = getStringWithLocale;\nexports.getStringWithLocaleAll = getStringWithLocaleAll;\nexports.getTerm = getTerm;\nexports.getTermAll = getTermAll;\nexports.getThing = getThing;\nexports.getThingAll = getThingAll;\nexports.getTime = getTime;\nexports.getTimeAll = getTimeAll;\nexports.getTurtleParser = getTurtleParser;\nexports.getUrl = getUrl;\nexports.getUrlAll = getUrlAll;\nexports.getWebIdDataset = getWebIdDataset;\nexports.getWellKnownSolid = getWellKnownSolid;\nexports.hasAccessibleAcl = hasAccessibleAcl;\nexports.hasAcl = hasAcl;\nexports.hasFallbackAcl = hasFallbackAcl;\nexports.hasResourceAcl = hasResourceAcl;\nexports.hasResourceInfo = hasResourceInfo;\nexports.hasServerResourceInfo = hasServerResourceInfo;\nexports.isContainer = isContainer;\nexports.isPodOwner = isPodOwner;\nexports.isRawData = isRawData;\nexports.isThing = isThing;\nexports.isThingLocal = isThingLocal;\nexports.mockContainerFrom = mockContainerFrom;\nexports.mockFetchError = mockFetchError;\nexports.mockFileFrom = mockFileFrom;\nexports.mockSolidDatasetFrom = mockSolidDatasetFrom;\nexports.mockThingFrom = mockThingFrom;\nexports.overwriteFile = overwriteFile;\nexports.removeAll = removeAll;\nexports.removeBoolean = removeBoolean;\nexports.removeDate = removeDate;\nexports.removeDatetime = removeDatetime;\nexports.removeDecimal = removeDecimal;\nexports.removeInteger = removeInteger;\nexports.removeIri = removeIri;\nexports.removeLiteral = removeLiteral;\nexports.removeNamedNode = removeNamedNode;\nexports.removeStringEnglish = removeStringEnglish;\nexports.removeStringNoLocale = removeStringNoLocale;\nexports.removeStringWithLocale = removeStringWithLocale;\nexports.removeThing = removeThing;\nexports.removeTime = removeTime;\nexports.removeUrl = removeUrl;\nexports.responseToResourceInfo = responseToResourceInfo;\nexports.responseToSolidDataset = responseToSolidDataset;\nexports.saveAclFor = saveAclFor;\nexports.saveFileInContainer = saveFileInContainer;\nexports.saveSolidDatasetAt = saveSolidDatasetAt;\nexports.saveSolidDatasetInContainer = saveSolidDatasetInContainer;\nexports.setAgentDefaultAccess = setAgentDefaultAccess;\nexports.setAgentResourceAccess = setAgentResourceAccess$1;\nexports.setBoolean = setBoolean;\nexports.setDate = setDate;\nexports.setDatetime = setDatetime;\nexports.setDecimal = setDecimal;\nexports.setGroupDefaultAccess = setGroupDefaultAccess;\nexports.setGroupResourceAccess = setGroupResourceAccess$1;\nexports.setInteger = setInteger;\nexports.setIri = setIri;\nexports.setLiteral = setLiteral;\nexports.setNamedNode = setNamedNode;\nexports.setProfileJwks = setProfileJwks;\nexports.setPublicDefaultAccess = setPublicDefaultAccess;\nexports.setPublicResourceAccess = setPublicResourceAccess$1;\nexports.setStringNoLocale = setStringNoLocale;\nexports.setStringWithLocale = setStringWithLocale;\nexports.setTerm = setTerm;\nexports.setThing = setThing;\nexports.setTime = setTime;\nexports.setUrl = setUrl;\nexports.solidDatasetAsMarkdown = solidDatasetAsMarkdown;\nexports.solidDatasetAsTurtle = solidDatasetAsTurtle;\nexports.thingAsMarkdown = thingAsMarkdown;\nexports.toRdfJsDataset = toRdfJsDataset;\nexports.universalAccess = index;\nexports.validateContainedResourceAll = validateContainedResourceAll;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar indexBrowser = globalThis.fetch;\nconst { fetch, Response, Request, Headers } = globalThis;\n\nexports.Headers = Headers;\nexports.Request = Request;\nexports.Response = Response;\nexports.default = indexBrowser;\nexports.fetch = fetch;\n","const DataFactory = require('./lib/DataFactory.js')\n\nmodule.exports = DataFactory\n","class BlankNode {\n constructor (id) {\n this.value = id || ('b' + (++BlankNode.nextId))\n }\n\n equals (other) {\n return !!other && other.termType === this.termType && other.value === this.value\n }\n}\n\nBlankNode.prototype.termType = 'BlankNode'\n\nBlankNode.nextId = 0\n\nmodule.exports = BlankNode\n","const BlankNode = require('./BlankNode.js')\nconst DefaultGraph = require('./DefaultGraph.js')\nconst fromTermRaw = require('./fromTerm.js')\nconst Literal = require('./Literal.js')\nconst NamedNode = require('./NamedNode.js')\nconst Quad = require('./Quad.js')\nconst Variable = require('./Variable.js')\n\nfunction namedNode (value) {\n return new NamedNode(value)\n}\n\nfunction blankNode (value) {\n return new BlankNode(value)\n}\n\nfunction literal (value, languageOrDatatype) {\n if (typeof languageOrDatatype === 'string') {\n if (languageOrDatatype.indexOf(':') === -1) {\n return new Literal(value, languageOrDatatype)\n }\n\n return new Literal(value, null, DataFactory.namedNode(languageOrDatatype))\n }\n\n return new Literal(value, null, languageOrDatatype)\n}\n\nfunction variable (value) {\n return new Variable(value)\n}\n\nfunction defaultGraph () {\n return DataFactory.defaultGraphInstance\n}\n\nfunction triple (subject, predicate, object) {\n return DataFactory.quad(subject, predicate, object)\n}\n\nfunction quad (subject, predicate, object, graph) {\n return new Quad(subject, predicate, object, graph || DataFactory.defaultGraphInstance)\n}\n\nfunction fromTerm (original) {\n return fromTermRaw.call(DataFactory, original)\n}\n\nfunction fromQuad (original) {\n return fromTermRaw.call(DataFactory, original)\n}\n\nconst DataFactory = {\n namedNode,\n blankNode,\n literal,\n variable,\n defaultGraph,\n triple,\n quad,\n fromTerm,\n fromQuad,\n defaultGraphInstance: new DefaultGraph()\n}\n\nmodule.exports = DataFactory\n","class DefaultGraph {\n equals (other) {\n return !!other && other.termType === this.termType\n }\n}\n\nDefaultGraph.prototype.termType = 'DefaultGraph'\nDefaultGraph.prototype.value = ''\n\nmodule.exports = DefaultGraph\n","const NamedNode = require('./NamedNode.js')\n\nclass Literal {\n constructor (value, language, datatype) {\n this.value = value\n this.datatype = Literal.stringDatatype\n this.language = ''\n\n if (language) {\n this.language = language\n this.datatype = Literal.langStringDatatype\n } else if (datatype) {\n this.datatype = datatype\n }\n }\n\n equals (other) {\n return !!other && other.termType === this.termType && other.value === this.value &&\n other.language === this.language && other.datatype.equals(this.datatype)\n }\n}\n\nLiteral.prototype.termType = 'Literal'\n\nLiteral.langStringDatatype = new NamedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#langString')\nLiteral.stringDatatype = new NamedNode('http://www.w3.org/2001/XMLSchema#string')\n\nmodule.exports = Literal\n","class NamedNode {\n constructor (iri) {\n this.value = iri\n }\n\n equals (other) {\n return !!other && other.termType === this.termType && other.value === this.value\n }\n}\n\nNamedNode.prototype.termType = 'NamedNode'\n\nmodule.exports = NamedNode\n","const DefaultGraph = require('./DefaultGraph.js')\n\nclass Quad {\n constructor (subject, predicate, object, graph) {\n this.subject = subject\n this.predicate = predicate\n this.object = object\n\n if (graph) {\n this.graph = graph\n } else {\n this.graph = new DefaultGraph()\n }\n }\n\n equals (other) {\n // `|| !other.termType` is for backwards-compatibility with old factories without RDF* support.\n return !!other && (other.termType === 'Quad' || !other.termType) &&\n other.subject.equals(this.subject) && other.predicate.equals(this.predicate) &&\n other.object.equals(this.object) && other.graph.equals(this.graph)\n }\n}\n\nQuad.prototype.termType = 'Quad'\nQuad.prototype.value = ''\n\nmodule.exports = Quad\n","class Variable {\n constructor (name) {\n this.value = name\n }\n\n equals (other) {\n return !!other && other.termType === this.termType && other.value === this.value\n }\n}\n\nVariable.prototype.termType = 'Variable'\n\nmodule.exports = Variable\n","function fromTerm (original) {\n if (!original) {\n return null\n }\n\n if (original.termType === 'BlankNode') {\n return this.blankNode(original.value)\n }\n\n if (original.termType === 'DefaultGraph') {\n return this.defaultGraph()\n }\n\n if (original.termType === 'Literal') {\n return this.literal(original.value, original.language || this.namedNode(original.datatype.value))\n }\n\n if (original.termType === 'NamedNode') {\n return this.namedNode(original.value)\n }\n\n if (original.termType === 'Quad') {\n const subject = this.fromTerm(original.subject)\n const predicate = this.fromTerm(original.predicate)\n const object = this.fromTerm(original.object)\n const graph = this.fromTerm(original.graph)\n\n return this.quad(subject, predicate, object, graph)\n }\n\n if (original.termType === 'Variable') {\n return this.variable(original.value)\n }\n\n throw new Error(`unknown termType ${original.termType}`)\n}\n\nmodule.exports = fromTerm\n","function isString (s) {\n return typeof s === 'string' || s instanceof String\n}\n\nconst xsdString = 'http://www.w3.org/2001/XMLSchema#string'\n\nfunction termToId (term) {\n if (typeof term === 'string') {\n return term\n }\n\n if (!term) {\n return ''\n }\n\n if (typeof term.id !== 'undefined' && term.termType !== 'Quad') {\n return term.id\n }\n\n let subject, predicate, object, graph\n\n // Term instantiated with another library\n switch (term.termType) {\n case 'NamedNode':\n return term.value\n\n case 'BlankNode':\n return `_:${term.value}`\n\n case 'Variable':\n return `?${term.value}`\n\n case 'DefaultGraph':\n return ''\n\n case 'Literal':\n if (term.language) {\n return `\"${term.value}\"@${term.language}`\n }\n\n return `\"${term.value}\"${term.datatype && term.datatype.value !== xsdString ? `^^${term.datatype.value}` : ''}`\n\n case 'Quad':\n // To identify RDF* quad components, we escape quotes by doubling them.\n // This avoids the overhead of backslash parsing of Turtle-like syntaxes.\n subject = escapeQuotes(termToId(term.subject))\n predicate = escapeQuotes(termToId(term.predicate))\n object = escapeQuotes(termToId(term.object))\n graph = term.graph.termType === 'DefaultGraph' ? '' : ` ${termToId(term.graph)}`\n\n return `<<${subject} ${predicate} ${object}${graph}>>`\n\n default:\n throw new Error(`Unexpected termType: ${term.termType}`)\n }\n}\n\nconst escapedLiteral = /^\"(.*\".*)(?=\"[^\"]*$)/\n\nfunction escapeQuotes (id) {\n return id.replace(escapedLiteral, (_, quoted) => `\"${quoted.replace(/\"/g, '\"\"')}`)\n}\n\nclass DatasetCore {\n constructor (quads) {\n // The number of quads is initially zero\n this._size = 0\n // `_graphs` contains subject, predicate, and object indexes per graph\n this._graphs = Object.create(null)\n // `_ids` maps entities such as `http://xmlns.com/foaf/0.1/name` to numbers,\n // saving memory by using only numbers as keys in `_graphs`\n this._id = 0\n this._ids = Object.create(null)\n this._ids['><'] = 0 // dummy entry, so the first actual key is non-zero\n this._entities = Object.create(null) // inverse of `_ids`\n\n this._quads = new Map()\n\n // Add quads if passed\n if (quads) {\n for (const quad of quads) {\n this.add(quad)\n }\n }\n }\n\n get size () {\n // Return the quad count if if was cached\n let size = this._size\n\n if (size !== null) {\n return size\n }\n\n // Calculate the number of quads by counting to the deepest level\n size = 0\n const graphs = this._graphs\n let subjects, subject\n\n for (const graphKey in graphs) {\n for (const subjectKey in (subjects = graphs[graphKey].subjects)) {\n for (const predicateKey in (subject = subjects[subjectKey])) {\n size += Object.keys(subject[predicateKey]).length\n }\n }\n }\n\n this._size = size\n\n return this._size\n }\n\n add (quad) {\n // Convert terms to internal string representation\n let subject = termToId(quad.subject)\n let predicate = termToId(quad.predicate)\n let object = termToId(quad.object)\n const graph = termToId(quad.graph)\n\n // Find the graph that will contain the triple\n let graphItem = this._graphs[graph]\n // Create the graph if it doesn't exist yet\n if (!graphItem) {\n graphItem = this._graphs[graph] = { subjects: {}, predicates: {}, objects: {} }\n // Freezing a graph helps subsequent `add` performance,\n // and properties will never be modified anyway\n Object.freeze(graphItem)\n }\n\n // Since entities can often be long IRIs, we avoid storing them in every index.\n // Instead, we have a separate index that maps entities to numbers,\n // which are then used as keys in the other indexes.\n const ids = this._ids\n const entities = this._entities\n subject = ids[subject] || (ids[entities[++this._id] = subject] = this._id)\n predicate = ids[predicate] || (ids[entities[++this._id] = predicate] = this._id)\n object = ids[object] || (ids[entities[++this._id] = object] = this._id)\n\n this._addToIndex(graphItem.subjects, subject, predicate, object)\n this._addToIndex(graphItem.predicates, predicate, object, subject)\n this._addToIndex(graphItem.objects, object, subject, predicate)\n\n this._setQuad(subject, predicate, object, graph, quad)\n\n // The cached quad count is now invalid\n this._size = null\n\n return this\n }\n\n delete (quad) {\n // Convert terms to internal string representation\n let subject = termToId(quad.subject)\n let predicate = termToId(quad.predicate)\n let object = termToId(quad.object)\n const graph = termToId(quad.graph)\n\n // Find internal identifiers for all components\n // and verify the quad exists.\n const ids = this._ids\n const graphs = this._graphs\n let graphItem, subjects, predicates\n\n if (!(subject = ids[subject]) || !(predicate = ids[predicate]) ||\n !(object = ids[object]) || !(graphItem = graphs[graph]) ||\n !(subjects = graphItem.subjects[subject]) ||\n !(predicates = subjects[predicate]) ||\n !(object in predicates)\n ) {\n return this\n }\n\n // Remove it from all indexes\n this._removeFromIndex(graphItem.subjects, subject, predicate, object)\n this._removeFromIndex(graphItem.predicates, predicate, object, subject)\n this._removeFromIndex(graphItem.objects, object, subject, predicate)\n\n if (this._size !== null) {\n this._size--\n }\n\n this._deleteQuad(subject, predicate, object, graph)\n\n // Remove the graph if it is empty\n for (subject in graphItem.subjects) { // eslint-disable-line no-unreachable-loop\n return this\n }\n\n delete graphs[graph]\n\n return this\n }\n\n has (quad) {\n // Convert terms to internal string representation\n const subject = termToId(quad.subject)\n const predicate = termToId(quad.predicate)\n const object = termToId(quad.object)\n const graph = termToId(quad.graph)\n\n const graphItem = this._graphs[graph]\n\n if (!graphItem) {\n return false\n }\n\n const ids = this._ids\n let subjectId, predicateId, objectId\n\n // Translate IRIs to internal index keys.\n if (\n (isString(subject) && !(subjectId = ids[subject])) ||\n (isString(predicate) && !(predicateId = ids[predicate])) ||\n (isString(object) && !(objectId = ids[object]))\n ) {\n return false\n }\n\n return this._countInIndex(graphItem.objects, objectId, subjectId, predicateId) === 1\n }\n\n match (subject, predicate, object, graph) {\n return this._createDataset(this._match(subject, predicate, object, graph))\n }\n\n [Symbol.iterator] () {\n return this._match()[Symbol.iterator]()\n }\n\n // ## Private methods\n\n // ### `_addToIndex` adds a quad to a three-layered index.\n // Returns if the index has changed, if the entry did not already exist.\n _addToIndex (index0, key0, key1, key2) {\n // Create layers as necessary\n const index1 = index0[key0] || (index0[key0] = {})\n const index2 = index1[key1] || (index1[key1] = {})\n // Setting the key to _any_ value signals the presence of the quad\n const existed = key2 in index2\n\n if (!existed) {\n index2[key2] = null\n }\n\n return !existed\n }\n\n // ### `_removeFromIndex` removes a quad from a three-layered index\n _removeFromIndex (index0, key0, key1, key2) {\n // Remove the quad from the index\n const index1 = index0[key0]\n const index2 = index1[key1]\n delete index2[key2]\n\n // Remove intermediary index layers if they are empty\n for (const key in index2) { // eslint-disable-line no-unreachable-loop\n return\n }\n\n delete index1[key1]\n\n for (const key in index1) { // eslint-disable-line no-unreachable-loop\n return\n }\n\n delete index0[key0]\n }\n\n // ### `_findInIndex` finds a set of quads in a three-layered index.\n // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`.\n // Any of these keys can be undefined, which is interpreted as a wildcard.\n // `name0`, `name1`, and `name2` are the names of the keys at each level,\n // used when reconstructing the resulting quad\n // (for instance: _subject_, _predicate_, and _object_).\n // Finally, `graph` will be the graph of the created quads.\n // If `callback` is given, each result is passed through it\n // and iteration halts when it returns truthy for any quad.\n // If instead `array` is given, each result is added to the array.\n _findInIndex (index0, key0, key1, key2, name0, name1, name2, graph, callback, array) {\n let tmp, index1, index2\n\n // If a key is specified, use only that part of index 0.\n if (key0) {\n (tmp = index0, index0 = {})[key0] = tmp[key0]\n }\n\n for (const value0 in index0) {\n index1 = index0[value0]\n\n if (index1) {\n // If a key is specified, use only that part of index 1.\n if (key1) {\n (tmp = index1, index1 = {})[key1] = tmp[key1]\n }\n\n for (const value1 in index1) {\n index2 = index1[value1]\n\n if (index2) {\n // If a key is specified, use only that part of index 2, if it exists.\n const values = key2 ? (key2 in index2 ? [key2] : []) : Object.keys(index2)\n // Create quads for all items found in index 2.\n for (let l = 0; l < values.length; l++) {\n const parts = {\n [name0]: value0,\n [name1]: value1,\n [name2]: values[l]\n }\n\n const quad = this._getQuad(parts.subject, parts.predicate, parts.object, graph)\n\n if (array) {\n array.push(quad)\n } else if (callback(quad)) {\n return true\n }\n }\n }\n }\n }\n }\n\n return array\n }\n\n // ### `_countInIndex` counts matching quads in a three-layered index.\n // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`.\n // Any of these keys can be undefined, which is interpreted as a wildcard.\n _countInIndex (index0, key0, key1, key2) {\n let count = 0\n let tmp, index1, index2\n\n // If a key is specified, count only that part of index 0\n if (key0) {\n (tmp = index0, index0 = {})[key0] = tmp[key0]\n }\n\n for (const value0 in index0) {\n index1 = index0[value0]\n\n if (index1) {\n // If a key is specified, count only that part of index 1\n if (key1) {\n (tmp = index1, index1 = {})[key1] = tmp[key1]\n }\n\n for (const value1 in index1) {\n index2 = index1[value1]\n\n if (index2) {\n if (key2) {\n // If a key is specified, count the quad if it exists\n (key2 in index2) && count++\n } else {\n // Otherwise, count all quads\n count += Object.keys(index2).length\n }\n }\n }\n }\n }\n\n return count\n }\n\n // ### `_getGraphs` returns an array with the given graph,\n // or all graphs if the argument is null or undefined.\n _getGraphs (graph) {\n if (!isString(graph)) {\n return this._graphs\n }\n\n return {\n [graph]: this._graphs[graph]\n }\n }\n\n _match (subject, predicate, object, graph) {\n // Convert terms to internal string representation\n subject = subject && termToId(subject)\n predicate = predicate && termToId(predicate)\n object = object && termToId(object)\n graph = graph && termToId(graph)\n\n const quads = []\n const graphs = this._getGraphs(graph)\n const ids = this._ids\n let content, subjectId, predicateId, objectId\n\n // Translate IRIs to internal index keys.\n if (\n (isString(subject) && !(subjectId = ids[subject])) ||\n (isString(predicate) && !(predicateId = ids[predicate])) ||\n (isString(object) && !(objectId = ids[object]))\n ) {\n return quads\n }\n\n for (const graphId in graphs) {\n content = graphs[graphId]\n\n // Only if the specified graph contains triples, there can be results\n if (content) {\n // Choose the optimal index, based on what fields are present\n if (subjectId) {\n if (objectId) {\n // If subject and object are given, the object index will be the fastest\n this._findInIndex(content.objects, objectId, subjectId, predicateId, 'object', 'subject', 'predicate', graphId, null, quads)\n } else {\n // If only subject and possibly predicate are given, the subject index will be the fastest\n this._findInIndex(content.subjects, subjectId, predicateId, null, 'subject', 'predicate', 'object', graphId, null, quads)\n }\n } else if (predicateId) {\n // if only predicate and possibly object are given, the predicate index will be the fastest\n this._findInIndex(content.predicates, predicateId, objectId, null, 'predicate', 'object', 'subject', graphId, null, quads)\n } else if (objectId) {\n // If only object is given, the object index will be the fastest\n this._findInIndex(content.objects, objectId, null, null, 'object', 'subject', 'predicate', graphId, null, quads)\n } else {\n // If nothing is given, iterate subjects and predicates first\n this._findInIndex(content.subjects, null, null, null, 'subject', 'predicate', 'object', graphId, null, quads)\n }\n }\n }\n\n return quads\n }\n\n _getQuad (subjectId, predicateId, objectId, graphId) {\n return this._quads.get(this._toId(subjectId, predicateId, objectId, graphId))\n }\n\n _setQuad (subjectId, predicateId, objectId, graphId, quad) {\n this._quads.set(this._toId(subjectId, predicateId, objectId, graphId), quad)\n }\n\n _deleteQuad (subjectId, predicateId, objectId, graphId) {\n this._quads.delete(this._toId(subjectId, predicateId, objectId, graphId))\n }\n\n _createDataset (quads) {\n return new this.constructor(quads)\n }\n\n _toId (subjectId, predicateId, objectId, graphId) {\n return `${subjectId}:${predicateId}:${objectId}:${graphId}`\n }\n}\n\nmodule.exports = DatasetCore\n","const rdf = require('@rdfjs/data-model')\nconst DatasetCore = require('./DatasetCore')\n\nfunction dataset (quads) {\n return new DatasetCore(quads)\n}\n\nmodule.exports = Object.assign({ dataset }, rdf)\n","/*globals self, window */\n\"use strict\"\n\n/*eslint-disable @mysticatea/prettier */\nconst { AbortController, AbortSignal } =\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window :\n /* otherwise */ undefined\n/*eslint-enable @mysticatea/prettier */\n\nmodule.exports = AbortController\nmodule.exports.AbortSignal = AbortSignal\nmodule.exports.default = AbortController\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/**\r\n * Create a blob builder even when vendor prefixes exist\r\n */\r\n\r\nvar BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :\r\n typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder :\r\n typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :\r\n typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : \r\n false;\r\n\r\n/**\r\n * Check if Blob constructor is supported\r\n */\r\n\r\nvar blobSupported = (function() {\r\n try {\r\n var a = new Blob(['hi']);\r\n return a.size === 2;\r\n } catch(e) {\r\n return false;\r\n }\r\n})();\r\n\r\n/**\r\n * Check if Blob constructor supports ArrayBufferViews\r\n * Fails in Safari 6, so we need to map to ArrayBuffers there.\r\n */\r\n\r\nvar blobSupportsArrayBufferView = blobSupported && (function() {\r\n try {\r\n var b = new Blob([new Uint8Array([1,2])]);\r\n return b.size === 2;\r\n } catch(e) {\r\n return false;\r\n }\r\n})();\r\n\r\n/**\r\n * Check if BlobBuilder is supported\r\n */\r\n\r\nvar blobBuilderSupported = BlobBuilder\r\n && BlobBuilder.prototype.append\r\n && BlobBuilder.prototype.getBlob;\r\n\r\n/**\r\n * Helper function that maps ArrayBufferViews to ArrayBuffers\r\n * Used by BlobBuilder constructor and old browsers that didn't\r\n * support it in the Blob constructor.\r\n */\r\n\r\nfunction mapArrayBufferViews(ary) {\r\n return ary.map(function(chunk) {\r\n if (chunk.buffer instanceof ArrayBuffer) {\r\n var buf = chunk.buffer;\r\n\r\n // if this is a subarray, make a copy so we only\r\n // include the subarray region from the underlying buffer\r\n if (chunk.byteLength !== buf.byteLength) {\r\n var copy = new Uint8Array(chunk.byteLength);\r\n copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));\r\n buf = copy.buffer;\r\n }\r\n\r\n return buf;\r\n }\r\n\r\n return chunk;\r\n });\r\n}\r\n\r\nfunction BlobBuilderConstructor(ary, options) {\r\n options = options || {};\r\n\r\n var bb = new BlobBuilder();\r\n mapArrayBufferViews(ary).forEach(function(part) {\r\n bb.append(part);\r\n });\r\n\r\n return (options.type) ? bb.getBlob(options.type) : bb.getBlob();\r\n}\r\n\r\nfunction BlobConstructor(ary, options) {\r\n return new Blob(mapArrayBufferViews(ary), options || {});\r\n}\r\n\r\nif (typeof Blob !== 'undefined') {\r\n BlobBuilderConstructor.prototype = Blob.prototype;\r\n BlobConstructor.prototype = Blob.prototype;\r\n}\r\n\r\nexport default (function() {\r\n if (blobSupported) {\r\n return blobSupportsArrayBufferView ? Blob : BlobConstructor;\r\n } else if (blobBuilderSupported) {\r\n return BlobBuilderConstructor;\r\n } else {\r\n return undefined;\r\n }\r\n})();\r\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nconst base64 = require('base64-js')\nconst ieee754 = require('ieee754')\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n","/* jshint esversion: 6 */\n/* jslint node: true */\n'use strict';\n\nmodule.exports = function serialize (object) {\n if (object === null || typeof object !== 'object' || object.toJSON != null) {\n return JSON.stringify(object);\n }\n\n if (Array.isArray(object)) {\n return '[' + object.reduce((t, cv, ci) => {\n const comma = ci === 0 ? '' : ',';\n const value = cv === undefined || typeof cv === 'symbol' ? null : cv;\n return t + comma + serialize(value);\n }, '') + ']';\n }\n\n return '{' + Object.keys(object).sort().reduce((t, cv, ci) => {\n if (object[cv] === undefined ||\n typeof object[cv] === 'symbol') {\n return t;\n }\n const comma = t.length === 0 ? '' : ',';\n return t + comma + serialize(cv) + ':' + serialize(object[cv]);\n }, '') + '}';\n};\n","(function(self) {\n\nvar irrelevant = (function (exports) {\n\n var support = {\n searchParams: 'URLSearchParams' in self,\n iterable: 'Symbol' in self && 'iterator' in Symbol,\n blob:\n 'FileReader' in self &&\n 'Blob' in self &&\n (function() {\n try {\n new Blob();\n return true\n } catch (e) {\n return false\n }\n })(),\n formData: 'FormData' in self,\n arrayBuffer: 'ArrayBuffer' in self\n };\n\n function isDataView(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n }\n\n if (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ];\n\n var isArrayBufferView =\n ArrayBuffer.isView ||\n function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n };\n }\n\n function normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name);\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n }\n\n function normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value);\n }\n return value\n }\n\n // Build a destructive iterator for the value list\n function iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift();\n return {done: value === undefined, value: value}\n }\n };\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n };\n }\n\n return iterator\n }\n\n function Headers(headers) {\n this.map = {};\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value);\n }, this);\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n this.append(header[0], header[1]);\n }, this);\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name]);\n }, this);\n }\n }\n\n Headers.prototype.append = function(name, value) {\n name = normalizeName(name);\n value = normalizeValue(value);\n var oldValue = this.map[name];\n this.map[name] = oldValue ? oldValue + ', ' + value : value;\n };\n\n Headers.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)];\n };\n\n Headers.prototype.get = function(name) {\n name = normalizeName(name);\n return this.has(name) ? this.map[name] : null\n };\n\n Headers.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n };\n\n Headers.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value);\n };\n\n Headers.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this);\n }\n }\n };\n\n Headers.prototype.keys = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push(name);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.values = function() {\n var items = [];\n this.forEach(function(value) {\n items.push(value);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.entries = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push([name, value]);\n });\n return iteratorFor(items)\n };\n\n if (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries;\n }\n\n function consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true;\n }\n\n function fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result);\n };\n reader.onerror = function() {\n reject(reader.error);\n };\n })\n }\n\n function readBlobAsArrayBuffer(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsArrayBuffer(blob);\n return promise\n }\n\n function readBlobAsText(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsText(blob);\n return promise\n }\n\n function readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf);\n var chars = new Array(view.length);\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i]);\n }\n return chars.join('')\n }\n\n function bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength);\n view.set(new Uint8Array(buf));\n return view.buffer\n }\n }\n\n function Body() {\n this.bodyUsed = false;\n\n this._initBody = function(body) {\n this._bodyInit = body;\n if (!body) {\n this._bodyText = '';\n } else if (typeof body === 'string') {\n this._bodyText = body;\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body;\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body;\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString();\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer);\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer]);\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body);\n } else {\n this._bodyText = body = Object.prototype.toString.call(body);\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8');\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type);\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n }\n }\n };\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n };\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n };\n }\n\n this.text = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n };\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n };\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n };\n\n return this\n }\n\n // HTTP methods whose capitalization should be normalized\n var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];\n\n function normalizeMethod(method) {\n var upcased = method.toUpperCase();\n return methods.indexOf(upcased) > -1 ? upcased : method\n }\n\n function Request(input, options) {\n options = options || {};\n var body = options.body;\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url;\n this.credentials = input.credentials;\n if (!options.headers) {\n this.headers = new Headers(input.headers);\n }\n this.method = input.method;\n this.mode = input.mode;\n this.signal = input.signal;\n if (!body && input._bodyInit != null) {\n body = input._bodyInit;\n input.bodyUsed = true;\n }\n } else {\n this.url = String(input);\n }\n\n this.credentials = options.credentials || this.credentials || 'same-origin';\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers);\n }\n this.method = normalizeMethod(options.method || this.method || 'GET');\n this.mode = options.mode || this.mode || null;\n this.signal = options.signal || this.signal;\n this.referrer = null;\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body);\n }\n\n Request.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n };\n\n function decode(body) {\n var form = new FormData();\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=');\n var name = split.shift().replace(/\\+/g, ' ');\n var value = split.join('=').replace(/\\+/g, ' ');\n form.append(decodeURIComponent(name), decodeURIComponent(value));\n }\n });\n return form\n }\n\n function parseHeaders(rawHeaders) {\n var headers = new Headers();\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ');\n preProcessedHeaders.split(/\\r?\\n/).forEach(function(line) {\n var parts = line.split(':');\n var key = parts.shift().trim();\n if (key) {\n var value = parts.join(':').trim();\n headers.append(key, value);\n }\n });\n return headers\n }\n\n Body.call(Request.prototype);\n\n function Response(bodyInit, options) {\n if (!options) {\n options = {};\n }\n\n this.type = 'default';\n this.status = options.status === undefined ? 200 : options.status;\n this.ok = this.status >= 200 && this.status < 300;\n this.statusText = 'statusText' in options ? options.statusText : 'OK';\n this.headers = new Headers(options.headers);\n this.url = options.url || '';\n this._initBody(bodyInit);\n }\n\n Body.call(Response.prototype);\n\n Response.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n };\n\n Response.error = function() {\n var response = new Response(null, {status: 0, statusText: ''});\n response.type = 'error';\n return response\n };\n\n var redirectStatuses = [301, 302, 303, 307, 308];\n\n Response.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n };\n\n exports.DOMException = self.DOMException;\n try {\n new exports.DOMException();\n } catch (err) {\n exports.DOMException = function(message, name) {\n this.message = message;\n this.name = name;\n var error = Error(message);\n this.stack = error.stack;\n };\n exports.DOMException.prototype = Object.create(Error.prototype);\n exports.DOMException.prototype.constructor = exports.DOMException;\n }\n\n function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init);\n\n if (request.signal && request.signal.aborted) {\n return reject(new exports.DOMException('Aborted', 'AbortError'))\n }\n\n var xhr = new XMLHttpRequest();\n\n function abortXhr() {\n xhr.abort();\n }\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n };\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');\n var body = 'response' in xhr ? xhr.response : xhr.responseText;\n resolve(new Response(body, options));\n };\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.onabort = function() {\n reject(new exports.DOMException('Aborted', 'AbortError'));\n };\n\n xhr.open(request.method, request.url, true);\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true;\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false;\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob';\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value);\n });\n\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr);\n\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr);\n }\n };\n }\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);\n })\n }\n\n fetch.polyfill = true;\n\n if (!self.fetch) {\n self.fetch = fetch;\n self.Headers = Headers;\n self.Request = Request;\n self.Response = Response;\n }\n\n exports.Headers = Headers;\n exports.Request = Request;\n exports.Response = Response;\n exports.fetch = fetch;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n return exports;\n\n})({});\n})(typeof self !== 'undefined' ? self : this);\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","'use strict'\n\nvar COMPATIBLE_ENCODING_PATTERN = /^utf-?8|ascii|utf-?16-?le|ucs-?2|base-?64|latin-?1$/i\nvar WS_TRIM_PATTERN = /^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g\nvar WS_CHAR_PATTERN = /\\s|\\uFEFF|\\xA0/\nvar WS_FOLD_PATTERN = /\\r?\\n[\\x20\\x09]+/g\nvar DELIMITER_PATTERN = /[;,\"]/\nvar WS_DELIMITER_PATTERN = /[;,\"]|\\s/\n\n/**\n * Token character pattern\n * @type {RegExp}\n * @see https://tools.ietf.org/html/rfc7230#section-3.2.6\n */\nvar TOKEN_PATTERN = /^[!#$%&'*+\\-\\.^_`|~\\da-zA-Z]+$/\n\nvar STATE = {\n IDLE: 1 << 0,\n URI: 1 << 1,\n ATTR: 1 << 2,\n}\n\nfunction trim( value ) {\n return value.replace( WS_TRIM_PATTERN, '' )\n}\n\nfunction hasWhitespace( value ) {\n return WS_CHAR_PATTERN.test( value )\n}\n\nfunction skipWhitespace( value, offset ) {\n while( hasWhitespace( value[offset] ) ) {\n offset++\n }\n return offset\n}\n\nfunction needsQuotes( value ) {\n return WS_DELIMITER_PATTERN.test( value ) ||\n !TOKEN_PATTERN.test( value )\n}\n\n/**\n * Shallow compares two objects to check if their properties match.\n * @param {object} object1 First object to compare.\n * @param {object} object2 Second object to compare.\n * @returns {boolean} Do the objects have matching properties.\n */\nfunction shallowCompareObjects( object1, object2 ) {\n return (\n Object.keys( object1 ).length === Object.keys( object2 ).length &&\n Object.keys( object1 ).every(\n ( key ) => key in object2 && object1[ key ] === object2[ key ]\n )\n );\n}\n\nclass Link {\n\n /**\n * Link\n * @constructor\n * @param {String} [value]\n * @returns {Link}\n */\n constructor( value ) {\n\n /** @type {Array} URI references */\n this.refs = []\n\n if( value ) {\n this.parse( value )\n }\n\n }\n\n /**\n * Get refs with given relation type\n * @param {String} value\n * @returns {Array}\n */\n rel( value ) {\n\n var links = []\n var type = value.toLowerCase()\n\n for( var i = 0; i < this.refs.length; i++ ) {\n if( typeof this.refs[ i ].rel === 'string' && this.refs[ i ].rel.toLowerCase() === type ) {\n links.push( this.refs[ i ] )\n }\n }\n\n return links\n\n }\n\n /**\n * Get refs where given attribute has a given value\n * @param {String} attr\n * @param {String} value\n * @returns {Array}\n */\n get( attr, value ) {\n\n attr = attr.toLowerCase()\n value = value.toLowerCase()\n\n var links = []\n\n for( var i = 0; i < this.refs.length; i++ ) {\n if( typeof this.refs[ i ][ attr ] === 'string' && this.refs[ i ][ attr ].toLowerCase() === value ) {\n links.push( this.refs[ i ] )\n }\n }\n\n return links\n\n }\n\n /** Sets a reference. */\n set( link ) {\n this.refs.push( link )\n return this\n }\n\n /**\n * Sets a reference if a reference with similar properties isn’t already set.\n */\n setUnique( link ) {\n\n if( !this.refs.some(( ref ) => shallowCompareObjects( ref, link )) ) {\n this.refs.push( link )\n }\n\n return this\n\n }\n\n has( attr, value ) {\n\n attr = attr.toLowerCase()\n value = value.toLowerCase()\n\n for( var i = 0; i < this.refs.length; i++ ) {\n if( typeof this.refs[ i ][ attr ] === 'string' && this.refs[ i ][ attr ].toLowerCase() === value ) {\n return true\n }\n }\n\n return false\n\n }\n\n parse( value, offset ) {\n\n offset = offset || 0\n value = offset ? value.slice( offset ) : value\n\n // Trim & unfold folded lines\n value = trim( value ).replace( WS_FOLD_PATTERN, '' )\n\n var state = STATE.IDLE\n var length = value.length\n var offset = 0\n var ref = null\n\n while( offset < length ) {\n if( state === STATE.IDLE ) {\n if( hasWhitespace( value[offset] ) ) {\n offset++\n continue\n } else if( value[offset] === '<' ) {\n if( ref != null ) {\n ref.rel != null ?\n this.refs.push( ...Link.expandRelations( ref ) ) :\n this.refs.push( ref )\n }\n var end = value.indexOf( '>', offset )\n if( end === -1 ) throw new Error( 'Expected end of URI delimiter at offset ' + offset )\n ref = { uri: value.slice( offset + 1, end ) }\n // this.refs.push( ref )\n offset = end\n state = STATE.URI\n } else {\n throw new Error( 'Unexpected character \"' + value[offset] + '\" at offset ' + offset )\n }\n offset++\n } else if( state === STATE.URI ) {\n if( hasWhitespace( value[offset] ) ) {\n offset++\n continue\n } else if( value[offset] === ';' ) {\n state = STATE.ATTR\n offset++\n } else if( value[offset] === ',' ) {\n state = STATE.IDLE\n offset++\n } else {\n throw new Error( 'Unexpected character \"' + value[offset] + '\" at offset ' + offset )\n }\n } else if( state === STATE.ATTR ) {\n if( value[offset] ===';' || hasWhitespace( value[offset] ) ) {\n offset++\n continue\n }\n var end = value.indexOf( '=', offset )\n if( end === -1 ) end = value.indexOf( ';', offset )\n if( end === -1 ) end = value.length\n var attr = trim( value.slice( offset, end ) ).toLowerCase()\n var attrValue = ''\n offset = end + 1\n offset = skipWhitespace( value, offset )\n if( value[offset] === '\"' ) {\n offset++\n while( offset < length ) {\n if( value[offset] === '\"' ) {\n offset++; break\n }\n if( value[offset] === '\\\\' ) {\n offset++\n }\n attrValue += value[offset]\n offset++\n }\n } else {\n var end = offset + 1\n while( !DELIMITER_PATTERN.test( value[end] ) && end < length ) {\n end++\n }\n attrValue = value.slice( offset, end )\n offset = end\n }\n if( ref[ attr ] && Link.isSingleOccurenceAttr( attr ) ) {\n // Ignore multiples of attributes which may only appear once\n } else if( attr[ attr.length - 1 ] === '*' ) {\n ref[ attr ] = Link.parseExtendedValue( attrValue )\n } else {\n attrValue = attr === 'type' ?\n attrValue.toLowerCase() : attrValue\n if( ref[ attr ] != null ) {\n if( Array.isArray( ref[ attr ] ) ) {\n ref[ attr ].push( attrValue )\n } else {\n ref[ attr ] = [ ref[ attr ], attrValue ]\n }\n } else {\n ref[ attr ] = attrValue\n }\n }\n switch( value[offset] ) {\n case ',': state = STATE.IDLE; break\n case ';': state = STATE.ATTR; break\n }\n offset++\n } else {\n throw new Error( 'Unknown parser state \"' + state + '\"' )\n }\n }\n\n if( ref != null ) {\n ref.rel != null ?\n this.refs.push( ...Link.expandRelations( ref ) ) :\n this.refs.push( ref )\n }\n\n ref = null\n\n return this\n\n }\n\n toString() {\n\n var refs = []\n var link = ''\n var ref = null\n\n for( var i = 0; i < this.refs.length; i++ ) {\n ref = this.refs[i]\n link = Object.keys( this.refs[i] ).reduce( function( link, attr ) {\n if( attr === 'uri' ) return link\n return link + '; ' + Link.formatAttribute( attr, ref[ attr ] )\n }, '<' + ref.uri + '>' )\n refs.push( link )\n }\n\n return refs.join( ', ' )\n\n }\n\n}\n\n/**\n * Determines whether an encoding can be\n * natively handled with a `Buffer`\n * @param {String} value\n * @returns {Boolean}\n */\nLink.isCompatibleEncoding = function( value ) {\n return COMPATIBLE_ENCODING_PATTERN.test( value )\n}\n\nLink.parse = function( value, offset ) {\n return new Link().parse( value, offset )\n}\n\nLink.isSingleOccurenceAttr = function( attr ) {\n return attr === 'rel' || attr === 'type' || attr === 'media' ||\n attr === 'title' || attr === 'title*'\n}\n\nLink.isTokenAttr = function( attr ) {\n return attr === 'rel' || attr === 'type' || attr === 'anchor'\n}\n\nLink.escapeQuotes = function( value ) {\n return value.replace( /\"/g, '\\\\\"' )\n}\n\nLink.expandRelations = function( ref ) {\n var rels = ref.rel.split( ' ' )\n return rels.map( function( rel ) {\n var value = Object.assign( {}, ref )\n value.rel = rel\n return value\n })\n}\n\n/**\n * Parses an extended value and attempts to decode it\n * @internal\n * @param {String} value\n * @return {Object}\n */\nLink.parseExtendedValue = function( value ) {\n var parts = /([^']+)?(?:'([^']*)')?(.+)/.exec( value )\n return {\n language: parts[2].toLowerCase(),\n encoding: Link.isCompatibleEncoding( parts[1] ) ?\n null : parts[1].toLowerCase(),\n value: Link.isCompatibleEncoding( parts[1] ) ?\n decodeURIComponent( parts[3] ) : parts[3]\n }\n}\n\n/**\n * Format a given extended attribute and it's value\n * @param {String} attr\n * @param {Object} data\n * @return {String}\n */\nLink.formatExtendedAttribute = function( attr, data ) {\n\n var encoding = ( data.encoding || 'utf-8' ).toUpperCase()\n var language = data.language || 'en'\n\n var encodedValue = ''\n\n if( Buffer.isBuffer( data.value ) && Link.isCompatibleEncoding( encoding ) ) {\n encodedValue = data.value.toString( encoding )\n } else if( Buffer.isBuffer( data.value ) ) {\n encodedValue = data.value.toString( 'hex' )\n .replace( /[0-9a-f]{2}/gi, '%$1' )\n } else {\n encodedValue = encodeURIComponent( data.value )\n }\n\n return attr + '=' + encoding + '\\'' +\n language + '\\'' + encodedValue\n\n}\n\n/**\n * Format a given attribute and it's value\n * @param {String} attr\n * @param {String|Object} value\n * @return {String}\n */\nLink.formatAttribute = function( attr, value ) {\n\n if( Array.isArray( value ) ) {\n return value.map(( item ) => {\n return Link.formatAttribute( attr, item )\n }).join( '; ' )\n }\n\n if( attr[ attr.length - 1 ] === '*' || typeof value !== 'string' ) {\n return Link.formatExtendedAttribute( attr, value )\n }\n\n if( Link.isTokenAttr( attr ) ) {\n value = needsQuotes( value ) ?\n '\"' + Link.escapeQuotes( value ) + '\"' :\n Link.escapeQuotes( value )\n } else if( needsQuotes( value ) ) {\n value = encodeURIComponent( value )\n // We don't need to escape <,> <;> within quotes\n value = value\n .replace( /%20/g, ' ' )\n .replace( /%2C/g, ',' )\n .replace( /%3B/g, ';' )\n\n value = '\"' + value + '\"'\n }\n\n return attr + '=' + value\n\n}\n\nmodule.exports = Link\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./lib/ContextParser\"), exports);\n__exportStar(require(\"./lib/ErrorCoded\"), exports);\n__exportStar(require(\"./lib/FetchDocumentLoader\"), exports);\n__exportStar(require(\"./lib/IDocumentLoader\"), exports);\n__exportStar(require(\"./lib/JsonLdContext\"), exports);\n__exportStar(require(\"./lib/JsonLdContextNormalized\"), exports);\n__exportStar(require(\"./lib/Util\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ContextParser = void 0;\nrequire(\"cross-fetch/polyfill\");\nconst relative_to_absolute_iri_1 = require(\"relative-to-absolute-iri\");\nconst ErrorCoded_1 = require(\"./ErrorCoded\");\nconst FetchDocumentLoader_1 = require(\"./FetchDocumentLoader\");\nconst JsonLdContextNormalized_1 = require(\"./JsonLdContextNormalized\");\nconst Util_1 = require(\"./Util\");\n/**\n * Parses JSON-LD contexts.\n */\nclass ContextParser {\n constructor(options) {\n options = options || {};\n this.documentLoader = options.documentLoader || new FetchDocumentLoader_1.FetchDocumentLoader();\n this.documentCache = {};\n this.validateContext = !options.skipValidation;\n this.expandContentTypeToBase = !!options.expandContentTypeToBase;\n this.remoteContextsDepthLimit = options.remoteContextsDepthLimit || 32;\n this.redirectSchemaOrgHttps = 'redirectSchemaOrgHttps' in options ? !!options.redirectSchemaOrgHttps : true;\n }\n /**\n * Validate the given @language value.\n * An error will be thrown if it is invalid.\n * @param value An @language value.\n * @param {boolean} strictRange If the string value should be strictly checked against a regex.\n * @param {string} errorCode The error code to emit on errors.\n * @return {boolean} If validation passed.\n * Can only be false if strictRange is false and the string value did not pass the regex.\n */\n static validateLanguage(value, strictRange, errorCode) {\n if (typeof value !== 'string') {\n throw new ErrorCoded_1.ErrorCoded(`The value of an '@language' must be a string, got '${JSON.stringify(value)}'`, errorCode);\n }\n if (!Util_1.Util.REGEX_LANGUAGE_TAG.test(value)) {\n if (strictRange) {\n throw new ErrorCoded_1.ErrorCoded(`The value of an '@language' must be a valid language tag, got '${JSON.stringify(value)}'`, errorCode);\n }\n else {\n return false;\n }\n }\n return true;\n }\n /**\n * Validate the given @direction value.\n * An error will be thrown if it is invalid.\n * @param value An @direction value.\n * @param {boolean} strictValues If the string value should be strictly checked against a regex.\n * @return {boolean} If validation passed.\n * Can only be false if strictRange is false and the string value did not pass the regex.\n */\n static validateDirection(value, strictValues) {\n if (typeof value !== 'string') {\n throw new ErrorCoded_1.ErrorCoded(`The value of an '@direction' must be a string, got '${JSON.stringify(value)}'`, ErrorCoded_1.ERROR_CODES.INVALID_BASE_DIRECTION);\n }\n if (!Util_1.Util.REGEX_DIRECTION_TAG.test(value)) {\n if (strictValues) {\n throw new ErrorCoded_1.ErrorCoded(`The value of an '@direction' must be 'ltr' or 'rtl', got '${JSON.stringify(value)}'`, ErrorCoded_1.ERROR_CODES.INVALID_BASE_DIRECTION);\n }\n else {\n return false;\n }\n }\n return true;\n }\n /**\n * Add an @id term for all @reverse terms.\n * @param {IJsonLdContextNormalizedRaw} context A context.\n * @return {IJsonLdContextNormalizedRaw} The mutated input context.\n */\n idifyReverseTerms(context) {\n for (const key of Object.keys(context)) {\n let value = context[key];\n if (value && typeof value === 'object') {\n if (value['@reverse'] && !value['@id']) {\n if (typeof value['@reverse'] !== 'string' || Util_1.Util.isValidKeyword(value['@reverse'])) {\n throw new ErrorCoded_1.ErrorCoded(`Invalid @reverse value, must be absolute IRI or blank node: '${value['@reverse']}'`, ErrorCoded_1.ERROR_CODES.INVALID_IRI_MAPPING);\n }\n value = context[key] = Object.assign(Object.assign({}, value), { '@id': value['@reverse'] });\n value['@id'] = value['@reverse'];\n if (Util_1.Util.isPotentialKeyword(value['@reverse'])) {\n delete value['@reverse'];\n }\n else {\n value['@reverse'] = true;\n }\n }\n }\n }\n return context;\n }\n /**\n * Expand all prefixed terms in the given context.\n * @param {IJsonLdContextNormalizedRaw} context A context.\n * @param {boolean} expandContentTypeToBase If @type inside the context may be expanded\n * via @base if @vocab is set to null.\n * @param {string[]} keys Optional set of keys from the context to expand. If left undefined, all\n * keys in the context will be expanded.\n */\n expandPrefixedTerms(context, expandContentTypeToBase, keys) {\n const contextRaw = context.getContextRaw();\n for (const key of (keys || Object.keys(contextRaw))) {\n // Only expand allowed keys\n if (Util_1.Util.EXPAND_KEYS_BLACKLIST.indexOf(key) < 0 && !Util_1.Util.isReservedInternalKeyword(key)) {\n // Error if we try to alias a keyword to something else.\n const keyValue = contextRaw[key];\n if (Util_1.Util.isPotentialKeyword(key) && Util_1.Util.ALIAS_DOMAIN_BLACKLIST.indexOf(key) >= 0) {\n if (key !== '@type' || typeof contextRaw[key] === 'object'\n && !(contextRaw[key]['@protected'] || contextRaw[key]['@container'] === '@set')) {\n throw new ErrorCoded_1.ErrorCoded(`Keywords can not be aliased to something else.\nTried mapping ${key} to ${JSON.stringify(keyValue)}`, ErrorCoded_1.ERROR_CODES.KEYWORD_REDEFINITION);\n }\n }\n // Error if we try to alias to an illegal keyword\n if (Util_1.Util.ALIAS_RANGE_BLACKLIST.indexOf(Util_1.Util.getContextValueId(keyValue)) >= 0) {\n throw new ErrorCoded_1.ErrorCoded(`Aliasing to certain keywords is not allowed.\nTried mapping ${key} to ${JSON.stringify(keyValue)}`, ErrorCoded_1.ERROR_CODES.INVALID_KEYWORD_ALIAS);\n }\n // Error if this term was marked as prefix as well\n if (keyValue && Util_1.Util.isPotentialKeyword(Util_1.Util.getContextValueId(keyValue))\n && keyValue['@prefix'] === true) {\n throw new ErrorCoded_1.ErrorCoded(`Tried to use keyword aliases as prefix: '${key}': '${JSON.stringify(keyValue)}'`, ErrorCoded_1.ERROR_CODES.INVALID_TERM_DEFINITION);\n }\n // Loop because prefixes might be nested\n while (Util_1.Util.isPrefixValue(contextRaw[key])) {\n const value = contextRaw[key];\n let changed = false;\n if (typeof value === 'string') {\n contextRaw[key] = context.expandTerm(value, true);\n changed = changed || value !== contextRaw[key];\n }\n else {\n const id = value['@id'];\n const type = value['@type'];\n // If @id is missing, don't allow @id to be added if @prefix: true and key not being a valid IRI.\n const canAddIdEntry = !('@prefix' in value) || Util_1.Util.isValidIri(key);\n if ('@id' in value) {\n // Use @id value for expansion\n if (id !== undefined && id !== null && typeof id === 'string') {\n contextRaw[key] = Object.assign(Object.assign({}, contextRaw[key]), { '@id': context.expandTerm(id, true) });\n changed = changed || id !== contextRaw[key]['@id'];\n }\n }\n else if (!Util_1.Util.isPotentialKeyword(key) && canAddIdEntry) {\n // Add an explicit @id value based on the expanded key value\n const newId = context.expandTerm(key, true);\n if (newId !== key) {\n // Don't set @id if expansion failed\n contextRaw[key] = Object.assign(Object.assign({}, contextRaw[key]), { '@id': newId });\n changed = true;\n }\n }\n if (type && typeof type === 'string' && type !== '@vocab'\n && (!value['@container'] || !value['@container']['@type'])\n && canAddIdEntry) {\n // First check @vocab, then fallback to @base\n let expandedType = context.expandTerm(type, true);\n if (expandContentTypeToBase && type === expandedType) {\n expandedType = context.expandTerm(type, false);\n }\n if (expandedType !== type) {\n changed = true;\n contextRaw[key] = Object.assign(Object.assign({}, contextRaw[key]), { '@type': expandedType });\n }\n }\n }\n if (!changed) {\n break;\n }\n }\n }\n }\n }\n /**\n * Normalize the @language entries in the given context to lowercase.\n * @param {IJsonLdContextNormalizedRaw} context A context.\n * @param {IParseOptions} parseOptions The parsing options.\n */\n normalize(context, { processingMode, normalizeLanguageTags }) {\n // Lowercase language keys in 1.0\n if (normalizeLanguageTags || processingMode === 1.0) {\n for (const key of Object.keys(context)) {\n if (key === '@language' && typeof context[key] === 'string') {\n context[key] = context[key].toLowerCase();\n }\n else {\n const value = context[key];\n if (value && typeof value === 'object') {\n if (typeof value['@language'] === 'string') {\n const lowercase = value['@language'].toLowerCase();\n if (lowercase !== value['@language']) {\n context[key] = Object.assign(Object.assign({}, value), { '@language': lowercase });\n }\n }\n }\n }\n }\n }\n }\n /**\n * Convert all @container strings and array values to hash-based values.\n * @param {IJsonLdContextNormalizedRaw} context A context.\n */\n containersToHash(context) {\n for (const key of Object.keys(context)) {\n const value = context[key];\n if (value && typeof value === 'object') {\n if (typeof value['@container'] === 'string') {\n context[key] = Object.assign(Object.assign({}, value), { '@container': { [value['@container']]: true } });\n }\n else if (Array.isArray(value['@container'])) {\n const newValue = {};\n for (const containerValue of value['@container']) {\n newValue[containerValue] = true;\n }\n context[key] = Object.assign(Object.assign({}, value), { '@container': newValue });\n }\n }\n }\n }\n /**\n * Normalize and apply context-level @protected terms onto each term separately.\n * @param {IJsonLdContextNormalizedRaw} context A context.\n * @param {number} processingMode The processing mode.\n */\n applyScopedProtected(context, { processingMode }, expandOptions) {\n if (processingMode && processingMode >= 1.1) {\n if (context['@protected']) {\n for (const key of Object.keys(context)) {\n if (Util_1.Util.isReservedInternalKeyword(key)) {\n continue;\n }\n if (!Util_1.Util.isPotentialKeyword(key) && !Util_1.Util.isTermProtected(context, key)) {\n const value = context[key];\n if (value && typeof value === 'object') {\n if (!('@protected' in context[key])) {\n // Mark terms with object values as protected if they don't have an @protected: false annotation\n context[key] = Object.assign(Object.assign({}, context[key]), { '@protected': true });\n }\n }\n else {\n // Convert string-based term values to object-based values with @protected: true\n context[key] = {\n '@id': value,\n '@protected': true,\n };\n if (Util_1.Util.isSimpleTermDefinitionPrefix(value, expandOptions)) {\n context[key] = Object.assign(Object.assign({}, context[key]), { '@prefix': true });\n }\n }\n }\n }\n delete context['@protected'];\n }\n }\n }\n /**\n * Check if the given context inheritance does not contain any overrides of protected terms.\n * @param {IJsonLdContextNormalizedRaw} contextBefore The context that may contain some protected terms.\n * @param {IJsonLdContextNormalizedRaw} contextAfter A new context that is being applied on the first one.\n * @param {IExpandOptions} expandOptions Options that are needed for any expansions during this validation.\n * @param {string[]} keys Optional set of keys from the context to validate. If left undefined, all\n * keys defined in contextAfter will be checked.\n */\n validateKeywordRedefinitions(contextBefore, contextAfter, expandOptions, keys) {\n for (const key of (keys !== null && keys !== void 0 ? keys : Object.keys(contextAfter))) {\n if (Util_1.Util.isTermProtected(contextBefore, key)) {\n // The entry in the context before will always be in object-mode\n // If the new entry is in string-mode, convert it to object-mode\n // before checking if it is identical.\n if (typeof contextAfter[key] === 'string') {\n contextAfter[key] = { '@id': contextAfter[key], '@protected': true };\n }\n else {\n // We modify this deliberately,\n // as we need it for the value comparison (they must be identical modulo '@protected')),\n // and for the fact that this new value will override the first one.\n contextAfter[key] = Object.assign(Object.assign({}, contextAfter[key]), { '@protected': true });\n }\n // Error if they are not identical\n if (!Util_1.Util.deepEqual(contextBefore[key], contextAfter[key])) {\n throw new ErrorCoded_1.ErrorCoded(`Attempted to override the protected keyword ${key} from ${JSON.stringify(Util_1.Util.getContextValueId(contextBefore[key]))} to ${JSON.stringify(Util_1.Util.getContextValueId(contextAfter[key]))}`, ErrorCoded_1.ERROR_CODES.PROTECTED_TERM_REDEFINITION);\n }\n }\n }\n }\n /**\n * Validate the entries of the given context.\n * @param {IJsonLdContextNormalizedRaw} context A context.\n * @param {IParseOptions} options The parse options.\n */\n validate(context, { processingMode }) {\n for (const key of Object.keys(context)) {\n // Ignore reserved internal keywords.\n if (Util_1.Util.isReservedInternalKeyword(key)) {\n continue;\n }\n // Do not allow empty term\n if (key === '') {\n throw new ErrorCoded_1.ErrorCoded(`The empty term is not allowed, got: '${key}': '${JSON.stringify(context[key])}'`, ErrorCoded_1.ERROR_CODES.INVALID_TERM_DEFINITION);\n }\n const value = context[key];\n const valueType = typeof value;\n // First check if the key is a keyword\n if (Util_1.Util.isPotentialKeyword(key)) {\n switch (key.substr(1)) {\n case 'vocab':\n if (value !== null && valueType !== 'string') {\n throw new ErrorCoded_1.ErrorCoded(`Found an invalid @vocab IRI: ${value}`, ErrorCoded_1.ERROR_CODES.INVALID_VOCAB_MAPPING);\n }\n break;\n case 'base':\n if (value !== null && valueType !== 'string') {\n throw new ErrorCoded_1.ErrorCoded(`Found an invalid @base IRI: ${context[key]}`, ErrorCoded_1.ERROR_CODES.INVALID_BASE_IRI);\n }\n break;\n case 'language':\n if (value !== null) {\n ContextParser.validateLanguage(value, true, ErrorCoded_1.ERROR_CODES.INVALID_DEFAULT_LANGUAGE);\n }\n break;\n case 'version':\n if (value !== null && valueType !== 'number') {\n throw new ErrorCoded_1.ErrorCoded(`Found an invalid @version number: ${value}`, ErrorCoded_1.ERROR_CODES.INVALID_VERSION_VALUE);\n }\n break;\n case 'direction':\n if (value !== null) {\n ContextParser.validateDirection(value, true);\n }\n break;\n case 'propagate':\n if (processingMode === 1.0) {\n throw new ErrorCoded_1.ErrorCoded(`Found an illegal @propagate keyword: ${value}`, ErrorCoded_1.ERROR_CODES.INVALID_CONTEXT_ENTRY);\n }\n if (value !== null && valueType !== 'boolean') {\n throw new ErrorCoded_1.ErrorCoded(`Found an invalid @propagate value: ${value}`, ErrorCoded_1.ERROR_CODES.INVALID_PROPAGATE_VALUE);\n }\n break;\n }\n // Don't allow keywords to be overridden\n if (Util_1.Util.isValidKeyword(key) && Util_1.Util.isValidKeyword(Util_1.Util.getContextValueId(value))) {\n throw new ErrorCoded_1.ErrorCoded(`Illegal keyword alias in term value, found: '${key}': '${Util_1.Util\n .getContextValueId(value)}'`, ErrorCoded_1.ERROR_CODES.KEYWORD_REDEFINITION);\n }\n continue;\n }\n // Otherwise, consider the key a term\n if (value !== null) {\n switch (valueType) {\n case 'string':\n if (Util_1.Util.getPrefix(value, context) === key) {\n throw new ErrorCoded_1.ErrorCoded(`Detected cyclical IRI mapping in context entry: '${key}': '${JSON\n .stringify(value)}'`, ErrorCoded_1.ERROR_CODES.CYCLIC_IRI_MAPPING);\n }\n if (Util_1.Util.isValidIriWeak(key)) {\n if (value === '@type') {\n throw new ErrorCoded_1.ErrorCoded(`IRIs can not be mapped to @type, found: '${key}': '${value}'`, ErrorCoded_1.ERROR_CODES.INVALID_IRI_MAPPING);\n }\n else if (Util_1.Util.isValidIri(value) && value !== new JsonLdContextNormalized_1.JsonLdContextNormalized(context).expandTerm(key)) {\n throw new ErrorCoded_1.ErrorCoded(`IRIs can not be mapped to other IRIs, found: '${key}': '${value}'`, ErrorCoded_1.ERROR_CODES.INVALID_IRI_MAPPING);\n }\n }\n break;\n case 'object':\n if (!Util_1.Util.isCompactIri(key) && !('@id' in value)\n && (value['@type'] === '@id' ? !context['@base'] : !context['@vocab'])) {\n throw new ErrorCoded_1.ErrorCoded(`Missing @id in context entry: '${key}': '${JSON.stringify(value)}'`, ErrorCoded_1.ERROR_CODES.INVALID_IRI_MAPPING);\n }\n for (const objectKey of Object.keys(value)) {\n const objectValue = value[objectKey];\n if (!objectValue) {\n continue;\n }\n switch (objectKey) {\n case '@id':\n if (Util_1.Util.isValidKeyword(objectValue)\n && objectValue !== '@type' && objectValue !== '@id' && objectValue !== '@graph' && objectValue !== '@nest') {\n throw new ErrorCoded_1.ErrorCoded(`Illegal keyword alias in term value, found: '${key}': '${JSON.stringify(value)}'`, ErrorCoded_1.ERROR_CODES.INVALID_IRI_MAPPING);\n }\n if (Util_1.Util.isValidIriWeak(key)) {\n if (objectValue === '@type') {\n throw new ErrorCoded_1.ErrorCoded(`IRIs can not be mapped to @type, found: '${key}': '${JSON.stringify(value)}'`, ErrorCoded_1.ERROR_CODES.INVALID_IRI_MAPPING);\n }\n else if (Util_1.Util.isValidIri(objectValue)\n && objectValue !== new JsonLdContextNormalized_1.JsonLdContextNormalized(context).expandTerm(key)) {\n throw new ErrorCoded_1.ErrorCoded(`IRIs can not be mapped to other IRIs, found: '${key}': '${JSON.stringify(value)}'`, ErrorCoded_1.ERROR_CODES.INVALID_IRI_MAPPING);\n }\n }\n if (typeof objectValue !== 'string') {\n throw new ErrorCoded_1.ErrorCoded(`Detected non-string @id in context entry: '${key}': '${JSON.stringify(value)}'`, ErrorCoded_1.ERROR_CODES.INVALID_IRI_MAPPING);\n }\n if (Util_1.Util.getPrefix(objectValue, context) === key) {\n throw new ErrorCoded_1.ErrorCoded(`Detected cyclical IRI mapping in context entry: '${key}': '${JSON\n .stringify(value)}'`, ErrorCoded_1.ERROR_CODES.CYCLIC_IRI_MAPPING);\n }\n break;\n case '@type':\n if (value['@container'] === '@type' && objectValue !== '@id' && objectValue !== '@vocab') {\n throw new ErrorCoded_1.ErrorCoded(`@container: @type only allows @type: @id or @vocab, but got: '${key}': '${objectValue}'`, ErrorCoded_1.ERROR_CODES.INVALID_TYPE_MAPPING);\n }\n if (typeof objectValue !== 'string') {\n throw new ErrorCoded_1.ErrorCoded(`The value of an '@type' must be a string, got '${JSON.stringify(valueType)}'`, ErrorCoded_1.ERROR_CODES.INVALID_TYPE_MAPPING);\n }\n if (objectValue !== '@id' && objectValue !== '@vocab'\n && (processingMode === 1.0 || objectValue !== '@json')\n && (processingMode === 1.0 || objectValue !== '@none')\n && (objectValue[0] === '_' || !Util_1.Util.isValidIri(objectValue))) {\n throw new ErrorCoded_1.ErrorCoded(`A context @type must be an absolute IRI, found: '${key}': '${objectValue}'`, ErrorCoded_1.ERROR_CODES.INVALID_TYPE_MAPPING);\n }\n break;\n case '@reverse':\n if (typeof objectValue === 'string' && value['@id'] && value['@id'] !== objectValue) {\n throw new ErrorCoded_1.ErrorCoded(`Found non-matching @id and @reverse term values in '${key}':\\\n'${objectValue}' and '${value['@id']}'`, ErrorCoded_1.ERROR_CODES.INVALID_REVERSE_PROPERTY);\n }\n if ('@nest' in value) {\n throw new ErrorCoded_1.ErrorCoded(`@nest is not allowed in the reverse property '${key}'`, ErrorCoded_1.ERROR_CODES.INVALID_REVERSE_PROPERTY);\n }\n break;\n case '@container':\n if (processingMode === 1.0) {\n if (Object.keys(objectValue).length > 1\n || Util_1.Util.CONTAINERS_1_0.indexOf(Object.keys(objectValue)[0]) < 0) {\n throw new ErrorCoded_1.ErrorCoded(`Invalid term @container for '${key}' ('${Object.keys(objectValue)}') in 1.0, \\\nmust be only one of ${Util_1.Util.CONTAINERS_1_0.join(', ')}`, ErrorCoded_1.ERROR_CODES.INVALID_CONTAINER_MAPPING);\n }\n }\n for (const containerValue of Object.keys(objectValue)) {\n if (containerValue === '@list' && value['@reverse']) {\n throw new ErrorCoded_1.ErrorCoded(`Term value can not be @container: @list and @reverse at the same time on '${key}'`, ErrorCoded_1.ERROR_CODES.INVALID_REVERSE_PROPERTY);\n }\n if (Util_1.Util.CONTAINERS.indexOf(containerValue) < 0) {\n throw new ErrorCoded_1.ErrorCoded(`Invalid term @container for '${key}' ('${containerValue}'), \\\nmust be one of ${Util_1.Util.CONTAINERS.join(', ')}`, ErrorCoded_1.ERROR_CODES.INVALID_CONTAINER_MAPPING);\n }\n }\n break;\n case '@language':\n ContextParser.validateLanguage(objectValue, true, ErrorCoded_1.ERROR_CODES.INVALID_LANGUAGE_MAPPING);\n break;\n case '@direction':\n ContextParser.validateDirection(objectValue, true);\n break;\n case '@prefix':\n if (objectValue !== null && typeof objectValue !== 'boolean') {\n throw new ErrorCoded_1.ErrorCoded(`Found an invalid term @prefix boolean in: '${key}': '${JSON.stringify(value)}'`, ErrorCoded_1.ERROR_CODES.INVALID_PREFIX_VALUE);\n }\n if (!('@id' in value) && !Util_1.Util.isValidIri(key)) {\n throw new ErrorCoded_1.ErrorCoded(`Invalid @prefix definition for '${key}' ('${JSON.stringify(value)}'`, ErrorCoded_1.ERROR_CODES.INVALID_TERM_DEFINITION);\n }\n break;\n case '@index':\n if (processingMode === 1.0 || !value['@container'] || !value['@container']['@index']) {\n throw new ErrorCoded_1.ErrorCoded(`Attempt to add illegal key to value object: '${key}': '${JSON.stringify(value)}'`, ErrorCoded_1.ERROR_CODES.INVALID_TERM_DEFINITION);\n }\n break;\n case '@nest':\n if (Util_1.Util.isPotentialKeyword(objectValue) && objectValue !== '@nest') {\n throw new ErrorCoded_1.ErrorCoded(`Found an invalid term @nest value in: '${key}': '${JSON.stringify(value)}'`, ErrorCoded_1.ERROR_CODES.INVALID_NEST_VALUE);\n }\n }\n }\n break;\n default:\n throw new ErrorCoded_1.ErrorCoded(`Found an invalid term value: '${key}': '${value}'`, ErrorCoded_1.ERROR_CODES.INVALID_TERM_DEFINITION);\n }\n }\n }\n }\n /**\n * Apply the @base context entry to the given context under certain circumstances.\n * @param context A context.\n * @param options Parsing options.\n * @param inheritFromParent If the @base value from the parent context can be inherited.\n * @return The given context.\n */\n applyBaseEntry(context, options, inheritFromParent) {\n // In some special cases, this can be a string, so ignore those.\n if (typeof context === 'string') {\n return context;\n }\n // Give priority to @base in the parent context\n if (inheritFromParent && !('@base' in context) && options.parentContext\n && typeof options.parentContext === 'object' && '@base' in options.parentContext) {\n context['@base'] = options.parentContext['@base'];\n if (options.parentContext['@__baseDocument']) {\n context['@__baseDocument'] = true;\n }\n }\n // Override the base IRI if provided.\n if (options.baseIRI && !options.external) {\n if (!('@base' in context)) {\n // The context base is the document base\n context['@base'] = options.baseIRI;\n context['@__baseDocument'] = true;\n }\n else if (context['@base'] !== null && typeof context['@base'] === 'string'\n && !Util_1.Util.isValidIri(context['@base'])) {\n // The context base is relative to the document base\n context['@base'] = (0, relative_to_absolute_iri_1.resolve)(context['@base'], options.parentContext && options.parentContext['@base'] || options.baseIRI);\n }\n }\n return context;\n }\n /**\n * Resolve relative context IRIs, or return full IRIs as-is.\n * @param {string} contextIri A context IRI.\n * @param {string} baseIRI A base IRI.\n * @return {string} The normalized context IRI.\n */\n normalizeContextIri(contextIri, baseIRI) {\n if (!Util_1.Util.isValidIri(contextIri)) {\n try {\n contextIri = (0, relative_to_absolute_iri_1.resolve)(contextIri, baseIRI);\n }\n catch (_a) {\n throw new Error(`Invalid context IRI: ${contextIri}`);\n }\n }\n // TODO: Temporary workaround for fixing schema.org CORS issues (https://github.com/schemaorg/schemaorg/issues/2578#issuecomment-652324465)\n if (this.redirectSchemaOrgHttps && contextIri.startsWith('http://schema.org')) {\n contextIri = 'https://schema.org/';\n }\n return contextIri;\n }\n /**\n * Parse scoped contexts in the given context.\n * @param {IJsonLdContextNormalizedRaw} context A context.\n * @param {IParseOptions} options Parsing options.\n * @return {IJsonLdContextNormalizedRaw} The mutated input context.\n * @param {string[]} keys Optional set of keys from the context to parseInnerContexts of. If left undefined, all\n * keys in the context will be iterated over.\n */\n async parseInnerContexts(context, options, keys) {\n for (const key of (keys !== null && keys !== void 0 ? keys : Object.keys(context))) {\n const value = context[key];\n if (value && typeof value === 'object') {\n if ('@context' in value && value['@context'] !== null && !options.ignoreScopedContexts) {\n // Simulate a processing based on the parent context to check if there are any (potential errors).\n // Honestly, I find it a bit weird to do this here, as the context may be unused,\n // and the final effective context may differ based on any other embedded/scoped contexts.\n // But hey, it's part of the spec, so we have no choice...\n // https://w3c.github.io/json-ld-api/#h-note-10\n if (this.validateContext) {\n try {\n const parentContext = Object.assign(Object.assign({}, context), { [key]: Object.assign({}, context[key]) });\n delete parentContext[key]['@context'];\n await this.parse(value['@context'], Object.assign(Object.assign({}, options), { external: false, parentContext, ignoreProtection: true, ignoreRemoteScopedContexts: true, ignoreScopedContexts: true }));\n }\n catch (e) {\n throw new ErrorCoded_1.ErrorCoded(e.message, ErrorCoded_1.ERROR_CODES.INVALID_SCOPED_CONTEXT);\n }\n }\n context[key] = Object.assign(Object.assign({}, value), { '@context': (await this.parse(value['@context'], Object.assign(Object.assign({}, options), { external: false, minimalProcessing: true, ignoreRemoteScopedContexts: true, parentContext: context })))\n .getContextRaw() });\n }\n }\n }\n return context;\n }\n async parse(context, options = {}, \n // These options are only for internal use on recursive calls and should not be used by\n // libraries consuming this function\n internalOptions = {}) {\n const { baseIRI, parentContext, external, processingMode = ContextParser.DEFAULT_PROCESSING_MODE, normalizeLanguageTags, ignoreProtection, minimalProcessing, } = options;\n const remoteContexts = options.remoteContexts || {};\n // Avoid remote context overflows\n if (Object.keys(remoteContexts).length >= this.remoteContextsDepthLimit) {\n throw new ErrorCoded_1.ErrorCoded('Detected an overflow in remote context inclusions: ' + Object.keys(remoteContexts), ErrorCoded_1.ERROR_CODES.CONTEXT_OVERFLOW);\n }\n if (context === null || context === undefined) {\n // Don't allow context nullification and there are protected terms\n if (!ignoreProtection && parentContext && Util_1.Util.hasProtectedTerms(parentContext)) {\n throw new ErrorCoded_1.ErrorCoded('Illegal context nullification when terms are protected', ErrorCoded_1.ERROR_CODES.INVALID_CONTEXT_NULLIFICATION);\n }\n // Context that are explicitly set to null are empty.\n return new JsonLdContextNormalized_1.JsonLdContextNormalized(this.applyBaseEntry({}, options, false));\n }\n else if (typeof context === 'string') {\n const contextIri = this.normalizeContextIri(context, baseIRI);\n const overriddenLoad = this.getOverriddenLoad(contextIri, options);\n if (overriddenLoad) {\n return new JsonLdContextNormalized_1.JsonLdContextNormalized(overriddenLoad);\n }\n const parsedStringContext = await this.parse(await this.load(contextIri), Object.assign(Object.assign({}, options), { baseIRI: contextIri, external: true, remoteContexts: Object.assign(Object.assign({}, remoteContexts), { [contextIri]: true }) }));\n this.applyBaseEntry(parsedStringContext.getContextRaw(), options, true);\n return parsedStringContext;\n }\n else if (Array.isArray(context)) {\n // As a performance consideration, first load all external contexts in parallel.\n const contextIris = [];\n const contexts = await Promise.all(context.map((subContext, i) => {\n if (typeof subContext === 'string') {\n const contextIri = this.normalizeContextIri(subContext, baseIRI);\n contextIris[i] = contextIri;\n const overriddenLoad = this.getOverriddenLoad(contextIri, options);\n if (overriddenLoad) {\n return overriddenLoad;\n }\n return this.load(contextIri);\n }\n else {\n return subContext;\n }\n }));\n // Don't apply inheritance logic on minimal processing\n if (minimalProcessing) {\n return new JsonLdContextNormalized_1.JsonLdContextNormalized(contexts);\n }\n const reducedContexts = await contexts.reduce((accContextPromise, contextEntry, i) => accContextPromise\n .then((accContext) => this.parse(contextEntry, Object.assign(Object.assign({}, options), { baseIRI: contextIris[i] || options.baseIRI, external: !!contextIris[i] || options.external, parentContext: accContext.getContextRaw(), remoteContexts: contextIris[i] ? Object.assign(Object.assign({}, remoteContexts), { [contextIris[i]]: true }) : remoteContexts }), \n // @ts-expect-error: This third argument causes a type error because we have hidden it from consumers\n {\n skipValidation: i < contexts.length - 1,\n })), Promise.resolve(new JsonLdContextNormalized_1.JsonLdContextNormalized(parentContext || {})));\n // Override the base IRI if provided.\n this.applyBaseEntry(reducedContexts.getContextRaw(), options, true);\n return reducedContexts;\n }\n else if (typeof context === 'object') {\n if ('@context' in context) {\n return await this.parse(context['@context'], options);\n }\n // Make a deep clone of the given context, to avoid modifying it.\n context = Object.assign({}, context);\n // According to the JSON-LD spec, @base must be ignored from external contexts.\n if (external) {\n delete context['@base'];\n }\n // Override the base IRI if provided.\n this.applyBaseEntry(context, options, true);\n // Hashify container entries\n // Do this before protected term validation as that influences term format\n this.containersToHash(context);\n // Don't perform any other modifications if only minimal processing is needed.\n if (minimalProcessing) {\n return new JsonLdContextNormalized_1.JsonLdContextNormalized(context);\n }\n // In JSON-LD 1.1, load @import'ed context prior to processing.\n let importContext = {};\n if ('@import' in context) {\n if (processingMode >= 1.1) {\n // Only accept string values\n if (typeof context['@import'] !== 'string') {\n throw new ErrorCoded_1.ErrorCoded('An @import value must be a string, but got ' + typeof context['@import'], ErrorCoded_1.ERROR_CODES.INVALID_IMPORT_VALUE);\n }\n // Load context\n importContext = await this.loadImportContext(this.normalizeContextIri(context['@import'], baseIRI));\n delete context['@import'];\n }\n else {\n throw new ErrorCoded_1.ErrorCoded('Context importing is not supported in JSON-LD 1.0', ErrorCoded_1.ERROR_CODES.INVALID_CONTEXT_ENTRY);\n }\n }\n this.applyScopedProtected(importContext, { processingMode }, JsonLdContextNormalized_1.defaultExpandOptions);\n const newContext = Object.assign(importContext, context);\n // Handle terms (before protection checks)\n this.idifyReverseTerms(newContext);\n this.normalize(newContext, { processingMode, normalizeLanguageTags });\n this.applyScopedProtected(newContext, { processingMode }, JsonLdContextNormalized_1.defaultExpandOptions);\n const keys = Object.keys(newContext);\n const overlappingKeys = [];\n if (typeof parentContext === 'object') {\n // Merge different parts of the final context in order\n for (const key in parentContext) {\n if (key in newContext) {\n overlappingKeys.push(key);\n }\n else {\n newContext[key] = parentContext[key];\n }\n }\n }\n // Parse inner contexts with minimal processing\n await this.parseInnerContexts(newContext, options, keys);\n const newContextWrapped = new JsonLdContextNormalized_1.JsonLdContextNormalized(newContext);\n // In JSON-LD 1.1, @vocab can be relative to @vocab in the parent context, or a compact IRI.\n if ((newContext && newContext['@version'] || ContextParser.DEFAULT_PROCESSING_MODE) >= 1.1\n && ((context['@vocab'] && typeof context['@vocab'] === 'string') || context['@vocab'] === '')) {\n if (parentContext && '@vocab' in parentContext && context['@vocab'].indexOf(':') < 0) {\n newContext['@vocab'] = parentContext['@vocab'] + context['@vocab'];\n }\n else if (Util_1.Util.isCompactIri(context['@vocab']) || context['@vocab'] in newContext) {\n // @vocab is a compact IRI or refers exactly to a prefix\n newContext['@vocab'] = newContextWrapped.expandTerm(context['@vocab'], true);\n }\n }\n this.expandPrefixedTerms(newContextWrapped, this.expandContentTypeToBase, keys);\n // In JSON-LD 1.1, check if we are not redefining any protected keywords\n if (!ignoreProtection && parentContext && processingMode >= 1.1) {\n this.validateKeywordRedefinitions(parentContext, newContext, JsonLdContextNormalized_1.defaultExpandOptions, overlappingKeys);\n }\n if (this.validateContext && !internalOptions.skipValidation) {\n this.validate(newContext, { processingMode });\n }\n return newContextWrapped;\n }\n else {\n throw new ErrorCoded_1.ErrorCoded(`Tried parsing a context that is not a string, array or object, but got ${context}`, ErrorCoded_1.ERROR_CODES.INVALID_LOCAL_CONTEXT);\n }\n }\n /**\n * Fetch the given URL as a raw JSON-LD context.\n * @param url An URL.\n * @return A promise resolving to a raw JSON-LD context.\n */\n async load(url) {\n // First try to retrieve the context from cache\n const cached = this.documentCache[url];\n if (cached) {\n return cached;\n }\n // If not in cache, load it\n let document;\n try {\n document = await this.documentLoader.load(url);\n }\n catch (e) {\n throw new ErrorCoded_1.ErrorCoded(`Failed to load remote context ${url}: ${e.message}`, ErrorCoded_1.ERROR_CODES.LOADING_REMOTE_CONTEXT_FAILED);\n }\n // Validate the context\n if (!('@context' in document)) {\n throw new ErrorCoded_1.ErrorCoded(`Missing @context in remote context at ${url}`, ErrorCoded_1.ERROR_CODES.INVALID_REMOTE_CONTEXT);\n }\n return this.documentCache[url] = document['@context'];\n }\n /**\n * Override the given context that may be loaded.\n *\n * This will check whether or not the url is recursively being loaded.\n * @param url An URL.\n * @param options Parsing options.\n * @return An overridden context, or null.\n * Optionally an error can be thrown if a cyclic context is detected.\n */\n getOverriddenLoad(url, options) {\n if (url in (options.remoteContexts || {})) {\n if (options.ignoreRemoteScopedContexts) {\n return url;\n }\n else {\n throw new ErrorCoded_1.ErrorCoded('Detected a cyclic context inclusion of ' + url, ErrorCoded_1.ERROR_CODES.RECURSIVE_CONTEXT_INCLUSION);\n }\n }\n return null;\n }\n /**\n * Load an @import'ed context.\n * @param importContextIri The full URI of an @import value.\n */\n async loadImportContext(importContextIri) {\n // Load the context - and do a deep clone since we are about to mutate it\n let importContext = await this.load(importContextIri);\n // Require the context to be a non-array object\n if (typeof importContext !== 'object' || Array.isArray(importContext)) {\n throw new ErrorCoded_1.ErrorCoded('An imported context must be a single object: ' + importContextIri, ErrorCoded_1.ERROR_CODES.INVALID_REMOTE_CONTEXT);\n }\n // Error if the context contains another @import\n if ('@import' in importContext) {\n throw new ErrorCoded_1.ErrorCoded('An imported context can not import another context: ' + importContextIri, ErrorCoded_1.ERROR_CODES.INVALID_CONTEXT_ENTRY);\n }\n importContext = Object.assign({}, importContext);\n // Containers have to be converted into hash values the same way as for the importing context\n // Otherwise context validation will fail for container values\n this.containersToHash(importContext);\n return importContext;\n }\n}\nContextParser.DEFAULT_PROCESSING_MODE = 1.1;\nexports.ContextParser = ContextParser;\n//# sourceMappingURL=ContextParser.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ERROR_CODES = exports.ErrorCoded = void 0;\n/**\n * An error that has a certain error code.\n *\n * The error code can be any string.\n * All standardized error codes are listed in {@link ERROR_CODES}.\n */\nclass ErrorCoded extends Error {\n /* istanbul ignore next */\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\nexports.ErrorCoded = ErrorCoded;\n/**\n * All standardized JSON-LD error codes.\n * @see https://w3c.github.io/json-ld-api/#dom-jsonlderrorcode\n */\n// tslint:disable:object-literal-sort-keys\nvar ERROR_CODES;\n(function (ERROR_CODES) {\n ERROR_CODES[\"COLLIDING_KEYWORDS\"] = \"colliding keywords\";\n ERROR_CODES[\"CONFLICTING_INDEXES\"] = \"conflicting indexes\";\n ERROR_CODES[\"CYCLIC_IRI_MAPPING\"] = \"cyclic IRI mapping\";\n ERROR_CODES[\"INVALID_ID_VALUE\"] = \"invalid @id value\";\n ERROR_CODES[\"INVALID_INDEX_VALUE\"] = \"invalid @index value\";\n ERROR_CODES[\"INVALID_NEST_VALUE\"] = \"invalid @nest value\";\n ERROR_CODES[\"INVALID_PREFIX_VALUE\"] = \"invalid @prefix value\";\n ERROR_CODES[\"INVALID_PROPAGATE_VALUE\"] = \"invalid @propagate value\";\n ERROR_CODES[\"INVALID_REVERSE_VALUE\"] = \"invalid @reverse value\";\n ERROR_CODES[\"INVALID_IMPORT_VALUE\"] = \"invalid @import value\";\n ERROR_CODES[\"INVALID_VERSION_VALUE\"] = \"invalid @version value\";\n ERROR_CODES[\"INVALID_BASE_IRI\"] = \"invalid base IRI\";\n ERROR_CODES[\"INVALID_CONTAINER_MAPPING\"] = \"invalid container mapping\";\n ERROR_CODES[\"INVALID_CONTEXT_ENTRY\"] = \"invalid context entry\";\n ERROR_CODES[\"INVALID_CONTEXT_NULLIFICATION\"] = \"invalid context nullification\";\n ERROR_CODES[\"INVALID_DEFAULT_LANGUAGE\"] = \"invalid default language\";\n ERROR_CODES[\"INVALID_INCLUDED_VALUE\"] = \"invalid @included value\";\n ERROR_CODES[\"INVALID_IRI_MAPPING\"] = \"invalid IRI mapping\";\n ERROR_CODES[\"INVALID_JSON_LITERAL\"] = \"invalid JSON literal\";\n ERROR_CODES[\"INVALID_KEYWORD_ALIAS\"] = \"invalid keyword alias\";\n ERROR_CODES[\"INVALID_LANGUAGE_MAP_VALUE\"] = \"invalid language map value\";\n ERROR_CODES[\"INVALID_LANGUAGE_MAPPING\"] = \"invalid language mapping\";\n ERROR_CODES[\"INVALID_LANGUAGE_TAGGED_STRING\"] = \"invalid language-tagged string\";\n ERROR_CODES[\"INVALID_LANGUAGE_TAGGED_VALUE\"] = \"invalid language-tagged value\";\n ERROR_CODES[\"INVALID_LOCAL_CONTEXT\"] = \"invalid local context\";\n ERROR_CODES[\"INVALID_REMOTE_CONTEXT\"] = \"invalid remote context\";\n ERROR_CODES[\"INVALID_REVERSE_PROPERTY\"] = \"invalid reverse property\";\n ERROR_CODES[\"INVALID_REVERSE_PROPERTY_MAP\"] = \"invalid reverse property map\";\n ERROR_CODES[\"INVALID_REVERSE_PROPERTY_VALUE\"] = \"invalid reverse property value\";\n ERROR_CODES[\"INVALID_SCOPED_CONTEXT\"] = \"invalid scoped context\";\n ERROR_CODES[\"INVALID_SCRIPT_ELEMENT\"] = \"invalid script element\";\n ERROR_CODES[\"INVALID_SET_OR_LIST_OBJECT\"] = \"invalid set or list object\";\n ERROR_CODES[\"INVALID_TERM_DEFINITION\"] = \"invalid term definition\";\n ERROR_CODES[\"INVALID_TYPE_MAPPING\"] = \"invalid type mapping\";\n ERROR_CODES[\"INVALID_TYPE_VALUE\"] = \"invalid type value\";\n ERROR_CODES[\"INVALID_TYPED_VALUE\"] = \"invalid typed value\";\n ERROR_CODES[\"INVALID_VALUE_OBJECT\"] = \"invalid value object\";\n ERROR_CODES[\"INVALID_VALUE_OBJECT_VALUE\"] = \"invalid value object value\";\n ERROR_CODES[\"INVALID_VOCAB_MAPPING\"] = \"invalid vocab mapping\";\n ERROR_CODES[\"IRI_CONFUSED_WITH_PREFIX\"] = \"IRI confused with prefix\";\n ERROR_CODES[\"KEYWORD_REDEFINITION\"] = \"keyword redefinition\";\n ERROR_CODES[\"LOADING_DOCUMENT_FAILED\"] = \"loading document failed\";\n ERROR_CODES[\"LOADING_REMOTE_CONTEXT_FAILED\"] = \"loading remote context failed\";\n ERROR_CODES[\"MULTIPLE_CONTEXT_LINK_HEADERS\"] = \"multiple context link headers\";\n ERROR_CODES[\"PROCESSING_MODE_CONFLICT\"] = \"processing mode conflict\";\n ERROR_CODES[\"PROTECTED_TERM_REDEFINITION\"] = \"protected term redefinition\";\n ERROR_CODES[\"CONTEXT_OVERFLOW\"] = \"context overflow\";\n ERROR_CODES[\"INVALID_BASE_DIRECTION\"] = \"invalid base direction\";\n ERROR_CODES[\"RECURSIVE_CONTEXT_INCLUSION\"] = \"recursive context inclusion\";\n ERROR_CODES[\"INVALID_STREAMING_KEY_ORDER\"] = \"invalid streaming key order\";\n /**\n * JSON-LD-star\n */\n ERROR_CODES[\"INVALID_EMBEDDED_NODE\"] = \"invalid embedded node\";\n ERROR_CODES[\"INVALID_ANNOTATION\"] = \"invalid annotation\";\n})(ERROR_CODES = exports.ERROR_CODES || (exports.ERROR_CODES = {}));\n//# sourceMappingURL=ErrorCoded.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FetchDocumentLoader = void 0;\nrequire(\"cross-fetch/polyfill\");\nconst ErrorCoded_1 = require(\"./ErrorCoded\");\nconst http_link_header_1 = require(\"http-link-header\");\nconst relative_to_absolute_iri_1 = require(\"relative-to-absolute-iri\");\n/**\n * Loads documents via the fetch API.\n */\nclass FetchDocumentLoader {\n constructor(fetcher) {\n this.fetcher = fetcher;\n }\n async load(url) {\n const response = await (this.fetcher || fetch)(url, { headers: new Headers({ accept: 'application/ld+json' }) });\n if (response.ok && response.headers) {\n let mediaType = response.headers.get('Content-Type');\n if (mediaType) {\n const colonPos = mediaType.indexOf(';');\n if (colonPos > 0) {\n mediaType = mediaType.substr(0, colonPos);\n }\n }\n if (mediaType === 'application/ld+json') {\n // Return JSON-LD if proper content type was returned\n return (await response.json());\n }\n else {\n // Check for alternate link for a non-JSON-LD response\n if (response.headers.has('Link')) {\n let alternateUrl;\n response.headers.forEach((value, key) => {\n if (key === 'link') {\n const linkHeader = (0, http_link_header_1.parse)(value);\n for (const link of linkHeader.get('type', 'application/ld+json')) {\n if (link.rel === 'alternate') {\n if (alternateUrl) {\n throw new Error('Multiple JSON-LD alternate links were found on ' + url);\n }\n alternateUrl = (0, relative_to_absolute_iri_1.resolve)(link.uri, url);\n }\n }\n }\n });\n if (alternateUrl) {\n return this.load(alternateUrl);\n }\n }\n throw new ErrorCoded_1.ErrorCoded(`Unsupported JSON-LD media type ${mediaType}`, ErrorCoded_1.ERROR_CODES.LOADING_DOCUMENT_FAILED);\n }\n }\n else {\n throw new Error(response.statusText || `Status code: ${response.status}`);\n }\n }\n}\nexports.FetchDocumentLoader = FetchDocumentLoader;\n//# sourceMappingURL=FetchDocumentLoader.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=IDocumentLoader.js.map","\"use strict\";\n// tslint:disable:max-line-length\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=JsonLdContext.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.defaultExpandOptions = exports.JsonLdContextNormalized = void 0;\nconst relative_to_absolute_iri_1 = require(\"relative-to-absolute-iri\");\nconst ErrorCoded_1 = require(\"./ErrorCoded\");\nconst Util_1 = require(\"./Util\");\n/**\n * A class exposing operations over a normalized JSON-LD context.\n */\nclass JsonLdContextNormalized {\n constructor(contextRaw) {\n this.contextRaw = contextRaw;\n }\n /**\n * @return The raw inner context.\n */\n getContextRaw() {\n return this.contextRaw;\n }\n /**\n * Expand the term or prefix of the given term if it has one,\n * otherwise return the term as-is.\n *\n * This will try to expand the IRI as much as possible.\n *\n * Iff in vocab-mode, then other references to other terms in the context can be used,\n * such as to `myTerm`:\n * ```\n * {\n * \"myTerm\": \"http://example.org/myLongTerm\"\n * }\n * ```\n *\n * @param {string} term A term that is an URL or a prefixed URL.\n * @param {boolean} expandVocab If the term is a predicate or type and should be expanded based on @vocab,\n * otherwise it is considered a regular term that is expanded based on @base.\n * @param {IExpandOptions} options Options that define the way how expansion must be done.\n * @return {string} The expanded term, the term as-is, or null if it was explicitly disabled in the context.\n * @throws If the term is aliased to an invalid value (not a string, IRI or keyword).\n */\n expandTerm(term, expandVocab, options = exports.defaultExpandOptions) {\n const contextValue = this.contextRaw[term];\n // Immediately return if the term was disabled in the context\n if (contextValue === null || (contextValue && contextValue['@id'] === null)) {\n return null;\n }\n // Check the @id\n let validIriMapping = true;\n if (contextValue && expandVocab) {\n const value = Util_1.Util.getContextValueId(contextValue);\n if (value && value !== term) {\n if (typeof value !== 'string' || (!Util_1.Util.isValidIri(value) && !Util_1.Util.isValidKeyword(value))) {\n // Don't mark this mapping as invalid if we have an unknown keyword, but of the correct form.\n if (!Util_1.Util.isPotentialKeyword(value)) {\n validIriMapping = false;\n }\n }\n else {\n return value;\n }\n }\n }\n // Check if the term is prefixed\n const prefix = Util_1.Util.getPrefix(term, this.contextRaw);\n const vocab = this.contextRaw['@vocab'];\n const vocabRelative = (!!vocab || vocab === '') && vocab.indexOf(':') < 0;\n const base = this.contextRaw['@base'];\n const potentialKeyword = Util_1.Util.isPotentialKeyword(term);\n if (prefix) {\n const contextPrefixValue = this.contextRaw[prefix];\n const value = Util_1.Util.getContextValueId(contextPrefixValue);\n if (value) {\n if (typeof contextPrefixValue === 'string' || !options.allowPrefixForcing) {\n // If we have a simple term definition,\n // check the last character of the prefix to determine whether or not it is a prefix.\n // Validate that prefix ends with gen-delim character, unless @prefix is true\n if (!Util_1.Util.isSimpleTermDefinitionPrefix(value, options)) {\n // Treat the term as an absolute IRI\n return term;\n }\n }\n else {\n // If we have an expanded term definition, default to @prefix: false\n if (value[0] !== '_' && !potentialKeyword && !contextPrefixValue['@prefix'] && !(term in this.contextRaw)) {\n // Treat the term as an absolute IRI\n return term;\n }\n }\n return value + term.substr(prefix.length + 1);\n }\n }\n else if (expandVocab && ((vocab || vocab === '') || (options.allowVocabRelativeToBase && (base && vocabRelative)))\n && !potentialKeyword && !Util_1.Util.isCompactIri(term)) {\n if (vocabRelative) {\n if (options.allowVocabRelativeToBase) {\n return ((vocab || base) ? (0, relative_to_absolute_iri_1.resolve)(vocab, base) : '') + term;\n }\n else {\n throw new ErrorCoded_1.ErrorCoded(`Relative vocab expansion for term '${term}' with vocab '${vocab}' is not allowed.`, ErrorCoded_1.ERROR_CODES.INVALID_VOCAB_MAPPING);\n }\n }\n else {\n return vocab + term;\n }\n }\n else if (!expandVocab && base && !potentialKeyword && !Util_1.Util.isCompactIri(term)) {\n return (0, relative_to_absolute_iri_1.resolve)(term, base);\n }\n // Return the term as-is, unless we discovered an invalid IRI mapping for this term in the context earlier.\n if (validIriMapping) {\n return term;\n }\n else {\n throw new ErrorCoded_1.ErrorCoded(`Invalid IRI mapping found for context entry '${term}': '${JSON.stringify(contextValue)}'`, ErrorCoded_1.ERROR_CODES.INVALID_IRI_MAPPING);\n }\n }\n /**\n * Compact the given term using @base, @vocab, an aliased term, or a prefixed term.\n *\n * This will try to compact the IRI as much as possible.\n *\n * @param {string} iri An IRI to compact.\n * @param {boolean} vocab If the term is a predicate or type and should be compacted based on @vocab,\n * otherwise it is considered a regular term that is compacted based on @base.\n * @return {string} The compacted term or the IRI as-is.\n */\n compactIri(iri, vocab) {\n // Try @vocab compacting\n if (vocab && this.contextRaw['@vocab'] && iri.startsWith(this.contextRaw['@vocab'])) {\n return iri.substr(this.contextRaw['@vocab'].length);\n }\n // Try @base compacting\n if (!vocab && this.contextRaw['@base'] && iri.startsWith(this.contextRaw['@base'])) {\n return iri.substr(this.contextRaw['@base'].length);\n }\n // Loop over all terms in the context\n // This will try to prefix as short as possible.\n // Once a fully compacted alias is found, return immediately, as we can not go any shorter.\n const shortestPrefixing = { prefix: '', suffix: iri };\n for (const key in this.contextRaw) {\n const value = this.contextRaw[key];\n if (value && !Util_1.Util.isPotentialKeyword(key)) {\n const contextIri = Util_1.Util.getContextValueId(value);\n if (iri.startsWith(contextIri)) {\n const suffix = iri.substr(contextIri.length);\n if (!suffix) {\n if (vocab) {\n // Immediately return on compacted alias\n return key;\n }\n }\n else if (suffix.length < shortestPrefixing.suffix.length) {\n // Overwrite the shortest prefix\n shortestPrefixing.prefix = key;\n shortestPrefixing.suffix = suffix;\n }\n }\n }\n }\n // Return the shortest prefix\n if (shortestPrefixing.prefix) {\n return shortestPrefixing.prefix + ':' + shortestPrefixing.suffix;\n }\n return iri;\n }\n}\nexports.JsonLdContextNormalized = JsonLdContextNormalized;\nexports.defaultExpandOptions = {\n allowPrefixForcing: true,\n allowPrefixNonGenDelims: false,\n allowVocabRelativeToBase: true,\n};\n//# sourceMappingURL=JsonLdContextNormalized.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Util = void 0;\nclass Util {\n /**\n * Check if the given term is a valid compact IRI.\n * Otherwise, it may be an IRI.\n * @param {string} term A term.\n * @return {boolean} If it is a compact IRI.\n */\n static isCompactIri(term) {\n return term.indexOf(':') > 0 && !(term && term[0] === '#');\n }\n /**\n * Get the prefix from the given term.\n * @see https://json-ld.org/spec/latest/json-ld/#compact-iris\n * @param {string} term A term that is an URL or a prefixed URL.\n * @param {IJsonLdContextNormalizedRaw} context A context.\n * @return {string} The prefix or null.\n */\n static getPrefix(term, context) {\n // Do not consider relative IRIs starting with a hash as compact IRIs\n if (term && term[0] === '#') {\n return null;\n }\n const separatorPos = term.indexOf(':');\n if (separatorPos >= 0) {\n // Suffix can not begin with two slashes\n if (term.length > separatorPos + 1\n && term.charAt(separatorPos + 1) === '/'\n && term.charAt(separatorPos + 2) === '/') {\n return null;\n }\n const prefix = term.substr(0, separatorPos);\n // Prefix can not be an underscore (this is a blank node)\n if (prefix === '_') {\n return null;\n }\n // Prefix must match a term in the active context\n if (context[prefix]) {\n return prefix;\n }\n }\n return null;\n }\n /**\n * From a given context entry value, get the string value, or the @id field.\n * @param contextValue A value for a term in a context.\n * @return {string} The id value, or null.\n */\n static getContextValueId(contextValue) {\n if (contextValue === null || typeof contextValue === 'string') {\n return contextValue;\n }\n const id = contextValue['@id'];\n return id ? id : null;\n }\n /**\n * Check if the given simple term definition (string-based value of a context term)\n * should be considered a prefix.\n * @param value A simple term definition value.\n * @param options Options that define the way how expansion must be done.\n */\n static isSimpleTermDefinitionPrefix(value, options) {\n return !Util.isPotentialKeyword(value)\n && (options.allowPrefixNonGenDelims || (typeof value === 'string' && (value[0] === '_' || Util.isPrefixIriEndingWithGenDelim(value))));\n }\n /**\n * Check if the given keyword is of the keyword format \"@\"1*ALPHA.\n * @param {string} keyword A potential keyword.\n * @return {boolean} If the given keyword is of the keyword format.\n */\n static isPotentialKeyword(keyword) {\n return typeof keyword === 'string' && Util.KEYWORD_REGEX.test(keyword);\n }\n /**\n * Check if the given prefix ends with a gen-delim character.\n * @param {string} prefixIri A prefix IRI.\n * @return {boolean} If the given prefix IRI is valid.\n */\n static isPrefixIriEndingWithGenDelim(prefixIri) {\n return Util.ENDS_WITH_GEN_DELIM.test(prefixIri);\n }\n /**\n * Check if the given context value can be a prefix value.\n * @param value A context value.\n * @return {boolean} If it can be a prefix value.\n */\n static isPrefixValue(value) {\n return value && (typeof value === 'string' || (value && typeof value === 'object'));\n }\n /**\n * Check if the given IRI is valid.\n * @param {string} iri A potential IRI.\n * @return {boolean} If the given IRI is valid.\n */\n static isValidIri(iri) {\n return Boolean(iri && Util.IRI_REGEX.test(iri));\n }\n /**\n * Check if the given IRI is valid, this includes the possibility of being a relative IRI.\n * @param {string} iri A potential IRI.\n * @return {boolean} If the given IRI is valid.\n */\n static isValidIriWeak(iri) {\n return !!iri && iri[0] !== ':' && Util.IRI_REGEX_WEAK.test(iri);\n }\n /**\n * Check if the given keyword is a defined according to the JSON-LD specification.\n * @param {string} keyword A potential keyword.\n * @return {boolean} If the given keyword is valid.\n */\n static isValidKeyword(keyword) {\n return Util.VALID_KEYWORDS[keyword];\n }\n /**\n * Check if the given term is protected in the context.\n * @param {IJsonLdContextNormalizedRaw} context A context.\n * @param {string} key A context term.\n * @return {boolean} If the given term has an @protected flag.\n */\n static isTermProtected(context, key) {\n const value = context[key];\n return !(typeof value === 'string') && value && value['@protected'];\n }\n /**\n * Check if the given context has at least one protected term.\n * @param context A context.\n * @return If the context has a protected term.\n */\n static hasProtectedTerms(context) {\n for (const key of Object.keys(context)) {\n if (Util.isTermProtected(context, key)) {\n return true;\n }\n }\n return false;\n }\n /**\n * Check if the given key is an internal reserved keyword.\n * @param key A context key.\n */\n static isReservedInternalKeyword(key) {\n return key.startsWith('@__');\n }\n /**\n * Check if two objects are deepEqual to on another.\n * @param object1 The first object to test.\n * @param object2 The second object to test.\n */\n static deepEqual(object1, object2) {\n const objKeys1 = Object.keys(object1);\n const objKeys2 = Object.keys(object2);\n if (objKeys1.length !== objKeys2.length)\n return false;\n return objKeys1.every((key) => {\n const value1 = object1[key];\n const value2 = object2[key];\n return (value1 === value2) || (value1 !== null &&\n value2 !== null &&\n typeof value1 === \"object\" &&\n typeof value2 === \"object\" &&\n this.deepEqual(value1, value2));\n });\n }\n ;\n}\n// Regex for valid IRIs\nUtil.IRI_REGEX = /^([A-Za-z][A-Za-z0-9+-.]*|_):[^ \"<>{}|\\\\\\[\\]`#]*(#[^#]*)?$/;\n// Weaker regex for valid IRIs, this includes relative IRIs\nUtil.IRI_REGEX_WEAK = /(?::[^:])|\\//;\n// Regex for keyword form\nUtil.KEYWORD_REGEX = /^@[a-z]+$/i;\n// Regex to see if an IRI ends with a gen-delim character (see RFC 3986)\nUtil.ENDS_WITH_GEN_DELIM = /[:/?#\\[\\]@]$/;\n// Regex for language tags\nUtil.REGEX_LANGUAGE_TAG = /^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/;\n// Regex for base directions\nUtil.REGEX_DIRECTION_TAG = /^(ltr)|(rtl)$/;\n// All known valid JSON-LD keywords\n// @see https://www.w3.org/TR/json-ld11/#keywords\nUtil.VALID_KEYWORDS = {\n '@annotation': true,\n '@base': true,\n '@container': true,\n '@context': true,\n '@direction': true,\n '@graph': true,\n '@id': true,\n '@import': true,\n '@included': true,\n '@index': true,\n '@json': true,\n '@language': true,\n '@list': true,\n '@nest': true,\n '@none': true,\n '@prefix': true,\n '@propagate': true,\n '@protected': true,\n '@reverse': true,\n '@set': true,\n '@type': true,\n '@value': true,\n '@version': true,\n '@vocab': true,\n};\n// Keys in the contexts that will not be expanded based on the base IRI\nUtil.EXPAND_KEYS_BLACKLIST = [\n '@base',\n '@vocab',\n '@language',\n '@version',\n '@direction',\n];\n// Keys in the contexts that may not be aliased from\nUtil.ALIAS_DOMAIN_BLACKLIST = [\n '@container',\n '@graph',\n '@id',\n '@index',\n '@list',\n '@nest',\n '@none',\n '@prefix',\n '@reverse',\n '@set',\n '@type',\n '@value',\n '@version',\n];\n// Keys in the contexts that may not be aliased to\nUtil.ALIAS_RANGE_BLACKLIST = [\n '@context',\n '@preserve',\n];\n// All valid @container values\nUtil.CONTAINERS = [\n '@list',\n '@set',\n '@index',\n '@language',\n '@graph',\n '@id',\n '@type',\n];\n// All valid @container values under processing mode 1.0\nUtil.CONTAINERS_1_0 = [\n '@list',\n '@set',\n '@index',\n];\nexports.Util = Util;\n//# sourceMappingURL=Util.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./lib/JsonLdParser\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ContextTree = void 0;\n/**\n * A tree structure that holds all contexts,\n * based on their position in the JSON object.\n *\n * Positions are identified by a path of keys.\n */\nclass ContextTree {\n constructor() {\n this.subTrees = {};\n }\n getContext(keys) {\n if (keys.length > 0) {\n const [head, ...tail] = keys;\n const subTree = this.subTrees[head];\n if (subTree) {\n const subContext = subTree.getContext(tail);\n if (subContext) {\n return subContext.then(({ context, depth }) => ({ context, depth: depth + 1 }));\n }\n }\n }\n return this.context ? this.context.then((context) => ({ context, depth: 0 })) : null;\n }\n setContext(keys, context) {\n if (keys.length === 0) {\n this.context = context;\n }\n else {\n const [head, ...tail] = keys;\n let subTree = this.subTrees[head];\n if (!subTree) {\n subTree = this.subTrees[head] = new ContextTree();\n }\n subTree.setContext(tail, context);\n }\n }\n removeContext(path) {\n this.setContext(path, null);\n }\n}\nexports.ContextTree = ContextTree;\n//# sourceMappingURL=ContextTree.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.JsonLdParser = void 0;\n// tslint:disable-next-line:no-var-requires\nconst Parser = require('@bergos/jsonparse');\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\nconst readable_stream_1 = require(\"readable-stream\");\nconst EntryHandlerArrayValue_1 = require(\"./entryhandler/EntryHandlerArrayValue\");\nconst EntryHandlerContainer_1 = require(\"./entryhandler/EntryHandlerContainer\");\nconst EntryHandlerInvalidFallback_1 = require(\"./entryhandler/EntryHandlerInvalidFallback\");\nconst EntryHandlerPredicate_1 = require(\"./entryhandler/EntryHandlerPredicate\");\nconst EntryHandlerKeywordContext_1 = require(\"./entryhandler/keyword/EntryHandlerKeywordContext\");\nconst EntryHandlerKeywordGraph_1 = require(\"./entryhandler/keyword/EntryHandlerKeywordGraph\");\nconst EntryHandlerKeywordId_1 = require(\"./entryhandler/keyword/EntryHandlerKeywordId\");\nconst EntryHandlerKeywordIncluded_1 = require(\"./entryhandler/keyword/EntryHandlerKeywordIncluded\");\nconst EntryHandlerKeywordNest_1 = require(\"./entryhandler/keyword/EntryHandlerKeywordNest\");\nconst EntryHandlerKeywordType_1 = require(\"./entryhandler/keyword/EntryHandlerKeywordType\");\nconst EntryHandlerKeywordUnknownFallback_1 = require(\"./entryhandler/keyword/EntryHandlerKeywordUnknownFallback\");\nconst EntryHandlerKeywordValue_1 = require(\"./entryhandler/keyword/EntryHandlerKeywordValue\");\nconst ParsingContext_1 = require(\"./ParsingContext\");\nconst Util_1 = require(\"./Util\");\nconst http_link_header_1 = require(\"http-link-header\");\nconst EntryHandlerKeywordAnnotation_1 = require(\"./entryhandler/keyword/EntryHandlerKeywordAnnotation\");\n/**\n * A stream transformer that parses JSON-LD (text) streams to an {@link RDF.Stream}.\n */\nclass JsonLdParser extends readable_stream_1.Transform {\n constructor(options) {\n super({ readableObjectMode: true });\n options = options || {};\n this.options = options;\n this.parsingContext = new ParsingContext_1.ParsingContext(Object.assign({ parser: this }, options));\n this.util = new Util_1.Util({ dataFactory: options.dataFactory, parsingContext: this.parsingContext });\n this.jsonParser = new Parser();\n this.contextJobs = [];\n this.typeJobs = [];\n this.contextAwaitingJobs = [];\n this.lastDepth = 0;\n this.lastKeys = [];\n this.lastOnValueJob = Promise.resolve();\n this.attachJsonParserListeners();\n this.on('end', () => {\n if (typeof this.jsonParser.mode !== 'undefined') {\n this.emit('error', new Error('Unclosed document'));\n }\n });\n }\n /**\n * Construct a JsonLdParser from the given HTTP response.\n *\n * This will throw an error if no valid JSON response is received\n * (application/ld+json, application/json, or something+json).\n *\n * For raw JSON responses, exactly one link header pointing to a JSON-LD context is required.\n *\n * This method is not responsible for handling redirects.\n *\n * @param baseIRI The URI of the received response.\n * @param mediaType The received content type.\n * @param headers Optional HTTP headers.\n * @param options Optional parser options.\n */\n static fromHttpResponse(baseIRI, mediaType, headers, options) {\n let context;\n let wellKnownMediaTypes = ['application/activity+json'];\n if (options && options.wellKnownMediaTypes) {\n wellKnownMediaTypes = options.wellKnownMediaTypes;\n }\n // Special cases when receiving something else than the JSON-LD media type or the wellKnownMediaTypes\n if (mediaType !== 'application/ld+json' && !wellKnownMediaTypes.includes(mediaType)) {\n // Only accept JSON or JSON extension types\n if (mediaType !== 'application/json' && !mediaType.endsWith('+json')) {\n throw new jsonld_context_parser_1.ErrorCoded(`Unsupported JSON-LD media type ${mediaType}`, jsonld_context_parser_1.ERROR_CODES.LOADING_DOCUMENT_FAILED);\n }\n // We need exactly one JSON-LD context in the link header\n if (headers && headers.has('Link')) {\n headers.forEach((value, key) => {\n if (key === 'link') {\n const linkHeader = (0, http_link_header_1.parse)(value);\n for (const link of linkHeader.get('rel', 'http://www.w3.org/ns/json-ld#context')) {\n if (context) {\n throw new jsonld_context_parser_1.ErrorCoded('Multiple JSON-LD context link headers were found on ' + baseIRI, jsonld_context_parser_1.ERROR_CODES.MULTIPLE_CONTEXT_LINK_HEADERS);\n }\n context = link.uri;\n }\n }\n });\n }\n if (!context && !(options === null || options === void 0 ? void 0 : options.ignoreMissingContextLinkHeader)) {\n throw new jsonld_context_parser_1.ErrorCoded(`Missing context link header for media type ${mediaType} on ${baseIRI}`, jsonld_context_parser_1.ERROR_CODES.LOADING_DOCUMENT_FAILED);\n }\n }\n // Check if the streaming profile is present\n let streamingProfile;\n if (headers && headers.has('Content-Type')) {\n const contentType = headers.get('Content-Type');\n const match = /; *profile=([^\"]*)/.exec(contentType);\n if (match && match[1] === 'http://www.w3.org/ns/json-ld#streaming') {\n streamingProfile = true;\n }\n }\n return new JsonLdParser(Object.assign({ baseIRI,\n context,\n streamingProfile }, options ? options : {}));\n }\n /**\n * Parses the given text stream into a quad stream.\n * @param {NodeJS.EventEmitter} stream A text stream.\n * @return {RDF.Stream} A quad stream.\n */\n import(stream) {\n if ('pipe' in stream) {\n stream.on('error', (error) => parsed.emit('error', error));\n const parsed = stream.pipe(new JsonLdParser(this.options));\n return parsed;\n }\n else {\n const output = new readable_stream_1.PassThrough({ readableObjectMode: true });\n stream.on('error', (error) => parsed.emit('error', error));\n stream.on('data', (data) => output.push(data));\n stream.on('end', () => output.push(null));\n const parsed = output.pipe(new JsonLdParser(this.options));\n return parsed;\n }\n }\n _transform(chunk, encoding, callback) {\n this.jsonParser.write(chunk);\n this.lastOnValueJob\n .then(() => callback(), (error) => callback(error));\n }\n /**\n * Start a new job for parsing the given value.\n *\n * This will let the first valid {@link IEntryHandler} handle the entry.\n *\n * @param {any[]} keys The stack of keys.\n * @param value The value to parse.\n * @param {number} depth The depth to parse at.\n * @param {boolean} lastDepthCheck If the lastDepth check should be done for buffer draining.\n * @return {Promise} A promise resolving when the job is done.\n */\n async newOnValueJob(keys, value, depth, lastDepthCheck) {\n let flushStacks = true;\n // When we go up the stack, emit all unidentified values\n // We need to do this before the new job, because the new job may require determined values from the flushed jobs.\n if (lastDepthCheck && depth < this.lastDepth) {\n // Check if we had any RDF lists that need to be terminated with an rdf:nil\n const listPointer = this.parsingContext.listPointerStack[this.lastDepth];\n if (listPointer) {\n // Terminate the list if the had at least one value\n if (listPointer.value) {\n this.push(this.util.dataFactory.quad(listPointer.value, this.util.rdfRest, this.util.rdfNil, this.util.getDefaultGraph()));\n }\n // Add the list id to the id stack, so it can be used higher up in the stack\n listPointer.listId.listHead = true;\n this.parsingContext.idStack[listPointer.listRootDepth + 1] = [listPointer.listId];\n this.parsingContext.listPointerStack.splice(this.lastDepth, 1);\n }\n // Flush the buffer for lastDepth\n // If the parent key is a special type of container, postpone flushing until that parent is handled.\n if (await EntryHandlerContainer_1.EntryHandlerContainer.isBufferableContainerHandler(this.parsingContext, this.lastKeys, this.lastDepth)) {\n this.parsingContext.pendingContainerFlushBuffers\n .push({ depth: this.lastDepth, keys: this.lastKeys.slice(0, this.lastKeys.length) });\n flushStacks = false;\n }\n else {\n await this.flushBuffer(this.lastDepth, this.lastKeys);\n }\n }\n const key = await this.util.unaliasKeyword(keys[depth], keys, depth);\n const parentKey = await this.util.unaliasKeywordParent(keys, depth);\n this.parsingContext.emittedStack[depth] = true;\n let handleKey = true;\n // Keywords inside @reverse is not allowed apart from @context\n if (jsonld_context_parser_1.Util.isValidKeyword(key) && parentKey === '@reverse' && key !== '@context') {\n this.emit('error', new jsonld_context_parser_1.ErrorCoded(`Found the @id '${value}' inside an @reverse property`, jsonld_context_parser_1.ERROR_CODES.INVALID_REVERSE_PROPERTY_MAP));\n }\n // Skip further processing if one of the parent nodes are invalid.\n // We use the validationStack to reuse validation results that were produced before with common key stacks.\n let inProperty = false;\n if (this.parsingContext.validationStack.length > 1) {\n inProperty = this.parsingContext.validationStack[this.parsingContext.validationStack.length - 1].property;\n }\n for (let i = Math.max(1, this.parsingContext.validationStack.length - 1); i < keys.length - 1; i++) {\n const validationResult = this.parsingContext.validationStack[i]\n || (this.parsingContext.validationStack[i] = await this.validateKey(keys.slice(0, i + 1), i, inProperty));\n if (!validationResult.valid) {\n this.parsingContext.emittedStack[depth] = false;\n handleKey = false;\n break;\n }\n else if (!inProperty && validationResult.property) {\n inProperty = true;\n }\n }\n // Skip further processing if this node is part of a literal\n if (await this.util.isLiteral(keys, depth)) {\n handleKey = false;\n }\n // Get handler\n if (handleKey) {\n for (const entryHandler of JsonLdParser.ENTRY_HANDLERS) {\n const testResult = await entryHandler.test(this.parsingContext, this.util, key, keys, depth);\n if (testResult) {\n // Pass processing over to the handler\n await entryHandler.handle(this.parsingContext, this.util, key, keys, value, depth, testResult);\n // Flag that this depth is processed\n if (entryHandler.isStackProcessor()) {\n this.parsingContext.processingStack[depth] = true;\n }\n break;\n }\n }\n }\n // Validate value indexes on the root.\n if (depth === 0 && Array.isArray(value)) {\n await this.util.validateValueIndexes(value);\n }\n // When we go up the stack, flush the old stack\n if (flushStacks && depth < this.lastDepth) {\n // Reset our stacks\n this.flushStacks(this.lastDepth);\n }\n this.lastDepth = depth;\n this.lastKeys = keys;\n // Clear the keyword cache at this depth, and everything underneath.\n this.parsingContext.unaliasedKeywordCacheStack.splice(depth - 1);\n }\n /**\n * Flush the processing stacks at the given depth.\n * @param {number} depth A depth.\n */\n flushStacks(depth) {\n this.parsingContext.processingStack.splice(depth, 1);\n this.parsingContext.processingType.splice(depth, 1);\n this.parsingContext.emittedStack.splice(depth, 1);\n this.parsingContext.idStack.splice(depth, 1);\n this.parsingContext.graphStack.splice(depth + 1, 1);\n this.parsingContext.graphContainerTermStack.splice(depth, 1);\n this.parsingContext.jsonLiteralStack.splice(depth, 1);\n this.parsingContext.validationStack.splice(depth - 1, 2);\n this.parsingContext.literalStack.splice(depth, this.parsingContext.literalStack.length - depth);\n this.parsingContext.annotationsBuffer.splice(depth, 1);\n // TODO: just like the literal stack, splice all other stack until the end as well?\n }\n /**\n * Flush buffers for the given depth.\n *\n * This should be called after the last entry at a given depth was processed.\n *\n * @param {number} depth A depth.\n * @param {any[]} keys A stack of keys.\n * @return {Promise} A promise resolving if flushing is done.\n */\n async flushBuffer(depth, keys) {\n let subjects = this.parsingContext.idStack[depth];\n const subjectsWasDefined = !!subjects;\n if (!subjectsWasDefined) {\n subjects = this.parsingContext.idStack[depth] = [this.util.dataFactory.blankNode()];\n }\n // Flush values at this level\n const valueBuffer = this.parsingContext.unidentifiedValuesBuffer[depth];\n if (valueBuffer) {\n for (const subject of subjects) {\n const depthOffsetGraph = await this.util.getDepthOffsetGraph(depth, keys);\n const graphs = (this.parsingContext.graphStack[depth] || depthOffsetGraph >= 0)\n ? this.parsingContext.idStack[depth - depthOffsetGraph - 1]\n : [await this.util.getGraphContainerValue(keys, depth)];\n if (graphs) {\n for (const graph of graphs) {\n // Flush values to stream if the graph @id is known\n this.parsingContext.emittedStack[depth] = true;\n for (const bufferedValue of valueBuffer) {\n this.util.emitQuadChecked(depth, subject, bufferedValue.predicate, bufferedValue.object, graph, bufferedValue.reverse, bufferedValue.isEmbedded);\n }\n }\n }\n else {\n // Place the values in the graphs buffer if the graph @id is not yet known\n const subGraphBuffer = this.parsingContext.getUnidentifiedGraphBufferSafe(depth - await this.util.getDepthOffsetGraph(depth, keys) - 1);\n for (const bufferedValue of valueBuffer) {\n if (bufferedValue.reverse) {\n subGraphBuffer.push({\n object: subject,\n predicate: bufferedValue.predicate,\n subject: bufferedValue.object,\n isEmbedded: bufferedValue.isEmbedded,\n });\n }\n else {\n subGraphBuffer.push({\n object: bufferedValue.object,\n predicate: bufferedValue.predicate,\n subject,\n isEmbedded: bufferedValue.isEmbedded,\n });\n }\n }\n }\n }\n this.parsingContext.unidentifiedValuesBuffer.splice(depth, 1);\n this.parsingContext.literalStack.splice(depth, 1);\n this.parsingContext.jsonLiteralStack.splice(depth, 1);\n }\n // Flush graphs at this level\n const graphBuffer = this.parsingContext.unidentifiedGraphsBuffer[depth];\n if (graphBuffer) {\n for (const subject of subjects) {\n // A @graph statement at the root without @id relates to the default graph,\n // unless there are top-level properties,\n // others relate to blank nodes.\n const graph = depth === 1 && subject.termType === 'BlankNode'\n && !this.parsingContext.topLevelProperties ? this.util.getDefaultGraph() : subject;\n this.parsingContext.emittedStack[depth] = true;\n for (const bufferedValue of graphBuffer) {\n this.parsingContext.emitQuad(depth, this.util.dataFactory.quad(bufferedValue.subject, bufferedValue.predicate, bufferedValue.object, graph));\n }\n }\n this.parsingContext.unidentifiedGraphsBuffer.splice(depth, 1);\n }\n // Push unhandled annotations up the stack as nested annotations\n const annotationsBuffer = this.parsingContext.annotationsBuffer[depth];\n if (annotationsBuffer) {\n // Throw an error if we reach the top, and still have annotations\n if (annotationsBuffer.length > 0 && depth === 1) {\n this.parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Annotations can not be made on top-level nodes`, jsonld_context_parser_1.ERROR_CODES.INVALID_ANNOTATION));\n }\n // Pass the annotations buffer up one level in the stack\n const annotationsBufferParent = this.parsingContext.getAnnotationsBufferSafe(depth - 1);\n for (const annotation of annotationsBuffer) {\n annotationsBufferParent.push(annotation);\n }\n delete this.parsingContext.annotationsBuffer[depth];\n }\n }\n /**\n * Check if at least one {@link IEntryHandler} validates the entry to true.\n * @param {any[]} keys A stack of keys.\n * @param {number} depth A depth.\n * @param {boolean} inProperty If the current depth is part of a valid property node.\n * @return {Promise<{ valid: boolean, property: boolean }>} A promise resolving to true or false.\n */\n async validateKey(keys, depth, inProperty) {\n for (const entryHandler of JsonLdParser.ENTRY_HANDLERS) {\n if (await entryHandler.validate(this.parsingContext, this.util, keys, depth, inProperty)) {\n return { valid: true, property: inProperty || entryHandler.isPropertyHandler() };\n }\n }\n return { valid: false, property: false };\n }\n /**\n * Attach all required listeners to the JSON parser.\n *\n * This should only be called once.\n */\n attachJsonParserListeners() {\n // Listen to json parser events\n this.jsonParser.onValue = (value) => {\n const depth = this.jsonParser.stack.length;\n const keys = (new Array(depth + 1).fill(0)).map((v, i) => {\n return i === depth ? this.jsonParser.key : this.jsonParser.stack[i].key;\n });\n if (!this.isParsingContextInner(depth)) { // Don't parse inner nodes inside @context\n const valueJobCb = () => this.newOnValueJob(keys, value, depth, true);\n if (!this.parsingContext.streamingProfile\n && !this.parsingContext.contextTree.getContext(keys.slice(0, -1))) {\n // If an out-of-order context is allowed,\n // we have to buffer everything.\n // We store jobs for @context's and @type's separately,\n // because at the end, we have to process them first.\n // We also handle @type because these *could* introduce a type-scoped context.\n if (keys[depth] === '@context') {\n let jobs = this.contextJobs[depth];\n if (!jobs) {\n jobs = this.contextJobs[depth] = [];\n }\n jobs.push(valueJobCb);\n }\n else {\n this.contextAwaitingJobs.push({ job: valueJobCb, keys, depth });\n }\n }\n else {\n // Make sure that our value jobs are chained synchronously\n this.lastOnValueJob = this.lastOnValueJob.then(valueJobCb);\n }\n // Execute all buffered jobs on deeper levels\n if (!this.parsingContext.streamingProfile && depth === 0) {\n this.lastOnValueJob = this.lastOnValueJob\n .then(() => this.executeBufferedJobs());\n }\n }\n };\n this.jsonParser.onError = (error) => {\n this.emit('error', error);\n };\n }\n /**\n * Check if the parser is currently parsing an element that is part of an @context entry.\n * @param {number} depth A depth.\n * @return {boolean} A boolean.\n */\n isParsingContextInner(depth) {\n for (let i = depth; i > 0; i--) {\n if (this.jsonParser.stack[i - 1].key === '@context') {\n return true;\n }\n }\n return false;\n }\n /**\n * Execute all buffered jobs.\n * @return {Promise} A promise resolving if all jobs are finished.\n */\n async executeBufferedJobs() {\n // Handle context jobs\n for (const jobs of this.contextJobs) {\n if (jobs) {\n for (const job of jobs) {\n await job();\n }\n }\n }\n // Clear the keyword cache.\n this.parsingContext.unaliasedKeywordCacheStack.splice(0);\n const contextAwaitingJobs = [];\n for (const job of this.contextAwaitingJobs) {\n if ((await this.util.unaliasKeyword(job.keys[job.depth], job.keys, job.depth, true)) === '@type'\n || typeof job.keys[job.depth] === 'number' && (await this.util.unaliasKeyword(job.keys[job.depth - 1], job.keys, job.depth - 1, true)) === '@type') { // Also capture @type with array values\n // Remove @type from keys, because we want it to apply to parent later on\n this.typeJobs.push({ job: job.job, keys: job.keys.slice(0, job.keys.length - 1) });\n }\n else {\n contextAwaitingJobs.push(job);\n }\n }\n // Handle non-context jobs\n for (const job of contextAwaitingJobs) {\n // Check if we have a type (with possible type-scoped context) that should be handled before.\n // We check all possible parent nodes for the current job, from root to leaves.\n if (this.typeJobs.length > 0) {\n // First collect all applicable type jobs\n const applicableTypeJobs = [];\n const applicableTypeJobIds = [];\n for (let i = 0; i < this.typeJobs.length; i++) {\n const typeJob = this.typeJobs[i];\n if (Util_1.Util.isPrefixArray(typeJob.keys, job.keys)) {\n applicableTypeJobs.push(typeJob);\n applicableTypeJobIds.push(i);\n }\n }\n // Next, sort the jobs from short to long key length (to ensure types higher up in the tree to be handled first)\n const sortedTypeJobs = applicableTypeJobs.sort((job1, job2) => job1.keys.length - job2.keys.length);\n // Finally, execute the jobs in order\n for (const typeJob of sortedTypeJobs) {\n await typeJob.job();\n }\n // Remove the executed type jobs\n // Sort first, so we can efficiently splice\n const sortedApplicableTypeJobIds = applicableTypeJobIds.sort().reverse();\n for (const jobId of sortedApplicableTypeJobIds) {\n this.typeJobs.splice(jobId, 1);\n }\n }\n await job.job();\n }\n }\n}\nJsonLdParser.DEFAULT_PROCESSING_MODE = '1.1';\nJsonLdParser.ENTRY_HANDLERS = [\n new EntryHandlerArrayValue_1.EntryHandlerArrayValue(),\n new EntryHandlerKeywordContext_1.EntryHandlerKeywordContext(),\n new EntryHandlerKeywordId_1.EntryHandlerKeywordId(),\n new EntryHandlerKeywordIncluded_1.EntryHandlerKeywordIncluded(),\n new EntryHandlerKeywordGraph_1.EntryHandlerKeywordGraph(),\n new EntryHandlerKeywordNest_1.EntryHandlerKeywordNest(),\n new EntryHandlerKeywordType_1.EntryHandlerKeywordType(),\n new EntryHandlerKeywordValue_1.EntryHandlerKeywordValue(),\n new EntryHandlerKeywordAnnotation_1.EntryHandlerKeywordAnnotation(),\n new EntryHandlerContainer_1.EntryHandlerContainer(),\n new EntryHandlerKeywordUnknownFallback_1.EntryHandlerKeywordUnknownFallback(),\n new EntryHandlerPredicate_1.EntryHandlerPredicate(),\n new EntryHandlerInvalidFallback_1.EntryHandlerInvalidFallback(),\n];\nexports.JsonLdParser = JsonLdParser;\n//# sourceMappingURL=JsonLdParser.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ParsingContext = void 0;\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\nconst ErrorCoded_1 = require(\"jsonld-context-parser/lib/ErrorCoded\");\nconst ContextTree_1 = require(\"./ContextTree\");\nconst JsonLdParser_1 = require(\"./JsonLdParser\");\n/**\n * Data holder for parsing information.\n */\nclass ParsingContext {\n constructor(options) {\n // Initialize settings\n this.contextParser = new jsonld_context_parser_1.ContextParser({ documentLoader: options.documentLoader, skipValidation: options.skipContextValidation });\n this.streamingProfile = !!options.streamingProfile;\n this.baseIRI = options.baseIRI;\n this.produceGeneralizedRdf = !!options.produceGeneralizedRdf;\n this.allowSubjectList = !!options.allowSubjectList;\n this.processingMode = options.processingMode || JsonLdParser_1.JsonLdParser.DEFAULT_PROCESSING_MODE;\n this.strictValues = !!options.strictValues;\n this.validateValueIndexes = !!options.validateValueIndexes;\n this.defaultGraph = options.defaultGraph;\n this.rdfDirection = options.rdfDirection;\n this.normalizeLanguageTags = options.normalizeLanguageTags;\n this.streamingProfileAllowOutOfOrderPlainType = options.streamingProfileAllowOutOfOrderPlainType;\n this.rdfstar = options.rdfstar !== false;\n this.rdfstarReverseInEmbedded = options.rdfstarReverseInEmbedded;\n this.topLevelProperties = false;\n this.activeProcessingMode = parseFloat(this.processingMode);\n // Initialize stacks\n this.processingStack = [];\n this.processingType = [];\n this.emittedStack = [];\n this.idStack = [];\n this.graphStack = [];\n this.graphContainerTermStack = [];\n this.listPointerStack = [];\n this.contextTree = new ContextTree_1.ContextTree();\n this.literalStack = [];\n this.validationStack = [];\n this.unaliasedKeywordCacheStack = [];\n this.jsonLiteralStack = [];\n this.unidentifiedValuesBuffer = [];\n this.unidentifiedGraphsBuffer = [];\n this.annotationsBuffer = [];\n this.pendingContainerFlushBuffers = [];\n this.parser = options.parser;\n if (options.context) {\n this.rootContext = this.parseContext(options.context);\n this.rootContext.then((context) => this.validateContext(context));\n }\n else {\n this.rootContext = Promise.resolve(new jsonld_context_parser_1.JsonLdContextNormalized(this.baseIRI ? { '@base': this.baseIRI, '@__baseDocument': true } : {}));\n }\n }\n /**\n * Parse the given context with the configured options.\n * @param {JsonLdContext} context A context to parse.\n * @param {JsonLdContextNormalized} parentContext An optional parent context.\n * @param {boolean} ignoreProtection If @protected term checks should be ignored.\n * @return {Promise} A promise resolving to the parsed context.\n */\n async parseContext(context, parentContext, ignoreProtection) {\n return this.contextParser.parse(context, {\n baseIRI: this.baseIRI,\n ignoreProtection,\n normalizeLanguageTags: this.normalizeLanguageTags,\n parentContext,\n processingMode: this.activeProcessingMode,\n });\n }\n /**\n * Check if the given context is valid.\n * If not, an error will be thrown.\n * @param {JsonLdContextNormalized} context A context.\n */\n validateContext(context) {\n const activeVersion = context.getContextRaw()['@version'];\n if (activeVersion) {\n if (this.activeProcessingMode && activeVersion > this.activeProcessingMode) {\n throw new ErrorCoded_1.ErrorCoded(`Unsupported JSON-LD version '${activeVersion}' under active processing mode ${this.activeProcessingMode}.`, ErrorCoded_1.ERROR_CODES.PROCESSING_MODE_CONFLICT);\n }\n else {\n if (this.activeProcessingMode && activeVersion < this.activeProcessingMode) {\n throw new ErrorCoded_1.ErrorCoded(`Invalid JSON-LD version ${activeVersion} under active processing mode ${this.activeProcessingMode}.`, ErrorCoded_1.ERROR_CODES.INVALID_VERSION_VALUE);\n }\n this.activeProcessingMode = activeVersion;\n }\n }\n }\n /**\n * Get the context at the given path.\n * @param {keys} keys The path of keys to get the context at.\n * @param {number} offset The path offset, defaults to 1.\n * @return {Promise} A promise resolving to a context.\n */\n async getContext(keys, offset = 1) {\n const keysOriginal = keys;\n // Ignore array keys at the end\n while (typeof keys[keys.length - 1] === 'number') {\n keys = keys.slice(0, keys.length - 1);\n }\n // Handle offset on keys\n if (offset) {\n keys = keys.slice(0, -offset);\n }\n // Determine the closest context\n const contextData = await this.getContextPropagationAware(keys);\n const context = contextData.context;\n // Process property-scoped contexts (high-to-low)\n let contextRaw = context.getContextRaw();\n for (let i = contextData.depth; i < keysOriginal.length - offset; i++) {\n const key = keysOriginal[i];\n const contextKeyEntry = contextRaw[key];\n if (contextKeyEntry && typeof contextKeyEntry === 'object' && '@context' in contextKeyEntry) {\n const scopedContext = (await this.parseContext(contextKeyEntry, contextRaw, true)).getContextRaw();\n const propagate = !(key in scopedContext)\n || scopedContext[key]['@context']['@propagate']; // Propagation is true by default\n if (propagate !== false || i === keysOriginal.length - 1 - offset) {\n contextRaw = Object.assign({}, scopedContext);\n // Clean up final context\n delete contextRaw['@propagate'];\n contextRaw[key] = Object.assign({}, contextRaw[key]);\n if ('@id' in contextKeyEntry) {\n contextRaw[key]['@id'] = contextKeyEntry['@id'];\n }\n delete contextRaw[key]['@context'];\n if (propagate !== false) {\n this.contextTree.setContext(keysOriginal.slice(0, i + offset), Promise.resolve(new jsonld_context_parser_1.JsonLdContextNormalized(contextRaw)));\n }\n }\n }\n }\n return new jsonld_context_parser_1.JsonLdContextNormalized(contextRaw);\n }\n /**\n * Get the context at the given path.\n * Non-propagating contexts will be skipped,\n * unless the context at that exact depth is retrieved.\n *\n * This ONLY takes into account context propagation logic,\n * so this should usually not be called directly,\n * call {@link #getContext} instead.\n *\n * @param keys The path of keys to get the context at.\n * @return {Promise<{ context: JsonLdContextNormalized, depth: number }>} A context and its depth.\n */\n async getContextPropagationAware(keys) {\n const originalDepth = keys.length;\n let contextData = null;\n let hasApplicablePropertyScopedContext;\n do {\n hasApplicablePropertyScopedContext = false;\n if (contextData && '@__propagateFallback' in contextData.context.getContextRaw()) {\n // If a propagation fallback context has been set,\n // fallback to that context and retry for the same depth.\n contextData.context = new jsonld_context_parser_1.JsonLdContextNormalized(contextData.context.getContextRaw()['@__propagateFallback']);\n }\n else {\n if (contextData) {\n // If we had a previous iteration, jump to the parent of context depth.\n // We must do this because once we get here, last context had propagation disabled,\n // so we check its first parent instead.\n keys = keys.slice(0, contextData.depth - 1);\n }\n contextData = await this.contextTree.getContext(keys) || { context: await this.rootContext, depth: 0 };\n }\n // Allow non-propagating contexts to propagate one level deeper\n // if it defines a property-scoped context that is applicable for the current key.\n // @see https://w3c.github.io/json-ld-api/tests/toRdf-manifest#tc012\n const lastKey = keys[keys.length - 1];\n if (lastKey in contextData.context.getContextRaw()) {\n const lastKeyValue = contextData.context.getContextRaw()[lastKey];\n if (lastKeyValue && typeof lastKeyValue === 'object' && '@context' in lastKeyValue) {\n hasApplicablePropertyScopedContext = true;\n }\n }\n } while (contextData.depth > 0 // Root context has a special case\n && contextData.context.getContextRaw()['@propagate'] === false // Stop loop if propagation is true\n && contextData.depth !== originalDepth // Stop loop if requesting exact depth of non-propagating\n && !hasApplicablePropertyScopedContext);\n // Special case for root context that does not allow propagation.\n // Fallback to empty context in that case.\n if (contextData.depth === 0\n && contextData.context.getContextRaw()['@propagate'] === false\n && contextData.depth !== originalDepth) {\n contextData.context = new jsonld_context_parser_1.JsonLdContextNormalized({});\n }\n return contextData;\n }\n /**\n * Start a new job for parsing the given value.\n * @param {any[]} keys The stack of keys.\n * @param value The value to parse.\n * @param {number} depth The depth to parse at.\n * @param {boolean} lastDepthCheck If the lastDepth check should be done for buffer draining.\n * @return {Promise} A promise resolving when the job is done.\n */\n async newOnValueJob(keys, value, depth, lastDepthCheck) {\n await this.parser.newOnValueJob(keys, value, depth, lastDepthCheck);\n }\n /**\n * Flush the pending container flush buffers\n * @return {boolean} If any pending buffers were flushed.\n */\n async handlePendingContainerFlushBuffers() {\n if (this.pendingContainerFlushBuffers.length > 0) {\n for (const pendingFlushBuffer of this.pendingContainerFlushBuffers) {\n await this.parser.flushBuffer(pendingFlushBuffer.depth, pendingFlushBuffer.keys);\n this.parser.flushStacks(pendingFlushBuffer.depth);\n }\n this.pendingContainerFlushBuffers.splice(0, this.pendingContainerFlushBuffers.length);\n return true;\n }\n else {\n return false;\n }\n }\n /**\n * Emit the given quad into the output stream.\n * @param {number} depth The depth the quad was generated at.\n * @param {Quad} quad A quad to emit.\n */\n emitQuad(depth, quad) {\n if (depth === 1) {\n this.topLevelProperties = true;\n }\n this.parser.push(quad);\n }\n /**\n * Emit the given error into the output stream.\n * @param {Error} error An error to emit.\n */\n emitError(error) {\n this.parser.emit('error', error);\n }\n /**\n * Emit the given context into the output stream under the 'context' event.\n * @param {JsonLdContext} context A context to emit.\n */\n emitContext(context) {\n this.parser.emit('context', context);\n }\n /**\n * Safely get or create the depth value of {@link ParsingContext.unidentifiedValuesBuffer}.\n * @param {number} depth A depth.\n * @return {{predicate: Term; object: Term; reverse: boolean}[]} An element of\n * {@link ParsingContext.unidentifiedValuesBuffer}.\n */\n getUnidentifiedValueBufferSafe(depth) {\n let buffer = this.unidentifiedValuesBuffer[depth];\n if (!buffer) {\n buffer = [];\n this.unidentifiedValuesBuffer[depth] = buffer;\n }\n return buffer;\n }\n /**\n * Safely get or create the depth value of {@link ParsingContext.unidentifiedGraphsBuffer}.\n * @param {number} depth A depth.\n * @return {{predicate: Term; object: Term; reverse: boolean}[]} An element of\n * {@link ParsingContext.unidentifiedGraphsBuffer}.\n */\n getUnidentifiedGraphBufferSafe(depth) {\n let buffer = this.unidentifiedGraphsBuffer[depth];\n if (!buffer) {\n buffer = [];\n this.unidentifiedGraphsBuffer[depth] = buffer;\n }\n return buffer;\n }\n /**\n * Safely get or create the depth value of {@link ParsingContext.annotationsBuffer}.\n * @param {number} depth A depth.\n * @return {} An element of {@link ParsingContext.annotationsBuffer}.\n */\n getAnnotationsBufferSafe(depth) {\n let buffer = this.annotationsBuffer[depth];\n if (!buffer) {\n buffer = [];\n this.annotationsBuffer[depth] = buffer;\n }\n return buffer;\n }\n /**\n * @return IExpandOptions The expand options for the active processing mode.\n */\n getExpandOptions() {\n return ParsingContext.EXPAND_OPTIONS[this.activeProcessingMode];\n }\n /**\n * Shift the stack at the given offset to the given depth.\n *\n * This will override anything in the stack at `depth`,\n * and this will remove anything at `depth + depthOffset`\n *\n * @param depth The target depth.\n * @param depthOffset The origin depth, relative to `depth`.\n */\n shiftStack(depth, depthOffset) {\n // Copy the id stack value up one level so that the next job can access the id.\n const deeperIdStack = this.idStack[depth + depthOffset];\n if (deeperIdStack) {\n this.idStack[depth] = deeperIdStack;\n this.emittedStack[depth] = true;\n delete this.idStack[depth + depthOffset];\n }\n // Shorten key stack\n if (this.pendingContainerFlushBuffers.length) {\n for (const buffer of this.pendingContainerFlushBuffers) {\n if (buffer.depth >= depth + depthOffset) {\n buffer.depth -= depthOffset;\n buffer.keys.splice(depth, depthOffset);\n }\n }\n }\n // Splice stacks\n if (this.unidentifiedValuesBuffer[depth + depthOffset]) {\n this.unidentifiedValuesBuffer[depth] = this.unidentifiedValuesBuffer[depth + depthOffset];\n delete this.unidentifiedValuesBuffer[depth + depthOffset];\n }\n if (this.annotationsBuffer[depth + depthOffset - 1]) {\n if (!this.annotationsBuffer[depth - 1]) {\n this.annotationsBuffer[depth - 1] = [];\n }\n this.annotationsBuffer[depth - 1] = [\n ...this.annotationsBuffer[depth - 1],\n ...this.annotationsBuffer[depth + depthOffset - 1],\n ];\n delete this.annotationsBuffer[depth + depthOffset - 1];\n }\n // TODO: also do the same for other stacks\n }\n}\nParsingContext.EXPAND_OPTIONS = {\n 1.0: {\n allowPrefixForcing: false,\n allowPrefixNonGenDelims: false,\n allowVocabRelativeToBase: false,\n },\n 1.1: {\n allowPrefixForcing: true,\n allowPrefixNonGenDelims: false,\n allowVocabRelativeToBase: true,\n },\n};\nexports.ParsingContext = ParsingContext;\n//# sourceMappingURL=ParsingContext.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Util = void 0;\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\nconst rdf_data_factory_1 = require(\"rdf-data-factory\");\nconst EntryHandlerContainer_1 = require(\"./entryhandler/EntryHandlerContainer\");\n// tslint:disable-next-line:no-var-requires\nconst canonicalizeJson = require('canonicalize');\n/**\n * Utility functions and methods.\n */\nclass Util {\n constructor(options) {\n this.parsingContext = options.parsingContext;\n this.dataFactory = options.dataFactory || new rdf_data_factory_1.DataFactory();\n this.rdfFirst = this.dataFactory.namedNode(Util.RDF + 'first');\n this.rdfRest = this.dataFactory.namedNode(Util.RDF + 'rest');\n this.rdfNil = this.dataFactory.namedNode(Util.RDF + 'nil');\n this.rdfType = this.dataFactory.namedNode(Util.RDF + 'type');\n this.rdfJson = this.dataFactory.namedNode(Util.RDF + 'JSON');\n }\n /**\n * Helper function to get the value of a context entry,\n * or fallback to a certain value.\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param {string} contextKey A pre-defined JSON-LD key in context entries.\n * @param {string} key A context entry key.\n * @param {string} fallback A fallback value for when the given contextKey\n * could not be found in the value with the given key.\n * @return {string} The value of the given contextKey in the entry behind key in the given context,\n * or the given fallback value.\n */\n static getContextValue(context, contextKey, key, fallback) {\n const entry = context.getContextRaw()[key];\n if (!entry) {\n return fallback;\n }\n const type = entry[contextKey];\n return type === undefined ? fallback : type;\n }\n /**\n * Get the container type of the given key in the context.\n *\n * Should any context-scoping bugs should occur related to this in the future,\n * it may be required to increase the offset from the depth at which the context is retrieved by one (to 2).\n * This is because containers act 2 levels deep.\n *\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param {string} key A context entry key.\n * @return {string} The container type.\n */\n static getContextValueContainer(context, key) {\n return Util.getContextValue(context, '@container', key, { '@set': true });\n }\n /**\n * Get the value type of the given key in the context.\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param {string} key A context entry key.\n * @return {string} The node type.\n */\n static getContextValueType(context, key) {\n const valueType = Util.getContextValue(context, '@type', key, null);\n if (valueType === '@none') {\n return null;\n }\n return valueType;\n }\n /**\n * Get the language of the given key in the context.\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param {string} key A context entry key.\n * @return {string} The node type.\n */\n static getContextValueLanguage(context, key) {\n return Util.getContextValue(context, '@language', key, context.getContextRaw()['@language'] || null);\n }\n /**\n * Get the direction of the given key in the context.\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param {string} key A context entry key.\n * @return {string} The node type.\n */\n static getContextValueDirection(context, key) {\n return Util.getContextValue(context, '@direction', key, context.getContextRaw()['@direction'] || null);\n }\n /**\n * Check if the given key in the context is a reversed property.\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param {string} key A context entry key.\n * @return {boolean} If the context value has a @reverse key.\n */\n static isContextValueReverse(context, key) {\n return !!Util.getContextValue(context, '@reverse', key, null);\n }\n /**\n * Get the @index of the given key in the context.\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param {string} key A context entry key.\n * @return {string} The index.\n */\n static getContextValueIndex(context, key) {\n return Util.getContextValue(context, '@index', key, context.getContextRaw()['@index'] || null);\n }\n /**\n * Check if the given key refers to a reversed property.\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param {string} key The property key.\n * @param {string} parentKey The parent key.\n * @return {boolean} If the property must be reversed.\n */\n static isPropertyReverse(context, key, parentKey) {\n // '!==' is needed because reversed properties in a @reverse container should cancel each other out.\n return parentKey === '@reverse' !== Util.isContextValueReverse(context, key);\n }\n /**\n * Check if the given key exists inside an embedded node as direct child.\n * @param {string} parentKey The parent key.\n * @return {boolean} If the property is embedded.\n */\n static isPropertyInEmbeddedNode(parentKey) {\n return parentKey === '@id';\n }\n /**\n * Check if the given key exists inside an annotation object as direct child.\n * @param {string} parentKey The parent key.\n * @return {boolean} If the property is an annotation.\n */\n static isPropertyInAnnotationObject(parentKey) {\n return parentKey === '@annotation';\n }\n /**\n * Check if the given IRI is valid.\n * @param {string} iri A potential IRI.\n * @return {boolean} If the given IRI is valid.\n */\n static isValidIri(iri) {\n return iri !== null && jsonld_context_parser_1.Util.isValidIri(iri);\n }\n /**\n * Check if the given first array (needle) is a prefix of the given second array (haystack).\n * @param needle An array to check if it is a prefix.\n * @param haystack An array to look in.\n */\n static isPrefixArray(needle, haystack) {\n if (needle.length > haystack.length) {\n return false;\n }\n for (let i = 0; i < needle.length; i++) {\n if (needle[i] !== haystack[i]) {\n return false;\n }\n }\n return true;\n }\n /**\n * Make sure that @id-@index pairs are equal over all array values.\n * Reject otherwise.\n * @param {any[]} value An array value.\n * @return {Promise} A promise rejecting if conflicts are present.\n */\n async validateValueIndexes(value) {\n if (this.parsingContext.validateValueIndexes) {\n const indexHashes = {};\n for (const entry of value) {\n if (entry && typeof entry === 'object') {\n const id = entry['@id'];\n const index = entry['@index'];\n if (id && index) {\n const existingIndexValue = indexHashes[id];\n if (existingIndexValue && existingIndexValue !== index) {\n throw new jsonld_context_parser_1.ErrorCoded(`Conflicting @index value for ${id}`, jsonld_context_parser_1.ERROR_CODES.CONFLICTING_INDEXES);\n }\n indexHashes[id] = index;\n }\n }\n }\n }\n }\n /**\n * Convert a given JSON value to an RDF term.\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param {string} key The current JSON key.\n * @param value A JSON value.\n * @param {number} depth The depth the value is at.\n * @param {string[]} keys The path of keys.\n * @return {Promise} An RDF term array.\n */\n async valueToTerm(context, key, value, depth, keys) {\n // Skip further processing if we have an @type: @json\n if (Util.getContextValueType(context, key) === '@json') {\n return [this.dataFactory.literal(this.valueToJsonString(value), this.rdfJson)];\n }\n const type = typeof value;\n switch (type) {\n case 'object':\n // Skip if we have a null or undefined object\n if (value === null || value === undefined) {\n return [];\n }\n // Special case for arrays\n if (Array.isArray(value)) {\n // We handle arrays at value level so we can emit earlier, so this is handled already when we get here.\n // Empty context-based lists are emitted at this place, because our streaming algorithm doesn't detect those.\n if ('@list' in Util.getContextValueContainer(context, key)) {\n if (value.length === 0) {\n return [this.rdfNil];\n }\n else {\n return this.parsingContext.idStack[depth + 1] || [];\n }\n }\n await this.validateValueIndexes(value);\n return [];\n }\n // Handle property-scoped contexts\n context = await this.getContextSelfOrPropertyScoped(context, key);\n // Handle local context in the value\n if ('@context' in value) {\n context = await this.parsingContext.parseContext(value['@context'], (await this.parsingContext.getContext(keys, 0)).getContextRaw());\n }\n // In all other cases, we have a hash\n value = await this.unaliasKeywords(value, keys, depth, context); // Un-alias potential keywords in this hash\n if ('@value' in value) {\n let val;\n let valueLanguage;\n let valueDirection;\n let valueType;\n let valueIndex; // We don't use the index, but we need to check its type for spec-compliance\n for (key in value) {\n const subValue = value[key];\n switch (key) {\n case '@value':\n val = subValue;\n break;\n case '@language':\n valueLanguage = subValue;\n break;\n case '@direction':\n valueDirection = subValue;\n break;\n case '@type':\n valueType = subValue;\n break;\n case '@index':\n valueIndex = subValue;\n break;\n case '@annotation':\n // This keyword is allowed, but is processed like normal nodes\n break;\n default:\n throw new jsonld_context_parser_1.ErrorCoded(`Unknown value entry '${key}' in @value: ${JSON.stringify(value)}`, jsonld_context_parser_1.ERROR_CODES.INVALID_VALUE_OBJECT);\n }\n }\n // Skip further processing if we have an @type: @json\n if (await this.unaliasKeyword(valueType, keys, depth, true, context) === '@json') {\n return [this.dataFactory.literal(this.valueToJsonString(val), this.rdfJson)];\n }\n // Validate @value\n if (val === null) {\n return [];\n }\n if (typeof val === 'object') {\n throw new jsonld_context_parser_1.ErrorCoded(`The value of an '@value' can not be an object, got '${JSON.stringify(val)}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_VALUE_OBJECT_VALUE);\n }\n // Validate @index\n if (this.parsingContext.validateValueIndexes && valueIndex && typeof valueIndex !== 'string') {\n throw new jsonld_context_parser_1.ErrorCoded(`The value of an '@index' must be a string, got '${JSON.stringify(valueIndex)}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_INDEX_VALUE);\n }\n // Validate @language and @direction\n if (valueLanguage) {\n if (typeof val !== 'string') {\n throw new jsonld_context_parser_1.ErrorCoded(`When an '@language' is set, the value of '@value' must be a string, got '${JSON.stringify(val)}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_LANGUAGE_TAGGED_VALUE);\n }\n if (!jsonld_context_parser_1.ContextParser.validateLanguage(valueLanguage, this.parsingContext.strictValues, jsonld_context_parser_1.ERROR_CODES.INVALID_LANGUAGE_TAGGED_STRING)) {\n return [];\n }\n // Language tags are always normalized to lowercase in 1.0.\n if (this.parsingContext.normalizeLanguageTags || this.parsingContext.activeProcessingMode === 1.0) {\n valueLanguage = valueLanguage.toLowerCase();\n }\n }\n if (valueDirection) {\n if (typeof val !== 'string') {\n throw new Error(`When an '@direction' is set, the value of '@value' must be a string, got '${JSON.stringify(val)}'`);\n }\n if (!jsonld_context_parser_1.ContextParser.validateDirection(valueDirection, this.parsingContext.strictValues)) {\n return [];\n }\n }\n // Check @language and @direction\n if (valueLanguage && valueDirection && this.parsingContext.rdfDirection) {\n if (valueType) {\n throw new jsonld_context_parser_1.ErrorCoded(`Can not have '@language', '@direction' and '@type' in a value: '${JSON\n .stringify(value)}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_VALUE_OBJECT);\n }\n return this.nullableTermToArray(this\n .createLanguageDirectionLiteral(depth, val, valueLanguage, valueDirection));\n }\n else if (valueLanguage) { // Check @language\n if (valueType) {\n throw new jsonld_context_parser_1.ErrorCoded(`Can not have both '@language' and '@type' in a value: '${JSON.stringify(value)}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_VALUE_OBJECT);\n }\n return [this.dataFactory.literal(val, valueLanguage)];\n }\n else if (valueDirection && this.parsingContext.rdfDirection) { // Check @direction\n if (valueType) {\n throw new jsonld_context_parser_1.ErrorCoded(`Can not have both '@direction' and '@type' in a value: '${JSON.stringify(value)}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_VALUE_OBJECT);\n }\n return this.nullableTermToArray(this\n .createLanguageDirectionLiteral(depth, val, valueLanguage, valueDirection));\n }\n else if (valueType) { // Validate @type\n if (typeof valueType !== 'string') {\n throw new jsonld_context_parser_1.ErrorCoded(`The value of an '@type' must be a string, got '${JSON.stringify(valueType)}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_TYPED_VALUE);\n }\n const typeTerm = this.createVocabOrBaseTerm(context, valueType);\n if (!typeTerm) {\n throw new jsonld_context_parser_1.ErrorCoded(`Invalid '@type' value, got '${JSON.stringify(valueType)}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_TYPED_VALUE);\n }\n if (typeTerm.termType !== 'NamedNode') {\n throw new jsonld_context_parser_1.ErrorCoded(`Illegal value type (${typeTerm.termType}): ${valueType}`, jsonld_context_parser_1.ERROR_CODES.INVALID_TYPED_VALUE);\n }\n return [this.dataFactory.literal(val, typeTerm)];\n }\n // We don't pass the context, because context-based things like @language should be ignored\n return await this.valueToTerm(new jsonld_context_parser_1.JsonLdContextNormalized({}), key, val, depth, keys);\n }\n else if ('@set' in value) {\n // No other entries are allow in this value\n if (Object.keys(value).length > 1) {\n throw new jsonld_context_parser_1.ErrorCoded(`Found illegal neighbouring entries next to @set for key: '${key}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_SET_OR_LIST_OBJECT);\n }\n // No need to do anything here, this is handled at the deeper level.\n return [];\n }\n else if ('@list' in value) {\n // No other entries are allowed in this value\n if (Object.keys(value).length > 1) {\n throw new jsonld_context_parser_1.ErrorCoded(`Found illegal neighbouring entries next to @list for key: '${key}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_SET_OR_LIST_OBJECT);\n }\n const listValue = value[\"@list\"];\n // We handle lists at value level so we can emit earlier, so this is handled already when we get here.\n // Empty anonymous lists are emitted at this place, because our streaming algorithm doesn't detect those.\n if (Array.isArray(listValue)) {\n if (listValue.length === 0) {\n return [this.rdfNil];\n }\n else {\n return this.parsingContext.idStack[depth + 1] || [];\n }\n }\n else {\n // We only have a single list element here, so emit this directly as single element\n return await this.valueToTerm(await this.parsingContext.getContext(keys), key, listValue, depth - 1, keys.slice(0, -1));\n }\n }\n else if ('@reverse' in value && typeof value['@reverse'] === 'boolean') {\n // We handle reverse properties at value level so we can emit earlier,\n // so this is handled already when we get here.\n return [];\n }\n else if ('@graph' in Util.getContextValueContainer(await this.parsingContext.getContext(keys), key)) {\n // We are processing a graph container\n const graphContainerEntries = this.parsingContext.graphContainerTermStack[depth + 1];\n return graphContainerEntries ? Object.values(graphContainerEntries) : [this.dataFactory.blankNode()];\n }\n else if (\"@id\" in value) {\n // Use deeper context if the value node contains other properties next to @id.\n if (Object.keys(value).length > 1) {\n context = await this.parsingContext.getContext(keys, 0);\n }\n // Handle local context in the value\n if ('@context' in value) {\n context = await this.parsingContext.parseContext(value['@context'], context.getContextRaw());\n }\n if (value[\"@type\"] === '@vocab') {\n return this.nullableTermToArray(this.createVocabOrBaseTerm(context, value[\"@id\"]));\n }\n else {\n const valueId = value[\"@id\"];\n let valueTerm;\n if (typeof valueId === 'object') {\n if (this.parsingContext.rdfstar) {\n valueTerm = this.parsingContext.idStack[depth + 1][0];\n }\n else {\n throw new jsonld_context_parser_1.ErrorCoded(`Found illegal @id '${value}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_ID_VALUE);\n }\n }\n else {\n valueTerm = this.resourceToTerm(context, valueId);\n }\n return this.nullableTermToArray(valueTerm);\n }\n }\n else {\n // Only make a blank node if at least one triple was emitted at the value's level.\n if (this.parsingContext.emittedStack[depth + 1]\n || (value && typeof value === 'object' && Object.keys(value).length === 0)) {\n return (this.parsingContext.idStack[depth + 1]\n || (this.parsingContext.idStack[depth + 1] = [this.dataFactory.blankNode()]));\n }\n else {\n return [];\n }\n }\n case 'string':\n return this.nullableTermToArray(this.stringValueToTerm(depth, await this.getContextSelfOrPropertyScoped(context, key), key, value, null));\n case 'boolean':\n return this.nullableTermToArray(this.stringValueToTerm(depth, await this.getContextSelfOrPropertyScoped(context, key), key, Boolean(value).toString(), this.dataFactory.namedNode(Util.XSD_BOOLEAN)));\n case 'number':\n return this.nullableTermToArray(this.stringValueToTerm(depth, await this.getContextSelfOrPropertyScoped(context, key), key, value, this.dataFactory.namedNode(value % 1 === 0 && value < 1e21 ? Util.XSD_INTEGER : Util.XSD_DOUBLE)));\n default:\n this.parsingContext.emitError(new Error(`Could not determine the RDF type of a ${type}`));\n return [];\n }\n }\n /**\n * If the context defines a property-scoped context for the given key,\n * that context will be returned.\n * Otherwise, the given context will be returned as-is.\n *\n * This should be used for valueToTerm cases that are not objects.\n * @param context A context.\n * @param key A JSON key.\n */\n async getContextSelfOrPropertyScoped(context, key) {\n const contextKeyEntry = context.getContextRaw()[key];\n if (contextKeyEntry && typeof contextKeyEntry === 'object' && '@context' in contextKeyEntry) {\n context = await this.parsingContext.parseContext(contextKeyEntry, context.getContextRaw(), true);\n }\n return context;\n }\n /**\n * If the given term is null, return an empty array, otherwise return an array with the single given term.\n * @param term A term.\n */\n nullableTermToArray(term) {\n return term ? [term] : [];\n }\n /**\n * Convert a given JSON key to an RDF predicate term,\n * based on @vocab.\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param key A JSON key.\n * @return {RDF.NamedNode} An RDF named node.\n */\n predicateToTerm(context, key) {\n const expanded = context.expandTerm(key, true, this.parsingContext.getExpandOptions());\n // Immediately return if the predicate was disabled in the context\n if (!expanded) {\n return null;\n }\n // Check if the predicate is a blank node\n if (expanded[0] === '_' && expanded[1] === ':') {\n if (this.parsingContext.produceGeneralizedRdf) {\n return this.dataFactory.blankNode(expanded.substr(2));\n }\n else {\n return null;\n }\n }\n // Check if the predicate is a valid IRI\n if (Util.isValidIri(expanded)) {\n return this.dataFactory.namedNode(expanded);\n }\n else {\n if (expanded && this.parsingContext.strictValues) {\n this.parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Invalid predicate IRI: ${expanded}`, jsonld_context_parser_1.ERROR_CODES.INVALID_IRI_MAPPING));\n }\n else {\n return null;\n }\n }\n return null;\n }\n /**\n * Convert a given JSON key to an RDF resource term or blank node,\n * based on @base.\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param key A JSON key.\n * @return {RDF.NamedNode} An RDF named node or null.\n */\n resourceToTerm(context, key) {\n if (key.startsWith('_:')) {\n return this.dataFactory.blankNode(key.substr(2));\n }\n const iri = context.expandTerm(key, false, this.parsingContext.getExpandOptions());\n if (!Util.isValidIri(iri)) {\n if (iri && this.parsingContext.strictValues) {\n this.parsingContext.emitError(new Error(`Invalid resource IRI: ${iri}`));\n }\n else {\n return null;\n }\n }\n return this.dataFactory.namedNode(iri);\n }\n /**\n * Convert a given JSON key to an RDF resource term.\n * It will do this based on the @vocab,\n * and fallback to @base.\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param key A JSON key.\n * @return {RDF.NamedNode} An RDF named node or null.\n */\n createVocabOrBaseTerm(context, key) {\n if (key.startsWith('_:')) {\n return this.dataFactory.blankNode(key.substr(2));\n }\n const expandOptions = this.parsingContext.getExpandOptions();\n let expanded = context.expandTerm(key, true, expandOptions);\n if (expanded === key) {\n expanded = context.expandTerm(key, false, expandOptions);\n }\n if (!Util.isValidIri(expanded)) {\n if (expanded && this.parsingContext.strictValues && !expanded.startsWith('@')) {\n this.parsingContext.emitError(new Error(`Invalid term IRI: ${expanded}`));\n }\n else {\n return null;\n }\n }\n return this.dataFactory.namedNode(expanded);\n }\n /**\n * Ensure that the given value becomes a string.\n * @param {string | number} value A string or number.\n * @param {NamedNode} datatype The intended datatype.\n * @return {string} The returned string.\n */\n intToString(value, datatype) {\n if (typeof value === 'number') {\n if (Number.isFinite(value)) {\n const isInteger = value % 1 === 0;\n if (isInteger && (!datatype || datatype.value !== Util.XSD_DOUBLE)) {\n return Number(value).toString();\n }\n else {\n return value.toExponential(15).replace(/(\\d)0*e\\+?/, '$1E');\n }\n }\n else {\n return value > 0 ? 'INF' : '-INF';\n }\n }\n else {\n return value;\n }\n }\n /**\n * Convert a given JSON string value to an RDF term.\n * @param {number} depth The current stack depth.\n * @param {JsonLdContextNormalized} context A JSON-LD context.\n * @param {string} key The current JSON key.\n * @param {string} value A JSON value.\n * @param {NamedNode} defaultDatatype The default datatype for the given value.\n * @return {RDF.Term} An RDF term or null.\n */\n stringValueToTerm(depth, context, key, value, defaultDatatype) {\n // Check the datatype from the context\n const contextType = Util.getContextValueType(context, key);\n if (contextType) {\n if (contextType === '@id') {\n if (!defaultDatatype) {\n return this.resourceToTerm(context, this.intToString(value, defaultDatatype));\n }\n }\n else if (contextType === '@vocab') {\n if (!defaultDatatype) {\n return this.createVocabOrBaseTerm(context, this.intToString(value, defaultDatatype));\n }\n }\n else {\n defaultDatatype = this.dataFactory.namedNode(contextType);\n }\n }\n // If we don't find such a datatype, check the language from the context\n if (!defaultDatatype) {\n const contextLanguage = Util.getContextValueLanguage(context, key);\n const contextDirection = Util.getContextValueDirection(context, key);\n if (contextDirection && this.parsingContext.rdfDirection) {\n return this.createLanguageDirectionLiteral(depth, this.intToString(value, defaultDatatype), contextLanguage, contextDirection);\n }\n else {\n return this.dataFactory.literal(this.intToString(value, defaultDatatype), contextLanguage);\n }\n }\n // If all else fails, make a literal based on the default content type\n return this.dataFactory.literal(this.intToString(value, defaultDatatype), defaultDatatype);\n }\n /**\n * Create a literal for the given value with the given language and direction.\n * Auxiliary quads may be emitted.\n * @param {number} depth The current stack depth.\n * @param {string} value A string value.\n * @param {string} language A language tag.\n * @param {string} direction A direction.\n * @return {Term} An RDF term.\n */\n createLanguageDirectionLiteral(depth, value, language, direction) {\n if (this.parsingContext.rdfDirection === 'i18n-datatype') {\n // Create a datatyped literal, by encoding the language and direction into https://www.w3.org/ns/i18n#.\n if (!language) {\n language = '';\n }\n return this.dataFactory.literal(value, this.dataFactory.namedNode(`https://www.w3.org/ns/i18n#${language}_${direction}`));\n }\n else {\n // Reify the literal.\n const valueNode = this.dataFactory.blankNode();\n const graph = this.getDefaultGraph();\n this.parsingContext.emitQuad(depth, this.dataFactory.quad(valueNode, this.dataFactory.namedNode(Util.RDF + 'value'), this.dataFactory.literal(value), graph));\n if (language) {\n this.parsingContext.emitQuad(depth, this.dataFactory.quad(valueNode, this.dataFactory.namedNode(Util.RDF + 'language'), this.dataFactory.literal(language), graph));\n }\n this.parsingContext.emitQuad(depth, this.dataFactory.quad(valueNode, this.dataFactory.namedNode(Util.RDF + 'direction'), this.dataFactory.literal(direction), graph));\n return valueNode;\n }\n }\n /**\n * Stringify the given JSON object to a canonical JSON string.\n * @param value Any valid JSON value.\n * @return {string} A canonical JSON string.\n */\n valueToJsonString(value) {\n return canonicalizeJson(value);\n }\n /**\n * If the key is not a keyword, try to check if it is an alias for a keyword,\n * and if so, un-alias it.\n * @param {string} key A key, can be falsy.\n * @param {string[]} keys The path of keys.\n * @param {number} depth The depth to\n * @param {boolean} disableCache If the cache should be disabled\n * @param {JsonLdContextNormalized} context A context to unalias with,\n * will fallback to retrieving the context for the given keys.\n * @return {Promise} A promise resolving to the key itself, or another key.\n */\n async unaliasKeyword(key, keys, depth, disableCache, context) {\n // Numbers can not be an alias\n if (Number.isInteger(key)) {\n return key;\n }\n // Try to grab from cache if it was already un-aliased before.\n if (!disableCache) {\n const cachedUnaliasedKeyword = this.parsingContext.unaliasedKeywordCacheStack[depth];\n if (cachedUnaliasedKeyword) {\n return cachedUnaliasedKeyword;\n }\n }\n if (!jsonld_context_parser_1.Util.isPotentialKeyword(key)) {\n context = context || await this.parsingContext.getContext(keys);\n let unliased = context.getContextRaw()[key];\n if (unliased && typeof unliased === 'object') {\n unliased = unliased['@id'];\n }\n if (jsonld_context_parser_1.Util.isValidKeyword(unliased)) {\n key = unliased;\n }\n }\n return disableCache ? key : (this.parsingContext.unaliasedKeywordCacheStack[depth] = key);\n }\n /**\n * Unalias the keyword of the parent.\n * This adds a safety check if no parent exist.\n * @param {any[]} keys A stack of keys.\n * @param {number} depth The current depth.\n * @return {Promise} A promise resolving to the parent key, or another key.\n */\n async unaliasKeywordParent(keys, depth) {\n return await this.unaliasKeyword(depth > 0 && keys[depth - 1], keys, depth - 1);\n }\n /**\n * Un-alias all keywords in the given hash.\n * @param {{[p: string]: any}} hash A hash object.\n * @param {string[]} keys The path of keys.\n * @param {number} depth The depth.\n * @param {JsonLdContextNormalized} context A context to unalias with,\n * will fallback to retrieving the context for the given keys.\n * @return {Promise<{[p: string]: any}>} A promise resolving to the new hash.\n */\n async unaliasKeywords(hash, keys, depth, context) {\n const newHash = {};\n for (const key in hash) {\n newHash[await this.unaliasKeyword(key, keys, depth + 1, true, context)] = hash[key];\n }\n return newHash;\n }\n /**\n * Check if we are processing a literal (including JSON literals) at the given depth.\n * This will also check higher levels,\n * because if a parent is a literal,\n * then the deeper levels are definitely a literal as well.\n * @param {any[]} keys The keys.\n * @param {number} depth The depth.\n * @return {boolean} If we are processing a literal.\n */\n async isLiteral(keys, depth) {\n for (let i = depth; i >= 0; i--) {\n if (await this.unaliasKeyword(keys[i], keys, i) === '@annotation') {\n // Literals may have annotations, which require processing of inner nodes.\n return false;\n }\n if (this.parsingContext.literalStack[i] || this.parsingContext.jsonLiteralStack[i]) {\n return true;\n }\n }\n return false;\n }\n /**\n * Check how many parents should be skipped for checking the @graph for the given node.\n *\n * @param {number} depth The depth of the node.\n * @param {any[]} keys An array of keys.\n * @return {number} The graph depth offset.\n */\n async getDepthOffsetGraph(depth, keys) {\n for (let i = depth - 1; i > 0; i--) {\n if (await this.unaliasKeyword(keys[i], keys, i) === '@graph') {\n // Skip further processing if we are already in an @graph-@id or @graph-@index container\n const containers = (await EntryHandlerContainer_1.EntryHandlerContainer.getContainerHandler(this.parsingContext, keys, i)).containers;\n if (EntryHandlerContainer_1.EntryHandlerContainer.isComplexGraphContainer(containers)) {\n return -1;\n }\n return depth - i - 1;\n }\n }\n return -1;\n }\n /**\n * Check if the given subject is of a valid type.\n * This should be called when applying @reverse'd properties.\n * @param {Term} subject A subject.\n */\n validateReverseSubject(subject) {\n if (subject.termType === 'Literal') {\n throw new jsonld_context_parser_1.ErrorCoded(`Found illegal literal in subject position: ${subject.value}`, jsonld_context_parser_1.ERROR_CODES.INVALID_REVERSE_PROPERTY_VALUE);\n }\n }\n /**\n * Get the default graph.\n * @return {Term} An RDF term.\n */\n getDefaultGraph() {\n return this.parsingContext.defaultGraph || this.dataFactory.defaultGraph();\n }\n /**\n * Get the current graph, while taking into account a graph that can be defined via @container: @graph.\n * If not within a graph container, the default graph will be returned.\n * @param keys The current keys.\n * @param depth The current depth.\n */\n async getGraphContainerValue(keys, depth) {\n // Default to default graph\n let graph = this.getDefaultGraph();\n // Check if we are in an @container: @graph.\n const { containers, depth: depthContainer } = await EntryHandlerContainer_1.EntryHandlerContainer\n .getContainerHandler(this.parsingContext, keys, depth);\n if ('@graph' in containers) {\n // Get the graph from the stack.\n const graphContainerIndex = EntryHandlerContainer_1.EntryHandlerContainer.getContainerGraphIndex(containers, depthContainer, keys);\n const entry = this.parsingContext.graphContainerTermStack[depthContainer];\n graph = entry ? entry[graphContainerIndex] : null;\n // Set the graph in the stack if none has been set yet.\n if (!graph) {\n let graphId = null;\n if ('@id' in containers) {\n const keyUnaliased = await this.getContainerKey(keys[depthContainer], keys, depthContainer);\n if (keyUnaliased !== null) {\n graphId = await this.resourceToTerm(await this.parsingContext.getContext(keys), keyUnaliased);\n }\n }\n if (!graphId) {\n graphId = this.dataFactory.blankNode();\n }\n if (!this.parsingContext.graphContainerTermStack[depthContainer]) {\n this.parsingContext.graphContainerTermStack[depthContainer] = {};\n }\n graph = this.parsingContext.graphContainerTermStack[depthContainer][graphContainerIndex] = graphId;\n }\n }\n return graph;\n }\n /**\n * Get the properties depth for retrieving properties.\n *\n * Typically, the properties depth will be identical to the given depth.\n *\n * The following exceptions apply:\n * * When the parent is @reverse, the depth is decremented by one.\n * * When @nest parents are found, the depth is decremented by the number of @nest parents.\n * If in combination with the exceptions above an intermediary array is discovered,\n * the depth is also decremented by this number of arrays.\n *\n * @param keys The current key chain.\n * @param depth The current depth.\n */\n async getPropertiesDepth(keys, depth) {\n let lastValidDepth = depth;\n for (let i = depth - 1; i > 0; i--) {\n if (typeof keys[i] !== 'number') { // Skip array keys\n const parentKey = await this.unaliasKeyword(keys[i], keys, i);\n if (parentKey === '@reverse') {\n return i;\n }\n else if (parentKey === '@nest') {\n lastValidDepth = i;\n }\n else {\n return lastValidDepth;\n }\n }\n }\n return lastValidDepth;\n }\n /**\n * Get the key for the current container entry.\n * @param key A key, can be falsy.\n * @param keys The key chain.\n * @param depth The current depth to get the key from.\n * @return Promise resolving to the key.\n * Null will be returned for @none entries, with aliasing taken into account.\n */\n async getContainerKey(key, keys, depth) {\n const keyUnaliased = await this.unaliasKeyword(key, keys, depth);\n return keyUnaliased === '@none' ? null : keyUnaliased;\n }\n /**\n * Check if no reverse properties are present in embedded nodes.\n * @param key The current key.\n * @param reverse If a reverse property is active.\n * @param isEmbedded If we're in an embedded node.\n */\n validateReverseInEmbeddedNode(key, reverse, isEmbedded) {\n if (isEmbedded && reverse && !this.parsingContext.rdfstarReverseInEmbedded) {\n throw new jsonld_context_parser_1.ErrorCoded(`Illegal reverse property in embedded node in ${key}`, jsonld_context_parser_1.ERROR_CODES.INVALID_EMBEDDED_NODE);\n }\n }\n /**\n * Emit a quad, with checks.\n * @param depth The current depth.\n * @param subject S\n * @param predicate P\n * @param object O\n * @param graph G\n * @param reverse If a reverse property is active.\n * @param isEmbedded If we're in an embedded node.\n */\n emitQuadChecked(depth, subject, predicate, object, graph, reverse, isEmbedded) {\n // Create a quad\n let quad;\n if (reverse) {\n this.validateReverseSubject(object);\n quad = this.dataFactory.quad(object, predicate, subject, graph);\n }\n else {\n quad = this.dataFactory.quad(subject, predicate, object, graph);\n }\n // Emit the quad, unless it was created in an embedded node\n if (isEmbedded) {\n // Embedded nodes don't inherit the active graph\n if (quad.graph.termType !== 'DefaultGraph') {\n quad = this.dataFactory.quad(quad.subject, quad.predicate, quad.object);\n }\n // Multiple embedded nodes are not allowed\n if (this.parsingContext.idStack[depth - 1]) {\n throw new jsonld_context_parser_1.ErrorCoded(`Illegal multiple properties in an embedded node`, jsonld_context_parser_1.ERROR_CODES.INVALID_EMBEDDED_NODE);\n }\n this.parsingContext.idStack[depth - 1] = [quad];\n }\n else {\n this.parsingContext.emitQuad(depth, quad);\n }\n // Flush annotations\n const annotationsBuffer = this.parsingContext.annotationsBuffer[depth];\n if (annotationsBuffer) {\n for (const annotation of annotationsBuffer) {\n this.emitAnnotation(depth, quad, annotation);\n }\n delete this.parsingContext.annotationsBuffer[depth];\n }\n }\n // This is a separate function to enable recursion\n emitAnnotation(depth, quad, annotation) {\n // Construct annotation quad\n let annotationQuad;\n if (annotation.reverse) {\n this.validateReverseSubject(annotation.object);\n annotationQuad = this.dataFactory.quad(annotation.object, annotation.predicate, quad);\n }\n else {\n annotationQuad = this.dataFactory.quad(quad, annotation.predicate, annotation.object);\n }\n // Emit annotated quad\n this.parsingContext.emitQuad(depth, annotationQuad);\n // Also emit nested annotations\n for (const nestedAnnotation of annotation.nestedAnnotations) {\n this.emitAnnotation(depth, annotationQuad, nestedAnnotation);\n }\n }\n}\nUtil.XSD = 'http://www.w3.org/2001/XMLSchema#';\nUtil.XSD_BOOLEAN = Util.XSD + 'boolean';\nUtil.XSD_INTEGER = Util.XSD + 'integer';\nUtil.XSD_DOUBLE = Util.XSD + 'double';\nUtil.RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';\nexports.Util = Util;\n//# sourceMappingURL=Util.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ContainerHandlerIdentifier = void 0;\n/**\n * Container handler for @id.\n *\n * It assumes that the current key is the identifier of the current value.\n * This will add this value to the parent node.\n */\nclass ContainerHandlerIdentifier {\n canCombineWithGraph() {\n return true;\n }\n async handle(containers, parsingContext, util, keys, value, depth) {\n let id;\n // First check if the child node already has a defined id.\n if (parsingContext.emittedStack[depth + 1] && parsingContext.idStack[depth + 1]) {\n // Use the existing identifier\n id = parsingContext.idStack[depth + 1][0];\n }\n else {\n // Create the identifier\n const keyUnaliased = await util.getContainerKey(keys[depth], keys, depth);\n const maybeId = keyUnaliased !== null\n ? await util.resourceToTerm(await parsingContext.getContext(keys), keys[depth])\n : util.dataFactory.blankNode();\n // Do nothing if the id is invalid\n if (!maybeId) {\n parsingContext.emittedStack[depth] = false; // Don't emit the predicate owning this container.\n return;\n }\n id = maybeId;\n // Insert the id into the stack so that buffered children can make us of it.\n parsingContext.idStack[depth + 1] = [id];\n }\n // Insert the id into the stack so that parents can make use of it.\n // Insert it as an array because multiple id container entries may exist\n let ids = parsingContext.idStack[depth];\n if (!ids) {\n ids = parsingContext.idStack[depth] = [];\n }\n // Only insert the term if it does not exist yet in the array.\n if (!ids.some((term) => term.equals(id))) {\n ids.push(id);\n }\n // Flush any pending flush buffers\n if (!await parsingContext.handlePendingContainerFlushBuffers()) {\n parsingContext.emittedStack[depth] = false; // Don't emit the predicate owning this container.\n }\n }\n}\nexports.ContainerHandlerIdentifier = ContainerHandlerIdentifier;\n//# sourceMappingURL=ContainerHandlerIdentifier.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ContainerHandlerIndex = void 0;\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\nconst EntryHandlerPredicate_1 = require(\"../entryhandler/EntryHandlerPredicate\");\nconst Util_1 = require(\"../Util\");\n/**\n * Container handler for @index.\n *\n * This will ignore the current key and add this entry to the parent node.\n */\nclass ContainerHandlerIndex {\n canCombineWithGraph() {\n return true;\n }\n async handle(containers, parsingContext, util, keys, value, depth) {\n if (!Array.isArray(value)) {\n const graphContainer = '@graph' in containers;\n // Check if the container is a property-based container by checking if there is a valid @index.\n const context = await parsingContext.getContext(keys);\n const indexKey = keys[depth - 1];\n const indexPropertyRaw = Util_1.Util.getContextValueIndex(context, indexKey);\n if (indexPropertyRaw) {\n // Validate the @index value\n if (jsonld_context_parser_1.Util.isPotentialKeyword(indexPropertyRaw)) {\n throw new jsonld_context_parser_1.ErrorCoded(`Keywords can not be used as @index value, got: ${indexPropertyRaw}`, jsonld_context_parser_1.ERROR_CODES.INVALID_TERM_DEFINITION);\n }\n if (typeof indexPropertyRaw !== 'string') {\n throw new jsonld_context_parser_1.ErrorCoded(`@index values must be strings, got: ${indexPropertyRaw}`, jsonld_context_parser_1.ERROR_CODES.INVALID_TERM_DEFINITION);\n }\n // When @index is used, values must be node values, unless @type: @id is defined in the context\n if (typeof value !== 'object') {\n // Error if we don't have @type: @id\n if (Util_1.Util.getContextValueType(context, indexKey) !== '@id') {\n throw new jsonld_context_parser_1.ErrorCoded(`Property-based index containers require nodes as values or strings with @type: @id, but got: ${value}`, jsonld_context_parser_1.ERROR_CODES.INVALID_VALUE_OBJECT);\n }\n // Add an @id to the stack, so our expanded @index value can make use of it\n const id = util.resourceToTerm(context, value);\n if (id) {\n parsingContext.idStack[depth + 1] = [id];\n }\n }\n // Expand the @index value\n const indexProperty = util.createVocabOrBaseTerm(context, indexPropertyRaw);\n if (indexProperty) {\n const indexValues = await util.valueToTerm(context, indexPropertyRaw, await util.getContainerKey(keys[depth], keys, depth), depth, keys);\n if (graphContainer) {\n // When we're in a graph container, attach the index to the graph identifier\n const graphId = await util.getGraphContainerValue(keys, depth + 1);\n for (const indexValue of indexValues) {\n parsingContext.emitQuad(depth, util.dataFactory.quad(graphId, indexProperty, indexValue, util.getDefaultGraph()));\n }\n }\n else {\n // Otherwise, attach the index to the node identifier\n for (const indexValue of indexValues) {\n await EntryHandlerPredicate_1.EntryHandlerPredicate.handlePredicateObject(parsingContext, util, keys, depth + 1, indexProperty, indexValue, false, false, false);\n }\n }\n }\n }\n const depthOffset = graphContainer ? 2 : 1;\n await parsingContext.newOnValueJob(keys.slice(0, keys.length - depthOffset), value, depth - depthOffset, true);\n // Flush any pending flush buffers\n await parsingContext.handlePendingContainerFlushBuffers();\n }\n parsingContext.emittedStack[depth] = false; // We have emitted a level higher\n }\n}\nexports.ContainerHandlerIndex = ContainerHandlerIndex;\n//# sourceMappingURL=ContainerHandlerIndex.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ContainerHandlerLanguage = void 0;\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\n/**\n * Container handler for @language.\n *\n * It assumes that the current key is the language of the current value.\n * This will add this value to the parent node.\n */\nclass ContainerHandlerLanguage {\n canCombineWithGraph() {\n return false;\n }\n async handle(containers, parsingContext, util, keys, value, depth) {\n const language = await util.getContainerKey(keys[depth], keys, depth);\n if (Array.isArray(value)) {\n // No type-checking needed, will be handled on each value when this handler is called recursively.\n value = value.map((subValue) => ({ '@value': subValue, '@language': language }));\n }\n else {\n if (typeof value !== 'string') {\n throw new jsonld_context_parser_1.ErrorCoded(`Got invalid language map value, got '${JSON.stringify(value)}', but expected string`, jsonld_context_parser_1.ERROR_CODES.INVALID_LANGUAGE_MAP_VALUE);\n }\n value = { '@value': value, '@language': language };\n }\n await parsingContext.newOnValueJob(keys.slice(0, keys.length - 1), value, depth - 1, true);\n parsingContext.emittedStack[depth] = false; // We have emitted a level higher\n }\n}\nexports.ContainerHandlerLanguage = ContainerHandlerLanguage;\n//# sourceMappingURL=ContainerHandlerLanguage.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ContainerHandlerType = void 0;\nconst EntryHandlerPredicate_1 = require(\"../entryhandler/EntryHandlerPredicate\");\nconst Util_1 = require(\"../Util\");\n/**\n * Container handler for @type.\n *\n * This will add this entry to the parent node, and use the current key as an rdf:type value.\n */\nclass ContainerHandlerType {\n canCombineWithGraph() {\n return false;\n }\n async handle(containers, parsingContext, util, keys, value, depth) {\n if (!Array.isArray(value)) {\n if (typeof value === 'string') {\n // Determine the @type of the container\n const context = await parsingContext.getContext(keys);\n const containerTypeType = Util_1.Util.getContextValueType(context, keys[depth - 1]);\n // String values refer to node references\n const id = containerTypeType === '@vocab'\n ? await util.createVocabOrBaseTerm(context, value)\n : await util.resourceToTerm(context, value);\n if (id) {\n // Handle the value of this node as @id, which will also cause the predicate from above to be emitted.\n const subValue = { '@id': id.termType === 'NamedNode' ? id.value : value };\n await parsingContext.newOnValueJob(keys.slice(0, keys.length - 1), subValue, depth - 1, true);\n // Set the id in the stack so it can be used for the rdf:type handling later on\n parsingContext.idStack[depth + 1] = [id];\n }\n }\n else {\n // Other values are handled by handling them as a proper job\n // Check needed for cases where entries don't have an explicit @id\n const entryHasIdentifier = !!parsingContext.idStack[depth + 1];\n // Handle the value of this node, which will also cause the predicate from above to be emitted.\n if (!entryHasIdentifier) {\n delete parsingContext.idStack[depth]; // Force new (blank node) identifier\n }\n await parsingContext.newOnValueJob(keys.slice(0, keys.length - 1), value, depth - 1, true);\n if (!entryHasIdentifier) {\n parsingContext.idStack[depth + 1] = parsingContext.idStack[depth]; // Copy the id to the child node, for @type\n }\n }\n // Identify the type to emit.\n const keyOriginal = await util.getContainerKey(keys[depth], keys, depth);\n const type = keyOriginal !== null\n ? util.createVocabOrBaseTerm(await parsingContext.getContext(keys), keyOriginal)\n : null;\n if (type) {\n // Push the type to the stack using the rdf:type predicate\n await EntryHandlerPredicate_1.EntryHandlerPredicate.handlePredicateObject(parsingContext, util, keys, depth + 1, util.rdfType, type, false, false, false);\n }\n // Flush any pending flush buffers\n await parsingContext.handlePendingContainerFlushBuffers();\n }\n parsingContext.emittedStack[depth] = false; // Don't emit the predicate owning this container.\n }\n}\nexports.ContainerHandlerType = ContainerHandlerType;\n//# sourceMappingURL=ContainerHandlerType.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerArrayValue = void 0;\nconst Util_1 = require(\"../Util\");\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\n/**\n * Handles values that are part of an array.\n */\nclass EntryHandlerArrayValue {\n isPropertyHandler() {\n return false;\n }\n isStackProcessor() {\n return true;\n }\n async validate(parsingContext, util, keys, depth, inProperty) {\n return this.test(parsingContext, util, null, keys, depth);\n }\n async test(parsingContext, util, key, keys, depth) {\n return typeof keys[depth] === 'number';\n }\n async handle(parsingContext, util, key, keys, value, depth) {\n let parentKey = await util.unaliasKeywordParent(keys, depth);\n // Check if we have an anonymous list\n if (parentKey === '@list') {\n // Our value is part of an array\n // Determine the list root key\n let listRootKey = null;\n let listRootDepth = 0;\n for (let i = depth - 2; i > 0; i--) {\n const keyOption = keys[i];\n if (typeof keyOption === 'string' || typeof keyOption === 'number') {\n listRootDepth = i;\n listRootKey = keyOption;\n break;\n }\n }\n if (listRootKey !== null) {\n // Emit the given objects as list elements\n const values = await util.valueToTerm(await parsingContext.getContext(keys), listRootKey, value, depth, keys);\n for (const object of values) {\n await this.handleListElement(parsingContext, util, object, value, depth, keys.slice(0, listRootDepth), listRootDepth);\n }\n // If no values were found, emit a falsy list element to force an empty RDF list to be emitted.\n if (values.length === 0) {\n await this.handleListElement(parsingContext, util, null, value, depth, keys.slice(0, listRootDepth), listRootDepth);\n }\n }\n }\n else if (parentKey === '@set') {\n // Our value is part of a set, so we just add it to the parent-parent\n await parsingContext.newOnValueJob(keys.slice(0, -2), value, depth - 2, false);\n }\n else if (parentKey !== undefined && parentKey !== '@type') {\n // Buffer our value using the parent key as predicate\n // Determine the first parent key that is *not* an array key\n // This is needed in case we have an @list container with nested arrays,\n // where each of them should produce nested RDF lists.\n for (let i = depth - 1; i > 0; i--) {\n if (typeof keys[i] !== 'number') {\n parentKey = await util.unaliasKeyword(keys[i], keys, i);\n break;\n }\n }\n // Check if the predicate is marked as an @list in the context\n const parentContext = await parsingContext.getContext(keys.slice(0, -1));\n if ('@list' in Util_1.Util.getContextValueContainer(parentContext, parentKey)) {\n // Our value is part of an array\n // Emit the given objects as list elements\n parsingContext.emittedStack[depth + 1] = true; // Ensure the creation of bnodes for empty nodes\n const values = await util.valueToTerm(await parsingContext.getContext(keys), parentKey, value, depth, keys);\n for (const object of values) {\n await this.handleListElement(parsingContext, util, object, value, depth, keys.slice(0, -1), depth - 1);\n }\n // If no values were found, emit a falsy list element to force an empty RDF list to be emitted.\n if (values.length === 0) {\n await this.handleListElement(parsingContext, util, null, value, depth, keys.slice(0, -1), depth - 1);\n }\n }\n else {\n // Copy the stack values up one level so that the next job can access them.\n parsingContext.shiftStack(depth, 1);\n // Execute the job one level higher\n await parsingContext.newOnValueJob(keys.slice(0, -1), value, depth - 1, false);\n // Remove any defined contexts at this level to avoid it to propagate to the next array element.\n parsingContext.contextTree.removeContext(keys.slice(0, -1));\n }\n }\n }\n async handleListElement(parsingContext, util, value, valueOriginal, depth, listRootKeys, listRootDepth) {\n // Buffer our value as an RDF list using the listRootKey as predicate\n let listPointer = parsingContext.listPointerStack[depth];\n if (valueOriginal !== null && (await util.unaliasKeywords(valueOriginal, listRootKeys, depth))['@value'] !== null) {\n if (!listPointer || !listPointer.value) {\n const linkTerm = util.dataFactory.blankNode();\n listPointer = { value: linkTerm, listRootDepth, listId: linkTerm };\n }\n else {\n // rdf:rest links are always emitted before the next element,\n // as the blank node identifier is only created at that point.\n // Because of this reason, the final rdf:nil is emitted when the stack depth is decreased.\n const newLinkTerm = util.dataFactory.blankNode();\n parsingContext.emitQuad(depth, util.dataFactory.quad(listPointer.value, util.rdfRest, newLinkTerm, util.getDefaultGraph()));\n // Update the list pointer for the next element\n listPointer.value = newLinkTerm;\n }\n // Emit a list element for the current value\n // Omit rdf:first if the value is invalid\n if (value) {\n parsingContext.emitQuad(depth, util.dataFactory.quad(listPointer.value, util.rdfFirst, value, util.getDefaultGraph()));\n }\n }\n else {\n // A falsy list element if found.\n // Mark it as an rdf:nil list until another valid list element comes in\n if (!listPointer) {\n listPointer = { listRootDepth, listId: util.rdfNil };\n }\n }\n parsingContext.listPointerStack[depth] = listPointer;\n // Error if an annotation was defined\n if (parsingContext.rdfstar && parsingContext.annotationsBuffer[depth]) {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found an illegal annotation inside a list`, jsonld_context_parser_1.ERROR_CODES.INVALID_ANNOTATION));\n }\n }\n}\nexports.EntryHandlerArrayValue = EntryHandlerArrayValue;\n//# sourceMappingURL=EntryHandlerArrayValue.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerContainer = void 0;\nconst ContainerHandlerIdentifier_1 = require(\"../containerhandler/ContainerHandlerIdentifier\");\nconst ContainerHandlerIndex_1 = require(\"../containerhandler/ContainerHandlerIndex\");\nconst ContainerHandlerLanguage_1 = require(\"../containerhandler/ContainerHandlerLanguage\");\nconst ContainerHandlerType_1 = require(\"../containerhandler/ContainerHandlerType\");\nconst Util_1 = require(\"../Util\");\n/**\n * Handles values that are part of a container type (like @index),\n * as specified by {@link IContainerHandler}.\n */\nclass EntryHandlerContainer {\n /**\n * Check fit the given container is a simple @graph container.\n * Concretely, it will check if no @index or @id is active as well.\n * @param containers A container hash.\n */\n static isSimpleGraphContainer(containers) {\n return '@graph' in containers\n && (('@set' in containers && Object.keys(containers).length === 2) || Object.keys(containers).length === 1);\n }\n /**\n * Check fit the given container is a complex @graph container.\n * Concretely, it will check if @index or @id is active as well next to @graph.\n * @param containers A container hash.\n */\n static isComplexGraphContainer(containers) {\n return '@graph' in containers\n && (('@set' in containers && Object.keys(containers).length > 2)\n || (!('@set' in containers) && Object.keys(containers).length > 1));\n }\n /**\n * Create an graph container index that can be used for identifying a graph term inside the graphContainerTermStack.\n * @param containers The applicable containers.\n * @param depth The container depth.\n * @param keys The array of keys.\n * @return The graph index.\n */\n static getContainerGraphIndex(containers, depth, keys) {\n let isSimpleGraphContainer = EntryHandlerContainer.isSimpleGraphContainer(containers);\n let index = '';\n for (let i = depth; i < keys.length; i++) {\n if (!isSimpleGraphContainer || typeof keys[i] === 'number') {\n index += ':' + keys[i];\n }\n // Only allow a second 'real' key if in a non-simple graph container.\n if (!isSimpleGraphContainer && typeof keys[i] !== 'number') {\n isSimpleGraphContainer = true;\n }\n }\n return index;\n }\n /**\n * Return the applicable container type at the given depth.\n *\n * This will ignore any arrays in the key chain.\n *\n * @param {ParsingContext} parsingContext A parsing context.\n * @param {any[]} keys The array of keys.\n * @param {number} depth The current depth.\n * @return {Promise<{ containers: {[typeName: string]: boolean}, depth: number, fallback: boolean }>}\n * All applicable containers for the given depth,\n * the `depth` of the container root (can change when arrays are in the key chain),\n * and the `fallback` flag that indicates if the default container type was returned\n * (i.e., no dedicated container type is defined).\n */\n static async getContainerHandler(parsingContext, keys, depth) {\n const fallback = {\n containers: { '@set': true },\n depth,\n fallback: true,\n };\n // A flag that is enabled when @graph container should be tested in next iteration\n let checkGraphContainer = false;\n // Iterate from deeper to higher\n const context = await parsingContext.getContext(keys, 2);\n for (let i = depth - 1; i >= 0; i--) {\n if (typeof keys[i] !== 'number') { // Skip array keys\n // @graph containers without any other types are one level less deep, and require special handling\n const containersSelf = Util_1.Util.getContextValue(context, '@container', keys[i], false);\n if (containersSelf && EntryHandlerContainer.isSimpleGraphContainer(containersSelf)) {\n return {\n containers: containersSelf,\n depth: i + 1,\n fallback: false,\n };\n }\n const containersParent = Util_1.Util.getContextValue(context, '@container', keys[i - 1], false);\n if (!containersParent) { // If we have the fallback container value\n if (checkGraphContainer) {\n // Return false if we were already expecting a @graph-@id of @graph-@index container\n return fallback;\n }\n // Check parent-parent, we may be in a @graph-@id of @graph-@index container, which have two levels\n checkGraphContainer = true;\n }\n else {\n // We had an invalid container next iteration, so we now have to check if we were in an @graph container\n const graphContainer = '@graph' in containersParent;\n // We're in a regular container\n for (const containerHandleName in EntryHandlerContainer.CONTAINER_HANDLERS) {\n if (containersParent[containerHandleName]) {\n if (graphContainer) {\n // Only accept graph containers if their combined handlers can handle them.\n if (EntryHandlerContainer.CONTAINER_HANDLERS[containerHandleName].canCombineWithGraph()) {\n return {\n containers: containersParent,\n depth: i,\n fallback: false,\n };\n }\n else {\n return fallback;\n }\n }\n else {\n // Only accept if we were not expecting a @graph-@id of @graph-@index container\n if (checkGraphContainer) {\n return fallback;\n }\n else {\n return {\n containers: containersParent,\n depth: i,\n fallback: false,\n };\n }\n }\n }\n }\n // Fail if no valid container handlers were found\n return fallback;\n }\n }\n }\n return fallback;\n }\n /**\n * Check if we are handling a value at the given depth\n * that is part of something that should be handled as a container,\n * AND if this container should be buffered, so that it can be handled by a dedicated container handler.\n *\n * For instance, any container with @graph will NOT be buffered.\n *\n * This will ignore any arrays in the key chain.\n *\n * @param {ParsingContext} parsingContext A parsing context.\n * @param {any[]} keys The array of keys.\n * @param {number} depth The current depth.\n * @return {Promise} If we are in the scope of a container handler.\n */\n static async isBufferableContainerHandler(parsingContext, keys, depth) {\n const handler = await EntryHandlerContainer.getContainerHandler(parsingContext, keys, depth);\n return !handler.fallback && !('@graph' in handler.containers);\n }\n isPropertyHandler() {\n return false;\n }\n isStackProcessor() {\n return true;\n }\n async validate(parsingContext, util, keys, depth, inProperty) {\n return !!await this.test(parsingContext, util, null, keys, depth);\n }\n async test(parsingContext, util, key, keys, depth) {\n const containers = Util_1.Util.getContextValueContainer(await parsingContext.getContext(keys, 2), keys[depth - 1]);\n for (const containerName in EntryHandlerContainer.CONTAINER_HANDLERS) {\n if (containers[containerName]) {\n return {\n containers,\n handler: EntryHandlerContainer.CONTAINER_HANDLERS[containerName],\n };\n }\n }\n return null;\n }\n async handle(parsingContext, util, key, keys, value, depth, testResult) {\n return testResult.handler.handle(testResult.containers, parsingContext, util, keys, value, depth);\n }\n}\nEntryHandlerContainer.CONTAINER_HANDLERS = {\n '@id': new ContainerHandlerIdentifier_1.ContainerHandlerIdentifier(),\n '@index': new ContainerHandlerIndex_1.ContainerHandlerIndex(),\n '@language': new ContainerHandlerLanguage_1.ContainerHandlerLanguage(),\n '@type': new ContainerHandlerType_1.ContainerHandlerType(),\n};\nexports.EntryHandlerContainer = EntryHandlerContainer;\n//# sourceMappingURL=EntryHandlerContainer.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerInvalidFallback = void 0;\n/**\n * A catch-all for properties, that will either emit an error or ignore,\n * depending on whether or not the `strictValues` property is set.\n */\nclass EntryHandlerInvalidFallback {\n isPropertyHandler() {\n return false;\n }\n isStackProcessor() {\n return true;\n }\n async validate(parsingContext, util, keys, depth, inProperty) {\n return false;\n }\n async test(parsingContext, util, key, keys, depth) {\n return true;\n }\n async handle(parsingContext, util, key, keys, value, depth) {\n parsingContext.emittedStack[depth] = false;\n }\n}\nexports.EntryHandlerInvalidFallback = EntryHandlerInvalidFallback;\n//# sourceMappingURL=EntryHandlerInvalidFallback.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerPredicate = void 0;\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\nconst Util_1 = require(\"../Util\");\n/**\n * Interprets keys as predicates.\n * The most common case in JSON-LD processing.\n */\nclass EntryHandlerPredicate {\n /**\n * Handle the given predicate-object by either emitting it,\n * or by placing it in the appropriate stack for later emission when no @graph and/or @id has been defined.\n * @param {ParsingContext} parsingContext A parsing context.\n * @param {Util} util A utility instance.\n * @param {any[]} keys A stack of keys.\n * @param {number} depth The current depth.\n * @param {Term} predicate The predicate.\n * @param {Term} object The object.\n * @param {boolean} reverse If the property is reversed.\n * @param {boolean} isEmbedded If the property exists in an embedded node as direct child.\n * @param {boolean} isAnnotation If the property exists in an annotation object.\n * @return {Promise} A promise resolving when handling is done.\n */\n static async handlePredicateObject(parsingContext, util, keys, depth, predicate, object, reverse, isEmbedded, isAnnotation) {\n const depthProperties = await util.getPropertiesDepth(keys, depth);\n const depthOffsetGraph = await util.getDepthOffsetGraph(depth, keys);\n const depthPropertiesGraph = depth - depthOffsetGraph;\n const subjects = parsingContext.idStack[depthProperties];\n if (subjects && !isAnnotation) {\n // Emit directly if the @id was already defined\n for (const subject of subjects) {\n // Check if we're in a @graph context\n const atGraph = depthOffsetGraph >= 0;\n if (atGraph) {\n const graphs = parsingContext.idStack[depthPropertiesGraph - 1];\n if (graphs) {\n for (const graph of graphs) {\n // Emit our quad if graph @id is known\n util.emitQuadChecked(depth, subject, predicate, object, graph, reverse, isEmbedded);\n }\n }\n else {\n // Buffer our triple if graph @id is not known yet.\n if (reverse) {\n util.validateReverseSubject(object);\n parsingContext.getUnidentifiedGraphBufferSafe(depthPropertiesGraph - 1).push({ subject: object, predicate, object: subject, isEmbedded });\n }\n else {\n parsingContext.getUnidentifiedGraphBufferSafe(depthPropertiesGraph - 1)\n .push({ subject, predicate, object, isEmbedded });\n }\n }\n }\n else {\n // Emit if no @graph was applicable\n const graph = await util.getGraphContainerValue(keys, depthProperties);\n util.emitQuadChecked(depth, subject, predicate, object, graph, reverse, isEmbedded);\n }\n }\n }\n else {\n // Buffer until our @id becomes known, or we go up the stack\n if (reverse) {\n util.validateReverseSubject(object);\n }\n // Either push to the annotations or the actual value buffer\n if (isAnnotation) {\n // Only add to buffer if rdfstar is enabled\n if (parsingContext.rdfstar) {\n // Error if an @id was defined\n if (parsingContext.idStack[depth]) {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found an illegal @id inside an annotation: ${parsingContext.idStack[depth][0].value}`, jsonld_context_parser_1.ERROR_CODES.INVALID_ANNOTATION));\n }\n // Error if we're in an embedded node\n for (let i = 0; i < depth; i++) {\n if (await util.unaliasKeyword(keys[i], keys, i) === '@id') {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found an illegal annotation inside an embedded node`, jsonld_context_parser_1.ERROR_CODES.INVALID_ANNOTATION));\n }\n }\n // Store new annotation in the buffer\n const annotationsBuffer = parsingContext.getAnnotationsBufferSafe(depthProperties);\n const newAnnotation = { predicate, object, reverse, nestedAnnotations: [], depth: depthProperties };\n annotationsBuffer.push(newAnnotation);\n // Check in the buffer if any annotations were defined at a deeper depth,\n // if so, they are considered nested annotations.\n for (let i = annotationsBuffer.length - 2; i >= 0; i--) {\n // We iterate in reverse order, to enable easy item removal from the back.\n const existingAnnotation = annotationsBuffer[i];\n if (existingAnnotation.depth > depthProperties) {\n newAnnotation.nestedAnnotations.push(existingAnnotation);\n annotationsBuffer.splice(i, 1);\n }\n }\n }\n }\n else {\n parsingContext.getUnidentifiedValueBufferSafe(depthProperties).push({ predicate, object, reverse, isEmbedded });\n }\n }\n }\n isPropertyHandler() {\n return true;\n }\n isStackProcessor() {\n return true;\n }\n async validate(parsingContext, util, keys, depth, inProperty) {\n const key = keys[depth];\n if (key) {\n const context = await parsingContext.getContext(keys);\n if (!parsingContext.jsonLiteralStack[depth] && await util.predicateToTerm(context, keys[depth])) {\n // If this valid predicate is of type @json, mark it so in the stack so that no deeper handling of nodes occurs.\n if (Util_1.Util.getContextValueType(context, key) === '@json') {\n parsingContext.jsonLiteralStack[depth + 1] = true;\n }\n return true;\n }\n }\n return false;\n }\n async test(parsingContext, util, key, keys, depth) {\n return keys[depth];\n }\n async handle(parsingContext, util, key, keys, value, depth, testResult) {\n const keyOriginal = keys[depth];\n const context = await parsingContext.getContext(keys);\n const predicate = await util.predicateToTerm(context, key);\n if (predicate) {\n const objects = await util.valueToTerm(context, key, value, depth, keys);\n if (objects.length) {\n for (let object of objects) {\n // Based on parent key, check if reverse, embedded, and annotation.\n let parentKey = await util.unaliasKeywordParent(keys, depth);\n const reverse = Util_1.Util.isPropertyReverse(context, keyOriginal, parentKey);\n let parentDepthOffset = 0;\n while (parentKey === '@reverse' || typeof parentKey === 'number') {\n // Check parent of parent when checking while we're in an array or in @reverse\n if (typeof parentKey === 'number') {\n parentDepthOffset++;\n }\n else {\n depth--;\n }\n parentKey = await util.unaliasKeywordParent(keys, depth - parentDepthOffset);\n }\n const isEmbedded = Util_1.Util.isPropertyInEmbeddedNode(parentKey);\n util.validateReverseInEmbeddedNode(key, reverse, isEmbedded);\n const isAnnotation = Util_1.Util.isPropertyInAnnotationObject(parentKey);\n if (value) {\n // Special case if our term was defined as an @list, but does not occur in an array,\n // In that case we just emit it as an RDF list with a single element.\n const listValueContainer = '@list' in Util_1.Util.getContextValueContainer(context, key);\n if (listValueContainer || value['@list']) {\n if (((listValueContainer && !Array.isArray(value) && !value['@list'])\n || (value['@list'] && !Array.isArray(value['@list'])))\n && object !== util.rdfNil) {\n const listPointer = util.dataFactory.blankNode();\n parsingContext.emitQuad(depth, util.dataFactory.quad(listPointer, util.rdfRest, util.rdfNil, util.getDefaultGraph()));\n parsingContext.emitQuad(depth, util.dataFactory.quad(listPointer, util.rdfFirst, object, util.getDefaultGraph()));\n object = listPointer;\n }\n // Lists are not allowed in @reverse'd properties\n if (reverse && !parsingContext.allowSubjectList) {\n throw new jsonld_context_parser_1.ErrorCoded(`Found illegal list value in subject position at ${key}`, jsonld_context_parser_1.ERROR_CODES.INVALID_REVERSE_PROPERTY_VALUE);\n }\n }\n }\n await EntryHandlerPredicate.handlePredicateObject(parsingContext, util, keys, depth, predicate, object, reverse, isEmbedded, isAnnotation);\n }\n }\n }\n }\n}\nexports.EntryHandlerPredicate = EntryHandlerPredicate;\n//# sourceMappingURL=EntryHandlerPredicate.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerKeyword = void 0;\n/**\n * An abstract keyword entry handler.\n */\nclass EntryHandlerKeyword {\n constructor(keyword) {\n this.keyword = keyword;\n }\n isPropertyHandler() {\n return false;\n }\n isStackProcessor() {\n return true;\n }\n async validate(parsingContext, util, keys, depth, inProperty) {\n return false;\n }\n async test(parsingContext, util, key, keys, depth) {\n return key === this.keyword;\n }\n}\nexports.EntryHandlerKeyword = EntryHandlerKeyword;\n//# sourceMappingURL=EntryHandlerKeyword.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerKeywordAnnotation = void 0;\nconst EntryHandlerKeyword_1 = require(\"./EntryHandlerKeyword\");\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\n/**\n * Handles @annotation entries.\n */\nclass EntryHandlerKeywordAnnotation extends EntryHandlerKeyword_1.EntryHandlerKeyword {\n constructor() {\n super('@annotation');\n }\n async handle(parsingContext, util, key, keys, value, depth) {\n // Validate value\n if (typeof value === 'string' || (typeof value === 'object' && value['@value'])) {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found illegal annotation value: ${JSON.stringify(value)}`, jsonld_context_parser_1.ERROR_CODES.INVALID_ANNOTATION));\n }\n // Rest of the processing is done as regular nodes\n }\n}\nexports.EntryHandlerKeywordAnnotation = EntryHandlerKeywordAnnotation;\n//# sourceMappingURL=EntryHandlerKeywordAnnotation.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerKeywordContext = void 0;\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\nconst EntryHandlerKeyword_1 = require(\"./EntryHandlerKeyword\");\n/**\n * Handles @context entries.\n */\nclass EntryHandlerKeywordContext extends EntryHandlerKeyword_1.EntryHandlerKeyword {\n constructor() {\n super('@context');\n }\n isStackProcessor() {\n return false;\n }\n async handle(parsingContext, util, key, keys, value, depth) {\n // Error if an out-of-order context was found when support is not enabled.\n if (parsingContext.streamingProfile\n && (parsingContext.processingStack[depth]\n || parsingContext.processingType[depth]\n || parsingContext.idStack[depth] !== undefined)) {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded('Found an out-of-order context, while streaming is enabled.' +\n '(disable `streamingProfile`)', jsonld_context_parser_1.ERROR_CODES.INVALID_STREAMING_KEY_ORDER));\n }\n // Find the parent context to inherit from.\n // We actually request a context for the current depth (with fallback to parent)\n // because we want to take into account any property-scoped contexts that are defined for this depth.\n const parentContext = parsingContext.getContext(keys);\n // Set the context for this scope\n const context = parsingContext.parseContext(value, (await parentContext).getContextRaw());\n parsingContext.contextTree.setContext(keys.slice(0, -1), context);\n parsingContext.emitContext(value);\n await parsingContext.validateContext(await context);\n }\n}\nexports.EntryHandlerKeywordContext = EntryHandlerKeywordContext;\n//# sourceMappingURL=EntryHandlerKeywordContext.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerKeywordGraph = void 0;\nconst EntryHandlerKeyword_1 = require(\"./EntryHandlerKeyword\");\n/**\n * Handles @graph entries.\n */\nclass EntryHandlerKeywordGraph extends EntryHandlerKeyword_1.EntryHandlerKeyword {\n constructor() {\n super('@graph');\n }\n async handle(parsingContext, util, key, keys, value, depth) {\n // The current identifier identifies a graph for the deeper level.\n parsingContext.graphStack[depth + 1] = true;\n }\n}\nexports.EntryHandlerKeywordGraph = EntryHandlerKeywordGraph;\n//# sourceMappingURL=EntryHandlerKeywordGraph.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerKeywordId = void 0;\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\nconst EntryHandlerKeyword_1 = require(\"./EntryHandlerKeyword\");\n/**\n * Handles @id entries.\n */\nclass EntryHandlerKeywordId extends EntryHandlerKeyword_1.EntryHandlerKeyword {\n constructor() {\n super('@id');\n }\n isStackProcessor() {\n return false;\n }\n async handle(parsingContext, util, key, keys, value, depth) {\n if (typeof value !== 'string') {\n // JSON-LD-star allows @id object values\n if (parsingContext.rdfstar && typeof value === 'object') {\n const valueKeys = Object.keys(value);\n if (valueKeys.length === 1 && valueKeys[0] === '@id') {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Invalid embedded node without property with @id ${value['@id']}`, jsonld_context_parser_1.ERROR_CODES.INVALID_EMBEDDED_NODE));\n }\n }\n else {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found illegal @id '${value}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_ID_VALUE));\n }\n return;\n }\n // Determine the canonical place for this id.\n // For example, @nest parents should be ignored.\n const depthProperties = await util.getPropertiesDepth(keys, depth);\n // Error if an @id for this node already existed.\n if (parsingContext.idStack[depthProperties] !== undefined) {\n if (parsingContext.idStack[depthProperties][0].listHead) {\n // Error if an @list was already defined for this node\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found illegal neighbouring entries next to @list for key: '${keys[depth - 1]}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_SET_OR_LIST_OBJECT));\n }\n else {\n // Otherwise, the previous id was just because of an @id entry.\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found duplicate @ids '${parsingContext\n .idStack[depthProperties][0].value}' and '${value}'`, jsonld_context_parser_1.ERROR_CODES.COLLIDING_KEYWORDS));\n }\n }\n // Error if an annotation was defined\n if (parsingContext.rdfstar && parsingContext.annotationsBuffer[depth]) {\n for (const annotation of parsingContext.annotationsBuffer[depth]) {\n if (annotation.depth === depth) {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found an illegal @id inside an annotation: ${value}`, jsonld_context_parser_1.ERROR_CODES.INVALID_ANNOTATION));\n }\n }\n }\n // Save our @id on the stack\n parsingContext.idStack[depthProperties] = util.nullableTermToArray(await util.resourceToTerm(await parsingContext.getContext(keys), value));\n }\n}\nexports.EntryHandlerKeywordId = EntryHandlerKeywordId;\n//# sourceMappingURL=EntryHandlerKeywordId.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerKeywordIncluded = void 0;\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\nconst EntryHandlerKeyword_1 = require(\"./EntryHandlerKeyword\");\n/**\n * Handles @included entries.\n */\nclass EntryHandlerKeywordIncluded extends EntryHandlerKeyword_1.EntryHandlerKeyword {\n constructor() {\n super('@included');\n }\n async handle(parsingContext, util, key, keys, value, depth) {\n if (typeof value !== 'object') {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found illegal @included '${value}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_INCLUDED_VALUE));\n }\n const valueUnliased = await util.unaliasKeywords(value, keys, depth, await parsingContext.getContext(keys));\n if ('@value' in valueUnliased) {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found an illegal @included @value node '${JSON.stringify(value)}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_INCLUDED_VALUE));\n }\n if ('@list' in valueUnliased) {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found an illegal @included @list node '${JSON.stringify(value)}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_INCLUDED_VALUE));\n }\n parsingContext.emittedStack[depth] = false;\n }\n}\nexports.EntryHandlerKeywordIncluded = EntryHandlerKeywordIncluded;\n//# sourceMappingURL=EntryHandlerKeywordIncluded.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerKeywordNest = void 0;\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\nconst EntryHandlerKeyword_1 = require(\"./EntryHandlerKeyword\");\n/**\n * Handles @nest entries.\n */\nclass EntryHandlerKeywordNest extends EntryHandlerKeyword_1.EntryHandlerKeyword {\n constructor() {\n super('@nest');\n }\n async handle(parsingContext, util, key, keys, value, depth) {\n if (typeof value !== 'object') {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found invalid @nest entry for '${key}': '${value}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_NEST_VALUE));\n }\n if ('@value' in await util.unaliasKeywords(value, keys, depth, await parsingContext.getContext(keys))) {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found an invalid @value node for '${key}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_NEST_VALUE));\n }\n parsingContext.emittedStack[depth] = false;\n }\n}\nexports.EntryHandlerKeywordNest = EntryHandlerKeywordNest;\n//# sourceMappingURL=EntryHandlerKeywordNest.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerKeywordType = void 0;\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\nconst Util_1 = require(\"../../Util\");\nconst EntryHandlerPredicate_1 = require(\"../EntryHandlerPredicate\");\nconst EntryHandlerKeyword_1 = require(\"./EntryHandlerKeyword\");\n/**\n * Handles @graph entries.\n */\nclass EntryHandlerKeywordType extends EntryHandlerKeyword_1.EntryHandlerKeyword {\n constructor() {\n super('@type');\n }\n isStackProcessor() {\n return false;\n }\n async handle(parsingContext, util, key, keys, value, depth) {\n const keyOriginal = keys[depth];\n // The current identifier identifies an rdf:type predicate.\n // But we only emit it once the node closes,\n // as it's possible that the @type is used to identify the datatype of a literal, which we ignore here.\n const context = await parsingContext.getContext(keys);\n const predicate = util.rdfType;\n const parentKey = await util.unaliasKeywordParent(keys, depth);\n const reverse = Util_1.Util.isPropertyReverse(context, keyOriginal, parentKey);\n const isEmbedded = Util_1.Util.isPropertyInEmbeddedNode(parentKey);\n util.validateReverseInEmbeddedNode(key, reverse, isEmbedded);\n const isAnnotation = Util_1.Util.isPropertyInAnnotationObject(parentKey);\n // Handle multiple values if the value is an array\n const elements = Array.isArray(value) ? value : [value];\n for (const element of elements) {\n if (typeof element !== 'string') {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found illegal @type '${element}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_TYPE_VALUE));\n }\n const type = util.createVocabOrBaseTerm(context, element);\n if (type) {\n await EntryHandlerPredicate_1.EntryHandlerPredicate.handlePredicateObject(parsingContext, util, keys, depth, predicate, type, reverse, isEmbedded, isAnnotation);\n }\n }\n // Collect type-scoped contexts if they exist\n let scopedContext = Promise.resolve(context);\n let hasTypedScopedContext = false;\n for (const element of elements.sort()) { // Spec requires lexicographical ordering\n const typeContext = Util_1.Util.getContextValue(context, '@context', element, null);\n if (typeContext) {\n hasTypedScopedContext = true;\n scopedContext = scopedContext.then((c) => parsingContext.parseContext(typeContext, c.getContextRaw()));\n }\n }\n // Error if an out-of-order type-scoped context was found when support is not enabled.\n if (parsingContext.streamingProfile\n && (hasTypedScopedContext || !parsingContext.streamingProfileAllowOutOfOrderPlainType)\n && (parsingContext.processingStack[depth] || parsingContext.idStack[depth])) {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded('Found an out-of-order type-scoped context, while streaming is enabled.' +\n '(disable `streamingProfile`)', jsonld_context_parser_1.ERROR_CODES.INVALID_STREAMING_KEY_ORDER));\n }\n // If at least least one type-scoped context applies, set them in the tree.\n if (hasTypedScopedContext) {\n // Do not propagate by default\n scopedContext = scopedContext.then((c) => {\n // Set the original context at this depth as a fallback\n // This is needed when a context was already defined at the given depth,\n // and this context needs to remain accessible from child nodes when propagation is disabled.\n if (c.getContextRaw()['@propagate'] !== true) {\n return new jsonld_context_parser_1.JsonLdContextNormalized(Object.assign(Object.assign({}, c.getContextRaw()), { '@propagate': false, '@__propagateFallback': context.getContextRaw() }));\n }\n return c;\n });\n // Set the new context in the context tree\n parsingContext.contextTree.setContext(keys.slice(0, keys.length - 1), scopedContext);\n }\n // Flag that type has been processed at this depth\n parsingContext.processingType[depth] = true;\n }\n}\nexports.EntryHandlerKeywordType = EntryHandlerKeywordType;\n//# sourceMappingURL=EntryHandlerKeywordType.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerKeywordUnknownFallback = void 0;\nconst jsonld_context_parser_1 = require(\"jsonld-context-parser\");\n/**\n * A catch-all for keywords, that will either emit an error or ignore,\n * depending on whether or not the `strictValues` property is set.\n */\nclass EntryHandlerKeywordUnknownFallback {\n isPropertyHandler() {\n return false;\n }\n isStackProcessor() {\n return true;\n }\n async validate(parsingContext, util, keys, depth, inProperty) {\n const key = await util.unaliasKeyword(keys[depth], keys, depth);\n if (jsonld_context_parser_1.Util.isPotentialKeyword(key)) {\n // Don't emit anything inside free-floating lists\n if (!inProperty) {\n if (key === '@list') {\n return false;\n }\n }\n return true;\n }\n return false;\n }\n async test(parsingContext, util, key, keys, depth) {\n return jsonld_context_parser_1.Util.isPotentialKeyword(key);\n }\n async handle(parsingContext, util, key, keys, value, depth) {\n const keywordType = EntryHandlerKeywordUnknownFallback.VALID_KEYWORDS_TYPES[key];\n if (keywordType !== undefined) {\n if (keywordType && typeof value !== keywordType.type) {\n parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Invalid value type for '${key}' with value '${value}'`, keywordType.errorCode));\n }\n }\n else if (parsingContext.strictValues) {\n parsingContext.emitError(new Error(`Unknown keyword '${key}' with value '${value}'`));\n }\n parsingContext.emittedStack[depth] = false;\n }\n}\nEntryHandlerKeywordUnknownFallback.VALID_KEYWORDS_TYPES = {\n '@index': { type: 'string', errorCode: jsonld_context_parser_1.ERROR_CODES.INVALID_INDEX_VALUE },\n '@list': null,\n '@reverse': { type: 'object', errorCode: jsonld_context_parser_1.ERROR_CODES.INVALID_REVERSE_VALUE },\n '@set': null,\n '@value': null,\n};\nexports.EntryHandlerKeywordUnknownFallback = EntryHandlerKeywordUnknownFallback;\n//# sourceMappingURL=EntryHandlerKeywordUnknownFallback.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EntryHandlerKeywordValue = void 0;\nconst EntryHandlerKeyword_1 = require(\"./EntryHandlerKeyword\");\n/**\n * Handles @value entries.\n */\nclass EntryHandlerKeywordValue extends EntryHandlerKeyword_1.EntryHandlerKeyword {\n constructor() {\n super('@value');\n }\n async validate(parsingContext, util, keys, depth, inProperty) {\n // If this is @value, mark it so in the stack so that no deeper handling of nodes occurs.\n const key = keys[depth];\n if (key && !parsingContext.literalStack[depth] && await this.test(parsingContext, util, key, keys, depth)) {\n parsingContext.literalStack[depth] = true;\n }\n return super.validate(parsingContext, util, keys, depth, inProperty);\n }\n async test(parsingContext, util, key, keys, depth) {\n return await util.unaliasKeyword(keys[depth], keys.slice(0, keys.length - 1), depth - 1, true) === '@value';\n }\n async handle(parsingContext, util, key, keys, value, depth) {\n // If the value is valid, indicate that we are processing a literal.\n // The actual value will be determined at the parent level when the @value is part of an object,\n // because we may want to take into account additional entries such as @language.\n // See {@link Util.valueToTerm}\n // Indicate that we are processing a literal, and that no later predicates should be parsed at this depth.\n parsingContext.literalStack[depth] = true;\n // Void any buffers that we may have accumulated up until now\n delete parsingContext.unidentifiedValuesBuffer[depth];\n delete parsingContext.unidentifiedGraphsBuffer[depth];\n // Indicate that we have not emitted at this depth\n parsingContext.emittedStack[depth] = false;\n }\n}\nexports.EntryHandlerKeywordValue = EntryHandlerKeywordValue;\n//# sourceMappingURL=EntryHandlerKeywordValue.js.map","'use strict'\n\nconst { SymbolDispose } = require('../../ours/primordials')\nconst { AbortError, codes } = require('../../ours/errors')\nconst { isNodeStream, isWebStream, kControllerErrorFunction } = require('./utils')\nconst eos = require('./end-of-stream')\nconst { ERR_INVALID_ARG_TYPE } = codes\nlet addAbortListener\n\n// This method is inlined here for readable-stream\n// It also does not allow for signal to not exist on the stream\n// https://github.com/nodejs/node/pull/36061#discussion_r533718029\nconst validateAbortSignal = (signal, name) => {\n if (typeof signal !== 'object' || !('aborted' in signal)) {\n throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n }\n}\nmodule.exports.addAbortSignal = function addAbortSignal(signal, stream) {\n validateAbortSignal(signal, 'signal')\n if (!isNodeStream(stream) && !isWebStream(stream)) {\n throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream)\n }\n return module.exports.addAbortSignalNoValidate(signal, stream)\n}\nmodule.exports.addAbortSignalNoValidate = function (signal, stream) {\n if (typeof signal !== 'object' || !('aborted' in signal)) {\n return stream\n }\n const onAbort = isNodeStream(stream)\n ? () => {\n stream.destroy(\n new AbortError(undefined, {\n cause: signal.reason\n })\n )\n }\n : () => {\n stream[kControllerErrorFunction](\n new AbortError(undefined, {\n cause: signal.reason\n })\n )\n }\n if (signal.aborted) {\n onAbort()\n } else {\n addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n const disposable = addAbortListener(signal, onAbort)\n eos(stream, disposable[SymbolDispose])\n }\n return stream\n}\n","'use strict'\n\nconst { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = require('../../ours/primordials')\nconst { Buffer } = require('buffer')\nconst { inspect } = require('../../ours/util')\nmodule.exports = class BufferList {\n constructor() {\n this.head = null\n this.tail = null\n this.length = 0\n }\n push(v) {\n const entry = {\n data: v,\n next: null\n }\n if (this.length > 0) this.tail.next = entry\n else this.head = entry\n this.tail = entry\n ++this.length\n }\n unshift(v) {\n const entry = {\n data: v,\n next: this.head\n }\n if (this.length === 0) this.tail = entry\n this.head = entry\n ++this.length\n }\n shift() {\n if (this.length === 0) return\n const ret = this.head.data\n if (this.length === 1) this.head = this.tail = null\n else this.head = this.head.next\n --this.length\n return ret\n }\n clear() {\n this.head = this.tail = null\n this.length = 0\n }\n join(s) {\n if (this.length === 0) return ''\n let p = this.head\n let ret = '' + p.data\n while ((p = p.next) !== null) ret += s + p.data\n return ret\n }\n concat(n) {\n if (this.length === 0) return Buffer.alloc(0)\n const ret = Buffer.allocUnsafe(n >>> 0)\n let p = this.head\n let i = 0\n while (p) {\n TypedArrayPrototypeSet(ret, p.data, i)\n i += p.data.length\n p = p.next\n }\n return ret\n }\n\n // Consumes a specified amount of bytes or characters from the buffered data.\n consume(n, hasStrings) {\n const data = this.head.data\n if (n < data.length) {\n // `slice` is the same for buffers and strings.\n const slice = data.slice(0, n)\n this.head.data = data.slice(n)\n return slice\n }\n if (n === data.length) {\n // First chunk is a perfect match.\n return this.shift()\n }\n // Result spans more than one buffer.\n return hasStrings ? this._getString(n) : this._getBuffer(n)\n }\n first() {\n return this.head.data\n }\n *[SymbolIterator]() {\n for (let p = this.head; p; p = p.next) {\n yield p.data\n }\n }\n\n // Consumes a specified amount of characters from the buffered data.\n _getString(n) {\n let ret = ''\n let p = this.head\n let c = 0\n do {\n const str = p.data\n if (n > str.length) {\n ret += str\n n -= str.length\n } else {\n if (n === str.length) {\n ret += str\n ++c\n if (p.next) this.head = p.next\n else this.head = this.tail = null\n } else {\n ret += StringPrototypeSlice(str, 0, n)\n this.head = p\n p.data = StringPrototypeSlice(str, n)\n }\n break\n }\n ++c\n } while ((p = p.next) !== null)\n this.length -= c\n return ret\n }\n\n // Consumes a specified amount of bytes from the buffered data.\n _getBuffer(n) {\n const ret = Buffer.allocUnsafe(n)\n const retLen = n\n let p = this.head\n let c = 0\n do {\n const buf = p.data\n if (n > buf.length) {\n TypedArrayPrototypeSet(ret, buf, retLen - n)\n n -= buf.length\n } else {\n if (n === buf.length) {\n TypedArrayPrototypeSet(ret, buf, retLen - n)\n ++c\n if (p.next) this.head = p.next\n else this.head = this.tail = null\n } else {\n TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n)\n this.head = p\n p.data = buf.slice(n)\n }\n break\n }\n ++c\n } while ((p = p.next) !== null)\n this.length -= c\n return ret\n }\n\n // Make sure the linked list only shows the minimal necessary information.\n [Symbol.for('nodejs.util.inspect.custom')](_, options) {\n return inspect(this, {\n ...options,\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n })\n }\n}\n","'use strict'\n\nconst { pipeline } = require('./pipeline')\nconst Duplex = require('./duplex')\nconst { destroyer } = require('./destroy')\nconst {\n isNodeStream,\n isReadable,\n isWritable,\n isWebStream,\n isTransformStream,\n isWritableStream,\n isReadableStream\n} = require('./utils')\nconst {\n AbortError,\n codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS }\n} = require('../../ours/errors')\nconst eos = require('./end-of-stream')\nmodule.exports = function compose(...streams) {\n if (streams.length === 0) {\n throw new ERR_MISSING_ARGS('streams')\n }\n if (streams.length === 1) {\n return Duplex.from(streams[0])\n }\n const orgStreams = [...streams]\n if (typeof streams[0] === 'function') {\n streams[0] = Duplex.from(streams[0])\n }\n if (typeof streams[streams.length - 1] === 'function') {\n const idx = streams.length - 1\n streams[idx] = Duplex.from(streams[idx])\n }\n for (let n = 0; n < streams.length; ++n) {\n if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) {\n // TODO(ronag): Add checks for non streams.\n continue\n }\n if (\n n < streams.length - 1 &&\n !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n]))\n ) {\n throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable')\n }\n if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) {\n throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable')\n }\n }\n let ondrain\n let onfinish\n let onreadable\n let onclose\n let d\n function onfinished(err) {\n const cb = onclose\n onclose = null\n if (cb) {\n cb(err)\n } else if (err) {\n d.destroy(err)\n } else if (!readable && !writable) {\n d.destroy()\n }\n }\n const head = streams[0]\n const tail = pipeline(streams, onfinished)\n const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head))\n const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail))\n\n // TODO(ronag): Avoid double buffering.\n // Implement Writable/Readable/Duplex traits.\n // See, https://github.com/nodejs/node/pull/33515.\n d = new Duplex({\n // TODO (ronag): highWaterMark?\n writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode),\n readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode),\n writable,\n readable\n })\n if (writable) {\n if (isNodeStream(head)) {\n d._write = function (chunk, encoding, callback) {\n if (head.write(chunk, encoding)) {\n callback()\n } else {\n ondrain = callback\n }\n }\n d._final = function (callback) {\n head.end()\n onfinish = callback\n }\n head.on('drain', function () {\n if (ondrain) {\n const cb = ondrain\n ondrain = null\n cb()\n }\n })\n } else if (isWebStream(head)) {\n const writable = isTransformStream(head) ? head.writable : head\n const writer = writable.getWriter()\n d._write = async function (chunk, encoding, callback) {\n try {\n await writer.ready\n writer.write(chunk).catch(() => {})\n callback()\n } catch (err) {\n callback(err)\n }\n }\n d._final = async function (callback) {\n try {\n await writer.ready\n writer.close().catch(() => {})\n onfinish = callback\n } catch (err) {\n callback(err)\n }\n }\n }\n const toRead = isTransformStream(tail) ? tail.readable : tail\n eos(toRead, () => {\n if (onfinish) {\n const cb = onfinish\n onfinish = null\n cb()\n }\n })\n }\n if (readable) {\n if (isNodeStream(tail)) {\n tail.on('readable', function () {\n if (onreadable) {\n const cb = onreadable\n onreadable = null\n cb()\n }\n })\n tail.on('end', function () {\n d.push(null)\n })\n d._read = function () {\n while (true) {\n const buf = tail.read()\n if (buf === null) {\n onreadable = d._read\n return\n }\n if (!d.push(buf)) {\n return\n }\n }\n }\n } else if (isWebStream(tail)) {\n const readable = isTransformStream(tail) ? tail.readable : tail\n const reader = readable.getReader()\n d._read = async function () {\n while (true) {\n try {\n const { value, done } = await reader.read()\n if (!d.push(value)) {\n return\n }\n if (done) {\n d.push(null)\n return\n }\n } catch {\n return\n }\n }\n }\n }\n }\n d._destroy = function (err, callback) {\n if (!err && onclose !== null) {\n err = new AbortError()\n }\n onreadable = null\n ondrain = null\n onfinish = null\n if (onclose === null) {\n callback(err)\n } else {\n onclose = callback\n if (isNodeStream(tail)) {\n destroyer(tail, err)\n }\n }\n }\n return d\n}\n","'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n aggregateTwoErrors,\n codes: { ERR_MULTIPLE_CALLBACK },\n AbortError\n} = require('../../ours/errors')\nconst { Symbol } = require('../../ours/primordials')\nconst { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require('./utils')\nconst kDestroy = Symbol('kDestroy')\nconst kConstruct = Symbol('kConstruct')\nfunction checkError(err, w, r) {\n if (err) {\n // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n err.stack // eslint-disable-line no-unused-expressions\n\n if (w && !w.errored) {\n w.errored = err\n }\n if (r && !r.errored) {\n r.errored = err\n }\n }\n}\n\n// Backwards compat. cb() is undocumented and unused in core but\n// unfortunately might be used by modules.\nfunction destroy(err, cb) {\n const r = this._readableState\n const w = this._writableState\n // With duplex streams we use the writable side for state.\n const s = w || r\n if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) {\n if (typeof cb === 'function') {\n cb()\n }\n return this\n }\n\n // We set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n checkError(err, w, r)\n if (w) {\n w.destroyed = true\n }\n if (r) {\n r.destroyed = true\n }\n\n // If still constructing then defer calling _destroy.\n if (!s.constructed) {\n this.once(kDestroy, function (er) {\n _destroy(this, aggregateTwoErrors(er, err), cb)\n })\n } else {\n _destroy(this, err, cb)\n }\n return this\n}\nfunction _destroy(self, err, cb) {\n let called = false\n function onDestroy(err) {\n if (called) {\n return\n }\n called = true\n const r = self._readableState\n const w = self._writableState\n checkError(err, w, r)\n if (w) {\n w.closed = true\n }\n if (r) {\n r.closed = true\n }\n if (typeof cb === 'function') {\n cb(err)\n }\n if (err) {\n process.nextTick(emitErrorCloseNT, self, err)\n } else {\n process.nextTick(emitCloseNT, self)\n }\n }\n try {\n self._destroy(err || null, onDestroy)\n } catch (err) {\n onDestroy(err)\n }\n}\nfunction emitErrorCloseNT(self, err) {\n emitErrorNT(self, err)\n emitCloseNT(self)\n}\nfunction emitCloseNT(self) {\n const r = self._readableState\n const w = self._writableState\n if (w) {\n w.closeEmitted = true\n }\n if (r) {\n r.closeEmitted = true\n }\n if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) {\n self.emit('close')\n }\n}\nfunction emitErrorNT(self, err) {\n const r = self._readableState\n const w = self._writableState\n if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) {\n return\n }\n if (w) {\n w.errorEmitted = true\n }\n if (r) {\n r.errorEmitted = true\n }\n self.emit('error', err)\n}\nfunction undestroy() {\n const r = this._readableState\n const w = this._writableState\n if (r) {\n r.constructed = true\n r.closed = false\n r.closeEmitted = false\n r.destroyed = false\n r.errored = null\n r.errorEmitted = false\n r.reading = false\n r.ended = r.readable === false\n r.endEmitted = r.readable === false\n }\n if (w) {\n w.constructed = true\n w.destroyed = false\n w.closed = false\n w.closeEmitted = false\n w.errored = null\n w.errorEmitted = false\n w.finalCalled = false\n w.prefinished = false\n w.ended = w.writable === false\n w.ending = w.writable === false\n w.finished = w.writable === false\n }\n}\nfunction errorOrDestroy(stream, err, sync) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n\n const r = stream._readableState\n const w = stream._writableState\n if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) {\n return this\n }\n if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy))\n stream.destroy(err)\n else if (err) {\n // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n err.stack // eslint-disable-line no-unused-expressions\n\n if (w && !w.errored) {\n w.errored = err\n }\n if (r && !r.errored) {\n r.errored = err\n }\n if (sync) {\n process.nextTick(emitErrorNT, stream, err)\n } else {\n emitErrorNT(stream, err)\n }\n }\n}\nfunction construct(stream, cb) {\n if (typeof stream._construct !== 'function') {\n return\n }\n const r = stream._readableState\n const w = stream._writableState\n if (r) {\n r.constructed = false\n }\n if (w) {\n w.constructed = false\n }\n stream.once(kConstruct, cb)\n if (stream.listenerCount(kConstruct) > 1) {\n // Duplex\n return\n }\n process.nextTick(constructNT, stream)\n}\nfunction constructNT(stream) {\n let called = false\n function onConstruct(err) {\n if (called) {\n errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK())\n return\n }\n called = true\n const r = stream._readableState\n const w = stream._writableState\n const s = w || r\n if (r) {\n r.constructed = true\n }\n if (w) {\n w.constructed = true\n }\n if (s.destroyed) {\n stream.emit(kDestroy, err)\n } else if (err) {\n errorOrDestroy(stream, err, true)\n } else {\n process.nextTick(emitConstructNT, stream)\n }\n }\n try {\n stream._construct((err) => {\n process.nextTick(onConstruct, err)\n })\n } catch (err) {\n process.nextTick(onConstruct, err)\n }\n}\nfunction emitConstructNT(stream) {\n stream.emit(kConstruct)\n}\nfunction isRequest(stream) {\n return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function'\n}\nfunction emitCloseLegacy(stream) {\n stream.emit('close')\n}\nfunction emitErrorCloseLegacy(stream, err) {\n stream.emit('error', err)\n process.nextTick(emitCloseLegacy, stream)\n}\n\n// Normalize destroy for legacy.\nfunction destroyer(stream, err) {\n if (!stream || isDestroyed(stream)) {\n return\n }\n if (!err && !isFinished(stream)) {\n err = new AbortError()\n }\n\n // TODO: Remove isRequest branches.\n if (isServerRequest(stream)) {\n stream.socket = null\n stream.destroy(err)\n } else if (isRequest(stream)) {\n stream.abort()\n } else if (isRequest(stream.req)) {\n stream.req.abort()\n } else if (typeof stream.destroy === 'function') {\n stream.destroy(err)\n } else if (typeof stream.close === 'function') {\n // TODO: Don't lose err?\n stream.close()\n } else if (err) {\n process.nextTick(emitErrorCloseLegacy, stream, err)\n } else {\n process.nextTick(emitCloseLegacy, stream)\n }\n if (!stream.destroyed) {\n stream[kIsDestroyed] = true\n }\n}\nmodule.exports = {\n construct,\n destroyer,\n destroy,\n undestroy,\n errorOrDestroy\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototype inheritance, this class\n// prototypically inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict'\n\nconst {\n ObjectDefineProperties,\n ObjectGetOwnPropertyDescriptor,\n ObjectKeys,\n ObjectSetPrototypeOf\n} = require('../../ours/primordials')\nmodule.exports = Duplex\nconst Readable = require('./readable')\nconst Writable = require('./writable')\nObjectSetPrototypeOf(Duplex.prototype, Readable.prototype)\nObjectSetPrototypeOf(Duplex, Readable)\n{\n const keys = ObjectKeys(Writable.prototype)\n // Allow the keys array to be GC'ed.\n for (let i = 0; i < keys.length; i++) {\n const method = keys[i]\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]\n }\n}\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options)\n Readable.call(this, options)\n Writable.call(this, options)\n if (options) {\n this.allowHalfOpen = options.allowHalfOpen !== false\n if (options.readable === false) {\n this._readableState.readable = false\n this._readableState.ended = true\n this._readableState.endEmitted = true\n }\n if (options.writable === false) {\n this._writableState.writable = false\n this._writableState.ending = true\n this._writableState.ended = true\n this._writableState.finished = true\n }\n } else {\n this.allowHalfOpen = true\n }\n}\nObjectDefineProperties(Duplex.prototype, {\n writable: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable')\n },\n writableHighWaterMark: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark')\n },\n writableObjectMode: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode')\n },\n writableBuffer: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer')\n },\n writableLength: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength')\n },\n writableFinished: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished')\n },\n writableCorked: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked')\n },\n writableEnded: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded')\n },\n writableNeedDrain: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain')\n },\n destroyed: {\n __proto__: null,\n get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false\n }\n return this._readableState.destroyed && this._writableState.destroyed\n },\n set(value) {\n // Backward compatibility, the user is explicitly\n // managing destroyed.\n if (this._readableState && this._writableState) {\n this._readableState.destroyed = value\n this._writableState.destroyed = value\n }\n }\n }\n})\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n return webStreamsAdapters\n}\nDuplex.fromWeb = function (pair, options) {\n return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options)\n}\nDuplex.toWeb = function (duplex) {\n return lazyWebStreams().newReadableWritablePairFromDuplex(duplex)\n}\nlet duplexify\nDuplex.from = function (body) {\n if (!duplexify) {\n duplexify = require('./duplexify')\n }\n return duplexify(body, 'body')\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\n;('use strict')\nconst bufferModule = require('buffer')\nconst {\n isReadable,\n isWritable,\n isIterable,\n isNodeStream,\n isReadableNodeStream,\n isWritableNodeStream,\n isDuplexNodeStream,\n isReadableStream,\n isWritableStream\n} = require('./utils')\nconst eos = require('./end-of-stream')\nconst {\n AbortError,\n codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE }\n} = require('../../ours/errors')\nconst { destroyer } = require('./destroy')\nconst Duplex = require('./duplex')\nconst Readable = require('./readable')\nconst Writable = require('./writable')\nconst { createDeferredPromise } = require('../../ours/util')\nconst from = require('./from')\nconst Blob = globalThis.Blob || bufferModule.Blob\nconst isBlob =\n typeof Blob !== 'undefined'\n ? function isBlob(b) {\n return b instanceof Blob\n }\n : function isBlob(b) {\n return false\n }\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst { FunctionPrototypeCall } = require('../../ours/primordials')\n\n// This is needed for pre node 17.\nclass Duplexify extends Duplex {\n constructor(options) {\n super(options)\n\n // https://github.com/nodejs/node/pull/34385\n\n if ((options === null || options === undefined ? undefined : options.readable) === false) {\n this._readableState.readable = false\n this._readableState.ended = true\n this._readableState.endEmitted = true\n }\n if ((options === null || options === undefined ? undefined : options.writable) === false) {\n this._writableState.writable = false\n this._writableState.ending = true\n this._writableState.ended = true\n this._writableState.finished = true\n }\n }\n}\nmodule.exports = function duplexify(body, name) {\n if (isDuplexNodeStream(body)) {\n return body\n }\n if (isReadableNodeStream(body)) {\n return _duplexify({\n readable: body\n })\n }\n if (isWritableNodeStream(body)) {\n return _duplexify({\n writable: body\n })\n }\n if (isNodeStream(body)) {\n return _duplexify({\n writable: false,\n readable: false\n })\n }\n if (isReadableStream(body)) {\n return _duplexify({\n readable: Readable.fromWeb(body)\n })\n }\n if (isWritableStream(body)) {\n return _duplexify({\n writable: Writable.fromWeb(body)\n })\n }\n if (typeof body === 'function') {\n const { value, write, final, destroy } = fromAsyncGen(body)\n if (isIterable(value)) {\n return from(Duplexify, value, {\n // TODO (ronag): highWaterMark?\n objectMode: true,\n write,\n final,\n destroy\n })\n }\n const then = value === null || value === undefined ? undefined : value.then\n if (typeof then === 'function') {\n let d\n const promise = FunctionPrototypeCall(\n then,\n value,\n (val) => {\n if (val != null) {\n throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val)\n }\n },\n (err) => {\n destroyer(d, err)\n }\n )\n return (d = new Duplexify({\n // TODO (ronag): highWaterMark?\n objectMode: true,\n readable: false,\n write,\n final(cb) {\n final(async () => {\n try {\n await promise\n process.nextTick(cb, null)\n } catch (err) {\n process.nextTick(cb, err)\n }\n })\n },\n destroy\n }))\n }\n throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value)\n }\n if (isBlob(body)) {\n return duplexify(body.arrayBuffer())\n }\n if (isIterable(body)) {\n return from(Duplexify, body, {\n // TODO (ronag): highWaterMark?\n objectMode: true,\n writable: false\n })\n }\n if (\n isReadableStream(body === null || body === undefined ? undefined : body.readable) &&\n isWritableStream(body === null || body === undefined ? undefined : body.writable)\n ) {\n return Duplexify.fromWeb(body)\n }\n if (\n typeof (body === null || body === undefined ? undefined : body.writable) === 'object' ||\n typeof (body === null || body === undefined ? undefined : body.readable) === 'object'\n ) {\n const readable =\n body !== null && body !== undefined && body.readable\n ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable)\n ? body === null || body === undefined\n ? undefined\n : body.readable\n : duplexify(body.readable)\n : undefined\n const writable =\n body !== null && body !== undefined && body.writable\n ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable)\n ? body === null || body === undefined\n ? undefined\n : body.writable\n : duplexify(body.writable)\n : undefined\n return _duplexify({\n readable,\n writable\n })\n }\n const then = body === null || body === undefined ? undefined : body.then\n if (typeof then === 'function') {\n let d\n FunctionPrototypeCall(\n then,\n body,\n (val) => {\n if (val != null) {\n d.push(val)\n }\n d.push(null)\n },\n (err) => {\n destroyer(d, err)\n }\n )\n return (d = new Duplexify({\n objectMode: true,\n writable: false,\n read() {}\n }))\n }\n throw new ERR_INVALID_ARG_TYPE(\n name,\n [\n 'Blob',\n 'ReadableStream',\n 'WritableStream',\n 'Stream',\n 'Iterable',\n 'AsyncIterable',\n 'Function',\n '{ readable, writable } pair',\n 'Promise'\n ],\n body\n )\n}\nfunction fromAsyncGen(fn) {\n let { promise, resolve } = createDeferredPromise()\n const ac = new AbortController()\n const signal = ac.signal\n const value = fn(\n (async function* () {\n while (true) {\n const _promise = promise\n promise = null\n const { chunk, done, cb } = await _promise\n process.nextTick(cb)\n if (done) return\n if (signal.aborted)\n throw new AbortError(undefined, {\n cause: signal.reason\n })\n ;({ promise, resolve } = createDeferredPromise())\n yield chunk\n }\n })(),\n {\n signal\n }\n )\n return {\n value,\n write(chunk, encoding, cb) {\n const _resolve = resolve\n resolve = null\n _resolve({\n chunk,\n done: false,\n cb\n })\n },\n final(cb) {\n const _resolve = resolve\n resolve = null\n _resolve({\n done: true,\n cb\n })\n },\n destroy(err, cb) {\n ac.abort()\n cb(err)\n }\n }\n}\nfunction _duplexify(pair) {\n const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable\n const w = pair.writable\n let readable = !!isReadable(r)\n let writable = !!isWritable(w)\n let ondrain\n let onfinish\n let onreadable\n let onclose\n let d\n function onfinished(err) {\n const cb = onclose\n onclose = null\n if (cb) {\n cb(err)\n } else if (err) {\n d.destroy(err)\n }\n }\n\n // TODO(ronag): Avoid double buffering.\n // Implement Writable/Readable/Duplex traits.\n // See, https://github.com/nodejs/node/pull/33515.\n d = new Duplexify({\n // TODO (ronag): highWaterMark?\n readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode),\n writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode),\n readable,\n writable\n })\n if (writable) {\n eos(w, (err) => {\n writable = false\n if (err) {\n destroyer(r, err)\n }\n onfinished(err)\n })\n d._write = function (chunk, encoding, callback) {\n if (w.write(chunk, encoding)) {\n callback()\n } else {\n ondrain = callback\n }\n }\n d._final = function (callback) {\n w.end()\n onfinish = callback\n }\n w.on('drain', function () {\n if (ondrain) {\n const cb = ondrain\n ondrain = null\n cb()\n }\n })\n w.on('finish', function () {\n if (onfinish) {\n const cb = onfinish\n onfinish = null\n cb()\n }\n })\n }\n if (readable) {\n eos(r, (err) => {\n readable = false\n if (err) {\n destroyer(r, err)\n }\n onfinished(err)\n })\n r.on('readable', function () {\n if (onreadable) {\n const cb = onreadable\n onreadable = null\n cb()\n }\n })\n r.on('end', function () {\n d.push(null)\n })\n d._read = function () {\n while (true) {\n const buf = r.read()\n if (buf === null) {\n onreadable = d._read\n return\n }\n if (!d.push(buf)) {\n return\n }\n }\n }\n }\n d._destroy = function (err, callback) {\n if (!err && onclose !== null) {\n err = new AbortError()\n }\n onreadable = null\n ondrain = null\n onfinish = null\n if (onclose === null) {\n callback(err)\n } else {\n onclose = callback\n destroyer(w, err)\n destroyer(r, err)\n }\n }\n return d\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n\n;('use strict')\nconst { AbortError, codes } = require('../../ours/errors')\nconst { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes\nconst { kEmptyObject, once } = require('../../ours/util')\nconst { validateAbortSignal, validateFunction, validateObject, validateBoolean } = require('../validators')\nconst { Promise, PromisePrototypeThen, SymbolDispose } = require('../../ours/primordials')\nconst {\n isClosed,\n isReadable,\n isReadableNodeStream,\n isReadableStream,\n isReadableFinished,\n isReadableErrored,\n isWritable,\n isWritableNodeStream,\n isWritableStream,\n isWritableFinished,\n isWritableErrored,\n isNodeStream,\n willEmitClose: _willEmitClose,\n kIsClosedPromise\n} = require('./utils')\nlet addAbortListener\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function'\n}\nconst nop = () => {}\nfunction eos(stream, options, callback) {\n var _options$readable, _options$writable\n if (arguments.length === 2) {\n callback = options\n options = kEmptyObject\n } else if (options == null) {\n options = kEmptyObject\n } else {\n validateObject(options, 'options')\n }\n validateFunction(callback, 'callback')\n validateAbortSignal(options.signal, 'options.signal')\n callback = once(callback)\n if (isReadableStream(stream) || isWritableStream(stream)) {\n return eosWeb(stream, options, callback)\n }\n if (!isNodeStream(stream)) {\n throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream)\n }\n const readable =\n (_options$readable = options.readable) !== null && _options$readable !== undefined\n ? _options$readable\n : isReadableNodeStream(stream)\n const writable =\n (_options$writable = options.writable) !== null && _options$writable !== undefined\n ? _options$writable\n : isWritableNodeStream(stream)\n const wState = stream._writableState\n const rState = stream._readableState\n const onlegacyfinish = () => {\n if (!stream.writable) {\n onfinish()\n }\n }\n\n // TODO (ronag): Improve soft detection to include core modules and\n // common ecosystem modules that do properly emit 'close' but fail\n // this generic check.\n let willEmitClose =\n _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable\n let writableFinished = isWritableFinished(stream, false)\n const onfinish = () => {\n writableFinished = true\n // Stream should not be destroyed here. If it is that\n // means that user space is doing something differently and\n // we cannot trust willEmitClose.\n if (stream.destroyed) {\n willEmitClose = false\n }\n if (willEmitClose && (!stream.readable || readable)) {\n return\n }\n if (!readable || readableFinished) {\n callback.call(stream)\n }\n }\n let readableFinished = isReadableFinished(stream, false)\n const onend = () => {\n readableFinished = true\n // Stream should not be destroyed here. If it is that\n // means that user space is doing something differently and\n // we cannot trust willEmitClose.\n if (stream.destroyed) {\n willEmitClose = false\n }\n if (willEmitClose && (!stream.writable || writable)) {\n return\n }\n if (!writable || writableFinished) {\n callback.call(stream)\n }\n }\n const onerror = (err) => {\n callback.call(stream, err)\n }\n let closed = isClosed(stream)\n const onclose = () => {\n closed = true\n const errored = isWritableErrored(stream) || isReadableErrored(stream)\n if (errored && typeof errored !== 'boolean') {\n return callback.call(stream, errored)\n }\n if (readable && !readableFinished && isReadableNodeStream(stream, true)) {\n if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE())\n }\n if (writable && !writableFinished) {\n if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE())\n }\n callback.call(stream)\n }\n const onclosed = () => {\n closed = true\n const errored = isWritableErrored(stream) || isReadableErrored(stream)\n if (errored && typeof errored !== 'boolean') {\n return callback.call(stream, errored)\n }\n callback.call(stream)\n }\n const onrequest = () => {\n stream.req.on('finish', onfinish)\n }\n if (isRequest(stream)) {\n stream.on('complete', onfinish)\n if (!willEmitClose) {\n stream.on('abort', onclose)\n }\n if (stream.req) {\n onrequest()\n } else {\n stream.on('request', onrequest)\n }\n } else if (writable && !wState) {\n // legacy streams\n stream.on('end', onlegacyfinish)\n stream.on('close', onlegacyfinish)\n }\n\n // Not all streams will emit 'close' after 'aborted'.\n if (!willEmitClose && typeof stream.aborted === 'boolean') {\n stream.on('aborted', onclose)\n }\n stream.on('end', onend)\n stream.on('finish', onfinish)\n if (options.error !== false) {\n stream.on('error', onerror)\n }\n stream.on('close', onclose)\n if (closed) {\n process.nextTick(onclose)\n } else if (\n (wState !== null && wState !== undefined && wState.errorEmitted) ||\n (rState !== null && rState !== undefined && rState.errorEmitted)\n ) {\n if (!willEmitClose) {\n process.nextTick(onclosed)\n }\n } else if (\n !readable &&\n (!willEmitClose || isReadable(stream)) &&\n (writableFinished || isWritable(stream) === false)\n ) {\n process.nextTick(onclosed)\n } else if (\n !writable &&\n (!willEmitClose || isWritable(stream)) &&\n (readableFinished || isReadable(stream) === false)\n ) {\n process.nextTick(onclosed)\n } else if (rState && stream.req && stream.aborted) {\n process.nextTick(onclosed)\n }\n const cleanup = () => {\n callback = nop\n stream.removeListener('aborted', onclose)\n stream.removeListener('complete', onfinish)\n stream.removeListener('abort', onclose)\n stream.removeListener('request', onrequest)\n if (stream.req) stream.req.removeListener('finish', onfinish)\n stream.removeListener('end', onlegacyfinish)\n stream.removeListener('close', onlegacyfinish)\n stream.removeListener('finish', onfinish)\n stream.removeListener('end', onend)\n stream.removeListener('error', onerror)\n stream.removeListener('close', onclose)\n }\n if (options.signal && !closed) {\n const abort = () => {\n // Keep it because cleanup removes it.\n const endCallback = callback\n cleanup()\n endCallback.call(\n stream,\n new AbortError(undefined, {\n cause: options.signal.reason\n })\n )\n }\n if (options.signal.aborted) {\n process.nextTick(abort)\n } else {\n addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n const disposable = addAbortListener(options.signal, abort)\n const originalCallback = callback\n callback = once((...args) => {\n disposable[SymbolDispose]()\n originalCallback.apply(stream, args)\n })\n }\n }\n return cleanup\n}\nfunction eosWeb(stream, options, callback) {\n let isAborted = false\n let abort = nop\n if (options.signal) {\n abort = () => {\n isAborted = true\n callback.call(\n stream,\n new AbortError(undefined, {\n cause: options.signal.reason\n })\n )\n }\n if (options.signal.aborted) {\n process.nextTick(abort)\n } else {\n addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n const disposable = addAbortListener(options.signal, abort)\n const originalCallback = callback\n callback = once((...args) => {\n disposable[SymbolDispose]()\n originalCallback.apply(stream, args)\n })\n }\n }\n const resolverFn = (...args) => {\n if (!isAborted) {\n process.nextTick(() => callback.apply(stream, args))\n }\n }\n PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn)\n return nop\n}\nfunction finished(stream, opts) {\n var _opts\n let autoCleanup = false\n if (opts === null) {\n opts = kEmptyObject\n }\n if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) {\n validateBoolean(opts.cleanup, 'cleanup')\n autoCleanup = opts.cleanup\n }\n return new Promise((resolve, reject) => {\n const cleanup = eos(stream, opts, (err) => {\n if (autoCleanup) {\n cleanup()\n }\n if (err) {\n reject(err)\n } else {\n resolve()\n }\n })\n })\n}\nmodule.exports = eos\nmodule.exports.finished = finished\n","'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require('../../ours/primordials')\nconst { Buffer } = require('buffer')\nconst { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = require('../../ours/errors').codes\nfunction from(Readable, iterable, opts) {\n let iterator\n if (typeof iterable === 'string' || iterable instanceof Buffer) {\n return new Readable({\n objectMode: true,\n ...opts,\n read() {\n this.push(iterable)\n this.push(null)\n }\n })\n }\n let isAsync\n if (iterable && iterable[SymbolAsyncIterator]) {\n isAsync = true\n iterator = iterable[SymbolAsyncIterator]()\n } else if (iterable && iterable[SymbolIterator]) {\n isAsync = false\n iterator = iterable[SymbolIterator]()\n } else {\n throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable)\n }\n const readable = new Readable({\n objectMode: true,\n highWaterMark: 1,\n // TODO(ronag): What options should be allowed?\n ...opts\n })\n\n // Flag to protect against _read\n // being called before last iteration completion.\n let reading = false\n readable._read = function () {\n if (!reading) {\n reading = true\n next()\n }\n }\n readable._destroy = function (error, cb) {\n PromisePrototypeThen(\n close(error),\n () => process.nextTick(cb, error),\n // nextTick is here in case cb throws\n (e) => process.nextTick(cb, e || error)\n )\n }\n async function close(error) {\n const hadError = error !== undefined && error !== null\n const hasThrow = typeof iterator.throw === 'function'\n if (hadError && hasThrow) {\n const { value, done } = await iterator.throw(error)\n await value\n if (done) {\n return\n }\n }\n if (typeof iterator.return === 'function') {\n const { value } = await iterator.return()\n await value\n }\n }\n async function next() {\n for (;;) {\n try {\n const { value, done } = isAsync ? await iterator.next() : iterator.next()\n if (done) {\n readable.push(null)\n } else {\n const res = value && typeof value.then === 'function' ? await value : value\n if (res === null) {\n reading = false\n throw new ERR_STREAM_NULL_VALUES()\n } else if (readable.push(res)) {\n continue\n } else {\n reading = false\n }\n }\n } catch (err) {\n readable.destroy(err)\n }\n break\n }\n }\n return readable\n}\nmodule.exports = from\n","'use strict'\n\nconst { ArrayIsArray, ObjectSetPrototypeOf } = require('../../ours/primordials')\nconst { EventEmitter: EE } = require('events')\nfunction Stream(opts) {\n EE.call(this, opts)\n}\nObjectSetPrototypeOf(Stream.prototype, EE.prototype)\nObjectSetPrototypeOf(Stream, EE)\nStream.prototype.pipe = function (dest, options) {\n const source = this\n function ondata(chunk) {\n if (dest.writable && dest.write(chunk) === false && source.pause) {\n source.pause()\n }\n }\n source.on('data', ondata)\n function ondrain() {\n if (source.readable && source.resume) {\n source.resume()\n }\n }\n dest.on('drain', ondrain)\n\n // If the 'end' option is not supplied, dest.end() will be called when\n // source gets the 'end' or 'close' events. Only dest.end() once.\n if (!dest._isStdio && (!options || options.end !== false)) {\n source.on('end', onend)\n source.on('close', onclose)\n }\n let didOnEnd = false\n function onend() {\n if (didOnEnd) return\n didOnEnd = true\n dest.end()\n }\n function onclose() {\n if (didOnEnd) return\n didOnEnd = true\n if (typeof dest.destroy === 'function') dest.destroy()\n }\n\n // Don't leave dangling pipes when there are errors.\n function onerror(er) {\n cleanup()\n if (EE.listenerCount(this, 'error') === 0) {\n this.emit('error', er)\n }\n }\n prependListener(source, 'error', onerror)\n prependListener(dest, 'error', onerror)\n\n // Remove all the event listeners that were added.\n function cleanup() {\n source.removeListener('data', ondata)\n dest.removeListener('drain', ondrain)\n source.removeListener('end', onend)\n source.removeListener('close', onclose)\n source.removeListener('error', onerror)\n dest.removeListener('error', onerror)\n source.removeListener('end', cleanup)\n source.removeListener('close', cleanup)\n dest.removeListener('close', cleanup)\n }\n source.on('end', cleanup)\n source.on('close', cleanup)\n dest.on('close', cleanup)\n dest.emit('pipe', source)\n\n // Allow for unix-like usage: A.pipe(B).pipe(C)\n return dest\n}\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn)\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn)\n else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn)\n else emitter._events[event] = [fn, emitter._events[event]]\n}\nmodule.exports = {\n Stream,\n prependListener\n}\n","'use strict'\n\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst {\n codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE },\n AbortError\n} = require('../../ours/errors')\nconst { validateAbortSignal, validateInteger, validateObject } = require('../validators')\nconst kWeakHandler = require('../../ours/primordials').Symbol('kWeak')\nconst kResistStopPropagation = require('../../ours/primordials').Symbol('kResistStopPropagation')\nconst { finished } = require('./end-of-stream')\nconst staticCompose = require('./compose')\nconst { addAbortSignalNoValidate } = require('./add-abort-signal')\nconst { isWritable, isNodeStream } = require('./utils')\nconst { deprecate } = require('../../ours/util')\nconst {\n ArrayPrototypePush,\n Boolean,\n MathFloor,\n Number,\n NumberIsNaN,\n Promise,\n PromiseReject,\n PromiseResolve,\n PromisePrototypeThen,\n Symbol\n} = require('../../ours/primordials')\nconst kEmpty = Symbol('kEmpty')\nconst kEof = Symbol('kEof')\nfunction compose(stream, options) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n if (isNodeStream(stream) && !isWritable(stream)) {\n throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable')\n }\n const composedStream = staticCompose(this, stream)\n if (options !== null && options !== undefined && options.signal) {\n // Not validating as we already validated before\n addAbortSignalNoValidate(options.signal, composedStream)\n }\n return composedStream\n}\nfunction map(fn, options) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n }\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n let concurrency = 1\n if ((options === null || options === undefined ? undefined : options.concurrency) != null) {\n concurrency = MathFloor(options.concurrency)\n }\n let highWaterMark = concurrency - 1\n if ((options === null || options === undefined ? undefined : options.highWaterMark) != null) {\n highWaterMark = MathFloor(options.highWaterMark)\n }\n validateInteger(concurrency, 'options.concurrency', 1)\n validateInteger(highWaterMark, 'options.highWaterMark', 0)\n highWaterMark += concurrency\n return async function* map() {\n const signal = require('../../ours/util').AbortSignalAny(\n [options === null || options === undefined ? undefined : options.signal].filter(Boolean)\n )\n const stream = this\n const queue = []\n const signalOpt = {\n signal\n }\n let next\n let resume\n let done = false\n let cnt = 0\n function onCatch() {\n done = true\n afterItemProcessed()\n }\n function afterItemProcessed() {\n cnt -= 1\n maybeResume()\n }\n function maybeResume() {\n if (resume && !done && cnt < concurrency && queue.length < highWaterMark) {\n resume()\n resume = null\n }\n }\n async function pump() {\n try {\n for await (let val of stream) {\n if (done) {\n return\n }\n if (signal.aborted) {\n throw new AbortError()\n }\n try {\n val = fn(val, signalOpt)\n if (val === kEmpty) {\n continue\n }\n val = PromiseResolve(val)\n } catch (err) {\n val = PromiseReject(err)\n }\n cnt += 1\n PromisePrototypeThen(val, afterItemProcessed, onCatch)\n queue.push(val)\n if (next) {\n next()\n next = null\n }\n if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) {\n await new Promise((resolve) => {\n resume = resolve\n })\n }\n }\n queue.push(kEof)\n } catch (err) {\n const val = PromiseReject(err)\n PromisePrototypeThen(val, afterItemProcessed, onCatch)\n queue.push(val)\n } finally {\n done = true\n if (next) {\n next()\n next = null\n }\n }\n }\n pump()\n try {\n while (true) {\n while (queue.length > 0) {\n const val = await queue[0]\n if (val === kEof) {\n return\n }\n if (signal.aborted) {\n throw new AbortError()\n }\n if (val !== kEmpty) {\n yield val\n }\n queue.shift()\n maybeResume()\n }\n await new Promise((resolve) => {\n next = resolve\n })\n }\n } finally {\n done = true\n if (resume) {\n resume()\n resume = null\n }\n }\n }.call(this)\n}\nfunction asIndexedPairs(options = undefined) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n return async function* asIndexedPairs() {\n let index = 0\n for await (const val of this) {\n var _options$signal\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal = options.signal) !== null &&\n _options$signal !== undefined &&\n _options$signal.aborted\n ) {\n throw new AbortError({\n cause: options.signal.reason\n })\n }\n yield [index++, val]\n }\n }.call(this)\n}\nasync function some(fn, options = undefined) {\n for await (const unused of filter.call(this, fn, options)) {\n return true\n }\n return false\n}\nasync function every(fn, options = undefined) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n }\n // https://en.wikipedia.org/wiki/De_Morgan%27s_laws\n return !(await some.call(\n this,\n async (...args) => {\n return !(await fn(...args))\n },\n options\n ))\n}\nasync function find(fn, options) {\n for await (const result of filter.call(this, fn, options)) {\n return result\n }\n return undefined\n}\nasync function forEach(fn, options) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n }\n async function forEachFn(value, options) {\n await fn(value, options)\n return kEmpty\n }\n // eslint-disable-next-line no-unused-vars\n for await (const unused of map.call(this, forEachFn, options));\n}\nfunction filter(fn, options) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n }\n async function filterFn(value, options) {\n if (await fn(value, options)) {\n return value\n }\n return kEmpty\n }\n return map.call(this, filterFn, options)\n}\n\n// Specific to provide better error to reduce since the argument is only\n// missing if the stream has no items in it - but the code is still appropriate\nclass ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS {\n constructor() {\n super('reduce')\n this.message = 'Reduce of an empty stream requires an initial value'\n }\n}\nasync function reduce(reducer, initialValue, options) {\n var _options$signal2\n if (typeof reducer !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('reducer', ['Function', 'AsyncFunction'], reducer)\n }\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n let hasInitialValue = arguments.length > 1\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal2 = options.signal) !== null &&\n _options$signal2 !== undefined &&\n _options$signal2.aborted\n ) {\n const err = new AbortError(undefined, {\n cause: options.signal.reason\n })\n this.once('error', () => {}) // The error is already propagated\n await finished(this.destroy(err))\n throw err\n }\n const ac = new AbortController()\n const signal = ac.signal\n if (options !== null && options !== undefined && options.signal) {\n const opts = {\n once: true,\n [kWeakHandler]: this,\n [kResistStopPropagation]: true\n }\n options.signal.addEventListener('abort', () => ac.abort(), opts)\n }\n let gotAnyItemFromStream = false\n try {\n for await (const value of this) {\n var _options$signal3\n gotAnyItemFromStream = true\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal3 = options.signal) !== null &&\n _options$signal3 !== undefined &&\n _options$signal3.aborted\n ) {\n throw new AbortError()\n }\n if (!hasInitialValue) {\n initialValue = value\n hasInitialValue = true\n } else {\n initialValue = await reducer(initialValue, value, {\n signal\n })\n }\n }\n if (!gotAnyItemFromStream && !hasInitialValue) {\n throw new ReduceAwareErrMissingArgs()\n }\n } finally {\n ac.abort()\n }\n return initialValue\n}\nasync function toArray(options) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n const result = []\n for await (const val of this) {\n var _options$signal4\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal4 = options.signal) !== null &&\n _options$signal4 !== undefined &&\n _options$signal4.aborted\n ) {\n throw new AbortError(undefined, {\n cause: options.signal.reason\n })\n }\n ArrayPrototypePush(result, val)\n }\n return result\n}\nfunction flatMap(fn, options) {\n const values = map.call(this, fn, options)\n return async function* flatMap() {\n for await (const val of values) {\n yield* val\n }\n }.call(this)\n}\nfunction toIntegerOrInfinity(number) {\n // We coerce here to align with the spec\n // https://github.com/tc39/proposal-iterator-helpers/issues/169\n number = Number(number)\n if (NumberIsNaN(number)) {\n return 0\n }\n if (number < 0) {\n throw new ERR_OUT_OF_RANGE('number', '>= 0', number)\n }\n return number\n}\nfunction drop(number, options = undefined) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n number = toIntegerOrInfinity(number)\n return async function* drop() {\n var _options$signal5\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal5 = options.signal) !== null &&\n _options$signal5 !== undefined &&\n _options$signal5.aborted\n ) {\n throw new AbortError()\n }\n for await (const val of this) {\n var _options$signal6\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal6 = options.signal) !== null &&\n _options$signal6 !== undefined &&\n _options$signal6.aborted\n ) {\n throw new AbortError()\n }\n if (number-- <= 0) {\n yield val\n }\n }\n }.call(this)\n}\nfunction take(number, options = undefined) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n number = toIntegerOrInfinity(number)\n return async function* take() {\n var _options$signal7\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal7 = options.signal) !== null &&\n _options$signal7 !== undefined &&\n _options$signal7.aborted\n ) {\n throw new AbortError()\n }\n for await (const val of this) {\n var _options$signal8\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal8 = options.signal) !== null &&\n _options$signal8 !== undefined &&\n _options$signal8.aborted\n ) {\n throw new AbortError()\n }\n if (number-- > 0) {\n yield val\n }\n\n // Don't get another item from iterator in case we reached the end\n if (number <= 0) {\n return\n }\n }\n }.call(this)\n}\nmodule.exports.streamReturningOperators = {\n asIndexedPairs: deprecate(asIndexedPairs, 'readable.asIndexedPairs will be removed in a future version.'),\n drop,\n filter,\n flatMap,\n map,\n take,\n compose\n}\nmodule.exports.promiseReturningOperators = {\n every,\n forEach,\n reduce,\n toArray,\n some,\n find\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict'\n\nconst { ObjectSetPrototypeOf } = require('../../ours/primordials')\nmodule.exports = PassThrough\nconst Transform = require('./transform')\nObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype)\nObjectSetPrototypeOf(PassThrough, Transform)\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options)\n Transform.call(this, options)\n}\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk)\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n\n;('use strict')\nconst { ArrayIsArray, Promise, SymbolAsyncIterator, SymbolDispose } = require('../../ours/primordials')\nconst eos = require('./end-of-stream')\nconst { once } = require('../../ours/util')\nconst destroyImpl = require('./destroy')\nconst Duplex = require('./duplex')\nconst {\n aggregateTwoErrors,\n codes: {\n ERR_INVALID_ARG_TYPE,\n ERR_INVALID_RETURN_VALUE,\n ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED,\n ERR_STREAM_PREMATURE_CLOSE\n },\n AbortError\n} = require('../../ours/errors')\nconst { validateFunction, validateAbortSignal } = require('../validators')\nconst {\n isIterable,\n isReadable,\n isReadableNodeStream,\n isNodeStream,\n isTransformStream,\n isWebStream,\n isReadableStream,\n isReadableFinished\n} = require('./utils')\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nlet PassThrough\nlet Readable\nlet addAbortListener\nfunction destroyer(stream, reading, writing) {\n let finished = false\n stream.on('close', () => {\n finished = true\n })\n const cleanup = eos(\n stream,\n {\n readable: reading,\n writable: writing\n },\n (err) => {\n finished = !err\n }\n )\n return {\n destroy: (err) => {\n if (finished) return\n finished = true\n destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe'))\n },\n cleanup\n }\n}\nfunction popCallback(streams) {\n // Streams should never be an empty array. It should always contain at least\n // a single stream. Therefore optimize for the average case instead of\n // checking for length === 0 as well.\n validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]')\n return streams.pop()\n}\nfunction makeAsyncIterable(val) {\n if (isIterable(val)) {\n return val\n } else if (isReadableNodeStream(val)) {\n // Legacy streams are not Iterable.\n return fromReadable(val)\n }\n throw new ERR_INVALID_ARG_TYPE('val', ['Readable', 'Iterable', 'AsyncIterable'], val)\n}\nasync function* fromReadable(val) {\n if (!Readable) {\n Readable = require('./readable')\n }\n yield* Readable.prototype[SymbolAsyncIterator].call(val)\n}\nasync function pumpToNode(iterable, writable, finish, { end }) {\n let error\n let onresolve = null\n const resume = (err) => {\n if (err) {\n error = err\n }\n if (onresolve) {\n const callback = onresolve\n onresolve = null\n callback()\n }\n }\n const wait = () =>\n new Promise((resolve, reject) => {\n if (error) {\n reject(error)\n } else {\n onresolve = () => {\n if (error) {\n reject(error)\n } else {\n resolve()\n }\n }\n }\n })\n writable.on('drain', resume)\n const cleanup = eos(\n writable,\n {\n readable: false\n },\n resume\n )\n try {\n if (writable.writableNeedDrain) {\n await wait()\n }\n for await (const chunk of iterable) {\n if (!writable.write(chunk)) {\n await wait()\n }\n }\n if (end) {\n writable.end()\n await wait()\n }\n finish()\n } catch (err) {\n finish(error !== err ? aggregateTwoErrors(error, err) : err)\n } finally {\n cleanup()\n writable.off('drain', resume)\n }\n}\nasync function pumpToWeb(readable, writable, finish, { end }) {\n if (isTransformStream(writable)) {\n writable = writable.writable\n }\n // https://streams.spec.whatwg.org/#example-manual-write-with-backpressure\n const writer = writable.getWriter()\n try {\n for await (const chunk of readable) {\n await writer.ready\n writer.write(chunk).catch(() => {})\n }\n await writer.ready\n if (end) {\n await writer.close()\n }\n finish()\n } catch (err) {\n try {\n await writer.abort(err)\n finish(err)\n } catch (err) {\n finish(err)\n }\n }\n}\nfunction pipeline(...streams) {\n return pipelineImpl(streams, once(popCallback(streams)))\n}\nfunction pipelineImpl(streams, callback, opts) {\n if (streams.length === 1 && ArrayIsArray(streams[0])) {\n streams = streams[0]\n }\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams')\n }\n const ac = new AbortController()\n const signal = ac.signal\n const outerSignal = opts === null || opts === undefined ? undefined : opts.signal\n\n // Need to cleanup event listeners if last stream is readable\n // https://github.com/nodejs/node/issues/35452\n const lastStreamCleanup = []\n validateAbortSignal(outerSignal, 'options.signal')\n function abort() {\n finishImpl(new AbortError())\n }\n addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n let disposable\n if (outerSignal) {\n disposable = addAbortListener(outerSignal, abort)\n }\n let error\n let value\n const destroys = []\n let finishCount = 0\n function finish(err) {\n finishImpl(err, --finishCount === 0)\n }\n function finishImpl(err, final) {\n var _disposable\n if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) {\n error = err\n }\n if (!error && !final) {\n return\n }\n while (destroys.length) {\n destroys.shift()(error)\n }\n ;(_disposable = disposable) === null || _disposable === undefined ? undefined : _disposable[SymbolDispose]()\n ac.abort()\n if (final) {\n if (!error) {\n lastStreamCleanup.forEach((fn) => fn())\n }\n process.nextTick(callback, error, value)\n }\n }\n let ret\n for (let i = 0; i < streams.length; i++) {\n const stream = streams[i]\n const reading = i < streams.length - 1\n const writing = i > 0\n const end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false\n const isLastStream = i === streams.length - 1\n if (isNodeStream(stream)) {\n if (end) {\n const { destroy, cleanup } = destroyer(stream, reading, writing)\n destroys.push(destroy)\n if (isReadable(stream) && isLastStream) {\n lastStreamCleanup.push(cleanup)\n }\n }\n\n // Catch stream errors that occur after pipe/pump has completed.\n function onError(err) {\n if (err && err.name !== 'AbortError' && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n finish(err)\n }\n }\n stream.on('error', onError)\n if (isReadable(stream) && isLastStream) {\n lastStreamCleanup.push(() => {\n stream.removeListener('error', onError)\n })\n }\n }\n if (i === 0) {\n if (typeof stream === 'function') {\n ret = stream({\n signal\n })\n if (!isIterable(ret)) {\n throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or Stream', 'source', ret)\n }\n } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) {\n ret = stream\n } else {\n ret = Duplex.from(stream)\n }\n } else if (typeof stream === 'function') {\n if (isTransformStream(ret)) {\n var _ret\n ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable)\n } else {\n ret = makeAsyncIterable(ret)\n }\n ret = stream(ret, {\n signal\n })\n if (reading) {\n if (!isIterable(ret, true)) {\n throw new ERR_INVALID_RETURN_VALUE('AsyncIterable', `transform[${i - 1}]`, ret)\n }\n } else {\n var _ret2\n if (!PassThrough) {\n PassThrough = require('./passthrough')\n }\n\n // If the last argument to pipeline is not a stream\n // we must create a proxy stream so that pipeline(...)\n // always returns a stream which can be further\n // composed through `.pipe(stream)`.\n\n const pt = new PassThrough({\n objectMode: true\n })\n\n // Handle Promises/A+ spec, `then` could be a getter that throws on\n // second use.\n const then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then\n if (typeof then === 'function') {\n finishCount++\n then.call(\n ret,\n (val) => {\n value = val\n if (val != null) {\n pt.write(val)\n }\n if (end) {\n pt.end()\n }\n process.nextTick(finish)\n },\n (err) => {\n pt.destroy(err)\n process.nextTick(finish, err)\n }\n )\n } else if (isIterable(ret, true)) {\n finishCount++\n pumpToNode(ret, pt, finish, {\n end\n })\n } else if (isReadableStream(ret) || isTransformStream(ret)) {\n const toRead = ret.readable || ret\n finishCount++\n pumpToNode(toRead, pt, finish, {\n end\n })\n } else {\n throw new ERR_INVALID_RETURN_VALUE('AsyncIterable or Promise', 'destination', ret)\n }\n ret = pt\n const { destroy, cleanup } = destroyer(ret, false, true)\n destroys.push(destroy)\n if (isLastStream) {\n lastStreamCleanup.push(cleanup)\n }\n }\n } else if (isNodeStream(stream)) {\n if (isReadableNodeStream(ret)) {\n finishCount += 2\n const cleanup = pipe(ret, stream, finish, {\n end\n })\n if (isReadable(stream) && isLastStream) {\n lastStreamCleanup.push(cleanup)\n }\n } else if (isTransformStream(ret) || isReadableStream(ret)) {\n const toRead = ret.readable || ret\n finishCount++\n pumpToNode(toRead, stream, finish, {\n end\n })\n } else if (isIterable(ret)) {\n finishCount++\n pumpToNode(ret, stream, finish, {\n end\n })\n } else {\n throw new ERR_INVALID_ARG_TYPE(\n 'val',\n ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'],\n ret\n )\n }\n ret = stream\n } else if (isWebStream(stream)) {\n if (isReadableNodeStream(ret)) {\n finishCount++\n pumpToWeb(makeAsyncIterable(ret), stream, finish, {\n end\n })\n } else if (isReadableStream(ret) || isIterable(ret)) {\n finishCount++\n pumpToWeb(ret, stream, finish, {\n end\n })\n } else if (isTransformStream(ret)) {\n finishCount++\n pumpToWeb(ret.readable, stream, finish, {\n end\n })\n } else {\n throw new ERR_INVALID_ARG_TYPE(\n 'val',\n ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'],\n ret\n )\n }\n ret = stream\n } else {\n ret = Duplex.from(stream)\n }\n }\n if (\n (signal !== null && signal !== undefined && signal.aborted) ||\n (outerSignal !== null && outerSignal !== undefined && outerSignal.aborted)\n ) {\n process.nextTick(abort)\n }\n return ret\n}\nfunction pipe(src, dst, finish, { end }) {\n let ended = false\n dst.on('close', () => {\n if (!ended) {\n // Finish if the destination closes before the source has completed.\n finish(new ERR_STREAM_PREMATURE_CLOSE())\n }\n })\n src.pipe(dst, {\n end: false\n }) // If end is true we already will have a listener to end dst.\n\n if (end) {\n // Compat. Before node v10.12.0 stdio used to throw an error so\n // pipe() did/does not end() stdio destinations.\n // Now they allow it but \"secretly\" don't close the underlying fd.\n\n function endFn() {\n ended = true\n dst.end()\n }\n if (isReadableFinished(src)) {\n // End the destination if the source has already ended.\n process.nextTick(endFn)\n } else {\n src.once('end', endFn)\n }\n } else {\n finish()\n }\n eos(\n src,\n {\n readable: true,\n writable: false\n },\n (err) => {\n const rState = src._readableState\n if (\n err &&\n err.code === 'ERR_STREAM_PREMATURE_CLOSE' &&\n rState &&\n rState.ended &&\n !rState.errored &&\n !rState.errorEmitted\n ) {\n // Some readable streams will emit 'close' before 'end'. However, since\n // this is on the readable side 'end' should still be emitted if the\n // stream has been ended and no error emitted. This should be allowed in\n // favor of backwards compatibility. Since the stream is piped to a\n // destination this should not result in any observable difference.\n // We don't need to check if this is a writable premature close since\n // eos will only fail with premature close on the reading side for\n // duplex streams.\n src.once('end', finish).once('error', finish)\n } else {\n finish(err)\n }\n }\n )\n return eos(\n dst,\n {\n readable: false,\n writable: true\n },\n finish\n )\n}\nmodule.exports = {\n pipelineImpl,\n pipeline\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n;('use strict')\nconst {\n ArrayPrototypeIndexOf,\n NumberIsInteger,\n NumberIsNaN,\n NumberParseInt,\n ObjectDefineProperties,\n ObjectKeys,\n ObjectSetPrototypeOf,\n Promise,\n SafeSet,\n SymbolAsyncDispose,\n SymbolAsyncIterator,\n Symbol\n} = require('../../ours/primordials')\nmodule.exports = Readable\nReadable.ReadableState = ReadableState\nconst { EventEmitter: EE } = require('events')\nconst { Stream, prependListener } = require('./legacy')\nconst { Buffer } = require('buffer')\nconst { addAbortSignal } = require('./add-abort-signal')\nconst eos = require('./end-of-stream')\nlet debug = require('../../ours/util').debuglog('stream', (fn) => {\n debug = fn\n})\nconst BufferList = require('./buffer_list')\nconst destroyImpl = require('./destroy')\nconst { getHighWaterMark, getDefaultHighWaterMark } = require('./state')\nconst {\n aggregateTwoErrors,\n codes: {\n ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED,\n ERR_OUT_OF_RANGE,\n ERR_STREAM_PUSH_AFTER_EOF,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT\n },\n AbortError\n} = require('../../ours/errors')\nconst { validateObject } = require('../validators')\nconst kPaused = Symbol('kPaused')\nconst { StringDecoder } = require('string_decoder')\nconst from = require('./from')\nObjectSetPrototypeOf(Readable.prototype, Stream.prototype)\nObjectSetPrototypeOf(Readable, Stream)\nconst nop = () => {}\nconst { errorOrDestroy } = destroyImpl\nconst kObjectMode = 1 << 0\nconst kEnded = 1 << 1\nconst kEndEmitted = 1 << 2\nconst kReading = 1 << 3\nconst kConstructed = 1 << 4\nconst kSync = 1 << 5\nconst kNeedReadable = 1 << 6\nconst kEmittedReadable = 1 << 7\nconst kReadableListening = 1 << 8\nconst kResumeScheduled = 1 << 9\nconst kErrorEmitted = 1 << 10\nconst kEmitClose = 1 << 11\nconst kAutoDestroy = 1 << 12\nconst kDestroyed = 1 << 13\nconst kClosed = 1 << 14\nconst kCloseEmitted = 1 << 15\nconst kMultiAwaitDrain = 1 << 16\nconst kReadingMore = 1 << 17\nconst kDataEmitted = 1 << 18\n\n// TODO(benjamingr) it is likely slower to do it this way than with free functions\nfunction makeBitMapDescriptor(bit) {\n return {\n enumerable: false,\n get() {\n return (this.state & bit) !== 0\n },\n set(value) {\n if (value) this.state |= bit\n else this.state &= ~bit\n }\n }\n}\nObjectDefineProperties(ReadableState.prototype, {\n objectMode: makeBitMapDescriptor(kObjectMode),\n ended: makeBitMapDescriptor(kEnded),\n endEmitted: makeBitMapDescriptor(kEndEmitted),\n reading: makeBitMapDescriptor(kReading),\n // Stream is still being constructed and cannot be\n // destroyed until construction finished or failed.\n // Async construction is opt in, therefore we start as\n // constructed.\n constructed: makeBitMapDescriptor(kConstructed),\n // A flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n sync: makeBitMapDescriptor(kSync),\n // Whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n needReadable: makeBitMapDescriptor(kNeedReadable),\n emittedReadable: makeBitMapDescriptor(kEmittedReadable),\n readableListening: makeBitMapDescriptor(kReadableListening),\n resumeScheduled: makeBitMapDescriptor(kResumeScheduled),\n // True if the error was already emitted and should not be thrown again.\n errorEmitted: makeBitMapDescriptor(kErrorEmitted),\n emitClose: makeBitMapDescriptor(kEmitClose),\n autoDestroy: makeBitMapDescriptor(kAutoDestroy),\n // Has it been destroyed.\n destroyed: makeBitMapDescriptor(kDestroyed),\n // Indicates whether the stream has finished destroying.\n closed: makeBitMapDescriptor(kClosed),\n // True if close has been emitted or would have been emitted\n // depending on emitClose.\n closeEmitted: makeBitMapDescriptor(kCloseEmitted),\n multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain),\n // If true, a maybeReadMore has been scheduled.\n readingMore: makeBitMapDescriptor(kReadingMore),\n dataEmitted: makeBitMapDescriptor(kDataEmitted)\n})\nfunction ReadableState(options, stream, isDuplex) {\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex')\n\n // Bit map field to store ReadableState more effciently with 1 bit per field\n // instead of a V8 slot per field.\n this.state = kEmitClose | kAutoDestroy | kConstructed | kSync\n // Object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away.\n if (options && options.objectMode) this.state |= kObjectMode\n if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode\n\n // The point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n this.highWaterMark = options\n ? getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex)\n : getDefaultHighWaterMark(false)\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift().\n this.buffer = new BufferList()\n this.length = 0\n this.pipes = []\n this.flowing = null\n this[kPaused] = null\n\n // Should close be emitted on destroy. Defaults to true.\n if (options && options.emitClose === false) this.state &= ~kEmitClose\n\n // Should .destroy() be called after 'end' (and potentially 'finish').\n if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy\n\n // Indicates whether the stream has errored. When true no further\n // _read calls, 'data' or 'readable' events should occur. This is needed\n // since when autoDestroy is disabled we need a way to tell whether the\n // stream has failed.\n this.errored = null\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'\n\n // Ref the piped dest which we need a drain event on it\n // type: null | Writable | Set.\n this.awaitDrainWriters = null\n this.decoder = null\n this.encoding = null\n if (options && options.encoding) {\n this.decoder = new StringDecoder(options.encoding)\n this.encoding = options.encoding\n }\n}\nfunction Readable(options) {\n if (!(this instanceof Readable)) return new Readable(options)\n\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5.\n const isDuplex = this instanceof require('./duplex')\n this._readableState = new ReadableState(options, this, isDuplex)\n if (options) {\n if (typeof options.read === 'function') this._read = options.read\n if (typeof options.destroy === 'function') this._destroy = options.destroy\n if (typeof options.construct === 'function') this._construct = options.construct\n if (options.signal && !isDuplex) addAbortSignal(options.signal, this)\n }\n Stream.call(this, options)\n destroyImpl.construct(this, () => {\n if (this._readableState.needReadable) {\n maybeReadMore(this, this._readableState)\n }\n })\n}\nReadable.prototype.destroy = destroyImpl.destroy\nReadable.prototype._undestroy = destroyImpl.undestroy\nReadable.prototype._destroy = function (err, cb) {\n cb(err)\n}\nReadable.prototype[EE.captureRejectionSymbol] = function (err) {\n this.destroy(err)\n}\nReadable.prototype[SymbolAsyncDispose] = function () {\n let error\n if (!this.destroyed) {\n error = this.readableEnded ? null : new AbortError()\n this.destroy(error)\n }\n return new Promise((resolve, reject) => eos(this, (err) => (err && err !== error ? reject(err) : resolve(null))))\n}\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n return readableAddChunk(this, chunk, encoding, false)\n}\n\n// Unshift should *always* be something directly out of read().\nReadable.prototype.unshift = function (chunk, encoding) {\n return readableAddChunk(this, chunk, encoding, true)\n}\nfunction readableAddChunk(stream, chunk, encoding, addToFront) {\n debug('readableAddChunk', chunk)\n const state = stream._readableState\n let err\n if ((state.state & kObjectMode) === 0) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding\n if (state.encoding !== encoding) {\n if (addToFront && state.encoding) {\n // When unshifting, if state.encoding is set, we have to save\n // the string in the BufferList with the state encoding.\n chunk = Buffer.from(chunk, encoding).toString(state.encoding)\n } else {\n chunk = Buffer.from(chunk, encoding)\n encoding = ''\n }\n }\n } else if (chunk instanceof Buffer) {\n encoding = ''\n } else if (Stream._isUint8Array(chunk)) {\n chunk = Stream._uint8ArrayToBuffer(chunk)\n encoding = ''\n } else if (chunk != null) {\n err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk)\n }\n }\n if (err) {\n errorOrDestroy(stream, err)\n } else if (chunk === null) {\n state.state &= ~kReading\n onEofChunk(stream, state)\n } else if ((state.state & kObjectMode) !== 0 || (chunk && chunk.length > 0)) {\n if (addToFront) {\n if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT())\n else if (state.destroyed || state.errored) return false\n else addChunk(stream, state, chunk, true)\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF())\n } else if (state.destroyed || state.errored) {\n return false\n } else {\n state.state &= ~kReading\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk)\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false)\n else maybeReadMore(stream, state)\n } else {\n addChunk(stream, state, chunk, false)\n }\n }\n } else if (!addToFront) {\n state.state &= ~kReading\n maybeReadMore(stream, state)\n }\n\n // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n return !state.ended && (state.length < state.highWaterMark || state.length === 0)\n}\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount('data') > 0) {\n // Use the guard to avoid creating `Set()` repeatedly\n // when we have multiple pipes.\n if ((state.state & kMultiAwaitDrain) !== 0) {\n state.awaitDrainWriters.clear()\n } else {\n state.awaitDrainWriters = null\n }\n state.dataEmitted = true\n stream.emit('data', chunk)\n } else {\n // Update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length\n if (addToFront) state.buffer.unshift(chunk)\n else state.buffer.push(chunk)\n if ((state.state & kNeedReadable) !== 0) emitReadable(stream)\n }\n maybeReadMore(stream, state)\n}\nReadable.prototype.isPaused = function () {\n const state = this._readableState\n return state[kPaused] === true || state.flowing === false\n}\n\n// Backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n const decoder = new StringDecoder(enc)\n this._readableState.decoder = decoder\n // If setEncoding(null), decoder.encoding equals utf8.\n this._readableState.encoding = this._readableState.decoder.encoding\n const buffer = this._readableState.buffer\n // Iterate over current buffer to convert already stored Buffers:\n let content = ''\n for (const data of buffer) {\n content += decoder.write(data)\n }\n buffer.clear()\n if (content !== '') buffer.push(content)\n this._readableState.length = content.length\n return this\n}\n\n// Don't raise the hwm > 1GB.\nconst MAX_HWM = 0x40000000\nfunction computeNewHighWaterMark(n) {\n if (n > MAX_HWM) {\n throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n)\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts.\n n--\n n |= n >>> 1\n n |= n >>> 2\n n |= n >>> 4\n n |= n >>> 8\n n |= n >>> 16\n n++\n }\n return n\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || (state.length === 0 && state.ended)) return 0\n if ((state.state & kObjectMode) !== 0) return 1\n if (NumberIsNaN(n)) {\n // Only flow one buffer at a time.\n if (state.flowing && state.length) return state.buffer.first().length\n return state.length\n }\n if (n <= state.length) return n\n return state.ended ? state.length : 0\n}\n\n// You can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n)\n // Same as parseInt(undefined, 10), however V8 7.3 performance regressed\n // in this scenario, so we are doing it manually.\n if (n === undefined) {\n n = NaN\n } else if (!NumberIsInteger(n)) {\n n = NumberParseInt(n, 10)\n }\n const state = this._readableState\n const nOrig = n\n\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n)\n if (n !== 0) state.state &= ~kEmittedReadable\n\n // If we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (\n n === 0 &&\n state.needReadable &&\n ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)\n ) {\n debug('read: emitReadable', state.length, state.ended)\n if (state.length === 0 && state.ended) endReadable(this)\n else emitReadable(this)\n return null\n }\n n = howMuchToRead(n, state)\n\n // If we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this)\n return null\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n let doRead = (state.state & kNeedReadable) !== 0\n debug('need readable', doRead)\n\n // If we currently have less than the highWaterMark, then also read some.\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true\n debug('length less than watermark', doRead)\n }\n\n // However, if we've ended, then there's no point, if we're already\n // reading, then it's unnecessary, if we're constructing we have to wait,\n // and if we're destroyed or errored, then it's not allowed,\n if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) {\n doRead = false\n debug('reading, ended or constructing', doRead)\n } else if (doRead) {\n debug('do read')\n state.state |= kReading | kSync\n // If the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.state |= kNeedReadable\n\n // Call internal read method\n try {\n this._read(state.highWaterMark)\n } catch (err) {\n errorOrDestroy(this, err)\n }\n state.state &= ~kSync\n\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state)\n }\n let ret\n if (n > 0) ret = fromList(n, state)\n else ret = null\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark\n n = 0\n } else {\n state.length -= n\n if (state.multiAwaitDrain) {\n state.awaitDrainWriters.clear()\n } else {\n state.awaitDrainWriters = null\n }\n }\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this)\n }\n if (ret !== null && !state.errorEmitted && !state.closeEmitted) {\n state.dataEmitted = true\n this.emit('data', ret)\n }\n return ret\n}\nfunction onEofChunk(stream, state) {\n debug('onEofChunk')\n if (state.ended) return\n if (state.decoder) {\n const chunk = state.decoder.end()\n if (chunk && chunk.length) {\n state.buffer.push(chunk)\n state.length += state.objectMode ? 1 : chunk.length\n }\n }\n state.ended = true\n if (state.sync) {\n // If we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call.\n emitReadable(stream)\n } else {\n // Emit 'readable' now to make sure it gets picked up.\n state.needReadable = false\n state.emittedReadable = true\n // We have to emit readable now that we are EOF. Modules\n // in the ecosystem (e.g. dicer) rely on this event being sync.\n emitReadable_(stream)\n }\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n const state = stream._readableState\n debug('emitReadable', state.needReadable, state.emittedReadable)\n state.needReadable = false\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing)\n state.emittedReadable = true\n process.nextTick(emitReadable_, stream)\n }\n}\nfunction emitReadable_(stream) {\n const state = stream._readableState\n debug('emitReadable_', state.destroyed, state.length, state.ended)\n if (!state.destroyed && !state.errored && (state.length || state.ended)) {\n stream.emit('readable')\n state.emittedReadable = false\n }\n\n // The stream needs another readable event if:\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark\n flow(stream)\n}\n\n// At this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore && state.constructed) {\n state.readingMore = true\n process.nextTick(maybeReadMore_, stream, state)\n }\n}\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (\n !state.reading &&\n !state.ended &&\n (state.length < state.highWaterMark || (state.flowing && state.length === 0))\n ) {\n const len = state.length\n debug('maybeReadMore read 0')\n stream.read(0)\n if (len === state.length)\n // Didn't get any data, stop spinning.\n break\n }\n state.readingMore = false\n}\n\n// Abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n throw new ERR_METHOD_NOT_IMPLEMENTED('_read()')\n}\nReadable.prototype.pipe = function (dest, pipeOpts) {\n const src = this\n const state = this._readableState\n if (state.pipes.length === 1) {\n if (!state.multiAwaitDrain) {\n state.multiAwaitDrain = true\n state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : [])\n }\n }\n state.pipes.push(dest)\n debug('pipe count=%d opts=%j', state.pipes.length, pipeOpts)\n const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr\n const endFn = doEnd ? onend : unpipe\n if (state.endEmitted) process.nextTick(endFn)\n else src.once('end', endFn)\n dest.on('unpipe', onunpipe)\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe')\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true\n cleanup()\n }\n }\n }\n function onend() {\n debug('onend')\n dest.end()\n }\n let ondrain\n let cleanedUp = false\n function cleanup() {\n debug('cleanup')\n // Cleanup event handlers once the pipe is broken.\n dest.removeListener('close', onclose)\n dest.removeListener('finish', onfinish)\n if (ondrain) {\n dest.removeListener('drain', ondrain)\n }\n dest.removeListener('error', onerror)\n dest.removeListener('unpipe', onunpipe)\n src.removeListener('end', onend)\n src.removeListener('end', unpipe)\n src.removeListener('data', ondata)\n cleanedUp = true\n\n // If the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain()\n }\n function pause() {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if (!cleanedUp) {\n if (state.pipes.length === 1 && state.pipes[0] === dest) {\n debug('false write response, pause', 0)\n state.awaitDrainWriters = dest\n state.multiAwaitDrain = false\n } else if (state.pipes.length > 1 && state.pipes.includes(dest)) {\n debug('false write response, pause', state.awaitDrainWriters.size)\n state.awaitDrainWriters.add(dest)\n }\n src.pause()\n }\n if (!ondrain) {\n // When the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n ondrain = pipeOnDrain(src, dest)\n dest.on('drain', ondrain)\n }\n }\n src.on('data', ondata)\n function ondata(chunk) {\n debug('ondata')\n const ret = dest.write(chunk)\n debug('dest.write', ret)\n if (ret === false) {\n pause()\n }\n }\n\n // If the dest has an error, then stop piping into it.\n // However, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er)\n unpipe()\n dest.removeListener('error', onerror)\n if (dest.listenerCount('error') === 0) {\n const s = dest._writableState || dest._readableState\n if (s && !s.errorEmitted) {\n // User incorrectly emitted 'error' directly on the stream.\n errorOrDestroy(dest, er)\n } else {\n dest.emit('error', er)\n }\n }\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror)\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish)\n unpipe()\n }\n dest.once('close', onclose)\n function onfinish() {\n debug('onfinish')\n dest.removeListener('close', onclose)\n unpipe()\n }\n dest.once('finish', onfinish)\n function unpipe() {\n debug('unpipe')\n src.unpipe(dest)\n }\n\n // Tell the dest that it's being piped to.\n dest.emit('pipe', src)\n\n // Start the flow if it hasn't been started already.\n\n if (dest.writableNeedDrain === true) {\n pause()\n } else if (!state.flowing) {\n debug('pipe resume')\n src.resume()\n }\n return dest\n}\nfunction pipeOnDrain(src, dest) {\n return function pipeOnDrainFunctionResult() {\n const state = src._readableState\n\n // `ondrain` will call directly,\n // `this` maybe not a reference to dest,\n // so we use the real dest here.\n if (state.awaitDrainWriters === dest) {\n debug('pipeOnDrain', 1)\n state.awaitDrainWriters = null\n } else if (state.multiAwaitDrain) {\n debug('pipeOnDrain', state.awaitDrainWriters.size)\n state.awaitDrainWriters.delete(dest)\n }\n if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount('data')) {\n src.resume()\n }\n }\n}\nReadable.prototype.unpipe = function (dest) {\n const state = this._readableState\n const unpipeInfo = {\n hasUnpiped: false\n }\n\n // If we're not piping anywhere, then do nothing.\n if (state.pipes.length === 0) return this\n if (!dest) {\n // remove all.\n const dests = state.pipes\n state.pipes = []\n this.pause()\n for (let i = 0; i < dests.length; i++)\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n })\n return this\n }\n\n // Try to find the right one.\n const index = ArrayPrototypeIndexOf(state.pipes, dest)\n if (index === -1) return this\n state.pipes.splice(index, 1)\n if (state.pipes.length === 0) this.pause()\n dest.emit('unpipe', this, unpipeInfo)\n return this\n}\n\n// Set up data events if they are asked for\n// Ensure readable listeners eventually get something.\nReadable.prototype.on = function (ev, fn) {\n const res = Stream.prototype.on.call(this, ev, fn)\n const state = this._readableState\n if (ev === 'data') {\n // Update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0\n\n // Try start flowing on next tick if stream isn't explicitly paused.\n if (state.flowing !== false) this.resume()\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true\n state.flowing = false\n state.emittedReadable = false\n debug('on readable', state.length, state.reading)\n if (state.length) {\n emitReadable(this)\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this)\n }\n }\n }\n return res\n}\nReadable.prototype.addListener = Readable.prototype.on\nReadable.prototype.removeListener = function (ev, fn) {\n const res = Stream.prototype.removeListener.call(this, ev, fn)\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this)\n }\n return res\n}\nReadable.prototype.off = Readable.prototype.removeListener\nReadable.prototype.removeAllListeners = function (ev) {\n const res = Stream.prototype.removeAllListeners.apply(this, arguments)\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this)\n }\n return res\n}\nfunction updateReadableListening(self) {\n const state = self._readableState\n state.readableListening = self.listenerCount('readable') > 0\n if (state.resumeScheduled && state[kPaused] === false) {\n // Flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true\n\n // Crude way to check if we should resume.\n } else if (self.listenerCount('data') > 0) {\n self.resume()\n } else if (!state.readableListening) {\n state.flowing = null\n }\n}\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0')\n self.read(0)\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n const state = this._readableState\n if (!state.flowing) {\n debug('resume')\n // We flow only if there is no one listening\n // for readable, but we still have to call\n // resume().\n state.flowing = !state.readableListening\n resume(this, state)\n }\n state[kPaused] = false\n return this\n}\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true\n process.nextTick(resume_, stream, state)\n }\n}\nfunction resume_(stream, state) {\n debug('resume', state.reading)\n if (!state.reading) {\n stream.read(0)\n }\n state.resumeScheduled = false\n stream.emit('resume')\n flow(stream)\n if (state.flowing && !state.reading) stream.read(0)\n}\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing)\n if (this._readableState.flowing !== false) {\n debug('pause')\n this._readableState.flowing = false\n this.emit('pause')\n }\n this._readableState[kPaused] = true\n return this\n}\nfunction flow(stream) {\n const state = stream._readableState\n debug('flow', state.flowing)\n while (state.flowing && stream.read() !== null);\n}\n\n// Wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n let paused = false\n\n // TODO (ronag): Should this.destroy(err) emit\n // 'error' on the wrapped stream? Would require\n // a static factory method, e.g. Readable.wrap(stream).\n\n stream.on('data', (chunk) => {\n if (!this.push(chunk) && stream.pause) {\n paused = true\n stream.pause()\n }\n })\n stream.on('end', () => {\n this.push(null)\n })\n stream.on('error', (err) => {\n errorOrDestroy(this, err)\n })\n stream.on('close', () => {\n this.destroy()\n })\n stream.on('destroy', () => {\n this.destroy()\n })\n this._read = () => {\n if (paused && stream.resume) {\n paused = false\n stream.resume()\n }\n }\n\n // Proxy all the other methods. Important when wrapping filters and duplexes.\n const streamKeys = ObjectKeys(stream)\n for (let j = 1; j < streamKeys.length; j++) {\n const i = streamKeys[j]\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = stream[i].bind(stream)\n }\n }\n return this\n}\nReadable.prototype[SymbolAsyncIterator] = function () {\n return streamToAsyncIterator(this)\n}\nReadable.prototype.iterator = function (options) {\n if (options !== undefined) {\n validateObject(options, 'options')\n }\n return streamToAsyncIterator(this, options)\n}\nfunction streamToAsyncIterator(stream, options) {\n if (typeof stream.read !== 'function') {\n stream = Readable.wrap(stream, {\n objectMode: true\n })\n }\n const iter = createAsyncIterator(stream, options)\n iter.stream = stream\n return iter\n}\nasync function* createAsyncIterator(stream, options) {\n let callback = nop\n function next(resolve) {\n if (this === stream) {\n callback()\n callback = nop\n } else {\n callback = resolve\n }\n }\n stream.on('readable', next)\n let error\n const cleanup = eos(\n stream,\n {\n writable: false\n },\n (err) => {\n error = err ? aggregateTwoErrors(error, err) : null\n callback()\n callback = nop\n }\n )\n try {\n while (true) {\n const chunk = stream.destroyed ? null : stream.read()\n if (chunk !== null) {\n yield chunk\n } else if (error) {\n throw error\n } else if (error === null) {\n return\n } else {\n await new Promise(next)\n }\n }\n } catch (err) {\n error = aggregateTwoErrors(error, err)\n throw error\n } finally {\n if (\n (error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) &&\n (error === undefined || stream._readableState.autoDestroy)\n ) {\n destroyImpl.destroyer(stream, null)\n } else {\n stream.off('readable', next)\n cleanup()\n }\n }\n}\n\n// Making it explicit these properties are not enumerable\n// because otherwise some prototype manipulation in\n// userland will fail.\nObjectDefineProperties(Readable.prototype, {\n readable: {\n __proto__: null,\n get() {\n const r = this._readableState\n // r.readable === false means that this is part of a Duplex stream\n // where the readable side was disabled upon construction.\n // Compat. The user might manually disable readable side through\n // deprecated setter.\n return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted\n },\n set(val) {\n // Backwards compat.\n if (this._readableState) {\n this._readableState.readable = !!val\n }\n }\n },\n readableDidRead: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return this._readableState.dataEmitted\n }\n },\n readableAborted: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return !!(\n this._readableState.readable !== false &&\n (this._readableState.destroyed || this._readableState.errored) &&\n !this._readableState.endEmitted\n )\n }\n },\n readableHighWaterMark: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark\n }\n },\n readableBuffer: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return this._readableState && this._readableState.buffer\n }\n },\n readableFlowing: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return this._readableState.flowing\n },\n set: function (state) {\n if (this._readableState) {\n this._readableState.flowing = state\n }\n }\n },\n readableLength: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState.length\n }\n },\n readableObjectMode: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.objectMode : false\n }\n },\n readableEncoding: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.encoding : null\n }\n },\n errored: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.errored : null\n }\n },\n closed: {\n __proto__: null,\n get() {\n return this._readableState ? this._readableState.closed : false\n }\n },\n destroyed: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.destroyed : false\n },\n set(value) {\n // We ignore the value if the stream\n // has not been initialized yet.\n if (!this._readableState) {\n return\n }\n\n // Backward compatibility, the user is explicitly\n // managing destroyed.\n this._readableState.destroyed = value\n }\n },\n readableEnded: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.endEmitted : false\n }\n }\n})\nObjectDefineProperties(ReadableState.prototype, {\n // Legacy getter for `pipesCount`.\n pipesCount: {\n __proto__: null,\n get() {\n return this.pipes.length\n }\n },\n // Legacy property for `paused`.\n paused: {\n __proto__: null,\n get() {\n return this[kPaused] !== false\n },\n set(value) {\n this[kPaused] = !!value\n }\n }\n})\n\n// Exposed for testing purposes only.\nReadable._fromList = fromList\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered.\n if (state.length === 0) return null\n let ret\n if (state.objectMode) ret = state.buffer.shift()\n else if (!n || n >= state.length) {\n // Read it all, truncate the list.\n if (state.decoder) ret = state.buffer.join('')\n else if (state.buffer.length === 1) ret = state.buffer.first()\n else ret = state.buffer.concat(state.length)\n state.buffer.clear()\n } else {\n // read part of list.\n ret = state.buffer.consume(n, state.decoder)\n }\n return ret\n}\nfunction endReadable(stream) {\n const state = stream._readableState\n debug('endReadable', state.endEmitted)\n if (!state.endEmitted) {\n state.ended = true\n process.nextTick(endReadableNT, state, stream)\n }\n}\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length)\n\n // Check that we didn't get one last unshift.\n if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) {\n state.endEmitted = true\n stream.emit('end')\n if (stream.writable && stream.allowHalfOpen === false) {\n process.nextTick(endWritableNT, stream)\n } else if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well.\n const wState = stream._writableState\n const autoDestroy =\n !wState ||\n (wState.autoDestroy &&\n // We don't expect the writable to ever 'finish'\n // if writable is explicitly set to false.\n (wState.finished || wState.writable === false))\n if (autoDestroy) {\n stream.destroy()\n }\n }\n }\n}\nfunction endWritableNT(stream) {\n const writable = stream.writable && !stream.writableEnded && !stream.destroyed\n if (writable) {\n stream.end()\n }\n}\nReadable.from = function (iterable, opts) {\n return from(Readable, iterable, opts)\n}\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n return webStreamsAdapters\n}\nReadable.fromWeb = function (readableStream, options) {\n return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options)\n}\nReadable.toWeb = function (streamReadable, options) {\n return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options)\n}\nReadable.wrap = function (src, options) {\n var _ref, _src$readableObjectMo\n return new Readable({\n objectMode:\n (_ref =\n (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined\n ? _src$readableObjectMo\n : src.objectMode) !== null && _ref !== undefined\n ? _ref\n : true,\n ...options,\n destroy(err, callback) {\n destroyImpl.destroyer(src, err)\n callback(err)\n }\n }).wrap(src)\n}\n","'use strict'\n\nconst { MathFloor, NumberIsInteger } = require('../../ours/primordials')\nconst { validateInteger } = require('../validators')\nconst { ERR_INVALID_ARG_VALUE } = require('../../ours/errors').codes\nlet defaultHighWaterMarkBytes = 16 * 1024\nlet defaultHighWaterMarkObjectMode = 16\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null\n}\nfunction getDefaultHighWaterMark(objectMode) {\n return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes\n}\nfunction setDefaultHighWaterMark(objectMode, value) {\n validateInteger(value, 'value', 0)\n if (objectMode) {\n defaultHighWaterMarkObjectMode = value\n } else {\n defaultHighWaterMarkBytes = value\n }\n}\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n const hwm = highWaterMarkFrom(options, isDuplex, duplexKey)\n if (hwm != null) {\n if (!NumberIsInteger(hwm) || hwm < 0) {\n const name = isDuplex ? `options.${duplexKey}` : 'options.highWaterMark'\n throw new ERR_INVALID_ARG_VALUE(name, hwm)\n }\n return MathFloor(hwm)\n }\n\n // Default value\n return getDefaultHighWaterMark(state.objectMode)\n}\nmodule.exports = {\n getHighWaterMark,\n getDefaultHighWaterMark,\n setDefaultHighWaterMark\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict'\n\nconst { ObjectSetPrototypeOf, Symbol } = require('../../ours/primordials')\nmodule.exports = Transform\nconst { ERR_METHOD_NOT_IMPLEMENTED } = require('../../ours/errors').codes\nconst Duplex = require('./duplex')\nconst { getHighWaterMark } = require('./state')\nObjectSetPrototypeOf(Transform.prototype, Duplex.prototype)\nObjectSetPrototypeOf(Transform, Duplex)\nconst kCallback = Symbol('kCallback')\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options)\n\n // TODO (ronag): This should preferably always be\n // applied but would be semver-major. Or even better;\n // make Transform a Readable with the Writable interface.\n const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null\n if (readableHighWaterMark === 0) {\n // A Duplex will buffer both on the writable and readable side while\n // a Transform just wants to buffer hwm number of elements. To avoid\n // buffering twice we disable buffering on the writable side.\n options = {\n ...options,\n highWaterMark: null,\n readableHighWaterMark,\n // TODO (ronag): 0 is not optimal since we have\n // a \"bug\" where we check needDrain before calling _write and not after.\n // Refs: https://github.com/nodejs/node/pull/32887\n // Refs: https://github.com/nodejs/node/pull/35941\n writableHighWaterMark: options.writableHighWaterMark || 0\n }\n }\n Duplex.call(this, options)\n\n // We have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false\n this[kCallback] = null\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform\n if (typeof options.flush === 'function') this._flush = options.flush\n }\n\n // When the writable side finishes, then flush out anything remaining.\n // Backwards compat. Some Transform streams incorrectly implement _final\n // instead of or in addition to _flush. By using 'prefinish' instead of\n // implementing _final we continue supporting this unfortunate use case.\n this.on('prefinish', prefinish)\n}\nfunction final(cb) {\n if (typeof this._flush === 'function' && !this.destroyed) {\n this._flush((er, data) => {\n if (er) {\n if (cb) {\n cb(er)\n } else {\n this.destroy(er)\n }\n return\n }\n if (data != null) {\n this.push(data)\n }\n this.push(null)\n if (cb) {\n cb()\n }\n })\n } else {\n this.push(null)\n if (cb) {\n cb()\n }\n }\n}\nfunction prefinish() {\n if (this._final !== final) {\n final.call(this)\n }\n}\nTransform.prototype._final = final\nTransform.prototype._transform = function (chunk, encoding, callback) {\n throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()')\n}\nTransform.prototype._write = function (chunk, encoding, callback) {\n const rState = this._readableState\n const wState = this._writableState\n const length = rState.length\n this._transform(chunk, encoding, (err, val) => {\n if (err) {\n callback(err)\n return\n }\n if (val != null) {\n this.push(val)\n }\n if (\n wState.ended ||\n // Backwards compat.\n length === rState.length ||\n // Backwards compat.\n rState.length < rState.highWaterMark\n ) {\n callback()\n } else {\n this[kCallback] = callback\n }\n })\n}\nTransform.prototype._read = function () {\n if (this[kCallback]) {\n const callback = this[kCallback]\n this[kCallback] = null\n callback()\n }\n}\n","'use strict'\n\nconst { SymbolAsyncIterator, SymbolIterator, SymbolFor } = require('../../ours/primordials')\n\n// We need to use SymbolFor to make these globally available\n// for interopt with readable-stream, i.e. readable-stream\n// and node core needs to be able to read/write private state\n// from each other for proper interoperability.\nconst kIsDestroyed = SymbolFor('nodejs.stream.destroyed')\nconst kIsErrored = SymbolFor('nodejs.stream.errored')\nconst kIsReadable = SymbolFor('nodejs.stream.readable')\nconst kIsWritable = SymbolFor('nodejs.stream.writable')\nconst kIsDisturbed = SymbolFor('nodejs.stream.disturbed')\nconst kIsClosedPromise = SymbolFor('nodejs.webstream.isClosedPromise')\nconst kControllerErrorFunction = SymbolFor('nodejs.webstream.controllerErrorFunction')\nfunction isReadableNodeStream(obj, strict = false) {\n var _obj$_readableState\n return !!(\n (\n obj &&\n typeof obj.pipe === 'function' &&\n typeof obj.on === 'function' &&\n (!strict || (typeof obj.pause === 'function' && typeof obj.resume === 'function')) &&\n (!obj._writableState ||\n ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined\n ? undefined\n : _obj$_readableState.readable) !== false) &&\n // Duplex\n (!obj._writableState || obj._readableState)\n ) // Writable has .pipe.\n )\n}\n\nfunction isWritableNodeStream(obj) {\n var _obj$_writableState\n return !!(\n (\n obj &&\n typeof obj.write === 'function' &&\n typeof obj.on === 'function' &&\n (!obj._readableState ||\n ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined\n ? undefined\n : _obj$_writableState.writable) !== false)\n ) // Duplex\n )\n}\n\nfunction isDuplexNodeStream(obj) {\n return !!(\n obj &&\n typeof obj.pipe === 'function' &&\n obj._readableState &&\n typeof obj.on === 'function' &&\n typeof obj.write === 'function'\n )\n}\nfunction isNodeStream(obj) {\n return (\n obj &&\n (obj._readableState ||\n obj._writableState ||\n (typeof obj.write === 'function' && typeof obj.on === 'function') ||\n (typeof obj.pipe === 'function' && typeof obj.on === 'function'))\n )\n}\nfunction isReadableStream(obj) {\n return !!(\n obj &&\n !isNodeStream(obj) &&\n typeof obj.pipeThrough === 'function' &&\n typeof obj.getReader === 'function' &&\n typeof obj.cancel === 'function'\n )\n}\nfunction isWritableStream(obj) {\n return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === 'function' && typeof obj.abort === 'function')\n}\nfunction isTransformStream(obj) {\n return !!(obj && !isNodeStream(obj) && typeof obj.readable === 'object' && typeof obj.writable === 'object')\n}\nfunction isWebStream(obj) {\n return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj)\n}\nfunction isIterable(obj, isAsync) {\n if (obj == null) return false\n if (isAsync === true) return typeof obj[SymbolAsyncIterator] === 'function'\n if (isAsync === false) return typeof obj[SymbolIterator] === 'function'\n return typeof obj[SymbolAsyncIterator] === 'function' || typeof obj[SymbolIterator] === 'function'\n}\nfunction isDestroyed(stream) {\n if (!isNodeStream(stream)) return null\n const wState = stream._writableState\n const rState = stream._readableState\n const state = wState || rState\n return !!(stream.destroyed || stream[kIsDestroyed] || (state !== null && state !== undefined && state.destroyed))\n}\n\n// Have been end():d.\nfunction isWritableEnded(stream) {\n if (!isWritableNodeStream(stream)) return null\n if (stream.writableEnded === true) return true\n const wState = stream._writableState\n if (wState !== null && wState !== undefined && wState.errored) return false\n if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== 'boolean') return null\n return wState.ended\n}\n\n// Have emitted 'finish'.\nfunction isWritableFinished(stream, strict) {\n if (!isWritableNodeStream(stream)) return null\n if (stream.writableFinished === true) return true\n const wState = stream._writableState\n if (wState !== null && wState !== undefined && wState.errored) return false\n if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== 'boolean') return null\n return !!(wState.finished || (strict === false && wState.ended === true && wState.length === 0))\n}\n\n// Have been push(null):d.\nfunction isReadableEnded(stream) {\n if (!isReadableNodeStream(stream)) return null\n if (stream.readableEnded === true) return true\n const rState = stream._readableState\n if (!rState || rState.errored) return false\n if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== 'boolean') return null\n return rState.ended\n}\n\n// Have emitted 'end'.\nfunction isReadableFinished(stream, strict) {\n if (!isReadableNodeStream(stream)) return null\n const rState = stream._readableState\n if (rState !== null && rState !== undefined && rState.errored) return false\n if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== 'boolean') return null\n return !!(rState.endEmitted || (strict === false && rState.ended === true && rState.length === 0))\n}\nfunction isReadable(stream) {\n if (stream && stream[kIsReadable] != null) return stream[kIsReadable]\n if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== 'boolean') return null\n if (isDestroyed(stream)) return false\n return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream)\n}\nfunction isWritable(stream) {\n if (stream && stream[kIsWritable] != null) return stream[kIsWritable]\n if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== 'boolean') return null\n if (isDestroyed(stream)) return false\n return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream)\n}\nfunction isFinished(stream, opts) {\n if (!isNodeStream(stream)) {\n return null\n }\n if (isDestroyed(stream)) {\n return true\n }\n if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream)) {\n return false\n }\n if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream)) {\n return false\n }\n return true\n}\nfunction isWritableErrored(stream) {\n var _stream$_writableStat, _stream$_writableStat2\n if (!isNodeStream(stream)) {\n return null\n }\n if (stream.writableErrored) {\n return stream.writableErrored\n }\n return (_stream$_writableStat =\n (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined\n ? undefined\n : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined\n ? _stream$_writableStat\n : null\n}\nfunction isReadableErrored(stream) {\n var _stream$_readableStat, _stream$_readableStat2\n if (!isNodeStream(stream)) {\n return null\n }\n if (stream.readableErrored) {\n return stream.readableErrored\n }\n return (_stream$_readableStat =\n (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined\n ? undefined\n : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined\n ? _stream$_readableStat\n : null\n}\nfunction isClosed(stream) {\n if (!isNodeStream(stream)) {\n return null\n }\n if (typeof stream.closed === 'boolean') {\n return stream.closed\n }\n const wState = stream._writableState\n const rState = stream._readableState\n if (\n typeof (wState === null || wState === undefined ? undefined : wState.closed) === 'boolean' ||\n typeof (rState === null || rState === undefined ? undefined : rState.closed) === 'boolean'\n ) {\n return (\n (wState === null || wState === undefined ? undefined : wState.closed) ||\n (rState === null || rState === undefined ? undefined : rState.closed)\n )\n }\n if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) {\n return stream._closed\n }\n return null\n}\nfunction isOutgoingMessage(stream) {\n return (\n typeof stream._closed === 'boolean' &&\n typeof stream._defaultKeepAlive === 'boolean' &&\n typeof stream._removedConnection === 'boolean' &&\n typeof stream._removedContLen === 'boolean'\n )\n}\nfunction isServerResponse(stream) {\n return typeof stream._sent100 === 'boolean' && isOutgoingMessage(stream)\n}\nfunction isServerRequest(stream) {\n var _stream$req\n return (\n typeof stream._consuming === 'boolean' &&\n typeof stream._dumped === 'boolean' &&\n ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) ===\n undefined\n )\n}\nfunction willEmitClose(stream) {\n if (!isNodeStream(stream)) return null\n const wState = stream._writableState\n const rState = stream._readableState\n const state = wState || rState\n return (\n (!state && isServerResponse(stream)) || !!(state && state.autoDestroy && state.emitClose && state.closed === false)\n )\n}\nfunction isDisturbed(stream) {\n var _stream$kIsDisturbed\n return !!(\n stream &&\n ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined\n ? _stream$kIsDisturbed\n : stream.readableDidRead || stream.readableAborted)\n )\n}\nfunction isErrored(stream) {\n var _ref,\n _ref2,\n _ref3,\n _ref4,\n _ref5,\n _stream$kIsErrored,\n _stream$_readableStat3,\n _stream$_writableStat3,\n _stream$_readableStat4,\n _stream$_writableStat4\n return !!(\n stream &&\n ((_ref =\n (_ref2 =\n (_ref3 =\n (_ref4 =\n (_ref5 =\n (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined\n ? _stream$kIsErrored\n : stream.readableErrored) !== null && _ref5 !== undefined\n ? _ref5\n : stream.writableErrored) !== null && _ref4 !== undefined\n ? _ref4\n : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined\n ? undefined\n : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined\n ? _ref3\n : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined\n ? undefined\n : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined\n ? _ref2\n : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined\n ? undefined\n : _stream$_readableStat4.errored) !== null && _ref !== undefined\n ? _ref\n : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined\n ? undefined\n : _stream$_writableStat4.errored)\n )\n}\nmodule.exports = {\n isDestroyed,\n kIsDestroyed,\n isDisturbed,\n kIsDisturbed,\n isErrored,\n kIsErrored,\n isReadable,\n kIsReadable,\n kIsClosedPromise,\n kControllerErrorFunction,\n kIsWritable,\n isClosed,\n isDuplexNodeStream,\n isFinished,\n isIterable,\n isReadableNodeStream,\n isReadableStream,\n isReadableEnded,\n isReadableFinished,\n isReadableErrored,\n isNodeStream,\n isWebStream,\n isWritable,\n isWritableNodeStream,\n isWritableStream,\n isWritableEnded,\n isWritableFinished,\n isWritableErrored,\n isServerRequest,\n isServerResponse,\n willEmitClose,\n isTransformStream\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n;('use strict')\nconst {\n ArrayPrototypeSlice,\n Error,\n FunctionPrototypeSymbolHasInstance,\n ObjectDefineProperty,\n ObjectDefineProperties,\n ObjectSetPrototypeOf,\n StringPrototypeToLowerCase,\n Symbol,\n SymbolHasInstance\n} = require('../../ours/primordials')\nmodule.exports = Writable\nWritable.WritableState = WritableState\nconst { EventEmitter: EE } = require('events')\nconst Stream = require('./legacy').Stream\nconst { Buffer } = require('buffer')\nconst destroyImpl = require('./destroy')\nconst { addAbortSignal } = require('./add-abort-signal')\nconst { getHighWaterMark, getDefaultHighWaterMark } = require('./state')\nconst {\n ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED,\n ERR_STREAM_ALREADY_FINISHED,\n ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING\n} = require('../../ours/errors').codes\nconst { errorOrDestroy } = destroyImpl\nObjectSetPrototypeOf(Writable.prototype, Stream.prototype)\nObjectSetPrototypeOf(Writable, Stream)\nfunction nop() {}\nconst kOnFinished = Symbol('kOnFinished')\nfunction WritableState(options, stream, isDuplex) {\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex')\n\n // Object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!(options && options.objectMode)\n if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode)\n\n // The point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write().\n this.highWaterMark = options\n ? getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex)\n : getDefaultHighWaterMark(false)\n\n // if _final has been called.\n this.finalCalled = false\n\n // drain event flag.\n this.needDrain = false\n // At the start of calling end()\n this.ending = false\n // When end() has been called, and returned.\n this.ended = false\n // When 'finish' is emitted.\n this.finished = false\n\n // Has it been destroyed\n this.destroyed = false\n\n // Should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n const noDecode = !!(options && options.decodeStrings === false)\n this.decodeStrings = !noDecode\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'\n\n // Not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0\n\n // A flag to see when we're in the middle of a write.\n this.writing = false\n\n // When true all writes will be buffered until .uncork() call.\n this.corked = 0\n\n // A flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true\n\n // A flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false\n\n // The callback that's passed to _write(chunk, cb).\n this.onwrite = onwrite.bind(undefined, stream)\n\n // The callback that the user supplies to write(chunk, encoding, cb).\n this.writecb = null\n\n // The amount that is being written when _write is called.\n this.writelen = 0\n\n // Storage for data passed to the afterWrite() callback in case of\n // synchronous _write() completion.\n this.afterWriteTickInfo = null\n resetBuffer(this)\n\n // Number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted.\n this.pendingcb = 0\n\n // Stream is still being constructed and cannot be\n // destroyed until construction finished or failed.\n // Async construction is opt in, therefore we start as\n // constructed.\n this.constructed = true\n\n // Emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams.\n this.prefinished = false\n\n // True if the error was already emitted and should not be thrown again.\n this.errorEmitted = false\n\n // Should close be emitted on destroy. Defaults to true.\n this.emitClose = !options || options.emitClose !== false\n\n // Should .destroy() be called after 'finish' (and potentially 'end').\n this.autoDestroy = !options || options.autoDestroy !== false\n\n // Indicates whether the stream has errored. When true all write() calls\n // should return false. This is needed since when autoDestroy\n // is disabled we need a way to tell whether the stream has failed.\n this.errored = null\n\n // Indicates whether the stream has finished destroying.\n this.closed = false\n\n // True if close has been emitted or would have been emitted\n // depending on emitClose.\n this.closeEmitted = false\n this[kOnFinished] = []\n}\nfunction resetBuffer(state) {\n state.buffered = []\n state.bufferedIndex = 0\n state.allBuffers = true\n state.allNoop = true\n}\nWritableState.prototype.getBuffer = function getBuffer() {\n return ArrayPrototypeSlice(this.buffered, this.bufferedIndex)\n}\nObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', {\n __proto__: null,\n get() {\n return this.buffered.length - this.bufferedIndex\n }\n})\nfunction Writable(options) {\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5.\n const isDuplex = this instanceof require('./duplex')\n if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options)\n this._writableState = new WritableState(options, this, isDuplex)\n if (options) {\n if (typeof options.write === 'function') this._write = options.write\n if (typeof options.writev === 'function') this._writev = options.writev\n if (typeof options.destroy === 'function') this._destroy = options.destroy\n if (typeof options.final === 'function') this._final = options.final\n if (typeof options.construct === 'function') this._construct = options.construct\n if (options.signal) addAbortSignal(options.signal, this)\n }\n Stream.call(this, options)\n destroyImpl.construct(this, () => {\n const state = this._writableState\n if (!state.writing) {\n clearBuffer(this, state)\n }\n finishMaybe(this, state)\n })\n}\nObjectDefineProperty(Writable, SymbolHasInstance, {\n __proto__: null,\n value: function (object) {\n if (FunctionPrototypeSymbolHasInstance(this, object)) return true\n if (this !== Writable) return false\n return object && object._writableState instanceof WritableState\n }\n})\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE())\n}\nfunction _write(stream, chunk, encoding, cb) {\n const state = stream._writableState\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = state.defaultEncoding\n } else {\n if (!encoding) encoding = state.defaultEncoding\n else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding)\n if (typeof cb !== 'function') cb = nop\n }\n if (chunk === null) {\n throw new ERR_STREAM_NULL_VALUES()\n } else if (!state.objectMode) {\n if (typeof chunk === 'string') {\n if (state.decodeStrings !== false) {\n chunk = Buffer.from(chunk, encoding)\n encoding = 'buffer'\n }\n } else if (chunk instanceof Buffer) {\n encoding = 'buffer'\n } else if (Stream._isUint8Array(chunk)) {\n chunk = Stream._uint8ArrayToBuffer(chunk)\n encoding = 'buffer'\n } else {\n throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk)\n }\n }\n let err\n if (state.ending) {\n err = new ERR_STREAM_WRITE_AFTER_END()\n } else if (state.destroyed) {\n err = new ERR_STREAM_DESTROYED('write')\n }\n if (err) {\n process.nextTick(cb, err)\n errorOrDestroy(stream, err, true)\n return err\n }\n state.pendingcb++\n return writeOrBuffer(stream, state, chunk, encoding, cb)\n}\nWritable.prototype.write = function (chunk, encoding, cb) {\n return _write(this, chunk, encoding, cb) === true\n}\nWritable.prototype.cork = function () {\n this._writableState.corked++\n}\nWritable.prototype.uncork = function () {\n const state = this._writableState\n if (state.corked) {\n state.corked--\n if (!state.writing) clearBuffer(this, state)\n }\n}\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = StringPrototypeToLowerCase(encoding)\n if (!Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding)\n this._writableState.defaultEncoding = encoding\n return this\n}\n\n// If we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, chunk, encoding, callback) {\n const len = state.objectMode ? 1 : chunk.length\n state.length += len\n\n // stream._write resets state.length\n const ret = state.length < state.highWaterMark\n // We must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true\n if (state.writing || state.corked || state.errored || !state.constructed) {\n state.buffered.push({\n chunk,\n encoding,\n callback\n })\n if (state.allBuffers && encoding !== 'buffer') {\n state.allBuffers = false\n }\n if (state.allNoop && callback !== nop) {\n state.allNoop = false\n }\n } else {\n state.writelen = len\n state.writecb = callback\n state.writing = true\n state.sync = true\n stream._write(chunk, encoding, state.onwrite)\n state.sync = false\n }\n\n // Return false if errored or destroyed in order to break\n // any synchronous while(stream.write(data)) loops.\n return ret && !state.errored && !state.destroyed\n}\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len\n state.writecb = cb\n state.writing = true\n state.sync = true\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'))\n else if (writev) stream._writev(chunk, state.onwrite)\n else stream._write(chunk, encoding, state.onwrite)\n state.sync = false\n}\nfunction onwriteError(stream, state, er, cb) {\n --state.pendingcb\n cb(er)\n // Ensure callbacks are invoked even when autoDestroy is\n // not enabled. Passing `er` here doesn't make sense since\n // it's related to one specific write, not to the buffered\n // writes.\n errorBuffer(state)\n // This can emit error, but error must always follow cb.\n errorOrDestroy(stream, er)\n}\nfunction onwrite(stream, er) {\n const state = stream._writableState\n const sync = state.sync\n const cb = state.writecb\n if (typeof cb !== 'function') {\n errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK())\n return\n }\n state.writing = false\n state.writecb = null\n state.length -= state.writelen\n state.writelen = 0\n if (er) {\n // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n er.stack // eslint-disable-line no-unused-expressions\n\n if (!state.errored) {\n state.errored = er\n }\n\n // In case of duplex streams we need to notify the readable side of the\n // error.\n if (stream._readableState && !stream._readableState.errored) {\n stream._readableState.errored = er\n }\n if (sync) {\n process.nextTick(onwriteError, stream, state, er, cb)\n } else {\n onwriteError(stream, state, er, cb)\n }\n } else {\n if (state.buffered.length > state.bufferedIndex) {\n clearBuffer(stream, state)\n }\n if (sync) {\n // It is a common case that the callback passed to .write() is always\n // the same. In that case, we do not schedule a new nextTick(), but\n // rather just increase a counter, to improve performance and avoid\n // memory allocations.\n if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) {\n state.afterWriteTickInfo.count++\n } else {\n state.afterWriteTickInfo = {\n count: 1,\n cb,\n stream,\n state\n }\n process.nextTick(afterWriteTick, state.afterWriteTickInfo)\n }\n } else {\n afterWrite(stream, state, 1, cb)\n }\n }\n}\nfunction afterWriteTick({ stream, state, count, cb }) {\n state.afterWriteTickInfo = null\n return afterWrite(stream, state, count, cb)\n}\nfunction afterWrite(stream, state, count, cb) {\n const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain\n if (needDrain) {\n state.needDrain = false\n stream.emit('drain')\n }\n while (count-- > 0) {\n state.pendingcb--\n cb()\n }\n if (state.destroyed) {\n errorBuffer(state)\n }\n finishMaybe(stream, state)\n}\n\n// If there's something in the buffer waiting, then invoke callbacks.\nfunction errorBuffer(state) {\n if (state.writing) {\n return\n }\n for (let n = state.bufferedIndex; n < state.buffered.length; ++n) {\n var _state$errored\n const { chunk, callback } = state.buffered[n]\n const len = state.objectMode ? 1 : chunk.length\n state.length -= len\n callback(\n (_state$errored = state.errored) !== null && _state$errored !== undefined\n ? _state$errored\n : new ERR_STREAM_DESTROYED('write')\n )\n }\n const onfinishCallbacks = state[kOnFinished].splice(0)\n for (let i = 0; i < onfinishCallbacks.length; i++) {\n var _state$errored2\n onfinishCallbacks[i](\n (_state$errored2 = state.errored) !== null && _state$errored2 !== undefined\n ? _state$errored2\n : new ERR_STREAM_DESTROYED('end')\n )\n }\n resetBuffer(state)\n}\n\n// If there's something in the buffer waiting, then process it.\nfunction clearBuffer(stream, state) {\n if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) {\n return\n }\n const { buffered, bufferedIndex, objectMode } = state\n const bufferedLength = buffered.length - bufferedIndex\n if (!bufferedLength) {\n return\n }\n let i = bufferedIndex\n state.bufferProcessing = true\n if (bufferedLength > 1 && stream._writev) {\n state.pendingcb -= bufferedLength - 1\n const callback = state.allNoop\n ? nop\n : (err) => {\n for (let n = i; n < buffered.length; ++n) {\n buffered[n].callback(err)\n }\n }\n // Make a copy of `buffered` if it's going to be used by `callback` above,\n // since `doWrite` will mutate the array.\n const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i)\n chunks.allBuffers = state.allBuffers\n doWrite(stream, state, true, state.length, chunks, '', callback)\n resetBuffer(state)\n } else {\n do {\n const { chunk, encoding, callback } = buffered[i]\n buffered[i++] = null\n const len = objectMode ? 1 : chunk.length\n doWrite(stream, state, false, len, chunk, encoding, callback)\n } while (i < buffered.length && !state.writing)\n if (i === buffered.length) {\n resetBuffer(state)\n } else if (i > 256) {\n buffered.splice(0, i)\n state.bufferedIndex = 0\n } else {\n state.bufferedIndex = i\n }\n }\n state.bufferProcessing = false\n}\nWritable.prototype._write = function (chunk, encoding, cb) {\n if (this._writev) {\n this._writev(\n [\n {\n chunk,\n encoding\n }\n ],\n cb\n )\n } else {\n throw new ERR_METHOD_NOT_IMPLEMENTED('_write()')\n }\n}\nWritable.prototype._writev = null\nWritable.prototype.end = function (chunk, encoding, cb) {\n const state = this._writableState\n if (typeof chunk === 'function') {\n cb = chunk\n chunk = null\n encoding = null\n } else if (typeof encoding === 'function') {\n cb = encoding\n encoding = null\n }\n let err\n if (chunk !== null && chunk !== undefined) {\n const ret = _write(this, chunk, encoding)\n if (ret instanceof Error) {\n err = ret\n }\n }\n\n // .end() fully uncorks.\n if (state.corked) {\n state.corked = 1\n this.uncork()\n }\n if (err) {\n // Do nothing...\n } else if (!state.errored && !state.ending) {\n // This is forgiving in terms of unnecessary calls to end() and can hide\n // logic errors. However, usually such errors are harmless and causing a\n // hard error can be disproportionately destructive. It is not always\n // trivial for the user to determine whether end() needs to be called\n // or not.\n\n state.ending = true\n finishMaybe(this, state, true)\n state.ended = true\n } else if (state.finished) {\n err = new ERR_STREAM_ALREADY_FINISHED('end')\n } else if (state.destroyed) {\n err = new ERR_STREAM_DESTROYED('end')\n }\n if (typeof cb === 'function') {\n if (err || state.finished) {\n process.nextTick(cb, err)\n } else {\n state[kOnFinished].push(cb)\n }\n }\n return this\n}\nfunction needFinish(state) {\n return (\n state.ending &&\n !state.destroyed &&\n state.constructed &&\n state.length === 0 &&\n !state.errored &&\n state.buffered.length === 0 &&\n !state.finished &&\n !state.writing &&\n !state.errorEmitted &&\n !state.closeEmitted\n )\n}\nfunction callFinal(stream, state) {\n let called = false\n function onFinish(err) {\n if (called) {\n errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK())\n return\n }\n called = true\n state.pendingcb--\n if (err) {\n const onfinishCallbacks = state[kOnFinished].splice(0)\n for (let i = 0; i < onfinishCallbacks.length; i++) {\n onfinishCallbacks[i](err)\n }\n errorOrDestroy(stream, err, state.sync)\n } else if (needFinish(state)) {\n state.prefinished = true\n stream.emit('prefinish')\n // Backwards compat. Don't check state.sync here.\n // Some streams assume 'finish' will be emitted\n // asynchronously relative to _final callback.\n state.pendingcb++\n process.nextTick(finish, stream, state)\n }\n }\n state.sync = true\n state.pendingcb++\n try {\n stream._final(onFinish)\n } catch (err) {\n onFinish(err)\n }\n state.sync = false\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.finalCalled = true\n callFinal(stream, state)\n } else {\n state.prefinished = true\n stream.emit('prefinish')\n }\n }\n}\nfunction finishMaybe(stream, state, sync) {\n if (needFinish(state)) {\n prefinish(stream, state)\n if (state.pendingcb === 0) {\n if (sync) {\n state.pendingcb++\n process.nextTick(\n (stream, state) => {\n if (needFinish(state)) {\n finish(stream, state)\n } else {\n state.pendingcb--\n }\n },\n stream,\n state\n )\n } else if (needFinish(state)) {\n state.pendingcb++\n finish(stream, state)\n }\n }\n }\n}\nfunction finish(stream, state) {\n state.pendingcb--\n state.finished = true\n const onfinishCallbacks = state[kOnFinished].splice(0)\n for (let i = 0; i < onfinishCallbacks.length; i++) {\n onfinishCallbacks[i]()\n }\n stream.emit('finish')\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well.\n const rState = stream._readableState\n const autoDestroy =\n !rState ||\n (rState.autoDestroy &&\n // We don't expect the readable to ever 'end'\n // if readable is explicitly set to false.\n (rState.endEmitted || rState.readable === false))\n if (autoDestroy) {\n stream.destroy()\n }\n }\n}\nObjectDefineProperties(Writable.prototype, {\n closed: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.closed : false\n }\n },\n destroyed: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.destroyed : false\n },\n set(value) {\n // Backward compatibility, the user is explicitly managing destroyed.\n if (this._writableState) {\n this._writableState.destroyed = value\n }\n }\n },\n writable: {\n __proto__: null,\n get() {\n const w = this._writableState\n // w.writable === false means that this is part of a Duplex stream\n // where the writable side was disabled upon construction.\n // Compat. The user might manually disable writable side through\n // deprecated setter.\n return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended\n },\n set(val) {\n // Backwards compatible.\n if (this._writableState) {\n this._writableState.writable = !!val\n }\n }\n },\n writableFinished: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.finished : false\n }\n },\n writableObjectMode: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.objectMode : false\n }\n },\n writableBuffer: {\n __proto__: null,\n get() {\n return this._writableState && this._writableState.getBuffer()\n }\n },\n writableEnded: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.ending : false\n }\n },\n writableNeedDrain: {\n __proto__: null,\n get() {\n const wState = this._writableState\n if (!wState) return false\n return !wState.destroyed && !wState.ending && wState.needDrain\n }\n },\n writableHighWaterMark: {\n __proto__: null,\n get() {\n return this._writableState && this._writableState.highWaterMark\n }\n },\n writableCorked: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.corked : 0\n }\n },\n writableLength: {\n __proto__: null,\n get() {\n return this._writableState && this._writableState.length\n }\n },\n errored: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._writableState ? this._writableState.errored : null\n }\n },\n writableAborted: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return !!(\n this._writableState.writable !== false &&\n (this._writableState.destroyed || this._writableState.errored) &&\n !this._writableState.finished\n )\n }\n }\n})\nconst destroy = destroyImpl.destroy\nWritable.prototype.destroy = function (err, cb) {\n const state = this._writableState\n\n // Invoke pending callbacks.\n if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) {\n process.nextTick(errorBuffer, state)\n }\n destroy.call(this, err, cb)\n return this\n}\nWritable.prototype._undestroy = destroyImpl.undestroy\nWritable.prototype._destroy = function (err, cb) {\n cb(err)\n}\nWritable.prototype[EE.captureRejectionSymbol] = function (err) {\n this.destroy(err)\n}\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n return webStreamsAdapters\n}\nWritable.fromWeb = function (writableStream, options) {\n return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options)\n}\nWritable.toWeb = function (streamWritable) {\n return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable)\n}\n","/* eslint jsdoc/require-jsdoc: \"error\" */\n\n'use strict'\n\nconst {\n ArrayIsArray,\n ArrayPrototypeIncludes,\n ArrayPrototypeJoin,\n ArrayPrototypeMap,\n NumberIsInteger,\n NumberIsNaN,\n NumberMAX_SAFE_INTEGER,\n NumberMIN_SAFE_INTEGER,\n NumberParseInt,\n ObjectPrototypeHasOwnProperty,\n RegExpPrototypeExec,\n String,\n StringPrototypeToUpperCase,\n StringPrototypeTrim\n} = require('../ours/primordials')\nconst {\n hideStackFrames,\n codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL }\n} = require('../ours/errors')\nconst { normalizeEncoding } = require('../ours/util')\nconst { isAsyncFunction, isArrayBufferView } = require('../ours/util').types\nconst signals = {}\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nfunction isInt32(value) {\n return value === (value | 0)\n}\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nfunction isUint32(value) {\n return value === value >>> 0\n}\nconst octalReg = /^[0-7]+$/\nconst modeDesc = 'must be a 32-bit unsigned integer or an octal string'\n\n/**\n * Parse and validate values that will be converted into mode_t (the S_*\n * constants). Only valid numbers and octal strings are allowed. They could be\n * converted to 32-bit unsigned integers or non-negative signed integers in the\n * C++ land, but any value higher than 0o777 will result in platform-specific\n * behaviors.\n * @param {*} value Values to be validated\n * @param {string} name Name of the argument\n * @param {number} [def] If specified, will be returned for invalid values\n * @returns {number}\n */\nfunction parseFileMode(value, name, def) {\n if (typeof value === 'undefined') {\n value = def\n }\n if (typeof value === 'string') {\n if (RegExpPrototypeExec(octalReg, value) === null) {\n throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc)\n }\n value = NumberParseInt(value, 8)\n }\n validateUint32(value, name)\n return value\n}\n\n/**\n * @callback validateInteger\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateInteger} */\nconst validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => {\n if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n})\n\n/**\n * @callback validateInt32\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateInt32} */\nconst validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => {\n // The defaults for min and max correspond to the limits of 32-bit integers.\n if (typeof value !== 'number') {\n throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n if (!NumberIsInteger(value)) {\n throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n }\n if (value < min || value > max) {\n throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n }\n})\n\n/**\n * @callback validateUint32\n * @param {*} value\n * @param {string} name\n * @param {number|boolean} [positive=false]\n * @returns {asserts value is number}\n */\n\n/** @type {validateUint32} */\nconst validateUint32 = hideStackFrames((value, name, positive = false) => {\n if (typeof value !== 'number') {\n throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n if (!NumberIsInteger(value)) {\n throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n }\n const min = positive ? 1 : 0\n // 2 ** 32 === 4294967296\n const max = 4294967295\n if (value < min || value > max) {\n throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n }\n})\n\n/**\n * @callback validateString\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is string}\n */\n\n/** @type {validateString} */\nfunction validateString(value, name) {\n if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value)\n}\n\n/**\n * @callback validateNumber\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateNumber} */\nfunction validateNumber(value, name, min = undefined, max) {\n if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n if (\n (min != null && value < min) ||\n (max != null && value > max) ||\n ((min != null || max != null) && NumberIsNaN(value))\n ) {\n throw new ERR_OUT_OF_RANGE(\n name,\n `${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`,\n value\n )\n }\n}\n\n/**\n * @callback validateOneOf\n * @template T\n * @param {T} value\n * @param {string} name\n * @param {T[]} oneOf\n */\n\n/** @type {validateOneOf} */\nconst validateOneOf = hideStackFrames((value, name, oneOf) => {\n if (!ArrayPrototypeIncludes(oneOf, value)) {\n const allowed = ArrayPrototypeJoin(\n ArrayPrototypeMap(oneOf, (v) => (typeof v === 'string' ? `'${v}'` : String(v))),\n ', '\n )\n const reason = 'must be one of: ' + allowed\n throw new ERR_INVALID_ARG_VALUE(name, value, reason)\n }\n})\n\n/**\n * @callback validateBoolean\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is boolean}\n */\n\n/** @type {validateBoolean} */\nfunction validateBoolean(value, name) {\n if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value)\n}\n\n/**\n * @param {any} options\n * @param {string} key\n * @param {boolean} defaultValue\n * @returns {boolean}\n */\nfunction getOwnPropertyValueOrDefault(options, key, defaultValue) {\n return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key]\n}\n\n/**\n * @callback validateObject\n * @param {*} value\n * @param {string} name\n * @param {{\n * allowArray?: boolean,\n * allowFunction?: boolean,\n * nullable?: boolean\n * }} [options]\n */\n\n/** @type {validateObject} */\nconst validateObject = hideStackFrames((value, name, options = null) => {\n const allowArray = getOwnPropertyValueOrDefault(options, 'allowArray', false)\n const allowFunction = getOwnPropertyValueOrDefault(options, 'allowFunction', false)\n const nullable = getOwnPropertyValueOrDefault(options, 'nullable', false)\n if (\n (!nullable && value === null) ||\n (!allowArray && ArrayIsArray(value)) ||\n (typeof value !== 'object' && (!allowFunction || typeof value !== 'function'))\n ) {\n throw new ERR_INVALID_ARG_TYPE(name, 'Object', value)\n }\n})\n\n/**\n * @callback validateDictionary - We are using the Web IDL Standard definition\n * of \"dictionary\" here, which means any value\n * whose Type is either Undefined, Null, or\n * Object (which includes functions).\n * @param {*} value\n * @param {string} name\n * @see https://webidl.spec.whatwg.org/#es-dictionary\n * @see https://tc39.es/ecma262/#table-typeof-operator-results\n */\n\n/** @type {validateDictionary} */\nconst validateDictionary = hideStackFrames((value, name) => {\n if (value != null && typeof value !== 'object' && typeof value !== 'function') {\n throw new ERR_INVALID_ARG_TYPE(name, 'a dictionary', value)\n }\n})\n\n/**\n * @callback validateArray\n * @param {*} value\n * @param {string} name\n * @param {number} [minLength]\n * @returns {asserts value is any[]}\n */\n\n/** @type {validateArray} */\nconst validateArray = hideStackFrames((value, name, minLength = 0) => {\n if (!ArrayIsArray(value)) {\n throw new ERR_INVALID_ARG_TYPE(name, 'Array', value)\n }\n if (value.length < minLength) {\n const reason = `must be longer than ${minLength}`\n throw new ERR_INVALID_ARG_VALUE(name, value, reason)\n }\n})\n\n/**\n * @callback validateStringArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is string[]}\n */\n\n/** @type {validateStringArray} */\nfunction validateStringArray(value, name) {\n validateArray(value, name)\n for (let i = 0; i < value.length; i++) {\n validateString(value[i], `${name}[${i}]`)\n }\n}\n\n/**\n * @callback validateBooleanArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is boolean[]}\n */\n\n/** @type {validateBooleanArray} */\nfunction validateBooleanArray(value, name) {\n validateArray(value, name)\n for (let i = 0; i < value.length; i++) {\n validateBoolean(value[i], `${name}[${i}]`)\n }\n}\n\n/**\n * @callback validateAbortSignalArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is AbortSignal[]}\n */\n\n/** @type {validateAbortSignalArray} */\nfunction validateAbortSignalArray(value, name) {\n validateArray(value, name)\n for (let i = 0; i < value.length; i++) {\n const signal = value[i]\n const indexedName = `${name}[${i}]`\n if (signal == null) {\n throw new ERR_INVALID_ARG_TYPE(indexedName, 'AbortSignal', signal)\n }\n validateAbortSignal(signal, indexedName)\n }\n}\n\n/**\n * @param {*} signal\n * @param {string} [name='signal']\n * @returns {asserts signal is keyof signals}\n */\nfunction validateSignalName(signal, name = 'signal') {\n validateString(signal, name)\n if (signals[signal] === undefined) {\n if (signals[StringPrototypeToUpperCase(signal)] !== undefined) {\n throw new ERR_UNKNOWN_SIGNAL(signal + ' (signals must use all capital letters)')\n }\n throw new ERR_UNKNOWN_SIGNAL(signal)\n }\n}\n\n/**\n * @callback validateBuffer\n * @param {*} buffer\n * @param {string} [name='buffer']\n * @returns {asserts buffer is ArrayBufferView}\n */\n\n/** @type {validateBuffer} */\nconst validateBuffer = hideStackFrames((buffer, name = 'buffer') => {\n if (!isArrayBufferView(buffer)) {\n throw new ERR_INVALID_ARG_TYPE(name, ['Buffer', 'TypedArray', 'DataView'], buffer)\n }\n})\n\n/**\n * @param {string} data\n * @param {string} encoding\n */\nfunction validateEncoding(data, encoding) {\n const normalizedEncoding = normalizeEncoding(encoding)\n const length = data.length\n if (normalizedEncoding === 'hex' && length % 2 !== 0) {\n throw new ERR_INVALID_ARG_VALUE('encoding', encoding, `is invalid for data of length ${length}`)\n }\n}\n\n/**\n * Check that the port number is not NaN when coerced to a number,\n * is an integer and that it falls within the legal range of port numbers.\n * @param {*} port\n * @param {string} [name='Port']\n * @param {boolean} [allowZero=true]\n * @returns {number}\n */\nfunction validatePort(port, name = 'Port', allowZero = true) {\n if (\n (typeof port !== 'number' && typeof port !== 'string') ||\n (typeof port === 'string' && StringPrototypeTrim(port).length === 0) ||\n +port !== +port >>> 0 ||\n port > 0xffff ||\n (port === 0 && !allowZero)\n ) {\n throw new ERR_SOCKET_BAD_PORT(name, port, allowZero)\n }\n return port | 0\n}\n\n/**\n * @callback validateAbortSignal\n * @param {*} signal\n * @param {string} name\n */\n\n/** @type {validateAbortSignal} */\nconst validateAbortSignal = hideStackFrames((signal, name) => {\n if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {\n throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n }\n})\n\n/**\n * @callback validateFunction\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is Function}\n */\n\n/** @type {validateFunction} */\nconst validateFunction = hideStackFrames((value, name) => {\n if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n})\n\n/**\n * @callback validatePlainFunction\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is Function}\n */\n\n/** @type {validatePlainFunction} */\nconst validatePlainFunction = hideStackFrames((value, name) => {\n if (typeof value !== 'function' || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n})\n\n/**\n * @callback validateUndefined\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is undefined}\n */\n\n/** @type {validateUndefined} */\nconst validateUndefined = hideStackFrames((value, name) => {\n if (value !== undefined) throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value)\n})\n\n/**\n * @template T\n * @param {T} value\n * @param {string} name\n * @param {T[]} union\n */\nfunction validateUnion(value, name, union) {\n if (!ArrayPrototypeIncludes(union, value)) {\n throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value)\n }\n}\n\n/*\n The rules for the Link header field are described here:\n https://www.rfc-editor.org/rfc/rfc8288.html#section-3\n\n This regex validates any string surrounded by angle brackets\n (not necessarily a valid URI reference) followed by zero or more\n link-params separated by semicolons.\n*/\nconst linkValueRegExp = /^(?:<[^>]*>)(?:\\s*;\\s*[^;\"\\s]+(?:=(\")?[^;\"\\s]*\\1)?)*$/\n\n/**\n * @param {any} value\n * @param {string} name\n */\nfunction validateLinkHeaderFormat(value, name) {\n if (typeof value === 'undefined' || !RegExpPrototypeExec(linkValueRegExp, value)) {\n throw new ERR_INVALID_ARG_VALUE(\n name,\n value,\n 'must be an array or string of format \"; rel=preload; as=style\"'\n )\n }\n}\n\n/**\n * @param {any} hints\n * @return {string}\n */\nfunction validateLinkHeaderValue(hints) {\n if (typeof hints === 'string') {\n validateLinkHeaderFormat(hints, 'hints')\n return hints\n } else if (ArrayIsArray(hints)) {\n const hintsLength = hints.length\n let result = ''\n if (hintsLength === 0) {\n return result\n }\n for (let i = 0; i < hintsLength; i++) {\n const link = hints[i]\n validateLinkHeaderFormat(link, 'hints')\n result += link\n if (i !== hintsLength - 1) {\n result += ', '\n }\n }\n return result\n }\n throw new ERR_INVALID_ARG_VALUE(\n 'hints',\n hints,\n 'must be an array or string of format \"; rel=preload; as=style\"'\n )\n}\nmodule.exports = {\n isInt32,\n isUint32,\n parseFileMode,\n validateArray,\n validateStringArray,\n validateBooleanArray,\n validateAbortSignalArray,\n validateBoolean,\n validateBuffer,\n validateDictionary,\n validateEncoding,\n validateFunction,\n validateInt32,\n validateInteger,\n validateNumber,\n validateObject,\n validateOneOf,\n validatePlainFunction,\n validatePort,\n validateSignalName,\n validateString,\n validateUint32,\n validateUndefined,\n validateUnion,\n validateAbortSignal,\n validateLinkHeaderValue\n}\n","'use strict'\n\nconst CustomStream = require('../stream')\nconst promises = require('../stream/promises')\nconst originalDestroy = CustomStream.Readable.destroy\nmodule.exports = CustomStream.Readable\n\n// Explicit export naming is needed for ESM\nmodule.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer\nmodule.exports._isUint8Array = CustomStream._isUint8Array\nmodule.exports.isDisturbed = CustomStream.isDisturbed\nmodule.exports.isErrored = CustomStream.isErrored\nmodule.exports.isReadable = CustomStream.isReadable\nmodule.exports.Readable = CustomStream.Readable\nmodule.exports.Writable = CustomStream.Writable\nmodule.exports.Duplex = CustomStream.Duplex\nmodule.exports.Transform = CustomStream.Transform\nmodule.exports.PassThrough = CustomStream.PassThrough\nmodule.exports.addAbortSignal = CustomStream.addAbortSignal\nmodule.exports.finished = CustomStream.finished\nmodule.exports.destroy = CustomStream.destroy\nmodule.exports.destroy = originalDestroy\nmodule.exports.pipeline = CustomStream.pipeline\nmodule.exports.compose = CustomStream.compose\nObject.defineProperty(CustomStream, 'promises', {\n configurable: true,\n enumerable: true,\n get() {\n return promises\n }\n})\nmodule.exports.Stream = CustomStream.Stream\n\n// Allow default importing\nmodule.exports.default = module.exports\n","'use strict'\n\nconst { format, inspect, AggregateError: CustomAggregateError } = require('./util')\n\n/*\n This file is a reduced and adapted version of the main lib/internal/errors.js file defined at\n\n https://github.com/nodejs/node/blob/master/lib/internal/errors.js\n\n Don't try to replace with the original file and keep it up to date (starting from E(...) definitions)\n with the upstream file.\n*/\n\nconst AggregateError = globalThis.AggregateError || CustomAggregateError\nconst kIsNodeError = Symbol('kIsNodeError')\nconst kTypes = [\n 'string',\n 'function',\n 'number',\n 'object',\n // Accept 'Function' and 'Object' as alternative to the lower cased version.\n 'Function',\n 'Object',\n 'boolean',\n 'bigint',\n 'symbol'\n]\nconst classRegExp = /^([A-Z][a-z0-9]*)+$/\nconst nodeInternalPrefix = '__node_internal_'\nconst codes = {}\nfunction assert(value, message) {\n if (!value) {\n throw new codes.ERR_INTERNAL_ASSERTION(message)\n }\n}\n\n// Only use this for integers! Decimal numbers do not work with this function.\nfunction addNumericalSeparator(val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\nfunction getMessage(key, msg, args) {\n if (typeof msg === 'function') {\n assert(\n msg.length <= args.length,\n // Default options do not count.\n `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`\n )\n return msg(...args)\n }\n const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length\n assert(\n expectedLength === args.length,\n `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`\n )\n if (args.length === 0) {\n return msg\n }\n return format(msg, ...args)\n}\nfunction E(code, message, Base) {\n if (!Base) {\n Base = Error\n }\n class NodeError extends Base {\n constructor(...args) {\n super(getMessage(code, message, args))\n }\n toString() {\n return `${this.name} [${code}]: ${this.message}`\n }\n }\n Object.defineProperties(NodeError.prototype, {\n name: {\n value: Base.name,\n writable: true,\n enumerable: false,\n configurable: true\n },\n toString: {\n value() {\n return `${this.name} [${code}]: ${this.message}`\n },\n writable: true,\n enumerable: false,\n configurable: true\n }\n })\n NodeError.prototype.code = code\n NodeError.prototype[kIsNodeError] = true\n codes[code] = NodeError\n}\nfunction hideStackFrames(fn) {\n // We rename the functions that will be hidden to cut off the stacktrace\n // at the outermost one\n const hidden = nodeInternalPrefix + fn.name\n Object.defineProperty(fn, 'name', {\n value: hidden\n })\n return fn\n}\nfunction aggregateTwoErrors(innerError, outerError) {\n if (innerError && outerError && innerError !== outerError) {\n if (Array.isArray(outerError.errors)) {\n // If `outerError` is already an `AggregateError`.\n outerError.errors.push(innerError)\n return outerError\n }\n const err = new AggregateError([outerError, innerError], outerError.message)\n err.code = outerError.code\n return err\n }\n return innerError || outerError\n}\nclass AbortError extends Error {\n constructor(message = 'The operation was aborted', options = undefined) {\n if (options !== undefined && typeof options !== 'object') {\n throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options)\n }\n super(message, options)\n this.code = 'ABORT_ERR'\n this.name = 'AbortError'\n }\n}\nE('ERR_ASSERTION', '%s', Error)\nE(\n 'ERR_INVALID_ARG_TYPE',\n (name, expected, actual) => {\n assert(typeof name === 'string', \"'name' must be a string\")\n if (!Array.isArray(expected)) {\n expected = [expected]\n }\n let msg = 'The '\n if (name.endsWith(' argument')) {\n // For cases like 'first argument'\n msg += `${name} `\n } else {\n msg += `\"${name}\" ${name.includes('.') ? 'property' : 'argument'} `\n }\n msg += 'must be '\n const types = []\n const instances = []\n const other = []\n for (const value of expected) {\n assert(typeof value === 'string', 'All expected entries have to be of type string')\n if (kTypes.includes(value)) {\n types.push(value.toLowerCase())\n } else if (classRegExp.test(value)) {\n instances.push(value)\n } else {\n assert(value !== 'object', 'The value \"object\" should be written as \"Object\"')\n other.push(value)\n }\n }\n\n // Special handle `object` in case other instances are allowed to outline\n // the differences between each other.\n if (instances.length > 0) {\n const pos = types.indexOf('object')\n if (pos !== -1) {\n types.splice(types, pos, 1)\n instances.push('Object')\n }\n }\n if (types.length > 0) {\n switch (types.length) {\n case 1:\n msg += `of type ${types[0]}`\n break\n case 2:\n msg += `one of type ${types[0]} or ${types[1]}`\n break\n default: {\n const last = types.pop()\n msg += `one of type ${types.join(', ')}, or ${last}`\n }\n }\n if (instances.length > 0 || other.length > 0) {\n msg += ' or '\n }\n }\n if (instances.length > 0) {\n switch (instances.length) {\n case 1:\n msg += `an instance of ${instances[0]}`\n break\n case 2:\n msg += `an instance of ${instances[0]} or ${instances[1]}`\n break\n default: {\n const last = instances.pop()\n msg += `an instance of ${instances.join(', ')}, or ${last}`\n }\n }\n if (other.length > 0) {\n msg += ' or '\n }\n }\n switch (other.length) {\n case 0:\n break\n case 1:\n if (other[0].toLowerCase() !== other[0]) {\n msg += 'an '\n }\n msg += `${other[0]}`\n break\n case 2:\n msg += `one of ${other[0]} or ${other[1]}`\n break\n default: {\n const last = other.pop()\n msg += `one of ${other.join(', ')}, or ${last}`\n }\n }\n if (actual == null) {\n msg += `. Received ${actual}`\n } else if (typeof actual === 'function' && actual.name) {\n msg += `. Received function ${actual.name}`\n } else if (typeof actual === 'object') {\n var _actual$constructor\n if (\n (_actual$constructor = actual.constructor) !== null &&\n _actual$constructor !== undefined &&\n _actual$constructor.name\n ) {\n msg += `. Received an instance of ${actual.constructor.name}`\n } else {\n const inspected = inspect(actual, {\n depth: -1\n })\n msg += `. Received ${inspected}`\n }\n } else {\n let inspected = inspect(actual, {\n colors: false\n })\n if (inspected.length > 25) {\n inspected = `${inspected.slice(0, 25)}...`\n }\n msg += `. Received type ${typeof actual} (${inspected})`\n }\n return msg\n },\n TypeError\n)\nE(\n 'ERR_INVALID_ARG_VALUE',\n (name, value, reason = 'is invalid') => {\n let inspected = inspect(value)\n if (inspected.length > 128) {\n inspected = inspected.slice(0, 128) + '...'\n }\n const type = name.includes('.') ? 'property' : 'argument'\n return `The ${type} '${name}' ${reason}. Received ${inspected}`\n },\n TypeError\n)\nE(\n 'ERR_INVALID_RETURN_VALUE',\n (input, name, value) => {\n var _value$constructor\n const type =\n value !== null &&\n value !== undefined &&\n (_value$constructor = value.constructor) !== null &&\n _value$constructor !== undefined &&\n _value$constructor.name\n ? `instance of ${value.constructor.name}`\n : `type ${typeof value}`\n return `Expected ${input} to be returned from the \"${name}\"` + ` function but got ${type}.`\n },\n TypeError\n)\nE(\n 'ERR_MISSING_ARGS',\n (...args) => {\n assert(args.length > 0, 'At least one arg needs to be specified')\n let msg\n const len = args.length\n args = (Array.isArray(args) ? args : [args]).map((a) => `\"${a}\"`).join(' or ')\n switch (len) {\n case 1:\n msg += `The ${args[0]} argument`\n break\n case 2:\n msg += `The ${args[0]} and ${args[1]} arguments`\n break\n default:\n {\n const last = args.pop()\n msg += `The ${args.join(', ')}, and ${last} arguments`\n }\n break\n }\n return `${msg} must be specified`\n },\n TypeError\n)\nE(\n 'ERR_OUT_OF_RANGE',\n (str, range, input) => {\n assert(range, 'Missing \"range\" argument')\n let received\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > 2n ** 32n || input < -(2n ** 32n)) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n } else {\n received = inspect(input)\n }\n return `The value of \"${str}\" is out of range. It must be ${range}. Received ${received}`\n },\n RangeError\n)\nE('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error)\nE('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error)\nE('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error)\nE('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error)\nE('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error)\nE('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError)\nE('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error)\nE('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error)\nE('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error)\nE('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error)\nE('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError)\nmodule.exports = {\n AbortError,\n aggregateTwoErrors: hideStackFrames(aggregateTwoErrors),\n hideStackFrames,\n codes\n}\n","'use strict'\n\n/*\n This file is a reduced and adapted version of the main lib/internal/per_context/primordials.js file defined at\n\n https://github.com/nodejs/node/blob/master/lib/internal/per_context/primordials.js\n\n Don't try to replace with the original file and keep it up to date with the upstream file.\n*/\nmodule.exports = {\n ArrayIsArray(self) {\n return Array.isArray(self)\n },\n ArrayPrototypeIncludes(self, el) {\n return self.includes(el)\n },\n ArrayPrototypeIndexOf(self, el) {\n return self.indexOf(el)\n },\n ArrayPrototypeJoin(self, sep) {\n return self.join(sep)\n },\n ArrayPrototypeMap(self, fn) {\n return self.map(fn)\n },\n ArrayPrototypePop(self, el) {\n return self.pop(el)\n },\n ArrayPrototypePush(self, el) {\n return self.push(el)\n },\n ArrayPrototypeSlice(self, start, end) {\n return self.slice(start, end)\n },\n Error,\n FunctionPrototypeCall(fn, thisArgs, ...args) {\n return fn.call(thisArgs, ...args)\n },\n FunctionPrototypeSymbolHasInstance(self, instance) {\n return Function.prototype[Symbol.hasInstance].call(self, instance)\n },\n MathFloor: Math.floor,\n Number,\n NumberIsInteger: Number.isInteger,\n NumberIsNaN: Number.isNaN,\n NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,\n NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,\n NumberParseInt: Number.parseInt,\n ObjectDefineProperties(self, props) {\n return Object.defineProperties(self, props)\n },\n ObjectDefineProperty(self, name, prop) {\n return Object.defineProperty(self, name, prop)\n },\n ObjectGetOwnPropertyDescriptor(self, name) {\n return Object.getOwnPropertyDescriptor(self, name)\n },\n ObjectKeys(obj) {\n return Object.keys(obj)\n },\n ObjectSetPrototypeOf(target, proto) {\n return Object.setPrototypeOf(target, proto)\n },\n Promise,\n PromisePrototypeCatch(self, fn) {\n return self.catch(fn)\n },\n PromisePrototypeThen(self, thenFn, catchFn) {\n return self.then(thenFn, catchFn)\n },\n PromiseReject(err) {\n return Promise.reject(err)\n },\n PromiseResolve(val) {\n return Promise.resolve(val)\n },\n ReflectApply: Reflect.apply,\n RegExpPrototypeTest(self, value) {\n return self.test(value)\n },\n SafeSet: Set,\n String,\n StringPrototypeSlice(self, start, end) {\n return self.slice(start, end)\n },\n StringPrototypeToLowerCase(self) {\n return self.toLowerCase()\n },\n StringPrototypeToUpperCase(self) {\n return self.toUpperCase()\n },\n StringPrototypeTrim(self) {\n return self.trim()\n },\n Symbol,\n SymbolFor: Symbol.for,\n SymbolAsyncIterator: Symbol.asyncIterator,\n SymbolHasInstance: Symbol.hasInstance,\n SymbolIterator: Symbol.iterator,\n SymbolDispose: Symbol.dispose || Symbol('Symbol.dispose'),\n SymbolAsyncDispose: Symbol.asyncDispose || Symbol('Symbol.asyncDispose'),\n TypedArrayPrototypeSet(self, buf, len) {\n return self.set(buf, len)\n },\n Boolean: Boolean,\n Uint8Array\n}\n","'use strict'\n\nconst bufferModule = require('buffer')\nconst { kResistStopPropagation, SymbolDispose } = require('./primordials')\nconst AbortSignal = globalThis.AbortSignal || require('abort-controller').AbortSignal\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst AsyncFunction = Object.getPrototypeOf(async function () {}).constructor\nconst Blob = globalThis.Blob || bufferModule.Blob\n/* eslint-disable indent */\nconst isBlob =\n typeof Blob !== 'undefined'\n ? function isBlob(b) {\n // eslint-disable-next-line indent\n return b instanceof Blob\n }\n : function isBlob(b) {\n return false\n }\n/* eslint-enable indent */\n\nconst validateAbortSignal = (signal, name) => {\n if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {\n throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n }\n}\nconst validateFunction = (value, name) => {\n if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n}\n\n// This is a simplified version of AggregateError\nclass AggregateError extends Error {\n constructor(errors) {\n if (!Array.isArray(errors)) {\n throw new TypeError(`Expected input to be an Array, got ${typeof errors}`)\n }\n let message = ''\n for (let i = 0; i < errors.length; i++) {\n message += ` ${errors[i].stack}\\n`\n }\n super(message)\n this.name = 'AggregateError'\n this.errors = errors\n }\n}\nmodule.exports = {\n AggregateError,\n kEmptyObject: Object.freeze({}),\n once(callback) {\n let called = false\n return function (...args) {\n if (called) {\n return\n }\n called = true\n callback.apply(this, args)\n }\n },\n createDeferredPromise: function () {\n let resolve\n let reject\n\n // eslint-disable-next-line promise/param-names\n const promise = new Promise((res, rej) => {\n resolve = res\n reject = rej\n })\n return {\n promise,\n resolve,\n reject\n }\n },\n promisify(fn) {\n return new Promise((resolve, reject) => {\n fn((err, ...args) => {\n if (err) {\n return reject(err)\n }\n return resolve(...args)\n })\n })\n },\n debuglog() {\n return function () {}\n },\n format(format, ...args) {\n // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args\n return format.replace(/%([sdifj])/g, function (...[_unused, type]) {\n const replacement = args.shift()\n if (type === 'f') {\n return replacement.toFixed(6)\n } else if (type === 'j') {\n return JSON.stringify(replacement)\n } else if (type === 's' && typeof replacement === 'object') {\n const ctor = replacement.constructor !== Object ? replacement.constructor.name : ''\n return `${ctor} {}`.trim()\n } else {\n return replacement.toString()\n }\n })\n },\n inspect(value) {\n // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options\n switch (typeof value) {\n case 'string':\n if (value.includes(\"'\")) {\n if (!value.includes('\"')) {\n return `\"${value}\"`\n } else if (!value.includes('`') && !value.includes('${')) {\n return `\\`${value}\\``\n }\n }\n return `'${value}'`\n case 'number':\n if (isNaN(value)) {\n return 'NaN'\n } else if (Object.is(value, -0)) {\n return String(value)\n }\n return value\n case 'bigint':\n return `${String(value)}n`\n case 'boolean':\n case 'undefined':\n return String(value)\n case 'object':\n return '{}'\n }\n },\n types: {\n isAsyncFunction(fn) {\n return fn instanceof AsyncFunction\n },\n isArrayBufferView(arr) {\n return ArrayBuffer.isView(arr)\n }\n },\n isBlob,\n deprecate(fn, message) {\n return fn\n },\n addAbortListener:\n require('events').addAbortListener ||\n function addAbortListener(signal, listener) {\n if (signal === undefined) {\n throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal)\n }\n validateAbortSignal(signal, 'signal')\n validateFunction(listener, 'listener')\n let removeEventListener\n if (signal.aborted) {\n queueMicrotask(() => listener())\n } else {\n signal.addEventListener('abort', listener, {\n __proto__: null,\n once: true,\n [kResistStopPropagation]: true\n })\n removeEventListener = () => {\n signal.removeEventListener('abort', listener)\n }\n }\n return {\n __proto__: null,\n [SymbolDispose]() {\n var _removeEventListener\n ;(_removeEventListener = removeEventListener) === null || _removeEventListener === undefined\n ? undefined\n : _removeEventListener()\n }\n }\n },\n AbortSignalAny:\n AbortSignal.any ||\n function AbortSignalAny(signals) {\n // Fast path if there is only one signal.\n if (signals.length === 1) {\n return signals[0]\n }\n const ac = new AbortController()\n const abort = () => ac.abort()\n signals.forEach((signal) => {\n validateAbortSignal(signal, 'signals')\n signal.addEventListener('abort', abort, {\n once: true\n })\n })\n ac.signal.addEventListener(\n 'abort',\n () => {\n signals.forEach((signal) => signal.removeEventListener('abort', abort))\n },\n {\n once: true\n }\n )\n return ac.signal\n }\n}\nmodule.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom')\n","/* replacement start */\n\nconst { Buffer } = require('buffer')\n\n/* replacement end */\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n;('use strict')\nconst { ObjectDefineProperty, ObjectKeys, ReflectApply } = require('./ours/primordials')\nconst {\n promisify: { custom: customPromisify }\n} = require('./ours/util')\nconst { streamReturningOperators, promiseReturningOperators } = require('./internal/streams/operators')\nconst {\n codes: { ERR_ILLEGAL_CONSTRUCTOR }\n} = require('./ours/errors')\nconst compose = require('./internal/streams/compose')\nconst { setDefaultHighWaterMark, getDefaultHighWaterMark } = require('./internal/streams/state')\nconst { pipeline } = require('./internal/streams/pipeline')\nconst { destroyer } = require('./internal/streams/destroy')\nconst eos = require('./internal/streams/end-of-stream')\nconst internalBuffer = {}\nconst promises = require('./stream/promises')\nconst utils = require('./internal/streams/utils')\nconst Stream = (module.exports = require('./internal/streams/legacy').Stream)\nStream.isDestroyed = utils.isDestroyed\nStream.isDisturbed = utils.isDisturbed\nStream.isErrored = utils.isErrored\nStream.isReadable = utils.isReadable\nStream.isWritable = utils.isWritable\nStream.Readable = require('./internal/streams/readable')\nfor (const key of ObjectKeys(streamReturningOperators)) {\n const op = streamReturningOperators[key]\n function fn(...args) {\n if (new.target) {\n throw ERR_ILLEGAL_CONSTRUCTOR()\n }\n return Stream.Readable.from(ReflectApply(op, this, args))\n }\n ObjectDefineProperty(fn, 'name', {\n __proto__: null,\n value: op.name\n })\n ObjectDefineProperty(fn, 'length', {\n __proto__: null,\n value: op.length\n })\n ObjectDefineProperty(Stream.Readable.prototype, key, {\n __proto__: null,\n value: fn,\n enumerable: false,\n configurable: true,\n writable: true\n })\n}\nfor (const key of ObjectKeys(promiseReturningOperators)) {\n const op = promiseReturningOperators[key]\n function fn(...args) {\n if (new.target) {\n throw ERR_ILLEGAL_CONSTRUCTOR()\n }\n return ReflectApply(op, this, args)\n }\n ObjectDefineProperty(fn, 'name', {\n __proto__: null,\n value: op.name\n })\n ObjectDefineProperty(fn, 'length', {\n __proto__: null,\n value: op.length\n })\n ObjectDefineProperty(Stream.Readable.prototype, key, {\n __proto__: null,\n value: fn,\n enumerable: false,\n configurable: true,\n writable: true\n })\n}\nStream.Writable = require('./internal/streams/writable')\nStream.Duplex = require('./internal/streams/duplex')\nStream.Transform = require('./internal/streams/transform')\nStream.PassThrough = require('./internal/streams/passthrough')\nStream.pipeline = pipeline\nconst { addAbortSignal } = require('./internal/streams/add-abort-signal')\nStream.addAbortSignal = addAbortSignal\nStream.finished = eos\nStream.destroy = destroyer\nStream.compose = compose\nStream.setDefaultHighWaterMark = setDefaultHighWaterMark\nStream.getDefaultHighWaterMark = getDefaultHighWaterMark\nObjectDefineProperty(Stream, 'promises', {\n __proto__: null,\n configurable: true,\n enumerable: true,\n get() {\n return promises\n }\n})\nObjectDefineProperty(pipeline, customPromisify, {\n __proto__: null,\n enumerable: true,\n get() {\n return promises.pipeline\n }\n})\nObjectDefineProperty(eos, customPromisify, {\n __proto__: null,\n enumerable: true,\n get() {\n return promises.finished\n }\n})\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream\nStream._isUint8Array = function isUint8Array(value) {\n return value instanceof Uint8Array\n}\nStream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n}\n","'use strict'\n\nconst { ArrayPrototypePop, Promise } = require('../ours/primordials')\nconst { isIterable, isNodeStream, isWebStream } = require('../internal/streams/utils')\nconst { pipelineImpl: pl } = require('../internal/streams/pipeline')\nconst { finished } = require('../internal/streams/end-of-stream')\nrequire('../../lib/stream.js')\nfunction pipeline(...streams) {\n return new Promise((resolve, reject) => {\n let signal\n let end\n const lastArg = streams[streams.length - 1]\n if (\n lastArg &&\n typeof lastArg === 'object' &&\n !isNodeStream(lastArg) &&\n !isIterable(lastArg) &&\n !isWebStream(lastArg)\n ) {\n const options = ArrayPrototypePop(streams)\n signal = options.signal\n end = options.end\n }\n pl(\n streams,\n (err, value) => {\n if (err) {\n reject(err)\n } else {\n resolve(value)\n }\n },\n {\n signal,\n end\n }\n )\n })\n}\nmodule.exports = {\n finished,\n pipeline\n}\n","/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","'use strict'\n\nconst { SymbolDispose } = require('../../ours/primordials')\nconst { AbortError, codes } = require('../../ours/errors')\nconst { isNodeStream, isWebStream, kControllerErrorFunction } = require('./utils')\nconst eos = require('./end-of-stream')\nconst { ERR_INVALID_ARG_TYPE } = codes\nlet addAbortListener\n\n// This method is inlined here for readable-stream\n// It also does not allow for signal to not exist on the stream\n// https://github.com/nodejs/node/pull/36061#discussion_r533718029\nconst validateAbortSignal = (signal, name) => {\n if (typeof signal !== 'object' || !('aborted' in signal)) {\n throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n }\n}\nmodule.exports.addAbortSignal = function addAbortSignal(signal, stream) {\n validateAbortSignal(signal, 'signal')\n if (!isNodeStream(stream) && !isWebStream(stream)) {\n throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream)\n }\n return module.exports.addAbortSignalNoValidate(signal, stream)\n}\nmodule.exports.addAbortSignalNoValidate = function (signal, stream) {\n if (typeof signal !== 'object' || !('aborted' in signal)) {\n return stream\n }\n const onAbort = isNodeStream(stream)\n ? () => {\n stream.destroy(\n new AbortError(undefined, {\n cause: signal.reason\n })\n )\n }\n : () => {\n stream[kControllerErrorFunction](\n new AbortError(undefined, {\n cause: signal.reason\n })\n )\n }\n if (signal.aborted) {\n onAbort()\n } else {\n addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n const disposable = addAbortListener(signal, onAbort)\n eos(stream, disposable[SymbolDispose])\n }\n return stream\n}\n","'use strict'\n\nconst { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = require('../../ours/primordials')\nconst { Buffer } = require('buffer')\nconst { inspect } = require('../../ours/util')\nmodule.exports = class BufferList {\n constructor() {\n this.head = null\n this.tail = null\n this.length = 0\n }\n push(v) {\n const entry = {\n data: v,\n next: null\n }\n if (this.length > 0) this.tail.next = entry\n else this.head = entry\n this.tail = entry\n ++this.length\n }\n unshift(v) {\n const entry = {\n data: v,\n next: this.head\n }\n if (this.length === 0) this.tail = entry\n this.head = entry\n ++this.length\n }\n shift() {\n if (this.length === 0) return\n const ret = this.head.data\n if (this.length === 1) this.head = this.tail = null\n else this.head = this.head.next\n --this.length\n return ret\n }\n clear() {\n this.head = this.tail = null\n this.length = 0\n }\n join(s) {\n if (this.length === 0) return ''\n let p = this.head\n let ret = '' + p.data\n while ((p = p.next) !== null) ret += s + p.data\n return ret\n }\n concat(n) {\n if (this.length === 0) return Buffer.alloc(0)\n const ret = Buffer.allocUnsafe(n >>> 0)\n let p = this.head\n let i = 0\n while (p) {\n TypedArrayPrototypeSet(ret, p.data, i)\n i += p.data.length\n p = p.next\n }\n return ret\n }\n\n // Consumes a specified amount of bytes or characters from the buffered data.\n consume(n, hasStrings) {\n const data = this.head.data\n if (n < data.length) {\n // `slice` is the same for buffers and strings.\n const slice = data.slice(0, n)\n this.head.data = data.slice(n)\n return slice\n }\n if (n === data.length) {\n // First chunk is a perfect match.\n return this.shift()\n }\n // Result spans more than one buffer.\n return hasStrings ? this._getString(n) : this._getBuffer(n)\n }\n first() {\n return this.head.data\n }\n *[SymbolIterator]() {\n for (let p = this.head; p; p = p.next) {\n yield p.data\n }\n }\n\n // Consumes a specified amount of characters from the buffered data.\n _getString(n) {\n let ret = ''\n let p = this.head\n let c = 0\n do {\n const str = p.data\n if (n > str.length) {\n ret += str\n n -= str.length\n } else {\n if (n === str.length) {\n ret += str\n ++c\n if (p.next) this.head = p.next\n else this.head = this.tail = null\n } else {\n ret += StringPrototypeSlice(str, 0, n)\n this.head = p\n p.data = StringPrototypeSlice(str, n)\n }\n break\n }\n ++c\n } while ((p = p.next) !== null)\n this.length -= c\n return ret\n }\n\n // Consumes a specified amount of bytes from the buffered data.\n _getBuffer(n) {\n const ret = Buffer.allocUnsafe(n)\n const retLen = n\n let p = this.head\n let c = 0\n do {\n const buf = p.data\n if (n > buf.length) {\n TypedArrayPrototypeSet(ret, buf, retLen - n)\n n -= buf.length\n } else {\n if (n === buf.length) {\n TypedArrayPrototypeSet(ret, buf, retLen - n)\n ++c\n if (p.next) this.head = p.next\n else this.head = this.tail = null\n } else {\n TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n)\n this.head = p\n p.data = buf.slice(n)\n }\n break\n }\n ++c\n } while ((p = p.next) !== null)\n this.length -= c\n return ret\n }\n\n // Make sure the linked list only shows the minimal necessary information.\n [Symbol.for('nodejs.util.inspect.custom')](_, options) {\n return inspect(this, {\n ...options,\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n })\n }\n}\n","'use strict'\n\nconst { pipeline } = require('./pipeline')\nconst Duplex = require('./duplex')\nconst { destroyer } = require('./destroy')\nconst {\n isNodeStream,\n isReadable,\n isWritable,\n isWebStream,\n isTransformStream,\n isWritableStream,\n isReadableStream\n} = require('./utils')\nconst {\n AbortError,\n codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS }\n} = require('../../ours/errors')\nconst eos = require('./end-of-stream')\nmodule.exports = function compose(...streams) {\n if (streams.length === 0) {\n throw new ERR_MISSING_ARGS('streams')\n }\n if (streams.length === 1) {\n return Duplex.from(streams[0])\n }\n const orgStreams = [...streams]\n if (typeof streams[0] === 'function') {\n streams[0] = Duplex.from(streams[0])\n }\n if (typeof streams[streams.length - 1] === 'function') {\n const idx = streams.length - 1\n streams[idx] = Duplex.from(streams[idx])\n }\n for (let n = 0; n < streams.length; ++n) {\n if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) {\n // TODO(ronag): Add checks for non streams.\n continue\n }\n if (\n n < streams.length - 1 &&\n !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n]))\n ) {\n throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable')\n }\n if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) {\n throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable')\n }\n }\n let ondrain\n let onfinish\n let onreadable\n let onclose\n let d\n function onfinished(err) {\n const cb = onclose\n onclose = null\n if (cb) {\n cb(err)\n } else if (err) {\n d.destroy(err)\n } else if (!readable && !writable) {\n d.destroy()\n }\n }\n const head = streams[0]\n const tail = pipeline(streams, onfinished)\n const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head))\n const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail))\n\n // TODO(ronag): Avoid double buffering.\n // Implement Writable/Readable/Duplex traits.\n // See, https://github.com/nodejs/node/pull/33515.\n d = new Duplex({\n // TODO (ronag): highWaterMark?\n writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode),\n readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode),\n writable,\n readable\n })\n if (writable) {\n if (isNodeStream(head)) {\n d._write = function (chunk, encoding, callback) {\n if (head.write(chunk, encoding)) {\n callback()\n } else {\n ondrain = callback\n }\n }\n d._final = function (callback) {\n head.end()\n onfinish = callback\n }\n head.on('drain', function () {\n if (ondrain) {\n const cb = ondrain\n ondrain = null\n cb()\n }\n })\n } else if (isWebStream(head)) {\n const writable = isTransformStream(head) ? head.writable : head\n const writer = writable.getWriter()\n d._write = async function (chunk, encoding, callback) {\n try {\n await writer.ready\n writer.write(chunk).catch(() => {})\n callback()\n } catch (err) {\n callback(err)\n }\n }\n d._final = async function (callback) {\n try {\n await writer.ready\n writer.close().catch(() => {})\n onfinish = callback\n } catch (err) {\n callback(err)\n }\n }\n }\n const toRead = isTransformStream(tail) ? tail.readable : tail\n eos(toRead, () => {\n if (onfinish) {\n const cb = onfinish\n onfinish = null\n cb()\n }\n })\n }\n if (readable) {\n if (isNodeStream(tail)) {\n tail.on('readable', function () {\n if (onreadable) {\n const cb = onreadable\n onreadable = null\n cb()\n }\n })\n tail.on('end', function () {\n d.push(null)\n })\n d._read = function () {\n while (true) {\n const buf = tail.read()\n if (buf === null) {\n onreadable = d._read\n return\n }\n if (!d.push(buf)) {\n return\n }\n }\n }\n } else if (isWebStream(tail)) {\n const readable = isTransformStream(tail) ? tail.readable : tail\n const reader = readable.getReader()\n d._read = async function () {\n while (true) {\n try {\n const { value, done } = await reader.read()\n if (!d.push(value)) {\n return\n }\n if (done) {\n d.push(null)\n return\n }\n } catch {\n return\n }\n }\n }\n }\n }\n d._destroy = function (err, callback) {\n if (!err && onclose !== null) {\n err = new AbortError()\n }\n onreadable = null\n ondrain = null\n onfinish = null\n if (onclose === null) {\n callback(err)\n } else {\n onclose = callback\n if (isNodeStream(tail)) {\n destroyer(tail, err)\n }\n }\n }\n return d\n}\n","'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n aggregateTwoErrors,\n codes: { ERR_MULTIPLE_CALLBACK },\n AbortError\n} = require('../../ours/errors')\nconst { Symbol } = require('../../ours/primordials')\nconst { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require('./utils')\nconst kDestroy = Symbol('kDestroy')\nconst kConstruct = Symbol('kConstruct')\nfunction checkError(err, w, r) {\n if (err) {\n // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n err.stack // eslint-disable-line no-unused-expressions\n\n if (w && !w.errored) {\n w.errored = err\n }\n if (r && !r.errored) {\n r.errored = err\n }\n }\n}\n\n// Backwards compat. cb() is undocumented and unused in core but\n// unfortunately might be used by modules.\nfunction destroy(err, cb) {\n const r = this._readableState\n const w = this._writableState\n // With duplex streams we use the writable side for state.\n const s = w || r\n if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) {\n if (typeof cb === 'function') {\n cb()\n }\n return this\n }\n\n // We set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n checkError(err, w, r)\n if (w) {\n w.destroyed = true\n }\n if (r) {\n r.destroyed = true\n }\n\n // If still constructing then defer calling _destroy.\n if (!s.constructed) {\n this.once(kDestroy, function (er) {\n _destroy(this, aggregateTwoErrors(er, err), cb)\n })\n } else {\n _destroy(this, err, cb)\n }\n return this\n}\nfunction _destroy(self, err, cb) {\n let called = false\n function onDestroy(err) {\n if (called) {\n return\n }\n called = true\n const r = self._readableState\n const w = self._writableState\n checkError(err, w, r)\n if (w) {\n w.closed = true\n }\n if (r) {\n r.closed = true\n }\n if (typeof cb === 'function') {\n cb(err)\n }\n if (err) {\n process.nextTick(emitErrorCloseNT, self, err)\n } else {\n process.nextTick(emitCloseNT, self)\n }\n }\n try {\n self._destroy(err || null, onDestroy)\n } catch (err) {\n onDestroy(err)\n }\n}\nfunction emitErrorCloseNT(self, err) {\n emitErrorNT(self, err)\n emitCloseNT(self)\n}\nfunction emitCloseNT(self) {\n const r = self._readableState\n const w = self._writableState\n if (w) {\n w.closeEmitted = true\n }\n if (r) {\n r.closeEmitted = true\n }\n if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) {\n self.emit('close')\n }\n}\nfunction emitErrorNT(self, err) {\n const r = self._readableState\n const w = self._writableState\n if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) {\n return\n }\n if (w) {\n w.errorEmitted = true\n }\n if (r) {\n r.errorEmitted = true\n }\n self.emit('error', err)\n}\nfunction undestroy() {\n const r = this._readableState\n const w = this._writableState\n if (r) {\n r.constructed = true\n r.closed = false\n r.closeEmitted = false\n r.destroyed = false\n r.errored = null\n r.errorEmitted = false\n r.reading = false\n r.ended = r.readable === false\n r.endEmitted = r.readable === false\n }\n if (w) {\n w.constructed = true\n w.destroyed = false\n w.closed = false\n w.closeEmitted = false\n w.errored = null\n w.errorEmitted = false\n w.finalCalled = false\n w.prefinished = false\n w.ended = w.writable === false\n w.ending = w.writable === false\n w.finished = w.writable === false\n }\n}\nfunction errorOrDestroy(stream, err, sync) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n\n const r = stream._readableState\n const w = stream._writableState\n if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) {\n return this\n }\n if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy))\n stream.destroy(err)\n else if (err) {\n // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n err.stack // eslint-disable-line no-unused-expressions\n\n if (w && !w.errored) {\n w.errored = err\n }\n if (r && !r.errored) {\n r.errored = err\n }\n if (sync) {\n process.nextTick(emitErrorNT, stream, err)\n } else {\n emitErrorNT(stream, err)\n }\n }\n}\nfunction construct(stream, cb) {\n if (typeof stream._construct !== 'function') {\n return\n }\n const r = stream._readableState\n const w = stream._writableState\n if (r) {\n r.constructed = false\n }\n if (w) {\n w.constructed = false\n }\n stream.once(kConstruct, cb)\n if (stream.listenerCount(kConstruct) > 1) {\n // Duplex\n return\n }\n process.nextTick(constructNT, stream)\n}\nfunction constructNT(stream) {\n let called = false\n function onConstruct(err) {\n if (called) {\n errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK())\n return\n }\n called = true\n const r = stream._readableState\n const w = stream._writableState\n const s = w || r\n if (r) {\n r.constructed = true\n }\n if (w) {\n w.constructed = true\n }\n if (s.destroyed) {\n stream.emit(kDestroy, err)\n } else if (err) {\n errorOrDestroy(stream, err, true)\n } else {\n process.nextTick(emitConstructNT, stream)\n }\n }\n try {\n stream._construct((err) => {\n process.nextTick(onConstruct, err)\n })\n } catch (err) {\n process.nextTick(onConstruct, err)\n }\n}\nfunction emitConstructNT(stream) {\n stream.emit(kConstruct)\n}\nfunction isRequest(stream) {\n return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function'\n}\nfunction emitCloseLegacy(stream) {\n stream.emit('close')\n}\nfunction emitErrorCloseLegacy(stream, err) {\n stream.emit('error', err)\n process.nextTick(emitCloseLegacy, stream)\n}\n\n// Normalize destroy for legacy.\nfunction destroyer(stream, err) {\n if (!stream || isDestroyed(stream)) {\n return\n }\n if (!err && !isFinished(stream)) {\n err = new AbortError()\n }\n\n // TODO: Remove isRequest branches.\n if (isServerRequest(stream)) {\n stream.socket = null\n stream.destroy(err)\n } else if (isRequest(stream)) {\n stream.abort()\n } else if (isRequest(stream.req)) {\n stream.req.abort()\n } else if (typeof stream.destroy === 'function') {\n stream.destroy(err)\n } else if (typeof stream.close === 'function') {\n // TODO: Don't lose err?\n stream.close()\n } else if (err) {\n process.nextTick(emitErrorCloseLegacy, stream, err)\n } else {\n process.nextTick(emitCloseLegacy, stream)\n }\n if (!stream.destroyed) {\n stream[kIsDestroyed] = true\n }\n}\nmodule.exports = {\n construct,\n destroyer,\n destroy,\n undestroy,\n errorOrDestroy\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototype inheritance, this class\n// prototypically inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict'\n\nconst {\n ObjectDefineProperties,\n ObjectGetOwnPropertyDescriptor,\n ObjectKeys,\n ObjectSetPrototypeOf\n} = require('../../ours/primordials')\nmodule.exports = Duplex\nconst Readable = require('./readable')\nconst Writable = require('./writable')\nObjectSetPrototypeOf(Duplex.prototype, Readable.prototype)\nObjectSetPrototypeOf(Duplex, Readable)\n{\n const keys = ObjectKeys(Writable.prototype)\n // Allow the keys array to be GC'ed.\n for (let i = 0; i < keys.length; i++) {\n const method = keys[i]\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]\n }\n}\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options)\n Readable.call(this, options)\n Writable.call(this, options)\n if (options) {\n this.allowHalfOpen = options.allowHalfOpen !== false\n if (options.readable === false) {\n this._readableState.readable = false\n this._readableState.ended = true\n this._readableState.endEmitted = true\n }\n if (options.writable === false) {\n this._writableState.writable = false\n this._writableState.ending = true\n this._writableState.ended = true\n this._writableState.finished = true\n }\n } else {\n this.allowHalfOpen = true\n }\n}\nObjectDefineProperties(Duplex.prototype, {\n writable: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable')\n },\n writableHighWaterMark: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark')\n },\n writableObjectMode: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode')\n },\n writableBuffer: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer')\n },\n writableLength: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength')\n },\n writableFinished: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished')\n },\n writableCorked: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked')\n },\n writableEnded: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded')\n },\n writableNeedDrain: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain')\n },\n destroyed: {\n __proto__: null,\n get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false\n }\n return this._readableState.destroyed && this._writableState.destroyed\n },\n set(value) {\n // Backward compatibility, the user is explicitly\n // managing destroyed.\n if (this._readableState && this._writableState) {\n this._readableState.destroyed = value\n this._writableState.destroyed = value\n }\n }\n }\n})\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n return webStreamsAdapters\n}\nDuplex.fromWeb = function (pair, options) {\n return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options)\n}\nDuplex.toWeb = function (duplex) {\n return lazyWebStreams().newReadableWritablePairFromDuplex(duplex)\n}\nlet duplexify\nDuplex.from = function (body) {\n if (!duplexify) {\n duplexify = require('./duplexify')\n }\n return duplexify(body, 'body')\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\n;('use strict')\nconst bufferModule = require('buffer')\nconst {\n isReadable,\n isWritable,\n isIterable,\n isNodeStream,\n isReadableNodeStream,\n isWritableNodeStream,\n isDuplexNodeStream,\n isReadableStream,\n isWritableStream\n} = require('./utils')\nconst eos = require('./end-of-stream')\nconst {\n AbortError,\n codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE }\n} = require('../../ours/errors')\nconst { destroyer } = require('./destroy')\nconst Duplex = require('./duplex')\nconst Readable = require('./readable')\nconst Writable = require('./writable')\nconst { createDeferredPromise } = require('../../ours/util')\nconst from = require('./from')\nconst Blob = globalThis.Blob || bufferModule.Blob\nconst isBlob =\n typeof Blob !== 'undefined'\n ? function isBlob(b) {\n return b instanceof Blob\n }\n : function isBlob(b) {\n return false\n }\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst { FunctionPrototypeCall } = require('../../ours/primordials')\n\n// This is needed for pre node 17.\nclass Duplexify extends Duplex {\n constructor(options) {\n super(options)\n\n // https://github.com/nodejs/node/pull/34385\n\n if ((options === null || options === undefined ? undefined : options.readable) === false) {\n this._readableState.readable = false\n this._readableState.ended = true\n this._readableState.endEmitted = true\n }\n if ((options === null || options === undefined ? undefined : options.writable) === false) {\n this._writableState.writable = false\n this._writableState.ending = true\n this._writableState.ended = true\n this._writableState.finished = true\n }\n }\n}\nmodule.exports = function duplexify(body, name) {\n if (isDuplexNodeStream(body)) {\n return body\n }\n if (isReadableNodeStream(body)) {\n return _duplexify({\n readable: body\n })\n }\n if (isWritableNodeStream(body)) {\n return _duplexify({\n writable: body\n })\n }\n if (isNodeStream(body)) {\n return _duplexify({\n writable: false,\n readable: false\n })\n }\n if (isReadableStream(body)) {\n return _duplexify({\n readable: Readable.fromWeb(body)\n })\n }\n if (isWritableStream(body)) {\n return _duplexify({\n writable: Writable.fromWeb(body)\n })\n }\n if (typeof body === 'function') {\n const { value, write, final, destroy } = fromAsyncGen(body)\n if (isIterable(value)) {\n return from(Duplexify, value, {\n // TODO (ronag): highWaterMark?\n objectMode: true,\n write,\n final,\n destroy\n })\n }\n const then = value === null || value === undefined ? undefined : value.then\n if (typeof then === 'function') {\n let d\n const promise = FunctionPrototypeCall(\n then,\n value,\n (val) => {\n if (val != null) {\n throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val)\n }\n },\n (err) => {\n destroyer(d, err)\n }\n )\n return (d = new Duplexify({\n // TODO (ronag): highWaterMark?\n objectMode: true,\n readable: false,\n write,\n final(cb) {\n final(async () => {\n try {\n await promise\n process.nextTick(cb, null)\n } catch (err) {\n process.nextTick(cb, err)\n }\n })\n },\n destroy\n }))\n }\n throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value)\n }\n if (isBlob(body)) {\n return duplexify(body.arrayBuffer())\n }\n if (isIterable(body)) {\n return from(Duplexify, body, {\n // TODO (ronag): highWaterMark?\n objectMode: true,\n writable: false\n })\n }\n if (\n isReadableStream(body === null || body === undefined ? undefined : body.readable) &&\n isWritableStream(body === null || body === undefined ? undefined : body.writable)\n ) {\n return Duplexify.fromWeb(body)\n }\n if (\n typeof (body === null || body === undefined ? undefined : body.writable) === 'object' ||\n typeof (body === null || body === undefined ? undefined : body.readable) === 'object'\n ) {\n const readable =\n body !== null && body !== undefined && body.readable\n ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable)\n ? body === null || body === undefined\n ? undefined\n : body.readable\n : duplexify(body.readable)\n : undefined\n const writable =\n body !== null && body !== undefined && body.writable\n ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable)\n ? body === null || body === undefined\n ? undefined\n : body.writable\n : duplexify(body.writable)\n : undefined\n return _duplexify({\n readable,\n writable\n })\n }\n const then = body === null || body === undefined ? undefined : body.then\n if (typeof then === 'function') {\n let d\n FunctionPrototypeCall(\n then,\n body,\n (val) => {\n if (val != null) {\n d.push(val)\n }\n d.push(null)\n },\n (err) => {\n destroyer(d, err)\n }\n )\n return (d = new Duplexify({\n objectMode: true,\n writable: false,\n read() {}\n }))\n }\n throw new ERR_INVALID_ARG_TYPE(\n name,\n [\n 'Blob',\n 'ReadableStream',\n 'WritableStream',\n 'Stream',\n 'Iterable',\n 'AsyncIterable',\n 'Function',\n '{ readable, writable } pair',\n 'Promise'\n ],\n body\n )\n}\nfunction fromAsyncGen(fn) {\n let { promise, resolve } = createDeferredPromise()\n const ac = new AbortController()\n const signal = ac.signal\n const value = fn(\n (async function* () {\n while (true) {\n const _promise = promise\n promise = null\n const { chunk, done, cb } = await _promise\n process.nextTick(cb)\n if (done) return\n if (signal.aborted)\n throw new AbortError(undefined, {\n cause: signal.reason\n })\n ;({ promise, resolve } = createDeferredPromise())\n yield chunk\n }\n })(),\n {\n signal\n }\n )\n return {\n value,\n write(chunk, encoding, cb) {\n const _resolve = resolve\n resolve = null\n _resolve({\n chunk,\n done: false,\n cb\n })\n },\n final(cb) {\n const _resolve = resolve\n resolve = null\n _resolve({\n done: true,\n cb\n })\n },\n destroy(err, cb) {\n ac.abort()\n cb(err)\n }\n }\n}\nfunction _duplexify(pair) {\n const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable\n const w = pair.writable\n let readable = !!isReadable(r)\n let writable = !!isWritable(w)\n let ondrain\n let onfinish\n let onreadable\n let onclose\n let d\n function onfinished(err) {\n const cb = onclose\n onclose = null\n if (cb) {\n cb(err)\n } else if (err) {\n d.destroy(err)\n }\n }\n\n // TODO(ronag): Avoid double buffering.\n // Implement Writable/Readable/Duplex traits.\n // See, https://github.com/nodejs/node/pull/33515.\n d = new Duplexify({\n // TODO (ronag): highWaterMark?\n readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode),\n writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode),\n readable,\n writable\n })\n if (writable) {\n eos(w, (err) => {\n writable = false\n if (err) {\n destroyer(r, err)\n }\n onfinished(err)\n })\n d._write = function (chunk, encoding, callback) {\n if (w.write(chunk, encoding)) {\n callback()\n } else {\n ondrain = callback\n }\n }\n d._final = function (callback) {\n w.end()\n onfinish = callback\n }\n w.on('drain', function () {\n if (ondrain) {\n const cb = ondrain\n ondrain = null\n cb()\n }\n })\n w.on('finish', function () {\n if (onfinish) {\n const cb = onfinish\n onfinish = null\n cb()\n }\n })\n }\n if (readable) {\n eos(r, (err) => {\n readable = false\n if (err) {\n destroyer(r, err)\n }\n onfinished(err)\n })\n r.on('readable', function () {\n if (onreadable) {\n const cb = onreadable\n onreadable = null\n cb()\n }\n })\n r.on('end', function () {\n d.push(null)\n })\n d._read = function () {\n while (true) {\n const buf = r.read()\n if (buf === null) {\n onreadable = d._read\n return\n }\n if (!d.push(buf)) {\n return\n }\n }\n }\n }\n d._destroy = function (err, callback) {\n if (!err && onclose !== null) {\n err = new AbortError()\n }\n onreadable = null\n ondrain = null\n onfinish = null\n if (onclose === null) {\n callback(err)\n } else {\n onclose = callback\n destroyer(w, err)\n destroyer(r, err)\n }\n }\n return d\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n\n;('use strict')\nconst { AbortError, codes } = require('../../ours/errors')\nconst { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes\nconst { kEmptyObject, once } = require('../../ours/util')\nconst { validateAbortSignal, validateFunction, validateObject, validateBoolean } = require('../validators')\nconst { Promise, PromisePrototypeThen, SymbolDispose } = require('../../ours/primordials')\nconst {\n isClosed,\n isReadable,\n isReadableNodeStream,\n isReadableStream,\n isReadableFinished,\n isReadableErrored,\n isWritable,\n isWritableNodeStream,\n isWritableStream,\n isWritableFinished,\n isWritableErrored,\n isNodeStream,\n willEmitClose: _willEmitClose,\n kIsClosedPromise\n} = require('./utils')\nlet addAbortListener\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function'\n}\nconst nop = () => {}\nfunction eos(stream, options, callback) {\n var _options$readable, _options$writable\n if (arguments.length === 2) {\n callback = options\n options = kEmptyObject\n } else if (options == null) {\n options = kEmptyObject\n } else {\n validateObject(options, 'options')\n }\n validateFunction(callback, 'callback')\n validateAbortSignal(options.signal, 'options.signal')\n callback = once(callback)\n if (isReadableStream(stream) || isWritableStream(stream)) {\n return eosWeb(stream, options, callback)\n }\n if (!isNodeStream(stream)) {\n throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream)\n }\n const readable =\n (_options$readable = options.readable) !== null && _options$readable !== undefined\n ? _options$readable\n : isReadableNodeStream(stream)\n const writable =\n (_options$writable = options.writable) !== null && _options$writable !== undefined\n ? _options$writable\n : isWritableNodeStream(stream)\n const wState = stream._writableState\n const rState = stream._readableState\n const onlegacyfinish = () => {\n if (!stream.writable) {\n onfinish()\n }\n }\n\n // TODO (ronag): Improve soft detection to include core modules and\n // common ecosystem modules that do properly emit 'close' but fail\n // this generic check.\n let willEmitClose =\n _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable\n let writableFinished = isWritableFinished(stream, false)\n const onfinish = () => {\n writableFinished = true\n // Stream should not be destroyed here. If it is that\n // means that user space is doing something differently and\n // we cannot trust willEmitClose.\n if (stream.destroyed) {\n willEmitClose = false\n }\n if (willEmitClose && (!stream.readable || readable)) {\n return\n }\n if (!readable || readableFinished) {\n callback.call(stream)\n }\n }\n let readableFinished = isReadableFinished(stream, false)\n const onend = () => {\n readableFinished = true\n // Stream should not be destroyed here. If it is that\n // means that user space is doing something differently and\n // we cannot trust willEmitClose.\n if (stream.destroyed) {\n willEmitClose = false\n }\n if (willEmitClose && (!stream.writable || writable)) {\n return\n }\n if (!writable || writableFinished) {\n callback.call(stream)\n }\n }\n const onerror = (err) => {\n callback.call(stream, err)\n }\n let closed = isClosed(stream)\n const onclose = () => {\n closed = true\n const errored = isWritableErrored(stream) || isReadableErrored(stream)\n if (errored && typeof errored !== 'boolean') {\n return callback.call(stream, errored)\n }\n if (readable && !readableFinished && isReadableNodeStream(stream, true)) {\n if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE())\n }\n if (writable && !writableFinished) {\n if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE())\n }\n callback.call(stream)\n }\n const onclosed = () => {\n closed = true\n const errored = isWritableErrored(stream) || isReadableErrored(stream)\n if (errored && typeof errored !== 'boolean') {\n return callback.call(stream, errored)\n }\n callback.call(stream)\n }\n const onrequest = () => {\n stream.req.on('finish', onfinish)\n }\n if (isRequest(stream)) {\n stream.on('complete', onfinish)\n if (!willEmitClose) {\n stream.on('abort', onclose)\n }\n if (stream.req) {\n onrequest()\n } else {\n stream.on('request', onrequest)\n }\n } else if (writable && !wState) {\n // legacy streams\n stream.on('end', onlegacyfinish)\n stream.on('close', onlegacyfinish)\n }\n\n // Not all streams will emit 'close' after 'aborted'.\n if (!willEmitClose && typeof stream.aborted === 'boolean') {\n stream.on('aborted', onclose)\n }\n stream.on('end', onend)\n stream.on('finish', onfinish)\n if (options.error !== false) {\n stream.on('error', onerror)\n }\n stream.on('close', onclose)\n if (closed) {\n process.nextTick(onclose)\n } else if (\n (wState !== null && wState !== undefined && wState.errorEmitted) ||\n (rState !== null && rState !== undefined && rState.errorEmitted)\n ) {\n if (!willEmitClose) {\n process.nextTick(onclosed)\n }\n } else if (\n !readable &&\n (!willEmitClose || isReadable(stream)) &&\n (writableFinished || isWritable(stream) === false)\n ) {\n process.nextTick(onclosed)\n } else if (\n !writable &&\n (!willEmitClose || isWritable(stream)) &&\n (readableFinished || isReadable(stream) === false)\n ) {\n process.nextTick(onclosed)\n } else if (rState && stream.req && stream.aborted) {\n process.nextTick(onclosed)\n }\n const cleanup = () => {\n callback = nop\n stream.removeListener('aborted', onclose)\n stream.removeListener('complete', onfinish)\n stream.removeListener('abort', onclose)\n stream.removeListener('request', onrequest)\n if (stream.req) stream.req.removeListener('finish', onfinish)\n stream.removeListener('end', onlegacyfinish)\n stream.removeListener('close', onlegacyfinish)\n stream.removeListener('finish', onfinish)\n stream.removeListener('end', onend)\n stream.removeListener('error', onerror)\n stream.removeListener('close', onclose)\n }\n if (options.signal && !closed) {\n const abort = () => {\n // Keep it because cleanup removes it.\n const endCallback = callback\n cleanup()\n endCallback.call(\n stream,\n new AbortError(undefined, {\n cause: options.signal.reason\n })\n )\n }\n if (options.signal.aborted) {\n process.nextTick(abort)\n } else {\n addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n const disposable = addAbortListener(options.signal, abort)\n const originalCallback = callback\n callback = once((...args) => {\n disposable[SymbolDispose]()\n originalCallback.apply(stream, args)\n })\n }\n }\n return cleanup\n}\nfunction eosWeb(stream, options, callback) {\n let isAborted = false\n let abort = nop\n if (options.signal) {\n abort = () => {\n isAborted = true\n callback.call(\n stream,\n new AbortError(undefined, {\n cause: options.signal.reason\n })\n )\n }\n if (options.signal.aborted) {\n process.nextTick(abort)\n } else {\n addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n const disposable = addAbortListener(options.signal, abort)\n const originalCallback = callback\n callback = once((...args) => {\n disposable[SymbolDispose]()\n originalCallback.apply(stream, args)\n })\n }\n }\n const resolverFn = (...args) => {\n if (!isAborted) {\n process.nextTick(() => callback.apply(stream, args))\n }\n }\n PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn)\n return nop\n}\nfunction finished(stream, opts) {\n var _opts\n let autoCleanup = false\n if (opts === null) {\n opts = kEmptyObject\n }\n if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) {\n validateBoolean(opts.cleanup, 'cleanup')\n autoCleanup = opts.cleanup\n }\n return new Promise((resolve, reject) => {\n const cleanup = eos(stream, opts, (err) => {\n if (autoCleanup) {\n cleanup()\n }\n if (err) {\n reject(err)\n } else {\n resolve()\n }\n })\n })\n}\nmodule.exports = eos\nmodule.exports.finished = finished\n","'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require('../../ours/primordials')\nconst { Buffer } = require('buffer')\nconst { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = require('../../ours/errors').codes\nfunction from(Readable, iterable, opts) {\n let iterator\n if (typeof iterable === 'string' || iterable instanceof Buffer) {\n return new Readable({\n objectMode: true,\n ...opts,\n read() {\n this.push(iterable)\n this.push(null)\n }\n })\n }\n let isAsync\n if (iterable && iterable[SymbolAsyncIterator]) {\n isAsync = true\n iterator = iterable[SymbolAsyncIterator]()\n } else if (iterable && iterable[SymbolIterator]) {\n isAsync = false\n iterator = iterable[SymbolIterator]()\n } else {\n throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable)\n }\n const readable = new Readable({\n objectMode: true,\n highWaterMark: 1,\n // TODO(ronag): What options should be allowed?\n ...opts\n })\n\n // Flag to protect against _read\n // being called before last iteration completion.\n let reading = false\n readable._read = function () {\n if (!reading) {\n reading = true\n next()\n }\n }\n readable._destroy = function (error, cb) {\n PromisePrototypeThen(\n close(error),\n () => process.nextTick(cb, error),\n // nextTick is here in case cb throws\n (e) => process.nextTick(cb, e || error)\n )\n }\n async function close(error) {\n const hadError = error !== undefined && error !== null\n const hasThrow = typeof iterator.throw === 'function'\n if (hadError && hasThrow) {\n const { value, done } = await iterator.throw(error)\n await value\n if (done) {\n return\n }\n }\n if (typeof iterator.return === 'function') {\n const { value } = await iterator.return()\n await value\n }\n }\n async function next() {\n for (;;) {\n try {\n const { value, done } = isAsync ? await iterator.next() : iterator.next()\n if (done) {\n readable.push(null)\n } else {\n const res = value && typeof value.then === 'function' ? await value : value\n if (res === null) {\n reading = false\n throw new ERR_STREAM_NULL_VALUES()\n } else if (readable.push(res)) {\n continue\n } else {\n reading = false\n }\n }\n } catch (err) {\n readable.destroy(err)\n }\n break\n }\n }\n return readable\n}\nmodule.exports = from\n","'use strict'\n\nconst { ArrayIsArray, ObjectSetPrototypeOf } = require('../../ours/primordials')\nconst { EventEmitter: EE } = require('events')\nfunction Stream(opts) {\n EE.call(this, opts)\n}\nObjectSetPrototypeOf(Stream.prototype, EE.prototype)\nObjectSetPrototypeOf(Stream, EE)\nStream.prototype.pipe = function (dest, options) {\n const source = this\n function ondata(chunk) {\n if (dest.writable && dest.write(chunk) === false && source.pause) {\n source.pause()\n }\n }\n source.on('data', ondata)\n function ondrain() {\n if (source.readable && source.resume) {\n source.resume()\n }\n }\n dest.on('drain', ondrain)\n\n // If the 'end' option is not supplied, dest.end() will be called when\n // source gets the 'end' or 'close' events. Only dest.end() once.\n if (!dest._isStdio && (!options || options.end !== false)) {\n source.on('end', onend)\n source.on('close', onclose)\n }\n let didOnEnd = false\n function onend() {\n if (didOnEnd) return\n didOnEnd = true\n dest.end()\n }\n function onclose() {\n if (didOnEnd) return\n didOnEnd = true\n if (typeof dest.destroy === 'function') dest.destroy()\n }\n\n // Don't leave dangling pipes when there are errors.\n function onerror(er) {\n cleanup()\n if (EE.listenerCount(this, 'error') === 0) {\n this.emit('error', er)\n }\n }\n prependListener(source, 'error', onerror)\n prependListener(dest, 'error', onerror)\n\n // Remove all the event listeners that were added.\n function cleanup() {\n source.removeListener('data', ondata)\n dest.removeListener('drain', ondrain)\n source.removeListener('end', onend)\n source.removeListener('close', onclose)\n source.removeListener('error', onerror)\n dest.removeListener('error', onerror)\n source.removeListener('end', cleanup)\n source.removeListener('close', cleanup)\n dest.removeListener('close', cleanup)\n }\n source.on('end', cleanup)\n source.on('close', cleanup)\n dest.on('close', cleanup)\n dest.emit('pipe', source)\n\n // Allow for unix-like usage: A.pipe(B).pipe(C)\n return dest\n}\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn)\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn)\n else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn)\n else emitter._events[event] = [fn, emitter._events[event]]\n}\nmodule.exports = {\n Stream,\n prependListener\n}\n","'use strict'\n\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst {\n codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE },\n AbortError\n} = require('../../ours/errors')\nconst { validateAbortSignal, validateInteger, validateObject } = require('../validators')\nconst kWeakHandler = require('../../ours/primordials').Symbol('kWeak')\nconst kResistStopPropagation = require('../../ours/primordials').Symbol('kResistStopPropagation')\nconst { finished } = require('./end-of-stream')\nconst staticCompose = require('./compose')\nconst { addAbortSignalNoValidate } = require('./add-abort-signal')\nconst { isWritable, isNodeStream } = require('./utils')\nconst { deprecate } = require('../../ours/util')\nconst {\n ArrayPrototypePush,\n Boolean,\n MathFloor,\n Number,\n NumberIsNaN,\n Promise,\n PromiseReject,\n PromiseResolve,\n PromisePrototypeThen,\n Symbol\n} = require('../../ours/primordials')\nconst kEmpty = Symbol('kEmpty')\nconst kEof = Symbol('kEof')\nfunction compose(stream, options) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n if (isNodeStream(stream) && !isWritable(stream)) {\n throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable')\n }\n const composedStream = staticCompose(this, stream)\n if (options !== null && options !== undefined && options.signal) {\n // Not validating as we already validated before\n addAbortSignalNoValidate(options.signal, composedStream)\n }\n return composedStream\n}\nfunction map(fn, options) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n }\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n let concurrency = 1\n if ((options === null || options === undefined ? undefined : options.concurrency) != null) {\n concurrency = MathFloor(options.concurrency)\n }\n let highWaterMark = concurrency - 1\n if ((options === null || options === undefined ? undefined : options.highWaterMark) != null) {\n highWaterMark = MathFloor(options.highWaterMark)\n }\n validateInteger(concurrency, 'options.concurrency', 1)\n validateInteger(highWaterMark, 'options.highWaterMark', 0)\n highWaterMark += concurrency\n return async function* map() {\n const signal = require('../../ours/util').AbortSignalAny(\n [options === null || options === undefined ? undefined : options.signal].filter(Boolean)\n )\n const stream = this\n const queue = []\n const signalOpt = {\n signal\n }\n let next\n let resume\n let done = false\n let cnt = 0\n function onCatch() {\n done = true\n afterItemProcessed()\n }\n function afterItemProcessed() {\n cnt -= 1\n maybeResume()\n }\n function maybeResume() {\n if (resume && !done && cnt < concurrency && queue.length < highWaterMark) {\n resume()\n resume = null\n }\n }\n async function pump() {\n try {\n for await (let val of stream) {\n if (done) {\n return\n }\n if (signal.aborted) {\n throw new AbortError()\n }\n try {\n val = fn(val, signalOpt)\n if (val === kEmpty) {\n continue\n }\n val = PromiseResolve(val)\n } catch (err) {\n val = PromiseReject(err)\n }\n cnt += 1\n PromisePrototypeThen(val, afterItemProcessed, onCatch)\n queue.push(val)\n if (next) {\n next()\n next = null\n }\n if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) {\n await new Promise((resolve) => {\n resume = resolve\n })\n }\n }\n queue.push(kEof)\n } catch (err) {\n const val = PromiseReject(err)\n PromisePrototypeThen(val, afterItemProcessed, onCatch)\n queue.push(val)\n } finally {\n done = true\n if (next) {\n next()\n next = null\n }\n }\n }\n pump()\n try {\n while (true) {\n while (queue.length > 0) {\n const val = await queue[0]\n if (val === kEof) {\n return\n }\n if (signal.aborted) {\n throw new AbortError()\n }\n if (val !== kEmpty) {\n yield val\n }\n queue.shift()\n maybeResume()\n }\n await new Promise((resolve) => {\n next = resolve\n })\n }\n } finally {\n done = true\n if (resume) {\n resume()\n resume = null\n }\n }\n }.call(this)\n}\nfunction asIndexedPairs(options = undefined) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n return async function* asIndexedPairs() {\n let index = 0\n for await (const val of this) {\n var _options$signal\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal = options.signal) !== null &&\n _options$signal !== undefined &&\n _options$signal.aborted\n ) {\n throw new AbortError({\n cause: options.signal.reason\n })\n }\n yield [index++, val]\n }\n }.call(this)\n}\nasync function some(fn, options = undefined) {\n for await (const unused of filter.call(this, fn, options)) {\n return true\n }\n return false\n}\nasync function every(fn, options = undefined) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n }\n // https://en.wikipedia.org/wiki/De_Morgan%27s_laws\n return !(await some.call(\n this,\n async (...args) => {\n return !(await fn(...args))\n },\n options\n ))\n}\nasync function find(fn, options) {\n for await (const result of filter.call(this, fn, options)) {\n return result\n }\n return undefined\n}\nasync function forEach(fn, options) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n }\n async function forEachFn(value, options) {\n await fn(value, options)\n return kEmpty\n }\n // eslint-disable-next-line no-unused-vars\n for await (const unused of map.call(this, forEachFn, options));\n}\nfunction filter(fn, options) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n }\n async function filterFn(value, options) {\n if (await fn(value, options)) {\n return value\n }\n return kEmpty\n }\n return map.call(this, filterFn, options)\n}\n\n// Specific to provide better error to reduce since the argument is only\n// missing if the stream has no items in it - but the code is still appropriate\nclass ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS {\n constructor() {\n super('reduce')\n this.message = 'Reduce of an empty stream requires an initial value'\n }\n}\nasync function reduce(reducer, initialValue, options) {\n var _options$signal2\n if (typeof reducer !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('reducer', ['Function', 'AsyncFunction'], reducer)\n }\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n let hasInitialValue = arguments.length > 1\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal2 = options.signal) !== null &&\n _options$signal2 !== undefined &&\n _options$signal2.aborted\n ) {\n const err = new AbortError(undefined, {\n cause: options.signal.reason\n })\n this.once('error', () => {}) // The error is already propagated\n await finished(this.destroy(err))\n throw err\n }\n const ac = new AbortController()\n const signal = ac.signal\n if (options !== null && options !== undefined && options.signal) {\n const opts = {\n once: true,\n [kWeakHandler]: this,\n [kResistStopPropagation]: true\n }\n options.signal.addEventListener('abort', () => ac.abort(), opts)\n }\n let gotAnyItemFromStream = false\n try {\n for await (const value of this) {\n var _options$signal3\n gotAnyItemFromStream = true\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal3 = options.signal) !== null &&\n _options$signal3 !== undefined &&\n _options$signal3.aborted\n ) {\n throw new AbortError()\n }\n if (!hasInitialValue) {\n initialValue = value\n hasInitialValue = true\n } else {\n initialValue = await reducer(initialValue, value, {\n signal\n })\n }\n }\n if (!gotAnyItemFromStream && !hasInitialValue) {\n throw new ReduceAwareErrMissingArgs()\n }\n } finally {\n ac.abort()\n }\n return initialValue\n}\nasync function toArray(options) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n const result = []\n for await (const val of this) {\n var _options$signal4\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal4 = options.signal) !== null &&\n _options$signal4 !== undefined &&\n _options$signal4.aborted\n ) {\n throw new AbortError(undefined, {\n cause: options.signal.reason\n })\n }\n ArrayPrototypePush(result, val)\n }\n return result\n}\nfunction flatMap(fn, options) {\n const values = map.call(this, fn, options)\n return async function* flatMap() {\n for await (const val of values) {\n yield* val\n }\n }.call(this)\n}\nfunction toIntegerOrInfinity(number) {\n // We coerce here to align with the spec\n // https://github.com/tc39/proposal-iterator-helpers/issues/169\n number = Number(number)\n if (NumberIsNaN(number)) {\n return 0\n }\n if (number < 0) {\n throw new ERR_OUT_OF_RANGE('number', '>= 0', number)\n }\n return number\n}\nfunction drop(number, options = undefined) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n number = toIntegerOrInfinity(number)\n return async function* drop() {\n var _options$signal5\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal5 = options.signal) !== null &&\n _options$signal5 !== undefined &&\n _options$signal5.aborted\n ) {\n throw new AbortError()\n }\n for await (const val of this) {\n var _options$signal6\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal6 = options.signal) !== null &&\n _options$signal6 !== undefined &&\n _options$signal6.aborted\n ) {\n throw new AbortError()\n }\n if (number-- <= 0) {\n yield val\n }\n }\n }.call(this)\n}\nfunction take(number, options = undefined) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n number = toIntegerOrInfinity(number)\n return async function* take() {\n var _options$signal7\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal7 = options.signal) !== null &&\n _options$signal7 !== undefined &&\n _options$signal7.aborted\n ) {\n throw new AbortError()\n }\n for await (const val of this) {\n var _options$signal8\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal8 = options.signal) !== null &&\n _options$signal8 !== undefined &&\n _options$signal8.aborted\n ) {\n throw new AbortError()\n }\n if (number-- > 0) {\n yield val\n }\n\n // Don't get another item from iterator in case we reached the end\n if (number <= 0) {\n return\n }\n }\n }.call(this)\n}\nmodule.exports.streamReturningOperators = {\n asIndexedPairs: deprecate(asIndexedPairs, 'readable.asIndexedPairs will be removed in a future version.'),\n drop,\n filter,\n flatMap,\n map,\n take,\n compose\n}\nmodule.exports.promiseReturningOperators = {\n every,\n forEach,\n reduce,\n toArray,\n some,\n find\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict'\n\nconst { ObjectSetPrototypeOf } = require('../../ours/primordials')\nmodule.exports = PassThrough\nconst Transform = require('./transform')\nObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype)\nObjectSetPrototypeOf(PassThrough, Transform)\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options)\n Transform.call(this, options)\n}\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk)\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n\n;('use strict')\nconst { ArrayIsArray, Promise, SymbolAsyncIterator, SymbolDispose } = require('../../ours/primordials')\nconst eos = require('./end-of-stream')\nconst { once } = require('../../ours/util')\nconst destroyImpl = require('./destroy')\nconst Duplex = require('./duplex')\nconst {\n aggregateTwoErrors,\n codes: {\n ERR_INVALID_ARG_TYPE,\n ERR_INVALID_RETURN_VALUE,\n ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED,\n ERR_STREAM_PREMATURE_CLOSE\n },\n AbortError\n} = require('../../ours/errors')\nconst { validateFunction, validateAbortSignal } = require('../validators')\nconst {\n isIterable,\n isReadable,\n isReadableNodeStream,\n isNodeStream,\n isTransformStream,\n isWebStream,\n isReadableStream,\n isReadableFinished\n} = require('./utils')\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nlet PassThrough\nlet Readable\nlet addAbortListener\nfunction destroyer(stream, reading, writing) {\n let finished = false\n stream.on('close', () => {\n finished = true\n })\n const cleanup = eos(\n stream,\n {\n readable: reading,\n writable: writing\n },\n (err) => {\n finished = !err\n }\n )\n return {\n destroy: (err) => {\n if (finished) return\n finished = true\n destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe'))\n },\n cleanup\n }\n}\nfunction popCallback(streams) {\n // Streams should never be an empty array. It should always contain at least\n // a single stream. Therefore optimize for the average case instead of\n // checking for length === 0 as well.\n validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]')\n return streams.pop()\n}\nfunction makeAsyncIterable(val) {\n if (isIterable(val)) {\n return val\n } else if (isReadableNodeStream(val)) {\n // Legacy streams are not Iterable.\n return fromReadable(val)\n }\n throw new ERR_INVALID_ARG_TYPE('val', ['Readable', 'Iterable', 'AsyncIterable'], val)\n}\nasync function* fromReadable(val) {\n if (!Readable) {\n Readable = require('./readable')\n }\n yield* Readable.prototype[SymbolAsyncIterator].call(val)\n}\nasync function pumpToNode(iterable, writable, finish, { end }) {\n let error\n let onresolve = null\n const resume = (err) => {\n if (err) {\n error = err\n }\n if (onresolve) {\n const callback = onresolve\n onresolve = null\n callback()\n }\n }\n const wait = () =>\n new Promise((resolve, reject) => {\n if (error) {\n reject(error)\n } else {\n onresolve = () => {\n if (error) {\n reject(error)\n } else {\n resolve()\n }\n }\n }\n })\n writable.on('drain', resume)\n const cleanup = eos(\n writable,\n {\n readable: false\n },\n resume\n )\n try {\n if (writable.writableNeedDrain) {\n await wait()\n }\n for await (const chunk of iterable) {\n if (!writable.write(chunk)) {\n await wait()\n }\n }\n if (end) {\n writable.end()\n await wait()\n }\n finish()\n } catch (err) {\n finish(error !== err ? aggregateTwoErrors(error, err) : err)\n } finally {\n cleanup()\n writable.off('drain', resume)\n }\n}\nasync function pumpToWeb(readable, writable, finish, { end }) {\n if (isTransformStream(writable)) {\n writable = writable.writable\n }\n // https://streams.spec.whatwg.org/#example-manual-write-with-backpressure\n const writer = writable.getWriter()\n try {\n for await (const chunk of readable) {\n await writer.ready\n writer.write(chunk).catch(() => {})\n }\n await writer.ready\n if (end) {\n await writer.close()\n }\n finish()\n } catch (err) {\n try {\n await writer.abort(err)\n finish(err)\n } catch (err) {\n finish(err)\n }\n }\n}\nfunction pipeline(...streams) {\n return pipelineImpl(streams, once(popCallback(streams)))\n}\nfunction pipelineImpl(streams, callback, opts) {\n if (streams.length === 1 && ArrayIsArray(streams[0])) {\n streams = streams[0]\n }\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams')\n }\n const ac = new AbortController()\n const signal = ac.signal\n const outerSignal = opts === null || opts === undefined ? undefined : opts.signal\n\n // Need to cleanup event listeners if last stream is readable\n // https://github.com/nodejs/node/issues/35452\n const lastStreamCleanup = []\n validateAbortSignal(outerSignal, 'options.signal')\n function abort() {\n finishImpl(new AbortError())\n }\n addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n let disposable\n if (outerSignal) {\n disposable = addAbortListener(outerSignal, abort)\n }\n let error\n let value\n const destroys = []\n let finishCount = 0\n function finish(err) {\n finishImpl(err, --finishCount === 0)\n }\n function finishImpl(err, final) {\n var _disposable\n if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) {\n error = err\n }\n if (!error && !final) {\n return\n }\n while (destroys.length) {\n destroys.shift()(error)\n }\n ;(_disposable = disposable) === null || _disposable === undefined ? undefined : _disposable[SymbolDispose]()\n ac.abort()\n if (final) {\n if (!error) {\n lastStreamCleanup.forEach((fn) => fn())\n }\n process.nextTick(callback, error, value)\n }\n }\n let ret\n for (let i = 0; i < streams.length; i++) {\n const stream = streams[i]\n const reading = i < streams.length - 1\n const writing = i > 0\n const end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false\n const isLastStream = i === streams.length - 1\n if (isNodeStream(stream)) {\n if (end) {\n const { destroy, cleanup } = destroyer(stream, reading, writing)\n destroys.push(destroy)\n if (isReadable(stream) && isLastStream) {\n lastStreamCleanup.push(cleanup)\n }\n }\n\n // Catch stream errors that occur after pipe/pump has completed.\n function onError(err) {\n if (err && err.name !== 'AbortError' && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n finish(err)\n }\n }\n stream.on('error', onError)\n if (isReadable(stream) && isLastStream) {\n lastStreamCleanup.push(() => {\n stream.removeListener('error', onError)\n })\n }\n }\n if (i === 0) {\n if (typeof stream === 'function') {\n ret = stream({\n signal\n })\n if (!isIterable(ret)) {\n throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or Stream', 'source', ret)\n }\n } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) {\n ret = stream\n } else {\n ret = Duplex.from(stream)\n }\n } else if (typeof stream === 'function') {\n if (isTransformStream(ret)) {\n var _ret\n ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable)\n } else {\n ret = makeAsyncIterable(ret)\n }\n ret = stream(ret, {\n signal\n })\n if (reading) {\n if (!isIterable(ret, true)) {\n throw new ERR_INVALID_RETURN_VALUE('AsyncIterable', `transform[${i - 1}]`, ret)\n }\n } else {\n var _ret2\n if (!PassThrough) {\n PassThrough = require('./passthrough')\n }\n\n // If the last argument to pipeline is not a stream\n // we must create a proxy stream so that pipeline(...)\n // always returns a stream which can be further\n // composed through `.pipe(stream)`.\n\n const pt = new PassThrough({\n objectMode: true\n })\n\n // Handle Promises/A+ spec, `then` could be a getter that throws on\n // second use.\n const then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then\n if (typeof then === 'function') {\n finishCount++\n then.call(\n ret,\n (val) => {\n value = val\n if (val != null) {\n pt.write(val)\n }\n if (end) {\n pt.end()\n }\n process.nextTick(finish)\n },\n (err) => {\n pt.destroy(err)\n process.nextTick(finish, err)\n }\n )\n } else if (isIterable(ret, true)) {\n finishCount++\n pumpToNode(ret, pt, finish, {\n end\n })\n } else if (isReadableStream(ret) || isTransformStream(ret)) {\n const toRead = ret.readable || ret\n finishCount++\n pumpToNode(toRead, pt, finish, {\n end\n })\n } else {\n throw new ERR_INVALID_RETURN_VALUE('AsyncIterable or Promise', 'destination', ret)\n }\n ret = pt\n const { destroy, cleanup } = destroyer(ret, false, true)\n destroys.push(destroy)\n if (isLastStream) {\n lastStreamCleanup.push(cleanup)\n }\n }\n } else if (isNodeStream(stream)) {\n if (isReadableNodeStream(ret)) {\n finishCount += 2\n const cleanup = pipe(ret, stream, finish, {\n end\n })\n if (isReadable(stream) && isLastStream) {\n lastStreamCleanup.push(cleanup)\n }\n } else if (isTransformStream(ret) || isReadableStream(ret)) {\n const toRead = ret.readable || ret\n finishCount++\n pumpToNode(toRead, stream, finish, {\n end\n })\n } else if (isIterable(ret)) {\n finishCount++\n pumpToNode(ret, stream, finish, {\n end\n })\n } else {\n throw new ERR_INVALID_ARG_TYPE(\n 'val',\n ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'],\n ret\n )\n }\n ret = stream\n } else if (isWebStream(stream)) {\n if (isReadableNodeStream(ret)) {\n finishCount++\n pumpToWeb(makeAsyncIterable(ret), stream, finish, {\n end\n })\n } else if (isReadableStream(ret) || isIterable(ret)) {\n finishCount++\n pumpToWeb(ret, stream, finish, {\n end\n })\n } else if (isTransformStream(ret)) {\n finishCount++\n pumpToWeb(ret.readable, stream, finish, {\n end\n })\n } else {\n throw new ERR_INVALID_ARG_TYPE(\n 'val',\n ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'],\n ret\n )\n }\n ret = stream\n } else {\n ret = Duplex.from(stream)\n }\n }\n if (\n (signal !== null && signal !== undefined && signal.aborted) ||\n (outerSignal !== null && outerSignal !== undefined && outerSignal.aborted)\n ) {\n process.nextTick(abort)\n }\n return ret\n}\nfunction pipe(src, dst, finish, { end }) {\n let ended = false\n dst.on('close', () => {\n if (!ended) {\n // Finish if the destination closes before the source has completed.\n finish(new ERR_STREAM_PREMATURE_CLOSE())\n }\n })\n src.pipe(dst, {\n end: false\n }) // If end is true we already will have a listener to end dst.\n\n if (end) {\n // Compat. Before node v10.12.0 stdio used to throw an error so\n // pipe() did/does not end() stdio destinations.\n // Now they allow it but \"secretly\" don't close the underlying fd.\n\n function endFn() {\n ended = true\n dst.end()\n }\n if (isReadableFinished(src)) {\n // End the destination if the source has already ended.\n process.nextTick(endFn)\n } else {\n src.once('end', endFn)\n }\n } else {\n finish()\n }\n eos(\n src,\n {\n readable: true,\n writable: false\n },\n (err) => {\n const rState = src._readableState\n if (\n err &&\n err.code === 'ERR_STREAM_PREMATURE_CLOSE' &&\n rState &&\n rState.ended &&\n !rState.errored &&\n !rState.errorEmitted\n ) {\n // Some readable streams will emit 'close' before 'end'. However, since\n // this is on the readable side 'end' should still be emitted if the\n // stream has been ended and no error emitted. This should be allowed in\n // favor of backwards compatibility. Since the stream is piped to a\n // destination this should not result in any observable difference.\n // We don't need to check if this is a writable premature close since\n // eos will only fail with premature close on the reading side for\n // duplex streams.\n src.once('end', finish).once('error', finish)\n } else {\n finish(err)\n }\n }\n )\n return eos(\n dst,\n {\n readable: false,\n writable: true\n },\n finish\n )\n}\nmodule.exports = {\n pipelineImpl,\n pipeline\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n;('use strict')\nconst {\n ArrayPrototypeIndexOf,\n NumberIsInteger,\n NumberIsNaN,\n NumberParseInt,\n ObjectDefineProperties,\n ObjectKeys,\n ObjectSetPrototypeOf,\n Promise,\n SafeSet,\n SymbolAsyncDispose,\n SymbolAsyncIterator,\n Symbol\n} = require('../../ours/primordials')\nmodule.exports = Readable\nReadable.ReadableState = ReadableState\nconst { EventEmitter: EE } = require('events')\nconst { Stream, prependListener } = require('./legacy')\nconst { Buffer } = require('buffer')\nconst { addAbortSignal } = require('./add-abort-signal')\nconst eos = require('./end-of-stream')\nlet debug = require('../../ours/util').debuglog('stream', (fn) => {\n debug = fn\n})\nconst BufferList = require('./buffer_list')\nconst destroyImpl = require('./destroy')\nconst { getHighWaterMark, getDefaultHighWaterMark } = require('./state')\nconst {\n aggregateTwoErrors,\n codes: {\n ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED,\n ERR_OUT_OF_RANGE,\n ERR_STREAM_PUSH_AFTER_EOF,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT\n },\n AbortError\n} = require('../../ours/errors')\nconst { validateObject } = require('../validators')\nconst kPaused = Symbol('kPaused')\nconst { StringDecoder } = require('string_decoder')\nconst from = require('./from')\nObjectSetPrototypeOf(Readable.prototype, Stream.prototype)\nObjectSetPrototypeOf(Readable, Stream)\nconst nop = () => {}\nconst { errorOrDestroy } = destroyImpl\nconst kObjectMode = 1 << 0\nconst kEnded = 1 << 1\nconst kEndEmitted = 1 << 2\nconst kReading = 1 << 3\nconst kConstructed = 1 << 4\nconst kSync = 1 << 5\nconst kNeedReadable = 1 << 6\nconst kEmittedReadable = 1 << 7\nconst kReadableListening = 1 << 8\nconst kResumeScheduled = 1 << 9\nconst kErrorEmitted = 1 << 10\nconst kEmitClose = 1 << 11\nconst kAutoDestroy = 1 << 12\nconst kDestroyed = 1 << 13\nconst kClosed = 1 << 14\nconst kCloseEmitted = 1 << 15\nconst kMultiAwaitDrain = 1 << 16\nconst kReadingMore = 1 << 17\nconst kDataEmitted = 1 << 18\n\n// TODO(benjamingr) it is likely slower to do it this way than with free functions\nfunction makeBitMapDescriptor(bit) {\n return {\n enumerable: false,\n get() {\n return (this.state & bit) !== 0\n },\n set(value) {\n if (value) this.state |= bit\n else this.state &= ~bit\n }\n }\n}\nObjectDefineProperties(ReadableState.prototype, {\n objectMode: makeBitMapDescriptor(kObjectMode),\n ended: makeBitMapDescriptor(kEnded),\n endEmitted: makeBitMapDescriptor(kEndEmitted),\n reading: makeBitMapDescriptor(kReading),\n // Stream is still being constructed and cannot be\n // destroyed until construction finished or failed.\n // Async construction is opt in, therefore we start as\n // constructed.\n constructed: makeBitMapDescriptor(kConstructed),\n // A flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n sync: makeBitMapDescriptor(kSync),\n // Whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n needReadable: makeBitMapDescriptor(kNeedReadable),\n emittedReadable: makeBitMapDescriptor(kEmittedReadable),\n readableListening: makeBitMapDescriptor(kReadableListening),\n resumeScheduled: makeBitMapDescriptor(kResumeScheduled),\n // True if the error was already emitted and should not be thrown again.\n errorEmitted: makeBitMapDescriptor(kErrorEmitted),\n emitClose: makeBitMapDescriptor(kEmitClose),\n autoDestroy: makeBitMapDescriptor(kAutoDestroy),\n // Has it been destroyed.\n destroyed: makeBitMapDescriptor(kDestroyed),\n // Indicates whether the stream has finished destroying.\n closed: makeBitMapDescriptor(kClosed),\n // True if close has been emitted or would have been emitted\n // depending on emitClose.\n closeEmitted: makeBitMapDescriptor(kCloseEmitted),\n multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain),\n // If true, a maybeReadMore has been scheduled.\n readingMore: makeBitMapDescriptor(kReadingMore),\n dataEmitted: makeBitMapDescriptor(kDataEmitted)\n})\nfunction ReadableState(options, stream, isDuplex) {\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex')\n\n // Bit map field to store ReadableState more effciently with 1 bit per field\n // instead of a V8 slot per field.\n this.state = kEmitClose | kAutoDestroy | kConstructed | kSync\n // Object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away.\n if (options && options.objectMode) this.state |= kObjectMode\n if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode\n\n // The point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n this.highWaterMark = options\n ? getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex)\n : getDefaultHighWaterMark(false)\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift().\n this.buffer = new BufferList()\n this.length = 0\n this.pipes = []\n this.flowing = null\n this[kPaused] = null\n\n // Should close be emitted on destroy. Defaults to true.\n if (options && options.emitClose === false) this.state &= ~kEmitClose\n\n // Should .destroy() be called after 'end' (and potentially 'finish').\n if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy\n\n // Indicates whether the stream has errored. When true no further\n // _read calls, 'data' or 'readable' events should occur. This is needed\n // since when autoDestroy is disabled we need a way to tell whether the\n // stream has failed.\n this.errored = null\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'\n\n // Ref the piped dest which we need a drain event on it\n // type: null | Writable | Set.\n this.awaitDrainWriters = null\n this.decoder = null\n this.encoding = null\n if (options && options.encoding) {\n this.decoder = new StringDecoder(options.encoding)\n this.encoding = options.encoding\n }\n}\nfunction Readable(options) {\n if (!(this instanceof Readable)) return new Readable(options)\n\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5.\n const isDuplex = this instanceof require('./duplex')\n this._readableState = new ReadableState(options, this, isDuplex)\n if (options) {\n if (typeof options.read === 'function') this._read = options.read\n if (typeof options.destroy === 'function') this._destroy = options.destroy\n if (typeof options.construct === 'function') this._construct = options.construct\n if (options.signal && !isDuplex) addAbortSignal(options.signal, this)\n }\n Stream.call(this, options)\n destroyImpl.construct(this, () => {\n if (this._readableState.needReadable) {\n maybeReadMore(this, this._readableState)\n }\n })\n}\nReadable.prototype.destroy = destroyImpl.destroy\nReadable.prototype._undestroy = destroyImpl.undestroy\nReadable.prototype._destroy = function (err, cb) {\n cb(err)\n}\nReadable.prototype[EE.captureRejectionSymbol] = function (err) {\n this.destroy(err)\n}\nReadable.prototype[SymbolAsyncDispose] = function () {\n let error\n if (!this.destroyed) {\n error = this.readableEnded ? null : new AbortError()\n this.destroy(error)\n }\n return new Promise((resolve, reject) => eos(this, (err) => (err && err !== error ? reject(err) : resolve(null))))\n}\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n return readableAddChunk(this, chunk, encoding, false)\n}\n\n// Unshift should *always* be something directly out of read().\nReadable.prototype.unshift = function (chunk, encoding) {\n return readableAddChunk(this, chunk, encoding, true)\n}\nfunction readableAddChunk(stream, chunk, encoding, addToFront) {\n debug('readableAddChunk', chunk)\n const state = stream._readableState\n let err\n if ((state.state & kObjectMode) === 0) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding\n if (state.encoding !== encoding) {\n if (addToFront && state.encoding) {\n // When unshifting, if state.encoding is set, we have to save\n // the string in the BufferList with the state encoding.\n chunk = Buffer.from(chunk, encoding).toString(state.encoding)\n } else {\n chunk = Buffer.from(chunk, encoding)\n encoding = ''\n }\n }\n } else if (chunk instanceof Buffer) {\n encoding = ''\n } else if (Stream._isUint8Array(chunk)) {\n chunk = Stream._uint8ArrayToBuffer(chunk)\n encoding = ''\n } else if (chunk != null) {\n err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk)\n }\n }\n if (err) {\n errorOrDestroy(stream, err)\n } else if (chunk === null) {\n state.state &= ~kReading\n onEofChunk(stream, state)\n } else if ((state.state & kObjectMode) !== 0 || (chunk && chunk.length > 0)) {\n if (addToFront) {\n if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT())\n else if (state.destroyed || state.errored) return false\n else addChunk(stream, state, chunk, true)\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF())\n } else if (state.destroyed || state.errored) {\n return false\n } else {\n state.state &= ~kReading\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk)\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false)\n else maybeReadMore(stream, state)\n } else {\n addChunk(stream, state, chunk, false)\n }\n }\n } else if (!addToFront) {\n state.state &= ~kReading\n maybeReadMore(stream, state)\n }\n\n // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n return !state.ended && (state.length < state.highWaterMark || state.length === 0)\n}\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount('data') > 0) {\n // Use the guard to avoid creating `Set()` repeatedly\n // when we have multiple pipes.\n if ((state.state & kMultiAwaitDrain) !== 0) {\n state.awaitDrainWriters.clear()\n } else {\n state.awaitDrainWriters = null\n }\n state.dataEmitted = true\n stream.emit('data', chunk)\n } else {\n // Update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length\n if (addToFront) state.buffer.unshift(chunk)\n else state.buffer.push(chunk)\n if ((state.state & kNeedReadable) !== 0) emitReadable(stream)\n }\n maybeReadMore(stream, state)\n}\nReadable.prototype.isPaused = function () {\n const state = this._readableState\n return state[kPaused] === true || state.flowing === false\n}\n\n// Backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n const decoder = new StringDecoder(enc)\n this._readableState.decoder = decoder\n // If setEncoding(null), decoder.encoding equals utf8.\n this._readableState.encoding = this._readableState.decoder.encoding\n const buffer = this._readableState.buffer\n // Iterate over current buffer to convert already stored Buffers:\n let content = ''\n for (const data of buffer) {\n content += decoder.write(data)\n }\n buffer.clear()\n if (content !== '') buffer.push(content)\n this._readableState.length = content.length\n return this\n}\n\n// Don't raise the hwm > 1GB.\nconst MAX_HWM = 0x40000000\nfunction computeNewHighWaterMark(n) {\n if (n > MAX_HWM) {\n throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n)\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts.\n n--\n n |= n >>> 1\n n |= n >>> 2\n n |= n >>> 4\n n |= n >>> 8\n n |= n >>> 16\n n++\n }\n return n\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || (state.length === 0 && state.ended)) return 0\n if ((state.state & kObjectMode) !== 0) return 1\n if (NumberIsNaN(n)) {\n // Only flow one buffer at a time.\n if (state.flowing && state.length) return state.buffer.first().length\n return state.length\n }\n if (n <= state.length) return n\n return state.ended ? state.length : 0\n}\n\n// You can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n)\n // Same as parseInt(undefined, 10), however V8 7.3 performance regressed\n // in this scenario, so we are doing it manually.\n if (n === undefined) {\n n = NaN\n } else if (!NumberIsInteger(n)) {\n n = NumberParseInt(n, 10)\n }\n const state = this._readableState\n const nOrig = n\n\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n)\n if (n !== 0) state.state &= ~kEmittedReadable\n\n // If we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (\n n === 0 &&\n state.needReadable &&\n ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)\n ) {\n debug('read: emitReadable', state.length, state.ended)\n if (state.length === 0 && state.ended) endReadable(this)\n else emitReadable(this)\n return null\n }\n n = howMuchToRead(n, state)\n\n // If we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this)\n return null\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n let doRead = (state.state & kNeedReadable) !== 0\n debug('need readable', doRead)\n\n // If we currently have less than the highWaterMark, then also read some.\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true\n debug('length less than watermark', doRead)\n }\n\n // However, if we've ended, then there's no point, if we're already\n // reading, then it's unnecessary, if we're constructing we have to wait,\n // and if we're destroyed or errored, then it's not allowed,\n if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) {\n doRead = false\n debug('reading, ended or constructing', doRead)\n } else if (doRead) {\n debug('do read')\n state.state |= kReading | kSync\n // If the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.state |= kNeedReadable\n\n // Call internal read method\n try {\n this._read(state.highWaterMark)\n } catch (err) {\n errorOrDestroy(this, err)\n }\n state.state &= ~kSync\n\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state)\n }\n let ret\n if (n > 0) ret = fromList(n, state)\n else ret = null\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark\n n = 0\n } else {\n state.length -= n\n if (state.multiAwaitDrain) {\n state.awaitDrainWriters.clear()\n } else {\n state.awaitDrainWriters = null\n }\n }\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this)\n }\n if (ret !== null && !state.errorEmitted && !state.closeEmitted) {\n state.dataEmitted = true\n this.emit('data', ret)\n }\n return ret\n}\nfunction onEofChunk(stream, state) {\n debug('onEofChunk')\n if (state.ended) return\n if (state.decoder) {\n const chunk = state.decoder.end()\n if (chunk && chunk.length) {\n state.buffer.push(chunk)\n state.length += state.objectMode ? 1 : chunk.length\n }\n }\n state.ended = true\n if (state.sync) {\n // If we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call.\n emitReadable(stream)\n } else {\n // Emit 'readable' now to make sure it gets picked up.\n state.needReadable = false\n state.emittedReadable = true\n // We have to emit readable now that we are EOF. Modules\n // in the ecosystem (e.g. dicer) rely on this event being sync.\n emitReadable_(stream)\n }\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n const state = stream._readableState\n debug('emitReadable', state.needReadable, state.emittedReadable)\n state.needReadable = false\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing)\n state.emittedReadable = true\n process.nextTick(emitReadable_, stream)\n }\n}\nfunction emitReadable_(stream) {\n const state = stream._readableState\n debug('emitReadable_', state.destroyed, state.length, state.ended)\n if (!state.destroyed && !state.errored && (state.length || state.ended)) {\n stream.emit('readable')\n state.emittedReadable = false\n }\n\n // The stream needs another readable event if:\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark\n flow(stream)\n}\n\n// At this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore && state.constructed) {\n state.readingMore = true\n process.nextTick(maybeReadMore_, stream, state)\n }\n}\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (\n !state.reading &&\n !state.ended &&\n (state.length < state.highWaterMark || (state.flowing && state.length === 0))\n ) {\n const len = state.length\n debug('maybeReadMore read 0')\n stream.read(0)\n if (len === state.length)\n // Didn't get any data, stop spinning.\n break\n }\n state.readingMore = false\n}\n\n// Abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n throw new ERR_METHOD_NOT_IMPLEMENTED('_read()')\n}\nReadable.prototype.pipe = function (dest, pipeOpts) {\n const src = this\n const state = this._readableState\n if (state.pipes.length === 1) {\n if (!state.multiAwaitDrain) {\n state.multiAwaitDrain = true\n state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : [])\n }\n }\n state.pipes.push(dest)\n debug('pipe count=%d opts=%j', state.pipes.length, pipeOpts)\n const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr\n const endFn = doEnd ? onend : unpipe\n if (state.endEmitted) process.nextTick(endFn)\n else src.once('end', endFn)\n dest.on('unpipe', onunpipe)\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe')\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true\n cleanup()\n }\n }\n }\n function onend() {\n debug('onend')\n dest.end()\n }\n let ondrain\n let cleanedUp = false\n function cleanup() {\n debug('cleanup')\n // Cleanup event handlers once the pipe is broken.\n dest.removeListener('close', onclose)\n dest.removeListener('finish', onfinish)\n if (ondrain) {\n dest.removeListener('drain', ondrain)\n }\n dest.removeListener('error', onerror)\n dest.removeListener('unpipe', onunpipe)\n src.removeListener('end', onend)\n src.removeListener('end', unpipe)\n src.removeListener('data', ondata)\n cleanedUp = true\n\n // If the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain()\n }\n function pause() {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if (!cleanedUp) {\n if (state.pipes.length === 1 && state.pipes[0] === dest) {\n debug('false write response, pause', 0)\n state.awaitDrainWriters = dest\n state.multiAwaitDrain = false\n } else if (state.pipes.length > 1 && state.pipes.includes(dest)) {\n debug('false write response, pause', state.awaitDrainWriters.size)\n state.awaitDrainWriters.add(dest)\n }\n src.pause()\n }\n if (!ondrain) {\n // When the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n ondrain = pipeOnDrain(src, dest)\n dest.on('drain', ondrain)\n }\n }\n src.on('data', ondata)\n function ondata(chunk) {\n debug('ondata')\n const ret = dest.write(chunk)\n debug('dest.write', ret)\n if (ret === false) {\n pause()\n }\n }\n\n // If the dest has an error, then stop piping into it.\n // However, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er)\n unpipe()\n dest.removeListener('error', onerror)\n if (dest.listenerCount('error') === 0) {\n const s = dest._writableState || dest._readableState\n if (s && !s.errorEmitted) {\n // User incorrectly emitted 'error' directly on the stream.\n errorOrDestroy(dest, er)\n } else {\n dest.emit('error', er)\n }\n }\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror)\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish)\n unpipe()\n }\n dest.once('close', onclose)\n function onfinish() {\n debug('onfinish')\n dest.removeListener('close', onclose)\n unpipe()\n }\n dest.once('finish', onfinish)\n function unpipe() {\n debug('unpipe')\n src.unpipe(dest)\n }\n\n // Tell the dest that it's being piped to.\n dest.emit('pipe', src)\n\n // Start the flow if it hasn't been started already.\n\n if (dest.writableNeedDrain === true) {\n pause()\n } else if (!state.flowing) {\n debug('pipe resume')\n src.resume()\n }\n return dest\n}\nfunction pipeOnDrain(src, dest) {\n return function pipeOnDrainFunctionResult() {\n const state = src._readableState\n\n // `ondrain` will call directly,\n // `this` maybe not a reference to dest,\n // so we use the real dest here.\n if (state.awaitDrainWriters === dest) {\n debug('pipeOnDrain', 1)\n state.awaitDrainWriters = null\n } else if (state.multiAwaitDrain) {\n debug('pipeOnDrain', state.awaitDrainWriters.size)\n state.awaitDrainWriters.delete(dest)\n }\n if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount('data')) {\n src.resume()\n }\n }\n}\nReadable.prototype.unpipe = function (dest) {\n const state = this._readableState\n const unpipeInfo = {\n hasUnpiped: false\n }\n\n // If we're not piping anywhere, then do nothing.\n if (state.pipes.length === 0) return this\n if (!dest) {\n // remove all.\n const dests = state.pipes\n state.pipes = []\n this.pause()\n for (let i = 0; i < dests.length; i++)\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n })\n return this\n }\n\n // Try to find the right one.\n const index = ArrayPrototypeIndexOf(state.pipes, dest)\n if (index === -1) return this\n state.pipes.splice(index, 1)\n if (state.pipes.length === 0) this.pause()\n dest.emit('unpipe', this, unpipeInfo)\n return this\n}\n\n// Set up data events if they are asked for\n// Ensure readable listeners eventually get something.\nReadable.prototype.on = function (ev, fn) {\n const res = Stream.prototype.on.call(this, ev, fn)\n const state = this._readableState\n if (ev === 'data') {\n // Update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0\n\n // Try start flowing on next tick if stream isn't explicitly paused.\n if (state.flowing !== false) this.resume()\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true\n state.flowing = false\n state.emittedReadable = false\n debug('on readable', state.length, state.reading)\n if (state.length) {\n emitReadable(this)\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this)\n }\n }\n }\n return res\n}\nReadable.prototype.addListener = Readable.prototype.on\nReadable.prototype.removeListener = function (ev, fn) {\n const res = Stream.prototype.removeListener.call(this, ev, fn)\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this)\n }\n return res\n}\nReadable.prototype.off = Readable.prototype.removeListener\nReadable.prototype.removeAllListeners = function (ev) {\n const res = Stream.prototype.removeAllListeners.apply(this, arguments)\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this)\n }\n return res\n}\nfunction updateReadableListening(self) {\n const state = self._readableState\n state.readableListening = self.listenerCount('readable') > 0\n if (state.resumeScheduled && state[kPaused] === false) {\n // Flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true\n\n // Crude way to check if we should resume.\n } else if (self.listenerCount('data') > 0) {\n self.resume()\n } else if (!state.readableListening) {\n state.flowing = null\n }\n}\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0')\n self.read(0)\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n const state = this._readableState\n if (!state.flowing) {\n debug('resume')\n // We flow only if there is no one listening\n // for readable, but we still have to call\n // resume().\n state.flowing = !state.readableListening\n resume(this, state)\n }\n state[kPaused] = false\n return this\n}\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true\n process.nextTick(resume_, stream, state)\n }\n}\nfunction resume_(stream, state) {\n debug('resume', state.reading)\n if (!state.reading) {\n stream.read(0)\n }\n state.resumeScheduled = false\n stream.emit('resume')\n flow(stream)\n if (state.flowing && !state.reading) stream.read(0)\n}\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing)\n if (this._readableState.flowing !== false) {\n debug('pause')\n this._readableState.flowing = false\n this.emit('pause')\n }\n this._readableState[kPaused] = true\n return this\n}\nfunction flow(stream) {\n const state = stream._readableState\n debug('flow', state.flowing)\n while (state.flowing && stream.read() !== null);\n}\n\n// Wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n let paused = false\n\n // TODO (ronag): Should this.destroy(err) emit\n // 'error' on the wrapped stream? Would require\n // a static factory method, e.g. Readable.wrap(stream).\n\n stream.on('data', (chunk) => {\n if (!this.push(chunk) && stream.pause) {\n paused = true\n stream.pause()\n }\n })\n stream.on('end', () => {\n this.push(null)\n })\n stream.on('error', (err) => {\n errorOrDestroy(this, err)\n })\n stream.on('close', () => {\n this.destroy()\n })\n stream.on('destroy', () => {\n this.destroy()\n })\n this._read = () => {\n if (paused && stream.resume) {\n paused = false\n stream.resume()\n }\n }\n\n // Proxy all the other methods. Important when wrapping filters and duplexes.\n const streamKeys = ObjectKeys(stream)\n for (let j = 1; j < streamKeys.length; j++) {\n const i = streamKeys[j]\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = stream[i].bind(stream)\n }\n }\n return this\n}\nReadable.prototype[SymbolAsyncIterator] = function () {\n return streamToAsyncIterator(this)\n}\nReadable.prototype.iterator = function (options) {\n if (options !== undefined) {\n validateObject(options, 'options')\n }\n return streamToAsyncIterator(this, options)\n}\nfunction streamToAsyncIterator(stream, options) {\n if (typeof stream.read !== 'function') {\n stream = Readable.wrap(stream, {\n objectMode: true\n })\n }\n const iter = createAsyncIterator(stream, options)\n iter.stream = stream\n return iter\n}\nasync function* createAsyncIterator(stream, options) {\n let callback = nop\n function next(resolve) {\n if (this === stream) {\n callback()\n callback = nop\n } else {\n callback = resolve\n }\n }\n stream.on('readable', next)\n let error\n const cleanup = eos(\n stream,\n {\n writable: false\n },\n (err) => {\n error = err ? aggregateTwoErrors(error, err) : null\n callback()\n callback = nop\n }\n )\n try {\n while (true) {\n const chunk = stream.destroyed ? null : stream.read()\n if (chunk !== null) {\n yield chunk\n } else if (error) {\n throw error\n } else if (error === null) {\n return\n } else {\n await new Promise(next)\n }\n }\n } catch (err) {\n error = aggregateTwoErrors(error, err)\n throw error\n } finally {\n if (\n (error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) &&\n (error === undefined || stream._readableState.autoDestroy)\n ) {\n destroyImpl.destroyer(stream, null)\n } else {\n stream.off('readable', next)\n cleanup()\n }\n }\n}\n\n// Making it explicit these properties are not enumerable\n// because otherwise some prototype manipulation in\n// userland will fail.\nObjectDefineProperties(Readable.prototype, {\n readable: {\n __proto__: null,\n get() {\n const r = this._readableState\n // r.readable === false means that this is part of a Duplex stream\n // where the readable side was disabled upon construction.\n // Compat. The user might manually disable readable side through\n // deprecated setter.\n return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted\n },\n set(val) {\n // Backwards compat.\n if (this._readableState) {\n this._readableState.readable = !!val\n }\n }\n },\n readableDidRead: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return this._readableState.dataEmitted\n }\n },\n readableAborted: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return !!(\n this._readableState.readable !== false &&\n (this._readableState.destroyed || this._readableState.errored) &&\n !this._readableState.endEmitted\n )\n }\n },\n readableHighWaterMark: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark\n }\n },\n readableBuffer: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return this._readableState && this._readableState.buffer\n }\n },\n readableFlowing: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return this._readableState.flowing\n },\n set: function (state) {\n if (this._readableState) {\n this._readableState.flowing = state\n }\n }\n },\n readableLength: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState.length\n }\n },\n readableObjectMode: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.objectMode : false\n }\n },\n readableEncoding: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.encoding : null\n }\n },\n errored: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.errored : null\n }\n },\n closed: {\n __proto__: null,\n get() {\n return this._readableState ? this._readableState.closed : false\n }\n },\n destroyed: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.destroyed : false\n },\n set(value) {\n // We ignore the value if the stream\n // has not been initialized yet.\n if (!this._readableState) {\n return\n }\n\n // Backward compatibility, the user is explicitly\n // managing destroyed.\n this._readableState.destroyed = value\n }\n },\n readableEnded: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.endEmitted : false\n }\n }\n})\nObjectDefineProperties(ReadableState.prototype, {\n // Legacy getter for `pipesCount`.\n pipesCount: {\n __proto__: null,\n get() {\n return this.pipes.length\n }\n },\n // Legacy property for `paused`.\n paused: {\n __proto__: null,\n get() {\n return this[kPaused] !== false\n },\n set(value) {\n this[kPaused] = !!value\n }\n }\n})\n\n// Exposed for testing purposes only.\nReadable._fromList = fromList\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered.\n if (state.length === 0) return null\n let ret\n if (state.objectMode) ret = state.buffer.shift()\n else if (!n || n >= state.length) {\n // Read it all, truncate the list.\n if (state.decoder) ret = state.buffer.join('')\n else if (state.buffer.length === 1) ret = state.buffer.first()\n else ret = state.buffer.concat(state.length)\n state.buffer.clear()\n } else {\n // read part of list.\n ret = state.buffer.consume(n, state.decoder)\n }\n return ret\n}\nfunction endReadable(stream) {\n const state = stream._readableState\n debug('endReadable', state.endEmitted)\n if (!state.endEmitted) {\n state.ended = true\n process.nextTick(endReadableNT, state, stream)\n }\n}\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length)\n\n // Check that we didn't get one last unshift.\n if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) {\n state.endEmitted = true\n stream.emit('end')\n if (stream.writable && stream.allowHalfOpen === false) {\n process.nextTick(endWritableNT, stream)\n } else if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well.\n const wState = stream._writableState\n const autoDestroy =\n !wState ||\n (wState.autoDestroy &&\n // We don't expect the writable to ever 'finish'\n // if writable is explicitly set to false.\n (wState.finished || wState.writable === false))\n if (autoDestroy) {\n stream.destroy()\n }\n }\n }\n}\nfunction endWritableNT(stream) {\n const writable = stream.writable && !stream.writableEnded && !stream.destroyed\n if (writable) {\n stream.end()\n }\n}\nReadable.from = function (iterable, opts) {\n return from(Readable, iterable, opts)\n}\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n return webStreamsAdapters\n}\nReadable.fromWeb = function (readableStream, options) {\n return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options)\n}\nReadable.toWeb = function (streamReadable, options) {\n return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options)\n}\nReadable.wrap = function (src, options) {\n var _ref, _src$readableObjectMo\n return new Readable({\n objectMode:\n (_ref =\n (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined\n ? _src$readableObjectMo\n : src.objectMode) !== null && _ref !== undefined\n ? _ref\n : true,\n ...options,\n destroy(err, callback) {\n destroyImpl.destroyer(src, err)\n callback(err)\n }\n }).wrap(src)\n}\n","'use strict'\n\nconst { MathFloor, NumberIsInteger } = require('../../ours/primordials')\nconst { validateInteger } = require('../validators')\nconst { ERR_INVALID_ARG_VALUE } = require('../../ours/errors').codes\nlet defaultHighWaterMarkBytes = 16 * 1024\nlet defaultHighWaterMarkObjectMode = 16\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null\n}\nfunction getDefaultHighWaterMark(objectMode) {\n return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes\n}\nfunction setDefaultHighWaterMark(objectMode, value) {\n validateInteger(value, 'value', 0)\n if (objectMode) {\n defaultHighWaterMarkObjectMode = value\n } else {\n defaultHighWaterMarkBytes = value\n }\n}\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n const hwm = highWaterMarkFrom(options, isDuplex, duplexKey)\n if (hwm != null) {\n if (!NumberIsInteger(hwm) || hwm < 0) {\n const name = isDuplex ? `options.${duplexKey}` : 'options.highWaterMark'\n throw new ERR_INVALID_ARG_VALUE(name, hwm)\n }\n return MathFloor(hwm)\n }\n\n // Default value\n return getDefaultHighWaterMark(state.objectMode)\n}\nmodule.exports = {\n getHighWaterMark,\n getDefaultHighWaterMark,\n setDefaultHighWaterMark\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict'\n\nconst { ObjectSetPrototypeOf, Symbol } = require('../../ours/primordials')\nmodule.exports = Transform\nconst { ERR_METHOD_NOT_IMPLEMENTED } = require('../../ours/errors').codes\nconst Duplex = require('./duplex')\nconst { getHighWaterMark } = require('./state')\nObjectSetPrototypeOf(Transform.prototype, Duplex.prototype)\nObjectSetPrototypeOf(Transform, Duplex)\nconst kCallback = Symbol('kCallback')\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options)\n\n // TODO (ronag): This should preferably always be\n // applied but would be semver-major. Or even better;\n // make Transform a Readable with the Writable interface.\n const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null\n if (readableHighWaterMark === 0) {\n // A Duplex will buffer both on the writable and readable side while\n // a Transform just wants to buffer hwm number of elements. To avoid\n // buffering twice we disable buffering on the writable side.\n options = {\n ...options,\n highWaterMark: null,\n readableHighWaterMark,\n // TODO (ronag): 0 is not optimal since we have\n // a \"bug\" where we check needDrain before calling _write and not after.\n // Refs: https://github.com/nodejs/node/pull/32887\n // Refs: https://github.com/nodejs/node/pull/35941\n writableHighWaterMark: options.writableHighWaterMark || 0\n }\n }\n Duplex.call(this, options)\n\n // We have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false\n this[kCallback] = null\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform\n if (typeof options.flush === 'function') this._flush = options.flush\n }\n\n // When the writable side finishes, then flush out anything remaining.\n // Backwards compat. Some Transform streams incorrectly implement _final\n // instead of or in addition to _flush. By using 'prefinish' instead of\n // implementing _final we continue supporting this unfortunate use case.\n this.on('prefinish', prefinish)\n}\nfunction final(cb) {\n if (typeof this._flush === 'function' && !this.destroyed) {\n this._flush((er, data) => {\n if (er) {\n if (cb) {\n cb(er)\n } else {\n this.destroy(er)\n }\n return\n }\n if (data != null) {\n this.push(data)\n }\n this.push(null)\n if (cb) {\n cb()\n }\n })\n } else {\n this.push(null)\n if (cb) {\n cb()\n }\n }\n}\nfunction prefinish() {\n if (this._final !== final) {\n final.call(this)\n }\n}\nTransform.prototype._final = final\nTransform.prototype._transform = function (chunk, encoding, callback) {\n throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()')\n}\nTransform.prototype._write = function (chunk, encoding, callback) {\n const rState = this._readableState\n const wState = this._writableState\n const length = rState.length\n this._transform(chunk, encoding, (err, val) => {\n if (err) {\n callback(err)\n return\n }\n if (val != null) {\n this.push(val)\n }\n if (\n wState.ended ||\n // Backwards compat.\n length === rState.length ||\n // Backwards compat.\n rState.length < rState.highWaterMark\n ) {\n callback()\n } else {\n this[kCallback] = callback\n }\n })\n}\nTransform.prototype._read = function () {\n if (this[kCallback]) {\n const callback = this[kCallback]\n this[kCallback] = null\n callback()\n }\n}\n","'use strict'\n\nconst { SymbolAsyncIterator, SymbolIterator, SymbolFor } = require('../../ours/primordials')\n\n// We need to use SymbolFor to make these globally available\n// for interopt with readable-stream, i.e. readable-stream\n// and node core needs to be able to read/write private state\n// from each other for proper interoperability.\nconst kIsDestroyed = SymbolFor('nodejs.stream.destroyed')\nconst kIsErrored = SymbolFor('nodejs.stream.errored')\nconst kIsReadable = SymbolFor('nodejs.stream.readable')\nconst kIsWritable = SymbolFor('nodejs.stream.writable')\nconst kIsDisturbed = SymbolFor('nodejs.stream.disturbed')\nconst kIsClosedPromise = SymbolFor('nodejs.webstream.isClosedPromise')\nconst kControllerErrorFunction = SymbolFor('nodejs.webstream.controllerErrorFunction')\nfunction isReadableNodeStream(obj, strict = false) {\n var _obj$_readableState\n return !!(\n (\n obj &&\n typeof obj.pipe === 'function' &&\n typeof obj.on === 'function' &&\n (!strict || (typeof obj.pause === 'function' && typeof obj.resume === 'function')) &&\n (!obj._writableState ||\n ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined\n ? undefined\n : _obj$_readableState.readable) !== false) &&\n // Duplex\n (!obj._writableState || obj._readableState)\n ) // Writable has .pipe.\n )\n}\n\nfunction isWritableNodeStream(obj) {\n var _obj$_writableState\n return !!(\n (\n obj &&\n typeof obj.write === 'function' &&\n typeof obj.on === 'function' &&\n (!obj._readableState ||\n ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined\n ? undefined\n : _obj$_writableState.writable) !== false)\n ) // Duplex\n )\n}\n\nfunction isDuplexNodeStream(obj) {\n return !!(\n obj &&\n typeof obj.pipe === 'function' &&\n obj._readableState &&\n typeof obj.on === 'function' &&\n typeof obj.write === 'function'\n )\n}\nfunction isNodeStream(obj) {\n return (\n obj &&\n (obj._readableState ||\n obj._writableState ||\n (typeof obj.write === 'function' && typeof obj.on === 'function') ||\n (typeof obj.pipe === 'function' && typeof obj.on === 'function'))\n )\n}\nfunction isReadableStream(obj) {\n return !!(\n obj &&\n !isNodeStream(obj) &&\n typeof obj.pipeThrough === 'function' &&\n typeof obj.getReader === 'function' &&\n typeof obj.cancel === 'function'\n )\n}\nfunction isWritableStream(obj) {\n return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === 'function' && typeof obj.abort === 'function')\n}\nfunction isTransformStream(obj) {\n return !!(obj && !isNodeStream(obj) && typeof obj.readable === 'object' && typeof obj.writable === 'object')\n}\nfunction isWebStream(obj) {\n return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj)\n}\nfunction isIterable(obj, isAsync) {\n if (obj == null) return false\n if (isAsync === true) return typeof obj[SymbolAsyncIterator] === 'function'\n if (isAsync === false) return typeof obj[SymbolIterator] === 'function'\n return typeof obj[SymbolAsyncIterator] === 'function' || typeof obj[SymbolIterator] === 'function'\n}\nfunction isDestroyed(stream) {\n if (!isNodeStream(stream)) return null\n const wState = stream._writableState\n const rState = stream._readableState\n const state = wState || rState\n return !!(stream.destroyed || stream[kIsDestroyed] || (state !== null && state !== undefined && state.destroyed))\n}\n\n// Have been end():d.\nfunction isWritableEnded(stream) {\n if (!isWritableNodeStream(stream)) return null\n if (stream.writableEnded === true) return true\n const wState = stream._writableState\n if (wState !== null && wState !== undefined && wState.errored) return false\n if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== 'boolean') return null\n return wState.ended\n}\n\n// Have emitted 'finish'.\nfunction isWritableFinished(stream, strict) {\n if (!isWritableNodeStream(stream)) return null\n if (stream.writableFinished === true) return true\n const wState = stream._writableState\n if (wState !== null && wState !== undefined && wState.errored) return false\n if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== 'boolean') return null\n return !!(wState.finished || (strict === false && wState.ended === true && wState.length === 0))\n}\n\n// Have been push(null):d.\nfunction isReadableEnded(stream) {\n if (!isReadableNodeStream(stream)) return null\n if (stream.readableEnded === true) return true\n const rState = stream._readableState\n if (!rState || rState.errored) return false\n if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== 'boolean') return null\n return rState.ended\n}\n\n// Have emitted 'end'.\nfunction isReadableFinished(stream, strict) {\n if (!isReadableNodeStream(stream)) return null\n const rState = stream._readableState\n if (rState !== null && rState !== undefined && rState.errored) return false\n if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== 'boolean') return null\n return !!(rState.endEmitted || (strict === false && rState.ended === true && rState.length === 0))\n}\nfunction isReadable(stream) {\n if (stream && stream[kIsReadable] != null) return stream[kIsReadable]\n if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== 'boolean') return null\n if (isDestroyed(stream)) return false\n return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream)\n}\nfunction isWritable(stream) {\n if (stream && stream[kIsWritable] != null) return stream[kIsWritable]\n if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== 'boolean') return null\n if (isDestroyed(stream)) return false\n return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream)\n}\nfunction isFinished(stream, opts) {\n if (!isNodeStream(stream)) {\n return null\n }\n if (isDestroyed(stream)) {\n return true\n }\n if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream)) {\n return false\n }\n if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream)) {\n return false\n }\n return true\n}\nfunction isWritableErrored(stream) {\n var _stream$_writableStat, _stream$_writableStat2\n if (!isNodeStream(stream)) {\n return null\n }\n if (stream.writableErrored) {\n return stream.writableErrored\n }\n return (_stream$_writableStat =\n (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined\n ? undefined\n : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined\n ? _stream$_writableStat\n : null\n}\nfunction isReadableErrored(stream) {\n var _stream$_readableStat, _stream$_readableStat2\n if (!isNodeStream(stream)) {\n return null\n }\n if (stream.readableErrored) {\n return stream.readableErrored\n }\n return (_stream$_readableStat =\n (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined\n ? undefined\n : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined\n ? _stream$_readableStat\n : null\n}\nfunction isClosed(stream) {\n if (!isNodeStream(stream)) {\n return null\n }\n if (typeof stream.closed === 'boolean') {\n return stream.closed\n }\n const wState = stream._writableState\n const rState = stream._readableState\n if (\n typeof (wState === null || wState === undefined ? undefined : wState.closed) === 'boolean' ||\n typeof (rState === null || rState === undefined ? undefined : rState.closed) === 'boolean'\n ) {\n return (\n (wState === null || wState === undefined ? undefined : wState.closed) ||\n (rState === null || rState === undefined ? undefined : rState.closed)\n )\n }\n if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) {\n return stream._closed\n }\n return null\n}\nfunction isOutgoingMessage(stream) {\n return (\n typeof stream._closed === 'boolean' &&\n typeof stream._defaultKeepAlive === 'boolean' &&\n typeof stream._removedConnection === 'boolean' &&\n typeof stream._removedContLen === 'boolean'\n )\n}\nfunction isServerResponse(stream) {\n return typeof stream._sent100 === 'boolean' && isOutgoingMessage(stream)\n}\nfunction isServerRequest(stream) {\n var _stream$req\n return (\n typeof stream._consuming === 'boolean' &&\n typeof stream._dumped === 'boolean' &&\n ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) ===\n undefined\n )\n}\nfunction willEmitClose(stream) {\n if (!isNodeStream(stream)) return null\n const wState = stream._writableState\n const rState = stream._readableState\n const state = wState || rState\n return (\n (!state && isServerResponse(stream)) || !!(state && state.autoDestroy && state.emitClose && state.closed === false)\n )\n}\nfunction isDisturbed(stream) {\n var _stream$kIsDisturbed\n return !!(\n stream &&\n ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined\n ? _stream$kIsDisturbed\n : stream.readableDidRead || stream.readableAborted)\n )\n}\nfunction isErrored(stream) {\n var _ref,\n _ref2,\n _ref3,\n _ref4,\n _ref5,\n _stream$kIsErrored,\n _stream$_readableStat3,\n _stream$_writableStat3,\n _stream$_readableStat4,\n _stream$_writableStat4\n return !!(\n stream &&\n ((_ref =\n (_ref2 =\n (_ref3 =\n (_ref4 =\n (_ref5 =\n (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined\n ? _stream$kIsErrored\n : stream.readableErrored) !== null && _ref5 !== undefined\n ? _ref5\n : stream.writableErrored) !== null && _ref4 !== undefined\n ? _ref4\n : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined\n ? undefined\n : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined\n ? _ref3\n : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined\n ? undefined\n : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined\n ? _ref2\n : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined\n ? undefined\n : _stream$_readableStat4.errored) !== null && _ref !== undefined\n ? _ref\n : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined\n ? undefined\n : _stream$_writableStat4.errored)\n )\n}\nmodule.exports = {\n isDestroyed,\n kIsDestroyed,\n isDisturbed,\n kIsDisturbed,\n isErrored,\n kIsErrored,\n isReadable,\n kIsReadable,\n kIsClosedPromise,\n kControllerErrorFunction,\n kIsWritable,\n isClosed,\n isDuplexNodeStream,\n isFinished,\n isIterable,\n isReadableNodeStream,\n isReadableStream,\n isReadableEnded,\n isReadableFinished,\n isReadableErrored,\n isNodeStream,\n isWebStream,\n isWritable,\n isWritableNodeStream,\n isWritableStream,\n isWritableEnded,\n isWritableFinished,\n isWritableErrored,\n isServerRequest,\n isServerResponse,\n willEmitClose,\n isTransformStream\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n;('use strict')\nconst {\n ArrayPrototypeSlice,\n Error,\n FunctionPrototypeSymbolHasInstance,\n ObjectDefineProperty,\n ObjectDefineProperties,\n ObjectSetPrototypeOf,\n StringPrototypeToLowerCase,\n Symbol,\n SymbolHasInstance\n} = require('../../ours/primordials')\nmodule.exports = Writable\nWritable.WritableState = WritableState\nconst { EventEmitter: EE } = require('events')\nconst Stream = require('./legacy').Stream\nconst { Buffer } = require('buffer')\nconst destroyImpl = require('./destroy')\nconst { addAbortSignal } = require('./add-abort-signal')\nconst { getHighWaterMark, getDefaultHighWaterMark } = require('./state')\nconst {\n ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED,\n ERR_STREAM_ALREADY_FINISHED,\n ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING\n} = require('../../ours/errors').codes\nconst { errorOrDestroy } = destroyImpl\nObjectSetPrototypeOf(Writable.prototype, Stream.prototype)\nObjectSetPrototypeOf(Writable, Stream)\nfunction nop() {}\nconst kOnFinished = Symbol('kOnFinished')\nfunction WritableState(options, stream, isDuplex) {\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex')\n\n // Object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!(options && options.objectMode)\n if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode)\n\n // The point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write().\n this.highWaterMark = options\n ? getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex)\n : getDefaultHighWaterMark(false)\n\n // if _final has been called.\n this.finalCalled = false\n\n // drain event flag.\n this.needDrain = false\n // At the start of calling end()\n this.ending = false\n // When end() has been called, and returned.\n this.ended = false\n // When 'finish' is emitted.\n this.finished = false\n\n // Has it been destroyed\n this.destroyed = false\n\n // Should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n const noDecode = !!(options && options.decodeStrings === false)\n this.decodeStrings = !noDecode\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'\n\n // Not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0\n\n // A flag to see when we're in the middle of a write.\n this.writing = false\n\n // When true all writes will be buffered until .uncork() call.\n this.corked = 0\n\n // A flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true\n\n // A flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false\n\n // The callback that's passed to _write(chunk, cb).\n this.onwrite = onwrite.bind(undefined, stream)\n\n // The callback that the user supplies to write(chunk, encoding, cb).\n this.writecb = null\n\n // The amount that is being written when _write is called.\n this.writelen = 0\n\n // Storage for data passed to the afterWrite() callback in case of\n // synchronous _write() completion.\n this.afterWriteTickInfo = null\n resetBuffer(this)\n\n // Number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted.\n this.pendingcb = 0\n\n // Stream is still being constructed and cannot be\n // destroyed until construction finished or failed.\n // Async construction is opt in, therefore we start as\n // constructed.\n this.constructed = true\n\n // Emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams.\n this.prefinished = false\n\n // True if the error was already emitted and should not be thrown again.\n this.errorEmitted = false\n\n // Should close be emitted on destroy. Defaults to true.\n this.emitClose = !options || options.emitClose !== false\n\n // Should .destroy() be called after 'finish' (and potentially 'end').\n this.autoDestroy = !options || options.autoDestroy !== false\n\n // Indicates whether the stream has errored. When true all write() calls\n // should return false. This is needed since when autoDestroy\n // is disabled we need a way to tell whether the stream has failed.\n this.errored = null\n\n // Indicates whether the stream has finished destroying.\n this.closed = false\n\n // True if close has been emitted or would have been emitted\n // depending on emitClose.\n this.closeEmitted = false\n this[kOnFinished] = []\n}\nfunction resetBuffer(state) {\n state.buffered = []\n state.bufferedIndex = 0\n state.allBuffers = true\n state.allNoop = true\n}\nWritableState.prototype.getBuffer = function getBuffer() {\n return ArrayPrototypeSlice(this.buffered, this.bufferedIndex)\n}\nObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', {\n __proto__: null,\n get() {\n return this.buffered.length - this.bufferedIndex\n }\n})\nfunction Writable(options) {\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5.\n const isDuplex = this instanceof require('./duplex')\n if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options)\n this._writableState = new WritableState(options, this, isDuplex)\n if (options) {\n if (typeof options.write === 'function') this._write = options.write\n if (typeof options.writev === 'function') this._writev = options.writev\n if (typeof options.destroy === 'function') this._destroy = options.destroy\n if (typeof options.final === 'function') this._final = options.final\n if (typeof options.construct === 'function') this._construct = options.construct\n if (options.signal) addAbortSignal(options.signal, this)\n }\n Stream.call(this, options)\n destroyImpl.construct(this, () => {\n const state = this._writableState\n if (!state.writing) {\n clearBuffer(this, state)\n }\n finishMaybe(this, state)\n })\n}\nObjectDefineProperty(Writable, SymbolHasInstance, {\n __proto__: null,\n value: function (object) {\n if (FunctionPrototypeSymbolHasInstance(this, object)) return true\n if (this !== Writable) return false\n return object && object._writableState instanceof WritableState\n }\n})\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE())\n}\nfunction _write(stream, chunk, encoding, cb) {\n const state = stream._writableState\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = state.defaultEncoding\n } else {\n if (!encoding) encoding = state.defaultEncoding\n else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding)\n if (typeof cb !== 'function') cb = nop\n }\n if (chunk === null) {\n throw new ERR_STREAM_NULL_VALUES()\n } else if (!state.objectMode) {\n if (typeof chunk === 'string') {\n if (state.decodeStrings !== false) {\n chunk = Buffer.from(chunk, encoding)\n encoding = 'buffer'\n }\n } else if (chunk instanceof Buffer) {\n encoding = 'buffer'\n } else if (Stream._isUint8Array(chunk)) {\n chunk = Stream._uint8ArrayToBuffer(chunk)\n encoding = 'buffer'\n } else {\n throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk)\n }\n }\n let err\n if (state.ending) {\n err = new ERR_STREAM_WRITE_AFTER_END()\n } else if (state.destroyed) {\n err = new ERR_STREAM_DESTROYED('write')\n }\n if (err) {\n process.nextTick(cb, err)\n errorOrDestroy(stream, err, true)\n return err\n }\n state.pendingcb++\n return writeOrBuffer(stream, state, chunk, encoding, cb)\n}\nWritable.prototype.write = function (chunk, encoding, cb) {\n return _write(this, chunk, encoding, cb) === true\n}\nWritable.prototype.cork = function () {\n this._writableState.corked++\n}\nWritable.prototype.uncork = function () {\n const state = this._writableState\n if (state.corked) {\n state.corked--\n if (!state.writing) clearBuffer(this, state)\n }\n}\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = StringPrototypeToLowerCase(encoding)\n if (!Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding)\n this._writableState.defaultEncoding = encoding\n return this\n}\n\n// If we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, chunk, encoding, callback) {\n const len = state.objectMode ? 1 : chunk.length\n state.length += len\n\n // stream._write resets state.length\n const ret = state.length < state.highWaterMark\n // We must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true\n if (state.writing || state.corked || state.errored || !state.constructed) {\n state.buffered.push({\n chunk,\n encoding,\n callback\n })\n if (state.allBuffers && encoding !== 'buffer') {\n state.allBuffers = false\n }\n if (state.allNoop && callback !== nop) {\n state.allNoop = false\n }\n } else {\n state.writelen = len\n state.writecb = callback\n state.writing = true\n state.sync = true\n stream._write(chunk, encoding, state.onwrite)\n state.sync = false\n }\n\n // Return false if errored or destroyed in order to break\n // any synchronous while(stream.write(data)) loops.\n return ret && !state.errored && !state.destroyed\n}\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len\n state.writecb = cb\n state.writing = true\n state.sync = true\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'))\n else if (writev) stream._writev(chunk, state.onwrite)\n else stream._write(chunk, encoding, state.onwrite)\n state.sync = false\n}\nfunction onwriteError(stream, state, er, cb) {\n --state.pendingcb\n cb(er)\n // Ensure callbacks are invoked even when autoDestroy is\n // not enabled. Passing `er` here doesn't make sense since\n // it's related to one specific write, not to the buffered\n // writes.\n errorBuffer(state)\n // This can emit error, but error must always follow cb.\n errorOrDestroy(stream, er)\n}\nfunction onwrite(stream, er) {\n const state = stream._writableState\n const sync = state.sync\n const cb = state.writecb\n if (typeof cb !== 'function') {\n errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK())\n return\n }\n state.writing = false\n state.writecb = null\n state.length -= state.writelen\n state.writelen = 0\n if (er) {\n // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n er.stack // eslint-disable-line no-unused-expressions\n\n if (!state.errored) {\n state.errored = er\n }\n\n // In case of duplex streams we need to notify the readable side of the\n // error.\n if (stream._readableState && !stream._readableState.errored) {\n stream._readableState.errored = er\n }\n if (sync) {\n process.nextTick(onwriteError, stream, state, er, cb)\n } else {\n onwriteError(stream, state, er, cb)\n }\n } else {\n if (state.buffered.length > state.bufferedIndex) {\n clearBuffer(stream, state)\n }\n if (sync) {\n // It is a common case that the callback passed to .write() is always\n // the same. In that case, we do not schedule a new nextTick(), but\n // rather just increase a counter, to improve performance and avoid\n // memory allocations.\n if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) {\n state.afterWriteTickInfo.count++\n } else {\n state.afterWriteTickInfo = {\n count: 1,\n cb,\n stream,\n state\n }\n process.nextTick(afterWriteTick, state.afterWriteTickInfo)\n }\n } else {\n afterWrite(stream, state, 1, cb)\n }\n }\n}\nfunction afterWriteTick({ stream, state, count, cb }) {\n state.afterWriteTickInfo = null\n return afterWrite(stream, state, count, cb)\n}\nfunction afterWrite(stream, state, count, cb) {\n const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain\n if (needDrain) {\n state.needDrain = false\n stream.emit('drain')\n }\n while (count-- > 0) {\n state.pendingcb--\n cb()\n }\n if (state.destroyed) {\n errorBuffer(state)\n }\n finishMaybe(stream, state)\n}\n\n// If there's something in the buffer waiting, then invoke callbacks.\nfunction errorBuffer(state) {\n if (state.writing) {\n return\n }\n for (let n = state.bufferedIndex; n < state.buffered.length; ++n) {\n var _state$errored\n const { chunk, callback } = state.buffered[n]\n const len = state.objectMode ? 1 : chunk.length\n state.length -= len\n callback(\n (_state$errored = state.errored) !== null && _state$errored !== undefined\n ? _state$errored\n : new ERR_STREAM_DESTROYED('write')\n )\n }\n const onfinishCallbacks = state[kOnFinished].splice(0)\n for (let i = 0; i < onfinishCallbacks.length; i++) {\n var _state$errored2\n onfinishCallbacks[i](\n (_state$errored2 = state.errored) !== null && _state$errored2 !== undefined\n ? _state$errored2\n : new ERR_STREAM_DESTROYED('end')\n )\n }\n resetBuffer(state)\n}\n\n// If there's something in the buffer waiting, then process it.\nfunction clearBuffer(stream, state) {\n if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) {\n return\n }\n const { buffered, bufferedIndex, objectMode } = state\n const bufferedLength = buffered.length - bufferedIndex\n if (!bufferedLength) {\n return\n }\n let i = bufferedIndex\n state.bufferProcessing = true\n if (bufferedLength > 1 && stream._writev) {\n state.pendingcb -= bufferedLength - 1\n const callback = state.allNoop\n ? nop\n : (err) => {\n for (let n = i; n < buffered.length; ++n) {\n buffered[n].callback(err)\n }\n }\n // Make a copy of `buffered` if it's going to be used by `callback` above,\n // since `doWrite` will mutate the array.\n const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i)\n chunks.allBuffers = state.allBuffers\n doWrite(stream, state, true, state.length, chunks, '', callback)\n resetBuffer(state)\n } else {\n do {\n const { chunk, encoding, callback } = buffered[i]\n buffered[i++] = null\n const len = objectMode ? 1 : chunk.length\n doWrite(stream, state, false, len, chunk, encoding, callback)\n } while (i < buffered.length && !state.writing)\n if (i === buffered.length) {\n resetBuffer(state)\n } else if (i > 256) {\n buffered.splice(0, i)\n state.bufferedIndex = 0\n } else {\n state.bufferedIndex = i\n }\n }\n state.bufferProcessing = false\n}\nWritable.prototype._write = function (chunk, encoding, cb) {\n if (this._writev) {\n this._writev(\n [\n {\n chunk,\n encoding\n }\n ],\n cb\n )\n } else {\n throw new ERR_METHOD_NOT_IMPLEMENTED('_write()')\n }\n}\nWritable.prototype._writev = null\nWritable.prototype.end = function (chunk, encoding, cb) {\n const state = this._writableState\n if (typeof chunk === 'function') {\n cb = chunk\n chunk = null\n encoding = null\n } else if (typeof encoding === 'function') {\n cb = encoding\n encoding = null\n }\n let err\n if (chunk !== null && chunk !== undefined) {\n const ret = _write(this, chunk, encoding)\n if (ret instanceof Error) {\n err = ret\n }\n }\n\n // .end() fully uncorks.\n if (state.corked) {\n state.corked = 1\n this.uncork()\n }\n if (err) {\n // Do nothing...\n } else if (!state.errored && !state.ending) {\n // This is forgiving in terms of unnecessary calls to end() and can hide\n // logic errors. However, usually such errors are harmless and causing a\n // hard error can be disproportionately destructive. It is not always\n // trivial for the user to determine whether end() needs to be called\n // or not.\n\n state.ending = true\n finishMaybe(this, state, true)\n state.ended = true\n } else if (state.finished) {\n err = new ERR_STREAM_ALREADY_FINISHED('end')\n } else if (state.destroyed) {\n err = new ERR_STREAM_DESTROYED('end')\n }\n if (typeof cb === 'function') {\n if (err || state.finished) {\n process.nextTick(cb, err)\n } else {\n state[kOnFinished].push(cb)\n }\n }\n return this\n}\nfunction needFinish(state) {\n return (\n state.ending &&\n !state.destroyed &&\n state.constructed &&\n state.length === 0 &&\n !state.errored &&\n state.buffered.length === 0 &&\n !state.finished &&\n !state.writing &&\n !state.errorEmitted &&\n !state.closeEmitted\n )\n}\nfunction callFinal(stream, state) {\n let called = false\n function onFinish(err) {\n if (called) {\n errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK())\n return\n }\n called = true\n state.pendingcb--\n if (err) {\n const onfinishCallbacks = state[kOnFinished].splice(0)\n for (let i = 0; i < onfinishCallbacks.length; i++) {\n onfinishCallbacks[i](err)\n }\n errorOrDestroy(stream, err, state.sync)\n } else if (needFinish(state)) {\n state.prefinished = true\n stream.emit('prefinish')\n // Backwards compat. Don't check state.sync here.\n // Some streams assume 'finish' will be emitted\n // asynchronously relative to _final callback.\n state.pendingcb++\n process.nextTick(finish, stream, state)\n }\n }\n state.sync = true\n state.pendingcb++\n try {\n stream._final(onFinish)\n } catch (err) {\n onFinish(err)\n }\n state.sync = false\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.finalCalled = true\n callFinal(stream, state)\n } else {\n state.prefinished = true\n stream.emit('prefinish')\n }\n }\n}\nfunction finishMaybe(stream, state, sync) {\n if (needFinish(state)) {\n prefinish(stream, state)\n if (state.pendingcb === 0) {\n if (sync) {\n state.pendingcb++\n process.nextTick(\n (stream, state) => {\n if (needFinish(state)) {\n finish(stream, state)\n } else {\n state.pendingcb--\n }\n },\n stream,\n state\n )\n } else if (needFinish(state)) {\n state.pendingcb++\n finish(stream, state)\n }\n }\n }\n}\nfunction finish(stream, state) {\n state.pendingcb--\n state.finished = true\n const onfinishCallbacks = state[kOnFinished].splice(0)\n for (let i = 0; i < onfinishCallbacks.length; i++) {\n onfinishCallbacks[i]()\n }\n stream.emit('finish')\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well.\n const rState = stream._readableState\n const autoDestroy =\n !rState ||\n (rState.autoDestroy &&\n // We don't expect the readable to ever 'end'\n // if readable is explicitly set to false.\n (rState.endEmitted || rState.readable === false))\n if (autoDestroy) {\n stream.destroy()\n }\n }\n}\nObjectDefineProperties(Writable.prototype, {\n closed: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.closed : false\n }\n },\n destroyed: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.destroyed : false\n },\n set(value) {\n // Backward compatibility, the user is explicitly managing destroyed.\n if (this._writableState) {\n this._writableState.destroyed = value\n }\n }\n },\n writable: {\n __proto__: null,\n get() {\n const w = this._writableState\n // w.writable === false means that this is part of a Duplex stream\n // where the writable side was disabled upon construction.\n // Compat. The user might manually disable writable side through\n // deprecated setter.\n return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended\n },\n set(val) {\n // Backwards compatible.\n if (this._writableState) {\n this._writableState.writable = !!val\n }\n }\n },\n writableFinished: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.finished : false\n }\n },\n writableObjectMode: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.objectMode : false\n }\n },\n writableBuffer: {\n __proto__: null,\n get() {\n return this._writableState && this._writableState.getBuffer()\n }\n },\n writableEnded: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.ending : false\n }\n },\n writableNeedDrain: {\n __proto__: null,\n get() {\n const wState = this._writableState\n if (!wState) return false\n return !wState.destroyed && !wState.ending && wState.needDrain\n }\n },\n writableHighWaterMark: {\n __proto__: null,\n get() {\n return this._writableState && this._writableState.highWaterMark\n }\n },\n writableCorked: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.corked : 0\n }\n },\n writableLength: {\n __proto__: null,\n get() {\n return this._writableState && this._writableState.length\n }\n },\n errored: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._writableState ? this._writableState.errored : null\n }\n },\n writableAborted: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return !!(\n this._writableState.writable !== false &&\n (this._writableState.destroyed || this._writableState.errored) &&\n !this._writableState.finished\n )\n }\n }\n})\nconst destroy = destroyImpl.destroy\nWritable.prototype.destroy = function (err, cb) {\n const state = this._writableState\n\n // Invoke pending callbacks.\n if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) {\n process.nextTick(errorBuffer, state)\n }\n destroy.call(this, err, cb)\n return this\n}\nWritable.prototype._undestroy = destroyImpl.undestroy\nWritable.prototype._destroy = function (err, cb) {\n cb(err)\n}\nWritable.prototype[EE.captureRejectionSymbol] = function (err) {\n this.destroy(err)\n}\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n return webStreamsAdapters\n}\nWritable.fromWeb = function (writableStream, options) {\n return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options)\n}\nWritable.toWeb = function (streamWritable) {\n return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable)\n}\n","/* eslint jsdoc/require-jsdoc: \"error\" */\n\n'use strict'\n\nconst {\n ArrayIsArray,\n ArrayPrototypeIncludes,\n ArrayPrototypeJoin,\n ArrayPrototypeMap,\n NumberIsInteger,\n NumberIsNaN,\n NumberMAX_SAFE_INTEGER,\n NumberMIN_SAFE_INTEGER,\n NumberParseInt,\n ObjectPrototypeHasOwnProperty,\n RegExpPrototypeExec,\n String,\n StringPrototypeToUpperCase,\n StringPrototypeTrim\n} = require('../ours/primordials')\nconst {\n hideStackFrames,\n codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL }\n} = require('../ours/errors')\nconst { normalizeEncoding } = require('../ours/util')\nconst { isAsyncFunction, isArrayBufferView } = require('../ours/util').types\nconst signals = {}\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nfunction isInt32(value) {\n return value === (value | 0)\n}\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nfunction isUint32(value) {\n return value === value >>> 0\n}\nconst octalReg = /^[0-7]+$/\nconst modeDesc = 'must be a 32-bit unsigned integer or an octal string'\n\n/**\n * Parse and validate values that will be converted into mode_t (the S_*\n * constants). Only valid numbers and octal strings are allowed. They could be\n * converted to 32-bit unsigned integers or non-negative signed integers in the\n * C++ land, but any value higher than 0o777 will result in platform-specific\n * behaviors.\n * @param {*} value Values to be validated\n * @param {string} name Name of the argument\n * @param {number} [def] If specified, will be returned for invalid values\n * @returns {number}\n */\nfunction parseFileMode(value, name, def) {\n if (typeof value === 'undefined') {\n value = def\n }\n if (typeof value === 'string') {\n if (RegExpPrototypeExec(octalReg, value) === null) {\n throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc)\n }\n value = NumberParseInt(value, 8)\n }\n validateUint32(value, name)\n return value\n}\n\n/**\n * @callback validateInteger\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateInteger} */\nconst validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => {\n if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n})\n\n/**\n * @callback validateInt32\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateInt32} */\nconst validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => {\n // The defaults for min and max correspond to the limits of 32-bit integers.\n if (typeof value !== 'number') {\n throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n if (!NumberIsInteger(value)) {\n throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n }\n if (value < min || value > max) {\n throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n }\n})\n\n/**\n * @callback validateUint32\n * @param {*} value\n * @param {string} name\n * @param {number|boolean} [positive=false]\n * @returns {asserts value is number}\n */\n\n/** @type {validateUint32} */\nconst validateUint32 = hideStackFrames((value, name, positive = false) => {\n if (typeof value !== 'number') {\n throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n if (!NumberIsInteger(value)) {\n throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n }\n const min = positive ? 1 : 0\n // 2 ** 32 === 4294967296\n const max = 4294967295\n if (value < min || value > max) {\n throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n }\n})\n\n/**\n * @callback validateString\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is string}\n */\n\n/** @type {validateString} */\nfunction validateString(value, name) {\n if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value)\n}\n\n/**\n * @callback validateNumber\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateNumber} */\nfunction validateNumber(value, name, min = undefined, max) {\n if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n if (\n (min != null && value < min) ||\n (max != null && value > max) ||\n ((min != null || max != null) && NumberIsNaN(value))\n ) {\n throw new ERR_OUT_OF_RANGE(\n name,\n `${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`,\n value\n )\n }\n}\n\n/**\n * @callback validateOneOf\n * @template T\n * @param {T} value\n * @param {string} name\n * @param {T[]} oneOf\n */\n\n/** @type {validateOneOf} */\nconst validateOneOf = hideStackFrames((value, name, oneOf) => {\n if (!ArrayPrototypeIncludes(oneOf, value)) {\n const allowed = ArrayPrototypeJoin(\n ArrayPrototypeMap(oneOf, (v) => (typeof v === 'string' ? `'${v}'` : String(v))),\n ', '\n )\n const reason = 'must be one of: ' + allowed\n throw new ERR_INVALID_ARG_VALUE(name, value, reason)\n }\n})\n\n/**\n * @callback validateBoolean\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is boolean}\n */\n\n/** @type {validateBoolean} */\nfunction validateBoolean(value, name) {\n if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value)\n}\n\n/**\n * @param {any} options\n * @param {string} key\n * @param {boolean} defaultValue\n * @returns {boolean}\n */\nfunction getOwnPropertyValueOrDefault(options, key, defaultValue) {\n return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key]\n}\n\n/**\n * @callback validateObject\n * @param {*} value\n * @param {string} name\n * @param {{\n * allowArray?: boolean,\n * allowFunction?: boolean,\n * nullable?: boolean\n * }} [options]\n */\n\n/** @type {validateObject} */\nconst validateObject = hideStackFrames((value, name, options = null) => {\n const allowArray = getOwnPropertyValueOrDefault(options, 'allowArray', false)\n const allowFunction = getOwnPropertyValueOrDefault(options, 'allowFunction', false)\n const nullable = getOwnPropertyValueOrDefault(options, 'nullable', false)\n if (\n (!nullable && value === null) ||\n (!allowArray && ArrayIsArray(value)) ||\n (typeof value !== 'object' && (!allowFunction || typeof value !== 'function'))\n ) {\n throw new ERR_INVALID_ARG_TYPE(name, 'Object', value)\n }\n})\n\n/**\n * @callback validateDictionary - We are using the Web IDL Standard definition\n * of \"dictionary\" here, which means any value\n * whose Type is either Undefined, Null, or\n * Object (which includes functions).\n * @param {*} value\n * @param {string} name\n * @see https://webidl.spec.whatwg.org/#es-dictionary\n * @see https://tc39.es/ecma262/#table-typeof-operator-results\n */\n\n/** @type {validateDictionary} */\nconst validateDictionary = hideStackFrames((value, name) => {\n if (value != null && typeof value !== 'object' && typeof value !== 'function') {\n throw new ERR_INVALID_ARG_TYPE(name, 'a dictionary', value)\n }\n})\n\n/**\n * @callback validateArray\n * @param {*} value\n * @param {string} name\n * @param {number} [minLength]\n * @returns {asserts value is any[]}\n */\n\n/** @type {validateArray} */\nconst validateArray = hideStackFrames((value, name, minLength = 0) => {\n if (!ArrayIsArray(value)) {\n throw new ERR_INVALID_ARG_TYPE(name, 'Array', value)\n }\n if (value.length < minLength) {\n const reason = `must be longer than ${minLength}`\n throw new ERR_INVALID_ARG_VALUE(name, value, reason)\n }\n})\n\n/**\n * @callback validateStringArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is string[]}\n */\n\n/** @type {validateStringArray} */\nfunction validateStringArray(value, name) {\n validateArray(value, name)\n for (let i = 0; i < value.length; i++) {\n validateString(value[i], `${name}[${i}]`)\n }\n}\n\n/**\n * @callback validateBooleanArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is boolean[]}\n */\n\n/** @type {validateBooleanArray} */\nfunction validateBooleanArray(value, name) {\n validateArray(value, name)\n for (let i = 0; i < value.length; i++) {\n validateBoolean(value[i], `${name}[${i}]`)\n }\n}\n\n/**\n * @callback validateAbortSignalArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is AbortSignal[]}\n */\n\n/** @type {validateAbortSignalArray} */\nfunction validateAbortSignalArray(value, name) {\n validateArray(value, name)\n for (let i = 0; i < value.length; i++) {\n const signal = value[i]\n const indexedName = `${name}[${i}]`\n if (signal == null) {\n throw new ERR_INVALID_ARG_TYPE(indexedName, 'AbortSignal', signal)\n }\n validateAbortSignal(signal, indexedName)\n }\n}\n\n/**\n * @param {*} signal\n * @param {string} [name='signal']\n * @returns {asserts signal is keyof signals}\n */\nfunction validateSignalName(signal, name = 'signal') {\n validateString(signal, name)\n if (signals[signal] === undefined) {\n if (signals[StringPrototypeToUpperCase(signal)] !== undefined) {\n throw new ERR_UNKNOWN_SIGNAL(signal + ' (signals must use all capital letters)')\n }\n throw new ERR_UNKNOWN_SIGNAL(signal)\n }\n}\n\n/**\n * @callback validateBuffer\n * @param {*} buffer\n * @param {string} [name='buffer']\n * @returns {asserts buffer is ArrayBufferView}\n */\n\n/** @type {validateBuffer} */\nconst validateBuffer = hideStackFrames((buffer, name = 'buffer') => {\n if (!isArrayBufferView(buffer)) {\n throw new ERR_INVALID_ARG_TYPE(name, ['Buffer', 'TypedArray', 'DataView'], buffer)\n }\n})\n\n/**\n * @param {string} data\n * @param {string} encoding\n */\nfunction validateEncoding(data, encoding) {\n const normalizedEncoding = normalizeEncoding(encoding)\n const length = data.length\n if (normalizedEncoding === 'hex' && length % 2 !== 0) {\n throw new ERR_INVALID_ARG_VALUE('encoding', encoding, `is invalid for data of length ${length}`)\n }\n}\n\n/**\n * Check that the port number is not NaN when coerced to a number,\n * is an integer and that it falls within the legal range of port numbers.\n * @param {*} port\n * @param {string} [name='Port']\n * @param {boolean} [allowZero=true]\n * @returns {number}\n */\nfunction validatePort(port, name = 'Port', allowZero = true) {\n if (\n (typeof port !== 'number' && typeof port !== 'string') ||\n (typeof port === 'string' && StringPrototypeTrim(port).length === 0) ||\n +port !== +port >>> 0 ||\n port > 0xffff ||\n (port === 0 && !allowZero)\n ) {\n throw new ERR_SOCKET_BAD_PORT(name, port, allowZero)\n }\n return port | 0\n}\n\n/**\n * @callback validateAbortSignal\n * @param {*} signal\n * @param {string} name\n */\n\n/** @type {validateAbortSignal} */\nconst validateAbortSignal = hideStackFrames((signal, name) => {\n if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {\n throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n }\n})\n\n/**\n * @callback validateFunction\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is Function}\n */\n\n/** @type {validateFunction} */\nconst validateFunction = hideStackFrames((value, name) => {\n if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n})\n\n/**\n * @callback validatePlainFunction\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is Function}\n */\n\n/** @type {validatePlainFunction} */\nconst validatePlainFunction = hideStackFrames((value, name) => {\n if (typeof value !== 'function' || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n})\n\n/**\n * @callback validateUndefined\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is undefined}\n */\n\n/** @type {validateUndefined} */\nconst validateUndefined = hideStackFrames((value, name) => {\n if (value !== undefined) throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value)\n})\n\n/**\n * @template T\n * @param {T} value\n * @param {string} name\n * @param {T[]} union\n */\nfunction validateUnion(value, name, union) {\n if (!ArrayPrototypeIncludes(union, value)) {\n throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value)\n }\n}\n\n/*\n The rules for the Link header field are described here:\n https://www.rfc-editor.org/rfc/rfc8288.html#section-3\n\n This regex validates any string surrounded by angle brackets\n (not necessarily a valid URI reference) followed by zero or more\n link-params separated by semicolons.\n*/\nconst linkValueRegExp = /^(?:<[^>]*>)(?:\\s*;\\s*[^;\"\\s]+(?:=(\")?[^;\"\\s]*\\1)?)*$/\n\n/**\n * @param {any} value\n * @param {string} name\n */\nfunction validateLinkHeaderFormat(value, name) {\n if (typeof value === 'undefined' || !RegExpPrototypeExec(linkValueRegExp, value)) {\n throw new ERR_INVALID_ARG_VALUE(\n name,\n value,\n 'must be an array or string of format \"; rel=preload; as=style\"'\n )\n }\n}\n\n/**\n * @param {any} hints\n * @return {string}\n */\nfunction validateLinkHeaderValue(hints) {\n if (typeof hints === 'string') {\n validateLinkHeaderFormat(hints, 'hints')\n return hints\n } else if (ArrayIsArray(hints)) {\n const hintsLength = hints.length\n let result = ''\n if (hintsLength === 0) {\n return result\n }\n for (let i = 0; i < hintsLength; i++) {\n const link = hints[i]\n validateLinkHeaderFormat(link, 'hints')\n result += link\n if (i !== hintsLength - 1) {\n result += ', '\n }\n }\n return result\n }\n throw new ERR_INVALID_ARG_VALUE(\n 'hints',\n hints,\n 'must be an array or string of format \"; rel=preload; as=style\"'\n )\n}\nmodule.exports = {\n isInt32,\n isUint32,\n parseFileMode,\n validateArray,\n validateStringArray,\n validateBooleanArray,\n validateAbortSignalArray,\n validateBoolean,\n validateBuffer,\n validateDictionary,\n validateEncoding,\n validateFunction,\n validateInt32,\n validateInteger,\n validateNumber,\n validateObject,\n validateOneOf,\n validatePlainFunction,\n validatePort,\n validateSignalName,\n validateString,\n validateUint32,\n validateUndefined,\n validateUnion,\n validateAbortSignal,\n validateLinkHeaderValue\n}\n","'use strict'\n\nconst CustomStream = require('../stream')\nconst promises = require('../stream/promises')\nconst originalDestroy = CustomStream.Readable.destroy\nmodule.exports = CustomStream.Readable\n\n// Explicit export naming is needed for ESM\nmodule.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer\nmodule.exports._isUint8Array = CustomStream._isUint8Array\nmodule.exports.isDisturbed = CustomStream.isDisturbed\nmodule.exports.isErrored = CustomStream.isErrored\nmodule.exports.isReadable = CustomStream.isReadable\nmodule.exports.Readable = CustomStream.Readable\nmodule.exports.Writable = CustomStream.Writable\nmodule.exports.Duplex = CustomStream.Duplex\nmodule.exports.Transform = CustomStream.Transform\nmodule.exports.PassThrough = CustomStream.PassThrough\nmodule.exports.addAbortSignal = CustomStream.addAbortSignal\nmodule.exports.finished = CustomStream.finished\nmodule.exports.destroy = CustomStream.destroy\nmodule.exports.destroy = originalDestroy\nmodule.exports.pipeline = CustomStream.pipeline\nmodule.exports.compose = CustomStream.compose\nObject.defineProperty(CustomStream, 'promises', {\n configurable: true,\n enumerable: true,\n get() {\n return promises\n }\n})\nmodule.exports.Stream = CustomStream.Stream\n\n// Allow default importing\nmodule.exports.default = module.exports\n","'use strict'\n\nconst { format, inspect, AggregateError: CustomAggregateError } = require('./util')\n\n/*\n This file is a reduced and adapted version of the main lib/internal/errors.js file defined at\n\n https://github.com/nodejs/node/blob/master/lib/internal/errors.js\n\n Don't try to replace with the original file and keep it up to date (starting from E(...) definitions)\n with the upstream file.\n*/\n\nconst AggregateError = globalThis.AggregateError || CustomAggregateError\nconst kIsNodeError = Symbol('kIsNodeError')\nconst kTypes = [\n 'string',\n 'function',\n 'number',\n 'object',\n // Accept 'Function' and 'Object' as alternative to the lower cased version.\n 'Function',\n 'Object',\n 'boolean',\n 'bigint',\n 'symbol'\n]\nconst classRegExp = /^([A-Z][a-z0-9]*)+$/\nconst nodeInternalPrefix = '__node_internal_'\nconst codes = {}\nfunction assert(value, message) {\n if (!value) {\n throw new codes.ERR_INTERNAL_ASSERTION(message)\n }\n}\n\n// Only use this for integers! Decimal numbers do not work with this function.\nfunction addNumericalSeparator(val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\nfunction getMessage(key, msg, args) {\n if (typeof msg === 'function') {\n assert(\n msg.length <= args.length,\n // Default options do not count.\n `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`\n )\n return msg(...args)\n }\n const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length\n assert(\n expectedLength === args.length,\n `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`\n )\n if (args.length === 0) {\n return msg\n }\n return format(msg, ...args)\n}\nfunction E(code, message, Base) {\n if (!Base) {\n Base = Error\n }\n class NodeError extends Base {\n constructor(...args) {\n super(getMessage(code, message, args))\n }\n toString() {\n return `${this.name} [${code}]: ${this.message}`\n }\n }\n Object.defineProperties(NodeError.prototype, {\n name: {\n value: Base.name,\n writable: true,\n enumerable: false,\n configurable: true\n },\n toString: {\n value() {\n return `${this.name} [${code}]: ${this.message}`\n },\n writable: true,\n enumerable: false,\n configurable: true\n }\n })\n NodeError.prototype.code = code\n NodeError.prototype[kIsNodeError] = true\n codes[code] = NodeError\n}\nfunction hideStackFrames(fn) {\n // We rename the functions that will be hidden to cut off the stacktrace\n // at the outermost one\n const hidden = nodeInternalPrefix + fn.name\n Object.defineProperty(fn, 'name', {\n value: hidden\n })\n return fn\n}\nfunction aggregateTwoErrors(innerError, outerError) {\n if (innerError && outerError && innerError !== outerError) {\n if (Array.isArray(outerError.errors)) {\n // If `outerError` is already an `AggregateError`.\n outerError.errors.push(innerError)\n return outerError\n }\n const err = new AggregateError([outerError, innerError], outerError.message)\n err.code = outerError.code\n return err\n }\n return innerError || outerError\n}\nclass AbortError extends Error {\n constructor(message = 'The operation was aborted', options = undefined) {\n if (options !== undefined && typeof options !== 'object') {\n throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options)\n }\n super(message, options)\n this.code = 'ABORT_ERR'\n this.name = 'AbortError'\n }\n}\nE('ERR_ASSERTION', '%s', Error)\nE(\n 'ERR_INVALID_ARG_TYPE',\n (name, expected, actual) => {\n assert(typeof name === 'string', \"'name' must be a string\")\n if (!Array.isArray(expected)) {\n expected = [expected]\n }\n let msg = 'The '\n if (name.endsWith(' argument')) {\n // For cases like 'first argument'\n msg += `${name} `\n } else {\n msg += `\"${name}\" ${name.includes('.') ? 'property' : 'argument'} `\n }\n msg += 'must be '\n const types = []\n const instances = []\n const other = []\n for (const value of expected) {\n assert(typeof value === 'string', 'All expected entries have to be of type string')\n if (kTypes.includes(value)) {\n types.push(value.toLowerCase())\n } else if (classRegExp.test(value)) {\n instances.push(value)\n } else {\n assert(value !== 'object', 'The value \"object\" should be written as \"Object\"')\n other.push(value)\n }\n }\n\n // Special handle `object` in case other instances are allowed to outline\n // the differences between each other.\n if (instances.length > 0) {\n const pos = types.indexOf('object')\n if (pos !== -1) {\n types.splice(types, pos, 1)\n instances.push('Object')\n }\n }\n if (types.length > 0) {\n switch (types.length) {\n case 1:\n msg += `of type ${types[0]}`\n break\n case 2:\n msg += `one of type ${types[0]} or ${types[1]}`\n break\n default: {\n const last = types.pop()\n msg += `one of type ${types.join(', ')}, or ${last}`\n }\n }\n if (instances.length > 0 || other.length > 0) {\n msg += ' or '\n }\n }\n if (instances.length > 0) {\n switch (instances.length) {\n case 1:\n msg += `an instance of ${instances[0]}`\n break\n case 2:\n msg += `an instance of ${instances[0]} or ${instances[1]}`\n break\n default: {\n const last = instances.pop()\n msg += `an instance of ${instances.join(', ')}, or ${last}`\n }\n }\n if (other.length > 0) {\n msg += ' or '\n }\n }\n switch (other.length) {\n case 0:\n break\n case 1:\n if (other[0].toLowerCase() !== other[0]) {\n msg += 'an '\n }\n msg += `${other[0]}`\n break\n case 2:\n msg += `one of ${other[0]} or ${other[1]}`\n break\n default: {\n const last = other.pop()\n msg += `one of ${other.join(', ')}, or ${last}`\n }\n }\n if (actual == null) {\n msg += `. Received ${actual}`\n } else if (typeof actual === 'function' && actual.name) {\n msg += `. Received function ${actual.name}`\n } else if (typeof actual === 'object') {\n var _actual$constructor\n if (\n (_actual$constructor = actual.constructor) !== null &&\n _actual$constructor !== undefined &&\n _actual$constructor.name\n ) {\n msg += `. Received an instance of ${actual.constructor.name}`\n } else {\n const inspected = inspect(actual, {\n depth: -1\n })\n msg += `. Received ${inspected}`\n }\n } else {\n let inspected = inspect(actual, {\n colors: false\n })\n if (inspected.length > 25) {\n inspected = `${inspected.slice(0, 25)}...`\n }\n msg += `. Received type ${typeof actual} (${inspected})`\n }\n return msg\n },\n TypeError\n)\nE(\n 'ERR_INVALID_ARG_VALUE',\n (name, value, reason = 'is invalid') => {\n let inspected = inspect(value)\n if (inspected.length > 128) {\n inspected = inspected.slice(0, 128) + '...'\n }\n const type = name.includes('.') ? 'property' : 'argument'\n return `The ${type} '${name}' ${reason}. Received ${inspected}`\n },\n TypeError\n)\nE(\n 'ERR_INVALID_RETURN_VALUE',\n (input, name, value) => {\n var _value$constructor\n const type =\n value !== null &&\n value !== undefined &&\n (_value$constructor = value.constructor) !== null &&\n _value$constructor !== undefined &&\n _value$constructor.name\n ? `instance of ${value.constructor.name}`\n : `type ${typeof value}`\n return `Expected ${input} to be returned from the \"${name}\"` + ` function but got ${type}.`\n },\n TypeError\n)\nE(\n 'ERR_MISSING_ARGS',\n (...args) => {\n assert(args.length > 0, 'At least one arg needs to be specified')\n let msg\n const len = args.length\n args = (Array.isArray(args) ? args : [args]).map((a) => `\"${a}\"`).join(' or ')\n switch (len) {\n case 1:\n msg += `The ${args[0]} argument`\n break\n case 2:\n msg += `The ${args[0]} and ${args[1]} arguments`\n break\n default:\n {\n const last = args.pop()\n msg += `The ${args.join(', ')}, and ${last} arguments`\n }\n break\n }\n return `${msg} must be specified`\n },\n TypeError\n)\nE(\n 'ERR_OUT_OF_RANGE',\n (str, range, input) => {\n assert(range, 'Missing \"range\" argument')\n let received\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > 2n ** 32n || input < -(2n ** 32n)) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n } else {\n received = inspect(input)\n }\n return `The value of \"${str}\" is out of range. It must be ${range}. Received ${received}`\n },\n RangeError\n)\nE('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error)\nE('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error)\nE('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error)\nE('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error)\nE('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error)\nE('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError)\nE('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error)\nE('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error)\nE('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error)\nE('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error)\nE('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError)\nmodule.exports = {\n AbortError,\n aggregateTwoErrors: hideStackFrames(aggregateTwoErrors),\n hideStackFrames,\n codes\n}\n","'use strict'\n\n/*\n This file is a reduced and adapted version of the main lib/internal/per_context/primordials.js file defined at\n\n https://github.com/nodejs/node/blob/master/lib/internal/per_context/primordials.js\n\n Don't try to replace with the original file and keep it up to date with the upstream file.\n*/\nmodule.exports = {\n ArrayIsArray(self) {\n return Array.isArray(self)\n },\n ArrayPrototypeIncludes(self, el) {\n return self.includes(el)\n },\n ArrayPrototypeIndexOf(self, el) {\n return self.indexOf(el)\n },\n ArrayPrototypeJoin(self, sep) {\n return self.join(sep)\n },\n ArrayPrototypeMap(self, fn) {\n return self.map(fn)\n },\n ArrayPrototypePop(self, el) {\n return self.pop(el)\n },\n ArrayPrototypePush(self, el) {\n return self.push(el)\n },\n ArrayPrototypeSlice(self, start, end) {\n return self.slice(start, end)\n },\n Error,\n FunctionPrototypeCall(fn, thisArgs, ...args) {\n return fn.call(thisArgs, ...args)\n },\n FunctionPrototypeSymbolHasInstance(self, instance) {\n return Function.prototype[Symbol.hasInstance].call(self, instance)\n },\n MathFloor: Math.floor,\n Number,\n NumberIsInteger: Number.isInteger,\n NumberIsNaN: Number.isNaN,\n NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,\n NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,\n NumberParseInt: Number.parseInt,\n ObjectDefineProperties(self, props) {\n return Object.defineProperties(self, props)\n },\n ObjectDefineProperty(self, name, prop) {\n return Object.defineProperty(self, name, prop)\n },\n ObjectGetOwnPropertyDescriptor(self, name) {\n return Object.getOwnPropertyDescriptor(self, name)\n },\n ObjectKeys(obj) {\n return Object.keys(obj)\n },\n ObjectSetPrototypeOf(target, proto) {\n return Object.setPrototypeOf(target, proto)\n },\n Promise,\n PromisePrototypeCatch(self, fn) {\n return self.catch(fn)\n },\n PromisePrototypeThen(self, thenFn, catchFn) {\n return self.then(thenFn, catchFn)\n },\n PromiseReject(err) {\n return Promise.reject(err)\n },\n PromiseResolve(val) {\n return Promise.resolve(val)\n },\n ReflectApply: Reflect.apply,\n RegExpPrototypeTest(self, value) {\n return self.test(value)\n },\n SafeSet: Set,\n String,\n StringPrototypeSlice(self, start, end) {\n return self.slice(start, end)\n },\n StringPrototypeToLowerCase(self) {\n return self.toLowerCase()\n },\n StringPrototypeToUpperCase(self) {\n return self.toUpperCase()\n },\n StringPrototypeTrim(self) {\n return self.trim()\n },\n Symbol,\n SymbolFor: Symbol.for,\n SymbolAsyncIterator: Symbol.asyncIterator,\n SymbolHasInstance: Symbol.hasInstance,\n SymbolIterator: Symbol.iterator,\n SymbolDispose: Symbol.dispose || Symbol('Symbol.dispose'),\n SymbolAsyncDispose: Symbol.asyncDispose || Symbol('Symbol.asyncDispose'),\n TypedArrayPrototypeSet(self, buf, len) {\n return self.set(buf, len)\n },\n Boolean: Boolean,\n Uint8Array\n}\n","'use strict'\n\nconst bufferModule = require('buffer')\nconst { kResistStopPropagation, SymbolDispose } = require('./primordials')\nconst AbortSignal = globalThis.AbortSignal || require('abort-controller').AbortSignal\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst AsyncFunction = Object.getPrototypeOf(async function () {}).constructor\nconst Blob = globalThis.Blob || bufferModule.Blob\n/* eslint-disable indent */\nconst isBlob =\n typeof Blob !== 'undefined'\n ? function isBlob(b) {\n // eslint-disable-next-line indent\n return b instanceof Blob\n }\n : function isBlob(b) {\n return false\n }\n/* eslint-enable indent */\n\nconst validateAbortSignal = (signal, name) => {\n if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {\n throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n }\n}\nconst validateFunction = (value, name) => {\n if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n}\n\n// This is a simplified version of AggregateError\nclass AggregateError extends Error {\n constructor(errors) {\n if (!Array.isArray(errors)) {\n throw new TypeError(`Expected input to be an Array, got ${typeof errors}`)\n }\n let message = ''\n for (let i = 0; i < errors.length; i++) {\n message += ` ${errors[i].stack}\\n`\n }\n super(message)\n this.name = 'AggregateError'\n this.errors = errors\n }\n}\nmodule.exports = {\n AggregateError,\n kEmptyObject: Object.freeze({}),\n once(callback) {\n let called = false\n return function (...args) {\n if (called) {\n return\n }\n called = true\n callback.apply(this, args)\n }\n },\n createDeferredPromise: function () {\n let resolve\n let reject\n\n // eslint-disable-next-line promise/param-names\n const promise = new Promise((res, rej) => {\n resolve = res\n reject = rej\n })\n return {\n promise,\n resolve,\n reject\n }\n },\n promisify(fn) {\n return new Promise((resolve, reject) => {\n fn((err, ...args) => {\n if (err) {\n return reject(err)\n }\n return resolve(...args)\n })\n })\n },\n debuglog() {\n return function () {}\n },\n format(format, ...args) {\n // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args\n return format.replace(/%([sdifj])/g, function (...[_unused, type]) {\n const replacement = args.shift()\n if (type === 'f') {\n return replacement.toFixed(6)\n } else if (type === 'j') {\n return JSON.stringify(replacement)\n } else if (type === 's' && typeof replacement === 'object') {\n const ctor = replacement.constructor !== Object ? replacement.constructor.name : ''\n return `${ctor} {}`.trim()\n } else {\n return replacement.toString()\n }\n })\n },\n inspect(value) {\n // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options\n switch (typeof value) {\n case 'string':\n if (value.includes(\"'\")) {\n if (!value.includes('\"')) {\n return `\"${value}\"`\n } else if (!value.includes('`') && !value.includes('${')) {\n return `\\`${value}\\``\n }\n }\n return `'${value}'`\n case 'number':\n if (isNaN(value)) {\n return 'NaN'\n } else if (Object.is(value, -0)) {\n return String(value)\n }\n return value\n case 'bigint':\n return `${String(value)}n`\n case 'boolean':\n case 'undefined':\n return String(value)\n case 'object':\n return '{}'\n }\n },\n types: {\n isAsyncFunction(fn) {\n return fn instanceof AsyncFunction\n },\n isArrayBufferView(arr) {\n return ArrayBuffer.isView(arr)\n }\n },\n isBlob,\n deprecate(fn, message) {\n return fn\n },\n addAbortListener:\n require('events').addAbortListener ||\n function addAbortListener(signal, listener) {\n if (signal === undefined) {\n throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal)\n }\n validateAbortSignal(signal, 'signal')\n validateFunction(listener, 'listener')\n let removeEventListener\n if (signal.aborted) {\n queueMicrotask(() => listener())\n } else {\n signal.addEventListener('abort', listener, {\n __proto__: null,\n once: true,\n [kResistStopPropagation]: true\n })\n removeEventListener = () => {\n signal.removeEventListener('abort', listener)\n }\n }\n return {\n __proto__: null,\n [SymbolDispose]() {\n var _removeEventListener\n ;(_removeEventListener = removeEventListener) === null || _removeEventListener === undefined\n ? undefined\n : _removeEventListener()\n }\n }\n },\n AbortSignalAny:\n AbortSignal.any ||\n function AbortSignalAny(signals) {\n // Fast path if there is only one signal.\n if (signals.length === 1) {\n return signals[0]\n }\n const ac = new AbortController()\n const abort = () => ac.abort()\n signals.forEach((signal) => {\n validateAbortSignal(signal, 'signals')\n signal.addEventListener('abort', abort, {\n once: true\n })\n })\n ac.signal.addEventListener(\n 'abort',\n () => {\n signals.forEach((signal) => signal.removeEventListener('abort', abort))\n },\n {\n once: true\n }\n )\n return ac.signal\n }\n}\nmodule.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom')\n","/* replacement start */\n\nconst { Buffer } = require('buffer')\n\n/* replacement end */\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n;('use strict')\nconst { ObjectDefineProperty, ObjectKeys, ReflectApply } = require('./ours/primordials')\nconst {\n promisify: { custom: customPromisify }\n} = require('./ours/util')\nconst { streamReturningOperators, promiseReturningOperators } = require('./internal/streams/operators')\nconst {\n codes: { ERR_ILLEGAL_CONSTRUCTOR }\n} = require('./ours/errors')\nconst compose = require('./internal/streams/compose')\nconst { setDefaultHighWaterMark, getDefaultHighWaterMark } = require('./internal/streams/state')\nconst { pipeline } = require('./internal/streams/pipeline')\nconst { destroyer } = require('./internal/streams/destroy')\nconst eos = require('./internal/streams/end-of-stream')\nconst internalBuffer = {}\nconst promises = require('./stream/promises')\nconst utils = require('./internal/streams/utils')\nconst Stream = (module.exports = require('./internal/streams/legacy').Stream)\nStream.isDestroyed = utils.isDestroyed\nStream.isDisturbed = utils.isDisturbed\nStream.isErrored = utils.isErrored\nStream.isReadable = utils.isReadable\nStream.isWritable = utils.isWritable\nStream.Readable = require('./internal/streams/readable')\nfor (const key of ObjectKeys(streamReturningOperators)) {\n const op = streamReturningOperators[key]\n function fn(...args) {\n if (new.target) {\n throw ERR_ILLEGAL_CONSTRUCTOR()\n }\n return Stream.Readable.from(ReflectApply(op, this, args))\n }\n ObjectDefineProperty(fn, 'name', {\n __proto__: null,\n value: op.name\n })\n ObjectDefineProperty(fn, 'length', {\n __proto__: null,\n value: op.length\n })\n ObjectDefineProperty(Stream.Readable.prototype, key, {\n __proto__: null,\n value: fn,\n enumerable: false,\n configurable: true,\n writable: true\n })\n}\nfor (const key of ObjectKeys(promiseReturningOperators)) {\n const op = promiseReturningOperators[key]\n function fn(...args) {\n if (new.target) {\n throw ERR_ILLEGAL_CONSTRUCTOR()\n }\n return ReflectApply(op, this, args)\n }\n ObjectDefineProperty(fn, 'name', {\n __proto__: null,\n value: op.name\n })\n ObjectDefineProperty(fn, 'length', {\n __proto__: null,\n value: op.length\n })\n ObjectDefineProperty(Stream.Readable.prototype, key, {\n __proto__: null,\n value: fn,\n enumerable: false,\n configurable: true,\n writable: true\n })\n}\nStream.Writable = require('./internal/streams/writable')\nStream.Duplex = require('./internal/streams/duplex')\nStream.Transform = require('./internal/streams/transform')\nStream.PassThrough = require('./internal/streams/passthrough')\nStream.pipeline = pipeline\nconst { addAbortSignal } = require('./internal/streams/add-abort-signal')\nStream.addAbortSignal = addAbortSignal\nStream.finished = eos\nStream.destroy = destroyer\nStream.compose = compose\nStream.setDefaultHighWaterMark = setDefaultHighWaterMark\nStream.getDefaultHighWaterMark = getDefaultHighWaterMark\nObjectDefineProperty(Stream, 'promises', {\n __proto__: null,\n configurable: true,\n enumerable: true,\n get() {\n return promises\n }\n})\nObjectDefineProperty(pipeline, customPromisify, {\n __proto__: null,\n enumerable: true,\n get() {\n return promises.pipeline\n }\n})\nObjectDefineProperty(eos, customPromisify, {\n __proto__: null,\n enumerable: true,\n get() {\n return promises.finished\n }\n})\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream\nStream._isUint8Array = function isUint8Array(value) {\n return value instanceof Uint8Array\n}\nStream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n}\n","'use strict'\n\nconst { ArrayPrototypePop, Promise } = require('../ours/primordials')\nconst { isIterable, isNodeStream, isWebStream } = require('../internal/streams/utils')\nconst { pipelineImpl: pl } = require('../internal/streams/pipeline')\nconst { finished } = require('../internal/streams/end-of-stream')\nrequire('../../lib/stream.js')\nfunction pipeline(...streams) {\n return new Promise((resolve, reject) => {\n let signal\n let end\n const lastArg = streams[streams.length - 1]\n if (\n lastArg &&\n typeof lastArg === 'object' &&\n !isNodeStream(lastArg) &&\n !isIterable(lastArg) &&\n !isWebStream(lastArg)\n ) {\n const options = ArrayPrototypePop(streams)\n signal = options.signal\n end = options.end\n }\n pl(\n streams,\n (err, value) => {\n if (err) {\n reject(err)\n } else {\n resolve(value)\n }\n },\n {\n signal,\n end\n }\n )\n })\n}\nmodule.exports = {\n finished,\n pipeline\n}\n","/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\n XSD = 'http://www.w3.org/2001/XMLSchema#',\n SWAP = 'http://www.w3.org/2000/10/swap/';\n\nexport default {\n xsd: {\n decimal: `${XSD}decimal`,\n boolean: `${XSD}boolean`,\n double: `${XSD}double`,\n integer: `${XSD}integer`,\n string: `${XSD}string`,\n },\n rdf: {\n type: `${RDF}type`,\n nil: `${RDF}nil`,\n first: `${RDF}first`,\n rest: `${RDF}rest`,\n langString: `${RDF}langString`,\n },\n owl: {\n sameAs: 'http://www.w3.org/2002/07/owl#sameAs',\n },\n r: {\n forSome: `${SWAP}reify#forSome`,\n forAll: `${SWAP}reify#forAll`,\n },\n log: {\n implies: `${SWAP}log#implies`,\n },\n};\n","// **N3Lexer** tokenizes N3 documents.\nimport { Buffer } from 'buffer';\nimport queueMicrotask from 'queue-microtask';\nimport namespaces from './IRIs';\n\nconst { xsd } = namespaces;\n\n// Regular expression and replacement string to escape N3 strings\nconst escapeSequence = /\\\\u([a-fA-F0-9]{4})|\\\\U([a-fA-F0-9]{8})|\\\\([^])/g;\nconst escapeReplacements = {\n '\\\\': '\\\\', \"'\": \"'\", '\"': '\"',\n 'n': '\\n', 'r': '\\r', 't': '\\t', 'f': '\\f', 'b': '\\b',\n '_': '_', '~': '~', '.': '.', '-': '-', '!': '!', '$': '$', '&': '&',\n '(': '(', ')': ')', '*': '*', '+': '+', ',': ',', ';': ';', '=': '=',\n '/': '/', '?': '?', '#': '#', '@': '@', '%': '%',\n};\nconst illegalIriChars = /[\\x00-\\x20<>\\\\\"\\{\\}\\|\\^\\`]/;\n\nconst lineModeRegExps = {\n _iri: true,\n _unescapedIri: true,\n _simpleQuotedString: true,\n _langcode: true,\n _blank: true,\n _newline: true,\n _comment: true,\n _whitespace: true,\n _endOfFile: true,\n};\nconst invalidRegExp = /$0^/;\n\n// ## Constructor\nexport default class N3Lexer {\n constructor(options) {\n // ## Regular expressions\n // It's slightly faster to have these as properties than as in-scope variables\n this._iri = /^<((?:[^ <>{}\\\\]|\\\\[uU])+)>[ \\t]*/; // IRI with escape sequences; needs sanity check after unescaping\n this._unescapedIri = /^<([^\\x00-\\x20<>\\\\\"\\{\\}\\|\\^\\`]*)>[ \\t]*/; // IRI without escape sequences; no unescaping\n this._simpleQuotedString = /^\"([^\"\\\\\\r\\n]*)\"(?=[^\"])/; // string without escape sequences\n this._simpleApostropheString = /^'([^'\\\\\\r\\n]*)'(?=[^'])/;\n this._langcode = /^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\\-])/i;\n this._prefix = /^((?:[A-Za-z\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02ff\\u0370-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff])(?:\\.?[\\-0-9A-Z_a-z\\xb7\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u203f\\u2040\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff])*)?:(?=[#\\s<])/;\n this._prefixed = /^((?:[A-Za-z\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02ff\\u0370-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff])(?:\\.?[\\-0-9A-Z_a-z\\xb7\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u203f\\u2040\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff])*)?:((?:(?:[0-:A-Z_a-z\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02ff\\u0370-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff]|%[0-9a-fA-F]{2}|\\\\[!#-\\/;=?\\-@_~])(?:(?:[\\.\\-0-:A-Z_a-z\\xb7\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u203f\\u2040\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff]|%[0-9a-fA-F]{2}|\\\\[!#-\\/;=?\\-@_~])*(?:[\\-0-:A-Z_a-z\\xb7\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u203f\\u2040\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff]|%[0-9a-fA-F]{2}|\\\\[!#-\\/;=?\\-@_~]))?)?)(?:[ \\t]+|(?=\\.?[,;!\\^\\s#()\\[\\]\\{\\}\"'<>]))/;\n this._variable = /^\\?(?:(?:[A-Z_a-z\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02ff\\u0370-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff])(?:[\\-0-:A-Z_a-z\\xb7\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u203f\\u2040\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff])*)(?=[.,;!\\^\\s#()\\[\\]\\{\\}\"'<>])/;\n this._blank = /^_:((?:[0-9A-Z_a-z\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02ff\\u0370-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff])(?:\\.?[\\-0-9A-Z_a-z\\xb7\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u203f\\u2040\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff])*)(?:[ \\t]+|(?=\\.?[,;:\\s#()\\[\\]\\{\\}\"'<>]))/;\n this._number = /^[\\-+]?(?:(\\d+\\.\\d*|\\.?\\d+)[eE][\\-+]?|\\d*(\\.)?)\\d+(?=\\.?[,;:\\s#()\\[\\]\\{\\}\"'<>])/;\n this._boolean = /^(?:true|false)(?=[.,;\\s#()\\[\\]\\{\\}\"'<>])/;\n this._keyword = /^@[a-z]+(?=[\\s#<:])/i;\n this._sparqlKeyword = /^(?:PREFIX|BASE|GRAPH)(?=[\\s#<])/i;\n this._shortPredicates = /^a(?=[\\s#()\\[\\]\\{\\}\"'<>])/;\n this._newline = /^[ \\t]*(?:#[^\\n\\r]*)?(?:\\r\\n|\\n|\\r)[ \\t]*/;\n this._comment = /#([^\\n\\r]*)/;\n this._whitespace = /^[ \\t]+/;\n this._endOfFile = /^(?:#[^\\n\\r]*)?$/;\n options = options || {};\n\n // In line mode (N-Triples or N-Quads), only simple features may be parsed\n if (this._lineMode = !!options.lineMode) {\n this._n3Mode = false;\n // Don't tokenize special literals\n for (const key in this) {\n if (!(key in lineModeRegExps) && this[key] instanceof RegExp)\n this[key] = invalidRegExp;\n }\n }\n // When not in line mode, enable N3 functionality by default\n else {\n this._n3Mode = options.n3 !== false;\n }\n // Don't output comment tokens by default\n this.comments = !!options.comments;\n // Cache the last tested closing position of long literals\n this._literalClosingPos = 0;\n }\n\n // ## Private methods\n\n // ### `_tokenizeToEnd` tokenizes as for as possible, emitting tokens through the callback\n _tokenizeToEnd(callback, inputFinished) {\n // Continue parsing as far as possible; the loop will return eventually\n let input = this._input;\n let currentLineLength = input.length;\n while (true) {\n // Count and skip whitespace lines\n let whiteSpaceMatch, comment;\n while (whiteSpaceMatch = this._newline.exec(input)) {\n // Try to find a comment\n if (this.comments && (comment = this._comment.exec(whiteSpaceMatch[0])))\n emitToken('comment', comment[1], '', this._line, whiteSpaceMatch[0].length);\n // Advance the input\n input = input.substr(whiteSpaceMatch[0].length, input.length);\n currentLineLength = input.length;\n this._line++;\n }\n // Skip whitespace on current line\n if (!whiteSpaceMatch && (whiteSpaceMatch = this._whitespace.exec(input)))\n input = input.substr(whiteSpaceMatch[0].length, input.length);\n\n // Stop for now if we're at the end\n if (this._endOfFile.test(input)) {\n // If the input is finished, emit EOF\n if (inputFinished) {\n // Try to find a final comment\n if (this.comments && (comment = this._comment.exec(input)))\n emitToken('comment', comment[1], '', this._line, input.length);\n input = null;\n emitToken('eof', '', '', this._line, 0);\n }\n return this._input = input;\n }\n\n // Look for specific token types based on the first character\n const line = this._line, firstChar = input[0];\n let type = '', value = '', prefix = '',\n match = null, matchLength = 0, inconclusive = false;\n switch (firstChar) {\n case '^':\n // We need at least 3 tokens lookahead to distinguish ^^ and ^^pre:fixed\n if (input.length < 3)\n break;\n // Try to match a type\n else if (input[1] === '^') {\n this._previousMarker = '^^';\n // Move to type IRI or prefixed name\n input = input.substr(2);\n if (input[0] !== '<') {\n inconclusive = true;\n break;\n }\n }\n // If no type, it must be a path expression\n else {\n if (this._n3Mode) {\n matchLength = 1;\n type = '^';\n }\n break;\n }\n // Fall through in case the type is an IRI\n case '<':\n // Try to find a full IRI without escape sequences\n if (match = this._unescapedIri.exec(input))\n type = 'IRI', value = match[1];\n // Try to find a full IRI with escape sequences\n else if (match = this._iri.exec(input)) {\n value = this._unescape(match[1]);\n if (value === null || illegalIriChars.test(value))\n return reportSyntaxError(this);\n type = 'IRI';\n }\n // Try to find a nested triple\n else if (input.length > 1 && input[1] === '<')\n type = '<<', matchLength = 2;\n // Try to find a backwards implication arrow\n else if (this._n3Mode && input.length > 1 && input[1] === '=')\n type = 'inverse', matchLength = 2, value = '>';\n break;\n\n case '>':\n if (input.length > 1 && input[1] === '>')\n type = '>>', matchLength = 2;\n break;\n\n case '_':\n // Try to find a blank node. Since it can contain (but not end with) a dot,\n // we always need a non-dot character before deciding it is a blank node.\n // Therefore, try inserting a space if we're at the end of the input.\n if ((match = this._blank.exec(input)) ||\n inputFinished && (match = this._blank.exec(`${input} `)))\n type = 'blank', prefix = '_', value = match[1];\n break;\n\n case '\"':\n // Try to find a literal without escape sequences\n if (match = this._simpleQuotedString.exec(input))\n value = match[1];\n // Try to find a literal wrapped in three pairs of quotes\n else {\n ({ value, matchLength } = this._parseLiteral(input));\n if (value === null)\n return reportSyntaxError(this);\n }\n if (match !== null || matchLength !== 0) {\n type = 'literal';\n this._literalClosingPos = 0;\n }\n break;\n\n case \"'\":\n if (!this._lineMode) {\n // Try to find a literal without escape sequences\n if (match = this._simpleApostropheString.exec(input))\n value = match[1];\n // Try to find a literal wrapped in three pairs of quotes\n else {\n ({ value, matchLength } = this._parseLiteral(input));\n if (value === null)\n return reportSyntaxError(this);\n }\n if (match !== null || matchLength !== 0) {\n type = 'literal';\n this._literalClosingPos = 0;\n }\n }\n break;\n\n case '?':\n // Try to find a variable\n if (this._n3Mode && (match = this._variable.exec(input)))\n type = 'var', value = match[0];\n break;\n\n case '@':\n // Try to find a language code\n if (this._previousMarker === 'literal' && (match = this._langcode.exec(input)))\n type = 'langcode', value = match[1];\n // Try to find a keyword\n else if (match = this._keyword.exec(input))\n type = match[0];\n break;\n\n case '.':\n // Try to find a dot as punctuation\n if (input.length === 1 ? inputFinished : (input[1] < '0' || input[1] > '9')) {\n type = '.';\n matchLength = 1;\n break;\n }\n // Fall through to numerical case (could be a decimal dot)\n\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n case '+':\n case '-':\n // Try to find a number. Since it can contain (but not end with) a dot,\n // we always need a non-dot character before deciding it is a number.\n // Therefore, try inserting a space if we're at the end of the input.\n if (match = this._number.exec(input) ||\n inputFinished && (match = this._number.exec(`${input} `))) {\n type = 'literal', value = match[0];\n prefix = (typeof match[1] === 'string' ? xsd.double :\n (typeof match[2] === 'string' ? xsd.decimal : xsd.integer));\n }\n break;\n\n case 'B':\n case 'b':\n case 'p':\n case 'P':\n case 'G':\n case 'g':\n // Try to find a SPARQL-style keyword\n if (match = this._sparqlKeyword.exec(input))\n type = match[0].toUpperCase();\n else\n inconclusive = true;\n break;\n\n case 'f':\n case 't':\n // Try to match a boolean\n if (match = this._boolean.exec(input))\n type = 'literal', value = match[0], prefix = xsd.boolean;\n else\n inconclusive = true;\n break;\n\n case 'a':\n // Try to find an abbreviated predicate\n if (match = this._shortPredicates.exec(input))\n type = 'abbreviation', value = 'a';\n else\n inconclusive = true;\n break;\n\n case '=':\n // Try to find an implication arrow or equals sign\n if (this._n3Mode && input.length > 1) {\n type = 'abbreviation';\n if (input[1] !== '>')\n matchLength = 1, value = '=';\n else\n matchLength = 2, value = '>';\n }\n break;\n\n case '!':\n if (!this._n3Mode)\n break;\n case ',':\n case ';':\n case '[':\n case ']':\n case '(':\n case ')':\n case '}':\n if (!this._lineMode) {\n matchLength = 1;\n type = firstChar;\n }\n break;\n case '{':\n // We need at least 2 tokens lookahead to distinguish \"{|\" and \"{ \"\n if (!this._lineMode && input.length >= 2) {\n // Try to find a quoted triple annotation start\n if (input[1] === '|')\n type = '{|', matchLength = 2;\n else\n type = firstChar, matchLength = 1;\n }\n break;\n case '|':\n // We need 2 tokens lookahead to parse \"|}\"\n // Try to find a quoted triple annotation end\n if (input.length >= 2 && input[1] === '}')\n type = '|}', matchLength = 2;\n break;\n\n default:\n inconclusive = true;\n }\n\n // Some first characters do not allow an immediate decision, so inspect more\n if (inconclusive) {\n // Try to find a prefix\n if ((this._previousMarker === '@prefix' || this._previousMarker === 'PREFIX') &&\n (match = this._prefix.exec(input)))\n type = 'prefix', value = match[1] || '';\n // Try to find a prefixed name. Since it can contain (but not end with) a dot,\n // we always need a non-dot character before deciding it is a prefixed name.\n // Therefore, try inserting a space if we're at the end of the input.\n else if ((match = this._prefixed.exec(input)) ||\n inputFinished && (match = this._prefixed.exec(`${input} `)))\n type = 'prefixed', prefix = match[1] || '', value = this._unescape(match[2]);\n }\n\n // A type token is special: it can only be emitted after an IRI or prefixed name is read\n if (this._previousMarker === '^^') {\n switch (type) {\n case 'prefixed': type = 'type'; break;\n case 'IRI': type = 'typeIRI'; break;\n default: type = '';\n }\n }\n\n // What if nothing of the above was found?\n if (!type) {\n // We could be in streaming mode, and then we just wait for more input to arrive.\n // Otherwise, a syntax error has occurred in the input.\n // One exception: error on an unaccounted linebreak (= not inside a triple-quoted literal).\n if (inputFinished || (!/^'''|^\"\"\"/.test(input) && /\\n|\\r/.test(input)))\n return reportSyntaxError(this);\n else\n return this._input = input;\n }\n\n // Emit the parsed token\n const length = matchLength || match[0].length;\n const token = emitToken(type, value, prefix, line, length);\n this.previousToken = token;\n this._previousMarker = type;\n\n // Advance to next part to tokenize\n input = input.substr(length, input.length);\n }\n\n // Emits the token through the callback\n function emitToken(type, value, prefix, line, length) {\n const start = input ? currentLineLength - input.length : currentLineLength;\n const end = start + length;\n const token = { type, value, prefix, line, start, end };\n callback(null, token);\n return token;\n }\n // Signals the syntax error through the callback\n function reportSyntaxError(self) { callback(self._syntaxError(/^\\S*/.exec(input)[0])); }\n }\n\n // ### `_unescape` replaces N3 escape codes by their corresponding characters\n _unescape(item) {\n let invalid = false;\n const replaced = item.replace(escapeSequence, (sequence, unicode4, unicode8, escapedChar) => {\n // 4-digit unicode character\n if (typeof unicode4 === 'string')\n return String.fromCharCode(Number.parseInt(unicode4, 16));\n // 8-digit unicode character\n if (typeof unicode8 === 'string') {\n let charCode = Number.parseInt(unicode8, 16);\n return charCode <= 0xFFFF ? String.fromCharCode(Number.parseInt(unicode8, 16)) :\n String.fromCharCode(0xD800 + ((charCode -= 0x10000) >> 10), 0xDC00 + (charCode & 0x3FF));\n }\n // fixed escape sequence\n if (escapedChar in escapeReplacements)\n return escapeReplacements[escapedChar];\n // invalid escape sequence\n invalid = true;\n return '';\n });\n return invalid ? null : replaced;\n }\n\n // ### `_parseLiteral` parses a literal into an unescaped value\n _parseLiteral(input) {\n // Ensure we have enough lookahead to identify triple-quoted strings\n if (input.length >= 3) {\n // Identify the opening quote(s)\n const opening = input.match(/^(?:\"\"\"|\"|'''|'|)/)[0];\n const openingLength = opening.length;\n\n // Find the next candidate closing quotes\n let closingPos = Math.max(this._literalClosingPos, openingLength);\n while ((closingPos = input.indexOf(opening, closingPos)) > 0) {\n // Count backslashes right before the closing quotes\n let backslashCount = 0;\n while (input[closingPos - backslashCount - 1] === '\\\\')\n backslashCount++;\n\n // An even number of backslashes (in particular 0)\n // means these are actual, non-escaped closing quotes\n if (backslashCount % 2 === 0) {\n // Extract and unescape the value\n const raw = input.substring(openingLength, closingPos);\n const lines = raw.split(/\\r\\n|\\r|\\n/).length - 1;\n const matchLength = closingPos + openingLength;\n // Only triple-quoted strings can be multi-line\n if (openingLength === 1 && lines !== 0 ||\n openingLength === 3 && this._lineMode)\n break;\n this._line += lines;\n return { value: this._unescape(raw), matchLength };\n }\n closingPos++;\n }\n this._literalClosingPos = input.length - openingLength + 1;\n }\n return { value: '', matchLength: 0 };\n }\n\n // ### `_syntaxError` creates a syntax error for the given issue\n _syntaxError(issue) {\n this._input = null;\n const err = new Error(`Unexpected \"${issue}\" on line ${this._line}.`);\n err.context = {\n token: undefined,\n line: this._line,\n previousToken: this.previousToken,\n };\n return err;\n }\n\n // ### Strips off any starting UTF BOM mark.\n _readStartingBom(input) {\n return input.startsWith('\\ufeff') ? input.substr(1) : input;\n }\n\n // ## Public methods\n\n // ### `tokenize` starts the transformation of an N3 document into an array of tokens.\n // The input can be a string or a stream.\n tokenize(input, callback) {\n this._line = 1;\n\n // If the input is a string, continuously emit tokens through the callback until the end\n if (typeof input === 'string') {\n this._input = this._readStartingBom(input);\n // If a callback was passed, asynchronously call it\n if (typeof callback === 'function')\n queueMicrotask(() => this._tokenizeToEnd(callback, true));\n // If no callback was passed, tokenize synchronously and return\n else {\n const tokens = [];\n let error;\n this._tokenizeToEnd((e, t) => e ? (error = e) : tokens.push(t), true);\n if (error) throw error;\n return tokens;\n }\n }\n // Otherwise, the input must be a stream\n else {\n this._pendingBuffer = null;\n if (typeof input.setEncoding === 'function')\n input.setEncoding('utf8');\n // Adds the data chunk to the buffer and parses as far as possible\n input.on('data', data => {\n if (this._input !== null && data.length !== 0) {\n // Prepend any previous pending writes\n if (this._pendingBuffer) {\n data = Buffer.concat([this._pendingBuffer, data]);\n this._pendingBuffer = null;\n }\n // Hold if the buffer ends in an incomplete unicode sequence\n if (data[data.length - 1] & 0x80) {\n this._pendingBuffer = data;\n }\n // Otherwise, tokenize as far as possible\n else {\n // Only read a BOM at the start\n if (typeof this._input === 'undefined')\n this._input = this._readStartingBom(typeof data === 'string' ? data : data.toString());\n else\n this._input += data;\n this._tokenizeToEnd(callback, false);\n }\n }\n });\n // Parses until the end\n input.on('end', () => {\n if (typeof this._input === 'string')\n this._tokenizeToEnd(callback, true);\n });\n input.on('error', callback);\n }\n }\n}\n","// N3.js implementations of the RDF/JS core data types\n// See http://rdf.js.org/data-model-spec/\n\nimport namespaces from './IRIs';\n\nconst { rdf, xsd } = namespaces;\n\n// eslint-disable-next-line prefer-const\nlet DEFAULTGRAPH;\nlet _blankNodeCounter = 0;\n\nconst escapedLiteral = /^\"(.*\".*)(?=\"[^\"]*$)/;\n\n// ## DataFactory singleton\nconst DataFactory = {\n namedNode,\n blankNode,\n variable,\n literal,\n defaultGraph,\n quad,\n triple: quad,\n fromTerm,\n fromQuad,\n};\nexport default DataFactory;\n\n// ## Term constructor\nexport class Term {\n constructor(id) {\n this.id = id;\n }\n\n // ### The value of this term\n get value() {\n return this.id;\n }\n\n // ### Returns whether this object represents the same term as the other\n equals(other) {\n // If both terms were created by this library,\n // equality can be computed through ids\n if (other instanceof Term)\n return this.id === other.id;\n // Otherwise, compare term type and value\n return !!other && this.termType === other.termType &&\n this.value === other.value;\n }\n\n // ### Implement hashCode for Immutable.js, since we implement `equals`\n // https://immutable-js.com/docs/v4.0.0/ValueObject/#hashCode()\n hashCode() {\n return 0;\n }\n\n // ### Returns a plain object representation of this term\n toJSON() {\n return {\n termType: this.termType,\n value: this.value,\n };\n }\n}\n\n\n// ## NamedNode constructor\nexport class NamedNode extends Term {\n // ### The term type of this term\n get termType() {\n return 'NamedNode';\n }\n}\n\n// ## Literal constructor\nexport class Literal extends Term {\n // ### The term type of this term\n get termType() {\n return 'Literal';\n }\n\n // ### The text value of this literal\n get value() {\n return this.id.substring(1, this.id.lastIndexOf('\"'));\n }\n\n // ### The language of this literal\n get language() {\n // Find the last quotation mark (e.g., '\"abc\"@en-us')\n const id = this.id;\n let atPos = id.lastIndexOf('\"') + 1;\n // If \"@\" it follows, return the remaining substring; empty otherwise\n return atPos < id.length && id[atPos++] === '@' ? id.substr(atPos).toLowerCase() : '';\n }\n\n // ### The datatype IRI of this literal\n get datatype() {\n return new NamedNode(this.datatypeString);\n }\n\n // ### The datatype string of this literal\n get datatypeString() {\n // Find the last quotation mark (e.g., '\"abc\"^^http://ex.org/types#t')\n const id = this.id, dtPos = id.lastIndexOf('\"') + 1;\n const char = dtPos < id.length ? id[dtPos] : '';\n // If \"^\" it follows, return the remaining substring\n return char === '^' ? id.substr(dtPos + 2) :\n // If \"@\" follows, return rdf:langString; xsd:string otherwise\n (char !== '@' ? xsd.string : rdf.langString);\n }\n\n // ### Returns whether this object represents the same term as the other\n equals(other) {\n // If both literals were created by this library,\n // equality can be computed through ids\n if (other instanceof Literal)\n return this.id === other.id;\n // Otherwise, compare term type, value, language, and datatype\n return !!other && !!other.datatype &&\n this.termType === other.termType &&\n this.value === other.value &&\n this.language === other.language &&\n this.datatype.value === other.datatype.value;\n }\n\n toJSON() {\n return {\n termType: this.termType,\n value: this.value,\n language: this.language,\n datatype: { termType: 'NamedNode', value: this.datatypeString },\n };\n }\n}\n\n// ## BlankNode constructor\nexport class BlankNode extends Term {\n constructor(name) {\n super(`_:${name}`);\n }\n\n // ### The term type of this term\n get termType() {\n return 'BlankNode';\n }\n\n // ### The name of this blank node\n get value() {\n return this.id.substr(2);\n }\n}\n\nexport class Variable extends Term {\n constructor(name) {\n super(`?${name}`);\n }\n\n // ### The term type of this term\n get termType() {\n return 'Variable';\n }\n\n // ### The name of this variable\n get value() {\n return this.id.substr(1);\n }\n}\n\n// ## DefaultGraph constructor\nexport class DefaultGraph extends Term {\n constructor() {\n super('');\n return DEFAULTGRAPH || this;\n }\n\n // ### The term type of this term\n get termType() {\n return 'DefaultGraph';\n }\n\n // ### Returns whether this object represents the same term as the other\n equals(other) {\n // If both terms were created by this library,\n // equality can be computed through strict equality;\n // otherwise, compare term types.\n return (this === other) || (!!other && (this.termType === other.termType));\n }\n}\n\n// ## DefaultGraph singleton\nDEFAULTGRAPH = new DefaultGraph();\n\n// ### Constructs a term from the given internal string ID\n// The third 'nested' parameter of this function is to aid\n// with recursion over nested terms. It should not be used\n// by consumers of this library.\n// See https://github.com/rdfjs/N3.js/pull/311#discussion_r1061042725\nexport function termFromId(id, factory, nested) {\n factory = factory || DataFactory;\n\n // Falsy value or empty string indicate the default graph\n if (!id)\n return factory.defaultGraph();\n\n // Identify the term type based on the first character\n switch (id[0]) {\n case '?':\n return factory.variable(id.substr(1));\n case '_':\n return factory.blankNode(id.substr(2));\n case '\"':\n // Shortcut for internal literals\n if (factory === DataFactory)\n return new Literal(id);\n // Literal without datatype or language\n if (id[id.length - 1] === '\"')\n return factory.literal(id.substr(1, id.length - 2));\n // Literal with datatype or language\n const endPos = id.lastIndexOf('\"', id.length - 1);\n return factory.literal(id.substr(1, endPos - 1),\n id[endPos + 1] === '@' ? id.substr(endPos + 2)\n : factory.namedNode(id.substr(endPos + 3)));\n case '[':\n id = JSON.parse(id);\n break;\n default:\n if (!nested || !Array.isArray(id)) {\n return factory.namedNode(id);\n }\n }\n return factory.quad(\n termFromId(id[0], factory, true),\n termFromId(id[1], factory, true),\n termFromId(id[2], factory, true),\n id[3] && termFromId(id[3], factory, true),\n );\n}\n\n// ### Constructs an internal string ID from the given term or ID string\n// The third 'nested' parameter of this function is to aid\n// with recursion over nested terms. It should not be used\n// by consumers of this library.\n// See https://github.com/rdfjs/N3.js/pull/311#discussion_r1061042725\nexport function termToId(term, nested) {\n if (typeof term === 'string')\n return term;\n if (term instanceof Term && term.termType !== 'Quad')\n return term.id;\n if (!term)\n return DEFAULTGRAPH.id;\n\n // Term instantiated with another library\n switch (term.termType) {\n case 'NamedNode': return term.value;\n case 'BlankNode': return `_:${term.value}`;\n case 'Variable': return `?${term.value}`;\n case 'DefaultGraph': return '';\n case 'Literal': return `\"${term.value}\"${\n term.language ? `@${term.language}` :\n (term.datatype && term.datatype.value !== xsd.string ? `^^${term.datatype.value}` : '')}`;\n case 'Quad':\n const res = [\n termToId(term.subject, true),\n termToId(term.predicate, true),\n termToId(term.object, true),\n ];\n if (term.graph && term.graph.termType !== 'DefaultGraph') {\n res.push(termToId(term.graph, true));\n }\n return nested ? res : JSON.stringify(res);\n default: throw new Error(`Unexpected termType: ${term.termType}`);\n }\n}\n\n\n// ## Quad constructor\nexport class Quad extends Term {\n constructor(subject, predicate, object, graph) {\n super('');\n this._subject = subject;\n this._predicate = predicate;\n this._object = object;\n this._graph = graph || DEFAULTGRAPH;\n }\n\n // ### The term type of this term\n get termType() {\n return 'Quad';\n }\n\n get subject() {\n return this._subject;\n }\n\n get predicate() {\n return this._predicate;\n }\n\n get object() {\n return this._object;\n }\n\n get graph() {\n return this._graph;\n }\n\n // ### Returns a plain object representation of this quad\n toJSON() {\n return {\n termType: this.termType,\n subject: this._subject.toJSON(),\n predicate: this._predicate.toJSON(),\n object: this._object.toJSON(),\n graph: this._graph.toJSON(),\n };\n }\n\n // ### Returns whether this object represents the same quad as the other\n equals(other) {\n return !!other && this._subject.equals(other.subject) &&\n this._predicate.equals(other.predicate) &&\n this._object.equals(other.object) &&\n this._graph.equals(other.graph);\n }\n}\nexport { Quad as Triple };\n\n// ### Escapes the quotes within the given literal\nexport function escapeQuotes(id) {\n return id.replace(escapedLiteral, (_, quoted) => `\"${quoted.replace(/\"/g, '\"\"')}`);\n}\n\n// ### Unescapes the quotes within the given literal\nexport function unescapeQuotes(id) {\n return id.replace(escapedLiteral, (_, quoted) => `\"${quoted.replace(/\"\"/g, '\"')}`);\n}\n\n// ### Creates an IRI\nfunction namedNode(iri) {\n return new NamedNode(iri);\n}\n\n// ### Creates a blank node\nfunction blankNode(name) {\n return new BlankNode(name || `n3-${_blankNodeCounter++}`);\n}\n\n// ### Creates a literal\nfunction literal(value, languageOrDataType) {\n // Create a language-tagged string\n if (typeof languageOrDataType === 'string')\n return new Literal(`\"${value}\"@${languageOrDataType.toLowerCase()}`);\n\n // Automatically determine datatype for booleans and numbers\n let datatype = languageOrDataType ? languageOrDataType.value : '';\n if (datatype === '') {\n // Convert a boolean\n if (typeof value === 'boolean')\n datatype = xsd.boolean;\n // Convert an integer or double\n else if (typeof value === 'number') {\n if (Number.isFinite(value))\n datatype = Number.isInteger(value) ? xsd.integer : xsd.double;\n else {\n datatype = xsd.double;\n if (!Number.isNaN(value))\n value = value > 0 ? 'INF' : '-INF';\n }\n }\n }\n\n // Create a datatyped literal\n return (datatype === '' || datatype === xsd.string) ?\n new Literal(`\"${value}\"`) :\n new Literal(`\"${value}\"^^${datatype}`);\n}\n\n// ### Creates a variable\nfunction variable(name) {\n return new Variable(name);\n}\n\n// ### Returns the default graph\nfunction defaultGraph() {\n return DEFAULTGRAPH;\n}\n\n// ### Creates a quad\nfunction quad(subject, predicate, object, graph) {\n return new Quad(subject, predicate, object, graph);\n}\n\nexport function fromTerm(term) {\n if (term instanceof Term)\n return term;\n\n // Term instantiated with another library\n switch (term.termType) {\n case 'NamedNode': return namedNode(term.value);\n case 'BlankNode': return blankNode(term.value);\n case 'Variable': return variable(term.value);\n case 'DefaultGraph': return DEFAULTGRAPH;\n case 'Literal': return literal(term.value, term.language || term.datatype);\n case 'Quad': return fromQuad(term);\n default: throw new Error(`Unexpected termType: ${term.termType}`);\n }\n}\n\nexport function fromQuad(inQuad) {\n if (inQuad instanceof Quad)\n return inQuad;\n\n if (inQuad.termType !== 'Quad')\n throw new Error(`Unexpected termType: ${inQuad.termType}`);\n\n return quad(fromTerm(inQuad.subject), fromTerm(inQuad.predicate), fromTerm(inQuad.object), fromTerm(inQuad.graph));\n}\n","// **N3Parser** parses N3 documents.\nimport N3Lexer from './N3Lexer';\nimport N3DataFactory from './N3DataFactory';\nimport namespaces from './IRIs';\n\nlet blankNodePrefix = 0;\n\n// ## Constructor\nexport default class N3Parser {\n constructor(options) {\n this._contextStack = [];\n this._graph = null;\n\n // Set the document IRI\n options = options || {};\n this._setBase(options.baseIRI);\n options.factory && initDataFactory(this, options.factory);\n\n // Set supported features depending on the format\n const format = (typeof options.format === 'string') ?\n options.format.match(/\\w*$/)[0].toLowerCase() : '',\n isTurtle = /turtle/.test(format), isTriG = /trig/.test(format),\n isNTriples = /triple/.test(format), isNQuads = /quad/.test(format),\n isN3 = this._n3Mode = /n3/.test(format),\n isLineMode = isNTriples || isNQuads;\n if (!(this._supportsNamedGraphs = !(isTurtle || isN3)))\n this._readPredicateOrNamedGraph = this._readPredicate;\n // Support triples in other graphs\n this._supportsQuads = !(isTurtle || isTriG || isNTriples || isN3);\n // Support nesting of triples\n this._supportsRDFStar = format === '' || /star|\\*$/.test(format);\n // Disable relative IRIs in N-Triples or N-Quads mode\n if (isLineMode)\n this._resolveRelativeIRI = iri => { return null; };\n this._blankNodePrefix = typeof options.blankNodePrefix !== 'string' ? '' :\n options.blankNodePrefix.replace(/^(?!_:)/, '_:');\n this._lexer = options.lexer || new N3Lexer({ lineMode: isLineMode, n3: isN3 });\n // Disable explicit quantifiers by default\n this._explicitQuantifiers = !!options.explicitQuantifiers;\n }\n\n // ## Static class methods\n\n // ### `_resetBlankNodePrefix` restarts blank node prefix identification\n static _resetBlankNodePrefix() {\n blankNodePrefix = 0;\n }\n\n // ## Private methods\n\n // ### `_setBase` sets the base IRI to resolve relative IRIs\n _setBase(baseIRI) {\n if (!baseIRI) {\n this._base = '';\n this._basePath = '';\n }\n else {\n // Remove fragment if present\n const fragmentPos = baseIRI.indexOf('#');\n if (fragmentPos >= 0)\n baseIRI = baseIRI.substr(0, fragmentPos);\n // Set base IRI and its components\n this._base = baseIRI;\n this._basePath = baseIRI.indexOf('/') < 0 ? baseIRI :\n baseIRI.replace(/[^\\/?]*(?:\\?.*)?$/, '');\n baseIRI = baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\\/\\/[^\\/]*)?/i);\n this._baseRoot = baseIRI[0];\n this._baseScheme = baseIRI[1];\n }\n }\n\n // ### `_saveContext` stores the current parsing context\n // when entering a new scope (list, blank node, formula)\n _saveContext(type, graph, subject, predicate, object) {\n const n3Mode = this._n3Mode;\n this._contextStack.push({\n type,\n subject, predicate, object, graph,\n inverse: n3Mode ? this._inversePredicate : false,\n blankPrefix: n3Mode ? this._prefixes._ : '',\n quantified: n3Mode ? this._quantified : null,\n });\n // The settings below only apply to N3 streams\n if (n3Mode) {\n // Every new scope resets the predicate direction\n this._inversePredicate = false;\n // In N3, blank nodes are scoped to a formula\n // (using a dot as separator, as a blank node label cannot start with it)\n this._prefixes._ = (this._graph ? `${this._graph.value}.` : '.');\n // Quantifiers are scoped to a formula\n this._quantified = Object.create(this._quantified);\n }\n }\n\n // ### `_restoreContext` restores the parent context\n // when leaving a scope (list, blank node, formula)\n _restoreContext(type, token) {\n // Obtain the previous context\n const context = this._contextStack.pop();\n if (!context || context.type !== type)\n return this._error(`Unexpected ${token.type}`, token);\n\n // Restore the quad of the previous context\n this._subject = context.subject;\n this._predicate = context.predicate;\n this._object = context.object;\n this._graph = context.graph;\n\n // Restore N3 context settings\n if (this._n3Mode) {\n this._inversePredicate = context.inverse;\n this._prefixes._ = context.blankPrefix;\n this._quantified = context.quantified;\n }\n }\n\n // ### `_readInTopContext` reads a token when in the top context\n _readInTopContext(token) {\n switch (token.type) {\n // If an EOF token arrives in the top context, signal that we're done\n case 'eof':\n if (this._graph !== null)\n return this._error('Unclosed graph', token);\n delete this._prefixes._;\n return this._callback(null, null, this._prefixes);\n // It could be a prefix declaration\n case 'PREFIX':\n this._sparqlStyle = true;\n case '@prefix':\n return this._readPrefix;\n // It could be a base declaration\n case 'BASE':\n this._sparqlStyle = true;\n case '@base':\n return this._readBaseIRI;\n // It could be a graph\n case '{':\n if (this._supportsNamedGraphs) {\n this._graph = '';\n this._subject = null;\n return this._readSubject;\n }\n case 'GRAPH':\n if (this._supportsNamedGraphs)\n return this._readNamedGraphLabel;\n // Otherwise, the next token must be a subject\n default:\n return this._readSubject(token);\n }\n }\n\n // ### `_readEntity` reads an IRI, prefixed name, blank node, or variable\n _readEntity(token, quantifier) {\n let value;\n switch (token.type) {\n // Read a relative or absolute IRI\n case 'IRI':\n case 'typeIRI':\n const iri = this._resolveIRI(token.value);\n if (iri === null)\n return this._error('Invalid IRI', token);\n value = this._factory.namedNode(iri);\n break;\n // Read a prefixed name\n case 'type':\n case 'prefixed':\n const prefix = this._prefixes[token.prefix];\n if (prefix === undefined)\n return this._error(`Undefined prefix \"${token.prefix}:\"`, token);\n value = this._factory.namedNode(prefix + token.value);\n break;\n // Read a blank node\n case 'blank':\n value = this._factory.blankNode(this._prefixes[token.prefix] + token.value);\n break;\n // Read a variable\n case 'var':\n value = this._factory.variable(token.value.substr(1));\n break;\n // Everything else is not an entity\n default:\n return this._error(`Expected entity but got ${token.type}`, token);\n }\n // In N3 mode, replace the entity if it is quantified\n if (!quantifier && this._n3Mode && (value.id in this._quantified))\n value = this._quantified[value.id];\n return value;\n }\n\n // ### `_readSubject` reads a quad's subject\n _readSubject(token) {\n this._predicate = null;\n switch (token.type) {\n case '[':\n // Start a new quad with a new blank node as subject\n this._saveContext('blank', this._graph,\n this._subject = this._factory.blankNode(), null, null);\n return this._readBlankNodeHead;\n case '(':\n // Start a new list\n this._saveContext('list', this._graph, this.RDF_NIL, null, null);\n this._subject = null;\n return this._readListItem;\n case '{':\n // Start a new formula\n if (!this._n3Mode)\n return this._error('Unexpected graph', token);\n this._saveContext('formula', this._graph,\n this._graph = this._factory.blankNode(), null, null);\n return this._readSubject;\n case '}':\n // No subject; the graph in which we are reading is closed instead\n return this._readPunctuation(token);\n case '@forSome':\n if (!this._n3Mode)\n return this._error('Unexpected \"@forSome\"', token);\n this._subject = null;\n this._predicate = this.N3_FORSOME;\n this._quantifier = 'blankNode';\n return this._readQuantifierList;\n case '@forAll':\n if (!this._n3Mode)\n return this._error('Unexpected \"@forAll\"', token);\n this._subject = null;\n this._predicate = this.N3_FORALL;\n this._quantifier = 'variable';\n return this._readQuantifierList;\n case 'literal':\n if (!this._n3Mode)\n return this._error('Unexpected literal', token);\n\n if (token.prefix.length === 0) {\n this._literalValue = token.value;\n return this._completeSubjectLiteral;\n }\n else\n this._subject = this._factory.literal(token.value, this._factory.namedNode(token.prefix));\n\n break;\n case '<<':\n if (!this._supportsRDFStar)\n return this._error('Unexpected RDF-star syntax', token);\n this._saveContext('<<', this._graph, null, null, null);\n this._graph = null;\n return this._readSubject;\n default:\n // Read the subject entity\n if ((this._subject = this._readEntity(token)) === undefined)\n return;\n // In N3 mode, the subject might be a path\n if (this._n3Mode)\n return this._getPathReader(this._readPredicateOrNamedGraph);\n }\n\n // The next token must be a predicate,\n // or, if the subject was actually a graph IRI, a named graph\n return this._readPredicateOrNamedGraph;\n }\n\n // ### `_readPredicate` reads a quad's predicate\n _readPredicate(token) {\n const type = token.type;\n switch (type) {\n case 'inverse':\n this._inversePredicate = true;\n case 'abbreviation':\n this._predicate = this.ABBREVIATIONS[token.value];\n break;\n case '.':\n case ']':\n case '}':\n // Expected predicate didn't come, must have been trailing semicolon\n if (this._predicate === null)\n return this._error(`Unexpected ${type}`, token);\n this._subject = null;\n return type === ']' ? this._readBlankNodeTail(token) : this._readPunctuation(token);\n case ';':\n // Additional semicolons can be safely ignored\n return this._predicate !== null ? this._readPredicate :\n this._error('Expected predicate but got ;', token);\n case '[':\n if (this._n3Mode) {\n // Start a new quad with a new blank node as subject\n this._saveContext('blank', this._graph, this._subject,\n this._subject = this._factory.blankNode(), null);\n return this._readBlankNodeHead;\n }\n case 'blank':\n if (!this._n3Mode)\n return this._error('Disallowed blank node as predicate', token);\n default:\n if ((this._predicate = this._readEntity(token)) === undefined)\n return;\n }\n // The next token must be an object\n return this._readObject;\n }\n\n // ### `_readObject` reads a quad's object\n _readObject(token) {\n switch (token.type) {\n case 'literal':\n // Regular literal, can still get a datatype or language\n if (token.prefix.length === 0) {\n this._literalValue = token.value;\n return this._readDataTypeOrLang;\n }\n // Pre-datatyped string literal (prefix stores the datatype)\n else\n this._object = this._factory.literal(token.value, this._factory.namedNode(token.prefix));\n break;\n case '[':\n // Start a new quad with a new blank node as subject\n this._saveContext('blank', this._graph, this._subject, this._predicate,\n this._subject = this._factory.blankNode());\n return this._readBlankNodeHead;\n case '(':\n // Start a new list\n this._saveContext('list', this._graph, this._subject, this._predicate, this.RDF_NIL);\n this._subject = null;\n return this._readListItem;\n case '{':\n // Start a new formula\n if (!this._n3Mode)\n return this._error('Unexpected graph', token);\n this._saveContext('formula', this._graph, this._subject, this._predicate,\n this._graph = this._factory.blankNode());\n return this._readSubject;\n case '<<':\n if (!this._supportsRDFStar)\n return this._error('Unexpected RDF-star syntax', token);\n this._saveContext('<<', this._graph, this._subject, this._predicate, null);\n this._graph = null;\n return this._readSubject;\n default:\n // Read the object entity\n if ((this._object = this._readEntity(token)) === undefined)\n return;\n // In N3 mode, the object might be a path\n if (this._n3Mode)\n return this._getPathReader(this._getContextEndReader());\n }\n return this._getContextEndReader();\n }\n\n // ### `_readPredicateOrNamedGraph` reads a quad's predicate, or a named graph\n _readPredicateOrNamedGraph(token) {\n return token.type === '{' ? this._readGraph(token) : this._readPredicate(token);\n }\n\n // ### `_readGraph` reads a graph\n _readGraph(token) {\n if (token.type !== '{')\n return this._error(`Expected graph but got ${token.type}`, token);\n // The \"subject\" we read is actually the GRAPH's label\n this._graph = this._subject, this._subject = null;\n return this._readSubject;\n }\n\n // ### `_readBlankNodeHead` reads the head of a blank node\n _readBlankNodeHead(token) {\n if (token.type === ']') {\n this._subject = null;\n return this._readBlankNodeTail(token);\n }\n else {\n this._predicate = null;\n return this._readPredicate(token);\n }\n }\n\n // ### `_readBlankNodeTail` reads the end of a blank node\n _readBlankNodeTail(token) {\n if (token.type !== ']')\n return this._readBlankNodePunctuation(token);\n\n // Store blank node quad\n if (this._subject !== null)\n this._emit(this._subject, this._predicate, this._object, this._graph);\n\n // Restore the parent context containing this blank node\n const empty = this._predicate === null;\n this._restoreContext('blank', token);\n // If the blank node was the object, restore previous context and read punctuation\n if (this._object !== null)\n return this._getContextEndReader();\n // If the blank node was the predicate, continue reading the object\n else if (this._predicate !== null)\n return this._readObject;\n // If the blank node was the subject, continue reading the predicate\n else\n // If the blank node was empty, it could be a named graph label\n return empty ? this._readPredicateOrNamedGraph : this._readPredicateAfterBlank;\n }\n\n // ### `_readPredicateAfterBlank` reads a predicate after an anonymous blank node\n _readPredicateAfterBlank(token) {\n switch (token.type) {\n case '.':\n case '}':\n // No predicate is coming if the triple is terminated here\n this._subject = null;\n return this._readPunctuation(token);\n default:\n return this._readPredicate(token);\n }\n }\n\n // ### `_readListItem` reads items from a list\n _readListItem(token) {\n let item = null, // The item of the list\n list = null, // The list itself\n next = this._readListItem; // The next function to execute\n const previousList = this._subject, // The previous list that contains this list\n stack = this._contextStack, // The stack of parent contexts\n parent = stack[stack.length - 1]; // The parent containing the current list\n\n switch (token.type) {\n case '[':\n // Stack the current list quad and start a new quad with a blank node as subject\n this._saveContext('blank', this._graph,\n list = this._factory.blankNode(), this.RDF_FIRST,\n this._subject = item = this._factory.blankNode());\n next = this._readBlankNodeHead;\n break;\n case '(':\n // Stack the current list quad and start a new list\n this._saveContext('list', this._graph,\n list = this._factory.blankNode(), this.RDF_FIRST, this.RDF_NIL);\n this._subject = null;\n break;\n case ')':\n // Closing the list; restore the parent context\n this._restoreContext('list', token);\n // If this list is contained within a parent list, return the membership quad here.\n // This will be ` rdf:first .`.\n if (stack.length !== 0 && stack[stack.length - 1].type === 'list')\n this._emit(this._subject, this._predicate, this._object, this._graph);\n // Was this list the parent's subject?\n if (this._predicate === null) {\n // The next token is the predicate\n next = this._readPredicate;\n // No list tail if this was an empty list\n if (this._subject === this.RDF_NIL)\n return next;\n }\n // The list was in the parent context's object\n else {\n next = this._getContextEndReader();\n // No list tail if this was an empty list\n if (this._object === this.RDF_NIL)\n return next;\n }\n // Close the list by making the head nil\n list = this.RDF_NIL;\n break;\n case 'literal':\n // Regular literal, can still get a datatype or language\n if (token.prefix.length === 0) {\n this._literalValue = token.value;\n next = this._readListItemDataTypeOrLang;\n }\n // Pre-datatyped string literal (prefix stores the datatype)\n else {\n item = this._factory.literal(token.value, this._factory.namedNode(token.prefix));\n next = this._getContextEndReader();\n }\n break;\n case '{':\n // Start a new formula\n if (!this._n3Mode)\n return this._error('Unexpected graph', token);\n this._saveContext('formula', this._graph, this._subject, this._predicate,\n this._graph = this._factory.blankNode());\n return this._readSubject;\n default:\n if ((item = this._readEntity(token)) === undefined)\n return;\n }\n\n // Create a new blank node if no item head was assigned yet\n if (list === null)\n this._subject = list = this._factory.blankNode();\n\n // Is this the first element of the list?\n if (previousList === null) {\n // This list is either the subject or the object of its parent\n if (parent.predicate === null)\n parent.subject = list;\n else\n parent.object = list;\n }\n else {\n // Continue the previous list with the current list\n this._emit(previousList, this.RDF_REST, list, this._graph);\n }\n // If an item was read, add it to the list\n if (item !== null) {\n // In N3 mode, the item might be a path\n if (this._n3Mode && (token.type === 'IRI' || token.type === 'prefixed')) {\n // Create a new context to add the item's path\n this._saveContext('item', this._graph, list, this.RDF_FIRST, item);\n this._subject = item, this._predicate = null;\n // _readPath will restore the context and output the item\n return this._getPathReader(this._readListItem);\n }\n // Output the item\n this._emit(list, this.RDF_FIRST, item, this._graph);\n }\n return next;\n }\n\n // ### `_readDataTypeOrLang` reads an _optional_ datatype or language\n _readDataTypeOrLang(token) {\n return this._completeObjectLiteral(token, false);\n }\n\n\n // ### `_readListItemDataTypeOrLang` reads an _optional_ datatype or language in a list\n _readListItemDataTypeOrLang(token) {\n return this._completeObjectLiteral(token, true);\n }\n\n // ### `_completeLiteral` completes a literal with an optional datatype or language\n _completeLiteral(token) {\n // Create a simple string literal by default\n let literal = this._factory.literal(this._literalValue);\n\n switch (token.type) {\n // Create a datatyped literal\n case 'type':\n case 'typeIRI':\n const datatype = this._readEntity(token);\n if (datatype === undefined) return; // No datatype means an error occurred\n literal = this._factory.literal(this._literalValue, datatype);\n token = null;\n break;\n // Create a language-tagged string\n case 'langcode':\n literal = this._factory.literal(this._literalValue, token.value);\n token = null;\n break;\n }\n\n return { token, literal };\n }\n\n // Completes a literal in subject position\n _completeSubjectLiteral(token) {\n this._subject = this._completeLiteral(token).literal;\n return this._readPredicateOrNamedGraph;\n }\n\n // Completes a literal in object position\n _completeObjectLiteral(token, listItem) {\n const completed = this._completeLiteral(token);\n if (!completed)\n return;\n this._object = completed.literal;\n\n // If this literal was part of a list, write the item\n // (we could also check the context stack, but passing in a flag is faster)\n if (listItem)\n this._emit(this._subject, this.RDF_FIRST, this._object, this._graph);\n // If the token was consumed, continue with the rest of the input\n if (completed.token === null)\n return this._getContextEndReader();\n // Otherwise, consume the token now\n else {\n this._readCallback = this._getContextEndReader();\n return this._readCallback(completed.token);\n }\n }\n\n // ### `_readFormulaTail` reads the end of a formula\n _readFormulaTail(token) {\n if (token.type !== '}')\n return this._readPunctuation(token);\n\n // Store the last quad of the formula\n if (this._subject !== null)\n this._emit(this._subject, this._predicate, this._object, this._graph);\n\n // Restore the parent context containing this formula\n this._restoreContext('formula', token);\n // If the formula was the subject, continue reading the predicate.\n // If the formula was the object, read punctuation.\n return this._object === null ? this._readPredicate : this._getContextEndReader();\n }\n\n // ### `_readPunctuation` reads punctuation between quads or quad parts\n _readPunctuation(token) {\n let next, graph = this._graph;\n const subject = this._subject, inversePredicate = this._inversePredicate;\n switch (token.type) {\n // A closing brace ends a graph\n case '}':\n if (this._graph === null)\n return this._error('Unexpected graph closing', token);\n if (this._n3Mode)\n return this._readFormulaTail(token);\n this._graph = null;\n // A dot just ends the statement, without sharing anything with the next\n case '.':\n this._subject = null;\n next = this._contextStack.length ? this._readSubject : this._readInTopContext;\n if (inversePredicate) this._inversePredicate = false;\n break;\n // Semicolon means the subject is shared; predicate and object are different\n case ';':\n next = this._readPredicate;\n break;\n // Comma means both the subject and predicate are shared; the object is different\n case ',':\n next = this._readObject;\n break;\n // {| means that the current triple is annotated with predicate-object pairs.\n case '{|':\n if (!this._supportsRDFStar)\n return this._error('Unexpected RDF-star syntax', token);\n // Continue using the last triple as quoted triple subject for the predicate-object pairs.\n const predicate = this._predicate, object = this._object;\n this._subject = this._factory.quad(subject, predicate, object, this.DEFAULTGRAPH);\n next = this._readPredicate;\n break;\n // |} means that the current quoted triple in annotation syntax is finalized.\n case '|}':\n if (this._subject.termType !== 'Quad')\n return this._error('Unexpected asserted triple closing', token);\n this._subject = null;\n next = this._readPunctuation;\n break;\n default:\n // An entity means this is a quad (only allowed if not already inside a graph)\n if (this._supportsQuads && this._graph === null && (graph = this._readEntity(token)) !== undefined) {\n next = this._readQuadPunctuation;\n break;\n }\n return this._error(`Expected punctuation to follow \"${this._object.id}\"`, token);\n }\n // A quad has been completed now, so return it\n if (subject !== null) {\n const predicate = this._predicate, object = this._object;\n if (!inversePredicate)\n this._emit(subject, predicate, object, graph);\n else\n this._emit(object, predicate, subject, graph);\n }\n return next;\n }\n\n // ### `_readBlankNodePunctuation` reads punctuation in a blank node\n _readBlankNodePunctuation(token) {\n let next;\n switch (token.type) {\n // Semicolon means the subject is shared; predicate and object are different\n case ';':\n next = this._readPredicate;\n break;\n // Comma means both the subject and predicate are shared; the object is different\n case ',':\n next = this._readObject;\n break;\n default:\n return this._error(`Expected punctuation to follow \"${this._object.id}\"`, token);\n }\n // A quad has been completed now, so return it\n this._emit(this._subject, this._predicate, this._object, this._graph);\n return next;\n }\n\n // ### `_readQuadPunctuation` reads punctuation after a quad\n _readQuadPunctuation(token) {\n if (token.type !== '.')\n return this._error('Expected dot to follow quad', token);\n return this._readInTopContext;\n }\n\n // ### `_readPrefix` reads the prefix of a prefix declaration\n _readPrefix(token) {\n if (token.type !== 'prefix')\n return this._error('Expected prefix to follow @prefix', token);\n this._prefix = token.value;\n return this._readPrefixIRI;\n }\n\n // ### `_readPrefixIRI` reads the IRI of a prefix declaration\n _readPrefixIRI(token) {\n if (token.type !== 'IRI')\n return this._error(`Expected IRI to follow prefix \"${this._prefix}:\"`, token);\n const prefixNode = this._readEntity(token);\n this._prefixes[this._prefix] = prefixNode.value;\n this._prefixCallback(this._prefix, prefixNode);\n return this._readDeclarationPunctuation;\n }\n\n // ### `_readBaseIRI` reads the IRI of a base declaration\n _readBaseIRI(token) {\n const iri = token.type === 'IRI' && this._resolveIRI(token.value);\n if (!iri)\n return this._error('Expected valid IRI to follow base declaration', token);\n this._setBase(iri);\n return this._readDeclarationPunctuation;\n }\n\n // ### `_readNamedGraphLabel` reads the label of a named graph\n _readNamedGraphLabel(token) {\n switch (token.type) {\n case 'IRI':\n case 'blank':\n case 'prefixed':\n return this._readSubject(token), this._readGraph;\n case '[':\n return this._readNamedGraphBlankLabel;\n default:\n return this._error('Invalid graph label', token);\n }\n }\n\n // ### `_readNamedGraphLabel` reads a blank node label of a named graph\n _readNamedGraphBlankLabel(token) {\n if (token.type !== ']')\n return this._error('Invalid graph label', token);\n this._subject = this._factory.blankNode();\n return this._readGraph;\n }\n\n // ### `_readDeclarationPunctuation` reads the punctuation of a declaration\n _readDeclarationPunctuation(token) {\n // SPARQL-style declarations don't have punctuation\n if (this._sparqlStyle) {\n this._sparqlStyle = false;\n return this._readInTopContext(token);\n }\n\n if (token.type !== '.')\n return this._error('Expected declaration to end with a dot', token);\n return this._readInTopContext;\n }\n\n // Reads a list of quantified symbols from a @forSome or @forAll statement\n _readQuantifierList(token) {\n let entity;\n switch (token.type) {\n case 'IRI':\n case 'prefixed':\n if ((entity = this._readEntity(token, true)) !== undefined)\n break;\n default:\n return this._error(`Unexpected ${token.type}`, token);\n }\n // Without explicit quantifiers, map entities to a quantified entity\n if (!this._explicitQuantifiers)\n this._quantified[entity.id] = this._factory[this._quantifier](this._factory.blankNode().value);\n // With explicit quantifiers, output the reified quantifier\n else {\n // If this is the first item, start a new quantifier list\n if (this._subject === null)\n this._emit(this._graph || this.DEFAULTGRAPH, this._predicate,\n this._subject = this._factory.blankNode(), this.QUANTIFIERS_GRAPH);\n // Otherwise, continue the previous list\n else\n this._emit(this._subject, this.RDF_REST,\n this._subject = this._factory.blankNode(), this.QUANTIFIERS_GRAPH);\n // Output the list item\n this._emit(this._subject, this.RDF_FIRST, entity, this.QUANTIFIERS_GRAPH);\n }\n return this._readQuantifierPunctuation;\n }\n\n // Reads punctuation from a @forSome or @forAll statement\n _readQuantifierPunctuation(token) {\n // Read more quantifiers\n if (token.type === ',')\n return this._readQuantifierList;\n // End of the quantifier list\n else {\n // With explicit quantifiers, close the quantifier list\n if (this._explicitQuantifiers) {\n this._emit(this._subject, this.RDF_REST, this.RDF_NIL, this.QUANTIFIERS_GRAPH);\n this._subject = null;\n }\n // Read a dot\n this._readCallback = this._getContextEndReader();\n return this._readCallback(token);\n }\n }\n\n // ### `_getPathReader` reads a potential path and then resumes with the given function\n _getPathReader(afterPath) {\n this._afterPath = afterPath;\n return this._readPath;\n }\n\n // ### `_readPath` reads a potential path\n _readPath(token) {\n switch (token.type) {\n // Forward path\n case '!': return this._readForwardPath;\n // Backward path\n case '^': return this._readBackwardPath;\n // Not a path; resume reading where we left off\n default:\n const stack = this._contextStack, parent = stack.length && stack[stack.length - 1];\n // If we were reading a list item, we still need to output it\n if (parent && parent.type === 'item') {\n // The list item is the remaining subejct after reading the path\n const item = this._subject;\n // Switch back to the context of the list\n this._restoreContext('item', token);\n // Output the list item\n this._emit(this._subject, this.RDF_FIRST, item, this._graph);\n }\n return this._afterPath(token);\n }\n }\n\n // ### `_readForwardPath` reads a '!' path\n _readForwardPath(token) {\n let subject, predicate;\n const object = this._factory.blankNode();\n // The next token is the predicate\n if ((predicate = this._readEntity(token)) === undefined)\n return;\n // If we were reading a subject, replace the subject by the path's object\n if (this._predicate === null)\n subject = this._subject, this._subject = object;\n // If we were reading an object, replace the subject by the path's object\n else\n subject = this._object, this._object = object;\n // Emit the path's current quad and read its next section\n this._emit(subject, predicate, object, this._graph);\n return this._readPath;\n }\n\n // ### `_readBackwardPath` reads a '^' path\n _readBackwardPath(token) {\n const subject = this._factory.blankNode();\n let predicate, object;\n // The next token is the predicate\n if ((predicate = this._readEntity(token)) === undefined)\n return;\n // If we were reading a subject, replace the subject by the path's subject\n if (this._predicate === null)\n object = this._subject, this._subject = subject;\n // If we were reading an object, replace the subject by the path's subject\n else\n object = this._object, this._object = subject;\n // Emit the path's current quad and read its next section\n this._emit(subject, predicate, object, this._graph);\n return this._readPath;\n }\n\n // ### `_readRDFStarTailOrGraph` reads the graph of a nested RDF-star quad or the end of a nested RDF-star triple\n _readRDFStarTailOrGraph(token) {\n if (token.type !== '>>') {\n // An entity means this is a quad (only allowed if not already inside a graph)\n if (this._supportsQuads && this._graph === null && (this._graph = this._readEntity(token)) !== undefined)\n return this._readRDFStarTail;\n return this._error(`Expected >> to follow \"${this._object.id}\"`, token);\n }\n return this._readRDFStarTail(token);\n }\n\n // ### `_readRDFStarTail` reads the end of a nested RDF-star triple\n _readRDFStarTail(token) {\n if (token.type !== '>>')\n return this._error(`Expected >> but got ${token.type}`, token);\n // Read the quad and restore the previous context\n const quad = this._factory.quad(this._subject, this._predicate, this._object,\n this._graph || this.DEFAULTGRAPH);\n this._restoreContext('<<', token);\n // If the triple was the subject, continue by reading the predicate.\n if (this._subject === null) {\n this._subject = quad;\n return this._readPredicate;\n }\n // If the triple was the object, read context end.\n else {\n this._object = quad;\n return this._getContextEndReader();\n }\n }\n\n // ### `_getContextEndReader` gets the next reader function at the end of a context\n _getContextEndReader() {\n const contextStack = this._contextStack;\n if (!contextStack.length)\n return this._readPunctuation;\n\n switch (contextStack[contextStack.length - 1].type) {\n case 'blank':\n return this._readBlankNodeTail;\n case 'list':\n return this._readListItem;\n case 'formula':\n return this._readFormulaTail;\n case '<<':\n return this._readRDFStarTailOrGraph;\n }\n }\n\n // ### `_emit` sends a quad through the callback\n _emit(subject, predicate, object, graph) {\n this._callback(null, this._factory.quad(subject, predicate, object, graph || this.DEFAULTGRAPH));\n }\n\n // ### `_error` emits an error message through the callback\n _error(message, token) {\n const err = new Error(`${message} on line ${token.line}.`);\n err.context = {\n token: token,\n line: token.line,\n previousToken: this._lexer.previousToken,\n };\n this._callback(err);\n this._callback = noop;\n }\n\n // ### `_resolveIRI` resolves an IRI against the base path\n _resolveIRI(iri) {\n return /^[a-z][a-z0-9+.-]*:/i.test(iri) ? iri : this._resolveRelativeIRI(iri);\n }\n\n // ### `_resolveRelativeIRI` resolves an IRI against the base path,\n // assuming that a base path has been set and that the IRI is indeed relative\n _resolveRelativeIRI(iri) {\n // An empty relative IRI indicates the base IRI\n if (!iri.length)\n return this._base;\n // Decide resolving strategy based in the first character\n switch (iri[0]) {\n // Resolve relative fragment IRIs against the base IRI\n case '#': return this._base + iri;\n // Resolve relative query string IRIs by replacing the query string\n case '?': return this._base.replace(/(?:\\?.*)?$/, iri);\n // Resolve root-relative IRIs at the root of the base IRI\n case '/':\n // Resolve scheme-relative IRIs to the scheme\n return (iri[1] === '/' ? this._baseScheme : this._baseRoot) + this._removeDotSegments(iri);\n // Resolve all other IRIs at the base IRI's path\n default:\n // Relative IRIs cannot contain a colon in the first path segment\n return (/^[^/:]*:/.test(iri)) ? null : this._removeDotSegments(this._basePath + iri);\n }\n }\n\n // ### `_removeDotSegments` resolves './' and '../' path segments in an IRI as per RFC3986\n _removeDotSegments(iri) {\n // Don't modify the IRI if it does not contain any dot segments\n if (!/(^|\\/)\\.\\.?($|[/#?])/.test(iri))\n return iri;\n\n // Start with an imaginary slash before the IRI in order to resolve trailing './' and '../'\n const length = iri.length;\n let result = '', i = -1, pathStart = -1, segmentStart = 0, next = '/';\n\n while (i < length) {\n switch (next) {\n // The path starts with the first slash after the authority\n case ':':\n if (pathStart < 0) {\n // Skip two slashes before the authority\n if (iri[++i] === '/' && iri[++i] === '/')\n // Skip to slash after the authority\n while ((pathStart = i + 1) < length && iri[pathStart] !== '/')\n i = pathStart;\n }\n break;\n // Don't modify a query string or fragment\n case '?':\n case '#':\n i = length;\n break;\n // Handle '/.' or '/..' path segments\n case '/':\n if (iri[i + 1] === '.') {\n next = iri[++i + 1];\n switch (next) {\n // Remove a '/.' segment\n case '/':\n result += iri.substring(segmentStart, i - 1);\n segmentStart = i + 1;\n break;\n // Remove a trailing '/.' segment\n case undefined:\n case '?':\n case '#':\n return result + iri.substring(segmentStart, i) + iri.substr(i + 1);\n // Remove a '/..' segment\n case '.':\n next = iri[++i + 1];\n if (next === undefined || next === '/' || next === '?' || next === '#') {\n result += iri.substring(segmentStart, i - 2);\n // Try to remove the parent path from result\n if ((segmentStart = result.lastIndexOf('/')) >= pathStart)\n result = result.substr(0, segmentStart);\n // Remove a trailing '/..' segment\n if (next !== '/')\n return `${result}/${iri.substr(i + 1)}`;\n segmentStart = i + 1;\n }\n }\n }\n }\n next = iri[++i];\n }\n return result + iri.substring(segmentStart);\n }\n\n // ## Public methods\n\n // ### `parse` parses the N3 input and emits each parsed quad through the onQuad callback.\n parse(input, quadCallback, prefixCallback) {\n // The second parameter accepts an object { onQuad: ..., onPrefix: ..., onComment: ...}\n // As a second and third parameter it still accepts a separate quadCallback and prefixCallback for backward compatibility as well\n let onQuad, onPrefix, onComment;\n if (quadCallback && (quadCallback.onQuad || quadCallback.onPrefix || quadCallback.onComment)) {\n onQuad = quadCallback.onQuad;\n onPrefix = quadCallback.onPrefix;\n onComment = quadCallback.onComment;\n }\n else {\n onQuad = quadCallback;\n onPrefix = prefixCallback;\n }\n // The read callback is the next function to be executed when a token arrives.\n // We start reading in the top context.\n this._readCallback = this._readInTopContext;\n this._sparqlStyle = false;\n this._prefixes = Object.create(null);\n this._prefixes._ = this._blankNodePrefix ? this._blankNodePrefix.substr(2)\n : `b${blankNodePrefix++}_`;\n this._prefixCallback = onPrefix || noop;\n this._inversePredicate = false;\n this._quantified = Object.create(null);\n\n // Parse synchronously if no quad callback is given\n if (!onQuad) {\n const quads = [];\n let error;\n this._callback = (e, t) => { e ? (error = e) : t && quads.push(t); };\n this._lexer.tokenize(input).every(token => {\n return this._readCallback = this._readCallback(token);\n });\n if (error) throw error;\n return quads;\n }\n\n let processNextToken = (error, token) => {\n if (error !== null)\n this._callback(error), this._callback = noop;\n else if (this._readCallback)\n this._readCallback = this._readCallback(token);\n };\n\n // Enable checking for comments on every token when a commentCallback has been set\n if (onComment) {\n // Enable the lexer to return comments as tokens first (disabled by default)\n this._lexer.comments = true;\n // Patch the processNextToken function\n processNextToken = (error, token) => {\n if (error !== null)\n this._callback(error), this._callback = noop;\n else if (this._readCallback) {\n if (token.type === 'comment')\n onComment(token.value);\n else\n this._readCallback = this._readCallback(token);\n }\n };\n }\n\n // Parse asynchronously otherwise, executing the read callback when a token arrives\n this._callback = onQuad;\n this._lexer.tokenize(input, processNextToken);\n }\n}\n\n// The empty function\nfunction noop() {}\n\n// Initializes the parser with the given data factory\nfunction initDataFactory(parser, factory) {\n parser._factory = factory;\n\n parser.DEFAULTGRAPH = factory.defaultGraph();\n\n // Set common named nodes\n parser.RDF_FIRST = factory.namedNode(namespaces.rdf.first);\n parser.RDF_REST = factory.namedNode(namespaces.rdf.rest);\n parser.RDF_NIL = factory.namedNode(namespaces.rdf.nil);\n parser.N3_FORALL = factory.namedNode(namespaces.r.forAll);\n parser.N3_FORSOME = factory.namedNode(namespaces.r.forSome);\n parser.ABBREVIATIONS = {\n 'a': factory.namedNode(namespaces.rdf.type),\n '=': factory.namedNode(namespaces.owl.sameAs),\n '>': factory.namedNode(namespaces.log.implies),\n };\n parser.QUANTIFIERS_GRAPH = factory.namedNode('urn:n3:quantifiers');\n}\ninitDataFactory(N3Parser.prototype, N3DataFactory);\n","// **N3Util** provides N3 utility functions.\n\nimport N3DataFactory from './N3DataFactory';\n\n// Tests whether the given term represents an IRI\nexport function isNamedNode(term) {\n return !!term && term.termType === 'NamedNode';\n}\n\n// Tests whether the given term represents a blank node\nexport function isBlankNode(term) {\n return !!term && term.termType === 'BlankNode';\n}\n\n// Tests whether the given term represents a literal\nexport function isLiteral(term) {\n return !!term && term.termType === 'Literal';\n}\n\n// Tests whether the given term represents a variable\nexport function isVariable(term) {\n return !!term && term.termType === 'Variable';\n}\n\n// Tests whether the given term represents the default graph\nexport function isDefaultGraph(term) {\n return !!term && term.termType === 'DefaultGraph';\n}\n\n// Tests whether the given quad is in the default graph\nexport function inDefaultGraph(quad) {\n return isDefaultGraph(quad.graph);\n}\n\n// Creates a function that prepends the given IRI to a local name\nexport function prefix(iri, factory) {\n return prefixes({ '': iri.value || iri }, factory)('');\n}\n\n// Creates a function that allows registering and expanding prefixes\nexport function prefixes(defaultPrefixes, factory) {\n // Add all of the default prefixes\n const prefixes = Object.create(null);\n for (const prefix in defaultPrefixes)\n processPrefix(prefix, defaultPrefixes[prefix]);\n // Set the default factory if none was specified\n factory = factory || N3DataFactory;\n\n // Registers a new prefix (if an IRI was specified)\n // or retrieves a function that expands an existing prefix (if no IRI was specified)\n function processPrefix(prefix, iri) {\n // Create a new prefix if an IRI is specified or the prefix doesn't exist\n if (typeof iri === 'string') {\n // Create a function that expands the prefix\n const cache = Object.create(null);\n prefixes[prefix] = local => {\n return cache[local] || (cache[local] = factory.namedNode(iri + local));\n };\n }\n else if (!(prefix in prefixes)) {\n throw new Error(`Unknown prefix: ${prefix}`);\n }\n return prefixes[prefix];\n }\n return processPrefix;\n}\n","// **N3Writer** writes N3 documents.\nimport namespaces from './IRIs';\nimport { default as N3DataFactory, Term } from './N3DataFactory';\nimport { isDefaultGraph } from './N3Util';\n\nconst DEFAULTGRAPH = N3DataFactory.defaultGraph();\n\nconst { rdf, xsd } = namespaces;\n\n// Characters in literals that require escaping\nconst escape = /[\"\\\\\\t\\n\\r\\b\\f\\u0000-\\u0019\\ud800-\\udbff]/,\n escapeAll = /[\"\\\\\\t\\n\\r\\b\\f\\u0000-\\u0019]|[\\ud800-\\udbff][\\udc00-\\udfff]/g,\n escapedCharacters = {\n '\\\\': '\\\\\\\\', '\"': '\\\\\"', '\\t': '\\\\t',\n '\\n': '\\\\n', '\\r': '\\\\r', '\\b': '\\\\b', '\\f': '\\\\f',\n };\n\n// ## Placeholder class to represent already pretty-printed terms\nclass SerializedTerm extends Term {\n // Pretty-printed nodes are not equal to any other node\n // (e.g., [] does not equal [])\n equals(other) {\n return other === this;\n }\n}\n\n// ## Constructor\nexport default class N3Writer {\n constructor(outputStream, options) {\n // ### `_prefixRegex` matches a prefixed name or IRI that begins with one of the added prefixes\n this._prefixRegex = /$0^/;\n\n // Shift arguments if the first argument is not a stream\n if (outputStream && typeof outputStream.write !== 'function')\n options = outputStream, outputStream = null;\n options = options || {};\n this._lists = options.lists;\n\n // If no output stream given, send the output as string through the end callback\n if (!outputStream) {\n let output = '';\n this._outputStream = {\n write(chunk, encoding, done) { output += chunk; done && done(); },\n end: done => { done && done(null, output); },\n };\n this._endStream = true;\n }\n else {\n this._outputStream = outputStream;\n this._endStream = options.end === undefined ? true : !!options.end;\n }\n\n // Initialize writer, depending on the format\n this._subject = null;\n if (!(/triple|quad/i).test(options.format)) {\n this._lineMode = false;\n this._graph = DEFAULTGRAPH;\n this._prefixIRIs = Object.create(null);\n options.prefixes && this.addPrefixes(options.prefixes);\n if (options.baseIRI) {\n this._baseMatcher = new RegExp(`^${escapeRegex(options.baseIRI)\n }${options.baseIRI.endsWith('/') ? '' : '[#?]'}`);\n this._baseLength = options.baseIRI.length;\n }\n }\n else {\n this._lineMode = true;\n this._writeQuad = this._writeQuadLine;\n }\n }\n\n // ## Private methods\n\n // ### Whether the current graph is the default graph\n get _inDefaultGraph() {\n return DEFAULTGRAPH.equals(this._graph);\n }\n\n // ### `_write` writes the argument to the output stream\n _write(string, callback) {\n this._outputStream.write(string, 'utf8', callback);\n }\n\n // ### `_writeQuad` writes the quad to the output stream\n _writeQuad(subject, predicate, object, graph, done) {\n try {\n // Write the graph's label if it has changed\n if (!graph.equals(this._graph)) {\n // Close the previous graph and start the new one\n this._write((this._subject === null ? '' : (this._inDefaultGraph ? '.\\n' : '\\n}\\n')) +\n (DEFAULTGRAPH.equals(graph) ? '' : `${this._encodeIriOrBlank(graph)} {\\n`));\n this._graph = graph;\n this._subject = null;\n }\n // Don't repeat the subject if it's the same\n if (subject.equals(this._subject)) {\n // Don't repeat the predicate if it's the same\n if (predicate.equals(this._predicate))\n this._write(`, ${this._encodeObject(object)}`, done);\n // Same subject, different predicate\n else\n this._write(`;\\n ${\n this._encodePredicate(this._predicate = predicate)} ${\n this._encodeObject(object)}`, done);\n }\n // Different subject; write the whole quad\n else\n this._write(`${(this._subject === null ? '' : '.\\n') +\n this._encodeSubject(this._subject = subject)} ${\n this._encodePredicate(this._predicate = predicate)} ${\n this._encodeObject(object)}`, done);\n }\n catch (error) { done && done(error); }\n }\n\n // ### `_writeQuadLine` writes the quad to the output stream as a single line\n _writeQuadLine(subject, predicate, object, graph, done) {\n // Write the quad without prefixes\n delete this._prefixMatch;\n this._write(this.quadToString(subject, predicate, object, graph), done);\n }\n\n // ### `quadToString` serializes a quad as a string\n quadToString(subject, predicate, object, graph) {\n return `${this._encodeSubject(subject)} ${\n this._encodeIriOrBlank(predicate)} ${\n this._encodeObject(object)\n }${graph && graph.value ? ` ${this._encodeIriOrBlank(graph)} .\\n` : ' .\\n'}`;\n }\n\n // ### `quadsToString` serializes an array of quads as a string\n quadsToString(quads) {\n let quadsString = '';\n for (const quad of quads)\n quadsString += this.quadToString(quad.subject, quad.predicate, quad.object, quad.graph);\n return quadsString;\n }\n\n // ### `_encodeSubject` represents a subject\n _encodeSubject(entity) {\n return entity.termType === 'Quad' ?\n this._encodeQuad(entity) : this._encodeIriOrBlank(entity);\n }\n\n // ### `_encodeIriOrBlank` represents an IRI or blank node\n _encodeIriOrBlank(entity) {\n // A blank node or list is represented as-is\n if (entity.termType !== 'NamedNode') {\n // If it is a list head, pretty-print it\n if (this._lists && (entity.value in this._lists))\n entity = this.list(this._lists[entity.value]);\n return 'id' in entity ? entity.id : `_:${entity.value}`;\n }\n let iri = entity.value;\n // Use relative IRIs if requested and possible\n if (this._baseMatcher && this._baseMatcher.test(iri))\n iri = iri.substr(this._baseLength);\n // Escape special characters\n if (escape.test(iri))\n iri = iri.replace(escapeAll, characterReplacer);\n // Try to represent the IRI as prefixed name\n const prefixMatch = this._prefixRegex.exec(iri);\n return !prefixMatch ? `<${iri}>` :\n (!prefixMatch[1] ? iri : this._prefixIRIs[prefixMatch[1]] + prefixMatch[2]);\n }\n\n // ### `_encodeLiteral` represents a literal\n _encodeLiteral(literal) {\n // Escape special characters\n let value = literal.value;\n if (escape.test(value))\n value = value.replace(escapeAll, characterReplacer);\n\n // Write a language-tagged literal\n if (literal.language)\n return `\"${value}\"@${literal.language}`;\n\n // Write dedicated literals per data type\n if (this._lineMode) {\n // Only abbreviate strings in N-Triples or N-Quads\n if (literal.datatype.value === xsd.string)\n return `\"${value}\"`;\n }\n else {\n // Use common datatype abbreviations in Turtle or TriG\n switch (literal.datatype.value) {\n case xsd.string:\n return `\"${value}\"`;\n case xsd.boolean:\n if (value === 'true' || value === 'false')\n return value;\n break;\n case xsd.integer:\n if (/^[+-]?\\d+$/.test(value))\n return value;\n break;\n case xsd.decimal:\n if (/^[+-]?\\d*\\.\\d+$/.test(value))\n return value;\n break;\n case xsd.double:\n if (/^[+-]?(?:\\d+\\.\\d*|\\.?\\d+)[eE][+-]?\\d+$/.test(value))\n return value;\n break;\n }\n }\n\n // Write a regular datatyped literal\n return `\"${value}\"^^${this._encodeIriOrBlank(literal.datatype)}`;\n }\n\n // ### `_encodePredicate` represents a predicate\n _encodePredicate(predicate) {\n return predicate.value === rdf.type ? 'a' : this._encodeIriOrBlank(predicate);\n }\n\n // ### `_encodeObject` represents an object\n _encodeObject(object) {\n switch (object.termType) {\n case 'Quad':\n return this._encodeQuad(object);\n case 'Literal':\n return this._encodeLiteral(object);\n default:\n return this._encodeIriOrBlank(object);\n }\n }\n\n // ### `_encodeQuad` encodes an RDF-star quad\n _encodeQuad({ subject, predicate, object, graph }) {\n return `<<${\n this._encodeSubject(subject)} ${\n this._encodePredicate(predicate)} ${\n this._encodeObject(object)}${\n isDefaultGraph(graph) ? '' : ` ${this._encodeIriOrBlank(graph)}`}>>`;\n }\n\n // ### `_blockedWrite` replaces `_write` after the writer has been closed\n _blockedWrite() {\n throw new Error('Cannot write because the writer has been closed.');\n }\n\n // ### `addQuad` adds the quad to the output stream\n addQuad(subject, predicate, object, graph, done) {\n // The quad was given as an object, so shift parameters\n if (object === undefined)\n this._writeQuad(subject.subject, subject.predicate, subject.object, subject.graph, predicate);\n // The optional `graph` parameter was not provided\n else if (typeof graph === 'function')\n this._writeQuad(subject, predicate, object, DEFAULTGRAPH, graph);\n // The `graph` parameter was provided\n else\n this._writeQuad(subject, predicate, object, graph || DEFAULTGRAPH, done);\n }\n\n // ### `addQuads` adds the quads to the output stream\n addQuads(quads) {\n for (let i = 0; i < quads.length; i++)\n this.addQuad(quads[i]);\n }\n\n // ### `addPrefix` adds the prefix to the output stream\n addPrefix(prefix, iri, done) {\n const prefixes = {};\n prefixes[prefix] = iri;\n this.addPrefixes(prefixes, done);\n }\n\n // ### `addPrefixes` adds the prefixes to the output stream\n addPrefixes(prefixes, done) {\n // Ignore prefixes if not supported by the serialization\n if (!this._prefixIRIs)\n return done && done();\n\n // Write all new prefixes\n let hasPrefixes = false;\n for (let prefix in prefixes) {\n let iri = prefixes[prefix];\n if (typeof iri !== 'string')\n iri = iri.value;\n hasPrefixes = true;\n // Finish a possible pending quad\n if (this._subject !== null) {\n this._write(this._inDefaultGraph ? '.\\n' : '\\n}\\n');\n this._subject = null, this._graph = '';\n }\n // Store and write the prefix\n this._prefixIRIs[iri] = (prefix += ':');\n this._write(`@prefix ${prefix} <${iri}>.\\n`);\n }\n // Recreate the prefix matcher\n if (hasPrefixes) {\n let IRIlist = '', prefixList = '';\n for (const prefixIRI in this._prefixIRIs) {\n IRIlist += IRIlist ? `|${prefixIRI}` : prefixIRI;\n prefixList += (prefixList ? '|' : '') + this._prefixIRIs[prefixIRI];\n }\n IRIlist = escapeRegex(IRIlist, /[\\]\\/\\(\\)\\*\\+\\?\\.\\\\\\$]/g, '\\\\$&');\n this._prefixRegex = new RegExp(`^(?:${prefixList})[^\\/]*$|` +\n `^(${IRIlist})([_a-zA-Z0-9][\\\\-_a-zA-Z0-9]*)$`);\n }\n // End a prefix block with a newline\n this._write(hasPrefixes ? '\\n' : '', done);\n }\n\n // ### `blank` creates a blank node with the given content\n blank(predicate, object) {\n let children = predicate, child, length;\n // Empty blank node\n if (predicate === undefined)\n children = [];\n // Blank node passed as blank(Term(\"predicate\"), Term(\"object\"))\n else if (predicate.termType)\n children = [{ predicate: predicate, object: object }];\n // Blank node passed as blank({ predicate: predicate, object: object })\n else if (!('length' in predicate))\n children = [predicate];\n\n switch (length = children.length) {\n // Generate an empty blank node\n case 0:\n return new SerializedTerm('[]');\n // Generate a non-nested one-triple blank node\n case 1:\n child = children[0];\n if (!(child.object instanceof SerializedTerm))\n return new SerializedTerm(`[ ${this._encodePredicate(child.predicate)} ${\n this._encodeObject(child.object)} ]`);\n // Generate a multi-triple or nested blank node\n default:\n let contents = '[';\n // Write all triples in order\n for (let i = 0; i < length; i++) {\n child = children[i];\n // Write only the object is the predicate is the same as the previous\n if (child.predicate.equals(predicate))\n contents += `, ${this._encodeObject(child.object)}`;\n // Otherwise, write the predicate and the object\n else {\n contents += `${(i ? ';\\n ' : '\\n ') +\n this._encodePredicate(child.predicate)} ${\n this._encodeObject(child.object)}`;\n predicate = child.predicate;\n }\n }\n return new SerializedTerm(`${contents}\\n]`);\n }\n }\n\n // ### `list` creates a list node with the given content\n list(elements) {\n const length = elements && elements.length || 0, contents = new Array(length);\n for (let i = 0; i < length; i++)\n contents[i] = this._encodeObject(elements[i]);\n return new SerializedTerm(`(${contents.join(' ')})`);\n }\n\n // ### `end` signals the end of the output stream\n end(done) {\n // Finish a possible pending quad\n if (this._subject !== null) {\n this._write(this._inDefaultGraph ? '.\\n' : '\\n}\\n');\n this._subject = null;\n }\n // Disallow further writing\n this._write = this._blockedWrite;\n\n // Try to end the underlying stream, ensuring done is called exactly one time\n let singleDone = done && ((error, result) => { singleDone = null, done(error, result); });\n if (this._endStream) {\n try { return this._outputStream.end(singleDone); }\n catch (error) { /* error closing stream */ }\n }\n singleDone && singleDone();\n }\n}\n\n// Replaces a character by its escaped version\nfunction characterReplacer(character) {\n // Replace a single character by its escaped version\n let result = escapedCharacters[character];\n if (result === undefined) {\n // Replace a single character with its 4-bit unicode escape sequence\n if (character.length === 1) {\n result = character.charCodeAt(0).toString(16);\n result = '\\\\u0000'.substr(0, 6 - result.length) + result;\n }\n // Replace a surrogate pair with its 8-bit unicode escape sequence\n else {\n result = ((character.charCodeAt(0) - 0xD800) * 0x400 +\n character.charCodeAt(1) + 0x2400).toString(16);\n result = '\\\\U00000000'.substr(0, 10 - result.length) + result;\n }\n }\n return result;\n}\n\nfunction escapeRegex(regex) {\n return regex.replace(/[\\]\\/\\(\\)\\*\\+\\?\\.\\\\\\$]/g, '\\\\$&');\n}\n","// **N3Store** objects store N3 quads by graph in memory.\nimport { Readable } from 'readable-stream';\nimport { default as N3DataFactory, termToId, termFromId } from './N3DataFactory';\nimport namespaces from './IRIs';\nimport { isDefaultGraph } from './N3Util';\nimport N3Writer from './N3Writer';\n\nconst ITERATOR = Symbol('iter');\n\nfunction merge(target, source, depth = 4) {\n if (depth === 0)\n return Object.assign(target, source);\n\n for (const key in source)\n target[key] = merge(target[key] || Object.create(null), source[key], depth - 1);\n\n return target;\n}\n\n/**\n * Determines the intersection of the `_graphs` index s1 and s2.\n * s1 and s2 *must* belong to Stores that share an `_entityIndex`.\n *\n * False is returned when there is no intersection; this should\n * *not* be set as the value for an index.\n */\nfunction intersect(s1, s2, depth = 4) {\n let target = false;\n\n for (const key in s1) {\n if (key in s2) {\n const intersection = depth === 0 ? null : intersect(s1[key], s2[key], depth - 1);\n if (intersection !== false) {\n target = target || Object.create(null);\n target[key] = intersection;\n }\n // Depth 3 is the 'subjects', 'predicates' and 'objects' keys.\n // If the 'subjects' index is empty, so will the 'predicates' and 'objects' index.\n else if (depth === 3) {\n return false;\n }\n }\n }\n\n return target;\n}\n\n/**\n * Determines the difference of the `_graphs` index s1 and s2.\n * s1 and s2 *must* belong to Stores that share an `_entityIndex`.\n *\n * False is returned when there is no difference; this should\n * *not* be set as the value for an index.\n */\nfunction difference(s1, s2, depth = 4) {\n let target = false;\n\n for (const key in s1) {\n // When the key is not in the index, then none of the triples defined by s1[key] are\n // in s2 and so we want to copy them over to the resultant store.\n if (!(key in s2)) {\n target = target || Object.create(null);\n target[key] = depth === 0 ? null : merge({}, s1[key], depth - 1);\n }\n else if (depth !== 0) {\n const diff = difference(s1[key], s2[key], depth - 1);\n if (diff !== false) {\n target = target || Object.create(null);\n target[key] = diff;\n }\n // Depth 3 is the 'subjects', 'predicates' and 'objects' keys.\n // If the 'subjects' index is empty, so will the 'predicates' and 'objects' index.\n else if (depth === 3) {\n return false;\n }\n }\n }\n\n return target;\n}\n\n// ## Constructor\nexport class N3EntityIndex {\n constructor(options = {}) {\n this._id = 1;\n // `_ids` maps entities such as `http://xmlns.com/foaf/0.1/name` to numbers,\n // saving memory by using only numbers as keys in `_graphs`\n this._ids = Object.create(null);\n this._ids[''] = 1;\n // inverse of `_ids`\n this._entities = Object.create(null);\n this._entities[1] = '';\n // `_blankNodeIndex` is the index of the last automatically named blank node\n this._blankNodeIndex = 0;\n this._factory = options.factory || N3DataFactory;\n }\n\n _termFromId(id) {\n if (id[0] === '.') {\n const entities = this._entities;\n const terms = id.split('.');\n const q = this._factory.quad(\n this._termFromId(entities[terms[1]]),\n this._termFromId(entities[terms[2]]),\n this._termFromId(entities[terms[3]]),\n terms[4] && this._termFromId(entities[terms[4]]),\n );\n return q;\n }\n return termFromId(id, this._factory);\n }\n\n _termToNumericId(term) {\n if (term.termType === 'Quad') {\n const s = this._termToNumericId(term.subject),\n p = this._termToNumericId(term.predicate),\n o = this._termToNumericId(term.object);\n let g;\n\n return s && p && o && (isDefaultGraph(term.graph) || (g = this._termToNumericId(term.graph))) &&\n this._ids[g ? `.${s}.${p}.${o}.${g}` : `.${s}.${p}.${o}`];\n }\n return this._ids[termToId(term)];\n }\n\n _termToNewNumericId(term) {\n // This assumes that no graph term is present - we may wish to error if there is one\n const str = term && term.termType === 'Quad' ?\n `.${this._termToNewNumericId(term.subject)}.${this._termToNewNumericId(term.predicate)}.${this._termToNewNumericId(term.object)}${\n isDefaultGraph(term.graph) ? '' : `.${this._termToNewNumericId(term.graph)}`\n }`\n : termToId(term);\n\n return this._ids[str] || (this._ids[this._entities[++this._id] = str] = this._id);\n }\n\n createBlankNode(suggestedName) {\n let name, index;\n // Generate a name based on the suggested name\n if (suggestedName) {\n name = suggestedName = `_:${suggestedName}`, index = 1;\n while (this._ids[name])\n name = suggestedName + index++;\n }\n // Generate a generic blank node name\n else {\n do { name = `_:b${this._blankNodeIndex++}`; }\n while (this._ids[name]);\n }\n // Add the blank node to the entities, avoiding the generation of duplicates\n this._ids[name] = ++this._id;\n this._entities[this._id] = name;\n return this._factory.blankNode(name.substr(2));\n }\n}\n\n// ## Constructor\nexport default class N3Store {\n constructor(quads, options) {\n // The number of quads is initially zero\n this._size = 0;\n // `_graphs` contains subject, predicate, and object indexes per graph\n this._graphs = Object.create(null);\n\n // Shift parameters if `quads` is not given\n if (!options && quads && !quads[0])\n options = quads, quads = null;\n options = options || {};\n this._factory = options.factory || N3DataFactory;\n this._entityIndex = options.entityIndex || new N3EntityIndex({ factory: this._factory });\n this._entities = this._entityIndex._entities;\n this._termFromId = this._entityIndex._termFromId.bind(this._entityIndex);\n this._termToNumericId = this._entityIndex._termToNumericId.bind(this._entityIndex);\n this._termToNewNumericId = this._entityIndex._termToNewNumericId.bind(this._entityIndex);\n\n // Add quads if passed\n if (quads)\n this.addQuads(quads);\n }\n\n // ## Public properties\n\n // ### `size` returns the number of quads in the store\n get size() {\n // Return the quad count if if was cached\n let size = this._size;\n if (size !== null)\n return size;\n\n // Calculate the number of quads by counting to the deepest level\n size = 0;\n const graphs = this._graphs;\n let subjects, subject;\n for (const graphKey in graphs)\n for (const subjectKey in (subjects = graphs[graphKey].subjects))\n for (const predicateKey in (subject = subjects[subjectKey]))\n size += Object.keys(subject[predicateKey]).length;\n return this._size = size;\n }\n\n // ## Private methods\n\n // ### `_addToIndex` adds a quad to a three-layered index.\n // Returns if the index has changed, if the entry did not already exist.\n _addToIndex(index0, key0, key1, key2) {\n // Create layers as necessary\n const index1 = index0[key0] || (index0[key0] = {});\n const index2 = index1[key1] || (index1[key1] = {});\n // Setting the key to _any_ value signals the presence of the quad\n const existed = key2 in index2;\n if (!existed)\n index2[key2] = null;\n return !existed;\n }\n\n // ### `_removeFromIndex` removes a quad from a three-layered index\n _removeFromIndex(index0, key0, key1, key2) {\n // Remove the quad from the index\n const index1 = index0[key0], index2 = index1[key1];\n delete index2[key2];\n\n // Remove intermediary index layers if they are empty\n for (const key in index2) return;\n delete index1[key1];\n for (const key in index1) return;\n delete index0[key0];\n }\n\n // ### `_findInIndex` finds a set of quads in a three-layered index.\n // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`.\n // Any of these keys can be undefined, which is interpreted as a wildcard.\n // `name0`, `name1`, and `name2` are the names of the keys at each level,\n // used when reconstructing the resulting quad\n // (for instance: _subject_, _predicate_, and _object_).\n // Finally, `graphId` will be the graph of the created quads.\n *_findInIndex(index0, key0, key1, key2, name0, name1, name2, graphId) {\n let tmp, index1, index2;\n const entityKeys = this._entities;\n const graph = this._termFromId(entityKeys[graphId]);\n const parts = { subject: null, predicate: null, object: null };\n\n // If a key is specified, use only that part of index 0.\n if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0];\n for (const value0 in index0) {\n if (index1 = index0[value0]) {\n parts[name0] = this._termFromId(entityKeys[value0]);\n // If a key is specified, use only that part of index 1.\n if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1];\n for (const value1 in index1) {\n if (index2 = index1[value1]) {\n parts[name1] = this._termFromId(entityKeys[value1]);\n // If a key is specified, use only that part of index 2, if it exists.\n const values = key2 ? (key2 in index2 ? [key2] : []) : Object.keys(index2);\n // Create quads for all items found in index 2.\n for (let l = 0; l < values.length; l++) {\n parts[name2] = this._termFromId(entityKeys[values[l]]);\n yield this._factory.quad(parts.subject, parts.predicate, parts.object, graph);\n }\n }\n }\n }\n }\n }\n\n // ### `_loop` executes the callback on all keys of index 0\n _loop(index0, callback) {\n for (const key0 in index0)\n callback(key0);\n }\n\n // ### `_loopByKey0` executes the callback on all keys of a certain entry in index 0\n _loopByKey0(index0, key0, callback) {\n let index1, key1;\n if (index1 = index0[key0]) {\n for (key1 in index1)\n callback(key1);\n }\n }\n\n // ### `_loopByKey1` executes the callback on given keys of all entries in index 0\n _loopByKey1(index0, key1, callback) {\n let key0, index1;\n for (key0 in index0) {\n index1 = index0[key0];\n if (index1[key1])\n callback(key0);\n }\n }\n\n // ### `_loopBy2Keys` executes the callback on given keys of certain entries in index 2\n _loopBy2Keys(index0, key0, key1, callback) {\n let index1, index2, key2;\n if ((index1 = index0[key0]) && (index2 = index1[key1])) {\n for (key2 in index2)\n callback(key2);\n }\n }\n\n // ### `_countInIndex` counts matching quads in a three-layered index.\n // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`.\n // Any of these keys can be undefined, which is interpreted as a wildcard.\n _countInIndex(index0, key0, key1, key2) {\n let count = 0, tmp, index1, index2;\n\n // If a key is specified, count only that part of index 0\n if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0];\n for (const value0 in index0) {\n if (index1 = index0[value0]) {\n // If a key is specified, count only that part of index 1\n if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1];\n for (const value1 in index1) {\n if (index2 = index1[value1]) {\n // If a key is specified, count the quad if it exists\n if (key2) (key2 in index2) && count++;\n // Otherwise, count all quads\n else count += Object.keys(index2).length;\n }\n }\n }\n }\n return count;\n }\n\n // ### `_getGraphs` returns an array with the given graph,\n // or all graphs if the argument is null or undefined.\n _getGraphs(graph) {\n graph = graph === '' ? 1 : (graph && (this._termToNumericId(graph) || -1));\n return typeof graph !== 'number' ? this._graphs : { [graph]: this._graphs[graph] };\n }\n\n // ### `_uniqueEntities` returns a function that accepts an entity ID\n // and passes the corresponding entity to callback if it hasn't occurred before.\n _uniqueEntities(callback) {\n const uniqueIds = Object.create(null);\n return id => {\n if (!(id in uniqueIds)) {\n uniqueIds[id] = true;\n callback(this._termFromId(this._entities[id], this._factory));\n }\n };\n }\n\n // ## Public methods\n\n // ### `add` adds the specified quad to the dataset.\n // Returns the dataset instance it was called on.\n // Existing quads, as defined in Quad.equals, will be ignored.\n add(quad) {\n this.addQuad(quad);\n return this;\n }\n\n // ### `addQuad` adds a new quad to the store.\n // Returns if the quad index has changed, if the quad did not already exist.\n addQuad(subject, predicate, object, graph) {\n // Shift arguments if a quad object is given instead of components\n if (!predicate)\n graph = subject.graph, object = subject.object,\n predicate = subject.predicate, subject = subject.subject;\n\n // Convert terms to internal string representation\n graph = graph ? this._termToNewNumericId(graph) : 1;\n\n // Find the graph that will contain the triple\n let graphItem = this._graphs[graph];\n // Create the graph if it doesn't exist yet\n if (!graphItem) {\n graphItem = this._graphs[graph] = { subjects: {}, predicates: {}, objects: {} };\n // Freezing a graph helps subsequent `add` performance,\n // and properties will never be modified anyway\n Object.freeze(graphItem);\n }\n\n // Since entities can often be long IRIs, we avoid storing them in every index.\n // Instead, we have a separate index that maps entities to numbers,\n // which are then used as keys in the other indexes.\n subject = this._termToNewNumericId(subject);\n predicate = this._termToNewNumericId(predicate);\n object = this._termToNewNumericId(object);\n\n if (!this._addToIndex(graphItem.subjects, subject, predicate, object))\n return false;\n this._addToIndex(graphItem.predicates, predicate, object, subject);\n this._addToIndex(graphItem.objects, object, subject, predicate);\n\n // The cached quad count is now invalid\n this._size = null;\n return true;\n }\n\n // ### `addQuads` adds multiple quads to the store\n addQuads(quads) {\n for (let i = 0; i < quads.length; i++)\n this.addQuad(quads[i]);\n }\n\n // ### `delete` removes the specified quad from the dataset.\n // Returns the dataset instance it was called on.\n delete(quad) {\n this.removeQuad(quad);\n return this;\n }\n\n // ### `has` determines whether a dataset includes a certain quad or quad pattern.\n has(subjectOrQuad, predicate, object, graph) {\n if (subjectOrQuad && subjectOrQuad.subject)\n ({ subject: subjectOrQuad, predicate, object, graph } = subjectOrQuad);\n return !this.readQuads(subjectOrQuad, predicate, object, graph).next().done;\n }\n\n // ### `import` adds a stream of quads to the store\n import(stream) {\n stream.on('data', quad => { this.addQuad(quad); });\n return stream;\n }\n\n // ### `removeQuad` removes a quad from the store if it exists\n removeQuad(subject, predicate, object, graph) {\n // Shift arguments if a quad object is given instead of components\n if (!predicate)\n ({ subject, predicate, object, graph } = subject);\n // Convert terms to internal string representation\n graph = graph ? this._termToNumericId(graph) : 1;\n\n // Find internal identifiers for all components\n // and verify the quad exists.\n const graphs = this._graphs;\n let graphItem, subjects, predicates;\n if (!(subject = subject && this._termToNumericId(subject)) || !(predicate = predicate && this._termToNumericId(predicate)) ||\n !(object = object && this._termToNumericId(object)) || !(graphItem = graphs[graph]) ||\n !(subjects = graphItem.subjects[subject]) ||\n !(predicates = subjects[predicate]) ||\n !(object in predicates))\n return false;\n\n // Remove it from all indexes\n this._removeFromIndex(graphItem.subjects, subject, predicate, object);\n this._removeFromIndex(graphItem.predicates, predicate, object, subject);\n this._removeFromIndex(graphItem.objects, object, subject, predicate);\n if (this._size !== null) this._size--;\n\n // Remove the graph if it is empty\n for (subject in graphItem.subjects) return true;\n delete graphs[graph];\n return true;\n }\n\n // ### `removeQuads` removes multiple quads from the store\n removeQuads(quads) {\n for (let i = 0; i < quads.length; i++)\n this.removeQuad(quads[i]);\n }\n\n // ### `remove` removes a stream of quads from the store\n remove(stream) {\n stream.on('data', quad => { this.removeQuad(quad); });\n return stream;\n }\n\n // ### `removeMatches` removes all matching quads from the store\n // Setting any field to `undefined` or `null` indicates a wildcard.\n removeMatches(subject, predicate, object, graph) {\n const stream = new Readable({ objectMode: true });\n\n const iterable = this.readQuads(subject, predicate, object, graph);\n stream._read = size => {\n while (--size >= 0) {\n const { done, value } = iterable.next();\n if (done) {\n stream.push(null);\n return;\n }\n stream.push(value);\n }\n };\n\n return this.remove(stream);\n }\n\n // ### `deleteGraph` removes all triples with the given graph from the store\n deleteGraph(graph) {\n return this.removeMatches(null, null, null, graph);\n }\n\n // ### `getQuads` returns an array of quads matching a pattern.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n getQuads(subject, predicate, object, graph) {\n return [...this.readQuads(subject, predicate, object, graph)];\n }\n\n /**\n * `readQuads` returns a generator of quads matching a pattern.\n * Setting any field to `undefined` or `null` indicates a wildcard.\n * @deprecated Use `match` instead.\n */\n *readQuads(subject, predicate, object, graph) {\n const graphs = this._getGraphs(graph);\n let content, subjectId, predicateId, objectId;\n\n // Translate IRIs to internal index keys.\n if (subject && !(subjectId = this._termToNumericId(subject)) ||\n predicate && !(predicateId = this._termToNumericId(predicate)) ||\n object && !(objectId = this._termToNumericId(object)))\n return;\n\n for (const graphId in graphs) {\n // Only if the specified graph contains triples, there can be results\n if (content = graphs[graphId]) {\n // Choose the optimal index, based on what fields are present\n if (subjectId) {\n if (objectId)\n // If subject and object are given, the object index will be the fastest\n yield* this._findInIndex(content.objects, objectId, subjectId, predicateId,\n 'object', 'subject', 'predicate', graphId);\n else\n // If only subject and possibly predicate are given, the subject index will be the fastest\n yield* this._findInIndex(content.subjects, subjectId, predicateId, null,\n 'subject', 'predicate', 'object', graphId);\n }\n else if (predicateId)\n // If only predicate and possibly object are given, the predicate index will be the fastest\n yield* this._findInIndex(content.predicates, predicateId, objectId, null,\n 'predicate', 'object', 'subject', graphId);\n else if (objectId)\n // If only object is given, the object index will be the fastest\n yield* this._findInIndex(content.objects, objectId, null, null,\n 'object', 'subject', 'predicate', graphId);\n else\n // If nothing is given, iterate subjects and predicates first\n yield* this._findInIndex(content.subjects, null, null, null,\n 'subject', 'predicate', 'object', graphId);\n }\n }\n }\n\n // ### `match` returns a new dataset that is comprised of all quads in the current instance matching the given arguments.\n // The logic described in Quad Matching is applied for each quad in this dataset to check if it should be included in the output dataset.\n // Note: This method always returns a new DatasetCore, even if that dataset contains no quads.\n // Note: Since a DatasetCore is an unordered set, the order of the quads within the returned sequence is arbitrary.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n // For backwards compatibility, the object return also implements the Readable stream interface.\n match(subject, predicate, object, graph) {\n return new DatasetCoreAndReadableStream(this, subject, predicate, object, graph, { entityIndex: this._entityIndex });\n }\n\n // ### `countQuads` returns the number of quads matching a pattern.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n countQuads(subject, predicate, object, graph) {\n const graphs = this._getGraphs(graph);\n let count = 0, content, subjectId, predicateId, objectId;\n\n // Translate IRIs to internal index keys.\n if (subject && !(subjectId = this._termToNumericId(subject)) ||\n predicate && !(predicateId = this._termToNumericId(predicate)) ||\n object && !(objectId = this._termToNumericId(object)))\n return 0;\n\n for (const graphId in graphs) {\n // Only if the specified graph contains triples, there can be results\n if (content = graphs[graphId]) {\n // Choose the optimal index, based on what fields are present\n if (subject) {\n if (object)\n // If subject and object are given, the object index will be the fastest\n count += this._countInIndex(content.objects, objectId, subjectId, predicateId);\n else\n // If only subject and possibly predicate are given, the subject index will be the fastest\n count += this._countInIndex(content.subjects, subjectId, predicateId, objectId);\n }\n else if (predicate) {\n // If only predicate and possibly object are given, the predicate index will be the fastest\n count += this._countInIndex(content.predicates, predicateId, objectId, subjectId);\n }\n else {\n // If only object is possibly given, the object index will be the fastest\n count += this._countInIndex(content.objects, objectId, subjectId, predicateId);\n }\n }\n }\n return count;\n }\n\n // ### `forEach` executes the callback on all quads.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n forEach(callback, subject, predicate, object, graph) {\n this.some(quad => {\n callback(quad, this);\n return false;\n }, subject, predicate, object, graph);\n }\n\n // ### `every` executes the callback on all quads,\n // and returns `true` if it returns truthy for all them.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n every(callback, subject, predicate, object, graph) {\n return !this.some(quad => !callback(quad, this), subject, predicate, object, graph);\n }\n\n // ### `some` executes the callback on all quads,\n // and returns `true` if it returns truthy for any of them.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n some(callback, subject, predicate, object, graph) {\n for (const quad of this.readQuads(subject, predicate, object, graph))\n if (callback(quad))\n return true;\n return false;\n }\n\n // ### `getSubjects` returns all subjects that match the pattern.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n getSubjects(predicate, object, graph) {\n const results = [];\n this.forSubjects(s => { results.push(s); }, predicate, object, graph);\n return results;\n }\n\n // ### `forSubjects` executes the callback on all subjects that match the pattern.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n forSubjects(callback, predicate, object, graph) {\n const graphs = this._getGraphs(graph);\n let content, predicateId, objectId;\n callback = this._uniqueEntities(callback);\n\n // Translate IRIs to internal index keys.\n if (predicate && !(predicateId = this._termToNumericId(predicate)) ||\n object && !(objectId = this._termToNumericId(object)))\n return;\n\n for (graph in graphs) {\n // Only if the specified graph contains triples, there can be results\n if (content = graphs[graph]) {\n // Choose optimal index based on which fields are wildcards\n if (predicateId) {\n if (objectId)\n // If predicate and object are given, the POS index is best.\n this._loopBy2Keys(content.predicates, predicateId, objectId, callback);\n else\n // If only predicate is given, the SPO index is best.\n this._loopByKey1(content.subjects, predicateId, callback);\n }\n else if (objectId)\n // If only object is given, the OSP index is best.\n this._loopByKey0(content.objects, objectId, callback);\n else\n // If no params given, iterate all the subjects\n this._loop(content.subjects, callback);\n }\n }\n }\n\n // ### `getPredicates` returns all predicates that match the pattern.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n getPredicates(subject, object, graph) {\n const results = [];\n this.forPredicates(p => { results.push(p); }, subject, object, graph);\n return results;\n }\n\n // ### `forPredicates` executes the callback on all predicates that match the pattern.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n forPredicates(callback, subject, object, graph) {\n const graphs = this._getGraphs(graph);\n let content, subjectId, objectId;\n callback = this._uniqueEntities(callback);\n\n // Translate IRIs to internal index keys.\n if (subject && !(subjectId = this._termToNumericId(subject)) ||\n object && !(objectId = this._termToNumericId(object)))\n return;\n\n for (graph in graphs) {\n // Only if the specified graph contains triples, there can be results\n if (content = graphs[graph]) {\n // Choose optimal index based on which fields are wildcards\n if (subjectId) {\n if (objectId)\n // If subject and object are given, the OSP index is best.\n this._loopBy2Keys(content.objects, objectId, subjectId, callback);\n else\n // If only subject is given, the SPO index is best.\n this._loopByKey0(content.subjects, subjectId, callback);\n }\n else if (objectId)\n // If only object is given, the POS index is best.\n this._loopByKey1(content.predicates, objectId, callback);\n else\n // If no params given, iterate all the predicates.\n this._loop(content.predicates, callback);\n }\n }\n }\n\n // ### `getObjects` returns all objects that match the pattern.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n getObjects(subject, predicate, graph) {\n const results = [];\n this.forObjects(o => { results.push(o); }, subject, predicate, graph);\n return results;\n }\n\n // ### `forObjects` executes the callback on all objects that match the pattern.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n forObjects(callback, subject, predicate, graph) {\n const graphs = this._getGraphs(graph);\n let content, subjectId, predicateId;\n callback = this._uniqueEntities(callback);\n\n // Translate IRIs to internal index keys.\n if (subject && !(subjectId = this._termToNumericId(subject)) ||\n predicate && !(predicateId = this._termToNumericId(predicate)))\n return;\n\n for (graph in graphs) {\n // Only if the specified graph contains triples, there can be results\n if (content = graphs[graph]) {\n // Choose optimal index based on which fields are wildcards\n if (subjectId) {\n if (predicateId)\n // If subject and predicate are given, the SPO index is best.\n this._loopBy2Keys(content.subjects, subjectId, predicateId, callback);\n else\n // If only subject is given, the OSP index is best.\n this._loopByKey1(content.objects, subjectId, callback);\n }\n else if (predicateId)\n // If only predicate is given, the POS index is best.\n this._loopByKey0(content.predicates, predicateId, callback);\n else\n // If no params given, iterate all the objects.\n this._loop(content.objects, callback);\n }\n }\n }\n\n // ### `getGraphs` returns all graphs that match the pattern.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n getGraphs(subject, predicate, object) {\n const results = [];\n this.forGraphs(g => { results.push(g); }, subject, predicate, object);\n return results;\n }\n\n // ### `forGraphs` executes the callback on all graphs that match the pattern.\n // Setting any field to `undefined` or `null` indicates a wildcard.\n forGraphs(callback, subject, predicate, object) {\n for (const graph in this._graphs) {\n this.some(quad => {\n callback(quad.graph);\n return true; // Halt iteration of some()\n }, subject, predicate, object, this._termFromId(this._entities[graph]));\n }\n }\n\n // ### `createBlankNode` creates a new blank node, returning its name\n createBlankNode(suggestedName) {\n return this._entityIndex.createBlankNode(suggestedName);\n }\n\n // ### `extractLists` finds and removes all list triples\n // and returns the items per list.\n extractLists({ remove = false, ignoreErrors = false } = {}) {\n const lists = {}; // has scalar keys so could be a simple Object\n const onError = ignoreErrors ? (() => true) :\n ((node, message) => { throw new Error(`${node.value} ${message}`); });\n\n // Traverse each list from its tail\n const tails = this.getQuads(null, namespaces.rdf.rest, namespaces.rdf.nil, null);\n const toRemove = remove ? [...tails] : [];\n tails.forEach(tailQuad => {\n const items = []; // the members found as objects of rdf:first quads\n let malformed = false; // signals whether the current list is malformed\n let head; // the head of the list (_:b1 in above example)\n let headPos; // set to subject or object when head is set\n const graph = tailQuad.graph; // make sure list is in exactly one graph\n\n // Traverse the list from tail to end\n let current = tailQuad.subject;\n while (current && !malformed) {\n const objectQuads = this.getQuads(null, null, current, null);\n const subjectQuads = this.getQuads(current, null, null, null);\n let quad, first = null, rest = null, parent = null;\n\n // Find the first and rest of this list node\n for (let i = 0; i < subjectQuads.length && !malformed; i++) {\n quad = subjectQuads[i];\n if (!quad.graph.equals(graph))\n malformed = onError(current, 'not confined to single graph');\n else if (head)\n malformed = onError(current, 'has non-list arcs out');\n\n // one rdf:first\n else if (quad.predicate.value === namespaces.rdf.first) {\n if (first)\n malformed = onError(current, 'has multiple rdf:first arcs');\n else\n toRemove.push(first = quad);\n }\n\n // one rdf:rest\n else if (quad.predicate.value === namespaces.rdf.rest) {\n if (rest)\n malformed = onError(current, 'has multiple rdf:rest arcs');\n else\n toRemove.push(rest = quad);\n }\n\n // alien triple\n else if (objectQuads.length)\n malformed = onError(current, 'can\\'t be subject and object');\n else {\n head = quad; // e.g. { (1 2 3) :p :o }\n headPos = 'subject';\n }\n }\n\n // { :s :p (1 2) } arrives here with no head\n // { (1 2) :p :o } arrives here with head set to the list.\n for (let i = 0; i < objectQuads.length && !malformed; ++i) {\n quad = objectQuads[i];\n if (head)\n malformed = onError(current, 'can\\'t have coreferences');\n // one rdf:rest\n else if (quad.predicate.value === namespaces.rdf.rest) {\n if (parent)\n malformed = onError(current, 'has incoming rdf:rest arcs');\n else\n parent = quad;\n }\n else {\n head = quad; // e.g. { :s :p (1 2) }\n headPos = 'object';\n }\n }\n\n // Store the list item and continue with parent\n if (!first)\n malformed = onError(current, 'has no list head');\n else\n items.unshift(first.object);\n current = parent && parent.subject;\n }\n\n // Don't remove any quads if the list is malformed\n if (malformed)\n remove = false;\n // Store the list under the value of its head\n else if (head)\n lists[head[headPos].value] = items;\n });\n\n // Remove list quads if requested\n if (remove)\n this.removeQuads(toRemove);\n return lists;\n }\n\n /**\n * Returns `true` if the current dataset is a superset of the given dataset; in other words, returns `true` if\n * the given dataset is a subset of, i.e., is contained within, the current dataset.\n *\n * Blank Nodes will be normalized.\n */\n addAll(quads) {\n if (quads instanceof DatasetCoreAndReadableStream)\n quads = quads.filtered;\n\n if (Array.isArray(quads))\n this.addQuads(quads);\n else if (quads instanceof N3Store && quads._entityIndex === this._entityIndex) {\n if (quads._size !== 0) {\n this._graphs = merge(this._graphs, quads._graphs);\n this._size = null; // Invalidate the cached size\n }\n }\n else {\n for (const quad of quads)\n this.add(quad);\n }\n return this;\n }\n\n /**\n * Returns `true` if the current dataset is a superset of the given dataset; in other words, returns `true` if\n * the given dataset is a subset of, i.e., is contained within, the current dataset.\n *\n * Blank Nodes will be normalized.\n */\n contains(other) {\n if (other instanceof DatasetCoreAndReadableStream)\n other = other.filtered;\n\n if (other === this)\n return true;\n\n if (!(other instanceof N3Store) || this._entityIndex !== other._entityIndex)\n return other.every(quad => this.has(quad));\n\n const g1 = this._graphs, g2 = other._graphs;\n let s1, s2, p1, p2, o1;\n for (const graph in g2) {\n if (!(s1 = g1[graph])) return false;\n s1 = s1.subjects;\n for (const subject in (s2 = g2[graph].subjects)) {\n if (!(p1 = s1[subject])) return false;\n for (const predicate in (p2 = s2[subject])) {\n if (!(o1 = p1[predicate])) return false;\n for (const object in p2[predicate])\n if (!(object in o1)) return false;\n }\n }\n }\n return true;\n }\n\n /**\n * This method removes the quads in the current dataset that match the given arguments.\n *\n * The logic described in {@link https://rdf.js.org/dataset-spec/#quad-matching|Quad Matching} is applied for each\n * quad in this dataset, to select the quads which will be deleted.\n *\n * @param subject The optional exact subject to match.\n * @param predicate The optional exact predicate to match.\n * @param object The optional exact object to match.\n * @param graph The optional exact graph to match.\n */\n deleteMatches(subject, predicate, object, graph) {\n for (const quad of this.match(subject, predicate, object, graph))\n this.removeQuad(quad);\n return this;\n }\n\n /**\n * Returns a new dataset that contains all quads from the current dataset that are not included in the given dataset.\n */\n difference(other) {\n if (other && other instanceof DatasetCoreAndReadableStream)\n other = other.filtered;\n\n if (other === this)\n return new N3Store({ entityIndex: this._entityIndex });\n\n if ((other instanceof N3Store) && other._entityIndex === this._entityIndex) {\n const store = new N3Store({ entityIndex: this._entityIndex });\n const graphs = difference(this._graphs, other._graphs);\n if (graphs) {\n store._graphs = graphs;\n store._size = null;\n }\n return store;\n }\n\n return this.filter(quad => !other.has(quad));\n }\n\n /**\n * Returns true if the current dataset contains the same graph structure as the given dataset.\n *\n * Blank Nodes will be normalized.\n */\n equals(other) {\n if (other instanceof DatasetCoreAndReadableStream)\n other = other.filtered;\n\n return other === this || (this.size === other.size && this.contains(other));\n }\n\n /**\n * Creates a new dataset with all the quads that pass the test implemented by the provided `iteratee`.\n *\n * This method is aligned with Array.prototype.filter() in ECMAScript-262.\n */\n filter(iteratee) {\n const store = new N3Store({ entityIndex: this._entityIndex });\n for (const quad of this)\n if (iteratee(quad, this))\n store.add(quad);\n return store;\n }\n\n /**\n * Returns a new dataset containing all quads from the current dataset that are also included in the given dataset.\n */\n intersection(other) {\n if (other instanceof DatasetCoreAndReadableStream)\n other = other.filtered;\n\n if (other === this) {\n const store = new N3Store({ entityIndex: this._entityIndex });\n store._graphs = merge(Object.create(null), this._graphs);\n store._size = this._size;\n return store;\n }\n else if ((other instanceof N3Store) && this._entityIndex === other._entityIndex) {\n const store = new N3Store({ entityIndex: this._entityIndex });\n const graphs = intersect(other._graphs, this._graphs);\n if (graphs) {\n store._graphs = graphs;\n store._size = null;\n }\n return store;\n }\n\n return this.filter(quad => other.has(quad));\n }\n\n /**\n * Returns a new dataset containing all quads returned by applying `iteratee` to each quad in the current dataset.\n */\n map(iteratee) {\n const store = new N3Store({ entityIndex: this._entityIndex });\n for (const quad of this)\n store.add(iteratee(quad, this));\n return store;\n }\n\n /**\n * This method calls the `iteratee` method on each `quad` of the `Dataset`. The first time the `iteratee` method\n * is called, the `accumulator` value is the `initialValue`, or, if not given, equals the first quad of the `Dataset`.\n * The return value of each call to the `iteratee` method is used as the `accumulator` value for the next call.\n *\n * This method returns the return value of the last `iteratee` call.\n *\n * This method is aligned with `Array.prototype.reduce()` in ECMAScript-262.\n */\n reduce(callback, initialValue) {\n const iter = this.readQuads();\n let accumulator = initialValue === undefined ? iter.next().value : initialValue;\n for (const quad of iter)\n accumulator = callback(accumulator, quad, this);\n return accumulator;\n }\n\n /**\n * Returns the set of quads within the dataset as a host-language-native sequence, for example an `Array` in\n * ECMAScript-262.\n *\n * Since a `Dataset` is an unordered set, the order of the quads within the returned sequence is arbitrary.\n */\n toArray() {\n return this.getQuads();\n }\n\n /**\n * Returns an N-Quads string representation of the dataset, preprocessed with the\n * {@link https://json-ld.github.io/normalization/spec/|RDF Dataset Normalization} algorithm.\n */\n toCanonical() {\n throw new Error('not implemented');\n }\n\n /**\n * Returns a stream that contains all quads of the dataset.\n */\n toStream() {\n return this.match();\n }\n\n /**\n * Returns an N-Quads string representation of the dataset.\n *\n * No prior normalization is required, therefore the results for the same quads may vary depending on the `Dataset`\n * implementation.\n */\n toString() {\n return (new N3Writer()).quadsToString(this);\n }\n\n /**\n * Returns a new `Dataset` that is a concatenation of this dataset and the quads given as an argument.\n */\n union(quads) {\n const store = new N3Store({ entityIndex: this._entityIndex });\n store._graphs = merge(Object.create(null), this._graphs);\n store._size = this._size;\n\n store.addAll(quads);\n return store;\n }\n\n // ### Store is an iterable.\n // Can be used where iterables are expected: for...of loops, array spread operator,\n // `yield*`, and destructuring assignment (order is not guaranteed).\n *[Symbol.iterator]() {\n yield* this.readQuads();\n }\n}\n\n/**\n * Returns a subset of the `index` with that part of the index\n * matching the `ids` array. `ids` contains 3 elements that are\n * either numerical ids; or `null`.\n *\n * `false` is returned when there are no matching indices; this should\n * *not* be set as the value for an index.\n */\nfunction indexMatch(index, ids, depth = 0) {\n const ind = ids[depth];\n if (ind && !(ind in index))\n return false;\n\n let target = false;\n for (const key in (ind ? { [ind]: index[ind] } : index)) {\n const result = depth === 2 ? null : indexMatch(index[key], ids, depth + 1);\n\n if (result !== false) {\n target = target || Object.create(null);\n target[key] = result;\n }\n }\n return target;\n}\n\n/**\n * A class that implements both DatasetCore and Readable.\n */\nclass DatasetCoreAndReadableStream extends Readable {\n constructor(n3Store, subject, predicate, object, graph, options) {\n super({ objectMode: true });\n Object.assign(this, { n3Store, subject, predicate, object, graph, options });\n }\n\n get filtered() {\n if (!this._filtered) {\n const { n3Store, graph, object, predicate, subject } = this;\n const newStore = this._filtered = new N3Store({ factory: n3Store._factory, entityIndex: this.options.entityIndex });\n\n let subjectId, predicateId, objectId;\n\n // Translate IRIs to internal index keys.\n if (subject && !(subjectId = newStore._termToNumericId(subject)) ||\n predicate && !(predicateId = newStore._termToNumericId(predicate)) ||\n object && !(objectId = newStore._termToNumericId(object)))\n return newStore;\n\n const graphs = n3Store._getGraphs(graph);\n for (const graphKey in graphs) {\n let subjects, predicates, objects;\n\n if (!subjectId && predicateId) {\n if (predicates = indexMatch(graphs[graphKey].predicates, [predicateId, objectId, subjectId])) {\n subjects = indexMatch(graphs[graphKey].subjects, [subjectId, predicateId, objectId]);\n objects = indexMatch(graphs[graphKey].objects, [objectId, subjectId, predicateId]);\n }\n }\n else if (objectId) {\n if (objects = indexMatch(graphs[graphKey].objects, [objectId, subjectId, predicateId])) {\n subjects = indexMatch(graphs[graphKey].subjects, [subjectId, predicateId, objectId]);\n predicates = indexMatch(graphs[graphKey].predicates, [predicateId, objectId, subjectId]);\n }\n }\n else if (subjects = indexMatch(graphs[graphKey].subjects, [subjectId, predicateId, objectId])) {\n predicates = indexMatch(graphs[graphKey].predicates, [predicateId, objectId, subjectId]);\n objects = indexMatch(graphs[graphKey].objects, [objectId, subjectId, predicateId]);\n }\n\n if (subjects)\n newStore._graphs[graphKey] = { subjects, predicates, objects };\n }\n newStore._size = null;\n }\n return this._filtered;\n }\n\n get size() {\n return this.filtered.size;\n }\n\n _read(size) {\n if (size > 0 && !this[ITERATOR])\n this[ITERATOR] = this[Symbol.iterator]();\n const iterable = this[ITERATOR];\n while (--size >= 0) {\n const { done, value } = iterable.next();\n if (done) {\n this.push(null);\n return;\n }\n this.push(value);\n }\n }\n\n addAll(quads) {\n return this.filtered.addAll(quads);\n }\n\n contains(other) {\n return this.filtered.contains(other);\n }\n\n deleteMatches(subject, predicate, object, graph) {\n return this.filtered.deleteMatches(subject, predicate, object, graph);\n }\n\n difference(other) {\n return this.filtered.difference(other);\n }\n\n equals(other) {\n return this.filtered.equals(other);\n }\n\n every(callback, subject, predicate, object, graph) {\n return this.filtered.every(callback, subject, predicate, object, graph);\n }\n\n filter(iteratee) {\n return this.filtered.filter(iteratee);\n }\n\n forEach(callback, subject, predicate, object, graph) {\n return this.filtered.forEach(callback, subject, predicate, object, graph);\n }\n\n import(stream) {\n return this.filtered.import(stream);\n }\n\n intersection(other) {\n return this.filtered.intersection(other);\n }\n\n map(iteratee) {\n return this.filtered.map(iteratee);\n }\n\n some(callback, subject, predicate, object, graph) {\n return this.filtered.some(callback, subject, predicate, object, graph);\n }\n\n toCanonical() {\n return this.filtered.toCanonical();\n }\n\n toStream() {\n return this._filtered ?\n this._filtered.toStream()\n : this.n3Store.match(this.subject, this.predicate, this.object, this.graph);\n }\n\n union(quads) {\n return this._filtered ?\n this._filtered.union(quads)\n : this.n3Store.match(this.subject, this.predicate, this.object, this.graph).addAll(quads);\n }\n\n toArray() {\n return this._filtered ? this._filtered.toArray() : this.n3Store.getQuads(this.subject, this.predicate, this.object, this.graph);\n }\n\n reduce(callback, initialValue) {\n return this.filtered.reduce(callback, initialValue);\n }\n\n toString() {\n return (new N3Writer()).quadsToString(this);\n }\n\n add(quad) {\n return this.filtered.add(quad);\n }\n\n delete(quad) {\n return this.filtered.delete(quad);\n }\n\n has(quad) {\n return this.filtered.has(quad);\n }\n\n match(subject, predicate, object, graph) {\n return new DatasetCoreAndReadableStream(this.filtered, subject, predicate, object, graph, this.options);\n }\n\n *[Symbol.iterator]() {\n yield* this._filtered || this.n3Store.readQuads(this.subject, this.predicate, this.object, this.graph);\n }\n}\n","import N3Store from './N3Store';\n\nexport default class N3DatasetCoreFactory {\n dataset(quads) {\n return new N3Store(quads);\n }\n}\n","import DF from './N3DataFactory';\n\n/**\n * Gets rules from a dataset. This will only collect horn rules declared using log:implies.\n */\nexport function getRulesFromDataset(dataset) {\n const rules = [];\n for (const { subject, object } of dataset.match(null, DF.namedNode('http://www.w3.org/2000/10/swap/log#implies'), null, DF.defaultGraph())) {\n const premise = [...dataset.match(null, null, null, subject)];\n const conclusion = [...dataset.match(null, null, null, object)];\n rules.push({ premise, conclusion });\n }\n return rules;\n}\n\nexport default class N3Reasoner {\n constructor(store) {\n this._store = store;\n }\n\n _add(subject, predicate, object, graphItem, cb) {\n // Only add to the remaining indexes if there is not already a value in the index\n if (!this._store._addToIndex(graphItem.subjects, subject, predicate, object)) return;\n this._store._addToIndex(graphItem.predicates, predicate, object, subject);\n this._store._addToIndex(graphItem.objects, object, subject, predicate);\n cb();\n }\n\n // eslint-disable-next-line no-warning-comments\n _evaluatePremise(rule, content, cb, i = 0) {\n let v1, v2, value, index1, index2;\n const [val0, val1, val2] = rule.premise[i].value, index = content[rule.premise[i].content];\n const v0 = !(value = val0.value);\n for (value in v0 ? index : { [value]: index[value] }) {\n if (index1 = index[value]) {\n if (v0) val0.value = Number(value);\n v1 = !(value = val1.value);\n for (value in v1 ? index1 : { [value]: index1[value] }) {\n if (index2 = index1[value]) {\n if (v1) val1.value = Number(value);\n v2 = !(value = val2.value);\n for (value in v2 ? index2 : { [value]: index2[value] }) {\n if (v2) val2.value = Number(value);\n\n if (i === rule.premise.length - 1)\n rule.conclusion.forEach(c => {\n // eslint-disable-next-line max-nested-callbacks\n this._add(c.subject.value, c.predicate.value, c.object.value, content, () => { cb(c); });\n });\n else\n this._evaluatePremise(rule, content, cb, i + 1);\n }\n if (v2) val2.value = null;\n }\n }\n if (v1) val1.value = null;\n }\n }\n if (v0) val0.value = null;\n }\n\n _evaluateRules(rules, content, cb) {\n for (let i = 0; i < rules.length; i++) {\n this._evaluatePremise(rules[i], content, cb);\n }\n }\n\n // A naive reasoning algorithm where rules are just applied by repeatedly applying rules\n // until no more evaluations are made\n _reasonGraphNaive(rules, content) {\n const newRules = [];\n\n function addRule(conclusion) {\n if (conclusion.next)\n conclusion.next.forEach(rule => {\n newRules.push([conclusion.subject.value, conclusion.predicate.value, conclusion.object.value, rule]);\n });\n }\n\n // eslint-disable-next-line func-style\n const addConclusions = conclusion => {\n conclusion.forEach(c => {\n // eslint-disable-next-line max-nested-callbacks\n this._add(c.subject.value, c.predicate.value, c.object.value, content, () => { addRule(c); });\n });\n };\n\n this._evaluateRules(rules, content, addRule);\n\n let r;\n while ((r = newRules.pop()) !== undefined) {\n const [subject, predicate, object, rule] = r;\n const v1 = rule.basePremise.subject.value;\n if (!v1) rule.basePremise.subject.value = subject;\n const v2 = rule.basePremise.predicate.value;\n if (!v2) rule.basePremise.predicate.value = predicate;\n const v3 = rule.basePremise.object.value;\n if (!v3) rule.basePremise.object.value = object;\n\n if (rule.premise.length === 0) {\n addConclusions(rule.conclusion);\n }\n else {\n this._evaluatePremise(rule, content, addRule);\n }\n\n if (!v1) rule.basePremise.subject.value = null;\n if (!v2) rule.basePremise.predicate.value = null;\n if (!v3) rule.basePremise.object.value = null;\n }\n }\n\n _createRule({ premise, conclusion }) {\n const varMapping = {};\n\n const toId = value => value.termType === 'Variable' ?\n // If the term is a variable, then create an empty object that values can be placed into\n (varMapping[value.value] = varMapping[value.value] || {}) :\n // If the term is not a variable, then set the ID value\n { value: this._store._termToNewNumericId(value) };\n\n // eslint-disable-next-line func-style\n const t = term => ({ subject: toId(term.subject), predicate: toId(term.predicate), object: toId(term.object) });\n\n return {\n premise: premise.map(p => t(p)),\n conclusion: conclusion.map(p => t(p)),\n variables: Object.values(varMapping),\n };\n }\n\n reason(rules) {\n if (!Array.isArray(rules)) {\n rules = getRulesFromDataset(rules);\n }\n rules = rules.map(rule => this._createRule(rule));\n\n for (const r1 of rules) {\n for (const r2 of rules) {\n for (let i = 0; i < r2.premise.length; i++) {\n const p = r2.premise[i];\n for (const c of r1.conclusion) {\n if (termEq(p.subject, c.subject) && termEq(p.predicate, c.predicate) && termEq(p.object, c.object)) {\n const set = new Set();\n\n const premise = [];\n\n // Since these *will* be substituted when we apply the rule,\n // we need to do this, so that we index correctly in the subsequent section\n p.subject.value = p.subject.value || 1;\n p.object.value = p.object.value || 1;\n p.predicate.value = p.predicate.value || 1;\n\n for (let j = 0; j < r2.premise.length; j++) {\n if (j !== i) {\n premise.push(getIndex(r2.premise[j], set));\n }\n }\n\n // eslint-disable-next-line no-warning-comments\n // TODO: Create new rule, with new indexing\n // Future, 'collapse' the next statements when they share a premise/base-premise\n (c.next = c.next || []).push({\n premise,\n conclusion: r2.conclusion,\n // This is a single premise of the form { subject, predicate, object },\n // which we can use to instantiate the rule using the new data that was emitted\n basePremise: p,\n });\n }\n r2.variables.forEach(v => { v.value = null; });\n }\n }\n }\n }\n\n for (const rule of rules) {\n const set = new Set();\n rule.premise = rule.premise.map(p => getIndex(p, set));\n }\n\n const graphs = this._store._getGraphs();\n for (const graphId in graphs) {\n this._reasonGraphNaive(rules, graphs[graphId]);\n }\n\n this._store._size = null;\n }\n}\n\nfunction getIndex({ subject, predicate, object }, set) {\n const s = subject.value || set.has(subject) || (set.add(subject), false);\n const p = predicate.value || set.has(predicate) || (set.add(predicate), false);\n const o = object.value || set.has(object) || (set.add(object), false);\n\n return (!s && p) ? { content: 'predicates', value: [predicate, object, subject] } :\n o ? { content: 'objects', value: [object, subject, predicate] } :\n { content: 'subjects', value: [subject, predicate, object] };\n}\n\nfunction termEq(t1, t2) {\n if (t1.value === null) {\n t1.value = t2.value;\n }\n return t1.value === t2.value;\n}\n","// **N3StreamParser** parses a text stream into a quad stream.\nimport { Transform } from 'readable-stream';\nimport N3Parser from './N3Parser';\n\n// ## Constructor\nexport default class N3StreamParser extends Transform {\n constructor(options) {\n super({ decodeStrings: true });\n this._readableState.objectMode = true;\n\n // Set up parser with dummy stream to obtain `data` and `end` callbacks\n const parser = new N3Parser(options);\n let onData, onEnd;\n\n const callbacks = {\n // Handle quads by pushing them down the pipeline\n onQuad: (error, quad) => { error && this.emit('error', error) || quad && this.push(quad); },\n // Emit prefixes through the `prefix` event\n onPrefix: (prefix, uri) => { this.emit('prefix', prefix, uri); },\n };\n\n if (options && options.comments)\n callbacks.onComment = comment => { this.emit('comment', comment); };\n\n parser.parse({\n on: (event, callback) => {\n switch (event) {\n case 'data': onData = callback; break;\n case 'end': onEnd = callback; break;\n }\n },\n }, callbacks);\n\n // Implement Transform methods through parser callbacks\n this._transform = (chunk, encoding, done) => { onData(chunk); done(); };\n this._flush = done => { onEnd(); done(); };\n }\n\n // ### Parses a stream of strings\n import(stream) {\n stream.on('data', chunk => { this.write(chunk); });\n stream.on('end', () => { this.end(); });\n stream.on('error', error => { this.emit('error', error); });\n return this;\n }\n}\n","// **N3StreamWriter** serializes a quad stream into a text stream.\nimport { Transform } from 'readable-stream';\nimport N3Writer from './N3Writer';\n\n// ## Constructor\nexport default class N3StreamWriter extends Transform {\n constructor(options) {\n super({ encoding: 'utf8', writableObjectMode: true });\n\n // Set up writer with a dummy stream object\n const writer = this._writer = new N3Writer({\n write: (quad, encoding, callback) => { this.push(quad); callback && callback(); },\n end: callback => { this.push(null); callback && callback(); },\n }, options);\n\n // Implement Transform methods on top of writer\n this._transform = (quad, encoding, done) => { writer.addQuad(quad, done); };\n this._flush = done => { writer.end(done); };\n }\n\n// ### Serializes a stream of quads\n import(stream) {\n stream.on('data', quad => { this.write(quad); });\n stream.on('end', () => { this.end(); });\n stream.on('error', error => { this.emit('error', error); });\n stream.on('prefix', (prefix, iri) => { this._writer.addPrefix(prefix, iri); });\n return this;\n }\n}\n","import Lexer from './N3Lexer';\nimport Parser from './N3Parser';\nimport Writer from './N3Writer';\nimport Store, { N3EntityIndex as EntityIndex } from './N3Store';\nimport StoreFactory from './N3StoreFactory';\nimport Reasoner, { getRulesFromDataset } from './N3Reasoner';\nimport StreamParser from './N3StreamParser';\nimport StreamWriter from './N3StreamWriter';\nimport * as Util from './N3Util';\n\nimport {\n default as DataFactory,\n\n Term,\n NamedNode,\n Literal,\n BlankNode,\n Variable,\n DefaultGraph,\n Quad,\n Triple,\n\n termFromId,\n termToId,\n} from './N3DataFactory';\n\n// Named exports\nexport {\n Lexer,\n Parser,\n Writer,\n Store,\n StoreFactory,\n EntityIndex,\n StreamParser,\n StreamWriter,\n Util,\n Reasoner,\n\n DataFactory,\n\n Term,\n NamedNode,\n Literal,\n BlankNode,\n Variable,\n DefaultGraph,\n Quad,\n Triple,\n\n termFromId,\n termToId,\n getRulesFromDataset,\n};\n\n// Export all named exports as a default object for backward compatibility\nexport default {\n Lexer,\n Parser,\n Writer,\n Store,\n StoreFactory,\n EntityIndex,\n StreamParser,\n StreamWriter,\n Util,\n Reasoner,\n\n DataFactory,\n\n Term,\n NamedNode,\n Literal,\n BlankNode,\n Variable,\n DefaultGraph,\n Quad,\n Triple,\n\n termFromId,\n termToId,\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","/*! queue-microtask. MIT License. Feross Aboukhadijeh */\nlet promise\n\nmodule.exports = typeof queueMicrotask === 'function'\n ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)\n // reuse resolved promise, and allocate it lazily\n : cb => (promise || (promise = Promise.resolve()))\n .then(cb)\n .catch(err => setTimeout(() => { throw err }, 0))\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./lib/BlankNode\"), exports);\n__exportStar(require(\"./lib/DataFactory\"), exports);\n__exportStar(require(\"./lib/DefaultGraph\"), exports);\n__exportStar(require(\"./lib/Literal\"), exports);\n__exportStar(require(\"./lib/NamedNode\"), exports);\n__exportStar(require(\"./lib/Quad\"), exports);\n__exportStar(require(\"./lib/Variable\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BlankNode = void 0;\n/**\n * A term that represents an RDF blank node with a label.\n */\nclass BlankNode {\n constructor(value) {\n this.termType = 'BlankNode';\n this.value = value;\n }\n equals(other) {\n return !!other && other.termType === 'BlankNode' && other.value === this.value;\n }\n}\nexports.BlankNode = BlankNode;\n//# sourceMappingURL=BlankNode.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DataFactory = void 0;\nconst BlankNode_1 = require(\"./BlankNode\");\nconst DefaultGraph_1 = require(\"./DefaultGraph\");\nconst Literal_1 = require(\"./Literal\");\nconst NamedNode_1 = require(\"./NamedNode\");\nconst Quad_1 = require(\"./Quad\");\nconst Variable_1 = require(\"./Variable\");\nlet dataFactoryCounter = 0;\n/**\n * A factory for instantiating RDF terms and quads.\n */\nclass DataFactory {\n constructor(options) {\n this.blankNodeCounter = 0;\n options = options || {};\n this.blankNodePrefix = options.blankNodePrefix || `df_${dataFactoryCounter++}_`;\n }\n /**\n * @param value The IRI for the named node.\n * @return A new instance of NamedNode.\n * @see NamedNode\n */\n namedNode(value) {\n return new NamedNode_1.NamedNode(value);\n }\n /**\n * @param value The optional blank node identifier.\n * @return A new instance of BlankNode.\n * If the `value` parameter is undefined a new identifier\n * for the blank node is generated for each call.\n * @see BlankNode\n */\n blankNode(value) {\n return new BlankNode_1.BlankNode(value || `${this.blankNodePrefix}${this.blankNodeCounter++}`);\n }\n /**\n * @param value The literal value.\n * @param languageOrDatatype The optional language or datatype.\n * If `languageOrDatatype` is a NamedNode,\n * then it is used for the value of `NamedNode.datatype`.\n * Otherwise `languageOrDatatype` is used for the value\n * of `NamedNode.language`.\n * @return A new instance of Literal.\n * @see Literal\n */\n literal(value, languageOrDatatype) {\n return new Literal_1.Literal(value, languageOrDatatype);\n }\n /**\n * This method is optional.\n * @param value The variable name\n * @return A new instance of Variable.\n * @see Variable\n */\n variable(value) {\n return new Variable_1.Variable(value);\n }\n /**\n * @return An instance of DefaultGraph.\n */\n defaultGraph() {\n return DefaultGraph_1.DefaultGraph.INSTANCE;\n }\n /**\n * @param subject The quad subject term.\n * @param predicate The quad predicate term.\n * @param object The quad object term.\n * @param graph The quad graph term.\n * @return A new instance of Quad.\n * @see Quad\n */\n quad(subject, predicate, object, graph) {\n return new Quad_1.Quad(subject, predicate, object, graph || this.defaultGraph());\n }\n /**\n * Create a deep copy of the given term using this data factory.\n * @param original An RDF term.\n * @return A deep copy of the given term.\n */\n fromTerm(original) {\n // TODO: remove nasty any casts when this TS bug has been fixed:\n // https://github.com/microsoft/TypeScript/issues/26933\n switch (original.termType) {\n case 'NamedNode':\n return this.namedNode(original.value);\n case 'BlankNode':\n return this.blankNode(original.value);\n case 'Literal':\n if (original.language) {\n return this.literal(original.value, original.language);\n }\n if (!original.datatype.equals(Literal_1.Literal.XSD_STRING)) {\n return this.literal(original.value, this.fromTerm(original.datatype));\n }\n return this.literal(original.value);\n case 'Variable':\n return this.variable(original.value);\n case 'DefaultGraph':\n return this.defaultGraph();\n case 'Quad':\n return this.quad(this.fromTerm(original.subject), this.fromTerm(original.predicate), this.fromTerm(original.object), this.fromTerm(original.graph));\n }\n }\n /**\n * Create a deep copy of the given quad using this data factory.\n * @param original An RDF quad.\n * @return A deep copy of the given quad.\n */\n fromQuad(original) {\n return this.fromTerm(original);\n }\n /**\n * Reset the internal blank node counter.\n */\n resetBlankNodeCounter() {\n this.blankNodeCounter = 0;\n }\n}\nexports.DataFactory = DataFactory;\n//# sourceMappingURL=DataFactory.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DefaultGraph = void 0;\n/**\n * A singleton term instance that represents the default graph.\n * It's only allowed to assign a DefaultGraph to the .graph property of a Quad.\n */\nclass DefaultGraph {\n constructor() {\n this.termType = 'DefaultGraph';\n this.value = '';\n // Private constructor\n }\n equals(other) {\n return !!other && other.termType === 'DefaultGraph';\n }\n}\nexports.DefaultGraph = DefaultGraph;\nDefaultGraph.INSTANCE = new DefaultGraph();\n//# sourceMappingURL=DefaultGraph.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Literal = void 0;\nconst NamedNode_1 = require(\"./NamedNode\");\n/**\n * A term that represents an RDF literal, containing a string with an optional language tag or datatype.\n */\nclass Literal {\n constructor(value, languageOrDatatype) {\n this.termType = 'Literal';\n this.value = value;\n if (typeof languageOrDatatype === 'string') {\n this.language = languageOrDatatype;\n this.datatype = Literal.RDF_LANGUAGE_STRING;\n }\n else if (languageOrDatatype) {\n this.language = '';\n this.datatype = languageOrDatatype;\n }\n else {\n this.language = '';\n this.datatype = Literal.XSD_STRING;\n }\n }\n equals(other) {\n return !!other && other.termType === 'Literal' && other.value === this.value &&\n other.language === this.language && this.datatype.equals(other.datatype);\n }\n}\nexports.Literal = Literal;\nLiteral.RDF_LANGUAGE_STRING = new NamedNode_1.NamedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#langString');\nLiteral.XSD_STRING = new NamedNode_1.NamedNode('http://www.w3.org/2001/XMLSchema#string');\n//# sourceMappingURL=Literal.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NamedNode = void 0;\n/**\n * A term that contains an IRI.\n */\nclass NamedNode {\n constructor(value) {\n this.termType = 'NamedNode';\n this.value = value;\n }\n equals(other) {\n return !!other && other.termType === 'NamedNode' && other.value === this.value;\n }\n}\nexports.NamedNode = NamedNode;\n//# sourceMappingURL=NamedNode.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Quad = void 0;\n/**\n * An instance of DefaultGraph represents the default graph.\n * It's only allowed to assign a DefaultGraph to the .graph property of a Quad.\n */\nclass Quad {\n constructor(subject, predicate, object, graph) {\n this.termType = 'Quad';\n this.value = '';\n this.subject = subject;\n this.predicate = predicate;\n this.object = object;\n this.graph = graph;\n }\n equals(other) {\n // `|| !other.termType` is for backwards-compatibility with old factories without RDF* support.\n return !!other && (other.termType === 'Quad' || !other.termType) &&\n this.subject.equals(other.subject) &&\n this.predicate.equals(other.predicate) &&\n this.object.equals(other.object) &&\n this.graph.equals(other.graph);\n }\n}\nexports.Quad = Quad;\n//# sourceMappingURL=Quad.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Variable = void 0;\n/**\n * A term that represents a variable.\n */\nclass Variable {\n constructor(value) {\n this.termType = 'Variable';\n this.value = value;\n }\n equals(other) {\n return !!other && other.termType === 'Variable' && other.value === this.value;\n }\n}\nexports.Variable = Variable;\n//# sourceMappingURL=Variable.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./lib/Resolve\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.removeDotSegmentsOfPath = exports.removeDotSegments = exports.resolve = void 0;\n/**\n * Convert the given relative IRI to an absolute IRI\n * by taking into account the given optional baseIRI.\n *\n * @param {string} relativeIRI The relative IRI to convert to an absolute IRI.\n * @param {string} baseIRI The optional base IRI.\n * @return {string} an absolute IRI.\n */\nfunction resolve(relativeIRI, baseIRI) {\n baseIRI = baseIRI || '';\n const baseFragmentPos = baseIRI.indexOf('#');\n // Ignore any fragments in the base IRI\n if (baseFragmentPos > 0) {\n baseIRI = baseIRI.substr(0, baseFragmentPos);\n }\n // Convert empty value directly to base IRI\n if (!relativeIRI.length) {\n // At this point, the baseIRI MUST be absolute, otherwise we error\n if (baseIRI.indexOf(':') < 0) {\n throw new Error(`Found invalid baseIRI '${baseIRI}' for value '${relativeIRI}'`);\n }\n return baseIRI;\n }\n // If the value starts with a query character, concat directly (but strip the existing query)\n if (relativeIRI.startsWith('?')) {\n const baseQueryPos = baseIRI.indexOf('?');\n if (baseQueryPos > 0) {\n baseIRI = baseIRI.substr(0, baseQueryPos);\n }\n return baseIRI + relativeIRI;\n }\n // If the value starts with a fragment character, concat directly\n if (relativeIRI.startsWith('#')) {\n return baseIRI + relativeIRI;\n }\n // Ignore baseIRI if it is empty\n if (!baseIRI.length) {\n const relativeColonPos = relativeIRI.indexOf(':');\n if (relativeColonPos < 0) {\n throw new Error(`Found invalid relative IRI '${relativeIRI}' for a missing baseIRI`);\n }\n return removeDotSegmentsOfPath(relativeIRI, relativeColonPos);\n }\n // Ignore baseIRI if the value is absolute\n const valueColonPos = relativeIRI.indexOf(':');\n if (valueColonPos >= 0) {\n return removeDotSegmentsOfPath(relativeIRI, valueColonPos);\n }\n // At this point, the baseIRI MUST be absolute, otherwise we error\n const baseColonPos = baseIRI.indexOf(':');\n if (baseColonPos < 0) {\n throw new Error(`Found invalid baseIRI '${baseIRI}' for value '${relativeIRI}'`);\n }\n const baseIRIScheme = baseIRI.substr(0, baseColonPos + 1);\n // Inherit the baseIRI scheme if the value starts with '//'\n if (relativeIRI.indexOf('//') === 0) {\n return baseIRIScheme + removeDotSegmentsOfPath(relativeIRI, valueColonPos);\n }\n // Check cases where '://' occurs in the baseIRI, and where there is no '/' after a ':' anymore.\n let baseSlashAfterColonPos;\n if (baseIRI.indexOf('//', baseColonPos) === baseColonPos + 1) {\n // If there is no additional '/' after the '//'.\n baseSlashAfterColonPos = baseIRI.indexOf('/', baseColonPos + 3);\n if (baseSlashAfterColonPos < 0) {\n // If something other than a '/' follows the '://', append the value after a '/',\n // otherwise, prefix the value with only the baseIRI scheme.\n if (baseIRI.length > baseColonPos + 3) {\n return baseIRI + '/' + removeDotSegmentsOfPath(relativeIRI, valueColonPos);\n }\n else {\n return baseIRIScheme + removeDotSegmentsOfPath(relativeIRI, valueColonPos);\n }\n }\n }\n else {\n // If there is not even a single '/' after the ':'\n baseSlashAfterColonPos = baseIRI.indexOf('/', baseColonPos + 1);\n if (baseSlashAfterColonPos < 0) {\n // If we don't have a '/' after the ':',\n // prefix the value with only the baseIRI scheme.\n return baseIRIScheme + removeDotSegmentsOfPath(relativeIRI, valueColonPos);\n }\n }\n // If the value starts with a '/', then prefix it with everything before the first effective slash of the base IRI.\n if (relativeIRI.indexOf('/') === 0) {\n return baseIRI.substr(0, baseSlashAfterColonPos) + removeDotSegments(relativeIRI);\n }\n let baseIRIPath = baseIRI.substr(baseSlashAfterColonPos);\n const baseIRILastSlashPos = baseIRIPath.lastIndexOf('/');\n // Ignore everything after the last '/' in the baseIRI path\n if (baseIRILastSlashPos >= 0 && baseIRILastSlashPos < baseIRIPath.length - 1) {\n baseIRIPath = baseIRIPath.substr(0, baseIRILastSlashPos + 1);\n // Also remove the first character of the relative path if it starts with '.' (and not '..' or './')\n // This change is only allowed if there is something else following the path\n if (relativeIRI[0] === '.' && relativeIRI[1] !== '.' && relativeIRI[1] !== '/' && relativeIRI[2]) {\n relativeIRI = relativeIRI.substr(1);\n }\n }\n // Prefix the value with the baseIRI path where\n relativeIRI = baseIRIPath + relativeIRI;\n // Remove dot segment from the IRI\n relativeIRI = removeDotSegments(relativeIRI);\n // Prefix our transformed value with the part of the baseIRI until the first '/' after the first ':'.\n return baseIRI.substr(0, baseSlashAfterColonPos) + relativeIRI;\n}\nexports.resolve = resolve;\n/**\n * Remove dot segments from the given path,\n * as described in https://www.ietf.org/rfc/rfc3986.txt (page 32).\n * @param {string} path An IRI path.\n * @return {string} A path, will always start with a '/'.\n */\nfunction removeDotSegments(path) {\n // Prepare a buffer with segments between each '/.\n // Each segment represents an array of characters.\n const segmentBuffers = [];\n let i = 0;\n while (i < path.length) {\n // Remove '/.' or '/..'\n switch (path[i]) {\n case '/':\n if (path[i + 1] === '.') {\n if (path[i + 2] === '.') {\n // Start a new segment if we find an invalid character after the '.'\n if (!isCharacterAllowedAfterRelativePathSegment(path[i + 3])) {\n segmentBuffers.push([]);\n i++;\n break;\n }\n // Go to parent directory,\n // so we remove a parent segment\n segmentBuffers.pop();\n // Ensure that we end with a slash if there is a trailing '/..'\n if (!path[i + 3]) {\n segmentBuffers.push([]);\n }\n i += 3;\n }\n else {\n // Start a new segment if we find an invalid character after the '.'\n if (!isCharacterAllowedAfterRelativePathSegment(path[i + 2])) {\n segmentBuffers.push([]);\n i++;\n break;\n }\n // Ensure that we end with a slash if there is a trailing '/.'\n if (!path[i + 2]) {\n segmentBuffers.push([]);\n }\n // Go to the current directory,\n // so we do nothing\n i += 2;\n }\n }\n else {\n // Start a new segment\n segmentBuffers.push([]);\n i++;\n }\n break;\n case '#':\n case '?':\n // Query and fragment string should be appended unchanged\n if (!segmentBuffers.length) {\n segmentBuffers.push([]);\n }\n segmentBuffers[segmentBuffers.length - 1].push(path.substr(i));\n // Break the while loop\n i = path.length;\n break;\n default:\n // Not a special character, just append it to our buffer\n if (!segmentBuffers.length) {\n segmentBuffers.push([]);\n }\n segmentBuffers[segmentBuffers.length - 1].push(path[i]);\n i++;\n break;\n }\n }\n return '/' + segmentBuffers.map((buffer) => buffer.join('')).join('/');\n}\nexports.removeDotSegments = removeDotSegments;\n/**\n * Removes dot segments of the given IRI.\n * @param {string} iri An IRI (or part of IRI).\n * @param {number} colonPosition The position of the first ':' in the IRI.\n * @return {string} The IRI where dot segments were removed.\n */\nfunction removeDotSegmentsOfPath(iri, colonPosition) {\n // Determine where we should start looking for the first '/' that indicates the start of the path\n let searchOffset = colonPosition + 1;\n if (colonPosition >= 0) {\n if (iri[colonPosition + 1] === '/' && iri[colonPosition + 2] === '/') {\n searchOffset = colonPosition + 3;\n }\n }\n else {\n if (iri[0] === '/' && iri[1] === '/') {\n searchOffset = 2;\n }\n }\n // Determine the path\n const pathSeparator = iri.indexOf('/', searchOffset);\n if (pathSeparator < 0) {\n return iri;\n }\n const base = iri.substr(0, pathSeparator);\n const path = iri.substr(pathSeparator);\n // Remove dot segments from the path\n return base + removeDotSegments(path);\n}\nexports.removeDotSegmentsOfPath = removeDotSegmentsOfPath;\nfunction isCharacterAllowedAfterRelativePathSegment(character) {\n return !character || character === '#' || character === '?' || character === '/';\n}\n//# sourceMappingURL=Resolve.js.map","export type AccessMode = 'r' | 'rw';\nexport type AccessScope = string;\n\ninterface ScopeEntry {\n name: string;\n mode: AccessMode;\n}\n\ninterface ScopeModeMap {\n // NOTE: key is actually AccessScope\n [key: string]: AccessMode;\n}\n\n/**\n * @class\n *\n * This class is for requesting and managing access to modules/folders on the\n * remote. It gets initialized as `remoteStorage.access`.\n */\nexport class Access {\n scopeModeMap: ScopeModeMap;\n rootPaths: string[];\n storageType: string;\n\n // TODO create custom type for init function\n static _rs_init(): void {\n return;\n }\n\n constructor() {\n this.reset();\n }\n\n /**\n * Holds an array of claimed scopes:\n *\n * ```javascript\n * [{ name: \"\", mode: \"\" }]\n * ```\n *\n * @ignore\n */\n get scopes(): ScopeEntry[] {\n return Object.keys(this.scopeModeMap).map((key) => {\n return { name: key, mode: this.scopeModeMap[key] };\n });\n }\n\n get scopeParameter(): string {\n return this.scopes.map((scope) => {\n return `${this._scopeNameForParameter(scope)}:${scope.mode}`;\n }).join(' ');\n }\n\n /**\n * Claim access on a given scope with given mode.\n *\n * @param scope - An access scope, such as `contacts` or `calendar`\n * @param mode - Access mode. Either `r` for read-only or `rw` for read/write\n *\n * @example\n * ```javascript\n * remoteStorage.access.claim('contacts', 'r');\n * remoteStorage.access.claim('pictures', 'rw');\n * ```\n *\n * Claiming root access, meaning complete access to all files and folders of a storage, can be done using an asterisk for the scope:\n *\n * ```javascript\n * remoteStorage.access.claim('*', 'rw');\n * ```\n */\n claim (scope: AccessScope, mode: AccessMode): void {\n if (typeof (scope) !== 'string' || scope.indexOf('/') !== -1 || scope.length === 0) {\n throw new Error('Scope should be a non-empty string without forward slashes');\n }\n if (!mode.match(/^rw?$/)) {\n throw new Error('Mode should be either \\'r\\' or \\'rw\\'');\n }\n this._adjustRootPaths(scope);\n this.scopeModeMap[scope] = mode;\n }\n\n /**\n * Get the access mode for a given scope.\n *\n * @param scope - Access scope\n * @returns Access mode\n * @ignore\n */\n get (scope: AccessScope): AccessMode {\n return this.scopeModeMap[scope];\n }\n\n\n /**\n * Remove access for the given scope.\n *\n * @param scope - Access scope\n * @ignore\n */\n remove (scope: AccessScope): void {\n const savedMap: ScopeModeMap = {};\n for (const name in this.scopeModeMap) {\n savedMap[name] = this.scopeModeMap[name];\n }\n this.reset();\n delete savedMap[scope];\n for (const name in savedMap) {\n this.claim(name as AccessScope, savedMap[name]);\n }\n }\n\n /**\n * Verify permission for a given scope.\n *\n * @param scope - Access scope\n * @param mode - Access mode\n * @returns `true` if the requested access mode is active, `false` otherwise\n * @ignore\n */\n checkPermission (scope: AccessScope, mode: AccessMode): boolean {\n const actualMode = this.get(scope);\n return actualMode && (mode === 'r' || actualMode === 'rw');\n }\n\n /**\n * Verify permission for a given path.\n *\n * @param path - Path\n * @param mode - Access mode\n * @returns true if the requested access mode is active, false otherwise\n * @ignore\n */\n checkPathPermission (path: string, mode: AccessMode): boolean {\n if (this.checkPermission('*', mode)) {\n return true;\n }\n // TODO check if this is reliable\n const scope = this._getModuleName(path) as AccessScope;\n return !!this.checkPermission(scope, mode);\n }\n\n /**\n * Reset all access permissions.\n *\n * @ignore\n */\n reset(): void {\n this.rootPaths = [];\n this.scopeModeMap = {};\n }\n\n /**\n * Return the module name for a given path.\n */\n private _getModuleName (path): string {\n if (path[0] !== '/') {\n throw new Error('Path should start with a slash');\n }\n const moduleMatch = path.replace(/^\\/public/, '').match(/^\\/([^/]*)\\//);\n return moduleMatch ? moduleMatch[1] : '*';\n }\n\n /**\n * TODO: document\n */\n private _adjustRootPaths (newScope: AccessScope): void {\n if ('*' in this.scopeModeMap || newScope === '*') {\n this.rootPaths = ['/'];\n } else if (!(newScope in this.scopeModeMap)) {\n this.rootPaths.push('/' + newScope + '/');\n this.rootPaths.push('/public/' + newScope + '/');\n }\n }\n\n /**\n * TODO: document\n */\n private _scopeNameForParameter (scope: ScopeEntry): string {\n if (scope.name === '*' && this.storageType) {\n if (this.storageType === '2012.04') {\n return '';\n } else if (this.storageType.match(/remotestorage-0[01]/)) {\n return 'root';\n }\n }\n return scope.name;\n }\n\n /**\n * Set the storage type of the remote.\n *\n * @param type - Storage type\n * @internal\n */\n setStorageType (type: string): void {\n this.storageType = type;\n }\n}\n\nexport default Access;\n","import log from './log';\nimport RemoteStorage from './remotestorage';\nimport { localStorageAvailable, globalContext, toBase64 } from './util';\nimport UnauthorizedError from './unauthorized-error';\nimport { EventHandler } from './eventhandling';\nimport { requestWithTimeout } from \"./requests\";\nimport { Remote } from \"./remote\";\n\ninterface AuthResult {\n access_token?: string;\n refresh_token?: string;\n code?: string;\n rsDiscovery?: object;\n error?: string;\n remotestorage?: string;\n state?: string;\n}\n\ninterface InAppBrowserEvent extends Event {\n type: 'loadstart'|'loadstop'|'loaderror'|'message'|'exit';\n url: string;\n code?: number;\n message?: string;\n data?: string;\n}\n\nexport interface AuthorizeOptions {\n /** URL of the authorization endpoint */\n authURL: string;\n /** access scope */\n scope?: string;\n redirectUri?: string;\n /**\n * client identifier\n * @defaultValue Origin of the redirectUri\n * */\n clientId?: string;\n response_type?: 'token' | 'code';\n state?: string;\n code_challenge?: string;\n code_challenge_method?: 'S256' | 'plain';\n token_access_type?: 'online' | 'offline'; // Dropbox only\n}\n\n// This is set in _rs_init and needed for removal in _rs_cleanup\nlet onFeaturesLoaded: EventHandler;\n\nfunction extractParams (url?: string): AuthResult {\n // FF already decodes the URL fragment in document.location.hash, so use this instead:\n // eslint-disable-next-line\n const location = url || Authorize.getLocation().href;\n\n const queryParam = {};\n for (const [key, value] of new URL(location).searchParams) {\n queryParam[key] = value;\n }\n\n const hashPos = location.indexOf('#');\n if (hashPos === -1) { return queryParam; }\n const urlFragment = location.substring(hashPos+1);\n // if hash is not of the form #key=val&key=val, it's probably not for us\n if (!urlFragment.includes('=')) { return queryParam; }\n\n return urlFragment.split('&').reduce(function(params, kvs) {\n const kv = kvs.split('=');\n\n if (kv[0] === 'state' && kv[1].match(/rsDiscovery/)) {\n // extract rsDiscovery data from the state param\n let stateValue = decodeURIComponent(kv[1]);\n const encodedData = stateValue.substr(stateValue.indexOf('rsDiscovery='))\n .split('&')[0]\n .split('=')[1];\n\n params['rsDiscovery'] = JSON.parse(atob(encodedData));\n\n // remove rsDiscovery param\n stateValue = stateValue.replace(new RegExp('&?rsDiscovery=' + encodedData), '');\n\n if (stateValue.length > 0) {\n params['state'] = stateValue;\n }\n } else {\n params[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n }\n\n return params;\n }, queryParam);\n}\n\nfunction buildOAuthURL (options: AuthorizeOptions): string {\n const redirect = new URL(options.redirectUri);\n if (! options.state) {\n options.state = redirect.hash ? redirect.hash.substring(1) : '';\n }\n\n if (! options.response_type) {\n options.response_type = 'token';\n }\n\n const url = new URL(options.authURL);\n\n // We don't add a trailing slash as only pathname to redirectUri.\n url.searchParams.set('redirect_uri', options.redirectUri.replace(/#.*$/, ''));\n url.searchParams.set('scope', options.scope);\n url.searchParams.set('client_id', options.clientId);\n\n for (const key of ['state', 'response_type', 'code_challenge', 'code_challenge_method', 'token_access_type']) {\n const value = options[key];\n if (value) {\n url.searchParams.set(key, value);\n }\n }\n\n return url.href;\n}\n\nexport class Authorize {\n static IMPLIED_FAKE_TOKEN = false;\n\n /**\n * Navigates browser to provider's OAuth page. When user grants access,\n * browser will navigate back to redirectUri and OAuth will continue\n * with onFeaturesLoaded.\n */\n static authorize (remoteStorage: RemoteStorage, options: AuthorizeOptions): void {\n log('[Authorize] authURL = ', options.authURL, 'scope = ', options.scope, 'redirectUri = ', options.redirectUri, 'clientId = ', options.clientId, 'response_type =', options.response_type );\n\n if (!options.scope) {\n throw new Error(\"Cannot authorize due to undefined or empty scope; did you forget to access.claim()?\");\n }\n\n // TODO add a test for this\n // keep track of the discovery data during redirect if we can't save it in localStorage\n if (!localStorageAvailable() && remoteStorage.backend === 'remotestorage') {\n options.redirectUri += options.redirectUri.indexOf('#') > 0 ? '&' : '#';\n\n const discoveryData = {\n userAddress: remoteStorage.remote.userAddress,\n href: remoteStorage.remote.href,\n storageApi: remoteStorage.remote.storageApi,\n properties: remoteStorage.remote.properties\n };\n\n options.redirectUri += 'rsDiscovery=' + toBase64(JSON.stringify(discoveryData));\n }\n\n const url = buildOAuthURL(options);\n\n // FIXME declare potential `cordova` property on global somehow, so we don't have to\n // use a string accessor here.\n if (globalContext['cordova']) {\n Authorize\n .openWindow(url, options.redirectUri, 'location=yes,clearsessioncache=yes,clearcache=yes')\n .then((authResult: AuthResult) => {\n remoteStorage.remote.configure({ token: authResult.access_token });\n });\n return;\n }\n\n Authorize.setLocation(url);\n }\n\n /** On success, calls remote.configure() with new access token */\n static async refreshAccessToken (rs: RemoteStorage, remote: Remote, refreshToken: string): Promise {\n await remote.configure({token: null, tokenType: null});\n const formValues = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: remote.clientId,\n refresh_token: refreshToken,\n });\n const xhr = await requestWithTimeout('POST', remote.TOKEN_URL, {\n headers: {'Content-Type': 'application/x-www-form-urlencoded'},\n body: formValues.toString(),\n responseType: 'json'\n });\n if (xhr?.status === 200) {\n log(`[Authorize] access token good for ${xhr?.response?.expires_in} seconds`);\n const settings = {\n token: xhr?.response?.access_token,\n tokenType: xhr?.response?.token_type,\n };\n if (settings.token) {\n await remote.configure(settings);\n } else {\n throw new Error(`no access_token in \"successful\" refresh: ${xhr.response}`);\n }\n } else {\n await remote.configure({refreshToken: null});\n throw new UnauthorizedError(\"refresh token rejected:\" + JSON.stringify(xhr.response));\n }\n }\n\n /**\n * Get current document location\n *\n * Override this method if access to document.location is forbidden\n */\n static getLocation = function (): Location {\n return document.location;\n };\n\n /**\n * Open new InAppBrowser window for OAuth in Cordova\n */\n static openWindow = function (url: string, redirectUri: string, options: string): Promise {\n return new Promise((resolve, reject) => {\n\n const newWindow = open(url, '_blank', options);\n\n if (!newWindow || newWindow.closed) {\n reject('Authorization popup was blocked'); return;\n }\n\n function handleExit (): void {\n reject('Authorization was canceled');\n }\n\n function handleLoadstart (event: InAppBrowserEvent): void {\n if (event.url.indexOf(redirectUri) !== 0) { return; }\n\n newWindow.removeEventListener('exit', handleExit);\n newWindow.close();\n\n const authResult: AuthResult = extractParams(event.url);\n\n if (!authResult) {\n reject('Authorization error'); return;\n }\n\n resolve(authResult);\n }\n\n newWindow.addEventListener('loadstart', handleLoadstart);\n newWindow.addEventListener('exit', handleExit);\n });\n };\n\n /**\n * Set current document location\n *\n * Override this method if access to document.location is forbidden\n */\n static setLocation (location: string | Location): void {\n if (typeof location === 'string') {\n document.location.href = location;\n } else if (typeof location === 'object') {\n document.location = location;\n } else {\n throw \"Invalid location \" + location;\n }\n }\n\n static _rs_supported (): boolean {\n return typeof(document) !== 'undefined';\n }\n\n static _rs_init = function (remoteStorage: RemoteStorage): void {\n const params = extractParams();\n let location: Location;\n\n if (params) {\n location = Authorize.getLocation();\n location.hash = '';\n }\n\n // eslint-disable-next-line\n onFeaturesLoaded = function(): void {\n let authParamsUsed = false;\n\n if (!params) {\n remoteStorage.remote.stopWaitingForToken();\n return;\n }\n\n if (params.error) {\n if (params.error === 'access_denied') {\n throw new UnauthorizedError('Authorization failed: access denied', { code: 'access_denied' });\n } else {\n throw new UnauthorizedError(`Authorization failed: ${params.error}`);\n }\n }\n\n // rsDiscovery came with the redirect, because it couldn't be\n // saved in localStorage\n if (params.rsDiscovery) {\n remoteStorage.remote.configure(params.rsDiscovery);\n }\n\n if (params.access_token) {\n remoteStorage.remote.configure({ token: params.access_token });\n authParamsUsed = true;\n }\n\n if (params.remotestorage) {\n remoteStorage.connect(params.remotestorage);\n authParamsUsed = true;\n }\n\n if (params.state) {\n location = Authorize.getLocation();\n Authorize.setLocation(location.href.split('#')[0]+'#'+params.state);\n }\n\n if (params.code) { // OAuth2 code or PKCE flow\n fetchTokens(params.code); // remote.configure() called asynchronously\n authParamsUsed = true;\n }\n\n if (!authParamsUsed) {\n remoteStorage.remote.stopWaitingForToken();\n }\n };\n\n // OAuth2 PKCE flow\n async function fetchTokens(code: string) {\n const codeVerifier = sessionStorage.getItem('remotestorage:codeVerifier');\n if (!codeVerifier) {\n log(\"[Authorize] Ignoring OAuth code parameter, because no PKCE code verifier found in sessionStorage\");\n return;\n }\n location = Authorize.getLocation();\n let redirectUri = location.origin;\n if (location.pathname !== '/') {\n redirectUri += location.pathname;\n }\n const formValues = new URLSearchParams({\n code: code,\n grant_type: 'authorization_code',\n client_id: remoteStorage.remote.clientId,\n redirect_uri: redirectUri,\n code_verifier: codeVerifier\n });\n const xhr = await requestWithTimeout(\n 'POST',\n remoteStorage.remote.TOKEN_URL,\n {\n headers: {'Content-Type': 'application/x-www-form-urlencoded'},\n body: formValues.toString(),\n responseType: 'json'\n }\n );\n\n switch (xhr.status) {\n case 200:\n log(`[Authorize] access token good for ${xhr?.response?.expires_in} seconds`);\n const settings = {\n token: xhr?.response?.access_token,\n refreshToken: xhr?.response?.refresh_token,\n tokenType: xhr?.response?.token_type,\n };\n if (settings.token) {\n remoteStorage.remote.configure(settings);\n } else {\n remoteStorage._emit('error', new Error(`no access_token in \"successful\" response: ${xhr.response}`));\n }\n sessionStorage.removeItem('remotestorage:codeVerifier');\n break;\n default:\n remoteStorage._emit('error', new Error(`${xhr.statusText}: ${xhr.response}`));\n }\n }\n\n remoteStorage.on('features-loaded', onFeaturesLoaded);\n };\n\n static _rs_cleanup (remoteStorage: RemoteStorage): void {\n remoteStorage.removeEventListener('features-loaded', onFeaturesLoaded);\n }\n}\n\nexport default Authorize;\n","import tv4 from 'tv4';\nimport type { JsonSchemas } from './interfaces/json_schema';\nimport type { ChangeObj } from './interfaces/change_obj';\nimport type { QueuedRequestResponse } from './interfaces/queued_request_response';\nimport Types from './types';\nimport SchemaNotFound from './schema-not-found-error';\nimport EventHandling from './eventhandling';\nimport config from './config';\nimport { applyMixins, cleanPath, isFolder } from './util';\nimport RemoteStorage from './remotestorage';\n\nfunction getModuleNameFromBase(path: string): string {\n const parts = path.split('/');\n return path.length > 2 ? parts[1] : 'root';\n}\n\n/**\n * A `BaseClient` instance is the main endpoint you will use for interacting\n * with a connected storage: listing, reading, creating, updating and deleting\n * documents, as well as handling incoming changes.\n *\n * Base clients are usually used in [data modules](../../../data-modules/),\n * which are loaded with two `BaseClient` instances by default: one for private\n * and one for public documents.\n *\n * However, you can also instantiate a BaseClient outside of a data module using\n * the `remoteStorage.scope()` function. Similarly, you can create a new scoped\n * client within another client, using the `BaseClient`'s own {@link scope}.\n *\n * ## Read/write operations\n *\n * A `BaseClient` deals with three types of data: folders, objects and files.\n *\n * * {@link getListing} returns a mapping of all items within a folder.\n *\n * * {@link getObject} and {@link storeObject} operate on JSON objects. Each object\n * has a type.\n *\n * * {@link getFile} and {@link storeFile} operates on files. Each file has a MIME\n * type.\n *\n * * {@link getAll} returns all objects or files for the given folder path.\n *\n * * {@link remove} operates on either objects or files (but not folders; folders\n * are created and removed implictly).\n *\n * ## Caching logic for read operations\n *\n * All functions requesting/reading data will immediately return data from the\n * local store, *as long as it is reasonably up-to-date*. If data is assumed to be\n * potentially outdated, they will check the remote storage for changes first, and then\n * return the requested data.\n *\n * The default maximum age of requested data is two times the periodic sync\n * interval (10 seconds by default).\n *\n * However, you can adjust this behavior by using the `maxAge` argument with any\n * of these functions, thereby changing the maximum age or removing the\n * requirement entirely.\n *\n * * If the `maxAge` requirement is set, and the last sync request for the path\n * is further in the past than the maximum age given, the folder will first be\n * checked for changes on the remote, and then the promise will be fulfilled\n * with the up-to-date document or listing.\n *\n * * If the `maxAge` requirement is set, and cannot be met because of network\n * problems, the promise will be rejected.\n *\n * * If the `maxAge` requirement is set to `false`, or the library is in\n * offline mode, or no remote storage is connected (a.k.a. \"anonymous mode\"),\n * the promise will always be fulfilled with data from the local store.\n *\n * > [!NOTE]\n * > If {@link caching!Caching caching} for the folder is turned off, none of\n * > this applies and data will always be requested from the remote store\n * > directly.\n *\n * ## Change events\n *\n * A `BaseClient` emits only one type of event, named `change`, which you can add\n * a handler for using the `.on()` function (same as with {@link RemoteStorage}):\n *\n * ```js\n * client.on('change', function (evt) {\n * console.log('data was added, updated, or removed:', evt)\n * });\n * ```\n *\n * Using this event, your app can stay informed about data changes, both remote\n * (from other devices or browsers), as well as locally (e.g. other browser tabs).\n *\n * In order to determine where a change originated from, look at the `origin`\n * property of the event. Possible values are `window`, `local`, `remote`, and\n * `conflict`, explained in detail below.\n *\n * #### Example\n *\n * ```js\n * {\n * // Absolute path of the changed node, from the storage root\n * path: path,\n * // Path of the changed node, relative to this baseclient's scope root\n * relativePath: relativePath,\n * // See origin descriptions below\n * origin: 'window|local|remote|conflict',\n * // Old body of the changed node (local version in conflicts; undefined if creation)\n * oldValue: oldBody,\n * // New body of the changed node (remote version in conflicts; undefined if deletion)\n * newValue: newBody,\n * // Body when local and remote last agreed; only present in conflict events\n * lastCommonValue: lastCommonBody,\n * // Old contentType of the changed node (local version for conflicts; undefined if creation)\n * oldContentType: oldContentType,\n * // New contentType of the changed node (remote version for conflicts; undefined if deletion)\n * newContentType: newContentType,\n * // ContentType when local and remote last agreed; only present in conflict events\n * lastCommonContentType: lastCommonContentType\n * }\n * ```\n *\n * ### `local`\n *\n * Events with origin `local` are fired conveniently during the page load, so\n * that you can fill your views when the page loads.\n *\n * Example:\n *\n * ```js\n * {\n * path: '/public/design/color.txt',\n * relativePath: 'color.txt',\n * origin: 'local',\n * oldValue: undefined,\n * newValue: 'white',\n * oldContentType: undefined,\n * newContentType: 'text/plain'\n * }\n * ```\n *\n * > [!TIP]\n * > You may also use for example {@link getAll} instead, and choose to\n * > deactivate these.\n *\n * ### `remote`\n *\n * Events with origin `remote` are fired when remote changes are discovered\n * during sync.\n *\n * > [!NOTE]\n * > Automatically receiving remote changes depends on the {@link caching!Caching} settings\n * > for your module/paths.\n *\n * ### `window`\n *\n * Events with origin `window` are fired whenever you change a value by calling a\n * method on the `BaseClient`; these are disabled by default.\n *\n * > [!TIP]\n * > You can enable them by configuring `changeEvents` for your\n * > {@link RemoteStorage remoteStorage} instance.\n *\n * ### `conflict`\n *\n * Events with origin `conflict` are fired when a conflict occurs while pushing\n * out your local changes to the remote store.\n *\n * Let's say you changed the content of `color.txt` from `white` to `blue`; if\n * you have set `config.changeEvents.window` to `true` for your {@link\n * RemoteStorage} instance, then you will receive:\n *\n * ```js\n * {\n * path: '/public/design/color.txt',\n * relativePath: 'color.txt',\n * origin: 'window',\n * oldValue: 'white',\n * newValue: 'blue',\n * oldContentType: 'text/plain',\n * newContentType: 'text/plain'\n * }\n * ```\n *\n * But when this change is pushed out by asynchronous synchronization, this change\n * may be rejected by the server, if the remote version has in the meantime changed\n * from `white` to for instance `red`; this will then lead to a change event with\n * origin `conflict` (usually a few seconds after the event with origin `window`,\n * if you have those activated). Note that since you already changed it from\n * `white` to `blue` in the local version a few seconds ago, `oldValue` is now\n * your local value of `blue`:\n *\n * ```js\n * {\n * path: '/public/design/color.txt',\n * relativePath: 'color.txt',\n * origin: 'conflict',\n * oldValue: 'blue',\n * newValue: 'red',\n * oldContentType: 'text/plain',\n * newContentType: 'text/plain',\n * // Most recent known common ancestor body of local and remote\n * lastCommonValue: 'white',\n * // Most recent known common ancestor contentType of local and remote\n * lastCommonContentType: 'text/plain'\n * }\n * ```\n *\n * #### Conflict Resolution\n *\n * Conflicts are resolved by calling {@link storeObject} or {@link storeFile} on\n * the device where the conflict surfaced. Other devices are not aware of the\n * conflict.\n *\n * If there is an algorithm to merge the differences between local and remote\n * versions of the data, conflicts may be automatically resolved.\n * {@link storeObject} or {@link storeFile} must not be called synchronously from\n * the change event handler, nor by chaining Promises. {@link storeObject} or\n * {@link storeFile} must not be called until the next iteration of the JavaScript\n * Task Queue, using for example\n * [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout).\n *\n * If no algorithm exists, conflict resolution typically involves displaying local\n * and remote versions to the user, and having the user merge them, or choose\n * which version to keep.\n */\nexport class BaseClient {\n /**\n * The {@link RemoteStorage} instance this {@link BaseClient} operates on.\n *\n * @internal\n */\n storage: RemoteStorage;\n\n /**\n * Base path, which this {@link BaseClient} operates on.\n *\n * For the module's `privateClient` this would be the module name, and for the\n * corresponding `publicClient` it is `/public//`.\n */\n base: string;\n\n moduleName: string;\n\n constructor(storage: RemoteStorage, base: string) {\n if (base[base.length - 1] !== '/') {\n throw \"Not a folder: \" + base;\n }\n\n if (base === '/') {\n // allow absolute and relative paths for the root scope.\n this.makePath = (path: string): string => {\n return (path[0] === '/' ? '' : '/') + path;\n };\n }\n\n this.storage = storage;\n this.base = base;\n this.moduleName = getModuleNameFromBase(this.base);\n\n this.addEvents(['change']);\n this.on = this.on.bind(this);\n storage.onChange(this.base, this._fireChange.bind(this));\n }\n\n /**\n * Instantiate a new client, scoped to a subpath of the current client's\n * path.\n *\n * @param path - The path to scope the new client to\n *\n * @returns A new `BaseClient` operating on a subpath of the current base path\n */\n scope (path: string): BaseClient {\n return new BaseClient(this.storage, this.makePath(path));\n }\n\n /**\n * Get a list of child nodes below a given path.\n *\n * @param path - The path to query. It must end with a forward slash.\n * @param maxAge - (optional) Either `false` or the maximum age of cached\n * listing in milliseconds. See [caching logic for read\n * operations](#caching-logic-for-read-operations).\n *\n * @returns A promise for a folder listing object\n *\n * @example\n * ```js\n * client.getListing().then(listing => console.log(listing));\n * ```\n *\n * The folder listing is returned as a JSON object, with the root keys\n * representing the pathnames of child nodes. Keys ending in a forward slash\n * represent _folder nodes_ (subdirectories), while all other keys represent\n * _data nodes_ (files/objects).\n *\n * Data node information contains the item's ETag, content type and -length.\n *\n * Example of a listing object:\n *\n * ```js\n * {\n * \"@context\": \"http://remotestorage.io/spec/folder-description\",\n * \"items\": {\n * \"thumbnails/\": true,\n * \"screenshot-20170902-1913.png\": {\n * \"ETag\": \"6749fcb9eef3f9e46bb537ed020aeece\",\n * \"Content-Length\": 53698,\n * \"Content-Type\": \"image/png;charset=binary\"\n * },\n * \"screenshot-20170823-0142.png\": {\n * \"ETag\": \"92ab84792ef3f9e46bb537edac9bc3a1\",\n * \"Content-Length\": 412401,\n * \"Content-Type\": \"image/png;charset=binary\"\n * }\n * }\n * }\n * ```\n *\n * > [!WARNING]\n * > At the moment, this function only returns detailed metadata, when\n * > caching is turned off. With caching turned on, it will only contain the\n * > item names as properties with `true` as value. See issues 721 and 1108 —\n * > contributions welcome!\n */\n // TODO add real return type\n async getListing (path?: string, maxAge?: false | number): Promise {\n if (typeof path !== 'string') { path = ''; }\n else if (path.length > 0 && !isFolder(path)) {\n return Promise.reject(\"Not a folder: \" + path);\n }\n\n return this.storage.get(this.makePath(path), maxAge).then((r: QueuedRequestResponse) => {\n return r.statusCode === 404 ? {} : r.body;\n });\n }\n\n /**\n * Get all objects directly below a given path.\n *\n * @param path - (optional) Path to the folder. Must end in a forward slash.\n * @param maxAge - (optional) Either `false` or the maximum age of cached\n * objects in milliseconds. See [caching logic for read\n * operations](#caching-logic-for-read-operations).\n\n *\n * @returns A promise for a collection of items\n *\n * @example\n * ```js\n * client.getAll('example-subdirectory/').then(objects => {\n * for (var path in objects) {\n * console.log(path, objects[path]);\n * }\n * });\n * ```\n *\n * Example response:\n *\n * ```js\n * {\n * \"27b8dc16483734625fff9de653a14e03\": {\n * \"@context\": \"http://remotestorage.io/spec/modules/bookmarks/archive-bookmark\",\n * \"id\": \"27b8dc16483734625fff9de653a14e03\",\n * \"url\": \"https://unhosted.org/\",\n * \"title\": \"Unhosted Web Apps\",\n * \"description\": \"Freedom from web 2.0's monopoly platforms\",\n * \"tags\": [\n * \"unhosted\",\n * \"remotestorage\"\n * ],\n * \"createdAt\": \"2017-11-02T15:22:25.289Z\",\n * \"updatedAt\": \"2019-11-07T17:52:22.643Z\"\n * },\n * \"900a5ca174bf57c56b79af0653053bdc\": {\n * \"@context\": \"http://remotestorage.io/spec/modules/bookmarks/archive-bookmark\",\n * \"id\": \"900a5ca174bf57c56b79af0653053bdc\",\n * \"url\": \"https://remotestorage.io/\",\n * \"title\": \"remoteStorage\",\n * \"description\": \"An open protocol for per-user storage on the Web\",\n * \"tags\": [\n * \"unhosted\",\n * \"remotestorage\"\n * ],\n * \"createdAt\": \"2019-11-07T17:59:34.883Z\"\n * }\n * }\n * ```\n * > [!NOTE]\n * > For items that are not JSON-stringified objects (for example stored using\n * > {@link storeFile} instead of {@link storeObject}), the object's value is\n * > filled in with `true`.\n *\n */\n // TODO add real return type\n async getAll (path?: string, maxAge?: false | number): Promise {\n if (typeof path !== 'string') { path = ''; }\n else if (path.length > 0 && !isFolder(path)) {\n return Promise.reject(\"Not a folder: \" + path);\n }\n\n return this.storage.get(this.makePath(path), maxAge).then((r: QueuedRequestResponse) => {\n if (r.statusCode === 404) { return {}; }\n if (typeof r.body === 'object') {\n const keys = Object.keys(r.body);\n // treat this like 404. it probably means a folder listing that\n // has changes that haven't been pushed out yet.\n if (keys.length === 0) { return {}; }\n\n const calls = keys.map((key: string) => {\n return this.storage.get(this.makePath(path + key), maxAge)\n .then((o: QueuedRequestResponse) => {\n if (typeof o.body === 'string') {\n try { o.body = JSON.parse(o.body); }\n catch (e) { /* empty */ }\n }\n if (typeof o.body === 'object') {\n r.body[key] = o.body;\n }\n });\n });\n\n return Promise.all(calls).then(() => { return r.body; });\n }\n });\n }\n\n /**\n * Get the file at the given path. A file is raw data, as opposed to\n * a JSON object (use {@link getObject} for that).\n *\n *\n * @param path - Relative path from the module root (without leading slash).\n * @param maxAge - (optional) Either ``false`` or the maximum age of\n * the cached file in milliseconds. See [caching logic for read\n * operations](#caching-logic-for-read-operations).\n *\n * @returns An object containing the content type as well as the file's content:\n *\n * * `mimeType`
\n * String representing the MIME Type of the document.\n * * `data`
\n * Raw data of the document (either a string or an ArrayBuffer)\n *\n * @example\n * Displaying an image:\n *\n * ```js\n * client.getFile('path/to/some/image').then(file => {\n * const blob = new Blob([file.data], { type: file.mimeType });\n * const targetElement = document.findElementById('my-image-element');\n * targetElement.src = window.URL.createObjectURL(blob);\n * });\n * ```\n */\n // TODO add real return type\n async getFile (path: string, maxAge?: false | number): Promise {\n if (typeof path !== 'string') {\n return Promise.reject('Argument \\'path\\' of baseClient.getFile must be a string');\n }\n\n return this.storage.get(this.makePath(path), maxAge).then((r: QueuedRequestResponse) => {\n return {\n data: r.body,\n contentType: r.contentType,\n revision: r.revision // (this is new)\n };\n });\n }\n\n /**\n * Store raw data at a given path.\n *\n * @param mimeType - MIME media type of the data being stored\n * @param path - Path relative to the module root\n * @param body - Raw data to store\n *\n * @returns A promise for the created/updated revision (ETag)\n *\n * @example\n * UTF-8 data:\n *\n * ```js\n * client.storeFile('text/html', 'index.html', '

Hello World!

')\n * .then(() => { console.log(\"File saved\") });\n * ```\n *\n * Binary data:\n *\n * ```js\n * const input = document.querySelector('form#upload input[type=file]');\n * const file = input.files[0];\n * const fileReader = new FileReader();\n *\n * fileReader.onload = function () {\n * client.storeFile(file.type, file.name, fileReader.result)\n * .then(() => { console.log(\"File saved\") });\n * };\n *\n * fileReader.readAsArrayBuffer(file);\n * ```\n */\n async storeFile (mimeType: string, path: string, body: string | ArrayBuffer | ArrayBufferView): Promise {\n if (typeof mimeType !== 'string') {\n return Promise.reject('Argument \\'mimeType\\' of baseClient.storeFile must be a string');\n }\n if (typeof path !== 'string') {\n return Promise.reject('Argument \\'path\\' of baseClient.storeFile must be a string');\n }\n if ((typeof body !== 'string') && (typeof body !== 'object')) {\n return Promise.reject('Argument \\'body\\' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView');\n }\n if (!this.storage.access.checkPathPermission(this.makePath(path), 'rw')) {\n console.warn('WARNING: Editing a document to which only read access (\\'r\\') was claimed');\n }\n\n return this.storage.put(this.makePath(path), body, mimeType).then((r: QueuedRequestResponse) => {\n if (r.statusCode === 200 || r.statusCode === 201) {\n return r.revision;\n } else {\n return Promise.reject(\"Request (PUT \" + this.makePath(path) + \") failed with status: \" + r.statusCode);\n }\n });\n }\n\n /**\n * Get a JSON object from the given path.\n *\n * @param path - Relative path from the module root (without leading slash).\n * @param maxAge - (optional) Either `false` or the maximum age of\n * cached object in milliseconds. See [caching logic for read\n * operations](#caching-logic-for-read-operations).\n *\n * @returns A promise, resolving with the requested object, or `null` if non-existent\n *\n * @example\n * client.getObject('/path/to/object').then(obj => console.log(obj));\n */\n\n // TODO add real return type\n async getObject (path: string, maxAge?: false | number): Promise {\n if (typeof path !== 'string') {\n return Promise.reject('Argument \\'path\\' of baseClient.getObject must be a string');\n }\n\n return this.storage.get(this.makePath(path), maxAge).then((r: QueuedRequestResponse) => {\n if (typeof r.body === 'object') { // will be the case for documents stored with rs.js <= 0.10.0-beta2\n return r.body;\n } else if (typeof r.body === 'string') {\n try {\n return JSON.parse(r.body);\n } catch (e) {\n throw new Error(\"Not valid JSON: \" + this.makePath(path));\n }\n } else if (typeof r.body !== 'undefined' && r.statusCode === 200) {\n return Promise.reject(\"Not an object: \" + this.makePath(path));\n }\n });\n }\n\n /**\n * Store an object at given path. Triggers synchronization. See {@link\n * declareType} and\n * [Defining data types](../../../data-modules/defining-data-types)\n * for info on object types.\n *\n * Must not be called more than once per second for any given `path`.\n *\n * @param typeAlias - Unique type of this object within this module.\n * @param path - Path relative to the module root.\n * @param object - A JavaScript object to be stored at the given path.\n * Must be serializable as JSON.\n *\n * @returns Resolves with revision on success. Rejects with an error object,\n * if schema validations fail.\n *\n * @example\n * const bookmark = {\n * url: 'http://unhosted.org',\n * description: 'Unhosted Adventures',\n * tags: ['unhosted', 'remotestorage', 'no-backend']\n * }\n * const path = MD5Hash(bookmark.url);\n\n * client.storeObject('bookmark', path, bookmark)\n * .then(() => console.log('bookmark saved'))\n * .catch((err) => console.log(err));\n */\n async storeObject (typeAlias: string, path: string, object: object): Promise {\n if (typeof typeAlias !== 'string') {\n return Promise.reject('Argument \\'typeAlias\\' of baseClient.storeObject must be a string');\n }\n if (typeof path !== 'string') {\n return Promise.reject('Argument \\'path\\' of baseClient.storeObject must be a string');\n }\n if (typeof object !== 'object') {\n return Promise.reject('Argument \\'object\\' of baseClient.storeObject must be an object');\n }\n\n this._attachType(object, typeAlias);\n\n try {\n const validationResult = this.validate(object);\n if (!validationResult.valid) {\n return Promise.reject(validationResult);\n }\n } catch (exc) {\n return Promise.reject(exc);\n }\n\n return this.storage.put(this.makePath(path), JSON.stringify(object), 'application/json; charset=UTF-8').then((r: QueuedRequestResponse) => {\n if (r.statusCode === 200 || r.statusCode === 201) {\n return r.revision;\n } else {\n return Promise.reject(\"Request (PUT \" + this.makePath(path) + \") failed with status: \" + r.statusCode);\n }\n });\n }\n\n /**\n * Remove node at given path from storage. Triggers synchronization.\n *\n * @param path - Path relative to the module root.\n *\n * @example\n * client.remove('path/to/object').then(() => console.log('item deleted'));\n */\n // TODO add real return type\n // TODO Don't return the RemoteResponse directly, handle response properly\n remove (path: string): Promise {\n if (typeof path !== 'string') {\n return Promise.reject('Argument \\'path\\' of baseClient.remove must be a string');\n }\n if (!this.storage.access.checkPathPermission(this.makePath(path), 'rw')) {\n console.warn('WARNING: Removing a document to which only read access (\\'r\\') was claimed');\n }\n\n return this.storage.delete(this.makePath(path));\n }\n\n /**\n * Retrieve full URL of a document. Useful for example for sharing the public\n * URL of an item in the ``/public`` folder.\n *\n * @param path - Path relative to the module root.\n *\n * @returns The full URL of the item, including the storage origin, or `undefined`\n * if no remote storage is connected\n *\n * > [!WARNING]\n * > This method currently only works for remoteStorage\n * > backends. The GitHub issues for implementing it for Dropbox and Google\n * > are 1052 and 1054.\n */\n // TODO refactor this into the Remote interface\n getItemURL (path: string): string | undefined {\n if (typeof path !== 'string') {\n throw 'Argument \\'path\\' of baseClient.getItemURL must be a string';\n }\n if (this.storage.connected) {\n path = cleanPath(this.makePath(path));\n return this.storage.remote.href + path;\n } else {\n return undefined;\n }\n }\n\n /**\n * Set caching strategy for a given path and its children.\n *\n * See [Caching strategies](../../caching/classes/Caching.html#caching-strategies)\n * for a detailed description of the available strategies.\n *\n * @param path - Path to cache\n * @param strategy - Caching strategy. One of 'ALL', 'SEEN', or FLUSH'.\n * Defaults to 'ALL'.\n *\n * @returns The same `BaseClient` instance this method is called on to allow\n * for method chaining\n *\n * @example\n * client.cache('lists/', 'SEEN');\n */\n cache (path: string, strategy: 'ALL' | 'SEEN' | 'FLUSH' = 'ALL'): BaseClient {\n if (typeof path !== 'string') {\n throw 'Argument \\'path\\' of baseClient.cache must be a string';\n }\n if (typeof strategy !== 'string') {\n throw 'Argument \\'strategy\\' of baseClient.cache must be a string or undefined';\n }\n if (strategy !== 'FLUSH' &&\n strategy !== 'SEEN' &&\n strategy !== 'ALL') {\n throw 'Argument \\'strategy\\' of baseclient.cache must be one of '\n + '[\"FLUSH\", \"SEEN\", \"ALL\"]';\n }\n\n this.storage.caching.set(this.makePath(path), strategy);\n return this;\n }\n\n /**\n * Declare a remoteStorage object type using a JSON Schema. Visit\n * [json-schema.org](http://json-schema.org) for details.\n *\n * See [Defining data types](../../../data-modules/defining-data-types) for more info.\n *\n * @param alias - A type alias/shortname\n * @param uriOrSchema - JSON-LD URI of the schema, or a JSON Schema object.\n * The URI is automatically generated if none given.\n * @param schema - (optional) A JSON Schema object describing the object type\n *\n * @example\n * client.declareType('todo-item', {\n * \"type\": \"object\",\n * \"properties\": {\n * \"id\": {\n * \"type\": \"string\"\n * },\n * \"title\": {\n * \"type\": \"string\"\n * },\n * \"finished\": {\n * \"type\": \"boolean\"\n * \"default\": false\n * },\n * \"createdAt\": {\n * \"type\": \"date\"\n * }\n * },\n * \"required\": [\"id\", \"title\"]\n * })\n **/\n declareType (alias: string, uriOrSchema: string|tv4.JsonSchema, schema?: tv4.JsonSchema): void {\n let uri: string;\n\n if (schema && typeof uriOrSchema === 'string') {\n uri = uriOrSchema;\n } else if (!schema && typeof uriOrSchema !== 'string') {\n schema = uriOrSchema;\n uri = this._defaultTypeURI(alias);\n } else if (!schema && typeof uriOrSchema === 'string') {\n throw new Error('declareType() requires a JSON Schema object to be passed, in order to validate object types/formats');\n }\n\n BaseClient.Types.declare(this.moduleName, alias, uri, schema);\n }\n\n /**\n * Validate an object against the associated schema.\n *\n * @param object - JS object to validate. Must have a `@context` property.\n *\n * @returns An object containing information about the validation result\n *\n * @example\n * var result = client.validate(document);\n *\n * // result:\n * // {\n * // error: null,\n * // missing: [],\n * // valid: true\n * // }\n **/\n validate (object: {[key: string]: any}): {[key: string]: any} {\n const schema = BaseClient.Types.getSchema(object['@context']);\n if (schema) {\n return tv4.validateResult(object, schema);\n } else {\n throw new SchemaNotFound(object['@context']);\n }\n }\n\n /**\n * TODO document\n *\n * @private\n */\n schemas = {\n configurable: true,\n\n get (): JsonSchemas {\n return BaseClient.Types.inScope(this.moduleName);\n }\n };\n\n /**\n * The default JSON-LD @context URL for RS types/objects/documents\n *\n * @private\n */\n _defaultTypeURI (alias: string): string {\n return 'http://remotestorage.io/spec/modules/' + encodeURIComponent(this.moduleName) + '/' + encodeURIComponent(alias);\n }\n\n /**\n * Attaches the JSON-LD @context to an object\n *\n * @private\n */\n _attachType (object: object, alias: string): void {\n object['@context'] = BaseClient.Types.resolveAlias(this.moduleName + '/' + alias) || this._defaultTypeURI(alias);\n }\n\n /**\n * TODO: document\n *\n * @private\n */\n makePath (path: string): string {\n return this.base + (path || '');\n }\n\n /**\n * TODO: document\n *\n * @private\n */\n _fireChange (event: ChangeObj): void {\n if (config.changeEvents[event.origin]) {\n ['new', 'old', 'lastCommon'].forEach(function (fieldNamePrefix) {\n if ((!event[fieldNamePrefix + 'ContentType'])\n || (/^application\\/(.*)json(.*)/.exec(event[fieldNamePrefix + 'ContentType']))) {\n if (typeof event[fieldNamePrefix + 'Value'] === 'string') {\n try {\n event[fieldNamePrefix + 'Value'] = JSON.parse(event[fieldNamePrefix + 'Value']);\n } catch (e) {\n // empty\n }\n }\n }\n });\n this._emit('change', event);\n }\n }\n\n static Types = Types;\n\n static _rs_init (): void {\n return;\n }\n}\n\nexport interface BaseClient extends EventHandling {}\napplyMixins(BaseClient, [EventHandling]);\n\nexport default BaseClient;\n","import { containingFolder, isFolder } from './util';\nimport log from './log';\n\n/**\n * @class\n *\n * The caching class gets initialized as `remoteStorage.caching`, unless the\n * {@link remotestorage!RemoteStorage RemoteStorage} instance is created with the option `cache: false`, disabling\n * caching entirely.\n *\n * In case your app hasn't explictly configured caching, the default setting is to\n * cache any documents that have been either created or requested since your app\n * loaded. For offline-capable apps, it usually makes sense to enable full,\n * automatic caching of all documents, which is what {@link enable} will do.\n *\n * Enabling full caching has several benefits:\n *\n * * Speed of access: locally cached data is available to the app a lot faster.\n * * Offline mode: when all data is cached, it can also be read when your app\n * starts while being offline.\n * * Initial synchronization time: the amount of data your app caches can\n * have a significant impact on its startup time.\n *\n * Caching can be configured on a per-path basis. When caching is enabled for a\n * folder, it causes all subdirectories to be cached as well.\n *\n * ## Caching strategies\n *\n * For each subtree, you can set the caching strategy to ``ALL``, ``SEEN``\n * (default), and ``FLUSH``.\n *\n * * `ALL` means that once all outgoing changes have been pushed, sync will\n * start retrieving nodes to cache pro-actively. If a local copy exists\n * of everything, it will check on each sync whether the ETag of the root\n * folder changed, and retrieve remote changes if they exist.\n * * `SEEN` does this only for documents and folders that have been either\n * read from or written to at least once since connecting to the current\n * remote backend, plus their parent/ancestor folders up to the root (to\n * make tree-based sync possible).\n * * `FLUSH` will only cache outgoing changes, and forget them as soon as\n * they have been saved to remote successfully.\n **/\nexport class Caching {\n pendingActivations: string[] = [];\n // TODO add correct type\n activateHandler: (firstPending: string) => void;\n\n private _rootPaths: object;\n\n constructor () {\n this.reset();\n }\n\n /**\n * Configure caching for a given path explicitly.\n *\n * Not needed when using ``enable``/``disable``.\n *\n * @param path - Path to cache\n * @param strategy - Caching strategy. One of 'ALL', 'SEEN', or 'FLUSH'.\n *\n * @example\n * ```js\n * remoteStorage.caching.set('/bookmarks/archive/', 'SEEN');\n * ```\n */\n set (path: string, strategy: 'ALL' | 'SEEN' | 'FLUSH'): void {\n if (typeof path !== 'string') {\n throw new Error('path should be a string');\n }\n if (!isFolder(path)) {\n throw new Error('path should be a folder');\n }\n // FIXME We need to get to the access instance somehow. But I'm not sure\n // this check is even necessary in the first place. -raucao\n // if (!this._remoteStorage.access.checkPathPermission(path, 'r')) {\n // throw new Error('No access to path \"' + path + '\". You have to claim access to it first.');\n // }\n if (!strategy.match(/^(FLUSH|SEEN|ALL)$/)) {\n throw new Error(\"strategy should be 'FLUSH', 'SEEN', or 'ALL'\");\n }\n\n this._rootPaths[path] = strategy;\n\n if (strategy === 'ALL') {\n if (this.activateHandler) {\n this.activateHandler(path);\n } else {\n this.pendingActivations.push(path);\n }\n }\n }\n\n /**\n * Enable caching for a given path.\n *\n * Uses caching strategy ``ALL``.\n *\n * @param path - Path to enable caching for\n * @returns\n *\n * @example\n * ```js\n * remoteStorage.caching.enable('/bookmarks/');\n * ```\n */\n enable (path: string): void {\n this.set(path, 'ALL');\n }\n\n /**\n * Disable caching for a given path.\n *\n * Uses caching strategy ``FLUSH`` (meaning items are only cached until\n * successfully pushed to the remote).\n *\n * @param path - Path to disable caching for\n *\n * @example\n * ```js\n * remoteStorage.caching.disable('/bookmarks/');\n * ```\n */\n disable (path: string): void {\n this.set(path, 'FLUSH');\n }\n\n /**\n * Set a callback for when caching is activated for a path.\n *\n * @param cb - Callback function\n */\n onActivate (cb: (firstPending: string) => void): void {\n log('[Caching] Setting activate handler', cb, this.pendingActivations);\n this.activateHandler = cb;\n for (let i = 0; i < this.pendingActivations.length; i++) {\n cb(this.pendingActivations[i]);\n }\n this.pendingActivations = [];\n }\n\n /**\n * Retrieve caching setting for a given path, or its next parent\n * with a caching strategy set.\n *\n * @param path - Path to retrieve setting for\n * @returns caching strategy for the path\n *\n * @example\n * ```js\n * remoteStorage.caching.checkPath('documents/').then(strategy => {\n * console.log(`caching strategy for 'documents/': ${strategy}`));\n * // \"caching strategy for 'documents/': SEEN\"\n * });\n * ```\n **/\n checkPath (path: string): string {\n if (this._rootPaths[path] !== undefined) {\n return this._rootPaths[path];\n } else if (path === '/') {\n return 'SEEN';\n } else {\n return this.checkPath(containingFolder(path));\n }\n }\n\n /**\n * Reset the state of caching by deleting all caching information.\n *\n * @example\n * ```js\n * remoteStorage.caching.reset();\n * ```\n **/\n reset (): void {\n this._rootPaths = {};\n }\n\n /**\n * Setup function that is called on initialization.\n *\n * @internal\n **/\n static _rs_init (/*remoteStorage*/): void {\n return;\n }\n}\n\nexport default Caching;\n","import type { ChangeObj } from './interfaces/change_obj';\nimport type { QueuedRequestResponse } from './interfaces/queued_request_response';\nimport type { RSEvent } from './interfaces/rs_event';\nimport type { RSNode, RSNodes, ProcessNodes } from './interfaces/rs_node';\nimport EventHandling from './eventhandling';\nimport config from './config';\nimport log from './log';\nimport {\n applyMixins,\n deepClone,\n equal,\n isDocument,\n isFolder,\n pathsFromRoot\n} from './util';\n\nfunction getLatest (node: RSNode): any {\n if (typeof (node) !== 'object' || typeof (node.path) !== 'string') {\n return;\n }\n if (isFolder(node.path)) {\n if (node.local && node.local.itemsMap) {\n return node.local;\n }\n if (node.common && node.common.itemsMap) {\n return node.common;\n }\n } else {\n if (node.local) {\n if (node.local.body && node.local.contentType) {\n return node.local;\n }\n if (node.local.body === false) {\n return;\n }\n }\n if (node.common && node.common.body && node.common.contentType) {\n return node.common;\n }\n // Migration code! Once all apps use at least this version of the lib, we\n // can publish clean-up code that migrates over any old-format data, and\n // stop supporting it. For now, new apps will support data in both\n // formats, thanks to this:\n if (node.body && node.contentType) {\n return {\n body: node.body,\n contentType: node.contentType\n };\n }\n }\n}\n\nfunction isOutdated (nodes: RSNodes, maxAge: number): boolean {\n for (const path in nodes) {\n if (nodes[path] && nodes[path].remote) {\n return true;\n }\n const nodeVersion = getLatest(nodes[path]);\n if (nodeVersion && nodeVersion.timestamp && (new Date().getTime()) - nodeVersion.timestamp <= maxAge) {\n return false;\n } else if (!nodeVersion) {\n return true;\n }\n }\n return true;\n}\n\n\nfunction makeNode (path: string): RSNode {\n const node: RSNode = {path: path, common: {}};\n\n if (isFolder(path)) {\n node.common.itemsMap = {};\n }\n return node;\n}\n\nfunction updateFolderNodeWithItemName (node: RSNode, itemName: string): RSNode {\n if (!node.common) {\n node.common = {\n itemsMap: {}\n };\n }\n if (!node.common.itemsMap) {\n node.common.itemsMap = {};\n }\n if (!node.local) {\n node.local = deepClone(node.common);\n }\n if (!node.local.itemsMap) {\n node.local.itemsMap = node.common.itemsMap;\n }\n node.local.itemsMap[itemName] = true;\n\n return node;\n}\n\n/**\n * This module defines functions that are mixed into remoteStorage.local when\n * it is instantiated (currently one of indexeddb.js, localstorage.js, or\n * inmemorystorage.js).\n *\n * All remoteStorage.local implementations should therefore implement\n * this.getNodes, this.setNodes, and this.forAllNodes. The rest is blended in\n * here to create a GPD (get/put/delete) interface which the BaseClient can\n * talk to.\n *\n * @interface\n */\n\nabstract class CachingLayer {\n // FIXME\n // this process of updating nodes needs to be heavily documented first, then\n // refactored. Right now it's almost impossible to refactor as there's no\n // explanation of why things are implemented certain ways or what the goal(s)\n // of the behavior are. -slvrbckt (+1 -les)\n private _updateNodesRunning = false;\n private _updateNodesQueued = [];\n\n\n // functions that will be overwritten\n // ----------------------------------\n abstract getNodes(paths: string[]): Promise;\n\n abstract diffHandler(...args: any[]);\n\n abstract forAllNodes(cb: (node) => any): Promise;\n\n abstract setNodes(nodes: RSNodes): Promise;\n\n\n // --------------------------------------------------\n\n // TODO: improve our code structure so that this function\n // could call sync.queueGetRequest directly instead of needing\n // this hacky third parameter as a callback\n async get (path: string, maxAge: number, queueGetRequest: (path2: string) => Promise): Promise {\n if (typeof (maxAge) === 'number') {\n return this.getNodes(pathsFromRoot(path))\n .then((objs) => {\n const node: RSNode = getLatest(objs[path]);\n\n if (isOutdated(objs, maxAge)) {\n return queueGetRequest(path);\n } else if (node) {\n return {\n statusCode: 200,\n body: node.body || node.itemsMap,\n contentType: node.contentType\n };\n } else {\n return { statusCode: 404 };\n }\n });\n } else {\n return this.getNodes([path])\n .then((objs) => {\n const node: RSNode = getLatest(objs[path]);\n\n if (node) {\n if (isFolder(path)) {\n for (const i in node.itemsMap) {\n // the hasOwnProperty check here is only because our jshint settings require it:\n if (node.itemsMap.hasOwnProperty(i) && node.itemsMap[i] === false) {\n delete node.itemsMap[i];\n }\n }\n }\n return {\n statusCode: 200,\n body: node.body || node.itemsMap,\n contentType: node.contentType\n };\n } else {\n return {statusCode: 404};\n }\n });\n }\n }\n\n async put (path: string, body: unknown, contentType: string): Promise {\n const paths = pathsFromRoot(path);\n\n function _processNodes(nodePaths: string[], nodes: RSNodes): RSNodes {\n try {\n for (let i = 0, len = nodePaths.length; i < len; i++) {\n const nodePath = nodePaths[i];\n let node = nodes[nodePath];\n let previous: RSNode;\n\n if (!node) {\n nodes[nodePath] = node = makeNode(nodePath);\n }\n\n // Document\n if (i === 0) {\n previous = getLatest(node);\n node.local = {\n body: body,\n contentType: contentType,\n previousBody: (previous ? previous.body : undefined),\n previousContentType: (previous ? previous.contentType : undefined),\n };\n }\n // Folder\n else {\n const itemName = nodePaths[i - 1].substring(nodePath.length);\n node = updateFolderNodeWithItemName(node, itemName);\n }\n }\n return nodes;\n } catch (e) {\n log('[Cachinglayer] Error during PUT', nodes, e);\n throw e;\n }\n }\n\n return this._updateNodes(paths, _processNodes);\n }\n\n delete (path: string): unknown {\n const paths = pathsFromRoot(path);\n\n return this._updateNodes(paths, function (nodePaths, nodes) {\n for (let i = 0, len = nodePaths.length; i < len; i++) {\n const nodePath = nodePaths[i];\n const node = nodes[nodePath];\n let previous;\n\n if (!node) {\n console.error('Cannot delete non-existing node ' + nodePath);\n continue;\n }\n\n if (i === 0) {\n // Document\n previous = getLatest(node);\n node.local = {\n body: false,\n previousBody: (previous ? previous.body : undefined),\n previousContentType: (previous ? previous.contentType : undefined),\n };\n } else {\n // Folder\n if (!node.local) {\n node.local = deepClone(node.common);\n }\n const itemName = nodePaths[i - 1].substring(nodePath.length);\n delete node.local.itemsMap[itemName];\n\n if (Object.getOwnPropertyNames(node.local.itemsMap).length > 0) {\n // This folder still contains other items, don't remove any further ancestors\n break;\n }\n }\n }\n return nodes;\n });\n }\n\n flush(path: string): unknown {\n\n return this._getAllDescendentPaths(path).then((paths: string[]) => {\n return this.getNodes(paths);\n }).then((nodes: RSNodes) => {\n for (const nodePath in nodes) {\n const node = nodes[nodePath];\n\n if (node && node.common && node.local) {\n this._emitChange({\n path: node.path,\n origin: 'local',\n oldValue: (node.local.body === false ? undefined : node.local.body),\n newValue: (node.common.body === false ? undefined : node.common.body)\n });\n }\n nodes[nodePath] = undefined;\n }\n\n return this.setNodes(nodes);\n });\n }\n\n private _emitChange(obj: ChangeObj): void {\n if (config.changeEvents[obj.origin]) {\n this._emit('change', obj);\n }\n }\n\n fireInitial (): void {\n if (!config.changeEvents.local) { return; }\n\n this.forAllNodes((node) => {\n if (isDocument(node.path)) {\n const latest = getLatest(node);\n if (latest) {\n this._emitChange({\n path: node.path,\n origin: 'local',\n oldValue: undefined,\n oldContentType: undefined,\n newValue: latest.body,\n newContentType: latest.contentType\n });\n }\n }\n }).then(() => {\n this._emit('local-events-done');\n });\n }\n\n // TODO add proper type\n onDiff(diffHandler: any) {\n this.diffHandler = diffHandler;\n }\n\n migrate(node: RSNode): RSNode {\n if (typeof (node) === 'object' && !node.common) {\n node.common = {};\n if (typeof (node.path) === 'string') {\n if (node.path.substr(-1) === '/' && typeof (node.body) === 'object') {\n node.common.itemsMap = node.body;\n }\n } else {\n //save legacy content of document node as local version\n if (!node.local) {\n node.local = {};\n }\n node.local.body = node.body;\n node.local.contentType = node.contentType;\n }\n }\n return node;\n }\n\n\n private _updateNodes(paths: string[], _processNodes: ProcessNodes): Promise {\n return new Promise((resolve, reject) => {\n this._doUpdateNodes(paths, _processNodes, {\n resolve: resolve,\n reject: reject\n });\n });\n }\n\n private _doUpdateNodes(paths: string[], _processNodes: ProcessNodes, promise) {\n if (this._updateNodesRunning) {\n this._updateNodesQueued.push({\n paths: paths,\n cb: _processNodes,\n promise: promise\n });\n return;\n } else {\n this._updateNodesRunning = true;\n }\n\n this.getNodes(paths).then((nodes) => {\n const existingNodes = deepClone(nodes);\n const changeEvents = [];\n\n nodes = _processNodes(paths, nodes);\n\n for (const path in nodes) {\n const node = nodes[path];\n if (equal(node, existingNodes[path])) {\n delete nodes[path];\n } else if (isDocument(path)) {\n if (\n !equal(node.local.body, node.local.previousBody) ||\n node.local.contentType !== node.local.previousContentType\n ) {\n changeEvents.push({\n path: path,\n origin: 'window',\n oldValue: node.local.previousBody,\n newValue: node.local.body === false ? undefined : node.local.body,\n oldContentType: node.local.previousContentType,\n newContentType: node.local.contentType\n });\n }\n delete node.local.previousBody;\n delete node.local.previousContentType;\n }\n }\n\n this.setNodes(nodes).then(() => {\n this._emitChangeEvents(changeEvents);\n promise.resolve({statusCode: 200});\n });\n }).then(() => {\n return Promise.resolve();\n }, (err) => {\n promise.reject(err);\n }).then(() => {\n this._updateNodesRunning = false;\n const nextJob = this._updateNodesQueued.shift();\n if (nextJob) {\n this._doUpdateNodes(nextJob.paths, nextJob.cb, nextJob.promise);\n }\n });\n }\n\n private _emitChangeEvents(events: RSEvent[]) {\n for (let i = 0, len = events.length; i < len; i++) {\n this._emitChange(events[i]);\n if (this.diffHandler) {\n this.diffHandler(events[i].path);\n }\n }\n }\n\n private _getAllDescendentPaths(path: string) {\n if (isFolder(path)) {\n return this.getNodes([path]).then((nodes) => {\n const allPaths = [path];\n const latest = getLatest(nodes[path]);\n\n const itemNames = Object.keys(latest.itemsMap);\n const calls = itemNames.map((itemName) => {\n return this._getAllDescendentPaths(path + itemName).then((paths) => {\n for (let i = 0, len = paths.length; i < len; i++) {\n allPaths.push(paths[i]);\n }\n });\n });\n return Promise.all(calls).then(() => {\n return allPaths;\n });\n });\n } else {\n return Promise.resolve([path]);\n }\n }\n\n // treated as private but made public for unit testing\n _getInternals() {\n return {\n getLatest: getLatest,\n makeNode: makeNode,\n isOutdated: isOutdated\n };\n }\n}\n\n\ninterface CachingLayer extends EventHandling {}\napplyMixins(CachingLayer, [EventHandling]);\n\nexport = CachingLayer;\n","/**\n * The default config, merged with the object passed to the constructor of the\n * RemoteStorage object\n */\nconst config = {\n cache: true,\n changeEvents: {\n local: true,\n window: false,\n remote: true,\n conflict: true\n },\n cordovaRedirectUri: undefined,\n logging: false,\n modules: [],\n // the following are not public and will probably be moved away from the\n // default config\n backgroundSyncInterval: 60000,\n disableFeatures: [],\n discoveryTimeout: 5000,\n isBackground: false,\n requestTimeout: 30000,\n syncInterval: 10000\n};\n\nexport = config;\n","'use strict';\n\nimport WebFinger from 'webfinger.js';\nimport type { StorageInfo } from './interfaces/storage_info';\nimport config from './config';\nimport log from './log';\nimport { globalContext, localStorageAvailable } from './util';\n\n// feature detection flags\nlet hasLocalStorage;\n\n// used to store settings in localStorage\nconst SETTINGS_KEY = 'remotestorage:discover';\n\n// cache loaded from localStorage\n// TODO use class property\nlet cachedInfo = {};\n\n/**\n * This function deals with the Webfinger lookup, discovering a connecting\n * user's storage details.\n *\n * @param userAddress - user@host or URL\n *\n * @returns A promise for an object with the following properties.\n * href - Storage base URL,\n * storageApi - RS protocol version,\n * authUrl - OAuth URL,\n * properties - Webfinger link properties\n **/\n\nconst Discover = function Discover(userAddress: string): Promise {\n return new Promise((resolve, reject) => {\n\n if (userAddress in cachedInfo) {\n return resolve(cachedInfo[userAddress]);\n }\n\n const webFinger = new WebFinger({\n tls_only: false,\n uri_fallback: true,\n request_timeout: config.discoveryTimeout\n });\n\n setTimeout(() => {\n return reject(new Error('timed out'));\n }, config.discoveryTimeout);\n\n return webFinger.lookup(userAddress, function (err, response) {\n if (err) {\n return reject(err);\n } else if ((typeof response.idx.links.remotestorage !== 'object') ||\n (typeof response.idx.links.remotestorage.length !== 'number') ||\n (response.idx.links.remotestorage.length <= 0)) {\n log(\"[Discover] WebFinger record for \" + userAddress + \" does not have remotestorage defined in the links section \", JSON.stringify(response.json));\n return reject(\"WebFinger record for \" + userAddress + \" does not have remotestorage defined in the links section.\");\n }\n\n const rs = response.idx.links.remotestorage[0];\n const authURL = rs.properties['http://tools.ietf.org/html/rfc6749#section-4.2'] ||\n rs.properties['auth-endpoint'];\n const storageApi = rs.properties['http://remotestorage.io/spec/version'] ||\n rs.type;\n\n // cache fetched data\n cachedInfo[userAddress] = {\n href: rs.href,\n storageApi: storageApi,\n authURL: authURL,\n properties: rs.properties\n };\n\n if (hasLocalStorage) {\n localStorage.setItem(SETTINGS_KEY, JSON.stringify({ cache: cachedInfo }));\n }\n\n return resolve(cachedInfo[userAddress]);\n });\n });\n};\n\nDiscover.DiscoveryError = function(message) {\n this.name = 'DiscoveryError';\n this.message = message;\n this.stack = (new Error()).stack;\n};\nDiscover.DiscoveryError.prototype = Object.create(Error.prototype);\nDiscover.DiscoveryError.prototype.constructor = Discover.DiscoveryError;\n\nDiscover._rs_init = function (/*remoteStorage*/): void {\n hasLocalStorage = localStorageAvailable();\n if (hasLocalStorage) {\n try {\n const settings = JSON.parse(localStorage[SETTINGS_KEY]);\n cachedInfo = settings.cache;\n } catch(e) {\n /* empty */\n }\n }\n};\n\nDiscover._rs_supported = function (): boolean {\n return Object.prototype.hasOwnProperty.call(globalContext, 'fetch') ||\n Object.prototype.hasOwnProperty.call(globalContext, 'XMLHttpRequest');\n};\n\nDiscover._rs_cleanup = function (): void {\n if (hasLocalStorage) {\n delete localStorage[SETTINGS_KEY];\n }\n};\n\n\nexport = Discover;\n","import EventHandling from './eventhandling';\nimport BaseClient from './baseclient';\nimport RevisionCache from './revisioncache';\nimport SyncError from './sync-error';\nimport UnauthorizedError from './unauthorized-error';\nimport {\n applyMixins,\n isFolder,\n shouldBeTreatedAsBinary,\n getJSONFromLocalStorage,\n getTextFromArrayBuffer,\n localStorageAvailable,\n generateCodeVerifier,\n} from './util';\nimport {requestWithTimeout, isArrayBufferView, retryAfterMs} from \"./requests\";\nimport {Remote, RemoteBase, RemoteResponse, RemoteSettings} from \"./remote\";\nimport RemoteStorage from \"./remotestorage\";\nimport Authorize from \"./authorize\";\n\n/**\n * WORK IN PROGRESS, NOT RECOMMENDED FOR PRODUCTION USE\n *\n * Dropbox backend for RemoteStorage.js\n * This file exposes a get/put/delete interface which is compatible with\n * .\n *\n * When remoteStorage.backend is set to 'dropbox', this backend will\n * initialize and replace remoteStorage.remote with remoteStorage.dropbox.\n *\n * In order to ensure compatibility with the public folder, \n * gets hijacked to return the Dropbox public share URL.\n *\n * To use this backend, you need to specify the Dropbox app key like so:\n *\n * @example\n * remoteStorage.setApiKeys({\n * dropbox: 'your-app-key'\n * });\n *\n * An app key can be obtained by registering your app at https://www.dropbox.com/developers/apps\n *\n * Known issues:\n *\n * - Storing files larger than 150MB is not yet supported\n * - Listing and deleting folders with more than 10'000 files will cause problems\n * - Content-Type is not supported; TODO: use file_properties\n * - Dropbox preserves cases but is not case-sensitive\n * - getItemURL is asynchronous which means it returns useful values\n * after the syncCycle\n */\n\nlet hasLocalStorage;\nconst AUTH_URL = 'https://www.dropbox.com/oauth2/authorize';\nconst ACCOUNT_URL = 'https://api.dropboxapi.com/2/users/get_current_account';\nconst TOKEN_URL = 'https://api.dropboxapi.com/oauth2/token';\nconst OAUTH_SCOPE = 'account_info.read files.content.read files.content.write files.metadata.read files.metadata.write';\nconst SETTINGS_KEY = 'remotestorage:dropbox';\nconst FOLDER_URL = 'https://api.dropboxapi.com/2/files/list_folder';\nconst CONTINUE_URL = 'https://api.dropboxapi.com/2/files/list_folder/continue';\nconst DOWNLOAD_URL = 'https://content.dropboxapi.com/2/files/download';\nconst UPLOAD_URL = 'https://content.dropboxapi.com/2/files/upload';\nconst DELETE_URL = 'https://api.dropboxapi.com/2/files/delete';\nconst METADATA_URL = 'https://api.dropboxapi.com/2/files/get_metadata';\nconst CREATE_SHARED_URL = 'https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings';\nconst LIST_SHARED_URL = 'https://api.dropbox.com/2/sharing/list_shared_links';\nconst PATH_PREFIX = '/remotestorage';\nconst NUM_RETRIES = 3;\n\ninterface Metadata {\n \".tag\": \"folder\" | \"file\";\n id: string;\n name: string;\n path_display: string;\n path_lower: string;\n property_groups: any[];\n sharing_info: {\n no_access?: boolean;\n parent_shared_folder_id: string;\n read_only: boolean;\n traverse_only?: boolean;\n modified_by?: string;\n };\n\n client_modified?: string; // date\n content_hash?: string;\n file_lock_info?: {\n created: string; // date\n is_lockholder: boolean;\n lockholder_name: string;\n };\n has_explicit_shared_members?: boolean;\n is_downloadable?: boolean;\n rev?: string;\n server_modified?: string; // date\n size?: number;\n\n preview_url?: string;\n}\n\n/**\n * Maps a remoteStorage path to a path in Dropbox.\n *\n * @param {string} path - Path\n * @returns {string} Actual path in Dropbox\n *\n * @private\n */\nfunction getDropboxPath (path: string): string {\n return (PATH_PREFIX + '/' + path).replace(/\\/+$/, '').replace(/\\/+/g, '/');\n}\n\n// This function is simple and has OK performance compared to more\n// complicated ones: https://jsperf.com/json-escape-unicode/4\nconst charsToEncode = /[\\u007f-\\uffff]/g;\nfunction httpHeaderSafeJson(obj) {\n return JSON.stringify(obj).replace(charsToEncode,\n function(c) {\n return '\\\\u'+('000'+c.charCodeAt(0).toString(16)).slice(-4);\n }\n );\n}\n\nfunction compareApiError (response: {error_summary: string}, expect: string[]): boolean {\n return new RegExp('^' + expect.join('\\\\/') + '(\\\\/|$)').test(response.error_summary);\n}\n\nfunction isBinaryData (data): boolean {\n return data instanceof ArrayBuffer || isArrayBufferView(data);\n}\n\n/**\n * @class\n */\nclass Dropbox extends RemoteBase implements Remote {\n clientId: string;\n TOKEN_URL: string; // OAuth2 PKCE\n token: string;\n refreshToken: string; // OAuth2 PKCE\n tokenType: string; // OAuth2 PKCE\n userAddress: string;\n\n _initialFetchDone: boolean;\n _revCache: RevisionCache;\n _fetchDeltaCursor: string;\n _fetchDeltaPromise: Promise;\n _itemRefs: { [key: string]: string };\n\n // TODO remove when refactoring eventhandling\n _emit: any;\n\n constructor (rs) {\n super(rs);\n this.online = true; // TODO implement offline detection on failed request\n this.storageApi = 'draft-dejong-remotestorage-19';\n this._initialFetchDone = false;\n\n this.addEvents(['connected', 'not-connected']);\n\n this.clientId = rs.apiKeys.dropbox.appKey;\n this.TOKEN_URL = TOKEN_URL;\n this._revCache = new RevisionCache('rev');\n this._fetchDeltaCursor = null;\n this._fetchDeltaPromise = null;\n this._itemRefs = {};\n\n hasLocalStorage = localStorageAvailable();\n\n if (hasLocalStorage){\n const settings = getJSONFromLocalStorage(SETTINGS_KEY);\n if (settings) {\n this.configure(settings); // can't await in constructor\n }\n this._itemRefs = getJSONFromLocalStorage(`${SETTINGS_KEY}:shares`) || {};\n }\n if (this.connected) {\n setTimeout(this._emit.bind(this), 0, 'connected');\n }\n }\n\n /**\n * Set the backed to 'dropbox' and start the authentication flow in order\n * to obtain an API token from Dropbox.\n */\n async connect () {\n // TODO handling when token is already present\n try {\n this.rs.setBackend('dropbox');\n if (this.token) {\n hookIt(this.rs);\n } else { // OAuth2 PKCE\n const {codeVerifier, codeChallenge, state} = await generateCodeVerifier();\n sessionStorage.setItem('remotestorage:codeVerifier', codeVerifier);\n sessionStorage.setItem('remotestorage:state', state);\n this.rs.authorize({\n authURL: AUTH_URL,\n scope: OAUTH_SCOPE,\n clientId: this.clientId,\n response_type: 'code',\n state: state,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n token_access_type: 'offline'\n });\n }\n } catch (err) {\n this.rs._emit('error', err);\n this.rs.setBackend(undefined);\n throw err;\n }\n }\n\n /**\n * Sets the connected flag\n * Accepts its parameters according to the .\n * @param {Object} settings\n * @param {string} [settings.userAddress] - The user's email address\n * @param {string} [settings.token] - Authorization token\n * @param {string} [settings.refreshToken] - OAuth2 PKCE refresh token\n * @param {string} [settings.tokenType] - usually 'bearer' - no support for 'mac' tokens yet\n *\n * @protected\n **/\n async configure (settings: RemoteSettings): Promise {\n // We only update this.userAddress if settings.userAddress is set to a string or to null:\n if (typeof settings.userAddress !== 'undefined') { this.userAddress = settings.userAddress; }\n // Same for this.token. If only one of these two is set, we leave the other one at its existing value:\n if (typeof settings.token !== 'undefined') { this.token = settings.token as string; }\n if (typeof settings.refreshToken !== 'undefined') { this.refreshToken = settings.refreshToken; }\n if (typeof settings.tokenType !== 'undefined') { this.tokenType = settings.tokenType; }\n\n const writeSettingsToCache = () => {\n if (hasLocalStorage) {\n localStorage.setItem(SETTINGS_KEY, JSON.stringify({\n userAddress: this.userAddress,\n token: this.token,\n refreshToken: this.refreshToken,\n tokenType: this.tokenType,\n }));\n }\n };\n\n const handleError = () => {\n this.connected = false;\n if (hasLocalStorage) {\n localStorage.removeItem(SETTINGS_KEY);\n }\n this.rs.setBackend(undefined);\n };\n\n if (this.refreshToken || this.token) {\n this.connected = true;\n if (this.userAddress) {\n this._emit('connected');\n writeSettingsToCache();\n } else {\n try {\n const info = await this.info();\n this.userAddress = info.email;\n this._emit('connected');\n writeSettingsToCache();\n } catch (err) {\n this.connected = false;\n this.rs._emit('error', new Error('Could not fetch user info.'));\n writeSettingsToCache.apply(this);\n }\n }\n } else {\n handleError();\n }\n }\n\n /**\n * Get all items in a folder.\n *\n * @param path {string} - path of the folder to get, with leading slash\n * @return {Object}\n * statusCode - HTTP status code\n * body - array of the items found\n * contentType - 'application/json; charset=UTF-8'\n * revision - revision of the folder\n *\n * @private\n */\n _getFolder (path: string) {\n const revCache = this._revCache;\n\n const processResponse = (resp) => {\n let body;\n\n if (resp.status !== 200 && resp.status !== 409) {\n return Promise.reject('Unexpected response status: ' + resp.status);\n }\n\n try {\n body = JSON.parse(resp.responseText);\n } catch (e) {\n return Promise.reject(e);\n }\n\n if (resp.status === 409) {\n if (compareApiError(body, ['path', 'not_found'])) {\n // if the folder is not found, handle it as an empty folder\n return Promise.resolve({});\n }\n\n return Promise.reject(new Error('API returned an error: ' + body.error_summary));\n }\n\n const listing = body.entries.reduce((map, item) => {\n try {\n const isDir = item['.tag'] === 'folder';\n const itemName = item.path_display.split('/').slice(-1)[0] + (isDir ? '/' : '');\n if (isDir) {\n map[itemName] = {ETag: revCache.get(path + itemName)};\n } else {\n const date = new Date(item.server_modified);\n map[itemName] = {ETag: item.rev, 'Content-Length': item.size, 'Last-Modified': date.toUTCString()};\n this._revCache.set(path + itemName, item.rev);\n }\n } catch (err) {\n console.error(`[Dropbox] folder “${path}” has entry ${JSON.stringify(item)}:`, err);\n }\n return map;\n }, {});\n\n if (body.has_more) {\n return loadNext(body.cursor).then(function (nextListing) {\n return Object.assign(listing, nextListing);\n });\n }\n\n return Promise.resolve(listing);\n };\n\n const loadNext = (cursor) => {\n const params = {\n body: { cursor: cursor }\n };\n\n return this._request('POST', CONTINUE_URL, params).then(processResponse);\n };\n\n return this._request('POST', FOLDER_URL, {\n body: {\n path: getDropboxPath(path)\n }\n }).then(processResponse).then(function (listing) {\n return Promise.resolve({\n statusCode: 200,\n body: listing,\n contentType: 'application/json; charset=UTF-8',\n revision: revCache.get(path)\n });\n });\n }\n\n /**\n * Checks for the path in ``_revCache`` and decides based on that if file\n * has changed. Calls ``_getFolder`` is the path points to a folder.\n *\n * Calls ``Dropbox.share`` afterwards to fill ``_itemRefs``.\n *\n * Compatible with ``WireClient.get``\n *\n * @param path {string} - path of the folder to get, with leading slash\n * @param options {Object}\n *\n * @protected\n */\n get (path: string, options: { ifNoneMatch?: string } = {}): Promise {\n if (! this.connected) { return Promise.reject(\"not connected (path: \" + path + \")\"); }\n const savedRev = this._revCache.get(path);\n if (savedRev === null) {\n // file was deleted server side\n return Promise.resolve({statusCode: 404});\n }\n if (options && options.ifNoneMatch) {\n // We must wait for local revision cache to be initialized before\n // checking if local revision is outdated\n if (! this._initialFetchDone) {\n return this.fetchDelta().then(() => {\n return this.get(path, options);\n });\n }\n\n if (savedRev && (savedRev === options.ifNoneMatch)) {\n // nothing changed.\n return Promise.resolve({statusCode: 304});\n }\n }\n\n // use _getFolder for folders\n if (path.slice(-1) === '/') {\n return this._getFolder(path);\n }\n\n const params = {\n headers: {\n 'Dropbox-API-Arg': httpHeaderSafeJson({path: getDropboxPath(path)}),\n },\n responseType: 'arraybuffer'\n };\n if (options && options.ifNoneMatch) {\n params.headers['If-None-Match'] = options.ifNoneMatch;\n }\n\n return this._request('GET', DOWNLOAD_URL, params).then(resp => {\n const status = resp.status;\n let meta, body, mime, rev;\n if (status !== 200 && status !== 409) {\n return Promise.resolve({statusCode: status});\n }\n meta = resp.getResponseHeader('Dropbox-API-Result');\n //first encode the response as text, and later check if\n //text appears to actually be binary data\n return getTextFromArrayBuffer(resp.response, 'UTF-8').then(responseText => {\n body = responseText;\n if (status === 409) {\n meta = body;\n }\n\n try {\n meta = JSON.parse(meta);\n } catch(e) {\n return Promise.reject(e);\n }\n\n if (status === 409) {\n if (compareApiError(meta, ['path', 'not_found'])) {\n return {statusCode: 404};\n }\n return Promise.reject(new Error('API error while downloading file (\"' + path + '\"): ' + meta.error_summary));\n }\n\n mime = resp.getResponseHeader('Content-Type');\n rev = meta.rev;\n this._revCache.set(path, rev);\n this._shareIfNeeded(path); // There doesn't appear to be a need to await this.\n\n if (shouldBeTreatedAsBinary(responseText, mime)) {\n // return unprocessed response\n body = resp.response;\n } else {\n // handling json (always try)\n try {\n body = JSON.parse(body);\n mime = 'application/json; charset=UTF-8';\n } catch(e) {\n //Failed parsing Json, assume it is something else then\n }\n }\n\n return {\n statusCode: status,\n body: body,\n contentType: mime,\n revision: rev\n };\n });\n });\n }\n\n /**\n * Checks for the path in ``_revCache`` and decides based on that if file\n * has changed.\n *\n * Compatible with ``WireClient``\n *\n * Calls ``Dropbox.share`` afterwards to fill ``_itemRefs``.\n *\n * @param {string} path - path of the folder to put, with leading slash\n * @param {XMLHttpRequestBodyInit} body - Blob | BufferSource | FormData | URLSearchParams | string\n * @param {string} contentType - MIME type of body\n * @param {Object} options\n * @param {string} options.ifNoneMatch - When *, only create or update the file if it doesn't yet exist\n * @param {string} options.ifMatch - Only saves if this matches current revision\n * @returns {Promise} Resolves with an object containing the status code,\n * content-type and revision\n * @protected\n */\n async put (path: string, body, contentType: string, options: { ifMatch?: string; ifNoneMatch?: string } = {}): Promise {\n if (!this.connected) {\n throw new Error(\"not connected (path: \" + path + \")\");\n }\n\n // check if file has changed and return 412\n const savedRev = this._revCache.get(path);\n if (options && options.ifMatch &&\n savedRev && (savedRev !== options.ifMatch)) {\n return {statusCode: 412, revision: savedRev};\n }\n if (options && (options.ifNoneMatch === '*') &&\n savedRev && (savedRev !== 'rev')) {\n return {statusCode: 412, revision: savedRev};\n }\n\n if ((!contentType.match(/charset=/)) && isBinaryData(body)) {\n contentType += '; charset=binary';\n }\n\n if (body.length > 150 * 1024 * 1024) {\n //https://www.dropbox.com/developers/core/docs#chunked-upload\n throw new Error(\"Cannot upload file larger than 150MB\");\n }\n\n const needsMetadata = options && (options.ifMatch || (options.ifNoneMatch === '*'));\n const uploadParams = {\n body: body,\n contentType: contentType,\n path: path\n };\n\n if (needsMetadata) {\n const metadata = await this._getMetadata(path);\n if (options && (options.ifNoneMatch === '*') && metadata) {\n // if !!metadata === true, the file exists\n return {\n statusCode: 412,\n revision: metadata.rev\n };\n }\n\n if (options && options.ifMatch && metadata && (metadata.rev !== options.ifMatch)) {\n return {\n statusCode: 412,\n revision: metadata.rev\n };\n }\n }\n const result = await this._uploadSimple(uploadParams);\n this._shareIfNeeded(path); // There doesn't appear to be a need to await this.\n return result;\n }\n\n /**\n * Checks for the path in ``_revCache`` and decides based on that if file\n * has changed.\n *\n * Compatible with ``WireClient.delete``\n *\n * Calls ``Dropbox.share`` afterwards to fill ``_itemRefs``.\n *\n * @param {string} path - path of the folder to delete, with leading slash\n * @param {Object} options\n *\n * @protected\n */\n async 'delete' (path: string, options: { ifMatch?: string } = {}): Promise {\n if (!this.connected) {\n throw new Error(\"not connected (path: \" + path + \")\");\n }\n\n // check if file has changed and return 412\n const savedRev = this._revCache.get(path);\n if (options?.ifMatch && savedRev && (options.ifMatch !== savedRev)) {\n return { statusCode: 412, revision: savedRev };\n }\n\n if (options?.ifMatch) {\n const metadata = await this._getMetadata(path);\n if (options?.ifMatch && metadata && (metadata.rev !== options.ifMatch)) {\n return {\n statusCode: 412,\n revision: metadata.rev\n };\n }\n }\n\n return this._deleteSimple(path);\n }\n\n /**\n * Calls share, if the provided path resides in a public folder.\n * @private\n */\n _shareIfNeeded (path: string): Promise {\n if (path.match(/^\\/public\\/.*[^/]$/) && this._itemRefs[path] === undefined) {\n return this.share(path);\n }\n }\n\n /**\n * Gets a publicly-accessible URL for the path from Dropbox and stores it\n * in ``_itemRefs``.\n *\n * @return {Promise} a promise for the URL\n *\n * @private\n */\n share (path: string): Promise {\n const options = {\n body: {path: getDropboxPath(path)}\n };\n\n return this._request('POST', CREATE_SHARED_URL, options).then((response) => {\n if (response.status !== 200 && response.status !== 409) {\n return Promise.reject(new Error('Invalid response status:' + response.status));\n }\n\n let body;\n\n try {\n body = JSON.parse(response.responseText);\n } catch (e) {\n return Promise.reject(new Error('Invalid response body: ' + response.responseText));\n }\n\n if (response.status === 409) {\n if (compareApiError(body, ['shared_link_already_exists'])) {\n return this._getSharedLink(path);\n }\n\n return Promise.reject(new Error('API error: ' + body.error_summary));\n }\n\n return Promise.resolve(body.url);\n }).then((link) => {\n this._itemRefs[path] = link;\n\n if (hasLocalStorage) {\n localStorage.setItem(SETTINGS_KEY+':shares', JSON.stringify(this._itemRefs));\n }\n\n return Promise.resolve(link);\n }, (error) => {\n error.message = 'Sharing Dropbox file or folder (\"' + path + '\") failed: ' + error.message;\n return Promise.reject(error);\n });\n }\n\n /**\n * Fetches the user's info from dropbox and returns a promise for it.\n *\n * @return {Promise} a promise for user info object (email - the user's email address)\n *\n * @protected\n */\n info (): Promise<{email: string}> {\n return this._request('POST', ACCOUNT_URL, {}).then(function (response) {\n let email;\n\n try {\n const info = JSON.parse(response.responseText);\n email = info?.email;\n } catch (e) {\n return Promise.reject(new Error('Could not query current account info: Invalid API response: ' + response.responseText));\n }\n\n return Promise.resolve({\n email: email\n });\n });\n }\n\n /**\n * Makes a network request.\n *\n * @param {string} method - Request method\n * @param {string} url - Target URL\n * @param {object} options - Request options\n * @param {number} numAttempts - # of times same request repeated\n * @returns {Promise} Resolves with the response of the network request\n *\n * @private\n */\n async _request (method: string, url: string, options, numAttempts = 1): Promise {\n if (this.isForbiddenRequestMethod(method, url)) {\n throw `Don't use ${method} on directories!`;\n }\n\n if (! this.token) { throw new UnauthorizedError(\"No access token\"); }\n\n if (!options.headers) { options.headers = {}; }\n options.headers['Authorization'] = 'Bearer ' + this.token;\n\n if (typeof options.body === 'object' && !isBinaryData(options.body)) {\n options.body = JSON.stringify(options.body);\n options.headers['Content-Type'] = 'application/json; charset=UTF-8';\n }\n\n this.rs._emit('wire-busy', {\n method: method,\n isFolder: isFolder(url)\n });\n\n try {\n const xhr = await requestWithTimeout(method, url, options);\n if (!this.online) {\n this.online = true;\n this.rs._emit('network-online');\n }\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(url),\n success: true\n });\n if (xhr?.status === 401 && this.refreshToken) {\n if (numAttempts >= NUM_RETRIES) {\n console.error(`Abandoned after ${numAttempts} attempts: ${method} ${url}`);\n return xhr;\n } else {\n this.rs._emit('wire-busy', {\n method: method,\n isFolder: isFolder(url)\n });\n await Authorize.refreshAccessToken(this.rs, this, this.refreshToken);\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(url),\n success: true\n });\n // re-runs original request\n return this._request(method, url, options, numAttempts + 1);\n }\n } else if ([503, 429].includes(xhr?.status)) {\n // 503 Service Unavailable; 429 Too Many Requests\n if (this.online) {\n this.online = false;\n this.rs._emit('network-offline');\n }\n\n if (numAttempts >= NUM_RETRIES) {\n console.warn(`Abandoned after ${numAttempts} attempts: ${method} ${url}`);\n return xhr;\n } else {\n await new Promise(resolve => setTimeout(resolve, retryAfterMs(xhr)));\n // re-runs original request\n return this._request(method, url, options, numAttempts+1);\n }\n } else {\n\n return xhr;\n }\n } catch (error) {\n if (this.online) {\n this.online = false;\n this.rs._emit('network-offline');\n }\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(url),\n success: false\n });\n throw error;\n }\n }\n\n /**\n * Fetches the revision of all the files from dropbox API and puts them\n * into ``_revCache``. These values can then be used to determine if\n * something has changed.\n *\n * @private\n */\n fetchDelta (...args: undefined[]): Promise {\n // If fetchDelta was already called, and didn't finish, return the existing\n // promise instead of calling Dropbox API again\n if (this._fetchDeltaPromise) {\n return this._fetchDeltaPromise;\n }\n\n /** This should resolve (with no value) on success, and reject on error. */\n const fetch = async (cursor: string) => {\n let url;\n let requestBody;\n\n if (typeof cursor === 'string') {\n url = CONTINUE_URL;\n requestBody = { cursor };\n } else {\n url = FOLDER_URL;\n requestBody = {\n path: PATH_PREFIX,\n recursive: true,\n include_deleted: true\n };\n }\n\n try {\n const response = await this._request('POST', url, {body: requestBody});\n if (response.status === 401) {\n throw new UnauthorizedError();\n }\n\n if (response.status !== 200 && response.status !== 409) {\n throw new Error('Invalid response status: ' + response.status);\n }\n\n let responseBody;\n\n try {\n responseBody = JSON.parse(response.responseText);\n } catch (e) {\n throw new Error('Invalid response body: ' + response.responseText);\n }\n\n if (response.status === 409) {\n if (compareApiError(responseBody, ['path', 'not_found'])) {\n responseBody = {\n cursor: null,\n entries: [],\n has_more: false\n };\n } else {\n throw new Error('API returned an error: ' + responseBody.error_summary);\n }\n }\n\n if (!cursor) {\n //we are doing a complete fetch, so propagation would introduce unnecessary overhead\n this._revCache.deactivatePropagation();\n }\n\n responseBody.entries.forEach(entry => {\n const path = entry.path_display.slice(PATH_PREFIX.length);\n\n if (entry['.tag'] === 'deleted') {\n // there's no way to know whether the entry was a file or a folder\n this._revCache.delete(path);\n this._revCache.delete(path + '/');\n } else if (entry['.tag'] === 'file') {\n this._revCache.set(path, entry.rev);\n }\n });\n\n this._fetchDeltaCursor = responseBody.cursor;\n if (responseBody.has_more) {\n return fetch(responseBody.cursor);\n } else {\n this._revCache.activatePropagation();\n this._initialFetchDone = true;\n }\n } catch (error) {\n if (error === 'timeout') {\n // Offline is handled elsewhere already, just ignore it here\n return;\n } else {\n throw error;\n }\n }\n };\n\n this._fetchDeltaPromise = fetch(this._fetchDeltaCursor).catch(error => {\n if (typeof(error) === 'object' && 'message' in error) {\n error.message = 'Dropbox: fetchDelta: ' + error.message;\n } else {\n error = `Dropbox: fetchDelta: ${error}`;\n }\n this.rs._emit('error', error);\n this._fetchDeltaPromise = null;\n return Promise.reject(error);\n }).then(() => {\n this._fetchDeltaPromise = null;\n return Promise.resolve(args);\n });\n\n return this._fetchDeltaPromise;\n }\n\n /**\n * Gets metadata for a path (can point to either a file or a folder).\n *\n * @param {string} path - the path to get metadata for\n *\n * @returns {Promise} A promise for the metadata\n *\n * @private\n */\n _getMetadata (path: string): Promise {\n const requestBody = {\n path: getDropboxPath(path)\n };\n\n return this._request('POST', METADATA_URL, { body: requestBody }).then((response) => {\n if (response.status !== 200 && response.status !== 409) {\n return Promise.reject(new Error('Invalid response status:' + response.status));\n }\n\n let responseBody;\n\n try {\n responseBody = JSON.parse(response.responseText);\n } catch (e) {\n return Promise.reject(new Error('Invalid response body: ' + response.responseText));\n }\n\n if (response.status === 409) {\n if (compareApiError(responseBody, ['path', 'not_found'])) {\n return Promise.resolve();\n }\n\n return Promise.reject(new Error('API error: ' + responseBody.error_summary));\n }\n\n return Promise.resolve(responseBody);\n }).then(undefined, (error) => {\n error.message = 'Could not load metadata for file or folder (\"' + path + '\"): ' + error.message;\n return Promise.reject(error);\n });\n }\n\n /**\n * Upload a simple file (the size is no more than 150MB).\n *\n * @param {Object} params\n * @param {string} params.ifMatch - Only update the file if its ETag\n * matches this string\n * @param {string} params.path - path of the file\n * @param {string} params.body - contents of the file to upload\n * @param {string} params.contentType - mime type of the file *\n * @return {Promise} A promise for an object with the following structure:\n * statusCode - HTTP status code\n * revision - revision of the newly-created file, if any\n *\n * @private\n */\n _uploadSimple (params: { body: XMLHttpRequestBodyInit; contentType?: string; path: string; ifMatch?: string; }): Promise {\n const args = {\n path: getDropboxPath(params.path),\n mode: { '.tag': 'overwrite', update: undefined },\n mute: true\n };\n\n if (params.ifMatch) {\n args.mode = { '.tag': 'update', update: params.ifMatch };\n }\n\n return this._request('POST', UPLOAD_URL, {\n body: params.body,\n headers: {\n 'Content-Type': 'application/octet-stream',\n 'Dropbox-API-Arg': httpHeaderSafeJson(args)\n }\n }).then(response => {\n if (response.status !== 200 && response.status !== 409) {\n return Promise.resolve({statusCode: response.status});\n }\n\n let body;\n\n try {\n body = JSON.parse(response.responseText);\n } catch (e) {\n return Promise.reject(new Error('Invalid API result: ' + response.responseText));\n }\n\n if (response.status === 409) {\n if (compareApiError(body, ['path', 'conflict'])) {\n return this._getMetadata(params.path).then(function (metadata) {\n return Promise.resolve({\n statusCode: 412,\n revision: metadata.rev\n });\n });\n }\n this.rs._emit('error', new Error(body.error_summary));\n return Promise.resolve({statusCode: response.status});\n }\n\n this._revCache.set(params.path, body.rev);\n\n return Promise.resolve({ statusCode: response.status, revision: body.rev });\n });\n }\n\n /**\n * Deletes a file or a folder.\n *\n * @param {string} path - the path to delete\n *\n * @returns {Promise} A promise for an object with the following structure:\n * statusCode - HTTP status code\n *\n * @private\n */\n _deleteSimple (path: string): Promise {\n const requestBody = { path: getDropboxPath(path) };\n\n return this._request('POST', DELETE_URL, { body: requestBody }).then((response) => {\n if (response.status !== 200 && response.status !== 409) {\n return Promise.resolve({statusCode: response.status});\n }\n\n let responseBody;\n\n try {\n responseBody = JSON.parse(response.responseText);\n } catch (e) {\n return Promise.reject(new Error('Invalid response body: ' + response.responseText));\n }\n\n if (response.status === 409) {\n if (compareApiError(responseBody, ['path_lookup', 'not_found'])) {\n return Promise.resolve({statusCode: 404});\n }\n this.rs._emit('error', new Error(responseBody.error_summary));\n }\n\n return Promise.resolve({statusCode: response.status});\n }).then(result => {\n if (result.statusCode === 200 || result.statusCode === 404) {\n this._revCache.delete(path);\n delete this._itemRefs[path];\n }\n return Promise.resolve(result);\n }, (error) => {\n error.message = 'Could not delete Dropbox file or folder (\"' + path + '\"): ' + error.message;\n return Promise.reject(error);\n });\n }\n\n /**\n * Requests the link for an already-shared file or folder.\n *\n * @param {string} path - path to the file or folder\n *\n * @returns {Promise} A promise for the shared link\n *\n * @private\n */\n async _getSharedLink (path: string): Promise {\n const options = {\n body: {\n path: getDropboxPath(path),\n direct_only: true\n }\n };\n\n return this._request('POST', LIST_SHARED_URL, options).then((response) => {\n if (response.status !== 200 && response.status !== 409) {\n return Promise.reject(new Error('Invalid response status: ' + response.status));\n }\n\n let body;\n\n try {\n body = JSON.parse(response.responseText);\n } catch (e) {\n return Promise.reject(new Error('Invalid response body: ' + response.responseText));\n }\n\n if (response.status === 409) {\n return Promise.reject(new Error('API error: ' + body?.error_summary || response.responseText));\n }\n\n if (!body.links.length) {\n return Promise.reject(new Error('No links returned'));\n }\n\n return Promise.resolve(body.links[0].url);\n }, error => {\n error.message = 'Could not get link to a shared file or folder (\"' + path + '\"): ' + error.message;\n return Promise.reject(error);\n });\n }\n\n /**\n * Initialize the Dropbox backend.\n *\n * @param {object} rs - RemoteStorage instance\n *\n * @protected\n */\n static _rs_init (rs: RemoteStorage): void {\n hasLocalStorage = localStorageAvailable();\n if ( rs.apiKeys.dropbox ) {\n rs.dropbox = new Dropbox(rs);\n }\n if (rs.backend === 'dropbox') {\n hookIt(rs);\n }\n }\n\n /**\n * Inform about the availability of the Dropbox backend.\n *\n * @returns {Boolean}\n *\n * @protected\n */\n static _rs_supported (): boolean {\n return true;\n }\n\n /**\n * Remove Dropbox as a backend.\n *\n * @param {object} rs - RemoteStorage instance\n *\n * @protected\n */\n static _rs_cleanup (rs: RemoteStorage): void {\n unHookIt(rs);\n if (hasLocalStorage){\n localStorage.removeItem(SETTINGS_KEY);\n }\n rs.setBackend(undefined);\n }\n}\n\n/**\n * Hooking the sync\n *\n * TODO: document\n */\nfunction hookSync(rs, ...args): void {\n if (rs._dropboxOrigSync) { return; } // already hooked\n rs._dropboxOrigSync = rs.sync.sync.bind(rs.sync);\n rs.sync.sync = function () {\n return this.dropbox.fetchDelta(rs, ...args).\n then(rs._dropboxOrigSync, function (err) {\n rs._emit('error', new SyncError(err));\n rs._emit('sync-done');\n });\n }.bind(rs);\n}\n\n/**\n * Unhooking the sync\n *\n * TODO: document\n */\nfunction unHookSync(rs): void {\n if (! rs._dropboxOrigSync) { return; } // not hooked\n rs.sync.sync = rs._dropboxOrigSync;\n delete rs._dropboxOrigSync;\n}\n\n/**\n * Hook RemoteStorage.syncCycle as it's the first function called\n * after RemoteStorage.sync is initialized, so we can then hook\n * the sync function\n * @param {object} rs RemoteStorage instance\n * @param {array} args remaining arguments\n */\nfunction hookSyncCycle(rs, ...args): void {\n if (rs._dropboxOrigSyncCycle) { return; } // already hooked\n rs._dropboxOrigSyncCycle = rs.syncCycle;\n rs.syncCycle = () => {\n if (rs.sync) {\n hookSync(rs);\n rs._dropboxOrigSyncCycle(rs, ...args);\n unHookSyncCycle(rs);\n } else {\n throw new Error('expected sync to be initialized by now');\n }\n };\n}\n\n/**\n * Restore RemoteStorage's syncCycle original implementation\n * @param {object} rs RemoteStorage instance\n */\nfunction unHookSyncCycle(rs): void {\n if (!rs._dropboxOrigSyncCycle) { return; } // not hooked\n rs.syncCycle = rs._dropboxOrigSyncCycle;\n delete rs._dropboxOrigSyncCycle;\n}\n\n/**\n * Overwrite BaseClient's getItemURL with our own implementation\n *\n * TODO: getItemURL still needs to be implemented\n *\n * @param {object} rs - RemoteStorage instance\n *\n * @private\n */\nfunction hookGetItemURL (rs): void {\n if (rs._origBaseClientGetItemURL) { return; }\n rs._origBaseClientGetItemURL = BaseClient.prototype.getItemURL;\n BaseClient.prototype.getItemURL = function (/*path*/) {\n throw new Error('getItemURL is not implemented for Dropbox yet');\n };\n}\n\n/**\n * Restore BaseClient's getItemURL original implementation\n *\n * @param {object} rs - RemoteStorage instance\n *\n * @private\n */\nfunction unHookGetItemURL(rs): void {\n if (! rs._origBaseClientGetItemURL) { return; }\n BaseClient.prototype.getItemURL = rs._origBaseClientGetItemURL;\n delete rs._origBaseClientGetItemURL;\n}\n\n/**\n * TODO: document\n */\nfunction hookRemote(rs): void {\n if (rs._origRemote) { return; }\n rs._origRemote = rs.remote;\n rs.remote = rs.dropbox;\n}\n\n/**\n * TODO: document\n */\nfunction unHookRemote(rs): void {\n if (rs._origRemote) {\n rs.remote = rs._origRemote;\n delete rs._origRemote;\n }\n}\n\n/**\n * TODO: document\n */\nfunction hookIt(rs: RemoteStorage): void {\n hookRemote(rs);\n if (rs.sync) {\n hookSync(rs);\n } else {\n // when sync is not available yet, we hook the syncCycle function which is called\n // right after sync is initialized\n hookSyncCycle(rs);\n }\n hookGetItemURL(rs);\n}\n\n/**\n * TODO: document\n */\nfunction unHookIt(rs: RemoteStorage): void {\n unHookRemote(rs);\n unHookSync(rs);\n unHookGetItemURL(rs);\n unHookSyncCycle(rs);\n}\n\ninterface Dropbox extends EventHandling {}\napplyMixins(Dropbox, [EventHandling]);\n\nexport = Dropbox;\n","import EventHandling from './eventhandling';\nimport { applyMixins } from './util';\n\nclass Env {\n hiddenProperty: \"hidden\" | \"mozHidden\" | \"msHidden\" | \"webkitHidden\";\n visibilityChangeEvent: \"visibilitychange\" | \"mozvisibilitychange\" | \"msvisibilitychange\" | \"webkitvisibilitychange\";\n mode: \"browser\" | \"node\";\n\n constructor() {\n this.addEvents([\"background\", \"foreground\"]);\n\n this.mode = typeof(window) !== 'undefined' ? 'browser' : 'node';\n\n if (this.mode === 'browser') {\n this.setBrowserPrefixedNames();\n document.addEventListener(this.visibilityChangeEvent, this.setVisibility.bind(this), false);\n this.setVisibility();\n }\n }\n\n setBrowserPrefixedNames (): void {\n if (this.mode !== 'browser') { return; }\n\n if (typeof document.hidden !== \"undefined\") {\n this.hiddenProperty = \"hidden\";\n this.visibilityChangeEvent = \"visibilitychange\";\n } else if (typeof document[\"mozHidden\"] !== \"undefined\") {\n this.hiddenProperty = \"mozHidden\";\n this.visibilityChangeEvent = \"mozvisibilitychange\";\n } else if (typeof document[\"msHidden\"] !== \"undefined\") {\n this.hiddenProperty = \"msHidden\";\n this.visibilityChangeEvent = \"msvisibilitychange\";\n } else if (typeof document[\"webkitHidden\"] !== \"undefined\") {\n this.hiddenProperty = \"webkitHidden\";\n this.visibilityChangeEvent = \"webkitvisibilitychange\";\n }\n }\n\n setVisibility (): void {\n if (document[this.hiddenProperty]) {\n this.goBackground();\n } else {\n this.goForeground();\n }\n }\n\n isBrowser (): boolean {\n return this.mode === \"browser\";\n }\n\n isNode (): boolean {\n return this.mode === \"node\";\n }\n\n goBackground (): void {\n this._emit(\"background\");\n }\n\n goForeground (): void {\n this._emit(\"foreground\");\n }\n\n static _rs_init (/* remoteStorage */): void {\n return;\n }\n\n static _rs_cleanup (/* remoteStorage */): void {\n return;\n }\n}\n\ninterface Env extends EventHandling {}\napplyMixins(Env, [EventHandling]);\n\nexport = Env;\n","import log from './log';\n\n/**\n */\nexport type EventHandler = (event?: unknown) => void;\n\nexport class EventHandling {\n /**\n * @internal\n */\n _handlers: { [key: string]: EventHandler[] };\n\n /**\n * Register event names\n *\n * TODO see if necessary, or can be done on the fly in addEventListener\n *\n * @internal\n */\n addEvents(additionalEvents: string[]): void {\n additionalEvents.forEach(evName => this._addEvent(evName));\n }\n\n /**\n * Install an event handler for the given event name\n *\n * Usually called via [`on()`](#on)\n */\n addEventListener (eventName: string, handler: EventHandler): void {\n // Check type for public consumption of API\n if (typeof (eventName) !== 'string') {\n throw new Error('Argument eventName should be a string');\n }\n if (typeof (handler) !== 'function') {\n throw new Error('Argument handler should be a function');\n }\n log('[EventHandling] Adding event listener', eventName);\n this._validateEvent(eventName);\n this._handlers[eventName].push(handler);\n }\n\n /**\n * Register an event handler for the given event name\n *\n * Alias for {@link addEventListener}\n *\n * @param eventName - Name of the event\n * @param handler - Function to handle the event\n *\n * @example\n * remoteStorage.on('connected', function() {\n * console.log('storage account has been connected');\n * });\n */\n on (eventName: string, handler: EventHandler): void {\n return this.addEventListener(eventName, handler);\n }\n\n /**\n * Remove a previously installed event handler\n */\n removeEventListener (eventName: string, handler: EventHandler): void {\n this._validateEvent(eventName);\n const hl = this._handlers[eventName].length;\n for (let i = 0; i < hl; i++) {\n if (this._handlers[eventName][i] === handler) {\n this._handlers[eventName].splice(i, 1);\n return;\n }\n }\n }\n\n /**\n * @internal\n */\n _emit (eventName: string, ...args: unknown[]): void {\n this._validateEvent(eventName);\n this._handlers[eventName].slice().forEach((handler) => {\n handler.apply(this, args);\n });\n }\n\n /**\n * @internal\n */\n _validateEvent (eventName: string): void {\n if (!(eventName in this._handlers)) {\n throw new Error(\"Unknown event: \" + eventName);\n }\n }\n\n /**\n * @internal\n */\n _delegateEvent (eventName: string, target): void {\n target.on(eventName, (event) => {\n this._emit(eventName, event);\n });\n }\n\n /**\n * @internal\n */\n _addEvent (eventName: string): void {\n if (typeof this._handlers === 'undefined') {\n this._handlers = {};\n }\n this._handlers[eventName] = [];\n }\n}\n\nexport default EventHandling;\n","'use strict';\n\nimport config from './config';\nimport Env from './env';\nimport log from './log';\nimport { extend, logError } from './util';\nimport SGPD from './syncedgetputdelete';\n\nimport Access from './access';\nimport Authorize from './authorize';\nimport Discover from './discover';\nimport BaseClient from './baseclient';\nimport GoogleDrive from './googledrive';\nimport Dropbox from './dropbox';\nimport Solid from './solid';\nimport WireClient from './wireclient';\nimport Sync from './sync';\n\n// Caching\nimport Caching from './caching';\nimport IndexedDB from './indexeddb';\nimport LocalStorage from './localstorage';\nimport InMemoryStorage from './inmemorystorage';\n\nconst Features = {\n features: [],\n featuresDone: 0,\n readyFired: false,\n\n loadFeatures (): void {\n this.features = [];\n this.featuresDone = 0;\n this.readyFired = false;\n\n this.featureModules = {\n 'WireClient': WireClient,\n 'Dropbox': Dropbox,\n 'GoogleDrive': GoogleDrive,\n 'Solid': Solid,\n 'Access': Access,\n 'Discover': Discover,\n 'Authorize': Authorize,\n 'BaseClient': BaseClient,\n 'Env': Env\n };\n\n // enable caching related modules if needed\n if (config.cache) {\n // TODO replace util.extend with modern JS {...object, ...object}\n extend(this.featureModules, {\n 'Caching': Caching,\n 'IndexedDB': IndexedDB,\n 'LocalStorage': LocalStorage,\n 'InMemoryStorage': InMemoryStorage,\n 'Sync': Sync\n });\n }\n\n // disable features set in the config object passed to the RemoteStorage\n // constructor\n // For example: ['IndexedDB']\n config.disableFeatures.forEach(feature => {\n if (this.featureModules[feature]) {\n // this.featureModules[feature] = undefined\n delete this.featureModules[feature];\n }\n });\n\n this._allLoaded = false;\n\n for (const featureName in this.featureModules) {\n // FIXME: this has to push the promised return value into an\n // array of promises and use Promise.all to emit `ready`\n // instead of increment a counter of loaded features. -les\n this.loadFeature(featureName);\n }\n },\n\n /**\n * Method: hasFeature\n *\n * Checks whether a feature is enabled or not within remoteStorage.\n * Returns a boolean.\n *\n * Parameters:\n * name - Capitalized name of the feature. e.g. Authorize, or IndexedDB\n *\n * Example:\n * (start code)\n * if (remoteStorage.hasFeature('LocalStorage')) {\n * console.log('LocalStorage is enabled!');\n * }\n * (end code)\n *\n */\n hasFeature (feature) {\n for (let i = this.features.length - 1; i >= 0; i--) {\n if (this.features[i].name === feature) {\n return this.features[i].supported;\n }\n }\n return false;\n },\n\n loadFeature (featureName) {\n const feature = this.featureModules[featureName];\n const supported = !feature._rs_supported || feature._rs_supported();\n\n log(`[RemoteStorage] [FEATURE ${featureName}] initializing ...`);\n\n if (typeof supported === 'object') {\n supported.then( () => {\n this.featureSupported(featureName, true);\n this.initFeature(featureName);\n }, () => {\n this.featureSupported(featureName, false);\n });\n } else if (typeof supported === 'boolean') {\n this.featureSupported(featureName, supported);\n if (supported) {\n this.initFeature(featureName);\n }\n } else {\n this.featureSupported(featureName, false);\n }\n },\n\n initFeature (featureName) {\n const feature = this.featureModules[featureName];\n let initResult;\n try {\n initResult = feature._rs_init(this);\n } catch(e) {\n this.featureFailed(featureName, e);\n return;\n }\n\n if (typeof(initResult) === 'object' && typeof(initResult.then) === 'function') {\n initResult.then(\n () => { this.featureInitialized(featureName); },\n (err) => { this.featureFailed(featureName, err); }\n );\n } else {\n this.featureInitialized(featureName);\n }\n },\n\n featureFailed (featureName, err) {\n log(`[RemoteStorage] [FEATURE ${featureName}] initialization failed (${err})`);\n this.featureDone();\n },\n\n featureSupported (featureName, success) {\n log(`[RemoteStorage] [FEATURE ${featureName}]${success ? '' : 'not '} supported`);\n if (!success) {\n this.featureDone();\n }\n },\n\n featureInitialized (featureName) {\n log(`[RemoteStorage] [FEATURE ${featureName}] initialized`);\n this.features.push({\n name : featureName,\n init : this.featureModules[featureName]._rs_init,\n supported : true,\n cleanup : this.featureModules[featureName]._rs_cleanup\n });\n this.featureDone();\n },\n\n featureDone () {\n this.featuresDone++;\n if (this.featuresDone === Object.keys(this.featureModules).length) {\n setTimeout(this.featuresLoaded.bind(this), 0);\n }\n },\n\n _setCachingModule () {\n const cachingModules = ['IndexedDB', 'LocalStorage', 'InMemoryStorage'];\n\n cachingModules.some( cachingLayer => {\n if (this.features.some(feature => feature.name === cachingLayer)) {\n this.features.local = this.featureModules[cachingLayer];\n return true;\n }\n });\n },\n\n _fireReady() {\n try {\n if (!this.readyFired) {\n this._emit('ready');\n this.readyFired = true;\n }\n } catch(e) {\n console.error(\"'ready' failed: \", e, e.stack);\n this._emit('error', e);\n }\n },\n\n featuresLoaded () {\n log(`[RemoteStorage] All features loaded`);\n\n this._setCachingModule();\n // eslint-disable-next-line new-cap\n this.local = config.cache && this.features.local && new this.features.local();\n\n // this.remote set by WireClient._rs_init as lazy property on\n // RS.prototype\n\n if (this.local && this.remote) {\n this._setGPD(SGPD, this);\n this._bindChange(this.local);\n } else if (this.remote) {\n this._setGPD(this.remote, this.remote);\n }\n if (this.remote) {\n this.remote.on('connected', () => {\n this._fireReady();\n this._emit('connected');\n });\n this.remote.on('not-connected', () => {\n this._fireReady();\n this._emit('not-connected');\n });\n if (this.remote.connected) {\n this._fireReady();\n this._emit('connected');\n }\n\n if (!this.hasFeature('Authorize')) {\n this.remote.stopWaitingForToken();\n }\n }\n\n this._collectCleanupFunctions();\n\n try {\n this._allLoaded = true;\n this._emit('features-loaded');\n } catch(exc) {\n logError(exc);\n this._emit('error', exc);\n }\n this._processPending();\n },\n\n _collectCleanupFunctions (): void {\n this._cleanups = [];\n for (let i=0; i < this.features.length; i++) {\n const cleanup = this.features[i].cleanup;\n if (typeof(cleanup) === 'function') {\n this._cleanups.push(cleanup);\n }\n }\n }\n};\n\nexport = Features;\n","import BaseClient from './baseclient';\nimport EventHandling from './eventhandling';\nimport {\n applyMixins,\n isFolder,\n cleanPath,\n shouldBeTreatedAsBinary,\n getJSONFromLocalStorage,\n getTextFromArrayBuffer,\n localStorageAvailable\n} from './util';\nimport {requestWithTimeout, RequestOptions} from \"./requests\";\nimport {Remote, RemoteBase, RemoteResponse, RemoteSettings} from \"./remote\";\n\nconst BASE_URL = 'https://www.googleapis.com';\nconst AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';\nconst AUTH_SCOPE = 'https://www.googleapis.com/auth/drive';\nconst SETTINGS_KEY = 'remotestorage:googledrive';\nconst PATH_PREFIX = '/remotestorage';\n\nconst GD_DIR_MIME_TYPE = 'application/vnd.google-apps.folder';\nconst RS_DIR_MIME_TYPE = 'application/json; charset=UTF-8';\n\nlet hasLocalStorage;\n\n/**\n * Produce a title from a filename for metadata.\n *\n * @param {string} filename\n * @returns {string} title\n *\n * @private\n */\nfunction metaTitleFromFileName (filename: string): string {\n if (filename.substr(-1) === '/') {\n filename = filename.substr(0, filename.length - 1);\n }\n\n return decodeURIComponent(filename);\n}\n\n/**\n * Get the parent directory for the given path.\n *\n * @param {string} path\n * @returns {string} parent directory\n *\n * @private\n */\nfunction parentPath (path: string): string {\n return path.replace(/[^\\/]+\\/?$/, '');\n}\n\n/**\n * Get only the filename from a full path.\n *\n * @param {string} path\n * @returns {string} filename\n *\n * @private\n */\nfunction baseName (path: string): string {\n const parts = path.split('/');\n if (path.substr(-1) === '/') {\n return parts[parts.length-2]+'/';\n } else {\n return parts[parts.length-1];\n }\n}\n\n/**\n * Prepend the path with the remoteStorage base directory.\n *\n * @param {string} path - Path\n * @returns {string} Actual path on Google Drive\n *\n * @private\n */\nfunction googleDrivePath (path: string): string {\n return cleanPath(`${PATH_PREFIX}/${path}`);\n}\n\n/**\n * Internal cache object for storing Google file IDs.\n *\n * @param {number} maxAge - Maximum age (in seconds) the content should be cached for\n */\nclass FileIdCache {\n maxAge: number;\n _items = {};\n\n constructor(maxAge?: number) {\n this.maxAge = maxAge;\n this._items = {};\n }\n\n get (key): number | undefined {\n const item = this._items[key];\n const now = new Date().getTime();\n return (item && item.t >= (now - this.maxAge)) ? item.v : undefined;\n }\n\n set (key, value): void {\n this._items[key] = {\n v: value,\n t: new Date().getTime()\n };\n }\n}\n\n/**\n * Overwrite BaseClient's getItemURL with our own implementation\n *\n * TODO: Still needs to be implemented. At the moment it just throws\n * and error saying that it's not implemented yet.\n *\n * @param {object} rs - RemoteStorage instance\n *\n * @private\n */\nfunction hookGetItemURL (rs): void {\n if (rs._origBaseClientGetItemURL) { return; }\n rs._origBaseClientGetItemURL = BaseClient.prototype.getItemURL;\n BaseClient.prototype.getItemURL = function (/* path */): never {\n throw new Error('getItemURL is not implemented for Google Drive yet');\n };\n}\n\n/**\n * Restore BaseClient's getItemURL original implementation\n *\n * @param {object} rs - RemoteStorage instance\n *\n * @private\n */\nfunction unHookGetItemURL (rs): void {\n if (!rs._origBaseClientGetItemURL) { return; }\n BaseClient.prototype.getItemURL = rs._origBaseClientGetItemURL;\n delete rs._origBaseClientGetItemURL;\n}\n\n/**\n * @class GoogleDrive\n *\n * To use this backend, you need to specify the app's client ID like so:\n *\n * @example\n * remoteStorage.setApiKeys({\n * googledrive: 'your-client-id'\n * });\n *\n * A client ID can be obtained by registering your app in the Google\n * Developers Console: https://console.developers.google.com/flows/enableapi?apiid=drive\n *\n * Docs: https://developers.google.com/drive/v3/web/quickstart/js\n**/\nclass GoogleDrive extends RemoteBase implements Remote {\n clientId: string;\n token: string;\n\n _fileIdCache: FileIdCache;\n\n constructor(remoteStorage, clientId) {\n super(remoteStorage);\n this.online = true;\n this.storageApi = 'draft-dejong-remotestorage-19';\n this.addEvents(['connected', 'not-connected']);\n\n this.clientId = clientId;\n\n this._fileIdCache = new FileIdCache(60 * 5); // IDs expire after 5 minutes (is this a good idea?)\n\n hasLocalStorage = localStorageAvailable();\n\n if (hasLocalStorage){\n const settings = getJSONFromLocalStorage(SETTINGS_KEY);\n if (settings) {\n this.configure(settings);\n }\n }\n }\n\n /**\n * Configure the Google Drive backend.\n *\n * Fetches the user info from Google when no ``userAddress`` is given.\n *\n * @param {Object} settings\n * @param {string} [settings.userAddress] - The user's email address\n * @param {string} [settings.token] - Authorization token\n *\n * @protected\n */\n configure (settings: RemoteSettings) { // Settings parameter compatible with WireClient\n // We only update this.userAddress if settings.userAddress is set to a string or to null\n if (typeof settings.userAddress !== 'undefined') { this.userAddress = settings.userAddress; }\n // Same for this.token. If only one of these two is set, we leave the other one at its existing value\n if (typeof settings.token !== 'undefined') { this.token = settings.token as string; }\n\n const writeSettingsToCache = function() {\n if (hasLocalStorage) {\n localStorage.setItem(SETTINGS_KEY, JSON.stringify({\n userAddress: this.userAddress,\n token: this.token\n }));\n }\n };\n\n const handleError = function() {\n this.connected = false;\n delete this.token;\n if (hasLocalStorage) {\n localStorage.removeItem(SETTINGS_KEY);\n }\n };\n\n if (this.token) {\n this.connected = true;\n\n if (this.userAddress) {\n this._emit('connected');\n writeSettingsToCache.apply(this);\n } else {\n this.info().then((info) => {\n this.userAddress = info.user.emailAddress;\n this._emit('connected');\n writeSettingsToCache.apply(this);\n }).catch(() => {\n handleError.apply(this);\n this.rs._emit('error', new Error('Could not fetch user info.'));\n });\n }\n } else {\n handleError.apply(this);\n }\n }\n\n /**\n * Initiate the authorization flow's OAuth dance.\n */\n connect (): void {\n this.rs.setBackend('googledrive');\n this.rs.authorize({ authURL: AUTH_URL, scope: AUTH_SCOPE, clientId: this.clientId });\n }\n\n /**\n * Request a resource (file or directory).\n *\n * @param {string} path - Path of the resource\n * @param {Object} options - Request options\n * @returns {Promise} Resolves with an object containing the status code,\n * body, content-type and revision\n *\n * @protected\n */\n get (path: string, options: { ifNoneMatch?: string } = {}): Promise {\n if (isFolder(path)) {\n return this._getFolder(googleDrivePath(path));\n } else {\n return this._getFile(googleDrivePath(path), options);\n }\n }\n\n /**\n * Create or update a file.\n *\n * @param {string} path - File path\n * @param body - File content\n * @param {string} contentType - File content-type\n * @param {Object} options\n * @param {string} options.ifNoneMatch - Only create of update the file if the\n * current ETag doesn't match this string\n * @returns {Promise} Resolves with an object containing the status code,\n * content-type and revision\n *\n * @protected\n */\n put (path: string, body: XMLHttpRequestBodyInit, contentType: string, options: { ifMatch?: string; ifNoneMatch?: string } = {}): Promise {\n const fullPath = googleDrivePath(path);\n\n function putDone(response) {\n if (response.status >= 200 && response.status < 300) {\n const meta = JSON.parse(response.responseText);\n const etagWithoutQuotes: string = this.stripQuotes(meta.etag);\n return Promise.resolve({statusCode: 200, contentType: meta.mimeType, revision: etagWithoutQuotes});\n } else if (response.status === 412) {\n return Promise.resolve({statusCode: 412, revision: 'conflict'});\n } else {\n return Promise.reject(\"PUT failed with status \" + response.status + \" (\" + response.responseText + \")\");\n }\n }\n\n return this._getFileId(fullPath).then((id) => {\n if (id) {\n if (options && (options.ifNoneMatch === '*')) {\n return putDone({ status: 412 });\n }\n return this._updateFile(id, fullPath, body, contentType, options).then(putDone);\n } else {\n return this._createFile(fullPath, body, contentType).then(putDone);\n }\n });\n }\n\n /**\n * Delete a file.\n *\n * @param {string} path - File path\n * @param {Object} options\n * @param {string} options.ifMatch - only delete the file if it's ETag\n * matches this string\n * @returns {Promise} Resolves with an object containing the status code\n *\n * @protected\n */\n delete (path: string, options: { ifMatch?: string } = {}): Promise {\n const fullPath = googleDrivePath(path);\n\n return this._getFileId(fullPath).then((id) => {\n if (!id) {\n // File doesn't exist. Ignore.\n return Promise.resolve({statusCode: 200});\n }\n\n return this._getMeta(id).then((meta) => {\n let etagWithoutQuotes;\n if ((typeof meta === 'object') && (typeof meta.etag === 'string')) {\n etagWithoutQuotes = this.stripQuotes(meta.etag);\n }\n if (options && options.ifMatch && (options.ifMatch !== etagWithoutQuotes)) {\n return {statusCode: 412, revision: etagWithoutQuotes};\n }\n\n return this._request('DELETE', BASE_URL + '/drive/v2/files/' + id, {}).then((response) => {\n if (response.status === 200 || response.status === 204) {\n return {statusCode: 200};\n } else {\n return Promise.reject(\"Delete failed: \" + response.status + \" (\" + response.responseText + \")\");\n }\n });\n });\n });\n }\n\n /**\n * Fetch the user's info from Google.\n *\n * @returns {Promise} resolves with the user's info.\n *\n * @protected\n */\n info () {\n const url = BASE_URL + '/drive/v2/about?fields=user';\n // requesting user info(mainly for userAdress)\n return this._request('GET', url, {}).then(function (resp){\n try {\n const info = JSON.parse(resp.responseText);\n return Promise.resolve(info);\n } catch (e) {\n return Promise.reject(e);\n }\n });\n }\n\n /**\n * Update an existing file.\n *\n * @param {string} id - File ID\n * @param {string} path - File path\n * @param body - File content\n * @param {string} contentType - File content-type\n * @param {Object} options\n * @param {string} options.ifMatch - Only update the file if its ETag\n * matches this string\n * @returns {Promise} Resolves with the response of the network request\n *\n * @private\n */\n _updateFile (id, path, body, contentType, options) {\n const metadata = {\n mimeType: contentType\n };\n const headers = {\n 'Content-Type': 'application/json; charset=UTF-8'\n };\n\n if (options && options.ifMatch) {\n headers['If-Match'] = this.addQuotes(options.ifMatch);\n }\n\n return this._request('PUT', BASE_URL + '/upload/drive/v2/files/' + id + '?uploadType=resumable', {\n body: JSON.stringify(metadata),\n headers: headers\n }).then((response) => {\n if (response.status === 412) {\n return (response);\n } else {\n return this._request('PUT', response.getResponseHeader('Location'), {\n body: contentType.match(/^application\\/json/) ? JSON.stringify(body) : body\n });\n }\n });\n }\n\n /**\n * Create a new file.\n *\n * @param {string} path - File path\n * @param body - File content\n * @param {string} contentType - File content-type\n * @returns {Promise} Resolves with the response of the network request\n *\n * @private\n */\n _createFile (path, body, contentType) {\n return this._getParentId(path).then((parentId) => {\n const fileName = baseName(path);\n const metadata = {\n title: metaTitleFromFileName(fileName),\n mimeType: contentType,\n parents: [{\n kind: \"drive#fileLink\",\n id: parentId\n }]\n };\n return this._request('POST', BASE_URL + '/upload/drive/v2/files?uploadType=resumable', {\n body: JSON.stringify(metadata),\n headers: {\n 'Content-Type': 'application/json; charset=UTF-8'\n }\n }).then((response) => {\n return this._request('POST', response.getResponseHeader('Location'), {\n body: contentType.match(/^application\\/json/) ? JSON.stringify(body) : body\n });\n });\n });\n }\n\n /**\n * Request a file.\n *\n * @param {string} path - File path\n * @param {Object} options\n * @param {string} [options.ifNoneMath] - Only return the file if its ETag\n * doesn't match the given string\n * @returns {Promise} Resolves with an object containing the status code,\n * body, content-type and revision\n *\n * @private\n */\n _getFile (path, options) {\n return this._getFileId(path).then((id) => {\n return this._getMeta(id).then((meta) => {\n let etagWithoutQuotes;\n if (typeof(meta) === 'object' && typeof(meta.etag) === 'string') {\n etagWithoutQuotes = this.stripQuotes(meta.etag);\n }\n\n if (options && options.ifNoneMatch && (etagWithoutQuotes === options.ifNoneMatch)) {\n return Promise.resolve({statusCode: 304});\n }\n\n if (!meta.downloadUrl) {\n if (meta.exportLinks && meta.exportLinks['text/html']) {\n // Documents that were generated inside GoogleDocs have no\n // downloadUrl, but you can export them to text/html instead:\n meta.mimeType += ';export=text/html';\n meta.downloadUrl = meta.exportLinks['text/html'];\n } else {\n // empty file\n return Promise.resolve({statusCode: 200, body: '', contentType: meta.mimeType, revision: etagWithoutQuotes});\n }\n }\n\n const params: RequestOptions = {\n responseType: 'arraybuffer'\n };\n return this._request('GET', meta.downloadUrl, params).then((response) => {\n //first encode the response as text, and later check if\n //text appears to actually be binary data\n return getTextFromArrayBuffer(response.response, 'UTF-8').then(function (responseText) {\n let body = responseText;\n if (meta.mimeType.match(/^application\\/json/)) {\n try {\n body = JSON.parse(body as string);\n } catch(e) {\n // body couldn't be parsed as JSON, so we'll just return it as is\n }\n } else if (shouldBeTreatedAsBinary(responseText, meta.mimeType)) {\n //return unprocessed response\n body = response.response;\n }\n\n return {\n statusCode: 200,\n body: body,\n contentType: meta.mimeType,\n revision: etagWithoutQuotes\n };\n });\n });\n });\n });\n }\n\n /**\n * Request a directory.\n *\n * @param {string} path - Directory path\n * @returns {Promise} Resolves with an object containing the status code,\n * body and content-type\n *\n * @private\n */\n _getFolder (path: string) {\n return this._getFileId(path).then((id) => {\n let data, etagWithoutQuotes, itemsMap;\n if (! id) {\n return Promise.resolve({statusCode: 404});\n }\n\n const query = '\\'' + id + '\\' in parents';\n const fields = 'items(downloadUrl,etag,fileSize,id,mimeType,title,labels)';\n return this._request('GET', BASE_URL + '/drive/v2/files?'\n + 'q=' + encodeURIComponent(query)\n + '&fields=' + encodeURIComponent(fields)\n + '&maxResults=1000'\n + '&trashed=false',\n {})\n .then((response) => {\n if (response.status !== 200) {\n return Promise.reject('request failed or something: ' + response.status);\n }\n\n try {\n data = JSON.parse(response.responseText);\n } catch(e) {\n return Promise.reject('non-JSON response from GoogleDrive');\n }\n\n itemsMap = {};\n for (const item of data.items) {\n if (item.labels?.trashed) { continue; } // ignore deleted files\n\n etagWithoutQuotes = this.stripQuotes(item.etag);\n if (item.mimeType === GD_DIR_MIME_TYPE) {\n this._fileIdCache.set(path + cleanPath(item.title) + '/', item.id);\n itemsMap[item.title + '/'] = {\n ETag: etagWithoutQuotes\n };\n } else {\n this._fileIdCache.set(path + cleanPath(item.title), item.id);\n itemsMap[item.title] = {\n ETag: etagWithoutQuotes,\n 'Content-Type': item.mimeType,\n 'Content-Length': item.fileSize\n };\n }\n }\n\n // FIXME: add revision of folder!\n return Promise.resolve({statusCode: 200, body: itemsMap, contentType: RS_DIR_MIME_TYPE, revision: undefined});\n });\n });\n }\n\n /**\n * Get the ID of a parent path.\n *\n * Creates the directory if it doesn't exist yet.\n *\n * @param {string} path - Full path of a directory or file\n * @returns {Promise} Resolves with ID of the parent directory.\n *\n * @private\n */\n _getParentId (path) {\n const foldername = parentPath(path);\n\n return this._getFileId(foldername).then((parentId) => {\n if (parentId) {\n return Promise.resolve(parentId);\n } else {\n return this._createFolder(foldername);\n }\n });\n }\n\n /**\n * Create a directory.\n *\n * Creates all parent directories as well if any of them didn't exist yet.\n *\n * @param {string} path - Directory path\n * @returns {Promise} Resolves with the ID of the new directory\n *\n * @private\n */\n _createFolder (path) {\n return this._getParentId(path).then((parentId) => {\n return this._request('POST', BASE_URL + '/drive/v2/files', {\n body: JSON.stringify({\n title: metaTitleFromFileName(baseName(path)),\n mimeType: GD_DIR_MIME_TYPE,\n parents: [{\n id: parentId\n }]\n }),\n headers: {\n 'Content-Type': 'application/json; charset=UTF-8'\n }\n }).then((response) => {\n const meta = JSON.parse(response.responseText);\n return Promise.resolve(meta.id);\n });\n });\n }\n\n /**\n * Get the ID of a file.\n *\n * @param {string} path - File path\n * @returns {Promise} Resolves with the ID\n *\n * @private\n */\n _getFileId (path) {\n let id;\n\n if (path === '/') {\n // \"root\" is a special alias for the fileId of the root folder\n return Promise.resolve('root');\n } else if ((id = this._fileIdCache.get(path))) {\n // id is cached.\n return Promise.resolve(id);\n }\n // id is not cached (or file doesn't exist).\n // load parent folder listing to propagate / update id cache.\n return this._getFolder(parentPath(path)).then(() => {\n id = this._fileIdCache.get(path);\n if (!id) {\n if (path.substr(-1) === '/') {\n return this._createFolder(path).then(() => {\n return this._getFileId(path);\n });\n } else {\n return Promise.resolve();\n }\n }\n return Promise.resolve(id);\n });\n }\n\n /**\n * Get the metadata for a given file ID.\n *\n * @param {string} id - File ID\n * @returns {Promise} Resolves with an object containing the metadata\n *\n * @private\n */\n _getMeta (id) {\n return this._request('GET', BASE_URL + '/drive/v2/files/' + id, {}).then(function (response) {\n if (response.status === 200) {\n return Promise.resolve(JSON.parse(response.responseText));\n } else {\n return Promise.reject(\"request (getting metadata for \" + id + \") failed with status: \" + response.status);\n }\n });\n }\n\n /**\n * Make a network request.\n *\n * @param {string} method - Request method\n * @param {string} url - Target URL\n * @param {Object} options - Request options\n * @returns {Promise} Resolves with the response of the network request\n *\n * @private\n */\n _request (method: string, url: string, options: RequestOptions) {\n if (this.isForbiddenRequestMethod(method, url)) {\n return Promise.reject(`Don't use ${method} on directories!`);\n }\n\n if (! options.headers) { options.headers = {}; }\n options.headers['Authorization'] = 'Bearer ' + this.token;\n\n this.rs._emit('wire-busy', {\n method: method,\n isFolder: isFolder(url)\n });\n\n return requestWithTimeout(method, url, options).then((xhr) => {\n // Google tokens expire from time to time...\n if (xhr && xhr.status === 401) {\n this.connect();\n return;\n } else {\n if (!this.online) {\n this.online = true;\n this.rs._emit('network-online');\n }\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(url),\n success: true\n });\n\n return Promise.resolve(xhr);\n }\n }, (error) => {\n if (this.online) {\n this.online = false;\n this.rs._emit('network-offline');\n }\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(url),\n success: false\n });\n\n return Promise.reject(error);\n });\n }\n\n /**\n * Initialize the Google Drive backend.\n *\n * @param {Object} remoteStorage - RemoteStorage instance\n *\n * @protected\n */\n static _rs_init (remoteStorage): void {\n const config = remoteStorage.apiKeys.googledrive;\n if (config) {\n remoteStorage.googledrive = new GoogleDrive(remoteStorage, config.clientId);\n if (remoteStorage.backend === 'googledrive') {\n remoteStorage._origRemote = remoteStorage.remote;\n remoteStorage.remote = remoteStorage.googledrive;\n\n hookGetItemURL(remoteStorage);\n }\n }\n }\n\n /**\n * Inform about the availability of the Google Drive backend.\n *\n * @returns {Boolean}\n *\n * @protected\n */\n static _rs_supported (): boolean {\n return true;\n }\n\n /**\n * Remove Google Drive as a backend.\n *\n * @param {Object} remoteStorage - RemoteStorage instance\n *\n * @protected\n */\n static _rs_cleanup (remoteStorage): void {\n remoteStorage.setBackend(undefined);\n if (remoteStorage._origRemote) {\n remoteStorage.remote = remoteStorage._origRemote;\n delete remoteStorage._origRemote;\n }\n unHookGetItemURL(remoteStorage);\n }\n}\n\ninterface GoogleDrive extends EventHandling {}\napplyMixins(GoogleDrive, [EventHandling]);\n\nexport = GoogleDrive;\n","/**\n * TODO rewrite, doesn't expose GPD anymore, it's in cachinglayer now\n *\n * This file exposes a get/put/delete interface, accessing data in an IndexedDB.\n *\n * There are multiple parts to this interface:\n *\n * The RemoteStorage integration:\n * - IndexedDB._rs_supported() determines if IndexedDB support\n * is available. If it isn't, RemoteStorage won't initialize the feature.\n * - IndexedDB._rs_init() initializes the feature. It returns\n * a promise that is fulfilled as soon as the database has been opened and\n * migrated.\n *\n * The storage interface (IndexedDB object):\n * - Usually this is accessible via \"remoteStorage.local\"\n * - #get() takes a path and returns a promise.\n * - #put() takes a path, body and contentType and also returns a promise.\n * - #delete() takes a path and also returns a promise.\n * - #on('change', ...) events, being fired whenever something changes in\n * the storage. Change events roughly follow the StorageEvent pattern.\n * They have \"oldValue\" and \"newValue\" properties, which can be used to\n * distinguish create/update/delete operations and analyze changes in\n * change handlers. In addition they carry a \"origin\" property, which\n * is either \"window\", \"local\", or \"remote\". \"remote\" events are fired\n * whenever a change comes in from Sync.\n *\n * The sync interface (also on IndexedDB object):\n * - #getNodes([paths]) returns the requested nodes in a promise.\n * - #setNodes(map) stores all the nodes given in the (path -> node) map.\n *\n * @interface\n */\n\nimport type { RSNode, RSNodes } from './interfaces/rs_node';\nimport EventHandling from './eventhandling';\nimport CachingLayer from './cachinglayer';\nimport log from './log';\nimport {\n applyMixins,\n deepClone,\n getGlobalContext\n} from './util';\n\nconst DB_VERSION = 2;\n\nconst DEFAULT_DB_NAME = 'remotestorage';\n\n// TODO very weird that this is re-assigned\nlet DEFAULT_DB;\n\nclass IndexedDB extends CachingLayer {\n db: any;\n getsRunning: number;\n putsRunning: number;\n changesQueued: { [key: string]: unknown };\n changesRunning: { [key: string]: unknown };\n commitSlownessWarning: any; // TODO null | number (but node's setInterval returns an unknown type)\n\n constructor(database) {\n super();\n this.addEvents(['change', 'local-events-done']);\n\n this.db = database || DEFAULT_DB;\n\n if (!this.db) {\n // TODO shouldn't this throw an error?\n log(\"[IndexedDB] Failed to open DB\");\n return undefined;\n }\n\n this.getsRunning = 0;\n this.putsRunning = 0;\n\n /**\n * Given a node for which uncommitted changes exist, this cache\n * stores either the entire uncommitted node, or false for a deletion.\n * The node's path is used as the key.\n *\n * changesQueued stores changes for which no IndexedDB transaction has\n * been started yet.\n */\n this.changesQueued = {};\n\n /**\n * Given a node for which uncommitted changes exist, this cache\n * stores either the entire uncommitted node, or false for a deletion.\n * The node's path is used as the key.\n *\n * At any time there is at most one IndexedDB transaction running.\n * changesRunning stores the changes that are included in that currently\n * running IndexedDB transaction, or if none is running, of the last one\n * that ran.\n */\n this.changesRunning = {};\n\n // TODO document\n this.commitSlownessWarning = null;\n }\n\n /**\n * TODO: Document\n */\n async getNodes (paths: string[]): Promise {\n const misses = [], fromCache = {};\n for (let i = 0, len = paths.length; i < len; i++) {\n if (this.changesQueued[paths[i]] !== undefined) {\n fromCache[paths[i]] = deepClone(this.changesQueued[paths[i]] || undefined);\n } else if (this.changesRunning[paths[i]] !== undefined) {\n fromCache[paths[i]] = deepClone(this.changesRunning[paths[i]] || undefined);\n } else {\n misses.push(paths[i]);\n }\n }\n if (misses.length > 0) {\n return this.getNodesFromDb(misses).then(function (nodes) {\n for (const i in fromCache) {\n nodes[i] = fromCache[i];\n }\n return nodes;\n });\n } else {\n return Promise.resolve(fromCache);\n }\n }\n\n /**\n * TODO: Document\n */\n async setNodes (nodes: RSNodes): Promise {\n for (const i in nodes) {\n this.changesQueued[i] = nodes[i] || false;\n }\n this.maybeFlush();\n return Promise.resolve();\n }\n\n /**\n * TODO: Document\n */\n maybeFlush (): void {\n if (this.putsRunning === 0) {\n this.flushChangesQueued();\n } else {\n if (!this.commitSlownessWarning) {\n this.commitSlownessWarning = global.setInterval(function () {\n console.warn('WARNING: waited more than 10 seconds for previous commit to finish');\n }, 10000);\n }\n }\n }\n\n /**\n * TODO: Document\n */\n flushChangesQueued (): void {\n if (this.commitSlownessWarning) {\n clearInterval(this.commitSlownessWarning);\n this.commitSlownessWarning = null;\n }\n if (Object.keys(this.changesQueued).length > 0) {\n this.changesRunning = this.changesQueued;\n this.changesQueued = {};\n this.setNodesInDb(this.changesRunning).then(this.flushChangesQueued.bind(this));\n }\n }\n\n /**\n * TODO: Document\n */\n getNodesFromDb (paths: string[]): Promise {\n return new Promise((resolve, reject) => {\n\n const transaction = this.db.transaction(['nodes'], 'readonly');\n const nodes = transaction.objectStore('nodes');\n const retrievedNodes = {};\n\n this.getsRunning++;\n\n paths.map((path: string) => {\n nodes.get(path).onsuccess = (evt) => {\n retrievedNodes[path] = evt.target.result;\n };\n });\n\n transaction.oncomplete = () => {\n resolve(retrievedNodes);\n this.getsRunning--;\n };\n\n transaction.onerror = transaction.onabort = () => {\n reject('get transaction error/abort');\n this.getsRunning--;\n };\n\n });\n }\n\n /**\n * TODO: Document\n */\n async setNodesInDb (nodes: { [key: string]: unknown }): Promise {\n return new Promise((resolve, reject) => {\n\n const transaction = this.db.transaction(['nodes'], 'readwrite');\n const nodesStore = transaction.objectStore('nodes');\n const startTime = new Date().getTime();\n\n this.putsRunning++;\n\n log('[IndexedDB] Starting put', nodes, this.putsRunning);\n\n for (const path in nodes) {\n const node = nodes[path];\n if (typeof (node) === 'object') {\n try {\n nodesStore.put(node);\n } catch (e) {\n log('[IndexedDB] Error while putting', node, e);\n throw e;\n }\n } else {\n try {\n nodesStore.delete(path);\n } catch (e) {\n log('[IndexedDB] Error while removing', nodesStore, node, e);\n throw e;\n }\n }\n }\n\n transaction.oncomplete = () => {\n this.putsRunning--;\n log('[IndexedDB] Finished put', nodes, this.putsRunning, (new Date().getTime() - startTime) + 'ms');\n resolve();\n };\n\n transaction.onerror = () => {\n this.putsRunning--;\n reject('transaction error');\n };\n\n transaction.onabort = () => {\n reject('transaction abort');\n this.putsRunning--;\n };\n\n });\n }\n\n /**\n * TODO: Document\n */\n // TODO add real types once known\n reset (callback: (p: unknown) => unknown): void {\n const dbName = this.db.name;\n\n this.db.close();\n\n IndexedDB.clean(this.db.name, () => {\n IndexedDB.open(dbName, (err, other) => {\n if (err) {\n log('[IndexedDB] Error while resetting local storage', err);\n } else {\n // hacky!\n this.db = other;\n }\n if (typeof callback === 'function') {\n callback(self);\n }\n });\n });\n }\n\n /**\n * TODO: Document\n */\n async forAllNodes (cb: (node: RSNode) => void): Promise {\n return new Promise((resolve/*, reject*/) => {\n\n const transaction = this.db.transaction(['nodes'], 'readonly');\n const cursorReq = transaction.objectStore('nodes').openCursor();\n\n cursorReq.onsuccess = (evt) => {\n const cursor = evt.target.result;\n\n if (cursor) {\n cb(this.migrate(cursor.value));\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n }\n\n closeDB (): void {\n if (this.putsRunning === 0) { // check if we are currently writing to the DB\n this.db.close();\n } else {\n setTimeout(this.closeDB.bind(this), 100); // try again a little later\n }\n }\n\n /**\n * TODO: Document\n */\n // TODO add real types once known\n static open (name: string, callback: (p: unknown, p2?: unknown) => unknown) {\n const timer = setTimeout(function () {\n callback(\"timeout trying to open db\");\n }, 10000);\n\n try {\n const req = indexedDB.open(name, DB_VERSION);\n\n req.onerror = function () {\n log('[IndexedDB] Opening DB failed', req);\n\n clearTimeout(timer);\n callback(req.error);\n };\n\n req.onupgradeneeded = function (event) {\n const db = req.result;\n\n log(\"[IndexedDB] Upgrade: from \", event.oldVersion, \" to \", event.newVersion);\n\n if (event.oldVersion !== 1) {\n log(\"[IndexedDB] Creating object store: nodes\");\n db.createObjectStore('nodes', {keyPath: 'path'});\n }\n\n log(\"[IndexedDB] Creating object store: changes\");\n\n db.createObjectStore('changes', {keyPath: 'path'});\n };\n\n req.onsuccess = function () {\n clearTimeout(timer);\n\n // check if all object stores exist\n const db = req.result;\n if (!db.objectStoreNames.contains('nodes') || !db.objectStoreNames.contains('changes')) {\n log(\"[IndexedDB] Missing object store. Resetting the database.\");\n IndexedDB.clean(name, function () {\n IndexedDB.open(name, callback);\n });\n return;\n }\n\n callback(null, req.result);\n };\n } catch (error) {\n log(\"[IndexedDB] Failed to open database: \" + error);\n log(\"[IndexedDB] Resetting database and trying again.\");\n\n clearTimeout(timer);\n\n IndexedDB.clean(name, function () {\n IndexedDB.open(name, callback);\n });\n }\n }\n\n /**\n * TODO: Document\n */\n static clean (databaseName: string, callback: () => void) {\n const req = indexedDB.deleteDatabase(databaseName);\n\n req.onsuccess = function () {\n log('[IndexedDB] Done removing DB');\n callback();\n };\n\n // TODO check if this does anything as onabort does not exist on type according to ts\n req.onerror = (req as any).onabort = function (evt) {\n console.error('Failed to remove database \"' + databaseName + '\"', evt);\n };\n }\n\n /**\n * Initialize the IndexedDB backend.\n *\n * @param {Object} remoteStorage - RemoteStorage instance\n *\n * @protected\n */\n // TODO add real type once known\n static _rs_init (remoteStorage: unknown): Promise {\n\n return new Promise((resolve, reject) => {\n\n IndexedDB.open(DEFAULT_DB_NAME, function (err, db) {\n if (err) {\n reject(err);\n } else {\n DEFAULT_DB = db;\n // TODO remove once real type once known\n (db as any).onerror = () => {\n (remoteStorage as any)._emit('error', err);\n };\n resolve();\n }\n });\n\n });\n }\n\n /**\n * Inform about the availability of the IndexedDB backend.\n *\n * @param {Object} rs - RemoteStorage instance\n * @returns {Boolean}\n *\n * @protected\n */\n static _rs_supported (): Promise {\n return new Promise((resolve, reject) => {\n\n const context = getGlobalContext();\n\n // FIXME: this is causing an error in chrome\n // context.indexedDB = context.indexedDB || context.webkitIndexedDB ||\n // context.mozIndexedDB || context.oIndexedDB ||\n // context.msIndexedDB;\n\n // Detect browsers with known IndexedDb issues (e.g. Android pre-4.4)\n let poorIndexedDbSupport = false;\n if (typeof navigator !== 'undefined' &&\n navigator.userAgent.match(/Android (2|3|4\\.[0-3])/)) {\n // Chrome and Firefox support IndexedDB\n if (!navigator.userAgent.match(/Chrome|Firefox/)) {\n poorIndexedDbSupport = true;\n }\n }\n\n if ('indexedDB' in context && !poorIndexedDbSupport) {\n try {\n const check = indexedDB.open(\"rs-check\");\n check.onerror = function (/* event */) {\n reject();\n };\n check.onsuccess = function (/* event */) {\n check.result.close();\n indexedDB.deleteDatabase(\"rs-check\");\n resolve();\n };\n } catch (e) {\n reject();\n }\n } else {\n reject();\n }\n\n });\n }\n\n /**\n * Remove IndexedDB as a backend.\n *\n * @param {Object} remoteStorage - RemoteStorage instance\n *\n * @protected\n */\n static _rs_cleanup (remoteStorage: any) {\n return new Promise((resolve/*, reject*/) => {\n if (remoteStorage.local) {\n remoteStorage.local.closeDB();\n }\n\n IndexedDB.clean(DEFAULT_DB_NAME, resolve as () => void);\n });\n }\n\n diffHandler() {\n // empty\n }\n}\n\n// TODO move to CachingLayer, same for all layers\ninterface IndexedDB extends EventHandling {}\napplyMixins(IndexedDB, [EventHandling]);\n\nexport = IndexedDB;\n","import type { RSNode, RSNodes } from './interfaces/rs_node';\nimport EventHandling from './eventhandling';\nimport CachingLayer from './cachinglayer';\nimport { applyMixins, deepClone } from './util';\n\n/**\n * In-memory caching adapter. Used when no IndexedDB or localStorage\n * available.\n *\n * @class\n **/\n\nclass InMemoryStorage extends CachingLayer {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _storage: { [key: string]: any } = {};\n\n constructor() {\n super();\n this.addEvents(['change', 'local-events-done']);\n }\n\n getNodes(paths: string[]): Promise {\n const nodes: RSNodes = {};\n\n for (let i = 0, len = paths.length; i < len; i++) {\n // Should use a clone of whatever we are retrieving to prevent\n // mutation, also to follow the same behavior as localStorage\n // and indexeddb.\n nodes[paths[i]] = deepClone(this._storage[paths[i]]);\n }\n\n return Promise.resolve(nodes);\n }\n\n setNodes(nodes: RSNodes): Promise {\n for (const path in nodes) {\n if (nodes[path] === undefined) {\n delete this._storage[path];\n } else {\n this._storage[path] = nodes[path];\n }\n }\n\n return Promise.resolve();\n }\n\n forAllNodes(cb: (node: RSNode) => void): Promise {\n for (const path in this._storage) {\n cb(this.migrate(this._storage[path]));\n }\n return Promise.resolve();\n }\n\n diffHandler(): void {\n // empty\n }\n\n /**\n * Initialize the InMemoryStorage backend.\n *\n * @param {Object} remoteStorage - RemoteStorage instance\n *\n * @protected\n */\n protected static _rs_init(): void {\n // empty\n }\n\n /**\n * Inform about the availability of the InMemoryStorage backend.\n *\n * @returns {Boolean}\n *\n * @protected\n */\n protected static _rs_supported(): true {\n // In-memory storage is always supported\n return true;\n }\n\n /**\n * Remove InMemoryStorage as a backend.\n *\n * @protected\n */\n protected static _rs_cleanup(): void {\n // empty\n }\n}\n\n// TODO move to CachingLayer, same for all layers\ninterface InMemoryStorage extends EventHandling {}\napplyMixins(InMemoryStorage, [EventHandling]);\n\nexport = InMemoryStorage;\n","import type { RSNode, RSNodes } from './interfaces/rs_node';\nimport CachingLayer from './cachinglayer';\nimport EventHandling from './eventhandling';\nimport log from './log';\nimport { applyMixins, localStorageAvailable } from './util';\n\n/**\n * localStorage caching adapter. Used when no IndexedDB available.\n **/\n\nconst NODES_PREFIX = \"remotestorage:cache:nodes:\";\nconst CHANGES_PREFIX = \"remotestorage:cache:changes:\";\n\nfunction isRemoteStorageKey(key: string): boolean {\n return key.substr(0, NODES_PREFIX.length) === NODES_PREFIX ||\n key.substr(0, CHANGES_PREFIX.length) === CHANGES_PREFIX;\n}\n\nfunction isNodeKey(key: string): boolean {\n return key.substr(0, NODES_PREFIX.length) === NODES_PREFIX;\n}\n\nclass LocalStorage extends CachingLayer {\n constructor() {\n super();\n this.addEvents(['change', 'local-events-done']);\n }\n\n // TODO fix this\n diffHandler(...args: any[]): void {\n return;\n }\n\n getNodes(paths: string[]): Promise {\n const nodes = {};\n\n for (let i = 0, len = paths.length; i < len; i++) {\n try {\n nodes[paths[i]] = JSON.parse(localStorage[NODES_PREFIX + paths[i]]);\n } catch (e) {\n nodes[paths[i]] = undefined;\n }\n }\n\n return Promise.resolve(nodes);\n }\n\n setNodes(nodes: RSNodes): Promise {\n for (const path in nodes) {\n // TODO shouldn't we use getItem/setItem?\n localStorage[NODES_PREFIX + path] = JSON.stringify(nodes[path]);\n }\n\n return Promise.resolve();\n }\n\n forAllNodes(cb: (node: RSNode) => void): Promise {\n let node: RSNode | undefined;\n\n for (let i = 0, len = localStorage.length; i < len; i++) {\n if (isNodeKey(localStorage.key(i))) {\n try {\n // NOTE: this is coming from caching layer todo fix via interface or similar\n node = this.migrate(JSON.parse(localStorage[localStorage.key(i)]));\n } catch (e) {\n node = undefined;\n }\n if (node) {\n cb(node);\n }\n }\n }\n return Promise.resolve();\n }\n\n /**\n * Initialize the LocalStorage backend.\n *\n * @protected\n */\n static _rs_init(): void {\n return;\n }\n\n /**\n * Inform about the availability of the LocalStorage backend.\n *\n * @protected\n */\n static _rs_supported(): boolean {\n return localStorageAvailable();\n }\n\n /**\n * Remove LocalStorage as a backend.\n *\n * @protected\n *\n * TODO: tests missing!\n */\n static _rs_cleanup(): void {\n const keys = [];\n\n for (let i = 0, len = localStorage.length; i < len; i++) {\n const key = localStorage.key(i);\n if (isRemoteStorageKey(key)) {\n keys.push(key);\n }\n }\n\n keys.forEach((key) => {\n log('[LocalStorage] Removing', key);\n delete localStorage[key];\n });\n }\n}\n\n// TODO move to CachingLayer, same for all layers\ninterface LocalStorage extends EventHandling {}\napplyMixins(LocalStorage, [EventHandling]);\n\nexport = LocalStorage;\n","import config from './config';\n\n/**\n * Log using console.log, when remoteStorage logging is enabled.\n *\n * You can enable logging with ``RemoteStorage#enableLog``.\n *\n * (You can also enable logging during remoteStorage object creation. See:\n * {@link RemoteStorage}).\n */\nfunction log(...args): void {\n if (config.logging) {\n // eslint-disable-next-line no-console\n console.log(...args);\n }\n}\n\nexport = log;\n","import RemoteStorage from \"./remotestorage\";\nimport EventHandling from \"./eventhandling\";\nimport { isFolder } from \"./util\";\n\n/**\n * The ancestor for WireClient, GoogleDrive & Dropbox\n */\nexport class RemoteBase extends EventHandling {\n rs: RemoteStorage;\n\n connected: boolean;\n online: boolean;\n userAddress: string;\n storageApi: string;\n\n constructor(rs: RemoteStorage) {\n super();\n this.rs = rs;\n this.connected = false;\n // TODO: Should `online` be set true or false for all, here or in configure?\n }\n\n stopWaitingForToken (): void {\n if (!this.connected) {\n this._emit('not-connected');\n }\n }\n\n addQuotes (str: string): string {\n if (typeof (str) !== 'string') {\n return str;\n }\n if (str === '*') {\n return '*';\n }\n\n return '\"' + str + '\"';\n }\n\n stripQuotes (str: string): string {\n if (typeof (str) !== 'string') {\n return str;\n }\n\n return str.replace(/^[\"']|[\"']$/g, '');\n }\n\n isForbiddenRequestMethod(method: string, uri: string): boolean {\n if (method === 'PUT' || method === 'DELETE') {\n return isFolder(uri);\n } else {\n return false;\n }\n }\n}\n\n\nexport interface RemoteSettings {\n userAddress?: string;\n href?: string; // remoteStorage server's base URL\n storageApi?: string; // spec version\n token?: string | false; // OAuth2 access token\n refreshToken?: string; // OAuth2 refresh token\n tokenType?: string; // type of access token; usually 'bearer'\n properties?: object;\n}\n\nexport interface RemoteResponse {\n statusCode: number;\n revision?: string;\n contentType?: string;\n body?: any;\n}\n\n/**\n * The public interface for WireClient, GoogleDrive, Dropbox & Solid\n */\nexport interface Remote {\n /**\n * Whether or not a remote store is connected\n */\n connected: boolean;\n\n /**\n * Whether last sync action was successful or not\n */\n online: boolean;\n\n /**\n * The user address of the connected user\n */\n userAddress: string;\n\n /**\n * Holds the spec version the server claims to be compatible with\n *\n * @example\n * ```js\n * remoteStorage.remote.storageApi\n * // 'draft-dejong-remotestorage-12'\n * ```\n *\n * @internal\n */\n storageApi: string;\n\n /**\n * Holds the server's base URL, as obtained in the Webfinger discovery\n *\n * @example\n * ```js\n * remoteStorage.remote.href\n * // 'https://storage.example.com/users/jblogg/'\n * ```\n *\n * @internal\n */\n href?: string;\n\n /**\n * The JSON-parsed properties object from the user's WebFinger record\n */\n properties?: object;\n\n /**\n * OAuth2 client ID\n *\n * @internal\n */\n clientId?: string;\n\n /**\n * OAuth2 PKCE\n *\n * @internal\n */\n TOKEN_URL?: string;\n\n configure (settings): void // TODO: harmonize settings & use type\n\n configure (settings: RemoteSettings): void;\n\n /**\n * Initiate the authorization flow's OAuth dance.\n *\n * @internal\n */\n connect? (): void;\n\n stopWaitingForToken (): void;\n\n get (path: string, options: { ifMatch?: string; ifNoneMatch?: string }): Promise;\n\n put (path: string, body: XMLHttpRequestBodyInit, contentType: string, options: { ifMatch?: string; ifNoneMatch?: string }): Promise\n\n delete (path: string, options: { ifMatch?: string }): Promise;\n}\n","'use strict';\n\nimport config from './config';\nimport log from './log';\nimport {\n applyMixins,\n getGlobalContext,\n getJSONFromLocalStorage,\n extend,\n localStorageAvailable\n} from './util';\n\nimport Access from './access';\nimport Authorize from './authorize';\nimport BaseClient from './baseclient';\nimport Caching from './caching';\nimport IndexedDB from './indexeddb';\nimport InMemoryStorage from './inmemorystorage';\nimport LocalStorage from './localstorage';\nimport { EventHandling, EventHandler } from './eventhandling';\nimport GoogleDrive from './googledrive';\nimport Dropbox from './dropbox';\nimport Solid from './solid';\nimport Discover from './discover';\nimport SyncError from './sync-error';\nimport UnauthorizedError from './unauthorized-error';\nimport Features from './features';\nimport { Remote } from \"./remote\";\n\nimport type { AuthorizeOptions } from './authorize';\nimport type { StorageInfo } from './interfaces/storage_info';\nimport type { Sync } from './sync';\n\n// TODO this is assigned to RemoteStorage.util later; check if still needed\nimport * as util from './util';\n\nconst globalContext = getGlobalContext();\n// declare global {\n// interface Window { cordova: any };\n// }\n\nlet hasLocalStorage: boolean;\n\n// TODO document and/or refactor (seems weird)\nfunction emitUnauthorized(r) {\n if (r.statusCode === 403 || r.statusCode === 401) {\n this._emit('error', new UnauthorizedError());\n }\n return Promise.resolve(r);\n}\n\n/**\n* Check if interval is valid: numeric and between 2s and 1hr inclusive\n*/\nfunction isValidInterval(interval: unknown): interval is number {\n return (typeof interval === 'number' &&\n interval >= 2000 &&\n interval <= 3600000);\n}\n\n/**\n * Represents a data module\n *\n * @example\n * ```js\n * {\n * name: 'examples',\n * builder: function(privateClient, publicClient) {\n * return {\n * exports: {\n * addItem(item): function() {\n * // Generate a random ID/path\n * const path = [...Array(10)].map(() => String.fromCharCode(Math.floor(Math.random() * 95) + 32)).join('');\n * // Store the object, and ensure it conforms to the JSON Schema\n * // type `example-item`\n * privateClient.storeObject('example-item', path, item);\n * }\n * }\n * }\n * }\n * }\n * ```\n */\nexport interface RSModule {\n /**\n * The module's name, which is also the category (i.e. base folder) for document URLs on the remote storage\n */\n name: string;\n /**\n * A module builder function, which defines the actual module\n */\n builder: (privateClient: BaseClient, publicClient: BaseClient) => {\n exports: {\n [key: string]: any;\n };\n };\n}\n\nenum ApiKeyType {\n GOOGLE = 'googledrive',\n DROPBOX = 'dropbox'\n}\n\n/**\n * Create a `remoteStorage` class instance so:\n *\n * ```js\n * const remoteStorage = new RemoteStorage();\n * ```\n *\n * The constructor can optionally be called with a configuration object. This\n * example shows all default values:\n *\n * ```js\n * const remoteStorage = new RemoteStorage({\n * cache: true,\n * changeEvents: {\n * local: true,\n * window: false,\n * remote: true,\n * conflict: true\n * },\n * cordovaRedirectUri: undefined,\n * logging: false,\n * modules: []\n * });\n * ```\n *\n * > [!NOTE]\n * > In the current version, it is only possible to use a single `remoteStorage`\n * > instance. You cannot connect to two different remotes in parallel yet.\n * > We intend to support this eventually.\n *\n * > [!TIP]\n * > For the change events configuration, you have to set all events\n * > explicitly. Otherwise it disables the unspecified ones.\n *\n * ## Events\n *\n * You can add event handlers to your `remoteStorage` instance by using the\n * {@link on} function. For example:\n *\n * ```js\n * remoteStorage.on('connected', function() {\n * // Storage account has been connected, let’s roll!\n * });\n * ```\n *\n * ### `ready`\n *\n * Emitted when all features are loaded and the RS instance is ready to be used\n * in your app\n *\n * ### `not-connected`\n *\n * Emitted when ready, but no storage connected (\"anonymous mode\")\n *\n * ### `connected`\n *\n * Emitted when a remote storage has been connected\n *\n * ### `disconnected`\n *\n * Emitted after disconnect\n *\n * ### `error`\n *\n * Emitted when an error occurs; receives an error object as argument\n *\n * There are a handful of known errors, which are identified by the `name`\n * property of the error object:\n *\n * * `Unauthorized`\n *\n * Emitted when a network request resulted in a 401 or 403 response. You can\n * use this event to handle invalid OAuth tokens in custom UI (i.e. when a\n * stored token has been revoked or expired by the RS server).\n *\n * * `DiscoveryError`\n *\n * A variety of storage discovery errors, e.g. from user address input\n * validation, or user address lookup issues\n *\n * #### Example\n *\n * ```js\n * remoteStorage.on('error', err => console.log(err));\n *\n * // {\n * // name: \"Unauthorized\",\n * // message: \"App authorization expired or revoked.\",\n * // stack: \"Error↵ at new a.Unauthorized (vendor.js:65710:41870)\"\n * // }\n * ```\n *\n * ### `connecting`\n *\n * Emitted before webfinger lookup\n *\n * ### `authing`\n *\n * Emitted before redirecting to the OAuth server\n *\n * ### `wire-busy`\n *\n * Emitted when a network request starts\n *\n * ### `wire-done`\n *\n * Emitted when a network request completes\n *\n * ### `sync-req-done`\n *\n * Emitted when a single sync request has finished. Callback functions\n * receive an object as argument, informing the client of remaining items\n * in the current sync task queue.\n *\n * #### Example\n *\n * ```js\n * remoteStorage.on('sync-req-done', result => console.log(result));\n * // { tasksRemaining: 21 }\n * ```\n *\n * > [!NOTE]\n * > The internal task queue holds at most 100 items at the same time,\n * > regardless of the overall amount of items to sync. Therefore, this number\n * > is only an indicator of sync status, not a precise amount of items left\n * > to sync. It can be useful to determine if your app should display any\n * > kind of sync status/progress information for the cycle or not.\n *\n * ### `sync-done`\n *\n * Emitted when a sync cycle has been completed and a new sync is scheduled.\n *\n * The callback function receives an object as argument, informing the client\n * if the sync process has completed successfully or not.\n *\n * #### Example\n *\n * ```js\n * remoteStorage.on('sync-done', result => console.log(result));\n * // { completed: true }\n * ```\n *\n * If `completed` is `false`, it means that some of the sync requests have\n * failed and will be retried in the next sync cycle (usually a few seconds\n * later in this case). This is not an unusual scenario on mobile networks or\n * when doing a large initial sync for example.\n *\n * For an app's user interface, you may want to consider the sync process as\n * ongoing in this case, and wait until your app sees a positive `completed`\n * status before updating the UI.\n *\n * ### `network-offline`\n *\n * Emitted once when a wire request fails for the first time, and\n * `remote.online` is set to false\n *\n * ### `network-online`\n *\n * Emitted once when a wire request succeeds for the first time after a failed\n * one, and `remote.online` is set back to true\n *\n * ### `sync-interval-change`\n *\n * Emitted when the sync interval changes\n */\nexport class RemoteStorage {\n /**\n * Pending get/put/delete calls\n * @internal\n */\n _pending: {[key: string]: any}[] = [];\n\n /**\n * TODO: document\n * @internal\n */\n _cleanups: [] = [];\n\n /**\n * TODO: document\n * @internal\n */\n _pathHandlers: { [key: string]: any } = { change: {} };\n\n /**\n * Holds OAuth app keys for Dropbox, Google Drive\n * @internal\n */\n apiKeys: {googledrive?: {clientId: string}; dropbox?: {appKey: string}} = {};\n\n /**\n */\n access: Access;\n /**\n */\n sync: Sync;\n /**\n */\n caching: Caching;\n\n /**\n * @internal\n */\n _syncTimer: any;\n /**\n * @internal\n */\n syncStopped: boolean;\n /**\n * @internal\n */\n get: Function;\n /**\n * @internal\n */\n put: Function;\n /**\n * @internal\n */\n delete: Function;\n\n /**\n */\n backend: 'remotestorage' | 'dropbox' | 'googledrive' | 'solid';\n\n /**\n * Depending on the chosen backend, this is either an instance of `WireClient`,\n * `Dropbox`, `GoogleDrive` or `Solid`.\n *\n * See {@link Remote} for public API\n *\n * @example\n * remoteStorage.remote.connected\n * // false\n */\n remote: Remote;\n\n /**\n * Access to the local caching backend used. Usually either a\n * `RemoteStorage.IndexedDB` or `RemoteStorage.LocalStorage` instance.\n *\n * Not available, when caching is turned off.\n *\n * @internal\n */\n local: IndexedDB | LocalStorage | InMemoryStorage;\n\n /**\n * @internal\n */\n dropbox: Dropbox;\n /**\n * @internal\n */\n googledrive: GoogleDrive;\n solid: Solid;\n\n /**\n * @internal\n */\n fireInitial: Function;\n\n\n constructor (cfg?: object) {\n // Initial configuration property settings.\n // TODO use modern JS to merge object properties\n if (typeof cfg === 'object') { extend(config, cfg); }\n\n this.addEvents([\n 'ready', 'authing', 'connecting', 'pod-not-selected', 'connected', 'disconnected',\n 'not-connected', 'conflict', 'error', 'features-loaded',\n 'sync-interval-change', 'sync-req-done', 'sync-done',\n 'wire-busy', 'wire-done', 'network-offline', 'network-online'\n ]);\n\n this._setGPD({\n get: this._pendingGPD('get'),\n put: this._pendingGPD('put'),\n delete: this._pendingGPD('delete')\n });\n\n hasLocalStorage = localStorageAvailable();\n\n if (hasLocalStorage) {\n this.apiKeys = getJSONFromLocalStorage('remotestorage:api-keys') || {};\n\n const backendType = localStorage.getItem('remotestorage:backend');\n\n if (backendType === 'dropbox' || backendType === 'googledrive' || backendType === 'solid') {\n this.setBackend(backendType);\n } else {\n this.setBackend('remotestorage');\n }\n }\n\n // Keep a reference to the orginal `on` function\n const origOn = this.on;\n\n this.on = function (eventName: string, handler: Function): void {\n if (this._allLoaded) {\n // check if the handler should be called immediately, because the\n // event has happened already\n switch(eventName) {\n case 'features-loaded':\n setTimeout(handler, 0);\n break;\n case 'ready':\n if (this.remote) {\n setTimeout(handler, 0);\n }\n break;\n case 'connected':\n if (this.remote && this.remote.connected) {\n setTimeout(handler, 0);\n }\n break;\n case 'not-connected':\n if (this.remote && !this.remote.connected) {\n setTimeout(handler, 0);\n }\n break;\n case 'pod-not-selected':\n if ((this.remote instanceof Solid)\n && Array.isArray(this.remote.getPodURLs())\n && this.remote.getPodURLs().length > 0\n && this.remote.getPodURL() === null) {\n setTimeout(handler, 0);\n }\n break;\n }\n }\n\n return origOn.call(this, eventName, handler);\n };\n\n // load all features and emit `ready`\n this._init();\n\n /**\n * TODO: document\n */\n this.fireInitial = function () {\n if (this.local) {\n setTimeout(this.local.fireInitial.bind(this.local), 0);\n }\n }.bind(this);\n\n this.on('ready', this.fireInitial.bind(this));\n this.loadModules();\n }\n\n /**\n * Indicating if remoteStorage is currently connected.\n */\n get connected (): boolean {\n return this.remote.connected;\n }\n\n /**\n * FIXME: Instead of doing this, would be better to only\n * export setAuthURL / getAuthURL from RemoteStorage prototype\n *\n * @ignore\n */\n static Authorize = Authorize;\n\n static SyncError = SyncError;\n static Unauthorized = UnauthorizedError;\n static DiscoveryError = Discover.DiscoveryError;\n static util = util;\n\n /**\n * Load all modules passed as arguments\n *\n * @internal\n */\n loadModules(): void {\n config.modules.forEach(this.addModule.bind(this));\n }\n\n /**\n * Initiate the OAuth authorization flow.\n *\n * @internal\n */\n authorize (options: AuthorizeOptions): void {\n this.access.setStorageType(this.remote.storageApi);\n if (typeof options.scope === 'undefined') {\n options.scope = this.access.scopeParameter;\n }\n\n if (globalContext.cordova) {\n options.redirectUri = config.cordovaRedirectUri;\n } else {\n const location = Authorize.getLocation();\n let redirectUri = location.origin;\n if (location.pathname !== '/') {\n redirectUri += location.pathname;\n }\n\n options.redirectUri = redirectUri;\n }\n\n if (typeof options.clientId === 'undefined') {\n options.clientId = options.redirectUri.match(/^(https?:\\/\\/[^/]+)/)[0];\n }\n\n Authorize.authorize(this, options);\n }\n\n /**\n * TODO: document\n * @internal\n */\n impliedauth (storageApi?: string, redirectUri?: string): void {\n // TODO shouldn't these be default argument values?\n storageApi = storageApi || this.remote.storageApi;\n redirectUri = redirectUri || String(document.location);\n\n log('ImpliedAuth proceeding due to absent authURL; storageApi = ' + storageApi + ' redirectUri = ' + redirectUri);\n // Set a fixed access token, signalling to not send it as Bearer\n this.remote.configure({\n token: Authorize.IMPLIED_FAKE_TOKEN\n });\n document.location.href = redirectUri;\n }\n\n /**\n * Connect to a remoteStorage server.\n *\n * Discovers the WebFinger profile of the given user address and initiates\n * the OAuth dance.\n *\n * This method must be called *after* all required access has been claimed.\n * When using the connect widget, it will call this method when the user\n * clicks/taps the \"connect\" button.\n *\n * Special cases:\n *\n * 1. If a bearer token is supplied as second argument, the OAuth dance\n * will be skipped and the supplied token be used instead. This is\n * useful outside of browser environments, where the token has been\n * acquired in a different way.\n *\n * 2. If the Webfinger profile for the given user address doesn't contain\n * an auth URL, the library will assume that client and server have\n * established authorization among themselves, which will omit bearer\n * tokens in all requests later on. This is useful for example when using\n * Kerberos and similar protocols.\n *\n * @param userAddress - The user address (user@host) or URL to connect to.\n * @param token - (optional) A bearer token acquired beforehand\n *\n * @example\n * remoteStorage.connect('user@example.com');\n */\n connect (userAddress: string, token?: string): void {\n this.setBackend('remotestorage');\n if (userAddress.indexOf('@') < 0 && !userAddress.match(/^(https?:\\/\\/)?[^\\s\\/$\\.?#]+\\.[^\\s]*$/)) {\n this._emit('error', new RemoteStorage.DiscoveryError(\"Not a valid user address or URL.\"));\n return;\n }\n\n // Prefix URL with https:// if it's missing\n if (userAddress.indexOf('@') < 0 && !userAddress.match(/^https?:\\/\\//)) {\n userAddress = `https://${userAddress}`;\n }\n\n if (globalContext.cordova) {\n if (typeof config.cordovaRedirectUri !== 'string') {\n this._emit('error', new RemoteStorage.DiscoveryError(\"Please supply a custom HTTPS redirect URI for your Cordova app\"));\n return;\n }\n if (!globalContext.cordova.InAppBrowser) {\n this._emit('error', new RemoteStorage.DiscoveryError(\"Please include the InAppBrowser Cordova plugin to enable OAuth\"));\n return;\n }\n }\n\n this.remote.configure({\n userAddress: userAddress\n });\n this._emit('connecting');\n\n Discover(userAddress).then((info: StorageInfo): void => {\n this._emit('authing');\n info.userAddress = userAddress;\n this.remote.configure(info);\n if (! this.remote.connected) {\n if (info.authURL) {\n if (typeof token === 'undefined') {\n // Normal authorization step; the default way to connect\n this.authorize({ authURL: info.authURL });\n } else if (typeof token === 'string') {\n // Token supplied directly by app/developer/user\n log('Skipping authorization sequence and connecting with known token');\n this.remote.configure({ token: token });\n } else {\n throw new Error(\"Supplied bearer token must be a string\");\n }\n } else {\n // In lieu of an excplicit authURL, assume that the browser and\n // server handle any authorization needs; for instance, TLS may\n // trigger the browser to use a client certificate, or a 401 Not\n // Authorized response may make the browser send a Kerberos ticket\n // using the SPNEGO method.\n this.impliedauth();\n }\n }\n }, (/*err*/) => {\n this._emit('error', new RemoteStorage.DiscoveryError(\"No storage information found for this user address.\"));\n });\n }\n\n /**\n * Reconnect the remote server to get a new authorization.\n *\n * Useful when not using the connect widget and encountering an\n * `Unauthorized` event.\n */\n reconnect (): void {\n this.remote.configure({ token: null });\n\n if (this.backend === 'remotestorage') {\n this.connect(this.remote.userAddress);\n } else {\n this.remote.connect();\n }\n }\n\n /**\n * \"Disconnect\" from remote server to terminate current session.\n *\n * This method clears all stored settings and deletes the entire local\n * cache.\n */\n disconnect (): void {\n if (this.remote) {\n this.remote.configure({\n userAddress: null,\n href: null,\n storageApi: null,\n token: null,\n properties: null\n });\n }\n this._setGPD({\n get: this._pendingGPD('get'),\n put: this._pendingGPD('put'),\n delete: this._pendingGPD('delete')\n });\n const n = this._cleanups.length;\n let i = 0;\n\n const oneDone = (): void => {\n i++;\n if (i >= n) {\n this._init();\n // FIXME Re-enable when modules are all imports\n // log('Done cleaning up, emitting disconnected and disconnect events');\n this._emit('disconnected');\n }\n };\n\n if (n > 0) {\n this._cleanups.forEach((cleanup: (thisarg: object) => Promise) => {\n const cleanupResult = cleanup(this);\n if (typeof(cleanupResult) === 'object' && typeof(cleanupResult.then) === 'function') {\n cleanupResult.then(oneDone);\n } else {\n oneDone();\n }\n });\n } else {\n oneDone();\n }\n }\n\n /**\n * @internal\n */\n setBackend (backendType: 'remotestorage' | 'dropbox' | 'googledrive' | 'solid'): void {\n this.backend = backendType;\n\n if (hasLocalStorage) {\n if (typeof backendType !== 'undefined') {\n localStorage.setItem('remotestorage:backend', backendType);\n } else {\n localStorage.removeItem('remotestorage:backend');\n }\n }\n }\n\n /**\n * Add a `change` event handler for the given path. Whenever a change\n * happens (as determined by the local backend, such as e.g.\n * `RemoteStorage.IndexedDB`), and the affected path is equal to or below the\n * given 'path', the given handler is called.\n *\n * > [!TIP]\n * > You should usually not use this method, but instead use the\n * > `change` events provided by {@link BaseClient}.\n *\n * @param path - Absolute path to attach handler to\n * @param handler - A function to handle the change\n *\n * @example\n * remoteStorage.onChange('/bookmarks/', function() {\n * // your code here\n * })\n */\n onChange (path: string, handler: EventHandler): void {\n if (! this._pathHandlers.change[path]) {\n this._pathHandlers.change[path] = [];\n }\n this._pathHandlers.change[path].push(handler);\n }\n\n /**\n * Enable remoteStorage debug logging.\n *\n * Usually done when instantiating remoteStorage:\n *\n * ```js\n * const remoteStorage = new RemoteStorage({ logging: true });\n * ```\n */\n enableLog (): void {\n config.logging = true;\n }\n\n /**\n * Disable remoteStorage debug logging\n */\n disableLog (): void {\n config.logging = false;\n }\n\n /**\n * Log something to the debug log\n *\n * @internal\n */\n log (...args): void {\n log.apply(RemoteStorage, args);\n }\n\n /**\n * Set the OAuth key/ID for GoogleDrive and/or Dropbox backend support.\n *\n * @param apiKeys - A config object\n *\n * @example\n * remoteStorage.setApiKeys({\n * dropbox: 'your-app-key',\n * googledrive: 'your-client-id'\n * });\n */\n setApiKeys (apiKeys: {[key in ApiKeyType]?: string}): void | boolean { // TODO fix the input type\n const validTypes: string[] = [ApiKeyType.GOOGLE, ApiKeyType.DROPBOX];\n if (typeof apiKeys !== 'object' || !Object.keys(apiKeys).every(type => validTypes.includes(type))) {\n console.error('setApiKeys() was called with invalid arguments') ;\n return false;\n }\n\n Object.keys(apiKeys).forEach(type => {\n const key = apiKeys[type];\n if (!key) { delete this.apiKeys[type]; return; }\n\n switch(type) {\n case ApiKeyType.DROPBOX:\n this.apiKeys[ApiKeyType.DROPBOX] = { appKey: key };\n if (typeof this.dropbox === 'undefined' ||\n this.dropbox.clientId !== key) {\n Dropbox._rs_init(this);\n }\n break;\n case ApiKeyType.GOOGLE:\n this.apiKeys[ApiKeyType.GOOGLE] = { clientId: key };\n if (typeof this.googledrive === 'undefined' ||\n this.googledrive.clientId !== key) {\n GoogleDrive._rs_init(this);\n }\n break;\n }\n return true;\n });\n\n if (hasLocalStorage) {\n localStorage.setItem('remotestorage:api-keys', JSON.stringify(this.apiKeys));\n }\n\n }\n\n /**\n * Set redirect URI to be used for the OAuth redirect within the\n * in-app-browser window in Cordova apps. See\n * [Usage in Cordova apps](../../../cordova) for details.\n *\n * @param uri - A valid HTTP(S) URI\n *\n * @example\n * remoteStorage.setCordovaRedirectUri('https://app.example.com');\n */\n setCordovaRedirectUri (uri: string): void {\n if (typeof uri !== 'string' || !uri.match(/http(s)?:\\/\\//)) {\n throw new Error(\"Cordova redirect URI must be a URI string\");\n }\n config.cordovaRedirectUri = uri;\n }\n\n //\n // FEATURES INITIALIZATION\n //\n\n /**\n * @internal\n */\n _init = Features.loadFeatures;\n /**\n * @internal\n */\n features = Features.features;\n /**\n * @internal\n */\n loadFeature = Features.loadFeature;\n /**\n * @internal\n */\n featureSupported = Features.featureSupported;\n /**\n * @internal\n */\n featureDone = Features.featureDone;\n /**\n * @internal\n */\n featuresDone = Features.featuresDone;\n /**\n * @internal\n */\n featuresLoaded = Features.featuresLoaded;\n /**\n * @internal\n */\n featureInitialized = Features.featureInitialized;\n /**\n * @internal\n */\n featureFailed = Features.featureFailed;\n /**\n * @internal\n */\n hasFeature = Features.hasFeature;\n /**\n * @internal\n */\n _setCachingModule = Features._setCachingModule;\n /**\n * @internal\n */\n _collectCleanupFunctions = Features._collectCleanupFunctions;\n /**\n * @internal\n */\n _fireReady = Features._fireReady;\n /**\n * @internal\n */\n initFeature = Features.initFeature;\n\n //\n // GET/PUT/DELETE INTERFACE HELPERS\n //\n\n /**\n * TODO: document\n * @internal\n */\n _setGPD (impl, context?) {\n function wrap(func) {\n return function (...args) {\n return func.apply(context, args)\n .then(emitUnauthorized.bind(this));\n };\n }\n this.get = wrap(impl.get);\n this.put = wrap(impl.put);\n this.delete = wrap(impl.delete);\n }\n\n /**\n * TODO: document\n * @internal\n */\n _pendingGPD (methodName): () => Promise {\n return (...args) => {\n const methodArguments = Array.prototype.slice.call(args);\n return new Promise((resolve, reject) => {\n this._pending.push({\n method: methodName,\n args: methodArguments,\n promise: {\n resolve: resolve,\n reject: reject\n }\n });\n });\n };\n }\n\n /**\n * TODO: document\n * @internal\n */\n _processPending (): void {\n this._pending.forEach((pending) => {\n try {\n this[pending.method](...pending.args).then(pending.promise.resolve, pending.promise.reject);\n } catch(e) {\n pending.promise.reject(e);\n }\n });\n this._pending = [];\n }\n\n //\n // CHANGE EVENT HANDLING\n //\n\n /**\n * TODO: document\n * @internal\n */\n _bindChange (object: { on }): void {\n object.on('change', this._dispatchEvent.bind(this, 'change'));\n }\n\n /**\n * TODO: document\n * @internal\n */\n _dispatchEvent (eventName: string, event): void {\n Object.keys(this._pathHandlers[eventName]).forEach((path: string) => {\n const pl = path.length;\n if (event.path.substr(0, pl) === path) {\n this._pathHandlers[eventName][path].forEach((handler) => {\n const ev: { relativePath?: string } = {};\n for (const key in event) { ev[key] = event[key]; }\n ev.relativePath = event.path.replace(new RegExp('^' + path), '');\n try {\n handler(ev);\n } catch(e) {\n console.error(\"'change' handler failed: \", e, e.stack);\n this._emit('error', e);\n }\n });\n }\n });\n }\n\n /**\n * This method allows you to quickly instantiate a BaseClient, which you can\n * use to directly read and manipulate data in the connected storage account.\n *\n * Please use this method only for debugging and development, and choose or\n * create a [data module](../../../data-modules/) for your app to use.\n *\n * @param path - The base directory of the BaseClient that will be returned\n * (with a leading and a trailing slash)\n *\n * @returns A client with the specified scope (category/base directory)\n *\n * @example\n * remoteStorage.scope('/pictures/').getListing('');\n * remoteStorage.scope('/public/pictures/').getListing('');\n */\n scope (path: string): BaseClient {\n if (typeof(path) !== 'string') {\n throw 'Argument \\'path\\' of baseClient.scope must be a string';\n }\n if (!this.access.checkPathPermission(path, 'r')) {\n console.warn('WARNING: Please use remoteStorage.access.claim() to ask for access permissions first: https://remotestoragejs.readthedocs.io/en/latest/js-api/access.html#claim');\n }\n return new BaseClient(this, path);\n }\n\n /**\n * Get the value of the sync interval when application is in the foreground\n *\n * @returns A number of milliseconds\n *\n * @example\n * remoteStorage.getSyncInterval();\n * // 10000\n */\n getSyncInterval (): number {\n return config.syncInterval;\n }\n\n /**\n * Set the value of the sync interval when application is in the foreground\n *\n * @param interval - Sync interval in milliseconds (between 2000 and 3600000 [1 hour])\n *\n * @example\n remoteStorage.setSyncInterval(20000);\n */\n setSyncInterval (interval: number): void {\n if (!isValidInterval(interval)) {\n throw interval + \" is not a valid sync interval\";\n }\n const oldValue = config.syncInterval;\n config.syncInterval = interval;\n\n this._emit('sync-interval-change', {\n oldValue: oldValue,\n newValue: interval\n });\n }\n\n /**\n * Get the value of the sync interval when application is in the background\n *\n * @returns A number of milliseconds\n *\n * @example\n * remoteStorage.getBackgroundSyncInterval();\n * // 60000\n */\n getBackgroundSyncInterval (): number {\n return config.backgroundSyncInterval;\n }\n\n /**\n * Set the value of the sync interval when the application is in the\n * background\n *\n * @param interval - Sync interval in milliseconds (between 2000 and 3600000 [1 hour])\n *\n * @example\n * remoteStorage.setBackgroundSyncInterval(90000);\n */\n setBackgroundSyncInterval (interval: number): void {\n if (!isValidInterval(interval)) {\n throw interval + \" is not a valid sync interval\";\n }\n const oldValue = config.backgroundSyncInterval;\n config.backgroundSyncInterval = interval;\n\n this._emit('sync-interval-change', {\n oldValue: oldValue,\n newValue: interval\n });\n }\n\n /**\n * Get the value of the current sync interval. Can be background or\n * foreground, custom or default.\n *\n * @returns number of milliseconds\n *\n * @example\n * remoteStorage.getCurrentSyncInterval();\n * // 15000\n */\n getCurrentSyncInterval (): number {\n return config.isBackground ? config.backgroundSyncInterval : config.syncInterval;\n }\n\n /**\n * Get the value of the current network request timeout\n *\n * @returns A number of milliseconds\n *\n * @example\n * remoteStorage.getRequestTimeout();\n * // 30000\n */\n getRequestTimeout (): number {\n return config.requestTimeout;\n }\n\n /**\n * Set the timeout for network requests.\n *\n * @param timeout - Timeout in milliseconds\n *\n * @example\n * remoteStorage.setRequestTimeout(30000);\n */\n setRequestTimeout (timeout: number): void {\n if (typeof timeout !== 'number') {\n throw timeout + \" is not a valid request timeout\";\n }\n config.requestTimeout = timeout;\n }\n\n /**\n * TODO: document\n * @internal\n */\n syncCycle (): void {\n if (!this.sync || this.sync.stopped) { return; }\n\n this.on('sync-done', (): void => {\n // FIXME Re-enable when modules are all imports\n // log('[Sync] Sync done. Setting timer to', this.getCurrentSyncInterval());\n if (this.sync && !this.sync.stopped) {\n if (this._syncTimer) {\n clearTimeout(this._syncTimer);\n this._syncTimer = undefined;\n }\n this._syncTimer = setTimeout(this.sync.sync.bind(this.sync), this.getCurrentSyncInterval());\n }\n });\n\n this.sync.sync();\n }\n\n /**\n * Start synchronization with remote storage, downloading and uploading any\n * changes within the cached paths.\n *\n * Please consider: local changes will attempt sync immediately, and remote\n * changes should also be synced timely when using library defaults. So\n * this is mostly useful for letting users sync manually, when pressing a\n * sync button for example. This might feel safer to them sometimes, esp.\n * when shifting between offline and online a lot.\n *\n * @returns A Promise which resolves when the sync has finished\n */\n startSync (): Promise {\n if (!config.cache) {\n console.warn('Nothing to sync, because caching is disabled.');\n return Promise.resolve();\n }\n this.sync.stopped = false;\n this.syncStopped = false;\n return this.sync.sync();\n }\n\n /**\n * Stop the periodic synchronization.\n */\n stopSync (): void {\n clearTimeout(this._syncTimer);\n this._syncTimer = undefined;\n\n if (this.sync) {\n // FIXME Re-enable when modules are all imports\n // log('[Sync] Stopping sync');\n this.sync.stopped = true;\n } else {\n // The sync class has not been initialized yet, so we make sure it will\n // not start the syncing process as soon as it's initialized.\n // FIXME Re-enable when modules are all imports\n // log('[Sync] Will instantiate sync stopped');\n this.syncStopped = true;\n }\n }\n\n /**\n * Add remoteStorage data module\n *\n * @param module - A data module object\n *\n * @example\n *\n * Usually, you will import your data module from either a package or a local path.\n * Let's say you want to use the\n * [bookmarks module](https://github.com/raucao/remotestorage-module-bookmarks)\n * in order to load data stored from [Webmarks](https://webmarks.5apps.com) for\n * example:\n *\n * ```js\n * import Bookmarks from 'remotestorage-module-bookmarks';\n *\n * remoteStorage.addModule(Bookmarks);\n * ```\n *\n * You can also forgo this function entirely and add modules when creating your\n * remoteStorage instance:\n *\n * ```js\n * const remoteStorage = new RemoteStorage({ modules: [ Bookmarks ] });\n * ```\n *\n * After the module has been added, it can be used like so:\n *\n * ```js\n * remoteStorage.bookmarks.archive.getAll(false)\n * .then(bookmarks => console.log(bookmarks));\n * ```\n */\n addModule (module: RSModule): void {\n const moduleName = module.name;\n const moduleBuilder = module.builder;\n\n Object.defineProperty(this, moduleName, {\n configurable: true,\n get: function () {\n const instance = this._loadModule(moduleName, moduleBuilder);\n Object.defineProperty(this, moduleName, {\n value: instance\n });\n return instance;\n }\n });\n\n if (moduleName.indexOf('-') !== -1) {\n const camelizedName = moduleName.replace(/\\-[a-z]/g, function (s) {\n return s[1].toUpperCase();\n });\n\n Object.defineProperty(this, camelizedName, {\n get: function () {\n return this[moduleName];\n }\n });\n }\n }\n\n /**\n * Load module\n *\n * @private\n */\n _loadModule (moduleName: string, moduleBuilder): { [key: string]: unknown } {\n if (moduleBuilder) {\n const module = moduleBuilder(\n new BaseClient(this, '/' + moduleName + '/'),\n new BaseClient(this, '/public/' + moduleName + '/')\n );\n return module.exports;\n } else {\n throw \"Unknown module: \" + moduleName;\n }\n }\n}\n\n/**\n * @property access\n *\n * Tracking claimed access scopes. A instance.\n*/\nObject.defineProperty(RemoteStorage.prototype, 'access', {\n get: function() {\n const access = new Access();\n Object.defineProperty(this, 'access', {\n value: access\n });\n return access;\n },\n configurable: true\n});\n\n// TODO Clean up/harmonize how modules are loaded and/or document this architecture properly\n//\n// At this point the remoteStorage object has not been created yet.\n// Only its prototype exists so far, so we define a self-constructing\n// property on there:\n\n/**\n * Property: caching\n *\n * Caching settings. A instance.\n */\n// FIXME Was in rs_init of Caching but don't want to require RemoteStorage from there.\nObject.defineProperty(RemoteStorage.prototype, 'caching', {\n configurable: true,\n get: function () {\n const caching = new Caching();\n Object.defineProperty(this, 'caching', {\n value: caching\n });\n return caching;\n }\n});\n\nexport interface RemoteStorage extends EventHandling {}\napplyMixins(RemoteStorage, [EventHandling]);\n\nexport default RemoteStorage;\n","/**\n * This file implements an HTTP request with timeout, on top of fetch or XHR.\n * The returned value always looks like an XHR.\n * It is used by authorize.ts, wireclient.ts, googledrive.ts and dropbox.ts.\n * The timeout is set by RemoteStorage#setRequestTimeout(timeout)\n */\n\nimport log from \"./log\";\nimport config from \"./config\";\n\n\n/**\n * Extracts a retry interval from header,\n * defaulting to three tries and a pause, within sync interval\n * */\nexport function retryAfterMs(xhr: XMLHttpRequest): number {\n const serverMs = parseInt(xhr.getResponseHeader('Retry-After')) * 1000;\n if (serverMs >= 1000) { // sanity check\n return serverMs;\n } else { // value is NaN if no such header, or malformed\n // three tries and a pause, within sync interval,\n // with lower & upper bounds\n return Math.max(1500, Math.min(60_000, Math.round(config.syncInterval / (2.9 + Math.random() * 0.2))));\n }\n}\n\nexport let isArrayBufferView: { (arg0: unknown): any; (object: any): boolean; (object: any): boolean };\n\nif (typeof ((global || window as any).ArrayBufferView) === 'function') {\n isArrayBufferView = function (object) {\n return object && (object instanceof (global || window as any).ArrayBufferView);\n };\n} else {\n const arrayBufferViews = [\n Int8Array, Uint8Array, Int16Array, Uint16Array,\n Int32Array, Uint32Array, Float32Array, Float64Array\n ];\n isArrayBufferView = function (object): boolean {\n for (let i = 0; i < 8; i++) {\n if (object instanceof arrayBufferViews[i]) {\n return true;\n }\n }\n return false;\n };\n}\n\n\nexport interface RequestOptions {\n body?: XMLHttpRequestBodyInit;\n headers?: HeadersInit;\n responseType?: XMLHttpRequestResponseType;\n}\n\nexport async function requestWithTimeout(method: string, url: string, options: RequestOptions): Promise {\n if (typeof fetch === 'function') {\n return _fetchRequestWithTimeout(method, url, options);\n } else if (typeof XMLHttpRequest === 'function') {\n return _xhrRequestWithTimeout(method, url, options);\n } else {\n return Promise.reject('[Requests] You need to add a polyfill for fetch or XMLHttpRequest');\n }\n}\n\nasync function _fetchRequestWithTimeout(method: string, url: string, options: RequestOptions): Promise {\n const abortController = typeof AbortController === 'function' ?\n new AbortController() :\n null;\n let timeoutId;\n\n const timeoutPromise: Promise = new Promise((_resolve, reject) => {\n timeoutId = setTimeout(() => {\n if (abortController) {\n abortController.abort();\n }\n reject('timeout');\n }, config.requestTimeout);\n });\n\n let syntheticXhr;\n const responseHeaders = {};\n\n const networkPromise: Promise = fetch(url, {\n method: method,\n headers: options.headers,\n body: options.body,\n signal: abortController ? abortController.signal : undefined\n }).then((response) => {\n log('[requests fetch]', response);\n\n response.headers.forEach((value: string, headerName: string) => {\n responseHeaders[headerName.toUpperCase()] = value;\n });\n\n syntheticXhr = {\n readyState: 4,\n status: response.status,\n statusText: response.statusText,\n response: undefined,\n getResponseHeader: (headerName: string): string => {\n return responseHeaders[headerName.toUpperCase()] || null;\n },\n // responseText: 'foo',\n responseType: options.responseType,\n responseURL: url,\n };\n switch (options.responseType) {\n case 'arraybuffer':\n return response.arrayBuffer();\n case 'blob':\n return response.blob();\n case 'json':\n return response.json();\n case undefined:\n case '':\n case 'text':\n return response.text();\n default: // document\n throw new Error(\"responseType 'document' is not currently supported using fetch\");\n }\n }).then((processedBody) => {\n syntheticXhr.response = processedBody;\n if (!options.responseType || options.responseType === 'text') {\n syntheticXhr.responseText = processedBody;\n }\n return syntheticXhr;\n }).finally(() => {\n clearTimeout(timeoutId);\n });\n\n return Promise.race([networkPromise, timeoutPromise]);\n}\n\nasync function _xhrRequestWithTimeout(method: string, url: string, options: RequestOptions): Promise {\n return new Promise((resolve, reject) => {\n\n log('[requests XHR]', method, url);\n\n let timedOut = false;\n\n const timer = setTimeout(() => {\n timedOut = true;\n reject('timeout');\n }, config.requestTimeout);\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url, true);\n\n if (options.responseType) {\n xhr.responseType = options.responseType;\n }\n\n if (options.headers) {\n for (const key in options.headers) {\n xhr.setRequestHeader(key, options.headers[key]);\n }\n }\n\n xhr.onload = (): void => {\n if (timedOut) {\n return;\n }\n clearTimeout(timer);\n resolve(xhr);\n };\n\n xhr.onerror = (error): void => {\n if (timedOut) {\n return;\n }\n clearTimeout(timer);\n reject(error);\n };\n\n let body = options.body;\n\n if (typeof (body) === 'object' && !isArrayBufferView(body) && body instanceof ArrayBuffer) {\n body = new Uint8Array(body);\n }\n xhr.send(body);\n });\n}\n","/**\n * A cache which can propagate changes up to parent folders and generate new\n * revision ids for them. The generated revision id is consistent across\n * different sessions. The keys for the cache are case-insensitive.\n *\n * @param defaultValue {string} the value that is returned for all keys that\n * don't exist in the cache\n * @class\n */\n\nclass RevisionCache {\n defaultValue: string;\n\n private _itemsRev: { [key: string]: any } = {};\n private _storage: { [key: string]: string } = {};\n private _canPropagate = false;\n\n constructor(defaultValue: string) {\n this.defaultValue = defaultValue;\n this.activatePropagation();\n }\n\n\n /**\n * Get a value from the cache or defaultValue, if the key is not in the\n * cache\n */\n get(key: string): string {\n key = key.toLowerCase();\n let stored = this._storage[key];\n if (typeof stored === 'undefined') {\n stored = this.defaultValue;\n this._storage[key] = stored;\n }\n return stored;\n }\n\n /**\n * Set a value\n */\n set(key: string, value): unknown {\n key = key.toLowerCase();\n if (this._storage[key] === value) {\n return value;\n }\n this._storage[key] = value;\n if (!value) {\n delete this._itemsRev[key];\n }\n this._updateParentFolderItemRev(key, value);\n if (this._canPropagate) {\n this._propagate(key);\n }\n return value;\n }\n\n /**\n * Delete a value\n */\n delete(key: string): unknown {\n return this.set(key, null);\n }\n\n /**\n * Disables automatic update of folder revisions when a key value is updated\n */\n deactivatePropagation(): true {\n this._canPropagate = false;\n return true;\n }\n\n /**\n * Enables automatic update of folder revisions when a key value is updated\n * and refreshes the folder revision ids for entire tree.\n */\n activatePropagation(): true {\n if (this._canPropagate) {\n return true;\n }\n this._generateFolderRev(\"/\");\n this._canPropagate = true;\n return true;\n }\n\n /**\n * Returns a hash code for a string.\n */\n private _hashCode(str: string): number {\n let hash = 0;\n if (str.length === 0) {\n return hash;\n }\n for (let i = 0; i < str.length; i++) {\n const chr = str.charCodeAt(i);\n // eslint-disable-next-line no-bitwise\n hash = ((hash << 5) - hash) + chr;\n // eslint-disable-next-line no-bitwise\n hash |= 0; // Convert to 32bit integer\n }\n return hash;\n }\n\n /**\n * Takes an array of strings and returns a hash of the items\n */\n private _generateHash(items: string[]): string {\n // We sort the items before joining them to ensure correct hash generation\n // every time\n const files = items.sort().join('|');\n const hash = \"\" + this._hashCode(files);\n return hash;\n }\n\n /**\n * Update the revision of a key in it's parent folder data\n */\n private _updateParentFolderItemRev(key: string, rev): void {\n if (key !== '/') {\n const parentFolder = this._getParentFolder(key);\n if (!this._itemsRev[parentFolder]) {\n this._itemsRev[parentFolder] = {};\n }\n const parentFolderItemsRev = this._itemsRev[parentFolder];\n if (!rev) {\n delete parentFolderItemsRev[key];\n } else {\n parentFolderItemsRev[key] = rev;\n }\n //reset revision until root\n this._updateParentFolderItemRev(parentFolder, this.defaultValue);\n }\n }\n\n private _getParentFolder(key: string): string {\n return key.substr(0, key.lastIndexOf('/', key.length - 2) + 1);\n }\n\n /**\n * Propagate the changes to the parent folders and generate new revision ids\n * for them\n */\n private _propagate(key: string): void {\n if (key !== '/') {\n const parentFolder = this._getParentFolder(key);\n const parentFolderItemsRev = this._itemsRev[parentFolder];\n const hashItems = [];\n for (const path in parentFolderItemsRev) {\n hashItems.push(parentFolderItemsRev[path]);\n }\n const newRev = this._generateHash(hashItems);\n this.set(parentFolder, newRev);\n }\n }\n\n /**\n * Generate revision id for a folder and it's subfolders, by hashing it's\n * listing\n */\n private _generateFolderRev(folder: string): string {\n const itemsRev = this._itemsRev[folder];\n let hash = this.defaultValue;\n if (itemsRev) {\n const hashItems = [];\n for (const path in itemsRev) {\n const isDir: boolean = (path.substr(-1) === '/');\n let hashItem;\n if (isDir) {\n hashItem = this._generateFolderRev(path);\n } else {\n hashItem = itemsRev[path];\n }\n hashItems.push(hashItem);\n }\n if (hashItems.length > 0) {\n hash = this._generateHash(hashItems);\n }\n }\n this.set(folder, hash);\n return hash;\n }\n}\n\nexport = RevisionCache;\n","class SchemaNotFound extends Error {\n constructor(uri: string) {\n super();\n const error = new Error(\"Schema not found: \" + uri);\n error.name = \"SchemaNotFound\";\n return error;\n }\n}\n\nexport = SchemaNotFound;\n","import {\n InMemoryStorage,\n Session\n} from \"@inrupt/solid-client-authn-browser\";\nimport {\n getFile, overwriteFile, getContentType,\n getPodUrlAll, deleteFile, getContainedResourceUrlAll, getSolidDataset,\n FetchError, UrlString,\n getThing, getInteger, getDatetime, getDecimal\n} from \"@inrupt/solid-client\";\nimport BaseClient from './baseclient';\nimport EventHandling from './eventhandling';\nimport {\n cleanPath,\n applyMixins,\n getJSONFromLocalStorage,\n localStorageAvailable\n} from './util';\nimport {Remote, RemoteBase, RemoteResponse, RemoteSettings} from \"./remote\";\nimport { ConfigObserver } from \"./interfaces/configObserver\";\nimport ConfigStorage from \"./solidStorage\";\nimport Blob from \"blob\";\n\nconst SETTINGS_KEY = 'remotestorage:solid';\n\nlet hasLocalStorage;\n\n/**\n * Overwrite BaseClient's getItemURL with our own implementation\n *\n * @param {object} rs - RemoteStorage instance\n *\n * @private\n */\nfunction hookGetItemURL (rs): void {\n if (rs._origBaseClientGetItemURL) { return; }\n rs._origBaseClientGetItemURL = BaseClient.prototype.getItemURL;\n BaseClient.prototype.getItemURL = function (path: string): string {\n console.log('getItemURL from', path);\n if (typeof path !== 'string') {\n throw 'Argument \\'path\\' of baseClient.getItemURL must be a string';\n }\n if (this.storage.connected) {\n if (path.startsWith('/')) {\n path = path.substring(1);\n }\n console.log('getItemURL to', this.selectedPodURL + cleanPath(path));\n return this.selectedPodURL + cleanPath(path);\n } else {\n return undefined;\n }\n };\n}\n\n/**\n * Restore BaseClient's getItemURL original implementation\n *\n * @param {object} rs - RemoteStorage instance\n *\n * @private\n */\nfunction unHookGetItemURL (rs): void {\n if (!rs._origBaseClientGetItemURL) { return; }\n BaseClient.prototype.getItemURL = rs._origBaseClientGetItemURL;\n delete rs._origBaseClientGetItemURL;\n}\n\n/**\n * Convert XMLHttpRequestBodyInit to Blob\n *\n * @param {XMLHttpRequestBodyInit} body - Request body\n * @returns {Blob} Blob equivalent of the body\n * \n * @private\n */\nfunction requestBodyToBlob(body: XMLHttpRequestBodyInit): Blob {\n if (typeof(body) === 'object') {\n if (body instanceof Blob) {\n return body;\n }\n if (body instanceof DataView) {\n return new Blob([ body ], { type : \"application/octet-stream\" });\n }\n if (body instanceof ArrayBuffer) {\n return new Blob([ new DataView(body) ]);\n }\n if (ArrayBuffer.isView(body)) {\n return new Blob([ body ], { type : \"application/octet-stream\" });\n }\n if (body instanceof FormData) {\n return new Blob([ new URLSearchParams([JSON.parse(JSON.stringify(body.entries()))]).toString() ],\n { type : 'application/x-www-form-urlencoded' });\n }\n if (body instanceof URLSearchParams) {\n return new Blob([ body.toString() ], { type : 'application/x-www-form-urlencoded' });\n }\n }\n if (typeof(body) === \"string\") {\n return new Blob([ body ], { type : 'plain/text' });\n }\n \n return new Blob([ JSON.stringify(body) ], { type : 'application/json' });\n}\n\n/**\n * @class Solid\n *\n * To use this backend, you need to specify the authURL before calling connect like so:\n * \n * @example\n * solid.setAuthURL('https://login.example.com');\n * solid.connect();\n * \n * If connect is successful a list of available pods for the Solid account is retrieved and\n * a `pod-not-selected` event is fired. After receiving this event you have to call getPodURLs\n * to get the list of available pods and set one of them to be used by calling setPodURL. After\n * setting the pod URL the `connected` event is fired.\n * \n * You can find a list of running solid servers on the solid project website here:\n * https://solidproject.org/for-developers#hosted-pod-services\n**/\nclass Solid extends RemoteBase implements Remote, ConfigObserver {\n authURL: string;\n podURLs: string[] = null;\n selectedPodURL: string;\n sessionProperties: object;\n configStorage: ConfigStorage;\n session: Session;\n\n constructor(remoteStorage) {\n super(remoteStorage);\n console.log('Solid constructor');\n this.online = true;\n this.addEvents(['connected', 'not-connected', 'pod-not-selected']);\n \n // We use a custom ConfigStore to store the solid session in a rs friendly manner to\n // make configuration and disconnect work.\n this.configStorage = new ConfigStorage(this);\n this.session = new Session({\n secureStorage: new InMemoryStorage(), // Inrupt prefers InMemoryStorage for tokens. We respect that.\n insecureStorage: this.configStorage\n }, 'any');\n\n hasLocalStorage = localStorageAvailable();\n\n if (hasLocalStorage){\n const settings = getJSONFromLocalStorage(SETTINGS_KEY);\n if (settings) {\n this.configure(settings);\n }\n }\n }\n\n /**\n * Solid Session storage state changed.\n * \n * This function is called by the ConfigStore that we provided to Session as an insecure storage.\n * \n * @param {string} config - The entire Session configuration object serialized into a string\n * \n * @private\n */\n onConfigChanged(config: string): void {\n if (config) {\n const sessionConfig = JSON.parse(config);\n\n if (typeof sessionConfig.clientSecret !== 'undefined') {\n let settings = getJSONFromLocalStorage(SETTINGS_KEY);\n\n if (!settings) {\n settings = { };\n }\n\n settings.href = this.authURL;\n settings.properties = {\n sessionProperties: sessionConfig,\n podURL: this.selectedPodURL\n };\n\n this.sessionProperties = sessionConfig;\n\n localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));\n return;\n }\n }\n\n this.podURLs = null;\n localStorage.removeItem(SETTINGS_KEY);\n }\n\n /**\n * Configure the Solid backend.\n *\n * @param {Object} settings\n * @param {string} [settings.userAddress] - The user's identity prodiver URL\n * @param {string} [settings.href] - The authURL\n * @param {object} [settings.properties] - All storage for Inrupt session is saved into properties plus the pod URL\n *\n * @protected\n */\n configure (settings: RemoteSettings) {\n // We only update this.userAddress if settings.userAddress is set to a string or to null\n if (typeof settings.userAddress !== 'undefined') { this.userAddress = settings.userAddress; }\n // We only update this.authURL if settings.href is set to a string or to null\n if (typeof settings.href !== 'undefined') { this.authURL = settings.href; }\n // Read session properties and pod URL from the properties if it exists\n if (typeof settings.properties !== 'undefined') {\n const properties = settings.properties as {sessionProperties: object, podURL: string};\n\n if (properties) {\n if (typeof properties.sessionProperties !== 'undefined') {\n this.sessionProperties = properties.sessionProperties;\n }\n else {\n this.sessionProperties = null;\n }\n if (typeof properties.podURL !== 'undefined') {\n this.selectedPodURL = properties.podURL;\n }\n else {\n this.selectedPodURL = null;\n }\n }\n else {\n this.sessionProperties = null;\n this.selectedPodURL = null;\n }\n }\n\n const writeSettingsToCache = function() {\n if (hasLocalStorage) {\n localStorage.setItem(SETTINGS_KEY, JSON.stringify({\n userAddress: this.userAddress,\n href: this.authURL,\n properties: {\n sessionProperties: this.sessionProperties,\n podURL: this.selectedPodURL\n }\n }));\n }\n };\n\n const handleError = function() {\n this.connected = false;\n this.sessionProperties = null;\n this.podURLs = null;\n if (hasLocalStorage) {\n localStorage.removeItem(SETTINGS_KEY);\n }\n };\n\n if (this.sessionProperties) {\n this.configStorage.setConfig(JSON.stringify(this.sessionProperties));\n this.connected = this.session.info && this.session.info.isLoggedIn;\n writeSettingsToCache.apply(this);\n } else {\n handleError.apply(this);\n }\n }\n\n /**\n * Set the auth URL\n * \n * @param {string} authURL - Auth URL\n * \n * @public\n */\n setAuthURL(authURL: string): void {\n this.authURL = authURL;\n }\n\n /**\n * Get a list of pod URLs for this Solid account.\n * \n * If the Solid Session is not connected, this function returns null.\n * \n * @returns Get the list of pod URLs\n * \n * @public\n */\n getPodURLs(): string[] | null {\n return this.podURLs;\n }\n\n /**\n * Set the pod URL to use as the storage.\n * \n * Pod URL must be one of the URLs provided by the getPodURLs function. This function does\n * not validate this constraint.\n * \n * If the Solid Session is connected and the pod URL is updated to be null, a\n * `pod-not-selected` event will be fired. If Session is connected and the pod URL is set,\n * a `connected` event will be fired.\n * \n * @param {string} podURL - URL of the pod to be used as storage\n * \n * @public\n */\n setPodURL(podURL: string): void {\n if (this.selectedPodURL === podURL) {\n return;\n }\n\n this.selectedPodURL = podURL;\n\n if (this.session.info && this.session.info.isLoggedIn) {\n if (this.selectedPodURL) {\n let settings = getJSONFromLocalStorage(SETTINGS_KEY);\n if (!settings) {\n settings = { };\n }\n \n settings.userAddress = this.session.info.webId;\n settings.href = this.authURL;\n settings.properties = {\n sessionProperties: this.sessionProperties,\n podURL: this.selectedPodURL\n };\n \n localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));\n \n this.connected = true;\n this._emit('connected');\n }\n else {\n this.connected = false;\n this.rs._emit('pod-not-selected');\n }\n }\n }\n\n /**\n * Get the pod URL that is being used as the storage.\n * \n * @returns {string} The in-use pod URL or null\n * \n * @public\n */\n getPodURL(): string {\n return this.selectedPodURL;\n }\n\n /**\n * Initiate the authorization flow's OAuth dance.\n * \n * @public\n */\n connect (): void {\n this.rs.setBackend('solid');\n \n if (!this.authURL) {\n this.rs._emit('error', new Error(`No authURL is configured.`));\n return;\n }\n\n this.session.login({\n oidcIssuer: this.authURL,\n redirectUrl: new URL(\"/\", window.location.href).toString(),\n clientName: \"Remote Storage\"\n });\n }\n\n /**\n * Get the connected Solid session\n * \n * @returns {Session} that is being used by this instance or null if Session is not connected\n * \n * @public\n */\n getSession(): Session {\n return (this.session.info && this.session.info.isLoggedIn)?this.session:null;\n }\n\n /**\n * Convert path to file URL\n *\n * @param {string} path - Path of the resource\n * @returns {string} Full URL of the resource on the pod\n * \n * @private\n */\n getFileURL(path: string): string {\n if (path.startsWith('/')) {\n path = path.substring(1);\n }\n if (path.length === 0) {\n path = '/';\n }\n return this.selectedPodURL + path;\n }\n\n /**\n * Request a resource (file or directory).\n *\n * @param {string} path - Path of the resource\n * @param {Object} options - Request options\n * @returns {Promise} Resolves with an object containing the status code,\n * body, content-type and revision\n *\n * @protected\n */\n get (path: string, options: { ifNoneMatch?: string } = {}): Promise {\n console.log('Solid get', path, options);\n const fileURL = this.getFileURL(path);\n\n if (path.slice(-1) === '/') {\n return getSolidDataset(fileURL, { fetch: this.session.fetch }).then(containerDataset => {\n console.log('container data set', containerDataset);\n const URLs: UrlString[] = getContainedResourceUrlAll(containerDataset);\n const listing = URLs.reduce((map, item) => {\n const itemName = item.substring(fileURL.length);\n const fileDataset = getThing(containerDataset, item);\n map[itemName] = {\n 'ETag': getDecimal(fileDataset, 'http://www.w3.org/ns/posix/stat#mtime').toString(),\n 'Last-Modified': getDatetime(fileDataset, 'http://purl.org/dc/terms/modified').toUTCString(), // date.toUTCString()\n }; // We are skipping ETag\n \n const isFolder = itemName.slice(-1) === '/';\n if (!isFolder) {\n map[itemName]['Content-Length'] = getInteger(fileDataset, 'http://www.w3.org/ns/posix/stat#size');\n }\n\n return map;\n }, { });\n \n return Promise.resolve({\n statusCode: 200,\n body: listing,\n contentType: 'application/json; charset=UTF-8',\n // revision: ? Skipping ETag\n } as RemoteResponse);\n }).catch(error => {\n if (error instanceof FetchError) {\n if (error.statusCode === 404) {\n return Promise.resolve({\n statusCode: 200,\n body: { },\n contentType: 'application/json; charset=UTF-8',\n // revision: ?\n } as RemoteResponse);\n }\n }\n\n return Promise.reject('Failed to get container: ' + error.message);\n });\n }\n\n return getFile(fileURL, { fetch: this.session.fetch}).then(async file => {\n return {\n statusCode: 200,\n body: await file.text(),\n contentType: getContentType(file)\n } as RemoteResponse;\n }).catch(error => {\n const statusCode = error.statusCode;\n\n if (statusCode === 401 || statusCode === 403 || statusCode === 404) {\n return {\n statusCode: statusCode\n } as RemoteResponse;\n }\n\n return Promise.reject('Failed to get the file: ' + error.message);\n });\n }\n\n /**\n * Create or update a file.\n *\n * @param {string} path - File path\n * @param body - File content\n * @param {string} contentType - File content-type\n * @param {Object} options\n * @param {string} options.ifNoneMatch - Only create or update the file if the\n * current ETag doesn't match this string\n * @returns {Promise} Resolves with an object containing the status code,\n * content-type and revision\n *\n * @protected\n */\n put (path: string, body: XMLHttpRequestBodyInit, contentType: string, options: { ifMatch?: string; ifNoneMatch?: string } = {}): Promise {\n console.log('Solid put', path, contentType);\n\n const fileURL = this.getFileURL(path);\n const fetch = this.session.fetch;\n\n const overwrite = function(): Promise {\n const blob = requestBodyToBlob(body);\n return overwriteFile(fileURL, blob, {\n contentType: contentType,\n fetch: fetch\n }).then(savedFile => {\n return {\n statusCode: 201\n } as RemoteResponse;\n }).catch(error => {\n return Promise.reject(\"PUT failed with status \" + error.statusCode + \" (\" + error.message + \")\");\n });\n };\n\n return getFile(fileURL, { fetch: fetch}).then(file => {\n if (options && (options.ifNoneMatch === '*')) {\n return {statusCode: 412, revision: 'conflict'} as RemoteResponse;\n }\n\n return overwrite();\n }).catch(error => {\n const statusCode = error.statusCode;\n\n if (statusCode === 404) {\n return overwrite();\n }\n\n return Promise.reject(\"PUT failed with status \" + statusCode + \" (\" + error.message + \")\");\n });\n }\n\n /**\n * Delete a file.\n *\n * @param {string} path - File path\n * @param {Object} options\n * @param {string} options.ifMatch - only delete the file if it's ETag\n * matches this string\n * @returns {Promise} Resolves with an object containing the status code\n *\n * @protected\n */\n delete (path: string, options: { ifMatch?: string } = {}): Promise {\n console.log('Solid delete', path);\n const fileURL = this.getFileURL(path);\n\n return deleteFile(fileURL, { fetch: this.session.fetch }).then(() => {\n return {statusCode: 200} as RemoteResponse;\n }).catch(error => {\n const statusCode = error.statusCode;\n\n if (statusCode === 404) {\n return {statusCode: 200} as RemoteResponse;\n }\n\n return Promise.reject(\"DELETE failed with status \" + statusCode + \" (\" + error.message + \")\");\n });\n }\n\n /**\n * Initialize the Solid backend.\n *\n * @param {Object} remoteStorage - RemoteStorage instance\n *\n * @protected\n */\n static _rs_init (remoteStorage): void {\n const solid = new Solid(remoteStorage);\n remoteStorage.solid = solid;\n if (remoteStorage.backend === 'solid') {\n remoteStorage._origRemote = remoteStorage.remote;\n remoteStorage.remote = remoteStorage.solid;\n\n hookGetItemURL(remoteStorage);\n\n (async () => {\n const session = solid.session;\n await session.handleIncomingRedirect();\n if (session.info.isLoggedIn) {\n const webId = session.info.webId;\n solid.userAddress = webId;\n\n if (solid.selectedPodURL) {\n solid._emit('connected');\n }\n else {\n solid.podURLs = await getPodUrlAll(webId, { fetch: fetch });\n remoteStorage._emit('pod-not-selected');\n }\n }\n else if (solid.sessionProperties) {\n solid.connect();\n }\n })();\n }\n }\n\n /**\n * Inform about the availability of the Solid backend.\n *\n * @returns {Boolean}\n *\n * @protected\n */\n static _rs_supported (): boolean {\n return true;\n }\n\n /**\n * Remove Solid as a backend.\n *\n * @param {Object} remoteStorage - RemoteStorage instance\n *\n * @protected\n */\n static _rs_cleanup (remoteStorage): void {\n remoteStorage.setBackend(undefined);\n if (remoteStorage._origRemote) {\n remoteStorage.remote = remoteStorage._origRemote;\n delete remoteStorage._origRemote;\n }\n unHookGetItemURL(remoteStorage);\n }\n}\n\napplyMixins(Solid, [EventHandling]);\n\nexport = Solid;\n","import {\n IStorage,\n} from \"@inrupt/solid-client-authn-browser\";\nimport { ConfigObserver } from \"./interfaces/configObserver\";\n\n/**\n * @class BrowserStorage\n * \n * Mirror of BrowserStorage that is defined (but not exported) in the Inrupt\n * library.\n */\nclass BrowserStorage implements IStorage {\n get storage(): typeof window.localStorage {\n return window.localStorage;\n }\n\n async get(key: string): Promise {\n return this.storage.getItem(key) || undefined;\n }\n\n async set(key: string, value: string): Promise {\n this.storage.setItem(key, value);\n }\n\n async delete(key: string): Promise {\n this.storage.removeItem(key);\n }\n}\n\n/**\n * @class ConfigStorage\n * \n * An implementation for the Inrupt's IStorage that bypasses storing of the\n * session information to the ConfigObserver i.e. Solid backend.\n */\nexport default class ConfigStorage implements IStorage {\n private browserStorage: BrowserStorage = new BrowserStorage();\n private config: string;\n private observer: ConfigObserver;\n\n constructor(observer: ConfigObserver) {\n this.observer = observer;\n }\n\n /**\n * Information specific to the user session are stored using this prefix.\n * Caution: This is a bit hacky. Inrupt stores different sorts of data and\n * does not differentiate between them and the session specific one. Saving\n * all that as the backend config is expensive and invalid. This key\n * constant is taken from Inrupt's private code here:\n * https://github.com/inrupt/solid-client-authn-js/blob/a34357598cc218be116e38f66a983e391dc1d6b2/packages/core/src/storage/StorageUtility.ts#L150\n */\n private isConfigKey(key: string): boolean {\n return key.startsWith('solidClientAuthenticationUser');\n }\n\n public setConfig(config: string): void {\n this.config = config;\n }\n\n async get(key: string): Promise {\n if (this.isConfigKey(key)) {\n return this.config;\n }\n else {\n this.browserStorage.get(key);\n }\n }\n\n async set(key: string, value: string): Promise {\n if (this.isConfigKey(key)) {\n if (this.config) {\n const oldConfig = JSON.parse(this.config);\n const additionalConfig = JSON.parse(value);\n const newConfig = { ...oldConfig, ...additionalConfig };\n this.config = JSON.stringify(newConfig);\n }\n else {\n this.config = value;\n }\n this.observer.onConfigChanged(this.config);\n }\n else {\n this.browserStorage.set(key, value);\n }\n }\n\n async delete(key: string): Promise {\n if (this.isConfigKey(key)) {\n this.config = undefined;\n this.observer.onConfigChanged(this.config);\n }\n else {\n this.browserStorage.delete(key);\n }\n }\n}","class SyncError extends Error {\n originalError: Error;\n\n constructor (originalError: string | Error) {\n super();\n this.name = 'SyncError';\n this.message = 'Sync failed: ';\n if (typeof originalError === 'string') {\n this.message += originalError;\n } else {\n this.message += originalError.message;\n this.stack = originalError.stack;\n this.originalError = originalError;\n }\n }\n}\n\nexport = SyncError;\n","import type { RSNode, RSNodes } from './interfaces/rs_node';\nimport config from './config';\nimport Env from './env';\nimport EventHandling from './eventhandling';\nimport log from './log';\nimport Authorize from './authorize';\nimport SyncError from './sync-error';\nimport UnauthorizedError from './unauthorized-error';\nimport {\n applyMixins,\n deepClone,\n equal,\n isFolder,\n isDocument,\n pathsFromRoot\n} from './util';\n\nlet syncCycleCb, syncOnConnect;\n\ninterface ResponseStatus {\n statusCode: string | number;\n successful: boolean | undefined;\n conflict: boolean | undefined;\n unAuth: boolean | undefined;\n notFound: boolean | undefined;\n changed: boolean | undefined;\n networkProblems: boolean | undefined;\n}\n\ninterface SyncTask {\n action: any;\n path: string;\n promise: Promise;\n}\n\nfunction taskFor (action, path: string, promise: Promise): SyncTask {\n return { action, path, promise };\n}\n\nfunction nodeChanged (node: RSNode, etag: string): boolean {\n return node.common.revision !== etag &&\n (!node.remote || node.remote.revision !== etag);\n}\n\nfunction isStaleChild (node: RSNode): boolean {\n return node.remote && node.remote.revision && !node.remote.itemsMap && !node.remote.body;\n}\n\nfunction hasCommonRevision (node: RSNode): boolean {\n return node.common && node.common.revision;\n}\n\nfunction hasNoRemoteChanges (node: RSNode): boolean {\n if (node.remote && node.remote.revision &&\n node.remote.revision !== node.common.revision) {\n return false;\n }\n return (node.common.body === undefined && node.remote.body === false) ||\n (node.remote.body === node.common.body &&\n node.remote.contentType === node.common.contentType);\n}\n\nfunction mergeMutualDeletion (node: RSNode): RSNode {\n if (node.remote && node.remote.body === false &&\n node.local && node.local.body === false) {\n delete node.local;\n }\n return node;\n}\n\nfunction handleVisibility (env, rs): void {\n function handleChange (isForeground): void {\n const oldValue = rs.getCurrentSyncInterval();\n config.isBackground = !isForeground;\n const newValue = rs.getCurrentSyncInterval();\n rs._emit('sync-interval-change', {oldValue: oldValue, newValue: newValue});\n }\n env.on('background', () => handleChange(false));\n env.on('foreground', () => handleChange(true));\n}\n\n/**\n * This class basically does six things:\n *\n * - retrieve the remote version of relevant documents and folders\n * - add all local and remote documents together into one tree\n * - push local documents out if they don't exist remotely\n * - push local changes out to remote documents (conditionally, to avoid race\n * conditions where both have changed)\n * - adopt the local version of a document to its remote version if both exist\n * and they differ\n * - delete the local version of a document if it was deleted remotely\n * - if any GET requests were waiting for remote data, resolve them once this\n * data comes in.\n *\n * It does this using requests to documents and folders. Whenever a folder GET\n * comes in, it gives information about all the documents it contains (this is\n * the `markChildren` function).\n **/\nexport class Sync {\n // TODO remove when RS is defined, or if unnecessary\n rs: { [propName: string]: any };\n\n numThreads: number;\n done: boolean;\n stopped: boolean;\n\n // TODO define in more detail\n _tasks: object;\n _running: object;\n _timeStarted: object;\n _finishedTasks: Array = [];\n\n constructor (remoteStorage: object) {\n this.rs = remoteStorage;\n\n this._tasks = {};\n this._running = {};\n this._timeStarted = {};\n\n this.numThreads = 10;\n\n this.rs.local.onDiff(path => {\n this.addTask(path);\n this.doTasks();\n });\n\n this.rs.caching.onActivate((path: string): void => {\n this.addTask(path);\n this.doTasks();\n });\n\n this.addEvents(['done', 'req-done']);\n }\n\n public now (): number {\n return new Date().getTime();\n }\n\n public queueGetRequest (path: string): object {\n return new Promise((resolve, reject) => {\n if (!this.rs.remote.connected) {\n reject('cannot fulfill maxAge requirement - remote is not connected');\n } else if (!this.rs.remote.online) {\n reject('cannot fulfill maxAge requirement - remote is not online');\n } else {\n this.addTask(path, function (): void {\n this.rs.local.get(path).then(r => resolve(r));\n }.bind(this));\n\n this.doTasks();\n }\n });\n }\n\n // FIXME force02 sounds like rs spec 02, thus could be removed\n public corruptServerItemsMap (itemsMap, force02?: boolean): boolean {\n if ((typeof(itemsMap) !== 'object') || (Array.isArray(itemsMap))) {\n return true;\n }\n\n for (const itemName in itemsMap) {\n const item = itemsMap[itemName];\n\n if (typeof(item) !== 'object') {\n return true;\n }\n if (typeof(item.ETag) !== 'string') {\n return true;\n }\n if (isFolder(itemName)) {\n if (itemName.substring(0, itemName.length-1).indexOf('/') !== -1) {\n return true;\n }\n } else {\n if (itemName.indexOf('/') !== -1) {\n return true;\n }\n if (force02) {\n if (typeof(item['Content-Type']) !== 'string') {\n return true;\n }\n if (typeof(item['Content-Length']) !== 'number') {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n\n public corruptItemsMap (itemsMap): boolean {\n if ((typeof(itemsMap) !== 'object') || (Array.isArray(itemsMap))) {\n return true;\n }\n\n for (const path in itemsMap) {\n if (typeof itemsMap[path] !== 'boolean') {\n return true;\n }\n }\n\n return false;\n }\n\n public corruptRevision (rev): boolean {\n return ((typeof(rev) !== 'object') ||\n (Array.isArray(rev)) ||\n (rev.revision && typeof(rev.revision) !== 'string') ||\n (rev.body && typeof(rev.body) !== 'string' && typeof(rev.body) !== 'object') ||\n (rev.contentType && typeof(rev.contentType) !== 'string') ||\n (rev.contentLength && typeof(rev.contentLength) !== 'number') ||\n (rev.timestamp && typeof(rev.timestamp) !== 'number') ||\n (rev.itemsMap && this.corruptItemsMap(rev.itemsMap)));\n }\n\n public isCorrupt (node: RSNode): boolean {\n return ((typeof(node) !== 'object') ||\n (Array.isArray(node)) ||\n (typeof(node.path) !== 'string') ||\n (this.corruptRevision(node.common)) ||\n (node.local && this.corruptRevision(node.local)) ||\n (node.remote && this.corruptRevision(node.remote)) ||\n (node.push && this.corruptRevision(node.push)));\n }\n\n public hasTasks (): boolean {\n return Object.getOwnPropertyNames(this._tasks).length > 0;\n }\n\n public async collectDiffTasks (): Promise {\n let num = 0;\n\n return this.rs.local.forAllNodes((node: RSNode) => {\n if (num > 100) { return; }\n\n if (this.isCorrupt(node)) {\n log('[Sync] WARNING: corrupt node in local cache', node);\n if (typeof(node) === 'object' && node.path) {\n this.addTask(node.path);\n num++;\n }\n } else if (this.needsFetch(node) && this.rs.access.checkPathPermission(node.path, 'r')) {\n this.addTask(node.path);\n num++;\n } else if (isDocument(node.path) && this.needsPush(node) &&\n this.rs.access.checkPathPermission(node.path, 'rw')) {\n this.addTask(node.path);\n num++;\n }\n })\n .then((): number => num)\n .catch(e => { throw e; });\n }\n\n public inConflict (node: RSNode): boolean {\n return (node.local && node.remote &&\n (node.remote.body !== undefined || node.remote.itemsMap));\n }\n\n public needsRefresh (node: RSNode): boolean {\n if (node.common) {\n if (!node.common.timestamp) {\n return true;\n }\n return (this.now() - node.common.timestamp > config.syncInterval);\n }\n return false;\n }\n\n public needsFetch (node: RSNode): boolean {\n if (this.inConflict(node)) {\n return true;\n }\n if (node.common &&\n node.common.itemsMap === undefined &&\n node.common.body === undefined) {\n return true;\n }\n if (node.remote &&\n node.remote.itemsMap === undefined &&\n node.remote.body === undefined) {\n return true;\n }\n return false;\n }\n\n public needsPush (node: RSNode): boolean {\n if (this.inConflict(node)) {\n return false;\n }\n if (node.local && !node.push) {\n return true;\n }\n }\n\n public needsRemotePut (node: RSNode): boolean {\n return node.local && node.local.body;\n }\n\n public needsRemoteDelete (node: RSNode): boolean {\n return node.local && node.local.body === false;\n }\n\n public getParentPath (path: string): string {\n const parts = path.match(/^(.*\\/)([^\\/]+\\/?)$/);\n\n if (parts) {\n return parts[1];\n } else {\n throw new Error('Not a valid path: \"'+path+'\"');\n }\n }\n\n public deleteChildPathsFromTasks (): void {\n for (const path in this._tasks) {\n const paths = pathsFromRoot(path);\n\n for (let i=1; i {\n return this.rs.local.forAllNodes((node: RSNode) => {\n let parentPath: string;\n if (this.needsRefresh(node)) {\n try {\n parentPath = this.getParentPath(node.path);\n } catch(e) {\n // node.path is already '/', can't take parentPath\n }\n if (parentPath && this.rs.access.checkPathPermission(parentPath, 'r')) {\n this.addTask(parentPath);\n } else if (this.rs.access.checkPathPermission(node.path, 'r')) {\n this.addTask(node.path);\n }\n }\n })\n .then(() => this.deleteChildPathsFromTasks())\n .catch((e: Error) => { throw e; });\n }\n\n public flush (nodes: RSNodes): RSNodes {\n for (const path in nodes) {\n // Strategy is 'FLUSH' and no local changes exist\n if (this.rs.caching.checkPath(path) === 'FLUSH' &&\n nodes[path] && !nodes[path].local) {\n log('[Sync] Flushing', path);\n nodes[path] = undefined; // Cause node to be flushed from cache\n }\n }\n return nodes;\n }\n\n public doTask (path: string): object {\n return this.rs.local.getNodes([path]).then((nodes: RSNodes) => {\n const node = nodes[path];\n // First fetch:\n if (typeof(node) === 'undefined') {\n return taskFor('get', path, this.rs.remote.get(path));\n }\n // Fetch known-stale child:\n else if (isStaleChild(node)) {\n return taskFor('get', path, this.rs.remote.get(path));\n }\n // Push PUT:\n else if (this.needsRemotePut(node)) {\n node.push = deepClone(node.local);\n node.push.timestamp = this.now();\n\n return this.rs.local.setNodes(this.flush(nodes)).then(() => {\n let options;\n if (hasCommonRevision(node)) {\n options = { ifMatch: node.common.revision };\n } else {\n // Initial PUT (fail if something is already there)\n options = { ifNoneMatch: '*' };\n }\n\n return taskFor('put', path,\n this.rs.remote.put(path, node.push.body, node.push.contentType, options)\n );\n });\n }\n // Push DELETE:\n else if (this.needsRemoteDelete(node)) {\n node.push = { body: false, timestamp: this.now() };\n\n return this.rs.local.setNodes(this.flush(nodes)).then(() => {\n if (hasCommonRevision(node)) {\n return taskFor('delete', path,\n this.rs.remote.delete(path, { ifMatch: node.common.revision })\n );\n } else { // Ascertain current common or remote revision first\n return taskFor('get', path, this.rs.remote.get(path));\n }\n });\n }\n // Conditional refresh:\n else if (hasCommonRevision(node)) {\n return taskFor('get', path,\n this.rs.remote.get(path, { ifNoneMatch: node.common.revision })\n );\n }\n else {\n return taskFor('get', path, this.rs.remote.get(path));\n }\n });\n }\n\n public autoMergeFolder (node: RSNode): RSNode {\n if (node.remote.itemsMap) {\n node.common = node.remote;\n delete node.remote;\n\n if (node.common.itemsMap) {\n for (const itemName in node.common.itemsMap) {\n if (!node.local.itemsMap[itemName]) {\n // Indicates the node is either newly being fetched\n // has been deleted locally (whether or not leading to conflict);\n // before listing it in local listings, check if a local deletion\n // exists.\n node.local.itemsMap[itemName] = false;\n }\n }\n\n if (equal(node.local.itemsMap, node.common.itemsMap)) {\n delete node.local;\n }\n }\n }\n return node;\n }\n\n public autoMergeDocument (node: RSNode): RSNode {\n if (hasNoRemoteChanges(node)) {\n node = mergeMutualDeletion(node);\n delete node.remote;\n } else if (node.remote.body !== undefined) {\n // keep/revert:\n log('[Sync] Emitting keep/revert');\n\n this.rs.local._emitChange({\n origin: 'conflict',\n path: node.path,\n oldValue: node.local.body,\n newValue: node.remote.body,\n lastCommonValue: node.common.body,\n oldContentType: node.local.contentType,\n newContentType: node.remote.contentType,\n lastCommonContentType: node.common.contentType\n });\n\n if (node.remote.body) {\n node.common = node.remote;\n } else {\n node.common = {};\n }\n delete node.remote;\n delete node.local;\n }\n\n return node;\n }\n\n public autoMerge (node: RSNode): RSNode {\n if (node.remote) {\n if (node.local) {\n if (isFolder(node.path)) {\n return this.autoMergeFolder(node);\n } else {\n return this.autoMergeDocument(node);\n }\n } else { // no local changes\n if (isFolder(node.path)) {\n if (node.remote.itemsMap !== undefined) {\n node.common = node.remote;\n delete node.remote;\n }\n } else {\n if (node.remote.body !== undefined) {\n const change = {\n origin: 'remote',\n path: node.path,\n oldValue: (node.common.body === false ? undefined : node.common.body),\n newValue: (node.remote.body === false ? undefined : node.remote.body),\n oldContentType: node.common.contentType,\n newContentType: node.remote.contentType\n };\n if (change.oldValue || change.newValue) {\n this.rs.local._emitChange(change);\n }\n\n if (!node.remote.body) { // no remote, so delete/don't create\n return;\n }\n\n node.common = node.remote;\n delete node.remote;\n }\n }\n }\n } else {\n if (node.common.body) {\n this.rs.local._emitChange({\n origin: 'remote',\n path: node.path,\n oldValue: node.common.body,\n newValue: undefined,\n oldContentType: node.common.contentType,\n newContentType: undefined\n });\n }\n\n return undefined;\n }\n\n return node;\n }\n\n public async updateCommonTimestamp (path: string, revision: string): Promise {\n return this.rs.local.getNodes([path]).then((nodes: RSNodes) => {\n if (nodes[path] &&\n nodes[path].common &&\n nodes[path].common.revision === revision) {\n nodes[path].common.timestamp = this.now();\n }\n return this.rs.local.setNodes(this.flush(nodes));\n });\n }\n\n public async markChildren (path, itemsMap, changedNodes: RSNodes, missingChildren): Promise {\n const paths = [];\n const meta = {};\n const recurse = {};\n\n for (const item in itemsMap) {\n paths.push(path+item);\n meta[path+item] = itemsMap[item];\n }\n for (const childName in missingChildren) {\n paths.push(path+childName);\n }\n\n return this.rs.local.getNodes(paths).then((nodes: RSNodes) => {\n let cachingStrategy;\n let node;\n\n for (const nodePath in nodes) {\n node = nodes[nodePath];\n\n if (meta[nodePath]) {\n if (node && node.common) {\n if (nodeChanged(node, meta[nodePath].ETag)) {\n changedNodes[nodePath] = deepClone(node);\n changedNodes[nodePath].remote = {\n revision: meta[nodePath].ETag,\n timestamp: this.now()\n };\n changedNodes[nodePath] = this.autoMerge(changedNodes[nodePath]);\n }\n } else {\n cachingStrategy = this.rs.caching.checkPath(nodePath);\n if (cachingStrategy === 'ALL') {\n changedNodes[nodePath] = {\n path: nodePath,\n common: {\n timestamp: this.now()\n },\n remote: {\n revision: meta[nodePath].ETag,\n timestamp: this.now()\n }\n };\n }\n }\n\n if (changedNodes[nodePath] && meta[nodePath]['Content-Type']) {\n changedNodes[nodePath].remote.contentType = meta[nodePath]['Content-Type'];\n }\n\n if (changedNodes[nodePath] && meta[nodePath]['Content-Length']) {\n changedNodes[nodePath].remote.contentLength = meta[nodePath]['Content-Length'];\n }\n } else if (missingChildren[nodePath.substring(path.length)] && node && node.common) {\n if (node.common.itemsMap) {\n for (const commonItem in node.common.itemsMap) {\n recurse[nodePath+commonItem] = true;\n }\n }\n\n if (node.local && node.local.itemsMap) {\n for (const localItem in node.local.itemsMap) {\n recurse[nodePath+localItem] = true;\n }\n }\n\n if (node.remote || isFolder(nodePath)) {\n changedNodes[nodePath] = undefined;\n } else {\n changedNodes[nodePath] = this.autoMerge(node);\n\n if (typeof changedNodes[nodePath] === 'undefined') {\n const parentPath = this.getParentPath(nodePath);\n const parentNode = changedNodes[parentPath];\n const itemName = nodePath.substring(path.length);\n if (parentNode && parentNode.local) {\n delete parentNode.local.itemsMap[itemName];\n\n if (equal(parentNode.local.itemsMap, parentNode.common.itemsMap)) {\n delete parentNode.local;\n }\n }\n }\n }\n }\n }\n\n return this.deleteRemoteTrees(Object.keys(recurse), changedNodes)\n .then(changedObjs2 => {\n return this.rs.local.setNodes(this.flush(changedObjs2));\n });\n });\n }\n\n public async deleteRemoteTrees (paths: Array, changedNodes: RSNodes): Promise {\n if (paths.length === 0) {\n return Promise.resolve(changedNodes);\n }\n\n return this.rs.local.getNodes(paths).then(async (nodes: RSNodes) => {\n const subPaths = {};\n\n function collectSubPaths (folder, path: string): void {\n if (folder && folder.itemsMap) {\n for (const itemName in folder.itemsMap) {\n subPaths[path+itemName] = true;\n }\n }\n }\n\n for (const path in nodes) {\n const node = nodes[path];\n\n // TODO Why check for the node here? I don't think this check ever applies\n if (!node) { continue; }\n\n if (isFolder(path)) {\n collectSubPaths(node.common, path);\n collectSubPaths(node.local, path);\n } else {\n if (node.common && typeof(node.common.body) !== undefined) {\n changedNodes[path] = deepClone(node);\n changedNodes[path].remote = {\n body: false,\n timestamp: this.now()\n };\n changedNodes[path] = this.autoMerge(changedNodes[path]);\n }\n }\n }\n\n // Recurse whole tree depth levels at once:\n return this.deleteRemoteTrees(Object.keys(subPaths), changedNodes)\n .then(changedNodes2 => {\n return this.rs.local.setNodes(this.flush(changedNodes2));\n });\n });\n }\n\n public async completeFetch (path: string, bodyOrItemsMap: object, contentType: string, revision: string): Promise {\n let paths: Array;\n let parentPath: string;\n const pathsFromRootArr = pathsFromRoot(path);\n\n if (isFolder(path)) {\n paths = [path];\n } else {\n parentPath = pathsFromRootArr[1];\n paths = [path, parentPath];\n }\n\n return this.rs.local.getNodes(paths).then((nodes: RSNodes) => {\n let itemName: string;\n let node: RSNode = nodes[path];\n let parentNode: RSNode;\n const missingChildren = {};\n\n function collectMissingChildren (folder): void {\n if (folder && folder.itemsMap) {\n for (itemName in folder.itemsMap) {\n if (!bodyOrItemsMap[itemName]) {\n missingChildren[itemName] = true;\n }\n }\n }\n }\n\n if (typeof(node) !== 'object' ||\n node.path !== path ||\n typeof(node.common) !== 'object') {\n node = { path: path, common: {} };\n nodes[path] = node;\n }\n\n node.remote = {\n revision: revision,\n timestamp: this.now()\n };\n\n if (isFolder(path)) {\n collectMissingChildren(node.common);\n collectMissingChildren(node.remote);\n\n node.remote.itemsMap = {};\n for (itemName in bodyOrItemsMap) {\n node.remote.itemsMap[itemName] = true;\n }\n } else {\n node.remote.body = bodyOrItemsMap;\n node.remote.contentType = contentType;\n\n parentNode = nodes[parentPath];\n if (parentNode && parentNode.local && parentNode.local.itemsMap) {\n itemName = path.substring(parentPath.length);\n parentNode.local.itemsMap[itemName] = true;\n if (equal(parentNode.local.itemsMap, parentNode.common.itemsMap)) {\n delete parentNode.local;\n }\n }\n }\n\n nodes[path] = this.autoMerge(node);\n\n return {\n toBeSaved: nodes,\n missingChildren: missingChildren\n };\n });\n }\n\n public async completePush (path: string, action, conflict, revision: string): Promise {\n return this.rs.local.getNodes([path]).then((nodes: RSNodes) => {\n const node = nodes[path];\n\n if (!node.push) {\n this.stopped = true;\n throw new Error('completePush called but no push version!');\n }\n\n if (conflict) {\n log('[Sync] We have a conflict');\n\n if (!node.remote || node.remote.revision !== revision) {\n node.remote = {\n revision: revision || 'conflict',\n timestamp: this.now()\n };\n delete node.push;\n }\n\n nodes[path] = this.autoMerge(node);\n } else {\n node.common = {\n revision: revision,\n timestamp: this.now()\n };\n\n if (action === 'put') {\n node.common.body = node.push.body;\n node.common.contentType = node.push.contentType;\n\n if (equal(node.local.body, node.push.body) &&\n node.local.contentType === node.push.contentType) {\n delete node.local;\n }\n\n delete node.push;\n } else if (action === 'delete') {\n if (node.local.body === false) { // No new local changes since push; flush it.\n nodes[path] = undefined;\n } else {\n delete node.push;\n }\n }\n }\n\n return this.rs.local.setNodes(this.flush(nodes));\n });\n }\n\n public async dealWithFailure (path: string): Promise {\n return this.rs.local.getNodes([path]).then((nodes: RSNodes) => {\n if (nodes[path]) {\n delete nodes[path].push;\n return this.rs.local.setNodes(this.flush(nodes));\n }\n });\n }\n\n public interpretStatus (statusCode: string | number): ResponseStatus {\n const status: ResponseStatus = {\n statusCode: statusCode,\n successful: undefined,\n conflict: undefined,\n unAuth: undefined,\n notFound: undefined,\n changed: undefined,\n networkProblems: undefined\n };\n\n if (typeof statusCode === 'string' &&\n (statusCode === 'offline' || statusCode === 'timeout')) {\n status.successful = false;\n status.networkProblems = true;\n return status;\n } else if (typeof statusCode === 'number') {\n const series = Math.floor(statusCode / 100);\n\n status.successful = (series === 2 ||\n statusCode === 304 ||\n statusCode === 412 ||\n statusCode === 404),\n status.conflict = (statusCode === 412);\n status.unAuth = ((statusCode === 401 && this.rs.remote.token !== Authorize.IMPLIED_FAKE_TOKEN) ||\n statusCode === 402 ||\n statusCode === 403);\n status.notFound = (statusCode === 404);\n status.changed = (statusCode !== 304);\n\n return status;\n }\n }\n\n public async handleGetResponse (path: string, status: ResponseStatus, bodyOrItemsMap, contentType: string, revision: string): Promise {\n if (status.notFound) {\n if (isFolder(path)) {\n bodyOrItemsMap = {};\n } else {\n bodyOrItemsMap = false;\n }\n }\n\n if (status.changed) {\n return this.completeFetch(path, bodyOrItemsMap, contentType, revision)\n .then(dataFromFetch => {\n if (isFolder(path)) {\n if (this.corruptServerItemsMap(bodyOrItemsMap)) {\n log('[Sync] WARNING: Discarding corrupt folder description from server for ' + path);\n return false;\n } else {\n return this.markChildren(path, bodyOrItemsMap, dataFromFetch.toBeSaved, dataFromFetch.missingChildren)\n .then(() => { return true; });\n }\n } else {\n return this.rs.local.setNodes(this.flush(dataFromFetch.toBeSaved))\n .then(() => { return true; });\n }\n });\n } else {\n return this.updateCommonTimestamp(path, revision)\n .then(() => { return true; });\n }\n }\n\n public handleResponse (path: string, action, r): Promise {\n const status = this.interpretStatus(r.statusCode);\n\n if (status.successful) {\n if (action === 'get') {\n return this.handleGetResponse(path, status, r.body, r.contentType, r.revision);\n } else if (action === 'put' || action === 'delete') {\n return this.completePush(path, action, status.conflict, r.revision).then(function () {\n return true;\n });\n } else {\n throw new Error(`cannot handle response for unknown action ${action}`);\n }\n } else {\n // Unsuccessful\n let error: Error;\n if (status.unAuth) {\n error = new UnauthorizedError();\n } else if (status.networkProblems) {\n error = new SyncError('Network request failed.');\n } else {\n error = new Error('HTTP response code ' + status.statusCode + ' received.');\n }\n\n return this.dealWithFailure(path).then(() => {\n this.rs._emit('error', error);\n throw error;\n });\n }\n }\n\n public finishTask (task: SyncTask, queueTask = true): void | Promise {\n if (task.action === undefined) {\n delete this._running[task.path];\n return;\n }\n\n if (queueTask) {\n log(\"[Sync] queue finished task:\", task.path);\n this._finishedTasks.push(task);\n if (this._finishedTasks.length > 1) {\n log(\"[Sync] delaying finished task:\", task.path);\n return;\n }\n }\n\n log(\"[Sync] run task:\", task.path);\n\n return task.promise\n .then(res => {\n return this.handleResponse(task.path, task.action, res);\n }, err => {\n log('[Sync] wireclient rejects its promise!', task.path, task.action, err);\n return this.handleResponse(task.path, task.action, { statusCode: 'offline' });\n })\n .then(async (completed) => {\n this._finishedTasks.shift();\n delete this._timeStarted[task.path];\n delete this._running[task.path];\n\n if (completed) {\n if (this._tasks[task.path]) {\n for (let i=0; i < this._tasks[task.path].length; i++) {\n this._tasks[task.path][i]();\n }\n delete this._tasks[task.path];\n }\n }\n\n this.rs._emit('sync-req-done', {\n tasksRemaining: Object.keys(this._tasks).length\n });\n\n if (this._finishedTasks.length > 0) {\n this.finishTask(this._finishedTasks[0], false);\n return;\n }\n\n await this.collectTasks(false).then(() => {\n // See if there are any more tasks that are not refresh tasks\n if (!this.hasTasks() || this.stopped) {\n log('[Sync] Sync is done! Reschedule?', Object.getOwnPropertyNames(this._tasks).length, this.stopped);\n if (!this.done) {\n this.done = true;\n this.rs._emit('sync-done', { completed: true });\n }\n } else {\n // Use a 10ms timeout to let the JavaScript runtime catch its breath\n // (and hopefully force an IndexedDB auto-commit?), and also to cause\n // the threads to get staggered and get a good spread over time:\n setTimeout(() => { this.doTasks(); }, 10);\n }\n });\n }, err => {\n log('[Sync] Error', err);\n\n this._finishedTasks.shift();\n delete this._timeStarted[task.path];\n delete this._running[task.path];\n\n this.rs._emit('sync-req-done', {\n tasksRemaining: Object.keys(this._tasks).length\n });\n\n if (this._finishedTasks.length > 0) {\n this.finishTask(this._finishedTasks[0], false);\n return;\n }\n\n if (!this.done) {\n this.done = true;\n this.rs._emit('sync-done', { completed: false });\n }\n });\n }\n\n public doTasks (): boolean {\n let numToHave: number, numAdded = 0, path: string;\n if (this.rs.remote.connected) {\n if (this.rs.remote.online) {\n numToHave = this.numThreads;\n } else {\n numToHave = 1;\n }\n } else {\n numToHave = 0;\n }\n const numToAdd = numToHave - Object.getOwnPropertyNames(this._running).length;\n if (numToAdd <= 0) {\n return true;\n }\n for (path in this._tasks) {\n if (!this._running[path]) {\n this._timeStarted[path] = this.now();\n this._running[path] = this.doTask(path);\n this._running[path].then(this.finishTask.bind(this));\n numAdded++;\n if (numAdded >= numToAdd) {\n return true;\n }\n }\n }\n return (numAdded >= numToAdd);\n }\n\n public async collectTasks (alsoCheckRefresh?: boolean): Promise {\n if (this.hasTasks() || this.stopped) {\n return Promise.resolve();\n }\n\n return this.collectDiffTasks().then(numDiffs => {\n if (numDiffs || alsoCheckRefresh === false) {\n return Promise.resolve();\n } else {\n return this.collectRefreshTasks();\n }\n }, function (err) { throw err; });\n }\n\n public addTask (path: string, cb?): void {\n if (!this._tasks[path]) {\n this._tasks[path] = [];\n }\n if (typeof(cb) === 'function') {\n this._tasks[path].push(cb);\n }\n }\n\n /**\n * Method: sync\n **/\n public sync (): Promise {\n this.done = false;\n\n if (!this.doTasks()) {\n return this.collectTasks().then(() => {\n try {\n this.doTasks();\n } catch(e) {\n log('[Sync] doTasks error', e);\n }\n }, function (e) {\n log('[Sync] Sync error', e);\n throw new Error('Local cache unavailable');\n });\n } else {\n return Promise.resolve();\n }\n }\n\n static _rs_init (remoteStorage): void {\n syncCycleCb = function (): void {\n // if (!config.cache) return false\n log('[Sync] syncCycleCb calling syncCycle');\n\n const env = new Env();\n if (env.isBrowser()) { handleVisibility(env, remoteStorage); }\n\n if (!remoteStorage.sync) {\n // Call this now that all other modules are also ready:\n remoteStorage.sync = new Sync(remoteStorage);\n\n if (remoteStorage.syncStopped) {\n log('[Sync] Instantiating sync stopped');\n remoteStorage.sync.stopped = true;\n delete remoteStorage.syncStopped;\n }\n }\n\n log('[Sync] syncCycleCb calling syncCycle');\n remoteStorage.syncCycle();\n };\n\n syncOnConnect = function (): void {\n remoteStorage.removeEventListener('connected', syncOnConnect);\n remoteStorage.startSync();\n };\n\n remoteStorage.on('ready', syncCycleCb);\n remoteStorage.on('connected', syncOnConnect);\n }\n\n static _rs_cleanup (remoteStorage): void {\n remoteStorage.stopSync();\n remoteStorage.removeEventListener('ready', syncCycleCb);\n remoteStorage.removeEventListener('connected', syncOnConnect);\n\n remoteStorage.sync = undefined;\n delete remoteStorage.sync;\n }\n}\n\nexport interface Sync extends EventHandling {}\napplyMixins(Sync, [EventHandling]);\n\nexport default Sync;\n","import log from './log';\n\nfunction shareFirst(path: string): boolean {\n return ( this.backend === 'dropbox' &&\n !!path.match(/^\\/public\\/.*[^\\/]$/) );\n}\n\nfunction defaultMaxAge(context): false | number {\n if ((typeof context.remote === 'object') &&\n context.remote.connected && context.remote.online) {\n return 2 * context.getSyncInterval();\n } else {\n log('Not setting default maxAge, because remote is offline or not connected');\n return false;\n }\n}\n\nconst SyncedGetPutDelete = {\n get: function (path: string, maxAge: undefined | false | number): Promise {\n if (!this.local) {\n return this.remote.get(path);\n } else {\n if (typeof maxAge === 'undefined') {\n maxAge = defaultMaxAge(this);\n } else if (typeof maxAge !== 'number' && maxAge !== false) {\n return Promise.reject(`Argument 'maxAge' must be 'false' or a number`);\n }\n return this.local.get(path, maxAge, this.sync.queueGetRequest.bind(this.sync));\n }\n },\n\n put: function (path: string, body: unknown, contentType: string): Promise {\n if (shareFirst.bind(this)(path)) {\n return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.put(path, body, contentType));\n }\n else if (this.local) {\n return this.local.put(path, body, contentType);\n } else {\n return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.put(path, body, contentType));\n }\n },\n\n 'delete': function (path: string): Promise {\n if (this.local) {\n return this.local.delete(path);\n } else {\n return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.delete(path));\n }\n },\n\n _wrapBusyDone: async function (result: Promise): Promise {\n this._emit('wire-busy');\n return result.then((r) => {\n this._emit('wire-done', { success: true });\n return Promise.resolve(r);\n }, (err: Error) => {\n this._emit('wire-done', { success: false });\n return Promise.reject(err);\n });\n }\n};\n\nexport = SyncedGetPutDelete;\n","import type { JsonSchemas } from './interfaces/json_schema';\n/**\n * - Manages and validates types of remoteStorage objects, using JSON-LD and\n * JSON Schema\n * - Adds schema declaration/validation methods to BaseClient instances.\n **/\nexport class BaseClientTypes {\n /**\n * -> \n */\n uris: { [key: string]: string } = {};\n\n /**\n * Contains schema objects of all types known to the BaseClient instance\n *\n * -> \n */\n schemas: JsonSchemas = {};\n\n /**\n * -> \n */\n aliases: { [key: string]: string } = {};\n\n /**\n * Called via public function BaseClient.declareType()\n *\n * @private\n */\n declare (moduleName: string, alias: string, uri: string, schema: tv4.JsonSchema): void {\n const fullAlias = moduleName + '/' + alias;\n\n if (schema.extends) {\n const parts = schema.extends.split('/');\n const extendedAlias = (parts.length === 1)\n ? moduleName + '/' + parts.shift()\n : parts.join('/');\n\n const extendedUri = this.uris[extendedAlias];\n if (!extendedUri) {\n throw \"Type '\" + fullAlias + \"' tries to extend unknown schema '\" + extendedAlias + \"'\";\n }\n schema.extends = this.schemas[extendedUri];\n }\n\n this.uris[fullAlias] = uri;\n this.aliases[uri] = fullAlias;\n this.schemas[uri] = schema;\n }\n\n resolveAlias (alias: string): string {\n return this.uris[alias];\n }\n\n getSchema (uri: string): tv4.JsonSchema {\n return this.schemas[uri];\n }\n\n inScope (moduleName: string): JsonSchemas {\n const ml = moduleName.length;\n const schemas = {};\n for (const alias in this.uris) {\n if (alias.substr(0, ml + 1) === moduleName + '/') {\n const uri = this.uris[alias];\n schemas[uri] = this.schemas[uri];\n }\n }\n return schemas;\n }\n}\n\nconst Types = new BaseClientTypes();\nexport default Types;\n","class UnauthorizedError extends Error {\n code: string;\n\n constructor (message?: string, options: {code?: string} = {}) {\n super();\n this.name = 'Unauthorized';\n\n if (typeof message === 'undefined') {\n this.message = 'App authorization expired or revoked.';\n } else {\n this.message = message;\n }\n\n if (typeof options.code !== 'undefined') {\n this.code = options.code;\n }\n\n this.stack = (new Error()).stack;\n }\n}\n\nexport = UnauthorizedError;\n","// Reusable utility functions\n\n/**\n * Takes an object and its copy as produced by the _deepClone function\n * below, and finds and fixes any ArrayBuffers that were cast to `{}` instead\n * of being cloned to new ArrayBuffers with the same content.\n *\n * It recurses into sub-objects, but skips arrays if they occur.\n */\nfunction _fixArrayBuffers(srcObj: object, dstObj: object) {\n if (typeof (srcObj) !== 'object' || Array.isArray(srcObj) || srcObj === null) {\n return;\n }\n for (const field in srcObj) {\n if (typeof (srcObj[field]) === 'object' && srcObj[field] !== null) {\n if (srcObj[field].toString() === '[object ArrayBuffer]') {\n dstObj[field] = new ArrayBuffer(srcObj[field].byteLength);\n const srcArr = new Int8Array(srcObj[field]);\n const dstArr = new Int8Array(dstObj[field]);\n dstArr.set(srcArr);\n } else {\n _fixArrayBuffers(srcObj[field], dstObj[field]);\n }\n }\n }\n}\n\nexport const logError = (error: string | Error): void => {\n if (typeof (error) === 'string') {\n console.error(error);\n } else {\n console.error(error.message, error.stack);\n }\n};\n\nexport const globalContext = (typeof (window) !== 'undefined' ? window : (typeof self === 'object' ? self : global));\n\nexport const getGlobalContext = (): any => {\n return (typeof (window) !== 'undefined' ? window : (typeof self === 'object' ? self : global));\n};\n\n// TODO Remove in favor of modern JS:\n// `const mergedObject = { ...obj1, ..obj2 }`\nexport const extend = (...args): unknown => {\n const target = args[0];\n const sources = Array.prototype.slice.call(args, 1);\n sources.forEach(function (source) {\n for (const key in source) {\n target[key] = source[key];\n }\n });\n return target;\n};\n\nexport const containingFolder = (path: string): string => {\n if (path === '') {\n return '/';\n }\n if (!path) {\n throw \"Path not given!\";\n }\n\n return path.replace(/\\/+/g, '/')\n .replace(/[^\\/]+\\/?$/, '');\n};\n\nexport const isFolder = (path: string): boolean => {\n return path.slice(-1) === '/';\n};\n\nexport const isDocument = (path: string): boolean => {\n return !isFolder(path);\n};\n\nexport const baseName = (path: string): string => {\n const parts = path.split('/');\n if (isFolder(path)) {\n return parts[parts.length - 2] + '/';\n } else {\n return parts[parts.length - 1];\n }\n};\n\nexport const cleanPath = (path: string): string => {\n return path.replace(/\\/+/g, '/')\n .split('/').map(encodeURIComponent).join('/')\n .replace(/'/g, '%27');\n};\n\nexport const bindAll = (object: object) => {\n for (const key in this) {\n if (typeof (object[key]) === 'function') {\n object[key] = object[key].bind(object);\n }\n }\n};\n\nexport const equal = (a: any, b: any, seen = []): boolean => {\n let key;\n\n if (typeof (a) !== typeof (b)) {\n return false;\n }\n\n if (typeof (a) === 'number' || typeof (a) === 'boolean' || typeof (a) === 'string') {\n return a === b;\n }\n\n if (typeof (a) === 'function') {\n return a.toString() === b.toString();\n }\n\n if (a instanceof ArrayBuffer && b instanceof ArrayBuffer) {\n // Without the following conversion the browsers wouldn't be able to\n // tell the ArrayBuffer instances apart.\n a = new Uint8Array(a);\n b = new Uint8Array(b);\n }\n\n // If this point has been reached, a and b are either arrays or objects.\n\n if (a instanceof Array) {\n if (a.length !== b.length) {\n return false;\n }\n\n for (let i = 0, c = a.length; i < c; i++) {\n if (!equal(a[i], b[i], seen)) {\n return false;\n }\n }\n } else {\n // Check that keys from a exist in b\n for (key in a) {\n if (a.hasOwnProperty(key) && !(key in b)) {\n return false;\n }\n }\n\n // Check that keys from b exist in a, and compare the values\n for (key in b) {\n if (!b.hasOwnProperty(key)) {\n continue;\n }\n\n if (!(key in a)) {\n return false;\n }\n\n let seenArg;\n\n if (typeof (b[key]) === 'object') {\n if (seen.indexOf(b[key]) >= 0) {\n // Circular reference, don't attempt to compare this object.\n // If nothing else returns false, the objects match.\n continue;\n }\n\n seenArg = seen.slice();\n seenArg.push(b[key]);\n }\n\n if (!equal(a[key], b[key], seenArg)) {\n return false;\n }\n }\n }\n\n return true;\n};\n\nexport const deepClone = (obj: any): any => {\n if (obj === undefined) {\n return undefined;\n } else {\n const clone = JSON.parse(JSON.stringify(obj));\n _fixArrayBuffers(obj, clone);\n return clone;\n }\n};\n\nexport const pathsFromRoot = (path: string): string[] => {\n const paths = [path];\n const parts = path.replace(/\\/$/, '').split('/');\n\n while (parts.length > 1) {\n parts.pop();\n paths.push(parts.join('/') + '/');\n }\n return paths;\n};\n\nexport const localStorageAvailable = (): boolean => {\n const context = getGlobalContext();\n\n if (!('localStorage' in context)) {\n return false;\n }\n\n try {\n context.localStorage.setItem('rs-check', '1');\n context.localStorage.removeItem('rs-check');\n return true;\n } catch (error) {\n return false;\n }\n};\n\n/**\n * Extract and parse JSON data from localStorage.\n *\n * @param {string} key - localStorage key\n *\n * @returns {object} parsed object or undefined\n */\nexport const getJSONFromLocalStorage = (key: string): { [key: string]: any } => {\n const context = getGlobalContext() as Window;\n\n try {\n return JSON.parse(context.localStorage.getItem(key));\n } catch (e) {\n // no JSON stored\n }\n};\n\n/**\n * Decide if data should be treated as binary based on the content (presence of non-printable characters\n * or replacement character) and content-type.\n *\n * @param {string} content - The data\n * @param {string} mimeType - The data's content-type\n *\n * @returns {boolean}\n */\nexport const shouldBeTreatedAsBinary = (content: string | ArrayBuffer, mimeType: string): boolean => {\n // eslint-disable-next-line no-control-regex\n return !!((mimeType && mimeType.match(/charset=binary/)) || /[\\x00-\\x08\\x0E-\\x1F\\uFFFD]/.test(content as string));\n};\n\n/**\n * Read data from an ArrayBuffer and return it as a string\n * @param {ArrayBuffer} arrayBuffer\n * @param {string} encoding\n * @returns {Promise} Resolves with a string containing the data\n */\nexport const getTextFromArrayBuffer = (arrayBuffer: ArrayBuffer, encoding): Promise => {\n return new Promise((resolve/*, reject*/) => {\n if (typeof Blob === 'undefined' || typeof FileReader === 'undefined') {\n const buffer = Buffer.from(arrayBuffer);\n resolve(buffer.toString(encoding));\n } else {\n let blob;\n const gc = globalContext as any;\n // TODO fix as BlobBuilder is not available in all browsers\n // @see https://developer.mozilla.org/en-US/docs/Web/API/BlobBuilder\n gc.BlobBuilder = gc.BlobBuilder || gc.WebKitBlobBuilder;\n if (typeof gc.BlobBuilder !== 'undefined') {\n const bb = new gc.BlobBuilder();\n bb.append(arrayBuffer);\n blob = bb.getBlob();\n } else {\n blob = new Blob([arrayBuffer]);\n }\n\n const fileReader = new FileReader();\n if (typeof fileReader.addEventListener === 'function') {\n fileReader.addEventListener('loadend', function (evt) {\n resolve(evt.target.result);\n });\n } else {\n fileReader.onloadend = function (evt) {\n resolve(evt.target.result);\n };\n }\n fileReader.readAsText(blob, encoding);\n }\n });\n};\n\n/**\n * Encode string in base64\n * @param {String} str\n * @returns {String} base64-encoded string\n */\nexport const toBase64 = (str: string): string => {\n const context = getGlobalContext();\n if ('btoa' in context) {\n return context['btoa'](str);\n } else {\n return Buffer.from(str).toString('base64');\n }\n};\n\n/**\n * Generates values required for OAuth2 PKCE in a cryptographically secure manner.\n * @param {number} [numChar=128] - length of codeVerifier to generate; from 43 to 128\n *\n * @typedef {Object} PkceValues\n * @property {string} codeVerifier - 43 to 128 chars from the 66-char set\n * @property {string} codeChallenge - verifier hashed & base-64 URL encoded\n * @property {string} state - a separate random value. Should be used to check redirect_uri.\n * @returns PkceValues\n */\nexport async function generateCodeVerifier(numChar = 128) {\n const randomBytes = new Uint8Array(numChar);\n crypto.getRandomValues(randomBytes);\n\n const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';\n const randomChar = Array.from(randomBytes).map(byte => charSet[byte % charSet.length]);\n const codeVerifier = randomChar.join('');\n\n const charsAsBytes = Uint8Array.from(randomChar.map(ch => ch.charCodeAt(0)));\n const sha256hash = await crypto.subtle.digest('SHA-256', charsAsBytes);\n const codeChallenge = base64Urlencode(sha256hash);\n\n crypto.getRandomValues(randomBytes);\n const stateRandomChar = Array.from(randomBytes).map(byte => charSet[byte % charSet.length]);\n const state = stateRandomChar.join('');\n\n return {codeVerifier, codeChallenge, state};\n}\n\nfunction base64Urlencode(str) {\n return btoa(String.fromCharCode.apply(null,\n new Uint8Array(str)))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\n/*\n * Apply mixins to an object\n *\n * https://www.typescriptlang.org/docs/handbook/mixins.html\n *\n * @param derivedConstructor Parent object\n * @param constructors Mixins to apply methods from\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function applyMixins(derivedCtor: any, constructors: any[]): void {\n constructors.forEach(baseCtor => {\n Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {\n Object.defineProperty(\n derivedCtor.prototype,\n name,\n Object.getOwnPropertyDescriptor(baseCtor.prototype, name));\n });\n });\n}\n","/**\n * This file exposes a get/put/delete interface on top of fetch() or XMLHttpRequest.\n * It requires to be configured with parameters about the remotestorage server to\n * connect to.\n * Each instance of WireClient is always associated with a single remotestorage\n * server and access token.\n *\n * Usually the WireClient instance can be accessed via `remoteStorage.remote`.\n *\n * This is the get/put/delete interface:\n *\n * - #get() takes a path and optionally a ifNoneMatch option carrying a version\n * string to check. It returns a promise that will be fulfilled with the HTTP\n * response status, the response body, the MIME type as returned in the\n * 'Content-Type' header and the current revision, as returned in the 'ETag'\n * header.\n * - #put() takes a path, the request body and a content type string. It also\n * accepts the ifMatch and ifNoneMatch options, that map to the If-Match and\n * If-None-Match headers respectively. See the remotestorage-01 specification\n * for details on handling these headers. It returns a promise, fulfilled with\n * the same values as the one for #get().\n * - #delete() takes a path and the ifMatch option as well. It returns a promise\n * fulfilled with the same values as the one for #get().\n *\n * In addition to this, the WireClient has some compatibility features to work with\n * remotestorage 2012.04 compatible storages. For example it will cache revisions\n * from folder listings in-memory and return them accordingly as the \"revision\"\n * parameter in response to #get() requests. Similarly it will return 404 when it\n * receives an empty folder listing, to mimic remotestorage-01 behavior. Note\n * that it is not always possible to know the revision beforehand, hence it may\n * be undefined at times (especially for caching-roots).\n */\nimport RemoteStorage from './remotestorage';\nimport Authorize from './authorize';\nimport EventHandling from './eventhandling';\nimport UnauthorizedError from './unauthorized-error';\nimport log from './log';\nimport {\n applyMixins,\n cleanPath,\n getJSONFromLocalStorage,\n getTextFromArrayBuffer,\n isFolder,\n localStorageAvailable,\n shouldBeTreatedAsBinary\n} from './util';\nimport {requestWithTimeout, isArrayBufferView} from \"./requests\";\nimport {Remote, RemoteBase, RemoteResponse, RemoteSettings} from \"./remote\";\n\nlet hasLocalStorage;\nconst SETTINGS_KEY = 'remotestorage:wireclient';\n\nconst API_2012 = 1;\nconst API_00 = 2;\nconst API_01 = 3;\nconst API_02 = 4;\nconst API_HEAD = 5;\n\nconst STORAGE_APIS = {\n 'draft-dejong-remotestorage-00': API_00,\n 'draft-dejong-remotestorage-01': API_01,\n 'draft-dejong-remotestorage-02': API_02,\n 'https://www.w3.org/community/rww/wiki/read-write-web-00#simple': API_2012\n};\n\nfunction readSettings () {\n const settings = getJSONFromLocalStorage(SETTINGS_KEY) || {};\n const { userAddress, href, storageApi, token, properties } = settings;\n\n return { userAddress, href, storageApi, token, properties };\n}\n\nfunction determineCharset (mimeType: string): string {\n let charset = 'utf-8';\n let charsetMatch;\n\n if (mimeType) {\n charsetMatch = mimeType.match(/charset=(.+)$/);\n if (charsetMatch) {\n charset = charsetMatch[1];\n }\n }\n return charset;\n}\n\nfunction isFolderDescription (body: object): boolean {\n return ((body['@context'] === 'http://remotestorage.io/spec/folder-description')\n && (typeof (body['items']) === 'object'));\n}\n\nfunction isSuccessStatus (status: number): boolean {\n return [201, 204, 304].indexOf(status) >= 0;\n}\n\nfunction isErrorStatus (status: number): boolean {\n return [401, 403, 404, 412].indexOf(status) >= 0;\n}\n\nclass WireClient extends RemoteBase implements Remote {\n /**\n * Holds the bearer token of this WireClient, as obtained in the OAuth dance\n *\n * Example:\n * (start code)\n *\n * remoteStorage.remote.token\n * // -> 'DEADBEEF01=='\n */\n token: string | false;\n\n /**\n * Holds the server's base URL, as obtained in the Webfinger discovery\n *\n * Example:\n * (start code)\n *\n * remoteStorage.remote.href\n * // -> 'https://storage.example.com/users/jblogg/'\n */\n href: string;\n\n supportsRevs: boolean;\n\n _revisionCache: { [key: string]: any } = {};\n\n properties: object;\n\n constructor (rs: RemoteStorage) {\n super(rs);\n hasLocalStorage = localStorageAvailable();\n\n /**\n * Event: connected\n * Fired when the wireclient connect method realizes that it is in\n * possession of a token and href\n **/\n this.addEvents(['connected', 'not-connected']);\n\n if (hasLocalStorage) {\n const settings = readSettings();\n if (settings) {\n setTimeout(() => {\n this.configure(settings);\n }, 0);\n }\n }\n\n if (this.connected) {\n setTimeout(this._emit.bind(this), 0, 'connected');\n }\n }\n\n get storageType () {\n if (this.storageApi) {\n const spec = this.storageApi.match(/draft-dejong-(remotestorage-\\d\\d)/);\n return spec ? spec[1] : '2012.04';\n } else {\n return undefined;\n }\n }\n\n async _request (method: string, uri: string, token: string | false, headers: HeadersInit, body: XMLHttpRequestBodyInit, getEtag: boolean, fakeRevision?: string): Promise {\n if (this.isForbiddenRequestMethod(method, uri)) {\n return Promise.reject(`Don't use ${method} on directories!`);\n }\n\n let revision: string | undefined;\n\n if (token !== Authorize.IMPLIED_FAKE_TOKEN) {\n headers['Authorization'] = 'Bearer ' + token;\n }\n\n this.rs._emit('wire-busy', {\n method: method,\n isFolder: isFolder(uri)\n });\n\n return requestWithTimeout(method, uri, {\n body: body,\n headers: headers,\n responseType: 'arraybuffer'\n }).then((response: XMLHttpRequest): Promise => {\n if (!this.online) {\n this.online = true;\n this.rs._emit('network-online');\n }\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(uri),\n success: true\n });\n\n if (isErrorStatus(response.status)) {\n log('[WireClient] Error response status', response.status);\n if (getEtag) {\n revision = this.stripQuotes(response.getResponseHeader('ETag'));\n } else {\n revision = undefined;\n }\n\n if (response.status === 401) {\n this.rs._emit('error', new UnauthorizedError());\n }\n\n return Promise.resolve({statusCode: response.status, revision: revision});\n } else if (isSuccessStatus(response.status) ||\n (response.status === 200 && method !== 'GET')) {\n revision = this.stripQuotes(response.getResponseHeader('ETag'));\n log('[WireClient] Successful request', revision);\n return Promise.resolve({statusCode: response.status, revision: revision});\n } else {\n const mimeType = response.getResponseHeader('Content-Type');\n if (getEtag) {\n revision = this.stripQuotes(response.getResponseHeader('ETag'));\n } else {\n revision = (response.status === 200) ? fakeRevision : undefined;\n }\n\n const charset = determineCharset(mimeType);\n\n if (shouldBeTreatedAsBinary(response.response, mimeType)) {\n log('[WireClient] Successful request with unknown or binary mime-type', revision);\n return Promise.resolve({\n statusCode: response.status,\n body: response.response,\n contentType: mimeType,\n revision: revision\n });\n } else {\n return getTextFromArrayBuffer(response.response, charset)\n .then((textContent) => {\n log('[WireClient] Successful request', revision);\n return Promise.resolve({\n statusCode: response.status,\n body: textContent,\n contentType: mimeType,\n revision: revision\n });\n });\n }\n }\n }, error => {\n if (this.online) {\n this.online = false;\n this.rs._emit('network-offline');\n }\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(uri),\n success: false\n });\n\n return Promise.reject(error);\n });\n }\n\n /**\n * Sets the userAddress, href, storageApi, token, and properties of a\n * remote store. Also sets connected and online to true and emits the\n * 'connected' event, if both token and href are present.\n *\n * Parameters:\n * settings - An object that may contain userAddress (string or null),\n * href (string or null), storageApi (string or null), token (string\n * or null), and/or properties (the JSON-parsed properties object\n * from the user's WebFinger record, see section 10 of\n * http://tools.ietf.org/html/draft-dejong-remotestorage-03\n * or null).\n * Fields that are not included (i.e. `undefined`), stay at\n * their current value. To set a field, include that field\n * with a `string` value. To reset a field, for instance when\n * the user disconnected their storage, or you found that the\n * token you have has expired, simply set that field to `null`.\n */\n configure (settings: RemoteSettings): void {\n if (typeof settings !== 'object') {\n throw new Error('WireClient configure settings parameter should be an object');\n }\n if (typeof settings.userAddress !== 'undefined') {\n this.userAddress = settings.userAddress;\n }\n if (typeof settings.href !== 'undefined') {\n this.href = settings.href;\n }\n if (typeof settings.storageApi !== 'undefined') {\n this.storageApi = settings.storageApi;\n }\n if (typeof settings.token !== 'undefined') {\n this.token = settings.token;\n }\n if (typeof settings.properties !== 'undefined') {\n this.properties = settings.properties;\n }\n\n if (typeof this.storageApi === 'string') {\n const _storageApi = STORAGE_APIS[this.storageApi] || API_HEAD;\n this.supportsRevs = _storageApi >= API_00;\n }\n if (this.href && this.token) {\n this.connected = true;\n this.online = true;\n this._emit('connected');\n } else {\n this.connected = false;\n }\n if (hasLocalStorage) {\n localStorage[SETTINGS_KEY] = JSON.stringify({\n userAddress: this.userAddress,\n href: this.href,\n storageApi: this.storageApi,\n token: this.token,\n properties: this.properties\n });\n }\n }\n\n get (path: string, options: { ifNoneMatch?: string } = {}): Promise {\n if (!this.connected) {\n return Promise.reject('not connected (path: ' + path + ')');\n }\n\n const headers = {};\n if (this.supportsRevs) {\n if (options.ifNoneMatch) {\n headers['If-None-Match'] = this.addQuotes(options.ifNoneMatch);\n }\n }\n // commenting it out as this is doing nothing and jshint is complaining -les\n // else if (options.ifNoneMatch) {\n // let oldRev = this._revisionCache[path];\n // }\n\n return this._request('GET', this.href + cleanPath(path), this.token, headers,\n undefined, this.supportsRevs, this._revisionCache[path])\n .then((r) => {\n if (!isFolder(path)) {\n return Promise.resolve(r);\n }\n let itemsMap = {};\n if (typeof (r.body) !== 'undefined') {\n try {\n r.body = JSON.parse(r.body);\n } catch (e) {\n return Promise.reject('Folder description at ' + this.href + cleanPath(path) + ' is not JSON');\n }\n }\n\n if (r.statusCode === 200 && typeof (r.body) === 'object') {\n // New folder listing received\n if (Object.keys(r.body).length === 0) {\n // Empty folder listing of any spec\n r.statusCode = 404;\n } else if (isFolderDescription(r.body)) {\n // >= 02 spec\n for (const item in r.body.items) {\n this._revisionCache[path + item] = r.body.items[item].ETag;\n }\n itemsMap = r.body.items;\n } else {\n // < 02 spec\n Object.keys(r.body).forEach((key) => {\n this._revisionCache[path + key] = r.body[key];\n itemsMap[key] = {'ETag': r.body[key]};\n });\n }\n r.body = itemsMap;\n return Promise.resolve(r);\n } else {\n return Promise.resolve(r);\n }\n });\n }\n\n put (path: string, body: XMLHttpRequestBodyInit, contentType: string, options: { ifMatch?: string; ifNoneMatch?: string } = {}): Promise {\n if (!this.connected) {\n return Promise.reject('not connected (path: ' + path + ')');\n }\n if ((!contentType.match(/charset=/)) && (body instanceof ArrayBuffer || isArrayBufferView(body))) {\n contentType += '; charset=binary';\n }\n const headers = {'Content-Type': contentType};\n if (this.supportsRevs) {\n if (options.ifMatch) {\n headers['If-Match'] = this.addQuotes(options.ifMatch);\n }\n if (options.ifNoneMatch) {\n headers['If-None-Match'] = this.addQuotes(options.ifNoneMatch);\n }\n }\n return this._request('PUT', this.href + cleanPath(path), this.token,\n headers, body, this.supportsRevs);\n }\n\n delete (path: string, options: { ifMatch?: string } = {}): Promise {\n if (!this.connected) {\n throw new Error('not connected (path: ' + path + ')');\n }\n if (!options) {\n options = {};\n }\n const headers = {};\n if (this.supportsRevs) {\n if (options.ifMatch) {\n headers['If-Match'] = this.addQuotes(options.ifMatch);\n }\n }\n return this._request('DELETE', this.href + cleanPath(path), this.token,\n headers,\n undefined, this.supportsRevs);\n }\n\n static _rs_init (remoteStorage): void {\n remoteStorage.remote = new WireClient(remoteStorage);\n remoteStorage.remote.online = true;\n }\n\n static _rs_supported (): boolean {\n return typeof fetch === 'function' || typeof XMLHttpRequest === 'function';\n }\n\n static _rs_cleanup (): void {\n if (hasLocalStorage) {\n delete localStorage[SETTINGS_KEY];\n }\n }\n}\n\ninterface WireClient extends EventHandling {}\napplyMixins(WireClient, [EventHandling]);\n\nexport = WireClient;\n","/*\r\nAuthor: Geraint Luff and others\r\nYear: 2013\r\n\r\nThis code is released into the \"public domain\" by its author(s). Anybody may use, alter and distribute the code without restriction. The author makes no guarantees, and takes no liability of any kind for use of this code.\r\n\r\nIf you find a bug or make an improvement, it would be courteous to let the author know, but it is not compulsory.\r\n*/\r\n(function (global, factory) {\r\n if (typeof define === 'function' && define.amd) {\r\n // AMD. Register as an anonymous module.\r\n define([], factory);\r\n } else if (typeof module !== 'undefined' && module.exports){\r\n // CommonJS. Define export.\r\n module.exports = factory();\r\n } else {\r\n // Browser globals\r\n global.tv4 = factory();\r\n }\r\n}(this, function () {\r\n\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FObject%2Fkeys\r\nif (!Object.keys) {\r\n\tObject.keys = (function () {\r\n\t\tvar hasOwnProperty = Object.prototype.hasOwnProperty,\r\n\t\t\thasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),\r\n\t\t\tdontEnums = [\r\n\t\t\t\t'toString',\r\n\t\t\t\t'toLocaleString',\r\n\t\t\t\t'valueOf',\r\n\t\t\t\t'hasOwnProperty',\r\n\t\t\t\t'isPrototypeOf',\r\n\t\t\t\t'propertyIsEnumerable',\r\n\t\t\t\t'constructor'\r\n\t\t\t],\r\n\t\t\tdontEnumsLength = dontEnums.length;\r\n\r\n\t\treturn function (obj) {\r\n\t\t\tif (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {\r\n\t\t\t\tthrow new TypeError('Object.keys called on non-object');\r\n\t\t\t}\r\n\r\n\t\t\tvar result = [];\r\n\r\n\t\t\tfor (var prop in obj) {\r\n\t\t\t\tif (hasOwnProperty.call(obj, prop)) {\r\n\t\t\t\t\tresult.push(prop);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (hasDontEnumBug) {\r\n\t\t\t\tfor (var i=0; i < dontEnumsLength; i++) {\r\n\t\t\t\t\tif (hasOwnProperty.call(obj, dontEnums[i])) {\r\n\t\t\t\t\t\tresult.push(dontEnums[i]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn result;\r\n\t\t};\r\n\t})();\r\n}\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create\r\nif (!Object.create) {\r\n\tObject.create = (function(){\r\n\t\tfunction F(){}\r\n\r\n\t\treturn function(o){\r\n\t\t\tif (arguments.length !== 1) {\r\n\t\t\t\tthrow new Error('Object.create implementation only accepts one parameter.');\r\n\t\t\t}\r\n\t\t\tF.prototype = o;\r\n\t\t\treturn new F();\r\n\t\t};\r\n\t})();\r\n}\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FisArray\r\nif(!Array.isArray) {\r\n\tArray.isArray = function (vArg) {\r\n\t\treturn Object.prototype.toString.call(vArg) === \"[object Array]\";\r\n\t};\r\n}\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FindexOf\r\nif (!Array.prototype.indexOf) {\r\n\tArray.prototype.indexOf = function (searchElement /*, fromIndex */ ) {\r\n\t\tif (this === null) {\r\n\t\t\tthrow new TypeError();\r\n\t\t}\r\n\t\tvar t = Object(this);\r\n\t\tvar len = t.length >>> 0;\r\n\r\n\t\tif (len === 0) {\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\tvar n = 0;\r\n\t\tif (arguments.length > 1) {\r\n\t\t\tn = Number(arguments[1]);\r\n\t\t\tif (n !== n) { // shortcut for verifying if it's NaN\r\n\t\t\t\tn = 0;\r\n\t\t\t} else if (n !== 0 && n !== Infinity && n !== -Infinity) {\r\n\t\t\t\tn = (n > 0 || -1) * Math.floor(Math.abs(n));\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (n >= len) {\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\tvar k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);\r\n\t\tfor (; k < len; k++) {\r\n\t\t\tif (k in t && t[k] === searchElement) {\r\n\t\t\t\treturn k;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn -1;\r\n\t};\r\n}\r\n\r\n// Grungey Object.isFrozen hack\r\nif (!Object.isFrozen) {\r\n\tObject.isFrozen = function (obj) {\r\n\t\tvar key = \"tv4_test_frozen_key\";\r\n\t\twhile (obj.hasOwnProperty(key)) {\r\n\t\t\tkey += Math.random();\r\n\t\t}\r\n\t\ttry {\r\n\t\t\tobj[key] = true;\r\n\t\t\tdelete obj[key];\r\n\t\t\treturn false;\r\n\t\t} catch (e) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t};\r\n}\r\n// Based on: https://github.com/geraintluff/uri-templates, but with all the de-substitution stuff removed\r\n\r\nvar uriTemplateGlobalModifiers = {\r\n\t\"+\": true,\r\n\t\"#\": true,\r\n\t\".\": true,\r\n\t\"/\": true,\r\n\t\";\": true,\r\n\t\"?\": true,\r\n\t\"&\": true\r\n};\r\nvar uriTemplateSuffices = {\r\n\t\"*\": true\r\n};\r\n\r\nfunction notReallyPercentEncode(string) {\r\n\treturn encodeURI(string).replace(/%25[0-9][0-9]/g, function (doubleEncoded) {\r\n\t\treturn \"%\" + doubleEncoded.substring(3);\r\n\t});\r\n}\r\n\r\nfunction uriTemplateSubstitution(spec) {\r\n\tvar modifier = \"\";\r\n\tif (uriTemplateGlobalModifiers[spec.charAt(0)]) {\r\n\t\tmodifier = spec.charAt(0);\r\n\t\tspec = spec.substring(1);\r\n\t}\r\n\tvar separator = \"\";\r\n\tvar prefix = \"\";\r\n\tvar shouldEscape = true;\r\n\tvar showVariables = false;\r\n\tvar trimEmptyString = false;\r\n\tif (modifier === '+') {\r\n\t\tshouldEscape = false;\r\n\t} else if (modifier === \".\") {\r\n\t\tprefix = \".\";\r\n\t\tseparator = \".\";\r\n\t} else if (modifier === \"/\") {\r\n\t\tprefix = \"/\";\r\n\t\tseparator = \"/\";\r\n\t} else if (modifier === '#') {\r\n\t\tprefix = \"#\";\r\n\t\tshouldEscape = false;\r\n\t} else if (modifier === ';') {\r\n\t\tprefix = \";\";\r\n\t\tseparator = \";\";\r\n\t\tshowVariables = true;\r\n\t\ttrimEmptyString = true;\r\n\t} else if (modifier === '?') {\r\n\t\tprefix = \"?\";\r\n\t\tseparator = \"&\";\r\n\t\tshowVariables = true;\r\n\t} else if (modifier === '&') {\r\n\t\tprefix = \"&\";\r\n\t\tseparator = \"&\";\r\n\t\tshowVariables = true;\r\n\t}\r\n\r\n\tvar varNames = [];\r\n\tvar varList = spec.split(\",\");\r\n\tvar varSpecs = [];\r\n\tvar varSpecMap = {};\r\n\tfor (var i = 0; i < varList.length; i++) {\r\n\t\tvar varName = varList[i];\r\n\t\tvar truncate = null;\r\n\t\tif (varName.indexOf(\":\") !== -1) {\r\n\t\t\tvar parts = varName.split(\":\");\r\n\t\t\tvarName = parts[0];\r\n\t\t\ttruncate = parseInt(parts[1], 10);\r\n\t\t}\r\n\t\tvar suffices = {};\r\n\t\twhile (uriTemplateSuffices[varName.charAt(varName.length - 1)]) {\r\n\t\t\tsuffices[varName.charAt(varName.length - 1)] = true;\r\n\t\t\tvarName = varName.substring(0, varName.length - 1);\r\n\t\t}\r\n\t\tvar varSpec = {\r\n\t\t\ttruncate: truncate,\r\n\t\t\tname: varName,\r\n\t\t\tsuffices: suffices\r\n\t\t};\r\n\t\tvarSpecs.push(varSpec);\r\n\t\tvarSpecMap[varName] = varSpec;\r\n\t\tvarNames.push(varName);\r\n\t}\r\n\tvar subFunction = function (valueFunction) {\r\n\t\tvar result = \"\";\r\n\t\tvar startIndex = 0;\r\n\t\tfor (var i = 0; i < varSpecs.length; i++) {\r\n\t\t\tvar varSpec = varSpecs[i];\r\n\t\t\tvar value = valueFunction(varSpec.name);\r\n\t\t\tif (value === null || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof value === 'object' && Object.keys(value).length === 0)) {\r\n\t\t\t\tstartIndex++;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif (i === startIndex) {\r\n\t\t\t\tresult += prefix;\r\n\t\t\t} else {\r\n\t\t\t\tresult += (separator || \",\");\r\n\t\t\t}\r\n\t\t\tif (Array.isArray(value)) {\r\n\t\t\t\tif (showVariables) {\r\n\t\t\t\t\tresult += varSpec.name + \"=\";\r\n\t\t\t\t}\r\n\t\t\t\tfor (var j = 0; j < value.length; j++) {\r\n\t\t\t\t\tif (j > 0) {\r\n\t\t\t\t\t\tresult += varSpec.suffices['*'] ? (separator || \",\") : \",\";\r\n\t\t\t\t\t\tif (varSpec.suffices['*'] && showVariables) {\r\n\t\t\t\t\t\t\tresult += varSpec.name + \"=\";\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tresult += shouldEscape ? encodeURIComponent(value[j]).replace(/!/g, \"%21\") : notReallyPercentEncode(value[j]);\r\n\t\t\t\t}\r\n\t\t\t} else if (typeof value === \"object\") {\r\n\t\t\t\tif (showVariables && !varSpec.suffices['*']) {\r\n\t\t\t\t\tresult += varSpec.name + \"=\";\r\n\t\t\t\t}\r\n\t\t\t\tvar first = true;\r\n\t\t\t\tfor (var key in value) {\r\n\t\t\t\t\tif (!first) {\r\n\t\t\t\t\t\tresult += varSpec.suffices['*'] ? (separator || \",\") : \",\";\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfirst = false;\r\n\t\t\t\t\tresult += shouldEscape ? encodeURIComponent(key).replace(/!/g, \"%21\") : notReallyPercentEncode(key);\r\n\t\t\t\t\tresult += varSpec.suffices['*'] ? '=' : \",\";\r\n\t\t\t\t\tresult += shouldEscape ? encodeURIComponent(value[key]).replace(/!/g, \"%21\") : notReallyPercentEncode(value[key]);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (showVariables) {\r\n\t\t\t\t\tresult += varSpec.name;\r\n\t\t\t\t\tif (!trimEmptyString || value !== \"\") {\r\n\t\t\t\t\t\tresult += \"=\";\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (varSpec.truncate != null) {\r\n\t\t\t\t\tvalue = value.substring(0, varSpec.truncate);\r\n\t\t\t\t}\r\n\t\t\t\tresult += shouldEscape ? encodeURIComponent(value).replace(/!/g, \"%21\"): notReallyPercentEncode(value);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t};\r\n\tsubFunction.varNames = varNames;\r\n\treturn {\r\n\t\tprefix: prefix,\r\n\t\tsubstitution: subFunction\r\n\t};\r\n}\r\n\r\nfunction UriTemplate(template) {\r\n\tif (!(this instanceof UriTemplate)) {\r\n\t\treturn new UriTemplate(template);\r\n\t}\r\n\tvar parts = template.split(\"{\");\r\n\tvar textParts = [parts.shift()];\r\n\tvar prefixes = [];\r\n\tvar substitutions = [];\r\n\tvar varNames = [];\r\n\twhile (parts.length > 0) {\r\n\t\tvar part = parts.shift();\r\n\t\tvar spec = part.split(\"}\")[0];\r\n\t\tvar remainder = part.substring(spec.length + 1);\r\n\t\tvar funcs = uriTemplateSubstitution(spec);\r\n\t\tsubstitutions.push(funcs.substitution);\r\n\t\tprefixes.push(funcs.prefix);\r\n\t\ttextParts.push(remainder);\r\n\t\tvarNames = varNames.concat(funcs.substitution.varNames);\r\n\t}\r\n\tthis.fill = function (valueFunction) {\r\n\t\tvar result = textParts[0];\r\n\t\tfor (var i = 0; i < substitutions.length; i++) {\r\n\t\t\tvar substitution = substitutions[i];\r\n\t\t\tresult += substitution(valueFunction);\r\n\t\t\tresult += textParts[i + 1];\r\n\t\t}\r\n\t\treturn result;\r\n\t};\r\n\tthis.varNames = varNames;\r\n\tthis.template = template;\r\n}\r\nUriTemplate.prototype = {\r\n\ttoString: function () {\r\n\t\treturn this.template;\r\n\t},\r\n\tfillFromObject: function (obj) {\r\n\t\treturn this.fill(function (varName) {\r\n\t\t\treturn obj[varName];\r\n\t\t});\r\n\t}\r\n};\r\nvar ValidatorContext = function ValidatorContext(parent, collectMultiple, errorReporter, checkRecursive, trackUnknownProperties) {\r\n\tthis.missing = [];\r\n\tthis.missingMap = {};\r\n\tthis.formatValidators = parent ? Object.create(parent.formatValidators) : {};\r\n\tthis.schemas = parent ? Object.create(parent.schemas) : {};\r\n\tthis.collectMultiple = collectMultiple;\r\n\tthis.errors = [];\r\n\tthis.handleError = collectMultiple ? this.collectError : this.returnError;\r\n\tif (checkRecursive) {\r\n\t\tthis.checkRecursive = true;\r\n\t\tthis.scanned = [];\r\n\t\tthis.scannedFrozen = [];\r\n\t\tthis.scannedFrozenSchemas = [];\r\n\t\tthis.scannedFrozenValidationErrors = [];\r\n\t\tthis.validatedSchemasKey = 'tv4_validation_id';\r\n\t\tthis.validationErrorsKey = 'tv4_validation_errors_id';\r\n\t}\r\n\tif (trackUnknownProperties) {\r\n\t\tthis.trackUnknownProperties = true;\r\n\t\tthis.knownPropertyPaths = {};\r\n\t\tthis.unknownPropertyPaths = {};\r\n\t}\r\n\tthis.errorReporter = errorReporter || defaultErrorReporter('en');\r\n\tif (typeof this.errorReporter === 'string') {\r\n\t\tthrow new Error('debug');\r\n\t}\r\n\tthis.definedKeywords = {};\r\n\tif (parent) {\r\n\t\tfor (var key in parent.definedKeywords) {\r\n\t\t\tthis.definedKeywords[key] = parent.definedKeywords[key].slice(0);\r\n\t\t}\r\n\t}\r\n};\r\nValidatorContext.prototype.defineKeyword = function (keyword, keywordFunction) {\r\n\tthis.definedKeywords[keyword] = this.definedKeywords[keyword] || [];\r\n\tthis.definedKeywords[keyword].push(keywordFunction);\r\n};\r\nValidatorContext.prototype.createError = function (code, messageParams, dataPath, schemaPath, subErrors, data, schema) {\r\n\tvar error = new ValidationError(code, messageParams, dataPath, schemaPath, subErrors);\r\n\terror.message = this.errorReporter(error, data, schema);\r\n\treturn error;\r\n};\r\nValidatorContext.prototype.returnError = function (error) {\r\n\treturn error;\r\n};\r\nValidatorContext.prototype.collectError = function (error) {\r\n\tif (error) {\r\n\t\tthis.errors.push(error);\r\n\t}\r\n\treturn null;\r\n};\r\nValidatorContext.prototype.prefixErrors = function (startIndex, dataPath, schemaPath) {\r\n\tfor (var i = startIndex; i < this.errors.length; i++) {\r\n\t\tthis.errors[i] = this.errors[i].prefixWith(dataPath, schemaPath);\r\n\t}\r\n\treturn this;\r\n};\r\nValidatorContext.prototype.banUnknownProperties = function (data, schema) {\r\n\tfor (var unknownPath in this.unknownPropertyPaths) {\r\n\t\tvar error = this.createError(ErrorCodes.UNKNOWN_PROPERTY, {path: unknownPath}, unknownPath, \"\", null, data, schema);\r\n\t\tvar result = this.handleError(error);\r\n\t\tif (result) {\r\n\t\t\treturn result;\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.addFormat = function (format, validator) {\r\n\tif (typeof format === 'object') {\r\n\t\tfor (var key in format) {\r\n\t\t\tthis.addFormat(key, format[key]);\r\n\t\t}\r\n\t\treturn this;\r\n\t}\r\n\tthis.formatValidators[format] = validator;\r\n};\r\nValidatorContext.prototype.resolveRefs = function (schema, urlHistory) {\r\n\tif (schema['$ref'] !== undefined) {\r\n\t\turlHistory = urlHistory || {};\r\n\t\tif (urlHistory[schema['$ref']]) {\r\n\t\t\treturn this.createError(ErrorCodes.CIRCULAR_REFERENCE, {urls: Object.keys(urlHistory).join(', ')}, '', '', null, undefined, schema);\r\n\t\t}\r\n\t\turlHistory[schema['$ref']] = true;\r\n\t\tschema = this.getSchema(schema['$ref'], urlHistory);\r\n\t}\r\n\treturn schema;\r\n};\r\nValidatorContext.prototype.getSchema = function (url, urlHistory) {\r\n\tvar schema;\r\n\tif (this.schemas[url] !== undefined) {\r\n\t\tschema = this.schemas[url];\r\n\t\treturn this.resolveRefs(schema, urlHistory);\r\n\t}\r\n\tvar baseUrl = url;\r\n\tvar fragment = \"\";\r\n\tif (url.indexOf('#') !== -1) {\r\n\t\tfragment = url.substring(url.indexOf(\"#\") + 1);\r\n\t\tbaseUrl = url.substring(0, url.indexOf(\"#\"));\r\n\t}\r\n\tif (typeof this.schemas[baseUrl] === 'object') {\r\n\t\tschema = this.schemas[baseUrl];\r\n\t\tvar pointerPath = decodeURIComponent(fragment);\r\n\t\tif (pointerPath === \"\") {\r\n\t\t\treturn this.resolveRefs(schema, urlHistory);\r\n\t\t} else if (pointerPath.charAt(0) !== \"/\") {\r\n\t\t\treturn undefined;\r\n\t\t}\r\n\t\tvar parts = pointerPath.split(\"/\").slice(1);\r\n\t\tfor (var i = 0; i < parts.length; i++) {\r\n\t\t\tvar component = parts[i].replace(/~1/g, \"/\").replace(/~0/g, \"~\");\r\n\t\t\tif (schema[component] === undefined) {\r\n\t\t\t\tschema = undefined;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tschema = schema[component];\r\n\t\t}\r\n\t\tif (schema !== undefined) {\r\n\t\t\treturn this.resolveRefs(schema, urlHistory);\r\n\t\t}\r\n\t}\r\n\tif (this.missing[baseUrl] === undefined) {\r\n\t\tthis.missing.push(baseUrl);\r\n\t\tthis.missing[baseUrl] = baseUrl;\r\n\t\tthis.missingMap[baseUrl] = baseUrl;\r\n\t}\r\n};\r\nValidatorContext.prototype.searchSchemas = function (schema, url) {\r\n\tif (Array.isArray(schema)) {\r\n\t\tfor (var i = 0; i < schema.length; i++) {\r\n\t\t\tthis.searchSchemas(schema[i], url);\r\n\t\t}\r\n\t} else if (schema && typeof schema === \"object\") {\r\n\t\tif (typeof schema.id === \"string\") {\r\n\t\t\tif (isTrustedUrl(url, schema.id)) {\r\n\t\t\t\tif (this.schemas[schema.id] === undefined) {\r\n\t\t\t\t\tthis.schemas[schema.id] = schema;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (var key in schema) {\r\n\t\t\tif (key !== \"enum\") {\r\n\t\t\t\tif (typeof schema[key] === \"object\") {\r\n\t\t\t\t\tthis.searchSchemas(schema[key], url);\r\n\t\t\t\t} else if (key === \"$ref\") {\r\n\t\t\t\t\tvar uri = getDocumentUri(schema[key]);\r\n\t\t\t\t\tif (uri && this.schemas[uri] === undefined && this.missingMap[uri] === undefined) {\r\n\t\t\t\t\t\tthis.missingMap[uri] = uri;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\nValidatorContext.prototype.addSchema = function (url, schema) {\r\n\t//overload\r\n\tif (typeof url !== 'string' || typeof schema === 'undefined') {\r\n\t\tif (typeof url === 'object' && typeof url.id === 'string') {\r\n\t\t\tschema = url;\r\n\t\t\turl = schema.id;\r\n\t\t}\r\n\t\telse {\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\tif (url === getDocumentUri(url) + \"#\") {\r\n\t\t// Remove empty fragment\r\n\t\turl = getDocumentUri(url);\r\n\t}\r\n\tthis.schemas[url] = schema;\r\n\tdelete this.missingMap[url];\r\n\tnormSchema(schema, url);\r\n\tthis.searchSchemas(schema, url);\r\n};\r\n\r\nValidatorContext.prototype.getSchemaMap = function () {\r\n\tvar map = {};\r\n\tfor (var key in this.schemas) {\r\n\t\tmap[key] = this.schemas[key];\r\n\t}\r\n\treturn map;\r\n};\r\n\r\nValidatorContext.prototype.getSchemaUris = function (filterRegExp) {\r\n\tvar list = [];\r\n\tfor (var key in this.schemas) {\r\n\t\tif (!filterRegExp || filterRegExp.test(key)) {\r\n\t\t\tlist.push(key);\r\n\t\t}\r\n\t}\r\n\treturn list;\r\n};\r\n\r\nValidatorContext.prototype.getMissingUris = function (filterRegExp) {\r\n\tvar list = [];\r\n\tfor (var key in this.missingMap) {\r\n\t\tif (!filterRegExp || filterRegExp.test(key)) {\r\n\t\t\tlist.push(key);\r\n\t\t}\r\n\t}\r\n\treturn list;\r\n};\r\n\r\nValidatorContext.prototype.dropSchemas = function () {\r\n\tthis.schemas = {};\r\n\tthis.reset();\r\n};\r\nValidatorContext.prototype.reset = function () {\r\n\tthis.missing = [];\r\n\tthis.missingMap = {};\r\n\tthis.errors = [];\r\n};\r\n\r\nValidatorContext.prototype.validateAll = function (data, schema, dataPathParts, schemaPathParts, dataPointerPath) {\r\n\tvar topLevel;\r\n\tschema = this.resolveRefs(schema);\r\n\tif (!schema) {\r\n\t\treturn null;\r\n\t} else if (schema instanceof ValidationError) {\r\n\t\tthis.errors.push(schema);\r\n\t\treturn schema;\r\n\t}\r\n\r\n\tvar startErrorCount = this.errors.length;\r\n\tvar frozenIndex, scannedFrozenSchemaIndex = null, scannedSchemasIndex = null;\r\n\tif (this.checkRecursive && data && typeof data === 'object') {\r\n\t\ttopLevel = !this.scanned.length;\r\n\t\tif (data[this.validatedSchemasKey]) {\r\n\t\t\tvar schemaIndex = data[this.validatedSchemasKey].indexOf(schema);\r\n\t\t\tif (schemaIndex !== -1) {\r\n\t\t\t\tthis.errors = this.errors.concat(data[this.validationErrorsKey][schemaIndex]);\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (Object.isFrozen(data)) {\r\n\t\t\tfrozenIndex = this.scannedFrozen.indexOf(data);\r\n\t\t\tif (frozenIndex !== -1) {\r\n\t\t\t\tvar frozenSchemaIndex = this.scannedFrozenSchemas[frozenIndex].indexOf(schema);\r\n\t\t\t\tif (frozenSchemaIndex !== -1) {\r\n\t\t\t\t\tthis.errors = this.errors.concat(this.scannedFrozenValidationErrors[frozenIndex][frozenSchemaIndex]);\r\n\t\t\t\t\treturn null;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.scanned.push(data);\r\n\t\tif (Object.isFrozen(data)) {\r\n\t\t\tif (frozenIndex === -1) {\r\n\t\t\t\tfrozenIndex = this.scannedFrozen.length;\r\n\t\t\t\tthis.scannedFrozen.push(data);\r\n\t\t\t\tthis.scannedFrozenSchemas.push([]);\r\n\t\t\t}\r\n\t\t\tscannedFrozenSchemaIndex = this.scannedFrozenSchemas[frozenIndex].length;\r\n\t\t\tthis.scannedFrozenSchemas[frozenIndex][scannedFrozenSchemaIndex] = schema;\r\n\t\t\tthis.scannedFrozenValidationErrors[frozenIndex][scannedFrozenSchemaIndex] = [];\r\n\t\t} else {\r\n\t\t\tif (!data[this.validatedSchemasKey]) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tObject.defineProperty(data, this.validatedSchemasKey, {\r\n\t\t\t\t\t\tvalue: [],\r\n\t\t\t\t\t\tconfigurable: true\r\n\t\t\t\t\t});\r\n\t\t\t\t\tObject.defineProperty(data, this.validationErrorsKey, {\r\n\t\t\t\t\t\tvalue: [],\r\n\t\t\t\t\t\tconfigurable: true\r\n\t\t\t\t\t});\r\n\t\t\t\t} catch (e) {\r\n\t\t\t\t\t//IE 7/8 workaround\r\n\t\t\t\t\tdata[this.validatedSchemasKey] = [];\r\n\t\t\t\t\tdata[this.validationErrorsKey] = [];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tscannedSchemasIndex = data[this.validatedSchemasKey].length;\r\n\t\t\tdata[this.validatedSchemasKey][scannedSchemasIndex] = schema;\r\n\t\t\tdata[this.validationErrorsKey][scannedSchemasIndex] = [];\r\n\t\t}\r\n\t}\r\n\r\n\tvar errorCount = this.errors.length;\r\n\tvar error = this.validateBasic(data, schema, dataPointerPath)\r\n\t\t|| this.validateNumeric(data, schema, dataPointerPath)\r\n\t\t|| this.validateString(data, schema, dataPointerPath)\r\n\t\t|| this.validateArray(data, schema, dataPointerPath)\r\n\t\t|| this.validateObject(data, schema, dataPointerPath)\r\n\t\t|| this.validateCombinations(data, schema, dataPointerPath)\r\n\t\t|| this.validateHypermedia(data, schema, dataPointerPath)\r\n\t\t|| this.validateFormat(data, schema, dataPointerPath)\r\n\t\t|| this.validateDefinedKeywords(data, schema, dataPointerPath)\r\n\t\t|| null;\r\n\r\n\tif (topLevel) {\r\n\t\twhile (this.scanned.length) {\r\n\t\t\tvar item = this.scanned.pop();\r\n\t\t\tdelete item[this.validatedSchemasKey];\r\n\t\t}\r\n\t\tthis.scannedFrozen = [];\r\n\t\tthis.scannedFrozenSchemas = [];\r\n\t}\r\n\r\n\tif (error || errorCount !== this.errors.length) {\r\n\t\twhile ((dataPathParts && dataPathParts.length) || (schemaPathParts && schemaPathParts.length)) {\r\n\t\t\tvar dataPart = (dataPathParts && dataPathParts.length) ? \"\" + dataPathParts.pop() : null;\r\n\t\t\tvar schemaPart = (schemaPathParts && schemaPathParts.length) ? \"\" + schemaPathParts.pop() : null;\r\n\t\t\tif (error) {\r\n\t\t\t\terror = error.prefixWith(dataPart, schemaPart);\r\n\t\t\t}\r\n\t\t\tthis.prefixErrors(errorCount, dataPart, schemaPart);\r\n\t\t}\r\n\t}\r\n\r\n\tif (scannedFrozenSchemaIndex !== null) {\r\n\t\tthis.scannedFrozenValidationErrors[frozenIndex][scannedFrozenSchemaIndex] = this.errors.slice(startErrorCount);\r\n\t} else if (scannedSchemasIndex !== null) {\r\n\t\tdata[this.validationErrorsKey][scannedSchemasIndex] = this.errors.slice(startErrorCount);\r\n\t}\r\n\r\n\treturn this.handleError(error);\r\n};\r\nValidatorContext.prototype.validateFormat = function (data, schema) {\r\n\tif (typeof schema.format !== 'string' || !this.formatValidators[schema.format]) {\r\n\t\treturn null;\r\n\t}\r\n\tvar errorMessage = this.formatValidators[schema.format].call(null, data, schema);\r\n\tif (typeof errorMessage === 'string' || typeof errorMessage === 'number') {\r\n\t\treturn this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage}, '', '/format', null, data, schema);\r\n\t} else if (errorMessage && typeof errorMessage === 'object') {\r\n\t\treturn this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage.message || \"?\"}, errorMessage.dataPath || '', errorMessage.schemaPath || \"/format\", null, data, schema);\r\n\t}\r\n\treturn null;\r\n};\r\nValidatorContext.prototype.validateDefinedKeywords = function (data, schema, dataPointerPath) {\r\n\tfor (var key in this.definedKeywords) {\r\n\t\tif (typeof schema[key] === 'undefined') {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tvar validationFunctions = this.definedKeywords[key];\r\n\t\tfor (var i = 0; i < validationFunctions.length; i++) {\r\n\t\t\tvar func = validationFunctions[i];\r\n\t\t\tvar result = func(data, schema[key], schema, dataPointerPath);\r\n\t\t\tif (typeof result === 'string' || typeof result === 'number') {\r\n\t\t\t\treturn this.createError(ErrorCodes.KEYWORD_CUSTOM, {key: key, message: result}, '', '', null, data, schema).prefixWith(null, key);\r\n\t\t\t} else if (result && typeof result === 'object') {\r\n\t\t\t\tvar code = result.code;\r\n\t\t\t\tif (typeof code === 'string') {\r\n\t\t\t\t\tif (!ErrorCodes[code]) {\r\n\t\t\t\t\t\tthrow new Error('Undefined error code (use defineError): ' + code);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcode = ErrorCodes[code];\r\n\t\t\t\t} else if (typeof code !== 'number') {\r\n\t\t\t\t\tcode = ErrorCodes.KEYWORD_CUSTOM;\r\n\t\t\t\t}\r\n\t\t\t\tvar messageParams = (typeof result.message === 'object') ? result.message : {key: key, message: result.message || \"?\"};\r\n\t\t\t\tvar schemaPath = result.schemaPath || (\"/\" + key.replace(/~/g, '~0').replace(/\\//g, '~1'));\r\n\t\t\t\treturn this.createError(code, messageParams, result.dataPath || null, schemaPath, null, data, schema);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nfunction recursiveCompare(A, B) {\r\n\tif (A === B) {\r\n\t\treturn true;\r\n\t}\r\n\tif (A && B && typeof A === \"object\" && typeof B === \"object\") {\r\n\t\tif (Array.isArray(A) !== Array.isArray(B)) {\r\n\t\t\treturn false;\r\n\t\t} else if (Array.isArray(A)) {\r\n\t\t\tif (A.length !== B.length) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\tfor (var i = 0; i < A.length; i++) {\r\n\t\t\t\tif (!recursiveCompare(A[i], B[i])) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tvar key;\r\n\t\t\tfor (key in A) {\r\n\t\t\t\tif (B[key] === undefined && A[key] !== undefined) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (key in B) {\r\n\t\t\t\tif (A[key] === undefined && B[key] !== undefined) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (key in A) {\r\n\t\t\t\tif (!recursiveCompare(A[key], B[key])) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nValidatorContext.prototype.validateBasic = function validateBasic(data, schema, dataPointerPath) {\r\n\tvar error;\r\n\tif (error = this.validateType(data, schema, dataPointerPath)) {\r\n\t\treturn error.prefixWith(null, \"type\");\r\n\t}\r\n\tif (error = this.validateEnum(data, schema, dataPointerPath)) {\r\n\t\treturn error.prefixWith(null, \"type\");\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateType = function validateType(data, schema) {\r\n\tif (schema.type === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tvar dataType = typeof data;\r\n\tif (data === null) {\r\n\t\tdataType = \"null\";\r\n\t} else if (Array.isArray(data)) {\r\n\t\tdataType = \"array\";\r\n\t}\r\n\tvar allowedTypes = schema.type;\r\n\tif (!Array.isArray(allowedTypes)) {\r\n\t\tallowedTypes = [allowedTypes];\r\n\t}\r\n\r\n\tfor (var i = 0; i < allowedTypes.length; i++) {\r\n\t\tvar type = allowedTypes[i];\r\n\t\tif (type === dataType || (type === \"integer\" && dataType === \"number\" && (data % 1 === 0))) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\treturn this.createError(ErrorCodes.INVALID_TYPE, {type: dataType, expected: allowedTypes.join(\"/\")}, '', '', null, data, schema);\r\n};\r\n\r\nValidatorContext.prototype.validateEnum = function validateEnum(data, schema) {\r\n\tif (schema[\"enum\"] === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tfor (var i = 0; i < schema[\"enum\"].length; i++) {\r\n\t\tvar enumVal = schema[\"enum\"][i];\r\n\t\tif (recursiveCompare(data, enumVal)) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\treturn this.createError(ErrorCodes.ENUM_MISMATCH, {value: (typeof JSON !== 'undefined') ? JSON.stringify(data) : data}, '', '', null, data, schema);\r\n};\r\n\r\nValidatorContext.prototype.validateNumeric = function validateNumeric(data, schema, dataPointerPath) {\r\n\treturn this.validateMultipleOf(data, schema, dataPointerPath)\r\n\t\t|| this.validateMinMax(data, schema, dataPointerPath)\r\n\t\t|| this.validateNaN(data, schema, dataPointerPath)\r\n\t\t|| null;\r\n};\r\n\r\nvar CLOSE_ENOUGH_LOW = Math.pow(2, -51);\r\nvar CLOSE_ENOUGH_HIGH = 1 - CLOSE_ENOUGH_LOW;\r\nValidatorContext.prototype.validateMultipleOf = function validateMultipleOf(data, schema) {\r\n\tvar multipleOf = schema.multipleOf || schema.divisibleBy;\r\n\tif (multipleOf === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tif (typeof data === \"number\") {\r\n\t\tvar remainder = (data/multipleOf)%1;\r\n\t\tif (remainder >= CLOSE_ENOUGH_LOW && remainder < CLOSE_ENOUGH_HIGH) {\r\n\t\t\treturn this.createError(ErrorCodes.NUMBER_MULTIPLE_OF, {value: data, multipleOf: multipleOf}, '', '', null, data, schema);\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateMinMax = function validateMinMax(data, schema) {\r\n\tif (typeof data !== \"number\") {\r\n\t\treturn null;\r\n\t}\r\n\tif (schema.minimum !== undefined) {\r\n\t\tif (data < schema.minimum) {\r\n\t\t\treturn this.createError(ErrorCodes.NUMBER_MINIMUM, {value: data, minimum: schema.minimum}, '', '/minimum', null, data, schema);\r\n\t\t}\r\n\t\tif (schema.exclusiveMinimum && data === schema.minimum) {\r\n\t\t\treturn this.createError(ErrorCodes.NUMBER_MINIMUM_EXCLUSIVE, {value: data, minimum: schema.minimum}, '', '/exclusiveMinimum', null, data, schema);\r\n\t\t}\r\n\t}\r\n\tif (schema.maximum !== undefined) {\r\n\t\tif (data > schema.maximum) {\r\n\t\t\treturn this.createError(ErrorCodes.NUMBER_MAXIMUM, {value: data, maximum: schema.maximum}, '', '/maximum', null, data, schema);\r\n\t\t}\r\n\t\tif (schema.exclusiveMaximum && data === schema.maximum) {\r\n\t\t\treturn this.createError(ErrorCodes.NUMBER_MAXIMUM_EXCLUSIVE, {value: data, maximum: schema.maximum}, '', '/exclusiveMaximum', null, data, schema);\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateNaN = function validateNaN(data, schema) {\r\n\tif (typeof data !== \"number\") {\r\n\t\treturn null;\r\n\t}\r\n\tif (isNaN(data) === true || data === Infinity || data === -Infinity) {\r\n\t\treturn this.createError(ErrorCodes.NUMBER_NOT_A_NUMBER, {value: data}, '', '/type', null, data, schema);\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateString = function validateString(data, schema, dataPointerPath) {\r\n\treturn this.validateStringLength(data, schema, dataPointerPath)\r\n\t\t|| this.validateStringPattern(data, schema, dataPointerPath)\r\n\t\t|| null;\r\n};\r\n\r\nValidatorContext.prototype.validateStringLength = function validateStringLength(data, schema) {\r\n\tif (typeof data !== \"string\") {\r\n\t\treturn null;\r\n\t}\r\n\tif (schema.minLength !== undefined) {\r\n\t\tif (data.length < schema.minLength) {\r\n\t\t\treturn this.createError(ErrorCodes.STRING_LENGTH_SHORT, {length: data.length, minimum: schema.minLength}, '', '/minLength', null, data, schema);\r\n\t\t}\r\n\t}\r\n\tif (schema.maxLength !== undefined) {\r\n\t\tif (data.length > schema.maxLength) {\r\n\t\t\treturn this.createError(ErrorCodes.STRING_LENGTH_LONG, {length: data.length, maximum: schema.maxLength}, '', '/maxLength', null, data, schema);\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateStringPattern = function validateStringPattern(data, schema) {\r\n\tif (typeof data !== \"string\" || (typeof schema.pattern !== \"string\" && !(schema.pattern instanceof RegExp))) {\r\n\t\treturn null;\r\n\t}\r\n\tvar regexp;\r\n\tif (schema.pattern instanceof RegExp) {\r\n\t regexp = schema.pattern;\r\n\t}\r\n\telse {\r\n\t var body, flags = '';\r\n\t // Check for regular expression literals\r\n\t // @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5\r\n\t var literal = schema.pattern.match(/^\\/(.+)\\/([img]*)$/);\r\n\t if (literal) {\r\n\t body = literal[1];\r\n\t flags = literal[2];\r\n\t }\r\n\t else {\r\n\t body = schema.pattern;\r\n\t }\r\n\t regexp = new RegExp(body, flags);\r\n\t}\r\n\tif (!regexp.test(data)) {\r\n\t\treturn this.createError(ErrorCodes.STRING_PATTERN, {pattern: schema.pattern}, '', '/pattern', null, data, schema);\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateArray = function validateArray(data, schema, dataPointerPath) {\r\n\tif (!Array.isArray(data)) {\r\n\t\treturn null;\r\n\t}\r\n\treturn this.validateArrayLength(data, schema, dataPointerPath)\r\n\t\t|| this.validateArrayUniqueItems(data, schema, dataPointerPath)\r\n\t\t|| this.validateArrayItems(data, schema, dataPointerPath)\r\n\t\t|| null;\r\n};\r\n\r\nValidatorContext.prototype.validateArrayLength = function validateArrayLength(data, schema) {\r\n\tvar error;\r\n\tif (schema.minItems !== undefined) {\r\n\t\tif (data.length < schema.minItems) {\r\n\t\t\terror = this.createError(ErrorCodes.ARRAY_LENGTH_SHORT, {length: data.length, minimum: schema.minItems}, '', '/minItems', null, data, schema);\r\n\t\t\tif (this.handleError(error)) {\r\n\t\t\t\treturn error;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (schema.maxItems !== undefined) {\r\n\t\tif (data.length > schema.maxItems) {\r\n\t\t\terror = this.createError(ErrorCodes.ARRAY_LENGTH_LONG, {length: data.length, maximum: schema.maxItems}, '', '/maxItems', null, data, schema);\r\n\t\t\tif (this.handleError(error)) {\r\n\t\t\t\treturn error;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateArrayUniqueItems = function validateArrayUniqueItems(data, schema) {\r\n\tif (schema.uniqueItems) {\r\n\t\tfor (var i = 0; i < data.length; i++) {\r\n\t\t\tfor (var j = i + 1; j < data.length; j++) {\r\n\t\t\t\tif (recursiveCompare(data[i], data[j])) {\r\n\t\t\t\t\tvar error = this.createError(ErrorCodes.ARRAY_UNIQUE, {match1: i, match2: j}, '', '/uniqueItems', null, data, schema);\r\n\t\t\t\t\tif (this.handleError(error)) {\r\n\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateArrayItems = function validateArrayItems(data, schema, dataPointerPath) {\r\n\tif (schema.items === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tvar error, i;\r\n\tif (Array.isArray(schema.items)) {\r\n\t\tfor (i = 0; i < data.length; i++) {\r\n\t\t\tif (i < schema.items.length) {\r\n\t\t\t\tif (error = this.validateAll(data[i], schema.items[i], [i], [\"items\", i], dataPointerPath + \"/\" + i)) {\r\n\t\t\t\t\treturn error;\r\n\t\t\t\t}\r\n\t\t\t} else if (schema.additionalItems !== undefined) {\r\n\t\t\t\tif (typeof schema.additionalItems === \"boolean\") {\r\n\t\t\t\t\tif (!schema.additionalItems) {\r\n\t\t\t\t\t\terror = (this.createError(ErrorCodes.ARRAY_ADDITIONAL_ITEMS, {}, '/' + i, '/additionalItems', null, data, schema));\r\n\t\t\t\t\t\tif (this.handleError(error)) {\r\n\t\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if (error = this.validateAll(data[i], schema.additionalItems, [i], [\"additionalItems\"], dataPointerPath + \"/\" + i)) {\r\n\t\t\t\t\treturn error;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t} else {\r\n\t\tfor (i = 0; i < data.length; i++) {\r\n\t\t\tif (error = this.validateAll(data[i], schema.items, [i], [\"items\"], dataPointerPath + \"/\" + i)) {\r\n\t\t\t\treturn error;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateObject = function validateObject(data, schema, dataPointerPath) {\r\n\tif (typeof data !== \"object\" || data === null || Array.isArray(data)) {\r\n\t\treturn null;\r\n\t}\r\n\treturn this.validateObjectMinMaxProperties(data, schema, dataPointerPath)\r\n\t\t|| this.validateObjectRequiredProperties(data, schema, dataPointerPath)\r\n\t\t|| this.validateObjectProperties(data, schema, dataPointerPath)\r\n\t\t|| this.validateObjectDependencies(data, schema, dataPointerPath)\r\n\t\t|| null;\r\n};\r\n\r\nValidatorContext.prototype.validateObjectMinMaxProperties = function validateObjectMinMaxProperties(data, schema) {\r\n\tvar keys = Object.keys(data);\r\n\tvar error;\r\n\tif (schema.minProperties !== undefined) {\r\n\t\tif (keys.length < schema.minProperties) {\r\n\t\t\terror = this.createError(ErrorCodes.OBJECT_PROPERTIES_MINIMUM, {propertyCount: keys.length, minimum: schema.minProperties}, '', '/minProperties', null, data, schema);\r\n\t\t\tif (this.handleError(error)) {\r\n\t\t\t\treturn error;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (schema.maxProperties !== undefined) {\r\n\t\tif (keys.length > schema.maxProperties) {\r\n\t\t\terror = this.createError(ErrorCodes.OBJECT_PROPERTIES_MAXIMUM, {propertyCount: keys.length, maximum: schema.maxProperties}, '', '/maxProperties', null, data, schema);\r\n\t\t\tif (this.handleError(error)) {\r\n\t\t\t\treturn error;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateObjectRequiredProperties = function validateObjectRequiredProperties(data, schema) {\r\n\tif (schema.required !== undefined) {\r\n\t\tfor (var i = 0; i < schema.required.length; i++) {\r\n\t\t\tvar key = schema.required[i];\r\n\t\t\tif (data[key] === undefined) {\r\n\t\t\t\tvar error = this.createError(ErrorCodes.OBJECT_REQUIRED, {key: key}, '', '/required/' + i, null, data, schema);\r\n\t\t\t\tif (this.handleError(error)) {\r\n\t\t\t\t\treturn error;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateObjectProperties = function validateObjectProperties(data, schema, dataPointerPath) {\r\n\tvar error;\r\n\tfor (var key in data) {\r\n\t\tvar keyPointerPath = dataPointerPath + \"/\" + key.replace(/~/g, '~0').replace(/\\//g, '~1');\r\n\t\tvar foundMatch = false;\r\n\t\tif (schema.properties !== undefined && schema.properties[key] !== undefined) {\r\n\t\t\tfoundMatch = true;\r\n\t\t\tif (error = this.validateAll(data[key], schema.properties[key], [key], [\"properties\", key], keyPointerPath)) {\r\n\t\t\t\treturn error;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (schema.patternProperties !== undefined) {\r\n\t\t\tfor (var patternKey in schema.patternProperties) {\r\n\t\t\t\tvar regexp = new RegExp(patternKey);\r\n\t\t\t\tif (regexp.test(key)) {\r\n\t\t\t\t\tfoundMatch = true;\r\n\t\t\t\t\tif (error = this.validateAll(data[key], schema.patternProperties[patternKey], [key], [\"patternProperties\", patternKey], keyPointerPath)) {\r\n\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!foundMatch) {\r\n\t\t\tif (schema.additionalProperties !== undefined) {\r\n\t\t\t\tif (this.trackUnknownProperties) {\r\n\t\t\t\t\tthis.knownPropertyPaths[keyPointerPath] = true;\r\n\t\t\t\t\tdelete this.unknownPropertyPaths[keyPointerPath];\r\n\t\t\t\t}\r\n\t\t\t\tif (typeof schema.additionalProperties === \"boolean\") {\r\n\t\t\t\t\tif (!schema.additionalProperties) {\r\n\t\t\t\t\t\terror = this.createError(ErrorCodes.OBJECT_ADDITIONAL_PROPERTIES, {key: key}, '', '/additionalProperties', null, data, schema).prefixWith(key, null);\r\n\t\t\t\t\t\tif (this.handleError(error)) {\r\n\t\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (error = this.validateAll(data[key], schema.additionalProperties, [key], [\"additionalProperties\"], keyPointerPath)) {\r\n\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else if (this.trackUnknownProperties && !this.knownPropertyPaths[keyPointerPath]) {\r\n\t\t\t\tthis.unknownPropertyPaths[keyPointerPath] = true;\r\n\t\t\t}\r\n\t\t} else if (this.trackUnknownProperties) {\r\n\t\t\tthis.knownPropertyPaths[keyPointerPath] = true;\r\n\t\t\tdelete this.unknownPropertyPaths[keyPointerPath];\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateObjectDependencies = function validateObjectDependencies(data, schema, dataPointerPath) {\r\n\tvar error;\r\n\tif (schema.dependencies !== undefined) {\r\n\t\tfor (var depKey in schema.dependencies) {\r\n\t\t\tif (data[depKey] !== undefined) {\r\n\t\t\t\tvar dep = schema.dependencies[depKey];\r\n\t\t\t\tif (typeof dep === \"string\") {\r\n\t\t\t\t\tif (data[dep] === undefined) {\r\n\t\t\t\t\t\terror = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: dep}, '', '', null, data, schema).prefixWith(null, depKey).prefixWith(null, \"dependencies\");\r\n\t\t\t\t\t\tif (this.handleError(error)) {\r\n\t\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if (Array.isArray(dep)) {\r\n\t\t\t\t\tfor (var i = 0; i < dep.length; i++) {\r\n\t\t\t\t\t\tvar requiredKey = dep[i];\r\n\t\t\t\t\t\tif (data[requiredKey] === undefined) {\r\n\t\t\t\t\t\t\terror = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: requiredKey}, '', '/' + i, null, data, schema).prefixWith(null, depKey).prefixWith(null, \"dependencies\");\r\n\t\t\t\t\t\t\tif (this.handleError(error)) {\r\n\t\t\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (error = this.validateAll(data, dep, [], [\"dependencies\", depKey], dataPointerPath)) {\r\n\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateCombinations = function validateCombinations(data, schema, dataPointerPath) {\r\n\treturn this.validateAllOf(data, schema, dataPointerPath)\r\n\t\t|| this.validateAnyOf(data, schema, dataPointerPath)\r\n\t\t|| this.validateOneOf(data, schema, dataPointerPath)\r\n\t\t|| this.validateNot(data, schema, dataPointerPath)\r\n\t\t|| null;\r\n};\r\n\r\nValidatorContext.prototype.validateAllOf = function validateAllOf(data, schema, dataPointerPath) {\r\n\tif (schema.allOf === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tvar error;\r\n\tfor (var i = 0; i < schema.allOf.length; i++) {\r\n\t\tvar subSchema = schema.allOf[i];\r\n\t\tif (error = this.validateAll(data, subSchema, [], [\"allOf\", i], dataPointerPath)) {\r\n\t\t\treturn error;\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateAnyOf = function validateAnyOf(data, schema, dataPointerPath) {\r\n\tif (schema.anyOf === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tvar errors = [];\r\n\tvar startErrorCount = this.errors.length;\r\n\tvar oldUnknownPropertyPaths, oldKnownPropertyPaths;\r\n\tif (this.trackUnknownProperties) {\r\n\t\toldUnknownPropertyPaths = this.unknownPropertyPaths;\r\n\t\toldKnownPropertyPaths = this.knownPropertyPaths;\r\n\t}\r\n\tvar errorAtEnd = true;\r\n\tfor (var i = 0; i < schema.anyOf.length; i++) {\r\n\t\tif (this.trackUnknownProperties) {\r\n\t\t\tthis.unknownPropertyPaths = {};\r\n\t\t\tthis.knownPropertyPaths = {};\r\n\t\t}\r\n\t\tvar subSchema = schema.anyOf[i];\r\n\r\n\t\tvar errorCount = this.errors.length;\r\n\t\tvar error = this.validateAll(data, subSchema, [], [\"anyOf\", i], dataPointerPath);\r\n\r\n\t\tif (error === null && errorCount === this.errors.length) {\r\n\t\t\tthis.errors = this.errors.slice(0, startErrorCount);\r\n\r\n\t\t\tif (this.trackUnknownProperties) {\r\n\t\t\t\tfor (var knownKey in this.knownPropertyPaths) {\r\n\t\t\t\t\toldKnownPropertyPaths[knownKey] = true;\r\n\t\t\t\t\tdelete oldUnknownPropertyPaths[knownKey];\r\n\t\t\t\t}\r\n\t\t\t\tfor (var unknownKey in this.unknownPropertyPaths) {\r\n\t\t\t\t\tif (!oldKnownPropertyPaths[unknownKey]) {\r\n\t\t\t\t\t\toldUnknownPropertyPaths[unknownKey] = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t// We need to continue looping so we catch all the property definitions, but we don't want to return an error\r\n\t\t\t\terrorAtEnd = false;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (error) {\r\n\t\t\terrors.push(error.prefixWith(null, \"\" + i).prefixWith(null, \"anyOf\"));\r\n\t\t}\r\n\t}\r\n\tif (this.trackUnknownProperties) {\r\n\t\tthis.unknownPropertyPaths = oldUnknownPropertyPaths;\r\n\t\tthis.knownPropertyPaths = oldKnownPropertyPaths;\r\n\t}\r\n\tif (errorAtEnd) {\r\n\t\terrors = errors.concat(this.errors.slice(startErrorCount));\r\n\t\tthis.errors = this.errors.slice(0, startErrorCount);\r\n\t\treturn this.createError(ErrorCodes.ANY_OF_MISSING, {}, \"\", \"/anyOf\", errors, data, schema);\r\n\t}\r\n};\r\n\r\nValidatorContext.prototype.validateOneOf = function validateOneOf(data, schema, dataPointerPath) {\r\n\tif (schema.oneOf === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tvar validIndex = null;\r\n\tvar errors = [];\r\n\tvar startErrorCount = this.errors.length;\r\n\tvar oldUnknownPropertyPaths, oldKnownPropertyPaths;\r\n\tif (this.trackUnknownProperties) {\r\n\t\toldUnknownPropertyPaths = this.unknownPropertyPaths;\r\n\t\toldKnownPropertyPaths = this.knownPropertyPaths;\r\n\t}\r\n\tfor (var i = 0; i < schema.oneOf.length; i++) {\r\n\t\tif (this.trackUnknownProperties) {\r\n\t\t\tthis.unknownPropertyPaths = {};\r\n\t\t\tthis.knownPropertyPaths = {};\r\n\t\t}\r\n\t\tvar subSchema = schema.oneOf[i];\r\n\r\n\t\tvar errorCount = this.errors.length;\r\n\t\tvar error = this.validateAll(data, subSchema, [], [\"oneOf\", i], dataPointerPath);\r\n\r\n\t\tif (error === null && errorCount === this.errors.length) {\r\n\t\t\tif (validIndex === null) {\r\n\t\t\t\tvalidIndex = i;\r\n\t\t\t} else {\r\n\t\t\t\tthis.errors = this.errors.slice(0, startErrorCount);\r\n\t\t\t\treturn this.createError(ErrorCodes.ONE_OF_MULTIPLE, {index1: validIndex, index2: i}, \"\", \"/oneOf\", null, data, schema);\r\n\t\t\t}\r\n\t\t\tif (this.trackUnknownProperties) {\r\n\t\t\t\tfor (var knownKey in this.knownPropertyPaths) {\r\n\t\t\t\t\toldKnownPropertyPaths[knownKey] = true;\r\n\t\t\t\t\tdelete oldUnknownPropertyPaths[knownKey];\r\n\t\t\t\t}\r\n\t\t\t\tfor (var unknownKey in this.unknownPropertyPaths) {\r\n\t\t\t\t\tif (!oldKnownPropertyPaths[unknownKey]) {\r\n\t\t\t\t\t\toldUnknownPropertyPaths[unknownKey] = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else if (error) {\r\n\t\t\terrors.push(error);\r\n\t\t}\r\n\t}\r\n\tif (this.trackUnknownProperties) {\r\n\t\tthis.unknownPropertyPaths = oldUnknownPropertyPaths;\r\n\t\tthis.knownPropertyPaths = oldKnownPropertyPaths;\r\n\t}\r\n\tif (validIndex === null) {\r\n\t\terrors = errors.concat(this.errors.slice(startErrorCount));\r\n\t\tthis.errors = this.errors.slice(0, startErrorCount);\r\n\t\treturn this.createError(ErrorCodes.ONE_OF_MISSING, {}, \"\", \"/oneOf\", errors, data, schema);\r\n\t} else {\r\n\t\tthis.errors = this.errors.slice(0, startErrorCount);\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateNot = function validateNot(data, schema, dataPointerPath) {\r\n\tif (schema.not === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tvar oldErrorCount = this.errors.length;\r\n\tvar oldUnknownPropertyPaths, oldKnownPropertyPaths;\r\n\tif (this.trackUnknownProperties) {\r\n\t\toldUnknownPropertyPaths = this.unknownPropertyPaths;\r\n\t\toldKnownPropertyPaths = this.knownPropertyPaths;\r\n\t\tthis.unknownPropertyPaths = {};\r\n\t\tthis.knownPropertyPaths = {};\r\n\t}\r\n\tvar error = this.validateAll(data, schema.not, null, null, dataPointerPath);\r\n\tvar notErrors = this.errors.slice(oldErrorCount);\r\n\tthis.errors = this.errors.slice(0, oldErrorCount);\r\n\tif (this.trackUnknownProperties) {\r\n\t\tthis.unknownPropertyPaths = oldUnknownPropertyPaths;\r\n\t\tthis.knownPropertyPaths = oldKnownPropertyPaths;\r\n\t}\r\n\tif (error === null && notErrors.length === 0) {\r\n\t\treturn this.createError(ErrorCodes.NOT_PASSED, {}, \"\", \"/not\", null, data, schema);\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateHypermedia = function validateCombinations(data, schema, dataPointerPath) {\r\n\tif (!schema.links) {\r\n\t\treturn null;\r\n\t}\r\n\tvar error;\r\n\tfor (var i = 0; i < schema.links.length; i++) {\r\n\t\tvar ldo = schema.links[i];\r\n\t\tif (ldo.rel === \"describedby\") {\r\n\t\t\tvar template = new UriTemplate(ldo.href);\r\n\t\t\tvar allPresent = true;\r\n\t\t\tfor (var j = 0; j < template.varNames.length; j++) {\r\n\t\t\t\tif (!(template.varNames[j] in data)) {\r\n\t\t\t\t\tallPresent = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (allPresent) {\r\n\t\t\t\tvar schemaUrl = template.fillFromObject(data);\r\n\t\t\t\tvar subSchema = {\"$ref\": schemaUrl};\r\n\t\t\t\tif (error = this.validateAll(data, subSchema, [], [\"links\", i], dataPointerPath)) {\r\n\t\t\t\t\treturn error;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\n// parseURI() and resolveUrl() are from https://gist.github.com/1088850\r\n// - released as public domain by author (\"Yaffle\") - see comments on gist\r\n\r\nfunction parseURI(url) {\r\n\tvar m = String(url).replace(/^\\s+|\\s+$/g, '').match(/^([^:\\/?#]+:)?(\\/\\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\\/?#]*)(?::(\\d*))?))?([^?#]*)(\\?[^#]*)?(#[\\s\\S]*)?/);\r\n\t// authority = '//' + user + ':' + pass '@' + hostname + ':' port\r\n\treturn (m ? {\r\n\t\thref : m[0] || '',\r\n\t\tprotocol : m[1] || '',\r\n\t\tauthority: m[2] || '',\r\n\t\thost : m[3] || '',\r\n\t\thostname : m[4] || '',\r\n\t\tport : m[5] || '',\r\n\t\tpathname : m[6] || '',\r\n\t\tsearch : m[7] || '',\r\n\t\thash : m[8] || ''\r\n\t} : null);\r\n}\r\n\r\nfunction resolveUrl(base, href) {// RFC 3986\r\n\r\n\tfunction removeDotSegments(input) {\r\n\t\tvar output = [];\r\n\t\tinput.replace(/^(\\.\\.?(\\/|$))+/, '')\r\n\t\t\t.replace(/\\/(\\.(\\/|$))+/g, '/')\r\n\t\t\t.replace(/\\/\\.\\.$/, '/../')\r\n\t\t\t.replace(/\\/?[^\\/]*/g, function (p) {\r\n\t\t\t\tif (p === '/..') {\r\n\t\t\t\t\toutput.pop();\r\n\t\t\t\t} else {\r\n\t\t\t\t\toutput.push(p);\r\n\t\t\t\t}\r\n\t\t});\r\n\t\treturn output.join('').replace(/^\\//, input.charAt(0) === '/' ? '/' : '');\r\n\t}\r\n\r\n\thref = parseURI(href || '');\r\n\tbase = parseURI(base || '');\r\n\r\n\treturn !href || !base ? null : (href.protocol || base.protocol) +\r\n\t\t(href.protocol || href.authority ? href.authority : base.authority) +\r\n\t\tremoveDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +\r\n\t\t(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +\r\n\t\thref.hash;\r\n}\r\n\r\nfunction getDocumentUri(uri) {\r\n\treturn uri.split('#')[0];\r\n}\r\nfunction normSchema(schema, baseUri) {\r\n\tif (schema && typeof schema === \"object\") {\r\n\t\tif (baseUri === undefined) {\r\n\t\t\tbaseUri = schema.id;\r\n\t\t} else if (typeof schema.id === \"string\") {\r\n\t\t\tbaseUri = resolveUrl(baseUri, schema.id);\r\n\t\t\tschema.id = baseUri;\r\n\t\t}\r\n\t\tif (Array.isArray(schema)) {\r\n\t\t\tfor (var i = 0; i < schema.length; i++) {\r\n\t\t\t\tnormSchema(schema[i], baseUri);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif (typeof schema['$ref'] === \"string\") {\r\n\t\t\t\tschema['$ref'] = resolveUrl(baseUri, schema['$ref']);\r\n\t\t\t}\r\n\t\t\tfor (var key in schema) {\r\n\t\t\t\tif (key !== \"enum\") {\r\n\t\t\t\t\tnormSchema(schema[key], baseUri);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunction defaultErrorReporter(language) {\r\n\tlanguage = language || 'en';\r\n\r\n\tvar errorMessages = languages[language];\r\n\r\n\treturn function (error) {\r\n\t\tvar messageTemplate = errorMessages[error.code] || ErrorMessagesDefault[error.code];\r\n\t\tif (typeof messageTemplate !== 'string') {\r\n\t\t\treturn \"Unknown error code \" + error.code + \": \" + JSON.stringify(error.messageParams);\r\n\t\t}\r\n\t\tvar messageParams = error.params;\r\n\t\t// Adapted from Crockford's supplant()\r\n\t\treturn messageTemplate.replace(/\\{([^{}]*)\\}/g, function (whole, varName) {\r\n\t\t\tvar subValue = messageParams[varName];\r\n\t\t\treturn typeof subValue === 'string' || typeof subValue === 'number' ? subValue : whole;\r\n\t\t});\r\n\t};\r\n}\r\n\r\nvar ErrorCodes = {\r\n\tINVALID_TYPE: 0,\r\n\tENUM_MISMATCH: 1,\r\n\tANY_OF_MISSING: 10,\r\n\tONE_OF_MISSING: 11,\r\n\tONE_OF_MULTIPLE: 12,\r\n\tNOT_PASSED: 13,\r\n\t// Numeric errors\r\n\tNUMBER_MULTIPLE_OF: 100,\r\n\tNUMBER_MINIMUM: 101,\r\n\tNUMBER_MINIMUM_EXCLUSIVE: 102,\r\n\tNUMBER_MAXIMUM: 103,\r\n\tNUMBER_MAXIMUM_EXCLUSIVE: 104,\r\n\tNUMBER_NOT_A_NUMBER: 105,\r\n\t// String errors\r\n\tSTRING_LENGTH_SHORT: 200,\r\n\tSTRING_LENGTH_LONG: 201,\r\n\tSTRING_PATTERN: 202,\r\n\t// Object errors\r\n\tOBJECT_PROPERTIES_MINIMUM: 300,\r\n\tOBJECT_PROPERTIES_MAXIMUM: 301,\r\n\tOBJECT_REQUIRED: 302,\r\n\tOBJECT_ADDITIONAL_PROPERTIES: 303,\r\n\tOBJECT_DEPENDENCY_KEY: 304,\r\n\t// Array errors\r\n\tARRAY_LENGTH_SHORT: 400,\r\n\tARRAY_LENGTH_LONG: 401,\r\n\tARRAY_UNIQUE: 402,\r\n\tARRAY_ADDITIONAL_ITEMS: 403,\r\n\t// Custom/user-defined errors\r\n\tFORMAT_CUSTOM: 500,\r\n\tKEYWORD_CUSTOM: 501,\r\n\t// Schema structure\r\n\tCIRCULAR_REFERENCE: 600,\r\n\t// Non-standard validation options\r\n\tUNKNOWN_PROPERTY: 1000\r\n};\r\nvar ErrorCodeLookup = {};\r\nfor (var key in ErrorCodes) {\r\n\tErrorCodeLookup[ErrorCodes[key]] = key;\r\n}\r\nvar ErrorMessagesDefault = {\r\n\tINVALID_TYPE: \"Invalid type: {type} (expected {expected})\",\r\n\tENUM_MISMATCH: \"No enum match for: {value}\",\r\n\tANY_OF_MISSING: \"Data does not match any schemas from \\\"anyOf\\\"\",\r\n\tONE_OF_MISSING: \"Data does not match any schemas from \\\"oneOf\\\"\",\r\n\tONE_OF_MULTIPLE: \"Data is valid against more than one schema from \\\"oneOf\\\": indices {index1} and {index2}\",\r\n\tNOT_PASSED: \"Data matches schema from \\\"not\\\"\",\r\n\t// Numeric errors\r\n\tNUMBER_MULTIPLE_OF: \"Value {value} is not a multiple of {multipleOf}\",\r\n\tNUMBER_MINIMUM: \"Value {value} is less than minimum {minimum}\",\r\n\tNUMBER_MINIMUM_EXCLUSIVE: \"Value {value} is equal to exclusive minimum {minimum}\",\r\n\tNUMBER_MAXIMUM: \"Value {value} is greater than maximum {maximum}\",\r\n\tNUMBER_MAXIMUM_EXCLUSIVE: \"Value {value} is equal to exclusive maximum {maximum}\",\r\n\tNUMBER_NOT_A_NUMBER: \"Value {value} is not a valid number\",\r\n\t// String errors\r\n\tSTRING_LENGTH_SHORT: \"String is too short ({length} chars), minimum {minimum}\",\r\n\tSTRING_LENGTH_LONG: \"String is too long ({length} chars), maximum {maximum}\",\r\n\tSTRING_PATTERN: \"String does not match pattern: {pattern}\",\r\n\t// Object errors\r\n\tOBJECT_PROPERTIES_MINIMUM: \"Too few properties defined ({propertyCount}), minimum {minimum}\",\r\n\tOBJECT_PROPERTIES_MAXIMUM: \"Too many properties defined ({propertyCount}), maximum {maximum}\",\r\n\tOBJECT_REQUIRED: \"Missing required property: {key}\",\r\n\tOBJECT_ADDITIONAL_PROPERTIES: \"Additional properties not allowed\",\r\n\tOBJECT_DEPENDENCY_KEY: \"Dependency failed - key must exist: {missing} (due to key: {key})\",\r\n\t// Array errors\r\n\tARRAY_LENGTH_SHORT: \"Array is too short ({length}), minimum {minimum}\",\r\n\tARRAY_LENGTH_LONG: \"Array is too long ({length}), maximum {maximum}\",\r\n\tARRAY_UNIQUE: \"Array items are not unique (indices {match1} and {match2})\",\r\n\tARRAY_ADDITIONAL_ITEMS: \"Additional items not allowed\",\r\n\t// Format errors\r\n\tFORMAT_CUSTOM: \"Format validation failed ({message})\",\r\n\tKEYWORD_CUSTOM: \"Keyword failed: {key} ({message})\",\r\n\t// Schema structure\r\n\tCIRCULAR_REFERENCE: \"Circular $refs: {urls}\",\r\n\t// Non-standard validation options\r\n\tUNKNOWN_PROPERTY: \"Unknown property (not in schema)\"\r\n};\r\n\r\nfunction ValidationError(code, params, dataPath, schemaPath, subErrors) {\r\n\tError.call(this);\r\n\tif (code === undefined) {\r\n\t\tthrow new Error (\"No error code supplied: \" + schemaPath);\r\n\t}\r\n\tthis.message = '';\r\n\tthis.params = params;\r\n\tthis.code = code;\r\n\tthis.dataPath = dataPath || \"\";\r\n\tthis.schemaPath = schemaPath || \"\";\r\n\tthis.subErrors = subErrors || null;\r\n\r\n\tvar err = new Error(this.message);\r\n\tthis.stack = err.stack || err.stacktrace;\r\n\tif (!this.stack) {\r\n\t\ttry {\r\n\t\t\tthrow err;\r\n\t\t}\r\n\t\tcatch(err) {\r\n\t\t\tthis.stack = err.stack || err.stacktrace;\r\n\t\t}\r\n\t}\r\n}\r\nValidationError.prototype = Object.create(Error.prototype);\r\nValidationError.prototype.constructor = ValidationError;\r\nValidationError.prototype.name = 'ValidationError';\r\n\r\nValidationError.prototype.prefixWith = function (dataPrefix, schemaPrefix) {\r\n\tif (dataPrefix !== null) {\r\n\t\tdataPrefix = dataPrefix.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\r\n\t\tthis.dataPath = \"/\" + dataPrefix + this.dataPath;\r\n\t}\r\n\tif (schemaPrefix !== null) {\r\n\t\tschemaPrefix = schemaPrefix.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\r\n\t\tthis.schemaPath = \"/\" + schemaPrefix + this.schemaPath;\r\n\t}\r\n\tif (this.subErrors !== null) {\r\n\t\tfor (var i = 0; i < this.subErrors.length; i++) {\r\n\t\t\tthis.subErrors[i].prefixWith(dataPrefix, schemaPrefix);\r\n\t\t}\r\n\t}\r\n\treturn this;\r\n};\r\n\r\nfunction isTrustedUrl(baseUrl, testUrl) {\r\n\tif(testUrl.substring(0, baseUrl.length) === baseUrl){\r\n\t\tvar remainder = testUrl.substring(baseUrl.length);\r\n\t\tif ((testUrl.length > 0 && testUrl.charAt(baseUrl.length - 1) === \"/\")\r\n\t\t\t|| remainder.charAt(0) === \"#\"\r\n\t\t\t|| remainder.charAt(0) === \"?\") {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvar languages = {};\r\nfunction createApi(language) {\r\n\tvar globalContext = new ValidatorContext();\r\n\tvar currentLanguage;\r\n\tvar customErrorReporter;\r\n\tvar api = {\r\n\t\tsetErrorReporter: function (reporter) {\r\n\t\t\tif (typeof reporter === 'string') {\r\n\t\t\t\treturn this.language(reporter);\r\n\t\t\t}\r\n\t\t\tcustomErrorReporter = reporter;\r\n\t\t\treturn true;\r\n\t\t},\r\n\t\taddFormat: function () {\r\n\t\t\tglobalContext.addFormat.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tlanguage: function (code) {\r\n\t\t\tif (!code) {\r\n\t\t\t\treturn currentLanguage;\r\n\t\t\t}\r\n\t\t\tif (!languages[code]) {\r\n\t\t\t\tcode = code.split('-')[0]; // fall back to base language\r\n\t\t\t}\r\n\t\t\tif (languages[code]) {\r\n\t\t\t\tcurrentLanguage = code;\r\n\t\t\t\treturn code; // so you can tell if fall-back has happened\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t},\r\n\t\taddLanguage: function (code, messageMap) {\r\n\t\t\tvar key;\r\n\t\t\tfor (key in ErrorCodes) {\r\n\t\t\t\tif (messageMap[key] && !messageMap[ErrorCodes[key]]) {\r\n\t\t\t\t\tmessageMap[ErrorCodes[key]] = messageMap[key];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tvar rootCode = code.split('-')[0];\r\n\t\t\tif (!languages[rootCode]) { // use for base language if not yet defined\r\n\t\t\t\tlanguages[code] = messageMap;\r\n\t\t\t\tlanguages[rootCode] = messageMap;\r\n\t\t\t} else {\r\n\t\t\t\tlanguages[code] = Object.create(languages[rootCode]);\r\n\t\t\t\tfor (key in messageMap) {\r\n\t\t\t\t\tif (typeof languages[rootCode][key] === 'undefined') {\r\n\t\t\t\t\t\tlanguages[rootCode][key] = messageMap[key];\r\n\t\t\t\t\t}\r\n\t\t\t\t\tlanguages[code][key] = messageMap[key];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn this;\r\n\t\t},\r\n\t\tfreshApi: function (language) {\r\n\t\t\tvar result = createApi();\r\n\t\t\tif (language) {\r\n\t\t\t\tresult.language(language);\r\n\t\t\t}\r\n\t\t\treturn result;\r\n\t\t},\r\n\t\tvalidate: function (data, schema, checkRecursive, banUnknownProperties) {\r\n\t\t\tvar def = defaultErrorReporter(currentLanguage);\r\n\t\t\tvar errorReporter = customErrorReporter ? function (error, data, schema) {\r\n\t\t\t\treturn customErrorReporter(error, data, schema) || def(error, data, schema);\r\n\t\t\t} : def;\r\n\t\t\tvar context = new ValidatorContext(globalContext, false, errorReporter, checkRecursive, banUnknownProperties);\r\n\t\t\tif (typeof schema === \"string\") {\r\n\t\t\t\tschema = {\"$ref\": schema};\r\n\t\t\t}\r\n\t\t\tcontext.addSchema(\"\", schema);\r\n\t\t\tvar error = context.validateAll(data, schema, null, null, \"\");\r\n\t\t\tif (!error && banUnknownProperties) {\r\n\t\t\t\terror = context.banUnknownProperties(data, schema);\r\n\t\t\t}\r\n\t\t\tthis.error = error;\r\n\t\t\tthis.missing = context.missing;\r\n\t\t\tthis.valid = (error === null);\r\n\t\t\treturn this.valid;\r\n\t\t},\r\n\t\tvalidateResult: function () {\r\n\t\t\tvar result = {toString: function () {\r\n\t\t\t\treturn this.valid ? 'valid' : this.error.message;\r\n\t\t\t}};\r\n\t\t\tthis.validate.apply(result, arguments);\r\n\t\t\treturn result;\r\n\t\t},\r\n\t\tvalidateMultiple: function (data, schema, checkRecursive, banUnknownProperties) {\r\n\t\t\tvar def = defaultErrorReporter(currentLanguage);\r\n\t\t\tvar errorReporter = customErrorReporter ? function (error, data, schema) {\r\n\t\t\t\treturn customErrorReporter(error, data, schema) || def(error, data, schema);\r\n\t\t\t} : def;\r\n\t\t\tvar context = new ValidatorContext(globalContext, true, errorReporter, checkRecursive, banUnknownProperties);\r\n\t\t\tif (typeof schema === \"string\") {\r\n\t\t\t\tschema = {\"$ref\": schema};\r\n\t\t\t}\r\n\t\t\tcontext.addSchema(\"\", schema);\r\n\t\t\tcontext.validateAll(data, schema, null, null, \"\");\r\n\t\t\tif (banUnknownProperties) {\r\n\t\t\t\tcontext.banUnknownProperties(data, schema);\r\n\t\t\t}\r\n\t\t\tvar result = {toString: function () {\r\n\t\t\t\treturn this.valid ? 'valid' : this.error.message;\r\n\t\t\t}};\r\n\t\t\tresult.errors = context.errors;\r\n\t\t\tresult.missing = context.missing;\r\n\t\t\tresult.valid = (result.errors.length === 0);\r\n\t\t\treturn result;\r\n\t\t},\r\n\t\taddSchema: function () {\r\n\t\t\treturn globalContext.addSchema.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tgetSchema: function () {\r\n\t\t\treturn globalContext.getSchema.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tgetSchemaMap: function () {\r\n\t\t\treturn globalContext.getSchemaMap.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tgetSchemaUris: function () {\r\n\t\t\treturn globalContext.getSchemaUris.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tgetMissingUris: function () {\r\n\t\t\treturn globalContext.getMissingUris.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tdropSchemas: function () {\r\n\t\t\tglobalContext.dropSchemas.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tdefineKeyword: function () {\r\n\t\t\tglobalContext.defineKeyword.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tdefineError: function (codeName, codeNumber, defaultMessage) {\r\n\t\t\tif (typeof codeName !== 'string' || !/^[A-Z]+(_[A-Z]+)*$/.test(codeName)) {\r\n\t\t\t\tthrow new Error('Code name must be a string in UPPER_CASE_WITH_UNDERSCORES');\r\n\t\t\t}\r\n\t\t\tif (typeof codeNumber !== 'number' || codeNumber%1 !== 0 || codeNumber < 10000) {\r\n\t\t\t\tthrow new Error('Code number must be an integer > 10000');\r\n\t\t\t}\r\n\t\t\tif (typeof ErrorCodes[codeName] !== 'undefined') {\r\n\t\t\t\tthrow new Error('Error already defined: ' + codeName + ' as ' + ErrorCodes[codeName]);\r\n\t\t\t}\r\n\t\t\tif (typeof ErrorCodeLookup[codeNumber] !== 'undefined') {\r\n\t\t\t\tthrow new Error('Error code already used: ' + ErrorCodeLookup[codeNumber] + ' as ' + codeNumber);\r\n\t\t\t}\r\n\t\t\tErrorCodes[codeName] = codeNumber;\r\n\t\t\tErrorCodeLookup[codeNumber] = codeName;\r\n\t\t\tErrorMessagesDefault[codeName] = ErrorMessagesDefault[codeNumber] = defaultMessage;\r\n\t\t\tfor (var langCode in languages) {\r\n\t\t\t\tvar language = languages[langCode];\r\n\t\t\t\tif (language[codeName]) {\r\n\t\t\t\t\tlanguage[codeNumber] = language[codeNumber] || language[codeName];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t},\r\n\t\treset: function () {\r\n\t\t\tglobalContext.reset();\r\n\t\t\tthis.error = null;\r\n\t\t\tthis.missing = [];\r\n\t\t\tthis.valid = true;\r\n\t\t},\r\n\t\tmissing: [],\r\n\t\terror: null,\r\n\t\tvalid: true,\r\n\t\tnormSchema: normSchema,\r\n\t\tresolveUrl: resolveUrl,\r\n\t\tgetDocumentUri: getDocumentUri,\r\n\t\terrorCodes: ErrorCodes\r\n\t};\r\n\tapi.language(language || 'en');\r\n\treturn api;\r\n}\r\n\r\nvar tv4 = createApi();\r\ntv4.addLanguage('en-gb', ErrorMessagesDefault);\r\n\r\n//legacy property\r\ntv4.tv4 = tv4;\r\n\r\nreturn tv4; // used by _header.js to globalise.\r\n\r\n}));","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"NIL\", {\n enumerable: true,\n get: function get() {\n return _nil.default;\n }\n});\nObject.defineProperty(exports, \"parse\", {\n enumerable: true,\n get: function get() {\n return _parse.default;\n }\n});\nObject.defineProperty(exports, \"stringify\", {\n enumerable: true,\n get: function get() {\n return _stringify.default;\n }\n});\nObject.defineProperty(exports, \"v1\", {\n enumerable: true,\n get: function get() {\n return _v.default;\n }\n});\nObject.defineProperty(exports, \"v3\", {\n enumerable: true,\n get: function get() {\n return _v2.default;\n }\n});\nObject.defineProperty(exports, \"v4\", {\n enumerable: true,\n get: function get() {\n return _v3.default;\n }\n});\nObject.defineProperty(exports, \"v5\", {\n enumerable: true,\n get: function get() {\n return _v4.default;\n }\n});\nObject.defineProperty(exports, \"validate\", {\n enumerable: true,\n get: function get() {\n return _validate.default;\n }\n});\nObject.defineProperty(exports, \"version\", {\n enumerable: true,\n get: function get() {\n return _version.default;\n }\n});\n\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\n\nvar _v2 = _interopRequireDefault(require(\"./v3.js\"));\n\nvar _v3 = _interopRequireDefault(require(\"./v4.js\"));\n\nvar _v4 = _interopRequireDefault(require(\"./v5.js\"));\n\nvar _nil = _interopRequireDefault(require(\"./nil.js\"));\n\nvar _version = _interopRequireDefault(require(\"./version.js\"));\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\n/*\n * Browser-compatible JavaScript MD5\n *\n * Modification of JavaScript MD5\n * https://github.com/blueimp/JavaScript-MD5\n *\n * Copyright 2011, Sebastian Tschan\n * https://blueimp.net\n *\n * Licensed under the MIT license:\n * https://opensource.org/licenses/MIT\n *\n * Based on\n * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message\n * Digest Algorithm, as defined in RFC 1321.\n * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n * Distributed under the BSD License\n * See http://pajhome.org.uk/crypt/md5 for more info.\n */\nfunction md5(bytes) {\n if (typeof bytes === 'string') {\n const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = new Uint8Array(msg.length);\n\n for (let i = 0; i < msg.length; ++i) {\n bytes[i] = msg.charCodeAt(i);\n }\n }\n\n return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));\n}\n/*\n * Convert an array of little-endian words to an array of bytes\n */\n\n\nfunction md5ToHexEncodedArray(input) {\n const output = [];\n const length32 = input.length * 32;\n const hexTab = '0123456789abcdef';\n\n for (let i = 0; i < length32; i += 8) {\n const x = input[i >> 5] >>> i % 32 & 0xff;\n const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);\n output.push(hex);\n }\n\n return output;\n}\n/**\n * Calculate output length with padding and bit length\n */\n\n\nfunction getOutputLength(inputLength8) {\n return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;\n}\n/*\n * Calculate the MD5 of an array of little-endian words, and a bit length.\n */\n\n\nfunction wordsToMd5(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << len % 32;\n x[getOutputLength(len) - 1] = len;\n let a = 1732584193;\n let b = -271733879;\n let c = -1732584194;\n let d = 271733878;\n\n for (let i = 0; i < x.length; i += 16) {\n const olda = a;\n const oldb = b;\n const oldc = c;\n const oldd = d;\n a = md5ff(a, b, c, d, x[i], 7, -680876936);\n d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);\n c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);\n b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);\n a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);\n d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);\n c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);\n b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);\n a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);\n d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);\n c = md5ff(c, d, a, b, x[i + 10], 17, -42063);\n b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);\n a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);\n d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);\n c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);\n b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);\n a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);\n d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);\n c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);\n b = md5gg(b, c, d, a, x[i], 20, -373897302);\n a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);\n d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);\n c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);\n b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);\n a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);\n d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);\n c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);\n b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);\n a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);\n d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);\n c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);\n b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);\n a = md5hh(a, b, c, d, x[i + 5], 4, -378558);\n d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);\n c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);\n b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);\n a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);\n d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);\n c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);\n b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);\n a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);\n d = md5hh(d, a, b, c, x[i], 11, -358537222);\n c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);\n b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);\n a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);\n d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);\n c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);\n b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);\n a = md5ii(a, b, c, d, x[i], 6, -198630844);\n d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);\n c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);\n b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);\n a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);\n d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);\n c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);\n b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);\n a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);\n d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);\n c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);\n b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);\n a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);\n d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);\n c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);\n b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);\n a = safeAdd(a, olda);\n b = safeAdd(b, oldb);\n c = safeAdd(c, oldc);\n d = safeAdd(d, oldd);\n }\n\n return [a, b, c, d];\n}\n/*\n * Convert an array bytes to an array of little-endian words\n * Characters >255 have their high-byte silently ignored.\n */\n\n\nfunction bytesToWords(input) {\n if (input.length === 0) {\n return [];\n }\n\n const length8 = input.length * 8;\n const output = new Uint32Array(getOutputLength(length8));\n\n for (let i = 0; i < length8; i += 8) {\n output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;\n }\n\n return output;\n}\n/*\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\n\n\nfunction safeAdd(x, y) {\n const lsw = (x & 0xffff) + (y & 0xffff);\n const msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return msw << 16 | lsw & 0xffff;\n}\n/*\n * Bitwise rotate a 32-bit number to the left.\n */\n\n\nfunction bitRotateLeft(num, cnt) {\n return num << cnt | num >>> 32 - cnt;\n}\n/*\n * These functions implement the four basic operations the algorithm uses.\n */\n\n\nfunction md5cmn(q, a, b, x, s, t) {\n return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);\n}\n\nfunction md5ff(a, b, c, d, x, s, t) {\n return md5cmn(b & c | ~b & d, a, b, x, s, t);\n}\n\nfunction md5gg(a, b, c, d, x, s, t) {\n return md5cmn(b & d | c & ~d, a, b, x, s, t);\n}\n\nfunction md5hh(a, b, c, d, x, s, t) {\n return md5cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction md5ii(a, b, c, d, x, s, t) {\n return md5cmn(c ^ (b | ~d), a, b, x, s, t);\n}\n\nvar _default = md5;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nconst randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nvar _default = {\n randomUUID\n};\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = '00000000-0000-0000-0000-000000000000';\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction parse(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nvar _default = parse;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rng;\n// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nlet getRandomValues;\nconst rnds8 = new Uint8Array(16);\n\nfunction rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\n// Adapted from Chris Veness' SHA1 code at\n// http://www.movable-type.co.uk/scripts/sha1.html\nfunction f(s, x, y, z) {\n switch (s) {\n case 0:\n return x & y ^ ~x & z;\n\n case 1:\n return x ^ y ^ z;\n\n case 2:\n return x & y ^ x & z ^ y & z;\n\n case 3:\n return x ^ y ^ z;\n }\n}\n\nfunction ROTL(x, n) {\n return x << n | x >>> 32 - n;\n}\n\nfunction sha1(bytes) {\n const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];\n const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n\n if (typeof bytes === 'string') {\n const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = [];\n\n for (let i = 0; i < msg.length; ++i) {\n bytes.push(msg.charCodeAt(i));\n }\n } else if (!Array.isArray(bytes)) {\n // Convert Array-like to Array\n bytes = Array.prototype.slice.call(bytes);\n }\n\n bytes.push(0x80);\n const l = bytes.length / 4 + 2;\n const N = Math.ceil(l / 16);\n const M = new Array(N);\n\n for (let i = 0; i < N; ++i) {\n const arr = new Uint32Array(16);\n\n for (let j = 0; j < 16; ++j) {\n arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];\n }\n\n M[i] = arr;\n }\n\n M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);\n M[N - 1][14] = Math.floor(M[N - 1][14]);\n M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;\n\n for (let i = 0; i < N; ++i) {\n const W = new Uint32Array(80);\n\n for (let t = 0; t < 16; ++t) {\n W[t] = M[i][t];\n }\n\n for (let t = 16; t < 80; ++t) {\n W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);\n }\n\n let a = H[0];\n let b = H[1];\n let c = H[2];\n let d = H[3];\n let e = H[4];\n\n for (let t = 0; t < 80; ++t) {\n const s = Math.floor(t / 20);\n const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;\n e = d;\n d = c;\n c = ROTL(b, 30) >>> 0;\n b = a;\n a = T;\n }\n\n H[0] = H[0] + a >>> 0;\n H[1] = H[1] + b >>> 0;\n H[2] = H[2] + c >>> 0;\n H[3] = H[3] + d >>> 0;\n H[4] = H[4] + e >>> 0;\n }\n\n return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];\n}\n\nvar _default = sha1;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nexports.unsafeStringify = unsafeStringify;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nfunction unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nvar _default = stringify;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = require(\"./stringify.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\nlet _nodeId;\n\nlet _clockseq; // Previous uuid creation time\n\n\nlet _lastMSecs = 0;\nlet _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details\n\nfunction v1(options, buf, offset) {\n let i = buf && offset || 0;\n const b = buf || new Array(16);\n options = options || {};\n let node = options.node || _nodeId;\n let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n\n if (node == null || clockseq == null) {\n const seedBytes = options.random || (options.rng || _rng.default)();\n\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n }\n\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n } // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\n\n let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n\n let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)\n\n const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression\n\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n\n\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n } // Per 4.2.1.2 Throw error if too many uuids are requested\n\n\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\n msecs += 12219292800000; // `time_low`\n\n const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff; // `time_mid`\n\n const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff; // `time_high_and_version`\n\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\n b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\n b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`\n\n b[i++] = clockseq & 0xff; // `node`\n\n for (let n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf || (0, _stringify.unsafeStringify)(b);\n}\n\nvar _default = v1;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _md = _interopRequireDefault(require(\"./md5.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v3 = (0, _v.default)('v3', 0x30, _md.default);\nvar _default = v3;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.URL = exports.DNS = void 0;\nexports.default = v35;\n\nvar _stringify = require(\"./stringify.js\");\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nconst DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexports.DNS = DNS;\nconst URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexports.URL = URL;\n\nfunction v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = (0, _parse.default)(namespace);\n }\n\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.unsafeStringify)(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _native = _interopRequireDefault(require(\"./native.js\"));\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = require(\"./stringify.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction v4(options, buf, offset) {\n if (_native.default.randomUUID && !buf && !options) {\n return _native.default.randomUUID();\n }\n\n options = options || {};\n\n const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.unsafeStringify)(rnds);\n}\n\nvar _default = v4;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _sha = _interopRequireDefault(require(\"./sha1.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v5 = (0, _v.default)('v5', 0x50, _sha.default);\nvar _default = v5;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _regex = _interopRequireDefault(require(\"./regex.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && _regex.default.test(uuid);\n}\n\nvar _default = validate;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction version(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n return parseInt(uuid.slice(14, 15), 16);\n}\n\nvar _default = version;\nexports.default = _default;","/* global define */\n/*!\n * webfinger.js\n * http://github.com/silverbucket/webfinger.js\n *\n * Developed and Maintained by:\n * Nick Jennings \n *\n * webfinger.js is released under the AGPL (see LICENSE).\n *\n * You don't have to do anything special to choose one license or the other and you don't\n * have to notify anyone which license you are using.\n * Please see the corresponding license file for details of these licenses.\n * You are free to use, modify and distribute this software, but all copyright\n * information must remain.\n *\n */\n\nif (typeof fetch !== 'function' && typeof XMLHttpRequest !== 'function') {\n // XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;\n XMLHttpRequest = require('xhr2');\n}\n\n(function (global) {\n\n // URI to property name map\n var LINK_URI_MAPS = {\n 'http://webfist.org/spec/rel': 'webfist',\n 'http://webfinger.net/rel/avatar': 'avatar',\n 'remotestorage': 'remotestorage',\n 'http://tools.ietf.org/id/draft-dejong-remotestorage': 'remotestorage',\n 'remoteStorage': 'remotestorage',\n 'http://www.packetizer.com/rel/share': 'share',\n 'http://webfinger.net/rel/profile-page': 'profile',\n 'me': 'profile',\n 'vcard': 'vcard',\n 'blog': 'blog',\n 'http://packetizer.com/rel/blog': 'blog',\n 'http://schemas.google.com/g/2010#updates-from': 'updates',\n 'https://camlistore.org/rel/server': 'camilstore'\n };\n\n var LINK_PROPERTIES = {\n 'avatar': [],\n 'remotestorage': [],\n 'blog': [],\n 'vcard': [],\n 'updates': [],\n 'share': [],\n 'profile': [],\n 'webfist': [],\n 'camlistore': []\n };\n\n // list of endpoints to try, fallback from beginning to end.\n var URIS = ['webfinger', 'host-meta', 'host-meta.json'];\n\n function generateErrorObject(obj) {\n obj.toString = function () {\n return this.message;\n };\n return obj;\n }\n\n // given a URL ensures it's HTTPS.\n // returns false for null string or non-HTTPS URL.\n function isSecure(url) {\n if (typeof url !== 'string') {\n return false;\n }\n var parts = url.split('://');\n if (parts[0] === 'https') {\n return true;\n }\n return false;\n }\n\n /**\n * Function: WebFinger\n *\n * WebFinger constructor\n *\n * Returns:\n *\n * return WebFinger object\n */\n function WebFinger(config) {\n if (typeof config !== 'object') {\n config = {};\n }\n\n this.config = {\n tls_only: (typeof config.tls_only !== 'undefined') ? config.tls_only : true,\n webfist_fallback: (typeof config.webfist_fallback !== 'undefined') ? config.webfist_fallback : false,\n uri_fallback: (typeof config.uri_fallback !== 'undefined') ? config.uri_fallback : false,\n request_timeout: (typeof config.request_timeout !== 'undefined') ? config.request_timeout : 10000\n };\n }\n\n // make an http request and look for JRD response, fails if request fails\n // or response not json.\n WebFinger.prototype.__fetchJRD = function (url, errorHandler, successHandler) {\n if (typeof fetch === 'function') {\n return this.__fetchJRD_fetch(url, errorHandler, successHandler);\n } else if (typeof XMLHttpRequest === 'function') {\n return this.__fetchJRD_XHR(url, errorHandler, successHandler);\n } else {\n throw new Error(\"add a polyfill for fetch or XMLHttpRequest\");\n }\n };\n WebFinger.prototype.__fetchJRD_fetch = function (url, errorHandler, successHandler) {\n var webfinger = this;\n var abortController;\n if (typeof AbortController === 'function') {\n abortController = new AbortController();\n }\n var networkPromise = fetch(url, {\n headers: {'Accept': 'application/jrd+json, application/json'},\n signal: abortController ? abortController.signal : undefined\n }).\n then(function (response) {\n if (response.ok) {\n return response.text();\n } else if (response.status === 404) {\n throw generateErrorObject({\n message: 'resource not found',\n url: url,\n status: response.status\n });\n } else { // other HTTP status (redirects are handled transparently)\n throw generateErrorObject({\n message: 'error during request',\n url: url,\n status: response.status\n });\n }\n },\n function (err) { // connection refused, etc.\n throw generateErrorObject({\n message: 'error during request',\n url: url,\n status: undefined,\n err: err\n })\n }).\n then(function (responseText) {\n if (webfinger.__isValidJSON(responseText)) {\n return responseText;\n } else {\n throw generateErrorObject({\n message: 'invalid json',\n url: url,\n status: undefined\n });\n }\n });\n\n var timeoutPromise = new Promise(function (resolve, reject) {\n setTimeout(function () {\n reject(generateErrorObject({\n message: 'request timed out',\n url: url,\n status: undefined\n }));\n if (abortController) {\n abortController.abort();\n }\n }, webfinger.config.request_timeout);\n });\n\n Promise.race([networkPromise, timeoutPromise]).\n then(function (responseText) {\n successHandler(responseText);\n }).catch(function (err) {\n errorHandler(err);\n });\n };\n WebFinger.prototype.__fetchJRD_XHR = function (url, errorHandler, successHandler) {\n var self = this;\n var handlerSpent = false;\n var xhr = new XMLHttpRequest();\n\n function __processState() {\n if (handlerSpent){\n return;\n }else{\n handlerSpent = true;\n }\n\n if (xhr.status === 200) {\n if (self.__isValidJSON(xhr.responseText)) {\n return successHandler(xhr.responseText);\n } else {\n return errorHandler(generateErrorObject({\n message: 'invalid json',\n url: url,\n status: xhr.status\n }));\n }\n } else if (xhr.status === 404) {\n return errorHandler(generateErrorObject({\n message: 'resource not found',\n url: url,\n status: xhr.status\n }));\n } else if ((xhr.status >= 301) && (xhr.status <= 302)) {\n var location = xhr.getResponseHeader('Location');\n if (isSecure(location)) {\n return __makeRequest(location); // follow redirect\n } else {\n return errorHandler(generateErrorObject({\n message: 'no redirect URL found',\n url: url,\n status: xhr.status\n }));\n }\n } else {\n return errorHandler(generateErrorObject({\n message: 'error during request',\n url: url,\n status: xhr.status\n }));\n }\n }\n\n function __makeRequest() {\n xhr.onreadystatechange = function () {\n if (xhr.readyState === 4) {\n __processState();\n }\n };\n\n xhr.onload = function () {\n __processState();\n };\n\n xhr.ontimeout = function () {\n return errorHandler(generateErrorObject({\n message: 'request timed out',\n url: url,\n status: xhr.status\n }));\n };\n\n xhr.open('GET', url, true);\n xhr.timeout = self.config.request_timeout;\n xhr.setRequestHeader('Accept', 'application/jrd+json, application/json');\n xhr.send();\n }\n\n return __makeRequest();\n };\n\n WebFinger.prototype.__isValidJSON = function (str) {\n try {\n JSON.parse(str);\n } catch (e) {\n return false;\n }\n return true;\n };\n\n WebFinger.prototype.__isLocalhost = function (host) {\n var local = /^localhost(\\.localdomain)?(\\:[0-9]+)?$/;\n return local.test(host);\n };\n\n // processes JRD object as if it's a webfinger response object\n // looks for known properties and adds them to profile datat struct.\n WebFinger.prototype.__processJRD = function (URL, JRD, errorHandler, successHandler) {\n var parsedJRD = JSON.parse(JRD);\n if ((typeof parsedJRD !== 'object') ||\n (typeof parsedJRD.links !== 'object')) {\n if (typeof parsedJRD.error !== 'undefined') {\n return errorHandler(generateErrorObject({ message: parsedJRD.error, request: URL }));\n } else {\n return errorHandler(generateErrorObject({ message: 'unknown response from server', request: URL }));\n }\n }\n\n var links = parsedJRD.links;\n if (!Array.isArray(links)) {\n links = [];\n }\n var result = { // webfinger JRD - object, json, and our own indexing\n object: parsedJRD,\n json: JRD,\n idx: {}\n };\n\n result.idx.properties = {\n 'name': undefined\n };\n result.idx.links = JSON.parse(JSON.stringify(LINK_PROPERTIES));\n\n // process links\n links.map(function (link, i) {\n if (LINK_URI_MAPS.hasOwnProperty(link.rel)) {\n if (result.idx.links[LINK_URI_MAPS[link.rel]]) {\n var entry = {};\n Object.keys(link).map(function (item, n) {\n entry[item] = link[item];\n });\n result.idx.links[LINK_URI_MAPS[link.rel]].push(entry);\n }\n }\n });\n\n // process properties\n var props = JSON.parse(JRD).properties;\n for (var key in props) {\n if (props.hasOwnProperty(key)) {\n if (key === 'http://packetizer.com/ns/name') {\n result.idx.properties.name = props[key];\n }\n }\n }\n return successHandler(result);\n };\n\n WebFinger.prototype.lookup = function (address, cb) {\n if (typeof address !== 'string') {\n throw new Error('first parameter must be a user address');\n } else if (typeof cb !== 'function') {\n throw new Error('second parameter must be a callback');\n }\n\n var self = this;\n var host = '';\n if (address.indexOf('://') > -1) {\n // other uri format\n host = address.replace(/ /g,'').split('/')[2];\n } else {\n // useraddress\n host = address.replace(/ /g,'').split('@')[1];\n }\n var uri_index = 0; // track which URIS we've tried already\n var protocol = 'https'; // we use https by default\n\n if (self.__isLocalhost(host)) {\n protocol = 'http';\n }\n\n function __buildURL() {\n var uri = '';\n if (! address.split('://')[1]) {\n // the URI has not been defined, default to acct\n uri = 'acct:';\n }\n return protocol + '://' + host + '/.well-known/' +\n URIS[uri_index] + '?resource=' + uri + address;\n }\n\n // control flow for failures, what to do in various cases, etc.\n function __fallbackChecks(err) {\n if ((self.config.uri_fallback) && (host !== 'webfist.org') && (uri_index !== URIS.length - 1)) { // we have uris left to try\n uri_index = uri_index + 1;\n return __call();\n } else if ((!self.config.tls_only) && (protocol === 'https')) { // try normal http\n uri_index = 0;\n protocol = 'http';\n return __call();\n } else if ((self.config.webfist_fallback) && (host !== 'webfist.org')) { // webfist attempt\n uri_index = 0;\n protocol = 'http';\n host = 'webfist.org';\n // webfist will\n // 1. make a query to the webfist server for the users account\n // 2. from the response, get a link to the actual webfinger json data\n // (stored somewhere in control of the user)\n // 3. make a request to that url and get the json\n // 4. process it like a normal webfinger response\n var URL = __buildURL();\n self.__fetchJRD(URL, cb, function (data) { // get link to users JRD\n self.__processJRD(URL, data, cb, function (result) {\n if ((typeof result.idx.links.webfist === 'object') &&\n (typeof result.idx.links.webfist[0].href === 'string')) {\n self.__fetchJRD(result.idx.links.webfist[0].href, cb, function (JRD) {\n self.__processJRD(URL, JRD, cb, function (result) {\n return cb(null, cb);\n });\n });\n }\n });\n });\n } else {\n return cb(err);\n }\n }\n\n function __call() {\n // make request\n var URL = __buildURL();\n self.__fetchJRD(URL, __fallbackChecks, function (JRD) {\n self.__processJRD(URL, JRD, cb, function (result) { cb(null, result); });\n });\n }\n\n return setTimeout(__call, 0);\n };\n\n WebFinger.prototype.lookupLink = function (address, rel, cb) {\n if (LINK_PROPERTIES.hasOwnProperty(rel)) {\n this.lookup(address, function (err, p) {\n var links = p.idx.links[rel];\n if (err) {\n return cb(err);\n } else if (links.length === 0) {\n return cb('no links found with rel=\"' + rel + '\"');\n } else {\n return cb(null, links[0]);\n }\n });\n } else {\n return cb('unsupported rel ' + rel);\n }\n };\n\n\n\n // AMD support\n if (typeof define === 'function' && define.amd) {\n define([], function () { return WebFinger; });\n // CommonJS and Node.js module support.\n } else if (typeof exports !== 'undefined') {\n // Support Node.js specific `module.exports` (which can be a function)\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = WebFinger;\n }\n // But always support CommonJS module 1.1.1 spec (`exports` cannot be a function)\n exports.WebFinger = WebFinger;\n } else {\n // browser