solid-logic 3.1.1-ecb4985 → 3.1.1-f3e6173

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +7 -12
  2. package/dist/acl/aclLogic.d.ts.map +1 -1
  3. package/dist/acl/aclLogic.js +0 -1
  4. package/dist/acl/aclLogic.js.map +1 -1
  5. package/dist/authn/SolidAuthnLogic.js +1 -2
  6. package/dist/authn/SolidAuthnLogic.js.map +1 -1
  7. package/dist/authn/authUtil.d.ts.map +1 -1
  8. package/dist/authn/authUtil.js +1 -4
  9. package/dist/authn/authUtil.js.map +1 -1
  10. package/dist/chat/chatLogic.d.ts.map +1 -1
  11. package/dist/chat/chatLogic.js +6 -6
  12. package/dist/chat/chatLogic.js.map +1 -1
  13. package/dist/inbox/inboxLogic.d.ts.map +1 -1
  14. package/dist/inbox/inboxLogic.js +0 -1
  15. package/dist/inbox/inboxLogic.js.map +1 -1
  16. package/dist/logic/CustomError.js +0 -1
  17. package/dist/logic/CustomError.js.map +1 -1
  18. package/dist/logic/solidLogic.d.ts.map +1 -1
  19. package/dist/logic/solidLogic.js +0 -1
  20. package/dist/logic/solidLogic.js.map +1 -1
  21. package/dist/logic/solidLogicSingleton.d.ts +2 -1
  22. package/dist/logic/solidLogicSingleton.d.ts.map +1 -1
  23. package/dist/logic/solidLogicSingleton.js +15 -2
  24. package/dist/logic/solidLogicSingleton.js.map +1 -1
  25. package/dist/profile/profileLogic.d.ts.map +1 -1
  26. package/dist/profile/profileLogic.js +0 -1
  27. package/dist/profile/profileLogic.js.map +1 -1
  28. package/dist/{solid-logic.esm.external.js → solid-logic.esm.js} +50 -39
  29. package/dist/solid-logic.esm.js.map +1 -0
  30. package/dist/{solid-logic.esm.external.min.js → solid-logic.esm.min.js} +2 -2
  31. package/dist/solid-logic.esm.min.js.map +1 -0
  32. package/dist/solid-logic.js +5560 -28370
  33. package/dist/solid-logic.js.map +1 -1
  34. package/dist/solid-logic.min.js +11 -20
  35. package/dist/solid-logic.min.js.map +1 -1
  36. package/dist/typeIndex/typeIndexLogic.d.ts.map +1 -1
  37. package/dist/typeIndex/typeIndexLogic.js +4 -8
  38. package/dist/typeIndex/typeIndexLogic.js.map +1 -1
  39. package/dist/types.d.ts.map +1 -1
  40. package/dist/util/debug.js +0 -1
  41. package/dist/util/debug.js.map +1 -1
  42. package/dist/versionInfo.js +2 -2
  43. package/package.json +11 -22
  44. package/dist/789.solid-logic.js +0 -11
  45. package/dist/789.solid-logic.js.map +0 -1
  46. package/dist/789.solid-logic.min.js +0 -1
  47. package/dist/841.solid-logic.js +0 -12133
  48. package/dist/841.solid-logic.js.map +0 -1
  49. package/dist/841.solid-logic.min.js +0 -73
  50. package/dist/841.solid-logic.min.js.map +0 -1
  51. package/dist/solid-logic.esm.external.js.map +0 -1
  52. package/dist/solid-logic.esm.external.min.js.map +0 -1
  53. package/dist/solid-logic.external.js +0 -7404
  54. package/dist/solid-logic.external.js.map +0 -1
  55. package/dist/solid-logic.external.min.js +0 -32
  56. package/dist/solid-logic.external.min.js.map +0 -1
@@ -1,41 +1,32 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("window")):"function"==typeof define&&define.amd?define(["window"],t):"object"==typeof exports?exports.SolidLogic=t(require("window")):e.SolidLogic=t(e.window)}(this,e=>(()=>{var t,r,n,i,s={251:(e,t)=>{
2
- /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
3
- t.read=function(e,t,r,n,i){var s,o,a=8*i-n-1,u=(1<<a)-1,c=u>>1,h=-7,l=r?i-1:0,d=r?-1:1,f=e[t+l];for(l+=d,s=f&(1<<-h)-1,f>>=-h,h+=a;h>0;s=256*s+e[t+l],l+=d,h-=8);for(o=s&(1<<-h)-1,s>>=-h,h+=n;h>0;o=256*o+e[t+l],l+=d,h-=8);if(0===s)s=1-c;else{if(s===u)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),s-=c}return(f?-1:1)*o*Math.pow(2,s-n)},t.write=function(e,t,r,n,i,s){var o,a,u,c=8*s-i-1,h=(1<<c)-1,l=h>>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-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,o=h):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),(t+=o+l>=1?d/u:d*Math.pow(2,1-l))*u>=2&&(o++,u/=2),o+l>=h?(a=0,o=h):o+l>=1?(a=(t*u-1)*Math.pow(2,i),o+=l):(a=t*Math.pow(2,l-1)*Math.pow(2,i),o=0));i>=8;e[r+f]=255&a,f+=p,a/=256,i-=8);for(o=o<<i|a,c+=i;c>0;e[r+f]=255&o,f+=p,o/=256,c-=8);e[r+f-p]|=128*g}},1059:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n={Literal:1,Collection:3,Graph:4,NamedNode:5,BlankNode:6,Variable:7}},2727:(e,t,r)=>{"use strict";r.r(t),r.d(t,{docpart:()=>s,document:()=>o,hostpart:()=>a,join:()=>u,protocol:()=>c,refTo:()=>h});var n=r(5108),i=i||console.log;function s(e){var t;return(t=e.indexOf("#"))<0?e:e.slice(0,t)}function o(e){return new n.A(s(e))}function a(e){var t=/[^\/]*\/\/([^\/]*)\//.exec(e);return t?t[1]:""}function u(e,t){var r,n,s,o,a,u=t.indexOf("#");if(u>0&&(t=t.slice(0,u)),0===e.length)return t;if(0===e.indexOf("#"))return t+e;if(e.indexOf(":")>=0)return e;if(r=t.indexOf(":"),0===t.length)return e;if(r<0)return i("Invalid base: "+t+" in join with given: "+e),e;if(n=t.slice(0,+r+1||9e9),0===e.indexOf("//"))return n+e;if(t.indexOf("//",r)===r+1){if((s=t.indexOf("/",r+3))<0)return t.length-r-3>0?t+"/"+e:n+e}else if((s=t.indexOf("/",r+1))<0)return t.length-r-1>0?t+"/"+e:n+e;if(0===e.indexOf("/"))return t.slice(0,s)+e;if((o=(a=t.slice(s)).lastIndexOf("/"))<0)return n+e;for(o>=0&&o<a.length-1&&(a=a.slice(0,+o+1||9e9)),a+=e;a.match(/[^\/]*\/\.\.\//);)a=a.replace(/[^\/]*\/\.\.\//,"");return a=(a=a.replace(/\.\//g,"")).replace(/\/\.$/,"/"),t.slice(0,s)+a}function c(e){const t=e.indexOf(":");return t<0?null:e.slice(0,t)}function h(e,t){var r,n,i,s,o,a,u,c,h,l,d,f,p=new RegExp("^[-_a-zA-Z0-9.]+:(//[^/]*)?/[^/]*$");if(!e)return t;if(e===t)return"";for(r=u=0,s=t.length;u<s;r=++u){if(t[r]!==e[r])break}if(e.slice(0,r).match(p)&&((n=t.indexOf("//"))<0&&(n=-2),i=t.indexOf("/",n+2),"/"!==t[i+1]&&"/"!==e[i+1]&&t.slice(0,i)===e.slice(0,i)))return t.slice(i);if("#"===t[r]&&e.length===r)return t.slice(r);for(;r>0&&"/"!==t[r-1];)r--;if(r<3)return t;if(e.indexOf("//",r-2)>0||t.indexOf("//",r-2)>0)return t;if(e.indexOf(":",r)>0)return t;for(a=0,c=0,o=(l=e.slice(r)).length;c<o;c++)"/"===l[c]&&a++;if(0===a&&r<t.length&&"#"===t[r])return"./"+t.slice(r);if(0===a&&r===t.length)return"./";if(f="",a>0)for(h=1,d=a;d>=1?h<=d:h>=d;d>=1?++h:--h)f+="../";return f+t.slice(r)}},2915:(e,t,r)=>{"use strict";r.d(t,{CZ:()=>u,D0:()=>l,DJ:()=>a,DZ:()=>h,GE:()=>m,P3:()=>o,RN:()=>w,SH:()=>i,Y2:()=>p,YC:()=>v,aF:()=>f,c$:()=>d,fY:()=>c,hr:()=>y,jt:()=>g,ok:()=>s});var n=r(9403);function i(e){return"object"==typeof e&&null!==e&&"subject"in e}function s(e){return"object"==typeof e&&null!==e&&"statements"in e}function o(e){return l(e)&&e.termType===n.r0}function a(e){return e&&Object.prototype.hasOwnProperty.call(e,"termType")&&(e.termType===n.Kk||e.termType===n.P2||e.termType===n.$Q||e.termType===n.r0||e.termType===n.QW||e.termType===n.bD)}function u(e){return e&&Object.prototype.hasOwnProperty.call(e,"termType")&&(e.termType===n.Kk||e.termType===n.P2||e.termType===n.$Q||e.termType===n.r0||e.termType===n.QW||e.termType===n.bD)}function c(e){return l(e)&&(e.termType===n.Kk||e.termType===n.$Q||e.termType===n.P2)}function h(e){return l(e)&&e.termType===n.P2}function l(e){return"object"==typeof e&&null!==e&&"termType"in e}function d(e){return e.termType===n.QW}function f(e){return"object"==typeof e&&null!==e&&"subject"in e&&"predicate"in e&&"object"in e}function p(e){return l(e)&&"NamedNode"===e.termType}function g(e){return l(e)&&"termType"in e&&"BlankNode"===e.termType}function y(e){return l(e)&&(e.termType===n.Kk||e.termType===n.P2||e.termType===n.$Q)}function v(e){return l(e)&&(e.termType===n.Kk||e.termType===n.P2)}function m(e){return l(e)&&(e.termType===n.Kk||e.termType===n.P2||e.termType===n.$Q||e.termType===n.QW)}function w(e){return l(e)&&(e.termType===n.Kk||e.termType===n.P2||e.termType===n.$Q||e.termType===n.ic)}},2931:(e,t,r)=>{"use strict";function n(e){return"string"==typeof e?e:e.value}r.d(t,{E:()=>n})},4011:(e,t,r)=>{"use strict";r.r(t),r.d(t,{DOMParserFactory:()=>l,RDFArrayRemove:()=>w,callbackify:()=>h,domToString:()=>d,dtstamp:()=>p,dumpNode:()=>f,heavyCompare:()=>g,heavyCompareSPO:()=>y,linkRelationProperty:()=>c,log:()=>n.A,mediaTypeClass:()=>u,output:()=>v,parseXML:()=>m,stackString:()=>_,string:()=>a,string_startswith:()=>b,uri:()=>i});var n=r(4940),i=r(2727),s=r(5108),o=r(8392);e=r.hmd(e);const a={template:function(e,t){for(var r=e.split("%s"),n="",i=0;i<t.length;i++)t[i]+="",n+=r[i]+t[i];return n+r.slice(t.length).join()}};function u(e){return e=e.split(";")[0].trim(),new s.A("http://www.w3.org/ns/iana/media-types/"+e+"#Resource")}function c(e){return new s.A("http://www.w3.org/ns/iana/link-relations/relation#"+e.trim())}function h(e,t){e.callbacks={};for(var r=t.length-1;r>=0;r--)e.callbacks[t[r]]=[];e.addHook=function(t){e.callbacks[t]||(e.callbacks[t]=[])},e.addCallback=function(t,r){e.callbacks[t].push(r)},e.removeCallback=function(t,r){for(var n=0;n<e.callbacks[t].length;n++)if(e.callbacks[t][n].name===r)return e.callbacks[t].splice(n,1),!0;return!1},e.insertCallback=function(t,r){e.callbacks[t].unshift(r)},e.fireCallbacks=function(t,r){var n,i=[],s=[],o=e.callbacks[t].length;let a;for(n=o-1;n>=0;n--)a=e.callbacks[t][n],a&&a.apply(e,r)&&i.push(a);for(n=i.length-1;n>=0;n--)s.push(i[n]);for(n=o;n<e.callbacks[t].length;n++)s.push(e.callbacks[t][n]);e.callbacks[t]=s}}function l(){return window.DOMParser?new o.DOMParser:!!window.ActiveXObject&&new ActiveXObject("Microsoft.XMLDOM")}function d(e,t){var r=[];(t=t||{})&&t.selfClosing&&t.selfClosing.split(" ").forEach(function(e){r[e]=!0});var n=[];return t&&t.skipAttributes&&t.skipAttributes.split(" ").forEach(function(e){n[e]=!0}),f(e,t,r,n)}function f(e,t,r,n){var i,s="",o=[!1];if(void 0===e.nodeType)return s;if(1===e.nodeType){if(e.hasAttribute("class")&&t&&t.classWithChildText&&e.matches(t.classWithChildText.class))s+=e.querySelector(t.classWithChildText.element).textContent;else if(!(t&&t.skipNodeWithClass&&e.matches("."+t.skipNodeWithClass))){var a=e.nodeName.toLowerCase();s+="<"+a;var u=[];for(i=e.attributes.length-1;i>=0;i--){var c=e.attributes[i];if(!(n&&n.length>0&&n[c.name])&&!/^\d+$/.test(c.name)){if("class"===c.name&&t&&t.replaceClassItemWith&&c.value.split(" ").indexOf(t.replaceClassItemWith.source)>-1){var h=new RegExp(t.replaceClassItemWith.source,"g");c.value=c.value.replace(h,t.replaceClassItemWith.target).trim()}"class"===c.name&&t&&t.skipClassWithValue&&t.skipClassWithValue===c.value||u.push(c.name+"='"+c.value.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/'/g,"&quot;")+"'")}}if(u.length>0&&(t&&t.sortAttributes&&u.sort(function(e,t){return e.toLowerCase().localeCompare(t.toLowerCase())}),s+=" "+u.join(" ")),r&&r.ename)s+=" />";else{for(s+=">",s+="html"===a?"\n ":"",o.push("style"===a||"script"===a),i=0;i<e.childNodes.length;i++)s+=f(e.childNodes[i]);o.pop(),s+="body"===a?"</"+a+">\n":"</"+a+">"}}}else if(8===e.nodeType)s+="\x3c!--"+e.nodeValue+"--\x3e";else if(3===e.nodeType||4===e.nodeType){var l=e.nodeValue.replace(/\n+$/,"");s+=o[o.length-1]?l:l.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}else console.log("Warning; Cannot handle serialising nodes of type: "+e.nodeType),console.log(e);return s}function p(){var e=new Date,t=e.getYear()+1900,r=e.getMonth()+1,n=e.getDate(),i=e.getUTCHours(),s=e.getUTCMinutes(),o=e.getSeconds();return r<10&&(r="0"+r),n<10&&(n="0"+n),i<10&&(i="0"+i),s<10&&(s="0"+s),o<10&&(o="0"+o),t+"-"+r+"-"+n+"T"+i+":"+s+":"+o+"Z"}function g(e,t,r,n){var i=function(e){return"BlankNode"===e.termType?null:e},s=function(e){var t=r.statementsMatching(e).map(function(e){return i(e.subject)+" "+i(e.predicate)+" "+i(e.object)}).concat(r.statementsMatching(void 0,void 0,e).map(function(e){return i(e.subject)+" "+i(e.predicate)+" "+i(e.object)}));return t.sort(),t.join("\n")};const o=Object.prototype.hasOwnProperty.call(r,"compareTerms")?r.compareTerms(e,t):e.compareTerm(t);return"BlankNode"===e.termType&&"BlankNode"===t.termType?0===o?0:s(e)>s(t)?1:s(e)<s(t)?-1:o:n&&e.uri&&t.uri?(n[e.uri]||e.uri).localeCompare(n[t.uri]||t.uri):o}function y(e,t,r,n){return g(e.subject,t.subject,r,n)||g(e.predicate,t.predicate,r,n)||g(e.object,t.object,r,n)}function v(e){var t=document.createElement("div");t.textContent=e,document.body.appendChild(t)}function m(t,r){return r=r||{},e&&e.exports?(new o.DOMParser).parseFromString(t,r.contentType||"application/xhtml+xml"):("undefined"!=typeof window&&window.DOMParser?new window.DOMParser:new o.DOMParser).parseFromString(t,"application/xml")}function w(e,t){for(var r=0;r<e.length;r++)if(e[r].subject.equals(t.subject)&&e[r].predicate.equals(t.predicate)&&e[r].object.equals(t.object)&&e[r].why.equals(t.why))return void e.splice(r,1);throw new Error("RDFArrayRemove: Array did not contain "+t+" "+t.why)}function b(e,t){return e.slice(0,t.length)===t}function _(e){var t=e+"\n";if(!e.stack)return t+"No stack available.\n";for(var r=e.stack.toString().split("\n"),n=[],i=0;i<r.length;i++){var s=r[i];if(s.indexOf("ecmaunit.js")>-1)break;"("==s.charAt(0)&&(s="function"+s);var o=s.split("@");n.push(o)}for(i=0;i<n.length;i++)t+=" "+n[i][1]+"\n "+n[i][0];return t}},4705:(e,t,r)=>{"use strict";function n(e){return 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},n(e)}function i(e){var t=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");if("object"!=n(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==n(t)?t:t+""}function s(e,t,r){return(t=i(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}r.d(t,{A:()=>s})},4940:(e,t,r)=>{"use strict";r.d(t,{A:()=>n});const n={debug(e){},warn(e){},info(e){},error(e){},success(e){},msg(e){}}},4945:(e,t,r)=>{var n="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==r.g&&r.g,i=function(){function e(){this.fetch=!1,this.DOMException=n.DOMException}return e.prototype=n,new e}();!function(e){!function(t){var n=void 0!==e&&e||"undefined"!=typeof self&&self||void 0!==r.g&&r.g||{},i="URLSearchParams"in n,s="Symbol"in n&&"iterator"in Symbol,o="FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch(e){return!1}}(),a="FormData"in n,u="ArrayBuffer"in n;if(u)var c=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(e){return e&&c.indexOf(Object.prototype.toString.call(e))>-1};function l(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||""===e)throw new TypeError('Invalid character in header field name: "'+e+'"');return e.toLowerCase()}function d(e){return"string"!=typeof e&&(e=String(e)),e}function f(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return s&&(t[Symbol.iterator]=function(){return t}),t}function p(e){this.map={},e instanceof p?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(2!=e.length)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function g(e){if(!e._noBody)return e.bodyUsed?Promise.reject(new TypeError("Already read")):void(e.bodyUsed=!0)}function y(e){return new Promise(function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}})}function v(e){var t=new FileReader,r=y(t);return t.readAsArrayBuffer(e),r}function m(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function w(){return this.bodyUsed=!1,this._initBody=function(e){var t;this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:o&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:a&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:i&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():u&&o&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=m(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u&&(ArrayBuffer.prototype.isPrototypeOf(e)||h(e))?this._bodyArrayBuffer=m(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,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):i&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o&&(this.blob=function(){var e=g(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(){if(this._bodyArrayBuffer){var e=g(this);return e||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}if(o)return this.blob().then(v);throw new Error("could not read as ArrayBuffer")},this.text=function(){var e,t,r,n,i,s=g(this);if(s)return s;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=y(t),n=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=n?n[1]:"utf-8",t.readAsText(e,i),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n<t.length;n++)r[n]=String.fromCharCode(t[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a&&(this.formData=function(){return this.text().then(S)}),this.json=function(){return this.text().then(JSON.parse)},this}p.prototype.append=function(e,t){e=l(e),t=d(t);var r=this.map[e];this.map[e]=r?r+", "+t:t},p.prototype.delete=function(e){delete this.map[l(e)]},p.prototype.get=function(e){return e=l(e),this.has(e)?this.map[e]:null},p.prototype.has=function(e){return this.map.hasOwnProperty(l(e))},p.prototype.set=function(e,t){this.map[l(e)]=d(t)},p.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},p.prototype.keys=function(){var e=[];return this.forEach(function(t,r){e.push(r)}),f(e)},p.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),f(e)},p.prototype.entries=function(){var e=[];return this.forEach(function(t,r){e.push([r,t])}),f(e)},s&&(p.prototype[Symbol.iterator]=p.prototype.entries);var b=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function _(e,t){if(!(this instanceof _))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');var r,i,s=(t=t||{}).body;if(e instanceof _){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new p(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,s||null==e._bodyInit||(s=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new p(t.headers)),this.method=(r=t.method||this.method||"GET",i=r.toUpperCase(),b.indexOf(i)>-1?i:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if("AbortController"in n)return(new AbortController).signal}(),this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&s)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(s),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==t.cache&&"no-cache"!==t.cache)){var o=/([?&])_=[^&]*/;if(o.test(this.url))this.url=this.url.replace(o,"$1_="+(new Date).getTime());else{this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function S(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(e,t){if(!(this instanceof E))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=void 0===t.statusText?"":""+t.statusText,this.headers=new p(t.headers),this.url=t.url||"",this._initBody(e)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})},w.call(_.prototype),w.call(E.prototype),E.prototype.clone=function(){return new E(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},E.error=function(){var e=new E(null,{status:200,statusText:""});return e.ok=!1,e.status=0,e.type="error",e};var x=[301,302,303,307,308];E.redirect=function(e,t){if(-1===x.indexOf(t))throw new RangeError("Invalid status code");return new E(null,{status:t,headers:{location:e}})},t.DOMException=n.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 A(e,r){return new Promise(function(i,s){var a=new _(e,r);if(a.signal&&a.signal.aborted)return s(new t.DOMException("Aborted","AbortError"));var c=new XMLHttpRequest;function h(){c.abort()}if(c.onload=function(){var e,t,r={statusText:c.statusText,headers:(e=c.getAllResponseHeaders()||"",t=new p,e.replace(/\r?\n[\t ]+/g," ").split("\r").map(function(e){return 0===e.indexOf("\n")?e.substr(1,e.length):e}).forEach(function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();try{t.append(n,i)}catch(e){console.warn("Response "+e.message)}}}),t)};0===a.url.indexOf("file://")&&(c.status<200||c.status>599)?r.status=200:r.status=c.status,r.url="responseURL"in c?c.responseURL:r.headers.get("X-Request-URL");var n="response"in c?c.response:c.responseText;setTimeout(function(){i(new E(n,r))},0)},c.onerror=function(){setTimeout(function(){s(new TypeError("Network request failed"))},0)},c.ontimeout=function(){setTimeout(function(){s(new TypeError("Network request timed out"))},0)},c.onabort=function(){setTimeout(function(){s(new t.DOMException("Aborted","AbortError"))},0)},c.open(a.method,function(e){try{return""===e&&n.location.href?n.location.href:e}catch(t){return e}}(a.url),!0),"include"===a.credentials?c.withCredentials=!0:"omit"===a.credentials&&(c.withCredentials=!1),"responseType"in c&&(o?c.responseType="blob":u&&(c.responseType="arraybuffer")),r&&"object"==typeof r.headers&&!(r.headers instanceof p||n.Headers&&r.headers instanceof n.Headers)){var f=[];Object.getOwnPropertyNames(r.headers).forEach(function(e){f.push(l(e)),c.setRequestHeader(e,d(r.headers[e]))}),a.headers.forEach(function(e,t){-1===f.indexOf(t)&&c.setRequestHeader(t,e)})}else a.headers.forEach(function(e,t){c.setRequestHeader(t,e)});a.signal&&(a.signal.addEventListener("abort",h),c.onreadystatechange=function(){4===c.readyState&&a.signal.removeEventListener("abort",h)}),c.send(void 0===a._bodyInit?null:a._bodyInit)})}A.polyfill=!0,n.fetch||(n.fetch=A,n.Headers=p,n.Request=_,n.Response=E),t.Headers=p,t.Request=_,t.Response=E,t.fetch=A,Object.defineProperty(t,"__esModule",{value:!0})}({})}(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=n.fetch?n:i;(t=s.fetch).default=s.fetch,t.fetch=s.fetch,t.Headers=s.Headers,t.Request=s.Request,t.Response=s.Response,e.exports=t},5108:(e,t,r)=>{"use strict";r.d(t,{A:()=>c});var n=r(4705),i=r(1059),s=r(8936),o=r(9403),a=r(2931),u=r(2915);class c extends s.A{constructor(e){if(super((0,a.E)(e)),(0,n.A)(this,"termType",o.Kk),(0,n.A)(this,"classOrder",i.A.NamedNode),!this.value)throw new Error("Missing IRI for NamedNode");if(!this.value.includes(":"))throw new Error('NamedNode IRI "'+e+'" must be absolute.');if(this.value.includes(" "))throw new Error('Error: NamedNode IRI "'+e+'" must not contain unencoded spaces.')}dir(){var e=this.value.split("#")[0],t=e.slice(0,-1).lastIndexOf("/"),r=e.indexOf("//");return r>=0&&t<r+2||t<0?null:new c(e.slice(0,t+1))}site(){var e=this.value.split("#")[0],t=e.indexOf("//");if(t<0)throw new Error("This URI does not have a web site part (origin)");var r=e.indexOf("/",t+2);return new c(r<0?e.slice(0)+"/":e.slice(0,r+1))}doc(){return this.value.indexOf("#")<0?this:new c(this.value.split("#")[0])}toString(){return"<"+this.value+">"}id(){return this.value.split("#")[1]}get uri(){return this.value}set uri(e){this.value=e}static fromValue(e){return null==e||(0,u.D0)(e)?e:new c(e)}}},5306:function(e,t){var r,n,i;n=[],void 0===(i="function"==typeof(r=function(){"use strict";function e(e,t){function r(){this.constructor=e}r.prototype=t.prototype,e.prototype=new r}function t(e,r,n,i){this.message=e,this.expected=r,this.found=n,this.location=i,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,t)}function r(e,r){r=void 0!==r?r:{};var n,i={},s={turtleDoc:Yr},o=Yr,a=function(e){var t=ei.toJSON();return t["@graph"]=[],e.filter(e=>Array.isArray(e)).forEach(e=>{e.forEach(e=>{t["@graph"].push(e)})}),1===t["@graph"].length&&(Object.assign(t,t["@graph"][0]),delete t["@graph"]),t},u="\ufeff",c=Kr("\ufeff",!1),h=".",l=Kr(".",!1),d=function(e){return e},f="#",p=Kr("#",!1),g=/^[^\n]/,y=Vr(["\n"],!0,!1),v="\n",m=Kr("\n",!1),w=function(e){return e.join("")},b="@prefix",_=Kr("@prefix",!1),S=function(e,t){return ei.addPrefix(""===e?"0":e,t),{}},E="@base",x=Kr("@base",!1),A=function(e){return ei.addBase(e),{}},F=/^[Bb]/,T=Vr(["B","b"],!1,!1),k=/^[Aa]/,I=Vr(["A","a"],!1,!1),C=/^[Ss]/,R=Vr(["S","s"],!1,!1),P=/^[Ee]/,N=Vr(["E","e"],!1,!1),U=/^[Pp]/,O=Vr(["P","p"],!1,!1),L=/^[Rr]/,D=Vr(["R","r"],!1,!1),j=/^[Ff]/,M=Vr(["F","f"],!1,!1),B=/^[Ii]/,H=Vr(["I","i"],!1,!1),q=/^[Xx]/,K=Vr(["X","x"],!1,!1),V=function(e,t){var r={};return"string"==typeof e&&"[]"!==e?r["@id"]=e:"object"==typeof e&&Object.assign(r,e),t&&Object.assign(r,t),[r]},$=function(e,t){var r={};return e&&Object.assign(r,e),t&&Object.assign(r,t),[r]},W=";",J=Kr(";",!1),z=function(e,t,r,n){var i={};return i[r]=n,i},X=function(e,t,r){return r},G=function(e,t,r){var n={};return r.unshift(Zn(e,t)),r.forEach(e=>{e&&Object.keys(e).forEach(t=>{e[t].forEach(e=>{"@type"===t&&void 0!==e["@id"]&&(e=e["@id"]),void 0===n[t]?n[t]=e:Array.isArray(n[t])?n[t].push(e):n[t]=[n[t],e]})})}),n},Y=",",Q=Kr(",",!1),Z=function(e,t){return t},ee=function(e,t){return t.unshift(e),t},te="a",re=Kr("a",!1),ne=function(){return"@type"},ie=function(e){return ti(e,!0)},se=function(e){return ti(e,!1)},oe=function(e){return"[]"===e?{}:{"@id":e}},ae=function(e){return{"@id":e}},ue="[",ce=Kr("[",!1),he="]",le=Kr("]",!1),de="(",fe=Kr("(",!1),pe=")",ge=Kr(")",!1),ye=function(e){return{"@list":e}},ve=function(e,t){return{"@value":e,"@language":t}},me="^^",we=Kr("^^",!1),be=function(e,t){if("http://www.w3.org/2001/XMLSchema#boolean"===t&&"true"===e)return!0;if("http://www.w3.org/2001/XMLSchema#boolean"===t&&"false"===e)return!1;if("http://www.w3.org/2001/XMLSchema#integer"===t)return parseInt(e);if("http://www.w3.org/2001/XMLSchema#double"===t)return parseFloat(e);const r=ei.resolve(t,!0);if(r){const n=t.split(":")[0];if("http://www.w3.org/2001/XMLSchema#boolean"===r&&"true"===e)return ei.decrement(n),!0;if("http://www.w3.org/2001/XMLSchema#boolean"===r&&"false"===e)return ei.decrement(n),!1;if("http://www.w3.org/2001/XMLSchema#integer"===r)return ei.decrement(n),parseInt(e);if("http://www.w3.org/2001/XMLSchema#double"===r)return ei.decrement(n),parseFloat(e)}return{"@value":e,"@type":t}},_e="true",Se=Kr("true",!1),Ee=function(){return!0},xe="false",Ae=Kr("false",!1),Fe=function(){return!1},Te=function(e){return e+":"},ke="<",Ie=Kr("<",!1),Ce=/^[^\0- <>"{}|\^`\\]/,Re=Vr([["\0"," "],"<",">",'"',"{","}","|","^","`","\\"],!0,!1),Pe=">",Ne=Kr(">",!1),Ue=function(e){const t=e.map(e=>65536<=e.codePointAt(0)&&e.codePointAt(0)<=983039?"a":1===e.length?e:6===e.length?String.fromCharCode("0x"+e.substring(2)):10===e.length?String.fromCodePoint("0x"+e.substring(2)):e).join("");if(t.match(/^[^\u0000-\u0020<>"{}|^`\\]*$/)){var r=e.join("");try{return ei.resolve(r)}catch(e){qr("Invalid IRIREF "+r)}}else qr("Invalid IRIREF "+e.join("")+" / "+t)},Oe=":",Le=Kr(":",!1),De=function(e){return e=e||"0",!1===ei.hasPrefix(e)&&qr("undefined prefix "+e),e},je=function(e){return e||""},Me=function(e,t){return ei.increment(e),ei.resolve(e+":"+t)},Be="_:",He=Kr("_:",!1),qe=/^[0-9]/,Ke=Vr([["0","9"]],!1,!1),Ve="@",$e=Kr("@",!1),We=/^[a-zA-Z]/,Je=Vr([["a","z"],["A","Z"]],!1,!1),ze="-",Xe=Kr("-",!1),Ge=/^[a-zA-Z0-9]/,Ye=Vr([["a","z"],["A","Z"],["0","9"]],!1,!1),Qe=function(e,t){return"-"+t.join("")},Ze=function(e,t){return e.join("")+t.join("")},et=/^[+\-]/,tt=Vr(["+","-"],!1,!1),rt=function(e){return e.match(/^[0+][0-9]+$/)?{"@value":e,"@type":"http://www.w3.org/2001/XMLSchema#integer"}:parseInt(e)},nt=function(e){return{"@value":e,"@type":"http://www.w3.org/2001/XMLSchema#decimal"}},it=function(e){return{"@value":e,"@type":"http://www.w3.org/2001/XMLSchema#double"}},st=/^[eE]/,ot=Vr(["e","E"],!1,!1),at='"',ut=Kr('"',!1),ct=/^[^"\\\n\r]/,ht=Vr(['"',"\\","\n","\r"],!0,!1),lt="'",dt=Kr("'",!1),ft=/^[^'\\\n\r]/,pt=Vr(["'","\\","\n","\r"],!0,!1),gt="'''",yt=Kr("'''",!1),vt=/^[^'\\]/,mt=Vr(["'","\\"],!0,!1),wt="''",bt=Kr("''",!1),_t=function(e,t){return"''"+t.join("")},St=function(e,t){return"'"+t.join("")},Et=function(e,t){return e.join("")+t.join("")},xt='"""',At=Kr('"""',!1),Ft=/^[^"\\]/,Tt=Vr(['"',"\\"],!0,!1),kt='""',It=Kr('""',!1),Ct=function(e,t){return'""'+t.join("")},Rt=function(e,t){return'"'+t.join("")},Pt="\\U",Nt=Kr("\\U",!1),Ut=function(e){return String.fromCodePoint(parseInt(e.join(""),16))},Ot="\\u",Lt=Kr("\\u",!1),Dt=function(e){return String.fromCharCode(parseInt(e.join(""),16))},jt="\\t",Mt=Kr("\\t",!1),Bt=function(){return"\t"},Ht="\\b",qt=Kr("\\b",!1),Kt=function(){return"\b"},Vt="\\n",$t=Kr("\\n",!1),Wt=function(){return"\n"},Jt="\\r",zt=Kr("\\r",!1),Xt=function(){return"\r"},Gt="\\f",Yt=Kr("\\f",!1),Qt=function(){return"\f"},Zt='\\"',er=Kr('\\"',!1),tr=function(){return'"'},rr="\\'",nr=Kr("\\'",!1),ir=function(){return"'"},sr="\\\\",or=Kr("\\\\",!1),ar=function(){return"\\"},ur=/^[ \t\r\n]/,cr=Vr([" ","\t","\r","\n"],!1,!1),hr=function(){return"[]"},lr=/^[\uD800-\uDBFF]/,dr=Vr([["\ud800","\udbff"]],!1,!1),fr=/^[\uDC00-\uDFFF]/,pr=Vr([["\udc00","\udfff"]],!1,!1),gr=function(e,t){return e+t},yr=/^[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]/,vr=Vr([["A","Z"],["a","z"],["À","Ö"],["Ø","ö"],["ø","˿"],["Ͱ","ͽ"],["Ϳ","῿"],["‌","‍"],["⁰","↏"],["Ⰰ","⿯"],["、","퟿"],["豈","﷏"],["ﷰ","�"]],!1,!1),mr="_",wr=Kr("_",!1),br="·",_r=Kr("·",!1),Sr=/^[\u0300-\u036F]/,Er=Vr([["̀","ͯ"]],!1,!1),xr=/^[\u203F-\u2040]/,Ar=Vr([["‿","⁀"]],!1,!1),Fr=function(e,t,r,n){return r.join("")+n.join("")},Tr=function(e,t,r){return e+t.join("")+r.join("")},kr="%",Ir=Kr("%",!1),Cr=/^[0-9A-Fa-f]/,Rr=Vr([["0","9"],["A","F"],["a","f"]],!1,!1),Pr="\\",Nr=Kr("\\",!1),Ur=/^[_~.!$&'()*+,;=\/?#@%\-]/,Or=Vr(["_","~",".","!","$","&","'","(",")","*","+",",",";","=","/","?","#","@","%","-"],!1,!1),Lr=0,Dr=0,jr=[{line:1,column:1}],Mr=0,Br=[],Hr=0;if("startRule"in r){if(!(r.startRule in s))throw new Error("Can't start parsing from rule \""+r.startRule+'".');o=s[r.startRule]}function qr(e,t){throw Xr(e,t=void 0!==t?t:Jr(Dr,Lr))}function Kr(e,t){return{type:"literal",text:e,ignoreCase:t}}function Vr(e,t,r){return{type:"class",parts:e,inverted:t,ignoreCase:r}}function $r(){return{type:"end"}}function Wr(t){var r,n=jr[t];if(n)return n;for(r=t-1;!jr[r];)r--;for(n={line:(n=jr[r]).line,column:n.column};r<t;)10===e.charCodeAt(r)?(n.line++,n.column=1):n.column++,r++;return jr[t]=n,n}function Jr(e,t){var r=Wr(e),n=Wr(t);return{start:{offset:e,line:r.line,column:r.column},end:{offset:t,line:n.line,column:n.column}}}function zr(e){Lr<Mr||(Lr>Mr&&(Mr=Lr,Br=[]),Br.push(e))}function Xr(e,r){return new t(e,null,null,r)}function Gr(e,r,n){return new t(t.buildMessage(e,r),e,r,n)}function Yr(){var e,t,r,n,s;for(e=Lr,t=[],r=Qr();r!==i;)t.push(r),r=Qr();if(t!==i){for(r=[],n=Zr();n!==i;)r.push(n),n=Zr();if(r!==i){for(n=[],s=tn();s!==i;)n.push(s),s=tn();n!==i?(Dr=e,e=t=a(r)):(Lr=e,e=i)}else Lr=e,e=i}else Lr=e,e=i;return e}function Qr(){var t;return 65279===e.charCodeAt(Lr)?(t=u,Lr++):(t=i,0===Hr&&zr(c)),t}function Zr(){var t,r,n,s;if((t=rn())===i)if(t=Lr,(r=un())!==i){for(n=[],s=tn();s!==i;)n.push(s),s=tn();n!==i?(46===e.charCodeAt(Lr)?(s=h,Lr++):(s=i,0===Hr&&zr(l)),s!==i?(Dr=t,t=r=d(r)):(Lr=t,t=i)):(Lr=t,t=i)}else Lr=t,t=i;return t}function en(){var t,r,n,s;if(t=Lr,35===e.charCodeAt(Lr)?(r=f,Lr++):(r=i,0===Hr&&zr(p)),r!==i){for(n=[],g.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(y));s!==i;)n.push(s),g.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(y));n!==i?(10===e.charCodeAt(Lr)?(s=v,Lr++):(s=i,0===Hr&&zr(m)),s!==i?(Dr=t,t=r=w(n)):(Lr=t,t=i)):(Lr=t,t=i)}else Lr=t,t=i;return t}function tn(){var e;return(e=Hn())===i&&(e=en()),e}function rn(){var e;return(e=nn())===i&&(e=sn())===i&&(e=an())===i&&(e=on()),e}function nn(){var t,r,n,s,o,a,u,c,d;for(t=Lr,r=[],n=tn();n!==i;)r.push(n),n=tn();if(r!==i)if(e.substr(Lr,7)===b?(n=b,Lr+=7):(n=i,0===Hr&&zr(_)),n!==i){for(s=[],o=tn();o!==i;)s.push(o),o=tn();if(s!==i)if((o=Tn())!==i){for(a=[],u=tn();u!==i;)a.push(u),u=tn();if(a!==i)if((u=An())!==i){for(c=[],d=tn();d!==i;)c.push(d),d=tn();c!==i?(46===e.charCodeAt(Lr)?(d=h,Lr++):(d=i,0===Hr&&zr(l)),d!==i?(Dr=t,t=r=S(o,u)):(Lr=t,t=i)):(Lr=t,t=i)}else Lr=t,t=i;else Lr=t,t=i}else Lr=t,t=i;else Lr=t,t=i}else Lr=t,t=i;else Lr=t,t=i;return t}function sn(){var t,r,n,s,o,a,u;for(t=Lr,r=[],n=tn();n!==i;)r.push(n),n=tn();if(r!==i)if(e.substr(Lr,5)===E?(n=E,Lr+=5):(n=i,0===Hr&&zr(x)),n!==i){for(s=[],o=tn();o!==i;)s.push(o),o=tn();if(s!==i)if((o=An())!==i){for(a=[],u=tn();u!==i;)a.push(u),u=tn();a!==i?(46===e.charCodeAt(Lr)?(u=h,Lr++):(u=i,0===Hr&&zr(l)),u!==i?(Dr=t,t=r=A(o)):(Lr=t,t=i)):(Lr=t,t=i)}else Lr=t,t=i;else Lr=t,t=i}else Lr=t,t=i;else Lr=t,t=i;return t}function on(){var t,r,n,s,o,a,u,c;for(t=Lr,r=[],n=tn();n!==i;)r.push(n),n=tn();if(r!==i)if(F.test(e.charAt(Lr))?(n=e.charAt(Lr),Lr++):(n=i,0===Hr&&zr(T)),n!==i)if(k.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(I)),s!==i)if(C.test(e.charAt(Lr))?(o=e.charAt(Lr),Lr++):(o=i,0===Hr&&zr(R)),o!==i)if(P.test(e.charAt(Lr))?(a=e.charAt(Lr),Lr++):(a=i,0===Hr&&zr(N)),a!==i){for(u=[],c=tn();c!==i;)u.push(c),c=tn();u!==i&&(c=An())!==i?(Dr=t,t=r=A(c)):(Lr=t,t=i)}else Lr=t,t=i;else Lr=t,t=i;else Lr=t,t=i;else Lr=t,t=i;else Lr=t,t=i;return t}function an(){var t,r,n,s,o,a,u,c,h,l,d,f;for(t=Lr,r=[],n=tn();n!==i;)r.push(n),n=tn();if(r!==i)if(U.test(e.charAt(Lr))?(n=e.charAt(Lr),Lr++):(n=i,0===Hr&&zr(O)),n!==i)if(L.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(D)),s!==i)if(P.test(e.charAt(Lr))?(o=e.charAt(Lr),Lr++):(o=i,0===Hr&&zr(N)),o!==i)if(j.test(e.charAt(Lr))?(a=e.charAt(Lr),Lr++):(a=i,0===Hr&&zr(M)),a!==i)if(B.test(e.charAt(Lr))?(u=e.charAt(Lr),Lr++):(u=i,0===Hr&&zr(H)),u!==i)if(q.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(K)),c!==i){for(h=[],l=tn();l!==i;)h.push(l),l=tn();if(h!==i)if((l=Tn())!==i){for(d=[],f=tn();f!==i;)d.push(f),f=tn();d!==i&&(f=An())!==i?(Dr=t,t=r=S(l,f)):(Lr=t,t=i)}else Lr=t,t=i;else Lr=t,t=i}else Lr=t,t=i;else Lr=t,t=i;else Lr=t,t=i;else Lr=t,t=i;else Lr=t,t=i;else Lr=t,t=i;else Lr=t,t=i;return t}function un(){var e,t,r;return e=Lr,(t=dn())!==i&&(r=cn())!==i?(Dr=e,e=t=V(t,r)):(Lr=e,e=i),e===i&&(e=Lr,(t=yn())!==i?((r=cn())===i&&(r=null),r!==i?(Dr=e,e=t=$(t,r)):(Lr=e,e=i)):(Lr=e,e=i)),e}function cn(){var t,r,n,s,o,a,u,c,h,l;if(t=Lr,(r=ln())!==i)if((n=hn())!==i){for(s=[],o=Lr,a=[],u=tn();u!==i;)a.push(u),u=tn();for(a!==i?(59===e.charCodeAt(Lr)?(u=W,Lr++):(u=i,0===Hr&&zr(J)),u!==i?(c=Lr,(h=ln())!==i&&(l=hn())!==i?(Dr=c,c=h=z(r,n,h,l)):(Lr=c,c=i),c===i&&(c=null),c!==i?(Dr=o,o=a=X(r,n,c)):(Lr=o,o=i)):(Lr=o,o=i)):(Lr=o,o=i);o!==i;){for(s.push(o),o=Lr,a=[],u=tn();u!==i;)a.push(u),u=tn();a!==i?(59===e.charCodeAt(Lr)?(u=W,Lr++):(u=i,0===Hr&&zr(J)),u!==i?(c=Lr,(h=ln())!==i&&(l=hn())!==i?(Dr=c,c=h=z(r,n,h,l)):(Lr=c,c=i),c===i&&(c=null),c!==i?(Dr=o,o=a=X(r,n,c)):(Lr=o,o=i)):(Lr=o,o=i)):(Lr=o,o=i)}s!==i?(Dr=t,t=r=G(r,n,s)):(Lr=t,t=i)}else Lr=t,t=i;else Lr=t,t=i;return t}function hn(){var t,r,n,s,o,a,u;if(t=Lr,(r=pn())!==i){for(n=[],s=Lr,o=[],a=tn();a!==i;)o.push(a),a=tn();for(o!==i?(44===e.charCodeAt(Lr)?(a=Y,Lr++):(a=i,0===Hr&&zr(Q)),a!==i&&(u=pn())!==i?(Dr=s,s=o=Z(r,u)):(Lr=s,s=i)):(Lr=s,s=i);s!==i;){for(n.push(s),s=Lr,o=[],a=tn();a!==i;)o.push(a),a=tn();o!==i?(44===e.charCodeAt(Lr)?(a=Y,Lr++):(a=i,0===Hr&&zr(Q)),a!==i&&(u=pn())!==i?(Dr=s,s=o=Z(r,u)):(Lr=s,s=i)):(Lr=s,s=i)}n!==i?(Dr=t,t=r=ee(r,n)):(Lr=t,t=i)}else Lr=t,t=i;return t}function ln(){var t,r,n;if(t=Lr,(r=fn())!==i&&(Dr=t,r=d(r)),(t=r)===i){for(t=Lr,r=[],n=tn();n!==i;)r.push(n),n=tn();r!==i?(97===e.charCodeAt(Lr)?(n=te,Lr++):(n=i,0===Hr&&zr(re)),n!==i?(Dr=t,t=r=ne()):(Lr=t,t=i)):(Lr=t,t=i)}return t}function dn(){var e,t;return e=Lr,(t=vn())!==i&&(Dr=e,t=ie(t)),(e=t)===i&&(e=xn())===i&&(e=Sn()),e}function fn(){var e,t,r;for(e=Lr,t=[],r=tn();r!==i;)t.push(r),r=tn();return t!==i&&(r=Sn())!==i?(Dr=e,e=t=d(r)):(Lr=e,e=i),e}function pn(){var e,t;return(e=gn())===i&&(e=Lr,(t=vn())!==i&&(Dr=e,t=se(t)),(e=t)===i&&(e=Lr,(t=xn())!==i&&(Dr=e,t=oe(t)),(e=t)===i&&(e=Lr,(t=yn())!==i&&(Dr=e,t=d(t)),(e=t)===i&&(e=Lr,(t=Sn())!==i&&(Dr=e,t=ae(t)),e=t)))),e}function gn(){var e;return(e=wn())===i&&(e=mn())===i&&(e=bn()),e}function yn(){var t,r,n,s,o,a;for(t=Lr,r=[],n=tn();n!==i;)r.push(n),n=tn();if(r!==i)if(91===e.charCodeAt(Lr)?(n=ue,Lr++):(n=i,0===Hr&&zr(ce)),n!==i)if((s=cn())!==i){for(o=[],a=tn();a!==i;)o.push(a),a=tn();o!==i?(93===e.charCodeAt(Lr)?(a=he,Lr++):(a=i,0===Hr&&zr(le)),a!==i?(Dr=t,t=r=d(s)):(Lr=t,t=i)):(Lr=t,t=i)}else Lr=t,t=i;else Lr=t,t=i;else Lr=t,t=i;return t}function vn(){var t,r,n,s,o,a;for(t=Lr,r=[],n=tn();n!==i;)r.push(n),n=tn();if(r!==i)if(40===e.charCodeAt(Lr)?(n=de,Lr++):(n=i,0===Hr&&zr(fe)),n!==i){for(s=[],o=pn();o!==i;)s.push(o),o=pn();if(s!==i){for(o=[],a=tn();a!==i;)o.push(a),a=tn();o!==i?(41===e.charCodeAt(Lr)?(a=pe,Lr++):(a=i,0===Hr&&zr(ge)),a!==i?(Dr=t,t=r=ye(s)):(Lr=t,t=i)):(Lr=t,t=i)}else Lr=t,t=i}else Lr=t,t=i;else Lr=t,t=i;return t}function mn(){var e,t,r;for(e=Lr,t=[],r=tn();r!==i;)t.push(r),r=tn();return t!==i?((r=Nn())===i&&(r=Pn())===i&&(r=Rn()),r!==i?(Dr=e,e=t=d(r)):(Lr=e,e=i)):(Lr=e,e=i),e}function wn(){var t,r,n,s,o,a,u;for(t=Lr,r=[],n=tn();n!==i;)r.push(n),n=tn();if(r!==i)if((n=_n())!==i){for(s=[],o=tn();o!==i;)s.push(o),o=tn();s!==i&&(o=Cn())!==i?(Dr=t,t=r=ve(n,o)):(Lr=t,t=i)}else Lr=t,t=i;else Lr=t,t=i;if(t===i){for(t=Lr,r=[],n=tn();n!==i;)r.push(n),n=tn();if(r!==i)if((n=_n())!==i){for(s=[],o=tn();o!==i;)s.push(o),o=tn();if(s!==i)if(e.substr(Lr,2)===me?(o=me,Lr+=2):(o=i,0===Hr&&zr(we)),o!==i){for(a=[],u=tn();u!==i;)a.push(u),u=tn();a!==i&&(u=Sn())!==i?(Dr=t,t=r=be(n,u)):(Lr=t,t=i)}else Lr=t,t=i;else Lr=t,t=i}else Lr=t,t=i;else Lr=t,t=i;if(t===i){for(t=Lr,r=[],n=tn();n!==i;)r.push(n),n=tn();r!==i&&(n=_n())!==i?(Dr=t,t=r=d(n)):(Lr=t,t=i)}}return t}function bn(){var t,r,n;for(t=Lr,r=[],n=tn();n!==i;)r.push(n),n=tn();if(r!==i?(e.substr(Lr,4)===_e?(n=_e,Lr+=4):(n=i,0===Hr&&zr(Se)),n!==i?(Dr=t,t=r=Ee()):(Lr=t,t=i)):(Lr=t,t=i),t===i){for(t=Lr,r=[],n=tn();n!==i;)r.push(n),n=tn();r!==i?(e.substr(Lr,5)===xe?(n=xe,Lr+=5):(n=i,0===Hr&&zr(Ae)),n!==i?(Dr=t,t=r=Fe()):(Lr=t,t=i)):(Lr=t,t=i)}return t}function _n(){var e,t,r;for(e=Lr,t=[],r=tn();r!==i;)t.push(r),r=tn();return t!==i?((r=Dn())===i&&(r=jn())===i&&(r=Ln())===i&&(r=On()),r!==i?(Dr=e,e=t=d(r)):(Lr=e,e=i)):(Lr=e,e=i),e}function Sn(){var e,t,r;for(e=Lr,t=[],r=tn();r!==i;)t.push(r),r=tn();if(t!==i&&(r=An())!==i?(Dr=e,e=t=d(r)):(Lr=e,e=i),e===i){for(e=Lr,t=[],r=tn();r!==i;)t.push(r),r=tn();t!==i&&(r=En())!==i?(Dr=e,e=t=d(r)):(Lr=e,e=i)}return e}function En(){var e,t;return(e=kn())===i&&(e=Lr,(t=Fn())!==i&&(Dr=e,t=Te(t)),e=t),e}function xn(){var e,t,r;for(e=Lr,t=[],r=tn();r!==i;)t.push(r),r=tn();if(t!==i&&(r=In())!==i?(Dr=e,e=t=d(r)):(Lr=e,e=i),e===i){for(e=Lr,t=[],r=tn();r!==i;)t.push(r),r=tn();t!==i&&(r=qn())!==i?(Dr=e,e=t=d(r)):(Lr=e,e=i)}return e}function An(){var t,r,n,s;if(t=Lr,60===e.charCodeAt(Lr)?(r=ke,Lr++):(r=i,0===Hr&&zr(Ie)),r!==i){for(n=[],Ce.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(Re)),s===i&&(s=Mn());s!==i;)n.push(s),Ce.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(Re)),s===i&&(s=Mn());n!==i?(62===e.charCodeAt(Lr)?(s=Pe,Lr++):(s=i,0===Hr&&zr(Ne)),s!==i?(Dr=t,t=r=Ue(n)):(Lr=t,t=i)):(Lr=t,t=i)}else Lr=t,t=i;return t}function Fn(){var t,r,n;return t=Lr,(r=Wn())===i&&(r=null),r!==i?(58===e.charCodeAt(Lr)?(n=Oe,Lr++):(n=i,0===Hr&&zr(Le)),n!==i?(Dr=t,t=r=De(r)):(Lr=t,t=i)):(Lr=t,t=i),t}function Tn(){var t,r,n;return t=Lr,(r=Wn())===i&&(r=null),r!==i?(58===e.charCodeAt(Lr)?(n=Oe,Lr++):(n=i,0===Hr&&zr(Le)),n!==i?(Dr=t,t=r=je(r)):(Lr=t,t=i)):(Lr=t,t=i),t}function kn(){var e,t,r;return e=Lr,(t=Fn())!==i&&(r=Jn())!==i?(Dr=e,e=t=Me(t,r)):(Lr=e,e=i),e}function In(){var t,r,n,s,o,a,u,c,d,f;if(t=Lr,r=Lr,e.substr(Lr,2)===Be?(n=Be,Lr+=2):(n=i,0===Hr&&zr(He)),n!==i)if((s=Vn())===i&&(qe.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(Ke))),s!==i){for(o=[],a=$n();a!==i;)o.push(a),a=$n();if(o!==i){if(a=[],u=Lr,c=[],46===e.charCodeAt(Lr)?(d=h,Lr++):(d=i,0===Hr&&zr(l)),d!==i)for(;d!==i;)c.push(d),46===e.charCodeAt(Lr)?(d=h,Lr++):(d=i,0===Hr&&zr(l));else c=i;if(c!==i){if(d=[],(f=$n())!==i)for(;f!==i;)d.push(f),f=$n();else d=i;d!==i?u=c=[c,d]:(Lr=u,u=i)}else Lr=u,u=i;for(;u!==i;){if(a.push(u),u=Lr,c=[],46===e.charCodeAt(Lr)?(d=h,Lr++):(d=i,0===Hr&&zr(l)),d!==i)for(;d!==i;)c.push(d),46===e.charCodeAt(Lr)?(d=h,Lr++):(d=i,0===Hr&&zr(l));else c=i;if(c!==i){if(d=[],(f=$n())!==i)for(;f!==i;)d.push(f),f=$n();else d=i;d!==i?u=c=[c,d]:(Lr=u,u=i)}else Lr=u,u=i}a!==i?r=n=[n,s,o,a]:(Lr=r,r=i)}else Lr=r,r=i}else Lr=r,r=i;else Lr=r,r=i;return t=r!==i?e.substring(t,Lr):r}function Cn(){var t,r,n,s,o,a,u,c;if(t=Lr,64===e.charCodeAt(Lr)?(r=Ve,Lr++):(r=i,0===Hr&&zr($e)),r!==i){if(n=[],We.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(Je)),s!==i)for(;s!==i;)n.push(s),We.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(Je));else n=i;if(n!==i){if(s=[],o=Lr,45===e.charCodeAt(Lr)?(a=ze,Lr++):(a=i,0===Hr&&zr(Xe)),a!==i){if(u=[],Ge.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Ye)),c!==i)for(;c!==i;)u.push(c),Ge.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Ye));else u=i;u!==i?(Dr=o,o=a=Qe(n,u)):(Lr=o,o=i)}else Lr=o,o=i;for(;o!==i;)if(s.push(o),o=Lr,45===e.charCodeAt(Lr)?(a=ze,Lr++):(a=i,0===Hr&&zr(Xe)),a!==i){if(u=[],Ge.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Ye)),c!==i)for(;c!==i;)u.push(c),Ge.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Ye));else u=i;u!==i?(Dr=o,o=a=Qe(n,u)):(Lr=o,o=i)}else Lr=o,o=i;s!==i?(Dr=t,t=r=Ze(n,s)):(Lr=t,t=i)}else Lr=t,t=i}else Lr=t,t=i;return t}function Rn(){var t,r,n,s,o,a;if(t=Lr,r=Lr,n=Lr,et.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(tt)),s===i&&(s=null),s!==i){if(o=[],qe.test(e.charAt(Lr))?(a=e.charAt(Lr),Lr++):(a=i,0===Hr&&zr(Ke)),a!==i)for(;a!==i;)o.push(a),qe.test(e.charAt(Lr))?(a=e.charAt(Lr),Lr++):(a=i,0===Hr&&zr(Ke));else o=i;o!==i?n=s=[s,o]:(Lr=n,n=i)}else Lr=n,n=i;return(r=n!==i?e.substring(r,Lr):n)!==i&&(Dr=t,r=rt(r)),t=r}function Pn(){var t,r,n,s,o,a,u,c;if(t=Lr,r=Lr,n=Lr,et.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(tt)),s===i&&(s=null),s!==i){for(o=[],qe.test(e.charAt(Lr))?(a=e.charAt(Lr),Lr++):(a=i,0===Hr&&zr(Ke));a!==i;)o.push(a),qe.test(e.charAt(Lr))?(a=e.charAt(Lr),Lr++):(a=i,0===Hr&&zr(Ke));if(o!==i)if(46===e.charCodeAt(Lr)?(a=h,Lr++):(a=i,0===Hr&&zr(l)),a!==i){if(u=[],qe.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Ke)),c!==i)for(;c!==i;)u.push(c),qe.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Ke));else u=i;u!==i?n=s=[s,o,a,u]:(Lr=n,n=i)}else Lr=n,n=i;else Lr=n,n=i}else Lr=n,n=i;return(r=n!==i?e.substring(r,Lr):n)!==i&&(Dr=t,r=nt(r)),t=r}function Nn(){var t,r,n,s,o,a,u,c,d;if(t=Lr,r=Lr,n=Lr,et.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(tt)),s===i&&(s=null),s!==i){if(o=Lr,a=[],qe.test(e.charAt(Lr))?(u=e.charAt(Lr),Lr++):(u=i,0===Hr&&zr(Ke)),u!==i)for(;u!==i;)a.push(u),qe.test(e.charAt(Lr))?(u=e.charAt(Lr),Lr++):(u=i,0===Hr&&zr(Ke));else a=i;if(a!==i)if(46===e.charCodeAt(Lr)?(u=h,Lr++):(u=i,0===Hr&&zr(l)),u!==i){for(c=[],qe.test(e.charAt(Lr))?(d=e.charAt(Lr),Lr++):(d=i,0===Hr&&zr(Ke));d!==i;)c.push(d),qe.test(e.charAt(Lr))?(d=e.charAt(Lr),Lr++):(d=i,0===Hr&&zr(Ke));c!==i&&(d=Un())!==i?o=a=[a,u,c,d]:(Lr=o,o=i)}else Lr=o,o=i;else Lr=o,o=i;if(o===i){if(o=Lr,46===e.charCodeAt(Lr)?(a=h,Lr++):(a=i,0===Hr&&zr(l)),a!==i){if(u=[],qe.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Ke)),c!==i)for(;c!==i;)u.push(c),qe.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Ke));else u=i;u!==i&&(c=Un())!==i?o=a=[a,u,c]:(Lr=o,o=i)}else Lr=o,o=i;if(o===i){if(o=Lr,a=[],qe.test(e.charAt(Lr))?(u=e.charAt(Lr),Lr++):(u=i,0===Hr&&zr(Ke)),u!==i)for(;u!==i;)a.push(u),qe.test(e.charAt(Lr))?(u=e.charAt(Lr),Lr++):(u=i,0===Hr&&zr(Ke));else a=i;a!==i&&(u=Un())!==i?o=a=[a,u]:(Lr=o,o=i)}}o!==i?n=s=[s,o]:(Lr=n,n=i)}else Lr=n,n=i;return(r=n!==i?e.substring(r,Lr):n)!==i&&(Dr=t,r=it(r)),t=r}function Un(){var t,r,n,s,o,a;if(t=Lr,r=Lr,st.test(e.charAt(Lr))?(n=e.charAt(Lr),Lr++):(n=i,0===Hr&&zr(ot)),n!==i)if(et.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(tt)),s===i&&(s=null),s!==i){if(o=[],qe.test(e.charAt(Lr))?(a=e.charAt(Lr),Lr++):(a=i,0===Hr&&zr(Ke)),a!==i)for(;a!==i;)o.push(a),qe.test(e.charAt(Lr))?(a=e.charAt(Lr),Lr++):(a=i,0===Hr&&zr(Ke));else o=i;o!==i?r=n=[n,s,o]:(Lr=r,r=i)}else Lr=r,r=i;else Lr=r,r=i;return t=r!==i?e.substring(t,Lr):r}function On(){var t,r,n,s;if(t=Lr,34===e.charCodeAt(Lr)?(r=at,Lr++):(r=i,0===Hr&&zr(ut)),r!==i){for(n=[],ct.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(ht)),s===i&&(s=Bn())===i&&(s=Mn());s!==i;)n.push(s),ct.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(ht)),s===i&&(s=Bn())===i&&(s=Mn());n!==i?(34===e.charCodeAt(Lr)?(s=at,Lr++):(s=i,0===Hr&&zr(ut)),s!==i?(Dr=t,t=r=w(n)):(Lr=t,t=i)):(Lr=t,t=i)}else Lr=t,t=i;return t}function Ln(){var t,r,n,s;if(t=Lr,39===e.charCodeAt(Lr)?(r=lt,Lr++):(r=i,0===Hr&&zr(dt)),r!==i){for(n=[],ft.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(pt)),s===i&&(s=Bn())===i&&(s=Mn());s!==i;)n.push(s),ft.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(pt)),s===i&&(s=Bn())===i&&(s=Mn());n!==i?(39===e.charCodeAt(Lr)?(s=lt,Lr++):(s=i,0===Hr&&zr(dt)),s!==i?(Dr=t,t=r=w(n)):(Lr=t,t=i)):(Lr=t,t=i)}else Lr=t,t=i;return t}function Dn(){var t,r,n,s,o,a,u,c;if(t=Lr,e.substr(Lr,3)===gt?(r=gt,Lr+=3):(r=i,0===Hr&&zr(yt)),r!==i){for(n=[],vt.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(mt)),s===i&&(s=Bn())===i&&(s=Mn());s!==i;)n.push(s),vt.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(mt)),s===i&&(s=Bn())===i&&(s=Mn());if(n!==i){if(s=[],o=Lr,e.substr(Lr,2)===wt?(a=wt,Lr+=2):(a=i,0===Hr&&zr(bt)),a!==i){if(u=[],vt.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(mt)),c===i&&(c=Bn())===i&&(c=Mn()),c!==i)for(;c!==i;)u.push(c),vt.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(mt)),c===i&&(c=Bn())===i&&(c=Mn());else u=i;u!==i?(Dr=o,o=a=_t(n,u)):(Lr=o,o=i)}else Lr=o,o=i;if(o===i)if(o=Lr,39===e.charCodeAt(Lr)?(a=lt,Lr++):(a=i,0===Hr&&zr(dt)),a!==i){if(u=[],vt.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(mt)),c===i&&(c=Bn())===i&&(c=Mn()),c!==i)for(;c!==i;)u.push(c),vt.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(mt)),c===i&&(c=Bn())===i&&(c=Mn());else u=i;u!==i?(Dr=o,o=a=St(n,u)):(Lr=o,o=i)}else Lr=o,o=i;for(;o!==i;){if(s.push(o),o=Lr,e.substr(Lr,2)===wt?(a=wt,Lr+=2):(a=i,0===Hr&&zr(bt)),a!==i){if(u=[],vt.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(mt)),c===i&&(c=Bn())===i&&(c=Mn()),c!==i)for(;c!==i;)u.push(c),vt.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(mt)),c===i&&(c=Bn())===i&&(c=Mn());else u=i;u!==i?(Dr=o,o=a=_t(n,u)):(Lr=o,o=i)}else Lr=o,o=i;if(o===i)if(o=Lr,39===e.charCodeAt(Lr)?(a=lt,Lr++):(a=i,0===Hr&&zr(dt)),a!==i){if(u=[],vt.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(mt)),c===i&&(c=Bn())===i&&(c=Mn()),c!==i)for(;c!==i;)u.push(c),vt.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(mt)),c===i&&(c=Bn())===i&&(c=Mn());else u=i;u!==i?(Dr=o,o=a=St(n,u)):(Lr=o,o=i)}else Lr=o,o=i}s!==i?(e.substr(Lr,3)===gt?(o=gt,Lr+=3):(o=i,0===Hr&&zr(yt)),o!==i?(Dr=t,t=r=Et(n,s)):(Lr=t,t=i)):(Lr=t,t=i)}else Lr=t,t=i}else Lr=t,t=i;return t}function jn(){var t,r,n,s,o,a,u,c;if(t=Lr,e.substr(Lr,3)===xt?(r=xt,Lr+=3):(r=i,0===Hr&&zr(At)),r!==i){for(n=[],Ft.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(Tt)),s===i&&(s=Bn())===i&&(s=Mn());s!==i;)n.push(s),Ft.test(e.charAt(Lr))?(s=e.charAt(Lr),Lr++):(s=i,0===Hr&&zr(Tt)),s===i&&(s=Bn())===i&&(s=Mn());if(n!==i){if(s=[],o=Lr,e.substr(Lr,2)===kt?(a=kt,Lr+=2):(a=i,0===Hr&&zr(It)),a!==i){if(u=[],Ft.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Tt)),c===i&&(c=Bn())===i&&(c=Mn()),c!==i)for(;c!==i;)u.push(c),Ft.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Tt)),c===i&&(c=Bn())===i&&(c=Mn());else u=i;u!==i?(Dr=o,o=a=Ct(n,u)):(Lr=o,o=i)}else Lr=o,o=i;if(o===i)if(o=Lr,34===e.charCodeAt(Lr)?(a=at,Lr++):(a=i,0===Hr&&zr(ut)),a!==i){if(u=[],Ft.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Tt)),c===i&&(c=Bn())===i&&(c=Mn()),c!==i)for(;c!==i;)u.push(c),Ft.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Tt)),c===i&&(c=Bn())===i&&(c=Mn());else u=i;u!==i?(Dr=o,o=a=Rt(n,u)):(Lr=o,o=i)}else Lr=o,o=i;for(;o!==i;){if(s.push(o),o=Lr,e.substr(Lr,2)===kt?(a=kt,Lr+=2):(a=i,0===Hr&&zr(It)),a!==i){if(u=[],Ft.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Tt)),c===i&&(c=Bn())===i&&(c=Mn()),c!==i)for(;c!==i;)u.push(c),Ft.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Tt)),c===i&&(c=Bn())===i&&(c=Mn());else u=i;u!==i?(Dr=o,o=a=Ct(n,u)):(Lr=o,o=i)}else Lr=o,o=i;if(o===i)if(o=Lr,34===e.charCodeAt(Lr)?(a=at,Lr++):(a=i,0===Hr&&zr(ut)),a!==i){if(u=[],Ft.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Tt)),c===i&&(c=Bn())===i&&(c=Mn()),c!==i)for(;c!==i;)u.push(c),Ft.test(e.charAt(Lr))?(c=e.charAt(Lr),Lr++):(c=i,0===Hr&&zr(Tt)),c===i&&(c=Bn())===i&&(c=Mn());else u=i;u!==i?(Dr=o,o=a=Rt(n,u)):(Lr=o,o=i)}else Lr=o,o=i}s!==i?(e.substr(Lr,3)===xt?(o=xt,Lr+=3):(o=i,0===Hr&&zr(At)),o!==i?(Dr=t,t=r=Et(n,s)):(Lr=t,t=i)):(Lr=t,t=i)}else Lr=t,t=i}else Lr=t,t=i;return t}function Mn(){var t,r,n,s,o,a,u,c,h,l,d;return t=Lr,e.substr(Lr,2)===Pt?(r=Pt,Lr+=2):(r=i,0===Hr&&zr(Nt)),r!==i?(n=Lr,(s=Gn())!==i&&(o=Gn())!==i&&(a=Gn())!==i&&(u=Gn())!==i&&(c=Gn())!==i&&(h=Gn())!==i&&(l=Gn())!==i&&(d=Gn())!==i?n=s=[s,o,a,u,c,h,l,d]:(Lr=n,n=i),n!==i?(Dr=t,t=r=Ut(n)):(Lr=t,t=i)):(Lr=t,t=i),t===i&&(t=Lr,e.substr(Lr,2)===Ot?(r=Ot,Lr+=2):(r=i,0===Hr&&zr(Lt)),r!==i?(n=Lr,(s=Gn())!==i&&(o=Gn())!==i&&(a=Gn())!==i&&(u=Gn())!==i?n=s=[s,o,a,u]:(Lr=n,n=i),n!==i?(Dr=t,t=r=Dt(n)):(Lr=t,t=i)):(Lr=t,t=i)),t}function Bn(){var t,r;return t=Lr,e.substr(Lr,2)===jt?(r=jt,Lr+=2):(r=i,0===Hr&&zr(Mt)),r!==i&&(Dr=t,r=Bt()),(t=r)===i&&(t=Lr,e.substr(Lr,2)===Ht?(r=Ht,Lr+=2):(r=i,0===Hr&&zr(qt)),r!==i&&(Dr=t,r=Kt()),(t=r)===i&&(t=Lr,e.substr(Lr,2)===Vt?(r=Vt,Lr+=2):(r=i,0===Hr&&zr($t)),r!==i&&(Dr=t,r=Wt()),(t=r)===i&&(t=Lr,e.substr(Lr,2)===Jt?(r=Jt,Lr+=2):(r=i,0===Hr&&zr(zt)),r!==i&&(Dr=t,r=Xt()),(t=r)===i&&(t=Lr,e.substr(Lr,2)===Gt?(r=Gt,Lr+=2):(r=i,0===Hr&&zr(Yt)),r!==i&&(Dr=t,r=Qt()),(t=r)===i&&(t=Lr,e.substr(Lr,2)===Zt?(r=Zt,Lr+=2):(r=i,0===Hr&&zr(er)),r!==i&&(Dr=t,r=tr()),(t=r)===i&&(t=Lr,e.substr(Lr,2)===rr?(r=rr,Lr+=2):(r=i,0===Hr&&zr(nr)),r!==i&&(Dr=t,r=ir()),(t=r)===i&&(t=Lr,e.substr(Lr,2)===sr?(r=sr,Lr+=2):(r=i,0===Hr&&zr(or)),r!==i&&(Dr=t,r=ar()),t=r))))))),t}function Hn(){var t;return ur.test(e.charAt(Lr))?(t=e.charAt(Lr),Lr++):(t=i,0===Hr&&zr(cr)),t}function qn(){var t,r,n,s;if(t=Lr,91===e.charCodeAt(Lr)?(r=ue,Lr++):(r=i,0===Hr&&zr(ce)),r!==i){for(n=[],s=tn();s!==i;)n.push(s),s=tn();n!==i?(93===e.charCodeAt(Lr)?(s=he,Lr++):(s=i,0===Hr&&zr(le)),s!==i?(Dr=t,t=r=hr()):(Lr=t,t=i)):(Lr=t,t=i)}else Lr=t,t=i;return t}function Kn(){var t,r,n;return t=Lr,lr.test(e.charAt(Lr))?(r=e.charAt(Lr),Lr++):(r=i,0===Hr&&zr(dr)),r!==i?(fr.test(e.charAt(Lr))?(n=e.charAt(Lr),Lr++):(n=i,0===Hr&&zr(pr)),n!==i?(Dr=t,t=r=gr(r,n)):(Lr=t,t=i)):(Lr=t,t=i),t===i&&(yr.test(e.charAt(Lr))?(t=e.charAt(Lr),Lr++):(t=i,0===Hr&&zr(vr))),t}function Vn(){var t;return(t=Kn())===i&&(95===e.charCodeAt(Lr)?(t=mr,Lr++):(t=i,0===Hr&&zr(wr))),t}function $n(){var t;return(t=Vn())===i&&(45===e.charCodeAt(Lr)?(t=ze,Lr++):(t=i,0===Hr&&zr(Xe)),t===i&&(qe.test(e.charAt(Lr))?(t=e.charAt(Lr),Lr++):(t=i,0===Hr&&zr(Ke)),t===i&&(183===e.charCodeAt(Lr)?(t=br,Lr++):(t=i,0===Hr&&zr(_r)),t===i&&(Sr.test(e.charAt(Lr))?(t=e.charAt(Lr),Lr++):(t=i,0===Hr&&zr(Er)),t===i&&(xr.test(e.charAt(Lr))?(t=e.charAt(Lr),Lr++):(t=i,0===Hr&&zr(Ar))))))),t}function Wn(){var t,r,n,s,o,a,u,c,d;if(t=Lr,r=Lr,(n=Kn())!==i){for(s=[],o=$n();o!==i;)s.push(o),o=$n();if(s!==i){if(o=[],a=Lr,u=[],46===e.charCodeAt(Lr)?(c=h,Lr++):(c=i,0===Hr&&zr(l)),c!==i)for(;c!==i;)u.push(c),46===e.charCodeAt(Lr)?(c=h,Lr++):(c=i,0===Hr&&zr(l));else u=i;if(u!==i){if(c=[],(d=$n())!==i)for(;d!==i;)c.push(d),d=$n();else c=i;c!==i?a=u=[u,c]:(Lr=a,a=i)}else Lr=a,a=i;for(;a!==i;){if(o.push(a),a=Lr,u=[],46===e.charCodeAt(Lr)?(c=h,Lr++):(c=i,0===Hr&&zr(l)),c!==i)for(;c!==i;)u.push(c),46===e.charCodeAt(Lr)?(c=h,Lr++):(c=i,0===Hr&&zr(l));else u=i;if(u!==i){if(c=[],(d=$n())!==i)for(;d!==i;)c.push(d),d=$n();else c=i;c!==i?a=u=[u,c]:(Lr=a,a=i)}else Lr=a,a=i}o!==i?r=n=[n,s,o]:(Lr=r,r=i)}else Lr=r,r=i}else Lr=r,r=i;return t=r!==i?e.substring(t,Lr):r}function Jn(){var t,r,n,s,o,a,u,c;if(t=Lr,(r=Vn())===i&&(58===e.charCodeAt(Lr)?(r=Oe,Lr++):(r=i,0===Hr&&zr(Le)),r===i&&(qe.test(e.charAt(Lr))?(r=e.charAt(Lr),Lr++):(r=i,0===Hr&&zr(Ke)),r===i&&(r=zn()))),r!==i){for(n=[],(s=$n())===i&&(58===e.charCodeAt(Lr)?(s=Oe,Lr++):(s=i,0===Hr&&zr(Le)),s===i&&(s=zn()));s!==i;)n.push(s),(s=$n())===i&&(58===e.charCodeAt(Lr)?(s=Oe,Lr++):(s=i,0===Hr&&zr(Le)),s===i&&(s=zn()));if(n!==i){if(s=[],o=Lr,a=[],46===e.charCodeAt(Lr)?(u=h,Lr++):(u=i,0===Hr&&zr(l)),u!==i)for(;u!==i;)a.push(u),46===e.charCodeAt(Lr)?(u=h,Lr++):(u=i,0===Hr&&zr(l));else a=i;if(a!==i){if(u=[],(c=$n())===i&&(58===e.charCodeAt(Lr)?(c=Oe,Lr++):(c=i,0===Hr&&zr(Le)),c===i&&(c=zn())),c!==i)for(;c!==i;)u.push(c),(c=$n())===i&&(58===e.charCodeAt(Lr)?(c=Oe,Lr++):(c=i,0===Hr&&zr(Le)),c===i&&(c=zn()));else u=i;u!==i?(Dr=o,o=a=Fr(r,n,a,u)):(Lr=o,o=i)}else Lr=o,o=i;for(;o!==i;){if(s.push(o),o=Lr,a=[],46===e.charCodeAt(Lr)?(u=h,Lr++):(u=i,0===Hr&&zr(l)),u!==i)for(;u!==i;)a.push(u),46===e.charCodeAt(Lr)?(u=h,Lr++):(u=i,0===Hr&&zr(l));else a=i;if(a!==i){if(u=[],(c=$n())===i&&(58===e.charCodeAt(Lr)?(c=Oe,Lr++):(c=i,0===Hr&&zr(Le)),c===i&&(c=zn())),c!==i)for(;c!==i;)u.push(c),(c=$n())===i&&(58===e.charCodeAt(Lr)?(c=Oe,Lr++):(c=i,0===Hr&&zr(Le)),c===i&&(c=zn()));else u=i;u!==i?(Dr=o,o=a=Fr(r,n,a,u)):(Lr=o,o=i)}else Lr=o,o=i}s!==i?(Dr=t,t=r=Tr(r,n,s)):(Lr=t,t=i)}else Lr=t,t=i}else Lr=t,t=i;return t}function zn(){var e;return(e=Xn())===i&&(e=Yn()),e}function Xn(){var t,r,n,s,o;return t=Lr,r=Lr,37===e.charCodeAt(Lr)?(n=kr,Lr++):(n=i,0===Hr&&zr(Ir)),n!==i&&(s=Gn())!==i&&(o=Gn())!==i?r=n=[n,s,o]:(Lr=r,r=i),t=r!==i?e.substring(t,Lr):r}function Gn(){var t;return Cr.test(e.charAt(Lr))?(t=e.charAt(Lr),Lr++):(t=i,0===Hr&&zr(Rr)),t}function Yn(){var t,r,n;return t=Lr,92===e.charCodeAt(Lr)?(r=Pr,Lr++):(r=i,0===Hr&&zr(Nr)),r!==i?(Ur.test(e.charAt(Lr))?(n=e.charAt(Lr),Lr++):(n=i,0===Hr&&zr(Or)),n!==i?(Dr=t,t=r=d(n)):(Lr=t,t=i)):(Lr=t,t=i),t}var Qn=function(e){return e.match(/^[a-z](.*?):(.+?)/g)};function Zn(e,t){var r={};return r[e]=t,r}var ei={base:[],data:{},addBase:function(e){if(0===ei.base.length)return void ei.base.push(e);const t=ei.base[ei.base.length-1];t!==e&&ei.base.push(new URL(e,t).toString())},addPrefix:function(e,t){const r=ei.data[e];void 0===r?ei.data[e]=[{uri:t,count:0}]:r[r.length-1].uri!==t&&r.push({uri:t,count:0})},hasPrefix:function(e){return void 0!==this.data[e]},resolve:function(e,t){const n=Object.keys(ei.data).find(t=>0===e.indexOf(t+":"));if(void 0!==n){const r=ei.data[n];if(1===r.length&&!0!==t&&Qn(r[0].uri))return e;const i=r[r.length-1].uri;return e.replace(n+":",i)}var i=0===ei.base.length?r.baseIRI:ei.base[ei.base.length-1];return!i||e.match(/^(http:|https:|urn:|file:)/)?e:0===e.indexOf("//")&&i?i.split("//")[0]+e:new URL(e,i).toString()},increment:function(e){const t=ei.data[e];void 0!==t&&t[t.length-1].count++},decrement:function(e){const t=ei.data[e];void 0!==t&&t[t.length-1].count--},toJSON:function(){const e={};return ei.base.length>0&&(void 0===e["@context"]&&(e["@context"]={}),e["@context"]["@base"]=ei.base[0]),Object.keys(ei.data).forEach(t=>{const r=ei.data[t][0];"http://www.w3.org/2001/XMLSchema#"===r.uri&&r.count<1||Qn(r.uri)&&(void 0===e["@context"]&&(e["@context"]={}),e["@context"][t]=r.uri)}),e}};function ti(e,t){if(void 0===e["@list"])return e;if(!t&&!e["@list"].find(e=>void 0!==e["@list"]))return e;if(0===e["@list"].length)return{"@id":"http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"};var r={},n=null;return e["@list"].forEach(e=>{null===n?n=r:(n["http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"]={},n=n["http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"]),n["http://www.w3.org/1999/02/22-rdf-syntax-ns#first"]=ti(e,!0),n["http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"]={"@id":"http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"}}),r}if((n=o())!==i&&Lr===e.length)return n;throw n!==i&&Lr<e.length&&zr($r()),Gr(Br,Mr<e.length?e.charAt(Mr):null,Mr<e.length?Jr(Mr,Mr+1):Jr(Mr,Mr))}return e(t,Error),t.buildMessage=function(e,t){var r={literal:function(e){return'"'+i(e.text)+'"'},class:function(e){var t,r="";for(t=0;t<e.parts.length;t++)r+=e.parts[t]instanceof Array?s(e.parts[t][0])+"-"+s(e.parts[t][1]):s(e.parts[t]);return"["+(e.inverted?"^":"")+r+"]"},any:function(e){return"any character"},end:function(e){return"end of input"},other:function(e){return e.description}};function n(e){return e.charCodeAt(0).toString(16).toUpperCase()}function i(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(e){return"\\x0"+n(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+n(e)})}function s(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(e){return"\\x0"+n(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+n(e)})}function o(e){return r[e.type](e)}function a(e){var t,r,n=new Array(e.length);for(t=0;t<e.length;t++)n[t]=o(e[t]);if(n.sort(),n.length>0){for(t=1,r=1;t<n.length;t++)n[t-1]!==n[t]&&(n[r]=n[t],r++);n.length=r}switch(n.length){case 1:return n[0];case 2:return n[0]+" or "+n[1];default:return n.slice(0,-1).join(", ")+", or "+n[n.length-1]}}function u(e){return e?'"'+i(e)+'"':"end of input"}return"Expected "+a(e)+" but "+u(t)+" found."},{SyntaxError:t,parse:r}})?r.apply(t,n):r)||(e.exports=i)},5386:e=>{const t={acl:"http://www.w3.org/ns/auth/acl#",arg:"http://www.w3.org/ns/pim/arg#",as:"https://www.w3.org/ns/activitystreams#",bookmark:"http://www.w3.org/2002/01/bookmark#",cal:"http://www.w3.org/2002/12/cal/ical#",cco:"http://www.ontologyrepository.com/CommonCoreOntologies/",cert:"http://www.w3.org/ns/auth/cert#",contact:"http://www.w3.org/2000/10/swap/pim/contact#",dc:"http://purl.org/dc/elements/1.1/",dct:"http://purl.org/dc/terms/",doap:"http://usefulinc.com/ns/doap#",foaf:"http://xmlns.com/foaf/0.1/",geo:"http://www.w3.org/2003/01/geo/wgs84_pos#",gpx:"http://www.w3.org/ns/pim/gpx#",gr:"http://purl.org/goodrelations/v1#",http:"http://www.w3.org/2007/ont/http#",httph:"http://www.w3.org/2007/ont/httph#",icalTZ:"http://www.w3.org/2002/12/cal/icaltzd#",ldp:"http://www.w3.org/ns/ldp#",link:"http://www.w3.org/2007/ont/link#",log:"http://www.w3.org/2000/10/swap/log#",meeting:"http://www.w3.org/ns/pim/meeting#",mo:"http://purl.org/ontology/mo/",org:"http://www.w3.org/ns/org#",owl:"http://www.w3.org/2002/07/owl#",pad:"http://www.w3.org/ns/pim/pad#",patch:"http://www.w3.org/ns/pim/patch#",prov:"http://www.w3.org/ns/prov#",pto:"http://www.productontology.org/id/",qu:"http://www.w3.org/2000/10/swap/pim/qif#",trip:"http://www.w3.org/ns/pim/trip#",rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",rss:"http://purl.org/rss/1.0/",sched:"http://www.w3.org/ns/pim/schedule#",schema:"http://schema.org/",sioc:"http://rdfs.org/sioc/ns#",skos:"http://www.w3.org/2004/02/skos/core#",solid:"http://www.w3.org/ns/solid/terms#",space:"http://www.w3.org/ns/pim/space#",stat:"http://www.w3.org/ns/posix/stat#",tab:"http://www.w3.org/2007/ont/link#",tabont:"http://www.w3.org/2007/ont/link#",ui:"http://www.w3.org/ns/ui#",vann:"http://purl.org/vocab/vann/",vcard:"http://www.w3.org/2006/vcard/ns#",wf:"http://www.w3.org/2005/01/wf/flow#",xsd:"http://www.w3.org/2001/XMLSchema#"};e.exports=function(e={namedNode:e=>e}){const r={};for(const n in t){const i=t[n];r[n]=function(t=""){return e.namedNode(i+t)}}return r}},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<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i={debug:function(){},info:function(){},warn:function(){},error:function(){}},s=void 0,o=void 0;(t.Log=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.reset=function(){o=3,s=i},e.debug=function(){if(o>=4){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];s.debug.apply(s,Array.from(t))}},e.info=function(){if(o>=3){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];s.info.apply(s,Array.from(t))}},e.warn=function(){if(o>=2){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];s.warn.apply(s,Array.from(t))}},e.error=function(){if(o>=1){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];s.error.apply(s,Array.from(t))}},n(e,null,[{key:"NONE",get:function(){return 0}},{key:"ERROR",get:function(){return 1}},{key:"WARN",get:function(){return 2}},{key:"INFO",get:function(){return 3}},{key:"DEBUG",get:function(){return 4}},{key:"level",get:function(){return o},set:function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");o=e}},{key:"logger",get:function(){return s},set:function(e){if(!e.debug&&e.info&&(e.debug=e.info),!(e.debug&&e.info&&e.warn&&e.error))throw new Error("Invalid logger");s=e}}]),e}()).reset()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i={setInterval:function(e){function t(t,r){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(e,t){return setInterval(e,t)}),clearInterval:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(e){return clearInterval(e)})},s=!1,o=null;t.Global=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e._testing=function(){s=!0},e.setXMLHttpRequest=function(e){o=e},n(e,null,[{key:"location",get:function(){if(!s)return location}},{key:"localStorage",get:function(){if(!s&&"undefined"!=typeof window)return localStorage}},{key:"sessionStorage",get:function(){if(!s&&"undefined"!=typeof window)return sessionStorage}},{key:"XMLHttpRequest",get:function(){if(!s&&"undefined"!=typeof window)return o||XMLHttpRequest}},{key:"timer",get:function(){if(!s)return i}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MetadataService=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),s=r(7),o=".well-known/openid-configuration";t.MetadataService=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.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(o)<0&&("/"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+="/"),this._metadataUrl+=o))),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 s=e.lastIndexOf(t);s>=0&&(e=e.substr(s+1)),"?"===t&&(s=e.indexOf("#"))>=0&&(e=e.substr(0,s));for(var o,a={},u=/([^&=]+)=([^&]*)/g,c=0;o=u.exec(e);)if(a[decodeURIComponent(o[1])]=decodeURIComponent(o[2].replace(/\+/g," ")),c++>50)return n.Log.error("UrlUtility.parseUrlFragment: response exceeded expected number of parameters",e),{error:"Response exceeded expected number of parameters"};for(var h 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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(0),o=r(23),a=r(6),u=r(24),c=r(2),h=".well-known/openid-configuration";t.OidcClientSettings=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.authority,i=t.metadataUrl,s=t.metadata,h=t.signingKeys,l=t.metadataSeed,d=t.client_id,f=t.client_secret,p=t.response_type,g=void 0===p?"id_token":p,y=t.scope,v=void 0===y?"openid":y,m=t.redirect_uri,w=t.post_logout_redirect_uri,b=t.client_authentication,_=void 0===b?"client_secret_post":b,S=t.prompt,E=t.display,x=t.max_age,A=t.ui_locales,F=t.acr_values,T=t.resource,k=t.response_mode,I=t.filterProtocolClaims,C=void 0===I||I,R=t.loadUserInfo,P=void 0===R||R,N=t.staleStateAge,U=void 0===N?900:N,O=t.clockSkew,L=void 0===O?300:O,D=t.clockService,j=void 0===D?new o.ClockService:D,M=t.userInfoJwtIssuer,B=void 0===M?"OP":M,H=t.mergeClaims,q=void 0!==H&&H,K=t.stateStore,V=void 0===K?new a.WebStorageStateStore:K,$=t.ResponseValidatorCtor,W=void 0===$?u.ResponseValidator:$,J=t.MetadataServiceCtor,z=void 0===J?c.MetadataService:J,X=t.extraQueryParams,G=void 0===X?{}:X,Y=t.extraTokenParams,Q=void 0===Y?{}:Y;(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=s,this._metadataSeed=l,this._signingKeys=h,this._client_id=d,this._client_secret=f,this._response_type=g,this._scope=v,this._redirect_uri=m,this._post_logout_redirect_uri=w,this._client_authentication=_,this._prompt=S,this._display=E,this._max_age=x,this._ui_locales=A,this._acr_values=F,this._resource=T,this._response_mode=k,this._filterProtocolClaims=!!C,this._loadUserInfo=!!P,this._staleStateAge=U,this._clockSkew=L,this._clockService=j,this._userInfoJwtIssuer=B,this._mergeClaims=!!q,this._stateStore=V,this._validator=new W(this),this._metadataService=new z(this),this._extraQueryParams="object"===(void 0===G?"undefined":n(G))?G:{},this._extraTokenParams="object"===(void 0===Q?"undefined":n(Q))?Q:{}}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 s.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 s.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(h)<0&&("/"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+="/"),this._metadataUrl+=h)),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,s=t.store,o=void 0===s?i.Global.localStorage:s;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._store=o,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;t<this._store.length;t++){var r=this._store.key(t);0===r.indexOf(this._prefix)&&e.push(r.substr(this._prefix.length))}return Promise.resolve(e)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonService=void 0;var n=r(0),i=r(1);t.JsonService=function(){function e(){var t=arguments.length>0&&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,s){var o=new r._XMLHttpRequest;o.open("GET",e);var a=r._contentTypes,u=r._jwtHandler;o.onload=function(){if(n.Log.debug("JsonService.getJson: HTTP response received, status",o.status),200===o.status){var t=o.getResponseHeader("Content-Type");if(t){var r=a.find(function(e){if(t.startsWith(e))return!0});if("application/jwt"==r)return void u(o).then(i,s);if(r)try{return void i(JSON.parse(o.responseText))}catch(e){return n.Log.error("JsonService.getJson: Error parsing JSON response",e.message),void s(e)}}s(Error("Invalid response Content-Type: "+t+", from URL: "+e))}else s(Error(o.statusText+" ("+o.status+")"))},o.onerror=function(){n.Log.error("JsonService.getJson: network error"),s(Error("Network Error"))},t&&(n.Log.debug("JsonService.getJson: token passed, setting Authorization header"),o.setRequestHeader("Authorization","Bearer "+t)),o.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(s,o){var a=new i._XMLHttpRequest;a.open("POST",e);var u=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"))&&u.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 o(new Error(t.error))}catch(e){return n.Log.error("JsonService.postForm: Error parsing JSON response",e.message),void o(e)}o(Error(a.statusText+" ("+a.status+")"))}else{var r;if((r=a.getResponseHeader("Content-Type"))&&u.find(function(e){if(r.startsWith(e))return!0}))try{return void s(JSON.parse(a.responseText))}catch(e){return n.Log.error("JsonService.postForm: Error parsing JSON response",e.message),void o(e)}o(Error("Invalid response Content-Type: "+r+", from URL: "+e))}},a.onerror=function(){n.Log.error("JsonService.postForm: network error"),o(Error("Network Error"))};var c="";for(var h in t){var l=t[h];l&&(c.length>0&&(c+="&"),c+=encodeURIComponent(h),c+="=",c+=encodeURIComponent(l))}a.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),void 0!==r&&a.setRequestHeader("Authorization","Basic "+btoa(r)),a.send(c)})},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SigninRequest=void 0;var n=r(0),i=r(3),s=r(13);t.SigninRequest=function(){function e(t){var r=t.url,o=t.client_id,a=t.redirect_uri,u=t.response_type,c=t.scope,h=t.authority,l=t.data,d=t.prompt,f=t.display,p=t.max_age,g=t.ui_locales,y=t.id_token_hint,v=t.login_hint,m=t.acr_values,w=t.resource,b=t.response_mode,_=t.request,S=t.request_uri,E=t.extraQueryParams,x=t.request_type,A=t.client_secret,F=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(!o)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 k=e.isOidc(u),I=e.isCode(u);b||(b=e.isCode(u)?"query":null),this.state=new s.SigninState({nonce:k,data:l,client_id:o,authority:h,redirect_uri:a,code_verifier:I,request_type:x,response_mode:b,client_secret:A,scope:c,extraTokenParams:F,skipUserInfo:T}),r=i.UrlUtility.addQueryParam(r,"client_id",o),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),k&&(r=i.UrlUtility.addQueryParam(r,"nonce",this.state.nonce)),I&&(r=i.UrlUtility.addQueryParam(r,"code_challenge",this.state.code_challenge),r=i.UrlUtility.addQueryParam(r,"code_challenge_method","S256"));var C={prompt:d,display:f,max_age:p,ui_locales:g,id_token_hint:y,login_hint:v,acr_values:m,resource:w,request:_,request_uri:S,response_mode:b};for(var R in C)C[R]&&(r=i.UrlUtility.addQueryParam(r,R,C[R]));for(var P in E)r=i.UrlUtility.addQueryParam(r,P,E[P]);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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),s=function(e){return e&&e.__esModule?e:{default:e}}(r(14));t.State=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.id,n=t.data,i=t.created,o=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,s.default)(),this._data=n,this._created="number"==typeof i&&i>0?i:parseInt(Date.now()/1e3),this._request_type=o}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 s=[],o=function(o){var a=r[o];u=t.get(a).then(function(r){var s=!1;if(r)try{var o=e.fromStorageString(r);i.Log.debug("State.clearStaleState: got item from key: ",a,o.created),o.created<=n&&(s=!0)}catch(e){i.Log.error("State.clearStaleState: Error parsing state for key",a,e.message),s=!0}else i.Log.debug("State.clearStaleState: no item in storage for key: ",a),s=!0;if(s)return i.Log.debug("State.clearStaleState: removed item for key: ",a),t.remove(a)}),s.push(u)},a=0;a<r.length;a++){var u;o(a)}return i.Log.debug("State.clearStaleState: waiting on promise count:",s.length),Promise.all(s)})},n(e,[{key:"id",get:function(){return this._id}},{key:"data",get:function(){return this._data}},{key:"created",get:function(){return this._created}},{key:"request_type",get:function(){return this._request_type}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OidcClient=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),s=r(5),o=r(12),a=r(8),u=r(34),c=r(35),h=r(36),l=r(13),d=r(9);t.OidcClient=function(){function e(){var t=arguments.length>0&&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 s.OidcClientSettings?this._settings=t:this._settings=new s.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,s=t.redirect_uri,o=t.data,u=t.state,c=t.prompt,h=t.display,l=t.max_age,d=t.ui_locales,f=t.id_token_hint,p=t.login_hint,g=t.acr_values,y=t.resource,v=t.request,m=t.request_uri,w=t.response_mode,b=t.extraQueryParams,_=t.extraTokenParams,S=t.request_type,E=t.skipUserInfo,x=arguments[1];i.Log.debug("OidcClient.createSigninRequest");var A=this._settings.client_id;r=r||this._settings.response_type,n=n||this._settings.scope,s=s||this._settings.redirect_uri,c=c||this._settings.prompt,h=h||this._settings.display,l=l||this._settings.max_age,d=d||this._settings.ui_locales,g=g||this._settings.acr_values,y=y||this._settings.resource,w=w||this._settings.response_mode,b=b||this._settings.extraQueryParams,_=_||this._settings.extraTokenParams;var F=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:A,redirect_uri:s,response_type:r,scope:n,data:o||u,authority:F,prompt:c,display:h,max_age:l,ui_locales:d,id_token_hint:f,login_hint:p,acr_values:g,resource:y,request:v,request_uri:m,extraQueryParams:b,extraTokenParams:_,request_type:S,response_mode:w,client_secret:e._settings.client_secret,skipUserInfo:E}),k=T.state;return(x=x||e._stateStore).set(k.id,k.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)?"?":"#",s=new u.SigninResponse(e,n);return s.state?(t=t||this._stateStore,(r?t.remove.bind(t):t.get.bind(t))(s.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:l.SigninState.fromStorageString(e),response:s}})):(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,s=t.state,o=t.post_logout_redirect_uri,a=t.extraQueryParams,u=t.request_type,h=arguments[1];return i.Log.debug("OidcClient.createSignoutRequest"),o=o||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 l=new c.SignoutRequest({url:t,id_token_hint:r,post_logout_redirect_uri:o,data:n||s,extraQueryParams:a,request_type:u}),d=l.state;return d&&(i.Log.debug("OidcClient.createSignoutRequest: Signout request has state to persist"),(h=h||e._stateStore).set(d.id,d.toStorageString())),l})},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 h.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 o.ErrorResponse(n))):Promise.resolve({state:void 0,response:n});var s=n.state;return t=t||this._stateStore,(r?t.remove.bind(t):t.get.bind(t))(s).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:d.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,d.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),s=r(0);t.TokenClient=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.JsonService,o=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 s.Log.error("TokenClient.ctor: No settings passed"),new Error("settings");this._settings=t,this._jsonService=new r,this._metadataService=new o(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 s.Log.debug("TokenClient.exchangeCode: Received token endpoint"),e._jsonService.postForm(n,t,r).then(function(e){return s.Log.debug("TokenClient.exchangeCode: response received"),e})})):(s.Log.error("TokenClient.exchangeCode: No client_secret passed"),Promise.reject(new Error("A client_secret is required"))):(s.Log.error("TokenClient.exchangeCode: No client_id passed"),Promise.reject(new Error("A client_id is required"))):(s.Log.error("TokenClient.exchangeCode: No code_verifier passed"),Promise.reject(new Error("A code_verifier is required"))):(s.Log.error("TokenClient.exchangeCode: No redirect_uri passed"),Promise.reject(new Error("A redirect_uri is required"))):(s.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 s.Log.debug("TokenClient.exchangeRefreshToken: Received token endpoint"),e._jsonService.postForm(n,t,r).then(function(e){return s.Log.debug("TokenClient.exchangeRefreshToken: response received"),e})})):(s.Log.error("TokenClient.exchangeRefreshToken: No client_id passed"),Promise.reject(new Error("A client_id is required"))):(s.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,s=r.error_description,o=r.error_uri,a=r.state,u=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 c=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,s||i));return c.name="ErrorResponse",c.error=i,c.error_description=s,c.error_uri=o,c.state=a,c.session_state=u,c}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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),s=r(9),o=r(4),a=function(e){return e&&e.__esModule?e:{default:e}}(r(14));t.SigninState=function(e){function t(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=r.nonce,i=r.authority,s=r.client_id,u=r.redirect_uri,c=r.code_verifier,h=r.response_mode,l=r.client_secret,d=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===c?g._code_verifier=(0,a.default)()+(0,a.default)()+(0,a.default)():c&&(g._code_verifier=c),g.code_verifier){var y=o.JoseUtil.hashString(g.code_verifier,"SHA256");g._code_challenge=o.JoseUtil.hexToBase64Url(y)}return g._redirect_uri=u,g._authority=i,g._client_id=s,g._response_mode=h,g._client_secret=l,g._scope=d,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}(s.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:s)().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 s(){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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0);t.User=function(){function e(t){var r=t.id_token,n=t.session_state,i=t.access_token,s=t.refresh_token,o=t.token_type,a=t.scope,u=t.profile,c=t.expires_at,h=t.state;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.id_token=r,this.session_state=n,this.access_token=i,this.refresh_token=s,this.token_type=o,this.scope=a,this.profile=u,this.expires_at=c,this.state=h}return e.prototype.toStorageString=function(){return i.Log.debug("User.toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})},e.fromStorageString=function(t){return i.Log.debug("User.fromStorageString"),new e(JSON.parse(t))},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(" ")}}]),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,s=t.accessTokenExpiringTimer,o=void 0===s?new i.Timer("Access token expiring"):s,a=t.accessTokenExpiredTimer,u=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=o,this._accessTokenExpired=u}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;e<this._callbacks.length;e++){var t;(t=this._callbacks)[e].apply(t,arguments)}},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SessionMonitor=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),s=r(19),o=r(1);t.SessionMonitor=function(){function e(t){var r=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.CheckSessionIFrame,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:o.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,s=t._checkSessionInterval,o=t._stopCheckSessionOnError;t._checkSessionIFrame=new t._CheckSessionIFrameCtor(t._callback.bind(t),n,e,s,o),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 s=!(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=s;var o=n.indexOf("/",n.indexOf("//")+2);this._frame_origin=n.substr(0,o),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),s=r(1);t.TokenRevocationClient=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.Global.XMLHttpRequest,o=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 o(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(s){if(s){n.Log.debug("TokenRevocationClient.revoke: Revoking "+i);var o=r._settings.client_id,a=r._settings.client_secret;return r._revoke(s,o,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,s){var o=this;return new Promise(function(a,u){var c=new o._XMLHttpRequestCtor;c.open("POST",e),c.onload=function(){n.Log.debug("TokenRevocationClient.revoke: HTTP response received, status",c.status),200===c.status?a():u(Error(c.statusText+" ("+c.status+")"))},c.onerror=function(){n.Log.debug("TokenRevocationClient.revoke: Network Error."),u("Network Error")};var h="client_id="+encodeURIComponent(t);r&&(h+="&client_secret="+encodeURIComponent(r)),h+="&token_type_hint="+encodeURIComponent(s),h+="&token="+encodeURIComponent(i),c.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),c.send(h)})},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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0);t.CordovaPopupWindow=function(){function e(t){var r=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._promise=new Promise(function(e,t){r._resolve=e,r._reject=t}),this.features=t.popupWindowFeatures||"location=no,toolbar=no,zoom=no",this.target=t.popupWindowTarget||"_blank",this.redirect_uri=t.startUrl,i.Log.debug("CordovaPopupWindow.ctor: redirect_uri: "+this.redirect_uri)}return e.prototype._isInAppBrowserInstalled=function(e){return["cordova-plugin-inappbrowser","cordova-plugin-inappbrowser.inappbrowser","org.apache.cordova.inappbrowser"].some(function(t){return e.hasOwnProperty(t)})},e.prototype.navigate=function(e){if(e&&e.url){if(!window.cordova)return this._error("cordova is undefined");var t=window.cordova.require("cordova/plugin_list").metadata;if(!1===this._isInAppBrowserInstalled(t))return this._error("InAppBrowser plugin not found");this._popup=cordova.InAppBrowser.open(e.url,this.target,this.features),this._popup?(i.Log.debug("CordovaPopupWindow.navigate: popup successfully created"),this._exitCallbackEvent=this._exitCallback.bind(this),this._loadStartCallbackEvent=this._loadStartCallback.bind(this),this._popup.addEventListener("exit",this._exitCallbackEvent,!1),this._popup.addEventListener("loadstart",this._loadStartCallbackEvent,!1)):this._error("Error opening popup window")}else this._error("No url provided");return this.promise},e.prototype._loadStartCallback=function(e){0===e.url.indexOf(this.redirect_uri)&&this._success({url:e.url})},e.prototype._exitCallback=function(e){this._error(e)},e.prototype._success=function(e){this._cleanup(),i.Log.debug("CordovaPopupWindow: Successful response from cordova popup window"),this._resolve(e)},e.prototype._error=function(e){this._cleanup(),i.Log.error(e),this._reject(new Error(e))},e.prototype.close=function(){this._cleanup()},e.prototype._cleanup=function(){this._popup&&(i.Log.debug("CordovaPopupWindow: cleaning up popup"),this._popup.removeEventListener("exit",this._exitCallbackEvent,!1),this._popup.removeEventListener("loadstart",this._loadStartCallbackEvent,!1),this._popup.close()),this._popup=null},n(e,[{key:"promise",get:function(){return this._promise}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(10),s=r(5),o=r(6),a=r(37),u=r(38),c=r(16),h=r(2),l=r(48),d=r(49),f=r(19),p=r(20),g=r(18),y=r(1),v=r(15),m=r(50);t.default={Version:m.Version,Log:n.Log,OidcClient:i.OidcClient,OidcClientSettings:s.OidcClientSettings,WebStorageStateStore:o.WebStorageStateStore,InMemoryWebStorage:a.InMemoryWebStorage,UserManager:u.UserManager,AccessTokenEvents:c.AccessTokenEvents,MetadataService:h.MetadataService,CordovaPopupNavigator:l.CordovaPopupNavigator,CordovaIFrameNavigator:d.CordovaIFrameNavigator,CheckSessionIFrame:f.CheckSessionIFrame,TokenRevocationClient:p.TokenRevocationClient,SessionMonitor:g.SessionMonitor,Global:y.Global,User:v.User},e.exports=t.default},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ClockService=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.prototype.getEpochTime=function(){return Promise.resolve(Date.now()/1e3|0)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ResponseValidator=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=r(0),s=r(2),o=r(25),a=r(11),u=r(12),c=r(4),h=["nonce","at_hash","iat","nbf","exp","aud","iss","c_hash"];t.ResponseValidator=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.MetadataService,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:o.UserInfoService,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:c.JoseUtil,h=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=u,this._tokenClient=new h(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 u.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 u.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 s=t[i];Array.isArray(s)||(s=[s]);for(var o=0;o<s.length;o++){var a=s[o];r[i]?Array.isArray(r[i])?r[i].indexOf(a)<0&&r[i].push(a):r[i]!==a&&("object"===(void 0===a?"undefined":n(a))&&this._settings.mergeClaims?r[i]=this._mergeClaims(r[i],a):r[i]=[r[i],a]):r[i]=a}}return r},e.prototype._filterProtocolClaims=function(e){i.Log.debug("ResponseValidator._filterProtocolClaims, incoming claims:",e);var t=Object.assign({},e);return this._settings._filterProtocolClaims?(h.forEach(function(e){delete t[e]}),i.Log.debug("ResponseValidator._filterProtocolClaims: protocol claims filtered",t)):i.Log.debug("ResponseValidator._filterProtocolClaims: protocol claims not filtered"),t},e.prototype._validateTokens=function(e,t){return t.code?(i.Log.debug("ResponseValidator._validateTokens: Validating code"),this._processCode(e,t)):t.id_token?t.access_token?(i.Log.debug("ResponseValidator._validateTokens: Validating id_token and access_token"),this._validateIdTokenAndAccessToken(e,t)):(i.Log.debug("ResponseValidator._validateTokens: Validating id_token"),this._validateIdToken(e,t)):(i.Log.debug("ResponseValidator._validateTokens: No code to process or id_token to validate"),Promise.resolve(t))},e.prototype._processCode=function(e,t){var r=this,s={client_id:e.client_id,client_secret:e.client_secret,code:t.code,redirect_uri:e.redirect_uri,code_verifier:e.code_verifier};return e.extraTokenParams&&"object"===n(e.extraTokenParams)&&Object.assign(s,e.extraTokenParams),this._tokenClient.exchangeCode(s).then(function(n){for(var s in n)t[s]=n[s];return t.id_token?(i.Log.debug("ResponseValidator._processCode: token response successful, processing id_token"),r._validateIdTokenAttributes(e,t)):(i.Log.debug("ResponseValidator._processCode: token response successful, returning response"),t)})},e.prototype._validateIdTokenAttributes=function(e,t){var r=this;return this._metadataService.getIssuer().then(function(n){var s=e.client_id,o=r._settings.clockSkew;return i.Log.debug("ResponseValidator._validateIdTokenAttributes: Validaing JWT attributes; using clock skew (in seconds) of: ",o),r._settings.getEpochTime().then(function(a){return r._joseUtil.validateJwtAttributes(t.id_token,n,s,o,a).then(function(r){return e.nonce&&e.nonce!==r.nonce?(i.Log.error("ResponseValidator._validateIdTokenAttributes: Invalid nonce in id_token"),Promise.reject(new Error("Invalid nonce in id_token"))):r.sub?(t.profile=r,t):(i.Log.error("ResponseValidator._validateIdTokenAttributes: No sub present in id_token"),Promise.reject(new Error("No sub present in id_token")))})})})},e.prototype._validateIdTokenAndAccessToken=function(e,t){var r=this;return this._validateIdToken(e,t).then(function(e){return r._validateAccessToken(e)})},e.prototype._getSigningKeyForJwt=function(e){var t=this;return this._metadataService.getSigningKeys().then(function(r){var n=e.header.kid;if(!r)return i.Log.error("ResponseValidator._validateIdToken: No signing keys from metadata"),Promise.reject(new Error("No signing keys from metadata"));i.Log.debug("ResponseValidator._validateIdToken: Received signing keys");var s=void 0;if(n)s=r.filter(function(e){return e.kid===n})[0];else{if((r=t._filterByAlg(r,e.header.alg)).length>1)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"));s=r[0]}return Promise.resolve(s)})},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(s){return i.Log.debug("ResponseValidator._validateIdToken: Received issuer"),r._getSigningKeyForJwtWithSingleRetry(n).then(function(o){if(!o)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=r._settings.clockSkew;return i.Log.debug("ResponseValidator._validateIdToken: Validaing JWT; using clock skew (in seconds) of: ",u),r._joseUtil.validateJwt(t.id_token,o,s,a,u).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 s="sha"+n,o=this._joseUtil.hashString(e.access_token,s);if(!o)return i.Log.error("ResponseValidator._validateAccessToken: access_token hash failed:",s),Promise.reject(new Error("Failed to validate at_hash"));var a=o.substr(0,o.length/2),u=this._joseUtil.hexToBase64Url(a);return u!==e.profile.at_hash?(i.Log.error("ResponseValidator._validateAccessToken: Failed to validate at_hash",u,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),s=r(0),o=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,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:o.JoseUtil;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw s.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=u}return e.prototype.getClaims=function(e){var t=this;return e?this._metadataService.getUserInfoEndpoint().then(function(r){return s.Log.debug("UserInfoService.getClaims: received userinfo url",r),t._jsonService.getJson(r,e).then(function(e){return s.Log.debug("UserInfoService.getClaims: claims received",e),e})}):(s.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 s.Log.error("UserInfoService._getClaimsFromJwt: Failed to parse JWT",n),Promise.reject(new Error("Failed to parse id_token"));var i=n.header.kid,o=void 0;switch(this._settings.userInfoJwtIssuer){case"OP":o=this._metadataService.getIssuer();break;case"ANY":o=Promise.resolve(n.payload.iss);break;default:o=Promise.resolve(this._settings.userInfoJwtIssuer)}return o.then(function(e){return s.Log.debug("UserInfoService._getClaimsFromJwt: Received issuer:"+e),r._metadataService.getSigningKeys().then(function(o){if(!o)return s.Log.error("UserInfoService._getClaimsFromJwt: No signing keys from metadata"),Promise.reject(new Error("No signing keys from metadata"));s.Log.debug("UserInfoService._getClaimsFromJwt: Received signing keys");var a=void 0;if(i)a=o.filter(function(e){return e.kid===i})[0];else{if((o=r._filterByAlg(o,n.header.alg)).length>1)return s.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=o[0]}if(!a)return s.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 s.Log.debug("UserInfoService._getClaimsFromJwt: Validaing JWT; using clock skew (in seconds) of: ",c),r._joseUtil.validateJwt(t.responseText,a,e,u,c,void 0,!0).then(function(){return s.Log.debug("UserInfoService._getClaimsFromJwt: JWT validation successful"),n.payload})})})}catch(e){return s.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 s.Log.debug("UserInfoService._filterByAlg: alg not supported: ",t),[];r="EC"}return s.Log.debug("UserInfoService._filterByAlg: Looking for keys that match kty: ",r),e=e.filter(function(e){return e.kty===r}),s.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,s,o,a,u,c,h,l,d,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={},s=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)}}}(),o=i.WordArray=s.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||u).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 s=0;s<i;s++){var o=r[s>>>2]>>>24-s%4*8&255;t[n+s>>>2]|=o<<24-(n+s)%4*8}else for(s=0;s<i;s+=4)t[n+s>>>2]=r[s>>>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=s.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],n=0;n<e;n+=4)t.push(4294967296*r.random()|0);return new o.init(t,e)}}),a=n.enc={},u=a.Hex={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i<r;i++){var s=t[i>>>2]>>>24-i%4*8&255;n.push((s>>>4).toString(16)),n.push((15&s).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n<t;n+=2)r[n>>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new o.init(r,t/2)}},c=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i<r;i++){var s=t[i>>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(s))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n<t;n++)r[n>>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new o.init(r,t)}},h=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},l=i.BufferedBlockAlgorithm=s.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=h.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(e){var t=this._data,n=t.words,i=t.sigBytes,s=this.blockSize,a=i/(4*s),u=(a=e?r.ceil(a):r.max((0|a)-this._minBufferSize,0))*s,c=r.min(4*u,i);if(u){for(var h=0;h<u;h+=s)this._doProcessBlock(n,h);var l=n.splice(0,u);t.sigBytes-=c}return new o.init(l,c)},clone:function(){var e=s.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0}),i.Hasher=l.extend({cfg:s.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){l.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,r){return new e.init(r).finalize(t)}},_createHmacHelper:function(e){return function(t,r){return new d.HMAC.init(e,r).finalize(t)}}}),d=n.algo={},n);!function(){var e,t=(e=y).lib,r=t.Base,n=t.WordArray;(e=e.x64={}).Word=r.extend({init:function(e,t){this.high=e,this.low=t}}),e.WordArray=r.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:8*e.length},toX32:function(){for(var e=this.words,t=e.length,r=[],i=0;i<t;i++){var s=e[i];r.push(s.high),r.push(s.low)}return n.create(r,this.sigBytes)},clone:function(){for(var e=r.clone.call(this),t=e.words=this.words.slice(0),n=t.length,i=0;i<n;i++)t[i]=t[i].clone();return e}})}(),function(){var e=y,t=e.lib.WordArray;e.enc.Base64={stringify:function(e){var t=e.words,r=e.sigBytes,n=this._map;e.clamp(),e=[];for(var i=0;i<r;i+=3)for(var s=(t[i>>>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,o=0;4>o&&i+.75*o<r;o++)e.push(n.charAt(s>>>6*(3-o)&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=[],s=0,o=0;o<r;o++)if(o%4){var a=n.indexOf(e.charAt(o-1))<<o%4*2,u=n.indexOf(e.charAt(o))>>>6-o%4*2;i[s>>>2]|=(a|u)<<24-s%4*8,s++}return t.create(i,s)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),function(e){for(var t=y,r=(i=t.lib).WordArray,n=i.Hasher,i=t.algo,s=[],o=[],a=function(e){return 4294967296*(e-(0|e))|0},u=2,c=0;64>c;){var h;e:{h=u;for(var l=e.sqrt(h),d=2;d<=l;d++)if(!(h%d)){h=!1;break e}h=!0}h&&(8>c&&(s[c]=a(e.pow(u,.5))),o[c]=a(e.pow(u,1/3)),c++),u++}var f=[];i=i.SHA256=n.extend({_doReset:function(){this._hash=new r.init(s.slice(0))},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],i=r[1],s=r[2],a=r[3],u=r[4],c=r[5],h=r[6],l=r[7],d=0;64>d;d++){if(16>d)f[d]=0|e[t+d];else{var p=f[d-15],g=f[d-2];f[d]=((p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3)+f[d-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+f[d-16]}p=l+((u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25))+(u&c^~u&h)+o[d]+f[d],g=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&i^n&s^i&s),l=h,h=c,c=u,u=a+p|0,a=s,s=i,i=n,n=p+g|0}r[0]=r[0]+n|0,r[1]=r[1]+i|0,r[2]=r[2]+s|0,r[3]=r[3]+a|0,r[4]=r[4]+u|0,r[5]=r[5]+c|0,r[6]=r[6]+h|0,r[7]=r[7]+l|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=(s=t.x64).Word,i=s.WordArray,s=t.algo,o=[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=[],u=0;80>u;u++)a[u]=e();s=s.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=(l=this._hash.words)[0],n=l[1],i=l[2],s=l[3],u=l[4],c=l[5],h=l[6],l=l[7],d=r.high,f=r.low,p=n.high,g=n.low,y=i.high,v=i.low,m=s.high,w=s.low,b=u.high,_=u.low,S=c.high,E=c.low,x=h.high,A=h.low,F=l.high,T=l.low,k=d,I=f,C=p,R=g,P=y,N=v,U=m,O=w,L=b,D=_,j=S,M=E,B=x,H=A,q=F,K=T,V=0;80>V;V++){var $=a[V];if(16>V)var W=$.high=0|e[t+2*V],J=$.low=0|e[t+2*V+1];else{W=((J=(W=a[V-15]).high)>>>1|(z=W.low)<<31)^(J>>>8|z<<24)^J>>>7;var z=(z>>>1|J<<31)^(z>>>8|J<<24)^(z>>>7|J<<25),X=((J=(X=a[V-2]).high)>>>19|(G=X.low)<<13)^(J<<3|G>>>29)^J>>>6,G=(G>>>19|J<<13)^(G<<3|J>>>29)^(G>>>6|J<<26),Y=(J=a[V-7]).high,Q=(Z=a[V-16]).high,Z=Z.low;W=(W=(W=W+Y+((J=z+J.low)>>>0<z>>>0?1:0))+X+((J+=G)>>>0<G>>>0?1:0))+Q+((J+=Z)>>>0<Z>>>0?1:0),$.high=W,$.low=J}Y=L&j^~L&B,Z=D&M^~D&H,$=k&C^k&P^C&P;var ee=I&R^I&N^R&N,te=(z=(k>>>28|I<<4)^(k<<30|I>>>2)^(k<<25|I>>>7),X=(I>>>28|k<<4)^(I<<30|k>>>2)^(I<<25|k>>>7),(G=o[V]).high),re=G.low;Q=q+((L>>>14|D<<18)^(L>>>18|D<<14)^(L<<23|D>>>9))+((G=K+((D>>>14|L<<18)^(D>>>18|L<<14)^(D<<23|L>>>9)))>>>0<K>>>0?1:0),q=B,K=H,B=j,H=M,j=L,M=D,L=U+(Q=(Q=(Q=Q+Y+((G+=Z)>>>0<Z>>>0?1:0))+te+((G+=re)>>>0<re>>>0?1:0))+W+((G+=J)>>>0<J>>>0?1:0))+((D=O+G|0)>>>0<O>>>0?1:0)|0,U=P,O=N,P=C,N=R,C=k,R=I,k=Q+($=z+$+((J=X+ee)>>>0<X>>>0?1:0))+((I=G+J|0)>>>0<G>>>0?1:0)|0}f=r.low=f+I,r.high=d+k+(f>>>0<I>>>0?1:0),g=n.low=g+R,n.high=p+C+(g>>>0<R>>>0?1:0),v=i.low=v+N,i.high=y+P+(v>>>0<N>>>0?1:0),w=s.low=w+O,s.high=m+U+(w>>>0<O>>>0?1:0),_=u.low=_+D,u.high=b+L+(_>>>0<D>>>0?1:0),E=c.low=E+M,c.high=S+j+(E>>>0<M>>>0?1:0),A=h.low=A+H,h.high=x+B+(A>>>0<H>>>0?1:0),T=l.low=T+K,l.high=F+q+(T>>>0<K>>>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(s),t.HmacSHA512=r._createHmacHelper(s)}(),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)}();
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("$rdf")):"function"==typeof define&&define.amd?define("SolidLogic",["$rdf"],t):"object"==typeof exports?exports.SolidLogic=t(require("$rdf")):e.SolidLogic=t(e.$rdf)}(this,e=>(()=>{var t={7: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,r){"function"==typeof e.on&&g(e,"error",t,r)}(e,i,{once:!0})})},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 u(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function c(e,t,r,n){var i,o,s,c;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=u(e))>0&&s.length>i&&!s.warned){s.warned=!0;var h=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");h.name="MaxListenersExceededWarning",h.emitter=e,h.type=t,h.count=s.length,c=h,console&&console.warn&&console.warn(c)}return e}function h(){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 l(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=h.bind(n);return i.listener=r,n.wrapFn=i,i}function d(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;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(i):p(i,i.length)}function f(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function p(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function g(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(o){n.once&&e.removeEventListener(t,i),r(o)})}}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");s=e}}),o.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return u(this)},o.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var u=o[e];if(void 0===u)return!1;if("function"==typeof u)n(u,this,t);else{var c=u.length,h=p(u,c);for(r=0;r<c;++r)n(h[r],this,t)}return!0},o.prototype.addListener=function(e,t){return c(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return c(this,e,t,!0)},o.prototype.once=function(e,t){return a(t),this.on(e,l(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,l(this,e,t)),this},o.prototype.removeListener=function(e,t){var r,n,i,o,s;if(a(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,o=r.length-1;o>=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<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,s||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,o=Object.keys(r);for(n=0;n<o.length;++n)"removeListener"!==(i=o[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},o.prototype.listeners=function(e){return d(this,e,!0)},o.prototype.rawListeners=function(e){return d(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):[]}},264:t=>{"use strict";t.exports=e},386:e=>{const t={acl:"http://www.w3.org/ns/auth/acl#",arg:"http://www.w3.org/ns/pim/arg#",as:"https://www.w3.org/ns/activitystreams#",bookmark:"http://www.w3.org/2002/01/bookmark#",cal:"http://www.w3.org/2002/12/cal/ical#",cco:"http://www.ontologyrepository.com/CommonCoreOntologies/",cert:"http://www.w3.org/ns/auth/cert#",contact:"http://www.w3.org/2000/10/swap/pim/contact#",dc:"http://purl.org/dc/elements/1.1/",dct:"http://purl.org/dc/terms/",doap:"http://usefulinc.com/ns/doap#",foaf:"http://xmlns.com/foaf/0.1/",geo:"http://www.w3.org/2003/01/geo/wgs84_pos#",gpx:"http://www.w3.org/ns/pim/gpx#",gr:"http://purl.org/goodrelations/v1#",http:"http://www.w3.org/2007/ont/http#",httph:"http://www.w3.org/2007/ont/httph#",icalTZ:"http://www.w3.org/2002/12/cal/icaltzd#",ldp:"http://www.w3.org/ns/ldp#",link:"http://www.w3.org/2007/ont/link#",log:"http://www.w3.org/2000/10/swap/log#",meeting:"http://www.w3.org/ns/pim/meeting#",mo:"http://purl.org/ontology/mo/",org:"http://www.w3.org/ns/org#",owl:"http://www.w3.org/2002/07/owl#",pad:"http://www.w3.org/ns/pim/pad#",patch:"http://www.w3.org/ns/pim/patch#",prov:"http://www.w3.org/ns/prov#",pto:"http://www.productontology.org/id/",qu:"http://www.w3.org/2000/10/swap/pim/qif#",trip:"http://www.w3.org/ns/pim/trip#",rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",rss:"http://purl.org/rss/1.0/",sched:"http://www.w3.org/ns/pim/schedule#",schema:"http://schema.org/",sioc:"http://rdfs.org/sioc/ns#",skos:"http://www.w3.org/2004/02/skos/core#",solid:"http://www.w3.org/ns/solid/terms#",space:"http://www.w3.org/ns/pim/space#",stat:"http://www.w3.org/ns/posix/stat#",tab:"http://www.w3.org/2007/ont/link#",tabont:"http://www.w3.org/2007/ont/link#",ui:"http://www.w3.org/ns/ui#",vann:"http://purl.org/vocab/vann/",vcard:"http://www.w3.org/2006/vcard/ns#",wf:"http://www.w3.org/2005/01/wf/flow#",xsd:"http://www.w3.org/2001/XMLSchema#"};e.exports=function(e={namedNode:e=>e}){const r={};for(const n in t){const i=t[n];r[n]=function(t=""){return e.namedNode(i+t)}}return r}},516: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<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i={debug:function(){},info:function(){},warn:function(){},error:function(){}},o=void 0,s=void 0;(t.Log=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.reset=function(){s=3,o=i},e.debug=function(){if(s>=4){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];o.debug.apply(o,Array.from(t))}},e.info=function(){if(s>=3){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];o.info.apply(o,Array.from(t))}},e.warn=function(){if(s>=2){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];o.warn.apply(o,Array.from(t))}},e.error=function(){if(s>=1){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];o.error.apply(o,Array.from(t))}},n(e,null,[{key:"NONE",get:function(){return 0}},{key:"ERROR",get:function(){return 1}},{key:"WARN",get:function(){return 2}},{key:"INFO",get:function(){return 3}},{key:"DEBUG",get:function(){return 4}},{key:"level",get:function(){return s},set:function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");s=e}},{key:"logger",get:function(){return o},set:function(e){if(!e.debug&&e.info&&(e.debug=e.info),!(e.debug&&e.info&&e.warn&&e.error))throw new Error("Invalid logger");o=e}}]),e}()).reset()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i={setInterval:function(e){function t(t,r){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(e,t){return setInterval(e,t)}),clearInterval:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(e){return clearInterval(e)})},o=!1,s=null;t.Global=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e._testing=function(){o=!0},e.setXMLHttpRequest=function(e){s=e},n(e,null,[{key:"location",get:function(){if(!o)return location}},{key:"localStorage",get:function(){if(!o&&"undefined"!=typeof window)return localStorage}},{key:"sessionStorage",get:function(){if(!o&&"undefined"!=typeof window)return sessionStorage}},{key:"XMLHttpRequest",get:function(){if(!o&&"undefined"!=typeof window)return s||XMLHttpRequest}},{key:"timer",get:function(){if(!o)return i}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MetadataService=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),o=r(7),s=".well-known/openid-configuration";t.MetadataService=function(){function e(t){var r=arguments.length>1&&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={},u=/([^&=]+)=([^&]*)/g,c=0;s=u.exec(e);)if(a[decodeURIComponent(s[1])]=decodeURIComponent(s[2].replace(/\+/g," ")),c++>50)return n.Log.error("UrlUtility.parseUrlFragment: response exceeded expected number of parameters",e),{error:"Response exceeded expected number of parameters"};for(var h 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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),o=r(0),s=r(23),a=r(6),u=r(24),c=r(2),h=".well-known/openid-configuration";t.OidcClientSettings=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.authority,i=t.metadataUrl,o=t.metadata,h=t.signingKeys,l=t.metadataSeed,d=t.client_id,f=t.client_secret,p=t.response_type,g=void 0===p?"id_token":p,y=t.scope,v=void 0===y?"openid":y,m=t.redirect_uri,w=t.post_logout_redirect_uri,_=t.client_authentication,S=void 0===_?"client_secret_post":_,b=t.prompt,E=t.display,F=t.max_age,x=t.ui_locales,A=t.acr_values,k=t.resource,P=t.response_mode,T=t.filterProtocolClaims,I=void 0===T||T,C=t.loadUserInfo,R=void 0===C||C,U=t.staleStateAge,L=void 0===U?900:U,D=t.clockSkew,N=void 0===D?300:D,O=t.clockService,H=void 0===O?new s.ClockService:O,j=t.userInfoJwtIssuer,M=void 0===j?"OP":j,B=t.mergeClaims,K=void 0!==B&&B,V=t.stateStore,q=void 0===V?new a.WebStorageStateStore:V,J=t.ResponseValidatorCtor,W=void 0===J?u.ResponseValidator:J,$=t.MetadataServiceCtor,z=void 0===$?c.MetadataService:$,Y=t.extraQueryParams,G=void 0===Y?{}:Y,X=t.extraTokenParams,Q=void 0===X?{}:X;(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=l,this._signingKeys=h,this._client_id=d,this._client_secret=f,this._response_type=g,this._scope=v,this._redirect_uri=m,this._post_logout_redirect_uri=w,this._client_authentication=S,this._prompt=b,this._display=E,this._max_age=F,this._ui_locales=x,this._acr_values=A,this._resource=k,this._response_mode=P,this._filterProtocolClaims=!!I,this._loadUserInfo=!!R,this._staleStateAge=L,this._clockSkew=N,this._clockService=H,this._userInfoJwtIssuer=M,this._mergeClaims=!!K,this._stateStore=q,this._validator=new W(this),this._metadataService=new z(this),this._extraQueryParams="object"===(void 0===G?"undefined":n(G))?G:{},this._extraTokenParams="object"===(void 0===Q?"undefined":n(Q))?Q:{}}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(h)<0&&("/"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+="/"),this._metadataUrl+=h)),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;t<this._store.length;t++){var r=this._store.key(t);0===r.indexOf(this._prefix)&&e.push(r.substr(this._prefix.length))}return Promise.resolve(e)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonService=void 0;var n=r(0),i=r(1);t.JsonService=function(){function e(){var t=arguments.length>0&&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,u=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 u(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 u=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"))&&u.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"))&&u.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 c="";for(var h in t){var l=t[h];l&&(c.length>0&&(c+="&"),c+=encodeURIComponent(h),c+="=",c+=encodeURIComponent(l))}a.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),void 0!==r&&a.setRequestHeader("Authorization","Basic "+btoa(r)),a.send(c)})},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,u=t.response_type,c=t.scope,h=t.authority,l=t.data,d=t.prompt,f=t.display,p=t.max_age,g=t.ui_locales,y=t.id_token_hint,v=t.login_hint,m=t.acr_values,w=t.resource,_=t.response_mode,S=t.request,b=t.request_uri,E=t.extraQueryParams,F=t.request_type,x=t.client_secret,A=t.extraTokenParams,k=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(!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 P=e.isOidc(u),T=e.isCode(u);_||(_=e.isCode(u)?"query":null),this.state=new o.SigninState({nonce:P,data:l,client_id:s,authority:h,redirect_uri:a,code_verifier:T,request_type:F,response_mode:_,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),P&&(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 I={prompt:d,display:f,max_age:p,ui_locales:g,id_token_hint:y,login_hint:v,acr_values:m,resource:w,request:S,request_uri:b,response_mode:_};for(var C in I)I[C]&&(r=i.UrlUtility.addQueryParam(r,C,I[C]));for(var R in E)r=i.UrlUtility.addQueryParam(r,R,E[R]);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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),o=function(e){return e&&e.__esModule?e:{default:e}}(r(14));t.State=function(){function e(){var t=arguments.length>0&&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];u=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(u)},a=0;a<r.length;a++){var u;s(a)}return i.Log.debug("State.clearStaleState: waiting on promise count:",o.length),Promise.all(o)})},n(e,[{key:"id",get:function(){return this._id}},{key:"data",get:function(){return this._data}},{key:"created",get:function(){return this._created}},{key:"request_type",get:function(){return this._request_type}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OidcClient=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),o=r(5),s=r(12),a=r(8),u=r(34),c=r(35),h=r(36),l=r(13),d=r(9);t.OidcClient=function(){function e(){var t=arguments.length>0&&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,u=t.state,c=t.prompt,h=t.display,l=t.max_age,d=t.ui_locales,f=t.id_token_hint,p=t.login_hint,g=t.acr_values,y=t.resource,v=t.request,m=t.request_uri,w=t.response_mode,_=t.extraQueryParams,S=t.extraTokenParams,b=t.request_type,E=t.skipUserInfo,F=arguments[1];i.Log.debug("OidcClient.createSigninRequest");var x=this._settings.client_id;r=r||this._settings.response_type,n=n||this._settings.scope,o=o||this._settings.redirect_uri,c=c||this._settings.prompt,h=h||this._settings.display,l=l||this._settings.max_age,d=d||this._settings.ui_locales,g=g||this._settings.acr_values,y=y||this._settings.resource,w=w||this._settings.response_mode,_=_||this._settings.extraQueryParams,S=S||this._settings.extraTokenParams;var A=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 k=new a.SigninRequest({url:t,client_id:x,redirect_uri:o,response_type:r,scope:n,data:s||u,authority:A,prompt:c,display:h,max_age:l,ui_locales:d,id_token_hint:f,login_hint:p,acr_values:g,resource:y,request:v,request_uri:m,extraQueryParams:_,extraTokenParams:S,request_type:b,response_mode:w,client_secret:e._settings.client_secret,skipUserInfo:E}),P=k.state;return(F=F||e._stateStore).set(P.id,P.toStorageString()).then(function(){return k})})},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 u.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:l.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,u=t.request_type,h=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 l=new c.SignoutRequest({url:t,id_token_hint:r,post_logout_redirect_uri:s,data:n||o,extraQueryParams:a,request_type:u}),d=l.state;return d&&(i.Log.debug("OidcClient.createSignoutRequest: Signout request has state to persist"),(h=h||e._stateStore).set(d.id,d.toStorageString())),l})},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 h.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:d.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,d.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,u=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 c=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 c.name="ErrorResponse",c.error=i,c.error_description=o,c.error_uri=s,c.state=a,c.session_state=u,c}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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),o=r(9),s=r(4),a=function(e){return e&&e.__esModule?e:{default:e}}(r(14));t.SigninState=function(e){function t(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=r.nonce,i=r.authority,o=r.client_id,u=r.redirect_uri,c=r.code_verifier,h=r.response_mode,l=r.client_secret,d=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===c?g._code_verifier=(0,a.default)()+(0,a.default)()+(0,a.default)():c&&(g._code_verifier=c),g.code_verifier){var y=s.JoseUtil.hashString(g.code_verifier,"SHA256");g._code_challenge=s.JoseUtil.hexToBase64Url(y)}return g._redirect_uri=u,g._authority=i,g._client_id=o,g._response_mode=h,g._client_secret=l,g._scope=d,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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0);t.User=function(){function e(t){var r=t.id_token,n=t.session_state,i=t.access_token,o=t.refresh_token,s=t.token_type,a=t.scope,u=t.profile,c=t.expires_at,h=t.state;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.id_token=r,this.session_state=n,this.access_token=i,this.refresh_token=o,this.token_type=s,this.scope=a,this.profile=u,this.expires_at=c,this.state=h}return e.prototype.toStorageString=function(){return i.Log.debug("User.toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})},e.fromStorageString=function(t){return i.Log.debug("User.fromStorageString"),new e(JSON.parse(t))},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(" ")}}]),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,u=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=u}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;e<this._callbacks.length;e++){var t;(t=this._callbacks)[e].apply(t,arguments)}},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SessionMonitor=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),o=r(19),s=r(1);t.SessionMonitor=function(){function e(t){var r=this,n=arguments.length>1&&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,u){var c=new s._XMLHttpRequestCtor;c.open("POST",e),c.onload=function(){n.Log.debug("TokenRevocationClient.revoke: HTTP response received, status",c.status),200===c.status?a():u(Error(c.statusText+" ("+c.status+")"))},c.onerror=function(){n.Log.debug("TokenRevocationClient.revoke: Network Error."),u("Network Error")};var h="client_id="+encodeURIComponent(t);r&&(h+="&client_secret="+encodeURIComponent(r)),h+="&token_type_hint="+encodeURIComponent(o),h+="&token="+encodeURIComponent(i),c.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),c.send(h)})},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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0);t.CordovaPopupWindow=function(){function e(t){var r=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._promise=new Promise(function(e,t){r._resolve=e,r._reject=t}),this.features=t.popupWindowFeatures||"location=no,toolbar=no,zoom=no",this.target=t.popupWindowTarget||"_blank",this.redirect_uri=t.startUrl,i.Log.debug("CordovaPopupWindow.ctor: redirect_uri: "+this.redirect_uri)}return e.prototype._isInAppBrowserInstalled=function(e){return["cordova-plugin-inappbrowser","cordova-plugin-inappbrowser.inappbrowser","org.apache.cordova.inappbrowser"].some(function(t){return e.hasOwnProperty(t)})},e.prototype.navigate=function(e){if(e&&e.url){if(!window.cordova)return this._error("cordova is undefined");var t=window.cordova.require("cordova/plugin_list").metadata;if(!1===this._isInAppBrowserInstalled(t))return this._error("InAppBrowser plugin not found");this._popup=cordova.InAppBrowser.open(e.url,this.target,this.features),this._popup?(i.Log.debug("CordovaPopupWindow.navigate: popup successfully created"),this._exitCallbackEvent=this._exitCallback.bind(this),this._loadStartCallbackEvent=this._loadStartCallback.bind(this),this._popup.addEventListener("exit",this._exitCallbackEvent,!1),this._popup.addEventListener("loadstart",this._loadStartCallbackEvent,!1)):this._error("Error opening popup window")}else this._error("No url provided");return this.promise},e.prototype._loadStartCallback=function(e){0===e.url.indexOf(this.redirect_uri)&&this._success({url:e.url})},e.prototype._exitCallback=function(e){this._error(e)},e.prototype._success=function(e){this._cleanup(),i.Log.debug("CordovaPopupWindow: Successful response from cordova popup window"),this._resolve(e)},e.prototype._error=function(e){this._cleanup(),i.Log.error(e),this._reject(new Error(e))},e.prototype.close=function(){this._cleanup()},e.prototype._cleanup=function(){this._popup&&(i.Log.debug("CordovaPopupWindow: cleaning up popup"),this._popup.removeEventListener("exit",this._exitCallbackEvent,!1),this._popup.removeEventListener("loadstart",this._loadStartCallbackEvent,!1),this._popup.close()),this._popup=null},n(e,[{key:"promise",get:function(){return this._promise}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(10),o=r(5),s=r(6),a=r(37),u=r(38),c=r(16),h=r(2),l=r(48),d=r(49),f=r(19),p=r(20),g=r(18),y=r(1),v=r(15),m=r(50);t.default={Version:m.Version,Log:n.Log,OidcClient:i.OidcClient,OidcClientSettings:o.OidcClientSettings,WebStorageStateStore:s.WebStorageStateStore,InMemoryWebStorage:a.InMemoryWebStorage,UserManager:u.UserManager,AccessTokenEvents:c.AccessTokenEvents,MetadataService:h.MetadataService,CordovaPopupNavigator:l.CordovaPopupNavigator,CordovaIFrameNavigator:d.CordovaIFrameNavigator,CheckSessionIFrame:f.CheckSessionIFrame,TokenRevocationClient:p.TokenRevocationClient,SessionMonitor:g.SessionMonitor,Global:y.Global,User:v.User},e.exports=t.default},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ClockService=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.prototype.getEpochTime=function(){return Promise.resolve(Date.now()/1e3|0)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ResponseValidator=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=r(0),o=r(2),s=r(25),a=r(11),u=r(12),c=r(4),h=["nonce","at_hash","iat","nbf","exp","aud","iss","c_hash"];t.ResponseValidator=function(){function e(t){var r=arguments.length>1&&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,h=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=u,this._tokenClient=new h(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 u.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 u.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;s<o.length;s++){var a=o[s];r[i]?Array.isArray(r[i])?r[i].indexOf(a)<0&&r[i].push(a):r[i]!==a&&("object"===(void 0===a?"undefined":n(a))&&this._settings.mergeClaims?r[i]=this._mergeClaims(r[i],a):r[i]=[r[i],a]):r[i]=a}}return r},e.prototype._filterProtocolClaims=function(e){i.Log.debug("ResponseValidator._filterProtocolClaims, incoming claims:",e);var t=Object.assign({},e);return this._settings._filterProtocolClaims?(h.forEach(function(e){delete t[e]}),i.Log.debug("ResponseValidator._filterProtocolClaims: protocol claims filtered",t)):i.Log.debug("ResponseValidator._filterProtocolClaims: protocol claims not filtered"),t},e.prototype._validateTokens=function(e,t){return t.code?(i.Log.debug("ResponseValidator._validateTokens: Validating code"),this._processCode(e,t)):t.id_token?t.access_token?(i.Log.debug("ResponseValidator._validateTokens: Validating id_token and access_token"),this._validateIdTokenAndAccessToken(e,t)):(i.Log.debug("ResponseValidator._validateTokens: Validating id_token"),this._validateIdToken(e,t)):(i.Log.debug("ResponseValidator._validateTokens: No code to process or id_token to validate"),Promise.resolve(t))},e.prototype._processCode=function(e,t){var r=this,o={client_id:e.client_id,client_secret:e.client_secret,code:t.code,redirect_uri:e.redirect_uri,code_verifier:e.code_verifier};return e.extraTokenParams&&"object"===n(e.extraTokenParams)&&Object.assign(o,e.extraTokenParams),this._tokenClient.exchangeCode(o).then(function(n){for(var o in n)t[o]=n[o];return t.id_token?(i.Log.debug("ResponseValidator._processCode: token response successful, processing id_token"),r._validateIdTokenAttributes(e,t)):(i.Log.debug("ResponseValidator._processCode: token response successful, returning response"),t)})},e.prototype._validateIdTokenAttributes=function(e,t){var r=this;return this._metadataService.getIssuer().then(function(n){var o=e.client_id,s=r._settings.clockSkew;return i.Log.debug("ResponseValidator._validateIdTokenAttributes: Validaing JWT attributes; using clock skew (in seconds) of: ",s),r._settings.getEpochTime().then(function(a){return r._joseUtil.validateJwtAttributes(t.id_token,n,o,s,a).then(function(r){return e.nonce&&e.nonce!==r.nonce?(i.Log.error("ResponseValidator._validateIdTokenAttributes: Invalid nonce in id_token"),Promise.reject(new Error("Invalid nonce in id_token"))):r.sub?(t.profile=r,t):(i.Log.error("ResponseValidator._validateIdTokenAttributes: No sub present in id_token"),Promise.reject(new Error("No sub present in id_token")))})})})},e.prototype._validateIdTokenAndAccessToken=function(e,t){var r=this;return this._validateIdToken(e,t).then(function(e){return r._validateAccessToken(e)})},e.prototype._getSigningKeyForJwt=function(e){var t=this;return this._metadataService.getSigningKeys().then(function(r){var n=e.header.kid;if(!r)return i.Log.error("ResponseValidator._validateIdToken: No signing keys from metadata"),Promise.reject(new Error("No signing keys from metadata"));i.Log.debug("ResponseValidator._validateIdToken: Received signing keys");var o=void 0;if(n)o=r.filter(function(e){return e.kid===n})[0];else{if((r=t._filterByAlg(r,e.header.alg)).length>1)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,u=r._settings.clockSkew;return i.Log.debug("ResponseValidator._validateIdToken: Validaing JWT; using clock skew (in seconds) of: ",u),r._joseUtil.validateJwt(t.id_token,s,o,a,u).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),u=this._joseUtil.hexToBase64Url(a);return u!==e.profile.at_hash?(i.Log.error("ResponseValidator._validateAccessToken: Failed to validate at_hash",u,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,u=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=u}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 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(t.responseText,a,e,u,c,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,u,c,h,l,d,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||u).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<i;o++){var s=r[o>>>2]>>>24-o%4*8&255;t[n+o>>>2]|=s<<24-(n+o)%4*8}else for(o=0;o<i;o+=4)t[n+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<e;n+=4)t.push(4294967296*r.random()|0);return new s.init(t,e)}}),a=n.enc={},u=a.Hex={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i<r;i++){var o=t[i>>>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<t;n+=2)r[n>>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new s.init(r,t/2)}},c=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i<r;i++){var o=t[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<t;n++)r[n>>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new s.init(r,t)}},h=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},l=i.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=h.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),u=(a=e?r.ceil(a):r.max((0|a)-this._minBufferSize,0))*o,c=r.min(4*u,i);if(u){for(var h=0;h<u;h+=o)this._doProcessBlock(n,h);var l=n.splice(0,u);t.sigBytes-=c}return new s.init(l,c)},clone:function(){var e=o.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0}),i.Hasher=l.extend({cfg:o.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){l.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,r){return new e.init(r).finalize(t)}},_createHmacHelper:function(e){return function(t,r){return new d.HMAC.init(e,r).finalize(t)}}}),d=n.algo={},n);!function(){var e,t=(e=y).lib,r=t.Base,n=t.WordArray;(e=e.x64={}).Word=r.extend({init:function(e,t){this.high=e,this.low=t}}),e.WordArray=r.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:8*e.length},toX32:function(){for(var e=this.words,t=e.length,r=[],i=0;i<t;i++){var o=e[i];r.push(o.high),r.push(o.low)}return n.create(r,this.sigBytes)},clone:function(){for(var e=r.clone.call(this),t=e.words=this.words.slice(0),n=t.length,i=0;i<n;i++)t[i]=t[i].clone();return e}})}(),function(){var e=y,t=e.lib.WordArray;e.enc.Base64={stringify:function(e){var t=e.words,r=e.sigBytes,n=this._map;e.clamp(),e=[];for(var i=0;i<r;i+=3)for(var o=(t[i>>>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<r;s++)e.push(n.charAt(o>>>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<r;s++)if(s%4){var a=n.indexOf(e.charAt(s-1))<<s%4*2,u=n.indexOf(e.charAt(s))>>>6-s%4*2;i[o>>>2]|=(a|u)<<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},u=2,c=0;64>c;){var h;e:{h=u;for(var l=e.sqrt(h),d=2;d<=l;d++)if(!(h%d)){h=!1;break e}h=!0}h&&(8>c&&(o[c]=a(e.pow(u,.5))),s[c]=a(e.pow(u,1/3)),c++),u++}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],u=r[4],c=r[5],h=r[6],l=r[7],d=0;64>d;d++){if(16>d)f[d]=0|e[t+d];else{var p=f[d-15],g=f[d-2];f[d]=((p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3)+f[d-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+f[d-16]}p=l+((u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25))+(u&c^~u&h)+s[d]+f[d],g=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&i^n&o^i&o),l=h,h=c,c=u,u=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]+u|0,r[5]=r[5]+c|0,r[6]=r[6]+h|0,r[7]=r[7]+l|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=[],u=0;80>u;u++)a[u]=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=(l=this._hash.words)[0],n=l[1],i=l[2],o=l[3],u=l[4],c=l[5],h=l[6],l=l[7],d=r.high,f=r.low,p=n.high,g=n.low,y=i.high,v=i.low,m=o.high,w=o.low,_=u.high,S=u.low,b=c.high,E=c.low,F=h.high,x=h.low,A=l.high,k=l.low,P=d,T=f,I=p,C=g,R=y,U=v,L=m,D=w,N=_,O=S,H=b,j=E,M=F,B=x,K=A,V=k,q=0;80>q;q++){var J=a[q];if(16>q)var W=J.high=0|e[t+2*q],$=J.low=0|e[t+2*q+1];else{W=(($=(W=a[q-15]).high)>>>1|(z=W.low)<<31)^($>>>8|z<<24)^$>>>7;var z=(z>>>1|$<<31)^(z>>>8|$<<24)^(z>>>7|$<<25),Y=(($=(Y=a[q-2]).high)>>>19|(G=Y.low)<<13)^($<<3|G>>>29)^$>>>6,G=(G>>>19|$<<13)^(G<<3|$>>>29)^(G>>>6|$<<26),X=($=a[q-7]).high,Q=(Z=a[q-16]).high,Z=Z.low;W=(W=(W=W+X+(($=z+$.low)>>>0<z>>>0?1:0))+Y+(($+=G)>>>0<G>>>0?1:0))+Q+(($+=Z)>>>0<Z>>>0?1:0),J.high=W,J.low=$}X=N&H^~N&M,Z=O&j^~O&B,J=P&I^P&R^I&R;var ee=T&C^T&U^C&U,te=(z=(P>>>28|T<<4)^(P<<30|T>>>2)^(P<<25|T>>>7),Y=(T>>>28|P<<4)^(T<<30|P>>>2)^(T<<25|P>>>7),(G=s[q]).high),re=G.low;Q=K+((N>>>14|O<<18)^(N>>>18|O<<14)^(N<<23|O>>>9))+((G=V+((O>>>14|N<<18)^(O>>>18|N<<14)^(O<<23|N>>>9)))>>>0<V>>>0?1:0),K=M,V=B,M=H,B=j,H=N,j=O,N=L+(Q=(Q=(Q=Q+X+((G+=Z)>>>0<Z>>>0?1:0))+te+((G+=re)>>>0<re>>>0?1:0))+W+((G+=$)>>>0<$>>>0?1:0))+((O=D+G|0)>>>0<D>>>0?1:0)|0,L=R,D=U,R=I,U=C,I=P,C=T,P=Q+(J=z+J+(($=Y+ee)>>>0<Y>>>0?1:0))+((T=G+$|0)>>>0<G>>>0?1:0)|0}f=r.low=f+T,r.high=d+P+(f>>>0<T>>>0?1:0),g=n.low=g+C,n.high=p+I+(g>>>0<C>>>0?1:0),v=i.low=v+U,i.high=y+R+(v>>>0<U>>>0?1:0),w=o.low=w+D,o.high=m+L+(w>>>0<D>>>0?1:0),S=u.low=S+O,u.high=_+N+(S>>>0<O>>>0?1:0),E=c.low=E+j,c.high=b+H+(E>>>0<j>>>0?1:0),x=h.low=x+B,h.high=F+M+(x>>>0<B>>>0?1:0),k=l.low=k+V,l.high=A+K+(k>>>0<V>>>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)}();
4
2
  /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
5
3
  */
6
- var v,m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function w(e){var t,r,n="";for(t=0;t+3<=e.length;t+=3)r=parseInt(e.substring(t,t+3),16),n+=m.charAt(r>>6)+m.charAt(63&r);for(t+1==e.length?(r=parseInt(e.substring(t,t+1),16),n+=m.charAt(r<<2)):t+2==e.length&&(r=parseInt(e.substring(t,t+2),16),n+=m.charAt(r>>2)+m.charAt((3&r)<<4));(3&n.length)>0;)n+="=";return n}function b(e){var t,r,n,i="",s=0;for(t=0;t<e.length&&"="!=e.charAt(t);++t)(n=m.indexOf(e.charAt(t)))<0||(0==s?(i+=T(n>>2),r=3&n,s=1):1==s?(i+=T(r<<2|n>>4),r=15&n,s=2):2==s?(i+=T(r),i+=T(n>>2),r=3&n,s=3):(i+=T(r<<2|n>>4),i+=T(15&n),s=0));return 1==s&&(i+=T(r<<2)),i}function _(e){var t,r=b(e),n=new Array;for(t=0;2*t<r.length;++t)n[t]=parseInt(r.substring(2*t,2*t+2),16);return n}function S(e,t,r){null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function E(){return new S(null)}"Microsoft Internet Explorer"==p.appName?(S.prototype.am=function(e,t,r,n,i,s){for(var o=32767&t,a=t>>15;--s>=0;){var u=32767&this[e],c=this[e++]>>15,h=a*u+c*o;i=((u=o*u+((32767&h)<<15)+r[n]+(1073741823&i))>>>30)+(h>>>15)+a*c+(i>>>30),r[n++]=1073741823&u}return i},v=30):"Netscape"!=p.appName?(S.prototype.am=function(e,t,r,n,i,s){for(;--s>=0;){var o=t*this[e++]+r[n]+i;i=Math.floor(o/67108864),r[n++]=67108863&o}return i},v=26):(S.prototype.am=function(e,t,r,n,i,s){for(var o=16383&t,a=t>>14;--s>=0;){var u=16383&this[e],c=this[e++]>>14,h=a*u+c*o;i=((u=o*u+((16383&h)<<14)+r[n]+i)>>28)+(h>>14)+a*c,r[n++]=268435455&u}return i},v=28),S.prototype.DB=v,S.prototype.DM=(1<<v)-1,S.prototype.DV=1<<v,S.prototype.FV=Math.pow(2,52),S.prototype.F1=52-v,S.prototype.F2=2*v-52;var x,A,F=new Array;for(x="0".charCodeAt(0),A=0;A<=9;++A)F[x++]=A;for(x="a".charCodeAt(0),A=10;A<36;++A)F[x++]=A;for(x="A".charCodeAt(0),A=10;A<36;++A)F[x++]=A;function T(e){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(e)}function k(e,t){var r=F[e.charCodeAt(t)];return null==r?-1:r}function I(e){var t=E();return t.fromInt(e),t}function C(e){var t,r=1;return 0!=(t=e>>>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 R(e){this.m=e}function P(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function N(e,t){return e&t}function U(e,t){return e|t}function O(e,t){return e^t}function L(e,t){return e&~t}function D(e){if(0==e)return-1;var t=0;return!(65535&e)&&(e>>=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}R.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},R.prototype.revert=function(e){return e},R.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},R.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},R.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},P.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},P.prototype.revert=function(e){var t=E();return e.copyTo(t),this.reduce(t),t},P.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var r=32767&e[t],n=r*this.mpl+((r*this.mph+(e[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)},P.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},P.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,s=0;--n>=0;){var o=8==r?255&e[n]:k(e,n);o<0?"-"==e.charAt(n)&&(i=!0):(i=!1,0==s?this[this.t++]=o:s+r>this.DB?(this[this.t-1]|=(o&(1<<this.DB-s)-1)<<s,this[this.t++]=o>>this.DB-s):this[this.t-1]|=o<<s,(s+=r)>=this.DB&&(s-=this.DB))}8==r&&!!(128&e[0])&&(this.s=-1,s>0&&(this[this.t-1]|=(1<<this.DB-s)-1<<s)),this.clamp(),i&&S.ZERO.subTo(this,this)},S.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>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<this.t;++r)t[r-e]=this[r];t.t=Math.max(this.t-e,0),t.s=this.s},S.prototype.lShiftTo=function(e,t){var r,n=e%this.DB,i=this.DB-n,s=(1<<i)-1,o=Math.floor(e/this.DB),a=this.s<<n&this.DM;for(r=this.t-1;r>=0;--r)t[r+o+1]=this[r]>>i|a,a=(this[r]&s)<<n;for(r=o-1;r>=0;--r)t[r]=0;t[o]=a,t.t=this.t+o+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,s=(1<<n)-1;t[0]=this[r]>>n;for(var o=r+1;o<this.t;++o)t[o-r-1]|=(this[o]&s)<<i,t[o-r]=this[o]>>n;n>0&&(t[this.t-r-1]|=(this.s&s)<<i),t.t=this.t-r,t.clamp()}},S.prototype.subTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this[r]-e[r],t[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n-=e.s;r<this.t;)n+=this[r],t[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n-=e[r],t[r++]=n&this.DM,n>>=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<n.t;++i)t[i+r.t]=r.am(0,n[i],t,i,0,r.t);t.s=0,t.clamp(),this.s!=e.s&&S.ZERO.subTo(t,t)},S.prototype.squareTo=function(e){for(var t=this.abs(),r=e.t=2*t.t;--r>=0;)e[r]=0;for(r=0;r<t.t-1;++r){var n=t.am(r,t[r],e,2*r,0,1);(e[r+t.t]+=t.am(r+1,2*t[r],e,2*r+1,n,t.t-r-1))>=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.t<n.t)return null!=t&&t.fromInt(0),void(null!=r&&this.copyTo(r));null==r&&(r=E());var s=E(),o=this.s,a=e.s,u=this.DB-C(n[n.t-1]);u>0?(n.lShiftTo(u,s),i.lShiftTo(u,r)):(n.copyTo(s),i.copyTo(r));var c=s.t,h=s[c-1];if(0!=h){var l=h*(1<<this.F1)+(c>1?s[c-2]>>this.F2:0),d=this.FV/l,f=(1<<this.F1)/l,p=1<<this.F2,g=r.t,y=g-c,v=null==t?E():t;for(s.dlShiftTo(y,v),r.compareTo(v)>=0&&(r[r.t++]=1,r.subTo(v,r)),S.ONE.dlShiftTo(c,v),v.subTo(s,s);s.t<c;)s[s.t++]=0;for(;--y>=0;){var m=r[--g]==h?this.DM:Math.floor(r[g]*d+(r[g-1]+p)*f);if((r[g]+=s.am(0,m,r,y,0,c))<m)for(s.dlShiftTo(y,v),r.subTo(v,r);r[g]<--m;)r.subTo(v,r)}null!=t&&(r.drShiftTo(c,t),o!=a&&S.ZERO.subTo(t,t)),r.t=c,r.clamp(),u>0&&r.rShiftTo(u,r),o<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),s=C(e)-1;for(i.copyTo(r);--s>=0;)if(t.sqrTo(r,n),(e&1<<s)>0)t.mulTo(n,i,r);else{var o=r;r=n,n=o}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<<t)-1,i=!1,s="",o=this.t,a=this.DB-o*this.DB%t;if(o-- >0)for(a<this.DB&&(r=this[o]>>a)>0&&(i=!0,s=T(r));o>=0;)a<t?(r=(this[o]&(1<<a)-1)<<t-a,r|=this[--o]>>(a+=this.DB-t)):(r=this[o]>>(a-=t)&n,a<=0&&(a+=this.DB,--o)),r>0&&(i=!0),i&&(s+=T(r));return i?s:"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 R(t):new P(t),this.exp(e,r)},S.ZERO=I(0),S.ONE=I(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 q,K,V,$=[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],W=(1<<26)/$[$.length-1];
4
+ var v,m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function w(e){var t,r,n="";for(t=0;t+3<=e.length;t+=3)r=parseInt(e.substring(t,t+3),16),n+=m.charAt(r>>6)+m.charAt(63&r);for(t+1==e.length?(r=parseInt(e.substring(t,t+1),16),n+=m.charAt(r<<2)):t+2==e.length&&(r=parseInt(e.substring(t,t+2),16),n+=m.charAt(r>>2)+m.charAt((3&r)<<4));(3&n.length)>0;)n+="=";return n}function _(e){var t,r,n,i="",o=0;for(t=0;t<e.length&&"="!=e.charAt(t);++t)(n=m.indexOf(e.charAt(t)))<0||(0==o?(i+=k(n>>2),r=3&n,o=1):1==o?(i+=k(r<<2|n>>4),r=15&n,o=2):2==o?(i+=k(r),i+=k(n>>2),r=3&n,o=3):(i+=k(r<<2|n>>4),i+=k(15&n),o=0));return 1==o&&(i+=k(r<<2)),i}function S(e){var t,r=_(e),n=new Array;for(t=0;2*t<r.length;++t)n[t]=parseInt(r.substring(2*t,2*t+2),16);return n}function b(e,t,r){null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function E(){return new b(null)}"Microsoft Internet Explorer"==p.appName?(b.prototype.am=function(e,t,r,n,i,o){for(var s=32767&t,a=t>>15;--o>=0;){var u=32767&this[e],c=this[e++]>>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},v=30):"Netscape"!=p.appName?(b.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},v=26):(b.prototype.am=function(e,t,r,n,i,o){for(var s=16383&t,a=t>>14;--o>=0;){var u=16383&this[e],c=this[e++]>>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},v=28),b.prototype.DB=v,b.prototype.DM=(1<<v)-1,b.prototype.DV=1<<v,b.prototype.FV=Math.pow(2,52),b.prototype.F1=52-v,b.prototype.F2=2*v-52;var F,x,A=new Array;for(F="0".charCodeAt(0),x=0;x<=9;++x)A[F++]=x;for(F="a".charCodeAt(0),x=10;x<36;++x)A[F++]=x;for(F="A".charCodeAt(0),x=10;x<36;++x)A[F++]=x;function k(e){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(e)}function P(e,t){var r=A[e.charCodeAt(t)];return null==r?-1:r}function T(e){var t=E();return t.fromInt(e),t}function I(e){var t,r=1;return 0!=(t=e>>>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 C(e){this.m=e}function R(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function U(e,t){return e&t}function L(e,t){return e|t}function D(e,t){return e^t}function N(e,t){return e&~t}function O(e){if(0==e)return-1;var t=0;return!(65535&e)&&(e>>=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 H(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function j(){}function M(e){return e}function B(e){this.r2=E(),this.q3=E(),b.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}C.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},C.prototype.revert=function(e){return e},C.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},C.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},C.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},R.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(b.ZERO)>0&&this.m.subTo(t,t),t},R.prototype.revert=function(e){var t=E();return e.copyTo(t),this.reduce(t),t},R.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var r=32767&e[t],n=r*this.mpl+((r*this.mph+(e[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)},R.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},R.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},b.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},b.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},b.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]:P(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)-1)<<o,this[this.t++]=s>>this.DB-o):this[this.t-1]|=s<<o,(o+=r)>=this.DB&&(o-=this.DB))}8==r&&!!(128&e[0])&&(this.s=-1,o>0&&(this[this.t-1]|=(1<<this.DB-o)-1<<o)),this.clamp(),i&&b.ZERO.subTo(this,this)},b.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t},b.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},b.prototype.drShiftTo=function(e,t){for(var r=e;r<this.t;++r)t[r-e]=this[r];t.t=Math.max(this.t-e,0),t.s=this.s},b.prototype.lShiftTo=function(e,t){var r,n=e%this.DB,i=this.DB-n,o=(1<<i)-1,s=Math.floor(e/this.DB),a=this.s<<n&this.DM;for(r=this.t-1;r>=0;--r)t[r+s+1]=this[r]>>i|a,a=(this[r]&o)<<n;for(r=s-1;r>=0;--r)t[r]=0;t[s]=a,t.t=this.t+s+1,t.s=this.s,t.clamp()},b.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)-1;t[0]=this[r]>>n;for(var s=r+1;s<this.t;++s)t[s-r-1]|=(this[s]&o)<<i,t[s-r]=this[s]>>n;n>0&&(t[this.t-r-1]|=(this.s&o)<<i),t.t=this.t-r,t.clamp()}},b.prototype.subTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this[r]-e[r],t[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n-=e.s;r<this.t;)n+=this[r],t[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n-=e[r],t[r++]=n&this.DM,n>>=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()},b.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<n.t;++i)t[i+r.t]=r.am(0,n[i],t,i,0,r.t);t.s=0,t.clamp(),this.s!=e.s&&b.ZERO.subTo(t,t)},b.prototype.squareTo=function(e){for(var t=this.abs(),r=e.t=2*t.t;--r>=0;)e[r]=0;for(r=0;r<t.t-1;++r){var n=t.am(r,t[r],e,2*r,0,1);(e[r+t.t]+=t.am(r+1,2*t[r],e,2*r+1,n,t.t-r-1))>=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()},b.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t<n.t)return null!=t&&t.fromInt(0),void(null!=r&&this.copyTo(r));null==r&&(r=E());var o=E(),s=this.s,a=e.s,u=this.DB-I(n[n.t-1]);u>0?(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<<this.F1)+(c>1?o[c-2]>>this.F2:0),d=this.FV/l,f=(1<<this.F1)/l,p=1<<this.F2,g=r.t,y=g-c,v=null==t?E():t;for(o.dlShiftTo(y,v),r.compareTo(v)>=0&&(r[r.t++]=1,r.subTo(v,r)),b.ONE.dlShiftTo(c,v),v.subTo(o,o);o.t<c;)o[o.t++]=0;for(;--y>=0;){var m=r[--g]==h?this.DM:Math.floor(r[g]*d+(r[g-1]+p)*f);if((r[g]+=o.am(0,m,r,y,0,c))<m)for(o.dlShiftTo(y,v),r.subTo(v,r);r[g]<--m;)r.subTo(v,r)}null!=t&&(r.drShiftTo(c,t),s!=a&&b.ZERO.subTo(t,t)),r.t=c,r.clamp(),u>0&&r.rShiftTo(u,r),s<0&&b.ZERO.subTo(r,r)}}},b.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},b.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},b.prototype.exp=function(e,t){if(e>4294967295||e<1)return b.ONE;var r=E(),n=E(),i=t.convert(this),o=I(e)-1;for(i.copyTo(r);--o>=0;)if(t.sqrTo(r,n),(e&1<<o)>0)t.mulTo(n,i,r);else{var s=r;r=n,n=s}return t.revert(r)},b.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<<t)-1,i=!1,o="",s=this.t,a=this.DB-s*this.DB%t;if(s-- >0)for(a<this.DB&&(r=this[s]>>a)>0&&(i=!0,o=k(r));s>=0;)a<t?(r=(this[s]&(1<<a)-1)<<t-a,r|=this[--s]>>(a+=this.DB-t)):(r=this[s]>>(a-=t)&n,a<=0&&(a+=this.DB,--s)),r>0&&(i=!0),i&&(o+=k(r));return i?o:"0"},b.prototype.negate=function(){var e=E();return b.ZERO.subTo(this,e),e},b.prototype.abs=function(){return this.s<0?this.negate():this},b.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},b.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+I(this[this.t-1]^this.s&this.DM)},b.prototype.mod=function(e){var t=E();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(b.ZERO)>0&&e.subTo(t,t),t},b.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new C(t):new R(t),this.exp(e,r)},b.ZERO=T(0),b.ONE=T(1),j.prototype.convert=M,j.prototype.revert=M,j.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},j.prototype.sqrTo=function(e,t){e.squareTo(t)},B.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},B.prototype.revert=function(e){return e},B.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)},B.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},B.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var K,V,q,J=[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],W=(1<<26)/J[J.length-1];
7
5
  /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
8
- */function J(){this.i=0,this.j=0,this.S=new Array}
6
+ */function $(){this.i=0,this.j=0,this.S=new Array}
9
7
  /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
10
8
  */
11
- function z(){!function(e){K[V++]^=255&e,K[V++]^=e>>8&255,K[V++]^=e>>16&255,K[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=I(r),i=E(),s=E(),o="";for(this.divRemTo(n,i,s);i.signum()>0;)o=(r+s.intValue()).toString(e).substr(1)+o,i.divRemTo(n,i,s);return s.intValue().toString(e)+o},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,s=0,o=0,a=0;a<e.length;++a){var u=k(e,a);u<0?"-"==e.charAt(a)&&0==this.signum()&&(i=!0):(o=t*o+u,++s>=r&&(this.dMultiply(n),this.dAddOffset(o,0),s=0,o=0))}s>0&&(this.dMultiply(Math.pow(t,s)),this.dAddOffset(o,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),U,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<<i)-1:n[0]=0,this.fromString(n,256)}},S.prototype.bitwiseTo=function(e,t,r){var n,i,s=Math.min(e.t,this.t);for(n=0;n<s;++n)r[n]=t(this[n],e[n]);if(e.t<this.t){for(i=e.s&this.DM,n=s;n<this.t;++n)r[n]=t(this[n],i);r.t=this.t}else{for(i=this.s&this.DM,n=s;n<e.t;++n)r[n]=t(i,e[n]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()},S.prototype.changeBit=function(e,t){var r=S.ONE.shiftLeft(e);return this.bitwiseTo(r,t,r),r},S.prototype.addTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this[r]+e[r],t[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n+=e.s;r<this.t;)n+=this[r],t[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n+=e[r],t[r++]=n&this.DM,n>>=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<n;++i)r[i+this.t]=this.am(0,e[i],r,i,0,this.t);for(n=Math.min(e.t,t);i<n;++i)this.am(0,e[i],r,i,0,t-i);r.clamp()},S.prototype.multiplyUpperTo=function(e,t,r){--t;var n=r.t=this.t+e.t-t;for(r.s=0;--n>=0;)r[n]=0;for(n=Math.max(t-this.t,0);n<e.t;++n)r[this.t+n-t]=this.am(t-n,e[n],r,0,0,this.t+n-t);r.clamp(),r.drShiftTo(1,r)},S.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)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)>$.length&&(e=$.length);for(var i=E(),s=0;s<e;++s){i.fromInt($[Math.floor(Math.random()*$.length)]);var o=i.modPow(n,this);if(0!=o.compareTo(S.ONE)&&0!=o.compareTo(t)){for(var a=1;a++<r&&0!=o.compareTo(t);)if(0==(o=o.modPowInt(2,this)).compareTo(S.ONE))return!1;if(0!=o.compareTo(t))return!1}}return!0},S.prototype.clone=
9
+ function z(){!function(e){V[q++]^=255&e,V[q++]^=e>>8&255,V[q++]^=e>>16&255,V[q++]^=e>>24&255,q>=256&&(q-=256)}((new Date).getTime())}if(b.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},b.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=T(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},b.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<e.length;++a){var u=P(e,a);u<0?"-"==e.charAt(a)&&0==this.signum()&&(i=!0):(s=t*s+u,++o>=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&&b.ZERO.subTo(this,this)},b.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(b.ONE.shiftLeft(e-1),L,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(b.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<<i)-1:n[0]=0,this.fromString(n,256)}},b.prototype.bitwiseTo=function(e,t,r){var n,i,o=Math.min(e.t,this.t);for(n=0;n<o;++n)r[n]=t(this[n],e[n]);if(e.t<this.t){for(i=e.s&this.DM,n=o;n<this.t;++n)r[n]=t(this[n],i);r.t=this.t}else{for(i=this.s&this.DM,n=o;n<e.t;++n)r[n]=t(i,e[n]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()},b.prototype.changeBit=function(e,t){var r=b.ONE.shiftLeft(e);return this.bitwiseTo(r,t,r),r},b.prototype.addTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this[r]+e[r],t[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n+=e.s;r<this.t;)n+=this[r],t[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n+=e[r],t[r++]=n&this.DM,n>>=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()},b.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},b.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]}},b.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<n;++i)r[i+this.t]=this.am(0,e[i],r,i,0,this.t);for(n=Math.min(e.t,t);i<n;++i)this.am(0,e[i],r,i,0,t-i);r.clamp()},b.prototype.multiplyUpperTo=function(e,t,r){--t;var n=r.t=this.t+e.t-t;for(r.s=0;--n>=0;)r[n]=0;for(n=Math.max(t-this.t,0);n<e.t;++n)r[this.t+n-t]=this.am(t-n,e[n],r,0,0,this.t+n-t);r.clamp(),r.drShiftTo(1,r)},b.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)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},b.prototype.millerRabin=function(e){var t=this.subtract(b.ONE),r=t.getLowestSetBit();if(r<=0)return!1;var n=t.shiftRight(r);(e=e+1>>1)>J.length&&(e=J.length);for(var i=E(),o=0;o<e;++o){i.fromInt(J[Math.floor(Math.random()*J.length)]);var s=i.modPow(n,this);if(0!=s.compareTo(b.ONE)&&0!=s.compareTo(t)){for(var a=1;a++<r&&0!=s.compareTo(t);)if(0==(s=s.modPowInt(2,this)).compareTo(b.ONE))return!1;if(0!=s.compareTo(t))return!1}}return!0},b.prototype.clone=
12
10
  /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
13
11
  */
14
- function(){var e=E();return this.copyTo(e),e},S.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},S.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>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<this.DB&&(r=this[e]>>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<<this.DB-n);e>=0;)n<8?(r=(this[e]&(1<<n)-1)<<8-n,r|=this[--e]>>(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,N,t),t},S.prototype.or=function(e){var t=E();return this.bitwiseTo(e,U,t),t},S.prototype.xor=function(e){var t=E();return this.bitwiseTo(e,O,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;++t)e[t]=this.DM&~this[t];return e.t=this.t,e.s=~this.s,e},S.prototype.shiftLeft=function(e){var t=E();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},S.prototype.shiftRight=function(e){var t=E();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},S.prototype.getLowestSetBit=function(){for(var e=0;e<this.t;++e)if(0!=this[e])return e*this.DB+D(this[e]);return this.s<0?this.t*this.DB:-1},S.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,r=0;r<this.t;++r)e+=j(this[r]^t);return e},S.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:!!(this[t]&1<<e%this.DB)},S.prototype.setBit=function(e){return this.changeBit(e,U)},S.prototype.clearBit=function(e){return this.changeBit(e,L)},S.prototype.flipBit=function(e){return this.changeBit(e,O)},S.prototype.add=function(e){var t=E();return this.addTo(e,t),t},S.prototype.subtract=function(e){var t=E();return this.subTo(e,t),t},S.prototype.multiply=function(e){var t=E();return this.multiplyTo(e,t),t},S.prototype.divide=function(e){var t=E();return this.divRemTo(e,t,null),t},S.prototype.remainder=function(e){var t=E();return this.divRemTo(e,null,t),t},S.prototype.divideAndRemainder=function(e){var t=E(),r=E();return this.divRemTo(e,t,r),new Array(t,r)},S.prototype.modPow=function(e,t){var r,n,i=e.bitLength(),s=I(1);if(i<=0)return s;r=i<18?1:i<48?3:i<144?4:i<768?5:6,n=i<8?new R(t):t.isEven()?new H(t):new P(t);var o=new Array,a=3,u=r-1,c=(1<<r)-1;if(o[1]=n.convert(this),r>1){var h=E();for(n.sqrTo(o[1],h);a<=c;)o[a]=E(),n.mulTo(h,o[a-2],o[a]),a+=2}var l,d,f=e.t-1,p=!0,g=E();for(i=C(e[f])-1;f>=0;){for(i>=u?l=e[f]>>i-u&c:(l=(e[f]&(1<<i+1)-1)<<u-i,f>0&&(l|=e[f-1]>>this.DB+i-u)),a=r;!(1&l);)l>>=1,--a;if((i-=a)<0&&(i+=this.DB,--f),p)o[l].copyTo(s),p=!1;else{for(;a>1;)n.sqrTo(s,g),n.sqrTo(g,s),a-=2;a>0?n.sqrTo(s,g):(d=s,s=g,g=d),n.mulTo(g,o[l],s)}for(;f>=0&&!(e[f]&1<<i);)n.sqrTo(s,g),d=s,s=g,g=d,--i<0&&(i=this.DB-1,--f)}return n.revert(s)},S.prototype.modInverse=function(e){var t=e.isEven();if(this.isEven()&&t||0==e.signum())return S.ZERO;for(var r=e.clone(),n=this.clone(),i=I(1),s=I(0),o=I(0),a=I(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),t?(i.isEven()&&s.isEven()||(i.addTo(this,i),s.subTo(e,s)),i.rShiftTo(1,i)):s.isEven()||s.subTo(e,s),s.rShiftTo(1,s);for(;n.isEven();)n.rShiftTo(1,n),t?(o.isEven()&&a.isEven()||(o.addTo(this,o),a.subTo(e,a)),o.rShiftTo(1,o)):a.isEven()||a.subTo(e,a),a.rShiftTo(1,a);r.compareTo(n)>=0?(r.subTo(n,r),t&&i.subTo(o,i),s.subTo(a,s)):(n.subTo(r,n),t&&o.subTo(i,o),a.subTo(s,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(),s=r.getLowestSetBit();if(s<0)return t;for(i<s&&(s=i),s>0&&(t.rShiftTo(s,t),r.rShiftTo(s,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 s>0&&r.lShiftTo(s,r),r},S.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r[0]<=$[$.length-1]){for(t=0;t<$.length;++t)if(r[0]==$[t])return!0;return!1}if(r.isEven())return!1;for(t=1;t<$.length;){for(var n=$[t],i=t+1;i<$.length&&n<W;)n*=$[i++];for(n=r.modInt(n);t<i;)if(n%$[t++]==0)return!1}return r.millerRabin(e)},S.prototype.square=function(){var e=E();return this.squareTo(e),e},J.prototype.init=function(e){var t,r,n;for(t=0;t<256;++t)this.S[t]=t;for(r=0,t=0;t<256;++t)r=r+this.S[t]+e[t%e.length]&255,n=this.S[t],this.S[t]=this.S[r],this.S[r]=n;this.i=0,this.j=0},J.prototype.next=function(){var e;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,e=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=e,this.S[e+this.S[this.i]&255]},null==K){var X;if(K=new Array,V=0,void 0!==g&&(void 0!==g.crypto||void 0!==g.msCrypto)){var G=g.crypto||g.msCrypto;if(G.getRandomValues){var Y=new Uint8Array(32);for(G.getRandomValues(Y),X=0;X<32;++X)K[V++]=Y[X]}else if("Netscape"==p.appName&&p.appVersion<"5"){var Q=g.crypto.random(32);for(X=0;X<Q.length;++X)K[V++]=255&Q.charCodeAt(X)}}for(;V<256;)X=Math.floor(65536*Math.random()),K[V++]=X>>>8,K[V++]=255&X;V=0,z()}function Z(){if(null==q){for(z(),(q=new J).init(K),V=0;V<K.length;++V)K[V]=0;V=0}return q.next()}function ee(){}
12
+ function(){var e=E();return this.copyTo(e),e},b.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},b.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>24},b.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},b.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},b.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<this.DB&&(r=this[e]>>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<<this.DB-n);e>=0;)n<8?(r=(this[e]&(1<<n)-1)<<8-n,r|=this[--e]>>(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},b.prototype.equals=function(e){return 0==this.compareTo(e)},b.prototype.min=function(e){return this.compareTo(e)<0?this:e},b.prototype.max=function(e){return this.compareTo(e)>0?this:e},b.prototype.and=function(e){var t=E();return this.bitwiseTo(e,U,t),t},b.prototype.or=function(e){var t=E();return this.bitwiseTo(e,L,t),t},b.prototype.xor=function(e){var t=E();return this.bitwiseTo(e,D,t),t},b.prototype.andNot=function(e){var t=E();return this.bitwiseTo(e,N,t),t},b.prototype.not=function(){for(var e=E(),t=0;t<this.t;++t)e[t]=this.DM&~this[t];return e.t=this.t,e.s=~this.s,e},b.prototype.shiftLeft=function(e){var t=E();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},b.prototype.shiftRight=function(e){var t=E();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},b.prototype.getLowestSetBit=function(){for(var e=0;e<this.t;++e)if(0!=this[e])return e*this.DB+O(this[e]);return this.s<0?this.t*this.DB:-1},b.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,r=0;r<this.t;++r)e+=H(this[r]^t);return e},b.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:!!(this[t]&1<<e%this.DB)},b.prototype.setBit=function(e){return this.changeBit(e,L)},b.prototype.clearBit=function(e){return this.changeBit(e,N)},b.prototype.flipBit=function(e){return this.changeBit(e,D)},b.prototype.add=function(e){var t=E();return this.addTo(e,t),t},b.prototype.subtract=function(e){var t=E();return this.subTo(e,t),t},b.prototype.multiply=function(e){var t=E();return this.multiplyTo(e,t),t},b.prototype.divide=function(e){var t=E();return this.divRemTo(e,t,null),t},b.prototype.remainder=function(e){var t=E();return this.divRemTo(e,null,t),t},b.prototype.divideAndRemainder=function(e){var t=E(),r=E();return this.divRemTo(e,t,r),new Array(t,r)},b.prototype.modPow=function(e,t){var r,n,i=e.bitLength(),o=T(1);if(i<=0)return o;r=i<18?1:i<48?3:i<144?4:i<768?5:6,n=i<8?new C(t):t.isEven()?new B(t):new R(t);var s=new Array,a=3,u=r-1,c=(1<<r)-1;if(s[1]=n.convert(this),r>1){var h=E();for(n.sqrTo(s[1],h);a<=c;)s[a]=E(),n.mulTo(h,s[a-2],s[a]),a+=2}var l,d,f=e.t-1,p=!0,g=E();for(i=I(e[f])-1;f>=0;){for(i>=u?l=e[f]>>i-u&c:(l=(e[f]&(1<<i+1)-1)<<u-i,f>0&&(l|=e[f-1]>>this.DB+i-u)),a=r;!(1&l);)l>>=1,--a;if((i-=a)<0&&(i+=this.DB,--f),p)s[l].copyTo(o),p=!1;else{for(;a>1;)n.sqrTo(o,g),n.sqrTo(g,o),a-=2;a>0?n.sqrTo(o,g):(d=o,o=g,g=d),n.mulTo(g,s[l],o)}for(;f>=0&&!(e[f]&1<<i);)n.sqrTo(o,g),d=o,o=g,g=d,--i<0&&(i=this.DB-1,--f)}return n.revert(o)},b.prototype.modInverse=function(e){var t=e.isEven();if(this.isEven()&&t||0==e.signum())return b.ZERO;for(var r=e.clone(),n=this.clone(),i=T(1),o=T(0),s=T(0),a=T(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),t?(i.isEven()&&o.isEven()||(i.addTo(this,i),o.subTo(e,o)),i.rShiftTo(1,i)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);for(;n.isEven();)n.rShiftTo(1,n),t?(s.isEven()&&a.isEven()||(s.addTo(this,s),a.subTo(e,a)),s.rShiftTo(1,s)):a.isEven()||a.subTo(e,a),a.rShiftTo(1,a);r.compareTo(n)>=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(b.ONE)?b.ZERO:a.compareTo(e)>=0?a.subtract(e):a.signum()<0?(a.addTo(e,a),a.signum()<0?a.add(e):a):a},b.prototype.pow=function(e){return this.exp(e,new j)},b.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(i<o&&(o=i),o>0&&(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},b.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r[0]<=J[J.length-1]){for(t=0;t<J.length;++t)if(r[0]==J[t])return!0;return!1}if(r.isEven())return!1;for(t=1;t<J.length;){for(var n=J[t],i=t+1;i<J.length&&n<W;)n*=J[i++];for(n=r.modInt(n);t<i;)if(n%J[t++]==0)return!1}return r.millerRabin(e)},b.prototype.square=function(){var e=E();return this.squareTo(e),e},$.prototype.init=function(e){var t,r,n;for(t=0;t<256;++t)this.S[t]=t;for(r=0,t=0;t<256;++t)r=r+this.S[t]+e[t%e.length]&255,n=this.S[t],this.S[t]=this.S[r],this.S[r]=n;this.i=0,this.j=0},$.prototype.next=function(){var e;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,e=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=e,this.S[e+this.S[this.i]&255]},null==V){var Y;if(V=new Array,q=0,void 0!==g&&(void 0!==g.crypto||void 0!==g.msCrypto)){var G=g.crypto||g.msCrypto;if(G.getRandomValues){var X=new Uint8Array(32);for(G.getRandomValues(X),Y=0;Y<32;++Y)V[q++]=X[Y]}else if("Netscape"==p.appName&&p.appVersion<"5"){var Q=g.crypto.random(32);for(Y=0;Y<Q.length;++Y)V[q++]=255&Q.charCodeAt(Y)}}for(;q<256;)Y=Math.floor(65536*Math.random()),V[q++]=Y>>>8,V[q++]=255&Y;q=0,z()}function Z(){if(null==K){for(z(),(K=new $).init(V),q=0;q<V.length;++q)V[q]=0;q=0}return K.next()}function ee(){}
15
13
  /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
16
- */function te(e,t){return new S(e,t)}function re(e,t,r){for(var n="",i=0;n.length<t;)n+=r(String.fromCharCode.apply(String,e.concat([(4278190080&i)>>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}
14
+ */function te(e,t){return new b(e,t)}function re(e,t,r){for(var n="",i=0;n.length<t;)n+=r(String.fromCharCode.apply(String,e.concat([(4278190080&i)>>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}
17
15
  /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
18
- */function ie(e,t){this.x=t,this.q=e}function se(e,t,r,n){this.curve=e,this.x=t,this.y=r,this.z=null==n?S.ONE:n,this.zinv=null}function oe(e,t,r){this.q=e,this.a=this.fromBigInteger(t),this.b=this.fromBigInteger(r),this.infinity=new se(this,null,null)}ee.prototype.nextBytes=function(e){var t;for(t=0;t<e.length;++t)e[t]=Z()},ne.prototype.doPublic=function(e){return e.modPowInt(this.e,this.n)},ne.prototype.setPublic=function(e,t){if(this.isPublic=!0,this.isPrivate=!1,"string"!=typeof e)this.n=e,this.e=t;else{if(!(null!=e&&null!=t&&e.length>0&&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<e.length+11)throw"Message too long for RSA";for(var r=new Array,n=e.length-1;n>=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 s=new ee,o=new Array;t>2;){for(o[0]=0;0==o[0];)s.nextBytes(o);r[--t]=o[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=ue.crypto.MessageDigest,s=ue.crypto.Util,o=null;if(r||(r="sha1"),"string"==typeof r&&(o=i.getCanonicalAlgName(r),n=i.getHashLength(o),r=function(e){return Se(s.hashHex(Ee(e),o))}),e.length+2*n+2>t)throw"Message too long for RSA";var a,u="";for(a=0;a<t-e.length-2*n-2;a+=1)u+="\0";var c=r("")+u+""+e,h=new Array(n);(new ee).nextBytes(h);var l=re(h,c.length,r),d=[];for(a=0;a<c.length;a+=1)d[a]=c.charCodeAt(a)^l.charCodeAt(a);var f=re(d,h.length,r),p=[0];for(a=0;a<h.length;a+=1)p[a+1]=h[a]^f.charCodeAt(a);return new S(p.concat(d))}(e,this.n.bitLength()+7>>3,t,r);if(null==n)return null;var i=this.doPublic(n);if(null==i)return null;var s=i.toString(16);return 1&s.length?"0"+s:s},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))},se.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))},se.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))},se.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))},se.prototype.isInfinity=function(){return null==this.x&&null==this.y||this.z.equals(S.ZERO)&&!this.y.toBigInteger().equals(S.ZERO)},se.prototype.negate=function(){return new se(this.curve,this.x,this.y.negate(),this.z)},se.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(),s=this.y.toBigInteger(),o=(e.x.toBigInteger(),e.y.toBigInteger(),r.square()),a=o.multiply(r),u=i.multiply(o),c=t.square().multiply(this.z),h=c.subtract(u.shiftLeft(1)).multiply(e.z).subtract(a).multiply(r).mod(this.curve.q),l=u.multiply(n).multiply(t).subtract(s.multiply(a)).subtract(c.multiply(t)).multiply(e.z).add(t.multiply(a)).mod(this.curve.q),d=a.multiply(this.z).multiply(e.z).mod(this.curve.q);return new se(this.curve,this.curve.fromBigInteger(h),this.curve.fromBigInteger(l),d)},se.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),s=this.curve.a.toBigInteger(),o=t.square().multiply(e);S.ZERO.equals(s)||(o=o.add(this.z.square().multiply(s)));var a=(o=o.mod(this.curve.q)).square().subtract(t.shiftLeft(3).multiply(i)).shiftLeft(1).multiply(n).mod(this.curve.q),u=o.multiply(e).multiply(t).subtract(i.shiftLeft(1)).shiftLeft(2).multiply(i).subtract(o.square().multiply(o)).mod(this.curve.q),c=n.square().multiply(n).shiftLeft(3).mod(this.curve.q);return new se(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(u),c)},se.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(),s=this,o=this.curve.q.subtract(e),a=o.multiply(new S("3")),u=new se(this.curve,this.x,this.y),c=u.negate();for(t=n.bitLength()-2;t>0;--t){s=s.twice();var h=n.testBit(t);h!=r.testBit(t)&&(s=s.add(h?this:i))}for(t=a.bitLength()-2;t>0;--t){u=u.twice();var l=a.testBit(t);l!=o.testBit(t)&&(u=u.add(l?u:c))}return s},se.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(),s=this.add(t);n>=0;)i=i.twice(),e.testBit(n)?i=r.testBit(n)?i.add(s):i.add(this):r.testBit(n)&&(i=i.add(t)),--n;return i},oe.prototype.getQ=function(){return this.q},oe.prototype.getA=function(){return this.a},oe.prototype.getB=function(){return this.b},oe.prototype.equals=function(e){return e==this||this.q.equals(e.q)&&this.a.equals(e.a)&&this.b.equals(e.b)},oe.prototype.getInfinity=function(){return this.infinity},oe.prototype.fromBigInteger=function(e){return new ie(this.q,e)},oe.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 se(this,this.fromBigInteger(new S(r,16)),this.fromBigInteger(new S(n,16)))}},
16
+ */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?b.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;t<e.length;++t)e[t]=Z()},ne.prototype.doPublic=function(e){return e.modPowInt(this.e,this.n)},ne.prototype.setPublic=function(e,t){if(this.isPublic=!0,this.isPrivate=!1,"string"!=typeof e)this.n=e,this.e=t;else{if(!(null!=e&&null!=t&&e.length>0&&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<e.length+11)throw"Message too long for RSA";for(var r=new Array,n=e.length-1;n>=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 b(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=ue.crypto.MessageDigest,o=ue.crypto.Util,s=null;if(r||(r="sha1"),"string"==typeof r&&(s=i.getCanonicalAlgName(r),n=i.getHashLength(s),r=function(e){return be(o.hashHex(Ee(e),s))}),e.length+2*n+2>t)throw"Message too long for RSA";var a,u="";for(a=0;a<t-e.length-2*n-2;a+=1)u+="\0";var c=r("")+u+""+e,h=new Array(n);(new ee).nextBytes(h);var l=re(h,c.length,r),d=[];for(a=0;a<c.length;a+=1)d[a]=c.charCodeAt(a)^l.charCodeAt(a);var f=re(d,h.length,r),p=[0];for(a=0;a<h.length;a+=1)p[a+1]=h[a]^f.charCodeAt(a);return new b(p.concat(d))}(e,this.n.bitLength()+7>>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(b.ZERO)&&e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(b.ZERO))},oe.prototype.isInfinity=function(){return null==this.x&&null==this.y||this.z.equals(b.ZERO)&&!this.y.toBigInteger().equals(b.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(b.ZERO.equals(r))return b.ZERO.equals(t)?this.twice():this.curve.getInfinity();var n=new b("3"),i=this.x.toBigInteger(),o=this.y.toBigInteger(),s=(e.x.toBigInteger(),e.y.toBigInteger(),r.square()),a=s.multiply(r),u=i.multiply(s),c=t.square().multiply(this.z),h=c.subtract(u.shiftLeft(1)).multiply(e.z).subtract(a).multiply(r).mod(this.curve.q),l=u.multiply(n).multiply(t).subtract(o.multiply(a)).subtract(c.multiply(t)).multiply(e.z).add(t.multiply(a)).mod(this.curve.q),d=a.multiply(this.z).multiply(e.z).mod(this.curve.q);return new oe(this.curve,this.curve.fromBigInteger(h),this.curve.fromBigInteger(l),d)},oe.prototype.twice=function(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=new b("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);b.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),u=s.multiply(e).multiply(t).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 oe(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(u),c)},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 b("3")),i=this.negate(),o=this,s=this.curve.q.subtract(e),a=s.multiply(new b("3")),u=new oe(this.curve,this.x,this.y),c=u.negate();for(t=n.bitLength()-2;t>0;--t){o=o.twice();var h=n.testBit(t);h!=r.testBit(t)&&(o=o.add(h?this:i))}for(t=a.bitLength()-2;t>0;--t){u=u.twice();var l=a.testBit(t);l!=s.testBit(t)&&(u=u.add(l?u:c))}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 b(r,16)),this.fromBigInteger(new b(n,16)))}},
19
17
  /*! (c) Stefan Thomas | https://github.com/bitcoinjs/bitcoinjs-lib
20
18
  */
21
- ie.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)},se.prototype.getEncoded=function(e){var t=function(e,t){var r=e.toByteArrayUnsigned();if(t<r.length)r=r.slice(r.length-t);else for(;t>r.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},se.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 s=new S(n),o=new S(i);return new se(e,e.fromBigInteger(s),e.fromBigInteger(o))},se.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),s=new S(n,16),o=new S(i,16);return new se(e,e.fromBigInteger(s),e.fromBigInteger(o))},se.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 se(this.curve,n,i)},se.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 se(this.curve,n,i)},se.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(),s=this;for(t=n.bitLength()-2;t>0;--t){s=s.twice();var o=n.testBit(t);o!=r.testBit(t)&&(s=s.add2D(o?this:i))}return s},se.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(),s=t.multiply(t).mod(i),o=e.multiply(e).multiply(e).add(r.multiply(e)).add(n).mod(i);return s.equals(o)},se.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"},se.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};
19
+ 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(t<r.length)r=r.slice(r.length-t);else for(;t>r.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 b(n),s=new b(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 b(n,16),s=new b(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(b.valueOf(2)),t=this.curve.fromBigInteger(b.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 b("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(b.ONE)<0||t.compareTo(e.subtract(b.ONE))>0)throw new Error("x coordinate out of bounds");if(r.compareTo(b.ONE)<0||r.compareTo(e.subtract(b.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};
22
20
  /*! Mike Samuel (c) 2009 | code.google.com/p/json-sans-eval
23
21
  */
24
- 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(""),s=Object.hasOwnProperty;return function(r,o){var a,u,c=r.match(e),h=c[0],l=!1;"{"===h?a={}:"["===h?a=[]:(a=[],l=!0);for(var d=[a],p=1-l,g=c.length;p<g;++p){var y;switch((h=c[p]).charCodeAt(0)){default:(y=d[0])[u||y.length]=+h,u=void 0;break;case 34:if(-1!==(h=h.substring(1,h.length-1)).indexOf("\\")&&(h=h.replace(t,n)),y=d[0],!u){if(!(y instanceof Array)){u=h||i;break}u=y.length}y[u]=h,u=void 0;break;case 91:y=d[0],d.unshift(y[u||y.length]=[]),u=void 0;break;case 93:case 125:d.shift();break;case 102:(y=d[0])[u||y.length]=!1,u=void 0;break;case 110:(y=d[0])[u||y.length]=null,u=void 0;break;case 116:(y=d[0])[u||y.length]=!0,u=void 0;break;case 123:y=d[0],d.unshift(y[u||y.length]={}),u=void 0}}if(l){if(1!==d.length)throw new Error;a=a[0]}else if(d.length)throw new Error;return o&&(a=function e(t,r){var n=t[r];if(n&&"object"===(void 0===n?"undefined":f(n))){var i=null;for(var a in n)if(s.call(n,a)&&n!==t){var u=e(n,a);void 0!==u?n[a]=u:(i||(i=[]),i.push(a))}if(i)for(var c=i.length;--c>=0;)delete n[i[c]]}return o.call(t,r,n)}({"":a},"")),a}}();void 0!==ue&&ue||(t.KJUR=ue={}),void 0!==ue.asn1&&ue.asn1||(ue.asn1={}),ue.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;i<r;i++)n+="f";t=new S(n,16).xor(e).add(S.ONE).toString(16).replace(/^-/,"")}return t},this.getPEMStringFromHex=function(e,t){return Te(e,t)},this.newObject=function(e){var t=ue.asn1,r=t.ASN1Object,n=t.DERBoolean,i=t.DERInteger,s=t.DERBitString,o=t.DEROctetString,a=t.DERNull,u=t.DERObjectIdentifier,c=t.DEREnumerated,h=t.DERUTF8String,l=t.DERNumericString,d=t.DERPrintableString,f=t.DERTeletexString,p=t.DERIA5String,g=t.DERUTCTime,y=t.DERGeneralizedTime,v=t.DERVisibleString,m=t.DERBMPString,w=t.DERSequence,b=t.DERSet,_=t.DERTaggedObject,S=t.ASN1Util.newObject;if(e instanceof t.ASN1Object)return e;var E=Object.keys(e);if(1!=E.length)throw new Error("key of param shall be only one.");var x=E[0];if(-1==":asn1:bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:visstr:bmpstr:seq:set:tag:".indexOf(":"+x+":"))throw new Error("undefined key: "+x);if("bool"==x)return new n(e[x]);if("int"==x)return new i(e[x]);if("bitstr"==x)return new s(e[x]);if("octstr"==x)return new o(e[x]);if("null"==x)return new a(e[x]);if("oid"==x)return new u(e[x]);if("enum"==x)return new c(e[x]);if("utf8str"==x)return new h(e[x]);if("numstr"==x)return new l(e[x]);if("prnstr"==x)return new d(e[x]);if("telstr"==x)return new f(e[x]);if("ia5str"==x)return new p(e[x]);if("utctime"==x)return new g(e[x]);if("gentime"==x)return new y(e[x]);if("visstr"==x)return new v(e[x]);if("bmpstr"==x)return new m(e[x]);if("asn1"==x)return new r(e[x]);if("seq"==x){for(var A=e[x],F=[],T=0;T<A.length;T++){var k=S(A[T]);F.push(k)}return new w({array:F})}if("set"==x){for(A=e[x],F=[],T=0;T<A.length;T++)k=S(A[T]),F.push(k);return new b({array:F})}if("tag"==x){var I=e[x];if("[object Array]"===Object.prototype.toString.call(I)&&3==I.length){var C=S(I[2]);return new _({tag:I[0],explicit:I[1],obj:C})}return new _(I)}},this.jsonToASN1HEX=function(e){return this.newObject(e).getEncodedHex()}},ue.asn1.ASN1Util.oidHexToInt=function(e){for(var t="",r=parseInt(e.substr(0,2),16),n=(t=Math.floor(r/40)+"."+r%40,""),i=2;i<e.length;i+=2){var s=("00000000"+parseInt(e.substr(i,2),16).toString(2)).slice(-8);n+=s.substr(1,7),"0"==s.substr(0,1)&&(t=t+"."+new S(n,2).toString(10),n="")}return t},ue.asn1.ASN1Util.oidIntToHex=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},r=function(e){var r="",n=new S(e,10).toString(2),i=7-n.length%7;7==i&&(i=0);for(var s="",o=0;o<i;o++)s+="0";for(n=s+n,o=0;o<n.length-1;o+=7){var a=n.substr(o,7);o!=n.length-7&&(a="1"+a),r+=t(parseInt(a,2))}return r};if(!e.match(/^[0-9.]+$/))throw"malformed oid string: "+e;var n="",i=e.split("."),s=40*parseInt(i[0])+parseInt(i[1]);n+=t(s),i.splice(0,2);for(var o=0;o<i.length;o++)n+=r(i[o]);return n},ue.asn1.ASN1Object=function(e){this.params=null,this.getLengthHexFromValue=function(){if(void 0===this.hV||null==this.hV)throw new Error("this.hV is null or undefined");if(this.hV.length%2==1)throw new Error("value hex must be even length: n=0,v="+this.hV);var e=this.hV.length/2,t=e.toString(16);if(t.length%2==1&&(t="0"+t),e<128)return t;var r=t.length/2;if(r>15)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)},ue.asn1.DERAbstractString=function(e){ue.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=be(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(ue.asn1.DERAbstractString,ue.asn1.ASN1Object),ue.asn1.DERAbstractTime=function(e){ue.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),s=String(i.getFullYear());"utc"==t&&(s=s.substr(2,2));var o=s+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);o=o+"."+(u=u.replace(/[0]+$/,""))}}return o+"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,s){var o=new Date(Date.UTC(e,t-1,r,n,i,s,0));this.setByDate(o)},this.getFreshValueHex=function(){return this.hV}},He(ue.asn1.DERAbstractTime,ue.asn1.ASN1Object),ue.asn1.DERAbstractStructured=function(e){ue.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(ue.asn1.DERAbstractStructured,ue.asn1.ASN1Object),ue.asn1.DERBoolean=function(e){ue.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=0==e?"010100":"0101ff"},He(ue.asn1.DERBoolean,ue.asn1.ASN1Object),ue.asn1.DERInteger=function(e){ue.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=ue.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(ue.asn1.DERInteger,ue.asn1.ASN1Object),ue.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=ue.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.getEncodedHex()}ue.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||7<e)throw"unused bits shall be from 0 to 7: u = "+e;var r="0"+e;this.hTLV=null,this.isModified=!0,this.hV=r+t},this.setByBinaryString=function(e){var t=8-(e=e.replace(/0+$/,"")).length%8;8==t&&(t=0);for(var r=0;r<=t;r++)e+="0";var n="";for(r=0;r<e.length-1;r+=8){var i=e.substr(r,8),s=parseInt(i,2).toString(16);1==s.length&&(s="0"+s),n+=s}this.hTLV=null,this.isModified=!0,this.hV="0"+t+n},this.setByBooleanArray=function(e){for(var t="",r=0;r<e.length;r++)1==e[r]?t+="1":t+="0";this.setByBinaryString(t)},this.newFalseArray=function(e){for(var t=new Array(e),r=0;r<e;r++)t[r]=!1;return t},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e&&e.toLowerCase().match(/^[0-9a-f]+$/)?this.setHexValueIncludingUnusedBits(e):void 0!==e.hex?this.setHexValueIncludingUnusedBits(e.hex):void 0!==e.bin?this.setByBinaryString(e.bin):void 0!==e.array&&this.setByBooleanArray(e.array))},He(ue.asn1.DERBitString,ue.asn1.ASN1Object),ue.asn1.DEROctetString=function(e){if(void 0!==e&&void 0!==e.obj){var t=ue.asn1.ASN1Util.newObject(e.obj);e.hex=t.getEncodedHex()}ue.asn1.DEROctetString.superclass.constructor.call(this,e),this.hT="04"},He(ue.asn1.DEROctetString,ue.asn1.DERAbstractString),ue.asn1.DERNull=function(){ue.asn1.DERNull.superclass.constructor.call(this),this.hT="05",this.hTLV="0500"},He(ue.asn1.DERNull,ue.asn1.ASN1Object),ue.asn1.DERObjectIdentifier=function(e){ue.asn1.DERObjectIdentifier.superclass.constructor.call(this),this.hT="06",this.setValueHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.setValueOidString=function(e){var t=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},r=function(e){var r="",n=parseInt(e,10).toString(2),i=7-n.length%7;7==i&&(i=0);for(var s="",o=0;o<i;o++)s+="0";for(n=s+n,o=0;o<n.length-1;o+=7){var a=n.substr(o,7);o!=n.length-7&&(a="1"+a),r+=t(parseInt(a,2))}return r};try{if(!e.match(/^[0-9.]+$/))return null;var n="",i=e.split("."),s=40*parseInt(i[0],10)+parseInt(i[1],10);n+=t(s),i.splice(0,2);for(var o=0;o<i.length;o++)n+=r(i[o]);return n}catch(e){return null}}(e);if(null==t)throw new Error("malformed oid string: "+e);this.hTLV=null,this.isModified=!0,this.s=null,this.hV=t},this.setValueName=function(e){var t=ue.asn1.x509.OID.name2oid(e);if(""===t)throw new Error("DERObjectIdentifier oidName undefined: "+e);this.setValueOidString(t)},this.setValueNameOrOid=function(e){e.match(/^[0-2].[0-9.]+$/)?this.setValueOidString(e):this.setValueName(e)},this.getFreshValueHex=function(){return this.hV},this.setByParam=function(e){"string"==typeof e?this.setValueNameOrOid(e):void 0!==e.oid?this.setValueNameOrOid(e.oid):void 0!==e.name?this.setValueNameOrOid(e.name):void 0!==e.hex&&this.setValueHex(e.hex)},void 0!==e&&this.setByParam(e)},He(ue.asn1.DERObjectIdentifier,ue.asn1.ASN1Object),ue.asn1.DEREnumerated=function(e){ue.asn1.DEREnumerated.superclass.constructor.call(this),this.hT="0a",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=ue.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.int?this.setByInteger(e.int):"number"==typeof e?this.setByInteger(e):void 0!==e.hex&&this.setValueHex(e.hex))},He(ue.asn1.DEREnumerated,ue.asn1.ASN1Object),ue.asn1.DERUTF8String=function(e){ue.asn1.DERUTF8String.superclass.constructor.call(this,e),this.hT="0c"},He(ue.asn1.DERUTF8String,ue.asn1.DERAbstractString),ue.asn1.DERNumericString=function(e){ue.asn1.DERNumericString.superclass.constructor.call(this,e),this.hT="12"},He(ue.asn1.DERNumericString,ue.asn1.DERAbstractString),ue.asn1.DERPrintableString=function(e){ue.asn1.DERPrintableString.superclass.constructor.call(this,e),this.hT="13"},He(ue.asn1.DERPrintableString,ue.asn1.DERAbstractString),ue.asn1.DERTeletexString=function(e){ue.asn1.DERTeletexString.superclass.constructor.call(this,e),this.hT="14"},He(ue.asn1.DERTeletexString,ue.asn1.DERAbstractString),ue.asn1.DERIA5String=function(e){ue.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="16"},He(ue.asn1.DERIA5String,ue.asn1.DERAbstractString),ue.asn1.DERVisibleString=function(e){ue.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="1a"},He(ue.asn1.DERVisibleString,ue.asn1.DERAbstractString),ue.asn1.DERBMPString=function(e){ue.asn1.DERBMPString.superclass.constructor.call(this,e),this.hT="1e"},He(ue.asn1.DERBMPString,ue.asn1.DERAbstractString),ue.asn1.DERUTCTime=function(e){ue.asn1.DERUTCTime.superclass.constructor.call(this,e),this.hT="17",this.setByDate=function(e){this.hTLV=null,this.isModified=!0,this.date=e,this.s=this.formatDate(this.date,"utc"),this.hV=ge(this.s)},this.getFreshValueHex=function(){return void 0===this.date&&void 0===this.s&&(this.date=new Date,this.s=this.formatDate(this.date,"utc"),this.hV=ge(this.s)),this.hV},void 0!==e&&(void 0!==e.str?this.setString(e.str):"string"==typeof e&&e.match(/^[0-9]{12}Z$/)?this.setString(e):void 0!==e.hex?this.setStringHex(e.hex):void 0!==e.date&&this.setByDate(e.date))},He(ue.asn1.DERUTCTime,ue.asn1.DERAbstractTime),ue.asn1.DERGeneralizedTime=function(e){ue.asn1.DERGeneralizedTime.superclass.constructor.call(this,e),this.hT="18",this.withMillis=!1,this.setByDate=function(e){this.hTLV=null,this.isModified=!0,this.date=e,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=ge(this.s)},this.getFreshValueHex=function(){return void 0===this.date&&void 0===this.s&&(this.date=new Date,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=ge(this.s)),this.hV},void 0!==e&&(void 0!==e.str?this.setString(e.str):"string"==typeof e&&e.match(/^[0-9]{14}Z$/)?this.setString(e):void 0!==e.hex?this.setStringHex(e.hex):void 0!==e.date&&this.setByDate(e.date),!0===e.millis&&(this.withMillis=!0))},He(ue.asn1.DERGeneralizedTime,ue.asn1.DERAbstractTime),ue.asn1.DERSequence=function(e){ue.asn1.DERSequence.superclass.constructor.call(this,e),this.hT="30",this.getFreshValueHex=function(){for(var e="",t=0;t<this.asn1Array.length;t++)e+=this.asn1Array[t].getEncodedHex();return this.hV=e,this.hV}},He(ue.asn1.DERSequence,ue.asn1.DERAbstractStructured),ue.asn1.DERSet=function(e){ue.asn1.DERSet.superclass.constructor.call(this,e),this.hT="31",this.sortFlag=!0,this.getFreshValueHex=function(){for(var e=new Array,t=0;t<this.asn1Array.length;t++){var r=this.asn1Array[t];e.push(r.getEncodedHex())}return 1==this.sortFlag&&e.sort(),this.hV=e.join(""),this.hV},void 0!==e&&void 0!==e.sortflag&&0==e.sortflag&&(this.sortFlag=!1)},He(ue.asn1.DERSet,ue.asn1.DERAbstractStructured),ue.asn1.DERTaggedObject=function(e){ue.asn1.DERTaggedObject.superclass.constructor.call(this);var t=ue.asn1;this.hT="a0",this.hV="",this.isExplicit=!0,this.asn1Object=null,this.setASN1Object=function(e,t,r){this.hT=t,this.isExplicit=e,this.asn1Object=r,this.isExplicit?(this.hV=this.asn1Object.getEncodedHex(),this.hTLV=null,this.isModified=!0):(this.hV=null,this.hTLV=r.getEncodedHex(),this.hTLV=this.hTLV.replace(/^../,t),this.isModified=!1)},this.getFreshValueHex=function(){return this.hV},this.setByParam=function(e){null!=e.tag&&(this.hT=e.tag),null!=e.explicit&&(this.isExplicit=e.explicit),null!=e.tage&&(this.hT=e.tage,this.isExplicit=!0),null!=e.tagi&&(this.hT=e.tagi,this.isExplicit=!1),null!=e.obj&&(e.obj instanceof t.ASN1Object?(this.asn1Object=e.obj,this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)):"object"==f(e.obj)&&(this.asn1Object=t.ASN1Util.newObject(e.obj),this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)))},null!=e&&this.setByParam(e)},He(ue.asn1.DERTaggedObject,ue.asn1.ASN1Object);var ue,ce,he,le=new function(){};function de(e){for(var t=new Array,r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function fe(e){for(var t="",r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}function pe(e){for(var t="",r=0;r<e.length;r++){var n=e[r].toString(16);1==n.length&&(n="0"+n),t+=n}return t}function ge(e){return pe(de(e))}function ye(e){return(e=(e=e.replace(/\=/g,"")).replace(/\+/g,"-")).replace(/\//g,"_")}function ve(e){return e.length%4==2?e+="==":e.length%4==3&&(e+="="),(e=e.replace(/-/g,"+")).replace(/_/g,"/")}function me(e){return e.length%2==1&&(e="0"+e),ye(w(e))}function we(e){return b(ve(e))}function be(e){return Re(De(e))}function _e(e){return decodeURIComponent(Pe(e))}function Se(e){for(var t="",r=0;r<e.length-1;r+=2)t+=String.fromCharCode(parseInt(e.substr(r,2),16));return t}function Ee(e){for(var t="",r=0;r<e.length;r++)t+=("0"+e.charCodeAt(r).toString(16)).slice(-2);return t}function xe(e){return w(e)}function Ae(e){var t=xe(e).replace(/(.{64})/g,"$1\r\n");return t.replace(/\r\n$/,"")}function Fe(e){return b(e.replace(/[^0-9A-Za-z\/+=]*/g,""))}function Te(e,t){return"-----BEGIN "+t+"-----\r\n"+Ae(e)+"\r\n-----END "+t+"-----\r\n"}function ke(e,t){if(-1==e.indexOf("-----BEGIN "))throw"can't find PEM header: "+t;return Fe(e=void 0!==t?(e=e.replace(new RegExp("^[^]*-----BEGIN "+t+"-----"),"")).replace(new RegExp("-----END "+t+"-----[^]*$"),""):(e=e.replace(/^[^]*-----BEGIN [^-]+-----/,"")).replace(/-----END [^-]+-----[^]*$/,""))}function Ie(e){var t,r,n,i,s,o,a,u,c,h,l;if(l=e.match(/^(\d{2}|\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/))return u=l[1],t=parseInt(u),2===u.length&&(50<=t&&t<100?t=1900+t:0<=t&&t<50&&(t=2e3+t)),r=parseInt(l[2])-1,n=parseInt(l[3]),i=parseInt(l[4]),s=parseInt(l[5]),o=parseInt(l[6]),a=0,""!==(c=l[7])&&(h=(c.substr(1)+"00").substr(0,3),a=parseInt(h)),Date.UTC(t,r,n,i,s,o,a);throw"unsupported zulu format: "+e}function Ce(e){return~~(Ie(e)/1e3)}function Re(e){return e.replace(/%/g,"")}function Pe(e){return e.replace(/(..)/g,"%$1")}function Ne(e){var t="malformed IPv6 address";if(!e.match(/^[0-9A-Fa-f:]+$/))throw t;var r=(e=e.toLowerCase()).split(":").length-1;if(r<2)throw t;var n=":".repeat(7-r+2),i=(e=e.replace("::",n)).split(":");if(8!=i.length)throw t;for(var s=0;s<8;s++)i[s]=("0000"+i[s]).slice(-4);return i.join("")}function Ue(e){if(!e.match(/^[0-9A-Fa-f]{32}$/))throw"malformed IPv6 address octet";for(var t=(e=e.toLowerCase()).match(/.{1,4}/g),r=0;r<8;r++)t[r]=t[r].replace(/^0+/,""),""==t[r]&&(t[r]="0");var n=(e=":"+t.join(":")+":").match(/:(0:){2,}/g);if(null===n)return e.slice(1,-1);var i="";for(r=0;r<n.length;r++)n[r].length>i.length&&(i=n[r]);return(e=e.replace(i,"::")).slice(1,-1)}function Oe(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?Ue(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 De(e){for(var t=encodeURIComponent(e),r="",n=0;n<t.length;n++)"%"==t[n]?(r+=t.substr(n,3),n+=2):r=r+"%"+ge(t[n]);return r}function je(e){return!(e.length%2!=0||!e.match(/^[0-9a-f]+$/)&&!e.match(/^[0-9A-F]+$/))}function Me(e){return e.length%2==1?"0"+e:e.substr(0,1)>"7"?"00"+e:e}le.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<r&&r<10?r+1:-2},le.getL=function(e,t){var r=le.getLblen(e,t);return r<1?"":e.substr(t+2,2*r)},le.getVblen=function(e,t){var r;return""==(r=le.getL(e,t))?-1:("8"===r.substr(0,1)?new S(r.substr(2),16):new S(r,16)).intValue()},le.getVidx=function(e,t){var r=le.getLblen(e,t);return r<0?r:t+2*(r+1)},le.getV=function(e,t){var r=le.getVidx(e,t),n=le.getVblen(e,t);return e.substr(r,2*n)},le.getTLV=function(e,t){return e.substr(t,2)+le.getL(e,t)+le.getV(e,t)},le.getTLVblen=function(e,t){return 2+2*le.getLblen(e,t)+2*le.getVblen(e,t)},le.getNextSiblingIdx=function(e,t){return le.getVidx(e,t)+2*le.getVblen(e,t)},le.getChildIdx=function(e,t){var r,n,i,s=le,o=[];r=s.getVidx(e,t),n=2*s.getVblen(e,t),"03"==e.substr(t,2)&&(r+=2,n-=2),i=0;for(var a=r;i<=n;){var u=s.getTLVblen(e,a);if((i+=u)<=n&&o.push(a),a+=u,i>=n)break}return o},le.getNthChildIdx=function(e,t,r){return le.getChildIdx(e,t)[r]},le.getIdxbyList=function(e,t,r,n){var i,s,o=le;return 0==r.length?void 0!==n&&e.substr(t,2)!==n?-1:t:(i=r.shift())>=(s=o.getChildIdx(e,t)).length?-1:o.getIdxbyList(e,s[i],r,n)},le.getIdxbyListEx=function(e,t,r,n){var i,s,o=le;if(0==r.length)return void 0!==n&&e.substr(t,2)!==n?-1:t;i=r.shift(),s=o.getChildIdx(e,t);for(var a=0,u=0;u<s.length;u++){var c=e.substr(s[u],2);if("number"==typeof i&&!o.isContextTag(c)&&a==i||"string"==typeof i&&o.isContextTag(c,i))return o.getIdxbyListEx(e,s[u],r,n);o.isContextTag(c)||a++}return-1},le.getTLVbyList=function(e,t,r,n){var i=le,s=i.getIdxbyList(e,t,r,n);return-1==s||s>=e.length?null:i.getTLV(e,s)},le.getTLVbyListEx=function(e,t,r,n){var i=le,s=i.getIdxbyListEx(e,t,r,n);return-1==s?null:i.getTLV(e,s)},le.getVbyList=function(e,t,r,n,i){var s,o,a=le;return-1==(s=a.getIdxbyList(e,t,r,n))||s>=e.length?null:(o=a.getV(e,s),!0===i&&(o=o.substr(2)),o)},le.getVbyListEx=function(e,t,r,n,i){var s,o,a=le;return-1==(s=a.getIdxbyListEx(e,t,r,n))?null:(o=a.getV(e,s),"03"==e.substr(s,2)&&!1!==i&&(o=o.substr(2)),o)},le.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=le.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}},le.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),s=[],o=0;o<i.length/2;o++)s.push(parseInt(i.substr(2*o,2),16));var a=[],u="";for(o=0;o<s.length;o++)128&s[o]?u+=Be((127&s[o]).toString(2),7):(u+=Be((127&s[o]).toString(2),7),a.push(new String(parseInt(u,2))),u="");var c=t.join(".");return a.length>0&&(c=c+"."+a.join(".")),c}catch(e){return null}}(le.getV(e,t))}catch(e){return r}},le.getOIDName=function(e,t,r){null==r&&(r=null);try{var n=le.getOID(e,t,r);if(n==r)return r;var i=ue.asn1.x509.OID.oid2name(n);return""==i?n:i}catch(e){return r}},le.getString=function(e,t,r){null==r&&(r=null);try{return Se(le.getV(e,t))}catch(e){return r}},le.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 s=e.substr(2),o=[],a=0;a<s.length/2;a++)o.push(parseInt(s.substr(2*a,2),16));var u=[],c="";for(a=0;a<o.length;a++)128&o[a]?c+=t((127&o[a]).toString(2),7):(c+=t((127&o[a]).toString(2),7),u.push(new String(parseInt(c,2))),c="");var h=r.join(".");return u.length>0&&(h=h+"."+u.join(".")),h},le.dump=function(e,t,r,n){var i=le,s=i.getV,o=i.dump,a=i.getChildIdx,u=e;e instanceof ue.asn1.ASN1Object&&(u=e.getEncodedHex());var c=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 h,l=t.ommit_long_octet;if("01"==(h=u.substr(r,2)))return"00"==(d=s(u,r))?n+"BOOLEAN FALSE\n":n+"BOOLEAN TRUE\n";if("02"==h)return n+"INTEGER "+c(d=s(u,r),l)+"\n";if("03"==h){var d=s(u,r);return i.isASN1HEX(d.substr(2))?(_=n+"BITSTRING, encapsulates\n")+o(d.substr(2),t,0,n+" "):n+"BITSTRING "+c(d,l)+"\n"}if("04"==h)return d=s(u,r),i.isASN1HEX(d)?(_=n+"OCTETSTRING, encapsulates\n")+o(d,t,0,n+" "):n+"OCTETSTRING "+c(d,l)+"\n";if("05"==h)return n+"NULL\n";if("06"==h){var f=s(u,r),p=ue.asn1.ASN1Util.oidHexToInt(f),g=ue.asn1.x509.OID.oid2name(p),y=p.replace(/\./g," ");return""!=g?n+"ObjectIdentifier "+g+" ("+y+")\n":n+"ObjectIdentifier ("+y+")\n"}if("0a"==h)return n+"ENUMERATED "+parseInt(s(u,r))+"\n";if("0c"==h)return n+"UTF8String '"+_e(s(u,r))+"'\n";if("13"==h)return n+"PrintableString '"+_e(s(u,r))+"'\n";if("14"==h)return n+"TeletexString '"+_e(s(u,r))+"'\n";if("16"==h)return n+"IA5String '"+_e(s(u,r))+"'\n";if("17"==h)return n+"UTCTime "+_e(s(u,r))+"\n";if("18"==h)return n+"GeneralizedTime "+_e(s(u,r))+"\n";if("1a"==h)return n+"VisualString '"+_e(s(u,r))+"'\n";if("1e"==h)return n+"BMPString '"+Le(s(u,r))+"'\n";if("30"==h){if("3000"==u.substr(r,4))return n+"SEQUENCE {}\n";_=n+"SEQUENCE\n";var v=t;if((2==(b=a(u,r)).length||3==b.length)&&"06"==u.substr(b[0],2)&&"04"==u.substr(b[b.length-1],2)){g=i.oidname(s(u,b[0]));var m=JSON.parse(JSON.stringify(t));m.x509ExtName=g,v=m}for(var w=0;w<b.length;w++)_+=o(u,v,b[w],n+" ");return _}if("31"==h){_=n+"SET\n";var b=a(u,r);for(w=0;w<b.length;w++)_+=o(u,t,b[w],n+" ");return _}if(128&(h=parseInt(h,16))){var _,S=31&h;if(32&h){for(_=n+"["+S+"]\n",b=a(u,r),w=0;w<b.length;w++)_+=o(u,t,b[w],n+" ");return _}return d=s(u,r),le.isASN1HEX(d)?(_=n+"["+S+"]\n")+o(d,t,0,n+" "):(("68747470"==d.substr(0,8)||"subjectAltName"===t.x509ExtName&&2==S)&&(d=_e(d)),n+"["+S+"] "+d+"\n")}return n+"UNKNOWN("+h+") "+s(u,r)+"\n"},le.isContextTag=function(e,t){var r,n;e=e.toLowerCase();try{r=parseInt(e,16)}catch(e){return-1}if(void 0===t)return 128==(192&r);try{return null!=t.match(/^\[[0-9]+\]$/)&&!((n=parseInt(t.substr(1,t.length-1),10))>31)&&128==(192&r)&&(31&r)==n}catch(e){return!1}},le.isASN1HEX=function(e){var t=le;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},le.checkStrictDER=function(e,t,r,n,i){var s=le;if(void 0===r){if("string"!=typeof e)throw new Error("not hex string");if(e=e.toLowerCase(),!ue.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(s.getL(e,t).length>2*i)throw new Error("L of TLV too long: idx="+t);var o=s.getVblen(e,t);if(o>n)throw new Error("value of L too long than hex: idx="+t);var a=s.getTLV(e,t),u=a.length-2-s.getL(e,t).length;if(u!==2*o)throw new Error("V string length and L's value not the same:"+u+"/"+2*o);if(0===t&&e.length!=a.length)throw new Error("total length and TLV length unmatch:"+e.length+"!="+a.length);var c=e.substr(t,2);if("02"===c){var h=s.getVidx(e,t);if("00"==e.substr(h,2)&&e.charCodeAt(h+2)<56)throw new Error("not least zeros for DER INTEGER")}if(32&parseInt(c,16)){for(var l=s.getVblen(e,t),d=0,f=s.getChildIdx(e,t),p=0;p<f.length;p++)d+=s.getTLV(e,f[p]).length,s.checkStrictDER(e,f[p],r,n,i);if(2*l!=d)throw new Error("sum of children's TLV length and L unmatch: "+2*l+"!="+d)}},le.oidname=function(e){var t=ue.asn1;ue.lang.String.isHex(e)&&(e=t.ASN1Util.oidHexToInt(e));var r=t.x509.OID.oid2name(e);return""===r&&(r=e),r},void 0!==ue&&ue||(t.KJUR=ue={}),void 0!==ue.lang&&ue.lang||(ue.lang={}),ue.lang.String=function(){},"function"==typeof e?(t.utf8tob64u=ce=function(t){return ye(e.from(t,"utf8").toString("base64"))},t.b64utoutf8=he=function(t){return e.from(ve(t),"base64").toString("utf8")}):(t.utf8tob64u=ce=function(e){return me(Re(De(e)))},t.b64utoutf8=he=function(e){return decodeURIComponent(Pe(we(e)))}),ue.lang.String.isInteger=function(e){return!!e.match(/^[0-9]+$/)||!!e.match(/^-[0-9]+$/)},ue.lang.String.isHex=function(e){return je(e)},ue.lang.String.isBase64=function(e){return!(!(e=e.replace(/\s+/g,"")).match(/^[0-9A-Za-z+\/]+={0,3}$/)||e.length%4!=0)},ue.lang.String.isBase64URL=function(e){return!e.match(/[+/=]/)&&(e=ve(e),ue.lang.String.isBase64(e))},ue.lang.String.isIntegerArray=function(e){return!!(e=e.replace(/\s+/g,"")).match(/^\[[0-9,]+\]$/)},ue.lang.String.isPrintable=function(e){return null!==e.match(/^[0-9A-Za-z '()+,-./:=?]*$/)},ue.lang.String.isIA5=function(e){return null!==e.match(/^[\x20-\x21\x23-\x7f]*$/)},ue.lang.String.isMail=function(e){return null!==e.match(/^[A-Za-z0-9]{1}[A-Za-z0-9_.-]*@{1}[A-Za-z0-9_.-]{1,}\.[A-Za-z0-9]{1,}$/)};var Be=function(e,t,r){return null==r&&(r="0"),e.length>=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!==ue&&ue||(t.KJUR=ue={}),void 0!==ue.crypto&&ue.crypto||(ue.crypto={}),ue.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 s="0001",o="00"+n,a="",u=i-4-o.length,c=0;c<u;c+=2)a+="ff";return s+a+o},this.hashString=function(e,t){return new ue.crypto.MessageDigest({alg:t}).digestString(e)},this.hashHex=function(e,t){return new ue.crypto.MessageDigest({alg:t}).digestHex(e)},this.sha1=function(e){return this.hashString(e,"sha1")},this.sha256=function(e){return this.hashString(e,"sha256")},this.sha256Hex=function(e){return this.hashHex(e,"sha256")},this.sha512=function(e){return this.hashString(e,"sha512")},this.sha512Hex=function(e){return this.hashHex(e,"sha512")},this.isKey=function(e){return e instanceof ne||e instanceof ue.crypto.DSA||e instanceof ue.crypto.ECDSA}},ue.crypto.Util.md5=function(e){return new ue.crypto.MessageDigest({alg:"md5",prov:"cryptojs"}).digestString(e)},ue.crypto.Util.ripemd160=function(e){return new ue.crypto.MessageDigest({alg:"ripemd160",prov:"cryptojs"}).digestString(e)},ue.crypto.Util.SECURERANDOMGEN=new ee,ue.crypto.Util.getRandomHexOfNbytes=function(e){var t=new Array(e);return ue.crypto.Util.SECURERANDOMGEN.nextBytes(t),pe(t)},ue.crypto.Util.getRandomBigIntegerOfNbytes=function(e){return new S(ue.crypto.Util.getRandomHexOfNbytes(e),16)},ue.crypto.Util.getRandomHexOfNbits=function(e){var t=e%8,r=new Array((e-t)/8+1);return ue.crypto.Util.SECURERANDOMGEN.nextBytes(r),r[0]=(255<<t&255^255)&r[0],pe(r)},ue.crypto.Util.getRandomBigIntegerOfNbits=function(e){return new S(ue.crypto.Util.getRandomHexOfNbits(e),16)},ue.crypto.Util.getRandomBigIntegerZeroToMax=function(e){for(var t=e.bitLength();;){var r=ue.crypto.Util.getRandomBigIntegerOfNbits(t);if(-1!=e.compareTo(r))return r}},ue.crypto.Util.getRandomBigIntegerMinToMax=function(e,t){var r=e.compareTo(t);if(1==r)throw"biMin is greater than biMax";if(0==r)return e;var n=t.subtract(e);return ue.crypto.Util.getRandomBigIntegerZeroToMax(n).add(e)},ue.crypto.MessageDigest=function(e){this.setAlgAndProvider=function(e,t){if(null!==(e=ue.crypto.MessageDigest.getCanonicalAlgName(e))&&void 0===t&&(t=ue.crypto.Util.DEFAULTPROVIDER[e]),-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(e)&&"cryptojs"==t){try{this.md=ue.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[e].create()}catch(t){throw"setAlgAndProvider hash alg set fail alg="+e+"/"+t}this.updateString=function(e){this.md.update(e)},this.updateHex=function(e){var t=y.enc.Hex.parse(e);this.md.update(t)},this.digest=function(){return this.md.finalize().toString(y.enc.Hex)},this.digestString=function(e){return this.updateString(e),this.digest()},this.digestHex=function(e){return this.updateHex(e),this.digest()}}if(-1!=":sha256:".indexOf(e)&&"sjcl"==t){try{this.md=new sjcl.hash.sha256}catch(t){throw"setAlgAndProvider hash alg set fail alg="+e+"/"+t}this.updateString=function(e){this.md.update(e)},this.updateHex=function(e){var t=sjcl.codec.hex.toBits(e);this.md.update(t)},this.digest=function(){var e=this.md.finalize();return sjcl.codec.hex.fromBits(e)},this.digestString=function(e){return this.updateString(e),this.digest()},this.digestHex=function(e){return this.updateHex(e),this.digest()}}},this.updateString=function(e){throw"updateString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.updateHex=function(e){throw"updateHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digest=function(){throw"digest() not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestString=function(e){throw"digestString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestHex=function(e){throw"digestHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},void 0!==e&&void 0!==e.alg&&(this.algName=e.alg,void 0===e.prov&&(this.provName=ue.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName))},ue.crypto.MessageDigest.getCanonicalAlgName=function(e){return"string"==typeof e&&(e=(e=e.toLowerCase()).replace(/-/,"")),e},ue.crypto.MessageDigest.getHashLength=function(e){var t=ue.crypto.MessageDigest,r=t.getCanonicalAlgName(e);if(void 0===t.HASHLENGTH[r])throw"not supported algorithm: "+e;return t.HASHLENGTH[r]},ue.crypto.MessageDigest.HASHLENGTH={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,ripemd160:20},ue.crypto.Mac=function(e){this.setAlgAndProvider=function(e,t){if(null==(e=e.toLowerCase())&&(e="hmacsha1"),"hmac"!=(e=e.toLowerCase()).substr(0,4))throw"setAlgAndProvider unsupported HMAC alg: "+e;void 0===t&&(t=ue.crypto.Util.DEFAULTPROVIDER[e]),this.algProv=e+"/"+t;var r=e.substr(4);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(r)&&"cryptojs"==t){try{var n=ue.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[r];this.mac=y.algo.HMAC.create(n,this.pass)}catch(e){throw"setAlgAndProvider hash alg set fail hashAlg="+r+"/"+e}this.updateString=function(e){this.mac.update(e)},this.updateHex=function(e){var t=y.enc.Hex.parse(e);this.mac.update(t)},this.doFinal=function(){return this.mac.finalize().toString(y.enc.Hex)},this.doFinalString=function(e){return this.updateString(e),this.doFinal()},this.doFinalHex=function(e){return this.updateHex(e),this.doFinal()}}},this.updateString=function(e){throw"updateString(str) not supported for this alg/prov: "+this.algProv},this.updateHex=function(e){throw"updateHex(hex) not supported for this alg/prov: "+this.algProv},this.doFinal=function(){throw"digest() not supported for this alg/prov: "+this.algProv},this.doFinalString=function(e){throw"digestString(str) not supported for this alg/prov: "+this.algProv},this.doFinalHex=function(e){throw"digestHex(hex) not supported for this alg/prov: "+this.algProv},this.setPassword=function(e){if("string"==typeof e){var t=e;return e.length%2!=1&&e.match(/^[0-9A-Fa-f]+$/)||(t=Ee(e)),void(this.pass=y.enc.Hex.parse(t))}if("object"!=(void 0===e?"undefined":f(e)))throw"KJUR.crypto.Mac unsupported password type: "+e;if(t=null,void 0!==e.hex){if(e.hex.length%2!=0||!e.hex.match(/^[0-9A-Fa-f]+$/))throw"Mac: wrong hex password: "+e.hex;t=e.hex}if(void 0!==e.utf8&&(t=be(e.utf8)),void 0!==e.rstr&&(t=Ee(e.rstr)),void 0!==e.b64&&(t=b(e.b64)),void 0!==e.b64u&&(t=we(e.b64u)),null==t)throw"KJUR.crypto.Mac unsupported password type: "+e;this.pass=y.enc.Hex.parse(t)},void 0!==e&&(void 0!==e.pass&&this.setPassword(e.pass),void 0!==e.alg&&(this.algName=e.alg,void 0===e.prov&&(this.provName=ue.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName)))},ue.crypto.Signature=function(e){var t=null;if(this._setAlgNames=function(){var e=this.algName.match(/^(.+)with(.+)$/);e&&(this.mdAlgName=e[1].toLowerCase(),this.pubkeyAlgName=e[2].toLowerCase(),"rsaandmgf1"==this.pubkeyAlgName&&"sha"==this.mdAlgName&&(this.mdAlgName="sha1"))},this._zeroPaddingOfSignature=function(e,t){for(var r="",n=t/4-e.length,i=0;i<n;i++)r+="0";return r+e},this.setAlgAndProvider=function(e,t){if(this._setAlgNames(),"cryptojs/jsrsa"!=t)throw new Error("provider not supported: "+t);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(this.mdAlgName)){try{this.md=new ue.crypto.MessageDigest({alg:this.mdAlgName})}catch(e){throw new Error("setAlgAndProvider hash alg set fail alg="+this.mdAlgName+"/"+e)}this.init=function(e,t){var r=null;try{r=void 0===t?qe.getKey(e):qe.getKey(e,t)}catch(e){throw"init failed:"+e}if(!0===r.isPrivate)this.prvKey=r,this.state="SIGN";else{if(!0!==r.isPublic)throw"init failed.:"+r;this.pubKey=r,this.state="VERIFY"}},this.updateString=function(e){this.md.updateString(e)},this.updateHex=function(e){this.md.updateHex(e)},this.sign=function(){if(this.sHashHex=this.md.digest(),void 0===this.prvKey&&void 0!==this.ecprvhex&&void 0!==this.eccurvename&&void 0!==ue.crypto.ECDSA&&(this.prvKey=new ue.crypto.ECDSA({curve:this.eccurvename,prv:this.ecprvhex})),this.prvKey instanceof ne&&"rsaandmgf1"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHashPSS(this.sHashHex,this.mdAlgName,this.pssSaltLen);else if(this.prvKey instanceof ne&&"rsa"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex,this.mdAlgName);else if(this.prvKey instanceof ue.crypto.ECDSA)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex);else{if(!(this.prvKey instanceof ue.crypto.DSA))throw"Signature: unsupported private key alg: "+this.pubkeyAlgName;this.hSign=this.prvKey.signWithMessageHash(this.sHashHex)}return this.hSign},this.signString=function(e){return this.updateString(e),this.sign()},this.signHex=function(e){return this.updateHex(e),this.sign()},this.verify=function(e){if(this.sHashHex=this.md.digest(),void 0===this.pubKey&&void 0!==this.ecpubhex&&void 0!==this.eccurvename&&void 0!==ue.crypto.ECDSA&&(this.pubKey=new ue.crypto.ECDSA({curve:this.eccurvename,pub:this.ecpubhex})),this.pubKey instanceof ne&&"rsaandmgf1"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHashPSS(this.sHashHex,e,this.mdAlgName,this.pssSaltLen);if(this.pubKey instanceof ne&&"rsa"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);if(void 0!==ue.crypto.ECDSA&&this.pubKey instanceof ue.crypto.ECDSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);if(void 0!==ue.crypto.DSA&&this.pubKey instanceof ue.crypto.DSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);throw"Signature: unsupported public key alg: "+this.pubkeyAlgName}}},this.init=function(e,t){throw"init(key, pass) not supported for this alg:prov="+this.algProvName},this.updateString=function(e){throw"updateString(str) not supported for this alg:prov="+this.algProvName},this.updateHex=function(e){throw"updateHex(hex) not supported for this alg:prov="+this.algProvName},this.sign=function(){throw"sign() not supported for this alg:prov="+this.algProvName},this.signString=function(e){throw"digestString(str) not supported for this alg:prov="+this.algProvName},this.signHex=function(e){throw"digestHex(hex) not supported for this alg:prov="+this.algProvName},this.verify=function(e){throw"verify(hSigVal) not supported for this alg:prov="+this.algProvName},this.initParams=e,void 0!==e&&(void 0!==e.alg&&(this.algName=e.alg,void 0===e.prov?this.provName=ue.crypto.Util.DEFAULTPROVIDER[this.algName]:this.provName=e.prov,this.algProvName=this.algName+":"+this.provName,this.setAlgAndProvider(this.algName,this.provName),this._setAlgNames()),void 0!==e.psssaltlen&&(this.pssSaltLen=e.psssaltlen),void 0!==e.prvkeypem)){if(void 0!==e.prvkeypas)throw"both prvkeypem and prvkeypas parameters not supported";try{t=qe.getKey(e.prvkeypem),this.init(t)}catch(e){throw"fatal error to load pem private key: "+e}}},ue.crypto.Cipher=function(e){},ue.crypto.Cipher.encrypt=function(e,t,r){if(t instanceof ne&&t.isPublic){var n=ue.crypto.Cipher.getAlgByKeyAndName(t,r);if("RSA"===n)return t.encrypt(e);if("RSAOAEP"===n)return t.encryptOAEP(e,"sha1");var i=n.match(/^RSAOAEP(\d+)$/);if(null!==i)return t.encryptOAEP(e,"sha"+i[1]);throw"Cipher.encrypt: unsupported algorithm for RSAKey: "+r}throw"Cipher.encrypt: unsupported key or algorithm"},ue.crypto.Cipher.decrypt=function(e,t,r){if(t instanceof ne&&t.isPrivate){var n=ue.crypto.Cipher.getAlgByKeyAndName(t,r);if("RSA"===n)return t.decrypt(e);if("RSAOAEP"===n)return t.decryptOAEP(e,"sha1");var i=n.match(/^RSAOAEP(\d+)$/);if(null!==i)return t.decryptOAEP(e,"sha"+i[1]);throw"Cipher.decrypt: unsupported algorithm for RSAKey: "+r}throw"Cipher.decrypt: unsupported key or algorithm"},ue.crypto.Cipher.getAlgByKeyAndName=function(e,t){if(e instanceof ne){if(-1!=":RSA:RSAOAEP:RSAOAEP224:RSAOAEP256:RSAOAEP384:RSAOAEP512:".indexOf(t))return t;if(null==t)return"RSA";throw"getAlgByKeyAndName: not supported algorithm name for RSAKey: "+t}throw"getAlgByKeyAndName: not supported algorithm name: "+t},ue.crypto.OID=new function(){this.oidhex2name={"2a864886f70d010101":"rsaEncryption","2a8648ce3d0201":"ecPublicKey","2a8648ce380401":"dsa","2a8648ce3d030107":"secp256r1","2b8104001f":"secp192k1","2b81040021":"secp224r1","2b8104000a":"secp256k1","2b81040023":"secp521r1","2b81040022":"secp384r1","2a8648ce380403":"SHA1withDSA","608648016503040301":"SHA224withDSA","608648016503040302":"SHA256withDSA"}},void 0!==ue&&ue||(t.KJUR=ue={}),void 0!==ue.crypto&&ue.crypto||(ue.crypto={}),ue.crypto.ECDSA=function(e){var t=Error,r=S,n=se,i=ue.crypto.ECDSA,s=ue.crypto.ECParameterDB,o=i.getName,a=le,u=a.getVbyListEx,c=a.isASN1HEX,h=new ee;this.type="EC",this.isPrivate=!1,this.isPublic=!1,this.getBigRandom=function(e){return new r(e.bitLength(),h).mod(e.subtract(r.ONE)).add(r.ONE)},this.setNamedCurve=function(e){this.ecparams=s.getByName(e),this.prvKeyHex=null,this.pubKeyHex=null,this.curveName=e},this.setPrivateKeyHex=function(e){this.isPrivate=!0,this.prvKeyHex=e},this.setPublicKeyHex=function(e){this.isPublic=!0,this.pubKeyHex=e},this.getPublicKeyXYHex=function(){var e=this.pubKeyHex;if("04"!==e.substr(0,2))throw"this method supports uncompressed format(04) only";var t=this.ecparams.keylen/4;if(e.length!==2+2*t)throw"malformed public key hex length";var r={};return r.x=e.substr(2,t),r.y=e.substr(2+t),r},this.getShortNISTPCurveName=function(){var e=this.curveName;return"secp256r1"===e||"NIST P-256"===e||"P-256"===e||"prime256v1"===e?"P-256":"secp384r1"===e||"NIST P-384"===e||"P-384"===e?"P-384":null},this.generateKeyPairHex=function(){var e=this.ecparams.n,t=this.getBigRandom(e),r=this.ecparams.G.multiply(t),n=r.getX().toBigInteger(),i=r.getY().toBigInteger(),s=this.ecparams.keylen/4,o=("0000000000"+t.toString(16)).slice(-s),a="04"+("0000000000"+n.toString(16)).slice(-s)+("0000000000"+i.toString(16)).slice(-s);return this.setPrivateKeyHex(o),this.setPublicKeyHex(a),{ecprvhex:o,ecpubhex:a}},this.signWithMessageHash=function(e){return this.signHex(e,this.prvKeyHex)},this.signHex=function(e,t){var n=new r(t,16),s=this.ecparams.n,o=new r(e.substring(0,this.ecparams.keylen/4),16);do{var a=this.getBigRandom(s),u=this.ecparams.G.multiply(a).getX().toBigInteger().mod(s)}while(u.compareTo(r.ZERO)<=0);var c=a.modInverse(s).multiply(o.add(n.multiply(u))).mod(s);return i.biRSSigToASN1Sig(u,c)},this.sign=function(e,t){var n=t,i=this.ecparams.n,s=r.fromByteArrayUnsigned(e);do{var o=this.getBigRandom(i),a=this.ecparams.G.multiply(o).getX().toBigInteger().mod(i)}while(a.compareTo(S.ZERO)<=0);var u=o.modInverse(i).multiply(s.add(n.multiply(a))).mod(i);return this.serializeSig(a,u)},this.verifyWithMessageHash=function(e,t){return this.verifyHex(e,t,this.pubKeyHex)},this.verifyHex=function(e,t,s){try{var o,a,u=i.parseSigHex(t);o=u.r,a=u.s;var c=n.decodeFromHex(this.ecparams.curve,s),h=new r(e.substring(0,this.ecparams.keylen/4),16);return this.verifyRaw(h,o,a,c)}catch(e){return!1}},this.verify=function(e,t,i){var s,o,a;if(Bitcoin.Util.isArray(t)){var u=this.parseSig(t);s=u.r,o=u.s}else{if("object"!==(void 0===t?"undefined":f(t))||!t.r||!t.s)throw"Invalid value for signature";s=t.r,o=t.s}if(i instanceof se)a=i;else{if(!Bitcoin.Util.isArray(i))throw"Invalid format for pubkey value, must be byte array or ECPointFp";a=n.decodeFrom(this.ecparams.curve,i)}var c=r.fromByteArrayUnsigned(e);return this.verifyRaw(c,s,o,a)},this.verifyRaw=function(e,t,n,i){var s=this.ecparams.n,o=this.ecparams.G;if(t.compareTo(r.ONE)<0||t.compareTo(s)>=0)return!1;if(n.compareTo(r.ONE)<0||n.compareTo(s)>=0)return!1;var a=n.modInverse(s),u=e.multiply(a).mod(s),c=t.multiply(a).mod(s);return o.multiply(u).add(i.multiply(c)).getX().toBigInteger().mod(s).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===c(e))throw new Error("not ASN.1 hex string");var t,r,n;try{t=u(e,0,["[0]",0],"06"),r=u(e,0,[1],"04");try{n=u(e,0,["[1]",0],"03")}catch(e){}}catch(e){throw new Error("malformed PKCS#1/5 plain ECC private key")}if(this.curveName=o(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===c(e))throw new t("not ASN.1 hex string");var r,n,i;try{u(e,0,[1,0],"06"),r=u(e,0,[1,1],"06"),n=u(e,0,[2,0,1],"04");try{i=u(e,0,[2,0,"[1]",0],"03")}catch(e){}}catch(e){throw new t("malformed PKCS#8 plain ECC private key")}if(this.curveName=o(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===c(e))throw new t("not ASN.1 hex string");var r,n;try{u(e,0,[0,0],"06"),r=u(e,0,[0,1],"06"),n=u(e,0,[1],"03")}catch(e){throw new t("malformed PKCS#8 ECC public key")}if(this.curveName=o(r),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(n)},this.readCertPubKeyHex=function(e,r){if(!1===c(e))throw new t("not ASN.1 hex string");var n,i;try{n=u(e,0,[0,5,0,1],"06"),i=u(e,0,[0,5,1],"03")}catch(e){throw new t("malformed X.509 certificate ECC public key")}if(this.curveName=o(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))},ue.crypto.ECDSA.parseSigHex=function(e){var t=ue.crypto.ECDSA.parseSigHexInHexRS(e);return{r:new S(t.r,16),s:new S(t.s,16)}},ue.crypto.ECDSA.parseSigHexInHexRS=function(e){var t=le,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 s=i[0],o=i[1];if("02"!=e.substr(s,2))throw new Error("1st item not ASN.1 integer");if("02"!=e.substr(o,2))throw new Error("2nd item not ASN.1 integer");return{r:n(e,s),s:n(e,o)}},ue.crypto.ECDSA.asn1SigToConcatSig=function(e){var t=ue.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},ue.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 ue.crypto.ECDSA.hexRSSigToASN1Sig(t,r)},ue.crypto.ECDSA.hexRSSigToASN1Sig=function(e,t){var r=new S(e,16),n=new S(t,16);return ue.crypto.ECDSA.biRSSigToASN1Sig(r,n)},ue.crypto.ECDSA.biRSSigToASN1Sig=function(e,t){var r=ue.asn1,n=new r.DERInteger({bigint:e}),i=new r.DERInteger({bigint:t});return new r.DERSequence({array:[n,i]}).getEncodedHex()},ue.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!==ue&&ue||(t.KJUR=ue={}),void 0!==ue.crypto&&ue.crypto||(ue.crypto={}),ue.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,s,o,a,u,c,h,l,d,f,p){e[n]={};var g=r(s),y=r(o),v=r(a),m=r(u),w=r(c),b=new oe(g,y,v),_=b.decodePointHex("04"+h+l);e[n].name=n,e[n].keylen=i,e[n].curve=b,e[n].G=_,e[n].n=m,e[n].h=w,e[n].oid=f,e[n].info=p;for(var S=0;S<d.length;S++)t[d[S]]=n}},ue.crypto.ECParameterDB.regist("secp128r1",128,"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC","E87579C11079F43DD824993C2CEE5ED3","FFFFFFFE0000000075A30D1B9038A115","1","161FF7528B899B2D0C28607CA52C5B86","CF5AC8395BAFEB13C02DA292DDED7A83",[],"","secp128r1 : SECG curve over a 128 bit prime field"),ue.crypto.ECParameterDB.regist("secp160k1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73","0","7","0100000000000000000001B8FA16DFAB9ACA16B6B3","1","3B4C382CE37AA192A4019E763036F4F5DD4D7EBB","938CF935318FDCED6BC28286531733C3F03C4FEE",[],"","secp160k1 : SECG curve over a 160 bit prime field"),ue.crypto.ECParameterDB.regist("secp160r1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC","1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45","0100000000000000000001F4C8F927AED3CA752257","1","4A96B5688EF573284664698968C38BB913CBFC82","23A628553168947D59DCC912042351377AC5FB32",[],"","secp160r1 : SECG curve over a 160 bit prime field"),ue.crypto.ECParameterDB.regist("secp192k1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37","0","3","FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D","1","DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D","9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D",[]),ue.crypto.ECParameterDB.regist("secp192r1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC","64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1","FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831","1","188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012","07192B95FFC8DA78631011ED6B24CDD573F977A11E794811",[]),ue.crypto.ECParameterDB.regist("secp224r1",224,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE","B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4","FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D","1","B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21","BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34",[]),ue.crypto.ECParameterDB.regist("secp256k1",256,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F","0","7","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141","1","79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798","483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",[]),ue.crypto.ECParameterDB.regist("secp256r1",256,"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC","5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B","FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551","1","6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296","4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",["NIST P-256","P-256","prime256v1"]),ue.crypto.ECParameterDB.regist("secp384r1",384,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC","B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973","1","AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7","3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f",["NIST P-384","P-384"]),ue.crypto.ECParameterDB.regist("secp521r1",521,"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC","051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409","1","C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66","011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650",["NIST P-521","P-521"]);var qe=function(){var e=function(e,r,n){return t(y.AES,e,r,n)},t=function(e,t,r,n){var i=y.enc.Hex.parse(t),s=y.enc.Hex.parse(r),o=y.enc.Hex.parse(n),a={};a.key=s,a.iv=o,a.ciphertext=i;var u=e.decrypt(a,s,{iv:o});return y.enc.Hex.stringify(u)},r=function(e,t,r){return n(y.AES,e,t,r)},n=function(e,t,r,n){var i=y.enc.Hex.parse(t),s=y.enc.Hex.parse(r),o=y.enc.Hex.parse(n),a=e.encrypt(i,s,{iv:o}),u=y.enc.Hex.parse(a.toString());return y.enc.Base64.stringify(u)},i={"AES-256-CBC":{proc:e,eproc:r,keylen:32,ivlen:16},"AES-192-CBC":{proc:e,eproc:r,keylen:24,ivlen:16},"AES-128-CBC":{proc:e,eproc:r,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:function(e,r,n){return t(y.TripleDES,e,r,n)},eproc:function(e,t,r){return n(y.TripleDES,e,t,r)},keylen:24,ivlen:8},"DES-CBC":{proc:function(e,r,n){return t(y.DES,e,r,n)},eproc:function(e,t,r){return n(y.DES,e,t,r)},keylen:8,ivlen:8}},s=function(e){var t={},r=e.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"));r&&(t.cipher=r[1],t.ivsalt=r[2]);var n=e.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));n&&(t.type=n[1]);var i=-1,s=0;-1!=e.indexOf("\r\n\r\n")&&(i=e.indexOf("\r\n\r\n"),s=2),-1!=e.indexOf("\n\n")&&(i=e.indexOf("\n\n"),s=1);var o=e.indexOf("-----END");if(-1!=i&&-1!=o){var a=e.substring(i+2*s,o-s);a=a.replace(/\s+/g,""),t.data=a}return t},o=function(e,t,r){for(var n=r.substring(0,16),s=y.enc.Hex.parse(n),o=y.enc.Utf8.parse(t),a=i[e].keylen+i[e].ivlen,u="",c=null;;){var h=y.algo.MD5.create();if(null!=c&&h.update(c),h.update(o),h.update(s),c=h.finalize(),(u+=y.enc.Hex.stringify(c)).length>=2*a)break}var l={};return l.keyhex=u.substr(0,2*i[e].keylen),l.ivhex=u.substr(2*i[e].keylen,2*i[e].ivlen),l},a=function(e,t,r,n){var s=y.enc.Base64.parse(e),o=y.enc.Hex.stringify(s);return(0,i[t].proc)(o,r,n)};return{version:"1.0.0",parsePKCS5PEM:function(e){return s(e)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(e,t,r){return o(e,t,r)},decryptKeyB64:function(e,t,r,n){return a(e,t,r,n)},getDecryptedKeyHex:function(e,t){var r=s(e),n=(r.type,r.cipher),i=r.ivsalt,u=r.data,c=o(n,t,i).keyhex;return a(u,n,c,i)},getEncryptedPKCS5PEMFromPrvKeyHex:function(e,t,r,n,s){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!==s&&null!=s||(s=function(e){var t=y.lib.WordArray.random(e);return y.enc.Hex.stringify(t)}(i[n].ivlen).toUpperCase());var u=function(e,t,r,n){return(0,i[t].eproc)(e,r,n)}(t,n,o(n,r,s).keyhex,s);return a="-----BEGIN "+e+" PRIVATE KEY-----\r\n",a+="Proc-Type: 4,ENCRYPTED\r\n",a+="DEK-Info: "+n+","+s+"\r\n",a+="\r\n",(a+=u.replace(/(.{64})/g,"$1\r\n"))+"\r\n-----END "+e+" PRIVATE KEY-----\r\n"},parseHexOfEncryptedPKCS8:function(e){var t=le,r=t.getChildIdx,n=t.getV,i={},s=r(e,0);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0).items != 2: "+s.length);i.ciphertext=n(e,s[1]);var o=r(e,s[0]);if(2!=o.length)throw new Error("malformed format: SEQUENCE(0.0).items != 2: "+o.length);if("2a864886f70d01050d"!=n(e,o[0]))throw new Error("this only supports pkcs5PBES2");var a=r(e,o[1]);if(2!=o.length)throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: "+a.length);var u=r(e,a[1]);if(2!=u.length)throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: "+u.length);if("2a864886f70d0307"!=n(e,u[0]))throw"this only supports TripleDES";i.encryptionSchemeAlg="TripleDES",i.encryptionSchemeIV=n(e,u[1]);var c=r(e,a[0]);if(2!=c.length)throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: "+c.length);if("2a864886f70d01050c"!=n(e,c[0]))throw new Error("this only supports pkcs5PBKDF2");var h=r(e,c[1]);if(h.length<2)throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+h.length);i.pbkdf2Salt=n(e,h[0]);var l=n(e,h[1]);try{i.pbkdf2Iter=parseInt(l,16)}catch(e){throw new Error("malformed format pbkdf2Iter: "+l)}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=ke(e,"ENCRYPTED PRIVATE KEY"),n=this.parseHexOfEncryptedPKCS8(r),i=qe.getPBKDF2KeyHexFromParam(n,t),s={};s.ciphertext=y.enc.Hex.parse(n.ciphertext);var o=y.enc.Hex.parse(i),a=y.enc.Hex.parse(n.encryptionSchemeIV),u=y.TripleDES.decrypt(s,o,{iv:a});return y.enc.Hex.stringify(u)},getKeyFromEncryptedPKCS8PEM:function(e,t){var r=this._getPlainPKCS8HexFromEncryptedPKCS8PEM(e,t);return this.getKeyFromPlainPrivatePKCS8Hex(r)},parsePlainPrivatePKCS8Hex:function(e){var t=le,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 s=r(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 o=r(e,s[1]);if(2!=o.length)throw new Error("malformed PKCS8 private key(code:004)");if("06"!=e.substr(o[0],2))throw new Error("malformed PKCS8 private key(code:005)");if(i.algoid=n(e,o[0]),"06"==e.substr(o[1],2)&&(i.algparam=n(e,o[1])),"04"!=e.substr(s[2],2))throw new Error("malformed PKCS8 private key(code:006)");return i.keyidx=t.getVidx(e,s[2]),i},getKeyFromPlainPrivatePKCS8PEM:function(e){var t=ke(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 ue.crypto.DSA;else{if("2a8648ce3d0201"!=r.algoid)throw new Error("unsupported private key algorithm");t=new ue.crypto.ECDSA}return t.readPKCS8PrvKeyHex(e),t},_getKeyFromPublicPKCS8Hex:function(e){var t,r=le.getVbyList(e,0,[0,0],"06");if("2a864886f70d010101"===r)t=new ne;else if("2a8648ce380401"===r)t=new ue.crypto.DSA;else{if("2a8648ce3d0201"!==r)throw new Error("unsupported PKCS#8 public key hex");t=new ue.crypto.ECDSA}return t.readPKCS8PubKeyHex(e),t},parsePublicRawRSAKeyHex:function(e){var t=le,r=t.getChildIdx,n=t.getV,i={};if("30"!=e.substr(0,2))throw new Error("malformed RSA key(code:001)");var s=r(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(i.n=n(e,s[0]),"02"!=e.substr(s[1],2))throw new Error("malformed RSA key(code:004)");return i.e=n(e,s[1]),i},parsePublicPKCS8Hex:function(e){var t=le,r=t.getChildIdx,n=t.getV,i={algparam:null},s=r(e,0);if(2!=s.length)throw new Error("outer DERSequence shall have 2 elements: "+s.length);var o=s[0];if("30"!=e.substr(o,2))throw new Error("malformed PKCS8 public key(code:001)");var a=r(e,o);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(s[1],2))throw new Error("malformed PKCS8 public key(code:004)");return i.key=n(e,s[1]).substr(2),i}}}();function Ke(e,t){for(var r="",n=t/4-e.length,i=0;i<n;i++)r+="0";return r+e}function Ve(e,t,r){for(var n="",i=0;n.length<t;)n+=Se(r(Ee(e+String.fromCharCode.apply(String,[(4278190080&i)>>24,(16711680&i)>>16,(65280&i)>>8,255&i])))),i+=1;return n}function $e(e){for(var t in ue.crypto.Util.DIGESTINFOHEAD){var r=ue.crypto.Util.DIGESTINFOHEAD[t],n=r.length;if(e.substring(0,n)==r)return[t,e.substring(n)]}return[]}function We(e){var t,r=le,n=r.getChildIdx,i=r.getV,s=r.getTLV,o=r.getVbyList,a=r.getVbyListEx,u=r.getTLVbyList,c=r.getTLVbyListEx,h=r.getIdxbyList,l=r.getIdxbyListEx,d=r.getVidx,f=r.getInt,p=r.oidname,g=r.hextooidstr,y=ke;try{t=ue.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=u(this.hex,0,[0,0]);if("a0"==e.substr(0,2)){var t=u(e,0,[0]),r=f(t,0);if(r<0||2<r)throw new Error("malformed version field");return this.version=r+1,this.version}return this.version=1,this.foffset=-1,1},this.getSerialNumberHex=function(){return a(this.hex,0,[0,0],"02")},this.getSignatureAlgorithmField=function(){var e=c(this.hex,0,[0,1]);return this.getAlgorithmIdentifierName(e)},this.getAlgorithmIdentifierName=function(e){for(var r in t)if(e===t[r])return r;return p(a(e,0,[0],"06"))},this.getIssuer=function(){return this.getX500Name(this.getIssuerHex())},this.getIssuerHex=function(){return u(this.hex,0,[0,3+this.foffset],"30")},this.getIssuerString=function(){return this.getIssuer().str},this.getSubject=function(){return this.getX500Name(this.getSubjectHex())},this.getSubjectHex=function(){return u(this.hex,0,[0,5+this.foffset],"30")},this.getSubjectString=function(){return this.getSubject().str},this.getNotBefore=function(){var e=o(this.hex,0,[0,4+this.foffset,0]);return e=e.replace(/(..)/g,"%$1"),decodeURIComponent(e)},this.getNotAfter=function(){var e=o(this.hex,0,[0,4+this.foffset,1]);return e=e.replace(/(..)/g,"%$1"),decodeURIComponent(e)},this.getPublicKeyHex=function(){return r.getTLVbyList(this.hex,0,[0,6+this.foffset],"30")},this.getPublicKeyIdx=function(){return h(this.hex,0,[0,6+this.foffset],"30")},this.getPublicKeyContentIdx=function(){var e=this.getPublicKeyIdx();return h(this.hex,e,[1,0],"30")},this.getPublicKey=function(){return qe.getKey(this.getPublicKeyHex(),null,"pkcs8pub")},this.getSignatureAlgorithmName=function(){var e=u(this.hex,0,[1],"30");return this.getAlgorithmIdentifierName(e)},this.getSignatureValueHex=function(){return o(this.hex,0,[2],"03",!0)},this.verifySignature=function(e){var t=this.getSignatureAlgorithmField(),r=this.getSignatureValueHex(),n=u(this.hex,0,[0],"30"),i=new ue.crypto.Signature({alg:t});return i.init(e),i.updateHex(n),i.verify(r)},this.parseExt=function(e){var t,s,a;if(void 0===e){if(a=this.hex,3!==this.version)return-1;t=h(a,0,[0,7,0],"30"),s=n(a,t)}else{a=ke(e);var u=h(a,0,[0,3,0,0],"06");if("2a864886f70d01090e"!=i(a,u))return void(this.aExtInfo=new Array);t=h(a,0,[0,3,0,1,0],"30"),s=n(a,t),this.hex=a}this.aExtInfo=new Array;for(var c=0;c<s.length;c++){var l={critical:!1},f=0;3===n(a,s[c]).length&&(l.critical=!0,f=1),l.oid=r.hextooidstr(o(a,s[c],[0],"06"));var p=h(a,s[c],[1+f]);l.vidx=d(a,p),this.aExtInfo.push(l)}},this.getExtInfo=function(e){var t=this.aExtInfo,r=e;if(e.match(/^[0-9.]+$/)||(r=ue.asn1.x509.OID.name2oid(e)),""!==r)for(var n=0;n<t.length;n++)if(t[n].oid===r)return t[n]},this.getExtBasicConstraints=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("basicConstraints");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var n={extname:"basicConstraints"};if(t&&(n.critical=!0),"3000"===e)return n;if("30030101ff"===e)return n.cA=!0,n;if("30060101ff02"===e.substr(0,12)){var o=i(e,10),a=parseInt(o,16);return n.cA=!0,n.pathLen=a,n}throw new Error("hExtV parse error: "+e)},this.getExtKeyUsage=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("keyUsage");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var n={extname:"keyUsage"};return t&&(n.critical=!0),n.names=this.getExtKeyUsageString(e).split(","),n},this.getExtKeyUsageBin=function(e){if(void 0===e){var t=this.getExtInfo("keyUsage");if(void 0===t)return"";e=s(this.hex,t.vidx)}if(8!=e.length&&10!=e.length)throw new Error("malformed key usage value: "+e);var r="000000000000000"+parseInt(e.substr(6),16).toString(2);return 8==e.length&&(r=r.slice(-8)),10==e.length&&(r=r.slice(-16)),""==(r=r.replace(/0+$/,""))&&(r="0"),r},this.getExtKeyUsageString=function(e){for(var t=this.getExtKeyUsageBin(e),r=new Array,n=0;n<t.length;n++)"1"==t.substr(n,1)&&r.push(We.KEYUSAGE_NAME[n]);return r.join(",")},this.getExtSubjectKeyIdentifier=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("subjectKeyIdentifier");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var n={extname:"subjectKeyIdentifier"};t&&(n.critical=!0);var o=i(e,0);return n.kid={hex:o},n},this.getExtAuthorityKeyIdentifier=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("authorityKeyIdentifier");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var o={extname:"authorityKeyIdentifier"};t&&(o.critical=!0);for(var a=n(e,0),u=0;u<a.length;u++){var c=e.substr(a[u],2);if("80"===c&&(o.kid={hex:i(e,a[u])}),"a1"===c){var h=s(e,a[u]),l=this.getGeneralNames(h);o.issuer=l[0].dn}"82"===c&&(o.sn={hex:i(e,a[u])})}return o},this.getExtExtKeyUsage=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("extKeyUsage");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var o={extname:"extKeyUsage",array:[]};t&&(o.critical=!0);for(var a=n(e,0),u=0;u<a.length;u++)o.array.push(p(i(e,a[u])));return o},this.getExtExtKeyUsageName=function(){var e=this.getExtInfo("extKeyUsage");if(void 0===e)return e;var t=new Array,r=s(this.hex,e.vidx);if(""===r)return t;for(var o=n(r,0),a=0;a<o.length;a++)t.push(p(i(r,o[a])));return t},this.getExtSubjectAltName=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("subjectAltName");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var n={extname:"subjectAltName",array:[]};return t&&(n.critical=!0),n.array=this.getGeneralNames(e),n},this.getExtIssuerAltName=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("issuerAltName");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var n={extname:"issuerAltName",array:[]};return t&&(n.critical=!0),n.array=this.getGeneralNames(e),n},this.getGeneralNames=function(e){for(var t=n(e,0),r=[],i=0;i<t.length;i++){var o=this.getGeneralName(s(e,t[i]));void 0!==o&&r.push(o)}return r},this.getGeneralName=function(e){var t=e.substr(0,2),r=i(e,0),n=Se(r);return"81"==t?{rfc822:n}:"82"==t?{dns:n}:"86"==t?{uri:n}:"87"==t?{ip:Oe(r)}:"a4"==t?{dn:this.getX500Name(r)}:void 0},this.getExtSubjectAltName2=function(){var e,t,r,o=this.getExtInfo("subjectAltName");if(void 0===o)return o;for(var a=new Array,u=s(this.hex,o.vidx),c=n(u,0),h=0;h<c.length;h++)r=u.substr(c[h],2),e=i(u,c[h]),"81"===r&&(t=_e(e),a.push(["MAIL",t])),"82"===r&&(t=_e(e),a.push(["DNS",t])),"84"===r&&(t=We.hex2dn(e,0),a.push(["DN",t])),"86"===r&&(t=_e(e),a.push(["URI",t])),"87"===r&&(t=Oe(e),a.push(["IP",t]));return a},this.getExtCRLDistributionPoints=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("cRLDistributionPoints");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var i={extname:"cRLDistributionPoints",array:[]};t&&(i.critical=!0);for(var o=n(e,0),a=0;a<o.length;a++){var u=s(e,o[a]);i.array.push(this.getDistributionPoint(u))}return i},this.getDistributionPoint=function(e){for(var t={},r=n(e,0),i=0;i<r.length;i++){var o=e.substr(r[i],2),a=s(e,r[i]);"a0"==o&&(t.dpname=this.getDistributionPointName(a))}return t},this.getDistributionPointName=function(e){for(var t={},r=n(e,0),i=0;i<r.length;i++){var o=e.substr(r[i],2),a=s(e,r[i]);"a0"==o&&(t.full=this.getGeneralNames(a))}return t},this.getExtCRLDistributionPointsURI=function(){var e=this.getExtInfo("cRLDistributionPoints");if(void 0===e)return e;for(var t=new Array,r=n(this.hex,e.vidx),i=0;i<r.length;i++)try{var s=_e(o(this.hex,r[i],[0,0,0],"86"));t.push(s)}catch(e){}return t},this.getExtAIAInfo=function(){var e=this.getExtInfo("authorityInfoAccess");if(void 0===e)return e;for(var t={ocsp:[],caissuer:[]},r=n(this.hex,e.vidx),i=0;i<r.length;i++){var s=o(this.hex,r[i],[0],"06"),a=o(this.hex,r[i],[1],"86");"2b06010505073001"===s&&t.ocsp.push(_e(a)),"2b06010505073002"===s&&t.caissuer.push(_e(a))}return t},this.getExtAuthorityInfoAccess=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("authorityInfoAccess");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var i={extname:"authorityInfoAccess",array:[]};t&&(i.critical=!0);for(var u=n(e,0),c=0;c<u.length;c++){var h=a(e,u[c],[0],"06"),l=_e(o(e,u[c],[1],"86"));if("2b06010505073001"==h)i.array.push({ocsp:l});else{if("2b06010505073002"!=h)throw new Error("unknown method: "+h);i.array.push({caissuer:l})}}return i},this.getExtCertificatePolicies=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("certificatePolicies");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var i={extname:"certificatePolicies",array:[]};t&&(i.critical=!0);for(var o=n(e,0),a=0;a<o.length;a++){var u=s(e,o[a]),c=this.getPolicyInformation(u);i.array.push(c)}return i},this.getPolicyInformation=function(e){var t={},r=o(e,0,[0],"06");t.policyoid=p(r);var i=l(e,0,[1],"30");if(-1!=i){t.array=[];for(var a=n(e,i),u=0;u<a.length;u++){var c=s(e,a[u]),h=this.getPolicyQualifierInfo(c);t.array.push(h)}}return t},this.getPolicyQualifierInfo=function(e){var t={},r=o(e,0,[0],"06");if("2b06010505070201"===r){var n=a(e,0,[1],"16");t.cps=Se(n)}else if("2b06010505070202"===r){var i=u(e,0,[1],"30");t.unotice=this.getUserNotice(i)}return t},this.getUserNotice=function(e){for(var t={},r=n(e,0),i=0;i<r.length;i++){var o=s(e,r[i]);"30"!=o.substr(0,2)&&(t.exptext=this.getDisplayText(o))}return t},this.getDisplayText=function(e){var t={};return t.type={"0c":"utf8",16:"ia5","1a":"vis","1e":"bmp"}[e.substr(0,2)],t.str=Se(i(e,0)),t},this.getExtCRLNumber=function(e,t){var r={extname:"cRLNumber"};if(t&&(r.critical=!0),"02"==e.substr(0,2))return r.num={hex:i(e,0)},r;throw new Error("hExtV parse error: "+e)},this.getExtCRLReason=function(e,t){var r={extname:"cRLReason"};if(t&&(r.critical=!0),"0a"==e.substr(0,2))return r.code=parseInt(i(e,0),16),r;throw new Error("hExtV parse error: "+e)},this.getExtOcspNonce=function(e,t){var r={extname:"ocspNonce"};t&&(r.critical=!0);var n=i(e,0);return r.hex=n,r},this.getExtOcspNoCheck=function(e,t){var r={extname:"ocspNoCheck"};return t&&(r.critical=!0),r},this.getExtAdobeTimeStamp=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("adobeTimeStamp");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var i={extname:"adobeTimeStamp"};t&&(i.critical=!0);var o=n(e,0);if(o.length>1){var a=s(e,o[1]),u=this.getGeneralName(a);null!=u.uri&&(i.uri=u.uri)}if(o.length>2){var c=s(e,o[2]);"0101ff"==c&&(i.reqauth=!0),"010100"==c&&(i.reqauth=!1)}return i},this.getX500NameRule=function(e){for(var t=null,r=[],n=0;n<e.length;n++)for(var i=e[n],s=0;s<i.length;s++)r.push(i[s]);for(n=0;n<r.length;n++){var o=r[n],a=o.ds,u=o.value,c=o.type;if("prn"!=a&&"utf8"!=a&&"ia5"!=a)return"mixed";if("ia5"==a){if("CN"!=c)return"mixed";if(ue.lang.String.isMail(u))continue;return"mixed"}if("C"==c){if("prn"==a)continue;return"mixed"}if(null==t)t=a;else if(t!==a)return"mixed"}return null==t?"prn":t},this.getX500Name=function(e){var t=this.getX500NameArray(e);return{array:t,str:this.dnarraytostr(t)}},this.getX500NameArray=function(e){for(var t=[],r=n(e,0),i=0;i<r.length;i++)t.push(this.getRDN(s(e,r[i])));return t},this.getRDN=function(e){for(var t=[],r=n(e,0),i=0;i<r.length;i++)t.push(this.getAttrTypeAndValue(s(e,r[i])));return t},this.getAttrTypeAndValue=function(e){var t={type:null,value:null,ds:null},r=n(e,0),i=o(e,r[0],[],"06"),s=o(e,r[1],[]),a=ue.asn1.ASN1Util.oidHexToInt(i);return t.type=ue.asn1.x509.OID.oid2atype(a),t.ds=this.HEX2STAG[e.substr(r[1],2)],"bmp"!=t.ds?t.value=_e(s):t.value=Le(s),t},this.readCertPEM=function(e){this.readCertHex(y(e))},this.readCertHex=function(e){this.hex=e,this.getVersion();try{h(this.hex,0,[0,7],"a3"),this.parseExt()}catch(e){}},this.getParam=function(){var e={};return e.version=this.getVersion(),e.serial={hex:this.getSerialNumberHex()},e.sigalg=this.getSignatureAlgorithmField(),e.issuer=this.getIssuer(),e.notbefore=this.getNotBefore(),e.notafter=this.getNotAfter(),e.subject=this.getSubject(),e.sbjpubkey=Te(this.getPublicKeyHex(),"PUBLIC KEY"),this.aExtInfo.length>0&&(e.ext=this.getExtParamArray()),e.sighex=this.getSignatureValueHex(),e},this.getExtParamArray=function(e){null==e&&-1!=l(this.hex,0,[0,"[3]"])&&(e=c(this.hex,0,[0,"[3]",0],"30"));for(var t=[],r=n(e,0),i=0;i<r.length;i++){var o=s(e,r[i]),a=this.getExtParam(o);null!=a&&t.push(a)}return t},this.getExtParam=function(e){var t=n(e,0).length;if(2!=t&&3!=t)throw new Error("wrong number elements in Extension: "+t+" "+e);var r=g(o(e,0,[0],"06")),i=!1;3==t&&"0101ff"==u(e,0,[1])&&(i=!0);var s=u(e,0,[t-1,0]),a=void 0;if("2.5.29.14"==r?a=this.getExtSubjectKeyIdentifier(s,i):"2.5.29.15"==r?a=this.getExtKeyUsage(s,i):"2.5.29.17"==r?a=this.getExtSubjectAltName(s,i):"2.5.29.18"==r?a=this.getExtIssuerAltName(s,i):"2.5.29.19"==r?a=this.getExtBasicConstraints(s,i):"2.5.29.31"==r?a=this.getExtCRLDistributionPoints(s,i):"2.5.29.32"==r?a=this.getExtCertificatePolicies(s,i):"2.5.29.35"==r?a=this.getExtAuthorityKeyIdentifier(s,i):"2.5.29.37"==r?a=this.getExtExtKeyUsage(s,i):"1.3.6.1.5.5.7.1.1"==r?a=this.getExtAuthorityInfoAccess(s,i):"2.5.29.20"==r?a=this.getExtCRLNumber(s,i):"2.5.29.21"==r?a=this.getExtCRLReason(s,i):"1.3.6.1.5.5.7.48.1.2"==r?a=this.getExtOcspNonce(s,i):"1.3.6.1.5.5.7.48.1.5"==r?a=this.getExtOcspNoCheck(s,i):"1.2.840.113583.1.1.9.1"==r&&(a=this.getExtAdobeTimeStamp(s,i)),null!=a)return a;var c={extname:r,extn:s};return i&&(c.critical=!0),c},this.findExt=function(e,t){for(var r=0;r<e.length;r++)if(e[r].extname==t)return e[r];return null},this.updateExtCDPFullURI=function(e,t){var r=this.findExt(e,"cRLDistributionPoints");if(null!=r&&null!=r.array)for(var n=r.array,i=0;i<n.length;i++)if(null!=n[i].dpname&&null!=n[i].dpname.full)for(var s=n[i].dpname.full,o=0;o<s.length;o++){var a=s[i];null!=a.uri&&(a.uri=t)}},this.updateExtAIAOCSP=function(e,t){var r=this.findExt(e,"authorityInfoAccess");if(null!=r&&null!=r.array)for(var n=r.array,i=0;i<n.length;i++)null!=n[i].ocsp&&(n[i].ocsp=t)},this.updateExtAIACAIssuer=function(e,t){var r=this.findExt(e,"authorityInfoAccess");if(null!=r&&null!=r.array)for(var n=r.array,i=0;i<n.length;i++)null!=n[i].caissuer&&(n[i].caissuer=t)},this.dnarraytostr=function(e){return"/"+e.map(function(e){return function(e){return e.map(function(e){return function(e){return e.type+"="+e.value}(e).replace(/\+/,"\\+")}).join("+")}(e).replace(/\//,"\\/")}).join("/")},this.getInfo=function(){var e,t,r,n=function(e){return JSON.stringify(e.array).replace(/[\[\]\{\}\"]/g,"")},i=function(e){for(var t="",r=e.array,n=0;n<r.length;n++){var i=r[n];if(t+=" policy oid: "+i.policyoid+"\n",void 0!==i.array)for(var s=0;s<i.array.length;s++){var o=i.array[s];void 0!==o.cps&&(t+=" cps: "+o.cps+"\n")}}return t},s=function(e){for(var t="",r=e.array,n=0;n<r.length;n++){var i=r[n];try{void 0!==i.dpname.full[0].uri&&(t+=" "+i.dpname.full[0].uri+"\n")}catch(e){}try{void 0!==i.dname.full[0].dn.hex&&(t+=" "+We.hex2dn(i.dpname.full[0].dn.hex)+"\n")}catch(e){}}return t},o=function(e){for(var t="",r=e.array,n=0;n<r.length;n++){var i=r[n];void 0!==i.caissuer&&(t+=" caissuer: "+i.caissuer+"\n"),void 0!==i.ocsp&&(t+=" ocsp: "+i.ocsp+"\n")}return t};if(e="Basic Fields\n",e+=" serial number: "+this.getSerialNumberHex()+"\n",e+=" signature algorithm: "+this.getSignatureAlgorithmField()+"\n",e+=" issuer: "+this.getIssuerString()+"\n",e+=" notBefore: "+this.getNotBefore()+"\n",e+=" notAfter: "+this.getNotAfter()+"\n",e+=" subject: "+this.getSubjectString()+"\n",e+=" subject public key info: \n",e+=" key algorithm: "+(t=this.getPublicKey()).type+"\n","RSA"===t.type&&(e+=" n="+Me(t.n.toString(16)).substr(0,16)+"...\n",e+=" e="+Me(t.e.toString(16))+"\n"),null!=(r=this.aExtInfo)){e+="X509v3 Extensions:\n";for(var a=0;a<r.length;a++){var u=r[a],c=ue.asn1.x509.OID.oid2name(u.oid);""===c&&(c=u.oid);var h="";if(!0===u.critical&&(h="CRITICAL"),e+=" "+c+" "+h+":\n","basicConstraints"===c){var l=this.getExtBasicConstraints();void 0===l.cA?e+=" {}\n":(e+=" cA=true",void 0!==l.pathLen&&(e+=", pathLen="+l.pathLen),e+="\n")}else if("keyUsage"===c)e+=" "+this.getExtKeyUsageString()+"\n";else if("subjectKeyIdentifier"===c)e+=" "+this.getExtSubjectKeyIdentifier().kid.hex+"\n";else if("authorityKeyIdentifier"===c){var d=this.getExtAuthorityKeyIdentifier();void 0!==d.kid&&(e+=" kid="+d.kid.hex+"\n")}else"extKeyUsage"===c?e+=" "+this.getExtExtKeyUsage().array.join(", ")+"\n":"subjectAltName"===c?e+=" "+n(this.getExtSubjectAltName())+"\n":"cRLDistributionPoints"===c?e+=s(this.getExtCRLDistributionPoints()):"authorityInfoAccess"===c?e+=o(this.getExtAuthorityInfoAccess()):"certificatePolicies"===c&&(e+=i(this.getExtCertificatePolicies()))}}return(e+="signature algorithm: "+this.getSignatureAlgorithmName()+"\n")+"signature: "+this.getSignatureValueHex().substr(0,16)+"...\n"},"string"==typeof e&&(-1!=e.indexOf("-----BEGIN")?this.readCertPEM(e):ue.lang.String.isHex(e)&&this.readCertHex(e))}qe.getKey=function(e,t,r){var n,i=(v=le).getChildIdx,s=(v.getV,v.getVbyList),o=ue.crypto,a=o.ECDSA,u=o.DSA,c=ne,h=ke,l=qe;if(void 0!==c&&e instanceof c)return e;if(void 0!==a&&e instanceof a)return e;if(void 0!==u&&e instanceof u)return e;if(void 0!==e.curve&&void 0!==e.xy&&void 0===e.d)return new a({pub:e.xy,curve:e.curve});if(void 0!==e.curve&&void 0!==e.d)return new a({prv:e.d,curve:e.curve});if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0===e.d)return(I=new c).setPublic(e.n,e.e),I;if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0!==e.p&&void 0!==e.q&&void 0!==e.dp&&void 0!==e.dq&&void 0!==e.co&&void 0===e.qi)return(I=new c).setPrivateEx(e.n,e.e,e.d,e.p,e.q,e.dp,e.dq,e.co),I;if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0===e.p)return(I=new c).setPrivate(e.n,e.e,e.d),I;if(void 0!==e.p&&void 0!==e.q&&void 0!==e.g&&void 0!==e.y&&void 0===e.x)return(I=new u).setPublic(e.p,e.q,e.g,e.y),I;if(void 0!==e.p&&void 0!==e.q&&void 0!==e.g&&void 0!==e.y&&void 0!==e.x)return(I=new u).setPrivate(e.p,e.q,e.g,e.y,e.x),I;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0===e.d)return(I=new c).setPublic(we(e.n),we(e.e)),I;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0!==e.p&&void 0!==e.q&&void 0!==e.dp&&void 0!==e.dq&&void 0!==e.qi)return(I=new c).setPrivateEx(we(e.n),we(e.e),we(e.d),we(e.p),we(e.q),we(e.dp),we(e.dq),we(e.qi)),I;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d)return(I=new c).setPrivate(we(e.n),we(e.e),we(e.d)),I;if("EC"===e.kty&&void 0!==e.crv&&void 0!==e.x&&void 0!==e.y&&void 0===e.d){var d=(k=new a({curve:e.crv})).ecparams.keylen/4,f="04"+("0000000000"+we(e.x)).slice(-d)+("0000000000"+we(e.y)).slice(-d);return k.setPublicKeyHex(f),k}if("EC"===e.kty&&void 0!==e.crv&&void 0!==e.x&&void 0!==e.y&&void 0!==e.d){d=(k=new a({curve:e.crv})).ecparams.keylen/4,f="04"+("0000000000"+we(e.x)).slice(-d)+("0000000000"+we(e.y)).slice(-d);var p=("0000000000"+we(e.d)).slice(-d);return k.setPublicKeyHex(f),k.setPrivateKeyHex(p),k}if("pkcs5prv"===r){var g,y=e,v=le;if(9===(g=i(y,0)).length)(I=new c).readPKCS5PrvKeyHex(y);else if(6===g.length)(I=new u).readPKCS5PrvKeyHex(y);else{if(!(g.length>2&&"04"===y.substr(g[1],2)))throw new Error("unsupported PKCS#1/5 hexadecimal key");(I=new a).readPKCS5PrvKeyHex(y)}return I}if("pkcs8prv"===r)return l.getKeyFromPlainPrivatePKCS8Hex(e);if("pkcs8pub"===r)return l._getKeyFromPublicPKCS8Hex(e);if("x509pub"===r)return We.getPublicKeyFromCertHex(e);if(-1!=e.indexOf("-END CERTIFICATE-",0)||-1!=e.indexOf("-END X509 CERTIFICATE-",0)||-1!=e.indexOf("-END TRUSTED CERTIFICATE-",0))return We.getPublicKeyFromCertPEM(e);if(-1!=e.indexOf("-END PUBLIC KEY-")){var m=ke(e,"PUBLIC KEY");return l._getKeyFromPublicPKCS8Hex(m)}if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var w=h(e,"RSA PRIVATE KEY");return l.getKey(w,null,"pkcs5prv")}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var b=s(n=h(e,"DSA PRIVATE KEY"),0,[1],"02"),_=s(n,0,[2],"02"),E=s(n,0,[3],"02"),x=s(n,0,[4],"02"),A=s(n,0,[5],"02");return(I=new u).setPrivate(new S(b,16),new S(_,16),new S(E,16),new S(x,16),new S(A,16)),I}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED"))return w=h(e,"EC PRIVATE KEY"),l.getKey(w,null,"pkcs5prv");if(-1!=e.indexOf("-END PRIVATE KEY-"))return l.getKeyFromPlainPrivatePKCS8PEM(e);if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var F=l.getDecryptedKeyHex(e,t),T=new ne;return T.readPKCS5PrvKeyHex(F),T}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var k,I=s(n=l.getDecryptedKeyHex(e,t),0,[1],"04"),C=s(n,0,[2,0],"06"),R=s(n,0,[3,0],"03").substr(2);if(void 0===ue.crypto.OID.oidhex2name[C])throw new Error("undefined OID(hex) in KJUR.crypto.OID: "+C);return(k=new a({curve:ue.crypto.OID.oidhex2name[C]})).setPublicKeyHex(R),k.setPrivateKeyHex(I),k.isPublic=!1,k}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED"))return b=s(n=l.getDecryptedKeyHex(e,t),0,[1],"02"),_=s(n,0,[2],"02"),E=s(n,0,[3],"02"),x=s(n,0,[4],"02"),A=s(n,0,[5],"02"),(I=new u).setPrivate(new S(b,16),new S(_,16),new S(E,16),new S(x,16),new S(A,16)),I;if(-1!=e.indexOf("-END ENCRYPTED PRIVATE KEY-"))return l.getKeyFromEncryptedPKCS8PEM(e,t);throw new Error("not supported argument")},qe.generateKeypair=function(e,t){if("RSA"==e){var r=t;(o=new ne).generate(r,"10001"),o.isPrivate=!0,o.isPublic=!0;var n=new ne,i=o.n.toString(16),s=o.e.toString(16);return n.setPublic(i,s),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=o,a.pubKeyObj=n,a}if("EC"==e){var o,a,u=t,c=new ue.crypto.ECDSA({curve:u}).generateKeyPairHex();return(o=new ue.crypto.ECDSA({curve:u})).setPublicKeyHex(c.ecpubhex),o.setPrivateKeyHex(c.ecprvhex),o.isPrivate=!0,o.isPublic=!1,(n=new ue.crypto.ECDSA({curve:u})).setPublicKeyHex(c.ecpubhex),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=o,a.pubKeyObj=n,a}throw new Error("unknown algorithm: "+e)},qe.getPEM=function(e,t,r,n,i,s){var o=ue,a=o.asn1,u=a.DERObjectIdentifier,c=a.DERInteger,h=a.ASN1Util.newObject,l=a.x509.SubjectPublicKeyInfo,d=o.crypto,f=d.DSA,p=d.ECDSA,g=ne;function v(e){return h({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 m(e){return h({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a0",!0,{oid:{name:e.curveName}}]},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]})}function w(e){return h({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 l(e).getEncodedHex(),"PUBLIC KEY");if("PKCS1PRV"==t&&void 0!==g&&e instanceof g&&(void 0===r||null==r)&&1==e.isPrivate)return Te(E=v(e).getEncodedHex(),"RSA PRIVATE KEY");if("PKCS1PRV"==t&&void 0!==p&&e instanceof p&&(void 0===r||null==r)&&1==e.isPrivate){var b=new u({name:e.curveName}).getEncodedHex(),_=m(e).getEncodedHex(),S="";return(S+=Te(b,"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=w(e).getEncodedHex(),"DSA PRIVATE KEY");if("PKCS5PRV"==t&&void 0!==g&&e instanceof g&&void 0!==r&&null!=r&&1==e.isPrivate){var E=v(e).getEncodedHex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",E,r,n,s)}if("PKCS5PRV"==t&&void 0!==p&&e instanceof p&&void 0!==r&&null!=r&&1==e.isPrivate)return E=m(e).getEncodedHex(),void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",E,r,n,s);if("PKCS5PRV"==t&&void 0!==f&&e instanceof f&&void 0!==r&&null!=r&&1==e.isPrivate)return E=w(e).getEncodedHex(),void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",E,r,n,s);var x=function(e,t){var r=A(e,t);return new h({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()},A=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}),s=y.enc.Hex.parse(e),o=y.TripleDES.encrypt(s,i,{iv:n})+"",a={};return a.ciphertext=o,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 F=v(e).getEncodedHex();return E=h({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:F}}]}).getEncodedHex(),void 0===r||null==r?Te(E,"PRIVATE KEY"):Te(_=x(E,r),"ENCRYPTED PRIVATE KEY")}if("PKCS8PRV"==t&&void 0!==p&&e instanceof p&&1==e.isPrivate)return F=new h({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]}).getEncodedHex(),E=h({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:e.curveName}}]},{octstr:{hex:F}}]}).getEncodedHex(),void 0===r||null==r?Te(E,"PRIVATE KEY"):Te(_=x(E,r),"ENCRYPTED PRIVATE KEY");if("PKCS8PRV"==t&&void 0!==f&&e instanceof f&&1==e.isPrivate)return F=new c({bigint:e.x}).getEncodedHex(),E=h({seq:[{int:0},{seq:[{oid:{name:"dsa"}},{seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]}]},{octstr:{hex:F}}]}).getEncodedHex(),void 0===r||null==r?Te(E,"PRIVATE KEY"):Te(_=x(E,r),"ENCRYPTED PRIVATE KEY");throw new Error("unsupported object nor format")},qe.getKeyFromCSRPEM=function(e){var t=ke(e,"CERTIFICATE REQUEST");return qe.getKeyFromCSRHex(t)},qe.getKeyFromCSRHex=function(e){var t=qe.parseCSRHex(e);return qe.getKey(t.p8pubkeyhex,null,"pkcs8pub")},qe.parseCSRHex=function(e){var t=le,r=t.getChildIdx,n=t.getTLV,i={},s=e;if("30"!=s.substr(0,2))throw new Error("malformed CSR(code:001)");var o=r(s,0);if(o.length<1)throw new Error("malformed CSR(code:002)");if("30"!=s.substr(o[0],2))throw new Error("malformed CSR(code:003)");var a=r(s,o[0]);if(a.length<3)throw new Error("malformed CSR(code:004)");return i.p8pubkeyhex=n(s,a[2]),i},qe.getKeyID=function(e){var t=qe,r=le;"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&(e=t.getKey(e));var n=ke(t.getPEM(e)),i=r.getIdxbyList(n,0,[1]),s=r.getV(n,i).substring(2);return ue.crypto.Util.hashHex(s,"sha1")},qe.getJWKFromKey=function(e){var t={};if(e instanceof ne&&e.isPrivate)return t.kty="RSA",t.n=me(e.n.toString(16)),t.e=me(e.e.toString(16)),t.d=me(e.d.toString(16)),t.p=me(e.p.toString(16)),t.q=me(e.q.toString(16)),t.dp=me(e.dmp1.toString(16)),t.dq=me(e.dmq1.toString(16)),t.qi=me(e.coeff.toString(16)),t;if(e instanceof ne&&e.isPublic)return t.kty="RSA",t.n=me(e.n.toString(16)),t.e=me(e.e.toString(16)),t;if(e instanceof ue.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=me(r.x),t.y=me(r.y),t.d=me(e.prvKeyHex),t}if(e instanceof ue.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=me(r.x),t.y=me(r.y),t}throw new Error("not supported key object")},ne.getPosArrayOfChildrenFromHex=function(e){return le.getChildIdx(e,0)},ne.getHexValueArrayOfChildrenFromHex=function(e){var t,r=le.getV,n=r(e,(t=ne.getPosArrayOfChildrenFromHex(e))[0]),i=r(e,t[1]),s=r(e,t[2]),o=r(e,t[3]),a=r(e,t[4]),u=r(e,t[5]),c=r(e,t[6]),h=r(e,t[7]),l=r(e,t[8]);return(t=new Array).push(n,i,s,o,a,u,c,h,l),t},ne.prototype.readPrivateKeyFromPEMString=function(e){var t=ke(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,s,o,a,u,c=le,h=c.getVbyListEx;if(!1===c.isASN1HEX(e))throw new Error("not ASN.1 hex string");try{t=h(e,0,[2,0,1],"02"),r=h(e,0,[2,0,2],"02"),n=h(e,0,[2,0,3],"02"),i=h(e,0,[2,0,4],"02"),s=h(e,0,[2,0,5],"02"),o=h(e,0,[2,0,6],"02"),a=h(e,0,[2,0,7],"02"),u=h(e,0,[2,0,8],"02")}catch(e){throw new Error("malformed PKCS#8 plain RSA private key")}this.setPrivateEx(t,r,n,i,s,o,a,u)},ne.prototype.readPKCS5PubKeyHex=function(e){var t=le,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]),s=r(e,n[1]);this.setPublic(i,s)},ne.prototype.readPKCS8PubKeyHex=function(e){var t=le;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 We).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 ue.crypto.Util.hashString(e,t)}(e);return this.signWithMessageHash(r,t)},ne.prototype.signWithMessageHash=function(e,t){var r=te(ue.crypto.Util.getPaddedDigestInfoHex(e,t,this.n.bitLength()),16);return Ke(this.doPrivate(r).toString(16),this.n.bitLength())},ne.prototype.signPSS=function(e,t,r){var n=function(e){return ue.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),s=i.length,o=this.n.bitLength()-1,a=Math.ceil(o/8),u=function(e){return ue.crypto.Util.hashHex(e,t)};if(-1===r||void 0===r)r=s;else if(-2===r)r=a-s-2;else if(r<-2)throw new Error("invalid salt length");if(a<s+r+2)throw new Error("data too long");var c="";r>0&&(c=new Array(r),(new ee).nextBytes(c),c=String.fromCharCode.apply(String,c));var h=Se(u(Ee("\0\0\0\0\0\0\0\0"+i+c))),l=[];for(n=0;n<a-r-s-2;n+=1)l[n]=0;var d=String.fromCharCode.apply(String,l)+""+c,f=Ve(h,d.length,u),p=[];for(n=0;n<d.length;n+=1)p[n]=d.charCodeAt(n)^f.charCodeAt(n);var g=65280>>8*a-o&255;for(p[0]&=~g,n=0;n<s;n++)p.push(h.charCodeAt(n));return p.push(188),Ke(this.doPrivate(new S(p)).toString(16),this.n.bitLength())},ne.prototype.verify=function(e,t){if(null==(t=t.toLowerCase()).match(/^[0-9a-f]+$/))return!1;var r=te(t,16),n=this.n.bitLength();if(r.bitLength()>n)return!1;var i=this.doPublic(r).toString(16);if(i.length+3!=n/4)return!1;var s=$e(i.replace(/^1f+00/,""));if(0==s.length)return!1;var o=s[0];return s[1]==function(e){return ue.crypto.Util.hashString(e,o)}(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=$e(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 ue.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,s=new S(t,16),o=function(e){return ue.crypto.Util.hashHex(e,r)},a=Se(e),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<u+n+2)throw new Error("data too long");var l=this.doPublic(s).toByteArray();for(i=0;i<l.length;i+=1)l[i]&=255;for(;l.length<h;)l.unshift(0);if(188!==l[h-1])throw new Error("encoded message does not end in 0xbc");var d=(l=String.fromCharCode.apply(String,l)).substr(0,h-u-1),f=l.substr(d.length,u),p=65280>>8*h-c&255;if(0!=(d.charCodeAt(0)&p))throw new Error("bits beyond keysize not zero");var g=Ve(f,d.length,o),y=[];for(i=0;i<d.length;i+=1)y[i]=d.charCodeAt(i)^g.charCodeAt(i);y[0]&=~p;var v=h-u-n-2;for(i=0;i<v;i+=1)if(0!==y[i])throw new Error("leftmost octets not zero");if(1!==y[v])throw new Error("0x01 marker not found");return f===Se(o(Ee("\0\0\0\0\0\0\0\0"+a+String.fromCharCode.apply(String,y.slice(-n)))))},ne.SALT_LEN_HLEN=-1,ne.SALT_LEN_MAX=-2,ne.SALT_LEN_RECOVER=-2,We.hex2dn=function(e,t){void 0===t&&(t=0);var r=new We;return le.getTLV(e,t),r.getX500Name(e).str},We.hex2rdn=function(e,t){if(void 0===t&&(t=0),"31"!==e.substr(t,2))throw new Error("malformed RDN");for(var r=new Array,n=le.getChildIdx(e,t),i=0;i<n.length;i++)r.push(We.hex2attrTypeValue(e,n[i]));return(r=r.map(function(e){return e.replace("+","\\+")})).join("+")},We.hex2attrTypeValue=function(e,t){var r=le,n=r.getV;if(void 0===t&&(t=0),"30"!==e.substr(t,2))throw new Error("malformed attribute type and value");var i=r.getChildIdx(e,t);2!==i.length||e.substr(i[0],2);var s=n(e,i[0]),o=ue.asn1.ASN1Util.oidHexToInt(s);return ue.asn1.x509.OID.oid2atype(o)+"="+Se(n(e,i[1]))},We.getPublicKeyFromCertHex=function(e){var t=new We;return t.readCertHex(e),t.getPublicKey()},We.getPublicKeyFromCertPEM=function(e){var t=new We;return t.readCertPEM(e),t.getPublicKey()},We.getPublicKeyInfoPropOfCertPEM=function(e){var t,r,n=le.getVbyList,i={algparam:null};return(t=new We).readCertPEM(e),r=t.getPublicKeyHex(),i.keyhex=n(r,0,[1],"03").substr(2),i.algoid=n(r,0,[0,0],"06"),"2a8648ce3d0201"===i.algoid&&(i.algparam=n(r,0,[0,1],"06")),i},We.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],void 0!==ue&&ue||(t.KJUR=ue={}),void 0!==ue.jws&&ue.jws||(ue.jws={}),ue.jws.JWS=function(){var e=ue.jws.JWS.isSafeJSONString;this.parseJWS=function(t,r){if(void 0===this.parsedJWS||!r&&void 0===this.parsedJWS.sigvalH){var n=t.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(null==n)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var i=n[1],s=n[2],o=n[3],a=i+"."+s;if(this.parsedJWS={},this.parsedJWS.headB64U=i,this.parsedJWS.payloadB64U=s,this.parsedJWS.sigvalB64U=o,this.parsedJWS.si=a,!r){var u=we(o),c=te(u,16);this.parsedJWS.sigvalH=u,this.parsedJWS.sigvalBI=c}var h=he(i),l=he(s);if(this.parsedJWS.headS=h,this.parsedJWS.payloadS=l,!e(h,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+h}}},ue.jws.JWS.sign=function(e,t,r,n,i){var s,o,a,u=ue,c=u.jws.JWS,h=c.readSafeJSONString,l=c.isSafeJSONString,d=u.crypto,p=(d.ECDSA,d.Mac),g=d.Signature,y=JSON;if("string"!=typeof t&&"object"!=(void 0===t?"undefined":f(t)))throw"spHeader must be JSON string or object: "+t;if("object"==(void 0===t?"undefined":f(t))&&(o=t,s=y.stringify(o)),"string"==typeof t){if(!l(s=t))throw"JWS Head is not safe JSON string: "+s;o=h(s)}if(a=r,"object"==(void 0===r?"undefined":f(r))&&(a=y.stringify(r)),""!=e&&null!=e||void 0===o.alg||(e=o.alg),""!=e&&null!=e&&void 0===o.alg&&(o.alg=e,s=y.stringify(o)),e!==o.alg)throw"alg and sHeader.alg doesn't match: "+e+"!="+o.alg;var v=null;if(void 0===c.jwsalg2sigalg[e])throw"unsupported alg name: "+e;v=c.jwsalg2sigalg[e];var m=ce(s)+"."+ce(a),w="";if("Hmac"==v.substr(0,4)){if(void 0===n)throw"mac key shall be specified for HS* alg";var b=new p({alg:v,prov:"cryptojs",pass:n});b.updateString(m),w=b.doFinal()}else if(-1!=v.indexOf("withECDSA")){(S=new g({alg:v})).init(n,i),S.updateString(m);var _=S.sign();w=ue.crypto.ECDSA.asn1SigToConcatSig(_)}else{var S;"none"!=v&&((S=new g({alg:v})).init(n,i),S.updateString(m),w=S.sign())}return m+"."+me(w)},ue.jws.JWS.verify=function(e,t,r){var n,i=ue,s=i.jws.JWS,o=s.readSafeJSONString,a=i.crypto,u=a.ECDSA,c=a.Mac,h=a.Signature;void 0!==f(ne)&&(n=ne);var l=e.split(".");if(3!==l.length)return!1;var d,p=l[0]+"."+l[1],g=we(l[2]),y=o(he(l[0])),v=null;if(void 0===y.alg)throw"algorithm not specified in header";if(d=(v=y.alg).substr(0,2),null!=r&&"[object Array]"===Object.prototype.toString.call(r)&&r.length>0&&-1==(":"+r.join(":")+":").indexOf(":"+v+":"))throw"algorithm '"+v+"' not accepted in the list";if("none"!=v&&null===t)throw"key shall be specified to verify.";if("string"==typeof t&&-1!=t.indexOf("-----BEGIN ")&&(t=qe.getKey(t)),!("RS"!=d&&"PS"!=d||t instanceof n))throw"key shall be a RSAKey obj for RS* and PS* algs";if("ES"==d&&!(t instanceof u))throw"key shall be a ECDSA obj for ES* algs";var m=null;if(void 0===s.jwsalg2sigalg[y.alg])throw"unsupported alg name: "+v;if("none"==(m=s.jwsalg2sigalg[v]))throw"not supported";if("Hmac"==m.substr(0,4)){if(void 0===t)throw"hexadecimal key shall be specified for HMAC";var w=new c({alg:m,pass:t});return w.updateString(p),g==w.doFinal()}if(-1!=m.indexOf("withECDSA")){var b,_=null;try{_=u.concatSigToASN1Sig(g)}catch(e){return!1}return(b=new h({alg:m})).init(t),b.updateString(p),b.verify(_)}return(b=new h({alg:m})).init(t),b.updateString(p),b.verify(g)},ue.jws.JWS.parse=function(e){var t,r,n,i=e.split("."),s={};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]),s.headerObj=ue.jws.JWS.readSafeJSONString(he(t)),s.payloadObj=ue.jws.JWS.readSafeJSONString(he(r)),s.headerPP=JSON.stringify(s.headerObj,null," "),null==s.payloadObj?s.payloadPP=he(r):s.payloadPP=JSON.stringify(s.payloadObj,null," "),void 0!==n&&(s.sigHex=we(n)),s},ue.jws.JWS.verifyJWT=function(e,t,r){var n=ue.jws,i=n.JWS,s=i.readSafeJSONString,o=i.inArray,a=i.includedArray,u=e.split("."),c=u[0],h=u[1],l=(we(u[2]),s(he(c))),d=s(he(h));if(void 0===l.alg)return!1;if(void 0===r.alg)throw"acceptField.alg shall be specified";if(!o(l.alg,r.alg))return!1;if(void 0!==d.iss&&"object"===f(r.iss)&&!o(d.iss,r.iss))return!1;if(void 0!==d.sub&&"object"===f(r.sub)&&!o(d.sub,r.sub))return!1;if(void 0!==d.aud&&"object"===f(r.aud))if("string"==typeof d.aud){if(!o(d.aud,r.aud))return!1}else if("object"==f(d.aud)&&!a(d.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!==d.exp&&"number"==typeof d.exp&&d.exp+r.gracePeriod<p||void 0!==d.nbf&&"number"==typeof d.nbf&&p<d.nbf-r.gracePeriod||void 0!==d.iat&&"number"==typeof d.iat&&p<d.iat-r.gracePeriod||void 0!==d.jti&&void 0!==r.jti&&d.jti!==r.jti||!i.verify(e,t,r.alg))},ue.jws.JWS.includedArray=function(e,t){var r=ue.jws.JWS.inArray;if(null===e)return!1;if("object"!==(void 0===e?"undefined":f(e)))return!1;if("number"!=typeof e.length)return!1;for(var n=0;n<e.length;n++)if(!r(e[n],t))return!1;return!0},ue.jws.JWS.inArray=function(e,t){if(null===t)return!1;if("object"!==(void 0===t?"undefined":f(t)))return!1;if("number"!=typeof t.length)return!1;for(var r=0;r<t.length;r++)if(t[r]==e)return!0;return!1},ue.jws.JWS.jwsalg2sigalg={HS256:"HmacSHA256",HS384:"HmacSHA384",HS512:"HmacSHA512",RS256:"SHA256withRSA",RS384:"SHA384withRSA",RS512:"SHA512withRSA",ES256:"SHA256withECDSA",ES384:"SHA384withECDSA",PS256:"SHA256withRSAandMGF1",PS384:"SHA384withRSAandMGF1",PS512:"SHA512withRSAandMGF1",none:"none"},ue.jws.JWS.isSafeJSONString=function(e,t,r){var n=null;try{return"object"!=(void 0===(n=ae(e))?"undefined":f(n))||n.constructor===Array?0:(t&&(t[r]=n),1)}catch(e){return 0}},ue.jws.JWS.readSafeJSONString=function(e){var t=null;try{return"object"!=(void 0===(t=ae(e))?"undefined":f(t))||t.constructor===Array?null:t}catch(e){return null}},ue.jws.JWS.getEncodedSignatureValueFromJWS=function(e){var t=e.match(/^[^.]+\.[^.]+\.([^.]+)$/);if(null==t)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";return t[1]},ue.jws.JWS.getJWKthumbprint=function(e){if("RSA"!==e.kty&&"EC"!==e.kty&&"oct"!==e.kty)throw"unsupported algorithm for JWK Thumprint";var t="{";if("RSA"===e.kty){if("string"!=typeof e.n||"string"!=typeof e.e)throw"wrong n and e value for RSA key";t+='"e":"'+e.e+'",',t+='"kty":"'+e.kty+'",',t+='"n":"'+e.n+'"}'}else if("EC"===e.kty){if("string"!=typeof e.crv||"string"!=typeof e.x||"string"!=typeof e.y)throw"wrong crv, x and y value for EC key";t+='"crv":"'+e.crv+'",',t+='"kty":"'+e.kty+'",',t+='"x":"'+e.x+'",',t+='"y":"'+e.y+'"}'}else if("oct"===e.kty){if("string"!=typeof e.k)throw"wrong k value for oct(symmetric) key";t+='"kty":"'+e.kty+'",',t+='"k":"'+e.k+'"}'}var r=Ee(t);return me(ue.crypto.Util.hashHex(r,"sha256"))},ue.jws.IntDate={},ue.jws.IntDate.get=function(e){var t=ue.jws.IntDate,r=t.getNow,n=t.getZulu;if("now"==e)return r();if("now + 1hour"==e)return r()+3600;if("now + 1day"==e)return r()+86400;if("now + 1month"==e)return r()+2592e3;if("now + 1year"==e)return r()+31536e3;if(e.match(/Z$/))return n(e);if(e.match(/^[0-9]+$/))return parseInt(e);throw"unsupported format: "+e},ue.jws.IntDate.getZulu=function(e){return Ce(e)},ue.jws.IntDate.getNow=function(){return~~(new Date/1e3)},ue.jws.IntDate.intDate2UTCString=function(e){return new Date(1e3*e).toUTCString()},ue.jws.IntDate.intDate2Zulu=function(e){var t=new Date(1e3*e);return("0000"+t.getUTCFullYear()).slice(-4)+("00"+(t.getUTCMonth()+1)).slice(-2)+("00"+t.getUTCDate()).slice(-2)+("00"+t.getUTCHours()).slice(-2)+("00"+t.getUTCMinutes()).slice(-2)+("00"+t.getUTCSeconds()).slice(-2)+"Z"},t.SecureRandom=ee,t.rng_seed_time=z,t.BigInteger=S,t.RSAKey=ne;var Je=ue.crypto.EDSA;t.EDSA=Je;var ze=ue.crypto.DSA;t.DSA=ze;var Xe=ue.crypto.Signature;t.Signature=Xe;var Ge=ue.crypto.MessageDigest;t.MessageDigest=Ge;var Ye=ue.crypto.Mac;t.Mac=Ye;var Qe=ue.crypto.Cipher;t.Cipher=Qe,t.KEYUTIL=qe,t.ASN1HEX=le,t.X509=We,t.CryptoJS=y,t.b64tohex=b,t.b64toBA=_,t.stoBA=de,t.BAtos=fe,t.BAtohex=pe,t.stohex=ge,t.stob64=function(e){return w(ge(e))},t.stob64u=function(e){return ye(w(ge(e)))},t.b64utos=function(e){return fe(_(ve(e)))},t.b64tob64u=ye,t.b64utob64=ve,t.hex2b64=w,t.hextob64u=me,t.b64utohex=we,t.utf8tob64u=ce,t.b64utoutf8=he,t.utf8tob64=function(e){return w(Re(De(e)))},t.b64toutf8=function(e){return decodeURIComponent(Pe(b(e)))},t.utf8tohex=be,t.hextoutf8=_e,t.hextorstr=Se,t.rstrtohex=Ee,t.hextob64=xe,t.hextob64nl=Ae,t.b64nltohex=Fe,t.hextopem=Te,t.pemtohex=ke,t.hextoArrayBuffer=function(e){if(e.length%2!=0)throw"input is not even length";if(null==e.match(/^[0-9A-Fa-f]+$/))throw"input is not hexadecimal";for(var t=new ArrayBuffer(e.length/2),r=new DataView(t),n=0;n<e.length/2;n++)r.setUint8(n,parseInt(e.substr(2*n,2),16));return t},t.ArrayBuffertohex=function(e){for(var t="",r=new DataView(e),n=0;n<e.byteLength;n++)t+=("00"+r.getUint8(n).toString(16)).slice(-2);return t},t.zulutomsec=Ie,t.zulutosec=Ce,t.zulutodate=function(e){return new Date(Ie(e))},t.datetozulu=function(e,t,r){var n,i=e.getUTCFullYear();if(t){if(i<1950||2049<i)throw"not proper year for UTCTime: "+i;n=(""+i).slice(-2)}else n=("000"+i).slice(-4);if(n+=("0"+(e.getUTCMonth()+1)).slice(-2),n+=("0"+e.getUTCDate()).slice(-2),n+=("0"+e.getUTCHours()).slice(-2),n+=("0"+e.getUTCMinutes()).slice(-2),n+=("0"+e.getUTCSeconds()).slice(-2),r){var s=e.getUTCMilliseconds();0!==s&&(n+="."+(s=(s=("00"+s).slice(-3)).replace(/0+$/g,"")))}return n+"Z"},t.uricmptohex=Re,t.hextouricmp=Pe,t.ipv6tohex=Ne,t.hextoipv6=Ue,t.hextoip=Oe,t.iptohex=function(e){var t="malformed IP address";if(!(e=e.toLowerCase(e)).match(/^[0-9.]+$/)){if(e.match(/^[0-9a-f:]+$/)&&-1!==e.indexOf(":"))return Ne(e);throw t}var r=e.split(".");if(4!==r.length)throw t;var n="";try{for(var i=0;i<4;i++)n+=("0"+parseInt(r[i]).toString(16)).slice(-2);return n}catch(e){throw t}},t.encodeURIComponentAll=De,t.newline_toUnix=function(e){return e.replace(/\r\n/gm,"\n")},t.newline_toDos=function(e){return(e=e.replace(/\r\n/gm,"\n")).replace(/\n/gm,"\r\n")},t.hextoposhex=Me,t.intarystrtohex=function(e){e=(e=(e=e.replace(/^\s*\[\s*/,"")).replace(/\s*\]\s*$/,"")).replace(/\s*/g,"");try{return e.split(/,/).map(function(e,t,r){var n=parseInt(e);if(n<0||255<n)throw"integer not in range 0-255";return("00"+n.toString(16)).slice(-2)}).join("")}catch(e){throw"malformed integer array string: "+e}},t.strdiffidx=function(e,t){var r=e.length;e.length>t.length&&(r=t.length);for(var n=0;n<r;n++)if(e.charCodeAt(n)!=t.charCodeAt(n))return n;return e.length!=t.length?r:-1},t.KJUR=ue;var Ze=ue.crypto;t.crypto=Ze;var et=ue.asn1;t.asn1=et;var tt=ue.jws;t.jws=tt;var rt=ue.lang;t.lang=rt}).call(this,r(28).Buffer)},function(e,t,r){"use strict";(function(e){
22
+ 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,u,c=r.match(e),h=c[0],l=!1;"{"===h?a={}:"["===h?a=[]:(a=[],l=!0);for(var d=[a],p=1-l,g=c.length;p<g;++p){var y;switch((h=c[p]).charCodeAt(0)){default:(y=d[0])[u||y.length]=+h,u=void 0;break;case 34:if(-1!==(h=h.substring(1,h.length-1)).indexOf("\\")&&(h=h.replace(t,n)),y=d[0],!u){if(!(y instanceof Array)){u=h||i;break}u=y.length}y[u]=h,u=void 0;break;case 91:y=d[0],d.unshift(y[u||y.length]=[]),u=void 0;break;case 93:case 125:d.shift();break;case 102:(y=d[0])[u||y.length]=!1,u=void 0;break;case 110:(y=d[0])[u||y.length]=null,u=void 0;break;case 116:(y=d[0])[u||y.length]=!0,u=void 0;break;case 123:y=d[0],d.unshift(y[u||y.length]={}),u=void 0}}if(l){if(1!==d.length)throw new Error;a=a[0]}else if(d.length)throw new Error;return s&&(a=function e(t,r){var n=t[r];if(n&&"object"===(void 0===n?"undefined":f(n))){var i=null;for(var a in n)if(o.call(n,a)&&n!==t){var u=e(n,a);void 0!==u?n[a]=u:(i||(i=[]),i.push(a))}if(i)for(var c=i.length;--c>=0;)delete n[i[c]]}return s.call(t,r,n)}({"":a},"")),a}}();void 0!==ue&&ue||(t.KJUR=ue={}),void 0!==ue.asn1&&ue.asn1||(ue.asn1={}),ue.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;i<r;i++)n+="f";t=new b(n,16).xor(e).add(b.ONE).toString(16).replace(/^-/,"")}return t},this.getPEMStringFromHex=function(e,t){return ke(e,t)},this.newObject=function(e){var t=ue.asn1,r=t.ASN1Object,n=t.DERBoolean,i=t.DERInteger,o=t.DERBitString,s=t.DEROctetString,a=t.DERNull,u=t.DERObjectIdentifier,c=t.DEREnumerated,h=t.DERUTF8String,l=t.DERNumericString,d=t.DERPrintableString,f=t.DERTeletexString,p=t.DERIA5String,g=t.DERUTCTime,y=t.DERGeneralizedTime,v=t.DERVisibleString,m=t.DERBMPString,w=t.DERSequence,_=t.DERSet,S=t.DERTaggedObject,b=t.ASN1Util.newObject;if(e instanceof t.ASN1Object)return e;var E=Object.keys(e);if(1!=E.length)throw new Error("key of param shall be only one.");var F=E[0];if(-1==":asn1:bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:visstr:bmpstr:seq:set:tag:".indexOf(":"+F+":"))throw new Error("undefined key: "+F);if("bool"==F)return new n(e[F]);if("int"==F)return new i(e[F]);if("bitstr"==F)return new o(e[F]);if("octstr"==F)return new s(e[F]);if("null"==F)return new a(e[F]);if("oid"==F)return new u(e[F]);if("enum"==F)return new c(e[F]);if("utf8str"==F)return new h(e[F]);if("numstr"==F)return new l(e[F]);if("prnstr"==F)return new d(e[F]);if("telstr"==F)return new f(e[F]);if("ia5str"==F)return new p(e[F]);if("utctime"==F)return new g(e[F]);if("gentime"==F)return new y(e[F]);if("visstr"==F)return new v(e[F]);if("bmpstr"==F)return new m(e[F]);if("asn1"==F)return new r(e[F]);if("seq"==F){for(var x=e[F],A=[],k=0;k<x.length;k++){var P=b(x[k]);A.push(P)}return new w({array:A})}if("set"==F){for(x=e[F],A=[],k=0;k<x.length;k++)P=b(x[k]),A.push(P);return new _({array:A})}if("tag"==F){var T=e[F];if("[object Array]"===Object.prototype.toString.call(T)&&3==T.length){var I=b(T[2]);return new S({tag:T[0],explicit:T[1],obj:I})}return new S(T)}},this.jsonToASN1HEX=function(e){return this.newObject(e).getEncodedHex()}},ue.asn1.ASN1Util.oidHexToInt=function(e){for(var t="",r=parseInt(e.substr(0,2),16),n=(t=Math.floor(r/40)+"."+r%40,""),i=2;i<e.length;i+=2){var o=("00000000"+parseInt(e.substr(i,2),16).toString(2)).slice(-8);n+=o.substr(1,7),"0"==o.substr(0,1)&&(t=t+"."+new b(n,2).toString(10),n="")}return t},ue.asn1.ASN1Util.oidIntToHex=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},r=function(e){var r="",n=new b(e,10).toString(2),i=7-n.length%7;7==i&&(i=0);for(var o="",s=0;s<i;s++)o+="0";for(n=o+n,s=0;s<n.length-1;s+=7){var a=n.substr(s,7);s!=n.length-7&&(a="1"+a),r+=t(parseInt(a,2))}return r};if(!e.match(/^[0-9.]+$/))throw"malformed oid string: "+e;var n="",i=e.split("."),o=40*parseInt(i[0])+parseInt(i[1]);n+=t(o),i.splice(0,2);for(var s=0;s<i.length;s++)n+=r(i[s]);return n},ue.asn1.ASN1Object=function(e){this.params=null,this.getLengthHexFromValue=function(){if(void 0===this.hV||null==this.hV)throw new Error("this.hV is null or undefined");if(this.hV.length%2==1)throw new Error("value hex must be even length: n=0,v="+this.hV);var e=this.hV.length/2,t=e.toString(16);if(t.length%2==1&&(t="0"+t),e<128)return t;var r=t.length/2;if(r>15)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)},ue.asn1.DERAbstractString=function(e){ue.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=_e(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))},Be(ue.asn1.DERAbstractString,ue.asn1.ASN1Object),ue.asn1.DERAbstractTime=function(e){ue.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 u=n(String(a),3);s=s+"."+(u=u.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}},Be(ue.asn1.DERAbstractTime,ue.asn1.ASN1Object),ue.asn1.DERAbstractStructured=function(e){ue.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)},Be(ue.asn1.DERAbstractStructured,ue.asn1.ASN1Object),ue.asn1.DERBoolean=function(e){ue.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=0==e?"010100":"0101ff"},Be(ue.asn1.DERBoolean,ue.asn1.ASN1Object),ue.asn1.DERInteger=function(e){ue.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=ue.asn1.ASN1Util.bigIntToMinTwosComplementsHex(e)},this.setByInteger=function(e){var t=new b(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))},Be(ue.asn1.DERInteger,ue.asn1.ASN1Object),ue.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=ue.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.getEncodedHex()}ue.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||7<e)throw"unused bits shall be from 0 to 7: u = "+e;var r="0"+e;this.hTLV=null,this.isModified=!0,this.hV=r+t},this.setByBinaryString=function(e){var t=8-(e=e.replace(/0+$/,"")).length%8;8==t&&(t=0);for(var r=0;r<=t;r++)e+="0";var n="";for(r=0;r<e.length-1;r+=8){var i=e.substr(r,8),o=parseInt(i,2).toString(16);1==o.length&&(o="0"+o),n+=o}this.hTLV=null,this.isModified=!0,this.hV="0"+t+n},this.setByBooleanArray=function(e){for(var t="",r=0;r<e.length;r++)1==e[r]?t+="1":t+="0";this.setByBinaryString(t)},this.newFalseArray=function(e){for(var t=new Array(e),r=0;r<e;r++)t[r]=!1;return t},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e&&e.toLowerCase().match(/^[0-9a-f]+$/)?this.setHexValueIncludingUnusedBits(e):void 0!==e.hex?this.setHexValueIncludingUnusedBits(e.hex):void 0!==e.bin?this.setByBinaryString(e.bin):void 0!==e.array&&this.setByBooleanArray(e.array))},Be(ue.asn1.DERBitString,ue.asn1.ASN1Object),ue.asn1.DEROctetString=function(e){if(void 0!==e&&void 0!==e.obj){var t=ue.asn1.ASN1Util.newObject(e.obj);e.hex=t.getEncodedHex()}ue.asn1.DEROctetString.superclass.constructor.call(this,e),this.hT="04"},Be(ue.asn1.DEROctetString,ue.asn1.DERAbstractString),ue.asn1.DERNull=function(){ue.asn1.DERNull.superclass.constructor.call(this),this.hT="05",this.hTLV="0500"},Be(ue.asn1.DERNull,ue.asn1.ASN1Object),ue.asn1.DERObjectIdentifier=function(e){ue.asn1.DERObjectIdentifier.superclass.constructor.call(this),this.hT="06",this.setValueHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.setValueOidString=function(e){var t=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},r=function(e){var r="",n=parseInt(e,10).toString(2),i=7-n.length%7;7==i&&(i=0);for(var o="",s=0;s<i;s++)o+="0";for(n=o+n,s=0;s<n.length-1;s+=7){var a=n.substr(s,7);s!=n.length-7&&(a="1"+a),r+=t(parseInt(a,2))}return r};try{if(!e.match(/^[0-9.]+$/))return null;var n="",i=e.split("."),o=40*parseInt(i[0],10)+parseInt(i[1],10);n+=t(o),i.splice(0,2);for(var s=0;s<i.length;s++)n+=r(i[s]);return n}catch(e){return null}}(e);if(null==t)throw new Error("malformed oid string: "+e);this.hTLV=null,this.isModified=!0,this.s=null,this.hV=t},this.setValueName=function(e){var t=ue.asn1.x509.OID.name2oid(e);if(""===t)throw new Error("DERObjectIdentifier oidName undefined: "+e);this.setValueOidString(t)},this.setValueNameOrOid=function(e){e.match(/^[0-2].[0-9.]+$/)?this.setValueOidString(e):this.setValueName(e)},this.getFreshValueHex=function(){return this.hV},this.setByParam=function(e){"string"==typeof e?this.setValueNameOrOid(e):void 0!==e.oid?this.setValueNameOrOid(e.oid):void 0!==e.name?this.setValueNameOrOid(e.name):void 0!==e.hex&&this.setValueHex(e.hex)},void 0!==e&&this.setByParam(e)},Be(ue.asn1.DERObjectIdentifier,ue.asn1.ASN1Object),ue.asn1.DEREnumerated=function(e){ue.asn1.DEREnumerated.superclass.constructor.call(this),this.hT="0a",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=ue.asn1.ASN1Util.bigIntToMinTwosComplementsHex(e)},this.setByInteger=function(e){var t=new b(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.int?this.setByInteger(e.int):"number"==typeof e?this.setByInteger(e):void 0!==e.hex&&this.setValueHex(e.hex))},Be(ue.asn1.DEREnumerated,ue.asn1.ASN1Object),ue.asn1.DERUTF8String=function(e){ue.asn1.DERUTF8String.superclass.constructor.call(this,e),this.hT="0c"},Be(ue.asn1.DERUTF8String,ue.asn1.DERAbstractString),ue.asn1.DERNumericString=function(e){ue.asn1.DERNumericString.superclass.constructor.call(this,e),this.hT="12"},Be(ue.asn1.DERNumericString,ue.asn1.DERAbstractString),ue.asn1.DERPrintableString=function(e){ue.asn1.DERPrintableString.superclass.constructor.call(this,e),this.hT="13"},Be(ue.asn1.DERPrintableString,ue.asn1.DERAbstractString),ue.asn1.DERTeletexString=function(e){ue.asn1.DERTeletexString.superclass.constructor.call(this,e),this.hT="14"},Be(ue.asn1.DERTeletexString,ue.asn1.DERAbstractString),ue.asn1.DERIA5String=function(e){ue.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="16"},Be(ue.asn1.DERIA5String,ue.asn1.DERAbstractString),ue.asn1.DERVisibleString=function(e){ue.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="1a"},Be(ue.asn1.DERVisibleString,ue.asn1.DERAbstractString),ue.asn1.DERBMPString=function(e){ue.asn1.DERBMPString.superclass.constructor.call(this,e),this.hT="1e"},Be(ue.asn1.DERBMPString,ue.asn1.DERAbstractString),ue.asn1.DERUTCTime=function(e){ue.asn1.DERUTCTime.superclass.constructor.call(this,e),this.hT="17",this.setByDate=function(e){this.hTLV=null,this.isModified=!0,this.date=e,this.s=this.formatDate(this.date,"utc"),this.hV=ge(this.s)},this.getFreshValueHex=function(){return void 0===this.date&&void 0===this.s&&(this.date=new Date,this.s=this.formatDate(this.date,"utc"),this.hV=ge(this.s)),this.hV},void 0!==e&&(void 0!==e.str?this.setString(e.str):"string"==typeof e&&e.match(/^[0-9]{12}Z$/)?this.setString(e):void 0!==e.hex?this.setStringHex(e.hex):void 0!==e.date&&this.setByDate(e.date))},Be(ue.asn1.DERUTCTime,ue.asn1.DERAbstractTime),ue.asn1.DERGeneralizedTime=function(e){ue.asn1.DERGeneralizedTime.superclass.constructor.call(this,e),this.hT="18",this.withMillis=!1,this.setByDate=function(e){this.hTLV=null,this.isModified=!0,this.date=e,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=ge(this.s)},this.getFreshValueHex=function(){return void 0===this.date&&void 0===this.s&&(this.date=new Date,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=ge(this.s)),this.hV},void 0!==e&&(void 0!==e.str?this.setString(e.str):"string"==typeof e&&e.match(/^[0-9]{14}Z$/)?this.setString(e):void 0!==e.hex?this.setStringHex(e.hex):void 0!==e.date&&this.setByDate(e.date),!0===e.millis&&(this.withMillis=!0))},Be(ue.asn1.DERGeneralizedTime,ue.asn1.DERAbstractTime),ue.asn1.DERSequence=function(e){ue.asn1.DERSequence.superclass.constructor.call(this,e),this.hT="30",this.getFreshValueHex=function(){for(var e="",t=0;t<this.asn1Array.length;t++)e+=this.asn1Array[t].getEncodedHex();return this.hV=e,this.hV}},Be(ue.asn1.DERSequence,ue.asn1.DERAbstractStructured),ue.asn1.DERSet=function(e){ue.asn1.DERSet.superclass.constructor.call(this,e),this.hT="31",this.sortFlag=!0,this.getFreshValueHex=function(){for(var e=new Array,t=0;t<this.asn1Array.length;t++){var r=this.asn1Array[t];e.push(r.getEncodedHex())}return 1==this.sortFlag&&e.sort(),this.hV=e.join(""),this.hV},void 0!==e&&void 0!==e.sortflag&&0==e.sortflag&&(this.sortFlag=!1)},Be(ue.asn1.DERSet,ue.asn1.DERAbstractStructured),ue.asn1.DERTaggedObject=function(e){ue.asn1.DERTaggedObject.superclass.constructor.call(this);var t=ue.asn1;this.hT="a0",this.hV="",this.isExplicit=!0,this.asn1Object=null,this.setASN1Object=function(e,t,r){this.hT=t,this.isExplicit=e,this.asn1Object=r,this.isExplicit?(this.hV=this.asn1Object.getEncodedHex(),this.hTLV=null,this.isModified=!0):(this.hV=null,this.hTLV=r.getEncodedHex(),this.hTLV=this.hTLV.replace(/^../,t),this.isModified=!1)},this.getFreshValueHex=function(){return this.hV},this.setByParam=function(e){null!=e.tag&&(this.hT=e.tag),null!=e.explicit&&(this.isExplicit=e.explicit),null!=e.tage&&(this.hT=e.tage,this.isExplicit=!0),null!=e.tagi&&(this.hT=e.tagi,this.isExplicit=!1),null!=e.obj&&(e.obj instanceof t.ASN1Object?(this.asn1Object=e.obj,this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)):"object"==f(e.obj)&&(this.asn1Object=t.ASN1Util.newObject(e.obj),this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)))},null!=e&&this.setByParam(e)},Be(ue.asn1.DERTaggedObject,ue.asn1.ASN1Object);var ue,ce,he,le=new function(){};function de(e){for(var t=new Array,r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function fe(e){for(var t="",r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}function pe(e){for(var t="",r=0;r<e.length;r++){var n=e[r].toString(16);1==n.length&&(n="0"+n),t+=n}return t}function ge(e){return pe(de(e))}function ye(e){return(e=(e=e.replace(/\=/g,"")).replace(/\+/g,"-")).replace(/\//g,"_")}function ve(e){return e.length%4==2?e+="==":e.length%4==3&&(e+="="),(e=e.replace(/-/g,"+")).replace(/_/g,"/")}function me(e){return e.length%2==1&&(e="0"+e),ye(w(e))}function we(e){return _(ve(e))}function _e(e){return Ce(Oe(e))}function Se(e){return decodeURIComponent(Re(e))}function be(e){for(var t="",r=0;r<e.length-1;r+=2)t+=String.fromCharCode(parseInt(e.substr(r,2),16));return t}function Ee(e){for(var t="",r=0;r<e.length;r++)t+=("0"+e.charCodeAt(r).toString(16)).slice(-2);return t}function Fe(e){return w(e)}function xe(e){var t=Fe(e).replace(/(.{64})/g,"$1\r\n");return t.replace(/\r\n$/,"")}function Ae(e){return _(e.replace(/[^0-9A-Za-z\/+=]*/g,""))}function ke(e,t){return"-----BEGIN "+t+"-----\r\n"+xe(e)+"\r\n-----END "+t+"-----\r\n"}function Pe(e,t){if(-1==e.indexOf("-----BEGIN "))throw"can't find PEM header: "+t;return Ae(e=void 0!==t?(e=e.replace(new RegExp("^[^]*-----BEGIN "+t+"-----"),"")).replace(new RegExp("-----END "+t+"-----[^]*$"),""):(e=e.replace(/^[^]*-----BEGIN [^-]+-----/,"")).replace(/-----END [^-]+-----[^]*$/,""))}function Te(e){var t,r,n,i,o,s,a,u,c,h,l;if(l=e.match(/^(\d{2}|\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/))return u=l[1],t=parseInt(u),2===u.length&&(50<=t&&t<100?t=1900+t:0<=t&&t<50&&(t=2e3+t)),r=parseInt(l[2])-1,n=parseInt(l[3]),i=parseInt(l[4]),o=parseInt(l[5]),s=parseInt(l[6]),a=0,""!==(c=l[7])&&(h=(c.substr(1)+"00").substr(0,3),a=parseInt(h)),Date.UTC(t,r,n,i,o,s,a);throw"unsupported zulu format: "+e}function Ie(e){return~~(Te(e)/1e3)}function Ce(e){return e.replace(/%/g,"")}function Re(e){return e.replace(/(..)/g,"%$1")}function Ue(e){var t="malformed IPv6 address";if(!e.match(/^[0-9A-Fa-f:]+$/))throw t;var r=(e=e.toLowerCase()).split(":").length-1;if(r<2)throw t;var n=":".repeat(7-r+2),i=(e=e.replace("::",n)).split(":");if(8!=i.length)throw t;for(var o=0;o<8;o++)i[o]=("0000"+i[o]).slice(-4);return i.join("")}function Le(e){if(!e.match(/^[0-9A-Fa-f]{32}$/))throw"malformed IPv6 address octet";for(var t=(e=e.toLowerCase()).match(/.{1,4}/g),r=0;r<8;r++)t[r]=t[r].replace(/^0+/,""),""==t[r]&&(t[r]="0");var n=(e=":"+t.join(":")+":").match(/:(0:){2,}/g);if(null===n)return e.slice(1,-1);var i="";for(r=0;r<n.length;r++)n[r].length>i.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?Le(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 Ne(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 Se((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 Se((224|(240&t)>>4).toString(16)+n.toString(16)+i.toString(16))}).join("")}function Oe(e){for(var t=encodeURIComponent(e),r="",n=0;n<t.length;n++)"%"==t[n]?(r+=t.substr(n,3),n+=2):r=r+"%"+ge(t[n]);return r}function He(e){return!(e.length%2!=0||!e.match(/^[0-9a-f]+$/)&&!e.match(/^[0-9A-F]+$/))}function je(e){return e.length%2==1?"0"+e:e.substr(0,1)>"7"?"00"+e:e}le.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<r&&r<10?r+1:-2},le.getL=function(e,t){var r=le.getLblen(e,t);return r<1?"":e.substr(t+2,2*r)},le.getVblen=function(e,t){var r;return""==(r=le.getL(e,t))?-1:("8"===r.substr(0,1)?new b(r.substr(2),16):new b(r,16)).intValue()},le.getVidx=function(e,t){var r=le.getLblen(e,t);return r<0?r:t+2*(r+1)},le.getV=function(e,t){var r=le.getVidx(e,t),n=le.getVblen(e,t);return e.substr(r,2*n)},le.getTLV=function(e,t){return e.substr(t,2)+le.getL(e,t)+le.getV(e,t)},le.getTLVblen=function(e,t){return 2+2*le.getLblen(e,t)+2*le.getVblen(e,t)},le.getNextSiblingIdx=function(e,t){return le.getVidx(e,t)+2*le.getVblen(e,t)},le.getChildIdx=function(e,t){var r,n,i,o=le,s=[];r=o.getVidx(e,t),n=2*o.getVblen(e,t),"03"==e.substr(t,2)&&(r+=2,n-=2),i=0;for(var a=r;i<=n;){var u=o.getTLVblen(e,a);if((i+=u)<=n&&s.push(a),a+=u,i>=n)break}return s},le.getNthChildIdx=function(e,t,r){return le.getChildIdx(e,t)[r]},le.getIdxbyList=function(e,t,r,n){var i,o,s=le;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)},le.getIdxbyListEx=function(e,t,r,n){var i,o,s=le;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,u=0;u<o.length;u++){var c=e.substr(o[u],2);if("number"==typeof i&&!s.isContextTag(c)&&a==i||"string"==typeof i&&s.isContextTag(c,i))return s.getIdxbyListEx(e,o[u],r,n);s.isContextTag(c)||a++}return-1},le.getTLVbyList=function(e,t,r,n){var i=le,o=i.getIdxbyList(e,t,r,n);return-1==o||o>=e.length?null:i.getTLV(e,o)},le.getTLVbyListEx=function(e,t,r,n){var i=le,o=i.getIdxbyListEx(e,t,r,n);return-1==o?null:i.getTLV(e,o)},le.getVbyList=function(e,t,r,n,i){var o,s,a=le;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)},le.getVbyListEx=function(e,t,r,n,i){var o,s,a=le;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)},le.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=le.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}},le.getOID=function(e,t,r){null==r&&(r=null);try{return"06"!=e.substr(t,2)?r:function(e){if(!He(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;s<i.length/2;s++)o.push(parseInt(i.substr(2*s,2),16));var a=[],u="";for(s=0;s<o.length;s++)128&o[s]?u+=Me((127&o[s]).toString(2),7):(u+=Me((127&o[s]).toString(2),7),a.push(new String(parseInt(u,2))),u="");var c=t.join(".");return a.length>0&&(c=c+"."+a.join(".")),c}catch(e){return null}}(le.getV(e,t))}catch(e){return r}},le.getOIDName=function(e,t,r){null==r&&(r=null);try{var n=le.getOID(e,t,r);if(n==r)return r;var i=ue.asn1.x509.OID.oid2name(n);return""==i?n:i}catch(e){return r}},le.getString=function(e,t,r){null==r&&(r=null);try{return be(le.getV(e,t))}catch(e){return r}},le.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;a<o.length/2;a++)s.push(parseInt(o.substr(2*a,2),16));var u=[],c="";for(a=0;a<s.length;a++)128&s[a]?c+=t((127&s[a]).toString(2),7):(c+=t((127&s[a]).toString(2),7),u.push(new String(parseInt(c,2))),c="");var h=r.join(".");return u.length>0&&(h=h+"."+u.join(".")),h},le.dump=function(e,t,r,n){var i=le,o=i.getV,s=i.dump,a=i.getChildIdx,u=e;e instanceof ue.asn1.ASN1Object&&(u=e.getEncodedHex());var c=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 h,l=t.ommit_long_octet;if("01"==(h=u.substr(r,2)))return"00"==(d=o(u,r))?n+"BOOLEAN FALSE\n":n+"BOOLEAN TRUE\n";if("02"==h)return n+"INTEGER "+c(d=o(u,r),l)+"\n";if("03"==h){var d=o(u,r);return i.isASN1HEX(d.substr(2))?(S=n+"BITSTRING, encapsulates\n")+s(d.substr(2),t,0,n+" "):n+"BITSTRING "+c(d,l)+"\n"}if("04"==h)return d=o(u,r),i.isASN1HEX(d)?(S=n+"OCTETSTRING, encapsulates\n")+s(d,t,0,n+" "):n+"OCTETSTRING "+c(d,l)+"\n";if("05"==h)return n+"NULL\n";if("06"==h){var f=o(u,r),p=ue.asn1.ASN1Util.oidHexToInt(f),g=ue.asn1.x509.OID.oid2name(p),y=p.replace(/\./g," ");return""!=g?n+"ObjectIdentifier "+g+" ("+y+")\n":n+"ObjectIdentifier ("+y+")\n"}if("0a"==h)return n+"ENUMERATED "+parseInt(o(u,r))+"\n";if("0c"==h)return n+"UTF8String '"+Se(o(u,r))+"'\n";if("13"==h)return n+"PrintableString '"+Se(o(u,r))+"'\n";if("14"==h)return n+"TeletexString '"+Se(o(u,r))+"'\n";if("16"==h)return n+"IA5String '"+Se(o(u,r))+"'\n";if("17"==h)return n+"UTCTime "+Se(o(u,r))+"\n";if("18"==h)return n+"GeneralizedTime "+Se(o(u,r))+"\n";if("1a"==h)return n+"VisualString '"+Se(o(u,r))+"'\n";if("1e"==h)return n+"BMPString '"+Ne(o(u,r))+"'\n";if("30"==h){if("3000"==u.substr(r,4))return n+"SEQUENCE {}\n";S=n+"SEQUENCE\n";var v=t;if((2==(_=a(u,r)).length||3==_.length)&&"06"==u.substr(_[0],2)&&"04"==u.substr(_[_.length-1],2)){g=i.oidname(o(u,_[0]));var m=JSON.parse(JSON.stringify(t));m.x509ExtName=g,v=m}for(var w=0;w<_.length;w++)S+=s(u,v,_[w],n+" ");return S}if("31"==h){S=n+"SET\n";var _=a(u,r);for(w=0;w<_.length;w++)S+=s(u,t,_[w],n+" ");return S}if(128&(h=parseInt(h,16))){var S,b=31&h;if(32&h){for(S=n+"["+b+"]\n",_=a(u,r),w=0;w<_.length;w++)S+=s(u,t,_[w],n+" ");return S}return d=o(u,r),le.isASN1HEX(d)?(S=n+"["+b+"]\n")+s(d,t,0,n+" "):(("68747470"==d.substr(0,8)||"subjectAltName"===t.x509ExtName&&2==b)&&(d=Se(d)),n+"["+b+"] "+d+"\n")}return n+"UNKNOWN("+h+") "+o(u,r)+"\n"},le.isContextTag=function(e,t){var r,n;e=e.toLowerCase();try{r=parseInt(e,16)}catch(e){return-1}if(void 0===t)return 128==(192&r);try{return null!=t.match(/^\[[0-9]+\]$/)&&!((n=parseInt(t.substr(1,t.length-1),10))>31)&&128==(192&r)&&(31&r)==n}catch(e){return!1}},le.isASN1HEX=function(e){var t=le;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},le.checkStrictDER=function(e,t,r,n,i){var o=le;if(void 0===r){if("string"!=typeof e)throw new Error("not hex string");if(e=e.toLowerCase(),!ue.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),u=a.length-2-o.getL(e,t).length;if(u!==2*s)throw new Error("V string length and L's value not the same:"+u+"/"+2*s);if(0===t&&e.length!=a.length)throw new Error("total length and TLV length unmatch:"+e.length+"!="+a.length);var c=e.substr(t,2);if("02"===c){var h=o.getVidx(e,t);if("00"==e.substr(h,2)&&e.charCodeAt(h+2)<56)throw new Error("not least zeros for DER INTEGER")}if(32&parseInt(c,16)){for(var l=o.getVblen(e,t),d=0,f=o.getChildIdx(e,t),p=0;p<f.length;p++)d+=o.getTLV(e,f[p]).length,o.checkStrictDER(e,f[p],r,n,i);if(2*l!=d)throw new Error("sum of children's TLV length and L unmatch: "+2*l+"!="+d)}},le.oidname=function(e){var t=ue.asn1;ue.lang.String.isHex(e)&&(e=t.ASN1Util.oidHexToInt(e));var r=t.x509.OID.oid2name(e);return""===r&&(r=e),r},void 0!==ue&&ue||(t.KJUR=ue={}),void 0!==ue.lang&&ue.lang||(ue.lang={}),ue.lang.String=function(){},"function"==typeof e?(t.utf8tob64u=ce=function(t){return ye(e.from(t,"utf8").toString("base64"))},t.b64utoutf8=he=function(t){return e.from(ve(t),"base64").toString("utf8")}):(t.utf8tob64u=ce=function(e){return me(Ce(Oe(e)))},t.b64utoutf8=he=function(e){return decodeURIComponent(Re(we(e)))}),ue.lang.String.isInteger=function(e){return!!e.match(/^[0-9]+$/)||!!e.match(/^-[0-9]+$/)},ue.lang.String.isHex=function(e){return He(e)},ue.lang.String.isBase64=function(e){return!(!(e=e.replace(/\s+/g,"")).match(/^[0-9A-Za-z+\/]+={0,3}$/)||e.length%4!=0)},ue.lang.String.isBase64URL=function(e){return!e.match(/[+/=]/)&&(e=ve(e),ue.lang.String.isBase64(e))},ue.lang.String.isIntegerArray=function(e){return!!(e=e.replace(/\s+/g,"")).match(/^\[[0-9,]+\]$/)},ue.lang.String.isPrintable=function(e){return null!==e.match(/^[0-9A-Za-z '()+,-./:=?]*$/)},ue.lang.String.isIA5=function(e){return null!==e.match(/^[\x20-\x21\x23-\x7f]*$/)},ue.lang.String.isMail=function(e){return null!==e.match(/^[A-Za-z0-9]{1}[A-Za-z0-9_.-]*@{1}[A-Za-z0-9_.-]{1,}\.[A-Za-z0-9]{1,}$/)};var Me=function(e,t,r){return null==r&&(r="0"),e.length>=t?e:new Array(t-e.length+1).join(r)+e};function Be(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!==ue&&ue||(t.KJUR=ue={}),void 0!==ue.crypto&&ue.crypto||(ue.crypto={}),ue.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="0001",s="00"+n,a="",u=i-4-s.length,c=0;c<u;c+=2)a+="ff";return o+a+s},this.hashString=function(e,t){return new ue.crypto.MessageDigest({alg:t}).digestString(e)},this.hashHex=function(e,t){return new ue.crypto.MessageDigest({alg:t}).digestHex(e)},this.sha1=function(e){return this.hashString(e,"sha1")},this.sha256=function(e){return this.hashString(e,"sha256")},this.sha256Hex=function(e){return this.hashHex(e,"sha256")},this.sha512=function(e){return this.hashString(e,"sha512")},this.sha512Hex=function(e){return this.hashHex(e,"sha512")},this.isKey=function(e){return e instanceof ne||e instanceof ue.crypto.DSA||e instanceof ue.crypto.ECDSA}},ue.crypto.Util.md5=function(e){return new ue.crypto.MessageDigest({alg:"md5",prov:"cryptojs"}).digestString(e)},ue.crypto.Util.ripemd160=function(e){return new ue.crypto.MessageDigest({alg:"ripemd160",prov:"cryptojs"}).digestString(e)},ue.crypto.Util.SECURERANDOMGEN=new ee,ue.crypto.Util.getRandomHexOfNbytes=function(e){var t=new Array(e);return ue.crypto.Util.SECURERANDOMGEN.nextBytes(t),pe(t)},ue.crypto.Util.getRandomBigIntegerOfNbytes=function(e){return new b(ue.crypto.Util.getRandomHexOfNbytes(e),16)},ue.crypto.Util.getRandomHexOfNbits=function(e){var t=e%8,r=new Array((e-t)/8+1);return ue.crypto.Util.SECURERANDOMGEN.nextBytes(r),r[0]=(255<<t&255^255)&r[0],pe(r)},ue.crypto.Util.getRandomBigIntegerOfNbits=function(e){return new b(ue.crypto.Util.getRandomHexOfNbits(e),16)},ue.crypto.Util.getRandomBigIntegerZeroToMax=function(e){for(var t=e.bitLength();;){var r=ue.crypto.Util.getRandomBigIntegerOfNbits(t);if(-1!=e.compareTo(r))return r}},ue.crypto.Util.getRandomBigIntegerMinToMax=function(e,t){var r=e.compareTo(t);if(1==r)throw"biMin is greater than biMax";if(0==r)return e;var n=t.subtract(e);return ue.crypto.Util.getRandomBigIntegerZeroToMax(n).add(e)},ue.crypto.MessageDigest=function(e){this.setAlgAndProvider=function(e,t){if(null!==(e=ue.crypto.MessageDigest.getCanonicalAlgName(e))&&void 0===t&&(t=ue.crypto.Util.DEFAULTPROVIDER[e]),-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(e)&&"cryptojs"==t){try{this.md=ue.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[e].create()}catch(t){throw"setAlgAndProvider hash alg set fail alg="+e+"/"+t}this.updateString=function(e){this.md.update(e)},this.updateHex=function(e){var t=y.enc.Hex.parse(e);this.md.update(t)},this.digest=function(){return this.md.finalize().toString(y.enc.Hex)},this.digestString=function(e){return this.updateString(e),this.digest()},this.digestHex=function(e){return this.updateHex(e),this.digest()}}if(-1!=":sha256:".indexOf(e)&&"sjcl"==t){try{this.md=new sjcl.hash.sha256}catch(t){throw"setAlgAndProvider hash alg set fail alg="+e+"/"+t}this.updateString=function(e){this.md.update(e)},this.updateHex=function(e){var t=sjcl.codec.hex.toBits(e);this.md.update(t)},this.digest=function(){var e=this.md.finalize();return sjcl.codec.hex.fromBits(e)},this.digestString=function(e){return this.updateString(e),this.digest()},this.digestHex=function(e){return this.updateHex(e),this.digest()}}},this.updateString=function(e){throw"updateString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.updateHex=function(e){throw"updateHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digest=function(){throw"digest() not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestString=function(e){throw"digestString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestHex=function(e){throw"digestHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},void 0!==e&&void 0!==e.alg&&(this.algName=e.alg,void 0===e.prov&&(this.provName=ue.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName))},ue.crypto.MessageDigest.getCanonicalAlgName=function(e){return"string"==typeof e&&(e=(e=e.toLowerCase()).replace(/-/,"")),e},ue.crypto.MessageDigest.getHashLength=function(e){var t=ue.crypto.MessageDigest,r=t.getCanonicalAlgName(e);if(void 0===t.HASHLENGTH[r])throw"not supported algorithm: "+e;return t.HASHLENGTH[r]},ue.crypto.MessageDigest.HASHLENGTH={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,ripemd160:20},ue.crypto.Mac=function(e){this.setAlgAndProvider=function(e,t){if(null==(e=e.toLowerCase())&&(e="hmacsha1"),"hmac"!=(e=e.toLowerCase()).substr(0,4))throw"setAlgAndProvider unsupported HMAC alg: "+e;void 0===t&&(t=ue.crypto.Util.DEFAULTPROVIDER[e]),this.algProv=e+"/"+t;var r=e.substr(4);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(r)&&"cryptojs"==t){try{var n=ue.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[r];this.mac=y.algo.HMAC.create(n,this.pass)}catch(e){throw"setAlgAndProvider hash alg set fail hashAlg="+r+"/"+e}this.updateString=function(e){this.mac.update(e)},this.updateHex=function(e){var t=y.enc.Hex.parse(e);this.mac.update(t)},this.doFinal=function(){return this.mac.finalize().toString(y.enc.Hex)},this.doFinalString=function(e){return this.updateString(e),this.doFinal()},this.doFinalHex=function(e){return this.updateHex(e),this.doFinal()}}},this.updateString=function(e){throw"updateString(str) not supported for this alg/prov: "+this.algProv},this.updateHex=function(e){throw"updateHex(hex) not supported for this alg/prov: "+this.algProv},this.doFinal=function(){throw"digest() not supported for this alg/prov: "+this.algProv},this.doFinalString=function(e){throw"digestString(str) not supported for this alg/prov: "+this.algProv},this.doFinalHex=function(e){throw"digestHex(hex) not supported for this alg/prov: "+this.algProv},this.setPassword=function(e){if("string"==typeof e){var t=e;return e.length%2!=1&&e.match(/^[0-9A-Fa-f]+$/)||(t=Ee(e)),void(this.pass=y.enc.Hex.parse(t))}if("object"!=(void 0===e?"undefined":f(e)))throw"KJUR.crypto.Mac unsupported password type: "+e;if(t=null,void 0!==e.hex){if(e.hex.length%2!=0||!e.hex.match(/^[0-9A-Fa-f]+$/))throw"Mac: wrong hex password: "+e.hex;t=e.hex}if(void 0!==e.utf8&&(t=_e(e.utf8)),void 0!==e.rstr&&(t=Ee(e.rstr)),void 0!==e.b64&&(t=_(e.b64)),void 0!==e.b64u&&(t=we(e.b64u)),null==t)throw"KJUR.crypto.Mac unsupported password type: "+e;this.pass=y.enc.Hex.parse(t)},void 0!==e&&(void 0!==e.pass&&this.setPassword(e.pass),void 0!==e.alg&&(this.algName=e.alg,void 0===e.prov&&(this.provName=ue.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName)))},ue.crypto.Signature=function(e){var t=null;if(this._setAlgNames=function(){var e=this.algName.match(/^(.+)with(.+)$/);e&&(this.mdAlgName=e[1].toLowerCase(),this.pubkeyAlgName=e[2].toLowerCase(),"rsaandmgf1"==this.pubkeyAlgName&&"sha"==this.mdAlgName&&(this.mdAlgName="sha1"))},this._zeroPaddingOfSignature=function(e,t){for(var r="",n=t/4-e.length,i=0;i<n;i++)r+="0";return r+e},this.setAlgAndProvider=function(e,t){if(this._setAlgNames(),"cryptojs/jsrsa"!=t)throw new Error("provider not supported: "+t);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(this.mdAlgName)){try{this.md=new ue.crypto.MessageDigest({alg:this.mdAlgName})}catch(e){throw new Error("setAlgAndProvider hash alg set fail alg="+this.mdAlgName+"/"+e)}this.init=function(e,t){var r=null;try{r=void 0===t?Ke.getKey(e):Ke.getKey(e,t)}catch(e){throw"init failed:"+e}if(!0===r.isPrivate)this.prvKey=r,this.state="SIGN";else{if(!0!==r.isPublic)throw"init failed.:"+r;this.pubKey=r,this.state="VERIFY"}},this.updateString=function(e){this.md.updateString(e)},this.updateHex=function(e){this.md.updateHex(e)},this.sign=function(){if(this.sHashHex=this.md.digest(),void 0===this.prvKey&&void 0!==this.ecprvhex&&void 0!==this.eccurvename&&void 0!==ue.crypto.ECDSA&&(this.prvKey=new ue.crypto.ECDSA({curve:this.eccurvename,prv:this.ecprvhex})),this.prvKey instanceof ne&&"rsaandmgf1"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHashPSS(this.sHashHex,this.mdAlgName,this.pssSaltLen);else if(this.prvKey instanceof ne&&"rsa"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex,this.mdAlgName);else if(this.prvKey instanceof ue.crypto.ECDSA)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex);else{if(!(this.prvKey instanceof ue.crypto.DSA))throw"Signature: unsupported private key alg: "+this.pubkeyAlgName;this.hSign=this.prvKey.signWithMessageHash(this.sHashHex)}return this.hSign},this.signString=function(e){return this.updateString(e),this.sign()},this.signHex=function(e){return this.updateHex(e),this.sign()},this.verify=function(e){if(this.sHashHex=this.md.digest(),void 0===this.pubKey&&void 0!==this.ecpubhex&&void 0!==this.eccurvename&&void 0!==ue.crypto.ECDSA&&(this.pubKey=new ue.crypto.ECDSA({curve:this.eccurvename,pub:this.ecpubhex})),this.pubKey instanceof ne&&"rsaandmgf1"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHashPSS(this.sHashHex,e,this.mdAlgName,this.pssSaltLen);if(this.pubKey instanceof ne&&"rsa"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);if(void 0!==ue.crypto.ECDSA&&this.pubKey instanceof ue.crypto.ECDSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);if(void 0!==ue.crypto.DSA&&this.pubKey instanceof ue.crypto.DSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);throw"Signature: unsupported public key alg: "+this.pubkeyAlgName}}},this.init=function(e,t){throw"init(key, pass) not supported for this alg:prov="+this.algProvName},this.updateString=function(e){throw"updateString(str) not supported for this alg:prov="+this.algProvName},this.updateHex=function(e){throw"updateHex(hex) not supported for this alg:prov="+this.algProvName},this.sign=function(){throw"sign() not supported for this alg:prov="+this.algProvName},this.signString=function(e){throw"digestString(str) not supported for this alg:prov="+this.algProvName},this.signHex=function(e){throw"digestHex(hex) not supported for this alg:prov="+this.algProvName},this.verify=function(e){throw"verify(hSigVal) not supported for this alg:prov="+this.algProvName},this.initParams=e,void 0!==e&&(void 0!==e.alg&&(this.algName=e.alg,void 0===e.prov?this.provName=ue.crypto.Util.DEFAULTPROVIDER[this.algName]:this.provName=e.prov,this.algProvName=this.algName+":"+this.provName,this.setAlgAndProvider(this.algName,this.provName),this._setAlgNames()),void 0!==e.psssaltlen&&(this.pssSaltLen=e.psssaltlen),void 0!==e.prvkeypem)){if(void 0!==e.prvkeypas)throw"both prvkeypem and prvkeypas parameters not supported";try{t=Ke.getKey(e.prvkeypem),this.init(t)}catch(e){throw"fatal error to load pem private key: "+e}}},ue.crypto.Cipher=function(e){},ue.crypto.Cipher.encrypt=function(e,t,r){if(t instanceof ne&&t.isPublic){var n=ue.crypto.Cipher.getAlgByKeyAndName(t,r);if("RSA"===n)return t.encrypt(e);if("RSAOAEP"===n)return t.encryptOAEP(e,"sha1");var i=n.match(/^RSAOAEP(\d+)$/);if(null!==i)return t.encryptOAEP(e,"sha"+i[1]);throw"Cipher.encrypt: unsupported algorithm for RSAKey: "+r}throw"Cipher.encrypt: unsupported key or algorithm"},ue.crypto.Cipher.decrypt=function(e,t,r){if(t instanceof ne&&t.isPrivate){var n=ue.crypto.Cipher.getAlgByKeyAndName(t,r);if("RSA"===n)return t.decrypt(e);if("RSAOAEP"===n)return t.decryptOAEP(e,"sha1");var i=n.match(/^RSAOAEP(\d+)$/);if(null!==i)return t.decryptOAEP(e,"sha"+i[1]);throw"Cipher.decrypt: unsupported algorithm for RSAKey: "+r}throw"Cipher.decrypt: unsupported key or algorithm"},ue.crypto.Cipher.getAlgByKeyAndName=function(e,t){if(e instanceof ne){if(-1!=":RSA:RSAOAEP:RSAOAEP224:RSAOAEP256:RSAOAEP384:RSAOAEP512:".indexOf(t))return t;if(null==t)return"RSA";throw"getAlgByKeyAndName: not supported algorithm name for RSAKey: "+t}throw"getAlgByKeyAndName: not supported algorithm name: "+t},ue.crypto.OID=new function(){this.oidhex2name={"2a864886f70d010101":"rsaEncryption","2a8648ce3d0201":"ecPublicKey","2a8648ce380401":"dsa","2a8648ce3d030107":"secp256r1","2b8104001f":"secp192k1","2b81040021":"secp224r1","2b8104000a":"secp256k1","2b81040023":"secp521r1","2b81040022":"secp384r1","2a8648ce380403":"SHA1withDSA","608648016503040301":"SHA224withDSA","608648016503040302":"SHA256withDSA"}},void 0!==ue&&ue||(t.KJUR=ue={}),void 0!==ue.crypto&&ue.crypto||(ue.crypto={}),ue.crypto.ECDSA=function(e){var t=Error,r=b,n=oe,i=ue.crypto.ECDSA,o=ue.crypto.ECParameterDB,s=i.getName,a=le,u=a.getVbyListEx,c=a.isASN1HEX,h=new ee;this.type="EC",this.isPrivate=!1,this.isPublic=!1,this.getBigRandom=function(e){return new r(e.bitLength(),h).mod(e.subtract(r.ONE)).add(r.ONE)},this.setNamedCurve=function(e){this.ecparams=o.getByName(e),this.prvKeyHex=null,this.pubKeyHex=null,this.curveName=e},this.setPrivateKeyHex=function(e){this.isPrivate=!0,this.prvKeyHex=e},this.setPublicKeyHex=function(e){this.isPublic=!0,this.pubKeyHex=e},this.getPublicKeyXYHex=function(){var e=this.pubKeyHex;if("04"!==e.substr(0,2))throw"this method supports uncompressed format(04) only";var t=this.ecparams.keylen/4;if(e.length!==2+2*t)throw"malformed public key hex length";var r={};return r.x=e.substr(2,t),r.y=e.substr(2+t),r},this.getShortNISTPCurveName=function(){var e=this.curveName;return"secp256r1"===e||"NIST P-256"===e||"P-256"===e||"prime256v1"===e?"P-256":"secp384r1"===e||"NIST P-384"===e||"P-384"===e?"P-384":null},this.generateKeyPairHex=function(){var e=this.ecparams.n,t=this.getBigRandom(e),r=this.ecparams.G.multiply(t),n=r.getX().toBigInteger(),i=r.getY().toBigInteger(),o=this.ecparams.keylen/4,s=("0000000000"+t.toString(16)).slice(-o),a="04"+("0000000000"+n.toString(16)).slice(-o)+("0000000000"+i.toString(16)).slice(-o);return this.setPrivateKeyHex(s),this.setPublicKeyHex(a),{ecprvhex:s,ecpubhex:a}},this.signWithMessageHash=function(e){return this.signHex(e,this.prvKeyHex)},this.signHex=function(e,t){var n=new r(t,16),o=this.ecparams.n,s=new r(e.substring(0,this.ecparams.keylen/4),16);do{var a=this.getBigRandom(o),u=this.ecparams.G.multiply(a).getX().toBigInteger().mod(o)}while(u.compareTo(r.ZERO)<=0);var c=a.modInverse(o).multiply(s.add(n.multiply(u))).mod(o);return i.biRSSigToASN1Sig(u,c)},this.sign=function(e,t){var n=t,i=this.ecparams.n,o=r.fromByteArrayUnsigned(e);do{var s=this.getBigRandom(i),a=this.ecparams.G.multiply(s).getX().toBigInteger().mod(i)}while(a.compareTo(b.ZERO)<=0);var u=s.modInverse(i).multiply(o.add(n.multiply(a))).mod(i);return this.serializeSig(a,u)},this.verifyWithMessageHash=function(e,t){return this.verifyHex(e,t,this.pubKeyHex)},this.verifyHex=function(e,t,o){try{var s,a,u=i.parseSigHex(t);s=u.r,a=u.s;var c=n.decodeFromHex(this.ecparams.curve,o),h=new r(e.substring(0,this.ecparams.keylen/4),16);return this.verifyRaw(h,s,a,c)}catch(e){return!1}},this.verify=function(e,t,i){var o,s,a;if(Bitcoin.Util.isArray(t)){var u=this.parseSig(t);o=u.r,s=u.s}else{if("object"!==(void 0===t?"undefined":f(t))||!t.r||!t.s)throw"Invalid value for signature";o=t.r,s=t.s}if(i instanceof oe)a=i;else{if(!Bitcoin.Util.isArray(i))throw"Invalid format for pubkey value, must be byte array or ECPointFp";a=n.decodeFrom(this.ecparams.curve,i)}var c=r.fromByteArrayUnsigned(e);return this.verifyRaw(c,o,s,a)},this.verifyRaw=function(e,t,n,i){var o=this.ecparams.n,s=this.ecparams.G;if(t.compareTo(r.ONE)<0||t.compareTo(o)>=0)return!1;if(n.compareTo(r.ONE)<0||n.compareTo(o)>=0)return!1;var a=n.modInverse(o),u=e.multiply(a).mod(o),c=t.multiply(a).mod(o);return s.multiply(u).add(i.multiply(c)).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===c(e))throw new Error("not ASN.1 hex string");var t,r,n;try{t=u(e,0,["[0]",0],"06"),r=u(e,0,[1],"04");try{n=u(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===c(e))throw new t("not ASN.1 hex string");var r,n,i;try{u(e,0,[1,0],"06"),r=u(e,0,[1,1],"06"),n=u(e,0,[2,0,1],"04");try{i=u(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===c(e))throw new t("not ASN.1 hex string");var r,n;try{u(e,0,[0,0],"06"),r=u(e,0,[0,1],"06"),n=u(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===c(e))throw new t("not ASN.1 hex string");var n,i;try{n=u(e,0,[0,5,0,1],"06"),i=u(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))},ue.crypto.ECDSA.parseSigHex=function(e){var t=ue.crypto.ECDSA.parseSigHexInHexRS(e);return{r:new b(t.r,16),s:new b(t.s,16)}},ue.crypto.ECDSA.parseSigHexInHexRS=function(e){var t=le,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)}},ue.crypto.ECDSA.asn1SigToConcatSig=function(e){var t=ue.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},ue.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 ue.crypto.ECDSA.hexRSSigToASN1Sig(t,r)},ue.crypto.ECDSA.hexRSSigToASN1Sig=function(e,t){var r=new b(e,16),n=new b(t,16);return ue.crypto.ECDSA.biRSSigToASN1Sig(r,n)},ue.crypto.ECDSA.biRSSigToASN1Sig=function(e,t){var r=ue.asn1,n=new r.DERInteger({bigint:e}),i=new r.DERInteger({bigint:t});return new r.DERSequence({array:[n,i]}).getEncodedHex()},ue.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!==ue&&ue||(t.KJUR=ue={}),void 0!==ue.crypto&&ue.crypto||(ue.crypto={}),ue.crypto.ECParameterDB=new function(){var e={},t={};function r(e){return new b(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,u,c,h,l,d,f,p){e[n]={};var g=r(o),y=r(s),v=r(a),m=r(u),w=r(c),_=new se(g,y,v),S=_.decodePointHex("04"+h+l);e[n].name=n,e[n].keylen=i,e[n].curve=_,e[n].G=S,e[n].n=m,e[n].h=w,e[n].oid=f,e[n].info=p;for(var b=0;b<d.length;b++)t[d[b]]=n}},ue.crypto.ECParameterDB.regist("secp128r1",128,"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC","E87579C11079F43DD824993C2CEE5ED3","FFFFFFFE0000000075A30D1B9038A115","1","161FF7528B899B2D0C28607CA52C5B86","CF5AC8395BAFEB13C02DA292DDED7A83",[],"","secp128r1 : SECG curve over a 128 bit prime field"),ue.crypto.ECParameterDB.regist("secp160k1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73","0","7","0100000000000000000001B8FA16DFAB9ACA16B6B3","1","3B4C382CE37AA192A4019E763036F4F5DD4D7EBB","938CF935318FDCED6BC28286531733C3F03C4FEE",[],"","secp160k1 : SECG curve over a 160 bit prime field"),ue.crypto.ECParameterDB.regist("secp160r1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC","1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45","0100000000000000000001F4C8F927AED3CA752257","1","4A96B5688EF573284664698968C38BB913CBFC82","23A628553168947D59DCC912042351377AC5FB32",[],"","secp160r1 : SECG curve over a 160 bit prime field"),ue.crypto.ECParameterDB.regist("secp192k1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37","0","3","FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D","1","DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D","9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D",[]),ue.crypto.ECParameterDB.regist("secp192r1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC","64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1","FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831","1","188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012","07192B95FFC8DA78631011ED6B24CDD573F977A11E794811",[]),ue.crypto.ECParameterDB.regist("secp224r1",224,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE","B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4","FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D","1","B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21","BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34",[]),ue.crypto.ECParameterDB.regist("secp256k1",256,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F","0","7","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141","1","79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798","483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",[]),ue.crypto.ECParameterDB.regist("secp256r1",256,"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC","5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B","FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551","1","6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296","4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",["NIST P-256","P-256","prime256v1"]),ue.crypto.ECParameterDB.regist("secp384r1",384,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC","B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973","1","AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7","3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f",["NIST P-384","P-384"]),ue.crypto.ECParameterDB.regist("secp521r1",521,"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC","051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409","1","C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66","011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650",["NIST P-521","P-521"]);var Ke=function(){var e=function(e,r,n){return t(y.AES,e,r,n)},t=function(e,t,r,n){var i=y.enc.Hex.parse(t),o=y.enc.Hex.parse(r),s=y.enc.Hex.parse(n),a={};a.key=o,a.iv=s,a.ciphertext=i;var u=e.decrypt(a,o,{iv:s});return y.enc.Hex.stringify(u)},r=function(e,t,r){return n(y.AES,e,t,r)},n=function(e,t,r,n){var i=y.enc.Hex.parse(t),o=y.enc.Hex.parse(r),s=y.enc.Hex.parse(n),a=e.encrypt(i,o,{iv:s}),u=y.enc.Hex.parse(a.toString());return y.enc.Base64.stringify(u)},i={"AES-256-CBC":{proc:e,eproc:r,keylen:32,ivlen:16},"AES-192-CBC":{proc:e,eproc:r,keylen:24,ivlen:16},"AES-128-CBC":{proc:e,eproc:r,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:function(e,r,n){return t(y.TripleDES,e,r,n)},eproc:function(e,t,r){return n(y.TripleDES,e,t,r)},keylen:24,ivlen:8},"DES-CBC":{proc:function(e,r,n){return t(y.DES,e,r,n)},eproc:function(e,t,r){return n(y.DES,e,t,r)},keylen:8,ivlen:8}},o=function(e){var t={},r=e.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"));r&&(t.cipher=r[1],t.ivsalt=r[2]);var n=e.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));n&&(t.type=n[1]);var i=-1,o=0;-1!=e.indexOf("\r\n\r\n")&&(i=e.indexOf("\r\n\r\n"),o=2),-1!=e.indexOf("\n\n")&&(i=e.indexOf("\n\n"),o=1);var s=e.indexOf("-----END");if(-1!=i&&-1!=s){var a=e.substring(i+2*o,s-o);a=a.replace(/\s+/g,""),t.data=a}return t},s=function(e,t,r){for(var n=r.substring(0,16),o=y.enc.Hex.parse(n),s=y.enc.Utf8.parse(t),a=i[e].keylen+i[e].ivlen,u="",c=null;;){var h=y.algo.MD5.create();if(null!=c&&h.update(c),h.update(s),h.update(o),c=h.finalize(),(u+=y.enc.Hex.stringify(c)).length>=2*a)break}var l={};return l.keyhex=u.substr(0,2*i[e].keylen),l.ivhex=u.substr(2*i[e].keylen,2*i[e].ivlen),l},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,u=r.data,c=s(n,t,i).keyhex;return a(u,n,c,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 u=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+=u.replace(/(.{64})/g,"$1\r\n"))+"\r\n-----END "+e+" PRIVATE KEY-----\r\n"},parseHexOfEncryptedPKCS8:function(e){var t=le,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 u=r(e,a[1]);if(2!=u.length)throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: "+u.length);if("2a864886f70d0307"!=n(e,u[0]))throw"this only supports TripleDES";i.encryptionSchemeAlg="TripleDES",i.encryptionSchemeIV=n(e,u[1]);var c=r(e,a[0]);if(2!=c.length)throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: "+c.length);if("2a864886f70d01050c"!=n(e,c[0]))throw new Error("this only supports pkcs5PBKDF2");var h=r(e,c[1]);if(h.length<2)throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+h.length);i.pbkdf2Salt=n(e,h[0]);var l=n(e,h[1]);try{i.pbkdf2Iter=parseInt(l,16)}catch(e){throw new Error("malformed format pbkdf2Iter: "+l)}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=Pe(e,"ENCRYPTED PRIVATE KEY"),n=this.parseHexOfEncryptedPKCS8(r),i=Ke.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),u=y.TripleDES.decrypt(o,s,{iv:a});return y.enc.Hex.stringify(u)},getKeyFromEncryptedPKCS8PEM:function(e,t){var r=this._getPlainPKCS8HexFromEncryptedPKCS8PEM(e,t);return this.getKeyFromPlainPrivatePKCS8Hex(r)},parsePlainPrivatePKCS8Hex:function(e){var t=le,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=Pe(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 ue.crypto.DSA;else{if("2a8648ce3d0201"!=r.algoid)throw new Error("unsupported private key algorithm");t=new ue.crypto.ECDSA}return t.readPKCS8PrvKeyHex(e),t},_getKeyFromPublicPKCS8Hex:function(e){var t,r=le.getVbyList(e,0,[0,0],"06");if("2a864886f70d010101"===r)t=new ne;else if("2a8648ce380401"===r)t=new ue.crypto.DSA;else{if("2a8648ce3d0201"!==r)throw new Error("unsupported PKCS#8 public key hex");t=new ue.crypto.ECDSA}return t.readPKCS8PubKeyHex(e),t},parsePublicRawRSAKeyHex:function(e){var t=le,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=le,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 Ve(e,t){for(var r="",n=t/4-e.length,i=0;i<n;i++)r+="0";return r+e}function qe(e,t,r){for(var n="",i=0;n.length<t;)n+=be(r(Ee(e+String.fromCharCode.apply(String,[(4278190080&i)>>24,(16711680&i)>>16,(65280&i)>>8,255&i])))),i+=1;return n}function Je(e){for(var t in ue.crypto.Util.DIGESTINFOHEAD){var r=ue.crypto.Util.DIGESTINFOHEAD[t],n=r.length;if(e.substring(0,n)==r)return[t,e.substring(n)]}return[]}function We(e){var t,r=le,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,d=r.getVidx,f=r.getInt,p=r.oidname,g=r.hextooidstr,y=Pe;try{t=ue.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=u(this.hex,0,[0,0]);if("a0"==e.substr(0,2)){var t=u(e,0,[0]),r=f(t,0);if(r<0||2<r)throw new Error("malformed version field");return this.version=r+1,this.version}return this.version=1,this.foffset=-1,1},this.getSerialNumberHex=function(){return a(this.hex,0,[0,0],"02")},this.getSignatureAlgorithmField=function(){var e=c(this.hex,0,[0,1]);return this.getAlgorithmIdentifierName(e)},this.getAlgorithmIdentifierName=function(e){for(var r in t)if(e===t[r])return r;return p(a(e,0,[0],"06"))},this.getIssuer=function(){return this.getX500Name(this.getIssuerHex())},this.getIssuerHex=function(){return u(this.hex,0,[0,3+this.foffset],"30")},this.getIssuerString=function(){return this.getIssuer().str},this.getSubject=function(){return this.getX500Name(this.getSubjectHex())},this.getSubjectHex=function(){return u(this.hex,0,[0,5+this.foffset],"30")},this.getSubjectString=function(){return this.getSubject().str},this.getNotBefore=function(){var e=s(this.hex,0,[0,4+this.foffset,0]);return e=e.replace(/(..)/g,"%$1"),decodeURIComponent(e)},this.getNotAfter=function(){var e=s(this.hex,0,[0,4+this.foffset,1]);return e=e.replace(/(..)/g,"%$1"),decodeURIComponent(e)},this.getPublicKeyHex=function(){return r.getTLVbyList(this.hex,0,[0,6+this.foffset],"30")},this.getPublicKeyIdx=function(){return h(this.hex,0,[0,6+this.foffset],"30")},this.getPublicKeyContentIdx=function(){var e=this.getPublicKeyIdx();return h(this.hex,e,[1,0],"30")},this.getPublicKey=function(){return Ke.getKey(this.getPublicKeyHex(),null,"pkcs8pub")},this.getSignatureAlgorithmName=function(){var e=u(this.hex,0,[1],"30");return this.getAlgorithmIdentifierName(e)},this.getSignatureValueHex=function(){return s(this.hex,0,[2],"03",!0)},this.verifySignature=function(e){var t=this.getSignatureAlgorithmField(),r=this.getSignatureValueHex(),n=u(this.hex,0,[0],"30"),i=new ue.crypto.Signature({alg:t});return i.init(e),i.updateHex(n),i.verify(r)},this.parseExt=function(e){var t,o,a;if(void 0===e){if(a=this.hex,3!==this.version)return-1;t=h(a,0,[0,7,0],"30"),o=n(a,t)}else{a=Pe(e);var u=h(a,0,[0,3,0,0],"06");if("2a864886f70d01090e"!=i(a,u))return void(this.aExtInfo=new Array);t=h(a,0,[0,3,0,1,0],"30"),o=n(a,t),this.hex=a}this.aExtInfo=new Array;for(var c=0;c<o.length;c++){var l={critical:!1},f=0;3===n(a,o[c]).length&&(l.critical=!0,f=1),l.oid=r.hextooidstr(s(a,o[c],[0],"06"));var p=h(a,o[c],[1+f]);l.vidx=d(a,p),this.aExtInfo.push(l)}},this.getExtInfo=function(e){var t=this.aExtInfo,r=e;if(e.match(/^[0-9.]+$/)||(r=ue.asn1.x509.OID.name2oid(e)),""!==r)for(var n=0;n<t.length;n++)if(t[n].oid===r)return t[n]},this.getExtBasicConstraints=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("basicConstraints");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var n={extname:"basicConstraints"};if(t&&(n.critical=!0),"3000"===e)return n;if("30030101ff"===e)return n.cA=!0,n;if("30060101ff02"===e.substr(0,12)){var s=i(e,10),a=parseInt(s,16);return n.cA=!0,n.pathLen=a,n}throw new Error("hExtV parse error: "+e)},this.getExtKeyUsage=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("keyUsage");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var n={extname:"keyUsage"};return t&&(n.critical=!0),n.names=this.getExtKeyUsageString(e).split(","),n},this.getExtKeyUsageBin=function(e){if(void 0===e){var t=this.getExtInfo("keyUsage");if(void 0===t)return"";e=o(this.hex,t.vidx)}if(8!=e.length&&10!=e.length)throw new Error("malformed key usage value: "+e);var r="000000000000000"+parseInt(e.substr(6),16).toString(2);return 8==e.length&&(r=r.slice(-8)),10==e.length&&(r=r.slice(-16)),""==(r=r.replace(/0+$/,""))&&(r="0"),r},this.getExtKeyUsageString=function(e){for(var t=this.getExtKeyUsageBin(e),r=new Array,n=0;n<t.length;n++)"1"==t.substr(n,1)&&r.push(We.KEYUSAGE_NAME[n]);return r.join(",")},this.getExtSubjectKeyIdentifier=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("subjectKeyIdentifier");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var n={extname:"subjectKeyIdentifier"};t&&(n.critical=!0);var s=i(e,0);return n.kid={hex:s},n},this.getExtAuthorityKeyIdentifier=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("authorityKeyIdentifier");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var s={extname:"authorityKeyIdentifier"};t&&(s.critical=!0);for(var a=n(e,0),u=0;u<a.length;u++){var c=e.substr(a[u],2);if("80"===c&&(s.kid={hex:i(e,a[u])}),"a1"===c){var h=o(e,a[u]),l=this.getGeneralNames(h);s.issuer=l[0].dn}"82"===c&&(s.sn={hex:i(e,a[u])})}return s},this.getExtExtKeyUsage=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("extKeyUsage");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var s={extname:"extKeyUsage",array:[]};t&&(s.critical=!0);for(var a=n(e,0),u=0;u<a.length;u++)s.array.push(p(i(e,a[u])));return s},this.getExtExtKeyUsageName=function(){var e=this.getExtInfo("extKeyUsage");if(void 0===e)return e;var t=new Array,r=o(this.hex,e.vidx);if(""===r)return t;for(var s=n(r,0),a=0;a<s.length;a++)t.push(p(i(r,s[a])));return t},this.getExtSubjectAltName=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("subjectAltName");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var n={extname:"subjectAltName",array:[]};return t&&(n.critical=!0),n.array=this.getGeneralNames(e),n},this.getExtIssuerAltName=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("issuerAltName");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var n={extname:"issuerAltName",array:[]};return t&&(n.critical=!0),n.array=this.getGeneralNames(e),n},this.getGeneralNames=function(e){for(var t=n(e,0),r=[],i=0;i<t.length;i++){var s=this.getGeneralName(o(e,t[i]));void 0!==s&&r.push(s)}return r},this.getGeneralName=function(e){var t=e.substr(0,2),r=i(e,0),n=be(r);return"81"==t?{rfc822:n}:"82"==t?{dns:n}:"86"==t?{uri:n}:"87"==t?{ip:De(r)}:"a4"==t?{dn:this.getX500Name(r)}:void 0},this.getExtSubjectAltName2=function(){var e,t,r,s=this.getExtInfo("subjectAltName");if(void 0===s)return s;for(var a=new Array,u=o(this.hex,s.vidx),c=n(u,0),h=0;h<c.length;h++)r=u.substr(c[h],2),e=i(u,c[h]),"81"===r&&(t=Se(e),a.push(["MAIL",t])),"82"===r&&(t=Se(e),a.push(["DNS",t])),"84"===r&&(t=We.hex2dn(e,0),a.push(["DN",t])),"86"===r&&(t=Se(e),a.push(["URI",t])),"87"===r&&(t=De(e),a.push(["IP",t]));return a},this.getExtCRLDistributionPoints=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("cRLDistributionPoints");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var i={extname:"cRLDistributionPoints",array:[]};t&&(i.critical=!0);for(var s=n(e,0),a=0;a<s.length;a++){var u=o(e,s[a]);i.array.push(this.getDistributionPoint(u))}return i},this.getDistributionPoint=function(e){for(var t={},r=n(e,0),i=0;i<r.length;i++){var s=e.substr(r[i],2),a=o(e,r[i]);"a0"==s&&(t.dpname=this.getDistributionPointName(a))}return t},this.getDistributionPointName=function(e){for(var t={},r=n(e,0),i=0;i<r.length;i++){var s=e.substr(r[i],2),a=o(e,r[i]);"a0"==s&&(t.full=this.getGeneralNames(a))}return t},this.getExtCRLDistributionPointsURI=function(){var e=this.getExtInfo("cRLDistributionPoints");if(void 0===e)return e;for(var t=new Array,r=n(this.hex,e.vidx),i=0;i<r.length;i++)try{var o=Se(s(this.hex,r[i],[0,0,0],"86"));t.push(o)}catch(e){}return t},this.getExtAIAInfo=function(){var e=this.getExtInfo("authorityInfoAccess");if(void 0===e)return e;for(var t={ocsp:[],caissuer:[]},r=n(this.hex,e.vidx),i=0;i<r.length;i++){var o=s(this.hex,r[i],[0],"06"),a=s(this.hex,r[i],[1],"86");"2b06010505073001"===o&&t.ocsp.push(Se(a)),"2b06010505073002"===o&&t.caissuer.push(Se(a))}return t},this.getExtAuthorityInfoAccess=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("authorityInfoAccess");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var i={extname:"authorityInfoAccess",array:[]};t&&(i.critical=!0);for(var u=n(e,0),c=0;c<u.length;c++){var h=a(e,u[c],[0],"06"),l=Se(s(e,u[c],[1],"86"));if("2b06010505073001"==h)i.array.push({ocsp:l});else{if("2b06010505073002"!=h)throw new Error("unknown method: "+h);i.array.push({caissuer:l})}}return i},this.getExtCertificatePolicies=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("certificatePolicies");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var i={extname:"certificatePolicies",array:[]};t&&(i.critical=!0);for(var s=n(e,0),a=0;a<s.length;a++){var u=o(e,s[a]),c=this.getPolicyInformation(u);i.array.push(c)}return i},this.getPolicyInformation=function(e){var t={},r=s(e,0,[0],"06");t.policyoid=p(r);var i=l(e,0,[1],"30");if(-1!=i){t.array=[];for(var a=n(e,i),u=0;u<a.length;u++){var c=o(e,a[u]),h=this.getPolicyQualifierInfo(c);t.array.push(h)}}return t},this.getPolicyQualifierInfo=function(e){var t={},r=s(e,0,[0],"06");if("2b06010505070201"===r){var n=a(e,0,[1],"16");t.cps=be(n)}else if("2b06010505070202"===r){var i=u(e,0,[1],"30");t.unotice=this.getUserNotice(i)}return t},this.getUserNotice=function(e){for(var t={},r=n(e,0),i=0;i<r.length;i++){var s=o(e,r[i]);"30"!=s.substr(0,2)&&(t.exptext=this.getDisplayText(s))}return t},this.getDisplayText=function(e){var t={};return t.type={"0c":"utf8",16:"ia5","1a":"vis","1e":"bmp"}[e.substr(0,2)],t.str=be(i(e,0)),t},this.getExtCRLNumber=function(e,t){var r={extname:"cRLNumber"};if(t&&(r.critical=!0),"02"==e.substr(0,2))return r.num={hex:i(e,0)},r;throw new Error("hExtV parse error: "+e)},this.getExtCRLReason=function(e,t){var r={extname:"cRLReason"};if(t&&(r.critical=!0),"0a"==e.substr(0,2))return r.code=parseInt(i(e,0),16),r;throw new Error("hExtV parse error: "+e)},this.getExtOcspNonce=function(e,t){var r={extname:"ocspNonce"};t&&(r.critical=!0);var n=i(e,0);return r.hex=n,r},this.getExtOcspNoCheck=function(e,t){var r={extname:"ocspNoCheck"};return t&&(r.critical=!0),r},this.getExtAdobeTimeStamp=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("adobeTimeStamp");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var i={extname:"adobeTimeStamp"};t&&(i.critical=!0);var s=n(e,0);if(s.length>1){var a=o(e,s[1]),u=this.getGeneralName(a);null!=u.uri&&(i.uri=u.uri)}if(s.length>2){var c=o(e,s[2]);"0101ff"==c&&(i.reqauth=!0),"010100"==c&&(i.reqauth=!1)}return i},this.getX500NameRule=function(e){for(var t=null,r=[],n=0;n<e.length;n++)for(var i=e[n],o=0;o<i.length;o++)r.push(i[o]);for(n=0;n<r.length;n++){var s=r[n],a=s.ds,u=s.value,c=s.type;if("prn"!=a&&"utf8"!=a&&"ia5"!=a)return"mixed";if("ia5"==a){if("CN"!=c)return"mixed";if(ue.lang.String.isMail(u))continue;return"mixed"}if("C"==c){if("prn"==a)continue;return"mixed"}if(null==t)t=a;else if(t!==a)return"mixed"}return null==t?"prn":t},this.getX500Name=function(e){var t=this.getX500NameArray(e);return{array:t,str:this.dnarraytostr(t)}},this.getX500NameArray=function(e){for(var t=[],r=n(e,0),i=0;i<r.length;i++)t.push(this.getRDN(o(e,r[i])));return t},this.getRDN=function(e){for(var t=[],r=n(e,0),i=0;i<r.length;i++)t.push(this.getAttrTypeAndValue(o(e,r[i])));return t},this.getAttrTypeAndValue=function(e){var t={type:null,value:null,ds:null},r=n(e,0),i=s(e,r[0],[],"06"),o=s(e,r[1],[]),a=ue.asn1.ASN1Util.oidHexToInt(i);return t.type=ue.asn1.x509.OID.oid2atype(a),t.ds=this.HEX2STAG[e.substr(r[1],2)],"bmp"!=t.ds?t.value=Se(o):t.value=Ne(o),t},this.readCertPEM=function(e){this.readCertHex(y(e))},this.readCertHex=function(e){this.hex=e,this.getVersion();try{h(this.hex,0,[0,7],"a3"),this.parseExt()}catch(e){}},this.getParam=function(){var e={};return e.version=this.getVersion(),e.serial={hex:this.getSerialNumberHex()},e.sigalg=this.getSignatureAlgorithmField(),e.issuer=this.getIssuer(),e.notbefore=this.getNotBefore(),e.notafter=this.getNotAfter(),e.subject=this.getSubject(),e.sbjpubkey=ke(this.getPublicKeyHex(),"PUBLIC KEY"),this.aExtInfo.length>0&&(e.ext=this.getExtParamArray()),e.sighex=this.getSignatureValueHex(),e},this.getExtParamArray=function(e){null==e&&-1!=l(this.hex,0,[0,"[3]"])&&(e=c(this.hex,0,[0,"[3]",0],"30"));for(var t=[],r=n(e,0),i=0;i<r.length;i++){var s=o(e,r[i]),a=this.getExtParam(s);null!=a&&t.push(a)}return t},this.getExtParam=function(e){var t=n(e,0).length;if(2!=t&&3!=t)throw new Error("wrong number elements in Extension: "+t+" "+e);var r=g(s(e,0,[0],"06")),i=!1;3==t&&"0101ff"==u(e,0,[1])&&(i=!0);var o=u(e,0,[t-1,0]),a=void 0;if("2.5.29.14"==r?a=this.getExtSubjectKeyIdentifier(o,i):"2.5.29.15"==r?a=this.getExtKeyUsage(o,i):"2.5.29.17"==r?a=this.getExtSubjectAltName(o,i):"2.5.29.18"==r?a=this.getExtIssuerAltName(o,i):"2.5.29.19"==r?a=this.getExtBasicConstraints(o,i):"2.5.29.31"==r?a=this.getExtCRLDistributionPoints(o,i):"2.5.29.32"==r?a=this.getExtCertificatePolicies(o,i):"2.5.29.35"==r?a=this.getExtAuthorityKeyIdentifier(o,i):"2.5.29.37"==r?a=this.getExtExtKeyUsage(o,i):"1.3.6.1.5.5.7.1.1"==r?a=this.getExtAuthorityInfoAccess(o,i):"2.5.29.20"==r?a=this.getExtCRLNumber(o,i):"2.5.29.21"==r?a=this.getExtCRLReason(o,i):"1.3.6.1.5.5.7.48.1.2"==r?a=this.getExtOcspNonce(o,i):"1.3.6.1.5.5.7.48.1.5"==r?a=this.getExtOcspNoCheck(o,i):"1.2.840.113583.1.1.9.1"==r&&(a=this.getExtAdobeTimeStamp(o,i)),null!=a)return a;var c={extname:r,extn:o};return i&&(c.critical=!0),c},this.findExt=function(e,t){for(var r=0;r<e.length;r++)if(e[r].extname==t)return e[r];return null},this.updateExtCDPFullURI=function(e,t){var r=this.findExt(e,"cRLDistributionPoints");if(null!=r&&null!=r.array)for(var n=r.array,i=0;i<n.length;i++)if(null!=n[i].dpname&&null!=n[i].dpname.full)for(var o=n[i].dpname.full,s=0;s<o.length;s++){var a=o[i];null!=a.uri&&(a.uri=t)}},this.updateExtAIAOCSP=function(e,t){var r=this.findExt(e,"authorityInfoAccess");if(null!=r&&null!=r.array)for(var n=r.array,i=0;i<n.length;i++)null!=n[i].ocsp&&(n[i].ocsp=t)},this.updateExtAIACAIssuer=function(e,t){var r=this.findExt(e,"authorityInfoAccess");if(null!=r&&null!=r.array)for(var n=r.array,i=0;i<n.length;i++)null!=n[i].caissuer&&(n[i].caissuer=t)},this.dnarraytostr=function(e){return"/"+e.map(function(e){return function(e){return e.map(function(e){return function(e){return e.type+"="+e.value}(e).replace(/\+/,"\\+")}).join("+")}(e).replace(/\//,"\\/")}).join("/")},this.getInfo=function(){var e,t,r,n=function(e){return JSON.stringify(e.array).replace(/[\[\]\{\}\"]/g,"")},i=function(e){for(var t="",r=e.array,n=0;n<r.length;n++){var i=r[n];if(t+=" policy oid: "+i.policyoid+"\n",void 0!==i.array)for(var o=0;o<i.array.length;o++){var s=i.array[o];void 0!==s.cps&&(t+=" cps: "+s.cps+"\n")}}return t},o=function(e){for(var t="",r=e.array,n=0;n<r.length;n++){var i=r[n];try{void 0!==i.dpname.full[0].uri&&(t+=" "+i.dpname.full[0].uri+"\n")}catch(e){}try{void 0!==i.dname.full[0].dn.hex&&(t+=" "+We.hex2dn(i.dpname.full[0].dn.hex)+"\n")}catch(e){}}return t},s=function(e){for(var t="",r=e.array,n=0;n<r.length;n++){var i=r[n];void 0!==i.caissuer&&(t+=" caissuer: "+i.caissuer+"\n"),void 0!==i.ocsp&&(t+=" ocsp: "+i.ocsp+"\n")}return t};if(e="Basic Fields\n",e+=" serial number: "+this.getSerialNumberHex()+"\n",e+=" signature algorithm: "+this.getSignatureAlgorithmField()+"\n",e+=" issuer: "+this.getIssuerString()+"\n",e+=" notBefore: "+this.getNotBefore()+"\n",e+=" notAfter: "+this.getNotAfter()+"\n",e+=" subject: "+this.getSubjectString()+"\n",e+=" subject public key info: \n",e+=" key algorithm: "+(t=this.getPublicKey()).type+"\n","RSA"===t.type&&(e+=" n="+je(t.n.toString(16)).substr(0,16)+"...\n",e+=" e="+je(t.e.toString(16))+"\n"),null!=(r=this.aExtInfo)){e+="X509v3 Extensions:\n";for(var a=0;a<r.length;a++){var u=r[a],c=ue.asn1.x509.OID.oid2name(u.oid);""===c&&(c=u.oid);var h="";if(!0===u.critical&&(h="CRITICAL"),e+=" "+c+" "+h+":\n","basicConstraints"===c){var l=this.getExtBasicConstraints();void 0===l.cA?e+=" {}\n":(e+=" cA=true",void 0!==l.pathLen&&(e+=", pathLen="+l.pathLen),e+="\n")}else if("keyUsage"===c)e+=" "+this.getExtKeyUsageString()+"\n";else if("subjectKeyIdentifier"===c)e+=" "+this.getExtSubjectKeyIdentifier().kid.hex+"\n";else if("authorityKeyIdentifier"===c){var d=this.getExtAuthorityKeyIdentifier();void 0!==d.kid&&(e+=" kid="+d.kid.hex+"\n")}else"extKeyUsage"===c?e+=" "+this.getExtExtKeyUsage().array.join(", ")+"\n":"subjectAltName"===c?e+=" "+n(this.getExtSubjectAltName())+"\n":"cRLDistributionPoints"===c?e+=o(this.getExtCRLDistributionPoints()):"authorityInfoAccess"===c?e+=s(this.getExtAuthorityInfoAccess()):"certificatePolicies"===c&&(e+=i(this.getExtCertificatePolicies()))}}return(e+="signature algorithm: "+this.getSignatureAlgorithmName()+"\n")+"signature: "+this.getSignatureValueHex().substr(0,16)+"...\n"},"string"==typeof e&&(-1!=e.indexOf("-----BEGIN")?this.readCertPEM(e):ue.lang.String.isHex(e)&&this.readCertHex(e))}Ke.getKey=function(e,t,r){var n,i=(v=le).getChildIdx,o=(v.getV,v.getVbyList),s=ue.crypto,a=s.ECDSA,u=s.DSA,c=ne,h=Pe,l=Ke;if(void 0!==c&&e instanceof c)return e;if(void 0!==a&&e instanceof a)return e;if(void 0!==u&&e instanceof u)return e;if(void 0!==e.curve&&void 0!==e.xy&&void 0===e.d)return new a({pub:e.xy,curve:e.curve});if(void 0!==e.curve&&void 0!==e.d)return new a({prv:e.d,curve:e.curve});if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0===e.d)return(T=new c).setPublic(e.n,e.e),T;if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0!==e.p&&void 0!==e.q&&void 0!==e.dp&&void 0!==e.dq&&void 0!==e.co&&void 0===e.qi)return(T=new c).setPrivateEx(e.n,e.e,e.d,e.p,e.q,e.dp,e.dq,e.co),T;if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0===e.p)return(T=new c).setPrivate(e.n,e.e,e.d),T;if(void 0!==e.p&&void 0!==e.q&&void 0!==e.g&&void 0!==e.y&&void 0===e.x)return(T=new u).setPublic(e.p,e.q,e.g,e.y),T;if(void 0!==e.p&&void 0!==e.q&&void 0!==e.g&&void 0!==e.y&&void 0!==e.x)return(T=new u).setPrivate(e.p,e.q,e.g,e.y,e.x),T;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0===e.d)return(T=new c).setPublic(we(e.n),we(e.e)),T;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0!==e.p&&void 0!==e.q&&void 0!==e.dp&&void 0!==e.dq&&void 0!==e.qi)return(T=new c).setPrivateEx(we(e.n),we(e.e),we(e.d),we(e.p),we(e.q),we(e.dp),we(e.dq),we(e.qi)),T;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d)return(T=new c).setPrivate(we(e.n),we(e.e),we(e.d)),T;if("EC"===e.kty&&void 0!==e.crv&&void 0!==e.x&&void 0!==e.y&&void 0===e.d){var d=(P=new a({curve:e.crv})).ecparams.keylen/4,f="04"+("0000000000"+we(e.x)).slice(-d)+("0000000000"+we(e.y)).slice(-d);return P.setPublicKeyHex(f),P}if("EC"===e.kty&&void 0!==e.crv&&void 0!==e.x&&void 0!==e.y&&void 0!==e.d){d=(P=new a({curve:e.crv})).ecparams.keylen/4,f="04"+("0000000000"+we(e.x)).slice(-d)+("0000000000"+we(e.y)).slice(-d);var p=("0000000000"+we(e.d)).slice(-d);return P.setPublicKeyHex(f),P.setPrivateKeyHex(p),P}if("pkcs5prv"===r){var g,y=e,v=le;if(9===(g=i(y,0)).length)(T=new c).readPKCS5PrvKeyHex(y);else if(6===g.length)(T=new u).readPKCS5PrvKeyHex(y);else{if(!(g.length>2&&"04"===y.substr(g[1],2)))throw new Error("unsupported PKCS#1/5 hexadecimal key");(T=new a).readPKCS5PrvKeyHex(y)}return T}if("pkcs8prv"===r)return l.getKeyFromPlainPrivatePKCS8Hex(e);if("pkcs8pub"===r)return l._getKeyFromPublicPKCS8Hex(e);if("x509pub"===r)return We.getPublicKeyFromCertHex(e);if(-1!=e.indexOf("-END CERTIFICATE-",0)||-1!=e.indexOf("-END X509 CERTIFICATE-",0)||-1!=e.indexOf("-END TRUSTED CERTIFICATE-",0))return We.getPublicKeyFromCertPEM(e);if(-1!=e.indexOf("-END PUBLIC KEY-")){var m=Pe(e,"PUBLIC KEY");return l._getKeyFromPublicPKCS8Hex(m)}if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var w=h(e,"RSA PRIVATE KEY");return l.getKey(w,null,"pkcs5prv")}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var _=o(n=h(e,"DSA PRIVATE KEY"),0,[1],"02"),S=o(n,0,[2],"02"),E=o(n,0,[3],"02"),F=o(n,0,[4],"02"),x=o(n,0,[5],"02");return(T=new u).setPrivate(new b(_,16),new b(S,16),new b(E,16),new b(F,16),new b(x,16)),T}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED"))return w=h(e,"EC PRIVATE KEY"),l.getKey(w,null,"pkcs5prv");if(-1!=e.indexOf("-END PRIVATE KEY-"))return l.getKeyFromPlainPrivatePKCS8PEM(e);if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var A=l.getDecryptedKeyHex(e,t),k=new ne;return k.readPKCS5PrvKeyHex(A),k}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var P,T=o(n=l.getDecryptedKeyHex(e,t),0,[1],"04"),I=o(n,0,[2,0],"06"),C=o(n,0,[3,0],"03").substr(2);if(void 0===ue.crypto.OID.oidhex2name[I])throw new Error("undefined OID(hex) in KJUR.crypto.OID: "+I);return(P=new a({curve:ue.crypto.OID.oidhex2name[I]})).setPublicKeyHex(C),P.setPrivateKeyHex(T),P.isPublic=!1,P}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED"))return _=o(n=l.getDecryptedKeyHex(e,t),0,[1],"02"),S=o(n,0,[2],"02"),E=o(n,0,[3],"02"),F=o(n,0,[4],"02"),x=o(n,0,[5],"02"),(T=new u).setPrivate(new b(_,16),new b(S,16),new b(E,16),new b(F,16),new b(x,16)),T;if(-1!=e.indexOf("-END ENCRYPTED PRIVATE KEY-"))return l.getKeyFromEncryptedPKCS8PEM(e,t);throw new Error("not supported argument")},Ke.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,u=t,c=new ue.crypto.ECDSA({curve:u}).generateKeyPairHex();return(s=new ue.crypto.ECDSA({curve:u})).setPublicKeyHex(c.ecpubhex),s.setPrivateKeyHex(c.ecprvhex),s.isPrivate=!0,s.isPublic=!1,(n=new ue.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: "+e)},Ke.getPEM=function(e,t,r,n,i,o){var s=ue,a=s.asn1,u=a.DERObjectIdentifier,c=a.DERInteger,h=a.ASN1Util.newObject,l=a.x509.SubjectPublicKeyInfo,d=s.crypto,f=d.DSA,p=d.ECDSA,g=ne;function v(e){return h({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 m(e){return h({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a0",!0,{oid:{name:e.curveName}}]},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]})}function w(e){return h({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 ke(E=new l(e).getEncodedHex(),"PUBLIC KEY");if("PKCS1PRV"==t&&void 0!==g&&e instanceof g&&(void 0===r||null==r)&&1==e.isPrivate)return ke(E=v(e).getEncodedHex(),"RSA PRIVATE KEY");if("PKCS1PRV"==t&&void 0!==p&&e instanceof p&&(void 0===r||null==r)&&1==e.isPrivate){var _=new u({name:e.curveName}).getEncodedHex(),S=m(e).getEncodedHex(),b="";return(b+=ke(_,"EC PARAMETERS"))+ke(S,"EC PRIVATE KEY")}if("PKCS1PRV"==t&&void 0!==f&&e instanceof f&&(void 0===r||null==r)&&1==e.isPrivate)return ke(E=w(e).getEncodedHex(),"DSA PRIVATE KEY");if("PKCS5PRV"==t&&void 0!==g&&e instanceof g&&void 0!==r&&null!=r&&1==e.isPrivate){var E=v(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=m(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=w(e).getEncodedHex(),void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",E,r,n,o);var F=function(e,t){var r=x(e,t);return new h({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()},x=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 A=v(e).getEncodedHex();return E=h({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:A}}]}).getEncodedHex(),void 0===r||null==r?ke(E,"PRIVATE KEY"):ke(S=F(E,r),"ENCRYPTED PRIVATE KEY")}if("PKCS8PRV"==t&&void 0!==p&&e instanceof p&&1==e.isPrivate)return A=new h({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]}).getEncodedHex(),E=h({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:e.curveName}}]},{octstr:{hex:A}}]}).getEncodedHex(),void 0===r||null==r?ke(E,"PRIVATE KEY"):ke(S=F(E,r),"ENCRYPTED PRIVATE KEY");if("PKCS8PRV"==t&&void 0!==f&&e instanceof f&&1==e.isPrivate)return A=new c({bigint:e.x}).getEncodedHex(),E=h({seq:[{int:0},{seq:[{oid:{name:"dsa"}},{seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]}]},{octstr:{hex:A}}]}).getEncodedHex(),void 0===r||null==r?ke(E,"PRIVATE KEY"):ke(S=F(E,r),"ENCRYPTED PRIVATE KEY");throw new Error("unsupported object nor format")},Ke.getKeyFromCSRPEM=function(e){var t=Pe(e,"CERTIFICATE REQUEST");return Ke.getKeyFromCSRHex(t)},Ke.getKeyFromCSRHex=function(e){var t=Ke.parseCSRHex(e);return Ke.getKey(t.p8pubkeyhex,null,"pkcs8pub")},Ke.parseCSRHex=function(e){var t=le,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},Ke.getKeyID=function(e){var t=Ke,r=le;"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&(e=t.getKey(e));var n=Pe(t.getPEM(e)),i=r.getIdxbyList(n,0,[1]),o=r.getV(n,i).substring(2);return ue.crypto.Util.hashHex(o,"sha1")},Ke.getJWKFromKey=function(e){var t={};if(e instanceof ne&&e.isPrivate)return t.kty="RSA",t.n=me(e.n.toString(16)),t.e=me(e.e.toString(16)),t.d=me(e.d.toString(16)),t.p=me(e.p.toString(16)),t.q=me(e.q.toString(16)),t.dp=me(e.dmp1.toString(16)),t.dq=me(e.dmq1.toString(16)),t.qi=me(e.coeff.toString(16)),t;if(e instanceof ne&&e.isPublic)return t.kty="RSA",t.n=me(e.n.toString(16)),t.e=me(e.e.toString(16)),t;if(e instanceof ue.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=me(r.x),t.y=me(r.y),t.d=me(e.prvKeyHex),t}if(e instanceof ue.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=me(r.x),t.y=me(r.y),t}throw new Error("not supported key object")},ne.getPosArrayOfChildrenFromHex=function(e){return le.getChildIdx(e,0)},ne.getHexValueArrayOfChildrenFromHex=function(e){var t,r=le.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]),u=r(e,t[5]),c=r(e,t[6]),h=r(e,t[7]),l=r(e,t[8]);return(t=new Array).push(n,i,o,s,a,u,c,h,l),t},ne.prototype.readPrivateKeyFromPEMString=function(e){var t=Pe(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,u,c=le,h=c.getVbyListEx;if(!1===c.isASN1HEX(e))throw new Error("not ASN.1 hex string");try{t=h(e,0,[2,0,1],"02"),r=h(e,0,[2,0,2],"02"),n=h(e,0,[2,0,3],"02"),i=h(e,0,[2,0,4],"02"),o=h(e,0,[2,0,5],"02"),s=h(e,0,[2,0,6],"02"),a=h(e,0,[2,0,7],"02"),u=h(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,u)},ne.prototype.readPKCS5PubKeyHex=function(e){var t=le,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=le;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 We).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 ue.crypto.Util.hashString(e,t)}(e);return this.signWithMessageHash(r,t)},ne.prototype.signWithMessageHash=function(e,t){var r=te(ue.crypto.Util.getPaddedDigestInfoHex(e,t,this.n.bitLength()),16);return Ve(this.doPrivate(r).toString(16),this.n.bitLength())},ne.prototype.signPSS=function(e,t,r){var n=function(e){return ue.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=be(e),o=i.length,s=this.n.bitLength()-1,a=Math.ceil(s/8),u=function(e){return ue.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(a<o+r+2)throw new Error("data too long");var c="";r>0&&(c=new Array(r),(new ee).nextBytes(c),c=String.fromCharCode.apply(String,c));var h=be(u(Ee("\0\0\0\0\0\0\0\0"+i+c))),l=[];for(n=0;n<a-r-o-2;n+=1)l[n]=0;var d=String.fromCharCode.apply(String,l)+""+c,f=qe(h,d.length,u),p=[];for(n=0;n<d.length;n+=1)p[n]=d.charCodeAt(n)^f.charCodeAt(n);var g=65280>>8*a-s&255;for(p[0]&=~g,n=0;n<o;n++)p.push(h.charCodeAt(n));return p.push(188),Ve(this.doPrivate(new b(p)).toString(16),this.n.bitLength())},ne.prototype.verify=function(e,t){if(null==(t=t.toLowerCase()).match(/^[0-9a-f]+$/))return!1;var r=te(t,16),n=this.n.bitLength();if(r.bitLength()>n)return!1;var i=this.doPublic(r).toString(16);if(i.length+3!=n/4)return!1;var o=Je(i.replace(/^1f+00/,""));if(0==o.length)return!1;var s=o[0];return o[1]==function(e){return ue.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=Je(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 ue.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 b(t,16),s=function(e){return ue.crypto.Util.hashHex(e,r)},a=be(e),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<u+n+2)throw new Error("data too long");var l=this.doPublic(o).toByteArray();for(i=0;i<l.length;i+=1)l[i]&=255;for(;l.length<h;)l.unshift(0);if(188!==l[h-1])throw new Error("encoded message does not end in 0xbc");var d=(l=String.fromCharCode.apply(String,l)).substr(0,h-u-1),f=l.substr(d.length,u),p=65280>>8*h-c&255;if(0!=(d.charCodeAt(0)&p))throw new Error("bits beyond keysize not zero");var g=qe(f,d.length,s),y=[];for(i=0;i<d.length;i+=1)y[i]=d.charCodeAt(i)^g.charCodeAt(i);y[0]&=~p;var v=h-u-n-2;for(i=0;i<v;i+=1)if(0!==y[i])throw new Error("leftmost octets not zero");if(1!==y[v])throw new Error("0x01 marker not found");return f===be(s(Ee("\0\0\0\0\0\0\0\0"+a+String.fromCharCode.apply(String,y.slice(-n)))))},ne.SALT_LEN_HLEN=-1,ne.SALT_LEN_MAX=-2,ne.SALT_LEN_RECOVER=-2,We.hex2dn=function(e,t){void 0===t&&(t=0);var r=new We;return le.getTLV(e,t),r.getX500Name(e).str},We.hex2rdn=function(e,t){if(void 0===t&&(t=0),"31"!==e.substr(t,2))throw new Error("malformed RDN");for(var r=new Array,n=le.getChildIdx(e,t),i=0;i<n.length;i++)r.push(We.hex2attrTypeValue(e,n[i]));return(r=r.map(function(e){return e.replace("+","\\+")})).join("+")},We.hex2attrTypeValue=function(e,t){var r=le,n=r.getV;if(void 0===t&&(t=0),"30"!==e.substr(t,2))throw new Error("malformed attribute type and value");var i=r.getChildIdx(e,t);2!==i.length||e.substr(i[0],2);var o=n(e,i[0]),s=ue.asn1.ASN1Util.oidHexToInt(o);return ue.asn1.x509.OID.oid2atype(s)+"="+be(n(e,i[1]))},We.getPublicKeyFromCertHex=function(e){var t=new We;return t.readCertHex(e),t.getPublicKey()},We.getPublicKeyFromCertPEM=function(e){var t=new We;return t.readCertPEM(e),t.getPublicKey()},We.getPublicKeyInfoPropOfCertPEM=function(e){var t,r,n=le.getVbyList,i={algparam:null};return(t=new We).readCertPEM(e),r=t.getPublicKeyHex(),i.keyhex=n(r,0,[1],"03").substr(2),i.algoid=n(r,0,[0,0],"06"),"2a8648ce3d0201"===i.algoid&&(i.algparam=n(r,0,[0,1],"06")),i},We.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],void 0!==ue&&ue||(t.KJUR=ue={}),void 0!==ue.jws&&ue.jws||(ue.jws={}),ue.jws.JWS=function(){var e=ue.jws.JWS.isSafeJSONString;this.parseJWS=function(t,r){if(void 0===this.parsedJWS||!r&&void 0===this.parsedJWS.sigvalH){var n=t.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(null==n)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var i=n[1],o=n[2],s=n[3],a=i+"."+o;if(this.parsedJWS={},this.parsedJWS.headB64U=i,this.parsedJWS.payloadB64U=o,this.parsedJWS.sigvalB64U=s,this.parsedJWS.si=a,!r){var u=we(s),c=te(u,16);this.parsedJWS.sigvalH=u,this.parsedJWS.sigvalBI=c}var h=he(i),l=he(o);if(this.parsedJWS.headS=h,this.parsedJWS.payloadS=l,!e(h,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+h}}},ue.jws.JWS.sign=function(e,t,r,n,i){var o,s,a,u=ue,c=u.jws.JWS,h=c.readSafeJSONString,l=c.isSafeJSONString,d=u.crypto,p=(d.ECDSA,d.Mac),g=d.Signature,y=JSON;if("string"!=typeof t&&"object"!=(void 0===t?"undefined":f(t)))throw"spHeader must be JSON string or object: "+t;if("object"==(void 0===t?"undefined":f(t))&&(s=t,o=y.stringify(s)),"string"==typeof t){if(!l(o=t))throw"JWS Head is not safe JSON string: "+o;s=h(o)}if(a=r,"object"==(void 0===r?"undefined":f(r))&&(a=y.stringify(r)),""!=e&&null!=e||void 0===s.alg||(e=s.alg),""!=e&&null!=e&&void 0===s.alg&&(s.alg=e,o=y.stringify(s)),e!==s.alg)throw"alg and sHeader.alg doesn't match: "+e+"!="+s.alg;var v=null;if(void 0===c.jwsalg2sigalg[e])throw"unsupported alg name: "+e;v=c.jwsalg2sigalg[e];var m=ce(o)+"."+ce(a),w="";if("Hmac"==v.substr(0,4)){if(void 0===n)throw"mac key shall be specified for HS* alg";var _=new p({alg:v,prov:"cryptojs",pass:n});_.updateString(m),w=_.doFinal()}else if(-1!=v.indexOf("withECDSA")){(b=new g({alg:v})).init(n,i),b.updateString(m);var S=b.sign();w=ue.crypto.ECDSA.asn1SigToConcatSig(S)}else{var b;"none"!=v&&((b=new g({alg:v})).init(n,i),b.updateString(m),w=b.sign())}return m+"."+me(w)},ue.jws.JWS.verify=function(e,t,r){var n,i=ue,o=i.jws.JWS,s=o.readSafeJSONString,a=i.crypto,u=a.ECDSA,c=a.Mac,h=a.Signature;void 0!==f(ne)&&(n=ne);var l=e.split(".");if(3!==l.length)return!1;var d,p=l[0]+"."+l[1],g=we(l[2]),y=s(he(l[0])),v=null;if(void 0===y.alg)throw"algorithm not specified in header";if(d=(v=y.alg).substr(0,2),null!=r&&"[object Array]"===Object.prototype.toString.call(r)&&r.length>0&&-1==(":"+r.join(":")+":").indexOf(":"+v+":"))throw"algorithm '"+v+"' not accepted in the list";if("none"!=v&&null===t)throw"key shall be specified to verify.";if("string"==typeof t&&-1!=t.indexOf("-----BEGIN ")&&(t=Ke.getKey(t)),!("RS"!=d&&"PS"!=d||t instanceof n))throw"key shall be a RSAKey obj for RS* and PS* algs";if("ES"==d&&!(t instanceof u))throw"key shall be a ECDSA obj for ES* algs";var m=null;if(void 0===o.jwsalg2sigalg[y.alg])throw"unsupported alg name: "+v;if("none"==(m=o.jwsalg2sigalg[v]))throw"not supported";if("Hmac"==m.substr(0,4)){if(void 0===t)throw"hexadecimal key shall be specified for HMAC";var w=new c({alg:m,pass:t});return w.updateString(p),g==w.doFinal()}if(-1!=m.indexOf("withECDSA")){var _,S=null;try{S=u.concatSigToASN1Sig(g)}catch(e){return!1}return(_=new h({alg:m})).init(t),_.updateString(p),_.verify(S)}return(_=new h({alg:m})).init(t),_.updateString(p),_.verify(g)},ue.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=ue.jws.JWS.readSafeJSONString(he(t)),o.payloadObj=ue.jws.JWS.readSafeJSONString(he(r)),o.headerPP=JSON.stringify(o.headerObj,null," "),null==o.payloadObj?o.payloadPP=he(r):o.payloadPP=JSON.stringify(o.payloadObj,null," "),void 0!==n&&(o.sigHex=we(n)),o},ue.jws.JWS.verifyJWT=function(e,t,r){var n=ue.jws,i=n.JWS,o=i.readSafeJSONString,s=i.inArray,a=i.includedArray,u=e.split("."),c=u[0],h=u[1],l=(we(u[2]),o(he(c))),d=o(he(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!==d.iss&&"object"===f(r.iss)&&!s(d.iss,r.iss))return!1;if(void 0!==d.sub&&"object"===f(r.sub)&&!s(d.sub,r.sub))return!1;if(void 0!==d.aud&&"object"===f(r.aud))if("string"==typeof d.aud){if(!s(d.aud,r.aud))return!1}else if("object"==f(d.aud)&&!a(d.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!==d.exp&&"number"==typeof d.exp&&d.exp+r.gracePeriod<p||void 0!==d.nbf&&"number"==typeof d.nbf&&p<d.nbf-r.gracePeriod||void 0!==d.iat&&"number"==typeof d.iat&&p<d.iat-r.gracePeriod||void 0!==d.jti&&void 0!==r.jti&&d.jti!==r.jti||!i.verify(e,t,r.alg))},ue.jws.JWS.includedArray=function(e,t){var r=ue.jws.JWS.inArray;if(null===e)return!1;if("object"!==(void 0===e?"undefined":f(e)))return!1;if("number"!=typeof e.length)return!1;for(var n=0;n<e.length;n++)if(!r(e[n],t))return!1;return!0},ue.jws.JWS.inArray=function(e,t){if(null===t)return!1;if("object"!==(void 0===t?"undefined":f(t)))return!1;if("number"!=typeof t.length)return!1;for(var r=0;r<t.length;r++)if(t[r]==e)return!0;return!1},ue.jws.JWS.jwsalg2sigalg={HS256:"HmacSHA256",HS384:"HmacSHA384",HS512:"HmacSHA512",RS256:"SHA256withRSA",RS384:"SHA384withRSA",RS512:"SHA512withRSA",ES256:"SHA256withECDSA",ES384:"SHA384withECDSA",PS256:"SHA256withRSAandMGF1",PS384:"SHA384withRSAandMGF1",PS512:"SHA512withRSAandMGF1",none:"none"},ue.jws.JWS.isSafeJSONString=function(e,t,r){var n=null;try{return"object"!=(void 0===(n=ae(e))?"undefined":f(n))||n.constructor===Array?0:(t&&(t[r]=n),1)}catch(e){return 0}},ue.jws.JWS.readSafeJSONString=function(e){var t=null;try{return"object"!=(void 0===(t=ae(e))?"undefined":f(t))||t.constructor===Array?null:t}catch(e){return null}},ue.jws.JWS.getEncodedSignatureValueFromJWS=function(e){var t=e.match(/^[^.]+\.[^.]+\.([^.]+)$/);if(null==t)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";return t[1]},ue.jws.JWS.getJWKthumbprint=function(e){if("RSA"!==e.kty&&"EC"!==e.kty&&"oct"!==e.kty)throw"unsupported algorithm for JWK Thumprint";var t="{";if("RSA"===e.kty){if("string"!=typeof e.n||"string"!=typeof e.e)throw"wrong n and e value for RSA key";t+='"e":"'+e.e+'",',t+='"kty":"'+e.kty+'",',t+='"n":"'+e.n+'"}'}else if("EC"===e.kty){if("string"!=typeof e.crv||"string"!=typeof e.x||"string"!=typeof e.y)throw"wrong crv, x and y value for EC key";t+='"crv":"'+e.crv+'",',t+='"kty":"'+e.kty+'",',t+='"x":"'+e.x+'",',t+='"y":"'+e.y+'"}'}else if("oct"===e.kty){if("string"!=typeof e.k)throw"wrong k value for oct(symmetric) key";t+='"kty":"'+e.kty+'",',t+='"k":"'+e.k+'"}'}var r=Ee(t);return me(ue.crypto.Util.hashHex(r,"sha256"))},ue.jws.IntDate={},ue.jws.IntDate.get=function(e){var t=ue.jws.IntDate,r=t.getNow,n=t.getZulu;if("now"==e)return r();if("now + 1hour"==e)return r()+3600;if("now + 1day"==e)return r()+86400;if("now + 1month"==e)return r()+2592e3;if("now + 1year"==e)return r()+31536e3;if(e.match(/Z$/))return n(e);if(e.match(/^[0-9]+$/))return parseInt(e);throw"unsupported format: "+e},ue.jws.IntDate.getZulu=function(e){return Ie(e)},ue.jws.IntDate.getNow=function(){return~~(new Date/1e3)},ue.jws.IntDate.intDate2UTCString=function(e){return new Date(1e3*e).toUTCString()},ue.jws.IntDate.intDate2Zulu=function(e){var t=new Date(1e3*e);return("0000"+t.getUTCFullYear()).slice(-4)+("00"+(t.getUTCMonth()+1)).slice(-2)+("00"+t.getUTCDate()).slice(-2)+("00"+t.getUTCHours()).slice(-2)+("00"+t.getUTCMinutes()).slice(-2)+("00"+t.getUTCSeconds()).slice(-2)+"Z"},t.SecureRandom=ee,t.rng_seed_time=z,t.BigInteger=b,t.RSAKey=ne;var $e=ue.crypto.EDSA;t.EDSA=$e;var ze=ue.crypto.DSA;t.DSA=ze;var Ye=ue.crypto.Signature;t.Signature=Ye;var Ge=ue.crypto.MessageDigest;t.MessageDigest=Ge;var Xe=ue.crypto.Mac;t.Mac=Xe;var Qe=ue.crypto.Cipher;t.Cipher=Qe,t.KEYUTIL=Ke,t.ASN1HEX=le,t.X509=We,t.CryptoJS=y,t.b64tohex=_,t.b64toBA=S,t.stoBA=de,t.BAtos=fe,t.BAtohex=pe,t.stohex=ge,t.stob64=function(e){return w(ge(e))},t.stob64u=function(e){return ye(w(ge(e)))},t.b64utos=function(e){return fe(S(ve(e)))},t.b64tob64u=ye,t.b64utob64=ve,t.hex2b64=w,t.hextob64u=me,t.b64utohex=we,t.utf8tob64u=ce,t.b64utoutf8=he,t.utf8tob64=function(e){return w(Ce(Oe(e)))},t.b64toutf8=function(e){return decodeURIComponent(Re(_(e)))},t.utf8tohex=_e,t.hextoutf8=Se,t.hextorstr=be,t.rstrtohex=Ee,t.hextob64=Fe,t.hextob64nl=xe,t.b64nltohex=Ae,t.hextopem=ke,t.pemtohex=Pe,t.hextoArrayBuffer=function(e){if(e.length%2!=0)throw"input is not even length";if(null==e.match(/^[0-9A-Fa-f]+$/))throw"input is not hexadecimal";for(var t=new ArrayBuffer(e.length/2),r=new DataView(t),n=0;n<e.length/2;n++)r.setUint8(n,parseInt(e.substr(2*n,2),16));return t},t.ArrayBuffertohex=function(e){for(var t="",r=new DataView(e),n=0;n<e.byteLength;n++)t+=("00"+r.getUint8(n).toString(16)).slice(-2);return t},t.zulutomsec=Te,t.zulutosec=Ie,t.zulutodate=function(e){return new Date(Te(e))},t.datetozulu=function(e,t,r){var n,i=e.getUTCFullYear();if(t){if(i<1950||2049<i)throw"not proper year for UTCTime: "+i;n=(""+i).slice(-2)}else n=("000"+i).slice(-4);if(n+=("0"+(e.getUTCMonth()+1)).slice(-2),n+=("0"+e.getUTCDate()).slice(-2),n+=("0"+e.getUTCHours()).slice(-2),n+=("0"+e.getUTCMinutes()).slice(-2),n+=("0"+e.getUTCSeconds()).slice(-2),r){var o=e.getUTCMilliseconds();0!==o&&(n+="."+(o=(o=("00"+o).slice(-3)).replace(/0+$/g,"")))}return n+"Z"},t.uricmptohex=Ce,t.hextouricmp=Re,t.ipv6tohex=Ue,t.hextoipv6=Le,t.hextoip=De,t.iptohex=function(e){var t="malformed IP address";if(!(e=e.toLowerCase(e)).match(/^[0-9.]+$/)){if(e.match(/^[0-9a-f:]+$/)&&-1!==e.indexOf(":"))return Ue(e);throw t}var r=e.split(".");if(4!==r.length)throw t;var n="";try{for(var i=0;i<4;i++)n+=("0"+parseInt(r[i]).toString(16)).slice(-2);return n}catch(e){throw t}},t.encodeURIComponentAll=Oe,t.newline_toUnix=function(e){return e.replace(/\r\n/gm,"\n")},t.newline_toDos=function(e){return(e=e.replace(/\r\n/gm,"\n")).replace(/\n/gm,"\r\n")},t.hextoposhex=je,t.intarystrtohex=function(e){e=(e=(e=e.replace(/^\s*\[\s*/,"")).replace(/\s*\]\s*$/,"")).replace(/\s*/g,"");try{return e.split(/,/).map(function(e,t,r){var n=parseInt(e);if(n<0||255<n)throw"integer not in range 0-255";return("00"+n.toString(16)).slice(-2)}).join("")}catch(e){throw"malformed integer array string: "+e}},t.strdiffidx=function(e,t){var r=e.length;e.length>t.length&&(r=t.length);for(var n=0;n<r;n++)if(e.charCodeAt(n)!=t.charCodeAt(n))return n;return e.length!=t.length?r:-1},t.KJUR=ue;var Ze=ue.crypto;t.crypto=Ze;var et=ue.asn1;t.asn1=et;var tt=ue.jws;t.jws=tt;var rt=ue.lang;t.lang=rt}).call(this,r(28).Buffer)},function(e,t,r){"use strict";(function(e){
25
23
  /*!
26
24
  * The buffer module from node.js, for the browser.
27
25
  *
28
26
  * @author Feross Aboukhadijeh <http://feross.org>
29
27
  * @license MIT
30
28
  */
31
- var n=r(30),i=r(31),s=r(32);function o(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(o()<t)throw new RangeError("Invalid typed array length");return u.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=u.prototype:(null===e&&(e=new u(t)),e.length=t),e}function u(e,t,r){if(!(u.TYPED_ARRAY_SUPPORT||this instanceof u))return new u(e,t,r);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return l(this,e)}return c(this,e,t,r)}function c(e,t,r,n){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,r,n){if(t.byteLength,r<0||t.byteLength<r)throw new RangeError("'offset' is out of bounds");if(t.byteLength<r+(n||0))throw new RangeError("'length' is out of bounds");return t=void 0===r&&void 0===n?new Uint8Array(t):void 0===n?new Uint8Array(t,r):new Uint8Array(t,r,n),u.TYPED_ARRAY_SUPPORT?(e=t).__proto__=u.prototype:e=d(e,t),e}(e,t,r,n):"string"==typeof t?function(e,t,r){if("string"==typeof r&&""!==r||(r="utf8"),!u.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=0|p(t,r),i=(e=a(e,n)).write(t,r);return i!==n&&(e=e.slice(0,i)),e}(e,t,r):function(e,t){if(u.isBuffer(t)){var r=0|f(t.length);return 0===(e=a(e,r)).length||t.copy(e,0,0,r),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||function(e){return e!=e}(t.length)?a(e,0):d(e,t);if("Buffer"===t.type&&s(t.data))return d(e,t.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function h(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function l(e,t){if(h(t),e=a(e,t<0?0:0|f(t)),!u.TYPED_ARRAY_SUPPORT)for(var r=0;r<t;++r)e[r]=0;return e}function d(e,t){var r=t.length<0?0:0|f(t.length);e=a(e,r);for(var n=0;n<r;n+=1)e[n]=255&t[n];return e}function f(e){if(e>=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|e}function p(e,t){if(u.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 q(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 F(this,t,r);case"ascii":return k(this,t,r);case"latin1":case"binary":return I(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(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 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),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=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:m(e,t,r,n,i);if("number"==typeof t)return t&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):m(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function m(e,t,r,n,i){var s,o=1,a=e.length,u=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;o=2,a/=2,u/=2,r/=2}function c(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){var h=-1;for(s=r;s<a;s++)if(c(e,s)===c(t,-1===h?0:s-h)){if(-1===h&&(h=s),s-h+1===u)return h*o}else-1!==h&&(s-=s-h),h=-1}else for(r+u>a&&(r=a-u),s=r;s>=0;s--){for(var l=!0,d=0;d<u;d++)if(c(e,s+d)!==c(t,d)){l=!1;break}if(l)return s}return-1}function w(e,t,r,n){r=Number(r)||0;var i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");n>s/2&&(n=s/2);for(var o=0;o<n;++o){var a=parseInt(t.substr(2*o,2),16);if(isNaN(a))return o;e[r+o]=a}return o}function b(e,t,r,n){return K(H(t,e.length-r),e,r,n)}function _(e,t,r,n){return K(function(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function S(e,t,r,n){return _(e,t,r,n)}function E(e,t,r,n){return K(q(t),e,r,n)}function x(e,t,r,n){return K(function(e,t){for(var r,n,i,s=[],o=0;o<e.length&&!((t-=2)<0);++o)n=(r=e.charCodeAt(o))>>8,i=r%256,s.push(i),s.push(n);return s}(t,e.length-r),e,r,n)}function A(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function F(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i<r;){var s,o,a,u,c=e[i],h=null,l=c>239?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&(s=e[i+1]))&&(u=(31&c)<<6|63&s)>127&&(h=u);break;case 3:s=e[i+1],o=e[i+2],128==(192&s)&&128==(192&o)&&(u=(15&c)<<12|(63&s)<<6|63&o)>2047&&(u<55296||u>57343)&&(h=u);break;case 4:s=e[i+1],o=e[i+2],a=e[i+3],128==(192&s)&&128==(192&o)&&128==(192&a)&&(u=(15&c)<<18|(63&s)<<12|(63&o)<<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(e){var t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);for(var r="",n=0;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=T));return r}(n)}t.Buffer=u,t.SlowBuffer=function(e){return+e!=e&&(e=0),u.alloc(+e)},t.INSPECT_MAX_BYTES=50,u.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}(),t.kMaxLength=o(),u.poolSize=8192,u._augment=function(e){return e.__proto__=u.prototype,e},u.from=function(e,t,r){return c(null,e,t,r)},u.TYPED_ARRAY_SUPPORT&&(u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0})),u.alloc=function(e,t,r){return function(e,t,r,n){return h(t),t<=0?a(e,t):void 0!==r?"string"==typeof n?a(e,t).fill(r,n):a(e,t).fill(r):a(e,t)}(null,e,t,r)},u.allocUnsafe=function(e){return l(null,e)},u.allocUnsafeSlow=function(e){return l(null,e)},u.isBuffer=function(e){return!(null==e||!e._isBuffer)},u.compare=function(e,t){if(!u.isBuffer(e)||!u.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,i=0,s=Math.min(r,n);i<s;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},u.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(e,t){if(!s(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return u.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var n=u.allocUnsafe(t),i=0;for(r=0;r<e.length;++r){var o=e[r];if(!u.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(n,i),i+=o.length}return n},u.byteLength=p,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)y(this,t,t+1);return this},u.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)y(this,t,t+3),y(this,t+1,t+2);return this},u.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},u.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?F(this,0,e):g.apply(this,arguments)},u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.prototype.inspect=function(){var e="",r=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),"<Buffer "+e+">"},u.prototype.compare=function(e,t,r,n,i){if(!u.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 s=(i>>>=0)-(n>>>=0),o=(r>>>=0)-(t>>>=0),a=Math.min(s,o),c=this.slice(n,i),h=e.slice(t,r),l=0;l<a;++l)if(c[l]!==h[l]){s=c[l],o=h[l];break}return s<o?-1:o<s?1:0},u.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},u.prototype.indexOf=function(e,t,r){return v(this,e,t,r,!0)},u.prototype.lastIndexOf=function(e,t,r){return v(this,e,t,r,!1)},u.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(r)?(r|=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var 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");for(var s=!1;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return b(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 x(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var T=4096;function k(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}function I(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}function C(e,t,r){var n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);for(var i="",s=t;s<r;++s)i+=B(e[s]);return i}function R(e,t,r){for(var n=e.slice(t,r),i="",s=0;s<n.length;s+=2)i+=String.fromCharCode(n[s]+256*n[s+1]);return i}function P(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,r,n,i,s){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function U(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,s=Math.min(e.length-r,2);i<s;++i)e[r+i]=(t&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function O(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,s=Math.min(e.length-r,4);i<s;++i)e[r+i]=t>>>8*(n?i:3-i)&255}function L(e,t,r,n,i,s){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function D(e,t,r,n,s){return s||L(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function j(e,t,r,n,s){return s||L(e,0,r,8),i.write(e,t,r,n,52,8),r+8}u.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),t<e&&(t=e),u.TYPED_ARRAY_SUPPORT)(r=this.subarray(e,t)).__proto__=u.prototype;else{var i=t-e;r=new u(i,void 0);for(var s=0;s<i;++s)r[s]=this[s+e]}return r},u.prototype.readUIntLE=function(e,t,r){e|=0,t|=0,r||P(e,t,this.length);for(var n=this[e],i=1,s=0;++s<t&&(i*=256);)n+=this[e+s]*i;return n},u.prototype.readUIntBE=function(e,t,r){e|=0,t|=0,r||P(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},u.prototype.readUInt8=function(e,t){return t||P(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||P(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||P(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||P(e,t,this.length);for(var n=this[e],i=1,s=0;++s<t&&(i*=256);)n+=this[e+s]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||P(e,t,this.length);for(var n=t,i=1,s=this[e+--n];n>0&&(i*=256);)s+=this[e+--n]*i;return s>=(i*=128)&&(s-=Math.pow(2,8*t)),s},u.prototype.readInt8=function(e,t){return t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){t||P(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){t||P(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return t||P(e,4,this.length),i.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||P(e,4,this.length),i.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||P(e,8,this.length),i.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||P(e,8,this.length),i.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,r,n){e=+e,t|=0,r|=0,n||N(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,s=0;for(this[t]=255&e;++s<r&&(i*=256);)this[t+s]=e/i&255;return t+r},u.prototype.writeUIntBE=function(e,t,r,n){e=+e,t|=0,r|=0,n||N(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+r},u.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):U(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):U(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):O(this,e,t,!0),t+4},u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):O(this,e,t,!1),t+4},u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);N(this,e,t,r,i-1,-i)}var s=0,o=1,a=0;for(this[t]=255&e;++s<r&&(o*=256);)e<0&&0===a&&0!==this[t+s-1]&&(a=1),this[t+s]=(e/o|0)-a&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);N(this,e,t,r,i-1,-i)}var s=r-1,o=1,a=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===a&&0!==this[t+s+1]&&(a=1),this[t+s]=(e/o|0)-a&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):U(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):U(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):O(this,e,t,!0),t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):O(this,e,t,!1),t+4},u.prototype.writeFloatLE=function(e,t,r){return D(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return D(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return j(this,e,t,!1,r)},u.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<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=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<n-r&&(n=e.length-t+r);var i,s=n-r;if(this===e&&r<t&&t<n)for(i=s-1;i>=0;--i)e[i+t]=this[i+r];else if(s<1e3||!u.TYPED_ARRAY_SUPPORT)for(i=0;i<s;++i)e[i+t]=this[i+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+s),t);return s},u.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),1===e.length){var i=e.charCodeAt(0);i<256&&(e=i)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!u.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;var s;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(s=t;s<r;++s)this[s]=e;else{var o=u.isBuffer(e)?e:H(new u(e,n).toString()),a=o.length;for(s=0;s<r-t;++s)this[s+t]=o[s%a]}return this};var M=/[^+\/0-9A-Za-z-_]/g;function B(e){return e<16?"0"+e.toString(16):e.toString(16)}function H(e,t){var r;t=t||1/0;for(var n=e.length,i=null,s=[],o=0;o<n;++o){if((r=e.charCodeAt(o))>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(t-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.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;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function q(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 K(e,t,r,n){for(var i=0;i<n&&!(i+r>=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=u(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,n=u(e),o=n[0],a=n[1],c=new s(function(e,t,r){return 3*(t+r)/4-r}(0,o,a)),h=0,l=a>0?o-4:o;for(r=0;r<l;r+=4)t=i[e.charCodeAt(r)]<<18|i[e.charCodeAt(r+1)]<<12|i[e.charCodeAt(r+2)]<<6|i[e.charCodeAt(r+3)],c[h++]=t>>16&255,c[h++]=t>>8&255,c[h++]=255&t;return 2===a&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,c[h++]=255&t),1===a&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,c[h++]=t>>8&255,c[h++]=255&t),c},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,s=[],o=16383,a=0,u=r-i;a<u;a+=o)s.push(c(e,a,a+o>u?u:a+o));return 1===i?(t=e[r-1],s.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],s.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),s.join("")};for(var n=[],i=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)n[a]=o[a],i[o.charCodeAt(a)]=a;function u(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,r){for(var i,s,o=[],a=t;a<r;a+=3)i=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(255&e[a+2]),o.push(n[(s=i)>>18&63]+n[s>>12&63]+n[s>>6&63]+n[63&s]);return o.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){
29
+ var n=r(30),i=r(31),o=r(32);function s(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(s()<t)throw new RangeError("Invalid typed array length");return u.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=u.prototype:(null===e&&(e=new u(t)),e.length=t),e}function u(e,t,r){if(!(u.TYPED_ARRAY_SUPPORT||this instanceof u))return new u(e,t,r);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return l(this,e)}return c(this,e,t,r)}function c(e,t,r,n){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,r,n){if(t.byteLength,r<0||t.byteLength<r)throw new RangeError("'offset' is out of bounds");if(t.byteLength<r+(n||0))throw new RangeError("'length' is out of bounds");return t=void 0===r&&void 0===n?new Uint8Array(t):void 0===n?new Uint8Array(t,r):new Uint8Array(t,r,n),u.TYPED_ARRAY_SUPPORT?(e=t).__proto__=u.prototype:e=d(e,t),e}(e,t,r,n):"string"==typeof t?function(e,t,r){if("string"==typeof r&&""!==r||(r="utf8"),!u.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=0|p(t,r),i=(e=a(e,n)).write(t,r);return i!==n&&(e=e.slice(0,i)),e}(e,t,r):function(e,t){if(u.isBuffer(t)){var r=0|f(t.length);return 0===(e=a(e,r)).length||t.copy(e,0,0,r),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||function(e){return e!=e}(t.length)?a(e,0):d(e,t);if("Buffer"===t.type&&o(t.data))return d(e,t.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function h(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function l(e,t){if(h(t),e=a(e,t<0?0:0|f(t)),!u.TYPED_ARRAY_SUPPORT)for(var r=0;r<t;++r)e[r]=0;return e}function d(e,t){var r=t.length<0?0:0|f(t.length);e=a(e,r);for(var n=0;n<r;n+=1)e[n]=255&t[n];return e}function f(e){if(e>=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(u.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 B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return K(e).length;default:if(n)return B(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 I(this,t,r);case"utf8":case"utf-8":return A(this,t,r);case"ascii":return P(this,t,r);case"latin1":case"binary":return T(this,t,r);case"base64":return x(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(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 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),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=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:m(e,t,r,n,i);if("number"==typeof t)return t&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):m(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function m(e,t,r,n,i){var o,s=1,a=e.length,u=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,u/=2,r/=2}function c(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){var h=-1;for(o=r;o<a;o++)if(c(e,o)===c(t,-1===h?0:o-h)){if(-1===h&&(h=o),o-h+1===u)return h*s}else-1!==h&&(o-=o-h),h=-1}else for(r+u>a&&(r=a-u),o=r;o>=0;o--){for(var l=!0,d=0;d<u;d++)if(c(e,o+d)!==c(t,d)){l=!1;break}if(l)return o}return-1}function w(e,t,r,n){r=Number(r)||0;var i=e.length-r;n?(n=Number(n))>i&&(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<n;++s){var a=parseInt(t.substr(2*s,2),16);if(isNaN(a))return s;e[r+s]=a}return s}function _(e,t,r,n){return V(B(t,e.length-r),e,r,n)}function S(e,t,r,n){return V(function(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function b(e,t,r,n){return S(e,t,r,n)}function E(e,t,r,n){return V(K(t),e,r,n)}function F(e,t,r,n){return V(function(e,t){for(var r,n,i,o=[],s=0;s<e.length&&!((t-=2)<0);++s)n=(r=e.charCodeAt(s))>>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function x(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function A(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i<r;){var o,s,a,u,c=e[i],h=null,l=c>239?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=e[i+1]))&&(u=(31&c)<<6|63&o)>127&&(h=u);break;case 3:o=e[i+1],s=e[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=e[i+1],s=e[i+2],a=e[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(e){var t=e.length;if(t<=k)return String.fromCharCode.apply(String,e);for(var r="",n=0;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=k));return r}(n)}t.Buffer=u,t.SlowBuffer=function(e){return+e!=e&&(e=0),u.alloc(+e)},t.INSPECT_MAX_BYTES=50,u.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}(),t.kMaxLength=s(),u.poolSize=8192,u._augment=function(e){return e.__proto__=u.prototype,e},u.from=function(e,t,r){return c(null,e,t,r)},u.TYPED_ARRAY_SUPPORT&&(u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0})),u.alloc=function(e,t,r){return function(e,t,r,n){return h(t),t<=0?a(e,t):void 0!==r?"string"==typeof n?a(e,t).fill(r,n):a(e,t).fill(r):a(e,t)}(null,e,t,r)},u.allocUnsafe=function(e){return l(null,e)},u.allocUnsafeSlow=function(e){return l(null,e)},u.isBuffer=function(e){return!(null==e||!e._isBuffer)},u.compare=function(e,t){if(!u.isBuffer(e)||!u.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,i=0,o=Math.min(r,n);i<o;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},u.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(e,t){if(!o(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return u.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var n=u.allocUnsafe(t),i=0;for(r=0;r<e.length;++r){var s=e[r];if(!u.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(n,i),i+=s.length}return n},u.byteLength=p,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)y(this,t,t+1);return this},u.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)y(this,t,t+3),y(this,t+1,t+2);return this},u.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},u.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?A(this,0,e):g.apply(this,arguments)},u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.prototype.inspect=function(){var e="",r=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),"<Buffer "+e+">"},u.prototype.compare=function(e,t,r,n,i){if(!u.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),c=this.slice(n,i),h=e.slice(t,r),l=0;l<a;++l)if(c[l]!==h[l]){o=c[l],s=h[l];break}return o<s?-1:s<o?1:0},u.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},u.prototype.indexOf=function(e,t,r){return v(this,e,t,r,!0)},u.prototype.lastIndexOf=function(e,t,r){return v(this,e,t,r,!1)},u.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(r)?(r|=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var 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");for(var o=!1;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return _(this,e,t,r);case"ascii":return S(this,e,t,r);case"latin1":case"binary":return b(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return F(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var k=4096;function P(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}function T(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}function I(e,t,r){var n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);for(var i="",o=t;o<r;++o)i+=M(e[o]);return i}function C(e,t,r){for(var n=e.slice(t,r),i="",o=0;o<n.length;o+=2)i+=String.fromCharCode(n[o]+256*n[o+1]);return i}function R(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function U(e,t,r,n,i,o){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function L(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);i<o;++i)e[r+i]=(t&255<<8*(n?i:1-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<o;++i)e[r+i]=t>>>8*(n?i:3-i)&255}function N(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 O(e,t,r,n,o){return o||N(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function H(e,t,r,n,o){return o||N(e,0,r,8),i.write(e,t,r,n,52,8),r+8}u.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),t<e&&(t=e),u.TYPED_ARRAY_SUPPORT)(r=this.subarray(e,t)).__proto__=u.prototype;else{var i=t-e;r=new u(i,void 0);for(var o=0;o<i;++o)r[o]=this[o+e]}return r},u.prototype.readUIntLE=function(e,t,r){e|=0,t|=0,r||R(e,t,this.length);for(var n=this[e],i=1,o=0;++o<t&&(i*=256);)n+=this[e+o]*i;return n},u.prototype.readUIntBE=function(e,t,r){e|=0,t|=0,r||R(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},u.prototype.readUInt8=function(e,t){return t||R(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||R(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||R(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||R(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return t||R(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||R(e,t,this.length);for(var n=this[e],i=1,o=0;++o<t&&(i*=256);)n+=this[e+o]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||R(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},u.prototype.readInt8=function(e,t){return t||R(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){t||R(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){t||R(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return t||R(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return t||R(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return t||R(e,4,this.length),i.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||R(e,4,this.length),i.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||R(e,8,this.length),i.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||R(e,8,this.length),i.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,r,n){e=+e,t|=0,r|=0,n||U(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o<r&&(i*=256);)this[t+o]=e/i&255;return t+r},u.prototype.writeUIntBE=function(e,t,r,n){e=+e,t|=0,r|=0,n||U(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},u.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||U(this,e,t,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||U(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):L(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||U(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):L(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||U(this,e,t,4,4294967295,0),u.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},u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||U(this,e,t,4,4294967295,0),u.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},u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);U(this,e,t,r,i-1,-i)}var o=0,s=1,a=0;for(this[t]=255&e;++o<r&&(s*=256);)e<0&&0===a&&0!==this[t+o-1]&&(a=1),this[t+o]=(e/s|0)-a&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);U(this,e,t,r,i-1,-i)}var o=r-1,s=1,a=0;for(this[t+o]=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},u.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||U(this,e,t,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||U(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):L(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||U(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):L(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||U(this,e,t,4,2147483647,-2147483648),u.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},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||U(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.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},u.prototype.writeFloatLE=function(e,t,r){return O(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return O(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return H(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return H(this,e,t,!1,r)},u.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<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=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<n-r&&(n=e.length-t+r);var i,o=n-r;if(this===e&&r<t&&t<n)for(i=o-1;i>=0;--i)e[i+t]=this[i+r];else if(o<1e3||!u.TYPED_ARRAY_SUPPORT)for(i=0;i<o;++i)e[i+t]=this[i+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+o),t);return o},u.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),1===e.length){var i=e.charCodeAt(0);i<256&&(e=i)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!u.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;var o;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o<r;++o)this[o]=e;else{var s=u.isBuffer(e)?e:B(new u(e,n).toString()),a=s.length;for(o=0;o<r-t;++o)this[o+t]=s[o%a]}return this};var j=/[^+\/0-9A-Za-z-_]/g;function M(e){return e<16?"0"+e.toString(16):e.toString(16)}function B(e,t){var r;t=t||1/0;for(var n=e.length,i=null,o=[],s=0;s<n;++s){if((r=e.charCodeAt(s))>55295&&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 K(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(j,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function V(e,t,r,n){for(var i=0;i<n&&!(i+r>=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=u(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,n=u(e),s=n[0],a=n[1],c=new o(function(e,t,r){return 3*(t+r)/4-r}(0,s,a)),h=0,l=a>0?s-4:s;for(r=0;r<l;r+=4)t=i[e.charCodeAt(r)]<<18|i[e.charCodeAt(r+1)]<<12|i[e.charCodeAt(r+2)]<<6|i[e.charCodeAt(r+3)],c[h++]=t>>16&255,c[h++]=t>>8&255,c[h++]=255&t;return 2===a&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,c[h++]=255&t),1===a&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,c[h++]=t>>8&255,c[h++]=255&t),c},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],s=16383,a=0,u=r-i;a<u;a+=s)o.push(c(e,a,a+s>u?u: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 u(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,r){for(var i,o,s=[],a=t;a<r;a+=3)i=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(255&e[a+2]),s.push(n[(o=i)>>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){
32
30
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
33
- t.read=function(e,t,r,n,i){var s,o,a=8*i-n-1,u=(1<<a)-1,c=u>>1,h=-7,l=r?i-1:0,d=r?-1:1,f=e[t+l];for(l+=d,s=f&(1<<-h)-1,f>>=-h,h+=a;h>0;s=256*s+e[t+l],l+=d,h-=8);for(o=s&(1<<-h)-1,s>>=-h,h+=n;h>0;o=256*o+e[t+l],l+=d,h-=8);if(0===s)s=1-c;else{if(s===u)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),s-=c}return(f?-1:1)*o*Math.pow(2,s-n)},t.write=function(e,t,r,n,i,s){var o,a,u,c=8*s-i-1,h=(1<<c)-1,l=h>>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-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,o=h):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),(t+=o+l>=1?d/u:d*Math.pow(2,1-l))*u>=2&&(o++,u/=2),o+l>=h?(a=0,o=h):o+l>=1?(a=(t*u-1)*Math.pow(2,i),o+=l):(a=t*Math.pow(2,l-1)*Math.pow(2,i),o=0));i>=8;e[r+f]=255&a,f+=p,a/=256,i-=8);for(o=o<<i|a,c+=i;c>0;e[r+f]=255&o,f+=p,o/=256,c-=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,s=e.crypto,o=e.hextob64u,a=e.b64tohex,u=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,s,o,u,c,h,l){n.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 n.Log.error("JoseUtil.validateJwt: RSA key missing key material",s),Promise.reject(new Error("RSA key missing key material"));var d=a(s.x5c[0]);s=i.getPublicKeyFromCertHex(d)}else{if("EC"!==s.kty)return n.Log.error("JoseUtil.validateJwt: Unsupported key type",s&&s.kty),Promise.reject(new Error(s.kty));if(!(s.crv&&s.x&&s.y))return n.Log.error("JoseUtil.validateJwt: EC key missing key material",s),Promise.reject(new Error("EC key missing key material"));s=r.getKey(s)}return e._validateJwt(t,s,o,u,c,h,l)}catch(e){return n.Log.error(e&&e.message||e),Promise.reject("JWT validation failed")}},e.validateJwtAttributes=function(t,r,i,s,o,a){s||(s=0),o||(o=parseInt(Date.now()/1e3));var u=e.parseJwt(t).payload;if(!u.iss)return n.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(u.iss!==r)return n.Log.error("JoseUtil._validateJwt: Invalid issuer in token",u.iss),Promise.reject(new Error("Invalid issuer in token: "+u.iss));if(!u.aud)return n.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(u.aud===i||Array.isArray(u.aud)&&u.aud.indexOf(i)>=0))return n.Log.error("JoseUtil._validateJwt: Invalid audience in token",u.aud),Promise.reject(new Error("Invalid audience in token: "+u.aud));if(u.azp&&u.azp!==i)return n.Log.error("JoseUtil._validateJwt: Invalid azp in token",u.azp),Promise.reject(new Error("Invalid azp in token: "+u.azp));if(!a){var c=o+s,h=o-s;if(!u.iat)return n.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(c<u.iat)return n.Log.error("JoseUtil._validateJwt: iat is in the future",u.iat),Promise.reject(new Error("iat is in the future: "+u.iat));if(u.nbf&&c<u.nbf)return n.Log.error("JoseUtil._validateJwt: nbf is in the future",u.nbf),Promise.reject(new Error("nbf is in the future: "+u.nbf));if(!u.exp)return n.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if(u.exp<h)return n.Log.error("JoseUtil._validateJwt: exp is in the past",u.exp),Promise.reject(new Error("exp is in the past:"+u.exp))}return Promise.resolve(u)},e._validateJwt=function(r,i,s,o,a,c,h){return e.validateJwtAttributes(r,s,o,a,c,h).then(function(e){try{return t.JWS.verify(r,i,u)?e:(n.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(e){return n.Log.error(e&&e.message||e),Promise.reject(new Error("signature validation failed"))}})},e.hashString=function e(t,r){try{return s.Util.hashString(t,r)}catch(e){n.Log.error(e)}},e.hexToBase64Url=function e(t){try{return o(t)}catch(e){n.Log.error(e)}},e}()};var n=r(0);e.exports=t.default},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SigninResponse=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(3);t.SigninResponse=function(){function e(t){var r=arguments.length>1&&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),s=r(9);t.SignoutRequest=function e(t){var r=t.url,o=t.id_token_hint,a=t.post_logout_redirect_uri,u=t.data,c=t.extraQueryParams,h=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 l in o&&(r=i.UrlUtility.addQueryParam(r,"id_token_hint",o)),a&&(r=i.UrlUtility.addQueryParam(r,"post_logout_redirect_uri",a),u&&(this.state=new s.State({data:u,request_type:h}),r=i.UrlUtility.addQueryParam(r,"state",this.state.id))),c)r=i.UrlUtility.addQueryParam(r,l,c[l]);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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0);t.InMemoryWebStorage=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._data={}}return e.prototype.getItem=function(e){return i.Log.debug("InMemoryWebStorage.getItem",e),this._data[e]},e.prototype.setItem=function(e,t){i.Log.debug("InMemoryWebStorage.setItem",e),this._data[e]=t},e.prototype.removeItem=function(e){i.Log.debug("InMemoryWebStorage.removeItem",e),delete this._data[e]},e.prototype.key=function(e){return Object.getOwnPropertyNames(this._data)[e]},n(e,[{key:"length",get:function(){return Object.getOwnPropertyNames(this._data).length}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserManager=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),s=r(10),o=r(39),a=r(15),u=r(45),c=r(47),h=r(18),l=r(8),d=r(20),f=r(11),p=r(4);t.UserManager=function(e){function t(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:c.SilentRenewService,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:h.SessionMonitor,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:d.TokenRevocationClient,l=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 o.UserManagerSettings||(r=new o.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 u.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 s(y)),y._tokenRevocationClient=new a(y._settings),y._tokenClient=new l(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(s){return r._joseUtil.validateJwtAttributes(t,n,r._settings.client_id,r._settings.clockSkew,s).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,s=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")):s})},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&&l.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(s){return i.Log.debug("UserManager._signoutStart: loaded current user from storage"),(t._settings.revokeAccessTokenOnSignout?t._revokeInternal(s):Promise.resolve()).then(function(){var o=e.id_token_hint||s&&s.id_token;return o&&(i.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),e.id_token_hint=o),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,s=e.refresh_token;return this._revokeAccessTokenInternal(n,t).then(function(e){return r._revokeRefreshTokenInternal(s,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}(s.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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=(r(0),r(5)),s=r(40),o=r(41),a=r(43),u=r(6),c=r(1),h=r(8);t.UserManagerSettings=function(e){function t(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=r.popup_redirect_uri,i=r.popup_post_logout_redirect_uri,l=r.popupWindowFeatures,d=r.popupWindowTarget,f=r.silent_redirect_uri,p=r.silentRequestTimeout,g=r.automaticSilentRenew,y=void 0!==g&&g,v=r.validateSubOnSilentRenew,m=void 0!==v&&v,w=r.includeIdTokenInSilentRenew,b=void 0===w||w,_=r.monitorSession,S=void 0===_||_,E=r.monitorAnonymousSession,x=void 0!==E&&E,A=r.checkSessionInterval,F=void 0===A?2e3:A,T=r.stopCheckSessionOnError,k=void 0===T||T,I=r.query_status_response_type,C=r.revokeAccessTokenOnSignout,R=void 0!==C&&C,P=r.accessTokenExpiringNotificationTime,N=void 0===P?60:P,U=r.redirectNavigator,O=void 0===U?new s.RedirectNavigator:U,L=r.popupNavigator,D=void 0===L?new o.PopupNavigator:L,j=r.iframeNavigator,M=void 0===j?new a.IFrameNavigator:j,B=r.userStore,H=void 0===B?new u.WebStorageStateStore({store:c.Global.sessionStorage}):B;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var q=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 q._popup_redirect_uri=n,q._popup_post_logout_redirect_uri=i,q._popupWindowFeatures=l,q._popupWindowTarget=d,q._silent_redirect_uri=f,q._silentRequestTimeout=p,q._automaticSilentRenew=y,q._validateSubOnSilentRenew=m,q._includeIdTokenInSilentRenew=b,q._accessTokenExpiringNotificationTime=N,q._monitorSession=S,q._monitorAnonymousSession=x,q._checkSessionInterval=F,q._stopCheckSessionOnError=k,I?q._query_status_response_type=I: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=R,q._redirectNavigator=O,q._popupNavigator=D,q._iframeNavigator=M,q._userStore=H,q}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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0);t.RedirectNavigator=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.prototype.prepare=function(){return Promise.resolve(this)},e.prototype.navigate=function(e){return e&&e.url?(e.useReplaceToNavigate?window.location.replace(e.url):window.location=e.url,Promise.resolve()):(i.Log.error("RedirectNavigator.navigate: No url provided"),Promise.reject(new Error("No url provided")))},n(e,[{key:"url",get:function(){return window.location.href}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PopupNavigator=void 0;var n=r(0),i=r(42);t.PopupNavigator=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.prototype.prepare=function(e){var t=new i.PopupWindow(e);return Promise.resolve(t)},e.prototype.callback=function e(t,r,s){n.Log.debug("PopupNavigator.callback");try{return i.PopupWindow.notifyOpener(t,r,s),Promise.resolve()}catch(e){return Promise.reject(e)}},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PopupWindow=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),s=r(3);t.PopupWindow=function(){function e(t){var r=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._promise=new Promise(function(e,t){r._resolve=e,r._reject=t});var n=t.popupWindowTarget||"_blank",s=t.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",n,s),this._popup&&(i.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return e.prototype.navigate=function(e){return this._popup?e&&e.url?(i.Log.debug("PopupWindow.navigate: Setting URL in popup"),this._id=e.id,this._id&&(window["popupCallback_"+e.id]=this._callback.bind(this)),this._popup.focus(),this._popup.window.location=e.url):(this._error("PopupWindow.navigate: no url provided"),this._error("No url provided")):this._error("PopupWindow.navigate: Error opening popup window"),this.promise},e.prototype._success=function(e){i.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(e)},e.prototype._error=function(e){i.Log.error("PopupWindow.error: ",e),this._cleanup(),this._reject(new Error(e))},e.prototype.close=function(){this._cleanup(!1)},e.prototype._cleanup=function(e){i.Log.debug("PopupWindow.cleanup"),window.clearInterval(this._checkForPopupClosedTimer),this._checkForPopupClosedTimer=null,delete window["popupCallback_"+this._id],this._popup&&!e&&this._popup.close(),this._popup=null},e.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},e.prototype._callback=function(e,t){this._cleanup(t),e?(i.Log.debug("PopupWindow.callback success"),this._success({url:e})):(i.Log.debug("PopupWindow.callback: Invalid response from popup"),this._error("Invalid response from popup"))},e.notifyOpener=function(e,t,r){if(window.opener){if(e=e||window.location.href){var n=s.UrlUtility.parseUrlFragment(e,r);if(n.state){var o="popupCallback_"+n.state,a=window.opener[o];a?(i.Log.debug("PopupWindow.notifyOpener: passing url message to opener"),a(e,t)):i.Log.warn("PopupWindow.notifyOpener: no matching callback found on opener")}else i.Log.warn("PopupWindow.notifyOpener: no state found in response url")}}else i.Log.warn("PopupWindow.notifyOpener: no window.opener. Can't complete notification.")},n(e,[{key:"promise",get:function(){return this._promise}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IFrameNavigator=void 0;var n=r(0),i=r(44);t.IFrameNavigator=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.prototype.prepare=function(e){var t=new i.IFrameWindow(e);return Promise.resolve(t)},e.prototype.callback=function e(t){n.Log.debug("IFrameNavigator.callback");try{return i.IFrameWindow.notifyParent(t),Promise.resolve()}catch(e){return Promise.reject(e)}},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IFrameWindow=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0);t.IFrameWindow=function(){function e(t){var r=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._promise=new Promise(function(e,t){r._resolve=e,r._reject=t}),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.width=0,this._frame.height=0,window.document.body.appendChild(this._frame)}return e.prototype.navigate=function(e){if(e&&e.url){var t=e.silentRequestTimeout||1e4;i.Log.debug("IFrameWindow.navigate: Using timeout of:",t),this._timer=window.setTimeout(this._timeout.bind(this),t),this._frame.src=e.url}else this._error("No url provided");return this.promise},e.prototype._success=function(e){this._cleanup(),i.Log.debug("IFrameWindow: Successful response from frame window"),this._resolve(e)},e.prototype._error=function(e){this._cleanup(),i.Log.error(e),this._reject(new Error(e))},e.prototype.close=function(){this._cleanup()},e.prototype._cleanup=function(){this._frame&&(i.Log.debug("IFrameWindow: cleanup"),window.removeEventListener("message",this._boundMessageEvent,!1),window.clearTimeout(this._timer),window.document.body.removeChild(this._frame),this._timer=null,this._frame=null,this._boundMessageEvent=null)},e.prototype._timeout=function(){i.Log.debug("IFrameWindow.timeout"),this._error("Frame window timed out")},e.prototype._message=function(e){if(i.Log.debug("IFrameWindow.message"),this._timer&&e.origin===this._origin&&e.source===this._frame.contentWindow&&"string"==typeof e.data&&(e.data.startsWith("http://")||e.data.startsWith("https://"))){var t=e.data;t?this._success({url:t}):this._error("Invalid response from frame")}},e.notifyParent=function(e){i.Log.debug("IFrameWindow.notifyParent"),(e=e||window.location.href)&&(i.Log.debug("IFrameWindow.notifyParent: posting url message to parent"),window.parent.postMessage(e,location.protocol+"//"+location.host))},n(e,[{key:"promise",get:function(){return this._promise}},{key:"_origin",get:function(){return location.protocol+"//"+location.host}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserManagerEvents=void 0;var n=r(0),i=r(16),s=r(17);t.UserManagerEvents=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=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 n._userLoaded=new s.Event("User loaded"),n._userUnloaded=new s.Event("User unloaded"),n._silentRenewError=new s.Event("Silent renew error"),n._userSignedIn=new s.Event("User signed in"),n._userSignedOut=new s.Event("User signed out"),n._userSessionChanged=new s.Event("User session changed"),n}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.load=function(t){var r=!(arguments.length>1&&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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),s=r(1),o=r(17);t.Timer=function(e){function t(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.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 o=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 o._timer=n,o._nowFunc=i||function(){return Date.now()/1e3},o}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<r&&(r=e),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*r)}},t.prototype.cancel=function(){this._timerHandle&&(i.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},t.prototype._callback=function(){var t=this._expiration-this.now;i.Log.debug("Timer.callback; "+this._name+" timer expires in:",t),this._expiration<=this.now&&(this.cancel(),e.prototype.raise.call(this))},n(t,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),t}(o.Event)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SilentRenewService=void 0;var n=r(0);t.SilentRenewService=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._userManager=t}return e.prototype.start=function(){this._callback||(this._callback=this._tokenExpiring.bind(this),this._userManager.events.addAccessTokenExpiring(this._callback),this._userManager.getUser().then(function(e){}).catch(function(e){n.Log.error("SilentRenewService.start: Error from getUser:",e.message)}))},e.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},e.prototype._tokenExpiring=function(){var e=this;this._userManager.signinSilent().then(function(e){n.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")},function(t){n.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",t.message),e._userManager.events._raiseSilentRenewError(t)})},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CordovaPopupNavigator=void 0;var n=r(21);t.CordovaPopupNavigator=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.prototype.prepare=function(e){var t=new n.CordovaPopupWindow(e);return Promise.resolve(t)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CordovaIFrameNavigator=void 0;var n=r(21);t.CordovaIFrameNavigator=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.prototype.prepare=function(e){e.popupWindowFeatures="hidden=yes";var t=new n.CordovaPopupWindow(e);return Promise.resolve(t)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Version="1.11.6"}])},e.exports=t()},7007: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 s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise(function(r,n){function i(r){e.removeListener(t,s),n(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}g(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&g(e,"error",t,r)}(e,i,{once:!0})})},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function u(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,r,n){var i,s,o,c;if(a(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(i=u(e))>0&&o.length>i&&!o.warned){o.warned=!0;var h=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");h.name="MaxListenersExceededWarning",h.emitter=e,h.type=t,h.count=o.length,c=h,console&&console.warn&&console.warn(c)}return e}function h(){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 l(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=h.bind(n);return i.listener=r,n.wrapFn=i,i}function d(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;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(i):p(i,i.length)}function f(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function p(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function g(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(s){n.once&&e.removeEventListener(t,i),r(s)})}}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,s=this._events;if(void 0!==s)i=i&&void 0===s.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var u=s[e];if(void 0===u)return!1;if("function"==typeof u)n(u,this,t);else{var c=u.length,h=p(u,c);for(r=0;r<c;++r)n(h[r],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return a(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var r,n,i,s,o;if(a(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return d(this,e,!0)},s.prototype.rawListeners=function(e){return d(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},s.prototype.listenerCount=f,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},7526:(e,t)=>{"use strict";t.byteLength=function(e){var t=a(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,s=a(e),o=s[0],u=s[1],c=new i(function(e,t,r){return 3*(t+r)/4-r}(0,o,u)),h=0,l=u>0?o-4:o;for(r=0;r<l;r+=4)t=n[e.charCodeAt(r)]<<18|n[e.charCodeAt(r+1)]<<12|n[e.charCodeAt(r+2)]<<6|n[e.charCodeAt(r+3)],c[h++]=t>>16&255,c[h++]=t>>8&255,c[h++]=255&t;2===u&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[h++]=255&t);1===u&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[h++]=t>>8&255,c[h++]=255&t);return c},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,s=[],o=16383,a=0,u=n-i;a<u;a+=o)s.push(c(e,a,a+o>u?u:a+o));1===i?(t=e[n-1],s.push(r[t>>2]+r[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],s.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return s.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)r[o]=s[o],n[s.charCodeAt(o)]=o;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 u(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}function c(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),i.push(u(n));return i.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},8287:(e,t,r)=>{"use strict";
34
- /*!
35
- * The buffer module from node.js, for the browser.
36
- *
37
- * @author Feross Aboukhadijeh <https://feross.org>
38
- * @license MIT
39
- */
40
- const n=r(7526),i=r(251),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=u,t.IS=50;const o=2147483647;function a(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,u.prototype),t}function u(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 l(e)}return c(e,t,r)}function c(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|g(e,t);let n=a(r);const i=n.write(e,t);i!==r&&(n=n.slice(0,i));return n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(X(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return d(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(X(e,ArrayBuffer)||e&&X(e.buffer,ArrayBuffer))return f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(X(e,SharedArrayBuffer)||e&&X(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 u.from(n,t,r);const i=function(e){if(u.isBuffer(e)){const t=0|p(e.length),r=a(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||G(e.length)?a(0):d(e);if("Buffer"===e.type&&Array.isArray(e.data))return d(e.data)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.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 h(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 l(e){return h(e),a(e<0?0:0|p(e))}function d(e){const t=e.length<0?0:0|p(e.length),r=a(t);for(let n=0;n<t;n+=1)r[n]=255&e[n];return r}function f(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),Object.setPrototypeOf(n,u.prototype),n}function p(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function g(e,t){if(u.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||X(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 W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return J(e).length;default:if(i)return n?-1:W(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 F(this,t,r);case"ascii":return k(this,t,r);case"latin1":case"binary":return I(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const 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),G(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=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:w(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):w(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function w(e,t,r,n,i){let s,o=1,a=e.length,u=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;o=2,a/=2,u/=2,r/=2}function c(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){let n=-1;for(s=r;s<a;s++)if(c(e,s)===c(t,-1===n?0:s-n)){if(-1===n&&(n=s),s-n+1===u)return n*o}else-1!==n&&(s-=s-n),n=-1}else for(r+u>a&&(r=a-u),s=r;s>=0;s--){let r=!0;for(let n=0;n<u;n++)if(c(e,s+n)!==c(t,n)){r=!1;break}if(r)return s}return-1}function b(e,t,r,n){r=Number(r)||0;const i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;const s=t.length;let o;for(n>s/2&&(n=s/2),o=0;o<n;++o){const n=parseInt(t.substr(2*o,2),16);if(G(n))return o;e[r+o]=n}return o}function _(e,t,r,n){return z(W(t,e.length-r),e,r,n)}function S(e,t,r,n){return z(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function E(e,t,r,n){return z(J(t),e,r,n)}function x(e,t,r,n){return z(function(e,t){let r,n,i;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)r=e.charCodeAt(o),n=r>>8,i=r%256,s.push(i),s.push(n);return s}(t,e.length-r),e,r,n)}function A(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function F(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i<r;){const t=e[i];let s=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=r){let r,n,a,u;switch(o){case 1:t<128&&(s=t);break;case 2:r=e[i+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(s=u));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:r=e[i+1],n=e[i+2],a=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&a,u>65535&&u<1114112&&(s=u))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),i+=o}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=T));return r}(n)}u.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),u.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.buffer}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.byteOffset}}),u.poolSize=8192,u.from=function(e,t,r){return c(e,t,r)},Object.setPrototypeOf(u.prototype,Uint8Array.prototype),Object.setPrototypeOf(u,Uint8Array),u.alloc=function(e,t,r){return function(e,t,r){return h(e),e<=0?a(e):void 0!==t?"string"==typeof r?a(e).fill(t,r):a(e).fill(t):a(e)}(e,t,r)},u.allocUnsafe=function(e){return l(e)},u.allocUnsafeSlow=function(e){return l(e)},u.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==u.prototype},u.compare=function(e,t){if(X(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),X(t,Uint8Array)&&(t=u.from(t,t.offset,t.byteLength)),!u.isBuffer(e)||!u.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let i=0,s=Math.min(r,n);i<s;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},u.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return u.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=u.allocUnsafe(t);let i=0;for(r=0;r<e.length;++r){let t=e[r];if(X(t,Uint8Array))i+t.length>n.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(n,i)):Uint8Array.prototype.set.call(n,t,i);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},u.byteLength=g,u.prototype._isBuffer=!0,u.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;t<e;t+=2)v(this,t,t+1);return this},u.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)v(this,t,t+3),v(this,t+1,t+2);return this},u.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)v(this,t,t+7),v(this,t+1,t+6),v(this,t+2,t+5),v(this,t+3,t+4);return this},u.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?F(this,0,e):y.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.prototype.inspect=function(){let e="";const r=t.IS;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},s&&(u.prototype[s]=u.prototype.inspect),u.prototype.compare=function(e,t,r,n,i){if(X(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.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 s=(i>>>=0)-(n>>>=0),o=(r>>>=0)-(t>>>=0);const a=Math.min(s,o),c=this.slice(n,i),h=e.slice(t,r);for(let e=0;e<a;++e)if(c[e]!==h[e]){s=c[e],o=h[e];break}return s<o?-1:o<s?1:0},u.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},u.prototype.indexOf=function(e,t,r){return m(this,e,t,r,!0)},u.prototype.lastIndexOf=function(e,t,r){return m(this,e,t,r,!1)},u.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=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 s=!1;for(;;)switch(n){case"hex":return b(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 x(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function k(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}function I(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}function C(e,t,r){const n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=t;n<r;++n)i+=Y[e[n]];return i}function R(e,t,r){const n=e.slice(t,r);let i="";for(let e=0;e<n.length-1;e+=2)i+=String.fromCharCode(n[e]+256*n[e+1]);return i}function P(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,r,n,i,s){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function U(e,t,r,n,i){q(t,n,i,e,r,7);let s=Number(t&BigInt(4294967295));e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,r}function O(e,t,r,n,i){q(t,n,i,e,r,7);let s=Number(t&BigInt(4294967295));e[r+7]=s,s>>=8,e[r+6]=s,s>>=8,e[r+5]=s,s>>=8,e[r+4]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=o,o>>=8,e[r+2]=o,o>>=8,e[r+1]=o,o>>=8,e[r]=o,r+8}function L(e,t,r,n,i,s){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function D(e,t,r,n,s){return t=+t,r>>>=0,s||L(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function j(e,t,r,n,s){return t=+t,r>>>=0,s||L(e,0,r,8),i.write(e,t,r,n,52,8),r+8}u.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<e&&(t=e);const n=this.subarray(e,t);return Object.setPrototypeOf(n,u.prototype),n},u.prototype.readUintLE=u.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let n=this[e],i=1,s=0;for(;++s<t&&(i*=256);)n+=this[e+s]*i;return n},u.prototype.readUintBE=u.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=Q(function(e){K(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)<<BigInt(32))}),u.prototype.readBigUInt64BE=Q(function(e){K(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*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)<<BigInt(32))+BigInt(i)}),u.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let n=this[e],i=1,s=0;for(;++s<t&&(i*=256);)n+=this[e+s]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let n=t,i=1,s=this[e+--n];for(;n>0&&(i*=256);)s+=this[e+--n]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s},u.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=Q(function(e){K(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)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),u.prototype.readBigInt64BE=Q(function(e){K(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<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)}),u.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),i.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),i.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),i.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),i.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){N(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=1,s=0;for(this[t]=255&e;++s<r&&(i*=256);)this[t+s]=e/i&255;return t+r},u.prototype.writeUintBE=u.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){N(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=r-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||N(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},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||N(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},u.prototype.writeBigUInt64LE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeBigUInt64BE=Q(function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);N(this,e,t,r,n-1,-n)}let i=0,s=1,o=0;for(this[t]=255&e;++i<r&&(s*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/s|0)-o&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);N(this,e,t,r,n-1,-n)}let i=r-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s|0)-o&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||N(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},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||N(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},u.prototype.writeBigInt64LE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeBigInt64BE=Q(function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeFloatLE=function(e,t,r){return D(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return D(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return j(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(!u.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<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=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<n-r&&(n=e.length-t+r);const i=n-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),i},u.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!u.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){const t=e.charCodeAt(0);("utf8"===n&&t<128||"latin1"===n)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let i;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{const s=u.isBuffer(e)?e:u.from(e,n),o=s.length;if(0===o)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=s[i%o]}return this};const M={};function B(e,t,r){M[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}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 q(e,t,r,n,i,s){if(e>r||e<t){const n="bigint"==typeof t?"n":"";let i;throw i=s>3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new M.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(n,i,s)}function K(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 K(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 $=/[^+/0-9A-Za-z-_]/g;function W(e,t){let r;t=t||1/0;const n=e.length;let i=null;const s=[];for(let o=0;o<n;++o){if(r=e.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(t-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.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;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function J(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace($,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function z(e,t,r,n){let i;for(i=0;i<n&&!(i+r>=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function X(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function G(e){return e!=e}const Y=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 Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},8392:t=>{"use strict";t.exports=e},8936:(e,t,r)=>{"use strict";r.d(t,{A:()=>i});var n=r(4705);class i{constructor(e){(0,n.A)(this,"termType",void 0),(0,n.A)(this,"classOrder",void 0),(0,n.A)(this,"value",void 0),this.value=e}substitute(e){return this}compareTerm(e){return this.classOrder<e.classOrder?-1:this.classOrder>e.classOrder?1:this.value<e.value?-1:this.value>e.value?1:0}equals(e){return!!e&&(this.termType===e.termType&&this.value===e.value)}hashString(){return this.toCanonical()}sameTerm(e){return this.equals(e)}toCanonical(){return this.toNT()}toNT(){return this.toString()}toNQ(){return this.toNT()}toString(){throw new Error("Node.toString() is abstract - see the subclasses instead")}}(0,n.A)(i,"fromValue",void 0),(0,n.A)(i,"toJS",void 0)},9403:(e,t,r)=>{"use strict";r.d(t,{$Q:()=>i,BR:()=>g,Fn:()=>b,H:()=>E,JG:()=>m,K9:()=>w,Kk:()=>n,MG:()=>p,P2:()=>o,QW:()=>s,S:()=>c,_0:()=>y,bD:()=>h,bM:()=>v,hu:()=>S,i2:()=>d,ic:()=>a,lc:()=>l,ny:()=>f,r0:()=>u,sT:()=>_});const n="NamedNode",i="BlankNode",s="Literal",o="Variable",a="DefaultGraph",u="Collection",c="Empty",h="Graph",l="text/html",d="application/ld+json",f="text/n3",p="application/n3",g="application/nquads",y="application/n-quads",v="application/n-triples",m="application/rdf+xml",w="application/sparql-update",b="application/sparql-update-single-match",_="text/turtle",S="application/x-turtle",E="application/xhtml+xml"}},o={};function a(e){var t=o[e];if(void 0!==t)return t.exports;var r=o[e]={id:e,loaded:!1,exports:{}};return s[e].call(r.exports,r,r.exports,a),r.loaded=!0,r.exports}a.m=s,a.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return a.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,a.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var i=Object.create(null);a.r(i);var s={};t=t||[null,r({}),r([]),r(r)];for(var o=2&n&&e;("object"==typeof o||"function"==typeof o)&&!~t.indexOf(o);o=r(o))Object.getOwnPropertyNames(o).forEach(t=>s[t]=()=>e[t]);return s.default=()=>e,a.d(i,s),i},a.d=(e,t)=>{for(var r in t)a.o(t,r)&&!a.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},a.f={},a.e=e=>Promise.all(Object.keys(a.f).reduce((t,r)=>(a.f[r](e,t),t),[])),a.u=e=>e+".solid-logic.min.js",a.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),a.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},i="SolidLogic:",a.l=(e,t,r,s)=>{if(n[e])n[e].push(t);else{var o,u;if(void 0!==r)for(var c=document.getElementsByTagName("script"),h=0;h<c.length;h++){var l=c[h];if(l.getAttribute("src")==e||l.getAttribute("data-webpack")==i+r){o=l;break}}o||(u=!0,(o=document.createElement("script")).charset="utf-8",o.timeout=120,a.nc&&o.setAttribute("nonce",a.nc),o.setAttribute("data-webpack",i+r),o.src=e),n[e]=[t];var d=(t,r)=>{o.onerror=o.onload=null,clearTimeout(f);var i=n[e];if(delete n[e],o.parentNode&&o.parentNode.removeChild(o),i&&i.forEach(e=>e(r)),t)return t(r)},f=setTimeout(d.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=d.bind(null,o.onerror),o.onload=d.bind(null,o.onload),u&&document.head.appendChild(o)}},a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;a.g.importScripts&&(e=a.g.location+"");var t=a.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var r=t.getElementsByTagName("script");if(r.length)for(var n=r.length-1;n>-1&&(!e||!/^http(s?):/.test(e));)e=r[n--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),a.p=e})(),(()=>{var e={792:0};a.f.j=(t,r)=>{var n=a.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var i=new Promise((r,i)=>n=e[t]=[r,i]);r.push(n[2]=i);var s=a.p+a.u(t),o=new Error;a.l(s,r=>{if(a.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var i=r&&("load"===r.type?"missing":r.type),s=r&&r.target&&r.target.src;o.message="Loading chunk "+t+" failed.\n("+i+": "+s+")",o.name="ChunkLoadError",o.type=i,o.request=s,n[1](o)}},"chunk-"+t,t)}};var t=(t,r)=>{var n,i,[s,o,u]=r,c=0;if(s.some(t=>0!==e[t])){for(n in o)a.o(o,n)&&(a.m[n]=o[n]);if(u)u(a)}for(t&&t(r);c<s.length;c++)i=s[c],a.o(e,i)&&e[i]&&e[i][0](),e[i]=0},r=this.webpackChunkSolidLogic=this.webpackChunkSolidLogic||[];r.forEach(t.bind(null,0)),r.push=t.bind(null,r.push.bind(r))})();var u={};return(()=>{"use strict";a.r(u),a.d(u,{ACL_LINK:()=>rs,CrossOriginForbiddenError:()=>ps,FetchError:()=>ws,NotEditableError:()=>vs,NotFoundError:()=>ys,SameOriginForbiddenError:()=>gs,UnauthorizedError:()=>fs,WebOperationError:()=>ms,appContext:()=>is,authSession:()=>Fs,authn:()=>As,createTypeIndexLogic:()=>_s,getSuggestedIssuers:()=>xs,offlineTestID:()=>ss,solidLogicSingleton:()=>Ss,store:()=>Ts});var e={};function t(...e){console.log(...e)}function r(...e){console.warn(...e)}a.r(e),a.d(e,{BlankNode:()=>tr,Collection:()=>ar,ConnectedStore:()=>Zi,DataFactory:()=>Ui,Empty:()=>ur,Fetcher:()=>ki,Formula:()=>Ur,IndexedFormula:()=>Kr,Literal:()=>sr,LiveStore:()=>es,N3Parser:()=>fn,NamedNode:()=>rr.A,Namespace:()=>_r,NextId:()=>Qi,Node:()=>Or,Query:()=>Dr,RDFParser:()=>ui,RDFaProcessor:()=>oi,SPARQLToQuery:()=>Ri,Serializer:()=>Tr,Statement:()=>fr,Store:()=>Kr,UpdateManager:()=>Pi,UpdatesSocket:()=>Oi,UpdatesVia:()=>Li,Util:()=>Sr,Variable:()=>gr,blankNode:()=>Vi,defaultGraph:()=>$i,fetcher:()=>ji,fromNT:()=>Gi,graph:()=>Mi,isBlankNode:()=>nr.jt,isCollection:()=>nr.P3,isGraph:()=>nr.RN,isLiteral:()=>nr.c$,isNamedNode:()=>nr.Y2,isPredicate:()=>nr.YC,isQuad:()=>nr.aF,isRDFObject:()=>nr.GE,isRDFlibObject:()=>nr.DJ,isRDFlibPredicate:()=>nr.fY,isRDFlibSubject:()=>nr.CZ,isStatement:()=>nr.SH,isStore:()=>nr.ok,isSubject:()=>nr.hr,isTerm:()=>nr.D0,isVariable:()=>nr.DZ,jsonParser:()=>Ii,lit:()=>Bi,literal:()=>Wi,log:()=>br.A,namedNode:()=>qi,parse:()=>hi,quad:()=>Ji,queryToSPARQL:()=>Ci,serialize:()=>Ir,sparqlUpdateParser:()=>ci,st:()=>Hi,sym:()=>qi,term:()=>Yi,termValue:()=>fi.E,triple:()=>zi,uri:()=>pr,variable:()=>Ki});const n=new TextEncoder,i=new TextDecoder;function s(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const o=e=>(e=>{let t=e;"string"==typeof t&&(t=n.encode(t));const r=[];for(let e=0;e<t.length;e+=32768)r.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(r.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),c=e=>{let t=e;t instanceof Uint8Array&&(t=i.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class h extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}h.code="ERR_JOSE_GENERIC";class l extends h{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}l.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class d extends h{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}d.code="ERR_JWT_EXPIRED";class f extends h{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}f.code="ERR_JOSE_ALG_NOT_ALLOWED";class p extends h{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}p.code="ERR_JOSE_NOT_SUPPORTED";(class extends h{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends h{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class g extends h{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}g.code="ERR_JWS_INVALID";class y extends h{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}y.code="ERR_JWT_INVALID";(class extends h{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}).code="ERR_JWK_INVALID";class v extends h{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}v.code="ERR_JWKS_INVALID";class m extends h{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}m.code="ERR_JWKS_NO_MATCHING_KEY";class w extends h{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Symbol.asyncIterator,w.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class b extends h{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}b.code="ERR_JWKS_TIMEOUT";class _ extends h{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function S(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new p(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}_.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const E=crypto,x=e=>e instanceof CryptoKey,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`)}};function F(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function T(e,t){return e.name===t}function k(e){return parseInt(e.name.slice(4),10)}function I(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 C(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!T(e.algorithm,"HMAC"))throw F("HMAC");const r=parseInt(t.slice(2),10);if(k(e.algorithm.hash)!==r)throw F(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!T(e.algorithm,"RSASSA-PKCS1-v1_5"))throw F("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(k(e.algorithm.hash)!==r)throw F(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!T(e.algorithm,"RSA-PSS"))throw F("RSA-PSS");const r=parseInt(t.slice(2),10);if(k(e.algorithm.hash)!==r)throw F(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw F("Ed25519 or Ed448");break;case"Ed25519":if(!T(e.algorithm,"Ed25519"))throw F("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!T(e.algorithm,"ECDSA"))throw F("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 F(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}I(e,r)}function R(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const P=(e,...t)=>R("Key must be ",e,...t);function N(e,t,...r){return R(`Key for the ${e} algorithm must be `,t,...r)}const U=e=>!!x(e)||"KeyObject"===e?.[Symbol.toStringTag],O=["CryptoKey"];function L(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}function D(e){return L(e)&&"string"==typeof e.kty}const j=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new p('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 p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new p('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],i={...e};return delete i.alg,delete i.use,E.subtle.importKey("jwk",i,...n)},M=e=>c(e);let B,H;const q=e=>"KeyObject"===e?.[Symbol.toStringTag],K=async(e,t,r,n,i=!1)=>{let s=e.get(t);if(s?.[n])return s[n];const o=await j({...r,alg:n});return i&&Object.freeze(t),s?s[n]=o:e.set(t,{[n]:o}),o},V=(e,t)=>{if(q(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?M(r.k):(H||(H=new WeakMap),K(H,e,r,t))}if(D(e)){if(e.k)return c(e.k);H||(H=new WeakMap);return K(H,e,e,t,!0)}return e},$=(e,t)=>{if(q(e)){let r=e.export({format:"jwk"});return r.k?M(r.k):(B||(B=new WeakMap),K(B,e,r,t))}if(D(e)){if(e.k)return c(e.k);B||(B=new WeakMap);return K(B,e,e,t,!0)}return e};async function W(e,t,r){if("sign"===r&&(t=await $(t,e)),"verify"===r&&(t=await V(t,e)),x(t))return C(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(P(t,...O));return E.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(P(t,...O,"Uint8Array","JSON Web Key"))}const J=async(e,t,r,n)=>{const i=await W(e,t,"verify");A(e,i);const s=S(e,i.algorithm);try{return await E.subtle.verify(s,i,r,n)}catch{return!1}},z=(...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},X=e=>e?.[Symbol.toStringTag],G=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Y=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&D(t)){if(function(e){return D(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&G(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!U(t))throw new TypeError(N(e,t,...O,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${X(t)} instances for symmetric algorithms must be of type "secret"`)}};function Q(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Y(t,r,n,e):((e,t,r,n)=>{if(n&&D(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&G(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&G(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!U(t))throw new TypeError(N(e,t,...O,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}Q.bind(void 0,!1);const Z=Q.bind(void 0,!0);const ee=function(e,t,r,n,i){if(void 0!==i.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;s=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!s.has(t))throw new p(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(s.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)},te=(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)};async function re(e,t){if(!L(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 c(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new p('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return j({...e,alg:t});default:throw new p('Unsupported "kty" (Key Type) Parameter value')}}async function ne(e,t,r){if(e instanceof Uint8Array&&(e=i.decode(e)),"string"!=typeof e)throw new g("Compact JWS must be a string or Uint8Array");const{0:o,1:a,2:u,length:h}=e.split(".");if(3!==h)throw new g("Invalid Compact JWS");const l=await async function(e,t,r){if(!L(e))throw new g("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new g('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new g("JWS Protected Header incorrect type");if(void 0===e.payload)throw new g("JWS Payload missing");if("string"!=typeof e.signature)throw new g("JWS Signature missing or incorrect type");if(void 0!==e.header&&!L(e.header))throw new g("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{const t=c(e.protected);o=JSON.parse(i.decode(t))}catch{throw new g("JWS Protected Header is invalid")}if(!z(o,e.header))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const a={...o,...e.header};let u=!0;if(ee(g,new Map([["b64",!0]]),r?.crit,o,a).has("b64")&&(u=o.b64,"boolean"!=typeof u))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:h}=a;if("string"!=typeof h||!h)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');const l=r&&te("algorithms",r.algorithms);if(l&&!l.has(h))throw new f('"alg" (Algorithm) Header Parameter value not allowed');if(u){if("string"!=typeof e.payload)throw new g("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new g("JWS Payload must be a string or an Uint8Array instance");let d=!1;"function"==typeof t?(t=await t(o,e),d=!0,Z(h,t,"verify"),D(t)&&(t=await re(t,h))):Z(h,t,"verify");const p=s(n.encode(e.protected??""),n.encode("."),"string"==typeof e.payload?n.encode(e.payload):e.payload);let y,v;try{y=c(e.signature)}catch{throw new g("Failed to base64url decode the signature")}if(!await J(h,t,y,p))throw new _;if(u)try{v=c(e.payload)}catch{throw new g("Failed to base64url decode the payload")}else v="string"==typeof e.payload?n.encode(e.payload):e.payload;const m={payload:v};return void 0!==e.protected&&(m.protectedHeader=o),void 0!==e.header&&(m.unprotectedHeader=e.header),d?{...m,key:t}:m}({payload:a,protected:o,signature:u},t,r),d={payload:l.payload,protectedHeader:l.protectedHeader};return"function"==typeof t?{...d,key:l.key}:d}const ie=e=>Math.floor(e.getTime()/1e3),se=86400,oe=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ae=e=>{const t=oe.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(r*se);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n},ue=e=>e.toLowerCase().replace(/^application\//,""),ce=(e,t,r={})=>{let n;try{n=JSON.parse(i.decode(t))}catch{}if(!L(n))throw new y("JWT Claims Set must be a top-level JSON object");const{typ:s}=r;if(s&&("string"!=typeof e.typ||ue(e.typ)!==ue(s)))throw new l('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:o=[],issuer:a,subject:u,audience:c,maxTokenAge:h}=r,f=[...o];void 0!==h&&f.push("iat"),void 0!==c&&f.push("aud"),void 0!==u&&f.push("sub"),void 0!==a&&f.push("iss");for(const e of new Set(f.reverse()))if(!(e in n))throw new l(`missing required "${e}" claim`,n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new l('unexpected "iss" claim value',n,"iss","check_failed");if(u&&n.sub!==u)throw new l('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(p=n.aud,g="string"==typeof c?[c]:c,!("string"==typeof p?g.includes(p):Array.isArray(p)&&g.some(Set.prototype.has.bind(new Set(p))))))throw new l('unexpected "aud" claim value',n,"aud","check_failed");var p,g;let v;switch(typeof r.clockTolerance){case"string":v=ae(r.clockTolerance);break;case"number":v=r.clockTolerance;break;case"undefined":v=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,w=ie(m||new Date);if((void 0!==n.iat||h)&&"number"!=typeof n.iat)throw new l('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new l('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>w+v)throw new l('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new l('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=w-v)throw new d('"exp" claim timestamp check failed',n,"exp","check_failed")}if(h){const e=w-n.iat;if(e-v>("number"==typeof h?h:ae(h)))throw new d('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-v)throw new l('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};const he=async(e,t,r)=>{let n,i,s=!1;"function"==typeof AbortController&&(n=new AbortController,i=setTimeout(()=>{s=!0,n.abort()},t));const o=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(e=>{if(s)throw new b;throw e});if(void 0!==i&&clearTimeout(i),200!==o.status)throw new h("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new h("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function le(e){return L(e)}function de(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class fe{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(le)}(e))throw new v("JSON Web Key Set malformed");this._jwks=de(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...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 p('Unsupported "alg" value for a JSON Web Key Set')}}(r),s=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)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":t="Ed25519"===e.crv;break;case"EdDSA":t="Ed25519"===e.crv||"Ed448"===e.crv}return t}),{0:o,length:a}=s;if(0===a)throw new m;if(1!==a){const e=new w,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of s)try{yield await pe(t,e,r)}catch{}},e}return pe(this._cached,o,r)}}async function pe(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await re({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new v("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function ge(e){const t=new fe(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>de(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}let ye;if("undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){ye=`${"jose"}/${"v5.10.0"}`}const ve=Symbol();class me{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");var r,n;this._url=new URL(e.href),this._options={agent:t?.agent,headers:t?.headers},this._timeoutDuration="number"==typeof t?.timeoutDuration?t?.timeoutDuration:5e3,this._cooldownDuration="number"==typeof t?.cooldownDuration?t?.cooldownDuration:3e4,this._cacheMaxAge="number"==typeof t?.cacheMaxAge?t?.cacheMaxAge:6e5,void 0!==t?.[ve]&&(this._cache=t?.[ve],r=t?.[ve],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&L(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,L)&&(this._jwksTimestamp=this._cache.uat,this._local=ge(this._cache.jwks)))}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){this._local&&this.fresh()||await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof m&&!1===this.coolingDown())return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);ye&&!e.has("User-Agent")&&(e.set("User-Agent",ye),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=he(this._url,this._timeoutDuration,this._options).then(e=>{this._local=ge(e),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=e),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}}const we=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:o(e)};if(!x(e))throw new TypeError(P(e,...O,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:t,key_ops:r,alg:n,use:i,...s}=await E.subtle.exportKey("jwk",e);return s};async function be(e){return we(e)}const _e=async(e,t,r)=>{const n=await W(e,t,"sign");A(e,n);const i=await E.subtle.sign(S(e,n.algorithm),n,r);return new Uint8Array(i)};class Se{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new g("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!z(this._protectedHeader,this._unprotectedHeader))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let a=!0;if(ee(g,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(a=this._protectedHeader.b64,"boolean"!=typeof a))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:u}=r;if("string"!=typeof u||!u)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');Z(u,e,"sign");let c,h=this._payload;a&&(h=n.encode(o(h))),c=this._protectedHeader?n.encode(o(JSON.stringify(this._protectedHeader))):n.encode("");const l=s(c,n.encode("."),h),d=await _e(u,e,l),f={signature:o(d),payload:""};return a&&(f.payload=i.decode(h)),this._unprotectedHeader&&(f.header=this._unprotectedHeader),this._protectedHeader&&(f.protected=i.decode(c)),f}}class Ee{constructor(e){this._flattened=new Se(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function xe(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class Ae{constructor(e={}){if(!L(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:xe("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:xe("setNotBefore",ie(e))}:this._payload={...this._payload,nbf:ie(new Date)+ae(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:xe("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:xe("setExpirationTime",ie(e))}:this._payload={...this._payload,exp:ie(new Date)+ae(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:ie(new Date)}:e instanceof Date?this._payload={...this._payload,iat:xe("setIssuedAt",ie(e))}:this._payload="string"==typeof e?{...this._payload,iat:xe("setIssuedAt",ie(new Date)+ae(e))}:{...this._payload,iat:xe("setIssuedAt",e)},this}}class Fe extends Ae{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new Ee(n.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new y("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}function Te(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new p("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function ke(e,t){return async function(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Te(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Te(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Te(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":r={name:"Ed25519"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];const e=t?.crv??"Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new p("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];const e=t?.crv??"P-256";switch(e){case"P-256":case"P-384":case"P-521":r={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":r={name:e};break;default:throw new p("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return E.subtle.generateKey(r,t?.extractable??!1,n)}(e,t)}const Ie={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let Ce;const Re=new Uint8Array(16);const Pe=[];for(let e=0;e<256;++e)Pe.push((e+256).toString(16).slice(1));function Ne(e,t=0){return(Pe[e[t+0]]+Pe[e[t+1]]+Pe[e[t+2]]+Pe[e[t+3]]+"-"+Pe[e[t+4]]+Pe[e[t+5]]+"-"+Pe[e[t+6]]+Pe[e[t+7]]+"-"+Pe[e[t+8]]+Pe[e[t+9]]+"-"+Pe[e[t+10]]+Pe[e[t+11]]+Pe[e[t+12]]+Pe[e[t+13]]+Pe[e[t+14]]+Pe[e[t+15]]).toLowerCase()}const Ue=function(e,t,r){if(Ie.randomUUID&&!t&&!e)return Ie.randomUUID();const n=(e=e||{}).random??e.rng?.()??function(){if(!Ce){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ce=crypto.getRandomValues.bind(crypto)}return Ce(Re)}();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){if((r=r||0)<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=n[e];return t}return Ne(n)},Oe="solidClientAuthn:",Le=["ES256","RS256"],De="error",je="login",Me="logout",Be="newRefreshToken",He="sessionExpired",qe="sessionExtended",Ke="sessionRestore",Ve="timeoutSet",$e=["openid","offline_access","webid"];class We{handleables;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<t.length;e+=1)if(t[e])return this.handleables[e];return null}async canHandle(...e){return null!==await this.getProperHandler(e)}async handle(...e){const t=await this.getProperHandler(e);if(t)return t.handle(...e);throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${e.map(e=>{try{return JSON.stringify(e)}catch(t){return e.toString()}}).join(", ")}`)}}async function Je(e,t,r,n){let i,s;try{const{payload:s}=await async function(e,t,r){const n=await ne(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new y("JWTs MUST NOT use unencoded payload");const i={payload:ce(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}(e,function(e,t){const r=new me(e,t),n=async(e,t)=>r.getKey(e,t);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}(new URL(t)),{issuer:r,audience:n});i=s}catch(e){throw new Error(`Token verification failed: ${e.stack}`)}if("string"==typeof i.azp&&(s=i.azp),"string"==typeof i.webid)return{webId:i.webid,clientId:s};if("string"!=typeof i.sub)throw new Error(`The token ${JSON.stringify(i)} is invalid: it has no 'webid' claim and no 'sub' claim.`);try{return new URL(i.sub),{webId:i.sub,clientId:s}}catch(e){throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${i.sub}] is invalid as a URL - error [${e}].`)}}function ze(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}}function Xe(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}class Ge{storageUtility;redirector;constructor(e,t){this.storageUtility=e,this.redirector=t,this.storageUtility=e,this.redirector=t}parametersGuard=e=>void 0!==e.issuerConfiguration.grantTypesSupported&&e.issuerConfiguration.grantTypesSupported.indexOf("authorization_code")>-1&&void 0!==e.redirectUrl;async canHandle(e){return this.parametersGuard(e)}async setupRedirectHandler({oidcLoginOptions:e,state:t,codeVerifier:r,targetUrl:n}){if(!this.parametersGuard(e))throw new Error("The authorization code grant requires a redirectUrl.");var i,s;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:Boolean(e.dpop).toString(),keepAlive:(i=e.keepAlive,s=!0,"boolean"==typeof i?Boolean(i):Boolean(s)).toString()})]),this.redirector.redirect(n,{handleRedirect:e.handleRedirect})}}class Ye{sessionInfoManager;constructor(e){this.sessionInfoManager=e,this.sessionInfoManager=e}async canHandle(){return!0}async handle(e){await this.sessionInfoManager.clear(e)}}class Qe{redirector;constructor(e){this.redirector=e,this.redirector=e}async canHandle(e,t){return"idp"===t?.logoutType}async handle(e,t){if("idp"!==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})}}class Ze{handlers;constructor(e,t){this.handlers=[new Ye(e),new Qe(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)}}function et(){return{isLoggedIn:!1,sessionId:Ue(),fetch:(...e)=>fetch(...e)}}async function tt(e,t){await Promise.all([t.deleteAllUserData(e,{secure:!1}),t.deleteAllUserData(e,{secure:!0})])}class rt{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}update(e,t){throw new Error("Not Implemented")}set(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 tt(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")}async setOidcContext(e,t){throw new Error("Not implemented")}}function nt({endSessionEndpoint:e,idTokenHint:t}){if(void 0!==e)return function({state:r,postLogoutUrl:n}){return function({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()}({endSessionEndpoint:e,idTokenHint:t,state:r,postLogoutRedirectUri:n})}}function it(e){try{return new URL(e),!0}catch{return!1}}async function st(e,t,r,n){let i;if(function(e,t){return t.scopesSupported.includes("webid")&&void 0!==e.clientId&&it(e.clientId)}(e,t))i={clientId:e.clientId,clientName:e.clientName,clientType:"solid-oidc"};else{if(!function(e){return void 0!==e.clientId&&!it(e.clientId)}(e))return n.getClient({sessionId:e.sessionId,clientName:e.clientName,redirectUrl:e.redirectUrl},t);i={clientId:e.clientId,clientSecret:e.clientSecret,clientName:e.clientName,clientType:"static"}}const s={clientId:i.clientId,clientType:i.clientType};return"static"===i.clientType&&(s.clientSecret=i.clientSecret),i.clientName&&(s.clientName=i.clientName),await r.setForUser(e.sessionId,s),i}const ot=(e,t)=>fetch(e,t);class at{loginHandler;redirectHandler;logoutHandler;sessionInfoManager;issuerConfigFetcher;boundLogout;constructor(e,t,r,n,i){this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=n,this.issuerConfigFetcher=i,this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=n,this.issuerConfigFetcher=i}fetch=ot;logout=async(e,t)=>{await this.logoutHandler.handle(e,"idp"===t?.logoutType?{...t,toLogoutUrl:this.boundLogout}:t),this.fetch=ot,delete this.boundLogout};getSessionInfo=async e=>this.sessionInfoManager.get(e);getAllSessionInfo=async()=>this.sessionInfoManager.getAll()}async function ut(e,t,r){try{const[n,i,s,o,a]=await Promise.all([t.getForUser(e,"issuer",{errorIfNull:!0}),t.getForUser(e,"codeVerifier"),t.getForUser(e,"redirectUrl"),t.getForUser(e,"dpop",{errorIfNull:!0}),t.getForUser(e,"keepAlive")]);await t.deleteForUser(e,"codeVerifier");return{codeVerifier:i,redirectUrl:s,issuerConfig:await r.fetchConfig(n),dpop:"true"===o,keepAlive:"string"!=typeof a||"true"===a}}catch(t){throw new Error(`Failed to retrieve OIDC context from storage associated with session [${e}]: ${t}`)}}class ct{secureStorage;insecureStorage;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(t?.secure?this.secureStorage:this.insecureStorage).get(e);if(void 0===r&&t?.errorIfNull)throw new Error(`[${e}] is not stored`);return r}async set(e,t,r){return(r?.secure?this.secureStorage:this.insecureStorage).set(e,t)}async delete(e,t){return(t?.secure?this.secureStorage:this.insecureStorage).delete(e)}async getForUser(e,t,r){const n=await this.getUserData(e,r?.secure);let i;if(n&&n[t]||(i=void 0),i=n[t],void 0===i&&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,r?.secure)}catch{n={}}await this.setUserData(e,{...n,...t},r?.secure)}async deleteForUser(e,t,r){const n=await this.getUserData(e,r?.secure);delete n[t],await this.setUserData(e,n,r?.secure)}async deleteAllUserData(e,t){await(t?.secure?this.secureStorage:this.insecureStorage).delete(this.getKey(e))}}class ht{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]}}class lt extends Error{constructor(e){super(e)}}Error;class dt extends Error{missingFields;constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class ft extends Error{error;errorDescription;constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function pt(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function gt(e,t,r){return new Fe({htu:pt(e),htm:t.toUpperCase(),jti:Ue()}).setProtectedHeader({alg:Le[0],jwk:r.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(r.privateKey,{})}async function yt(e,t,r,n){if(void 0!==r)return async function(e,t,r,n){const i=new Headers(n?.headers);return i.set("Authorization",`DPoP ${t}`),i.set("DPoP",await gt(e,n?.method??"get",r)),{...n,headers:i}}(e,t,r,n);const i=new Headers(n?.headers);return i.set("Authorization",`Bearer ${t}`),{...n,headers:i}}async function vt(e,t,r,n,i=fetch){return i(t,await yt(t.toString(),e,n,r))}const mt=e=>void 0!==e?e-5>0?e-5:e:600;function wt(e,t){let r,n=e;const i=t?.refreshOptions;if(void 0!==i){const e=async()=>{try{const{accessToken:s,refreshToken:o,expiresIn:a}=await async function(e,t,r){const n=await e.tokenRefresher.refresh(e.sessionId,e.refreshToken,t);return r?.emit(qe,n.expiresIn??600),{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresIn:n.expiresIn}}(i,t.dpopKey,t.eventEmitter);n=s,void 0!==o&&(i.refreshToken=o),clearTimeout(r),r=setTimeout(e,1e3*mt(a)),t.eventEmitter?.emit(Ve,r)}catch(e){e instanceof ft&&(t?.eventEmitter?.emit(De,e.error,e.errorDescription),t?.eventEmitter?.emit(He)),e instanceof dt&&e.missingFields.includes("access_token")&&t?.eventEmitter?.emit(He)}};r=setTimeout(e,1e3*mt(t.expiresIn)),t.eventEmitter?.emit(Ve,r)}else if(void 0!==t&&void 0!==t.eventEmitter){const e=setTimeout(()=>{t.eventEmitter.emit(He)},1e3*mt(t.expiresIn));t.eventEmitter.emit(Ve,e)}return async(e,r)=>{let i=await vt(n,e,r,t?.dpopKey,t?.fetch);const s=!i.ok&&(o=i.status,![401,403].includes(o));var o;if(i.ok||s)return i;return i.url!==e&&void 0!==t?.dpopKey&&(i=await vt(n,i.url,r,t.dpopKey,t.fetch)),i}}var bt=a(7007),_t=a(6516);function St(e,t){if("string"!=typeof e.client_id)throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(e)}`);if(t.redirectUrl&&function(e){return Array.isArray(e.redirect_uris)&&e.redirect_uris.every(e=>"string"==typeof e)}(e)&&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()])}`);return!0}async function Et(e,t){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 r=(n=t.idTokenSigningAlgValuesSupported,Le.find(e=>n.includes(e))??null);var n;const i={client_name:e.clientName,application_type:"web",redirect_uris:[e.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:r,grant_types:["authorization_code","refresh_token"]},s=await fetch(t.registrationEndpoint.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(s.ok){const t=await s.json();return St(t,e),{clientId:t.client_id,clientSecret:t.client_secret,expiresAt:t.client_secret_expires_at,idTokenSignedResponseAlg:t.id_token_signed_response_alg,clientType:"dynamic"}}throw 400===s.status&&function(e,t){if("invalid_redirect_uri"===e.error)throw new Error(`Dynamic client registration failed: the provided redirect uri [${t.redirectUrl?.toString()}] is invalid - ${e.error_description??""}`);if("invalid_client_metadata"===e.error)throw new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(t)} is invalid - ${e.error_description??""}`);throw new Error(`Dynamic client registration failed: ${e.error} - ${e.error_description??""}`)}(await s.json(),e),new Error(`Dynamic client registration failed: the server returned ${s.status} ${s.statusText} - ${await s.text()}`)}function xt(e){return void 0!==e.error_description&&"string"==typeof e.error_description}function At(e,t){if(void 0!==(r=e).error&&"string"==typeof r.error)throw new ft(`Token endpoint returned error [${e.error}]${xt(e)?`: ${e.error_description}`:""}${function(e){return void 0!==e.error_uri&&"string"==typeof e.error_uri}(e)?` (see ${e.error_uri})`:""}`,e.error,xt(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 dt(["access_token"]);if(!function(e){return void 0!==e.id_token&&"string"==typeof e.id_token}(e))throw new dt(["id_token"]);if(!function(e){return void 0!==e.token_type&&"string"==typeof e.token_type}(e))throw new dt(["token_type"]);if(!function(e){return void 0===e.expires_in||"number"==typeof e.expires_in}(e))throw new dt(["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 Ft(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 i={"content-type":"application/x-www-form-urlencoded"};let s;n&&(s=await async function(){const{privateKey:e,publicKey:t}=await ke(Le[0]),r={privateKey:e,publicKey:await be(t)};return[r.publicKey.alg]=Le,r}(),i.DPoP=await gt(e.tokenEndpoint,"POST",s)),t.clientSecret&&(i.Authorization=`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`);const o={grant_type:r.grantType,redirect_uri:r.redirectUrl,code:r.code,code_verifier:r.codeVerifier,client_id:t.clientId},a={method:"POST",headers:i,body:new URLSearchParams(o).toString()},u=await fetch(e.tokenEndpoint,a),c=At(await u.json(),n),{webId:h,clientId:l}=await Je(c.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:c.access_token,idToken:c.id_token,refreshToken:(d=c,void 0!==d.refresh_token&&"string"==typeof d.refresh_token?c.refresh_token:void 0),webId:h,clientId:l,dpopKey:s,expiresIn:c.expires_in};var d}async function Tt(e,t,r,n){if(void 0===r.clientId)throw new Error("No client ID available when trying to refresh the access token.");const i={grant_type:"refresh_token",refresh_token:e};let s={};void 0!==n&&(s={DPoP:await gt(t.tokenEndpoint,"POST",n)});let o={};void 0!==r.clientSecret?o={Authorization:`Basic ${btoa(`${r.clientId}:${r.clientSecret}`)}`}:(e=>{try{return new URL(e),!0}catch{return!1}})(r.clientId)&&(i.client_id=r.clientId);const a=await fetch(t.tokenEndpoint,{method:"POST",body:new URLSearchParams(i).toString(),headers:{...s,...o,"Content-Type":"application/x-www-form-urlencoded"}});let u;try{u=await a.json()}catch(e){throw new Error(`The token endpoint of issuer ${t.issuer} returned a malformed response.`)}const c=At(u,void 0!==n),{webId:h}=await Je(c.id_token,t.jwksUri,t.issuer,r.clientId);return{accessToken:c.access_token,idToken:c.id_token,refreshToken:"string"==typeof c.refresh_token?c.refresh_token:void 0,webId:h,dpopKey:n,expiresIn:c.expires_in}}class kt extends ct{constructor(e,t){super(e,t)}}class It extends at{login=async(e,t)=>{"none"!==e.prompt&&await this.sessionInfoManager.clear(e.sessionId);const r=e.redirectUrl??function(e){const t=Xe(e);return t.hash="",e.includes(`${t.origin}/`)?t.href:`${t.origin}${t.href.substring(t.origin.length+1)}`}(window.location.href);if(!ze(r))throw new Error(`${r} 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:r,clientName:e.clientName??e.clientId,eventEmitter:t})};validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return void 0===t||void 0===t.clientAppId||void 0===t.issuer?null:t};handleIncomingRedirect=async(e,t)=>{try{const r=await this.redirectHandler.handle(e,t,void 0);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,clientAppId:r.clientAppId}}catch(r){return await this.cleanUrlAfterRedirect(e),void t.emit(De,"redirect",r)}};async cleanUrlAfterRedirect(e){const t=Xe(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(e=>{setTimeout(()=>e(),1)})}}function Ct(e){return"string"==typeof e.oidcIssuer}function Rt(e){return"string"==typeof e.redirectUrl}class Pt{storageUtility;oidcHandler;issuerConfigFetcher;clientRegistrar;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 Ct(e)&&Rt(e)}async handle(e){if(!Ct(e))throw new lt(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!Rt(e))throw new lt(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),r=await st(e,t,this.storageUtility,this.clientRegistrar),n={issuer:t.issuer,dpop:"dpop"===e.tokenType.toLowerCase(),...e,issuerConfiguration:t,client:r,scopes:(i=e.customScopes,Array.isArray(i)?Array.from(new Set([...$e,...i.filter(e=>"string"==typeof e&&!e.includes(" "))])):$e)};var i;return this.oidcHandler.handle(n)}}class Nt extends Ge{async handle(e){const t={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:e.prompt??"consent"},r=new _t.OidcClient(t);try{const t=await r.createSigninRequest();return await this.setupRedirectHandler({oidcLoginOptions:e,state:t.state._id,codeVerifier:t.state._code_verifier,targetUrl:t.url.toString()})}catch(e){console.error(e)}}}const Ut={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 Ot{storageUtility;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,n=await fetch(r);try{t=function(e){const t={};return Object.keys(e).forEach(r=>{Ut[r]&&(t[Ut[r].toKey]=e[r])}),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(await n.json())}catch(t){throw new lt(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return await this.storageUtility.set(Ot.getLocalStorageKey(e),JSON.stringify(t)),t}}async function Lt(e,t){await tt(e,t),await async function(){const e=new _t.OidcClient({response_mode:"query"});await e.clearStaleState(new _t.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))}()}class Dt extends rt{async get(e){const[t,r,n,i,s,o,a,u]=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||ze(s)){if(void 0!==u&&("string"!=typeof(c=u)||!["DPoP","Bearer"].includes(c)))throw new Error(`Tokens of type [${u}] are not supported.`);var c;if(void 0!==n||void 0!==t||void 0!==r||void 0!==o)return{sessionId:e,webId:r,isLoggedIn:"true"===t,redirectUrl:s,refreshToken:o,issuer:a,clientAppId:n,clientAppSecret:i,tokenType:u??"DPoP"}}else await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})])}async clear(e){return Lt(e,this.storageUtility)}}class jt{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 et()}}class Mt{storageUtility;sessionInfoManager;issuerConfigFetcher;clientRegistrar;tokerRefresher;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),n=r.searchParams.get("state"),i=await this.storageUtility.getForUser(n,"sessionId",{errorIfNull:!0}),{issuerConfig:s,codeVerifier:o,redirectUrl:a,dpop:u}=await ut(i,this.storageUtility,this.issuerConfigFetcher),c=r.searchParams.get("iss");if("string"==typeof c&&c!==s.issuer)throw new Error(`The value of the iss parameter (${c}) does not match the issuer identifier of the authorization server (${s.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(void 0===o)throw new Error(`The code verifier for session ${i} is missing from storage.`);if(void 0===a)throw new Error(`The redirect URL for session ${i} is missing from storage.`);const h=await this.clientRegistrar.getClient({sessionId:i},s),l=Date.now(),d=await Ft(s,h,{grantType:"authorization_code",code:r.searchParams.get("code"),codeVerifier:o,redirectUrl:a},u);let f;window.localStorage.removeItem(`oidc.${n}`),void 0!==d.refreshToken&&(f={sessionId:i,refreshToken:d.refreshToken,tokenRefresher:this.tokerRefresher});const p=wt(d.accessToken,{dpopKey:d.dpopKey,refreshOptions:f,eventEmitter:t,expiresIn:d.expiresIn});await async function(e,t,r,n,i,s,o,a){void 0!==s&&await e.setForUser(t,{refreshToken:s},{secure:o}),void 0!==r&&await e.setForUser(t,{webId:r},{secure:o}),void 0!==n&&await e.setForUser(t,{clientId:n},{secure:o}),void 0!==i&&await e.setForUser(t,{isLoggedIn:i},{secure:o}),void 0!==a&&await e.setForUser(t,{publicKey:JSON.stringify(a.publicKey),privateKey:JSON.stringify(await be(a.privateKey))},{secure:o})}(this.storageUtility,i,d.webId,d.clientId,"true",void 0,!0);const g=await this.sessionInfoManager.get(i);if(!g)throw new Error(`Could not retrieve session: [${i}].`);return Object.assign(g,{fetch:p,getLogoutUrl:nt({idTokenHint:d.idToken,endSessionEndpoint:s.endSessionEndpoint}),expirationDate:"number"==typeof d.expiresIn?l+1e3*d.expiresIn:void 0})}}class Bt extends We{constructor(e){super(e)}}class Ht{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 qt{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class Kt{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[r,n,i,s,o]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"expiresAt",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientName",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientType",{secure:!1})]),a=void 0!==i?Number.parseInt(i,10):-1,u=void 0!==n&&0!==a&&Math.floor(Date.now()/1e3)>a;if(r&&("string"==typeof(c=o)&&["dynamic","static","solid-oidc"].includes(c))&&!u)return void 0!==n?{clientId:r,clientSecret:n,clientName:s,clientType:"dynamic",expiresAt:a}:{clientId:r,clientName:s,clientType:o};var c;try{const r=await Et(e,t),n={clientId:r.clientId,clientType:"dynamic"};return void 0!==r.clientSecret&&(n.clientSecret=r.clientSecret,n.expiresAt=String(r.expiresAt)),r.idTokenSignedResponseAlg&&(n.idTokenSignedResponseAlg=r.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,n,{secure:!1}),r}catch(e){throw new Error("Client registration failed.",{cause:e})}}}class Vt{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),n=r.searchParams.get("error"),i=r.searchParams.get("error_description");t.emit(De,n,i)}return et()}}class $t{storageUtility;issuerConfigFetcher;clientRegistrar;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,n){const i=await ut(e,this.storageUtility,this.issuerConfigFetcher),s=await this.clientRegistrar.getClient({sessionId:e},i.issuerConfig);if(void 0===t)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(i.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 o=await Tt(t,i.issuerConfig,s,r);return void 0!==o.refreshToken&&n?.emit(Be,o.refreshToken),o}}function Wt(e){const t=new ht,r=e.secureStorage||t,n=e.insecureStorage||new Ht,i=new kt(r,n),s=new Ot(i),o=new Kt(i),a=new Dt(i),u=new $t(i,s,o),c=new qt,h=new Pt(i,new Nt(i,c),s,o),l=new Bt([new Vt,new Mt(i,a,s,o,u),new jt]);return new It(h,l,new Ze(a,c),a,s)}const Jt=`${Oe}currentSession`,zt=`${Oe}currentUrl`;class Xt{info;events;clientAuthentication;tokenRequestInProgress=!1;constructor(e={},t=void 0){this.events=new bt,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=Wt({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage}):this.clientAuthentication=Wt({}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??Ue(),isLoggedIn:!1},this.events.on(je,()=>window.localStorage.setItem(Jt,this.info.sessionId)),this.events.on(He,()=>this.internalLogout(!1)),this.events.on(De,()=>this.internalLogout(!1))}login=async e=>(await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:e.tokenType??"DPoP"},this.events),new Promise(()=>{}));fetch=(e,t)=>this.clientAuthentication.fetch(e,t);internalLogout=async(e,t)=>{window.localStorage.removeItem(Jt),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(Me)};logout=async e=>this.internalLogout(!0,e);handleIncomingRedirect=async(e={})=>{if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const t="string"==typeof e?{url:e}:e,r=t.url??window.location.href;this.tokenRequestInProgress=!0;const n=await this.clientAuthentication.handleIncomingRedirect(r,this.events);if(function(e){return!!e?.isLoggedIn}(n)){this.setSessionInfo(n);const e=window.localStorage.getItem(zt);null===e?this.events.emit(je):(window.localStorage.removeItem(zt),this.events.emit(Ke,e))}else if(!0===t.restorePreviousSession){const e=window.localStorage.getItem(Jt);if(null!==e){if(await async function(e,t,r){const n=await t.validateCurrentSession(e);return null!==n&&(window.localStorage.setItem(zt,window.location.href),await t.login({sessionId:e,prompt:"none",oidcIssuer:n.issuer,redirectUrl:n.redirectUrl,clientId:n.clientAppId,clientSecret:n.clientAppSecret,tokenType:n.tokenType??"DPoP"},r.events),!0)}(e,this.clientAuthentication,this))return new Promise(()=>{})}}return this.tokenRequestInProgress=!1,n};setSessionInfo(e){this.info.isLoggedIn=e.isLoggedIn,this.info.webId=e.webId,this.info.sessionId=e.sessionId,this.info.clientAppId=e.clientAppId,this.info.expirationDate=e.expirationDate,this.events.on(qe,e=>{this.info.expirationDate=Date.now()+1e3*e})}}const Gt=new Xt;var Yt=a(4705),Qt=a(1059),Zt=a(8936),er=a(9403);class tr extends Zt.A{static getId(e){if(e){if("string"!=typeof e)throw new Error("Bad id argument to new blank node: "+e);if(e.includes("#")){let t=e.split("#");return t[t.length-1]}return e}return"n"+tr.nextId++}constructor(e){super(tr.getId(e)),(0,Yt.A)(this,"termType",er.$Q),(0,Yt.A)(this,"classOrder",Qt.A.BlankNode),(0,Yt.A)(this,"isBlank",1),(0,Yt.A)(this,"isVar",1)}get id(){return this.value}set id(e){this.value=e}compareTerm(e){return this.classOrder<e.classOrder?-1:this.classOrder>e.classOrder?1:this.id<e.id?-1:this.id>e.id?1:0}copy(e){var t=new tr;return e.copyTo(this,t),t}toCanonical(){return tr.NTAnonymousNodePrefix+this.value}toString(){return tr.NTAnonymousNodePrefix+this.id}}(0,Yt.A)(tr,"nextId",0),(0,Yt.A)(tr,"NTAnonymousNodePrefix","_:");var rr=a(5108),nr=a(2915);const ir={boolean:new rr.A("http://www.w3.org/2001/XMLSchema#boolean"),dateTime:new rr.A("http://www.w3.org/2001/XMLSchema#dateTime"),decimal:new rr.A("http://www.w3.org/2001/XMLSchema#decimal"),double:new rr.A("http://www.w3.org/2001/XMLSchema#double"),integer:new rr.A("http://www.w3.org/2001/XMLSchema#integer"),langString:new rr.A("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),string:new rr.A("http://www.w3.org/2001/XMLSchema#string")};class sr extends Zt.A{constructor(e,t,r){super(e),(0,Yt.A)(this,"termType",er.QW),(0,Yt.A)(this,"classOrder",Qt.A.Literal),(0,Yt.A)(this,"datatype",ir.string),(0,Yt.A)(this,"isVar",0),(0,Yt.A)(this,"language",""),t?(this.language=t,this.datatype=ir.langString):this.datatype=r?rr.A.fromValue(r):ir.string}copy(){return new sr(this.value,this.lang,this.datatype)}equals(e){return!!e&&(this.termType===e.termType&&this.value===e.value&&this.language===e.language&&(!this.datatype&&!e.datatype||this.datatype&&this.datatype.equals(e.datatype)))}get lang(){return this.language}set lang(e){this.language=e||""}toNT(){return sr.toNT(this)}static toNT(e){if("number"==typeof e.value)return""+e.value;if("string"!=typeof e.value)throw new Error("Value of RDF literal is not string or number: "+e.value);var t=e.value;return t='"'+(t=(t=(t=(t=t.replace(/\\/g,"\\\\")).replace(/\"/g,'\\"')).replace(/\n/g,"\\n")).replace(/\r/g,"\\r"))+'"',e.language?t+="@"+e.language:e.datatype.equals(ir.string)||(t+="^^"+e.datatype.toCanonical()),t}toString(){return""+this.value}static fromBoolean(e){return new sr(e?"1":"0",null,ir.boolean)}static fromDate(e){if(!(e instanceof Date))throw new TypeError("Invalid argument to Literal.fromDate()");let t=function(e){return(""+(100+e)).slice(1,3)},r=e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"Z";return new sr(r,null,ir.dateTime)}static fromNumber(e){if("number"!=typeof e)throw new TypeError("Invalid argument to Literal.fromNumber()");let t;const r=e.toString();return t=r.indexOf("e")<0&&Math.abs(e)<=Number.MAX_SAFE_INTEGER?Number.isInteger(e)?ir.integer:ir.decimal:ir.double,new sr(r,null,t)}static fromValue(e){if((0,nr.c$)(e))return e;switch(typeof e){case"object":if(e instanceof Date)return sr.fromDate(e);case"boolean":return sr.fromBoolean(e);case"number":return sr.fromNumber(e);case"string":return new sr(e)}throw new Error("Can't make literal from "+e+" of type "+typeof e)}}function or(e){return null==e||(0,nr.D0)(e)?e:Array.isArray(e)?new ar(e):sr.fromValue(e)}class ar extends Zt.A{constructor(e){super((tr.nextId++).toString()),(0,Yt.A)(this,"termType",er.r0),(0,Yt.A)(this,"classOrder",Qt.A.Collection),(0,Yt.A)(this,"closed",!1),(0,Yt.A)(this,"compareTerm",tr.prototype.compareTerm),(0,Yt.A)(this,"elements",[]),(0,Yt.A)(this,"isVar",0),e&&e.length>0&&e.forEach(e=>{this.elements.push(or(e))})}get id(){return this.value}set id(e){this.value=e}append(e){return this.elements.push(e)}close(){return this.closed=!0,this.closed}shift(){return this.elements.shift()}substitute(e){const t=this.elements.map(t=>t.substitute(e));return new ar(t)}toNT(){return ar.toNT(this)}static toNT(e){return tr.NTAnonymousNodePrefix+e.id}toString(){return"("+this.elements.join(" ")+")"}unshift(e){return this.elements.unshift(e)}}(0,Yt.A)(ar,"termType",er.r0);class ur extends Zt.A{constructor(){super(""),(0,Yt.A)(this,"termType",er.S)}toString(){return"()"}}const cr="chrome:theSession";new rr.A(cr);class hr extends Zt.A{constructor(){super(""),(0,Yt.A)(this,"value",""),(0,Yt.A)(this,"termType",er.ic),(0,Yt.A)(this,"uri",cr)}toCanonical(){return this.value}toString(){return"DefaultGraph"}}function lr(e){return!!e&&e.termType===er.ic}const dr=new hr;class fr{constructor(e,t,r,n){(0,Yt.A)(this,"subject",void 0),(0,Yt.A)(this,"predicate",void 0),(0,Yt.A)(this,"object",void 0),(0,Yt.A)(this,"graph",void 0),this.subject=Zt.A.fromValue(e),this.predicate=Zt.A.fromValue(t),this.object=Zt.A.fromValue(r),this.graph=null==n?dr:Zt.A.fromValue(n)}get why(){return this.graph}set why(e){this.graph=e}equals(e){return e.subject.equals(this.subject)&&e.predicate.equals(this.predicate)&&e.object.equals(this.object)&&e.graph.equals(this.graph)}substitute(e){return new fr(this.subject.substitute(e),this.predicate.substitute(e),this.object.substitute(e),lr(this.graph)?this.graph:this.graph.substitute(e))}toCanonical(){let e=[this.subject.toCanonical(),this.predicate.toCanonical(),this.object.toCanonical()];return this.graph&&this.graph.termType!==er.ic&&e.push(this.graph.toCanonical()),e.join(" ")+" ."}toNT(){return[this.subject.toNT(),this.predicate.toNT(),this.object.toNT()].join(" ")+" ."}toNQ(){return[this.subject.toNT(),this.predicate.toNT(),this.object.toNT(),lr(this.graph)?"":this.graph.toNT()].join(" ")+" ."}toString(){return this.toNT()}}var pr=a(2727);class gr extends Zt.A{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";super(e),(0,Yt.A)(this,"termType",er.P2),(0,Yt.A)(this,"base","varid:"),(0,Yt.A)(this,"classOrder",Qt.A.Variable),(0,Yt.A)(this,"isVar",1),(0,Yt.A)(this,"uri",void 0),this.base="varid:",this.uri=pr.join(e,this.base)}equals(e){return!!e&&(this.termType===e.termType&&this.value===e.value)}hashString(){return this.toString()}substitute(e){var t;return null!=(t=e[this.toNT()])?t:this}toString(){return gr.toString(this)}static toString(e){return e.uri.slice(0,e.base.length)===e.base?`?${e.uri.slice(e.base.length)}`:`?${e.uri}`}}let yr=function(e){return e.collections="COLLECTIONS",e.defaultGraphType="DEFAULT_GRAPH_TYPE",e.equalsMethod="EQUALS_METHOD",e.id="ID",e.identity="IDENTITY",e.reversibleId="REVERSIBLE_ID",e.variableType="VARIABLE_TYPE",e}({});const vr=new hr,mr={supports:{[yr.collections]:!1,[yr.defaultGraphType]:!1,[yr.equalsMethod]:!0,[yr.identity]:!1,[yr.id]:!0,[yr.reversibleId]:!1,[yr.variableType]:!0},blankNode:e=>new tr(e),defaultGraph:()=>vr,equals(e,t){return e===t||!e||!t||((0,nr.aF)(e)||(0,nr.aF)(t)?!(!(0,nr.aF)(e)||!(0,nr.aF)(t))&&(this.equals(e.subject,t.subject)&&this.equals(e.predicate,t.predicate)&&this.equals(e.object,t.object)&&this.equals(e.graph,t.graph)):!(!(0,nr.D0)(e)||!(0,nr.D0)(t))&&this.id(e)===this.id(t))},id(e){if(!e)return"undefined";if((0,nr.aF)(e))return this.quadToNQ(e);switch(e.termType){case er.ic:return"defaultGraph";case er.P2:return gr.toString(e);default:const t=this.termToNQ(e);if(t)return t;throw new Error(`Can't id term with type '${e.termType}'`)}},isQuad:e=>e instanceof fr,literal(e,t){if("string"!=typeof e&&!t)return sr.fromValue(e);const r="string"==typeof e?e:""+e;return"string"==typeof t?-1===t.indexOf(":")?new sr(r,t):new sr(r,null,this.namedNode(t)):new sr(r,null,t)},namedNode:e=>new rr.A(e),quad:(e,t,r,n)=>new fr(e,t,r,n||vr),triple(e,t,r,n){return this.quad(e,t,r,n)},quadToNQ(e){return`${this.termToNQ(e.subject)} ${this.termToNQ(e.predicate)} ${this.termToNQ(e.object)} ${this.termToNQ(e.graph)} .`},termToNQ(e){switch(e.termType){case er.$Q:return"_:"+e.value;case er.ic:return"";case er.S:return"<http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>";case er.QW:return sr.toNT(e);case er.bD:case er.Kk:return"<"+e.value+">";case er.r0:return"("+e.elements.map(e=>this.termToNQ(e)).join(" ")+")";default:throw new Error(`Can't serialize nonstandard term type (was '${e.termType}')`)}},toNQ(e){return this.isQuad(e)?this.quadToNQ(e):this.termToNQ(e)},variable:e=>new gr(e)},wr=mr;var br=a(4940);function _r(e,t){const r=t||{namedNode:e=>new rr.A(e)};return function(t){return r.namedNode(e+(t||""))}}var Sr=a(4011);function Er(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:wr;return{boolean:e.namedNode("http://www.w3.org/2001/XMLSchema#boolean"),dateTime:e.namedNode("http://www.w3.org/2001/XMLSchema#dateTime"),decimal:e.namedNode("http://www.w3.org/2001/XMLSchema#decimal"),double:e.namedNode("http://www.w3.org/2001/XMLSchema#double"),integer:e.namedNode("http://www.w3.org/2001/XMLSchema#integer"),langString:e.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),string:e.namedNode("http://www.w3.org/2001/XMLSchema#string")}}Er(wr);var xr=a(5386),Ar=a.n(xr),Fr=a(5306);function Tr(e){return new kr(e)}class kr{constructor(e){(0,Yt.A)(this,"_notQNameChars","\t\r\n !\"#$%&'()*.,+/;<=>?@[\\]^`{|}~"),(0,Yt.A)(this,"_notNameChars",this._notQNameChars+":"),(0,Yt.A)(this,"validPrefix",new RegExp(/^[a-zA-Z][a-zA-Z0-9]*$/)),(0,Yt.A)(this,"forbidden1",new RegExp(/[\\"\b\f\r\v\t\n\u0080-\uffff]/gm)),(0,Yt.A)(this,"forbidden3",new RegExp(/[\\"\b\f\r\v\u0080-\uffff]/gm)),this.flags="",this.base=null,this.prefixes=[],this.namespaces=[];const t=Object.keys(Ar()());for(const e in t){const r=Ar()()[t[e]](""),n=t[e];this.prefixes[r]=n,this.namespaces[n]=r}this.suggestPrefix("rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#"),this.suggestPrefix("xml","reserved:reservedForFutureUse"),this.namespacesUsed=[],this.keywords=["a"],this.prefixchars="abcdefghijklmnopqustuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",this.incoming=null,this.formulas=[],this.store=e,this.rdfFactory=e.rdfFactory||wr,this.xsd=Er(this.rdfFactory)}setBase(e){return this.base=e,this}setFlags(e){return this.flags=e||"",this}toStr(e){var t=e.toNT();return"Graph"===e.termType&&(this.formulas[t]=e),t}fromStr(e){if("{"===e[0]){var t=this.formulas[e];return t||console.log("No formula object for "+e),t}return this.store.fromNT(e)}setNamespaces(e){for(var t in e)this.setPrefix(t,e[t]);return this}setPrefix(e,t){if("default"!==e.slice(0,7)&&"ns"!==e.slice(0,2)&&e&&t){for(let t in this.prefixes)this.prefixes[t]==e&&delete this.prefixes[t];this.prefixes[t]=e,this.namespaces[e]=t}}suggestPrefix(e,t){"default"!==e.slice(0,7)&&"ns"!==e.slice(0,2)&&e&&t&&(e in this.namespaces||t in this.prefixes||(this.prefixes[t]=e,this.namespaces[e]=t))}suggestNamespaces(e){for(var t in e)this.suggestPrefix(t,e[t]);return this}checkIntegrity(){var e,t;for(e in this.namespaces)if(this.prefixes[this.namespaces[e]]!==e)throw new Error("Serializer integity error 1: "+e+", "+this.namespaces[e]+", "+this.prefixes[this.namespaces[e]]+"!");for(t in this.prefixes)if(this.namespaces[this.prefixes[t]]!==t)throw new Error("Serializer integity error 2: "+t+", "+this.prefixs[t]+", "+this.namespaces[this.prefixes[t]]+"!")}makeUpPrefix(e){var t=e;var r=function(t){return!!this.validPrefix.test(t)&&("ns"!==t&&(!(t in this.namespaces)&&(this.prefixes[e]=t,this.namespaces[t]=e,t)))}.bind(this);"#/".indexOf(t[t.length-1])>=0&&(t=t.slice(0,-1));var n=t.lastIndexOf("/");n>=0&&(t=t.slice(n+1));for(var i=0;i<t.length&&this.prefixchars.indexOf(t[i]);)i++;if((t=t.slice(0,i)).length<6&&r(t))return t;if(r(t.slice(0,3)))return t.slice(0,3);if(r(t.slice(0,2)))return t.slice(0,2);if(r(t.slice(0,4)))return t.slice(0,4);if(r(t.slice(0,1)))return t.slice(0,1);if(r(t.slice(0,5)))return t.slice(0,5);this.validPrefix.test(t)||(t="n");for(var s=0;;s++)if(r(t.slice(0,3)+s))return t.slice(0,3)+s}rootSubjects(e){for(var t={},r={},n={},i=0;i<e.length;i++){var s=e[i],o=function(e){t.hasOwnProperty(e)||(t[e]=[]),t[e].push(s.subject)};[s.subject,s.predicate,s.object].map(function(e){"BlankNode"===e.termType?n[e.toNT()]=!0:"Collection"===e.termType&&e.elements.forEach(function(e){o(e)})}),o(e[i].object);var a=r[this.toStr(s.subject)];a||(a=[]),a.push(s),r[this.toStr(s.subject)]=a}var u=[];for(var c in r)if(r.hasOwnProperty(c)){var h=this.fromStr(c);"BlankNode"===h.termType&&t[h]&&1===t[h].length||u.push(h)}this.incoming=t;for(var l={},d=0;d<u.length;d++)l[u[d].toNT()]=!0;return{roots:u,subjects:r,rootsHash:l,incoming:t}}toN3(e){return this.statementsToN3(e.statements)}explicitURI(e){var t;return this.flags.indexOf("r")<0&&this.base?e=pr.refTo(this.base,e):this.flags.indexOf("u")>=0?e=function(e){for(var t,r="",n=0;n<e.length;n++)r+=(t=e.charCodeAt(n))>65535?"\\U"+("00000000"+t.toString(16)).slice(-8):t>126?"\\u"+("0000"+t.toString(16)).slice(-4):e[n];return r}(e):(t=decodeURI(e),e=encodeURI(t)),"<"+e+">"}statementsToNTriples(e){var t=e.slice();t.sort();for(var r="",n="http://www.w3.org/1999/02/22-rdf-syntax-ns#",i=this,s=this.store,o=this.rdfFactory,a=function(e){if("Collection"!==e.termType)return i.atomicTermToN3(e);for(var t=e.elements,u=s.sym(n+"nill"),c=t.length-1;c>=0;c--){var h=o.blankNode();r+=a(h)+" "+a(s.sym(n+"first"))+" "+a(t[c])+".\n",r+=a(h)+" "+a(s.sym(n+"rest"))+" "+a(u)+".\n",u=h}return i.atomicTermToN3(u)},u=0;u<t.length;u++){var c=t[u],h="";h+=a(c.subject)+" ",h+=a(c.predicate)+" ",h+=a(c.object)+" ",this.flags.indexOf("q")>=0&&(h+=a(c.why)+" "),r+=h+=".\n"}return r}statementsToN3(e){var t=this.store,r={"http://www.w3.org/1999/02/22-rdf-syntax-ns#type":"aaa:00"};e.sort(function(e,n){return Sr.heavyCompareSPO(e,n,t,r)}),this.base&&!this.defaultNamespace&&(this.defaultNamespace=this.base+"#");var n={};this.flags.indexOf("s")<0&&(n["http://www.w3.org/2002/07/owl#sameAs"]="="),this.flags.indexOf("t")<0&&(n["http://www.w3.org/1999/02/22-rdf-syntax-ns#type"]="a"),this.flags.indexOf("i")<0&&(n["http://www.w3.org/2000/10/swap/log#implies"]="=>");var i=function(e){for(var t="",r=0;r<e;r++)t+=" ";return t},s=function(e){for(var t="",r=0;r<e.length;r++){var n=e[r],i="string"==typeof n?n:s(n);if(0!==r){var o=t.slice(-1)||" ";","===i||";"===i||("."!==i||"0123456789.:".includes(o))&&(t+=" ")}t+=i}return t},o=function(e,t){var r="",n=1e5;void 0===t&&(t=-1);for(var a=0;a<e.length;a++){var u=e[a];if("string"!=typeof u){var c=o(u,t+1);if(c.length<10*(80-4*t)&&c.indexOf('"""')<0){var h=s(u);h.length<80-4*t&&(u=h,c="")}c&&(n=1e4),r+=c}if("string"==typeof u){if(1===u.length&&"\n"===r.slice(-1)&&",.;".indexOf(u)>=0){r=r.slice(0,-1),"."==u&&"0123456789.:".includes(r.charAt(r.length-1))&&(r+=" ",n+=1),r+=u+"\n",n+=1;continue}if(n<4*t+4||n+u.length+1<80&&";.".indexOf(r[r.length-2])<0)r=r.slice(0,-1)+" "+u+"\n",n+=u.length+1;else{let e=i(4*t)+u;r+=e+"\n",n=e.length,t<0&&(r+="\n",n=1e5)}}}return r};var a=function(e){for(var t=this.rootSubjects(e),r=t.roots,n=[],i=0;i<r.length;i++){var s=r[i];n.push(u(s,t))}return n}.bind(this);function u(e,t){return"BlankNode"!==e.termType||t.incoming[e]?[l(e,t)].concat([c(e,t)]).concat(["."]):h(e,t,!0).concat(["."])}var c=function(e,t){var r=[],i=null,s=t.subjects[this.toStr(e)]||[];if(void 0===s)throw new Error("Cant find statements for "+e);for(var o=[],a=0;a<s.length;a++){var u=s[a];u.predicate.uri===i?o.push(","):(i&&(r=r.concat([o]).concat([";"]),o=[]),r.push(n[u.predicate.uri]?n[u.predicate.uri]:l(u.predicate,t))),i=u.predicate.uri,o.push(h(u.object,t))}return r=r.concat([o])}.bind(this);var h=function(e,t,r){return"BlankNode"!==e.termType||!r&&void 0!==t.rootsHash[e.toNT()]?l(e,t):t.subjects[this.toStr(e)]?["[",c(e,t),"]"]:"[]"}.bind(this);kr.prototype.termToN3=l;var l=function(e,t){var r,n;switch(e.termType){case"Graph":return(n=(n=["{"]).concat(a(e.statements))).concat(["}"]);case"Collection":for(n=["("],r=0;r<e.elements.length;r++)n.push([h(e.elements[r],t)]);return n.push(")"),n;default:return this.atomicTermToN3(e)}}.bind(this);var d=function(){var e="";for(var t in this.flags.indexOf("d")<0&&this.defaultNamespace&&(e+="@prefix : "+this.explicitURI(this.defaultNamespace)+".\n"),this.prefixes)this.prefixes.hasOwnProperty(t)&&this.namespacesUsed[t]&&(e+="@prefix "+this.prefixes[t]+": "+this.explicitURI(t)+".\n");return e+"\n"}.bind(this),f=a(e);return d()+o(f)}atomicTermToN3(e,t){switch(e.termType){case"BlankNode":case"Variable":return e.toNT();case"Literal":var r=e.value;if("string"!=typeof r)throw new TypeError("Value of RDF literal node must be a string");if(e.datatype&&this.flags.indexOf("x")<0)switch(e.datatype.uri){case"http://www.w3.org/2001/XMLSchema#integer":return r;case"http://www.w3.org/2001/XMLSchema#decimal":return r.indexOf(".")<0&&(r+=".0"),r;case"http://www.w3.org/2001/XMLSchema#double":{const e=r.toLowerCase().indexOf("e")>0;return r.indexOf(".")<0&&!e&&(r+=".0"),e||(r+="e0"),r}case"http://www.w3.org/2001/XMLSchema#boolean":return"1"===e.value?"true":"false"}var n=this.stringToN3(e.value,this.flags);return e.language?n+="@"+e.language:e.datatype.equals(this.xsd.string)||(n+="^^"+this.atomicTermToN3(e.datatype,t)),n;case"NamedNode":return this.symbolToN3(e);case"DefaultGraph":return"";default:throw new Error("Internal: atomicTermToN3 cannot handle "+e+" of termType: "+e.termType)}}stringToN3(e,t){t||(t="e");var r,n,i,s,o,a="";for(e.length>20&&'"'!==e.slice(-1)&&t.indexOf("n")<0&&(e.indexOf("\n")>0||e.indexOf('"')>0)?(s='"""',o=this.forbidden3):(s='"',o=this.forbidden1),r=0;r<e.length;){if(o.lastIndex=0,null==o.exec(e.slice(r)))break;n=r+o.lastIndex-1,a+=e.slice(r,n);var u=e[n];'"'===u&&'"""'===s&&'"""'!==e.slice(n,n+3)?a+=u:(i='\b\f\r\t\v\n\\"'.indexOf(u))>=0?a+="\\"+'bfrtvn\\"'[i]:t.indexOf("e")>=0?a+="\\u"+("000"+u.charCodeAt(0).toString(16).toLowerCase()).slice(-4):a+=u,r=n+1}return s+a+e.slice(r)+s}symbolToN3(e){var t=e.uri,r=t.indexOf("#");if(r<0&&this.flags.indexOf("/")<0&&(r=t.lastIndexOf("/")),r>=0&&this.flags.indexOf("p")<0&&(0===t.indexOf("http")||0===t.indexOf("ws")||0===t.indexOf("file"))){for(var n=!0,i=r+1;i<t.length;i++)if(this._notNameChars.indexOf(t[i])>=0){n=!1;break}if(n){var s=t.slice(r+1),o=t.slice(0,r+1);if(this.defaultNamespace&&this.defaultNamespace===o&&this.flags.indexOf("d")<0)return this.flags.indexOf("k")>=0&&this.keyords.indexOf(s)<0?s:":"+s;var a=this.prefixes[o];if(a||(a=this.makeUpPrefix(o)),a)return this.namespacesUsed[o]=!0,a+":"+s}}return this.explicitURI(t)}writeStore(e){var t=this.store,r=t.fetcher,n=r&&r.appNode,i=this.store.index[3];for(var s in i){var o=t.fromNT(s);n&&o.equals(n)||e("\n"+this.atomicTermToN3(o)+" "+this.atomicTermToN3(t.sym("http://www.w3.org/2000/10/swap/log#semantics"))+" { "+this.statementsToN3(t.statementsMatching(void 0,void 0,void 0,o))+" }.\n")}t.statementsMatching(void 0,t.sym("http://www.w3.org/2007/ont/link#requestedURI")).map(function(r){e("\n<"+r.object.value+"> log:metadata {\n");var n=t.statementsMatching(void 0,void 0,void 0,r.subject);e(this.statementsToN3(this.statementsToN3(n))),e("}.\n")});var a=[];n&&a.push(n);var u=[];a.map(function(e){u=u.concat(t.statementsMatching(void 0,void 0,void 0,e))}),e(this.statementsToN3(u))}statementsToXML(e){var t=[];t["http://www.w3.org/1999/02/22-rdf-syntax-ns#"]=!0;var r="http://www.w3.org/1999/02/22-rdf-syntax-ns#_",n=function(e){for(var t="",r=0;r<e;r++)t+=" ";return t},i=function(e){for(var t="",r=0;r<e.length;r++){var n=e[r];t+="string"==typeof n?n:i(n)}return t},s=function(e,t){var r,o="",a=1e5;t||(t=0);for(var u=0;u<e.length;u++){var c=e[u];if("string"!=typeof c){var h=s(c,t+1);h.length<10*(80-4*t)&&h.indexOf('"""')<0&&(r=i(c)).length<80-4*t&&(c=" "+r,h=""),h&&(a=1e4),o+=h}"string"==typeof c&&(a<4*t+4?(o=o.slice(0,-1)+" "+c+"\n",a+=c.length+1):(o+=(r=n(4*t)+c)+"\n",a=r.length))}return o};var o=function(e){this.suggestPrefix("rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#");for(var t=this.rootSubjects(e),r=t.roots,n=[],i=0;i<r.length;i++){var s=r[i];n.push(c(s,t))}return n}.bind(this);function a(e){return void 0===e?"@@@undefined@@@@":e.replace(/[&<"]/g,function(e){switch(e[0]){case"&":return"&amp;";case"<":return"&lt;";case'"':return"&quot;"}})}var u=function(e){return a(this.base?pr.refTo(this.base,e.uri):e.uri)}.bind(this);var c=function(e,t){var n,i,s,o,f=[],p=t.subjects[this.toStr(e)];if(void 0===p)return l(e,t);p.sort(function(e,t){var n=e.predicate.uri,i=t.predicate.uri;if(n.substring(0,44)===r||i.substring(0,44)===r)return n.localeCompare(i);var s=n.substring(44),o=i.substring(44),a=parseInt(s,10),u=parseInt(o,10);return isNaN(a)||isNaN(u)||a!==s||u!==o?n.localeCompare(i):a-u});for(var g=0;g<p.length;g++)if("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"!==(s=p[g]).predicate.uri||n||"NamedNode"!==s.object.termType){if((o=s.predicate).uri.substr(0,44)===r){var y=o.uri.substr(44);y===parseInt(y,10).toString()&&(o=this.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#li"))}switch(i=d(o),s.object.termType){case"BlankNode":f=1===t.incoming[s.object].length?f.concat(["<"+i+' rdf:parseType="Resource">',c(s.object,t),"</"+i+">"]):f.concat(["<"+i+' rdf:nodeID="'+s.object.toNT().slice(2)+'"/>']);break;case"NamedNode":f=f.concat(["<"+i+' rdf:resource="'+u(s.object)+'"/>']);break;case"Literal":f=f.concat(["<"+i+(s.object.datatype.equals(this.xsd.string)?"":' rdf:datatype="'+a(s.object.datatype.uri)+'"')+(s.object.language?' xml:lang="'+s.object.language+'"':"")+">"+a(s.object.value)+"</"+i+">"]);break;case"Collection":f=f.concat(["<"+i+' rdf:parseType="Collection">',h(s.object,t),"</"+i+">"]);break;default:throw new Error("Can't serialize object of type "+s.object.termType+" into XML")}}else n=s.object;var v=n?d(n):"rdf:Description",m="";return"BlankNode"===e.termType?t.incoming[e]&&1===t.incoming[e].length||(m=' rdf:nodeID="'+e.toNT().slice(2)+'"'):m=' rdf:about="'+u(e)+'"',["<"+v+m+">"].concat([f]).concat(["</"+v+">"])}.bind(this);function h(e,t){for(var r=[],n=0;n<e.elements.length;n++)r.push(c(e.elements[n],t));return r}var l=function(e,t){var r=[],n=t.subjects[this.toStr(e)];if(!n)return r;n.sort();for(var i=0;i<n.length;i++){var s=n[i];switch(s.object.termType){case"BlankNode":r=t.rootsHash[s.object.toNT()]?r.concat(["<"+d(s.predicate)+' rdf:nodeID="'+s.object.toNT().slice(2)+'">',"</"+d(s.predicate)+">"]):r.concat(["<"+d(s.predicate)+' rdf:parseType="Resource">',l(s.object,t),"</"+d(s.predicate)+">"]);break;case"NamedNode":r=r.concat(["<"+d(s.predicate)+' rdf:resource="'+u(s.object)+'"/>']);break;case"Literal":r=r.concat(["<"+d(s.predicate)+(s.object.datatype.equals(this.xsd.string)?"":' rdf:datatype="'+a(s.object.datatype.value)+'"')+(s.object.language?' xml:lang="'+s.object.language+'"':"")+">"+a(s.object.value)+"</"+d(s.predicate)+">"]);break;case"Collection":r=r.concat(["<"+d(s.predicate)+' rdf:parseType="Collection">',h(s.object,t),"</"+d(s.predicate)+">"]);break;default:throw new Error("Can't serialize object of type "+s.object.termType+" into XML")}}return r}.bind(this);var d=function(e){var r=e.uri,n=r.indexOf("#");if(n<0&&this.flags.indexOf("/")<0&&(n=r.lastIndexOf("/")),n<0)throw new Error("Cannot make qname out of <"+r+">");for(var i=n+1;i<r.length;i++)if(this._notNameChars.indexOf(r[i])>=0)throw new Error('Invalid character "'+r[i]+'" cannot be in XML qname for URI: '+r);var s=r.slice(n+1),o=r.slice(0,n+1);if(this.defaultNamespace&&this.defaultNamespace===o&&this.flags.indexOf("d")<0)return s;var a=this.prefixes[o];return a||(a=this.makeUpPrefix(o)),t[o]=!0,a+":"+s}.bind(this),f=o(e),p="<rdf:RDF";for(var g in this.defaultNamespace&&(p+=' xmlns="'+a(this.defaultNamespace)+'"'),t)if(t.hasOwnProperty(g)){var y=this.base&&this.flags.includes("z")?pr.refTo(this.base,g):g;p+="\n xmlns:"+this.prefixes[g]+'="'+a(y)+'"'}return s([p+=">",f,"</rdf:RDF>"],-1)}statementsToJsonld(e){const t=this.statementsToN3(e),r=Fr.parse(t);return JSON.stringify(r,null,2)}}function Ir(e,t,r,n,i,s){r=r||e?.value;const o=s||{};n=n||er.sT;try{var a=Tr(t);o.flags&&a.setFlags(o.flags);var u=t.statementsMatching(void 0,void 0,void 0,e);switch("namespaces"in t&&a.suggestNamespaces(t.namespaces),o.namespaces&&a.setNamespaces(o.namespaces),a.setBase(r),n){case er.JG:return c(null,a.statementsToXML(u));case er.ny:case er.MG:return c(null,a.statementsToN3(u));case er.sT:case er.hu:return a.setFlags("si"),c(null,a.statementsToN3(u));case er.bM:return a.setFlags("deinprstux"),c(null,a.statementsToNTriples(u));case er.i2:return a.setFlags("si dr"),c(null,a.statementsToJsonld(u));case er._0:case er.BR:return a.setFlags("deinprstux q"),c(null,a.statementsToNTriples(u));default:throw new Error("Serialize: Content-type "+n+" not supported for data write.")}}catch(e){if(i)return i(e,void 0);throw e}function c(e,t){return i?void i(e,t):t}}const Cr=["blankNode","defaultGraph","literal","namedNode","quad","variable","supports"],Rr={first:"http://www.w3.org/1999/02/22-rdf-syntax-ns#first",rest:"http://www.w3.org/1999/02/22-rdf-syntax-ns#rest",nil:"http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"};function Pr(e,t,r){const n=[];return r.reduce((t,r,i,s)=>{let o;return n.push(e.quad(t,e.namedNode(Rr.first),s[i])),i<s.length-1?(o=e.blankNode(),n.push(e.quad(t,e.namedNode(Rr.rest),o))):n.push(e.quad(t,e.namedNode(Rr.rest),e.namedNode(Rr.nil))),o},t),n}function Nr(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;var n=e.length;for(r<0&&(r=n+r);r<n;r++)if(e[r]===t)return r;return-1}class Ur extends Zt.A{constructor(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};super(""),e=this,this.statements=t,this.constraints=r,this.initBindings=n,this.optional=i,(0,Yt.A)(this,"termType",er.bD),(0,Yt.A)(this,"classOrder",Qt.A.Graph),(0,Yt.A)(this,"fetcher",void 0),(0,Yt.A)(this,"isVar",0),(0,Yt.A)(this,"ns",_r),(0,Yt.A)(this,"rdfFactory",void 0),this.rdfFactory=s&&s.rdfFactory||wr;for(const t of Cr)this[t]=function(){return e.rdfFactory[t](...arguments)}}add(e,t,r,n){return 1===arguments.length&&e.forEach(e=>this.add(e.subject,e.predicate,e.object,e.graph)),this.statements.push(this.rdfFactory.quad(e,t,r,n))}addStatement(e){return this.add(e)}bnode(e){return this.rdfFactory.blankNode(e)}addAll(e){e.forEach(e=>{this.add(e.subject,e.predicate,e.object,e.graph)})}any(e,t,r,n){const i=this.anyStatementMatching(e,t,r,n);return null==i?null:null==e?i.subject:null==t?i.predicate:null==r?i.object:null}anyValue(e,t,r,n){const i=this.any(e,t,r,n);return i?i.value:void 0}anyJS(e,t,r,n){const i=this.any(e,t,r,n);return i?Zt.A.toJS(i):void 0}anyStatementMatching(e,t,r,n){let i=this.statementsMatching(e,t,r,n,!0);if(i&&0!==i.length)return i[0]}id(e){return this.rdfFactory.id(e)}statementsMatching(e,t,r,n,i){const s=this.statements.filter(i=>(!e||e.equals(i.subject))&&(!t||t.equals(i.predicate))&&(!r||r.equals(i.object))&&(!n||n.equals(i.graph)));return i?0===s.length?[]:[s[0]]:s}bottomTypeURIs(e){let t,r,n,i,s,o,a,u;t=[];for(let c in e)if(e.hasOwnProperty(c)){for(u=e[c],a=this.each(void 0,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),this.rdfFactory.namedNode(c)),r=!0,i=0,s=a.length;i<s;i++)if(n=a[i],o=n.uri,o in e){r=!1;break}r&&(t[c]=u)}return t}collection(){return new ar}each(e,t,r,n){const i=[];let s=this.statementsMatching(e,t,r,n,!1);if(null==e)for(let e=0,t=s.length;e<t;e++)i.push(s[e].subject);else if(null==t)for(let e=0,t=s.length;e<t;e++)i.push(s[e].predicate);else if(null==r)for(let e=0,t=s.length;e<t;e++)i.push(s[e].object);else if(null==n)for(let e=0,t=s.length;e<t;e++)i.push(new rr.A(s[e].graph.value));return i}equals(e){return!!e&&this.hashString()===e.hashString()}findMembersNT(e){let t,r,n,i,s,o,a,u,c,h,l,d,f,p;d={},d[e.toNT()]=!0,i={},o=this.transitiveClosure(d,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),!0);for(let e in o)if(o.hasOwnProperty(e)){a=this.statementsMatching(void 0,this.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),this.fromNT(e));for(let e=0,t=a.length;e<t;e++)f=a[e],i[f.subject.toNT()]=f;u=this.each(void 0,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#domain"),this.fromNT(e));for(let e=0,r=u.length;e<r;e++)for(s=u[e],c=this.statementsMatching(void 0,s),n=0,t=c.length;n<t;n++)f=c[n],i[f.subject.toNT()]=f;h=this.each(void 0,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#range"),this.fromNT(e));for(let e=0,t=h.length;e<t;e++)for(s=h[e],l=this.statementsMatching(void 0,s),p=0,r=l.length;p<r;p++)f=l[p],i[f.object.toNT()]=f}return i}findMemberURIs(e){return this.NTtoURI(this.findMembersNT(e))}findSubClassesNT(e){let t={};return t[e.toNT()]=!0,this.transitiveClosure(t,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),!0)}findSuperClassesNT(e){let t={};return t[e.toNT()]=!0,this.transitiveClosure(t,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),!1)}findTypesNT(e){let t,r,n,i,s,o,a,u,c;n="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",c=[],i=this.statementsMatching(e,void 0,void 0);for(let e=0,t=i.length;e<t;e++)if(u=i[e],"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"===u.predicate.uri)c[u.object.toNT()]=u;else{s=this.each(u.predicate,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#domain"));for(let e=0,t=s.length;e<t;e++)r=s[e],c[r.toNT()]=u}o=this.statementsMatching(void 0,void 0,e);for(let e=0,r=o.length;e<r;e++){u=o[e],a=this.each(u.predicate,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#range"));for(let e=0,r=a.length;e<r;e++)t=a[e],c[t.toNT()]=u}return this.transitiveClosure(c,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),!1)}findTypeURIs(e){return this.NTtoURI(this.findTypesNT(e))}connectedStatements(e,t,r){r=r||[];let n=[e],i={},s={},o=[],a=this,u=function(e){let u=function(e){"BlankNode"!==e.termType||i[e.value]||(i[e.value]=!0,n.push(e))},c=a.statementsMatching(null,null,e,t).concat(a.statementsMatching(e,null,null,t));c=c.filter(function(e){if(r[e.predicate.value])return!1;let t=e.toNT();return!s[t]&&(s[t]=!0,!0)}),c.forEach(function(e){u(e.subject),u(e.object)}),o=o.concat(c)};for(;n.length;)u(n.shift());return o}formula(e){return new Ur}fromNT(e){let t,r,n;switch(e[0]){case"<":return this.sym(e.slice(1,-1));case'"':if(n=void 0,t=void 0,r=e.lastIndexOf('"'),r<e.length-1)if("@"===e[r+1])n=e.slice(r+2);else{if("^^"!==e.slice(r+1,r+3))throw new Error("Can't convert string from NT: "+e);t=this.fromNT(e.slice(r+3))}return e=(e=(e=(e=e.slice(1,r)).replace(/\\"/g,'"')).replace(/\\n/g,"\n")).replace(/\\\\/g,"\\"),this.rdfFactory.literal(e,n||t);case"_":return this.rdfFactory.blankNode(e.slice(2));case"?":return new gr(e.slice(1))}throw new Error("Can't convert from NT: "+e)}holds(e,t,r,n){let i;if(1===arguments.length){if(!e)return!0;if(e instanceof Array){for(i=0;i<e.length;i++)if(!this.holds(e[i]))return!1;return!0}if((0,nr.SH)(e))return this.holds(e.subject,e.predicate,e.object,e.graph);if(e.statements)return this.holds(e.statements)}return null!=this.anyStatementMatching(e,t,r,n)}holdsStatement(e){return this.holds(e.subject,e.predicate,e.object,e.graph)}list(e,t){if(t.rdfFactory.supports.COLLECTIONS){const r=t.rdfFactory.collection();return e.forEach(function(e){r.append(e)}),r}{const r=t.rdfFactory.blankNode(),n=Pr(t.rdfFactory,r,e);return t.addAll(n),r}}NTtoURI(e){let t,r,n={};for(t in e)e.hasOwnProperty(t)&&(r=e[t],"<"===t[0]&&(n[t.slice(1,-1)]=r));return n}serialize(e,t,r,n){return Ir(r,this,e,t,void 0,n)}substitute(e){let t=this.statements.map(function(t){return t.substitute(e)});const r=new Ur;return r.addAll(t),r}sym(e,t){if(t)throw new Error("This feature (kb.sym with 2 args) is removed. Do not assume prefix mappings.");return this.rdfFactory.namedNode(e)}the(e,t,r,n){let i=this.any(e,t,r,n);return null==i&&br.A.error("No value found for the() {"+e+" "+t+" "+r+"}."),i}transitiveClosure(e,t,r){let n,i,s,o,a,u,c={};Object.assign(c,e);let h={};for(;;){if(u=function(){for(let e in c)if(c.hasOwnProperty(e))return e}(),null==u)return h;for(a=r?this.each(void 0,t,this.fromNT(u)):this.each(this.fromNT(u),t),i=0,s=a.length;i<s;i++)n=a[i],o=n.toNT(),o in h||o in c||(c[o]=c[u]);h[u]=c[u],delete c[u]}}topTypeURIs(e){let t,r,n,i,s,o,a,u;for(n in a=[],e)if(e.hasOwnProperty(n)){for(u=e[n],s=0,o=this.each(this.rdfFactory.namedNode(n),this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf")),t=0,i=o.length;t<i;t++)if(r=o[t],"http://www.w3.org/2000/01/rdf-schema#Resource"!==r.uri){s++;break}s||(a[n]=u)}return a["http://www.w3.org/2000/01/rdf-schema#Resource"]&&delete a["http://www.w3.org/2000/01/rdf-schema#Resource"],a["http://www.w3.org/2002/07/owl#Thing"]&&delete a["http://www.w3.org/2002/07/owl#Thing"],a}toString(){return"{"+this.statements.join("\n")+"}"}variable(e){return new gr(e)}whether(e,t,r,n){return this.statementsMatching(e,t,r,n,!1).length}}Zt.A.fromValue=or;const Or=Zt.A,Lr={xsd:_r("http://www.w3.org/2001/XMLSchema#")};Zt.A.toJS=function(e){return(0,nr.P3)(e)?e.elements.map(Zt.A.toJS):(0,nr.c$)(e)?e.datatype.equals(Lr.xsd("boolean"))?"1"===e.value||"true"===e.value:e.datatype.equals(Lr.xsd("dateTime"))||e.datatype.equals(Lr.xsd("date"))?new Date(e.value):e.datatype.equals(Lr.xsd("integer"))||e.datatype.equals(Lr.xsd("float"))||e.datatype.equals(Lr.xsd("decimal"))?Number(e.value):e.value:e};class Dr{constructor(e,t){this.pat=new Kr,this.vars=[],this.name=e,this.id=t}}function jr(e,t,r,n){function i(e){var t,r="";for(t in e)e.hasOwnProperty(t)&&(r+=" "+t+" -> "+e[t]);return r}function s(e){var t,r="Bindings: ",n=e.length;for(t=0;t<n;t++)r+=i(e[t][0])+";\n\t";return r}function o(e,t,r,n){var i;if(e.length!==t.length)return[];if(!e.length)return[[[],null]];var s=function(e,t,r,n){var i=r[e];if(void 0===i){if(e.isVar){var s=[];return s[e]=t,[[s,null]]}i=e}if(!i.complexType)return n.redirections[i]&&(i=n.redirections[i]),n.redirections[t]&&(t=n.redirections[t]),i.equals(t)||i.uri&&i.uri===cr?[[[],null]]:[];if(e instanceof Array)return t instanceof Array?o(e,t,r):[];throw new Error("query.js: oops - code not written yet")}(e[0],t[0],r,n);if(0===s.length)return s;var a,u,c,h,l,d,f,p=[],g=s.length;for(a=0;a<g;a++){for(l in f=[],u=s[a][0])u.hasOwnProperty(l)&&(f[l]=u[l]);for(l in r)r.hasOwnProperty(l)&&(f[l]=r[l]);for(h=(i=o(e.slice(1),t.slice(1),f,n)).length,c=0;c<h;c++){for(l in d=i[c][0],u)u.hasOwnProperty(l)&&(d[l]=u[l]);p.push([d,null])}}return p}function a(e,t){var r=t[e];return void 0===r?e:r}function u(e,t){var r,n={};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);for(r in t)t.hasOwnProperty(r)&&(n[r]=t[r]);return n}function c(e,t){return this.trunkBindings=t,this.originalCallback=e,this.branches=[],this}function h(e,t){return this.count=0,this.success=!1,this.done=!1,this.callback=e,this.onDone=t,this}c.prototype.checkAllDone=function(){var e;for(e=0;e<this.branches.length;e++)if(!this.branches[e].done)return;br.A.debug("OPTIONAL BIDNINGS ALL DONE:"),this.doCallBacks(this.branches.length-1,this.trunkBindings)},c.prototype.doCallBacks=function(e,t){var r;if(e<0)return this.originalCallback(t);for(r=0;r<this.branches[e].results.length;r++)this.doCallBacks(e-1,u(t,this.branches[e].results[r]))},h.prototype.reportMatch=function(e){this.callback(e),this.success=!0},h.prototype.reportDone=function(){this.done=!0,br.A.info("Mandatory query branch finished.***"),void 0!==this.onDone&&this.onDone()};var l=function(e){return this.count=0,this.done=!1,this.results=[],this.junction=e,e.branches.push(this),this};function d(e,t,r){var n,i,s,o;for(t.nvars=0,t.index=null,n=[t.subject,t.predicate,t.object,t.why],o=[e.subjectIndex,e.predicateIndex,e.objectIndex,e.whyIndex],s=0;s<4;s++){let u=n[s];if(u.uri&&u.uri===cr);else if(u.isVar&&void 0===r[u])t.nvars++;else{if(u=a(n[s],r),e.redirections[e.id(u)]&&(u=e.redirections[e.id(u)]),!(i=o[s][e.id(u)]))return t.index=[],!1;(null===t.index||t.index.length>i.length)&&(t.index=i)}}return null===t.index&&(t.index=e.statements),!0}function f(e,t){return e.nvars!==t.nvars?e.nvars-t.nvars:e.index.length-t.index.length}l.prototype.reportMatch=function(e){this.results.push(e)},l.prototype.reportDone=function(){br.A.debug("Optional branch finished - results.length = "+this.results.length),0===this.results.length&&(this.results.push({}),br.A.debug("Optional branch FAILED - that's OK.")),this.done=!0,this.junction.checkAllDone()};var p=function(e,r,n,s,o,a,u){br.A.debug("Match begins, Branch count now: "+u.count+" for "+u.pattern_debug);var h,d,f=r.statements;if(0===f.length){if(br.A.debug("FOUND MATCH WITH BINDINGS:"+i(n)),0===r.optional.length)u.reportMatch(n);else{br.A.debug("OPTIONAL: "+r.optional);var g,v=new c(t,n),m=[];for(g=0;g<r.optional.length;g++)m[g]=new l(v),m[g].pattern_debug=r.optional[g];for(g=0;g<r.optional.length;g++)m[g].count=m[g].count+1,p(e,r.optional[g],n,"",o,t,m[g])}return u.count--,void br.A.debug("Match ends -- success , Branch count now: "+u.count+" for "+u.pattern_debug)}var w=f.length;if(o){0;var b=function(t,i){var c=t.uri.split("#")[0];o.nowOrWhenFetched(c,void 0,function(i,c,h){i||console.log("Error following link to <"+t.uri+"> in query: "+c),p(e,r,n,s,o,a,u)})};for(d=0;d<w;d++){if(h=f[d],void 0!==n[h.subject]&&n[h.subject].uri&&o&&"unrequested"===o.getState((0,pr.docpart)(n[h.subject].uri)))return void b(n[h.subject]);if(void 0!==n[h.object]&&n[h.object].uri&&o&&"unrequested"===o.getState((0,pr.docpart)(n[h.object].uri)))return void b(n[h.object])}}y(e,r,n,s,o,a,u)},g=function(e,t){var r,n,i=!0;for(r in e)e.hasOwnProperty(r)&&t[r]&&(n=t[r].test)&&!n(e[r])&&(i=!1);return i},y=function(e,t,r,n,a,u,c){var h,l,y,v,m,w,b,_=t.statements,S=_.length;for(h=0;h<S;h++)d(e,b=_[h],r);_.sort(f),b=_[0];var E,x=e.formula();x.optional=t.optional,x.constraints=t.constraints,x.statements=_.slice(1),br.A.debug(n+"match2 searching "+b.index.length+" for "+b+"; bindings so far="+i(r));var A,F,T=b.index.length,k=0;for(E=0;E<T;E++)for(F=b.index[E],A=o([b.subject,b.predicate,b.object,b.why],[F.subject,F.predicate,F.object,F.why],r,e),br.A.info(n+" From first: "+A.length+": "+s(A)),y=A.length,l=0;l<y;l++)if(m=[],w=A[l][0],g(w,t.constraints)){for(v in w)w.hasOwnProperty(v)&&(m[v]=w[v]);for(v in r)r.hasOwnProperty(v)&&(m[v]=r[v]);c.count++,k++,p(e,x,m,n+" ",a,u,c)}else br.A.debug("Branch count CS: "+c.count);c.count--,0===k&&br.A.debug("Match2 fails completely on "+b),br.A.debug("Match2 ends, Branch count: "+c.count+" for "+c.pattern_debug),0===c.count&&(br.A.debug("Branch finished."),c.reportDone())},v=this;br.A.debug("Query on "+this.statements.length);var m=new h(t,n);m.count++,e.sync?p(v,e.pat,e.pat.initBindings,"",r,t,m):setTimeout(function(){p(v,e.pat,e.pat.initBindings,"",r,t,m)},0)}const Mr="http://www.w3.org/2002/07/owl#";function Br(e,t,r,n){var i=e.any(t,r,void 0);return!!i&&(e.equate(i,n),!0)}function Hr(e,t,r,n){var i=e.any(void 0,r,n);return!!i&&(e.equate(i,t),!0)}function qr(e,t,r,n,i){e.typeCallback&&e.typeCallback(e,n,i);var s=e.classActions[e.id(n)],o=!1;if(s)for(var a=0;a<s.length;a++)o=o||s[a](e,t,r,n,i);return o}class Kr extends Ur{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(void 0,void 0,void 0,void 0,t),(0,Yt.A)(this,"updater",void 0),(0,Yt.A)(this,"namespaces",void 0),(0,Yt.A)(this,"classActions",void 0),(0,Yt.A)(this,"propertyActions",void 0),(0,Yt.A)(this,"redirections",void 0),(0,Yt.A)(this,"aliases",void 0),(0,Yt.A)(this,"HTTPRedirects",void 0),(0,Yt.A)(this,"subjectIndex",void 0),(0,Yt.A)(this,"predicateIndex",void 0),(0,Yt.A)(this,"objectIndex",void 0),(0,Yt.A)(this,"whyIndex",void 0),(0,Yt.A)(this,"index",void 0),(0,Yt.A)(this,"features",void 0),(0,Yt.A)(this,"_universalVariables",void 0),(0,Yt.A)(this,"_existentialVariables",void 0),(0,Yt.A)(this,"rdfArrayRemove",void 0),(0,Yt.A)(this,"dataCallbacks",[]),(0,Yt.A)(this,"dataRemovalCallbacks",[]),this.propertyActions={},this.classActions={},this.redirections=[],this.aliases=[],this.HTTPRedirects=[],this.subjectIndex=[],this.predicateIndex=[],this.objectIndex=[],this.whyIndex=[],this.index=[this.subjectIndex,this.predicateIndex,this.objectIndex,this.whyIndex],this.namespaces={},this.features=e||[],this.rdfArrayRemove=t.rdfArrayRemove||Sr.RDFArrayRemove,t.dataCallback&&(this.dataCallbacks=[t.dataCallback]),t.dataRemovalCallback&&(this.dataRemovalCallbacks=[t.dataRemovalCallback]),this.initPropertyActions(this.features)}static get defaultGraphURI(){return cr}substitute(e){var t=this.statements.map(function(t){return t.substitute(e)}),r=new Kr;return r.add(t),r}addDataCallback(e){this.dataCallbacks.push(e)}addDataRemovalCallback(e){this.dataRemovalCallbacks.push(e)}applyPatch(e,t,r){var n,i=this,s=null;function o(o){if(e.delete){n=e.delete,s&&(n=n.substitute(s)),n=n.statements;var a=[],u=n.map(function(e){var r=i.statementsMatching(e.subject,e.predicate,e.object,t);return 0===r.length?(a.push(e),null):r[0]});if(a.length)return r("Could not find to delete: "+a.join("\n or "));u.map(function(e){i.remove(e)})}e.insert&&(n=e.insert,s&&(n=n.substitute(s)),(n=n.statements).map(function(e){e.graph=t,i.add(e.subject,e.predicate,e.object,e.graph)})),o()}if(e.where){var a=new Dr("patch");a.pat=e.where,a.pat.statements.map(function(e){e.graph=qi(t.value)}),a.sync=!0;var u=[];i.query(a,function(e){u.push(e)},i.fetcher,function(){return 0===u.length?r("No match found to be patched:"+e.where):u.length>1?r("Patch ambiguous. No patch done."):(s=u[0],void o(r))})}else o(r)}declareExistential(e){return this._existentialVariables||(this._existentialVariables=[]),this._existentialVariables.push(e),e}initPropertyActions(e){this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"))]=[qr],Nr(e,"sameAs")>=0&&(this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${Mr}sameAs`))]=[function(e,t,r,n,i){return e.equate(t,n),!0}]),Nr(e,"InverseFunctionalProperty")>=0&&(this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${Mr}InverseFunctionalProperty`))]=[function(e,t,r,n,i){return e.newPropertyAction(t,Hr)}]),Nr(e,"FunctionalProperty")>=0&&(this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${Mr}FunctionalProperty`))]=[function(e,t,r,n,i){return e.newPropertyAction(t,Br)}])}addStatement(e){return this.add(e.subject,e.predicate,e.object,e.graph),this.statements.length}add(e,t,r,n){var i,s,o;if(1===arguments.length){if(e instanceof Array)for(i=0;i<e.length;i++)this.add(e[i]);else(0,nr.aF)(e)?this.add(e.subject,e.predicate,e.object,e.graph):(0,nr.ok)(e)&&this.add(e.statements);return this}n||(n=this.fetcher?this.fetcher.appNode:this.rdfFactory.defaultGraph()),"string"==typeof e&&(e=this.rdfFactory.namedNode(e)),t=Or.fromValue(t);const a=Or.fromValue(r);if(n=Or.fromValue(n),!(0,nr.CZ)(e))throw new Error("Subject is not a subject type");if(!(0,nr.fY)(t))throw new Error(`Predicate ${t} is not a predicate type`);if(!(0,nr.DJ)(a))throw new Error(`Object ${a} is not an object type`);if(!(0,nr.RN)(n))throw new Error("Why is not a graph type");this.predicateCallback&&this.predicateCallback(this,t,n);var u=this.id(this.canon(t)),c=!1;if(s=this.propertyActions[u])for(i=0;i<s.length;i++)c=c||s[i](this,e,t,a,n);if(this.holds(e,t,a,n))return null;var h=[this.id(this.canon(e)),u,this.id(this.canon(a)),this.id(this.canon(n))];for(o=this.rdfFactory.quad(e,t,a,n),i=0;i<4;i++){var l=this.index[i],d=h[i];l[d]||(l[d]=[]),l[d].push(o)}this.statements.push(o);for(const e of this.dataCallbacks)e(o);return o}canon(e){if(!e)return e;const t=this.redirections[this.id(e)];if(t)return t;switch(e.termType){case er.$Q:return new tr(e.value);case er.r0:return e;case er.ic:return new hr;case er.S:case er.bD:return e;case er.QW:return new sr(e.value,e.language,e.datatype);case er.Kk:return new rr.A(e.value);case er.P2:return new gr(e.value);default:throw new Error(`Term Type not recognized for canonization: ${e.termType}`)}}check(){this.checkStatementList(this.statements);for(var e=0;e<4;e++){var t=this.index[e];for(var r in t)t.hasOwnProperty(r)&&this.checkStatementList(t[r],e)}}checkStatementList(e,t){void 0===t&&(t=0);for(var r,n=" found in "+["subject","predicate","object","why"][t]+" index.",i=0;i<e.length;i++){for(var s=[(r=e[i]).subject,r.predicate,r.object,r.graph],o=function(e,t){for(var r=0;r<e.length;r++)if(e[r].subject.equals(t.subject)&&e[r].predicate.equals(t.predicate)&&e[r].object.equals(t.object)&&e[r].why.equals(t.graph))return!0},a=0;a<4;a++){var u=this.canon(s[a]),c=this.id(u);this.index[a][c]&&o(this.index[a][c],r)}if(!o(this.statements,r))throw new Error("Statement list does not statement "+r+"@"+r.graph+n)}}close(){return this}compareTerms(e,t){return Object.prototype.hasOwnProperty.call(e,"compareTerm")?e.compareTerm(t):Qt.A[e.termType]<Qt.A[t.termType]?-1:Qt.A[e.termType]>Qt.A[t.termType]?1:e.value<t.value?-1:e.value>t.value?1:0}copyTo(e,t,r){r||(r=[]);var n=this.statementsMatching(e);-1!==Nr(r,"two-direction")&&n.concat(this.statementsMatching(void 0,void 0,e));for(var i=0;i<n.length;i++){var s=n[i];switch(s.object.termType){case"NamedNode":this.add(t,s.predicate,s.object);break;case"Literal":case"BlankNode":case"Collection":this.add(t,s.predicate,s.object.copy(this))}-1!==Nr(r,"delete")&&this.remove(s)}}equate(e,t){const r=this.canon(e),n=this.canon(t);var i=this.compareTerms(r,n);return!i||(i<0?this.replaceWith(n,r):this.replaceWith(r,n))}formula(e){return new Kr(e)}get length(){return this.statements.length}match(e,t,r,n){return this.statementsMatching(Or.fromValue(e),Or.fromValue(t),Or.fromValue(r),Or.fromValue(n))}mentionsURI(e){var t="<"+e+">";return!!this.subjectIndex[t]||!!this.objectIndex[t]||!!this.predicateIndex[t]}newExistential(e){if(!e)return this.bnode();var t=this.sym(e);return this.declareExistential(t)}newPropertyAction(e,t){var r=this.id(e);this.propertyActions[r]||(this.propertyActions[r]=[]),this.propertyActions[r].push(t);for(var n=this.statementsMatching(void 0,e,void 0),i=!1,s=0;s<n.length;s++)i=i||t(this,n[s].subject,e,n[s].object);return i}newUniversal(e){var t=this.sym(e);return this._universalVariables||(this._universalVariables=[]),this._universalVariables.push(t),t}variable(e){return new gr(e)}nextSymbol(e){for(var t=0;;t++){var r=e.value+"#n"+t;if(!this.mentionsURI(r))return this.sym(r)}}query(e,t,r,n){return jr.call(this,e,t,r,n)}querySync(e){var t=[];var r=!1;if(e.sync=!0,jr.call(this,e,function(e){t.push(e)},null,function(){r=!0}),!r)throw new Error("Sync query should have called done function");return t}remove(e){if(e instanceof Array){for(var t=0;t<e.length;t++)this.remove(e[t]);return this}if((0,nr.ok)(e))return this.remove(e.statements);var r=this.statementsMatching(e.subject,e.predicate,e.object,e.graph);if(!r.length)throw new Error("Statement to be removed is not on store: "+e);return this.removeStatement(r[0]),this}removeDocument(e){this.removeMetadata(e);for(var t=this.statementsMatching(void 0,void 0,void 0,e).slice(),r=0;r<t.length;r++)this.removeStatement(t[r]);return this.removeMatches(e,null,null),this}removeMetadata(e){const t=this.sym("chrome://TheCurrentSession"),r="http://www.w3.org/2007/ont/link#",n=this.statementsMatching(void 0,this.sym(`${r}requestedURI`),this.rdfFactory.literal(e.value),t).map(e=>e.subject);for(var i=0;i<n.length;i++){const e=n[i];if(null!=e){let n;const i=this.any(e,this.sym(`${r}status`),null,t);if(null!=i){n=this.statementsMatching(i,this.sym(`${r}status`),null,t).slice();for(var s=0;s<n.length;s++)this.removeStatement(n[s])}const o=this.any(e,this.sym(`${r}response`),null,t);if(null!=o){n=this.statementsMatching(o,null,null,t).slice();for(s=0;s<n.length;s++)this.removeStatement(n[s])}n=this.statementsMatching(e,null,null,t).slice();for(s=0;s<n.length;s++)this.removeStatement(n[s])}}return this.removeMatches(this.sym(e.value),null,null,t),this}removeMany(e,t,r,n,i){for(var s=this.statementsMatching(e,t,r,n,!1),o=[],a=0;a<s.length;a++)o.push(s[a]);for(i&&(o=o.slice(0,i)),a=0;a<o.length;a++)this.remove(o[a])}removeMatches(e,t,r,n){return this.removeMany(e,t,r,n),this}removeStatement(e){for(var t=[e.subject,e.predicate,e.object,e.graph],r=0;r<4;r++){var n=this.canon(t[r]),i=this.id(n);this.index[r][i]&&this.rdfArrayRemove(this.index[r][i],e)}this.rdfArrayRemove(this.statements,e);for(const t of this.dataRemovalCallbacks)t(e);return this}removeStatements(e){for(var t=0;t<e.length;t++)this.remove(e[t]);return this}replaceWith(e,t){for(var r=this.id(e),n=this.id(t),i=function(e){var t=e[r];if(t){var i=e[n];e[n]=i?t.concat(i):t,delete e[r]}},s=0;s<4;s++)i(this.index[s]);if(this.redirections[r]=t,e.value){if(this.aliases[n]||(this.aliases[n]=[]),this.aliases[n].push(e),this.aliases[r])for(s=0;s<this.aliases[r].length;s++)this.redirections[this.id(this.aliases[r][s])]=t,this.aliases[n].push(this.aliases[r][s]);this.add(t,this.sym("http://www.w3.org/2007/ont/link#uri"),e),this.fetcher&&this.fetcher.nowKnownAs(e,t)}return i(this.classActions),i(this.propertyActions),!0}allAliases(e){var t=this.aliases[this.id(this.canon(e))]||[];return t.push(this.canon(e)),t}sameThings(e,t){if(e.equals(t))return!0;var r=this.canon(e);if(!r)return!1;var n=this.canon(t);return!!n&&r.value===n.value}setPrefixForURI(e,t){if(("tab"!==e||!this.namespaces.tab)&&"ns"!==e.slice(0,2)&&"default"!==e.slice(0,7)){for(let e in this.namespaces)this.namespaces[e]==t&&delete this.namespaces[e];this.namespaces[e]=t}}statementsMatching(e,t,r,n,i){var s,o,a=[e,t,r,n],u=[],c=[],h=[],l=[];for(s=0;s<4;s++)u[s]=this.canon(Or.fromValue(a[s])),u[s]?(l.push(s),c[s]=this.id(u[s])):h.push(s);if(0===l.length)return this.statements;if(1===l.length)return s=l[0],(o=this.index[s][c[s]])&&i&&o.length>1&&(o=o.slice(0,1)),o=o||[];var d,f,p=1e10;for(f=0;f<l.length;f++){if(s=l[f],!(o=this.index[s][c[s]]))return[];o.length<p&&(p=o.length,d=f)}for(var g=l[d],y=this.index[g][c[g]],v=l.slice(0,d).concat(l.slice(d+1)),m=[],w=["subject","predicate","object","why"],b=0;b<y.length;b++){var _=y[b];for(f=0;f<v.length;f++)if(s=v[f],!this.canon(_[w[s]]).equals(u[s])){_=null;break}if(null!=_&&(m.push(_),i))break}return m}uris(e){var t=this.canon(e),r=this.aliases[this.id(t)];if(!t.value)return[];var n=[t.value];if(r)for(var i=0;i<r.length;i++)n.push(r[i].uri);return n}serialize(e,t,r,n){return Ir(r,this,e,t,void 0,n={...n||{},namespaces:n?.namespaces?{...this.namespaces,...n.namespaces}:{...this.namespaces}})}}(0,Yt.A)(Kr,"handleRDFType",void 0),Kr.handleRDFType=qr;const Vr=_r("http://www.w3.org/1999/02/22-rdf-syntax-ns#");function $r(e,t){function r(n,i,s){const o=e.statementsMatching(n,Vr("rest"),null,t);if(1!==o.length)throw new Error(`Bad list structure: no rest at ${n}`);const a=e.statementsMatching(n,Vr("first"),null,t);if(1!==a.length)throw new Error(`Bad list structure: rest but ${a.length} firsts at ${n}`);const u=[a[0].object].concat(i),c=s.concat(o).concat(a),h=e.statementsMatching(null,Vr("rest"),n,t);if(0===h.length){const r=new ar(u);return e.remove(c),void function(e,t,r,n){for(const i of e.statementsMatching(r,null,null,n)){const r=new fr(t,i.predicate,i.object,n);e.remove(i),e.add(r)}for(const i of e.statementsMatching(null,r,null,n))e.remove(i),e.add(new fr(i.subject,t,i.object,n));for(const i of e.statementsMatching(null,null,r,n))e.remove(i),e.add(new fr(i.subject,i.predicate,t,n))}(e,r,n,t)}if(1!==h.length)throw new Error(`Bad list structure: ${h.length} pres at ${n}`);const l=h[0].subject;if("BlankNode"!==l.termType)throw new Error(`Bad list element node ${l} type: ${l.termType} `);r(l,u,c)}!function(e,t){const r=Vr("nil");for(const n of e.statementsMatching(r,null,null,t)){e.remove(n);const r=new ar;e.add(new fr(r,n.predicate,n.object,t))}for(const n of e.statementsMatching(null,null,r,t))if(!n.predicate.sameTerm(Vr("rest"))){e.remove(n);const r=new ar;e.add(new fr(n.subject,n.predicate,r,t))}}(e,t);e.statementsMatching(null,Vr("rest"),Vr("nil"),t).forEach(e=>{if("BlankNode"!==e.subject.termType)throw new Error(`Bad list element node ${e.subject} type: ${e.subject.termType} `);r(e.subject,[],[])})}var Wr=function(e){e=e.replace(/\r\n/g,"\n");for(var t="",r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t+=String.fromCharCode(n):n>127&&n<2048?(t+=String.fromCharCode(n>>6|192),t+=String.fromCharCode(63&n|128)):(t+=String.fromCharCode(n>>12|224),t+=String.fromCharCode(n>>6&63|128),t+=String.fromCharCode(63&n|128))}return t},Jr="http://www.w3.org/2000/10/swap/log#",zr=function(e){return e},Xr=function(e){return e},Gr=function(e){if(e.length>0)throw"missing.js: oops nnonempty dict not imp";return[]},Yr=function(e){return e.length},Qr=function(e,t,r){if(void 0===e.slice)throw"@@ mising.js: No .slice function for "+e+" of type "+typeof e;return void 0===r||null==r?e.slice(t):e.slice(t,r)},Zr=Error("dummy error stop iteration"),en=function(e){return this.last=0,this.li=e,this.next=function(){if(this.last==this.li.length)throw Zr;return this.li[this.last++]},this},tn=function(e,t){return e.indexOf(t)},rn=function(e,t){if(!e){if(t)throw"python Assertion failed: "+t;throw"(python) Assertion failed."}};String.prototype.encode=function(e){if("utf-8"!=e)throw"UTF8_converter: can only do utf-8";return Wr(this)},String.prototype.decode=function(e){if("utf-8"!=e)throw"UTF8_converter: can only do utf-8";return this};var nn=function(e,t){return pr.join(t,e)},sn="http://www.w3.org/1999/02/22-rdf-syntax-ns#nil",on="http://www.w3.org/2002/07/owl#sameAs";var an="\t\r\n !\"#$%&'()*.,+/;<=>?@[\\]^`{|}~",un=an+":",cn=new RegExp("^([-+]?[0-9]+)(\\.[0-9]+)?([eE][-+]?[0-9]+)?","g"),hn=new RegExp("^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9](T[0-9][0-9]:[0-9][0-9](:[0-9][0-9](\\.[0-9]*)?)?)?Z?"),ln=new RegExp('[\\\\\\r\\n\\"]',"g"),dn=new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*","g");const fn=function(e,t,r,n,i,s,o,a){return new pn(e,t,r,n,i,s,o,a)};class pn{constructor(e,t,r,n,i,s,o,a){void 0===t&&(t=null),void 0===r&&(r=""),void 0===n&&(n=null),void 0===i&&(i=""),void 0===s&&(s=null),void 0===o&&(o=""),void 0===a&&(a=null),this._bindings=new Gr([]),this._flags=o,""!=r&&(rn(r.indexOf(":")>=0,"Document URI not absolute: "+r),this._bindings[""]=r+"#"),this._store=e,i&&e.setGenPrefix(i),this._thisDoc=r,this.source=e.sym(r),this.lines=0,this.statementCount=0,this.hasNil=!1,this.startOfLine=0,this.previousLine=0,this._genPrefix=i,this.keywords=new Xr(["a","this","bind","has","is","of","true","false"]),this.keywordsSet=0,this._anonymousNodes=new Gr([]),this._variables=new Gr([]),this._parentVariables=new Gr([]),this._reason=a,this._reason2=null,this._baseURI=n||(r||null),rn(!this._baseURI||this._baseURI.indexOf(":")>=0),this._genPrefix||(this._thisDoc?this._genPrefix=this._thisDoc+"#_g":this._genPrefix=RDFSink_uniqueURI()),null==t?this._thisDoc?this._formula=e.formula(r+"#_formula"):this._formula=e.formula():this._formula=t,this._context=this._formula,this._parentContext=null}here(e){return this._genPrefix+"_L"+this.lines+"C"+(e-this.startOfLine+1)}formula(){return this._formula}loadStream(e){return this.loadBuf(e.read())}loadBuf(e){return this.startDoc(),this.feed(e),this.endDoc()}feed(e){for(var t=e.decode("utf-8"),r=0;r>=0;){var n=this.skipSpace(t,r);if(n<0)return;if((r=this.directiveOrStatement(t,n))<0)throw yn(this._thisDoc,this.lines,t,n,"expected directive or statement")}}directiveOrStatement(e,t){var r,n=this.skipSpace(e,t);return n<0?n:(r=this.directive(e,n))>=0||(r=this.statement(e,n))>=0?this.checkDot(e,r):r}tok(e,t,r){if("@"==t.slice(r,r+1))r=r+1;else if(Nr(this.keywords,e)<0)return-1;var n=r+Yr(e);return t.slice(r,n)==e&&an.indexOf(t.charAt(n))>=0?n:-1}directive(e,t){if((s=this.skipSpace(e,t))<0)return s;var r=new Xr([]);if((s=this.tok("bind",e,t))>0)throw yn(this._thisDoc,this.lines,e,t,"keyword bind is obsolete: use @prefix");if((s=this.tok("keywords",e,t))>0){if((t=this.commaSeparatedList(e,s,r,!1))<0)throw yn(this._thisDoc,this.lines,e,t,"'@keywords' needs comma separated list of words");return this.setKeywords(Qr(r,null,null)),t}if((s=this.tok("forAll",e,t))>0){if((t=this.commaSeparatedList(e,s,r,!0))<0)throw yn(this._thisDoc,this.lines,e,t,"Bad variable list after @forAll");var n=new en(r);try{for(;;){var i=n.next();(Nr(this._variables,i)<0||Nr(this._parentVariables,i)>=0)&&(this._variables[i]=this._context.newUniversal(i))}}catch(e){if(e!=Zr)throw e}return t}if((s=this.tok("forSome",e,t))>0){if((t=this.commaSeparatedList(e,s,r,this.uri_ref2))<0)throw yn(this._thisDoc,this.lines,e,t,"Bad variable list after @forSome");n=new en(r);try{for(;;){i=n.next();this._context.declareExistential(i)}}catch(e){if(e!=Zr)throw e}return t}if((s=this.tok("prefix",e,t))>=0){var s,o=new Xr([]);if((t=this.qname(e,s,o))<0)throw yn(this._thisDoc,this.lines,e,s,"expected qname after @prefix");if((s=this.uri_ref2(e,t,o))<0)throw yn(this._thisDoc,this.lines,e,t,"expected <uriref> after @prefix _qname_");var a=o[1].uri;if(this._baseURI)a=nn(this._baseURI,a);else rn(a.indexOf(":")>=0,"With no base URI, cannot handle relative URI for NS");return rn(a.indexOf(":")>=0),this._bindings[o[0][0]]=a,this.bind(o[0][0],function(e){return encodeURI(e)}(a)),s}if((s=this.tok("base",e,t))>=0){o=new Xr([]);if((t=this.uri_ref2(e,s,o))<0)throw yn(this._thisDoc,this.lines,e,s,"expected <uri> after @base ");a=o[0].uri;if(!this._baseURI)throw yn(this._thisDoc,this.lines,e,s,"With no previous base URI, cannot use relative URI in @base <"+a+">");a=nn(this._baseURI,a);return rn(a.indexOf(":")>=0),this._baseURI=a,t}return-1}bind(e,t){""==e||this._store.setPrefixForURI(e,t)}setKeywords(e){null==e?this.keywordsSet=0:(this.keywords=e,this.keywordsSet=1)}startDoc(){}endDoc(){return this.hasNil&&this._store.rdfFactory.supports.COLLECTIONS&&$r(this._store,this.source),this._formula}makeStatement(e){e[0].add(e[2],e[1],e[3],this.source),(e[2].uri&&e[2].uri===sn||e[3].uri&&e[3].uri===sn)&&(this.hasNil=!0),this.statementCount+=1}statement(e,t){var r=new Xr([]);if((t=this.object(e,t,r))<0)return t;var n=this.property_list(e,t,r[0]);if(n<0)throw yn(this._thisDoc,this.lines,e,t,"expected propertylist");return n}subject(e,t,r){return this.item(e,t,r)}verb(e,t,r){if((i=this.skipSpace(e,t))<0)return i;var n=new Xr([]);if((i=this.tok("has",e,t))>=0){if((t=this.prop(e,i,n))<0)throw yn(this._thisDoc,this.lines,e,i,"expected property after 'has'");return r.push(new zr(["->",n[0]])),t}if((i=this.tok("is",e,t))>=0){if((t=this.prop(e,i,n))<0)throw yn(this._thisDoc,this.lines,e,i,"expected <property> after 'is'");if((i=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"End of file found, expected property after 'is'");var i;t=i;if((i=this.tok("of",e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"expected 'of' after 'is' <prop>");return r.push(new zr(["<-",n[0]])),i}if((i=this.tok("a",e,t))>=0)return r.push(new zr(["->",this._store.sym("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")])),i;if("<="==e.slice(t,t+2))return r.push(new zr(["<-",this._store.sym(Jr+"implies")])),t+2;if("="==e.slice(t,t+1))return">"==e.slice(t+1,t+2)?(r.push(new zr(["->",this._store.sym(Jr+"implies")])),t+2):(r.push(new zr(["->",this._store.sym(on)])),t+1);if(":="==e.slice(t,t+2))return r.push(new zr(["->",Jr+"becomes"])),t+2;if((i=this.prop(e,t,n))>=0)return r.push(new zr(["->",n[0]])),i;if(">-"==e.slice(t,t+2)||"<-"==e.slice(t,t+2))throw yn(this._thisDoc,this.lines,e,i,">- ... -> syntax is obsolete.");return-1}prop(e,t,r){return this.item(e,t,r)}item(e,t,r){return this.path(e,t,r)}blankNode(e){return this._context.bnode(e,this._reason2)}path(e,t,r){if((s=this.nodeOrLiteral(e,t,r))<0)return s;for(;"!^.".indexOf(e.slice(s,s+1))>=0;){var n=e.slice(s,s+1);if("."==n){var i=e.slice(s+1,s+2);if(!i||un.indexOf(i)>=0&&":?<[{(".indexOf(i)<0)break}var s,o=r.pop(),a=this.blankNode(this.here(s));if((s=this.node(e,s+1,r))<0)throw yn(this._thisDoc,this.lines,e,s,"EOF found in middle of path syntax");var u=r.pop();"^"==n?this.makeStatement(new zr([this._context,u,a,o])):this.makeStatement(new zr([this._context,u,o,a])),r.push(a)}return s}anonymousNode(e){if(t=this._anonymousNodes[e])return t;var t=this._store.bnode(e);return this._anonymousNodes[e]=t,t}node(e,t,r,n){void 0===n&&(n=null);var i=n;if((h=this.skipSpace(e,t))<0)return h;t=h;var s=e.slice(t,t+1);if("["==s){var o=this.here(t);if((h=this.skipSpace(e,t+1))<0)throw yn(this._thisDoc,this.lines,e,t,"EOF after '['");if("="==e.slice(h,h+1)){var t=h+1,a=new Xr([]);if(!((h=this.objectList(e,t,a))>=0))throw yn(this._thisDoc,this.lines,e,t,"objectList expected after [= ");i=a[0];if(Yr(a)>1){var u=new en(a);try{for(;;){var c=u.next();this.makeStatement(new zr([this._context,this._store.sym(on),i,c]))}}catch(e){if(e!=Zr)throw e}}if((h=this.skipSpace(e,h))<0)throw yn(this._thisDoc,this.lines,e,t,"EOF when objectList expected after [ = ");if(";"==e.slice(h,h+1))var h=h+1}if(null==i)i=this.blankNode(o);if((t=this.property_list(e,h,i))<0)throw yn(this._thisDoc,this.lines,e,h,"property_list expected");if((h=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"EOF when ']' expected after [ <propertyList>");if("]"!=e.slice(h,h+1))throw yn(this._thisDoc,this.lines,e,h,"']' expected");return r.push(i),h+1}if("{"==s){if("$"==e.slice(t+1,t+2)){for(var h=(t+=1)+1,l=new Xr([]),d=!0;;){if((t=this.skipSpace(e,h))<0)throw yn(this._thisDoc,this.lines,e,t,"needed '$}', found end.");if("$}"==e.slice(t,t+2)){var h=t+2;break}if(d)d=!1;else{if(","!=e.slice(t,t+1))throw yn(this._thisDoc,this.lines,e,t,"expected: ','");t+=1}var f=new Xr([]);if((h=this.item(e,t,f))<0)throw yn(this._thisDoc,this.lines,e,t,"expected item in set or '$}'");l.push(f[0])}return r.push(this._store.newSet(l,this._context)),h}var h=t+1,p=this._parentContext;this._parentContext=this._context;var g=this._anonymousNodes,y=this._parentVariables;this._parentVariables=this._variables,this._anonymousNodes=new Gr([]),this._variables=this._variables.slice();var v=this._reason2;if(this._reason2=null,null==i)i=this._store.formula();for(this._context=i;;){if((t=this.skipSpace(e,h))<0)throw yn(this._thisDoc,this.lines,e,t,"needed '}', found end.");if("}"==e.slice(t,t+1)){var h=t+1;break}if((h=this.directiveOrStatement(e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"expected statement or '}'")}return this._anonymousNodes=g,this._variables=this._parentVariables,this._parentVariables=y,this._context=this._parentContext,this._reason2=v,this._parentContext=p,r.push(i.close()),h}if("("==s){var m=this._store.list;if("$"==e.slice(t+1,t+2)){m=this._store.newSet;t+=1}for(h=t+1,l=new Xr([]);;){if((t=this.skipSpace(e,h))<0)throw yn(this._thisDoc,this.lines,e,t,"needed ')', found end.");if(")"==e.slice(t,t+1)){h=t+1;break}f=new Xr([]);if((h=this.item(e,t,f))<0)throw yn(this._thisDoc,this.lines,e,t,"expected item in list or ')'");l.push(f[0])}return r.push(m(l,this._context)),h}if((h=this.tok("this",e,t))>=0)throw yn(this._thisDoc,this.lines,e,t,"Keyword 'this' was ancient N3. Now use @forSome and @forAll keywords.");if((h=this.tok("true",e,t))>=0)return r.push(!0),h;if((h=this.tok("false",e,t))>=0)return r.push(!1),h;if(null==i&&(h=this.uri_ref2(e,t,r))>=0)return h;return-1}property_list(e,t,r){for(;;){if((h=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"EOF found when expected verb in property list");if(":-"!=e.slice(h,h+2)){t=h;var n=new Xr([]);if((h=this.verb(e,t,n))<=0)return t;var i=new Xr([]);if((t=this.objectList(e,h,i))<0)throw yn(this._thisDoc,this.lines,e,h,"objectList expected");var s=new en(i);try{for(;;){var o=s.next(),a=n[0],u=a[0],c=a[1];"->"==u?this.makeStatement(new zr([this._context,c,r,o])):this.makeStatement(new zr([this._context,c,o,r]))}}catch(e){if(e!=Zr)throw e}if((h=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,h,"EOF found in list of objects");if(";"!=e.slice(t,t+1))return t;t=t+1}else{var h,t=h+2,l=new Xr([]);if((h=this.node(e,t,l,r))<0)throw yn(this._thisDoc,this.lines,e,t,"bad {} or () or [] node after :- ");var t=h}}}commaSeparatedList(e,t,r,n){if((i=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,i,"EOF found expecting comma sep list");if("."==e.charAt(i))return t;if(n)var i=this.uri_ref2(e,i,r);else i=this.bareWord(e,i,r);if(i<0)return-1;for(;;){if((t=this.skipSpace(e,i))<0)return t;var s=e.slice(t,t+1);if(","!=s)return"."!=s?-1:t;if(n)i=this.uri_ref2(e,t+1,r);else i=this.bareWord(e,t+1,r);if(i<0)throw yn(this._thisDoc,this.lines,e,i,"bad list content")}}objectList(e,t,r){if((t=this.object(e,t,r))<0)return-1;for(;;){var n=this.skipSpace(e,t);if(n<0)throw yn(this._thisDoc,this.lines,e,n,"EOF found after object");if(","!=e.slice(n,n+1))return n;if((t=this.object(e,n+1,r))<0)return t}}checkDot(e,t){var r=this.skipSpace(e,t);if(r<0)return r;if("."==e.slice(r,r+1))return r+1;if("}"==e.slice(r,r+1))return r;if("]"==e.slice(r,r+1))return r;throw yn(this._thisDoc,this.lines,e,r,"expected '.' or '}' or ']' at end of statement")}uri_ref2(e,t,r){var n=new Xr([]);if((d=this.qname(e,t,n))>=0){var i=n[0],s=i[0],o=i[1];if(null==s){rn(0,"not used?");var a=this._baseURI+"#"}else{if(!(a=this._bindings[s])){if("_"==s)return r.push(this.anonymousNode(o)),d;throw yn(this._thisDoc,this.lines,e,t,"Prefix "+s+" not bound.")}}var u=this._store.sym(a+o);return Nr(this._variables,u)>=0?r.push(this._variables[u]):r.push(u),d}if((t=this.skipSpace(e,t))<0)return-1;if("?"==e.charAt(t)){var c=new Xr([]);return(d=this.variable(e,t,c))>0?(r.push(c[0]),d):-1}if("<"==e.charAt(t)){for(var h=t=t+1;t<Yr(e);){if(">"==e.charAt(t)){var l=e.slice(h,t);if(this._baseURI)l=nn(this._baseURI,l);else rn(l.indexOf(":")>=0,"With no base URI, cannot deal with relative URIs");if("#"==e.slice(t-1,t)&&"#"!=Qr(l,-1,null))l=l+"#";u=this._store.sym(l);return Nr(this._variables,u)>=0?r.push(this._variables[u]):r.push(u),t+1}t=t+1}throw yn(this._thisDoc,this.lines,e,d,"unterminated URI reference")}if(this.keywordsSet){var d;c=new Xr([]);if((d=this.bareWord(e,t,c))<0)return-1;if(Nr(this.keywords,c[0])>=0)throw yn(this._thisDoc,this.lines,e,t,'Keyword "'+c[0]+'" not allowed here.');return r.push(this._store.sym(this._bindings[""]+c[0])),d}return-1}skipSpace(e,t){for(var r=t||0;r<e.length;r++){var n=e.charAt(r);if(" \n\r\t\f\v            ​\u2028\u2029 ".indexOf(n)<0){if("#"!==e.charAt(r))return r;for(;;r++){if(r===e.length)return-1;if("\n"===e.charAt(r)){this.lines=this.lines+1;break}}}else"\n"===e.charAt(r)&&(this.lines=this.lines+1)}return-1}variable(e,t,r){if((n=this.skipSpace(e,t))<0)return-1;if("?"!=e.slice(n,n+1))return-1;var n;t=n+=1;if("0123456789-".indexOf(e.charAt(n))>=0)throw yn(this._thisDoc,this.lines,e,n,"Varible name can't start with '"+e.charAt(n)+"s'");for(;t<Yr(e)&&un.indexOf(e.charAt(t))<0;)t=t+1;if(null==this._parentContext)throw yn(this._thisDoc,this.lines,e,n,"Can't use ?xxx syntax for variable in outermost level: "+e.slice(n-1,t));return r.push(this._store.variable(e.slice(n,t))),t}bareWord(e,t,r){var n=this.skipSpace(e,t);if(n<0)return-1;var i=e.charAt(n);if("0123456789-".indexOf(i)>=0)return-1;if(un.indexOf(i)>=0)return-1;for(t=n;t<Yr(e)&&un.indexOf(e.charAt(t))<0;)t=t+1;return r.push(e.slice(n,t)),t}qname(e,t,r){if((t=this.skipSpace(e,t))<0)return-1;var n=e.charAt(t);if("0123456789-+".indexOf(n)>=0)return-1;if(un.indexOf(n)<0){var i=n;for(t=t+1;t<Yr(e);){n=e.charAt(t);if(!(un.indexOf(n)<0))break;i=i+n,t=t+1}}else i="";if(t<Yr(e)&&":"==e.charAt(t)){var s=i;for(t=t+1,i="";t<Yr(e);){n=e.charAt(t);if(!(un.indexOf(n)<0))break;i=i+n,t=t+1}return r.push(new zr([s,i])),t}return i&&this.keywordsSet&&Nr(this.keywords,i)<0?(r.push(new zr(["",i])),t):-1}object(e,t,r){if((s=this.subject(e,t,r))>=0)return s;{if((s=this.skipSpace(e,t))<0)return-1;t=s;var n=null;let a=e.charAt(t);if('"'==a||"'"==a){n=e.slice(t,t+3==a+a)?a+a+a:a;t=t+Yr(n);var i=this.strconst(e,t,n),s=i[0],o=i[1];return r.push(this._store.literal(o)),s}return-1}}nodeOrLiteral(e,t,r){if((u=this.node(e,t,r))>=0)return u;if((u=this.skipSpace(e,t))<0)return-1;t=u;var n=e.charAt(t);if("-+0987654321".indexOf(n)>=0){if(hn.lastIndex=0,null!=(l=hn.exec(e.slice(t)))){u=t+(i=l[0]).length,i.indexOf("T")>=0?r.push(this._store.literal(i,this._store.sym("http://www.w3.org/2001/XMLSchema#dateTime"))):r.push(this._store.literal(i,this._store.sym("http://www.w3.org/2001/XMLSchema#date")))}else{var i;if(cn.lastIndex=0,null==(l=cn.exec(e.slice(t))))throw yn(this._thisDoc,this.lines,e,t,"Bad number or date syntax");u=t+cn.lastIndex,(i=e.slice(t,u)).indexOf("e")>=0?r.push(this._store.literal(parseFloat(i),this._store.sym("http://www.w3.org/2001/XMLSchema#double"))):e.slice(t,u).indexOf(".")>=0?r.push(this._store.literal(parseFloat(i),this._store.sym("http://www.w3.org/2001/XMLSchema#decimal"))):r.push(this._store.literal(parseInt(i),this._store.sym("http://www.w3.org/2001/XMLSchema#integer")))}return u}if('"'==e.charAt(t)){if('"""'==e.slice(t,t+3))var s='"""';else s='"';t=t+Yr(s);var o=null,a=this.strconst(e,t,s),u=a[0],c=a[1],h=null;if("@"==e.slice(u,u+1)){var l;if(dn.lastIndex=0,null==(l=dn.exec(e.slice(u+1))))throw yn(this._thisDoc,startline,e,t,"Bad language code syntax on string literal, after @");t=dn.lastIndex+u+1,h=e.slice(u+1,t),u=t}if("^^"==e.slice(u,u+2)){var d=new Xr([]);u=this.uri_ref2(e,u+2,d),o=d[0]}return r.push(this._store.literal(c,h||o)),u}return-1}strconst(e,t,r){for(var n=t,i="",s=this.lines;n<Yr(e);){t=n+Yr(r);if(e.slice(n,t)==r)return new zr([t,i]);if('"'!=e.charAt(n)){if(ln.lastIndex=0,!ln.exec(e.slice(n)))throw yn(this._thisDoc,s,e,n,"Closing quote missing in string at ^ in "+e.slice(n-20,n)+"^"+e.slice(n,n+20));t=n+ln.lastIndex-1,i=i+e.slice(n,t);if('"'!=(u=e.charAt(t)))if("\r"!=u){if("\n"==u){if('"'==r)throw yn(this._thisDoc,s,e,t,"newline found in string literal");this.lines=this.lines+1;i=i+u,n=t+1;this.previousLine=this.startOfLine,this.startOfLine=n}else if("\\"==u){n=t+1;if(!(u=e.slice(n,n+1)))throw yn(this._thisDoc,s,e,t,"unterminated string literal (2)");var o=tn('abfrtvn\\"',u);if(o>=0)i=i+'a\b\f\r\t\v\n\\"'.charAt(o),n=n+1;else if("u"==u)n=(a=this.uEscape(e,n+1,s))[0],i=i+(u=a[1]);else{if("U"!=u)throw yn(this._thisDoc,this.lines,e,t,"bad escape");var a,u;n=(a=this.UEscape(e,n+1,s))[0],i=i+(u=a[1])}}}else var n=t+1;else var n=t}else var i=i+'"',n=n+1}throw yn(this._thisDoc,this.lines,e,t,"unterminated string literal")}uEscape(e,t,r){for(var n=t,i=0,s=0;i<4;){var o=e.slice(n,n+1).toLowerCase();n=n+1;if(""==o)throw yn(this._thisDoc,r,e,t,"unterminated string literal(3)");var a=tn("0123456789abcdef",o);if(a<0)throw yn(this._thisDoc,r,e,t,"bad string literal hex escape");s=16*s+a,i=i+1}var u=String.fromCharCode(s);return new zr([n,u])}UEscape(e,t,r){for(var n=t,i=0,s="\\U";i<8;){var o=e.slice(n,n+1).toLowerCase();n=n+1;if(""==o)throw yn(this._thisDoc,r,e,t,"unterminated string literal(3)");if(tn("0123456789abcdef",o)<0)throw yn(this._thisDoc,r,e,t,"bad string literal hex escape");s=s+o,i=i+1}var a,u=(a="0x"+Qr(s,2,10)-0,String.fromCharCode(a));return new zr([n,u])}}function gn(e,t,r,n,i){this._str=r.encode("utf-8"),this._str=r,this._i=n,this._why=i,this.lines=t,this._uri=e}function yn(e,t,r,n,i){let s=t+1,o="Line "+s+" of <"+e+">: Bad syntax: "+i+'\nat: "'+r.slice(n,n+30)+'"',a=new SyntaxError(o,e,s);return a.lineNo=s,a.characterInFile=n,a.syntaxProblem=i,a}gn.prototype.toString=function(){var e=this._str,t=this._i,r=0;if(t>60){var n="...";r=t-60}else n="";if(Yr(e)-t>60)var i="...";else i="";return'Line %i of <%s>: Bad syntax (%s) at ^ in:\n"%s%s^%s%s"'%new zr([this.lines+1,this._uri,this._why,n,e.slice(r,t),e.slice(t,t+60),i])};const vn={...wr,supports:{[yr.collections]:!0,[yr.defaultGraphType]:!1,[yr.equalsMethod]:!0,[yr.identity]:!1,[yr.id]:!0,[yr.reversibleId]:!1,[yr.variableType]:!0},collection:e=>new ar(e),id(e){return(0,nr.P3)(e)?`( ${e.elements.map(e=>this.id(e)).join(", ")} )`:(0,nr.DZ)(e)?gr.toString(e):wr.id(e)},termToNQ:e=>e.termType===er.r0?ar.toNT(e):wr.termToNQ(e)},mn=vn;function wn(e,t){return"string"==typeof t?e.rdfFactory.literal(t):Object.prototype.hasOwnProperty.call(t,"@list")?!0===e.rdfFactory.supports.COLLECTIONS?function(e,t){if(!Array.isArray(t))throw new TypeError("Object must be an array");return e.rdfFactory.collection(t.map(t=>wn(e,t)))}(e,t["@list"]):function(e,t){const r=t["@id"]?_n(e,t):e.rdfFactory.blankNode(),n=t["@list"].map(t=>wn(e,t)),i=Pr(e.rdfFactory,r,n);return e.addAll(i),r}(e,t):Object.prototype.hasOwnProperty.call(t,"@id")?_n(e,t):Object.prototype.hasOwnProperty.call(t,"@language")?e.rdfFactory.literal(t["@value"],t["@language"]):Object.prototype.hasOwnProperty.call(t,"@type")?e.rdfFactory.literal(t["@value"],e.rdfFactory.namedNode(t["@type"])):Object.prototype.hasOwnProperty.call(t,"@value")?e.rdfFactory.literal(t["@value"]):e.rdfFactory.literal(t)}async function bn(e,t,r){const n=r&&Object.prototype.hasOwnProperty.call(r,"termType")?r.value:r,i=await Promise.all([a.e(841),a.e(789)]).then(a.t.bind(a,4841,23));return(await i.default.flatten(JSON.parse(e),null,{base:n})).reduce((e,t)=>Sn(e,r,t),t)}function _n(e,t){return t["@id"].startsWith("_:")?e.rdfFactory.blankNode(t["@id"].substring(2)):e.rdfFactory.namedNode(t["@id"])}function Sn(e,t,r){const n=r["@id"]?_n(e,r):e.rdfFactory.blankNode();for(const i of Object.keys(r)){if("@id"===i)continue;if("@graph"==i){const t=n,s=r[i];for(let r=0;r<s.length;r++)e=Sn(e,t,s[r])}const s=r[i];if(Array.isArray(s))for(let r=0;r<s.length;r++)e.addStatement(En(e,n,i,s[r],t));else e.addStatement(En(e,n,i,s,t))}return e}function En(e,t,r,n,i){let s,o;return"@type"===r?(s=e.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),o=e.rdfFactory.namedNode(n)):(s=e.rdfFactory.namedNode(r),o=wn(e,n)),e.rdfFactory.quad(t,s,o,e.rdfFactory.namedNode(i))}var xn=a(8287);const An="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Fn="http://www.w3.org/2001/XMLSchema#",Tn="http://www.w3.org/2000/10/swap/",kn={xsd:{decimal:`${Fn}decimal`,boolean:`${Fn}boolean`,double:`${Fn}double`,integer:`${Fn}integer`,string:`${Fn}string`},rdf:{type:`${An}type`,nil:`${An}nil`,first:`${An}first`,rest:`${An}rest`,langString:`${An}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${Tn}reify#forSome`,forAll:`${Tn}reify#forAll`},log:{implies:`${Tn}log#implies`,isImpliedBy:`${Tn}log#isImpliedBy`}},{xsd:In}=kn,Cn=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,Rn={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},Pn=/[\x00-\x20<>\\"\{\}\|\^\`]/,Nn={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},Un=/$0^/;class On{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._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const e in this)!(e in Nn)&&this[e]instanceof RegExp&&(this[e]=Un)}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,o;for(;e=this._newline.exec(r);)this.comments&&(o=this._comment.exec(e[0]))&&i("comment",o[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&&(o=this._comment.exec(r))&&i("comment",o[1],"",this._line,r.length),r=null,i("eof","","",this._line,0)),this._input=r;const a=this._line,u=r[0];let c="",h="",l="",d=null,f=0,p=!1;switch(u){case"^":if(r.length<3)break;if("^"!==r[1]){this._n3Mode&&(f=1,c="^");break}if(this._previousMarker="^^",r=r.substr(2),"<"!==r[0]){p=!0;break}case"<":if(d=this._unescapedIri.exec(r))c="IRI",h=d[1];else if(d=this._iri.exec(r)){if(h=this._unescape(d[1]),null===h||Pn.test(h))return s(this);c="IRI"}else r.length>1&&"<"===r[1]?(c="<<",f=2):this._n3Mode&&r.length>1&&"="===r[1]&&(f=2,this._isImpliedBy?(c="abbreviation",h="<"):(c="inverse",h=">"));break;case">":r.length>1&&">"===r[1]&&(c=">>",f=2);break;case"_":((d=this._blank.exec(r))||t&&(d=this._blank.exec(`${r} `)))&&(c="blank",l="_",h=d[1]);break;case'"':if(d=this._simpleQuotedString.exec(r))h=d[1];else if(({value:h,matchLength:f}=this._parseLiteral(r)),null===h)return s(this);null===d&&0===f||(c="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(d=this._simpleApostropheString.exec(r))h=d[1];else if(({value:h,matchLength:f}=this._parseLiteral(r)),null===h)return s(this);null===d&&0===f||(c="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(d=this._variable.exec(r))&&(c="var",h=d[0]);break;case"@":"literal"===this._previousMarker&&(d=this._langcode.exec(r))?(c="langcode",h=d[1]):(d=this._keyword.exec(r))&&(c=d[0]);break;case".":if(1===r.length?t:r[1]<"0"||r[1]>"9"){c=".",f=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(d=this._number.exec(r)||t&&(d=this._number.exec(`${r} `)))&&(c="literal",h=d[0],l="string"==typeof d[1]?In.double:"string"==typeof d[2]?In.decimal:In.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(d=this._sparqlKeyword.exec(r))?c=d[0].toUpperCase():p=!0;break;case"f":case"t":(d=this._boolean.exec(r))?(c="literal",h=d[0],l=In.boolean):p=!0;break;case"a":(d=this._shortPredicates.exec(r))?(c="abbreviation",h="a"):p=!0;break;case"=":this._n3Mode&&r.length>1&&(c="abbreviation",">"!==r[1]?(f=1,h="="):(f=2,h=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(f=1,c=u);break;case"{":!this._lineMode&&r.length>=2&&("|"===r[1]?(c="{|",f=2):(c=u,f=1));break;case"|":r.length>=2&&"}"===r[1]&&(c="|}",f=2);break;default:p=!0}if(p&&("@prefix"!==this._previousMarker&&"PREFIX"!==this._previousMarker||!(d=this._prefix.exec(r))?((d=this._prefixed.exec(r))||t&&(d=this._prefixed.exec(`${r} `)))&&(c="prefixed",l=d[1]||"",h=this._unescape(d[2])):(c="prefix",h=d[1]||"")),"^^"===this._previousMarker)switch(c){case"prefixed":c="type";break;case"IRI":c="typeIRI";break;default:c=""}if(!c)return t||!/^'''|^"""/.test(r)&&/\n|\r/.test(r)?s(this):this._input=r;const g=f||d[0].length,y=i(c,h,l,a,g);this.previousToken=y,this._previousMarker=c,r=r.substr(g,r.length)}function i(t,i,s,o,a){const u=r?n-r.length:n,c={type:t,value:i,prefix:s,line:o,start:u,end:u+a};return e(null,c),c}function s(t){e(t._syntaxError(/^\S*/.exec(r)[0]))}}_unescape(e){let t=!1;const r=e.replace(Cn,(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 Rn?Rn[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,s=n+r;if(1===r&&0!==i||3===r&&this._lineMode)break;return this._line+=i,{value:this._unescape(t),matchLength:s}}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}queueMicrotask(()=>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=xn.hp.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:Ln,xsd:Dn}=kn;let jn,Mn=0;const Bn={namedNode:zn,blankNode:Xn,variable:Yn,literal:Gn,defaultGraph:function(){return jn},quad:Qn,triple:Qn,fromTerm:Zn,fromQuad:ei},Hn=Bn;class qn{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof qn?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 Kn extends qn{get termType(){return"NamedNode"}}class Vn extends qn{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 t<e.length&&"@"===e[t++]?e.substr(t).toLowerCase():""}get datatype(){return new Kn(this.datatypeString)}get datatypeString(){const e=this.id,t=e.lastIndexOf('"')+1,r=t<e.length?e[t]:"";return"^"===r?e.substr(t+2):"@"!==r?Dn.string:Ln.langString}equals(e){return e instanceof Vn?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}}class $n extends qn{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class Wn extends qn{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}jn=new class extends qn{constructor(){return super(""),jn||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}};class Jn extends qn{constructor(e,t,r,n){super(""),this._subject=e,this._predicate=t,this._object=r,this._graph=n||jn}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(e){return!!e&&this._subject.equals(e.subject)&&this._predicate.equals(e.predicate)&&this._object.equals(e.object)&&this._graph.equals(e.graph)}}function zn(e){return new Kn(e)}function Xn(e){return new $n(e||"n3-"+Mn++)}function Gn(e,t){if("string"==typeof t)return new Vn(`"${e}"@${t.toLowerCase()}`);let r=t?t.value:"";return""===r&&("boolean"==typeof e?r=Dn.boolean:"number"==typeof e&&(Number.isFinite(e)?r=Number.isInteger(e)?Dn.integer:Dn.double:(r=Dn.double,Number.isNaN(e)||(e=e>0?"INF":"-INF")))),""===r||r===Dn.string?new Vn(`"${e}"`):new Vn(`"${e}"^^${r}`)}function Yn(e){return new Wn(e)}function Qn(e,t,r,n){return new Jn(e,t,r,n)}function Zn(e){if(e instanceof qn)return e;switch(e.termType){case"NamedNode":return zn(e.value);case"BlankNode":return Xn(e.value);case"Variable":return Yn(e.value);case"DefaultGraph":return jn;case"Literal":return Gn(e.value,e.language||e.datatype);case"Quad":return ei(e);default:throw new Error(`Unexpected termType: ${e.termType}`)}}function ei(e){if(e instanceof Jn)return e;if("Quad"!==e.termType)throw new Error(`Unexpected termType: ${e.termType}`);return Qn(Zn(e.subject),Zn(e.predicate),Zn(e.object),Zn(e.graph))}let ti=0;class ri{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&ii(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),s=/quad/.test(t),o=this._n3Mode=/n3/.test(t),a=i||s;(this._supportsNamedGraphs=!(r||o))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||n||i||o),this._isImpliedBy=e.isImpliedBy,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 On({lineMode:a,n3:o,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){ti=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 s=this._n3Mode;this._contextStack.push({type:e,subject:r,predicate:n,object:i,graph:t,inverse:!!s&&this._inversePredicate,blankPrefix:s?this._prefixes._:"",quantified:s?this._quantified:null}),s&&(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,s=this._contextStack,o=s[s.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!==s.length&&"list"===s[s.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===o.predicate?o.subject=r:o.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 s=this._predicate,o=this._object;this._subject=this._factory.quad(n,s,o,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=ni}_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,s=0,o="/";for(;n<t;){switch(o){case":":if(i<0&&"/"===e[++n]&&"/"===e[++n])for(;(i=n+1)<t&&"/"!==e[i];)n=i;break;case"?":case"#":n=t;break;case"/":if("."===e[n+1])switch(o=e[1+ ++n],o){case"/":r+=e.substring(s,n-1),s=n+1;break;case void 0:case"?":case"#":return r+e.substring(s,n)+e.substr(n+1);case".":if(o=e[1+ ++n],void 0===o||"/"===o||"?"===o||"#"===o){if(r+=e.substring(s,n-2),(s=r.lastIndexOf("/"))>=i&&(r=r.substr(0,s)),"/"!==o)return`${r}/${e.substr(n+1)}`;s=n+1}}}o=e[++n]}return r+e.substring(s)}parse(e,t,r){let n,i,s;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(n=t.onQuad,i=t.onPrefix,s=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${ti++}_`,this._prefixCallback=i||ni,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 o=(e,t)=>{null!==e?(this._callback(e),this._callback=ni):this._readCallback&&(this._readCallback=this._readCallback(t))};s&&(this._lexer.comments=!0,o=(e,t)=>{null!==e?(this._callback(e),this._callback=ni):this._readCallback&&("comment"===t.type?s(t.value):this._readCallback=this._readCallback(t))}),this._callback=n,this._lexer.tokenize(e,o)}}function ni(){}function ii(e,t){e._factory=t,e.DEFAULTGRAPH=t.defaultGraph(),e.RDF_FIRST=t.namedNode(kn.rdf.first),e.RDF_REST=t.namedNode(kn.rdf.rest),e.RDF_NIL=t.namedNode(kn.rdf.nil),e.N3_FORALL=t.namedNode(kn.r.forAll),e.N3_FORSOME=t.namedNode(kn.r.forSome),e.ABBREVIATIONS={a:t.namedNode(kn.rdf.type),"=":t.namedNode(kn.owl.sameAs),">":t.namedNode(kn.log.implies),"<":t.namedNode(kn.log.isImpliedBy)},e.QUANTIFIERS_GRAPH=t.namedNode("urn:n3:quantifiers")}if(ii(ri.prototype,Hn),void 0===si)var si={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12};class oi{constructor(e,t){this.options=t||{},this.kb=e,this.target=t.target||{graph:{subjects:{},prefixes:{},terms:{}}},this.blankNodes=[],this.htmlOptions={selfClosing:"br img input area base basefont col colgroup source wbr isindex link meta param hr"},this.theOne="_:"+(new Date).getTime(),this.language=null,this.vocabulary=null,this.blankCounter=0,this.langAttributes=[{namespaceURI:"http://www.w3.org/XML/1998/namespace",localName:"lang"}],this.inXHTMLMode=!1,this.absURIRE=/[\w\_\-]+:\S+/,this.finishedHandlers=[],this.init()}addTriple(e,t,r,n){var i,s,o,a;i=void 0===t?wr.namedNode(this.options.base):this.toRDFNodeObject(t),o=this.toRDFNodeObject(r),s=this.toRDFNodeObject(n),a=wr.namedNode(this.options.base),this.kb.add(i,o,s,a)}ancestorPath(e){for(var t="";e&&e.nodeType!==si.DOCUMENT_NODE;)t="/"+e.localName+t,e=e.parentNode;return t}copyMappings(e){var t={};for(var r in e)t[r]=e[r];return t}copyProperties(){}deriveDateTimeType(e){for(var t=0;t<oi.dateTimeTypes.length;t++){var r=oi.dateTimeTypes[t].pattern.exec(e);if(r&&r[0].length===e.length)return oi.dateTimeTypes[t].type}return null}init(){}newBlankNode(){return this.blankCounter++,"_:"+this.blankCounter}newSubjectOrigin(e,t){}parseCURIE(e,t,r){var n,i=e.indexOf(":");if(i>=0){var s=e.substring(0,i);if(""===s)return(n=t[""])?n+e.substring(i+1):null;if("_"===s)return"_:"+e.substring(i+1);if(oi.NCNAME.test(s)&&(n=t[s]))return n+e.substring(i+1)}return null}parseCURIEOrURI(e,t,r){var n=this.parseCURIE(e,t,r);return n||this.resolveAndNormalize(r,e)}parsePredicate(e,t,r,n,i,s){if(""===e)return null;var o=this.parseTermOrCURIEOrAbsURI(e,t,s?null:r,n,i);return o&&0===o.indexOf("_:")?null:o}parsePrefixMappings(e,t){for(var r=this.tokenize(e),n=null,i=0;i<r.length;i++)":"===r[i][r[i].length-1]?n=r[i].substring(0,r[i].length-1):n&&(t[n]=this.options.base?pr.join(r[i],this.options.base):r[i],n=null)}static parseRDFaDOM(e,t,r){var n=new oi(t,{base:r});e.baseURI||(e.baseURI=r),n.process(e,{baseURI:r})}parseSafeCURIEOrCURIEOrURI(e,t,r){return"["===(e=this.trim(e)).charAt(0)&&"]"===e.charAt(e.length-1)?0===(e=(e=e.substring(1,e.length-1)).trim(e)).length?null:"_:"===e?this.theOne:this.parseCURIE(e,t,r):this.parseCURIEOrURI(e,t,r)}parseTermOrCURIEOrAbsURI(e,t,r,n,i){e=this.trim(e);var s=this.parseCURIE(e,n,i);if(s)return s;if(r){if(t&&!this.absURIRE.exec(e))return t+e;var o=r[e];if(o)return o;if(o=r[e.toLowerCase()])return o}return this.absURIRE.exec(e)?this.resolveAndNormalize(i,e):null}parseTermOrCURIEOrURI(e,t,r,n,i){e=this.trim(e);var s=this.parseCURIE(e,n,i);if(s)return s;var o=r[e];return o||((o=r[e.toLowerCase()])?o:t&&!this.absURIRE.exec(e)?t+e:this.resolveAndNormalize(i,e))}parseURI(e){return e}process(e,t){var r;t=t||{},e.nodeType===si.DOCUMENT_NODE?(e.baseURI&&!t.baseURI&&(t.baseURI=e.baseURI),r=e.baseURI,(e=e.documentElement).baseURI||(e.baseURI=r),this.setContext(e)):e.parentNode.nodeType===si.DOCUMENT_NODE&&this.setContext(e);var n=[],i=function(e){if(!e&&t&&t.baseURI)return t.baseURI;var r=e.indexOf("#");return r>=0&&(e=e.substring(0,r)),t&&t.baseURIMap&&(e=t.baseURIMap(e)),e};for(n.push({current:e,context:this.push(null,i(e.baseURI))});n.length>0;){var s=n.shift();if(s.parent){if(s.context.parent&&s.context.parent.listMapping===s.listMapping)continue;for(let e in s.listMapping){var o=s.listMapping[e];if(0!==o.length){var a=[];for(let e=0;e<o.length;e++)a.push(this.newBlankNode());for(let e=0;e<a.length;e++)this.addTriple(s.parent,a[e],"http://www.w3.org/1999/02/22-rdf-syntax-ns#first",o[e]),this.addTriple(s.parent,a[e],"http://www.w3.org/1999/02/22-rdf-syntax-ns#rest",{type:oi.objectURI,value:e+1<a.length?a[e+1]:"http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"});this.addTriple(s.parent,s.subject,e,{type:oi.objectURI,value:a[0]})}else this.addTriple(s.parent,s.subject,e,{type:oi.objectURI,value:"http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"})}}else{var u=s.current,c=s.context,h=!1,l=null,d=null,f=null,p=c.prefixes,g=!1,y=[],v=c.listMapping,m=!c.parent,w=c.language,b=c.vocabulary;r=this.parseURI(i(u.baseURI)),u.item=null;var _=u.getAttributeNode("vocab");if(_){let e=this.trim(_.value);if(e.length>0){b=e;var S=r.spec;this.addTriple(u,S,"http://www.w3.org/ns/rdfa#usesVocabulary",{type:oi.objectURI,value:b})}else b=this.vocabulary}for(var E=0;E<u.attributes.length;E++){var x=u.attributes[E];if("x"===x.nodeName.charAt(0)&&0===x.nodeName.indexOf("xmlns:")){g||(p=this.copyMappings(p),g=!0);var A=x.nodeName.substring(6),F=oi.trim(x.value);p[A]=this.options.base?pr.join(F,this.options.base):F}}var T=u.getAttributeNode("prefix");T&&(g||(p=this.copyMappings(p),g=!0),this.parsePrefixMappings(T.value,p));var k=null;for(let e=0;!k&&e<this.langAttributes.length;e++)k=u.getAttributeNodeNS(this.langAttributes[e].namespaceURI,this.langAttributes[e].localName);if(k){let e=oi.trim(k.value);w=e.length>0?e:null}var I,C,R=u.getAttributeNode("rel"),P=u.getAttributeNode("rev"),N=u.getAttributeNode("typeof"),U=u.getAttributeNode("property"),O=u.getAttributeNode("datatype"),L=this.inHTMLMode?u.getAttributeNode("datetime"):null,D=u.getAttributeNode("content"),j=u.getAttributeNode("about"),M=u.getAttributeNode("src"),B=u.getAttributeNode("resource"),H=u.getAttributeNode("href"),q=u.getAttributeNode("inlist"),K=[];if(R){C=this.tokenize(R.value);for(let e=0;e<C.length;e++)(I=this.parsePredicate(C[e],b,c.terms,p,r,this.inHTMLMode&&null!==U))&&K.push(I)}var V=[];if(P){C=this.tokenize(P.value);for(let e=0;e<C.length;e++)(I=this.parsePredicate(C[e],b,c.terms,p,r,this.inHTMLMode&&U))&&V.push(I)}if(this.inHTMLMode&&(R||P)&&U&&(0===K.length&&(R=null),0===V.length&&(P=null)),R||P?(j&&(l=this.parseSafeCURIEOrCURIEOrURI(j.value,p,r)),N&&(f=l),l||(u.parentNode.nodeType===si.DOCUMENT_NODE?l=i(u.baseURI):c.parentObject&&(l=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject)),B&&(d=this.parseSafeCURIEOrCURIEOrURI(B.value,p,r)),d||(H?d=this.resolveAndNormalize(r,encodeURI(H.value)):M?d=this.resolveAndNormalize(r,encodeURI(M.value)):!N||j||this.inXHTMLMode&&("head"===u.localName||"body"===u.localName)||(d=this.newBlankNode())),!N||j||!this.inXHTMLMode||"head"!==u.localName&&"body"!==u.localName?N&&!j&&(f=d):f=l):!U||D||O?(j&&(l=this.parseSafeCURIEOrCURIEOrURI(j.value,p,r)),!l&&B&&(l=this.parseSafeCURIEOrCURIEOrURI(B.value,p,r)),!l&&H&&(l=this.resolveAndNormalize(r,encodeURI(H.value))),!l&&M&&(l=this.resolveAndNormalize(r,encodeURI(M.value))),l||(u.parentNode.nodeType===si.DOCUMENT_NODE?l=i(u.baseURI):!this.inXHTMLMode&&!this.inHTMLMode||"head"!==u.localName&&"body"!==u.localName?N?l=this.newBlankNode():c.parentObject&&(l=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject,U||(h=!0)):l=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject),N&&(f=l)):(j&&(l=this.parseSafeCURIEOrCURIEOrURI(j.value,p,r),N&&(f=l)),l||u.parentNode.nodeType!==si.DOCUMENT_NODE?!l&&c.parentObject&&(l=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject):(l=i(u.baseURI),N&&(f=l)),N&&!f&&(B&&(f=this.parseSafeCURIEOrCURIEOrURI(B.value,p,r)),!f&&H&&(f=this.resolveAndNormalize(r,encodeURI(H.value))),!f&&M&&(f=this.resolveAndNormalize(r,encodeURI(M.value))),f||!this.inXHTMLMode&&!this.inHTMLMode||"head"!==u.localName&&"body"!==u.localName||(f=l),f||(f=this.newBlankNode()),d=f)),l&&(j||B||f)){var $=l;N&&!j&&!B&&d&&($=d),this.newSubjectOrigin(u,$)}if(f){C=this.tokenize(N.value);for(let e=0;e<C.length;e++){var W=this.parseTermOrCURIEOrAbsURI(C[e],b,c.terms,p,r);W&&this.addTriple(u,f,oi.typeURI,{type:oi.objectURI,value:W})}}if(l&&l!==c.parentObject&&(v={},m=!0),d){if(R&&q)for(let e=0;e<K.length;e++){let t=v[K[e]];t||(t=[],v[K[e]]=t),t.push({type:oi.objectURI,value:d})}else if(R)for(let e=0;e<K.length;e++)this.addTriple(u,l,K[e],{type:oi.objectURI,value:d});if(P)for(let e=0;e<V.length;e++)this.addTriple(u,d,V[e],{type:oi.objectURI,value:l})}else{if(l&&!d&&(R||P)&&(d=this.newBlankNode()),R&&q)for(let e=0;e<K.length;e++){let t=v[K[e]];t||(t=[],v[I]=t),y.push({predicate:K[e],list:t})}else if(R)for(let e=0;e<K.length;e++)y.push({predicate:K[e],forward:!0});if(P)for(let e=0;e<V.length;e++)y.push({predicate:V[e],forward:!1})}if(U){var J=null,z=null;O?(J=""===O.value?oi.PlainLiteralURI:this.parseTermOrCURIEOrAbsURI(O.value,b,c.terms,p,r),z=L&&!D?L.value:J===oi.XMLLiteralURI||J===oi.HTMLLiteralURI?null:D?D.value:u.textContent):D?(J=oi.PlainLiteralURI,z=D.value):L?(z=L.value,(J=oi.deriveDateTimeType(z))||(J=oi.PlainLiteralURI)):R||P||(B&&(z=this.parseSafeCURIEOrCURIEOrURI(B.value,p,r)),!z&&H?z=this.resolveAndNormalize(r,encodeURI(H.value)):!z&&M&&(z=this.resolveAndNormalize(r,encodeURI(M.value))),z&&(J=oi.objectURI)),J||(N&&!j?(J=oi.objectURI,z=f):(z=u.textContent,this.inHTMLMode&&"time"===u.localName&&(J=oi.deriveDateTimeType(z)),J||(J=oi.PlainLiteralURI))),C=this.tokenize(U.value);for(let e=0;e<C.length;e++){let t=this.parsePredicate(C[e],b,c.terms,p,r);if(t)if(q){let e=v[t];e||(e=[],v[t]=e),e.push(J===oi.XMLLiteralURI||J===oi.HTMLLiteralURI?{type:J,value:u.childNodes}:{type:J||oi.PlainLiteralURI,value:z,language:w})}else J===oi.XMLLiteralURI||J===oi.HTMLLiteralURI?this.addTriple(u,l,t,{type:J,value:u.childNodes}):this.addTriple(u,l,t,{type:J||oi.PlainLiteralURI,value:z,language:w})}}if(l&&!h)for(let e=0;e<c.incomplete.length;e++)c.incomplete[e].list?c.incomplete[e].list.push({type:oi.objectURI,value:l}):c.incomplete[e].forward?this.addTriple(u,c.subject,c.incomplete[e].predicate,{type:oi.objectURI,value:l}):this.addTriple(u,l,c.incomplete[e].predicate,{type:oi.objectURI,value:c.subject});var X=null,G=l;h?((X=this.push(c,c.subject)).parentObject=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject,X.incomplete=c.incomplete,X.language=w,X.prefixes=p,X.vocabulary=b):((X=this.push(c,l)).parentObject=d||l||c.subject,X.prefixes=p,X.incomplete=y,d&&(G=d,v={},m=!0),X.listMapping=v,X.language=w,X.vocabulary=b),m&&n.unshift({parent:u,context:c,subject:G,listMapping:v});for(var Y=u.lastChild;Y;Y=Y.previousSibling)Y.nodeType===si.ELEMENT_NODE&&n.unshift({current:Y,context:X})}}this.inHTMLMode&&this.copyProperties();for(let t=0;t<this.finishedHandlers.length;t++)this.finishedHandlers[t](e)}push(e,t){return{parent:e,subject:t||(e?e.subject:null),parentObject:null,incomplete:[],listMapping:e?e.listMapping:{},language:e?e.language:this.language,prefixes:e?e.prefixes:this.target.graph.prefixes,terms:e?e.terms:this.target.graph.terms,vocabulary:e?e.vocabulary:this.vocabulary}}resolveAndNormalize(e,t){return pr.join(t,e)}setContext(e){"html"===e.localName&&"XHTML+RDFa 1.1"===e.getAttribute("version")?this.setXHTMLContext():"html"===e.localName||"http://www.w3.org/1999/xhtml"===e.namespaceURI?"undefined"!=typeof document&&document.doctype?"-//W3C//DTD XHTML+RDFa 1.0//EN"===document.doctype.publicId&&"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"===document.doctype.systemId?(console.log("WARNING: RDF 1.0 is not supported. Defaulting to HTML5 mode."),this.setHTMLContext()):"-//W3C//DTD XHTML+RDFa 1.1//EN"===document.doctype.publicId&&"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd"===document.doctype.systemId?this.setXHTMLContext():this.setHTMLContext():this.setHTMLContext():this.setXMLContext()}setHTMLContext(){this.setInitialContext(),this.langAttributes=[{namespaceURI:"http://www.w3.org/XML/1998/namespace",localName:"lang"},{namespaceURI:null,localName:"lang"}],this.inXHTMLMode=!1,this.inHTMLMode=!0}setInitialContext(){this.vocabulary=null,this.langAttributes=[{namespaceURI:"http://www.w3.org/XML/1998/namespace",localName:"lang"}]}setXHTMLContext(){this.setInitialContext(),this.inXHTMLMode=!0,this.inHTMLMode=!1,this.langAttributes=[{namespaceURI:"http://www.w3.org/XML/1998/namespace",localName:"lang"},{namespaceURI:null,localName:"lang"}],this.target.graph.terms.alternate="http://www.w3.org/1999/xhtml/vocab#alternate",this.target.graph.terms.appendix="http://www.w3.org/1999/xhtml/vocab#appendix",this.target.graph.terms.bookmark="http://www.w3.org/1999/xhtml/vocab#bookmark",this.target.graph.terms.cite="http://www.w3.org/1999/xhtml/vocab#cite",this.target.graph.terms.chapter="http://www.w3.org/1999/xhtml/vocab#chapter",this.target.graph.terms.contents="http://www.w3.org/1999/xhtml/vocab#contents",this.target.graph.terms.copyright="http://www.w3.org/1999/xhtml/vocab#copyright",this.target.graph.terms.first="http://www.w3.org/1999/xhtml/vocab#first",this.target.graph.terms.glossary="http://www.w3.org/1999/xhtml/vocab#glossary",this.target.graph.terms.help="http://www.w3.org/1999/xhtml/vocab#help",this.target.graph.terms.icon="http://www.w3.org/1999/xhtml/vocab#icon",this.target.graph.terms.index="http://www.w3.org/1999/xhtml/vocab#index",this.target.graph.terms.last="http://www.w3.org/1999/xhtml/vocab#last",this.target.graph.terms.license="http://www.w3.org/1999/xhtml/vocab#license",this.target.graph.terms.meta="http://www.w3.org/1999/xhtml/vocab#meta",this.target.graph.terms.next="http://www.w3.org/1999/xhtml/vocab#next",this.target.graph.terms.prev="http://www.w3.org/1999/xhtml/vocab#prev",this.target.graph.terms.previous="http://www.w3.org/1999/xhtml/vocab#previous",this.target.graph.terms.section="http://www.w3.org/1999/xhtml/vocab#section",this.target.graph.terms.stylesheet="http://www.w3.org/1999/xhtml/vocab#stylesheet",this.target.graph.terms.subsection="http://www.w3.org/1999/xhtml/vocab#subsection",this.target.graph.terms.start="http://www.w3.org/1999/xhtml/vocab#start",this.target.graph.terms.top="http://www.w3.org/1999/xhtml/vocab#top",this.target.graph.terms.up="http://www.w3.org/1999/xhtml/vocab#up",this.target.graph.terms.p3pv1="http://www.w3.org/1999/xhtml/vocab#p3pv1",this.target.graph.terms.related="http://www.w3.org/1999/xhtml/vocab#related",this.target.graph.terms.role="http://www.w3.org/1999/xhtml/vocab#role",this.target.graph.terms.transformation="http://www.w3.org/1999/xhtml/vocab#transformation"}setXMLContext(){this.setInitialContext(),this.inXHTMLMode=!1,this.inHTMLMode=!1}tokenize(e){return this.trim(e).split(/\s+/)}static tokenize(e){return this.trim(e).split(/\s+/)}toRDFNodeObject(e){if(void 0!==e){if("string"==typeof e)return"_:"===e.substring(0,2)?(void 0===this.blankNodes[e.substring(2)]&&(this.blankNodes[e.substring(2)]=new tr(e.substring(2))),this.blankNodes[e.substring(2)]):wr.namedNode(e);switch(e.type){case oi.objectURI:return"_:"===e.value.substring(0,2)?(void 0===this.blankNodes[e.value.substring(2)]&&(this.blankNodes[e.value.substring(2)]=new tr(e.value.substring(2))),this.blankNodes[e.value.substring(2)]):wr.namedNode(e.value);case oi.PlainLiteralURI:return new sr(e.value,e.language||"");case oi.XMLLiteralURI:case oi.HTMLLiteralURI:var t="";return Object.keys(e.value).forEach(r=>{t+=Sr.domToString(e.value[r],this.htmlOptions)}),new sr(t,"",new rr.A(e.type));default:return new sr(e.value,"",new rr.A(e.type))}}}trim(e){return e.replace(/^\s\s*/,"").replace(/\s\s*$/,"")}static trim(e){return e.replace(/^\s\s*/,"").replace(/\s\s*$/,"")}}oi.XMLLiteralURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral",oi.HTMLLiteralURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML",oi.PlainLiteralURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral",oi.objectURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#object",oi.typeURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",oi.nameChar="[-A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�က0-F.0-9·̀-ͯ‿-⁀]",oi.nameStartChar="[A-Za-zÀ-ÖØ-öø-ÿĀ-ıĴ-ľŁ-ňŊ-žƀ-ǃǍ-ǰǴ-ǵǺ-ȗɐ-ʨʻ-ˁΆΈ-ΊΌΎ-ΡΣ-ώϐ-ϖϚϜϞϠϢ-ϳЁ-ЌЎ-яё-ќў-ҁҐ-ӄӇ-ӈӋ-ӌӐ-ӫӮ-ӵӸ-ӹԱ-Ֆՙա-ֆא-תװ-ײء-غف-يٱ-ڷں-ھۀ-ێې-ۓەۥ-ۦअ-हऽक़-ॡঅ-ঌএ-ঐও-নপ-রলশ-হড়-ঢ়য়-ৡৰ-ৱਅ-ਊਏ-ਐਓ-ਨਪ-ਰਲ-ਲ਼ਵ-ਸ਼ਸ-ਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઋઍએ-ઑઓ-નપ-રલ-ળવ-હઽૠଅ-ଌଏ-ଐଓ-ନପ-ରଲ-ଳଶ-ହଽଡ଼-ଢ଼ୟ-ୡஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-வஷ-ஹఅ-ఌఎ-ఐఒ-నప-ళవ-హౠ-ౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹೞೠ-ೡഅ-ഌഎ-ഐഒ-നപ-ഹൠ-ൡก-ฮะา-ำเ-ๅກ-ຂຄງ-ຈຊຍດ-ທນ-ຟມ-ຣລວສ-ຫອ-ຮະາ-ຳຽເ-ໄཀ-ཇཉ-ཀྵႠ-Ⴥა-ჶᄀᄂ-ᄃᄅ-ᄇᄉᄋ-ᄌᄎ-ᄒᄼᄾᅀᅌᅎᅐᅔ-ᅕᅙᅟ-ᅡᅣᅥᅧᅩᅭ-ᅮᅲ-ᅳᅵᆞᆨᆫᆮ-ᆯᆷ-ᆸᆺᆼ-ᇂᇫᇰᇹḀ-ẛẠ-ỹἀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼΩK-Å℮ↀ-ↂぁ-ゔァ-ヺㄅ-ㄬ가-힣一-龥〇〡-〩_]",oi.NCNAME=new RegExp("^"+oi.nameStartChar+oi.nameChar+"*$"),oi.dateTimeTypes=[{pattern:/-?P(?:[0-9]+Y)?(?:[0-9]+M)?(?:[0-9]+D)?(?:T(?:[0-9]+H)?(?:[0-9]+M)?(?:[0-9]+(?:\.[0-9]+)?S)?)?/,type:"http://www.w3.org/2001/XMLSchema#duration"},{pattern:/-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]-[0-9][0-9]T(?:[0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]+)?(?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/,type:"http://www.w3.org/2001/XMLSchema#dateTime"},{pattern:/-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]-[0-9][0-9](?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/,type:"http://www.w3.org/2001/XMLSchema#date"},{pattern:/(?:[0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]+)?(?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/,type:"http://www.w3.org/2001/XMLSchema#time"},{pattern:/-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]/,type:"http://www.w3.org/2001/XMLSchema#gYearMonth"},{pattern:/-?[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9]/,type:"http://www.w3.org/2001/XMLSchema#gYear"}];const ai=oi.parseRDFaDOM;class ui{constructor(e){this.store=e,this.bnodes={},this.why=null,this.reify=!1}frameFactory(e,t,r){return{NODE:1,ARC:2,parent:t,parser:e,store:e.store,element:r,lastChild:0,base:null,lang:null,node:null,nodeType:null,listIndex:1,rdfid:null,datatype:null,collection:!1,terminateFrame:function(){this.collection&&this.node.close()},addSymbol:function(e,t){t=pr.join(t,this.base),this.node=this.store.sym(t),this.nodeType=e},loadTriple:function(){if(this.parent.parent.collection?this.parent.parent.node.append(this.node):this.store.add(this.parent.parent.node,this.parent.node,this.node,this.parser.why),null!=this.parent.rdfid){var e=this.store.sym(pr.join("#"+this.parent.rdfid,this.base));this.store.add(e,this.store.sym(ui.ns.RDF+"type"),this.store.sym(ui.ns.RDF+"Statement"),this.parser.why),this.store.add(e,this.store.sym(ui.ns.RDF+"subject"),this.parent.parent.node,this.parser.why),this.store.add(e,this.store.sym(ui.ns.RDF+"predicate"),this.parent.node,this.parser.why),this.store.add(e,this.store.sym(ui.ns.RDF+"object"),this.node,this.parser.why)}},isTripleToLoad:function(){return null!=this.parent&&null!=this.parent.parent&&this.nodeType===this.NODE&&this.parent.nodeType===this.ARC&&this.parent.parent.nodeType===this.NODE},addNode:function(e){this.addSymbol(this.NODE,e),this.isTripleToLoad()&&this.loadTriple()},addCollection:function(){this.nodeType=this.NODE,this.node=this.store.collection(),this.collection=!0,this.isTripleToLoad()&&this.loadTriple()},addCollectionArc:function(){this.nodeType=this.ARC},addBNode:function(e){null!=e?null!=this.parser.bnodes[e]?this.node=this.parser.bnodes[e]:this.node=this.parser.bnodes[e]=this.store.bnode():this.node=this.store.bnode(),this.nodeType=this.NODE,this.isTripleToLoad()&&this.loadTriple()},addArc:function(e){e===ui.ns.RDF+"li"&&(e=ui.ns.RDF+"_"+this.parent.listIndex,this.parent.listIndex++),this.addSymbol(this.ARC,e)},addLiteral:function(e){this.parent.datatype&&this.parent.datatype!==ui.ns.RDF+"langString"?this.node=this.store.literal(e,this.store.sym(this.parent.datatype)):this.node=this.store.literal(e,this.lang),this.nodeType=this.NODE,this.isTripleToLoad()&&this.loadTriple()}}}getAttributeNodeNS(e,t,r){var n=null;if(e.getAttributeNodeNS)n=e.getAttributeNodeNS(t,r);else for(var i,s=e.attributes,o=0;o<s.length;++o)if((i=s[o]).namespaceURI===t&&(i.prefix?i.prefix+":"+r:r)===i.nodeName){n=i;break}return n}parse(e,t,r){var n,i=e.childNodes;if(this.cleanParser(),e.nodeType===ui.nodeType.DOCUMENT){for(var s=0;s<i.length;s++)if(i[s].nodeType===ui.nodeType.ELEMENT){n=i[s];break}}else{if(e.nodeType!==ui.nodeType.ELEMENT)throw new Error("RDFParser: can't find root in "+t+". Halting. ");n=e}this.why=r;var o=this.frameFactory(this);return this.base=t,o.base=t,o.lang=null,this.parseDOM(this.buildFrame(o,n)),!0}parseDOM(e){for(var t,r=function(e){var t="";if(null==e.namespaceURI)throw new Error("RDF/XML syntax error: No namespace for "+e.localName+" in "+this.base);return e.namespaceURI&&(t+=e.namespaceURI),e.localName?t+=e.localName:e.nodeName&&(e.nodeName.indexOf(":")>=0?t+=e.nodeName.split(":")[1]:t+=e.nodeName),t}.bind(this),n=!0;e.parent;){var i=e.element,s=i.attributes;if(i.nodeType===ui.nodeType.TEXT||i.nodeType===ui.nodeType.CDATA_SECTION)e.parent.nodeType===e.NODE&&(e.addArc(ui.ns.RDF+"value"),e=this.buildFrame(e)),e.addLiteral(i.nodeValue);else if(r(i)!==ui.ns.RDF+"RDF")if(e.parent&&e.parent.collection&&(e.addCollectionArc(),(e=this.buildFrame(e,e.element)).parent.element=null),e.parent&&e.parent.nodeType&&e.parent.nodeType!==e.ARC){e.addArc(r(i)),this.reify&&(t=this.getAttributeNodeNS(i,ui.ns.RDF,"ID"))&&(e.rdfid=t.nodeValue,i.removeAttributeNode(t));var o=this.getAttributeNodeNS(i,ui.ns.RDF,"parseType"),a=this.getAttributeNodeNS(i,ui.ns.RDF,"datatype");if(a&&(e.datatype=a.nodeValue,i.removeAttributeNode(a)),o){var u=o.nodeValue;"Literal"===u?(e.datatype=ui.ns.RDF+"XMLLiteral",(e=this.buildFrame(e)).addLiteral(i.innerHTML||i.childNodes),n=!1):"Resource"===u?((e=this.buildFrame(e,e.element)).parent.element=null,e.addBNode()):"Collection"===u&&((e=this.buildFrame(e,e.element)).parent.element=null,e.addCollection()),i.removeAttributeNode(o)}if(0!==s.length){var c=this.getAttributeNodeNS(i,ui.ns.RDF,"resource"),h=this.getAttributeNodeNS(i,ui.ns.RDF,"nodeID");e=this.buildFrame(e),c?(e.addNode(c.nodeValue),i.removeAttributeNode(c)):h?(e.addBNode(h.nodeValue),i.removeAttributeNode(h)):e.addBNode();for(var l=s.length-1;l>=0;l--){var d=this.buildFrame(e);d.addArc(r(s[l])),r(s[l])===ui.ns.RDF+"type"?this.buildFrame(d).addNode(s[l].nodeValue):this.buildFrame(d).addLiteral(s[l].nodeValue)}}else 0===i.childNodes.length&&this.buildFrame(e).addLiteral("")}else{var f=this.getAttributeNodeNS(i,ui.ns.RDF,"about");if(t=this.getAttributeNodeNS(i,ui.ns.RDF,"ID"),f&&t)throw new Error("RDFParser: "+i.nodeName+" has both rdf:id and rdf:about. Halting. Only one of these properties may be specified on a node.");if(!f&&t)e.addNode("#"+t.nodeValue),i.removeAttributeNode(t);else if(null==f&&null==t){var p=this.getAttributeNodeNS(i,ui.ns.RDF,"nodeID");p?(e.addBNode(p.nodeValue),i.removeAttributeNode(p)):e.addBNode()}else e.addNode(f.nodeValue),i.removeAttributeNode(f);var g=this.getAttributeNodeNS(i,ui.ns.RDF,"type");ui.ns.RDF+"Description"!==r(i)&&(g={nodeValue:r(i)}),null!=g&&(this.store.add(e.node,this.store.sym(ui.ns.RDF+"type"),this.store.sym(pr.join(g.nodeValue,e.base)),this.why),g.nodeName&&i.removeAttributeNode(g));for(var y=s.length-1;y>=0;y--)this.store.add(e.node,this.store.sym(r(s[y])),this.store.literal(s[y].nodeValue,e.lang),this.why)}for(i=e.element;e.parent;){for(var v=e;null==i;)i=(e=e.parent).element;var m=i.childNodes&&i.childNodes[e.lastChild];if(m&&n){if((m.nodeType===ui.nodeType.ELEMENT||m.nodeType===ui.nodeType.TEXT||m.nodeType===ui.nodeType.CDATA_SECTION)&&(m.nodeType!==ui.nodeType.TEXT&&m.nodeType!==ui.nodeType.CDATA_SECTION||1===i.childNodes.length)){e.lastChild++,e=this.buildFrame(v,i.childNodes[e.lastChild-1]);break}e.lastChild++}else{if(e.terminateFrame(),!(e=e.parent))break;i=e.element,n=!0}}}}cleanParser(){this.bnodes={},this.why=null}buildFrame(e,t){var r=this.frameFactory(this,e,t);if(e&&(r.base=e.base,r.lang=e.lang),!t||t.nodeType===ui.nodeType.TEXT||t.nodeType===ui.nodeType.CDATA_SECTION)return r;var n=t.attributes,i=t.getAttributeNode("xml:base");null!=i&&(r.base=i.nodeValue,t.removeAttribute("xml:base"));var s=t.getAttributeNode("xml:lang");null!=s&&(r.lang=s.nodeValue,t.removeAttribute("xml:lang"));for(var o=n.length-1;o>=0;o--)if("xml"===n[o].nodeName.substr(0,3)){if("xmlns:"===n[o].name.slice(0,6)){var a=n[o].nodeValue;this.base&&(a=pr.join(a,this.base)),this.store.setPrefixForURI(n[o].name.slice(6),a)}t.removeAttributeNode(n[o])}return r}}function ci(e,t,r){var n,i,s,o=["INSERT","DELETE","WHERE"],a=_r("http://www.w3.org/ns/pim/patch#"),u=fn(t,t,r,r,null,null,"",null),c={},h=function(e,t,r,n,i){return"Line "+(t+1)+" of <"+e+">: Bad syntax:\n "+i+'\n at: "'+r.slice(n,n+30)+'"'};n=0;var l=t.sym(r+"#query");for(c.query=l;;){if((i=u.skipSpace(e,n))<0)return c;if(";"===e[i]){if((n=u.skipSpace(e,i+1))<0)return c;i=n}var d=!1;for(s=0;s<o.length;s++){var f=o[s];if(e.slice(i,i+f.length)===f){if((n=u.skipSpace(e,i+f.length))<0)throw h(u._thisDoc,u.lines,e,i+f.length,"found EOF, needed {...} after "+f);if(("INSERT"===f||"DELETE"===f)&&"DATA"===e.slice(n,n+4)){if((i=u.skipSpace(e,n+4))<0)throw h(u._thisDoc,u.lines,e,n+4,"needed {...} after INSERT DATA "+f);n=i}var p=[];if((i=u.node(e,n,p))<0)throw h(u._thisDoc,u.lines,e,n,"bad syntax or EOF in {...} after "+f);c[f.toLowerCase()]=p[0],t.add(l,a(f.toLowerCase()),p[0]),d=!0,n=i}}if(!d&&"@prefix"===e.slice(i,i+7)){if((n=u.directive(e,i))<0)throw h(u._thisDoc,u.lines,e,n,"bad syntax or EOF after @prefix ");n=u.checkDot(e,n),d=!0}if(!d)throw h(u._thisDoc,u.lines,e,i,"Unknown syntax at start of statememt: '"+e.slice(i).slice(0,20)+"'")}}function hi(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"text/turtle",i=arguments.length>4?arguments[4]:void 0;n=n||er.sT,n=n.split(";")[0];try{if(n===er.ny||n===er.sT)fn(t,t,r,r,null,null,"",null).loadBuf(e),o();else if(n===er.JG){new ui(t).parse(Sr.parseXML(e),r,t.sym(r)),o()}else if(n===er.H)ai(Sr.parseXML(e,{contentType:er.H}),t,r),o();else if(n===er.lc)ai(Sr.parseXML(e,{contentType:er.lc}),t,r),o();else if(n===er.K9||n===er.Fn)ci(e,t,r),o();else if(n===er.i2)bn(e,t,r).then(o).catch(a);else{if(n!==er._0&&n!==er.BR)throw void 0===n?new Error("contentType is undefined"):new Error("Don't know how to parse "+n+" yet");var s=new ri({factory:mn});!function(e,r){e&&i(e,t);try{s.parse(r,u)}catch(e){i(e,t)}}(null,e)}}catch(e){a(e)}function o(){i&&i(null,t)}function a(e){if(n!==er.i2||n!==er._0||n!==er.BR){if(!i){let t=new Error(e+" while trying to parse <"+r+"> as "+n);throw t.cause=e,t}i(e,t)}}function u(e,r){r?t.add(r.subject,r.predicate,r.object,r.graph):i(e,t)}hi.handled={"text/n3":!0,"text/turtle":!0,"application/rdf+xml":!0,"application/xhtml+xml":!0,"text/html":!0,"application/sparql-update":!0,"application/sparql-update-single-match":!0,"application/ld+json":!0,"application/nquads":!0,"application/n-quads":!0}}(0,Yt.A)(ui,"ns",{RDF:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",RDFS:"http://www.w3.org/2000/01/rdf-schema#"}),(0,Yt.A)(ui,"nodeType",{ELEMENT:1,ATTRIBUTE:2,TEXT:3,CDATA_SECTION:4,ENTITY_REFERENCE:5,ENTITY:6,PROCESSING_INSTRUCTION:7,COMMENT:8,DOCUMENT:9,DOCUMENT_TYPE:10,DOCUMENT_FRAGMENT:11,NOTATION:12});var li=a(4945),di=a.n(li),fi=a(2931);const pi={"text/n3":!0,"text/turtle":!0,"application/rdf+xml":!0,"application/xhtml+xml":!0,"text/html":!0,"application/ld+json":!0},gi={rdf:er.JG,owl:er.JG,n3:"text/n3",ttl:"text/turtle",nt:"text/n3",acl:"text/n3",html:"text/html",xml:"text/xml"},yi=e=>({link:_r("http://www.w3.org/2007/ont/link#",e),http:_r("http://www.w3.org/2007/ont/http#",e),httph:_r("http://www.w3.org/2007/ont/httph#",e),rdf:_r("http://www.w3.org/1999/02/22-rdf-syntax-ns#",e),rdfs:_r("http://www.w3.org/2000/01/rdf-schema#",e),dc:_r("http://purl.org/dc/elements/1.1/",e),ldp:_r("http://www.w3.org/ns/ldp#",e)}),vi=yi();class mi{constructor(e,t){(0,Yt.A)(this,"response",void 0),(0,Yt.A)(this,"dom",void 0),this.response=e,this.dom=t}}(0,Yt.A)(mi,"pattern",void 0);class wi extends mi{static toString(){return"RDFXMLHandler"}static register(e){e.mediatypes[er.JG]={q:.9}}parse(e,t,r){let n=e.store;if(this.dom||(this.dom=Sr.parseXML(t)),"parsererror"===this.dom.documentElement.nodeName)return e.failFetch(r,"Badly formed XML in "+r.resource.value,"parse_error");let i=new ui(n);try{i.parse(this.dom,r.original.value,r.original)}catch(t){return e.failFetch(r,"Syntax error parsing RDF/XML! "+t,"parse_error")}return r.noMeta||n.add(r.original,vi.rdf("type"),vi.link("RDFDocument"),e.appNode),e.doneFetch(r,this.response)}}wi.pattern=new RegExp("application/rdf\\+xml");class bi extends mi{static toString(){return"XHTMLHandler"}static register(e){e.mediatypes[er.H]={q:.8}}parse(e,t,r){let n,i;this.dom||(this.dom=Sr.parseXML(t));let s=e.store,o=this.dom.getElementsByTagName("title");o.length>0&&s.add(r.resource,vi.dc("title"),s.rdfFactory.literal(o[0].textContent),r.resource);let a=this.dom.getElementsByTagName("link");for(let t=a.length-1;t>=0;t--)n=a[t].getAttribute("rel"),i=!1,n||(n=a[t].getAttribute("rev"),i=!0),n&&e.linkData(r.original,n,a[t].getAttribute("href"),r.resource,i);let u=this.dom.getElementsByTagName("script");for(let e=0;e<u.length;e++){let t=u[e].getAttribute("type");pi[t]&&(hi(u[e].textContent,s,r.original.value,t),hi(u[e].textContent,s,r.original.value,t))}if(r.noMeta||s.add(r.resource,vi.rdf("type"),vi.link("WebPage"),e.appNode),!r.noRDFa&&ai)try{ai(this.dom,s,r.original.value)}catch(t){let n="Error trying to parse "+r.resource+" as RDFa:\n"+t+":\n"+t.stack;return e.failFetch(r,n,"parse_error")}return e.doneFetch(r,this.response)}}bi.pattern=new RegExp("application/xhtml");class _i extends mi{static toString(){return"XMLHandler"}static register(e){e.mediatypes["text/xml"]={q:.5},e.mediatypes["application/xml"]={q:.5}}static isElement(e){return e.nodeType===Node.ELEMENT_NODE}parse(e,t,r){let n=Sr.parseXML(t);for(let i=0;i<n.childNodes.length;i++){const s=n.childNodes[i];if(_i.isElement(s)){let i=s.namespaceURI;if(i&&i===i.rdf){return e.addStatus(r.req,"Has XML root element in the RDF namespace, so assume RDF/XML."),new wi(this.response,n).parse(e,t,r)}break}}if(n.doctype&&"html"===n.doctype.name&&n.doctype.publicId.match(/^-\/\/W3C\/\/DTD XHTML/)&&n.doctype.systemId.match(/http:\/\/www.w3.org\/TR\/xhtml/)){return e.addStatus(r.req,"Has XHTML DOCTYPE. Switching to XHTML Handler.\n"),new bi(this.response,n).parse(e,t,r)}let i=n.getElementsByTagName("html")[0];if(i){let s=i.getAttribute("xmlns");if(s&&s.match(/^http:\/\/www.w3.org\/1999\/xhtml/)){return e.addStatus(r.req,"Has a default namespace for XHTML. Switching to XHTMLHandler.\n"),new bi(this.response,n).parse(e,t,r)}}return e.failFetch(r,"Unsupported dialect of XML: not RDF or XHTML namespace, etc.\n"+t.slice(0,80),901)}}_i.pattern=new RegExp("(text|application)/(.*)xml");class Si extends mi{static toString(){return"HTMLHandler"}static register(e){e.mediatypes["text/html"]={q:.8}}parse(e,t,r){let n=e.store;if(Ti(t)){return e.addStatus(r.req,"Has an XML declaration. We'll assume it's XHTML as the content-type was text/html.\n"),new bi(this.response).parse(e,t,r)}if(function(e){const t=e.indexOf("<!DOCTYPE html"),r=e.indexOf(">");if(-1===t||-1===r||t>r)return!1;return-1!==e.substr(t,r-t).indexOf("XHTML")}(t)){return e.addStatus(r.req,"Has XHTML DOCTYPE. Switching to XHTMLHandler.\n"),new bi(this.response).parse(e,t,r)}if(function(e){const t=e.match(/[^(<html)]*<html\s+[^<]*xmlns=['"]http:\/\/www.w3.org\/1999\/xhtml["'][^<]*>/);return!!t}(t)){return e.addStatus(r.req,"Has default namespace for XHTML, so switching to XHTMLHandler.\n"),new bi(this.response).parse(e,t,r)}let i=new RegExp("<title>([\\s\\S]+?)</title>","im").exec(t);return i&&n.add(r.resource,vi.dc("title"),n.rdfFactory.literal(i[1]),r.resource),n.add(r.resource,vi.rdf("type"),vi.link("WebPage"),e.appNode),e.addStatus(r.req,"non-XML HTML document, not parsed for data."),e.doneFetch(r,this.response)}}Si.pattern=new RegExp("text/html");class Ei extends mi{static toString(){return"JsonLdHandler"}static register(e){e.mediatypes["application/ld+json"]={q:.9}}async parse(e,t,r,n){const i=e.store;try{return await bn(t,i,r.original.value),e.store.add(r.original,vi.rdf("type"),vi.link("RDFDocument"),e.appNode),e.doneFetch(r,n)}catch(t){const i="Error trying to parse "+r.resource+" as JSON-LD:\n"+t;return e.failFetch(r,i,"parse_error",n)}}}Ei.pattern=/application\/(ld\+json|activity\+json)/;class xi extends mi{static toString(){return"TextHandler"}static register(e){e.mediatypes["text/plain"]={q:.5}}parse(e,t,r){if(Ti(t)){return e.addStatus(r.req,"Warning: "+r.resource+" has an XML declaration. We'll assume it's XML but its content-type wasn't XML.\n"),new _i(this.response).parse(e,t,r)}if(t.slice(0,500).match(/xmlns:/)){return e.addStatus(r.req,"May have an XML namespace. We'll assume it's XML but its content-type wasn't XML.\n"),new _i(this.response).parse(e,t,r)}return e.addStatus(r.req,"Plain text document, no known RDF semantics."),e.doneFetch(r,this.response)}}xi.pattern=new RegExp("text/plain");class Ai extends mi{static toString(){return"N3Handler"}static register(e){e.mediatypes["text/n3"]={},e.mediatypes["text/turtle"]={}}parse(e,t,r,n){let i=e.store,s=fn(i,i,r.original.value,r.original.value,null,null,"",null);try{s.loadBuf(t)}catch(t){let i="Error trying to parse "+r.resource+" as Notation3:\n"+t;return e.failFetch(r,i,"parse_error",n)}return e.addStatus(r.req,"N3 parsed: "+s.statementCount+" triples in "+s.lines+" lines."),e.store.add(r.original,vi.rdf("type"),vi.link("RDFDocument"),e.appNode),e.doneFetch(r,this.response)}}Ai.pattern=new RegExp("(application|text)/(x-)?(rdf\\+)?(n3|turtle)");const Fi={RDFXMLHandler:wi,XHTMLHandler:bi,XMLHandler:_i,HTMLHandler:Si,TextHandler:xi,N3Handler:Ai,JsonLdHandler:Ei};function Ti(e){return!!e.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/)}class ki{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if((0,Yt.A)(this,"store",void 0),(0,Yt.A)(this,"timeout",void 0),(0,Yt.A)(this,"_fetch",void 0),(0,Yt.A)(this,"mediatypes",void 0),(0,Yt.A)(this,"appNode",void 0),(0,Yt.A)(this,"requested",void 0),(0,Yt.A)(this,"timeouts",void 0),(0,Yt.A)(this,"redirectedTo",void 0),(0,Yt.A)(this,"fetchQueue",void 0),(0,Yt.A)(this,"fetchCallbacks",void 0),(0,Yt.A)(this,"nonexistent",void 0),(0,Yt.A)(this,"lookedUp",void 0),(0,Yt.A)(this,"handlers",void 0),(0,Yt.A)(this,"ns",void 0),(0,Yt.A)(this,"fireCallbacks",void 0),this.store=e||new Kr,this.ns=yi(this.store.rdfFactory),this.timeout=t.timeout||3e4,this._fetch=t.fetch||void 0!==a.g&&(a.g.solidFetcher||a.g.solidFetch)||"undefined"!=typeof window&&(window.solidFetcher||window.solidFetch)||di(),!this._fetch)throw new Error("No _fetch function available for Fetcher");this.appNode=this.store.sym("chrome://TheCurrentSession"),this.store.fetcher=this,this.requested={},this.timeouts={},this.redirectedTo={},this.fetchQueue={},this.fetchCallbacks={},this.nonexistent={},this.lookedUp={},this.handlers=[],this.mediatypes={"image/*":{q:.9},"*/*":{q:.1}},Sr.callbackify(this,["request","fail","refresh","retract","done"]),Object.keys(t.handlers||Fi).map(e=>this.addHandler(Fi[e]))}static crossSiteProxy(e){return ki.crossSiteProxyTemplate?ki.crossSiteProxyTemplate.replace("{uri}",encodeURIComponent(e)):void 0}static offlineOverride(e){let t=e;var r;return"undefined"!=typeof window&&window.panes&&(r=window.panes.UI)&&r.preferences&&r.preferences.get("offlineModeUsingLocalhost")&&"http://"===t.slice(0,7)&&"localhost/"!==t.slice(7,17)&&(t="http://localhost/"+t.slice(7),br.A.warn("Localhost kludge for offline use: actually getting <"+t+">")),t}static proxyIfNecessary(e){var t;if("undefined"!=typeof window&&window.panes&&(t=window.panes.UI)&&t.isExtension)return e;if("undefined"!=typeof $SolidTestEnvironment&&$SolidTestEnvironment.localSiteMap){let t=e.split("/").slice(2);const r=(e,t)=>{let n=t[e.shift()];return n?"string"==typeof n?n+e.join("/"):e?r(e,n):null:null},n=r(t,$SolidTestEnvironment.localSiteMap);if(n)return n}return ki.crossSiteProxyTemplate&&"undefined"!=typeof document&&document.location&&"https:"===(""+document.location).slice(0,6)&&"http:"===e.slice(0,5)?ki.crossSiteProxyTemplate.replace("{uri}",encodeURIComponent(e)):e}static unsupportedProtocol(e){let t=pr.protocol(e);return"tel"===t||"mailto"===t||"urn"===t}static setCredentials(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};void 0===t.credentials&&(void 0!==t.withCredentials?t.credentials=t.withCredentials?"include":"omit":t.credentials="include")}load(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t=Object.assign({},t),e instanceof Array)return Promise.all(e.map(e=>this.load(e,Object.assign({},t))));const r=e;let n=(0,fi.E)(r);n=n.split("#")[0],t=this.initFetchOptions(n,t);const i=this.appNode,s=this.store,o=s.statementsMatching(void 0,this.ns.link("requestedURI"),s.sym(n),i).map(e=>e.subject);for(const e of o){const r=s.any(e,this.ns.link("response"),null,i);if(null!=r){const e=s.statementsMatching(r,this.ns.link("outOfDate"),!0,i);s.remove(e),t.force=!0,t.clearPreviousData=!0}}const a=this.initFetchOptions(n,t);return this.pendingFetchPromise(n,a.baseURI,a)}async pendingFetchPromise(e,t,r){let n;return!r.force&&await this.fetchQueue[t]?n=this.fetchQueue[t]:(n=Promise.race([this.setRequestTimeout(e,r),this.fetchUri(e,r)]),this.fetchQueue[t]=n,this.cleanupFetchRequest(t,void 0,this.timeout)),n.then(t=>(e in this.timeouts&&(this.timeouts[e].forEach(clearTimeout),delete this.timeouts[e]),t))}cleanupFetchRequest(e,t,r){void 0!==t&&console.warn("_options is deprecated"),this.timeouts[e]=(this.timeouts[e]||[]).concat(setTimeout(()=>{this.isPending(e)||delete this.fetchQueue[e]},r))}initFetchOptions(e,t){let r=this.store;!t.method||"GET"===t.method.toUpperCase()||(t.force=!0),t.resource=r.rdfFactory.namedNode(e),t.baseURI=t.baseURI||e,t.original=r.rdfFactory.namedNode(t.baseURI),t.req=r.bnode(),t.headers=t.headers||{},t.contentType&&(t.headers["content-type"]=t.contentType),t.force&&(t.cache="no-cache");let n=this.acceptString();t.headers.accept=n;let i=ki.offlineOverride(e);t.requestedURI=i,ki.setCredentials(i,t);let s=ki.proxyIfNecessary(i);return i!==s&&(t.proxyUsed=!0),t.actualProxyURI=s,t}fetchUri(e,t){if(!e)return Promise.reject(new Error("Cannot fetch an empty uri"));if(ki.unsupportedProtocol(e))return this.failFetch(t,"fetcher: Unsupported protocol","unsupported_protocol");let r=this.getState(e);if(t.force)delete this.nonexistent[e];else{if("fetched"===r)return Promise.resolve(this.doneFetch(t,{status:200,ok:!0,statusText:"Already loaded into quadstore."}));if("failed"===r&&404===this.requested[e]){let r="Previously failed: "+this.requested[e],n={url:e,status:this.requested[e],statusText:r,responseText:r,headers:new li.Headers,ok:!1,body:null,bodyUsed:!1,size:0,timeout:0};return this.failFetch(t,r,this.requested[e],n)}}this.fireCallbacks("request",[e]),this.requested[e]=!0,t.noMeta||this.saveRequestMetadata(e,t);let{actualProxyURI:n}=t;return this._fetch(n,t).then(r=>this.handleResponse(r,e,t),r=>{let i={url:n,status:999,statusText:(r.name||"network failure")+": "+(r.errno||r.code||r.type),responseText:r.message,headers:new li.Headers,ok:!1,body:null,bodyUsed:!1,size:0,timeout:0};return this.handleError(i,e,t)})}nowOrWhenFetched(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};const i=(0,fi.E)(e);"function"==typeof t?r=t:void 0===t||((0,nr.Y2)(t)?n.referringTerm=t:n=t),this.load(i,n).then(e=>{if(r)if(e)if(e.ok)r(!0,"OK",e);else{let t="HTTP error: Status "+e.status+" ("+e.statusText+")";e.responseText&&(t+=" "+e.responseText),r(!1,t,e)}else{r(!1,"@@ nowOrWhenFetched: no response object!")}},function(e){var t=e.message||e.statusText;t="Failed to load <"+i+"> "+t,e.response&&e.response.status&&(t+=" status: "+e.response.status),r(!1,t,e.response)})}addStatus(e,t){let r=new Date;t="["+r.getHours()+":"+r.getMinutes()+":"+r.getSeconds()+"."+r.getMilliseconds()+"] "+t;let n=this.store;const i=n.the(e,this.ns.link("status"));(0,nr.P3)(i)?i.append(n.rdfFactory.literal(t)):br.A.warn("web.js: No list to add to: "+i+","+t)}failFetch(e,t,r,n){this.addStatus(e.req,t),e.noMeta||this.store.add(e.original,this.ns.link("error"),this.store.rdfFactory.literal(t));let i=(e.method||"GET").toUpperCase();("GET"===i||"HEAD"===i)&&(e.resource.equals(e.original),this.requested[pr.docpart(e.original.value)]=r,this.fireCallbacks("fail",[e.original.value,t]));var s=new Error("Fetcher: "+t);return s.status=r,s.statusText=t,s.response=n,Promise.reject(s)}linkData(e,t,r,n,i){if(!r)return;let s,o=this.store,a=o.rdfFactory.namedNode(pr.join(r,e.value));if("alternate"===t||"seeAlso"===t||"meta"===t||"describedby"===t){if(a.value===e.value)return;s=this.ns.rdfs("seeAlso")}else s="type"===t?o.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"):o.rdfFactory.namedNode(pr.join(encodeURIComponent(t),"http://www.iana.org/assignments/link-relations/"));i?o.add(a,s,e,n):o.add(e,s,a,n)}parseLinkHeader(e,t,r){if(!e)return;const n=/[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g,i=e.match(/<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*")))*(,|$)/g);if(null!=i)for(let e=0;e<i.length;e++){let s=i[e].split(">"),o=s[0].substring(1),a=s[1].match(n);if(null==a)return;for(let e=0;e<a.length;e++){let n=a[e].split("=")[1].replace(/["']/g,"");this.linkData(t,n,o,r)}}}doneFetch(e,t){return this.addStatus(e.req,"Done."),this.requested[e.original.value]="done",this.fireCallbacks("done",[e.original.value]),t.req=e.req,t}nowKnownAs(e,t){this.lookedUp[e.value]?this.lookedUp[t.value]||this.lookUpThing(t,e):this.lookedUp[t.value]&&(this.lookedUp[e.value]||this.lookUpThing(e,t))}putBack(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=(0,fi.E)(e);let n=new rr.A(r).doc();return t.contentType=t["content-type"]||t["Content-Type"]||t.contentType||er.sT,"application/ld+json"===t.contentType?new Promise((r,i)=>{Ir(n,this.store,n.uri,t.contentType,(n,s)=>{n?i(n):(t.data=s,this.webOperation("PUT",e,t).then(e=>r(e)).catch(e=>i(e)))})}):(t.data=Ir(n,this.store,n.value,t.contentType),this.webOperation("PUT",r,t))}webCopy(e,t,r){return this.webOperation("GET",e).then(e=>this.webOperation("PUT",t,{data:e.responseText,contentType:r}))}delete(e,t){return this.webOperation("DELETE",e,t).then(t=>(this.requested[e]=404,this.nonexistent[e]=!0,this.unload(this.store.rdfFactory.namedNode(e)),t))}async createIfNotExists(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:er.sT,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";const n=this;try{var i=await n.load(e)}catch(s){if(404===s.response.status){try{i=await n.webOperation("PUT",e.value,{data:r,contentType:t})}catch(e){throw e}return delete n.requested[e.value],i}throw s}return i}createContainer(e,t,r){let n={"content-type":er.sT,link:this.ns.ldp("BasicContainer")+'; rel="type"'};t&&(n.slug=t);let i={headers:n};return r&&(i.body=r),this.webOperation("POST",e,i)}invalidateCache(e){const t=(0,fi.E)(e),r=this;r.fetchQueue&&r.fetchQueue[t]&&(r.fetchQueue[t].PromiseStatus,delete r.fetchQueue[t]);if(r.requested[t]&&"done"!==r.requested[t]&&"failed"!==r.requested[t]&&404!==r.requested[t]){let e=`Rdflib: fetcher: Destructive operation on <${r.requested[t]}> file being fetched! `+t;console.error(e)}else delete r.requested[t],delete r.nonexistent[t]}webOperation(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=(0,fi.E)(t);r.method=e,r.body=r.data||r.body,r.force=!0;const i=this;if(r.body&&!r.contentType)throw new Error("Web operation sending data must have a defined contentType.");return r.contentType&&(r.headers=r.headers||{},r.headers["content-type"]=r.contentType),ki.setCredentials(n,r),new Promise(function(t,s){i._fetch(n,r).then(r=>{if(r.ok)"PUT"!==e&&"PATCH"!==e&&"POST"!==e&&"DELETE"!==e||i.invalidateCache(n),r.text?r.text().then(e=>{r.responseText=e,t(r)}):t(r);else{let t="Web error: "+r.status;r.statusText&&(t+=" ("+r.statusText+")"),t+=" on "+e+" of <"+n+">",r.responseText&&(t+=": "+r.responseText);let i=new Error(t);i.response=r,s(i)}},t=>{s(new Error("Fetch error for "+e+" of <"+n+">:"+t))})})}lookUpThing(e,t){let r=this.store.uris(e);return r=r.map(e=>pr.docpart(e)),r.forEach(e=>{this.lookedUp[e]=!0}),this.load(r,{referringTerm:t})}getHeader(e,t){const r=this.store,n=e.value,i=r.each(void 0,this.ns.link("requestedURI"),r.rdfFactory.literal(n));for(let e=0;e<i.length;e++){let n=i[e];if(void 0!==n){let e=r.any(n,this.ns.link("response"));if(void 0!==e&&r.anyValue(e,this.ns.http("status"))&&r.anyValue(e,this.ns.http("status")).startsWith("2")){let n=r.each(e,this.ns.httph(t.toLowerCase()));return n.length?n.map(e=>e.value):[]}}}}saveRequestMetadata(e,t){let r=t.req,n=this.store,i=t.referringTerm;this.addStatus(t.req,"Accept: "+t.headers.accept),(0,nr.Y2)(i)&&n.add(n.rdfFactory.namedNode(e),this.ns.link("requestedBy"),i,this.appNode),t.original&&t.original.value!==e&&n.add(r,this.ns.link("orginalURI"),n.rdfFactory.literal(t.original.value),this.appNode);const s=new Date,o="["+s.getHours()+":"+s.getMinutes()+":"+s.getSeconds()+"] ";n.add(r,this.ns.rdfs("label"),n.rdfFactory.literal(o+" Request for "+e),this.appNode),n.add(r,this.ns.link("requestedURI"),n.rdfFactory.literal(e),this.appNode),n.add(r,this.ns.link("status"),n.collection(),this.appNode)}saveResponseMetadata(e,t){const r=this.store;let n=r.bnode();return r.add(t.req,this.ns.link("response"),n,this.appNode),r.add(n,this.ns.http("status"),r.rdfFactory.literal(e.status),this.appNode),r.add(n,this.ns.http("statusText"),r.rdfFactory.literal(e.statusText),this.appNode),e.headers.forEach((e,i)=>{r.add(n,this.ns.httph(i),this.store.rdfFactory.literal(e),this.appNode),"content-type"===i&&r.add(t.resource,this.ns.rdf("type"),r.rdfFactory.namedNode(Sr.mediaTypeClass(e).value),this.appNode)}),n}objectRefresh(e){let t=this.store.uris(e);if(void 0!==t)for(let e=0;e<t.length;e++)this.refresh(this.store.rdfFactory.namedNode(pr.docpart(t[e])))}refresh(e,t){this.fireCallbacks("refresh",arguments),this.nowOrWhenFetched(e,{force:!0,clearPreviousData:!0},t)}refreshIfExpired(e,t){let r=this.getHeader(e,"Expires");!r||new Date(r[0]).getTime()<=(new Date).getTime()?this.refresh(e,t):t(!0,"Not expired",{})}retract(e){this.store.removeMany(void 0,void 0,void 0,e),e.value&&delete this.requested[pr.docpart(e.value)],this.fireCallbacks("retract",arguments)}getState(e){return void 0===this.requested[e]?"unrequested":!0===this.requested[e]?"requested":"done"===this.requested[e]?"fetched":"redirected"===this.requested[e]?this.getState(this.redirectedTo[e]):"failed"}isPending(e){return!0===this.requested[e]}unload(e){this.store.removeDocument(e),delete this.requested[e.value]}addHandler(e){this.handlers.push(e),e.register(this)}retryNoCredentials(e,t){t.retriedWithNoCredentials=!0,delete this.requested[e],delete this.fetchQueue[e];let r=Object.assign({},t,{credentials:"omit"});return this.addStatus(t.req,"Abort: Will retry with credentials SUPPRESSED to see if that helps"),this.load(e,r)}isCrossSite(e){if("undefined"==typeof document||!document.location)return!1;const t=pr.hostpart,r=""+document.location;return(t(r)&&t(e)&&t(r))!==t(e)}handleError(e,t,r){if(this.isCrossSite(t)){if(r.credentials&&"include"===r.credentials&&!r.retriedWithNoCredentials)return this.retryNoCredentials(t,r);let e=ki.crossSiteProxy(t);if(e&&!r.proxyUsed)return this.redirectToProxy(e,r)}var n;return e instanceof Error?n="Fetch error: "+e.message:(n=e.statusText,e.responseText&&(n+=` ${e.responseText}`)),this.failFetch(r,n,e.status||998,e)}addType(e,t,r,n){let i=t;if(n){var s=r.any(i,this.ns.link("requestedURI"));s&&s.value!==n&&r.add(r.rdfFactory.namedNode(n),this.ns.rdf("type"),e,this.appNode)}for(;;){const t=r.any(i,this.ns.link("requestedURI"));if(t&&t.value&&r.add(r.rdfFactory.namedNode(t.value),this.ns.rdf("type"),e,this.appNode),i=r.any(void 0,r.rdfFactory.namedNode("http://www.w3.org/2007/ont/link#redirectedRequest"),i),!i)break;var o=r.any(i,r.rdfFactory.namedNode("http://www.w3.org/2007/ont/link#response"));if(!o)break;var a=r.any(o,r.rdfFactory.namedNode("http://www.w3.org/2007/ont/http#status"));if(!a)break;if("301"!==a&&"302"!==a)break}}handleResponse(e,t,r){const n=this.store,i=e.headers,s=r.req,o=this.saveResponseMetadata(e,r),a=this.normalizedContentType(r,i)||"";let u=i.get("content-location");if(0===e.status)return this.handleError(e,t,r);if(e.status>=400)return 404===e.status&&(this.nonexistent[r.original.value]=!0,this.nonexistent[t]=!0),this.saveErrorResponse(e,o).then(()=>{let t=r.resource+" "+e.statusText;return this.failFetch(r,t,e.status,e)});var c=null,h=null;if(u&&(h=pr.join(u,t))!==t&&(c=h),200===e.status){if(this.addType(this.ns.link("Document"),s,n,t),c&&this.addType(this.ns.link("Document"),s,n,c),r.clearPreviousData){const e=n.statementsMatching(void 0,void 0,void 0,r.resource).slice();for(let t=0;t<e.length;t++)n.removeStatement(e[t])}let e=a.includes("image/")||a.includes("application/pdf");a&&e&&(this.addType(n.rdfFactory.namedNode("http://purl.org/dc/terms/Image"),s,n,t),c&&this.addType(n.rdfFactory.namedNode("http://purl.org/dc/terms/Image"),s,n,c))}if(u){if(!r.force&&c&&"done"===this.requested[h])return this.doneFetch(r,e);this.requested[h]=!0}this.parseLinkHeader(i.get("link"),r.original,s);let l=this.handlerForContentType(a,e);return l?e.text().then(t=>(e.responseText=t,l.parse(this,t,r,e))):(this.addStatus(s,"Fetch over. No data handled."),this.doneFetch(r,e))}saveErrorResponse(e,t){let r=this.store;return e.text().then(e=>{e.length>10&&r.add(t,this.ns.http("content"),r.rdfFactory.literal(e),t)})}handlerForContentType(e,t){if(!e)return null;let r=this.handlers.find(t=>e.match(t.pattern));return r?new r(t):null}guessContentType(e){return gi[e.split(".").pop()]}normalizedContentType(e,t){if(e.forceContentType)return e.forceContentType;let r=t.get("content-type");if(!r||r.includes("application/octet-stream")){let t=this.guessContentType(e.resource.value);if(t)return t}let n=pr.protocol(e.resource.value);return!r&&["file","chrome"].includes(n)?"text/xml":r}redirectToProxy(e,t){this.addStatus(t.req,"BLOCKED -> Cross-site Proxy to <"+e+">"),t.proxyUsed=!0;const r=this.store,n=t.req;t.noMeta||(r.add(n,this.ns.link("redirectedTo"),r.rdfFactory.namedNode(e),n),this.addStatus(n,"redirected to new request")),this.requested[t.resource.value]="redirected",this.redirectedTo[t.resource.value]=e;let i=Object.assign({},t);return i.baseURI=t.resource.value,this.fetchUri(e,i).then(e=>(i.noMeta||r.add(n,this.ns.link("redirectedRequest"),i.req,this.appNode),e))}setRequestTimeout(e,t){return new Promise(r=>{this.timeouts[e]=(this.timeouts[e]||[]).concat(setTimeout(()=>{!this.isPending(e)||t.retriedWithNoCredentials||t.proxyUsed||r(this.failFetch(t,`Request to ${e} timed out`,"timeout"))},this.timeout))})}addFetchCallback(e,t){this.fetchCallbacks[e]?this.fetchCallbacks[e].push(t):this.fetchCallbacks[e]=[t]}acceptString(){let e="";for(let t in this.mediatypes){""!==e&&(e+=", "),e+=t;for(let r in this.mediatypes[t])e+=";"+r+"="+this.mediatypes[t][r]}return e}}(0,Yt.A)(ki,"HANDLERS",void 0),(0,Yt.A)(ki,"CONTENT_TYPE_BY_EXT",void 0),(0,Yt.A)(ki,"crossSiteProxyTemplate",void 0),ki.HANDLERS=Fi,ki.CONTENT_TYPE_BY_EXT=gi;const Ii={parseJSON:function(e,t,r){var n,i,s,o={},a=r.sym(t);for(var u in e){0===u.indexOf("_:")?o[u]?n=o[u]:(n=r.bnode(u),o[u]=n):n=r.sym(u);var c=e[u];for(var h in c){var l=c[h];for(var d in i=r.sym(h),l){var f=l[d];if("uri"===f.type)s=r.sym(f.value),r.add(n,i,s,a);else if("BlankNode"===f.type)o[f.value]?s=o[f.value]:(s=r.bnode(f.value),o[f.value]=s),r.add(n,i,s,a);else{if("Literal"!==f.type)throw new Error("error: unexpected termtype: "+d.type);s=f.datatype?r.literal(f.value,void 0,r.sym(f.datatype)):f.lang?r.literal(f.value,f.lang):r.literal(f.value),r.add(n,i,s,a)}}}}}};function Ci(e){var t=0;function r(e){var t="",r=e.statements;for(var n in r)br.A.debug("Found statement: "+r),t+=o()+r[n]+"\n";return t}function n(e){var t="";for(var r in e.constraints){var n=e.constraints[r];t+=o()+"FILTER ( "+n.describe(r)+" ) \n"}return t}function i(e){for(var s="",a=0;a<e.optional.length;a++)br.A.debug("Found optional query"),s+=o()+"OPTIONAL { \n",t++,s+=r(e.optional[a]),s+=n(e.optional[a]),s+=i(e.optional[a]),t--,s+=o()+"}\n";return s}function s(e){var s=o()+"WHERE \n{ \n";return t++,s+=r(e),s+=n(e),s+=i(e),t--,s+="}"}function o(){for(var e="",r=0;r<t;r++)e+=" ";return e}return function(e){return function(e){for(var t=o()+"SELECT ",r=0;r<e.vars.length;r++)t+=e.vars[r]+" ";return t+"\n"}(e)+s(e.pat)}(e)}function Ri(e,t,r){var n=[];function i(e){if(n[e])return n[e];var t=r.variable(e);return n[e]=t,t}function s(e){return"string"==typeof e&&e.match(/[^ \n\t]/)}function o(e){return"string"==typeof e&&e.match(/^[\?\$]/)}function a(e){return"string"==typeof e?e.replace(/^&lt;/,"<").replace(/&gt;$/,">"):e}function u(e){return"string"==typeof e&&e.match(/^<[^>]*>$/)}function c(e){return"string"==typeof e&&(e.match(/^_:/)||e.match(/^$/))}function h(e){return"string"==typeof e&&e.match(/:$/)}function l(e){return"string"==typeof e&&e.match(/^:|^[^_][^:]*:/)}function d(e){return e.split(":")[0]}function f(e){return e.split(":")[1]}function p(e){return u(e)?e.slice(1,e.length-1):e}function g(e){var t=-1===e.indexOf("'")?null:e.indexOf("'"),n=-1===e.indexOf('"')?null:e.indexOf('"');if(!t&&!n){var i=new Array(1);return i[0]=e,i}var s,o,a=new Array(2);if(!t||n&&n<t)s='"',o=n;else{if(n&&!(t&&t<n))return br.A.error("SQARQL QUERY OOPS!"),a;s="'",o=t}a[0]=e.slice(0,o);var u,c=e.slice(o+1).indexOf(s);return-1===c?(br.A.error("SPARQL parsing error: no matching parentheses in literal "+e),e):(e.slice(c+o+2).match(/^\^\^/)?(u=e.slice(c+o+2).indexOf(" "),a[1]=r.literal(e.slice(o+1,o+1+c),r.sym(p(e.slice(o+4+c,o+2+c+u)))),a=a.concat(g(e.slice(c+o+3+u)))):e.slice(c+o+2).match(/^@/)?(u=e.slice(c+o+2).indexOf(" "),a[1]=r.literal(e.slice(o+1,o+1+c),e.slice(o+3+c,o+2+c+u),null),a=a.concat(g(e.slice(c+o+2+u)))):(a[1]=r.literal(e.slice(o+1,o+1+c)),br.A.info("Literal found: "+a[1]),a=a.concat(g(e.slice(c+o+2)))),a)}function y(e){e=e.replace(/\(/g," ( ").replace(/\)/g," ) ").replace(/</g," <").replace(/>/g,"> ").replace(/{/g," { ").replace(/}/g," } ").replace(/[\t\n\r]/g," ").replace(/; /g," ; ").replace(/\. /g," . ").replace(/, /g," , "),br.A.info("New str into spaceDelimit: \n"+e);var t=[],r=e.split(" ");for(var n in r)s(r[n])&&(t=t.concat(r[n]));return t}function v(e,t){for(var r=0;r<t.length;r++)if("string"==typeof t[r]&&t[r].toLowerCase()===e.toLowerCase())return r;return null}function m(e,t){for(var r=[],n=0;n<t.length;n++)"string"==typeof t[n]&&t[n].toLowerCase()===e.toLowerCase()&&r.push(n);return r}function w(e,t,r){br.A.info("Looking for a close bracket of type "+r+" in "+e);for(var n=0,i=0;i<e.length;i++)if(e[i]===t&&n++,e[i]===r&&n--,n<0)return i;return br.A.error("Statement had no close parenthesis in SPARQL query"),0}function b(e){return this.describe=function(t){return t+" = "+e.toNT()},this.test=function(t){return e.equals(t)},this}function _(e){this.describe=function(t){return"REGEXP( '"+e+"' , "+t+" )"},this.test=function(t){var r=new RegExp(e);return!!t.value&&r.test(t.value)}}function S(e,t){3!==e.length||"Variable"!==e[0].termType||"NamedNode"!==e[2].termType&&"Literal"!==e[2].termType?6===e.length&&"string"==typeof e[0]&&"regexp"===e[0].toLowerCase()&&"("===e[1]&&")"===e[5]&&","===e[3]&&"Variable"===e[4].termType&&"Literal"===e[2].termType&&(br.A.debug("Constraint added: "+e),t.constraints[e[4]]=new _(e[2].value)):"="===e[1]||">"===e[1]||"<"===e[1]?(br.A.debug("Constraint added: "+e),t.constraints[e[0]]=new b(e[2])):br.A.warn("I don't know how to handle the constraint: "+e)}function E(e,t){br.A.debug("Optional query: "+e+" not yet implemented.");var n=r.formula();x(e,n),t.optional.push(n)}function x(e,t){var n,s,h=function(e){for(var t=[],n=0;n<e.length;n++)"string"==typeof e[n]?(e[n]=a(e[n]),o(e[n])?t[n]=i(e[n].slice(1)):c(e[n])?(br.A.info(e[n]+" was identified as a bnode."),t[n]=r.bnode()):u(e[n])?(br.A.info(e[n]+" was identified as a symbol."),t[n]=r.sym(p(e[n]))):l(e[n])?(br.A.info(e[n]+" was identified as a prefixed symbol"),T[d(e[n])]?t[n]=r.sym(e[n]=T[d(e[n])]+f(e[n])):(br.A.error("SPARQL error: "+e[n]+" with prefix "+d(e[n])+" does not have a correct prefix entry."),t[n]=e[n])):t[n]=e[n]):t[n]=e[n];return t}(e);for(br.A.debug("WHERE: "+h);v("OPTIONAL",h);)s=v("OPTIONAL",h),br.A.debug("OPT: "+s+" "+h[s]+" in "+h),"{"!==h[s+1]&&br.A.warn("Bad optional opening bracket in word "+s),-1===(n=w(h.slice(s+2),"{","}"))?br.A.error("No matching bracket in word "+s):(E(h.slice(s+2,s+2+n),t),s=v("OPTIONAL",h),n=w(h.slice(s+2),"{","}"),h.splice(s,n+3));for(br.A.debug("WHERE after optionals: "+h);v("FILTER",h);){var g=v("FILTER",h);"("!==h[g+1]&&br.A.warn("Bad filter opening bracket in word "+g),-1===(n=w(h.slice(g+2),"(",")"))?br.A.error("No matching bracket in word "+g):(S(h.slice(g+2,g+2+n),t),g=v("FILTER",h),n=w(h.slice(g+2),"(",")"),h.splice(g,n+3))}br.A.debug("WHERE after filters and optionals: "+h),function(e,t){var r=new Array(1);r[0]=-1;for(var n=r.concat(m(".",e)),i=[],s=0;s<n.length-1;s++)i[s]=e.slice(n[s]+1,n[s+1]);for(s in i){br.A.info("s+p+o "+s+" = "+i[s]);var o=i[s][0];i[s].splice(0,1);var a=r.concat(m(";",i[s]));a.push(i[s].length);for(var u=[],c=0;c<a.length-1;c++)u[c]=i[s].slice(a[c]+1,a[c+1]);for(s in u){br.A.info("p+o "+s+" = "+i[s]);var h=u[s][0];u[s].splice(0,1);var l=r.concat(m(",",u[s]));l.push(u[s].length);var d=[];for(c=0;c<l.length-1;c++)d[c]=u[s].slice(l[c]+1,l[c+1]);for(s in d){var f=d[s][0];br.A.info("Subj="+o+" Pred="+h+" Obj="+f),t.add(o,h,f)}}}}(h,t)}br.A.info("SPARQL input: \n"+e);var A=new Dr,F=function(e){var t=g(e),r=[];for(var n in t)r="string"==typeof t[n]?r.concat(y(t[n])):r.concat(t[n]);return r=function(e){for(var t=e,r=0;r<t.length;r++)if("a"===t[r]&&(t[r]="<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"),"is"===t[r]&&"of"===t[r+2]){t.splice(r,1),t.splice(r+1,1);var n=t[r-1];t[r-1]=t[r+1],t[r+1]=n}return t}(r),br.A.info("SPARQL Tokens: "+r),r}(e),T=function(e){var t=m("PREFIX",e),r=[];for(var n in t){var i=e[t[n]+1],s=e[t[n]+2];if(h(i))if(u(s)){br.A.info("Prefix found: "+i+" -> "+s);var o=d(i),a=p(s);r[o]=a}else br.A.error("Invalid SPARQL symbol: "+s);else br.A.error("Invalid SPARQL prefix: "+i)}return r}(F);T.rdf||(T.rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"),T.rdfs||(T.rdfs="http://www.w3.org/2000/01/rdf-schema#");var k=v("SELECT",F),I=v("WHERE",F);if(k<0||I<0||k>I)return br.A.error("Invalid or nonexistent SELECT and WHERE tags in SPARQL query"),!1;if(function(e,t){for(var r in br.A.info("SPARQL vars: "+e),e)if(o(e[r])){br.A.info("Added "+e[r]+" to query variables from SPARQL");var n=i(e[r].slice(1));t.vars.push(n),n.label=e[r].slice(1)}else br.A.warn("Incorrect SPARQL variable in SELECT: "+e[r])}(F.slice(k+1,I),A),x(F.slice(I+2,F.length-1),A.pat),t)return A;for(var C in A.pat.statements){var R=A.pat.statements[C];"NamedNode"===R.subject.termType&&r.fetcher&&r.fetcher.lookUpThing(R.subject,"sparql:"+R.subject),"NamedNode"===R.object.termType&&r.fetcher&&r.fetcher.lookUpThing(R.object,"sparql:"+R.object)}return A}class Pi{constructor(e){if((0,Yt.A)(this,"store",void 0),(0,Yt.A)(this,"ifps",void 0),(0,Yt.A)(this,"fps",void 0),(0,Yt.A)(this,"patchControl",void 0),(0,Yt.A)(this,"ns",void 0),(e=e||new Kr).updater)throw new Error("You can't have two UpdateManagers for the same store");e.fetcher||(e.fetcher=new ki(e)),this.store=e,e.updater=this,this.ifps={},this.fps={},this.ns={},this.ns.link=_r("http://www.w3.org/2007/ont/link#"),this.ns.http=_r("http://www.w3.org/2007/ont/http#"),this.ns.httph=_r("http://www.w3.org/2007/ont/httph#"),this.ns.ldp=_r("http://www.w3.org/ns/ldp#"),this.ns.rdf=_r("http://www.w3.org/1999/02/22-rdf-syntax-ns#"),this.ns.rdfs=_r("http://www.w3.org/2000/01/rdf-schema#"),this.ns.rdf=_r("http://www.w3.org/1999/02/22-rdf-syntax-ns#"),this.ns.owl=_r("http://www.w3.org/2002/07/owl#"),this.patchControl=[]}patchControlFor(e){return this.patchControl[e.value]||(this.patchControl[e.value]=[]),this.patchControl[e.value]}isHttpUri(e){return"http"===e.slice(0,4)}flagAuthorizationMetadata(e){e||(e=this.store);const t=e.fetcher?.appNode,r=e.statementsMatching(void 0,this.ns.link("requestedURI"),void 0,t).map(e=>e.subject);for(const n of r){const r=e.any(n,this.ns.link("response"),null,t);null!=r&&e.add(r,this.ns.link("outOfDate"),!0,t)}}async checkEditable(e,t){if(!e)return!1;t||(t=this.store);const r=this.editable(e,t);if(void 0!==r)return r;await(t.fetcher?.load(e));return this.editable(e,t)}editable(e,t){if(!e)return!1;if(t||(t=this.store),e=(0,fi.E)(e),!this.isHttpUri(e)&&t.holds(t.rdfFactory.namedNode(e),t.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),t.rdfFactory.namedNode("http://www.w3.org/2007/ont/link#MachineEditableDocument")))return"LOCALFILE";var r,n=!1;const i=t.fetcher?.appNode;for(var s,o=t.each(void 0,this.ns.link("requestedURI"),(0,pr.docpart)(e),i),a=0;a<o.length;a++)if(void 0!==(r=o[a])){const o=t.any(r,this.ns.link("response"),null,i);if(void 0!==o){if(t.anyJS(o,this.ns.link("outOfDate"),null,i))continue;var u=t.anyValue(o,this.ns.httph("wac-allow"));if(u)for(var c of u.split(",")){var h=c.split("=");if(h[0].includes("user")&&!h[1].includes("write")&&!h[1].includes("append"))return!1}var l=t.each(o,this.ns.httph("accept-patch"));if(l.length)for(let e=0;e<l.length;e++){if((s=l[e].value.trim()).indexOf("application/sparql-update")>=0)return"SPARQL";if(s.indexOf("application/sparql-update-single-match")>=0)return"SPARQL";if(s.indexOf("text/n3")>=0)return"N3PATCH"}var d=t.each(o,this.ns.httph("ms-author-via"));if(d.length)for(let e=0;e<d.length;e++){if((s=d[e].value.trim()).indexOf("SPARQL")>=0)return"SPARQL";if(s.indexOf("DAV")>=0)return"DAV"}if(!this.isHttpUri(e))return!!u&&"LOCALFILE";var f=t.each(o,this.ns.http("status"));if(f.length)for(let e=0;e<f.length;e++)200!==f[e]&&404!==f[e]||(n=!0)}}if(0===o.length);else if(n)return!1}anonymize(e){return"_:"===e.toNT().substr(0,2)&&this.mentioned(e)?"?"+e.toNT().substr(2):e.toNT()}anonymizeNT(e){return this.anonymize(e.subject)+" "+this.anonymize(e.predicate)+" "+this.anonymize(e.object)+" ."}nTriples(e){return`${e.subject.toNT()} ${e.predicate.toNT()} ${e.object.toNT()} .`}statementBnodes(e){return[e.subject,e.predicate,e.object].filter(function(e){return(0,nr.jt)(e)})}statementArrayBnodes(e){var t=[];for(let r=0;r<e.length;r++)t=t.concat(this.statementBnodes(e[r]));t.sort();var r=[];for(let e=0;e<t.length;e++)0!==e&&t[e].equals(t[e-1])||r.push(t[e]);return r}cacheIfps(){this.ifps={};var e=this.store.each(void 0,this.ns.rdf("type"),this.ns.owl("InverseFunctionalProperty"));for(let t=0;t<e.length;t++)this.ifps[e[t].value]=!0;this.fps={},e=this.store.each(void 0,this.ns.rdf("type"),this.ns.owl("FunctionalProperty"));for(let t=0;t<e.length;t++)this.fps[e[t].value]=!0}bnodeContext2(e,t,r){var n,i,s=this.store.statementsMatching(void 0,void 0,e,t);for(let e=0;e<s.length;e++)if(this.fps[s[e].predicate.value]){if(!(n=s[e].subject).isBlank)return[s[e]];if(r&&(i=this.bnodeContext2(n,t,r-1)))return i.concat([s[e]])}s=this.store.statementsMatching(e,void 0,void 0,t);for(let e=0;e<s.length;e++)if(this.ifps[s[e].predicate.value]){if(!(n=s[e].object).isBlank)return[s[e]];if(r&&(i=this.bnodeContext2(n,t,r-1)))return i.concat([s[e]])}return null}bnodeContext1(e,t){for(var r=0;r<3;r++){var n=this.bnodeContext2(e,t,r);if(null!==n)return n}return this.store.connectedStatements(e,t)}mentioned(e){return 0!==this.store.statementsMatching(e,null,null,null).length||0!==this.store.statementsMatching(null,e).length||0!==this.store.statementsMatching(null,null,e).length}bnodeContext(e,t){var r=[];if(e.length){this.cacheIfps();for(let i=0;i<e.length;i++){var n=e[i];this.mentioned(n)&&(r=r.concat(this.bnodeContext1(n,t)))}}return r}statementContext(e){var t=this.statementBnodes(e);return this.bnodeContext(t,e.graph)}contextWhere(e){var t=this;return e&&0!==e.length?"WHERE { "+e.map(function(e){return t.anonymizeNT(e)}).join("\n")+" }\n":""}fire(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return Promise.resolve().then(()=>{if(!e)throw new Error("No URI given for remote editing operation: "+t);return n.noMeta=!0,n.contentType=n.contentType||"application/sparql-update",n.body=t,this.store.fetcher.webOperation("PATCH",e,n)}).then(n=>{if(!n.ok){let r="UpdateManager: update failed for <"+e+"> status="+n.status+", "+n.statusText+"\n for query: "+t;throw new Error(r)}r(e,n.ok,n.responseText,n)}).catch(t=>{r(e,!1,t.message,t)})}update_statement(e){if(!e||e.graph){var t=this,r=this.statementContext(e);return{statement:e?[e.subject,e.predicate,e.object,e.graph]:void 0,statementNT:e?this.anonymizeNT(e):void 0,where:t.contextWhere(r),set_object:function(e,r){var n=this.where;n+="DELETE DATA { "+this.statementNT+" } ;\n",n+="INSERT DATA { "+this.anonymize(this.statement[0])+" "+this.anonymize(this.statement[1])+" "+this.anonymize(e)+" . }\n",t.fire(this.statement[3].value,n,r)}}}}insert_statement(e,t){var r=e instanceof Array?e[0]:e,n=this.contextWhere(this.statementContext(r));if(e instanceof Array){var i="";for(let t=0;t<e.length;t++)i+=e[t]+"\n";n+="INSERT DATA { "+i+" }\n"}else n+="INSERT DATA { "+this.anonymize(e.subject)+" "+this.anonymize(e.predicate)+" "+this.anonymize(e.object)+" . }\n";this.fire(r.graph.value,n,t)}delete_statement(e,t){var r=e instanceof Array?e[0]:e,n=this.contextWhere(this.statementContext(r));if(e instanceof Array){var i="";for(let t=0;t<e.length;t++)i+=e[t]+"\n";n+="DELETE DATA { "+i+" }\n"}else n+="DELETE DATA { "+this.anonymize(e.subject)+" "+this.anonymize(e.predicate)+" "+this.anonymize(e.object)+" . }\n";this.fire(r.graph.value,n,t)}requestDownstreamAction(e,t){var r=this.patchControlFor(e);if(r.pendingUpstream)if(r.downstreamAction){if(""+r.downstreamAction!=""+t)throw new Error("Can't wait for > 1 different downstream actions")}else r.downstreamAction=t;else t(e)}clearUpstreamCount(e){this.patchControlFor(e).upstreamCount=0}getUpdatesVia(e){var t=this.store.fetcher.getHeader(e,"updates-via");return t&&t.length?t[0].trim():null}addDownstreamChangeListener(e,t){var r=this.patchControlFor(e);r.downstreamChangeListeners||(r.downstreamChangeListeners=[]),r.downstreamChangeListeners.push(t),this.setRefreshHandler(e,e=>{this.reloadAndSync(e)})}reloadAndSync(e){var t=this.patchControlFor(e),r=this;if(t.reloading)t.outOfDate=!0;else{t.reloading=!0;var n=1e3,i=function(){r.reload(r.store,e,function(e,r,s){if(e){if(t.downstreamChangeListeners)for(let e=0;e<t.downstreamChangeListeners.length;e++)t.downstreamChangeListeners[e]();t.reloading=!1,t.outOfDate&&(t.outOfDate=!1,i())}else t.reloading=!1,s&&0===s.status&&(t.reloading=!0,n*=2,setTimeout(i,n))})};i()}}setRefreshHandler(e,t){let r=this.getUpdatesVia(e);var n=t,i=this,s=this,o=1500,a=0;if(!r)return!1;r=(0,pr.join)(r,e.value);const u=r.replace(/^http:/,"ws:").replace(/^https:/,"wss:");var c=function(){var t;if("undefined"!=typeof WebSocket)t=new WebSocket(u);else{if("undefined"==typeof window||!window.WebSocket)return;t=window.WebSocket(u)}t.onopen=function(){o=1500,this.send("sub "+e.value),a&&s.requestDownstreamAction(e,n)};var r=i.patchControlFor(e);r.upstreamCount=0,t.onerror=function(e){},t.onclose=function(e){o*=2,a+=1,setTimeout(function(){c()},o)},t.onmessage=function(t){if(t.data&&"pub"===t.data.slice(0,3)){if("upstreamCount"in r&&(r.upstreamCount-=1,r.upstreamCount>=0))return;r.upstreamCount=0,i.requestDownstreamAction(e,n)}}};return c(),!0}updateMany(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const r=e.concat(t).map(e=>e.why),n=this,i=[];r.forEach(e=>{i.find(t=>t.equals(e))||i.push(e)});const s=i.map(r=>n.update(e.filter(e=>e.why.equals(r)),t.filter(e=>e.why.equals(r))));return s.length,Promise.all(s)}constructSparqlUpdateQuery(e,t,r){var n=this.contextWhere(r),i="";if(n.length){if(e.length){i+="DELETE { ";for(let t=0;t<e.length;t++)i+=this.anonymizeNT(e[t])+"\n";i+=" }\n"}if(t.length){i+="INSERT { ";for(let e=0;e<t.length;e++)i+=this.anonymizeNT(t[e])+"\n";i+=" }\n"}i+=n}else{if(e.length){i+="DELETE DATA { ";for(let t=0;t<e.length;t++)i+=this.anonymizeNT(e[t])+"\n";i+=" } \n"}if(t.length){e.length&&(i+=" ; "),i+="INSERT DATA { ";for(let e=0;e<t.length;e++)i+=this.nTriples(t[e])+"\n";i+=" }\n"}}return i}constructN3PatchQuery(e,t,r){var n="\n@prefix solid: <http://www.w3.org/ns/solid/terms#>.\n@prefix ex: <http://www.example.org/terms#>.\n\n_:patch\n";return r&&r.length>0&&(n+=`\n solid:where {\n ${r.map(e=>this.anonymizeNT(e)).join("\n ")}\n };`),e.length>0&&(n+=`\n solid:deletes {\n ${e.map(e=>this.anonymizeNT(e)).join("\n ")}\n };`),t.length>0&&(n+=`\n solid:inserts {\n ${t.map(e=>this.anonymizeNT(e)).join("\n ")}\n };`),n+=" a solid:InsertDeletePatch .\n"}update(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!r){var s=this;return new Promise(function(r,o){s.update(e,t,function(e,t,n){t?r():o(new Error(n))},n,i)})}try{var o=this.store,a=e?(0,nr.ok)(e)?e.statements:e instanceof Array?e:[e]:[],u=t?(0,nr.ok)(t)?t.statements:t instanceof Array?t:[t]:[];if(!(a instanceof Array))throw new Error("Type Error "+typeof a+": "+a);if(!(u instanceof Array))throw new Error("Type Error "+typeof u+": "+u);if(0===a.length&&0===u.length)return r(null,!0);var c=a.length?a[0].graph:u[0].graph;if(!c){let e="Error patching: statement does not specify which document to patch:"+a[0]+", "+u[0];throw new Error(e)}if("NamedNode"!==c.termType){let e="Error patching: document not a NamedNode:"+a[0]+", "+u[0];throw new Error(e)}var h=this.patchControlFor(c),l=Date.now(),d=["subject","predicate","object","why"],f={delete:a,insert:u};["insert","delete"].map(function(e){f[e].map(function(e){if(!c.equals(e.graph))throw new Error("update: destination "+c+" inconsistent with delete quad "+e.graph);d.map(function(t){if(void 0===e[t])throw new Error("update: undefined "+t+" of statement.")})})});var p=this.editable(c.value,o);if(!1===p)throw new Error("Update: Can't make changes in uneditable "+c);if(void 0===p){if(n)throw new Error("Update: Loaded "+c+"but still can't figure out what editing protocol it supports.");return void this.store.fetcher.load(c).then(n=>{this.update(e,t,r,!0,i)},n=>{if(404!==n.response.status)throw new Error(`Update: Can't get updatability status ${c} before patching: ${n}`);this.update(e,t,r,!0,i)})}if(p.indexOf("SPARQL")>=0||p.indexOf("N3PATCH")>=0){var g=p.indexOf("SPARQL")>=0,y=[];a.length&&(y=this.statementArrayBnodes(a)),u.length&&(y=y.concat(this.statementArrayBnodes(u)));var v=this.bnodeContext(y,c),m=g?this.constructSparqlUpdateQuery(a,u,v):this.constructN3PatchQuery(a,u,v);i.contentType=g?"application/sparql-update":"text/n3",h.pendingUpstream=h.pendingUpstream?h.pendingUpstream+1:1,"upstreamCount"in h&&(h.upstreamCount+=1),this.fire(c.value,m,(e,t,n,i)=>{if(i.elapsedTimeMs=Date.now()-l,t){try{o.remove(a)}catch(e){t=!1,n="Remote Ok BUT error deleting "+a.length+" from store!!! "+e}for(let e=0;e<u.length;e++)o.add(u[e].subject,u[e].predicate,u[e].object,c)}if(r(e,t,n,i),h.pendingUpstream-=1,0===h.pendingUpstream&&h.downstreamAction){var s=h.downstreamAction;delete h.downstreamAction,s(c)}},i)}else if(p.indexOf("DAV")>=0)this.updateDav(c,a,u,r,i);else{if(!(p.indexOf("LOCALFILE")>=0))throw new Error("Unhandled edit method: '"+p+"' for "+c);try{this.updateLocalFile(c,a,u,r,i)}catch(e){r(c.value,!1,"Exception trying to write back file <"+c.value+">\n")}}}catch(e){r(void 0,!1,"Exception in update: "+e+"\n"+Sr.stackString(e))}}updateDav(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},s=this.store;var o=s.any(e,this.ns.link("request"));if(!o)throw new Error("No record of our HTTP GET request for document: "+e);var a=s.any(o,this.ns.link("response"));if(!a)return null;var u=s.the(a,this.ns.httph("content-type")).value;let c=s.statementsMatching(void 0,void 0,void 0,e).slice();for(let e=0;e<t.length;e++)Sr.RDFArrayRemove(c,t[e]);for(let e=0;e<r.length;e++)c.push(r[e]);const h=this.serialize(e.value,c,u);var l,d=s.the(a,this.ns.httph("content-location"));return d&&(l=(0,pr.join)(d.value,l)),i.contentType=u,i.noMeta=!0,i.body=h,s.fetcher.webOperation("PUT",l,i).then(i=>{if(!i.ok)throw new Error(i.error);for(let e=0;e<t.length;e++)s.remove(t[e]);for(let t=0;t<r.length;t++)s.add(r[t].subject,r[t].predicate,r[t].object,e);n(e.value,i.ok,i.responseText,i)}).catch(t=>{n(e.value,!1,t.message,t)})}updateLocalFile(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};const s=this.store;let o=s.statementsMatching(void 0,void 0,void 0,e).slice();for(let e=0;e<t.length;e++)Sr.RDFArrayRemove(o,t[e]);for(let e=0;e<r.length;e++)o.push(r[e]);var a=e.value.lastIndexOf(".");if(a<1)throw new Error("Rewriting file: No filename extension: "+e.value);var u=e.value.slice(a+1);let c=ki.CONTENT_TYPE_BY_EXT[u];if(!c)throw new Error("File extension ."+u+" not supported for data write");i.body=this.serialize(e.value,o,c),i.contentType=c,s.fetcher.webOperation("PUT",e.value,i).then(i=>{if(!i.ok)return n(e.value,!1,i.error);for(let e=0;e<t.length;e++)s.remove(t[e]);for(let t=0;t<r.length;t++)s.add(r[t].subject,r[t].predicate,r[t].object,e);n(e.value,!0,"")})}serialize(e,t,r){const n=this.store;let i;if("string"==typeof t)return t;var s=Tr(n);switch(s.suggestNamespaces(n.namespaces),s.setBase(e),r){case"text/xml":case"application/rdf+xml":i=s.statementsToXML(t);break;case"text/n3":case"text/turtle":case"application/x-turtle":case"application/n3":i=s.statementsToN3(t);break;default:throw new Error("Content-type "+r+" not supported for data serialization")}return i}put(e,t,r,n){const i=this.store;let s;return Promise.resolve().then(()=>(s=this.serialize(e.value,t,r),i.fetcher.webOperation("PUT",e.value,{contentType:r,body:s}))).then(r=>{if(!r.ok)return n(e.value,r.ok,r.error,r);delete i.fetcher.nonexistent[e.value],delete i.fetcher.requested[e.value],"string"!=typeof t&&t.map(e=>{i.addStatement(e)}),n(e.value,r.ok,"",r)}).catch(t=>{n(e.value,!1,t.message)})}reload(e,t,r){var n=Date.now();e.fetcher.nowOrWhenFetched(t.value,{force:!0,noMeta:!0,clearPreviousData:!0},function(e,i,s){if(e)if(s.onErrorWasCalled||200!==s.status)r(!1,"Non-HTTP error reloading data: "+i,s);else{var o=Date.now()-n;t.reloadTimeTotal||(t.reloadTimeTotal=0),t.reloadTimeCount||(t.reloadTimeCount=0),t.reloadTimeTotal+=o,t.reloadTimeCount+=1,r(!0)}else r(!1,"Error reloading data: "+i,s)})}}const Ni={...mn,fetcher:(e,t)=>new ki(e,t),graph(){return new Kr(arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0)||{rdfFactory:mn})},lit(e,t,r){return this.literal(""+e,t||r)},st(e,t,r,n){return this.quad(e,t,r,n)}},Ui=Ni;class Oi{constructor(e,t){this.parent=e,this.via=t,this.connected=!1,this.pending={},this.subscribed={},this.socket={};try{this.socket=new WebSocket(t),this.socket.onopen=this.onOpen,this.socket.onclose=this.onClose,this.socket.onmessage=this.onMessage,this.socket.onerror=this.onError}catch(e){this.onError(e)}}_decode(e){var t,r,n,i,s,o,a;for(r in i={},s=function(){var r,n,i,s;for(s=[],r=0,n=(i=e.split("&")).length;r<n;r++)t=i[r],s.push(t.split("="));return s}())t=s[r],a=(o=[decodeURIComponent(t[0]),decodeURIComponent(t[1])])[1],null==i[n=o[0]]&&(i[n]=[]),i[n].push(a);return i}_send(e,t,r){var n,i;return i=[e,t,r].join(" "),"function"==typeof(n=this.socket).send?n.send(i):void 0}_subscribe(e){return this._send("sub",e,""),this.subscribed[e]=!0,this.subscribed[e]}onClose(e){var t;for(t in this.connected=!1,this.subscribed)this.pending[t]=!0;return this.subscribed={},this.subscribed}onError(e){throw new Error("onError"+e)}onMessage(e){var t,r;return"ping"===(r=e.data.split(" "))[0]?"function"==typeof(t=this.socket).send?t.send("pong "+r.slice(1).join(" ")):void 0:"pub"===r[0]?this.parent.onUpdate(r[1],this._decode(r[2])):void 0}onOpen(e){var t,r;for(r in this.connected=!0,t=[],this.pending)delete this.pending[r],t.push(this._subscribe(r));return t}subscribe(e){return this.connected?this._subscribe(e):(this.pending[e]=!0,this.pending[e])}}class Li{constructor(e){this.fetcher=e,this.graph={},this.via={},this.fetcher.addCallback("headers",this.onHeaders)}onHeaders(e){var t,r,n;return null==e.headers||"undefined"==typeof WebSocket||null===WebSocket||(t=e.headers.etag,n=e.headers["updates-via"],r=e.uri,t&&n&&(this.graph[r]={etag:t,via:n},this.register(n,r))),!0}onUpdate(e,t){return this.fetcher.refresh(Ui.namedNode(e))}register(e,t){return null==this.via[e]&&(this.via[e]=new Oi(this,e)),this.via[e].subscribe(t)}}const Di={};for(const e in Ui)"function"==typeof Ui[e]&&(Di[e]=Ui[e].bind(Ui));const{fetcher:ji,graph:Mi,lit:Bi,st:Hi,namedNode:qi,variable:Ki,blankNode:Vi,defaultGraph:$i,literal:Wi,quad:Ji,triple:zi}=Di,Xi=new Ur,Gi=e=>Xi.fromNT(e),Yi=Or.fromValue,Qi=tr.nextId;class Zi extends Kr{constructor(e){super(e),(0,Yt.A)(this,"fetcher",void 0),this.fetcher=new ki(this,{})}}class es extends Zi{constructor(e){super(e),(0,Yt.A)(this,"updater",void 0),this.updater=new Pi(this)}}const ts=Ar()(e),rs=qi("http://www.iana.org/assignments/link-relations/acl");function ns(e){const t=ts;function r(e,r,n,i={}){const s=i.public||[],o=Mi(),a=_r("http://www.w3.org/ns/auth/acl#");let u=o.sym(`${n}#a1`);const c=o.sym(n),h=o.sym(e);if(o.add(u,t.rdf("type"),a("Authorization"),c),o.add(u,a("accessTo"),h,c),i.defaultForNew&&o.add(u,a("default"),h,c),o.add(u,a("agent"),r,c),o.add(u,a("mode"),a("Read"),c),o.add(u,a("mode"),a("Write"),c),o.add(u,a("mode"),a("Control"),c),s.length){u=o.sym(`${n}#a2`),o.add(u,t.rdf("type"),a("Authorization"),c),o.add(u,a("accessTo"),h,c),o.add(u,a("agentClass"),t.foaf("Agent"),c);for(let e=0;e<s.length;e++)o.add(u,a("mode"),a(s[e]),c)}return Ir(c,o,n)}return{findAclDocUrl:async function(t){await e.fetcher.load(t);const r=e.any(t,rs);if(!r)throw new Error(`No ACL link discovered for ${t}`);return r.value},setACLUserPublic:function(t,n,i){const s=e.any(e.sym(t),rs);return Promise.resolve().then(()=>s||function(t){const r=e.fetcher;if(!r)throw new Error("Cannot fetch ACL rel, store has no fetcher");return r.load(t).then(r=>{if(!r.ok)throw new Error("fetchACLRel: While loading:"+r.error);const n=e.any(e.sym(t),rs);if(!n)throw new Error("fetchACLRel: No Link rel=ACL header for "+t);return n})}(t).catch(e=>{throw new Error(`Error fetching rel=ACL header for ${t}: ${e}`)})).then(s=>{const o=r(t,n,s.uri,i);if(!e.fetcher)throw new Error("Cannot PUT this, store has no fetcher");return e.fetcher.webOperation("PUT",s.uri,{data:o,contentType:"text/turtle"}).then(e=>{if(!e.ok)throw new Error("Error writing ACL text: "+e.error);return s})})},genACLText:r}}const is=()=>{let{SolidAppContext:e}=window;if(e||={},e.viewingNoAuthPage=!1,e.noAuth&&window.document){if(window.document.location.href.startsWith(e.noAuth)){e.viewingNoAuthPage=!0;const t=new URLSearchParams(window.document.location.search);if(t){let r=e.viewedPage=t.get("uri")||null;if(r&&(r=decodeURI(r),!r.startsWith(e.noAuth))){const t=r.split(/\//);e.idp=t[0]+"//"+t[2],e.viewingNoAuthPage=!1}}}}return e};function ss(){const{$SolidTestEnvironment:e}=window;if(void 0!==e&&e.username)return t("Assuming the user is "+e.username),qi(e.username);if("undefined"!=typeof document&&document.location&&"http://localhost"===(""+document.location).slice(0,16)){const e=document.getElementById("appTarget");if(!e)return null;const r=e.getAttribute("testID");return r?(t("Assuming user is "+r),qi(r)):null}return null}class os{session;constructor(e){this.session=e}get authSession(){return this.session}currentUser(){const e=is();return e.viewingNoAuthPage?qi(e.webId):this&&this.session&&this.session.info&&this.session.info.webId&&this.session.info.isLoggedIn?qi(this.session.info.webId):ss()}async checkUser(e){const r=new URL(window.location.href).hash;r&&window.localStorage.setItem("preLoginRedirectHash",r),this.session.events.on(Ke,e=>{t(`Session restored to ${e}`),document.location.toString()!==e&&history.replaceState(null,"",e)});const n=new URL(window.location.href);n.hash="",await this.session.handleIncomingRedirect({restorePreviousSession:!0,url:n.href});const i=window.localStorage.getItem("preLoginRedirectHash");if(i){const e=new URL(window.location.href);e.hash!==i&&(history.pushState?history.pushState(null,document.title,i):location.hash=i,e.hash=i),window.localStorage.setItem("preLoginRedirectHash","")}let s=ss();if(s)return Promise.resolve(e?e(s):s);const o=this.webIdFromSession(this.session.info);return o&&(s=this.saveUser(o)),s&&t(`(Logged in as ${s} by authentication)`),Promise.resolve(e?e(s):s)}saveUser(e,t){let r;if(e){r="string"==typeof e?e:e.uri;const n=qi(r);return t&&(t.me=n),n}return null}webIdFromSession(e){return e?.webId&&e.isLoggedIn?e.webId:null}}function as(e){return qi(e.uri+"#id"+Date.now())}function us(e){return!e||`${window.location.origin}/`!==new URL(e.value).origin}const cs="index.ttl#this";function hs(e,t){const r=ts;async function n(t,r,n){await e.fetcher.load(t);const i=e.any(t,new rr.A("http://www.iana.org/assignments/link-relations/acl"));if(!i)throw new Error("Chat ACL doc not found!");const s=`\n @prefix acl: <http://www.w3.org/ns/auth/acl#>.\n <#owner>\n a acl:Authorization;\n acl:agent <${r.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Write, acl:Control.\n <#invitee>\n a acl:Authorization;\n acl:agent <${n.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Append.\n `;await e.fetcher.webOperation("PUT",i.value,{data:s,contentType:"text/turtle"})}async function i(t,n){const i=e.any(n,r.solid("privateTypeIndex"));if(!i)throw new Error("Private type index not found!");await e.fetcher.load(i);const s=as(i),o=[Hi(s,r.rdf("type"),r.solid("TypeRegistration"),i.doc()),Hi(s,r.solid("forClass"),r.meeting("LongChat"),i.doc()),Hi(s,r.solid("instance"),t,i.doc())];await new Promise((t,r)=>{e.updater.update([],o,function(e,n,i){n?t(null):r(new Error(i))})})}async function s(r){const n=await t.loadMe(),i=function(e,t){const r=new URL(`IndividualChats/${new URL(e.value).host}/`,t.value).toString();return new rr.A(r)}(r,await t.getPodRoot(n));let s=!0;try{await e.fetcher.load(new rr.A(i.value+"index.ttl#this"))}catch(e){s=!1}return{me:n,chatContainer:i,exists:s}}async function o(e,t){return(await a({me:t,newBase:e.value})).newInstance}function a(t){const n=e,i=n.updater;if(t.me&&!t.me.uri)throw new Error("chat mintNew: Invalid userid "+t.me);const s=t.newInstance=t.newInstance||n.sym(t.newBase+cs),o=s.doc();return n.add(s,r.rdf("type"),r.meeting("LongChat"),o),n.add(s,r.dc("title"),"Chat channel",o),n.add(s,r.dc("created"),Yi(new Date(Date.now())),o),t.me&&n.add(s,r.dc("author"),t.me,o),new Promise(function(e,r){i?.put(o,n.statementsMatching(void 0,void 0,void 0,o),"text/turtle",function(n,i,o){i?e({...t,newInstance:s}):r(new Error("FAILED to save new chat channel at: "+n+" : "+o))})})}async function u(t,n){await e.fetcher.load(t.doc());const i=e.any(t,r.ldp("inbox"),void 0,t.doc());if(!i)throw new Error(`Invitee inbox not found! ${t.value}`);const s=`\n <> a <http://www.w3.org/ns/pim/meeting#LongChatInvite> ;\n ${r.rdf("seeAlso")} <${n.value}> .\n `,o=await(e.fetcher?.webOperation("POST",i.value,{data:s,contentType:"text/turtle"})),a=o?.headers.get("location");if(!a)throw new Error(`Invite sending returned a ${o?.status}`)}return{setAcl:n,addToPrivateTypeIndex:i,findChat:s,createChatThing:o,getChat:async function(e,t=!0){const{me:r,chatContainer:a,exists:c}=await s(e);if(c)return new rr.A(a.value+cs);if(t){const t=await o(a,r);return await u(e,t),await n(a,r,e),await i(t,r),t}return null},sendInvite:u,mintNew:a}}function ls(e,t,r,n,i){return{createInboxFor:async function(e,i){const s=await t.loadMe(),o=`${(await t.getPodRoot(s)).value}p2p-inboxes/${encodeURIComponent(i)}/`;return await n.createContainer(o),await r.setSinglePeerAccess({ownerWebId:s.value,peerWebId:e,accessToModes:"acl:Append",target:o}),o},getNewMessages:async function(e){e||(e=await t.loadMe());const r=await t.getMainInbox(e);return(await n.getContainerMembers(r)).filter(e=>!n.isContainer(e))},markAsRead:async function(t,r){const n=await e.fetcher._fetch(t);if(200!==n.status)throw new Error(`Not OK! ${t}`);const i=function(e,t){const r=t.getUTCFullYear(),n=("0"+(t.getUTCMonth()+1)).slice(-2),i=("0"+t.getUTCDate()).slice(-2),s=e.split("/"),o=s[s.length-1];return new URL(`./archive/${r}/${n}/${i}/${o}`,e).toString()}(t,r),s={method:"PUT",body:await n.text(),headers:[["Content-Type",n.headers.get("Content-Type")||"application/octet-stream"]]};"2"===(await e.fetcher._fetch(i,s)).status.toString()[0]&&await e.fetcher._fetch(t,{method:"DELETE"})}}}class ds extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}}class fs extends ds{}class ps extends ds{}class gs extends ds{}class ys extends ds{}class vs extends ds{}class ms extends ds{}class ws extends ds{status;constructor(e,t){super(t),this.status=e}}function bs(e,t,n){const i=ts;async function s(t){await o(t);const s=function(e){const t=e.uri.replace("/profile/","/").replace("/public/","/").split("/").slice(0,-1).join("/")+"/Settings/";return qi(t+"Preferences.ttl")}(t);let a;try{a=await n.followOrCreateLink(t,i.space("preferencesFile"),s,t.doc())}catch(e){if(r(`User ${t} has no pointer in profile to preferences file.`),e instanceof vs)throw e;if(e instanceof ms)throw e;if(e instanceof fs)throw e;if(e instanceof ps)throw e;if(e instanceof gs)throw e;if(e instanceof ws)throw e;throw e}try{await e.fetcher.load(a)}catch(e){const n=`Unable to load preference of user ${t}: ${e}`;if(r(n),401===e.response.status)throw new fs;if(403===e.response.status){if(us(a))throw new ps;throw new gs}throw new Error(n)}return a}async function o(t){if(!t)throw new Error("loadProfile: no user given.");try{await e.fetcher.load(t.doc())}catch(e){throw new Error(`Unable to load profile of user ${t}: ${e}`)}return t.doc()}function a(t){return e.any(t,i.space("storage"),void 0,t.doc())}return{loadMe:async function(){const r=t.currentUser();if(null===r)throw new Error("Current user not found! Not logged in?");return await e.fetcher.load(r.doc()),r},getPodRoot:function(e){const t=a(e);if(!t)throw new Error("User pod root not found!");return t},getMainInbox:async function(t){await e.fetcher.load(t);const r=e.any(t,i.ldp("inbox"),void 0,t.doc());if(!r)throw new Error("User main inbox not found!");return r},findStorage:a,loadPreferences:s,loadProfile:o,silencedLoadPreferences:async function(e){try{return await s(e)}catch(e){return}}}}function _s(e,t,n,i){const s=ts;async function o(t){if(!t)throw new Error("loadTypeIndexesFor: No user given");const o=await n.loadProfile(t),a=h(t);let u;try{u=await i.followOrCreateLink(t,s.solid("publicTypeIndex"),a,o)}catch(e){r(`User ${t} has no pointer in profile to publicTypeIndex file.`)}const c=u?[{label:"public",index:u,agent:t}]:[];let d,f;try{d=await n.silencedLoadPreferences(t)}catch(e){d=null}if(d){const n=l(d);let a;try{a=e.any(t,s.solid("privateTypeIndex"),void 0,o)||await i.followOrCreateLink(t,s.solid("privateTypeIndex"),n,d)}catch(e){r(`User ${t} has no pointer in preference file to privateTypeIndex file.`)}f=a?[{label:"private",index:a,agent:t}]:[]}else f=[];const p=c.concat(f);if(0===p.length)return p;const g=p.map(e=>e.index);try{await e.fetcher.load(g)}catch(e){r("Problems loading type index: ",e)}return p}async function a(t){let i;try{i=await n.silencedLoadPreferences(t)}catch(e){r(`User ${t} has no pointer in profile to preferences file.`)}if(i){const r=e.each(t,s.solid("community"),void 0,i).concat(e.each(t,s.solid("community"),void 0,t.doc()));let n=[];for(const e of r)n=n.concat(await o(e));return n}return[]}async function u(e){return(await o(e)).concat((await a(e)).flat())}async function c(e,t){const r=await u(t);let n=[];for(const t of r){const r=await d(t,e);n=n.concat(r)}return n}function h(e){return qi(e.doc().dir()?.uri+"publicTypeIndex.ttl")}function l(e){return qi(e.doc().dir()?.uri+"privateTypeIndex.ttl")}async function d(t,r){const n=t.index,i=[],o=e.statementsMatching(null,s.solid("instance"),null,n).concat(e.statementsMatching(null,s.solid("instanceContainer"),null,n)).map(e=>e.subject);for(const a of o){const o=e.any(a,s.solid("forClass"),null,n);if(!r||o.sameTerm(r)){const r=e.each(a,s.solid("instance"),null,n);for(const e of r)i.push({instance:e,type:o,scope:t});const u=e.each(a,s.solid("instanceContainer"),null,n);for(const r of u)await e.fetcher.load(r),i.push({instance:qi(r.value),type:o,scope:t})}}return i}return{registerInTypeIndex:async function(t,r,n){const i=as(r),o=[Hi(i,s.rdf("type"),s.solid("TypeRegistration"),r),Hi(i,s.solid("forClass"),n,r),Hi(i,s.solid("instance"),t,r)];try{await e.updater.update([],o)}catch(e){const n=`Unable to register ${t} in index ${r}: ${e}`;return console.warn(n),null}return i},getRegistrations:function(t,r){return e.each(void 0,s.solid("instance"),t).filter(t=>e.holds(t,s.solid("forClass"),r))},loadTypeIndexesFor:o,loadCommunityTypeIndexes:a,loadAllTypeIndexes:u,getScopedAppInstances:c,getAppInstances:async function(e){const r=t.currentUser();if(!r)throw new Error("getAppInstances: Must be logged in to find apps.");return(await c(e,r)).map(e=>e.instance)},suggestPublicTypeIndex:h,suggestPrivateTypeIndex:l,deleteTypeIndexRegistration:async function(t){const r=e.the(null,s.solid("instance"),t.instance,t.scope.index);if(!r)throw new Error(`deleteTypeIndexRegistration: No registration found for ${t.instance}`);const n=e.statementsMatching(r,null,null,t.scope.index);await e.updater.update(n,[])},getScopedAppsFromIndex:d}}const Ss=function(e,n){t("SolidLogic: Unique instance created. There should only be one of these.");const i=Mi();ji(i,{fetch:e.fetch}),i.updater=new Pi(i),i.features=[];const s=new os(n),o=ns(i),a=function(e){function t(t){return e.statementsMatching(t,qi("http://www.w3.org/ns/ldp#contains"),void 0).map(e=>e.object)}function r(e){const t=e.value;return"/"===t.charAt(t.length-1)}return{isContainer:r,createContainer:async function(t){if(!r(qi(t)))throw new Error(`Not a container URL ${t}`);const n=await e.fetcher._fetch(t,{method:"PUT",headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:'<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'},body:" "});if("2"!==n.status.toString()[0])throw new Error(`Not OK: got ${n.status} response while creating container at ${t}`)},getContainerElements:t,getContainerMembers:async function(r){return await e.fetcher.load(r),t(r)}}}(i),u=function(e,n,i){async function s(t){let r;try{r=await e.fetcher.load(t)}catch(r){if(404!==r.response.status){if(401===r.response.status)throw new fs;if(403===r.response.status){if(us(t))throw new ps;throw new gs}const e="createIfNotExists doc load error NOT 404: "+t+": "+r;throw new ws(r.status,r.message+e)}try{await e.fetcher.webOperation("PUT",t,{data:"",contentType:"text/turtle"})}catch(e){throw new ms("createIfNotExists: PUT FAILED: "+t+": "+e)}await e.fetcher.load(t)}return r}return{recursiveDelete:async function r(s){try{if(i.isContainer(s)){const t=await n.findAclDocUrl(s);await e.fetcher._fetch(t,{method:"DELETE"});const o=await i.getContainerMembers(s);await Promise.all(o.map(e=>r(e)))}const t=s.value;return e.fetcher._fetch(t,{method:"DELETE"})}catch(e){t(`Please manually remove ${s.value} from your system.`,e)}},setSinglePeerAccess:async function(t){let r=["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","",`<#alice> a acl:Authorization;\n acl:agent <${t.ownerWebId}>;`,` acl:accessTo <${t.target}>;`,` acl:default <${t.target}>;`," acl:mode acl:Read, acl:Write, acl:Control.",""].join("\n");t.accessToModes&&(r+=["<#bobAccessTo> a acl:Authorization;",` acl:agent <${t.peerWebId}>;`,` acl:accessTo <${t.target}>;`,` acl:mode ${t.accessToModes}.`,""].join("\n")),t.defaultModes&&(r+=["<#bobDefault> a acl:Authorization;",` acl:agent <${t.peerWebId}>;`,` acl:default <${t.target}>;`,` acl:mode ${t.defaultModes}.`,""].join("\n"));const i=await n.findAclDocUrl(qi(t.target));return e.fetcher._fetch(i,{method:"PUT",body:r,headers:[["Content-Type","text/turtle"]]})},createEmptyRdfDoc:async function(t,r){await e.fetcher.webOperation("PUT",t.uri,{data:`# ${new Date} ${r}\n `,contentType:"text/turtle"})},followOrCreateLink:async function(t,n,i,o){await e.fetcher.load(o);const a=e.any(t,n,null,o);if(a)return a;if(!e.updater.editable(o)){const e=`followOrCreateLink: cannot edit ${o.value}`;throw r(e),new vs(e)}try{await e.updater.update([],[Hi(t,n,i,o)])}catch(e){throw r(`followOrCreateLink: Error making link in ${o} to ${i}: ${e}`),new ms(e)}try{await s(i)}catch(e){throw r(`followOrCreateLink: Error loading or saving new linked document: ${i}: ${e}`),e}return i},loadOrCreateIfNotExists:s}}(i,o,a),c=bs(i,s,u),h=hs(i,c),l=ls(i,c,u,a),d=_s(i,s,c,u);return t("SolidAuthnLogic initialized"),{store:i,authn:s,acl:o,inbox:l,chat:h,profile:c,typeIndex:d,load:function(e){return i.fetcher.load(e)},updatePromise:function(e,t=[]){return new Promise((r,n)=>{i.updater.update(e,t,function(e,t,i){t?r():n(new Error(i))})})},clearStore:function(){i.statements.slice().forEach(i.remove.bind(i))}}}({fetch:async(e,t)=>{const r=t&&t.credentials&&"omit"==t.credentials;return Gt.info.webId&&!r?Gt.fetch(e,t):window.fetch(e,t)}},Gt);t("Unique quadstore initialized.");const Es=[{name:"Solid Community",uri:"https://solidcommunity.net"},{name:"Solid Web",uri:"https://solidweb.org"},{name:"Solid Web ME",uri:"https://solidweb.me"},{name:"Inrupt.com",uri:"https://login.inrupt.com"}];function xs(){const e=[...Es],{host:t,origin:r}=new URL(location.href),n=e.map(({uri:e})=>new URL(e).host);return n.includes(t)||n.some(e=>function(e,t){const r=e.length-t.length-1;return r>0&&"."===e[r]&&e.endsWith(t)}(t,e))||e.unshift({name:t,uri:r}),e}const As=Ss.authn,Fs=Ss.authn.authSession,Ts=Ss.store})(),u})());
31
+ t.read=function(e,t,r,n,i){var o,s,a=8*i-n-1,u=(1<<a)-1,c=u>>1,h=-7,l=r?i-1:0,d=r?-1:1,f=e[t+l];for(l+=d,o=f&(1<<-h)-1,f>>=-h,h+=a;h>0;o=256*o+e[t+l],l+=d,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=n;h>0;s=256*s+e[t+l],l+=d,h-=8);if(0===o)o=1-c;else{if(o===u)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),o-=c}return(f?-1:1)*s*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var s,a,u,c=8*o-i-1,h=(1<<c)-1,l=h>>1,d=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=h):(s=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-s))<1&&(s--,u*=2),(t+=s+l>=1?d/u:d*Math.pow(2,1-l))*u>=2&&(s++,u/=2),s+l>=h?(a=0,s=h):s+l>=1?(a=(t*u-1)*Math.pow(2,i),s+=l):(a=t*Math.pow(2,l-1)*Math.pow(2,i),s=0));i>=8;e[r+f]=255&a,f+=p,a/=256,i-=8);for(s=s<<i|a,c+=i;c>0;e[r+f]=255&s,f+=p,s/=256,c-=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,u=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,u,c,h,l){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 d=a(o.x5c[0]);o=i.getPublicKeyFromCertHex(d)}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,u,c,h,l)}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 u=e.parseJwt(t).payload;if(!u.iss)return n.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(u.iss!==r)return n.Log.error("JoseUtil._validateJwt: Invalid issuer in token",u.iss),Promise.reject(new Error("Invalid issuer in token: "+u.iss));if(!u.aud)return n.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(u.aud===i||Array.isArray(u.aud)&&u.aud.indexOf(i)>=0))return n.Log.error("JoseUtil._validateJwt: Invalid audience in token",u.aud),Promise.reject(new Error("Invalid audience in token: "+u.aud));if(u.azp&&u.azp!==i)return n.Log.error("JoseUtil._validateJwt: Invalid azp in token",u.azp),Promise.reject(new Error("Invalid azp in token: "+u.azp));if(!a){var c=s+o,h=s-o;if(!u.iat)return n.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(c<u.iat)return n.Log.error("JoseUtil._validateJwt: iat is in the future",u.iat),Promise.reject(new Error("iat is in the future: "+u.iat));if(u.nbf&&c<u.nbf)return n.Log.error("JoseUtil._validateJwt: nbf is in the future",u.nbf),Promise.reject(new Error("nbf is in the future: "+u.nbf));if(!u.exp)return n.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if(u.exp<h)return n.Log.error("JoseUtil._validateJwt: exp is in the past",u.exp),Promise.reject(new Error("exp is in the past:"+u.exp))}return Promise.resolve(u)},e._validateJwt=function(r,i,o,s,a,c,h){return e.validateJwtAttributes(r,o,s,a,c,h).then(function(e){try{return t.JWS.verify(r,i,u)?e:(n.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(e){return n.Log.error(e&&e.message||e),Promise.reject(new Error("signature validation failed"))}})},e.hashString=function e(t,r){try{return o.Util.hashString(t,r)}catch(e){n.Log.error(e)}},e.hexToBase64Url=function e(t){try{return s(t)}catch(e){n.Log.error(e)}},e}()};var n=r(0);e.exports=t.default},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SigninResponse=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(3);t.SigninResponse=function(){function e(t){var r=arguments.length>1&&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,u=t.data,c=t.extraQueryParams,h=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 l 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,l,c[l]);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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0);t.InMemoryWebStorage=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._data={}}return e.prototype.getItem=function(e){return i.Log.debug("InMemoryWebStorage.getItem",e),this._data[e]},e.prototype.setItem=function(e,t){i.Log.debug("InMemoryWebStorage.setItem",e),this._data[e]=t},e.prototype.removeItem=function(e){i.Log.debug("InMemoryWebStorage.removeItem",e),delete this._data[e]},e.prototype.key=function(e){return Object.getOwnPropertyNames(this._data)[e]},n(e,[{key:"length",get:function(){return Object.getOwnPropertyNames(this._data).length}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserManager=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),o=r(10),s=r(39),a=r(15),u=r(45),c=r(47),h=r(18),l=r(8),d=r(20),f=r(11),p=r(4);t.UserManager=function(e){function t(){var r=arguments.length>0&&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]:d.TokenRevocationClient,l=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 u.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 l(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&&l.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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=(r(0),r(5)),o=r(40),s=r(41),a=r(43),u=r(6),c=r(1),h=r(8);t.UserManagerSettings=function(e){function t(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=r.popup_redirect_uri,i=r.popup_post_logout_redirect_uri,l=r.popupWindowFeatures,d=r.popupWindowTarget,f=r.silent_redirect_uri,p=r.silentRequestTimeout,g=r.automaticSilentRenew,y=void 0!==g&&g,v=r.validateSubOnSilentRenew,m=void 0!==v&&v,w=r.includeIdTokenInSilentRenew,_=void 0===w||w,S=r.monitorSession,b=void 0===S||S,E=r.monitorAnonymousSession,F=void 0!==E&&E,x=r.checkSessionInterval,A=void 0===x?2e3:x,k=r.stopCheckSessionOnError,P=void 0===k||k,T=r.query_status_response_type,I=r.revokeAccessTokenOnSignout,C=void 0!==I&&I,R=r.accessTokenExpiringNotificationTime,U=void 0===R?60:R,L=r.redirectNavigator,D=void 0===L?new o.RedirectNavigator:L,N=r.popupNavigator,O=void 0===N?new s.PopupNavigator:N,H=r.iframeNavigator,j=void 0===H?new a.IFrameNavigator:H,M=r.userStore,B=void 0===M?new u.WebStorageStateStore({store:c.Global.sessionStorage}):M;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var K=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 K._popup_redirect_uri=n,K._popup_post_logout_redirect_uri=i,K._popupWindowFeatures=l,K._popupWindowTarget=d,K._silent_redirect_uri=f,K._silentRequestTimeout=p,K._automaticSilentRenew=y,K._validateSubOnSilentRenew=m,K._includeIdTokenInSilentRenew=_,K._accessTokenExpiringNotificationTime=U,K._monitorSession=b,K._monitorAnonymousSession=F,K._checkSessionInterval=A,K._stopCheckSessionOnError=P,T?K._query_status_response_type=T:arguments[0]&&arguments[0].response_type?K._query_status_response_type=h.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":K._query_status_response_type="id_token",K._revokeAccessTokenOnSignout=C,K._redirectNavigator=D,K._popupNavigator=O,K._iframeNavigator=j,K._userStore=B,K}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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0);t.RedirectNavigator=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.prototype.prepare=function(){return Promise.resolve(this)},e.prototype.navigate=function(e){return e&&e.url?(e.useReplaceToNavigate?window.location.replace(e.url):window.location=e.url,Promise.resolve()):(i.Log.error("RedirectNavigator.navigate: No url provided"),Promise.reject(new Error("No url provided")))},n(e,[{key:"url",get:function(){return window.location.href}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PopupNavigator=void 0;var n=r(0),i=r(42);t.PopupNavigator=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.prototype.prepare=function(e){var t=new i.PopupWindow(e);return Promise.resolve(t)},e.prototype.callback=function e(t,r,o){n.Log.debug("PopupNavigator.callback");try{return i.PopupWindow.notifyOpener(t,r,o),Promise.resolve()}catch(e){return Promise.reject(e)}},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PopupWindow=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),o=r(3);t.PopupWindow=function(){function e(t){var r=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._promise=new Promise(function(e,t){r._resolve=e,r._reject=t});var n=t.popupWindowTarget||"_blank",o=t.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",n,o),this._popup&&(i.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return e.prototype.navigate=function(e){return this._popup?e&&e.url?(i.Log.debug("PopupWindow.navigate: Setting URL in popup"),this._id=e.id,this._id&&(window["popupCallback_"+e.id]=this._callback.bind(this)),this._popup.focus(),this._popup.window.location=e.url):(this._error("PopupWindow.navigate: no url provided"),this._error("No url provided")):this._error("PopupWindow.navigate: Error opening popup window"),this.promise},e.prototype._success=function(e){i.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(e)},e.prototype._error=function(e){i.Log.error("PopupWindow.error: ",e),this._cleanup(),this._reject(new Error(e))},e.prototype.close=function(){this._cleanup(!1)},e.prototype._cleanup=function(e){i.Log.debug("PopupWindow.cleanup"),window.clearInterval(this._checkForPopupClosedTimer),this._checkForPopupClosedTimer=null,delete window["popupCallback_"+this._id],this._popup&&!e&&this._popup.close(),this._popup=null},e.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},e.prototype._callback=function(e,t){this._cleanup(t),e?(i.Log.debug("PopupWindow.callback success"),this._success({url:e})):(i.Log.debug("PopupWindow.callback: Invalid response from popup"),this._error("Invalid response from popup"))},e.notifyOpener=function(e,t,r){if(window.opener){if(e=e||window.location.href){var n=o.UrlUtility.parseUrlFragment(e,r);if(n.state){var s="popupCallback_"+n.state,a=window.opener[s];a?(i.Log.debug("PopupWindow.notifyOpener: passing url message to opener"),a(e,t)):i.Log.warn("PopupWindow.notifyOpener: no matching callback found on opener")}else i.Log.warn("PopupWindow.notifyOpener: no state found in response url")}}else i.Log.warn("PopupWindow.notifyOpener: no window.opener. Can't complete notification.")},n(e,[{key:"promise",get:function(){return this._promise}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IFrameNavigator=void 0;var n=r(0),i=r(44);t.IFrameNavigator=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.prototype.prepare=function(e){var t=new i.IFrameWindow(e);return Promise.resolve(t)},e.prototype.callback=function e(t){n.Log.debug("IFrameNavigator.callback");try{return i.IFrameWindow.notifyParent(t),Promise.resolve()}catch(e){return Promise.reject(e)}},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IFrameWindow=void 0;var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0);t.IFrameWindow=function(){function e(t){var r=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._promise=new Promise(function(e,t){r._resolve=e,r._reject=t}),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.width=0,this._frame.height=0,window.document.body.appendChild(this._frame)}return e.prototype.navigate=function(e){if(e&&e.url){var t=e.silentRequestTimeout||1e4;i.Log.debug("IFrameWindow.navigate: Using timeout of:",t),this._timer=window.setTimeout(this._timeout.bind(this),t),this._frame.src=e.url}else this._error("No url provided");return this.promise},e.prototype._success=function(e){this._cleanup(),i.Log.debug("IFrameWindow: Successful response from frame window"),this._resolve(e)},e.prototype._error=function(e){this._cleanup(),i.Log.error(e),this._reject(new Error(e))},e.prototype.close=function(){this._cleanup()},e.prototype._cleanup=function(){this._frame&&(i.Log.debug("IFrameWindow: cleanup"),window.removeEventListener("message",this._boundMessageEvent,!1),window.clearTimeout(this._timer),window.document.body.removeChild(this._frame),this._timer=null,this._frame=null,this._boundMessageEvent=null)},e.prototype._timeout=function(){i.Log.debug("IFrameWindow.timeout"),this._error("Frame window timed out")},e.prototype._message=function(e){if(i.Log.debug("IFrameWindow.message"),this._timer&&e.origin===this._origin&&e.source===this._frame.contentWindow&&"string"==typeof e.data&&(e.data.startsWith("http://")||e.data.startsWith("https://"))){var t=e.data;t?this._success({url:t}):this._error("Invalid response from frame")}},e.notifyParent=function(e){i.Log.debug("IFrameWindow.notifyParent"),(e=e||window.location.href)&&(i.Log.debug("IFrameWindow.notifyParent: posting url message to parent"),window.parent.postMessage(e,location.protocol+"//"+location.host))},n(e,[{key:"promise",get:function(){return this._promise}},{key:"_origin",get:function(){return location.protocol+"//"+location.host}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserManagerEvents=void 0;var n=r(0),i=r(16),o=r(17);t.UserManagerEvents=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=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 n._userLoaded=new o.Event("User loaded"),n._userUnloaded=new o.Event("User unloaded"),n._silentRenewError=new o.Event("Silent renew error"),n._userSignedIn=new o.Event("User signed in"),n._userSignedOut=new o.Event("User signed out"),n._userSessionChanged=new o.Event("User session changed"),n}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.load=function(t){var r=!(arguments.length>1&&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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(0),o=r(1),s=r(17);t.Timer=function(e){function t(r){var n=arguments.length>1&&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<r&&(r=e),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*r)}},t.prototype.cancel=function(){this._timerHandle&&(i.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},t.prototype._callback=function(){var t=this._expiration-this.now;i.Log.debug("Timer.callback; "+this._name+" timer expires in:",t),this._expiration<=this.now&&(this.cancel(),e.prototype.raise.call(this))},n(t,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),t}(s.Event)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SilentRenewService=void 0;var n=r(0);t.SilentRenewService=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._userManager=t}return e.prototype.start=function(){this._callback||(this._callback=this._tokenExpiring.bind(this),this._userManager.events.addAccessTokenExpiring(this._callback),this._userManager.getUser().then(function(e){}).catch(function(e){n.Log.error("SilentRenewService.start: Error from getUser:",e.message)}))},e.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},e.prototype._tokenExpiring=function(){var e=this;this._userManager.signinSilent().then(function(e){n.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")},function(t){n.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",t.message),e._userManager.events._raiseSilentRenewError(t)})},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CordovaPopupNavigator=void 0;var n=r(21);t.CordovaPopupNavigator=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.prototype.prepare=function(e){var t=new n.CordovaPopupWindow(e);return Promise.resolve(t)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CordovaIFrameNavigator=void 0;var n=r(21);t.CordovaIFrameNavigator=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.prototype.prepare=function(e){e.popupWindowFeatures="hidden=yes";var t=new n.CordovaPopupWindow(e);return Promise.resolve(t)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Version="1.11.6"}])},e.exports=t()}},r={};function n(e){var i=r[e];if(void 0!==i)return i.exports;var o=r[e]={exports:{}};return t[e].call(o.exports,o,o.exports,n),o.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return(()=>{"use strict";function e(...e){console.log(...e)}function t(...e){console.warn(...e)}n.r(i),n.d(i,{ACL_LINK:()=>Zt,CrossOriginForbiddenError:()=>lr,FetchError:()=>yr,NotEditableError:()=>pr,NotFoundError:()=>fr,SameOriginForbiddenError:()=>dr,UnauthorizedError:()=>hr,WebOperationError:()=>gr,appContext:()=>tr,authSession:()=>kr,authn:()=>Ar,createTypeIndexLogic:()=>mr,getSuggestedIssuers:()=>xr,offlineTestID:()=>rr,solidLogicSingleton:()=>Er,store:()=>Pr});const r=new TextEncoder,o=new TextDecoder;function s(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const a=e=>(e=>{let t=e;"string"==typeof t&&(t=r.encode(t));const n=[];for(let e=0;e<t.length;e+=32768)n.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(n.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),u=e=>{let t=e;t instanceof Uint8Array&&(t=o.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class c extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}c.code="ERR_JOSE_GENERIC";class h extends c{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}h.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class l extends c{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}l.code="ERR_JWT_EXPIRED";class d extends c{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}d.code="ERR_JOSE_ALG_NOT_ALLOWED";class f extends c{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}f.code="ERR_JOSE_NOT_SUPPORTED";(class extends c{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends c{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class p extends c{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}p.code="ERR_JWS_INVALID";class g extends c{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}g.code="ERR_JWT_INVALID";(class extends c{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}).code="ERR_JWK_INVALID";class y extends c{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}y.code="ERR_JWKS_INVALID";class v extends c{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}v.code="ERR_JWKS_NO_MATCHING_KEY";class m extends c{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Symbol.asyncIterator,m.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class w extends c{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}w.code="ERR_JWKS_TIMEOUT";class _ extends c{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function S(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new f(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}_.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const b=crypto,E=e=>e instanceof CryptoKey,F=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function x(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function A(e,t){return e.name===t}function k(e){return parseInt(e.name.slice(4),10)}function P(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 T(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!A(e.algorithm,"HMAC"))throw x("HMAC");const r=parseInt(t.slice(2),10);if(k(e.algorithm.hash)!==r)throw x(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!A(e.algorithm,"RSASSA-PKCS1-v1_5"))throw x("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(k(e.algorithm.hash)!==r)throw x(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!A(e.algorithm,"RSA-PSS"))throw x("RSA-PSS");const r=parseInt(t.slice(2),10);if(k(e.algorithm.hash)!==r)throw x(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw x("Ed25519 or Ed448");break;case"Ed25519":if(!A(e.algorithm,"Ed25519"))throw x("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!A(e.algorithm,"ECDSA"))throw x("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 x(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}P(e,r)}function I(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const C=(e,...t)=>I("Key must be ",e,...t);function R(e,t,...r){return I(`Key for the ${e} algorithm must be `,t,...r)}const U=e=>!!E(e)||"KeyObject"===e?.[Symbol.toStringTag],L=["CryptoKey"];function D(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}function N(e){return D(e)&&"string"==typeof e.kty}const O=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new f('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 f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new f('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],i={...e};return delete i.alg,delete i.use,b.subtle.importKey("jwk",i,...n)},H=e=>u(e);let j,M;const B=e=>"KeyObject"===e?.[Symbol.toStringTag],K=async(e,t,r,n,i=!1)=>{let o=e.get(t);if(o?.[n])return o[n];const s=await O({...r,alg:n});return i&&Object.freeze(t),o?o[n]=s:e.set(t,{[n]:s}),s},V=(e,t)=>{if(B(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?H(r.k):(M||(M=new WeakMap),K(M,e,r,t))}if(N(e)){if(e.k)return u(e.k);M||(M=new WeakMap);return K(M,e,e,t,!0)}return e},q=(e,t)=>{if(B(e)){let r=e.export({format:"jwk"});return r.k?H(r.k):(j||(j=new WeakMap),K(j,e,r,t))}if(N(e)){if(e.k)return u(e.k);j||(j=new WeakMap);return K(j,e,e,t,!0)}return e};async function J(e,t,r){if("sign"===r&&(t=await q(t,e)),"verify"===r&&(t=await V(t,e)),E(t))return T(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(C(t,...L));return b.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(C(t,...L,"Uint8Array","JSON Web Key"))}const W=async(e,t,r,n)=>{const i=await J(e,t,"verify");F(e,i);const o=S(e,i.algorithm);try{return await b.subtle.verify(o,i,r,n)}catch{return!1}},$=(...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},z=e=>e?.[Symbol.toStringTag],Y=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},G=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&N(t)){if(function(e){return N(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&Y(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!U(t))throw new TypeError(R(e,t,...L,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${z(t)} instances for symmetric algorithms must be of type "secret"`)}};function X(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?G(t,r,n,e):((e,t,r,n)=>{if(n&&N(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&Y(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&Y(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!U(t))throw new TypeError(R(e,t,...L,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${z(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${z(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${z(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${z(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${z(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}X.bind(void 0,!1);const Q=X.bind(void 0,!0);const Z=function(e,t,r,n,i){if(void 0!==i.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!o.has(t))throw new f(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)},ee=(e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};async function te(e,t){if(!D(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return u(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new f('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return O({...e,alg:t});default:throw new f('Unsupported "kty" (Key Type) Parameter value')}}async function re(e,t,n){if(e instanceof Uint8Array&&(e=o.decode(e)),"string"!=typeof e)throw new p("Compact JWS must be a string or Uint8Array");const{0:i,1:a,2:c,length:h}=e.split(".");if(3!==h)throw new p("Invalid Compact JWS");const l=await async function(e,t,n){if(!D(e))throw new p("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new p('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new p("JWS Protected Header incorrect type");if(void 0===e.payload)throw new p("JWS Payload missing");if("string"!=typeof e.signature)throw new p("JWS Signature missing or incorrect type");if(void 0!==e.header&&!D(e.header))throw new p("JWS Unprotected Header incorrect type");let i={};if(e.protected)try{const t=u(e.protected);i=JSON.parse(o.decode(t))}catch{throw new p("JWS Protected Header is invalid")}if(!$(i,e.header))throw new p("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const a={...i,...e.header};let c=!0;if(Z(p,new Map([["b64",!0]]),n?.crit,i,a).has("b64")&&(c=i.b64,"boolean"!=typeof c))throw new p('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:h}=a;if("string"!=typeof h||!h)throw new p('JWS "alg" (Algorithm) Header Parameter missing or invalid');const l=n&&ee("algorithms",n.algorithms);if(l&&!l.has(h))throw new d('"alg" (Algorithm) Header Parameter value not allowed');if(c){if("string"!=typeof e.payload)throw new p("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new p("JWS Payload must be a string or an Uint8Array instance");let f=!1;"function"==typeof t?(t=await t(i,e),f=!0,Q(h,t,"verify"),N(t)&&(t=await te(t,h))):Q(h,t,"verify");const g=s(r.encode(e.protected??""),r.encode("."),"string"==typeof e.payload?r.encode(e.payload):e.payload);let y,v;try{y=u(e.signature)}catch{throw new p("Failed to base64url decode the signature")}if(!await W(h,t,y,g))throw new _;if(c)try{v=u(e.payload)}catch{throw new p("Failed to base64url decode the payload")}else v="string"==typeof e.payload?r.encode(e.payload):e.payload;const m={payload:v};return void 0!==e.protected&&(m.protectedHeader=i),void 0!==e.header&&(m.unprotectedHeader=e.header),f?{...m,key:t}:m}({payload:a,protected:i,signature:c},t,n),f={payload:l.payload,protectedHeader:l.protectedHeader};return"function"==typeof t?{...f,key:l.key}:f}const ne=e=>Math.floor(e.getTime()/1e3),ie=86400,oe=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,se=e=>{const t=oe.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(r*ie);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n},ae=e=>e.toLowerCase().replace(/^application\//,""),ue=(e,t,r={})=>{let n;try{n=JSON.parse(o.decode(t))}catch{}if(!D(n))throw new g("JWT Claims Set must be a top-level JSON object");const{typ:i}=r;if(i&&("string"!=typeof e.typ||ae(e.typ)!==ae(i)))throw new h('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:s=[],issuer:a,subject:u,audience:c,maxTokenAge:d}=r,f=[...s];void 0!==d&&f.push("iat"),void 0!==c&&f.push("aud"),void 0!==u&&f.push("sub"),void 0!==a&&f.push("iss");for(const e of new Set(f.reverse()))if(!(e in n))throw new h(`missing required "${e}" claim`,n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new h('unexpected "iss" claim value',n,"iss","check_failed");if(u&&n.sub!==u)throw new h('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(p=n.aud,y="string"==typeof c?[c]:c,!("string"==typeof p?y.includes(p):Array.isArray(p)&&y.some(Set.prototype.has.bind(new Set(p))))))throw new h('unexpected "aud" claim value',n,"aud","check_failed");var p,y;let v;switch(typeof r.clockTolerance){case"string":v=se(r.clockTolerance);break;case"number":v=r.clockTolerance;break;case"undefined":v=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,w=ne(m||new Date);if((void 0!==n.iat||d)&&"number"!=typeof n.iat)throw new h('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new h('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>w+v)throw new h('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new h('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=w-v)throw new l('"exp" claim timestamp check failed',n,"exp","check_failed")}if(d){const e=w-n.iat;if(e-v>("number"==typeof d?d:se(d)))throw new l('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-v)throw new h('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};const ce=async(e,t,r)=>{let n,i,o=!1;"function"==typeof AbortController&&(n=new AbortController,i=setTimeout(()=>{o=!0,n.abort()},t));const s=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(e=>{if(o)throw new w;throw e});if(void 0!==i&&clearTimeout(i),200!==s.status)throw new c("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await s.json()}catch{throw new c("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function he(e){return D(e)}function le(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class de{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(he)}(e))throw new y("JSON Web Key Set malformed");this._jwks=le(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...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 f('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)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":t="Ed25519"===e.crv;break;case"EdDSA":t="Ed25519"===e.crv||"Ed448"===e.crv}return t}),{0:s,length:a}=o;if(0===a)throw new v;if(1!==a){const e=new m,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of o)try{yield await fe(t,e,r)}catch{}},e}return fe(this._cached,s,r)}}async function fe(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await te({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new y("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function pe(e){const t=new de(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>le(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}let ge;if("undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){ge=`${"jose"}/${"v5.10.0"}`}const ye=Symbol();class ve{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");var r,n;this._url=new URL(e.href),this._options={agent:t?.agent,headers:t?.headers},this._timeoutDuration="number"==typeof t?.timeoutDuration?t?.timeoutDuration:5e3,this._cooldownDuration="number"==typeof t?.cooldownDuration?t?.cooldownDuration:3e4,this._cacheMaxAge="number"==typeof t?.cacheMaxAge?t?.cacheMaxAge:6e5,void 0!==t?.[ye]&&(this._cache=t?.[ye],r=t?.[ye],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&D(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,D)&&(this._jwksTimestamp=this._cache.uat,this._local=pe(this._cache.jwks)))}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){this._local&&this.fresh()||await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof v&&!1===this.coolingDown())return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);ge&&!e.has("User-Agent")&&(e.set("User-Agent",ge),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=ce(this._url,this._timeoutDuration,this._options).then(e=>{this._local=pe(e),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=e),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}}const me=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:a(e)};if(!E(e))throw new TypeError(C(e,...L,"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:i,...o}=await b.subtle.exportKey("jwk",e);return o};async function we(e){return me(e)}const _e=async(e,t,r)=>{const n=await J(e,t,"sign");F(e,n);const i=await b.subtle.sign(S(e,n.algorithm),n,r);return new Uint8Array(i)};class Se{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 p("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!$(this._protectedHeader,this._unprotectedHeader))throw new p("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...this._protectedHeader,...this._unprotectedHeader};let i=!0;if(Z(p,new Map([["b64",!0]]),t?.crit,this._protectedHeader,n).has("b64")&&(i=this._protectedHeader.b64,"boolean"!=typeof i))throw new p('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:u}=n;if("string"!=typeof u||!u)throw new p('JWS "alg" (Algorithm) Header Parameter missing or invalid');Q(u,e,"sign");let c,h=this._payload;i&&(h=r.encode(a(h))),c=this._protectedHeader?r.encode(a(JSON.stringify(this._protectedHeader))):r.encode("");const l=s(c,r.encode("."),h),d=await _e(u,e,l),f={signature:a(d),payload:""};return i&&(f.payload=o.decode(h)),this._unprotectedHeader&&(f.header=this._unprotectedHeader),this._protectedHeader&&(f.protected=o.decode(c)),f}}class be{constructor(e){this._flattened=new Se(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function Ee(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class Fe{constructor(e={}){if(!D(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:Ee("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:Ee("setNotBefore",ne(e))}:this._payload={...this._payload,nbf:ne(new Date)+se(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:Ee("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:Ee("setExpirationTime",ne(e))}:this._payload={...this._payload,exp:ne(new Date)+se(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:ne(new Date)}:e instanceof Date?this._payload={...this._payload,iat:Ee("setIssuedAt",ne(e))}:this._payload="string"==typeof e?{...this._payload,iat:Ee("setIssuedAt",ne(new Date)+se(e))}:{...this._payload,iat:Ee("setIssuedAt",e)},this}}class xe extends Fe{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const n=new be(r.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new g("JWTs MUST NOT use unencoded payload");return n.sign(e,t)}}function Ae(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new f("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function ke(e,t){return async function(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ae(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ae(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ae(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":r={name:"Ed25519"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];const e=t?.crv??"Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new f("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];const e=t?.crv??"P-256";switch(e){case"P-256":case"P-384":case"P-521":r={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":r={name:e};break;default:throw new f("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return b.subtle.generateKey(r,t?.extractable??!1,n)}(e,t)}const Pe={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let Te;const Ie=new Uint8Array(16);const Ce=[];for(let e=0;e<256;++e)Ce.push((e+256).toString(16).slice(1));function Re(e,t=0){return(Ce[e[t+0]]+Ce[e[t+1]]+Ce[e[t+2]]+Ce[e[t+3]]+"-"+Ce[e[t+4]]+Ce[e[t+5]]+"-"+Ce[e[t+6]]+Ce[e[t+7]]+"-"+Ce[e[t+8]]+Ce[e[t+9]]+"-"+Ce[e[t+10]]+Ce[e[t+11]]+Ce[e[t+12]]+Ce[e[t+13]]+Ce[e[t+14]]+Ce[e[t+15]]).toLowerCase()}const Ue=function(e,t,r){if(Pe.randomUUID&&!t&&!e)return Pe.randomUUID();const n=(e=e||{}).random??e.rng?.()??function(){if(!Te){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Te=crypto.getRandomValues.bind(crypto)}return Te(Ie)}();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){if((r=r||0)<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=n[e];return t}return Re(n)},Le="solidClientAuthn:",De=["ES256","RS256"],Ne="error",Oe="login",He="logout",je="newRefreshToken",Me="sessionExpired",Be="sessionExtended",Ke="sessionRestore",Ve="timeoutSet",qe=["openid","offline_access","webid"];class Je{handleables;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<t.length;e+=1)if(t[e])return this.handleables[e];return null}async canHandle(...e){return null!==await this.getProperHandler(e)}async handle(...e){const t=await this.getProperHandler(e);if(t)return t.handle(...e);throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${e.map(e=>{try{return JSON.stringify(e)}catch(t){return e.toString()}}).join(", ")}`)}}async function We(e,t,r,n){let i,o;try{const{payload:o}=await async function(e,t,r){const n=await re(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new g("JWTs MUST NOT use unencoded payload");const i={payload:ue(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}(e,function(e,t){const r=new ve(e,t),n=async(e,t)=>r.getKey(e,t);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}(new URL(t)),{issuer:r,audience:n});i=o}catch(e){throw new Error(`Token verification failed: ${e.stack}`)}if("string"==typeof i.azp&&(o=i.azp),"string"==typeof i.webid)return{webId:i.webid,clientId:o};if("string"!=typeof i.sub)throw new Error(`The token ${JSON.stringify(i)} is invalid: it has no 'webid' claim and no 'sub' claim.`);try{return new URL(i.sub),{webId:i.sub,clientId:o}}catch(e){throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${i.sub}] is invalid as a URL - error [${e}].`)}}function $e(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}}function ze(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}class Ye{storageUtility;redirector;constructor(e,t){this.storageUtility=e,this.redirector=t,this.storageUtility=e,this.redirector=t}parametersGuard=e=>void 0!==e.issuerConfiguration.grantTypesSupported&&e.issuerConfiguration.grantTypesSupported.indexOf("authorization_code")>-1&&void 0!==e.redirectUrl;async canHandle(e){return this.parametersGuard(e)}async setupRedirectHandler({oidcLoginOptions:e,state:t,codeVerifier:r,targetUrl:n}){if(!this.parametersGuard(e))throw new Error("The authorization code grant requires a redirectUrl.");var i,o;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:Boolean(e.dpop).toString(),keepAlive:(i=e.keepAlive,o=!0,"boolean"==typeof i?Boolean(i):Boolean(o)).toString()})]),this.redirector.redirect(n,{handleRedirect:e.handleRedirect})}}class Ge{sessionInfoManager;constructor(e){this.sessionInfoManager=e,this.sessionInfoManager=e}async canHandle(){return!0}async handle(e){await this.sessionInfoManager.clear(e)}}class Xe{redirector;constructor(e){this.redirector=e,this.redirector=e}async canHandle(e,t){return"idp"===t?.logoutType}async handle(e,t){if("idp"!==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})}}class Qe{handlers;constructor(e,t){this.handlers=[new Ge(e),new Xe(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)}}function Ze(){return{isLoggedIn:!1,sessionId:Ue(),fetch:(...e)=>fetch(...e)}}async function et(e,t){await Promise.all([t.deleteAllUserData(e,{secure:!1}),t.deleteAllUserData(e,{secure:!0})])}class tt{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}update(e,t){throw new Error("Not Implemented")}set(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 et(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")}async setOidcContext(e,t){throw new Error("Not implemented")}}function rt({endSessionEndpoint:e,idTokenHint:t}){if(void 0!==e)return function({state:r,postLogoutUrl:n}){return function({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()}({endSessionEndpoint:e,idTokenHint:t,state:r,postLogoutRedirectUri:n})}}function nt(e){try{return new URL(e),!0}catch{return!1}}async function it(e,t,r,n){let i;if(function(e,t){return t.scopesSupported.includes("webid")&&void 0!==e.clientId&&nt(e.clientId)}(e,t))i={clientId:e.clientId,clientName:e.clientName,clientType:"solid-oidc"};else{if(!function(e){return void 0!==e.clientId&&!nt(e.clientId)}(e))return n.getClient({sessionId:e.sessionId,clientName:e.clientName,redirectUrl:e.redirectUrl},t);i={clientId:e.clientId,clientSecret:e.clientSecret,clientName:e.clientName,clientType:"static"}}const o={clientId:i.clientId,clientType:i.clientType};return"static"===i.clientType&&(o.clientSecret=i.clientSecret),i.clientName&&(o.clientName=i.clientName),await r.setForUser(e.sessionId,o),i}const ot=(e,t)=>fetch(e,t);class st{loginHandler;redirectHandler;logoutHandler;sessionInfoManager;issuerConfigFetcher;boundLogout;constructor(e,t,r,n,i){this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=n,this.issuerConfigFetcher=i,this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=n,this.issuerConfigFetcher=i}fetch=ot;logout=async(e,t)=>{await this.logoutHandler.handle(e,"idp"===t?.logoutType?{...t,toLogoutUrl:this.boundLogout}:t),this.fetch=ot,delete this.boundLogout};getSessionInfo=async e=>this.sessionInfoManager.get(e);getAllSessionInfo=async()=>this.sessionInfoManager.getAll()}async function at(e,t,r){try{const[n,i,o,s,a]=await Promise.all([t.getForUser(e,"issuer",{errorIfNull:!0}),t.getForUser(e,"codeVerifier"),t.getForUser(e,"redirectUrl"),t.getForUser(e,"dpop",{errorIfNull:!0}),t.getForUser(e,"keepAlive")]);await t.deleteForUser(e,"codeVerifier");return{codeVerifier:i,redirectUrl:o,issuerConfig:await r.fetchConfig(n),dpop:"true"===s,keepAlive:"string"!=typeof a||"true"===a}}catch(t){throw new Error(`Failed to retrieve OIDC context from storage associated with session [${e}]: ${t}`)}}class ut{secureStorage;insecureStorage;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(t?.secure?this.secureStorage:this.insecureStorage).get(e);if(void 0===r&&t?.errorIfNull)throw new Error(`[${e}] is not stored`);return r}async set(e,t,r){return(r?.secure?this.secureStorage:this.insecureStorage).set(e,t)}async delete(e,t){return(t?.secure?this.secureStorage:this.insecureStorage).delete(e)}async getForUser(e,t,r){const n=await this.getUserData(e,r?.secure);let i;if(n&&n[t]||(i=void 0),i=n[t],void 0===i&&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,r?.secure)}catch{n={}}await this.setUserData(e,{...n,...t},r?.secure)}async deleteForUser(e,t,r){const n=await this.getUserData(e,r?.secure);delete n[t],await this.setUserData(e,n,r?.secure)}async deleteAllUserData(e,t){await(t?.secure?this.secureStorage:this.insecureStorage).delete(this.getKey(e))}}class ct{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]}}class ht extends Error{constructor(e){super(e)}}Error;class lt extends Error{missingFields;constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class dt extends Error{error;errorDescription;constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function ft(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function pt(e,t,r){return new xe({htu:ft(e),htm:t.toUpperCase(),jti:Ue()}).setProtectedHeader({alg:De[0],jwk:r.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(r.privateKey,{})}async function gt(e,t,r,n){if(void 0!==r)return async function(e,t,r,n){const i=new Headers(n?.headers);return i.set("Authorization",`DPoP ${t}`),i.set("DPoP",await pt(e,n?.method??"get",r)),{...n,headers:i}}(e,t,r,n);const i=new Headers(n?.headers);return i.set("Authorization",`Bearer ${t}`),{...n,headers:i}}async function yt(e,t,r,n,i=fetch){return i(t,await gt(t.toString(),e,n,r))}const vt=e=>void 0!==e?e-5>0?e-5:e:600;function mt(e,t){let r,n=e;const i=t?.refreshOptions;if(void 0!==i){const e=async()=>{try{const{accessToken:o,refreshToken:s,expiresIn:a}=await async function(e,t,r){const n=await e.tokenRefresher.refresh(e.sessionId,e.refreshToken,t);return r?.emit(Be,n.expiresIn??600),{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresIn:n.expiresIn}}(i,t.dpopKey,t.eventEmitter);n=o,void 0!==s&&(i.refreshToken=s),clearTimeout(r),r=setTimeout(e,1e3*vt(a)),t.eventEmitter?.emit(Ve,r)}catch(e){e instanceof dt&&(t?.eventEmitter?.emit(Ne,e.error,e.errorDescription),t?.eventEmitter?.emit(Me)),e instanceof lt&&e.missingFields.includes("access_token")&&t?.eventEmitter?.emit(Me)}};r=setTimeout(e,1e3*vt(t.expiresIn)),t.eventEmitter?.emit(Ve,r)}else if(void 0!==t&&void 0!==t.eventEmitter){const e=setTimeout(()=>{t.eventEmitter.emit(Me)},1e3*vt(t.expiresIn));t.eventEmitter.emit(Ve,e)}return async(e,r)=>{let i=await yt(n,e,r,t?.dpopKey,t?.fetch);const o=!i.ok&&(s=i.status,![401,403].includes(s));var s;if(i.ok||o)return i;return i.url!==e&&void 0!==t?.dpopKey&&(i=await yt(n,i.url,r,t.dpopKey,t.fetch)),i}}var wt=n(7),_t=n(516);function St(e,t){if("string"!=typeof e.client_id)throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(e)}`);if(t.redirectUrl&&function(e){return Array.isArray(e.redirect_uris)&&e.redirect_uris.every(e=>"string"==typeof e)}(e)&&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()])}`);return!0}async function bt(e,t){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 r=(n=t.idTokenSigningAlgValuesSupported,De.find(e=>n.includes(e))??null);var n;const i={client_name:e.clientName,application_type:"web",redirect_uris:[e.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:r,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 St(t,e),{clientId:t.client_id,clientSecret:t.client_secret,expiresAt:t.client_secret_expires_at,idTokenSignedResponseAlg:t.id_token_signed_response_alg,clientType:"dynamic"}}throw 400===o.status&&function(e,t){if("invalid_redirect_uri"===e.error)throw new Error(`Dynamic client registration failed: the provided redirect uri [${t.redirectUrl?.toString()}] is invalid - ${e.error_description??""}`);if("invalid_client_metadata"===e.error)throw new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(t)} is invalid - ${e.error_description??""}`);throw new Error(`Dynamic client registration failed: ${e.error} - ${e.error_description??""}`)}(await o.json(),e),new Error(`Dynamic client registration failed: the server returned ${o.status} ${o.statusText} - ${await o.text()}`)}function Et(e){return void 0!==e.error_description&&"string"==typeof e.error_description}function Ft(e,t){if(void 0!==(r=e).error&&"string"==typeof r.error)throw new dt(`Token endpoint returned error [${e.error}]${Et(e)?`: ${e.error_description}`:""}${function(e){return void 0!==e.error_uri&&"string"==typeof e.error_uri}(e)?` (see ${e.error_uri})`:""}`,e.error,Et(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 lt(["access_token"]);if(!function(e){return void 0!==e.id_token&&"string"==typeof e.id_token}(e))throw new lt(["id_token"]);if(!function(e){return void 0!==e.token_type&&"string"==typeof e.token_type}(e))throw new lt(["token_type"]);if(!function(e){return void 0===e.expires_in||"number"==typeof e.expires_in}(e))throw new lt(["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 xt(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 i={"content-type":"application/x-www-form-urlencoded"};let o;n&&(o=await async function(){const{privateKey:e,publicKey:t}=await ke(De[0]),r={privateKey:e,publicKey:await we(t)};return[r.publicKey.alg]=De,r}(),i.DPoP=await pt(e.tokenEndpoint,"POST",o)),t.clientSecret&&(i.Authorization=`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`);const s={grant_type:r.grantType,redirect_uri:r.redirectUrl,code:r.code,code_verifier:r.codeVerifier,client_id:t.clientId},a={method:"POST",headers:i,body:new URLSearchParams(s).toString()},u=await fetch(e.tokenEndpoint,a),c=Ft(await u.json(),n),{webId:h,clientId:l}=await We(c.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:c.access_token,idToken:c.id_token,refreshToken:(d=c,void 0!==d.refresh_token&&"string"==typeof d.refresh_token?c.refresh_token:void 0),webId:h,clientId:l,dpopKey:o,expiresIn:c.expires_in};var d}async function At(e,t,r,n){if(void 0===r.clientId)throw new Error("No client ID available when trying to refresh the access token.");const i={grant_type:"refresh_token",refresh_token:e};let o={};void 0!==n&&(o={DPoP:await pt(t.tokenEndpoint,"POST",n)});let s={};void 0!==r.clientSecret?s={Authorization:`Basic ${btoa(`${r.clientId}:${r.clientSecret}`)}`}:(e=>{try{return new URL(e),!0}catch{return!1}})(r.clientId)&&(i.client_id=r.clientId);const a=await fetch(t.tokenEndpoint,{method:"POST",body:new URLSearchParams(i).toString(),headers:{...o,...s,"Content-Type":"application/x-www-form-urlencoded"}});let u;try{u=await a.json()}catch(e){throw new Error(`The token endpoint of issuer ${t.issuer} returned a malformed response.`)}const c=Ft(u,void 0!==n),{webId:h}=await We(c.id_token,t.jwksUri,t.issuer,r.clientId);return{accessToken:c.access_token,idToken:c.id_token,refreshToken:"string"==typeof c.refresh_token?c.refresh_token:void 0,webId:h,dpopKey:n,expiresIn:c.expires_in}}class kt extends ut{constructor(e,t){super(e,t)}}class Pt extends st{login=async(e,t)=>{"none"!==e.prompt&&await this.sessionInfoManager.clear(e.sessionId);const r=e.redirectUrl??function(e){const t=ze(e);return t.hash="",e.includes(`${t.origin}/`)?t.href:`${t.origin}${t.href.substring(t.origin.length+1)}`}(window.location.href);if(!$e(r))throw new Error(`${r} 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:r,clientName:e.clientName??e.clientId,eventEmitter:t})};validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return void 0===t||void 0===t.clientAppId||void 0===t.issuer?null:t};handleIncomingRedirect=async(e,t)=>{try{const r=await this.redirectHandler.handle(e,t,void 0);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,clientAppId:r.clientAppId}}catch(r){return await this.cleanUrlAfterRedirect(e),void t.emit(Ne,"redirect",r)}};async cleanUrlAfterRedirect(e){const t=ze(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(e=>{setTimeout(()=>e(),1)})}}function Tt(e){return"string"==typeof e.oidcIssuer}function It(e){return"string"==typeof e.redirectUrl}class Ct{storageUtility;oidcHandler;issuerConfigFetcher;clientRegistrar;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 Tt(e)&&It(e)}async handle(e){if(!Tt(e))throw new ht(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!It(e))throw new ht(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),r=await it(e,t,this.storageUtility,this.clientRegistrar),n={issuer:t.issuer,dpop:"dpop"===e.tokenType.toLowerCase(),...e,issuerConfiguration:t,client:r,scopes:(i=e.customScopes,Array.isArray(i)?Array.from(new Set([...qe,...i.filter(e=>"string"==typeof e&&!e.includes(" "))])):qe)};var i;return this.oidcHandler.handle(n)}}class Rt extends Ye{async handle(e){const t={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:e.prompt??"consent"},r=new _t.OidcClient(t);try{const t=await r.createSigninRequest();return await this.setupRedirectHandler({oidcLoginOptions:e,state:t.state._id,codeVerifier:t.state._code_verifier,targetUrl:t.url.toString()})}catch(e){console.error(e)}}}const Ut={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 Lt{storageUtility;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,n=await fetch(r);try{t=function(e){const t={};return Object.keys(e).forEach(r=>{Ut[r]&&(t[Ut[r].toKey]=e[r])}),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(await n.json())}catch(t){throw new ht(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return await this.storageUtility.set(Lt.getLocalStorageKey(e),JSON.stringify(t)),t}}async function Dt(e,t){await et(e,t),await async function(){const e=new _t.OidcClient({response_mode:"query"});await e.clearStaleState(new _t.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))}()}class Nt extends tt{async get(e){const[t,r,n,i,o,s,a,u]=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 o||$e(o)){if(void 0!==u&&("string"!=typeof(c=u)||!["DPoP","Bearer"].includes(c)))throw new Error(`Tokens of type [${u}] are not supported.`);var c;if(void 0!==n||void 0!==t||void 0!==r||void 0!==s)return{sessionId:e,webId:r,isLoggedIn:"true"===t,redirectUrl:o,refreshToken:s,issuer:a,clientAppId:n,clientAppSecret:i,tokenType:u??"DPoP"}}else await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})])}async clear(e){return Dt(e,this.storageUtility)}}class Ot{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 Ze()}}class Ht{storageUtility;sessionInfoManager;issuerConfigFetcher;clientRegistrar;tokerRefresher;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),n=r.searchParams.get("state"),i=await this.storageUtility.getForUser(n,"sessionId",{errorIfNull:!0}),{issuerConfig:o,codeVerifier:s,redirectUrl:a,dpop:u}=await at(i,this.storageUtility,this.issuerConfigFetcher),c=r.searchParams.get("iss");if("string"==typeof c&&c!==o.issuer)throw new Error(`The value of the iss parameter (${c}) does not match the issuer identifier of the authorization server (${o.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(void 0===s)throw new Error(`The code verifier for session ${i} is missing from storage.`);if(void 0===a)throw new Error(`The redirect URL for session ${i} is missing from storage.`);const h=await this.clientRegistrar.getClient({sessionId:i},o),l=Date.now(),d=await xt(o,h,{grantType:"authorization_code",code:r.searchParams.get("code"),codeVerifier:s,redirectUrl:a},u);let f;window.localStorage.removeItem(`oidc.${n}`),void 0!==d.refreshToken&&(f={sessionId:i,refreshToken:d.refreshToken,tokenRefresher:this.tokerRefresher});const p=mt(d.accessToken,{dpopKey:d.dpopKey,refreshOptions:f,eventEmitter:t,expiresIn:d.expiresIn});await async function(e,t,r,n,i,o,s,a){void 0!==o&&await e.setForUser(t,{refreshToken:o},{secure:s}),void 0!==r&&await e.setForUser(t,{webId:r},{secure:s}),void 0!==n&&await e.setForUser(t,{clientId:n},{secure:s}),void 0!==i&&await e.setForUser(t,{isLoggedIn:i},{secure:s}),void 0!==a&&await e.setForUser(t,{publicKey:JSON.stringify(a.publicKey),privateKey:JSON.stringify(await we(a.privateKey))},{secure:s})}(this.storageUtility,i,d.webId,d.clientId,"true",void 0,!0);const g=await this.sessionInfoManager.get(i);if(!g)throw new Error(`Could not retrieve session: [${i}].`);return Object.assign(g,{fetch:p,getLogoutUrl:rt({idTokenHint:d.idToken,endSessionEndpoint:o.endSessionEndpoint}),expirationDate:"number"==typeof d.expiresIn?l+1e3*d.expiresIn:void 0})}}class jt extends Je{constructor(e){super(e)}}class Mt{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 Bt{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class Kt{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[r,n,i,o,s]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"expiresAt",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientName",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientType",{secure:!1})]),a=void 0!==i?Number.parseInt(i,10):-1,u=void 0!==n&&0!==a&&Math.floor(Date.now()/1e3)>a;if(r&&("string"==typeof(c=s)&&["dynamic","static","solid-oidc"].includes(c))&&!u)return void 0!==n?{clientId:r,clientSecret:n,clientName:o,clientType:"dynamic",expiresAt:a}:{clientId:r,clientName:o,clientType:s};var c;try{const r=await bt(e,t),n={clientId:r.clientId,clientType:"dynamic"};return void 0!==r.clientSecret&&(n.clientSecret=r.clientSecret,n.expiresAt=String(r.expiresAt)),r.idTokenSignedResponseAlg&&(n.idTokenSignedResponseAlg=r.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,n,{secure:!1}),r}catch(e){throw new Error("Client registration failed.",{cause:e})}}}class Vt{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),n=r.searchParams.get("error"),i=r.searchParams.get("error_description");t.emit(Ne,n,i)}return Ze()}}class qt{storageUtility;issuerConfigFetcher;clientRegistrar;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,n){const i=await at(e,this.storageUtility,this.issuerConfigFetcher),o=await this.clientRegistrar.getClient({sessionId:e},i.issuerConfig);if(void 0===t)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(i.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 s=await At(t,i.issuerConfig,o,r);return void 0!==s.refreshToken&&n?.emit(je,s.refreshToken),s}}function Jt(e){const t=new ct,r=e.secureStorage||t,n=e.insecureStorage||new Mt,i=new kt(r,n),o=new Lt(i),s=new Kt(i),a=new Nt(i),u=new qt(i,o,s),c=new Bt,h=new Ct(i,new Rt(i,c),o,s),l=new jt([new Vt,new Ht(i,a,o,s,u),new Ot]);return new Pt(h,l,new Qe(a,c),a,o)}const Wt=`${Le}currentSession`,$t=`${Le}currentUrl`;class zt{info;events;clientAuthentication;tokenRequestInProgress=!1;constructor(e={},t=void 0){this.events=new wt,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=Jt({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage}):this.clientAuthentication=Jt({}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??Ue(),isLoggedIn:!1},this.events.on(Oe,()=>window.localStorage.setItem(Wt,this.info.sessionId)),this.events.on(Me,()=>this.internalLogout(!1)),this.events.on(Ne,()=>this.internalLogout(!1))}login=async e=>(await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:e.tokenType??"DPoP"},this.events),new Promise(()=>{}));fetch=(e,t)=>this.clientAuthentication.fetch(e,t);internalLogout=async(e,t)=>{window.localStorage.removeItem(Wt),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(He)};logout=async e=>this.internalLogout(!0,e);handleIncomingRedirect=async(e={})=>{if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const t="string"==typeof e?{url:e}:e,r=t.url??window.location.href;this.tokenRequestInProgress=!0;const n=await this.clientAuthentication.handleIncomingRedirect(r,this.events);if(function(e){return!!e?.isLoggedIn}(n)){this.setSessionInfo(n);const e=window.localStorage.getItem($t);null===e?this.events.emit(Oe):(window.localStorage.removeItem($t),this.events.emit(Ke,e))}else if(!0===t.restorePreviousSession){const e=window.localStorage.getItem(Wt);if(null!==e){if(await async function(e,t,r){const n=await t.validateCurrentSession(e);return null!==n&&(window.localStorage.setItem($t,window.location.href),await t.login({sessionId:e,prompt:"none",oidcIssuer:n.issuer,redirectUrl:n.redirectUrl,clientId:n.clientAppId,clientSecret:n.clientAppSecret,tokenType:n.tokenType??"DPoP"},r.events),!0)}(e,this.clientAuthentication,this))return new Promise(()=>{})}}return this.tokenRequestInProgress=!1,n};setSessionInfo(e){this.info.isLoggedIn=e.isLoggedIn,this.info.webId=e.webId,this.info.sessionId=e.sessionId,this.info.clientAppId=e.clientAppId,this.info.expirationDate=e.expirationDate,this.events.on(Be,e=>{this.info.expirationDate=Date.now()+1e3*e})}}const Yt=new zt;var Gt=n(264),Xt=n(386);const Qt=n.n(Xt)()(Gt),Zt=(0,Gt.sym)("http://www.iana.org/assignments/link-relations/acl");function er(e){const t=Qt;function r(e,r,n,i={}){const o=i.public||[],s=(0,Gt.graph)(),a=(0,Gt.Namespace)("http://www.w3.org/ns/auth/acl#");let u=s.sym(`${n}#a1`);const c=s.sym(n),h=s.sym(e);if(s.add(u,t.rdf("type"),a("Authorization"),c),s.add(u,a("accessTo"),h,c),i.defaultForNew&&s.add(u,a("default"),h,c),s.add(u,a("agent"),r,c),s.add(u,a("mode"),a("Read"),c),s.add(u,a("mode"),a("Write"),c),s.add(u,a("mode"),a("Control"),c),o.length){u=s.sym(`${n}#a2`),s.add(u,t.rdf("type"),a("Authorization"),c),s.add(u,a("accessTo"),h,c),s.add(u,a("agentClass"),t.foaf("Agent"),c);for(let e=0;e<o.length;e++)s.add(u,a("mode"),a(o[e]),c)}return(0,Gt.serialize)(c,s,n)}return{findAclDocUrl:async function(t){await e.fetcher.load(t);const r=e.any(t,Zt);if(!r)throw new Error(`No ACL link discovered for ${t}`);return r.value},setACLUserPublic:function(t,n,i){const o=e.any(e.sym(t),Zt);return Promise.resolve().then(()=>o||function(t){const r=e.fetcher;if(!r)throw new Error("Cannot fetch ACL rel, store has no fetcher");return r.load(t).then(r=>{if(!r.ok)throw new Error("fetchACLRel: While loading:"+r.error);const n=e.any(e.sym(t),Zt);if(!n)throw new Error("fetchACLRel: No Link rel=ACL header for "+t);return n})}(t).catch(e=>{throw new Error(`Error fetching rel=ACL header for ${t}: ${e}`)})).then(o=>{const s=r(t,n,o.uri,i);if(!e.fetcher)throw new Error("Cannot PUT this, store has no fetcher");return e.fetcher.webOperation("PUT",o.uri,{data:s,contentType:"text/turtle"}).then(e=>{if(!e.ok)throw new Error("Error writing ACL text: "+e.error);return o})})},genACLText:r}}const tr=()=>{let{SolidAppContext:e}=window;if(e||(e={}),e.viewingNoAuthPage=!1,e.noAuth&&window.document){if(window.document.location.href.startsWith(e.noAuth)){e.viewingNoAuthPage=!0;const t=new URLSearchParams(window.document.location.search);if(t){let r=e.viewedPage=t.get("uri")||null;if(r&&(r=decodeURI(r),!r.startsWith(e.noAuth))){const t=r.split(/\//);e.idp=t[0]+"//"+t[2],e.viewingNoAuthPage=!1}}}}return e};function rr(){const{$SolidTestEnvironment:t}=window;if(void 0!==t&&t.username)return e("Assuming the user is "+t.username),(0,Gt.sym)(t.username);if("undefined"!=typeof document&&document.location&&"http://localhost"===(""+document.location).slice(0,16)){const t=document.getElementById("appTarget");if(!t)return null;const r=t.getAttribute("testID");return r?(e("Assuming user is "+r),(0,Gt.sym)(r)):null}return null}class nr{constructor(e){this.session=e}get authSession(){return this.session}currentUser(){const e=tr();return e.viewingNoAuthPage?(0,Gt.sym)(e.webId):this&&this.session&&this.session.info&&this.session.info.webId&&this.session.info.isLoggedIn?(0,Gt.sym)(this.session.info.webId):rr()}async checkUser(t){const r=new URL(window.location.href).hash;r&&window.localStorage.setItem("preLoginRedirectHash",r),this.session.events.on(Ke,t=>{e(`Session restored to ${t}`),document.location.toString()!==t&&history.replaceState(null,"",t)});const n=new URL(window.location.href);n.hash="",await this.session.handleIncomingRedirect({restorePreviousSession:!0,url:n.href});const i=window.localStorage.getItem("preLoginRedirectHash");if(i){const e=new URL(window.location.href);e.hash!==i&&(history.pushState?history.pushState(null,document.title,i):location.hash=i,e.hash=i),window.localStorage.setItem("preLoginRedirectHash","")}let o=rr();if(o)return Promise.resolve(t?t(o):o);const s=this.webIdFromSession(this.session.info);return s&&(o=this.saveUser(s)),o&&e(`(Logged in as ${o} by authentication)`),Promise.resolve(t?t(o):o)}saveUser(e,t){let r;if(e){r="string"==typeof e?e:e.uri;const n=(0,Gt.namedNode)(r);return t&&(t.me=n),n}return null}webIdFromSession(e){return(null==e?void 0:e.webId)&&e.isLoggedIn?e.webId:null}}function ir(e){return(0,Gt.sym)(e.uri+"#id"+Date.now())}function or(e){return!e||`${window.location.origin}/`!==new URL(e.value).origin}const sr="index.ttl#this";function ar(e,t){const r=Qt;async function n(t,r,n){await e.fetcher.load(t);const i=e.any(t,new Gt.NamedNode("http://www.iana.org/assignments/link-relations/acl"));if(!i)throw new Error("Chat ACL doc not found!");const o=`\n @prefix acl: <http://www.w3.org/ns/auth/acl#>.\n <#owner>\n a acl:Authorization;\n acl:agent <${r.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Write, acl:Control.\n <#invitee>\n a acl:Authorization;\n acl:agent <${n.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Append.\n `;await e.fetcher.webOperation("PUT",i.value,{data:o,contentType:"text/turtle"})}async function i(t,n){const i=e.any(n,r.solid("privateTypeIndex"));if(!i)throw new Error("Private type index not found!");await e.fetcher.load(i);const o=ir(i),s=[(0,Gt.st)(o,r.rdf("type"),r.solid("TypeRegistration"),i.doc()),(0,Gt.st)(o,r.solid("forClass"),r.meeting("LongChat"),i.doc()),(0,Gt.st)(o,r.solid("instance"),t,i.doc())];await new Promise((t,r)=>{e.updater.update([],s,function(e,n,i){n?t(null):r(new Error(i))})})}async function o(r){const n=await t.loadMe(),i=function(e,t){const r=new URL(`IndividualChats/${new URL(e.value).host}/`,t.value).toString();return new Gt.NamedNode(r)}(r,await t.getPodRoot(n));let o=!0;try{await e.fetcher.load(new Gt.NamedNode(i.value+"index.ttl#this"))}catch(e){o=!1}return{me:n,chatContainer:i,exists:o}}async function s(e,t){return(await a({me:t,newBase:e.value})).newInstance}function a(t){const n=e,i=n.updater;if(t.me&&!t.me.uri)throw new Error("chat mintNew: Invalid userid "+t.me);const o=t.newInstance=t.newInstance||n.sym(t.newBase+sr),s=o.doc();return n.add(o,r.rdf("type"),r.meeting("LongChat"),s),n.add(o,r.dc("title"),"Chat channel",s),n.add(o,r.dc("created"),(0,Gt.term)(new Date(Date.now())),s),t.me&&n.add(o,r.dc("author"),t.me,s),new Promise(function(e,r){null==i||i.put(s,n.statementsMatching(void 0,void 0,void 0,s),"text/turtle",function(n,i,s){i?e({...t,newInstance:o}):r(new Error("FAILED to save new chat channel at: "+n+" : "+s))})})}async function u(t,n){var i;await e.fetcher.load(t.doc());const o=e.any(t,r.ldp("inbox"),void 0,t.doc());if(!o)throw new Error(`Invitee inbox not found! ${t.value}`);const s=`\n <> a <http://www.w3.org/ns/pim/meeting#LongChatInvite> ;\n ${r.rdf("seeAlso")} <${n.value}> .\n `,a=await(null===(i=e.fetcher)||void 0===i?void 0:i.webOperation("POST",o.value,{data:s,contentType:"text/turtle"}));if(!(null==a?void 0:a.headers.get("location")))throw new Error(`Invite sending returned a ${null==a?void 0:a.status}`)}return{setAcl:n,addToPrivateTypeIndex:i,findChat:o,createChatThing:s,getChat:async function(e,t=!0){const{me:r,chatContainer:a,exists:c}=await o(e);if(c)return new Gt.NamedNode(a.value+sr);if(t){const t=await s(a,r);return await u(e,t),await n(a,r,e),await i(t,r),t}return null},sendInvite:u,mintNew:a}}function ur(e,t,r,n,i){return{createInboxFor:async function(e,i){const o=await t.loadMe(),s=`${(await t.getPodRoot(o)).value}p2p-inboxes/${encodeURIComponent(i)}/`;return await n.createContainer(s),await r.setSinglePeerAccess({ownerWebId:o.value,peerWebId:e,accessToModes:"acl:Append",target:s}),s},getNewMessages:async function(e){e||(e=await t.loadMe());const r=await t.getMainInbox(e);return(await n.getContainerMembers(r)).filter(e=>!n.isContainer(e))},markAsRead:async function(t,r){const n=await e.fetcher._fetch(t);if(200!==n.status)throw new Error(`Not OK! ${t}`);const i=function(e,t){const r=t.getUTCFullYear(),n=("0"+(t.getUTCMonth()+1)).slice(-2),i=("0"+t.getUTCDate()).slice(-2),o=e.split("/"),s=o[o.length-1];return new URL(`./archive/${r}/${n}/${i}/${s}`,e).toString()}(t,r),o={method:"PUT",body:await n.text(),headers:[["Content-Type",n.headers.get("Content-Type")||"application/octet-stream"]]};"2"===(await e.fetcher._fetch(i,o)).status.toString()[0]&&await e.fetcher._fetch(t,{method:"DELETE"})}}}class cr extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}}class hr extends cr{}class lr extends cr{}class dr extends cr{}class fr extends cr{}class pr extends cr{}class gr extends cr{}class yr extends cr{constructor(e,t){super(t),this.status=e}}function vr(e,r,n){const i=Qt;async function o(r){await s(r);const o=function(e){const t=e.uri.replace("/profile/","/").replace("/public/","/").split("/").slice(0,-1).join("/")+"/Settings/Preferences.ttl";return(0,Gt.sym)(t)}(r);let a;try{a=await n.followOrCreateLink(r,i.space("preferencesFile"),o,r.doc())}catch(e){if(t(`User ${r} has no pointer in profile to preferences file.`),e instanceof pr)throw e;if(e instanceof gr)throw e;if(e instanceof hr)throw e;if(e instanceof lr)throw e;if(e instanceof dr)throw e;if(e instanceof yr)throw e;throw e}try{await e.fetcher.load(a)}catch(e){const n=`Unable to load preference of user ${r}: ${e}`;if(t(n),401===e.response.status)throw new hr;if(403===e.response.status){if(or(a))throw new lr;throw new dr}throw new Error(n)}return a}async function s(t){if(!t)throw new Error("loadProfile: no user given.");try{await e.fetcher.load(t.doc())}catch(e){throw new Error(`Unable to load profile of user ${t}: ${e}`)}return t.doc()}function a(t){return e.any(t,i.space("storage"),void 0,t.doc())}return{loadMe:async function(){const t=r.currentUser();if(null===t)throw new Error("Current user not found! Not logged in?");return await e.fetcher.load(t.doc()),t},getPodRoot:function(e){const t=a(e);if(!t)throw new Error("User pod root not found!");return t},getMainInbox:async function(t){await e.fetcher.load(t);const r=e.any(t,i.ldp("inbox"),void 0,t.doc());if(!r)throw new Error("User main inbox not found!");return r},findStorage:a,loadPreferences:o,loadProfile:s,silencedLoadPreferences:async function(e){try{return await o(e)}catch(e){return}}}}function mr(e,r,n,i){const o=Qt;async function s(r){if(!r)throw new Error("loadTypeIndexesFor: No user given");const s=await n.loadProfile(r),a=h(r);let u;try{u=await i.followOrCreateLink(r,o.solid("publicTypeIndex"),a,s)}catch(e){t(`User ${r} has no pointer in profile to publicTypeIndex file.`)}const c=u?[{label:"public",index:u,agent:r}]:[];let d,f;try{d=await n.silencedLoadPreferences(r)}catch(e){d=null}if(d){const n=l(d);let a;try{a=e.any(r,o.solid("privateTypeIndex"),void 0,s)||await i.followOrCreateLink(r,o.solid("privateTypeIndex"),n,d)}catch(e){t(`User ${r} has no pointer in preference file to privateTypeIndex file.`)}f=a?[{label:"private",index:a,agent:r}]:[]}else f=[];const p=c.concat(f);if(0===p.length)return p;const g=p.map(e=>e.index);try{await e.fetcher.load(g)}catch(e){t("Problems loading type index: ",e)}return p}async function a(r){let i;try{i=await n.silencedLoadPreferences(r)}catch(e){t(`User ${r} has no pointer in profile to preferences file.`)}if(i){const t=e.each(r,o.solid("community"),void 0,i).concat(e.each(r,o.solid("community"),void 0,r.doc()));let n=[];for(const e of t)n=n.concat(await s(e));return n}return[]}async function u(e){return(await s(e)).concat((await a(e)).flat())}async function c(e,t){const r=await u(t);let n=[];for(const t of r){const r=await d(t,e);n=n.concat(r)}return n}function h(e){var t;return(0,Gt.sym)((null===(t=e.doc().dir())||void 0===t?void 0:t.uri)+"publicTypeIndex.ttl")}function l(e){var t;return(0,Gt.sym)((null===(t=e.doc().dir())||void 0===t?void 0:t.uri)+"privateTypeIndex.ttl")}async function d(t,r){const n=t.index,i=[],s=e.statementsMatching(null,o.solid("instance"),null,n).concat(e.statementsMatching(null,o.solid("instanceContainer"),null,n)).map(e=>e.subject);for(const a of s){const s=e.any(a,o.solid("forClass"),null,n);if(!r||s.sameTerm(r)){const r=e.each(a,o.solid("instance"),null,n);for(const e of r)i.push({instance:e,type:s,scope:t});const u=e.each(a,o.solid("instanceContainer"),null,n);for(const r of u)await e.fetcher.load(r),i.push({instance:(0,Gt.sym)(r.value),type:s,scope:t})}}return i}return{registerInTypeIndex:async function(t,r,n){const i=ir(r),s=[(0,Gt.st)(i,o.rdf("type"),o.solid("TypeRegistration"),r),(0,Gt.st)(i,o.solid("forClass"),n,r),(0,Gt.st)(i,o.solid("instance"),t,r)];try{await e.updater.update([],s)}catch(e){const n=`Unable to register ${t} in index ${r}: ${e}`;return console.warn(n),null}return i},getRegistrations:function(t,r){return e.each(void 0,o.solid("instance"),t).filter(t=>e.holds(t,o.solid("forClass"),r))},loadTypeIndexesFor:s,loadCommunityTypeIndexes:a,loadAllTypeIndexes:u,getScopedAppInstances:c,getAppInstances:async function(e){const t=r.currentUser();if(!t)throw new Error("getAppInstances: Must be logged in to find apps.");return(await c(e,t)).map(e=>e.instance)},suggestPublicTypeIndex:h,suggestPrivateTypeIndex:l,deleteTypeIndexRegistration:async function(t){const r=e.the(null,o.solid("instance"),t.instance,t.scope.index);if(!r)throw new Error(`deleteTypeIndexRegistration: No registration found for ${t.instance}`);const n=e.statementsMatching(r,null,null,t.scope.index);await e.updater.update(n,[])},getScopedAppsFromIndex:d}}function wr(r,n){e("SolidLogic: Unique instance created. There should only be one of these.");const i=Gt.graph();Gt.fetcher(i,{fetch:r.fetch}),i.updater=new Gt.UpdateManager(i),i.features=[];const o=new nr(n),s=er(i),a=function(e){function t(t){return e.statementsMatching(t,(0,Gt.sym)("http://www.w3.org/ns/ldp#contains"),void 0).map(e=>e.object)}function r(e){const t=e.value;return"/"===t.charAt(t.length-1)}return{isContainer:r,createContainer:async function(t){if(!r((0,Gt.sym)(t)))throw new Error(`Not a container URL ${t}`);const n=await e.fetcher._fetch(t,{method:"PUT",headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:'<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'},body:" "});if("2"!==n.status.toString()[0])throw new Error(`Not OK: got ${n.status} response while creating container at ${t}`)},getContainerElements:t,getContainerMembers:async function(r){return await e.fetcher.load(r),t(r)}}}(i),u=function(r,n,i){async function o(e){let t;try{t=await r.fetcher.load(e)}catch(t){if(404!==t.response.status){if(401===t.response.status)throw new hr;if(403===t.response.status){if(or(e))throw new lr;throw new dr}const r="createIfNotExists doc load error NOT 404: "+e+": "+t;throw new yr(t.status,t.message+r)}try{await r.fetcher.webOperation("PUT",e,{data:"",contentType:"text/turtle"})}catch(t){throw new gr("createIfNotExists: PUT FAILED: "+e+": "+t)}await r.fetcher.load(e)}return t}return{recursiveDelete:async function t(o){try{if(i.isContainer(o)){const e=await n.findAclDocUrl(o);await r.fetcher._fetch(e,{method:"DELETE"});const s=await i.getContainerMembers(o);await Promise.all(s.map(e=>t(e)))}const e=o.value;return r.fetcher._fetch(e,{method:"DELETE"})}catch(t){e(`Please manually remove ${o.value} from your system.`,t)}},setSinglePeerAccess:async function(e){let t=["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","",`<#alice> a acl:Authorization;\n acl:agent <${e.ownerWebId}>;`,` acl:accessTo <${e.target}>;`,` acl:default <${e.target}>;`," acl:mode acl:Read, acl:Write, acl:Control.",""].join("\n");e.accessToModes&&(t+=["<#bobAccessTo> a acl:Authorization;",` acl:agent <${e.peerWebId}>;`,` acl:accessTo <${e.target}>;`,` acl:mode ${e.accessToModes}.`,""].join("\n")),e.defaultModes&&(t+=["<#bobDefault> a acl:Authorization;",` acl:agent <${e.peerWebId}>;`,` acl:default <${e.target}>;`,` acl:mode ${e.defaultModes}.`,""].join("\n"));const i=await n.findAclDocUrl((0,Gt.sym)(e.target));return r.fetcher._fetch(i,{method:"PUT",body:t,headers:[["Content-Type","text/turtle"]]})},createEmptyRdfDoc:async function(e,t){await r.fetcher.webOperation("PUT",e.uri,{data:`# ${new Date} ${t}\n `,contentType:"text/turtle"})},followOrCreateLink:async function(e,n,i,s){await r.fetcher.load(s);const a=r.any(e,n,null,s);if(a)return a;if(!r.updater.editable(s)){const e=`followOrCreateLink: cannot edit ${s.value}`;throw t(e),new pr(e)}try{await r.updater.update([],[(0,Gt.st)(e,n,i,s)])}catch(e){throw t(`followOrCreateLink: Error making link in ${s} to ${i}: ${e}`),new gr(e)}try{await o(i)}catch(e){throw t(`followOrCreateLink: Error loading or saving new linked document: ${i}: ${e}`),e}return i},loadOrCreateIfNotExists:o}}(i,s,a),c=vr(i,o,u),h=ar(i,c),l=ur(i,c,u,a),d=mr(i,o,c,u);return e("SolidAuthnLogic initialized"),{store:i,authn:o,acl:s,inbox:l,chat:h,profile:c,typeIndex:d,load:function(e){return i.fetcher.load(e)},updatePromise:function(e,t=[]){return new Promise((r,n)=>{i.updater.update(e,t,function(e,t,i){t?r():n(new Error(i))})})},clearStore:function(){i.statements.slice().forEach(i.remove.bind(i))}}}const _r=async(e,t)=>{const r=t&&t.credentials&&"omit"==t.credentials;return Yt.info.webId&&!r?Yt.fetch(e,t):window.fetch(e,t)},Sr=Symbol.for("solid-logic-singleton"),br="undefined"!=typeof window?window:n.g;const Er=(br[Sr]?e("SolidLogic: Using existing global singleton instance."):(e("SolidLogic: Creating new global singleton instance."),br[Sr]=wr({fetch:_r},Yt),e("Unique quadstore initialized.")),br[Sr]),Fr=[{name:"Solid Community",uri:"https://solidcommunity.net"},{name:"Solid Web",uri:"https://solidweb.org"},{name:"Solid Web ME",uri:"https://solidweb.me"},{name:"Inrupt.com",uri:"https://login.inrupt.com"}];function xr(){const e=[...Fr],{host:t,origin:r}=new URL(location.href),n=e.map(({uri:e})=>new URL(e).host);return n.includes(t)||n.some(e=>function(e,t){const r=e.length-t.length-1;return r>0&&"."===e[r]&&e.endsWith(t)}(t,e))||e.unshift({name:t,uri:r}),e}const Ar=Er.authn,kr=Er.authn.authSession,Pr=Er.store})(),i})());
41
32
  //# sourceMappingURL=solid-logic.min.js.map