@fanoutio/grip
Advanced tools
Comparing version
/*! For license information please see grip.min.js.LICENSE.txt */ | ||
var Grip;(()=>{var e={448:(e,t,n)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(s=r))})),t.splice(s,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=n(656)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},656:(e,t,n)=>{e.exports=function(e){function t(e){let n,s,o,a=null;function i(...e){if(!i.enabled)return;const r=i,s=Number(new Date),o=s-(n||s);r.diff=o,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";a++;const o=t.formatters[s];if("function"==typeof o){const t=e[a];n=o.call(r,t),e.splice(a,1),a--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return i.namespace=e,i.useColors=t.useColors(),i.color=t.selectColor(e),i.extend=r,i.destroy=t.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(s!==t.namespaces&&(s=t.namespaces,o=t.enabled(e)),o),set:e=>{a=e}}),"function"==typeof t.init&&t.init(i),i}function r(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function s(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(s),...t.skips.map(s).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(n=0;n<s;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=n(952),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}},716:(e,t)=>{t.I=new function(){var e,t=!1,n=this;n._DeArray=function(e,t,n){return[e.slice(t,t+n)]},n._EnArray=function(e,t,n,r){for(var s=0;s<n;e[t+s]=r[s]?r[s]:0,s++);},n._DeChar=function(e,t){return String.fromCharCode(e[t])},n._EnChar=function(e,t,n){e[t]=n.charCodeAt(0)},n._DeInt=function(n,r){var s,o,a,i=t?e.len-1:0,c=t?-1:1,l=i+c*e.len;for(s=0,o=i,a=1;o!=l;s+=n[r+o]*a,o+=c,a*=256);return e.bSigned&&s&Math.pow(2,8*e.len-1)&&(s-=Math.pow(2,8*e.len)),s},n._EnInt=function(n,r,s){var o,a=t?e.len-1:0,i=t?-1:1,c=a+i*e.len;for(s=s<e.min?e.min:s>e.max?e.max:s,o=a;o!=c;n[r+o]=255&s,o+=i,s>>=8);},n._DeString=function(e,t,n){for(var r=new Array(n),s=0;s<n;r[s]=String.fromCharCode(e[t+s]),s++);return r.join("")},n._EnString=function(e,t,n,r){for(var s,o=0;o<n;e[t+o]=(s=r.charCodeAt(o))?s:0,o++);},n._De754=function(n,r){var s,o,a,i,c,l,d,u,h,p;for(d=e.mLen,h=(p=(1<<(u=8*e.len-e.mLen-1))-1)>>1,i=t?0:e.len-1,c=t?1:-1,s=n[r+i],i+=c,o=s&(1<<-(l=-7))-1,s>>=-l,l+=u;l>0;o=256*o+n[r+i],i+=c,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=d;l>0;a=256*a+n[r+i],i+=c,l-=8);switch(o){case 0:o=1-h;break;case p:return a?NaN:1/0*(s?-1:1);default:a+=Math.pow(2,d),o-=h}return(s?-1:1)*a*Math.pow(2,o-d)},n._En754=function(n,r,s){var o,a,i,c,l,d,u,h,p,f;for(u=e.mLen,p=(f=(1<<(h=8*e.len-e.mLen-1))-1)>>1,o=s<0?1:0,s=Math.abs(s),isNaN(s)||s==1/0?(i=isNaN(s)?1:0,a=f):(a=Math.floor(Math.log(s)/Math.LN2),s*(d=Math.pow(2,-a))<1&&(a--,d*=2),(s+=a+p>=1?e.rt/d:e.rt*Math.pow(2,1-p))*d>=2&&(a++,d/=2),a+p>=f?(i=0,a=f):a+p>=1?(i=(s*d-1)*Math.pow(2,u),a+=p):(i=s*Math.pow(2,p-1)*Math.pow(2,u),a=0)),c=t?e.len-1:0,l=t?-1:1;u>=8;n[r+c]=255&i,c+=l,i/=256,u-=8);for(a=a<<u|i,h+=u;h>0;n[r+c]=255&a,c+=l,a/=256,h-=8);n[r+c-l]|=128*o},n._DeInt64=function(n,r){var s,o,a,i=t?0:7,c=t?1:-1,l=i+8*c,d=[0,0,!e.bSigned];for(s=i,a=1,o=0;s!=l;d[a]=(d[a]<<8>>>0)+n[r+s],s+=c,a=++o<4?1:0);return d},n._EnInt64=function(e,n,r){var s,o,a,i,c=t?0:7,l=t?1:-1,d=c+8*l;for(s=c,a=1,o=0,i=24;s!=d;e[n+s]=r[a]>>i&255,s+=l,a=++o<4?1:0,i=24-o%4*8);},n._sPattern="(\\d+)?([AxcbBhHsfdiIlLqQ])",n._lenLut={A:1,x:1,c:1,b:1,B:1,h:2,H:2,s:1,f:4,d:8,i:4,I:4,l:4,L:4,q:8,Q:8},n._elLut={A:{en:n._EnArray,de:n._DeArray},s:{en:n._EnString,de:n._DeString},c:{en:n._EnChar,de:n._DeChar},b:{en:n._EnInt,de:n._DeInt,len:1,bSigned:!0,min:-Math.pow(2,7),max:Math.pow(2,7)-1},B:{en:n._EnInt,de:n._DeInt,len:1,bSigned:!1,min:0,max:Math.pow(2,8)-1},h:{en:n._EnInt,de:n._DeInt,len:2,bSigned:!0,min:-Math.pow(2,15),max:Math.pow(2,15)-1},H:{en:n._EnInt,de:n._DeInt,len:2,bSigned:!1,min:0,max:Math.pow(2,16)-1},i:{en:n._EnInt,de:n._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},I:{en:n._EnInt,de:n._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},l:{en:n._EnInt,de:n._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},L:{en:n._EnInt,de:n._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},f:{en:n._En754,de:n._De754,len:4,mLen:23,rt:Math.pow(2,-24)-Math.pow(2,-77)},d:{en:n._En754,de:n._De754,len:8,mLen:52,rt:0},q:{en:n._EnInt64,de:n._DeInt64,bSigned:!0},Q:{en:n._EnInt64,de:n._DeInt64,bSigned:!1}},n._UnpackSeries=function(t,n,r,s){for(var o=e.de,a=[],i=0;i<t;a.push(o(r,s+i*n)),i++);return a},n._PackSeries=function(t,n,r,s,o,a){for(var i=e.en,c=0;c<t;i(r,s+c*n,o[a+c]),c++);},n.Unpack=function(n,r,s){t="<"!=n.charAt(0),s=s||0;for(var o,a,i,c=new RegExp(this._sPattern,"g"),l=[];o=c.exec(n);){if(s+(a=null==o[1]||""==o[1]?1:parseInt(o[1]))*(i=this._lenLut[o[2]])>r.length)return;switch(o[2]){case"A":case"s":l.push(this._elLut[o[2]].de(r,s,a));break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":e=this._elLut[o[2]],l.push(this._UnpackSeries(a,i,r,s))}s+=a*i}return Array.prototype.concat.apply([],l)},n.PackTo=function(n,r,s,o){t="<"!=n.charAt(0);for(var a,i,c,l,d=new RegExp(this._sPattern,"g"),u=0;a=d.exec(n);){if(s+(i=null==a[1]||""==a[1]?1:parseInt(a[1]))*(c=this._lenLut[a[2]])>r.length)return!1;switch(a[2]){case"A":case"s":if(u+1>o.length)return!1;this._elLut[a[2]].en(r,s,i,o[u]),u+=1;break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":if(e=this._elLut[a[2]],u+i>o.length)return!1;this._PackSeries(i,c,r,s,o,u),u+=i;break;case"x":for(l=0;l<i;l++)r[s+l]=0}s+=i*c}return r},n.Pack=function(e,t){return this.PackTo(e,new Array(this.CalcLength(e)),0,t)},n.CalcLength=function(e){for(var t,n=new RegExp(this._sPattern,"g"),r=0;t=n.exec(e);)r+=(null==t[1]||""==t[1]?1:parseInt(t[1]))*this._lenLut[t[2]];return r}}},952:e=>{var t=1e3,n=60*t,r=60*n,s=24*r;function o(e,t,n,r){var s=t>=1.5*n;return Math.round(e/n)+" "+r+(s?"s":"")}e.exports=function(e,a){a=a||{};var i,c,l=typeof e;if("string"===l&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return 6048e5*a;case"days":case"day":case"d":return a*s;case"hours":case"hour":case"hrs":case"hr":case"h":return a*r;case"minutes":case"minute":case"mins":case"min":case"m":return a*n;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===l&&isFinite(e))return a.long?(i=e,(c=Math.abs(i))>=s?o(i,c,s,"day"):c>=r?o(i,c,r,"hour"):c>=n?o(i,c,n,"minute"):c>=t?o(i,c,t,"second"):i+" ms"):function(e){var o=Math.abs(e);return o>=s?Math.round(e/s)+"d":o>=r?Math.round(e/r)+"h":o>=n?Math.round(e/n)+"m":o>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}}},t={};function n(r){var s=t[r];if(void 0!==s)return s.exports;var o=t[r]={exports:{}};return e[r](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.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 r={};(()=>{"use strict";n.d(r,{default:()=>st});var e={};n.r(e),n.d(e,{Basic:()=>ze,Bearer:()=>Qe,Jwt:()=>Xe});var t={};function s(e){const t=[];for(let n=0;n<e.length;n+=32768)t.push(String.fromCharCode.apply(null,[...e.subarray(n,n+32768)]));return btoa(t.join(""))}function o(e){let t;e=(e=(e=e.replace(/ /g,"+")).replace(/_/g,"/")).replace(/-/g,"+");try{t=atob(e)}catch(e){throw new TypeError("Invalid base64 sequence",{cause:e})}const n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}n.r(t),n.d(t,{Auth:()=>e,CONTENT_SUBTYPE_WEBSOCKET_EVENTS:()=>K,CONTENT_TYPE_APPLICATION:()=>M,CONTENT_TYPE_WEBSOCKET_EVENTS:()=>U,Channel:()=>w,ConnectionIdMissingException:()=>d,Format:()=>S,GripInstruct:()=>A,HttpResponseFormat:()=>i,HttpStreamFormat:()=>c,Item:()=>k,JwkKey:()=>$e,PUBLIC_KEY_FASTLY_FANOUT_JWK:()=>rt,PUBLIC_KEY_FASTLY_FANOUT_PEM:()=>nt,PemKey:()=>Je,PublishException:()=>I,Publisher:()=>tt,PublisherClient:()=>et,Response:()=>a,WebSocketContext:()=>y,WebSocketDecodeEventException:()=>m,WebSocketEvent:()=>h,WebSocketException:()=>l,WebSocketMessageFormat:()=>g,concatUint8Arrays:()=>H,createGripChannelHeader:()=>x,createKeepAliveHeader:()=>C,createMetaHeader:()=>v,createNextLinkHeader:()=>_,createWebSocketControlMessage:()=>L,decodeBytesFromBase64String:()=>o,decodeWebSocketEvents:()=>D,encodeBytesToBase64String:()=>s,encodeCString:()=>E,encodeWebSocketEvents:()=>F,escapeQuotes:()=>b,getWebSocketContextFromReq:()=>B,getWebSocketContextImpl:()=>J,isSymmetricSecret:()=>Be,isWsOverHttp:()=>$,isWsOverHttpImpl:()=>j,loadKey:()=>Ye,parseChannels:()=>P,parseGripUri:()=>T,validateSig:()=>qe});class a{code;reason;headers;body;constructor(...e){let t,n,r,s;1===e.length?({code:t=null,reason:n=null,headers:r=null,body:s=null}=e[0]):[t=null,n=null,r=null,s=null]=e,this.code=t,this.reason=n,this.headers=r,this.body=s}export(){const e={};return null!=this.code&&(e.code=this.code),null!=this.reason&&(e.reason=this.reason),null!=this.headers&&(e.headers=this.headers),null!=this.body&&(this.body instanceof Uint8Array?e["body-bin"]=s(this.body):e.body=this.body.toString()),e}}class i extends a{name(){return"http-response"}}class c{content;close;constructor(e=null,t=!1){if(null==e&&!t)throw new Error("HttpStreamFormat requires content.");this.content=e,this.close=t}name(){return"http-stream"}export(){const e={};return this.close?(e.action="close",e.content=""):this.content instanceof Uint8Array?e["content-bin"]=s(this.content):null!=this.content&&(e.content=this.content.toString()),e}}class l extends Error{}class d extends l{}var u=n(716);class h{type;content;constructor(e,t=null){this.type=e,this.content=t}getType(){return this.type}getContent(){return this.content}}const p=new TextEncoder,f=new TextDecoder;class y{id;inEvents;readIndex=0;accepted=!1;closeCode=null;closed=!1;outCloseCode=null;outEvents=[];origMeta;meta;prefix;constructor(e,t,n,r=""){this.id=e,this.meta=JSON.parse(JSON.stringify(t)),this.origMeta=t,this.inEvents=n,this.prefix=r}isOpening(){return this.inEvents.length>0&&"OPEN"===this.inEvents[0].type}accept(){this.accepted=!0}close(e=0){this.closed=!0,this.outCloseCode=e}canRecv(){for(let e=this.readIndex;e<this.inEvents.length;e++)if(["TEXT","BINARY","CLOSE","DISCONNECT"].indexOf(this.inEvents[e].type)>-1)return!0;return!1}disconnect(){this.outEvents.push(new h("DISCONNECT"))}recvRaw(){let e=null;for(;null==e&&this.readIndex<this.inEvents.length;)["TEXT","BINARY","CLOSE","DISCONNECT"].indexOf(this.inEvents[this.readIndex].type)>-1?e=this.inEvents[this.readIndex]:"PING"===this.inEvents[this.readIndex].type&&this.outEvents.push(new h("PONG")),this.readIndex+=1;if(null==e)throw new Error("Read from empty buffer.");const{type:t}=e;if("TEXT"===t)return null==e.content?"":"string"==typeof e.content?e.content:f.decode(e.content);if("BINARY"===t)return null==e.content?new Uint8Array:"string"==typeof e.content?p.encode(e.content):e.content;if("CLOSE"===t){const{content:t}=e;return t instanceof Uint8Array&&2===t.length&&(this.closeCode=u.I.Unpack(">H",[...t])[0]),null}throw new Error("Client disconnected unexpectedly.")}recv(){const e=this.recvRaw();return null==e?null:e.toString()}send(e){this.outEvents.push(new h("TEXT",H(p.encode("m:"),e instanceof Uint8Array?e:p.encode(e))))}sendBinary(e){this.outEvents.push(new h("BINARY",H(p.encode("m:"),e instanceof Uint8Array?e:p.encode(e))))}sendControl(e){this.outEvents.push(new h("TEXT",H(p.encode("c:"),e instanceof Uint8Array?e:p.encode(e))))}subscribe(e){this.sendControl(L("subscribe",{channel:this.prefix+e}))}unsubscribe(e){this.sendControl(L("unsubscribe",{channel:this.prefix+e}))}detach(){this.sendControl(L("detach"))}getOutgoingEvents(){const e=[];this.accepted&&e.push(new h("OPEN"));for(const t of this.outEvents)e.push(t);if(this.closed){const t=u.I.Pack(">H",[this.outCloseCode]);t&&e.push(new h("CLOSE",new Uint8Array(t)))}return e}toHeaders(){const e=Object.keys(this.origMeta).filter((e=>Object.keys(this.meta).every((t=>t.toLowerCase()!==e)))),t=Object.entries(this.meta).reduce(((e,[t,n])=>{const r=t.toLowerCase();return Object.entries(this.origMeta).every((([e,t])=>r!==e||n!==t))&&(e[r]=n),e}),{}),n={"Content-Type":"application/websocket-events"};this.accepted&&(n["Sec-WebSocket-Extensions"]="grip");for(const t of e)n["Set-Meta-"+t]="";for(const[e,r]of Object.entries(t))n["Set-Meta-"+e]=String(r);return n}}class m extends l{}class g{content;close;code;constructor(e=null,t=!1,n){if(null==e&&!t)throw new Error("WebSocketMessageFormat requires content.");this.content=e,this.close=t,this.code=n}name(){return"ws-message"}export(){const e={};return this.close?(e.action="close",null!=this.code&&(e.code=this.code)):this.content instanceof Uint8Array?e["content-bin"]=s(this.content):null!=this.content&&(e.content=this.content.toString()),e}}class w{name;prevId;constructor(e,t=null){this.name=e,this.prevId=t}export(){const e={name:this.name};return null!=this.prevId&&(e.prevId=this.prevId),e}}class S{}function E(e){let t="";for(const n of e)if("\\"===n)t+="\\\\";else if("\r"===n)t+="\\r";else if("\n"===n)t+="\\n";else if("\t"===n)t+="\\t";else{if(n.charCodeAt(0)<32)throw new Error("can't encode");t+=n}return t}function b(e){let t="";for(const n of e)t+='"'===n?'\\"':n;return t}function C(e,t){let n=null;if("string"==typeof e)try{n=E(e)+"; format=cstring"}catch(e){n=null}if(null==n){const t=new TextEncoder;n=s("string"==typeof e?t.encode(e):e)+"; format=base64"}return n+=`; timeout=${Math.floor(t)}`,n}function v(e){return Object.entries(e).map((([e,t])=>`${e}="${b(t)}"`)).join(", ")}function _(e,t=0){let n=`<${e}>; rel=next`;return t>0&&(n+=`; timeout=${Math.floor(t)}`),n}class A{status;hold;channels=[];timeout=0;keepAlive;keepAliveTimeout=0;nextLink;nextLinkTimeout=0;meta;constructor(e){null!=e&&this.addChannel(e)}addChannel(e){this.channels.push(...P(e))}setStatus(e){this.status=e}setHoldLongPoll(e){this.hold="response",null!=e&&(this.timeout=Math.floor(e))}setHoldStream(){this.hold="stream"}setKeepAlive(e,t){this.keepAlive=e,this.keepAliveTimeout=t}setNextLink(e,t=0){this.nextLink=e,this.nextLinkTimeout=t}toHeaders(e){const t={};return t["Grip-Channel"]=x(this.channels),null!=this.status&&(t["Grip-Status"]=`${this.status}`),null!=this.hold&&(t["Grip-Hold"]=this.hold,this.timeout>0&&(t["Grip-Timeout"]=`${this.timeout}`),null!=this.keepAlive&&(t["Grip-Keep-Alive"]=C(this.keepAlive,this.keepAliveTimeout)),null!=this.meta&&Object.entries(this.meta).length>0&&(t["Grip-Set-Meta"]=v(this.meta))),null!=this.nextLink&&(t["Grip-Link"]=_(this.nextLink,this.nextLinkTimeout)),Object.assign(t,e),t}}class k{formats;id;prevId;constructor(e,t,n){e=Array.isArray(e)?e:[e],this.formats=e,arguments.length>=3&&(this.prevId=n),arguments.length>=2&&(this.id=t)}export(){const e={formats:{}};null!=this.id&&(e.id=this.id),null!=this.prevId&&(e["prev-id"]=this.prevId);const t=new Set;for(const n of this.formats){const r=n.name();if(t.has(r))throw new Error(`More than one instance of ${r} specified`);t.add(r),e.formats[r]=n.export()}return e}}class I{message;context;constructor(e,t){this.message=e,this.context=t}}function P(e){return(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?new w(e):e))}function T(e,t){const n=new URL(e),r=n.searchParams;if(null!=t)for(const[e,n]of Object.entries(t))null!=n&&r.set(e,n);let s=null,o=null;""!==n.username&&(s=n.username,n.username=""),""!==n.password&&(o=n.password,n.password="");let a=null,i=null,c=null,l=null;r.has("iss")&&(a=r.get("iss"),r.delete("iss")),r.has("key")&&(i=r.get("key"),r.delete("key")),r.has("verify-iss")&&(c=r.get("verify-iss"),r.delete("verify-iss")),r.has("verify-key")&&(l=r.get("verify-key"),r.delete("verify-key")),n.pathname.endsWith("/")&&(n.pathname=n.pathname.slice(0,n.pathname.length-1));const d={control_uri:n.toString()};return null!=a&&(d.control_iss=a),null!=s&&(d.user=s),null!=o&&(d.pass=o),null!=i&&(d.key=i),null!=c&&(d.verify_iss=c),null!=l&&(d.verify_key=l),d}function x(e){e=P(e);const t=[];for(const n of e){const e=n.export();let r=e.name;e.prevId&&(r+="; prev-id="+e.prevId),t.push(r)}return t.join(", ")}function H(...e){const t=new Uint8Array(e.reduce(((e,t)=>e+t.length),0));let n=0;for(const r of e)t.set(r,n),n+=r.length;return t}const O=new TextEncoder,R=new TextDecoder;function F(e){const t=[],n=new Uint8Array([13,10]);for(const r of e){let e=r.getContent();null!=e?("string"==typeof e&&(e=O.encode(e)),t.push(O.encode(r.getType()+" "+e.length.toString(16)),n,e,n)):t.push(O.encode(r.getType()),n)}return H(...t)}function D(e){const t=[];let n=0,r=!1;for("string"==typeof e&&(e=O.encode(e),r=!0);n<e.length;){let s=e.findIndex(((t,r)=>!(r<n||r===e.length-1)&&13===t&&10===e.at(r+1)));if(-1===s)throw new Error("bad format");const o=e.slice(n,s);n=s+2,s=o.indexOf(32);let a=null;if(-1!==s){const t=o.slice(0,s),i=parseInt(R.decode(o.slice(s+1)),16),c=e.slice(n,n+i);n=n+i+2,a=new h(R.decode(t),r?R.decode(c):c)}else a=new h(R.decode(o));t.push(a)}return t}function L(e,t=null){const n=Object.assign({},t,{type:e});return JSON.stringify(n)}var W=n(448);const N=n.n(W)()("js-grip"),M="application",K="websocket-events",U=`${M}/${K}`;function j(e,t){if("POST"!==e)return!1;let n=t.get("content-type");if(null!=n){const e=n.indexOf(";");e>=0&&(n=n.slice(0,e)),n=n.trim(),N("content-type header",n)}else N("content-type header not present");if(n!==U)return!1;const r=t.get("accept");if(null==r)return N("accept header not present"),!1;N("accept header",r);for(let e of r.split(",")){const t=e.indexOf(";");if(t>=0&&(e=e.slice(0,t)),e=e.trim(),"*/*"===e||e===`${M}/*`||e===U)return!0}return!1}async function J(e,t,n){const r=e.get("connection-id");if(null==r)throw new d;N("Connection ID",r),N("Handling Meta - start");const s={};for(const[t,n]of e.entries()){const e=t.toLowerCase();if(e.startsWith("meta-")){const t=e.slice(5);s[t]=n,N(t,"=",n)}}N("Handling Meta - end");const o=await t();N("Decode body - start");let a=null;try{a=D(o)}catch(e){throw new m}N("Decode body - end"),N("Websocket Events",a),N("Creating Websocket Context - start");const i=new y(r,s,a,n);return N("Creating Websocket Context - end"),i}function $(e){return j(e.method,e.headers)}async function B(e,t=""){return J(e.headers,(async()=>{const t=await e.arrayBuffer();return new Uint8Array(t)}),t)}const G=new TextEncoder,V=new TextDecoder;function Y(...e){const t=e.reduce(((e,{length:t})=>e+t),0),n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n}const q=e=>(e=>{let t=e;"string"==typeof t&&(t=G.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,"_"),z=e=>{let t=e;t instanceof Uint8Array&&(t=V.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Q extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(e){super(e),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class X extends Q{static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(e,t="unspecified",n="unspecified"){super(e),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n}}class Z extends Q{static get code(){return"ERR_JWT_EXPIRED"}constructor(e,t="unspecified",n="unspecified"){super(e),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n}}class ee extends Q{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}}class te extends Q{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class ne extends Q{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class re extends Q{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}Symbol.asyncIterator;class se extends Q{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}const oe=crypto,ae=e=>e instanceof CryptoKey;oe.getRandomValues.bind(oe);const ie=(e,t,n=0)=>{0===n&&(t.unshift(t.length),t.unshift(6));const r=e.indexOf(t[0],n);if(-1===r)return!1;const s=e.subarray(r,r+t.length);return s.length===t.length&&(s.every(((e,n)=>e===t[n]))||ie(e,t,r+1))},ce=e=>{switch(!0){case ie(e,[42,134,72,206,61,3,1,7]):return"P-256";case ie(e,[43,129,4,0,34]):return"P-384";case ie(e,[43,129,4,0,35]):return"P-521";case ie(e,[43,101,110]):return"X25519";case ie(e,[43,101,111]):return"X448";case ie(e,[43,101,112]):return"Ed25519";case ie(e,[43,101,113]):return"Ed448";default:throw new te("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},le=async(e,t,n,r,s)=>{let o,a;const i=new Uint8Array(atob(n.replace(e,"")).split("").map((e=>e.charCodeAt(0)))),c="spki"===t;switch(r){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},a=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},a=c?["verify"]:["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},a=c?["verify"]:["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},a=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=ce(i);o=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},a=c?[]:["deriveBits"];break}case"EdDSA":o={name:ce(i)},a=c?["verify"]:["sign"];break;default:throw new te('Invalid or unsupported "alg" (Algorithm) value')}return oe.subtle.importKey(t,i,o,s?.extractable??!1,a)};function de(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 n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}async function ue(e,t){if(!de(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 z(e.k);case"RSA":if(void 0!==e.oth)throw new te('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return(async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:n}=function(e){let t,n;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},n=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},n=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}`},n=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new te('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},n=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},n=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},n=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},n=e.d?["deriveBits"]:[];break;default:throw new te('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"EdDSA":t={name:e.crv},n=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new te('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new te('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:n}}(e),r=[t,e.ext??!1,e.key_ops??n],s={...e};return delete s.alg,delete s.use,oe.subtle.importKey("jwk",s,...r)})({...e,alg:t});default:throw new te('Unsupported "kty" (Key Type) Parameter value')}}const he=function(e,t,n,r,s){if(void 0!==s.crit&&void 0===r.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||void 0===r.crit)return new Set;if(!Array.isArray(r.crit)||0===r.crit.length||r.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!==n?new Map([...Object.entries(n),...t.entries()]):t;for(const t of r.crit){if(!o.has(t))throw new te(`Extension Header Parameter "${t}" is not recognized`);if(void 0===s[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o.get(t)&&void 0===r[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)};function pe(e,t){const n=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:n,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:n,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:n,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:n,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new te(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}Symbol();const fe=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:n}=t.algorithm;if("number"!=typeof n||n<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function ye(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function me(e,t){return e.name===t}function ge(e){return parseInt(e.name.slice(4),10)}function we(e,t,...n){switch(t){case"HS256":case"HS384":case"HS512":{if(!me(e.algorithm,"HMAC"))throw ye("HMAC");const n=parseInt(t.slice(2),10);if(ge(e.algorithm.hash)!==n)throw ye(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!me(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ye("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(ge(e.algorithm.hash)!==n)throw ye(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!me(e.algorithm,"RSA-PSS"))throw ye("RSA-PSS");const n=parseInt(t.slice(2),10);if(ge(e.algorithm.hash)!==n)throw ye(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw ye("Ed25519 or Ed448");break;case"ES256":case"ES384":case"ES512":{if(!me(e.algorithm,"ECDSA"))throw ye("ECDSA");const n=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!==n)throw ye(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some((t=>e.usages.includes(t)))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const n=t.pop();e+=`one of ${t.join(", ")}, or ${n}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,n)}function Se(e,t,...n){if(n.length>2){const t=n.pop();e+=`one of type ${n.join(", ")}, or ${t}.`}else 2===n.length?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[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 Ee=(e,...t)=>Se("Key must be ",e,...t);function be(e,t,...n){return Se(`Key for the ${e} algorithm must be `,t,...n)}const Ce=e=>ae(e),ve=["CryptoKey"];function _e(e,t,n){if(ae(t))return we(t,e,n),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Ee(t,...ve));return oe.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[n])}throw new TypeError(Ee(t,...ve,"Uint8Array"))}const Ae=async(e,t,n,r)=>{const s=await _e(e,t,"verify");fe(e,s);const o=pe(e,s.algorithm);try{return await oe.subtle.verify(o,s,n,r)}catch{return!1}},ke=(...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let n;for(const e of t){const t=Object.keys(e);if(n&&0!==n.size)for(const e of t){if(n.has(e))return!1;n.add(e)}else n=new Set(t)}return!0},Ie=(e,t,n)=>{e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?((e,t)=>{if(!(t instanceof Uint8Array)){if(!Ce(t))throw new TypeError(be(e,t,...ve,"Uint8Array"));if("secret"!==t.type)throw new TypeError(`${ve.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}})(e,t):((e,t,n)=>{if(!Ce(t))throw new TypeError(be(e,t,...ve));if("secret"===t.type)throw new TypeError(`${ve.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===n&&"public"===t.type)throw new TypeError(`${ve.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===n&&"public"===t.type)throw new TypeError(`${ve.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===n&&"private"===t.type)throw new TypeError(`${ve.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===n&&"private"===t.type)throw new TypeError(`${ve.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)})(e,t,n)},Pe=(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)};const Te=e=>Math.floor(e.getTime()/1e3),xe=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,He=e=>{const t=xe.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let r;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":r=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":r=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":r=Math.round(3600*n);break;case"day":case"days":case"d":r=Math.round(86400*n);break;case"week":case"weeks":case"w":r=Math.round(604800*n);break;default:r=Math.round(31557600*n)}return"-"===t[1]||"ago"===t[4]?-r:r},Oe=e=>e.toLowerCase().replace(/^application\//,""),Re=(e,t,n={})=>{const{typ:r}=n;if(r&&("string"!=typeof e.typ||Oe(e.typ)!==Oe(r)))throw new X('unexpected "typ" JWT header value',"typ","check_failed");let s;try{s=JSON.parse(V.decode(t))}catch{}if(!de(s))throw new re("JWT Claims Set must be a top-level JSON object");const{requiredClaims:o=[],issuer:a,subject:i,audience:c,maxTokenAge:l}=n,d=[...o];void 0!==l&&d.push("iat"),void 0!==c&&d.push("aud"),void 0!==i&&d.push("sub"),void 0!==a&&d.push("iss");for(const e of new Set(d.reverse()))if(!(e in s))throw new X(`missing required "${e}" claim`,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(s.iss))throw new X('unexpected "iss" claim value',"iss","check_failed");if(i&&s.sub!==i)throw new X('unexpected "sub" claim value',"sub","check_failed");if(c&&(h="string"==typeof c?[c]:c,!("string"==typeof(u=s.aud)?h.includes(u):Array.isArray(u)&&h.some(Set.prototype.has.bind(new Set(u))))))throw new X('unexpected "aud" claim value',"aud","check_failed");var u,h;let p;switch(typeof n.clockTolerance){case"string":p=He(n.clockTolerance);break;case"number":p=n.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:f}=n,y=Te(f||new Date);if((void 0!==s.iat||l)&&"number"!=typeof s.iat)throw new X('"iat" claim must be a number',"iat","invalid");if(void 0!==s.nbf){if("number"!=typeof s.nbf)throw new X('"nbf" claim must be a number',"nbf","invalid");if(s.nbf>y+p)throw new X('"nbf" claim timestamp check failed',"nbf","check_failed")}if(void 0!==s.exp){if("number"!=typeof s.exp)throw new X('"exp" claim must be a number',"exp","invalid");if(s.exp<=y-p)throw new Z('"exp" claim timestamp check failed',"exp","check_failed")}if(l){const e=y-s.iat;if(e-p>("number"==typeof l?l:He(l)))throw new Z('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(e<0-p)throw new X('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return s};class Fe{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new ne("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!ke(this._protectedHeader,this._unprotectedHeader))throw new ne("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...this._protectedHeader,...this._unprotectedHeader};let r=!0;if(he(ne,new Map([["b64",!0]]),t?.crit,this._protectedHeader,n).has("b64")&&(r=this._protectedHeader.b64,"boolean"!=typeof r))throw new ne('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=n;if("string"!=typeof s||!s)throw new ne('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ie(s,e,"sign");let o,a=this._payload;r&&(a=G.encode(q(a))),o=this._protectedHeader?G.encode(q(JSON.stringify(this._protectedHeader))):G.encode("");const i=Y(o,G.encode("."),a),c=await(async(e,t,n)=>{const r=await _e(e,t,"sign");fe(e,r);const s=await oe.subtle.sign(pe(e,r.algorithm),r,n);return new Uint8Array(s)})(s,e,i),l={signature:q(c),payload:""};return r&&(l.payload=V.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=V.decode(o)),l}}class De{constructor(e){this._flattened=new Fe(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const n=await this._flattened.sign(e,t);if(void 0===n.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}function Le(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class We{constructor(e={}){if(!de(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:Le("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:Le("setNotBefore",Te(e))}:this._payload={...this._payload,nbf:Te(new Date)+He(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:Le("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:Le("setExpirationTime",Te(e))}:this._payload={...this._payload,exp:Te(new Date)+He(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:Te(new Date)}:e instanceof Date?this._payload={...this._payload,iat:Le("setIssuedAt",Te(e))}:this._payload="string"==typeof e?{...this._payload,iat:Le("setIssuedAt",Te(new Date)+He(e))}:{...this._payload,iat:Le("setIssuedAt",e)},this}}class Ne extends We{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const n=new De(G.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 re("JWTs MUST NOT use unencoded payload");return n.sign(e,t)}}let Me;"undefined"!=typeof navigator&&navigator.userAgent?.startsWith?.("Mozilla/5.0 ")||(Me="jose/v5.2.2");const Ke=z,Ue=new TextEncoder,je=new TextDecoder;class Je{keyString;type;constructor(e){if(e.startsWith("-----BEGIN PUBLIC KEY-----"))this.type="public";else{if(!e.startsWith("-----BEGIN PRIVATE KEY-----"))throw new TypeError("Attempt to construct PemKey with string that is evidently not a PEM");this.type="private"}this.keyString=e}async getKeyLike(e){if(0===this.keyString.indexOf("-----BEGIN PRIVATE KEY-----"))return async function(e,t,n){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return((e,t,n)=>le(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,n))(e,t,n)}(this.keyString,e);if(0===this.keyString.indexOf("-----BEGIN PUBLIC KEY-----"))return async function(e,t,n){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw new TypeError('"spki" must be SPKI formatted string');return((e,t,n)=>le(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,n))(e,t,void 0)}(this.keyString,e);throw new Error("PEM type not supported.")}}class $e{jwk;constructor(e){this.jwk=e}async getSecretOrKeyLike(e){return ue(this.jwk,e)}}function Be(e){return e instanceof Uint8Array||!(e instanceof Je)&&(e instanceof $e?"oct"===e.jwk.kty:"secret"===e.type)}function Ge(e){return e.startsWith("-----BEGIN PUBLIC KEY-----")||e.startsWith("-----BEGIN PRIVATE KEY-----")}function Ve(e){return null!=e.kty}function Ye(e){let t=e;if("string"==typeof t&&t.startsWith("base64:")&&(t=t.slice(7),t=o(t)),t instanceof Uint8Array&&45===t.at(0)&&45===t.at(1)&&45===t.at(2)&&45===t.at(3)&&45===t.at(4)){let e=null;try{e=je.decode(t)}catch{}null!=e&&Ge(e)&&(t=new Je(e))}if("string"==typeof t&&Ge(t)&&(t=new Je(t)),t instanceof Uint8Array&&123===t.at(0)){let e=null;try{e=je.decode(t)}catch{}if(null!=e){let n=null;try{n=JSON.parse(e)}catch{}null!=n&&Ve(n)&&(t=new $e(n))}}if("string"==typeof t&&t.startsWith("{")){let e=null;try{e=JSON.parse(t)}catch{}null!=e&&Ve(e)&&(t=new $e(e))}return Ve(t)&&(t=new $e(t)),"string"==typeof t&&(t=Ue.encode(t)),t}async function qe(e,t,n){let r,s;if(("string"==typeof t||t instanceof Uint8Array)&&(t=Ye(t)),t instanceof $e||t instanceof Je){let n;try{n=function(e){let t;if("string"==typeof e){const n=e.split(".");3!==n.length&&5!==n.length||([t]=n)}else if("object"==typeof e&&e){if(!("protected"in e))throw new TypeError("Token does not contain a Protected Header");t=e.protected}try{if("string"!=typeof t||!t)throw new Error;const e=JSON.parse(V.decode(Ke(t)));if(!de(e))throw new Error;return e}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}(e)}catch{n={}}const s=n.alg??(Be(t)?"HS256":"RS256");r=t instanceof $e?await t.getSecretOrKeyLike(s):await t.getKeyLike(s)}else r=t;try{s=await async function(e,t,n){const r=await async function(e,t,n){if(e instanceof Uint8Array&&(e=V.decode(e)),"string"!=typeof e)throw new ne("Compact JWS must be a string or Uint8Array");const{0:r,1:s,2:o,length:a}=e.split(".");if(3!==a)throw new ne("Invalid Compact JWS");const i=await async function(e,t,n){if(!de(e))throw new ne("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new ne('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new ne("JWS Protected Header incorrect type");if(void 0===e.payload)throw new ne("JWS Payload missing");if("string"!=typeof e.signature)throw new ne("JWS Signature missing or incorrect type");if(void 0!==e.header&&!de(e.header))throw new ne("JWS Unprotected Header incorrect type");let r={};if(e.protected)try{const t=z(e.protected);r=JSON.parse(V.decode(t))}catch{throw new ne("JWS Protected Header is invalid")}if(!ke(r,e.header))throw new ne("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...r,...e.header};let o=!0;if(he(ne,new Map([["b64",!0]]),n?.crit,r,s).has("b64")&&(o=r.b64,"boolean"!=typeof o))throw new ne('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=s;if("string"!=typeof a||!a)throw new ne('JWS "alg" (Algorithm) Header Parameter missing or invalid');const i=n&&Pe("algorithms",n.algorithms);if(i&&!i.has(a))throw new ee('"alg" (Algorithm) Header Parameter value not allowed');if(o){if("string"!=typeof e.payload)throw new ne("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new ne("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t&&(t=await t(r,e),c=!0),Ie(a,t,"verify");const l=Y(G.encode(e.protected??""),G.encode("."),"string"==typeof e.payload?G.encode(e.payload):e.payload);let d,u;try{d=z(e.signature)}catch{throw new ne("Failed to base64url decode the signature")}if(!await Ae(a,t,d,l))throw new se;if(o)try{u=z(e.payload)}catch{throw new ne("Failed to base64url decode the payload")}else u="string"==typeof e.payload?G.encode(e.payload):e.payload;const h={payload:u};return void 0!==e.protected&&(h.protectedHeader=r),void 0!==e.header&&(h.unprotectedHeader=e.header),c?{...h,key:t}:h}({payload:s,protected:r,signature:o},t,n),c={payload:i.payload,protectedHeader:i.protectedHeader};return"function"==typeof t?{...c,key:i.key}:c}(e,t,n);if(r.protectedHeader.crit?.includes("b64")&&!1===r.protectedHeader.b64)throw new re("JWTs MUST NOT use unencoded payload");const s={payload:Re(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return"function"==typeof t?{...s,key:r.key}:s}(e,r)}catch(e){return!1}return null==n||s.payload.iss===n}class ze{_user;_pass;constructor(e,t){this._user=e,this._pass=t}getUser(){return this._user}getPass(){return this._pass}async buildHeader(){const e=`${this._user}:${this._pass}`;return`Basic ${s((new TextEncoder).encode(e))}`}}class Qe{_token;constructor(e){this._token=e}getToken(){return this._token}async buildHeader(){return`Bearer ${this._token}`}}class Xe{_claim;_key;_alg;constructor(e,t,n){this._claim=e,this._key=t,this._alg=n}async buildHeader(){const e=this._key;let t,n=this._alg??(Be(e)?"HS256":"RS256");t=e instanceof $e?await e.getSecretOrKeyLike(n):e instanceof Je?await e.getKeyLike(n):e;const r=new Ne(this._claim).setProtectedHeader({alg:n}).setExpirationTime("10m");return`Bearer ${await r.sign(t)}`}getClaim(){return this._claim}getKey(){return this._key}}const Ze=new TextEncoder;class et{publishUri;_auth;_verifyComponents;options;constructor(e,t){let{control_uri:n,control_iss:r,user:s,pass:o,key:a,verify_key:i,verify_iss:c}=e;const l=new URL(n);if(l.pathname.endsWith("/")||(l.pathname+="/"),l.pathname+="publish/",this.publishUri=String(l),null!=r){const e=null!=a?Ye(a):new Uint8Array;this._auth=new Xe({iss:r},e),Be(e)&&null==i&&(i=a)}else"string"==typeof a?this._auth=new Qe(a):null!=s&&null!=o&&(this._auth=new ze(s,o));if(null!=c||null!=i){const e=null!=i?Ye(i):void 0;this._verifyComponents={verifyIss:c,verifyKey:e}}this.options=t??{}}getAuth(){return this._auth}getVerifyIss(){return this._verifyComponents?.verifyIss}getVerifyKey(){return this._verifyComponents?.verifyKey}async publish(e,t){const n=t.export();n.channel=e;const r=null!=this._auth?await this._auth.buildHeader():null,s=[n],o=JSON.stringify({items:s}),a={"Content-Type":"application/json","Content-Length":String(Ze.encode(o).length)};null!=r&&(a.Authorization=r);const i={method:"POST",headers:a,body:o};let c,l,d;try{c=await(this.options.fetch??fetch)(this.publishUri,i)}catch(e){throw new I(e instanceof Error?e.message:String(e),{statusCode:-1})}try{l="end",d=await c.text()}catch(e){l="close",d=e}const u={statusCode:c.status,headers:c.headers,httpBody:d};if("end"===l){if(u.statusCode<200||u.statusCode>=300)throw new I(JSON.stringify(u.httpBody),u)}else if("close"===l)throw new I("Connection closed unexpectedly",u)}}class tt{clients=[];constructor(e,t){this.applyConfigs(e??[],t)}applyConfigs(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)this.applyConfig(e,t)}applyConfig(e,t){const n="string"==typeof e?T(e):e,r=new et(n,{fetch:t?.fetch});this.addClient(r)}addClient(e){this.clients.push(e)}async publish(e,t){await Promise.all(this.clients.map((n=>n.publish(e,t))))}async publishFormats(e,t,n,r){await this.publish(e,new k(t,n,r))}async publishHttpResponse(e,t,n,r){const s=t instanceof i?t:new i({body:t});return this.publishFormats(e,s,n,r)}async publishHttpStream(e,t,n,r){const s=t instanceof c?t:new c(t);return this.publishFormats(e,s,n,r)}async validateGripSig(e){let t=!1,n=!1,r=!1;if(null==e||0===this.clients.length)return{isProxied:t,needsSigned:n,isSigned:r};let s=!1;n=!0;for(const t of this.clients){const r=t.getVerifyKey();if(null==r){n=!1;break}if(!s){const n=t.getVerifyIss();s=null==n?await qe(e,r):await qe(e,r,n)}}return n?s&&(t=!0,r=!0):t=!0,{isProxied:t,needsSigned:n,isSigned:r}}}const nt="-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAECKo5A1ebyFcnmVV8SE5On+8G81Jy\nBjSvcrx4VLetWCjuDAmppTo3xM/zz763COTCgHfp/6lPdCyYjjqc+GM7sw==\n-----END PUBLIC KEY-----",rt={kty:"EC",crv:"P-256",x:"CKo5A1ebyFcnmVV8SE5On-8G81JyBjSvcrx4VLetWCg",y:"7gwJqaU6N8TP88--twjkwoB36f-pT3QsmI46nPhjO7M"},st=t})(),Grip=r.default})(); | ||
var Grip;(()=>{var e={448:(e,t,n)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(s=r))})),t.splice(s,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=n(656)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},656:(e,t,n)=>{e.exports=function(e){function t(e){let n,s,o,a=null;function i(...e){if(!i.enabled)return;const r=i,s=Number(new Date),o=s-(n||s);r.diff=o,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";a++;const o=t.formatters[s];if("function"==typeof o){const t=e[a];n=o.call(r,t),e.splice(a,1),a--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return i.namespace=e,i.useColors=t.useColors(),i.color=t.selectColor(e),i.extend=r,i.destroy=t.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(s!==t.namespaces&&(s=t.namespaces,o=t.enabled(e)),o),set:e=>{a=e}}),"function"==typeof t.init&&t.init(i),i}function r(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function s(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(s),...t.skips.map(s).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(n=0;n<s;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=n(952),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}},716:(e,t)=>{t.I=new function(){var e,t=!1,n=this;n._DeArray=function(e,t,n){return[e.slice(t,t+n)]},n._EnArray=function(e,t,n,r){for(var s=0;s<n;e[t+s]=r[s]?r[s]:0,s++);},n._DeChar=function(e,t){return String.fromCharCode(e[t])},n._EnChar=function(e,t,n){e[t]=n.charCodeAt(0)},n._DeInt=function(n,r){var s,o,a,i=t?e.len-1:0,c=t?-1:1,l=i+c*e.len;for(s=0,o=i,a=1;o!=l;s+=n[r+o]*a,o+=c,a*=256);return e.bSigned&&s&Math.pow(2,8*e.len-1)&&(s-=Math.pow(2,8*e.len)),s},n._EnInt=function(n,r,s){var o,a=t?e.len-1:0,i=t?-1:1,c=a+i*e.len;for(s=s<e.min?e.min:s>e.max?e.max:s,o=a;o!=c;n[r+o]=255&s,o+=i,s>>=8);},n._DeString=function(e,t,n){for(var r=new Array(n),s=0;s<n;r[s]=String.fromCharCode(e[t+s]),s++);return r.join("")},n._EnString=function(e,t,n,r){for(var s,o=0;o<n;e[t+o]=(s=r.charCodeAt(o))?s:0,o++);},n._De754=function(n,r){var s,o,a,i,c,l,d,u,h,p;for(d=e.mLen,h=(p=(1<<(u=8*e.len-e.mLen-1))-1)>>1,i=t?0:e.len-1,c=t?1:-1,s=n[r+i],i+=c,o=s&(1<<-(l=-7))-1,s>>=-l,l+=u;l>0;o=256*o+n[r+i],i+=c,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=d;l>0;a=256*a+n[r+i],i+=c,l-=8);switch(o){case 0:o=1-h;break;case p:return a?NaN:1/0*(s?-1:1);default:a+=Math.pow(2,d),o-=h}return(s?-1:1)*a*Math.pow(2,o-d)},n._En754=function(n,r,s){var o,a,i,c,l,d,u,h,p,f;for(u=e.mLen,p=(f=(1<<(h=8*e.len-e.mLen-1))-1)>>1,o=s<0?1:0,s=Math.abs(s),isNaN(s)||s==1/0?(i=isNaN(s)?1:0,a=f):(a=Math.floor(Math.log(s)/Math.LN2),s*(d=Math.pow(2,-a))<1&&(a--,d*=2),(s+=a+p>=1?e.rt/d:e.rt*Math.pow(2,1-p))*d>=2&&(a++,d/=2),a+p>=f?(i=0,a=f):a+p>=1?(i=(s*d-1)*Math.pow(2,u),a+=p):(i=s*Math.pow(2,p-1)*Math.pow(2,u),a=0)),c=t?e.len-1:0,l=t?-1:1;u>=8;n[r+c]=255&i,c+=l,i/=256,u-=8);for(a=a<<u|i,h+=u;h>0;n[r+c]=255&a,c+=l,a/=256,h-=8);n[r+c-l]|=128*o},n._DeInt64=function(n,r){var s,o,a,i=t?0:7,c=t?1:-1,l=i+8*c,d=[0,0,!e.bSigned];for(s=i,a=1,o=0;s!=l;d[a]=(d[a]<<8>>>0)+n[r+s],s+=c,a=++o<4?1:0);return d},n._EnInt64=function(e,n,r){var s,o,a,i,c=t?0:7,l=t?1:-1,d=c+8*l;for(s=c,a=1,o=0,i=24;s!=d;e[n+s]=r[a]>>i&255,s+=l,a=++o<4?1:0,i=24-o%4*8);},n._sPattern="(\\d+)?([AxcbBhHsfdiIlLqQ])",n._lenLut={A:1,x:1,c:1,b:1,B:1,h:2,H:2,s:1,f:4,d:8,i:4,I:4,l:4,L:4,q:8,Q:8},n._elLut={A:{en:n._EnArray,de:n._DeArray},s:{en:n._EnString,de:n._DeString},c:{en:n._EnChar,de:n._DeChar},b:{en:n._EnInt,de:n._DeInt,len:1,bSigned:!0,min:-Math.pow(2,7),max:Math.pow(2,7)-1},B:{en:n._EnInt,de:n._DeInt,len:1,bSigned:!1,min:0,max:Math.pow(2,8)-1},h:{en:n._EnInt,de:n._DeInt,len:2,bSigned:!0,min:-Math.pow(2,15),max:Math.pow(2,15)-1},H:{en:n._EnInt,de:n._DeInt,len:2,bSigned:!1,min:0,max:Math.pow(2,16)-1},i:{en:n._EnInt,de:n._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},I:{en:n._EnInt,de:n._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},l:{en:n._EnInt,de:n._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},L:{en:n._EnInt,de:n._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},f:{en:n._En754,de:n._De754,len:4,mLen:23,rt:Math.pow(2,-24)-Math.pow(2,-77)},d:{en:n._En754,de:n._De754,len:8,mLen:52,rt:0},q:{en:n._EnInt64,de:n._DeInt64,bSigned:!0},Q:{en:n._EnInt64,de:n._DeInt64,bSigned:!1}},n._UnpackSeries=function(t,n,r,s){for(var o=e.de,a=[],i=0;i<t;a.push(o(r,s+i*n)),i++);return a},n._PackSeries=function(t,n,r,s,o,a){for(var i=e.en,c=0;c<t;i(r,s+c*n,o[a+c]),c++);},n.Unpack=function(n,r,s){t="<"!=n.charAt(0),s=s||0;for(var o,a,i,c=new RegExp(this._sPattern,"g"),l=[];o=c.exec(n);){if(s+(a=null==o[1]||""==o[1]?1:parseInt(o[1]))*(i=this._lenLut[o[2]])>r.length)return;switch(o[2]){case"A":case"s":l.push(this._elLut[o[2]].de(r,s,a));break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":e=this._elLut[o[2]],l.push(this._UnpackSeries(a,i,r,s))}s+=a*i}return Array.prototype.concat.apply([],l)},n.PackTo=function(n,r,s,o){t="<"!=n.charAt(0);for(var a,i,c,l,d=new RegExp(this._sPattern,"g"),u=0;a=d.exec(n);){if(s+(i=null==a[1]||""==a[1]?1:parseInt(a[1]))*(c=this._lenLut[a[2]])>r.length)return!1;switch(a[2]){case"A":case"s":if(u+1>o.length)return!1;this._elLut[a[2]].en(r,s,i,o[u]),u+=1;break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":if(e=this._elLut[a[2]],u+i>o.length)return!1;this._PackSeries(i,c,r,s,o,u),u+=i;break;case"x":for(l=0;l<i;l++)r[s+l]=0}s+=i*c}return r},n.Pack=function(e,t){return this.PackTo(e,new Array(this.CalcLength(e)),0,t)},n.CalcLength=function(e){for(var t,n=new RegExp(this._sPattern,"g"),r=0;t=n.exec(e);)r+=(null==t[1]||""==t[1]?1:parseInt(t[1]))*this._lenLut[t[2]];return r}}},952:e=>{var t=1e3,n=60*t,r=60*n,s=24*r;function o(e,t,n,r){var s=t>=1.5*n;return Math.round(e/n)+" "+r+(s?"s":"")}e.exports=function(e,a){a=a||{};var i,c,l=typeof e;if("string"===l&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return 6048e5*a;case"days":case"day":case"d":return a*s;case"hours":case"hour":case"hrs":case"hr":case"h":return a*r;case"minutes":case"minute":case"mins":case"min":case"m":return a*n;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===l&&isFinite(e))return a.long?(i=e,(c=Math.abs(i))>=s?o(i,c,s,"day"):c>=r?o(i,c,r,"hour"):c>=n?o(i,c,n,"minute"):c>=t?o(i,c,t,"second"):i+" ms"):function(e){var o=Math.abs(e);return o>=s?Math.round(e/s)+"d":o>=r?Math.round(e/r)+"h":o>=n?Math.round(e/n)+"m":o>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}}},t={};function n(r){var s=t[r];if(void 0!==s)return s.exports;var o=t[r]={exports:{}};return e[r](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.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 r={};(()=>{"use strict";n.d(r,{default:()=>st});var e={};n.r(e),n.d(e,{Basic:()=>ze,Bearer:()=>Qe,Jwt:()=>Xe});var t={};function s(e){const t=[];for(let n=0;n<e.length;n+=32768)t.push(String.fromCharCode.apply(null,[...e.subarray(n,n+32768)]));return btoa(t.join(""))}function o(e){let t;e=(e=(e=e.replace(/ /g,"+")).replace(/_/g,"/")).replace(/-/g,"+");try{t=atob(e)}catch(e){throw new TypeError("Invalid base64 sequence",{cause:e})}const n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}n.r(t),n.d(t,{Auth:()=>e,CONTENT_SUBTYPE_WEBSOCKET_EVENTS:()=>K,CONTENT_TYPE_APPLICATION:()=>M,CONTENT_TYPE_WEBSOCKET_EVENTS:()=>U,Channel:()=>w,ConnectionIdMissingException:()=>d,Format:()=>S,GripInstruct:()=>A,HttpResponseFormat:()=>i,HttpStreamFormat:()=>c,Item:()=>k,JwkKey:()=>$e,PUBLIC_KEY_FASTLY_FANOUT_JWK:()=>rt,PUBLIC_KEY_FASTLY_FANOUT_PEM:()=>nt,PemKey:()=>Je,PublishException:()=>I,Publisher:()=>tt,PublisherClient:()=>et,Response:()=>a,WebSocketContext:()=>y,WebSocketDecodeEventException:()=>m,WebSocketEvent:()=>h,WebSocketException:()=>l,WebSocketMessageFormat:()=>g,concatUint8Arrays:()=>H,createGripChannelHeader:()=>x,createKeepAliveHeader:()=>C,createMetaHeader:()=>v,createNextLinkHeader:()=>_,createWebSocketControlMessage:()=>L,decodeBytesFromBase64String:()=>o,decodeWebSocketEvents:()=>D,encodeBytesToBase64String:()=>s,encodeCString:()=>E,encodeWebSocketEvents:()=>F,escapeQuotes:()=>b,getWebSocketContextFromReq:()=>B,getWebSocketContextImpl:()=>J,isSymmetricSecret:()=>Be,isWsOverHttp:()=>$,isWsOverHttpImpl:()=>j,loadKey:()=>Ye,parseChannels:()=>P,parseGripUri:()=>T,validateSig:()=>qe});class a{code;reason;headers;body;constructor(...e){let t,n,r,s;1===e.length?({code:t=null,reason:n=null,headers:r=null,body:s=null}=e[0]):[t=null,n=null,r=null,s=null]=e,this.code=t,this.reason=n,this.headers=r,this.body=s}export(){const e={};return null!=this.code&&(e.code=this.code),null!=this.reason&&(e.reason=this.reason),null!=this.headers&&(e.headers=this.headers),null!=this.body&&(this.body instanceof Uint8Array?e["body-bin"]=s(this.body):e.body=this.body.toString()),e}}class i extends a{name(){return"http-response"}}class c{content;close;constructor(e=null,t=!1){if(null==e&&!t)throw new Error("HttpStreamFormat requires content.");this.content=e,this.close=t}name(){return"http-stream"}export(){const e={};return this.close?(e.action="close",e.content=""):this.content instanceof Uint8Array?e["content-bin"]=s(this.content):null!=this.content&&(e.content=this.content.toString()),e}}class l extends Error{}class d extends l{}var u=n(716);class h{type;content;constructor(e,t=null){this.type=e,this.content=t}getType(){return this.type}getContent(){return this.content}}const p=new TextEncoder,f=new TextDecoder;class y{id;inEvents;readIndex=0;accepted=!1;closeCode=null;closed=!1;outCloseCode=null;outEvents=[];origMeta;meta;prefix;constructor(e,t,n,r=""){this.id=e,this.meta=JSON.parse(JSON.stringify(t)),this.origMeta=t,this.inEvents=n,this.prefix=r}isOpening(){return this.inEvents.length>0&&"OPEN"===this.inEvents[0].type}accept(){this.accepted=!0}close(e=0){this.closed=!0,this.outCloseCode=e}canRecv(){for(let e=this.readIndex;e<this.inEvents.length;e++)if(["TEXT","BINARY","CLOSE","DISCONNECT"].indexOf(this.inEvents[e].type)>-1)return!0;return!1}disconnect(){this.outEvents.push(new h("DISCONNECT"))}recvRaw(){let e=null;for(;null==e&&this.readIndex<this.inEvents.length;)["TEXT","BINARY","CLOSE","DISCONNECT"].indexOf(this.inEvents[this.readIndex].type)>-1?e=this.inEvents[this.readIndex]:"PING"===this.inEvents[this.readIndex].type&&this.outEvents.push(new h("PONG")),this.readIndex+=1;if(null==e)throw new Error("Read from empty buffer.");const{type:t}=e;if("TEXT"===t)return null==e.content?"":"string"==typeof e.content?e.content:f.decode(e.content);if("BINARY"===t)return null==e.content?new Uint8Array:"string"==typeof e.content?p.encode(e.content):e.content;if("CLOSE"===t){const{content:t}=e;return t instanceof Uint8Array&&2===t.length&&(this.closeCode=u.I.Unpack(">H",[...t])[0]),null}throw new Error("Client disconnected unexpectedly.")}recv(){const e=this.recvRaw();return null==e?null:e.toString()}send(e){this.outEvents.push(new h("TEXT",H(p.encode("m:"),e instanceof Uint8Array?e:p.encode(e))))}sendBinary(e){this.outEvents.push(new h("BINARY",H(p.encode("m:"),e instanceof Uint8Array?e:p.encode(e))))}sendControl(e){this.outEvents.push(new h("TEXT",H(p.encode("c:"),e instanceof Uint8Array?e:p.encode(e))))}subscribe(e){this.sendControl(L("subscribe",{channel:this.prefix+e}))}unsubscribe(e){this.sendControl(L("unsubscribe",{channel:this.prefix+e}))}detach(){this.sendControl(L("detach"))}getOutgoingEvents(){const e=[];this.accepted&&e.push(new h("OPEN"));for(const t of this.outEvents)e.push(t);if(this.closed){const t=u.I.Pack(">H",[this.outCloseCode]);t&&e.push(new h("CLOSE",new Uint8Array(t)))}return e}toHeaders(){const e=Object.keys(this.origMeta).filter((e=>Object.keys(this.meta).every((t=>t.toLowerCase()!==e)))),t=Object.entries(this.meta).reduce(((e,[t,n])=>{const r=t.toLowerCase();return Object.entries(this.origMeta).every((([e,t])=>r!==e||n!==t))&&(e[r]=n),e}),{}),n={"Content-Type":"application/websocket-events"};this.accepted&&(n["Sec-WebSocket-Extensions"]="grip");for(const t of e)n["Set-Meta-"+t]="";for(const[e,r]of Object.entries(t))n["Set-Meta-"+e]=String(r);return n}}class m extends l{}class g{content;close;code;constructor(e=null,t=!1,n){if(null==e&&!t)throw new Error("WebSocketMessageFormat requires content.");this.content=e,this.close=t,this.code=n}name(){return"ws-message"}export(){const e={};return this.close?(e.action="close",null!=this.code&&(e.code=this.code)):this.content instanceof Uint8Array?e["content-bin"]=s(this.content):null!=this.content&&(e.content=this.content.toString()),e}}class w{name;prevId;constructor(e,t=null){this.name=e,this.prevId=t}export(){const e={name:this.name};return null!=this.prevId&&(e.prevId=this.prevId),e}}class S{}function E(e){let t="";for(const n of e)if("\\"===n)t+="\\\\";else if("\r"===n)t+="\\r";else if("\n"===n)t+="\\n";else if("\t"===n)t+="\\t";else{if(n.charCodeAt(0)<32)throw new Error("can't encode");t+=n}return t}function b(e){let t="";for(const n of e)t+='"'===n?'\\"':n;return t}function C(e,t){let n=null;if("string"==typeof e)try{n=E(e)+"; format=cstring"}catch(e){n=null}if(null==n){const t=new TextEncoder;n=s("string"==typeof e?t.encode(e):e)+"; format=base64"}return n+=`; timeout=${Math.floor(t)}`,n}function v(e){return Object.entries(e).map((([e,t])=>`${e}="${b(t)}"`)).join(", ")}function _(e,t=0){let n=`<${e}>; rel=next`;return t>0&&(n+=`; timeout=${Math.floor(t)}`),n}class A{status;hold;channels=[];timeout=0;keepAlive;keepAliveTimeout=0;nextLink;nextLinkTimeout=0;meta;constructor(e){null!=e&&this.addChannel(e)}addChannel(e){this.channels.push(...P(e))}setStatus(e){this.status=e}setHoldLongPoll(e){this.hold="response",null!=e&&(this.timeout=Math.floor(e))}setHoldStream(){this.hold="stream"}setKeepAlive(e,t){this.keepAlive=e,this.keepAliveTimeout=t}setNextLink(e,t=0){this.nextLink=e,this.nextLinkTimeout=t}toHeaders(e){const t={};return t["Grip-Channel"]=x(this.channels),null!=this.status&&(t["Grip-Status"]=`${this.status}`),null!=this.hold&&(t["Grip-Hold"]=this.hold,this.timeout>0&&(t["Grip-Timeout"]=`${this.timeout}`),null!=this.keepAlive&&(t["Grip-Keep-Alive"]=C(this.keepAlive,this.keepAliveTimeout)),null!=this.meta&&Object.entries(this.meta).length>0&&(t["Grip-Set-Meta"]=v(this.meta))),null!=this.nextLink&&(t["Grip-Link"]=_(this.nextLink,this.nextLinkTimeout)),Object.assign(t,e),t}}class k{formats;id;prevId;constructor(e,t,n){e=Array.isArray(e)?e:[e],this.formats=e,arguments.length>=3&&(this.prevId=n),arguments.length>=2&&(this.id=t)}export(){const e={formats:{}};null!=this.id&&(e.id=this.id),null!=this.prevId&&(e["prev-id"]=this.prevId);const t=new Set;for(const n of this.formats){const r=n.name();if(t.has(r))throw new Error(`More than one instance of ${r} specified`);t.add(r),e.formats[r]=n.export()}return e}}class I{message;context;constructor(e,t){this.message=e,this.context=t}}function P(e){return(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?new w(e):e))}function T(e,t){const n=new URL(e),r=n.searchParams;if(null!=t)for(const[e,n]of Object.entries(t))null!=n&&r.set(e,n);let s=null,o=null;""!==n.username&&(s=n.username,n.username=""),""!==n.password&&(o=n.password,n.password="");let a=null,i=null,c=null,l=null;r.has("iss")&&(a=r.get("iss"),r.delete("iss")),r.has("key")&&(i=r.get("key"),r.delete("key")),r.has("verify-iss")&&(c=r.get("verify-iss"),r.delete("verify-iss")),r.has("verify-key")&&(l=r.get("verify-key"),r.delete("verify-key")),n.pathname.endsWith("/")&&(n.pathname=n.pathname.slice(0,n.pathname.length-1));const d={control_uri:n.toString()};return null!=a&&(d.control_iss=a),null!=s&&(d.user=s),null!=o&&(d.pass=o),null!=i&&(d.key=i),null!=c&&(d.verify_iss=c),null!=l&&(d.verify_key=l),d}function x(e){e=P(e);const t=[];for(const n of e){const e=n.export();let r=e.name;e.prevId&&(r+="; prev-id="+e.prevId),t.push(r)}return t.join(", ")}function H(...e){const t=new Uint8Array(e.reduce(((e,t)=>e+t.length),0));let n=0;for(const r of e)t.set(r,n),n+=r.length;return t}const O=new TextEncoder,R=new TextDecoder;function F(e){const t=[],n=new Uint8Array([13,10]);for(const r of e){let e=r.getContent();null!=e?("string"==typeof e&&(e=O.encode(e)),t.push(O.encode(r.getType()+" "+e.length.toString(16)),n,e,n)):t.push(O.encode(r.getType()),n)}return H(...t)}function D(e){const t=[];let n=0,r=!1;for("string"==typeof e&&(e=O.encode(e),r=!0);n<e.length;){let s=e.findIndex(((t,r)=>!(r<n||r===e.length-1)&&13===t&&10===e.at(r+1)));if(-1===s)throw new Error("bad format");const o=e.slice(n,s);n=s+2,s=o.indexOf(32);let a=null;if(-1!==s){const t=o.slice(0,s),i=parseInt(R.decode(o.slice(s+1)),16),c=e.slice(n,n+i);n=n+i+2,a=new h(R.decode(t),r?R.decode(c):c)}else a=new h(R.decode(o));t.push(a)}return t}function L(e,t=null){const n=Object.assign({},t,{type:e});return JSON.stringify(n)}var W=n(448);const N=n.n(W)()("js-grip"),M="application",K="websocket-events",U=`${M}/${K}`;function j(e,t){if("POST"!==e)return!1;let n=t.get("content-type");if(null!=n){const e=n.indexOf(";");e>=0&&(n=n.slice(0,e)),n=n.trim(),N("content-type header",n)}else N("content-type header not present");if(n!==U)return!1;const r=t.get("accept");if(null==r)return N("accept header not present"),!1;N("accept header",r);for(let e of r.split(",")){const t=e.indexOf(";");if(t>=0&&(e=e.slice(0,t)),e=e.trim(),"*/*"===e||e===`${M}/*`||e===U)return!0}return!1}async function J(e,t,n){const r=e.get("connection-id");if(null==r)throw new d;N("Connection ID",r),N("Handling Meta - start");const s={};for(const[t,n]of e.entries()){const e=t.toLowerCase();if(e.startsWith("meta-")){const t=e.slice(5);s[t]=n,N(t,"=",n)}}N("Handling Meta - end");const o=await t();N("Decode body - start");let a=null;try{a=D(o)}catch(e){throw new m}N("Decode body - end"),N("Websocket Events",a),N("Creating Websocket Context - start");const i=new y(r,s,a,n);return N("Creating Websocket Context - end"),i}function $(e){return j(e.method,e.headers)}async function B(e,t=""){return J(e.headers,(async()=>{const t=await e.arrayBuffer();return new Uint8Array(t)}),t)}const G=new TextEncoder,V=new TextDecoder;function Y(...e){const t=e.reduce(((e,{length:t})=>e+t),0),n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n}const q=e=>(e=>{let t=e;"string"==typeof t&&(t=G.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,"_"),z=e=>{let t=e;t instanceof Uint8Array&&(t=V.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Q extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(e){super(e),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class X extends Q{static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(e,t="unspecified",n="unspecified"){super(e),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n}}class Z extends Q{static get code(){return"ERR_JWT_EXPIRED"}constructor(e,t="unspecified",n="unspecified"){super(e),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n}}class ee extends Q{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}}class te extends Q{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class ne extends Q{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class re extends Q{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}Symbol.asyncIterator;class se extends Q{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}const oe=crypto,ae=e=>e instanceof CryptoKey;oe.getRandomValues.bind(oe);const ie=(e,t,n=0)=>{0===n&&(t.unshift(t.length),t.unshift(6));const r=e.indexOf(t[0],n);if(-1===r)return!1;const s=e.subarray(r,r+t.length);return s.length===t.length&&(s.every(((e,n)=>e===t[n]))||ie(e,t,r+1))},ce=e=>{switch(!0){case ie(e,[42,134,72,206,61,3,1,7]):return"P-256";case ie(e,[43,129,4,0,34]):return"P-384";case ie(e,[43,129,4,0,35]):return"P-521";case ie(e,[43,101,110]):return"X25519";case ie(e,[43,101,111]):return"X448";case ie(e,[43,101,112]):return"Ed25519";case ie(e,[43,101,113]):return"Ed448";default:throw new te("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},le=async(e,t,n,r,s)=>{let o,a;const i=new Uint8Array(atob(n.replace(e,"")).split("").map((e=>e.charCodeAt(0)))),c="spki"===t;switch(r){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},a=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},a=c?["verify"]:["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},a=c?["verify"]:["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},a=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=ce(i);o=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},a=c?[]:["deriveBits"];break}case"EdDSA":o={name:ce(i)},a=c?["verify"]:["sign"];break;default:throw new te('Invalid or unsupported "alg" (Algorithm) value')}return oe.subtle.importKey(t,i,o,s?.extractable??!1,a)};function de(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 n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}async function ue(e,t){if(!de(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 z(e.k);case"RSA":if(void 0!==e.oth)throw new te('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return(async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:n}=function(e){let t,n;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},n=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},n=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}`},n=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new te('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},n=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},n=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},n=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},n=e.d?["deriveBits"]:[];break;default:throw new te('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"EdDSA":t={name:e.crv},n=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new te('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new te('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:n}}(e),r=[t,e.ext??!1,e.key_ops??n],s={...e};return delete s.alg,delete s.use,oe.subtle.importKey("jwk",s,...r)})({...e,alg:t});default:throw new te('Unsupported "kty" (Key Type) Parameter value')}}const he=function(e,t,n,r,s){if(void 0!==s.crit&&void 0===r.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||void 0===r.crit)return new Set;if(!Array.isArray(r.crit)||0===r.crit.length||r.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!==n?new Map([...Object.entries(n),...t.entries()]):t;for(const t of r.crit){if(!o.has(t))throw new te(`Extension Header Parameter "${t}" is not recognized`);if(void 0===s[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o.get(t)&&void 0===r[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)};function pe(e,t){const n=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:n,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:n,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:n,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:n,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new te(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}Symbol();const fe=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:n}=t.algorithm;if("number"!=typeof n||n<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function ye(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function me(e,t){return e.name===t}function ge(e){return parseInt(e.name.slice(4),10)}function we(e,t,...n){switch(t){case"HS256":case"HS384":case"HS512":{if(!me(e.algorithm,"HMAC"))throw ye("HMAC");const n=parseInt(t.slice(2),10);if(ge(e.algorithm.hash)!==n)throw ye(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!me(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ye("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(ge(e.algorithm.hash)!==n)throw ye(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!me(e.algorithm,"RSA-PSS"))throw ye("RSA-PSS");const n=parseInt(t.slice(2),10);if(ge(e.algorithm.hash)!==n)throw ye(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw ye("Ed25519 or Ed448");break;case"ES256":case"ES384":case"ES512":{if(!me(e.algorithm,"ECDSA"))throw ye("ECDSA");const n=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!==n)throw ye(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some((t=>e.usages.includes(t)))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const n=t.pop();e+=`one of ${t.join(", ")}, or ${n}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,n)}function Se(e,t,...n){if(n.length>2){const t=n.pop();e+=`one of type ${n.join(", ")}, or ${t}.`}else 2===n.length?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[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 Ee=(e,...t)=>Se("Key must be ",e,...t);function be(e,t,...n){return Se(`Key for the ${e} algorithm must be `,t,...n)}const Ce=e=>ae(e),ve=["CryptoKey"];function _e(e,t,n){if(ae(t))return we(t,e,n),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Ee(t,...ve));return oe.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[n])}throw new TypeError(Ee(t,...ve,"Uint8Array"))}const Ae=async(e,t,n,r)=>{const s=await _e(e,t,"verify");fe(e,s);const o=pe(e,s.algorithm);try{return await oe.subtle.verify(o,s,n,r)}catch{return!1}},ke=(...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let n;for(const e of t){const t=Object.keys(e);if(n&&0!==n.size)for(const e of t){if(n.has(e))return!1;n.add(e)}else n=new Set(t)}return!0},Ie=(e,t,n)=>{e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?((e,t)=>{if(!(t instanceof Uint8Array)){if(!Ce(t))throw new TypeError(be(e,t,...ve,"Uint8Array"));if("secret"!==t.type)throw new TypeError(`${ve.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}})(e,t):((e,t,n)=>{if(!Ce(t))throw new TypeError(be(e,t,...ve));if("secret"===t.type)throw new TypeError(`${ve.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===n&&"public"===t.type)throw new TypeError(`${ve.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===n&&"public"===t.type)throw new TypeError(`${ve.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===n&&"private"===t.type)throw new TypeError(`${ve.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===n&&"private"===t.type)throw new TypeError(`${ve.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)})(e,t,n)},Pe=(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)};const Te=e=>Math.floor(e.getTime()/1e3),xe=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,He=e=>{const t=xe.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let r;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":r=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":r=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":r=Math.round(3600*n);break;case"day":case"days":case"d":r=Math.round(86400*n);break;case"week":case"weeks":case"w":r=Math.round(604800*n);break;default:r=Math.round(31557600*n)}return"-"===t[1]||"ago"===t[4]?-r:r},Oe=e=>e.toLowerCase().replace(/^application\//,""),Re=(e,t,n={})=>{const{typ:r}=n;if(r&&("string"!=typeof e.typ||Oe(e.typ)!==Oe(r)))throw new X('unexpected "typ" JWT header value',"typ","check_failed");let s;try{s=JSON.parse(V.decode(t))}catch{}if(!de(s))throw new re("JWT Claims Set must be a top-level JSON object");const{requiredClaims:o=[],issuer:a,subject:i,audience:c,maxTokenAge:l}=n,d=[...o];void 0!==l&&d.push("iat"),void 0!==c&&d.push("aud"),void 0!==i&&d.push("sub"),void 0!==a&&d.push("iss");for(const e of new Set(d.reverse()))if(!(e in s))throw new X(`missing required "${e}" claim`,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(s.iss))throw new X('unexpected "iss" claim value',"iss","check_failed");if(i&&s.sub!==i)throw new X('unexpected "sub" claim value',"sub","check_failed");if(c&&(h="string"==typeof c?[c]:c,!("string"==typeof(u=s.aud)?h.includes(u):Array.isArray(u)&&h.some(Set.prototype.has.bind(new Set(u))))))throw new X('unexpected "aud" claim value',"aud","check_failed");var u,h;let p;switch(typeof n.clockTolerance){case"string":p=He(n.clockTolerance);break;case"number":p=n.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:f}=n,y=Te(f||new Date);if((void 0!==s.iat||l)&&"number"!=typeof s.iat)throw new X('"iat" claim must be a number',"iat","invalid");if(void 0!==s.nbf){if("number"!=typeof s.nbf)throw new X('"nbf" claim must be a number',"nbf","invalid");if(s.nbf>y+p)throw new X('"nbf" claim timestamp check failed',"nbf","check_failed")}if(void 0!==s.exp){if("number"!=typeof s.exp)throw new X('"exp" claim must be a number',"exp","invalid");if(s.exp<=y-p)throw new Z('"exp" claim timestamp check failed',"exp","check_failed")}if(l){const e=y-s.iat;if(e-p>("number"==typeof l?l:He(l)))throw new Z('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(e<0-p)throw new X('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return s};class Fe{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new ne("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!ke(this._protectedHeader,this._unprotectedHeader))throw new ne("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...this._protectedHeader,...this._unprotectedHeader};let r=!0;if(he(ne,new Map([["b64",!0]]),t?.crit,this._protectedHeader,n).has("b64")&&(r=this._protectedHeader.b64,"boolean"!=typeof r))throw new ne('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=n;if("string"!=typeof s||!s)throw new ne('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ie(s,e,"sign");let o,a=this._payload;r&&(a=G.encode(q(a))),o=this._protectedHeader?G.encode(q(JSON.stringify(this._protectedHeader))):G.encode("");const i=Y(o,G.encode("."),a),c=await(async(e,t,n)=>{const r=await _e(e,t,"sign");fe(e,r);const s=await oe.subtle.sign(pe(e,r.algorithm),r,n);return new Uint8Array(s)})(s,e,i),l={signature:q(c),payload:""};return r&&(l.payload=V.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=V.decode(o)),l}}class De{constructor(e){this._flattened=new Fe(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const n=await this._flattened.sign(e,t);if(void 0===n.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}function Le(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class We{constructor(e={}){if(!de(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:Le("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:Le("setNotBefore",Te(e))}:this._payload={...this._payload,nbf:Te(new Date)+He(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:Le("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:Le("setExpirationTime",Te(e))}:this._payload={...this._payload,exp:Te(new Date)+He(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:Te(new Date)}:e instanceof Date?this._payload={...this._payload,iat:Le("setIssuedAt",Te(e))}:this._payload="string"==typeof e?{...this._payload,iat:Le("setIssuedAt",Te(new Date)+He(e))}:{...this._payload,iat:Le("setIssuedAt",e)},this}}class Ne extends We{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const n=new De(G.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 re("JWTs MUST NOT use unencoded payload");return n.sign(e,t)}}let Me;"undefined"!=typeof navigator&&navigator.userAgent?.startsWith?.("Mozilla/5.0 ")||(Me="jose/v5.2.2");const Ke=z,Ue=new TextEncoder,je=new TextDecoder;class Je{keyString;type;constructor(e){if(e.startsWith("-----BEGIN PUBLIC KEY-----"))this.type="public";else{if(!e.startsWith("-----BEGIN PRIVATE KEY-----"))throw new TypeError("Attempt to construct PemKey with string that is evidently not a PEM");this.type="private"}this.keyString=e}async getKeyLike(e){if(0===this.keyString.indexOf("-----BEGIN PRIVATE KEY-----"))return async function(e,t,n){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return((e,t,n)=>le(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,n))(e,t,n)}(this.keyString,e);if(0===this.keyString.indexOf("-----BEGIN PUBLIC KEY-----"))return async function(e,t,n){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw new TypeError('"spki" must be SPKI formatted string');return((e,t,n)=>le(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,n))(e,t,void 0)}(this.keyString,e);throw new Error("PEM type not supported.")}}class $e{jwk;constructor(e){this.jwk=e}async getSecretOrKeyLike(e){return ue(this.jwk,e)}}function Be(e){return e instanceof Uint8Array||!(e instanceof Je)&&(e instanceof $e?"oct"===e.jwk.kty:"secret"===e.type)}function Ge(e){return e.startsWith("-----BEGIN PUBLIC KEY-----")||e.startsWith("-----BEGIN PRIVATE KEY-----")}function Ve(e){return null!=e.kty}function Ye(e){let t=e;if("string"==typeof t&&t.startsWith("base64:")&&(t=t.slice(7),t=o(t)),t instanceof Uint8Array&&45===t.at(0)&&45===t.at(1)&&45===t.at(2)&&45===t.at(3)&&45===t.at(4)){let e=null;try{e=je.decode(t)}catch{}null!=e&&Ge(e)&&(t=new Je(e))}if("string"==typeof t&&Ge(t)&&(t=new Je(t)),t instanceof Uint8Array&&123===t.at(0)){let e=null;try{e=je.decode(t)}catch{}if(null!=e){let n=null;try{n=JSON.parse(e)}catch{}null!=n&&Ve(n)&&(t=new $e(n))}}if("string"==typeof t&&t.startsWith("{")){let e=null;try{e=JSON.parse(t)}catch{}null!=e&&Ve(e)&&(t=new $e(e))}return Ve(t)&&(t=new $e(t)),"string"==typeof t&&(t=Ue.encode(t)),t}async function qe(e,t,n){let r,s;if(("string"==typeof t||t instanceof Uint8Array)&&(t=Ye(t)),t instanceof $e||t instanceof Je){let n;try{n=function(e){let t;if("string"==typeof e){const n=e.split(".");3!==n.length&&5!==n.length||([t]=n)}else if("object"==typeof e&&e){if(!("protected"in e))throw new TypeError("Token does not contain a Protected Header");t=e.protected}try{if("string"!=typeof t||!t)throw new Error;const e=JSON.parse(V.decode(Ke(t)));if(!de(e))throw new Error;return e}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}(e)}catch{n={}}const s=n.alg??(Be(t)?"HS256":"RS256");r=t instanceof $e?await t.getSecretOrKeyLike(s):await t.getKeyLike(s)}else r=t;try{s=await async function(e,t,n){const r=await async function(e,t,n){if(e instanceof Uint8Array&&(e=V.decode(e)),"string"!=typeof e)throw new ne("Compact JWS must be a string or Uint8Array");const{0:r,1:s,2:o,length:a}=e.split(".");if(3!==a)throw new ne("Invalid Compact JWS");const i=await async function(e,t,n){if(!de(e))throw new ne("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new ne('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new ne("JWS Protected Header incorrect type");if(void 0===e.payload)throw new ne("JWS Payload missing");if("string"!=typeof e.signature)throw new ne("JWS Signature missing or incorrect type");if(void 0!==e.header&&!de(e.header))throw new ne("JWS Unprotected Header incorrect type");let r={};if(e.protected)try{const t=z(e.protected);r=JSON.parse(V.decode(t))}catch{throw new ne("JWS Protected Header is invalid")}if(!ke(r,e.header))throw new ne("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...r,...e.header};let o=!0;if(he(ne,new Map([["b64",!0]]),n?.crit,r,s).has("b64")&&(o=r.b64,"boolean"!=typeof o))throw new ne('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=s;if("string"!=typeof a||!a)throw new ne('JWS "alg" (Algorithm) Header Parameter missing or invalid');const i=n&&Pe("algorithms",n.algorithms);if(i&&!i.has(a))throw new ee('"alg" (Algorithm) Header Parameter value not allowed');if(o){if("string"!=typeof e.payload)throw new ne("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new ne("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t&&(t=await t(r,e),c=!0),Ie(a,t,"verify");const l=Y(G.encode(e.protected??""),G.encode("."),"string"==typeof e.payload?G.encode(e.payload):e.payload);let d,u;try{d=z(e.signature)}catch{throw new ne("Failed to base64url decode the signature")}if(!await Ae(a,t,d,l))throw new se;if(o)try{u=z(e.payload)}catch{throw new ne("Failed to base64url decode the payload")}else u="string"==typeof e.payload?G.encode(e.payload):e.payload;const h={payload:u};return void 0!==e.protected&&(h.protectedHeader=r),void 0!==e.header&&(h.unprotectedHeader=e.header),c?{...h,key:t}:h}({payload:s,protected:r,signature:o},t,n),c={payload:i.payload,protectedHeader:i.protectedHeader};return"function"==typeof t?{...c,key:i.key}:c}(e,t,n);if(r.protectedHeader.crit?.includes("b64")&&!1===r.protectedHeader.b64)throw new re("JWTs MUST NOT use unencoded payload");const s={payload:Re(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return"function"==typeof t?{...s,key:r.key}:s}(e,r)}catch(e){return!1}return null==n||s.payload.iss===n}class ze{_user;_pass;constructor(e,t){this._user=e,this._pass=t}getUser(){return this._user}getPass(){return this._pass}async buildHeader(){const e=`${this._user}:${this._pass}`;return`Basic ${s((new TextEncoder).encode(e))}`}}class Qe{_token;constructor(e){this._token=e}getToken(){return this._token}async buildHeader(){return`Bearer ${this._token}`}}class Xe{_claim;_key;_alg;constructor(e,t,n){this._claim=e,this._key=t,this._alg=n}async buildHeader(){const e=this._key;let t,n=this._alg??(Be(e)?"HS256":"RS256");t=e instanceof $e?await e.getSecretOrKeyLike(n):e instanceof Je?await e.getKeyLike(n):e;const r=new Ne(this._claim).setProtectedHeader({alg:n}).setExpirationTime("10m");return`Bearer ${await r.sign(t)}`}getClaim(){return this._claim}getKey(){return this._key}}const Ze=new TextEncoder;class et{publishUri;_auth;_verifyComponents;options;constructor(e,t){let{control_uri:n,control_iss:r,user:s,pass:o,key:a,verify_key:i,verify_iss:c}=e;const l=new URL(n);if(l.pathname.endsWith("/")||(l.pathname+="/"),l.pathname+="publish/",this.publishUri=String(l),null!=r){const e=null!=a?Ye(a):new Uint8Array;this._auth=new Xe({iss:r},e),Be(e)&&null==i&&(i=a)}else"string"==typeof a?this._auth=new Qe(a):null!=s&&null!=o&&(this._auth=new ze(s,o));if(null!=c||null!=i){const e=null!=i?Ye(i):void 0;this._verifyComponents={verifyIss:c,verifyKey:e}}this.options=t??{}}getAuth(){return this._auth}getVerifyIss(){return this._verifyComponents?.verifyIss}getVerifyKey(){return this._verifyComponents?.verifyKey}async publish(e,t){const n=t.export();n.channel=e;const r=null!=this._auth?await this._auth.buildHeader():null,s=[n],o=JSON.stringify({items:s}),a={"Content-Type":"application/json","Content-Length":String(Ze.encode(o).length)};null!=r&&(a.Authorization=r);const i={method:"POST",headers:a,body:o};let c,l,d;try{c=await(this.options.fetch??fetch)(this.publishUri,i)}catch(e){throw new I(e instanceof Error?e.message:String(e),{statusCode:-1})}try{l="end",d=await c.text()}catch(e){l="close",d=e}const u={statusCode:c.status,headers:c.headers,httpBody:d};if("end"===l){if(u.statusCode<200||u.statusCode>=300)throw new I(JSON.stringify(u.httpBody),u)}else if("close"===l)throw new I("Connection closed unexpectedly",u)}}class tt{clients=[];prefix;constructor(e,t){this.applyConfigs(e??[],t),this.prefix=t?.prefix}applyConfigs(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)this.applyConfig(e,t)}applyConfig(e,t){const n="string"==typeof e?T(e):e,r=new et(n,{fetch:t?.fetch});this.addClient(r)}addClient(e){this.clients.push(e)}async publish(e,t){await Promise.all(this.clients.map((n=>n.publish((this.prefix??"")+e,t))))}async publishFormats(e,t,n,r){await this.publish(e,new k(t,n,r))}async publishHttpResponse(e,t,n,r){const s=t instanceof i?t:new i({body:t});return this.publishFormats(e,s,n,r)}async publishHttpStream(e,t,n,r){const s=t instanceof c?t:new c(t);return this.publishFormats(e,s,n,r)}async validateGripSig(e){let t=!1,n=!1,r=!1;if(null==e||0===this.clients.length)return{isProxied:t,needsSigned:n,isSigned:r};let s=!1;n=!0;for(const t of this.clients){const r=t.getVerifyKey?.();if(null==r){n=!1;break}if(!s){const n=t.getVerifyIss?.();s=null==n?await qe(e,r):await qe(e,r,n)}}return n?s&&(t=!0,r=!0):t=!0,{isProxied:t,needsSigned:n,isSigned:r}}}const nt="-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAECKo5A1ebyFcnmVV8SE5On+8G81Jy\nBjSvcrx4VLetWCjuDAmppTo3xM/zz763COTCgHfp/6lPdCyYjjqc+GM7sw==\n-----END PUBLIC KEY-----",rt={kty:"EC",crv:"P-256",x:"CKo5A1ebyFcnmVV8SE5On-8G81JyBjSvcrx4VLetWCg",y:"7gwJqaU6N8TP88--twjkwoB36f-pT3QsmI46nPhjO7M"},st=t})(),Grip=r.default})(); | ||
//# sourceMappingURL=grip.min.js.map |
@@ -6,7 +6,7 @@ import * as jose from 'jose'; | ||
export interface IPublisherClient { | ||
getAuth(): Auth.IAuth | undefined; | ||
getVerifyIss(): string | undefined; | ||
getVerifyKey(): Uint8Array | jose.KeyLike | PemKey | JwkKey | undefined; | ||
getAuth?(): Auth.IAuth | undefined; | ||
getVerifyIss?(): string | undefined; | ||
getVerifyKey?(): Uint8Array | jose.KeyLike | PemKey | JwkKey | undefined; | ||
publish(channel: string, item: IItem): Promise<void>; | ||
} | ||
//# sourceMappingURL=IPublisherClient.d.ts.map |
import { HttpResponseFormat, HttpStreamFormat } from '../data/index.js'; | ||
import { PublisherClientOptions } from './PublisherClient.js'; | ||
import type { IPublisherClient } from './IPublisherClient.js'; | ||
@@ -6,4 +7,4 @@ import type { IGripConfig } from './IGripConfig.js'; | ||
export type GripUrlOrConfigs = string | IGripConfig | (string | IGripConfig)[]; | ||
export type PublisherOptions = { | ||
fetch?: typeof fetch; | ||
export type PublisherOptions = PublisherClientOptions & { | ||
prefix?: string; | ||
}; | ||
@@ -17,5 +18,6 @@ export type ValidateGripSigResult = { | ||
clients: IPublisherClient[]; | ||
constructor(config?: GripUrlOrConfigs, clientOptions?: PublisherOptions); | ||
applyConfigs(config: GripUrlOrConfigs, clientOptions?: PublisherOptions): void; | ||
applyConfig(config: string | IGripConfig, clientOptions?: PublisherOptions): void; | ||
prefix: string | undefined; | ||
constructor(config?: GripUrlOrConfigs, publisherOptions?: PublisherOptions); | ||
applyConfigs(config: GripUrlOrConfigs, publisherClientOptions?: PublisherClientOptions): void; | ||
applyConfig(config: string | IGripConfig, publisherClientOptions?: PublisherClientOptions): void; | ||
addClient(client: IPublisherClient): void; | ||
@@ -22,0 +24,0 @@ publish(channel: string, item: IItem): Promise<void>; |
@@ -10,10 +10,12 @@ import { Item } from '../data/index.js'; | ||
clients = []; | ||
constructor(config, clientOptions) { | ||
this.applyConfigs(config ?? [], clientOptions); | ||
prefix; | ||
constructor(config, publisherOptions) { | ||
this.applyConfigs(config ?? [], publisherOptions); | ||
this.prefix = publisherOptions?.prefix; | ||
} | ||
// Apply the specified GRIP configurations to this PublisherBase instance. | ||
applyConfigs(config, clientOptions) { | ||
applyConfigs(config, publisherClientOptions) { | ||
const configsAsArray = Array.isArray(config) ? config : [config]; | ||
for (const configEntry of configsAsArray) { | ||
this.applyConfig(configEntry, clientOptions); | ||
this.applyConfig(configEntry, publisherClientOptions); | ||
} | ||
@@ -25,6 +27,6 @@ } | ||
// a URI or a URI and authentication information (Basic, JWT, or Bearer Token). | ||
applyConfig(config, clientOptions) { | ||
applyConfig(config, publisherClientOptions) { | ||
const gripConfig = typeof config === 'string' ? parseGripUri(config) : config; | ||
const client = new PublisherClient(gripConfig, { | ||
fetch: clientOptions?.fetch, | ||
fetch: publisherClientOptions?.fetch, | ||
}); | ||
@@ -42,3 +44,3 @@ this.addClient(client); | ||
async publish(channel, item) { | ||
await Promise.all(this.clients.map((client) => client.publish(channel, item))); | ||
await Promise.all(this.clients.map((client) => client.publish((this.prefix ?? '') + channel, item))); | ||
} | ||
@@ -90,3 +92,3 @@ // A utility method for publishing an item to the specified channel on the configured endpoint | ||
for (const client of this.clients) { | ||
const verifyKey = client.getVerifyKey(); | ||
const verifyKey = client.getVerifyKey?.(); | ||
if (verifyKey == null) { | ||
@@ -98,3 +100,3 @@ needsSigned = false; | ||
if (!signatureValidated) { | ||
const verifyIss = client.getVerifyIss(); | ||
const verifyIss = client.getVerifyIss?.(); | ||
if (verifyIss == null) { | ||
@@ -101,0 +103,0 @@ signatureValidated = await validateSig(gripSigHeaderValue, verifyKey); |
{ | ||
"name": "@fanoutio/grip", | ||
"version": "4.0.0-beta.2", | ||
"version": "4.0.0-beta.3", | ||
"type": "module", | ||
@@ -20,3 +20,6 @@ "author": "Fanout, Inc. <info@fanout.io>", | ||
".": "./build/index.js", | ||
"./node": "./build/node/index.js" | ||
"./node": { | ||
"types": "./build/node/index.d.ts", | ||
"default": "./build/node/index.js" | ||
} | ||
}, | ||
@@ -23,0 +26,0 @@ "files": [ |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
1707732
0.06%9447
0.06%